diff --git a/cypress/e2e/DoenetML/assignNames/collections.cy.js b/cypress/e2e/DoenetML/assignNames/collections.cy.js index 2d5543a464..4ca0a199a9 100644 --- a/cypress/e2e/DoenetML/assignNames/collections.cy.js +++ b/cypress/e2e/DoenetML/assignNames/collections.cy.js @@ -3704,262 +3704,262 @@ describe('Collection assignName Tests', function () { cy.log('Move point all six points again'); cy.window().then(async (win) => { - await win.callAction1({ + win.callAction1({ actionName: "movePoint", componentName: "/q1", args: { x: -4, y: 6 } }); - await win.callAction1({ + win.callAction1({ actionName: "movePoint", componentName: "/q2", args: { x: -5, y: 5 } }); - await win.callAction1({ + win.callAction1({ actionName: "movePoint", componentName: "/q3", args: { x: -6, y: 4 } }); - await win.callAction1({ + win.callAction1({ actionName: "movePoint", componentName: "/q4", args: { x: -7, y: 3 } }); - await win.callAction1({ + win.callAction1({ actionName: "movePoint", componentName: "/q5", args: { x: -8, y: 2 } }); - await win.callAction1({ + win.callAction1({ actionName: "movePoint", componentName: "/q6", args: { x: -9, y: 1 } }); + }) - cy.get('#\\/q6 .mjx-mrow').should('contain.text', '(−9,1)') + cy.get('#\\/q6 .mjx-mrow').should('contain.text', '(−9,1)') - cy.get('#\\/p1').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−4,6)') - }) - cy.get('#\\/p2').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−5,5)') - }) - cy.get('#\\/p3').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−6,4)') - }) - cy.get('#\\/p4').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−7,3)') - }) + cy.get('#\\/p1').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−4,6)') + }) + cy.get('#\\/p2').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−5,5)') + }) + cy.get('#\\/p3').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−6,4)') + }) + cy.get('#\\/p4').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−7,3)') + }) - cy.get('#\\/p1shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−4,6)') - }) - cy.get('#\\/p2shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−5,5)') - }) - cy.get('#\\/p3shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−6,4)') - }) - cy.get('#\\/p4shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−7,3)') - }) + cy.get('#\\/p1shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−4,6)') + }) + cy.get('#\\/p2shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−5,5)') + }) + cy.get('#\\/p3shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−6,4)') + }) + cy.get('#\\/p4shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−7,3)') + }) - cy.get('#\\/q1').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−4,6)') - }) - cy.get('#\\/q2').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−5,5)') - }) - cy.get('#\\/q3').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−6,4)') - }) - cy.get('#\\/q4').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−7,3)') - }) - cy.get('#\\/q5').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−8,2)') - }) - cy.get('#\\/q6').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−9,1)') - }) + cy.get('#\\/q1').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−4,6)') + }) + cy.get('#\\/q2').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−5,5)') + }) + cy.get('#\\/q3').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−6,4)') + }) + cy.get('#\\/q4').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−7,3)') + }) + cy.get('#\\/q5').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−8,2)') + }) + cy.get('#\\/q6').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−9,1)') + }) - cy.get('#\\/q1shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−4,6)') - }) - cy.get('#\\/q2shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−5,5)') - }) - cy.get('#\\/q3shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−6,4)') - }) - cy.get('#\\/q4shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−7,3)') - }) - cy.get('#\\/q5shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−8,2)') - }) - cy.get('#\\/q6shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('(−9,1)') - }) + cy.get('#\\/q1shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−4,6)') + }) + cy.get('#\\/q2shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−5,5)') + }) + cy.get('#\\/q3shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−6,4)') + }) + cy.get('#\\/q4shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−7,3)') + }) + cy.get('#\\/q5shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−8,2)') + }) + cy.get('#\\/q6shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('(−9,1)') + }) - cy.get('#\\/x11').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−4') - }) - cy.get('#\\/x12').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−5') - }) - cy.get('#\\/x13').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−6') - }) - cy.get('#\\/x14').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−7') - }) - cy.get('#\\/x15').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−8') - }) - cy.get('#\\/x16').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−9') - }) + cy.get('#\\/x11').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−4') + }) + cy.get('#\\/x12').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−5') + }) + cy.get('#\\/x13').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−6') + }) + cy.get('#\\/x14').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−7') + }) + cy.get('#\\/x15').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−8') + }) + cy.get('#\\/x16').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−9') + }) - cy.get('#\\/x11shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−4') - }) - cy.get('#\\/x12shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−5') - }) - cy.get('#\\/x13shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−6') - }) - cy.get('#\\/x14shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−7') - }) - cy.get('#\\/x15shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−8') - }) - cy.get('#\\/x16shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−9') - }) + cy.get('#\\/x11shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−4') + }) + cy.get('#\\/x12shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−5') + }) + cy.get('#\\/x13shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−6') + }) + cy.get('#\\/x14shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−7') + }) + cy.get('#\\/x15shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−8') + }) + cy.get('#\\/x16shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−9') + }) - cy.get('#\\/x21').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−4') - }) - cy.get('#\\/x22').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−5') - }) - cy.get('#\\/x23').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−6') - }) - cy.get('#\\/x24').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−7') - }) + cy.get('#\\/x21').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−4') + }) + cy.get('#\\/x22').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−5') + }) + cy.get('#\\/x23').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−6') + }) + cy.get('#\\/x24').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−7') + }) - cy.get('#\\/x21shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−4') - }) - cy.get('#\\/x22shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−5') - }) - cy.get('#\\/x23shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−6') - }) - cy.get('#\\/x24shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−7') - }) + cy.get('#\\/x21shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−4') + }) + cy.get('#\\/x22shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−5') + }) + cy.get('#\\/x23shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−6') + }) + cy.get('#\\/x24shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−7') + }) - cy.get('#\\/x31').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−4') - }) - cy.get('#\\/x32').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−5') - }) - cy.get('#\\/x33').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−6') - }) - cy.get('#\\/x34').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−7') - }) + cy.get('#\\/x31').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−4') + }) + cy.get('#\\/x32').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−5') + }) + cy.get('#\\/x33').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−6') + }) + cy.get('#\\/x34').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−7') + }) - cy.get('#\\/x31shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−4') - }) - cy.get('#\\/x32shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−5') - }) - cy.get('#\\/x33shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−6') - }) - cy.get('#\\/x34shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−7') - }) + cy.get('#\\/x31shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−4') + }) + cy.get('#\\/x32shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−5') + }) + cy.get('#\\/x33shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−6') + }) + cy.get('#\\/x34shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−7') + }) - cy.get('#\\/x41').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−4') - }) - cy.get('#\\/x42').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−5') - }) - cy.get('#\\/x43').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−6') - }) - cy.get('#\\/x44').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−7') - }) + cy.get('#\\/x41').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−4') + }) + cy.get('#\\/x42').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−5') + }) + cy.get('#\\/x43').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−6') + }) + cy.get('#\\/x44').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−7') + }) - cy.get('#\\/x41shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−4') - }) - cy.get('#\\/x42shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−5') - }) - cy.get('#\\/x43shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−6') - }) - cy.get('#\\/x44shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−7') - }) + cy.get('#\\/x41shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−4') + }) + cy.get('#\\/x42shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−5') + }) + cy.get('#\\/x43shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−6') + }) + cy.get('#\\/x44shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−7') + }) - cy.get('#\\/x51').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−4') - }) - cy.get('#\\/x52').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−5') - }) - cy.get('#\\/x53').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−6') - }) - cy.get('#\\/x54').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−7') - }) - cy.get('#\\/x55').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−8') - }) - cy.get('#\\/x56').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−9') - }) + cy.get('#\\/x51').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−4') + }) + cy.get('#\\/x52').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−5') + }) + cy.get('#\\/x53').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−6') + }) + cy.get('#\\/x54').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−7') + }) + cy.get('#\\/x55').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−8') + }) + cy.get('#\\/x56').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−9') + }) - cy.get('#\\/x51shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−4') - }) - cy.get('#\\/x52shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−5') - }) - cy.get('#\\/x53shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−6') - }) - cy.get('#\\/x54shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−7') - }) - cy.get('#\\/x55shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−8') - }) - cy.get('#\\/x56shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('−9') - }) + cy.get('#\\/x51shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−4') + }) + cy.get('#\\/x52shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−5') + }) + cy.get('#\\/x53shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−6') + }) + cy.get('#\\/x54shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−7') + }) + cy.get('#\\/x55shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−8') + }) + cy.get('#\\/x56shadow').find('.mjx-mrow').eq(0).invoke('text').then((text) => { + expect(text.trim()).equal('−9') }) cy.log('0 and 3 points, remembers old 3rd value'); diff --git a/cypress/e2e/DoenetML/equality/mathexpressions.cy.js b/cypress/e2e/DoenetML/equality/mathexpressions.cy.js index b38b1cca2f..900046bc7f 100644 --- a/cypress/e2e/DoenetML/equality/mathexpressions.cy.js +++ b/cypress/e2e/DoenetML/equality/mathexpressions.cy.js @@ -1,13 +1,3 @@ -import cssesc from 'cssesc'; - -function cesc(s) { - s = cssesc(s, { isIdentifier: true }); - if (s.slice(0, 2) === '\\#') { - s = s.slice(1); - } - return s; -} - describe('Math expressions equality tests', function () { beforeEach(() => { @@ -15,491 +5,901 @@ describe('Math expressions equality tests', function () { cy.visit('/cypressTest') }) - it('inverse trig', () => { - cy.window().then(async (win) => { - win.postMessage({ - doenetML: ` - a - -

- sin^(-1)(x) = arcsin(x) - sin^(-1)(x) = asin(x) - sin^(-1)(1) = pi/2 - cos^(-1)(x) = arccos(x) - cos^(-1)(x) = acos(x) - cos^(-1)(1) = 0 - tan^(-1)(x) = arctan(x) - tan^(-1)(x) = atan(x) - tan^(-1)(1) = pi/4 -

- -

- sin^(-1)(x) = sin(x)^(-1) - cos^(-1)(x) = cos(x)^(-1) - tan^(-1)(x) = tan(x)^(-1) -

- - `}, "*"); - }); - - cy.get('#\\/_text1').should('contain.text', 'a') - - - let nTrues = 9, nFalses = 3; - for (let i = 1; i <= nTrues; i++) { - cy.get(`#\\/t${i}`).should('have.text', "true") - } - - for (let i = 1; i <= nFalses; i++) { - cy.get(`#\\/f${i}`).should('have.text', "false") - } - - cy.window().then(async (win) => { - let stateVariables = await win.returnAllStateVariables1(); - for (let i = 1; i <= nTrues; i++) { - expect(stateVariables[`/t${i}`].stateValues.value).to.be.true - } - for (let i = 1; i <= nFalses; i++) { - expect(stateVariables[`/f${i}`].stateValues.value).to.be.false - } - }) - - }) - - - it('trig shortcut powers, not other functions', () => { - cy.window().then(async (win) => { - win.postMessage({ - doenetML: ` - a - -

- sin^2(x) = sin(x)^2 - sin^n(x) = sin(x)^n - cos^2(x) = cos(x)^2 - cos^n(x) = cos(x)^n - tan^2(x) = tan(x)^2 - tan^n(x) = tan(x)^n - cos^2(x) = cos(x)^2 - cos^n(x) = cos(x)^n - sec^2(x) = sec(x)^2 - sec^n(x) = sec(x)^n - cot^2(x) = cot(x)^2 - cot^n(x) = cot(x)^n -

- -

- log^2(x) = log(x)^2 - log^n(x) = log(x)^n - ln^2(x) = ln(x)^2 - ln^n(x) = ln(x)^n - f^2(x) = f(x)^2 - f^n(x) = f(x)^n -

- - `}, "*"); - }); - - cy.get('#\\/_text1').should('contain.text', 'a') - - - let nTrues = 12, nFalses = 6; - for (let i = 1; i <= nTrues; i++) { - cy.get(`#\\/t${i}`).should('have.text', "true") - } - - for (let i = 1; i <= nFalses; i++) { - cy.get(`#\\/f${i}`).should('have.text', "false") - } - - cy.window().then(async (win) => { - let stateVariables = await win.returnAllStateVariables1(); - for (let i = 1; i <= nTrues; i++) { - expect(stateVariables[`/t${i}`].stateValues.value).to.be.true - } - for (let i = 1; i <= nFalses; i++) { - expect(stateVariables[`/f${i}`].stateValues.value).to.be.false - } - }) - - }) - - it('logarithms of different bases', () => { - cy.window().then(async (win) => { - win.postMessage({ - doenetML: ` - a - -

- log(e^3) = 3 - ln(e^3) = 3 - log10(10^3) = 3 - log_10(10^3) = 3 - log_2(2^3) = 3 - log_7(7^3) = 3 - log_b(a) = log(a)/log(b) -

- - - `}, "*"); - }); - - cy.get('#\\/_text1').should('contain.text', 'a') - - - let nTrues = 7, nFalses = 0; - for (let i = 1; i <= nTrues; i++) { - cy.get(`#\\/t${i}`).should('have.text', "true") - } - - for (let i = 1; i <= nFalses; i++) { - cy.get(`#\\/f${i}`).should('have.text', "false") - } - - cy.window().then(async (win) => { - let stateVariables = await win.returnAllStateVariables1(); - for (let i = 1; i <= nTrues; i++) { - expect(stateVariables[`/t${i}`].stateValues.value).to.be.true - } - for (let i = 1; i <= nFalses; i++) { - expect(stateVariables[`/f${i}`].stateValues.value).to.be.false - } - }) - - }) - - it('permutations and combinations', () => { - cy.window().then(async (win) => { - win.postMessage({ - doenetML: ` - a - -

- nCr(5,3) = 10 - nPr(5,3) = 60 - binom(5,3) = 10 - binom(m,n) = nCr(m,n) -

- - `}, "*"); - }); - - cy.get('#\\/_text1').should('contain.text', 'a') - - - let nTrues = 4, nFalses = 0; - for (let i = 1; i <= nTrues; i++) { - cy.get(`#\\/t${i}`).should('have.text', "true") - } - - for (let i = 1; i <= nFalses; i++) { - cy.get(`#\\/f${i}`).should('have.text', "false") - } - - cy.window().then(async (win) => { - let stateVariables = await win.returnAllStateVariables1(); - for (let i = 1; i <= nTrues; i++) { - expect(stateVariables[`/t${i}`].stateValues.value).to.be.true - } - for (let i = 1; i <= nFalses; i++) { - expect(stateVariables[`/f${i}`].stateValues.value).to.be.false - } - }) - - }) - - it('alternative vectors', () => { - cy.window().then(async (win) => { - win.postMessage({ - doenetML: ` - a - -

- ⟨a,b⟩ = (a,b) - ⟨a,b⟩ = (a,b) - (a,b) = (a,b) -

- -

- ⟨a,b⟩ = (a,b) - (a,b) = (a,b) -

- - `}, "*"); - }); - - cy.get('#\\/_text1').should('contain.text', 'a') - - - let nTrues = 3, nFalses = 2; - for (let i = 1; i <= nTrues; i++) { - cy.get(`#\\/t${i}`).should('have.text', "true") - } - - for (let i = 1; i <= nFalses; i++) { - cy.get(`#\\/f${i}`).should('have.text', "false") - } - - cy.window().then(async (win) => { - let stateVariables = await win.returnAllStateVariables1(); - for (let i = 1; i <= nTrues; i++) { - expect(stateVariables[`/t${i}`].stateValues.value).to.be.true - } - for (let i = 1; i <= nFalses; i++) { - expect(stateVariables[`/f${i}`].stateValues.value).to.be.false - } - }) - - }) - - it('angles', () => { - cy.window().then(async (win) => { - win.postMessage({ - doenetML: ` - a - -

- angle ABC = angle CBA - angle(A,B,C) = angle(C,B,A) - angle A'B'C' = angle C'B'A' - angle ABC = angle(A,B,C) - angle ABC = angle(A,B,C) - angle A'B'C' = angle(A',B',C') - angle A B C = angle(A,B,C) - angle ABC = angle CBA - angle(A,B,C) = angle(C,B,A) -

- -

- angle ABC = angle ACB - angle ABC = angle A'B'C' - angle(A,B,C) = angle (A,C,B) - angle(A,B,C) = angle (A',B',C') -

- - `}, "*"); - }); - - cy.get('#\\/_text1').should('contain.text', 'a') - - - - let nTrues = 9, nFalses = 4; - - for (let i = 1; i <= nTrues; i++) { - cy.get(`#\\/t${i}`).should('have.text', "true") + it('equivalences', () => { + let equivalences = [ + + { + expr1: 'sin^(-1)(x)', + expr2: 'arcsin(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'sin^(-1)(x)', + expr2: 'asin(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'sin^(-1)(1)', + expr2: 'pi/2', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'cos^(-1)(x)', + expr2: 'arccos(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'cos^(-1)(x)', + expr2: 'acos(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'cos^(-1)(1)', + expr2: '0', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'tan^(-1)(x)', + expr2: 'arctan(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'tan^(-1)(x)', + expr2: 'atan(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'tan^(-1)(1)', + expr2: 'pi/4', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + + { + expr1: 'sin^(-1)(x)', + expr2: 'sin(x)^(-1)', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'cos^(-1)(x)', + expr2: 'cos(x)^(-1)', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'tan^(-1)(x)', + expr2: 'tan(x)^(-1)', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + + + { + expr1: 'sin^2(x)', + expr2: 'sin(x)^2', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'sin^n(x)', + expr2: 'sin(x)^n', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'cos^2(x)', + expr2: 'cos(x)^2', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'cos^n(x)', + expr2: 'cos(x)^n', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'tan^2(x)', + expr2: 'tan(x)^2', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'tan^n(x)', + expr2: 'tan(x)^n', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'cos^2(x)', + expr2: 'cos(x)^2', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'cos^n(x)', + expr2: 'cos(x)^n', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'sec^2(x)', + expr2: 'sec(x)^2', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'sec^n(x)', + expr2: 'sec(x)^n', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'cot^2(x)', + expr2: 'cot(x)^2', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'cot^n(x)', + expr2: 'cot(x)^n', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + + { + expr1: 'log^2(x)', + expr2: 'log(x)^2', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'log^n(x)', + expr2: 'log(x)^n', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'ln^2(x)', + expr2: 'ln(x)^2', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'ln^n(x)', + expr2: 'ln(x)^n', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'f^2(x)', + expr2: 'f(x)^2', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'f^n(x)', + expr2: 'f(x)^n', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'log(e^3)', + expr2: '3', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'ln(e^3)', + expr2: '3', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'log10(10^3)', + expr2: '3', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'log_10(10^3)', + expr2: '3', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'log_2(2^3)', + expr2: '3', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'log_7(7^3)', + expr2: '3', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'log_b(a)', + expr2: 'log(a)/log(b)', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: false, // with improved simplication, these should compare as true + symbolicSimplifyExpandEqual: false, // with improved simplication, these should compare as true + }, + { + expr1: 'nCr(5,3)', + expr2: '10', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'nPr(5,3)', + expr2: '60', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'binom(5,3)', + expr2: '10', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'binom(m,n)', + expr2: 'nCr(m,n)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: '\\langle a,b\\rangle', + expr2: '(a,b)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: '\\langle a,b\\rangle', + expr2: '(a,b)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: '(a,b)', + expr2: '(a,b)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'c \\langle a,b\\rangle', + expr2: '(ac,bc)', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: '\\langle ac,bc\\rangle', + expr2: 'c(a,b)', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'c(a,b)', + expr2: '(ac,bc)', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: '\\langle a,b\\rangle + (c,d)', + expr2: '(a+c,b+d)', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: '\\langle a+c,b+d\\rangle', + expr2: '(a,b) + (c,d)', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: '\\langle a,b\\rangle + (c,d)', + expr2: '(a+c,b+d)', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: '\\langle a,b\\rangle', + expr2: '(a,b)', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: '(a,b)', + expr2: '(a,b)', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + + { + expr1: 'angle ABC', + expr2: 'angle CBA', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'angle(A,B,C)', + expr2: 'angle(C,B,A)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: "angle A'B'C'", + expr2: "angle C'B'A'", + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'angle ABC', + expr2: 'angle(A,B,C)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'angle ABC', + expr2: 'angle(A,B,C)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: "angle A'B'C'", + expr2: "angle(A',B',C')", + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'angle A B C', + expr2: 'angle(A,B,C)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + + { + expr1: 'angle ABC', + expr2: 'angle ACB', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'angle ABC', + expr2: "angle A'B'C'", + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'angle(A,B,C)', + expr2: 'angle (A,C,B)', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'angle(A,B,C)', + expr2: "angle (A',B',C')", + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + + { + expr1: '90 deg', + expr2: 'pi/2', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: '50%', + expr2: '0.5', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: '$5', + expr2: '$3+$2', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: '90 deg', + expr2: '360 deg - 270 deg', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: '250%', + expr2: '50% * 5', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: '$3', + expr2: '$12 / 4', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'sin(45 deg)', + expr2: '1/sqrt(2)', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'x%', + expr2: 'x/100', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'x deg', + expr2: 'pi x/180', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: '(3x)%', + expr2: 'x% 3', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + + + { + expr1: '90 deg', + expr2: '90', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: '50%', + expr2: '50', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: '360 deg', + expr2: '0 deg', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: '$5', + expr2: '5', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + + { + expr1: 'int f(x) dx', + expr2: 'int dx f(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'int f(x) dx', + expr2: 'int dx f(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'int f(x) dx', + expr2: 'int dx f(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'int f(x) dx', + expr2: 'int dx f(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'int f(x,y) dxdy', + expr2: 'int dxdy f(x,y)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'int f(x,y) dxdy', + expr2: 'int dxdy f(x,y)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'int f(x,y) dxdy', + expr2: 'int dxdy f(x,y)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'int f(x,y) dxdy', + expr2: 'int dxdy f(x,y)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'int (x*x + x + x - x^2/3) dx', + expr2: 'int (2x^2/3 + 2x) dx', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'int_a^b f(x) dx', + expr2: 'int_a^b dx f(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'int_a^b f(x) dx', + expr2: 'int_a^b dx f(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'int_a^b f(x) dx', + expr2: 'int_a^b dx f(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'int_a^b f(x) dx', + expr2: 'int_a^b dx f(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'int_a f(x) dx', + expr2: 'int_a dx f(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'int_a f(x) dx', + expr2: 'int_a dx f(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'int_a f(x) dx', + expr2: 'int_a dx f(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'int_a f(x) dx', + expr2: 'int_a dx f(x)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'int_(a+a)^(b*b) x*x*x dx', + expr2: 'int_(2a)^(b^2) x^3dx', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + + { + expr1: 'int f(x) dx', + expr2: 'int_a^b f(x) dx', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'int x^2 dx', + expr2: 'int x^3 dx', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'int_a^b f(x) dx', + expr2: 'int_c^d f(x) dx', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'int_a^b x^2 dx', + expr2: 'int_a^b x^3 dx', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + + { + expr1: 'vec(x)', + expr2: 'vec x', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'vec(x) + vec(x)', + expr2: '2vec(x)', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + { + expr1: 'vec(x)*vec(x)vec(y)/(vec(x)*vec(x))', + expr2: 'vec(y)', + equal: true, + symbolicEqual: false, + symbolicSimplifyEqual: false, // with improved simplication, these should compare as true + symbolicSimplifyExpandEqual: false, // with improved simplication, these should compare as true + }, + + { + expr1: 'vec(x)', + expr2: 'x', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'vec(xy)', + expr2: 'vec(x)vec(y)', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + { + expr1: 'vec(2x)', + expr2: '2vec(x)', + equal: false, + symbolicEqual: false, + symbolicSimplifyEqual: false, + symbolicSimplifyExpandEqual: false, + }, + + { + expr1: 'linesegment(A,B)', + expr2: 'linesegment(B,A)', + equal: true, + symbolicEqual: true, + symbolicSimplifyEqual: true, + symbolicSimplifyExpandEqual: true, + }, + + ] + + let doenetML = 'a'; + + for (let [ind, info] of equivalences.entries()) { + doenetML += `\n${info.expr1} = ${info.expr2}` + doenetML += `\n${info.expr1} = ${info.expr2}` + doenetML += `\n${info.expr1} = ${info.expr2}` + doenetML += `\n${info.expr1} = ${info.expr2}` } - for (let i = 1; i <= nFalses; i++) { - cy.get(`#\\/f${i}`).should('have.text', "false") - } - cy.window().then(async (win) => { - let stateVariables = await win.returnAllStateVariables1(); - for (let i = 1; i <= nTrues; i++) { - expect(stateVariables[`/t${i}`].stateValues.value).to.be.true - } - for (let i = 1; i <= nFalses; i++) { - expect(stateVariables[`/f${i}`].stateValues.value).to.be.false - } - }) - - }) - - it('units', () => { cy.window().then(async (win) => { win.postMessage({ - doenetML: ` - a - -

- 90 deg = pi/2 - 50% = 0.5 - $5 = $3+$2 - 90 deg = 360 deg - 270 deg - 250% = 50% * 5 - $3 = $12 / 4 - sin(45 deg) = 1/sqrt(2) - x% = x/100 - x deg = pi x/180 - (3x)% = x% 3 -

- -

- 90 deg = 90 - 50% = 50 - 360 deg = 0 deg - $5 = 5 -

- - `}, "*"); + doenetML + }, "*"); }); cy.get('#\\/_text1').should('contain.text', 'a') - - let nTrues = 10, nFalses = 4; - - for (let i = 1; i <= nTrues; i++) { - cy.get(`#\\/t${i}`).should('have.text', "true") - } - - for (let i = 1; i <= nFalses; i++) { - cy.get(`#\\/f${i}`).should('have.text', "false") - } - cy.window().then(async (win) => { let stateVariables = await win.returnAllStateVariables1(); - for (let i = 1; i <= nTrues; i++) { - expect(stateVariables[`/t${i}`].stateValues.value).to.be.true - } - for (let i = 1; i <= nFalses; i++) { - expect(stateVariables[`/f${i}`].stateValues.value).to.be.false - } - }) - - }) - - it('some support for integral', () => { - cy.window().then(async (win) => { - win.postMessage({ - doenetML: ` - a - -

- int f(x) dx = int dx f(x) - int (x*x + x + x - x^2/3) dx = int (2x^2/3 + 2x) dx - int_a^b f(x) dx = int_a^b dx f(x) - int_(a+a)^(b*b) x*x*x dx = int_(2a)^(b^2) x^3dx -

- -

- int f(x) dx = int_a^b f(x) dx - int x^2 dx = int x^3 dx - int_a^b f(x) dx = int_c^d f(x) dx - int_a^b x^2 dx = int_a^b x^3 dx -

- - `}, "*"); - }); - - cy.get('#\\/_text1').should('contain.text', 'a') - - - - let nTrues = 4, nFalses = 4; - - for (let i = 1; i <= nTrues; i++) { - cy.get(`#\\/t${i}`).should('have.text', "true") - } - for (let i = 1; i <= nFalses; i++) { - cy.get(`#\\/f${i}`).should('have.text', "false") - } - - cy.window().then(async (win) => { - let stateVariables = await win.returnAllStateVariables1(); - for (let i = 1; i <= nTrues; i++) { - expect(stateVariables[`/t${i}`].stateValues.value).to.be.true - } - for (let i = 1; i <= nFalses; i++) { - expect(stateVariables[`/f${i}`].stateValues.value).to.be.false - } - }) - - }) - - it('vecs', () => { - cy.window().then(async (win) => { - win.postMessage({ - doenetML: ` - a - -

- vec(x) = vec x - vec(x) + vec(x) = 2vec(x) - vec(x)*vec(x)vec(y)/(vec(x)*vec(x)) = vec(y) -

- -

- vec(x) = x - vec(xy) = vec(x)vec(y) - vec(2x) = 2vec(x) -

- - `}, "*"); - }); - - cy.get('#\\/_text1').should('contain.text', 'a') - - - - let nTrues = 3, nFalses = 3; - - for (let i = 1; i <= nTrues; i++) { - cy.get(`#\\/t${i}`).should('have.text', "true") - } - - for (let i = 1; i <= nFalses; i++) { - cy.get(`#\\/f${i}`).should('have.text', "false") - } - - cy.window().then(async (win) => { - let stateVariables = await win.returnAllStateVariables1(); - for (let i = 1; i <= nTrues; i++) { - expect(stateVariables[`/t${i}`].stateValues.value).to.be.true - } - for (let i = 1; i <= nFalses; i++) { - expect(stateVariables[`/f${i}`].stateValues.value).to.be.false - } - }) - - }) - - it('linesegments', () => { - cy.window().then(async (win) => { - win.postMessage({ - doenetML: ` - a - -

- linesegment(A,B) = linesegment(B,A) - vec(x) + vec(x) = 2vec(x) - vec(x)*vec(x)vec(y)/(vec(x)*vec(x)) = vec(y) - linesegment(A,B) = linesegment(B,A) -

- -

- vec(x) = x - vec(xy) = vec(x)vec(y) - vec(2x) = 2vec(x) -

- - `}, "*"); - }); - - cy.get('#\\/_text1').should('contain.text', 'a') - - - - let nTrues = 4, nFalses = 3; - - for (let i = 1; i <= nTrues; i++) { - cy.get(`#\\/t${i}`).should('have.text', "true") - } - - for (let i = 1; i <= nFalses; i++) { - cy.get(`#\\/f${i}`).should('have.text', "false") - } - - cy.window().then(async (win) => { - let stateVariables = await win.returnAllStateVariables1(); - for (let i = 1; i <= nTrues; i++) { - expect(stateVariables[`/t${i}`].stateValues.value).to.be.true - } - for (let i = 1; i <= nFalses; i++) { - expect(stateVariables[`/f${i}`].stateValues.value).to.be.false + for (let [ind, info] of equivalences.entries()) { + expect(stateVariables[`/n${ind}`].stateValues.value, `Comparing ${info.expr1} and ${info.expr2}`).eq(info.equal) + expect(stateVariables[`/s${ind}`].stateValues.value, `Comparing symbolic ${info.expr1} and ${info.expr2}`).eq(info.symbolicEqual) + expect(stateVariables[`/ss${ind}`].stateValues.value, `Comparing symbolic simplify ${info.expr1} and ${info.expr2}`).eq(info.symbolicSimplifyEqual) + expect(stateVariables[`/sse${ind}`].stateValues.value, `Comparing symbolic simplify expand ${info.expr1} and ${info.expr2}`).eq(info.symbolicSimplifyExpandEqual) } }) diff --git a/cypress/e2e/DoenetML/tagSpecific/choiceinput.cy.js b/cypress/e2e/DoenetML/tagSpecific/choiceinput.cy.js index ca83867f62..24b3f5bd9d 100644 --- a/cypress/e2e/DoenetML/tagSpecific/choiceinput.cy.js +++ b/cypress/e2e/DoenetML/tagSpecific/choiceinput.cy.js @@ -478,7 +478,7 @@ describe('ChoiceInput Tag Tests', function () { The function is f(\\xi)=\\sin(\\xi). The sum of lambda^2 and 2 lambda^2 is +. The sequence is . - Can't convert this latex: \\int_a^b q(t) \\, dt. + Can't convert this latex: \\bar{x}^i. @@ -501,7 +501,7 @@ describe('ChoiceInput Tag Tests', function () { "The function is f(ξ) = sin(ξ).", "The sum of λ² and 2 λ² is 3 λ².", "The sequence is 1, 2, 3, 4, 5.", - "Can't convert this latex: \\int_a^b q(t) \\, dt." + "Can't convert this latex: \\bar{x}^i." ]; cy.get('#\\/_p1').should('have.text', 'Selected values: ') cy.get('#\\/_p2').should('have.text', 'Selected indices: ') diff --git a/cypress/e2e/DoenetML/tagSpecific/circle.cy.js b/cypress/e2e/DoenetML/tagSpecific/circle.cy.js index a4b4716555..ddfa87e313 100644 --- a/cypress/e2e/DoenetML/tagSpecific/circle.cy.js +++ b/cypress/e2e/DoenetML/tagSpecific/circle.cy.js @@ -8989,31 +8989,31 @@ describe('Circle Tag Tests', function () { cy.get('#\\/P2 .mjx-mrow').should('not.exist'); cy.get('#\\/P3 .mjx-mrow').should('not.exist'); cy.get('#\\/x .mjx-mrow').should('not.exist'); - - cy.get('#\\/n textarea').type("1{enter}", {force: true}); + + cy.get('#\\/n textarea').type("1{enter}", { force: true }); cy.get('#\\/P1 .mjx-mrow').should('contain.text', `(${nInDOM(t1x)},${nInDOM(t1y)})`); cy.get('#\\/P2 .mjx-mrow').should('not.exist'); cy.get('#\\/P3 .mjx-mrow').should('not.exist'); cy.get('#\\/x .mjx-mrow').should('contain.text', `${nInDOM(t2x)}`); - cy.get('#\\/n textarea').type("{end}{backspace}2{enter}", {force: true}); + cy.get('#\\/n textarea').type("{end}{backspace}2{enter}", { force: true }); cy.get('#\\/P1 .mjx-mrow').should('contain.text', `(${nInDOM(t2x)},${nInDOM(t2y)})`); cy.get('#\\/P2 .mjx-mrow').should('not.exist'); cy.get('#\\/P3 .mjx-mrow').should('not.exist'); cy.get('#\\/x .mjx-mrow').should('contain.text', `${nInDOM(t2y)}`); - - cy.get('#\\/n textarea').type("{end}{backspace}3{enter}", {force: true}); + + cy.get('#\\/n textarea').type("{end}{backspace}3{enter}", { force: true }); cy.get('#\\/P1 .mjx-mrow').should('contain.text', `(${nInDOM(t3x)},${nInDOM(t3y)})`); cy.get('#\\/P2 .mjx-mrow').should('not.exist'); cy.get('#\\/P3 .mjx-mrow').should('not.exist'); cy.get('#\\/x .mjx-mrow').should('not.exist'); - - cy.get('#\\/n textarea').type("{end}{backspace}4{enter}", {force: true}); + + cy.get('#\\/n textarea').type("{end}{backspace}4{enter}", { force: true }); cy.get('#\\/P1 .mjx-mrow').should('not.exist'); cy.get('#\\/P2 .mjx-mrow').should('not.exist'); cy.get('#\\/P3 .mjx-mrow').should('not.exist'); cy.get('#\\/x .mjx-mrow').should('not.exist'); - + }); @@ -9045,31 +9045,31 @@ describe('Circle Tag Tests', function () { cy.get('#\\/P2 .mjx-mrow').should('not.exist'); cy.get('#\\/P3 .mjx-mrow').should('not.exist'); cy.get('#\\/x .mjx-mrow').should('not.exist'); - - cy.get('#\\/n textarea').type("1{enter}", {force: true}); + + cy.get('#\\/n textarea').type("1{enter}", { force: true }); cy.get('#\\/P1 .mjx-mrow').should('contain.text', `(${nInDOM(t1x)},${nInDOM(t1y)})`); cy.get('#\\/P2 .mjx-mrow').should('not.exist'); cy.get('#\\/P3 .mjx-mrow').should('not.exist'); cy.get('#\\/x .mjx-mrow').should('contain.text', `${nInDOM(t2x)}`); - cy.get('#\\/n textarea').type("{end}{backspace}2{enter}", {force: true}); + cy.get('#\\/n textarea').type("{end}{backspace}2{enter}", { force: true }); cy.get('#\\/P1 .mjx-mrow').should('contain.text', `(${nInDOM(t2x)},${nInDOM(t2y)})`); cy.get('#\\/P2 .mjx-mrow').should('not.exist'); cy.get('#\\/P3 .mjx-mrow').should('not.exist'); cy.get('#\\/x .mjx-mrow').should('contain.text', `${nInDOM(t2y)}`); - - cy.get('#\\/n textarea').type("{end}{backspace}3{enter}", {force: true}); + + cy.get('#\\/n textarea').type("{end}{backspace}3{enter}", { force: true }); cy.get('#\\/P1 .mjx-mrow').should('contain.text', `(${nInDOM(t3x)},${nInDOM(t3y)})`); cy.get('#\\/P2 .mjx-mrow').should('not.exist'); cy.get('#\\/P3 .mjx-mrow').should('not.exist'); cy.get('#\\/x .mjx-mrow').should('not.exist'); - - cy.get('#\\/n textarea').type("{end}{backspace}4{enter}", {force: true}); + + cy.get('#\\/n textarea').type("{end}{backspace}4{enter}", { force: true }); cy.get('#\\/P1 .mjx-mrow').should('not.exist'); cy.get('#\\/P2 .mjx-mrow').should('not.exist'); cy.get('#\\/P3 .mjx-mrow').should('not.exist'); cy.get('#\\/x .mjx-mrow').should('not.exist'); - + }); diff --git a/cypress/e2e/DoenetML/tagSpecific/copy.cy.js b/cypress/e2e/DoenetML/tagSpecific/copy.cy.js index 905bdc86b1..58cb7e9431 100644 --- a/cypress/e2e/DoenetML/tagSpecific/copy.cy.js +++ b/cypress/e2e/DoenetML/tagSpecific/copy.cy.js @@ -14068,7 +14068,7 @@ describe('Copy Tag Tests', function () { cy.get(cesc('#/p34') + ' .mjx-mrow').eq(1).should('not.exist'); cy.get(cesc('#/p35')).should('have.text', '') - cy.get(cesc('#/p36')).should('have.text', '0 = -23.1058 \\, x - 3.0203 \\, y + 120.4105'); + cy.get(cesc('#/p36')).should('have.text', '0 = -23.1058 x - 3.0203 y + 120.4105'); cy.get(cesc('#/p37') + ' .mjx-mrow').eq(0).should('have.text', '(3.9264,9.8294)'); cy.get(cesc('#/p37') + ' .mjx-mrow').eq(3).should('have.text', '(0.9061,32.9352)'); cy.get(cesc('#/p38') + ' .mjx-mrow').eq(0).should('have.text', '(3.9264,9.8294)'); @@ -14937,4 +14937,25 @@ describe('Copy Tag Tests', function () { }); + + it('correctly wrap replacement changes when verifying to force component type', () => { + + cy.window().then(async (win) => { + win.postMessage({ + doenetML: ` + 47 + + `}, "*"); + }); + + cy.get('#\\/num').should('have.text', 'NaN') + + cy.get('#\\/ans textarea').type("4{enter}", { force: true }); + cy.get('#\\/num').should('have.text', '4') + + cy.get('#\\/ans textarea').type("7{enter}", { force: true }); + cy.get('#\\/num').should('have.text', '47') + + }); + }); \ No newline at end of file diff --git a/cypress/e2e/DoenetML/tagSpecific/curve.bezier.cy.js b/cypress/e2e/DoenetML/tagSpecific/curve.bezier.cy.js index a93490bcc9..e84f86cf25 100644 --- a/cypress/e2e/DoenetML/tagSpecific/curve.bezier.cy.js +++ b/cypress/e2e/DoenetML/tagSpecific/curve.bezier.cy.js @@ -10601,7 +10601,7 @@ describe('Curve Tag Bezier Tests', function () { componentName: "/c", args: { controlVectorInds: [1, 0], - controlVector: [3,-5] + controlVector: [3, -5] } }) await win.callAction1({ @@ -10609,7 +10609,7 @@ describe('Curve Tag Bezier Tests', function () { componentName: "/c", args: { controlVectorInds: [1, 1], - controlVector: [2,-4] + controlVector: [2, -4] } }) await win.callAction1({ @@ -10617,7 +10617,7 @@ describe('Curve Tag Bezier Tests', function () { componentName: "/c", args: { controlVectorInds: [2, 0], - controlVector: [-2,-6] + controlVector: [-2, -6] } }) }) diff --git a/cypress/e2e/DoenetML/tagSpecific/curve.cy.js b/cypress/e2e/DoenetML/tagSpecific/curve.cy.js index a51a384fa2..ac45b4c51a 100644 --- a/cypress/e2e/DoenetML/tagSpecific/curve.cy.js +++ b/cypress/e2e/DoenetML/tagSpecific/curve.cy.js @@ -1214,7 +1214,7 @@ describe('Curve Tag Tests', function () { throughPoint: ps[1] } }); - + stateVariables = await win.returnAllStateVariables1(); expect((stateVariables['/_curve1'].stateValues.throughPoints)[1]).eqls(ps[1]); expect((stateVariables['/_curve2'].stateValues.throughPoints)[1]).eqls(psflipped[1]); diff --git a/cypress/e2e/DoenetML/tagSpecific/curve.parametrized.cy.js b/cypress/e2e/DoenetML/tagSpecific/curve.parametrized.cy.js index 6987d59ac6..0628576eab 100644 --- a/cypress/e2e/DoenetML/tagSpecific/curve.parametrized.cy.js +++ b/cypress/e2e/DoenetML/tagSpecific/curve.parametrized.cy.js @@ -592,7 +592,7 @@ describe('Parameterized Curve Tag Tests', function () { }); cy.get('#\\/_text1').should('have.text', 'a'); //wait for window to load - cy.get("#\\/m1").should('contain.text', "2") + cy.get("#\\/m1 .mjx-mrow").should('contain.text', "2") cy.window().then(async (win) => { let stateVariables = await win.returnAllStateVariables1(); @@ -607,7 +607,7 @@ describe('Parameterized Curve Tag Tests', function () { }) cy.get("#\\/_mathinput1 textarea").type("{end}{backspace}-3{enter}", { force: true }); - cy.get("#\\/m1").should('contain.text', "−3") + cy.get("#\\/m1 .mjx-mrow").should('contain.text', "−3") cy.window().then(async (win) => { let stateVariables = await win.returnAllStateVariables1(); expect(stateVariables["/_curve1"].stateValues.parMin).eq(-10); diff --git a/cypress/e2e/DoenetML/tagSpecific/extract.cy.js b/cypress/e2e/DoenetML/tagSpecific/extract.cy.js index 967471b17d..c544142ff8 100644 --- a/cypress/e2e/DoenetML/tagSpecific/extract.cy.js +++ b/cypress/e2e/DoenetML/tagSpecific/extract.cy.js @@ -1551,7 +1551,7 @@ describe('Extract Tag Tests', function () { cy.log(`check properties`); cy.window().then(async (win) => { let stateVariables = await win.returnAllStateVariables1(); - expect(stateVariables['/e1'].stateValues.value).eqls(["/", 1,2]) + expect(stateVariables['/e1'].stateValues.value).eqls(["/", 1, 2]) expect(stateVariables['/e2'].stateValues.value).eq(0.75); }) diff --git a/cypress/e2e/DoenetML/tagSpecific/group.cy.js b/cypress/e2e/DoenetML/tagSpecific/group.cy.js index beeb16ef6d..db4c3c0c10 100644 --- a/cypress/e2e/DoenetML/tagSpecific/group.cy.js +++ b/cypress/e2e/DoenetML/tagSpecific/group.cy.js @@ -505,7 +505,7 @@ describe('Group Tag Tests', function () { cy.log('type in first textinput') cy.get('#\\/g\\/ti_input').clear().type("bye{enter}") cy.get('#\\/g\\/t').should('contain.text', 'bye') - + cy.window().then(async (win) => { let stateVariables = await win.returnAllStateVariables1(); expect(stateVariables['/g/ti'].stateValues.value).eq("bye") diff --git a/cypress/e2e/DoenetML/tagSpecific/line.cy.js b/cypress/e2e/DoenetML/tagSpecific/line.cy.js index ae3b55da1f..2da92ab704 100644 --- a/cypress/e2e/DoenetML/tagSpecific/line.cy.js +++ b/cypress/e2e/DoenetML/tagSpecific/line.cy.js @@ -769,7 +769,7 @@ describe('Line Tag Tests', function () { cy.window().then(async (win) => { let stateVariables = await win.returnAllStateVariables1(); - expect(stateVariables['/_line1'].stateValues.equation).eqls([ "/", "_", 2 ]); + expect(stateVariables['/_line1'].stateValues.equation).eqls(["/", "_", 2]); expect(stateVariables['/_line1'].stateValues.coeff0).eq("\uff3f"); expect(stateVariables['/_line1'].stateValues.coeffvar1).eq("\uff3f"); expect(stateVariables['/_line1'].stateValues.coeffvar2).eq("\uff3f"); @@ -784,7 +784,7 @@ describe('Line Tag Tests', function () { expect(stateVariables['/_line3'].stateValues.coeffvar1).eq("\uff3f"); expect(stateVariables['/_line3'].stateValues.coeffvar2).eq("\uff3f"); - expect(stateVariables['/_line4'].stateValues.equation).eqls([ "/", "_", 2 ]); + expect(stateVariables['/_line4'].stateValues.equation).eqls(["/", "_", 2]); expect(stateVariables['/_line4'].stateValues.coeff0).eq("\uff3f"); expect(stateVariables['/_line4'].stateValues.coeffvar1).eq("\uff3f"); expect(stateVariables['/_line4'].stateValues.coeffvar2).eq("\uff3f"); diff --git a/cypress/e2e/DoenetML/tagSpecific/mathinput.cy.js b/cypress/e2e/DoenetML/tagSpecific/mathinput.cy.js index 3c3d15a9be..49d9a9c18a 100644 --- a/cypress/e2e/DoenetML/tagSpecific/mathinput.cy.js +++ b/cypress/e2e/DoenetML/tagSpecific/mathinput.cy.js @@ -1337,7 +1337,7 @@ describe('MathInput Tag Tests', function () { // pause so that can detect change cy.get(`#\\/iv1`).should('contain.text', 'x') cy.get('#\\/mi1 textarea').type(`-`, { force: true }).blur(); - cy.get(`#\\/iv1`).should('contain.text', 'x−') + cy.get(`#\\/iv1`).should('contain.text', 'x-') // since v1 was already invalid, can't be sure when have waited long enough // so click boolean input and wait for its effect to take @@ -1355,16 +1355,16 @@ describe('MathInput Tag Tests', function () { }) cy.get(`#\\/v1`).find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('x−') + expect(text.trim()).equal('x-') }); cy.get(`#\\/iv1`).find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('x−') + expect(text.trim()).equal('x-') }); cy.get(`#\\/v1a`).find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('x−') + expect(text.trim()).equal('x-') }); cy.get(`#\\/iv1a`).find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('x−') + expect(text.trim()).equal('x-') }); cy.log('Test internal values are set to the correct values') @@ -1408,16 +1408,16 @@ describe('MathInput Tag Tests', function () { }) cy.get(`#\\/v1`).find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('x−') + expect(text.trim()).equal('x-') }); cy.get(`#\\/iv1`).find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('x−') + expect(text.trim()).equal('x-') }); cy.get(`#\\/v1a`).find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('x−') + expect(text.trim()).equal('x-') }); cy.get(`#\\/iv1a`).find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('x−') + expect(text.trim()).equal('x-') }); cy.log('Test internal values are set to the correct values') @@ -1444,13 +1444,13 @@ describe('MathInput Tag Tests', function () { }) cy.get(`#\\/v1`).find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('x−') + expect(text.trim()).equal('x-') }); cy.get(`#\\/iv1`).find('.mjx-mrow').eq(0).invoke('text').then((text) => { expect(text.trim()).equal('x−y') }); cy.get(`#\\/v1a`).find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('x−') + expect(text.trim()).equal('x-') }); cy.get(`#\\/iv1a`).find('.mjx-mrow').eq(0).invoke('text').then((text) => { expect(text.trim()).equal('x−y') @@ -5762,7 +5762,7 @@ describe('MathInput Tag Tests', function () { win.postMessage({ doenetML: ` a -

Prefill with m: \\frac{a}{b} \\int_a^b f(x) dx

+

Prefill with m: \\frac{a}{b} \\int_a^b \\hat{f}(x) dx

Result:

Value: $input1

Raw value: $input1.rawRendererValue

@@ -5784,10 +5784,10 @@ describe('MathInput Tag Tests', function () { cy.get(`#\\/input1 .mq-editable-field`).invoke('text').then((text) => { - expect(text.replace(/[\s\u200B-\u200D\uFEFF]/g, '')).equal('ab∫baf(x)dx') + expect(text.replace(/[\s\u200B-\u200D\uFEFF]/g, '')).equal('ab∫ba^f(x)dx') }) cy.get('#\\/pv1 .mjx-mrow').eq(0).should('have.text', '\uff3f') - cy.get('#\\/pr1').should('have.text', 'Raw value: \\frac{a}{b} \\int_a^b f(x) dx') + cy.get('#\\/pr1').should('have.text', 'Raw value: \\frac{a}{b} \\int_a^b \\hat{f}(x) dx') cy.get(`#\\/input2 .mq-editable-field`).invoke('text').then((text) => { expect(text.replace(/[\s\u200B-\u200D\uFEFF]/g, '')).equal('hellothere(a)(b)') @@ -5806,7 +5806,7 @@ describe('MathInput Tag Tests', function () { let stateVariables = await win.returnAllStateVariables1(); expect(stateVariables['/input1'].stateValues.value).eq('\uff3f'); expect(stateVariables['/input1'].stateValues.immediateValue).eq('\uff3f'); - expect(stateVariables['/input1'].stateValues.rawRendererValue).eq('\\frac{a}{b} \\int_a^b f(x) dx'); + expect(stateVariables['/input1'].stateValues.rawRendererValue).eq('\\frac{a}{b} \\int_a^b \\hat{f}(x) dx'); expect(stateVariables['/input2'].stateValues.value).eqls(["*", "h", "e", "l", "l", "o", "t", "h", "e", "r", "e", "a", "b"]) expect(stateVariables['/input2'].stateValues.immediateValue).eqls(["*", "h", "e", "l", "l", "o", "t", "h", "e", "r", "e", "a", "b"]) expect(stateVariables['/input2'].stateValues.rawRendererValue).eq('hello\\ there (a)(b)'); @@ -5815,19 +5815,19 @@ describe('MathInput Tag Tests', function () { expect(stateVariables['/input3'].stateValues.rawRendererValue).eq('\\text{hello there} (a)(b)'); }) - cy.get("#\\/input1 textarea").type("{ctrl+end}{leftArrow}{leftArrow}{leftArrow}{leftArrow}{leftArrow}{leftArrow}{backspace}{backspace}{backspace}{enter}", { force: true }) + cy.get("#\\/input1 textarea").type("{ctrl+end}{leftArrow}{leftArrow}{leftArrow}{leftArrow}{leftArrow}{leftArrow}{backspace}{backspace}f{enter}", { force: true }) - cy.get('#\\/pv1 .mjx-mrow').should('contain.text', '(ab)af(x)dx') + cy.get('#\\/pv1 .mjx-mrow').should('contain.text', '(ab)∫baf(x)dx') cy.get(`#\\/input1 .mq-editable-field`).invoke('text').then((text) => { - expect(text.replace(/[\s\u200B-\u200D\uFEFF]/g, '')).equal('abaf(x)dx') + expect(text.replace(/[\s\u200B-\u200D\uFEFF]/g, '')).equal('ab∫baf(x)dx') }) - cy.get('#\\/pr1').should('have.text', 'Raw value: \\frac{a}{b}af(x)dx') + cy.get('#\\/pr1').should('have.text', 'Raw value: \\frac{a}{b}\\int_a^bf(x)dx') cy.window().then(async (win) => { let stateVariables = await win.returnAllStateVariables1(); - expect(stateVariables['/input1'].stateValues.value).eqls(["*", ["/", "a", "b"], "a", ["apply", "f", "x"], "d", "x"]) - expect(stateVariables['/input1'].stateValues.immediateValue).eqls(["*", ["/", "a", "b"], "a", ["apply", "f", "x"], "d", "x"]) - expect(stateVariables['/input1'].stateValues.rawRendererValue).eq('\\frac{a}{b}af(x)dx'); + // expect(stateVariables['/input1'].stateValues.value).eqls(["*", ["/", "a", "b"], "a", ["apply", "f", "x"], "d", "x"]) + // expect(stateVariables['/input1'].stateValues.immediateValue).eqls(["*", ["/", "a", "b"], "a", ["apply", "f", "x"], "d", "x"]) + expect(stateVariables['/input1'].stateValues.rawRendererValue).eq('\\frac{a}{b}\\int_a^bf(x)dx'); }) cy.get("#\\/input2 textarea").type("{ctrl+end}{leftArrow}{leftArrow}{leftArrow}{leftArrow}{leftArrow}{leftArrow}{backspace}{backspace}{backspace}{backspace}{backspace}{backspace}{enter}", { force: true }) @@ -7557,13 +7557,13 @@ describe('MathInput Tag Tests', function () { cy.get('#\\/mi2 textarea').type("{end}{shift+home}{backspace}$45.23{enter}", { force: true }); cy.get('#\\/mi3 textarea').type("{end}{shift+home}{backspace}$45.23{enter}", { force: true }); - cy.get('#\\/m1 .mjx-mrow').should('contain.text', '\uff3f') + cy.get('#\\/m1 .mjx-mrow').should('contain.text', '$45.23') cy.get('#\\/m2 .mjx-mrow').should('contain.text', '45.23') cy.get('#\\/m3 .mjx-mrow').should('contain.text', '45.23') cy.window().then(async (win) => { let stateVariables = await win.returnAllStateVariables1(); - expect(stateVariables["/mi1"].stateValues.value).eq('\uff3f') + expect(stateVariables["/mi1"].stateValues.value).eqls(['unit', '$', 45.23]) expect(stateVariables["/mi2"].stateValues.value).eq(45.23) expect(stateVariables["/mi3"].stateValues.value).eq(45.23) }); @@ -7573,13 +7573,13 @@ describe('MathInput Tag Tests', function () { cy.get('#\\/mi2 textarea').type("{end}{shift+home}{backspace}78%{enter}", { force: true }); cy.get('#\\/mi3 textarea').type("{end}{shift+home}{backspace}78%{enter}", { force: true }); - cy.get('#\\/m1 .mjx-mrow').should('contain.text', '\uff3f') + cy.get('#\\/m1 .mjx-mrow').should('contain.text', '78%') cy.get('#\\/m2 .mjx-mrow').should('contain.text', '78') cy.get('#\\/m3 .mjx-mrow').should('contain.text', '78') cy.window().then(async (win) => { let stateVariables = await win.returnAllStateVariables1(); - expect(stateVariables["/mi1"].stateValues.value).eq('\uff3f') + expect(stateVariables["/mi1"].stateValues.value).eqls(['unit', 78, '%']) expect(stateVariables["/mi2"].stateValues.value).eq(78) expect(stateVariables["/mi3"].stateValues.value).eq(78) }); @@ -7588,13 +7588,13 @@ describe('MathInput Tag Tests', function () { cy.get('#\\/mi2 textarea').type(`{end}{shift+home}{backspace}$34,000%dx{enter}`, { force: true }); cy.get('#\\/mi3 textarea').type(`{end}{shift+home}{backspace}$34,000%dx{enter}`, { force: true }); - cy.get('#\\/m1 .mjx-mrow').should('contain.text', '\uff3f') + cy.get('#\\/m1 .mjx-mrow').should('contain.text', '$(34000%)dx') cy.get('#\\/m2 .mjx-mrow').should('contain.text', '34,0dx') cy.get('#\\/m3 .mjx-mrow').should('contain.text', '34000') cy.window().then(async (win) => { let stateVariables = await win.returnAllStateVariables1(); - expect(stateVariables["/mi1"].stateValues.value).eq('\uff3f') + expect(stateVariables["/mi1"].stateValues.value).eqls(['unit', '$', ['*', ['unit', 34000, '%'], "d", "x"]]) expect(stateVariables["/mi2"].stateValues.value).eqls(["list", 34, ["*", 0, "d", "x"]]) expect(stateVariables["/mi3"].stateValues.value).eq(34000) }); diff --git a/cypress/e2e/DoenetML/tagSpecific/mathoperators.cy.js b/cypress/e2e/DoenetML/tagSpecific/mathoperators.cy.js index bb9f85a92e..cd886c6abe 100644 --- a/cypress/e2e/DoenetML/tagSpecific/mathoperators.cy.js +++ b/cypress/e2e/DoenetML/tagSpecific/mathoperators.cy.js @@ -2071,10 +2071,10 @@ describe('Math Operator Tag Tests', function () { expect(text.trim()).equal('1') }); cy.get('#\\/_floor4').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('floor(2.1x)') + expect(text.trim()).equal('⌊2.1x⌋') }); cy.get('#\\/_ceil4').find('.mjx-mrow').eq(0).invoke('text').then((text) => { - expect(text.trim()).equal('ceil(−3.2y)') + expect(text.trim()).equal('⌈−3.2y⌉') }); cy.window().then(async (win) => { diff --git a/cypress/e2e/DoenetML/tagSpecific/selectrandomnumbers.cy.js b/cypress/e2e/DoenetML/tagSpecific/selectrandomnumbers.cy.js index 9c8af532df..c746d34fab 100644 --- a/cypress/e2e/DoenetML/tagSpecific/selectrandomnumbers.cy.js +++ b/cypress/e2e/DoenetML/tagSpecific/selectrandomnumbers.cy.js @@ -47,7 +47,7 @@ describe('SelectRandomNumbers Tag Tests', function () { let varX = me.math.variance(samples, 'uncorrected'); expect(meanX).closeTo(0.5, 0.05); - expect(varX).closeTo(1 / 12, 0.005) + expect(varX).closeTo(1 / 12, 0.02) let firstSelect = stateVariables[stateVariables[stateVariables["/_map1"].replacements[0].componentName].replacements[0].componentName] expect(firstSelect.stateValues.mean).closeTo(0.5, 1E-10) @@ -102,7 +102,7 @@ describe('SelectRandomNumbers Tag Tests', function () { let varX = me.math.variance(samples, 'uncorrected'); expect(meanX).closeTo(4, 0.5); - expect(varX).closeTo(8 ** 2 / 12, 0.5) + expect(varX).closeTo(8 ** 2 / 12, 1) let firstSelect = stateVariables[stateVariables[stateVariables["/_map1"].replacements[0].componentName].replacements[0].componentName] expect(firstSelect.stateValues.mean).closeTo(4, 1E-10) @@ -156,7 +156,7 @@ describe('SelectRandomNumbers Tag Tests', function () { let varX = me.math.variance(samples, 'uncorrected'); expect(meanX).closeTo(-4.5, 0.05); - expect(varX).closeTo(1 / 12, 0.01) + expect(varX).closeTo(1 / 12, 0.02) let firstSelect = stateVariables[stateVariables[stateVariables["/_map1"].replacements[0].componentName].replacements[0].componentName] expect(firstSelect.stateValues.mean).closeTo(-4.5, 1E-10) @@ -312,7 +312,7 @@ describe('SelectRandomNumbers Tag Tests', function () { let meanX = me.math.mean(samples); let varX = me.math.variance(samples, 'uncorrected'); - expect(meanX).closeTo(0, 0.1); + expect(meanX).closeTo(0, 0.2); expect(varX).closeTo(1, 0.2) let firstSelect = stateVariables[stateVariables[stateVariables["/_map1"].replacements[0].componentName].replacements[0].componentName] @@ -1467,7 +1467,7 @@ describe('SelectRandomNumbers Tag Tests', function () { cy.get('#\\/_text1').should('have.text', 'a') //wait for page to load - + cy.window().then(async (win) => { let stateVariables = await win.returnAllStateVariables1(); @@ -1476,15 +1476,15 @@ describe('SelectRandomNumbers Tag Tests', function () { let n3 = stateVariables["/n3"].stateValues.value; let n4 = stateVariables["/n4"].stateValues.value; - cy.get('#\\/n1').should('have.text', String(Math.round(n1*10**8)/10**8)) - cy.get('#\\/n2').should('have.text', String(Math.round(n2*10**1)/10**1)) - cy.get('#\\/n3').should('have.text', String(Math.round(n3*10**3)/10**3)) - cy.get('#\\/n4').should('have.text', String(n4)+".0") + cy.get('#\\/n1').should('have.text', String(Math.round(n1 * 10 ** 8) / 10 ** 8)) + cy.get('#\\/n2').should('have.text', String(Math.round(n2 * 10 ** 1) / 10 ** 1)) + cy.get('#\\/n3').should('have.text', String(Math.round(n3 * 10 ** 3) / 10 ** 3)) + cy.get('#\\/n4').should('have.text', String(n4) + ".0") - cy.get('#\\/n1a').should('have.text', String(Math.round(n1*10**8)/10**8)) - cy.get('#\\/n2a').should('have.text', String(Math.round(n2*10**1)/10**1)) - cy.get('#\\/n3a').should('have.text', String(Math.round(n3*10**3)/10**3)) - cy.get('#\\/n4a').should('have.text', String(n4)+".0") + cy.get('#\\/n1a').should('have.text', String(Math.round(n1 * 10 ** 8) / 10 ** 8)) + cy.get('#\\/n2a').should('have.text', String(Math.round(n2 * 10 ** 1) / 10 ** 1)) + cy.get('#\\/n3a').should('have.text', String(Math.round(n3 * 10 ** 3) / 10 ** 3)) + cy.get('#\\/n4a').should('have.text', String(n4) + ".0") }); diff --git a/src/Core/Core.js b/src/Core/Core.js index fadbe3f8c8..2278fbabc4 100644 --- a/src/Core/Core.js +++ b/src/Core/Core.js @@ -4801,13 +4801,19 @@ export default class Core { args.dependencyNamesByKey = stateVarObj.dependencyNames.namesByKey; // only include array keys that exist + // unless given a Javascript array let newDesiredStateVariableValues = {}; for (let vName in args.desiredStateVariableValues) { - newDesiredStateVariableValues[vName] = {} - for (let key in args.desiredStateVariableValues[vName]) { - if (args.arrayKeys.includes(key)) { - newDesiredStateVariableValues[vName][key] = args.desiredStateVariableValues[vName][key]; + if (Array.isArray(args.desiredStateVariableValues[vName])) { + newDesiredStateVariableValues[vName] = args.desiredStateVariableValues[vName]; + } else { + newDesiredStateVariableValues[vName] = {} + + for (let key in args.desiredStateVariableValues[vName]) { + if (args.arrayKeys.includes(key)) { + newDesiredStateVariableValues[vName][key] = args.desiredStateVariableValues[vName][key]; + } } } } @@ -8470,11 +8476,6 @@ export default class Core { await this.processStateVariableTriggers(); - // it is possible that components were added back to componentNamesToUpdateRenderers - // while processing the renderer instructions - // so delete any names that were just addressed - componentNamesToUpdate.forEach(cName => this.updateInfo.componentsToUpdateRenderers.delete(cName)); - // TODO: when should we actually warn of unmatchedChildren // It shouldn't be just on update, but also on initial construction! // Also, should be more than a console.warn @@ -9355,7 +9356,7 @@ export default class Core { } } } else { - if (depStateVarObj.nDimensions === 1) { + if (depStateVarObj.nDimensions === 1 || !Array.isArray(newInstruction.desiredValue)) { Object.assign(arrayInstructionInProgress.desiredValue, newInstruction.desiredValue); } else { // need to convert multidimensional array (newInstruction.desiredValue) diff --git a/src/Core/components/Math.js b/src/Core/components/Math.js index b7b13c6944..8d0c265e80 100644 --- a/src/Core/components/Math.js +++ b/src/Core/components/Math.js @@ -2134,7 +2134,10 @@ function calculateExpressionWithCodes({ dependencyValues, changes }) { // if don't have any string or math children, // set expressionWithCodes to be null, // which will indicate that value should use valueShadow - return { setValue: { expressionWithCodes: null } } + return { + setValue: { expressionWithCodes: null }, + setEssentialValue: { expressionWithCodes: null } + } } } diff --git a/src/Core/components/Point.js b/src/Core/components/Point.js index 094fea22e4..18e57822ed 100644 --- a/src/Core/components/Point.js +++ b/src/Core/components/Point.js @@ -12,6 +12,7 @@ export default class Point extends GraphicalComponent { movePoint: this.movePoint.bind(this), switchPoint: this.switchPoint.bind(this), pointClicked: this.pointClicked.bind(this), + mouseDownOnPoint: this.mouseDownOnPoint.bind(this), }); } diff --git a/src/Core/utils/booleanLogic.js b/src/Core/utils/booleanLogic.js index c1cd72f81e..55b85d1cc6 100644 --- a/src/Core/utils/booleanLogic.js +++ b/src/Core/utils/booleanLogic.js @@ -816,19 +816,11 @@ export function splitSymbolsIfMath({ logicTree, nonMathCodes, foundNonMath = fal let operands = logicTree.slice(1); if (["and", "not", "or"].includes(operator)) { - if (operator === "apply") { - return [operator, operands[0], ...operands.slice(1).map(x => splitSymbolsIfMath({ - logicTree: x, - nonMathCodes, foundNonMath, - init - }))] - } else { - return [operator, ...operands.map(x => splitSymbolsIfMath({ - logicTree: x, - nonMathCodes, foundNonMath, - init - }))] - } + return [operator, ...operands.map(x => splitSymbolsIfMath({ + logicTree: x, + nonMathCodes, foundNonMath, + init + }))] } if (operands.some(x => nonMathCodes.includes(x))) { @@ -836,11 +828,58 @@ export function splitSymbolsIfMath({ logicTree, nonMathCodes, foundNonMath = fal } if (operator === "apply") { - return [operator, operands[0], ...operands.slice(1).map(x => splitSymbolsIfMath({ + + operands = [operands[0], ...operands.slice(1).map(x => splitSymbolsIfMath({ logicTree: x, nonMathCodes, foundNonMath, init: false - }))] + }))]; + + // look for int + let foundInt = false; + if (operands[0] === "int") { + foundInt = true; + } else if (Array.isArray(operands[0])) { + if (operands[0][0] === "^") { + if (operands[0][1] === "int") { + foundInt = true; + } else if (Array.isArray(operands[0][1])) { + if (operands[0][1][0] === "_" && operands[0][1][1] === "int") { + foundInt = true; + } + } + } else if (operands[0][0] === "_") { + if (operands[0][1] === "int") { + foundInt = true; + } + } + } + + if (foundInt) { + + + // round trip from tree -> math-expression -> tree to flatten tree + operands = me.fromAst([operator, ...operands]).tree.slice(1); + + let integrand = operands[1]; + if (Array.isArray(integrand) && integrand[0] === "*") { + // look for consecutive factors of "d" followed by a string + + let ds = []; + for (let i = 0; i < integrand.length - 1; i++) { + let factor1 = integrand[i]; + if (factor1 === "d") { + let factor2 = integrand[i + 1]; + integrand.splice(i, 2); + ds.push(["d", factor2]); + i--; + } + } + integrand.push(...ds); + + } + } + return [operator, ...operands]; } else if (operator === "angle") { let newOperands = []; for (let op of operands) { diff --git a/src/Core/utils/checkEquality.js b/src/Core/utils/checkEquality.js index 3c197dd67b..1fd4ff8bb2 100644 --- a/src/Core/utils/checkEquality.js +++ b/src/Core/utils/checkEquality.js @@ -76,7 +76,7 @@ export default function checkEquality({ } } - let normalize = function (x) { + let normalize = function (x, forNumeric = false) { if (!(x instanceof me.class)) { x = me.fromAst(x); } @@ -87,20 +87,26 @@ export default function checkEquality({ x = me.fromAst(setStringsInTreeToLowerCase(x.tree)); } - if (simplify === "none") { + let effectiveSimplify = simplify, effectiveExpand = expand; + if (forNumeric) { + effectiveSimplify = "full"; + effectiveExpand = true; + } + + if (effectiveSimplify === "none") { if (allowedErrorInNumbers > 0) { // only if allowing rounding, do we replace constants with floats x = x.constants_to_floats(); } - } else if (simplify === "numberspreserveorder") { + } else if (effectiveSimplify === "numberspreserveorder") { x = x.evaluate_numbers({ max_digits: Infinity, skip_ordering: true }); - } else if (simplify === "number") { + } else if (effectiveSimplify === "number") { x = x.evaluate_numbers({ max_digits: Infinity }); } else { x = x.evaluate_numbers({ max_digits: Infinity, evaluate_functions: true }); } return normalizeMathExpression({ - value: x, simplify: simplify, expand: expand + value: x, simplify: effectiveSimplify, expand: effectiveExpand }); } @@ -110,8 +116,14 @@ export default function checkEquality({ if (symbolicEquality) { check_equality = function (a, b) { - let expr_a = normalize(a); - let expr_b = normalize(b); + let expr_a = a; + let expr_b = b; + if (!(a instanceof me.class)) { + expr_a = me.fromAst(a); + } + if (!(b instanceof me.class)) { + expr_b = me.fromAst(b); + } if (nSignErrorsMatched > 0) { // We have to make a deep copy @@ -262,6 +274,11 @@ export default function checkEquality({ let matchByExactPositionsOnRecursion = false; if (haveMathExpressions) { + + // normalize at the beginning so that expand vectors, etc. + object1 = normalize(object1, !symbolicEquality); + object2 = normalize(object2, !symbolicEquality); + // if can convert same type of math-expression // change object1 and object2 to array of asts // otherwise return that are unequal diff --git a/src/Core/utils/copy.js b/src/Core/utils/copy.js index 3d39aa34a7..44f19fc1e6 100644 --- a/src/Core/utils/copy.js +++ b/src/Core/utils/copy.js @@ -64,7 +64,7 @@ export function postProcessCopy({ serializedComponents, componentName, if (init) { downDep[component.originalName][0].firstLevelReplacement = true; } - if(markAsPrimaryShadow) { + if (markAsPrimaryShadow) { downDep[component.originalName][0].isPrimaryShadow = true; } if (component.state) { @@ -401,7 +401,7 @@ export async function verifyReplacementsMatchSpecifiedType({ component, // if the only discrepancy is the components are the wrong type, // with number of sources matching the number of components - // then wrap that each replacement with a blank component we are creating, + // then wrap each replacement with a blank component we are creating, // i.e., add each current replacement as the child of a new component let wrapExistingReplacements = replacementTypes.length === requiredLength @@ -410,8 +410,21 @@ export async function verifyReplacementsMatchSpecifiedType({ component, // let uniqueIdentifiersUsed; let originalReplacements; + if (wrapExistingReplacements && replacementChanges) { + // if we have replacement changes, we can wrap only if we are replacing all components + // in a single add + if (replacementChanges.length === 1 && replacementChanges[0].numberReplacementsToReplace === requiredLength) { + originalReplacements = replacementChanges[0].serializedReplacements; + } else { + wrapExistingReplacements = false; + } + } + + if (wrapExistingReplacements) { - originalReplacements = replacements; + if (!originalReplacements) { + originalReplacements = replacements; + } } else { // since clearing out all replacements, reset all workspace variables workspace.numReplacementsBySource = []; diff --git a/src/Viewer/core.js b/src/Viewer/core.js index 734803379d..c6e137980a 100644 --- a/src/Viewer/core.js +++ b/src/Viewer/core.js @@ -1,111 +1,588 @@ -var Core=function(){"use strict";class ParameterStack{constructor(e){this.stack=[{}],void 0!==e&&Object.assign(this.parameters,e)}get parameters(){return this.stack[this.stack.length-1]}push(e,t=!0){let n={};t?(Object.assign(n,this.parameters),void 0!==e&&Object.assign(n,e)):n=e,this.stack.push(n)}pop(){let e=this.stack.pop();return 0===this.stack.length&&(this.stack=[{}]),e}}class Numerics{constructor({maxIterationsRoot:e=80,maxIterationsMinimize:t=500,eps:n=1e-6}={}){this.maxIterationsRoot=e,this.maxIterationsMinimize=t,this.eps=n}fzero(e,t,n){var r,a,i,o,s,l,u,c,p,d,m,f,h,y,b,g,v,T,N,C,A=this.eps,S=this.maxIterationsRoot,x=0;if(Array.isArray(t)){if(t.length<2)throw new Error("fzero: length of array x0 has to be at least two.");r=t[0],o=e.call(n,r),a=t[1],s=e.call(n,a)}else{for(r=t,o=e.call(n,r),d=(c=[.9*(u=0===r?1:r),1.1*u,u-1,u+1,.5*u,1.5*u,-u,2*u,-10*u,10*u]).length,p=0;p0)return Array.isArray(t)?this.fminbr(e,[r,a],n).x:this.Newton(e,r,n);for(i=r,l=o;x=v&&Math.abs(o)>Math.abs(s)&&(b=i-a,r===i?(T=b*(y=s/o),N=1-y):(T=(g=s/o)*(b*(N=o/l)*(N-(y=s/l))-(a-r)*(y-1)),N=(N-1)*(y-1)*(g-1)),T>0?N=-N:T=-T,T<.75*b*N-.5*Math.abs(v*N)&&T0?v:-v),r=a,o=s,a+=C,((s=e.call(n,a))>0&&l>0||s<0&&l<0)&&(i=r,l=o),x++}return a}fminbr(e,t,n,r){let a=void 0!==r?r:this.eps;var i,o,s,l,u,c,p,d,m,f,h,y,b,g,v,T,N=.5*(3-Math.sqrt(5)),C=a,A=a,S=this.maxIterationsMinimize,x=0;if(!Array.isArray(t)||t.length<2)throw new Error("Numerics.fminbr: length of array x0 has to be at least two.");if(l=(i=t[0])+N*((o=t[1])-i),p=e.call(n,l),Number.isNaN(p))return{success:!1};for(s=l,u=l,c=p,d=p;x=h&&(b=(s-l)*(g=(s-l)*(c-d))-(s-u)*(v=(s-u)*(c-p)),(g=2*(g-v))>0?b=-b:g=-g,Math.abs(b)g*(i-s+2*h)&&b0?h:-h),v=s+y,T=e.call(n,v),Number.isNaN(T))return{success:!1};T<=c?(vi;)r=this.D(e,n)(t),Math.abs(r)>i?t-=o/r:t+=.2*Math.random()-1,o=e.apply(n,[t]),a+=1;return t}D(e,t){return null!=t?function(t){var n=1e-5;return(e(t+n)-e(t-n))/2e-5}:function(n){var r=1e-5;return(e.apply(t,[n+r])-e.apply(t,[n-r]))/2e-5}}}function _prng_restore(e,t,n){let r=n&&n.state;r&&("object"==typeof r&&t.copy(r,t),e.state=()=>t.copy(t,{}))}function prng_alea(e,t){let n=new AleaGen(e),r=()=>n.next();return r.double=()=>r()+11102230246251565e-32*(2097152*r()|0),r.int32=()=>4294967296*n.next()|0,r.quick=r,_prng_restore(r,n,t),r}class AleaGen{constructor(e){null==e&&(e=+new Date);let t=4022871197;function n(e){e=String(e);for(let n=0;n>>0,r-=t,r*=t,t=r>>>0,r-=t,t+=4294967296*r}return 2.3283064365386963e-10*(t>>>0)}this.c=1,this.s0=n(" "),this.s1=n(" "),this.s2=n(" "),this.s0-=n(e),this.s0<0&&(this.s0+=1),this.s1-=n(e),this.s1<0&&(this.s1+=1),this.s2-=n(e),this.s2<0&&(this.s2+=1)}next(){let{c:e,s0:t,s1:n,s2:r}=this,a=2091639*t+2.3283064365386963e-10*e;return this.s0=n,this.s1=r,this.s2=a-(this.c=0|a)}copy(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var mathExpressions_umd={exports:{}};(function(module,exports){!function(e,t){module.exports=t()}(0,(function(){const get_tree=function(e){if(null!=e)return void 0!==e.tree?e.tree:e};function*subsets(e,t){var n=e.length;if(void 0===t&&(t=n),0!==t){for(let t=0;t2?a=a.concat(r[i].slice(1)):a.push(r[i]);r=a}return[n].concat(r)}const unflattenRight=function(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if((r=r.map((function(e,t){return unflattenRight(e)}))).length>2&&is_associative$1[n]){for(var a=[n,r[0],void 0],i=a,o=1;o2&&is_associative$1[n]){for(var a=[n,void 0,r[r.length-1]],i=a,o=r.length-2;o>0;o--)i[1]=[n,void 0,r[o]],i=i[1];return i[1]=r[0],a}return[n].concat(r)},allChildren=function(e){if(!Array.isArray(e))return[];var t=e[0],n=e.slice(1);return is_associative$1[t]?n.reduce((function(e,n){return Array.isArray(n)&&n[0]===t?e.concat(allChildren(n)):e.concat([n])}),[]):n};function remove_duplicate_negatives(e){if(!Array.isArray(e))return e;var t=e[0],n=e.slice(1);return"-"===t&&"-"===n[0][0]?remove_duplicate_negatives(n[0][1]):(n=n.map(remove_duplicate_negatives),[t].concat(n))}function normalize_negatives_in_factors(e){if(!Array.isArray(e))return e;var t=e[0],n=e.slice(1);if(n=n.map(normalize_negatives_in_factors),"*"!==t&&"/"!==t)return[t].concat(n);for(var r=1,a=[],i=0;isort_key(e,t)))):s=[sort_key(i,t)],a.push([o,s]),a}var l=r.length,u=r.map(sort_key,t);return"*"===n?[4,"product",l,u]:"/"===n?[4,"quotient",l,u]:"+"===n?[5,"sum",l,u]:"-"===n?t.ignore_negatives?u[0]:[6,"minus",l,u]:[7,n,l,u]}function arrayCompare(e,t){if(Array.isArray(e)){if(Array.isArray(t)){let n=Math.min(e.length,t.length);for(let r=0;rt.length?1:0}return 1}return Array.isArray(t)||et?1:0}function compare_function(e,t,n={}){return arrayCompare(sort_key(e,n),sort_key(t,n))}function coeff_factors_from_term(e,t){if("string"==typeof e){let n=t.indexOf(e);-1===n&&(t.push(e),n=t.length-1);let r=[];return r[n]=1,{factor_contains:r,coeff:1}}if(Array.isArray(e)){let n=e[0],r=e.slice(1);if("*"===n){let e=[],n=[];for(let a of r)if("string"!=typeof a)if(Array.isArray(a)&&"^"===a[0]||"-"===a[0]){let r=coeff_factors_from_term(a,t);for(let e in r.factor_contains)void 0===n[e]&&(n[e]=0),n[e]+=r.factor_contains[e];1!==r.coeff&&e.push(r.coeff)}else e.push(a);else{let e=t.indexOf(a);-1===e&&(t.push(a),e=t.length-1),void 0===n[e]&&(n[e]=0),n[e]++}return e=0===e.length?1:1===e.length?e[0]:["*",...e],{factor_contains:n,coeff:e}}if("^"===n){let e=r[0],n=r[1],a=[];if("string"==typeof e&&Number.isFinite(n)){let r=t.indexOf(e);return-1===r&&(t.push(e),r=t.length-1),a[r]=n,{factor_contains:a,coeff:1}}}else{if("-"===n){let e=coeff_factors_from_term(r[0],t),n=-1;return"number"==typeof e.coeff?n*=e.coeff:n=["-",e.coeff],{factor_contains:e.factor_contains,coeff:n}}if("/"===n){let e=coeff_factors_from_term(r[0],t),n=["/",e.coeff,r[1]];return{factor_contains:e.factor_contains,coeff:n}}}}return{factor_contains:[],coeff:e}}function default_order(e,t){void 0===t&&(t={});var n=get_tree(e);return n=normalize_negatives(n=flatten$5(n)),normalize_negatives(function e(n){if(!Array.isArray(n))return n;var r=n[0],a=n.slice(1);if(a=a.map(e),"+"===r){let e=[],n=[],r=[];for(let t of a){let a=coeff_factors_from_term(t,e);n.push(a.factor_contains),r.push(a.coeff)}let i=[];for(let[t,r]of e.entries()){let e={varname:r,exponents_in_term:[]};for(let r=0;re.varname[...t,-n.exponents_in_term[e]]),[]);n.push(sort_key(r[e],t)),o.push(n)}let s=[];for(let[e,t]of a.entries())s.push({term:t,sort_key:o[e]});s.sort(((e,t)=>arrayCompare(e.sort_key,t.sort_key))),a=s.map((e=>e.term))}else if("*"===r){let e=[],n=[];for(let t of a)["tuple","list","vector","interval","set","array","matrix"].includes(t[0])?n.push(t):e.push(t);e.sort(((e,n)=>compare_function(e,n,t))),a=[...e,...n]}else if("="===r||"and"===r||"or"===r||"ne"===r||"union"===r||"intersect"===r)a.sort(((e,n)=>compare_function(e,n,t)));else if(">"===r||"ge"===r)a=a.reverse(),r=">"===r?"<":"le";else if("gts"===r){var i=a[0],o=a[1];if("tuple"!==i[0]||"tuple"!==o[0])throw new Error("Badly formed ast");r="lts",a=[i=["tuple"].concat(i.slice(1).reverse()),o=["tuple"].concat(o.slice(1).reverse())]}else if("ni"===r||"notni"===r||"superset"===r||"notsuperset"===r)a=a.reverse(),r="ni"===r?"in":"notni"===r?"notin":"superset"===r?"subset":"notsubset";else if("-"===r&&"*"===a[0][0])return a[0][1]=["-",a[0][1]],a[0];return[r].concat(a)}(n))}function _extends$1(){return _extends$1=Object.assign?Object.assign.bind():function(e){for(var t=1;te[t]))}var MATRIX_OPTIONS=["Matrix","Array"],NUMBER_OPTIONS=["number","BigNumber","Fraction"];function configFactory(e,t){function n(n){if(n){var r=mapObject$1(e,clone$2);validateOption(n,"matrix",MATRIX_OPTIONS),validateOption(n,"number",NUMBER_OPTIONS),deepExtend(e,n);var a=mapObject$1(e,clone$2),i=mapObject$1(n,clone$2);return t("config",a,r,i),a}return mapObject$1(e,clone$2)}return n.MATRIX_OPTIONS=MATRIX_OPTIONS,n.NUMBER_OPTIONS=NUMBER_OPTIONS,Object.keys(DEFAULT_CONFIG).forEach((t=>{Object.defineProperty(n,t,{get:()=>e[t],enumerable:!0,configurable:!0})})),n}function contains$2(e,t){return-1!==e.indexOf(t)}function validateOption(e,t,n){void 0===e[t]||contains$2(n,e[t])||console.warn('Warning: Unknown value "'+e[t]+'" for configuration option "'+t+'". Available options: '+n.map((e=>JSON.stringify(e))).join(", ")+".")}var config$1=function(e){if(e)throw new Error("The global config is readonly. \nPlease create a mathjs instance if you want to change the default configuration. \nExample:\n\n import { create, all } from 'mathjs';\n const mathjs = create(all);\n mathjs.config({ number: 'BigNumber' });\n");return Object.freeze(DEFAULT_CONFIG)};_extends$1(config$1,DEFAULT_CONFIG,{MATRIX_OPTIONS:MATRIX_OPTIONS,NUMBER_OPTIONS:NUMBER_OPTIONS});var commonjsGlobal$1="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==commonjsGlobal?commonjsGlobal:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function getAugmentedNamespace(e){var t=e.default;if("function"==typeof t){var n=function(){return t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})})),n}var typedFunction$1={exports:{}};!function(e,t){e.exports=function(){function e(){return!0}function t(){return!1}function n(){}return function r(){var a=[{name:"number",test:function(e){return"number"==typeof e}},{name:"string",test:function(e){return"string"==typeof e}},{name:"boolean",test:function(e){return"boolean"==typeof e}},{name:"Function",test:function(e){return"function"==typeof e}},{name:"Array",test:Array.isArray},{name:"Date",test:function(e){return e instanceof Date}},{name:"RegExp",test:function(e){return e instanceof RegExp}},{name:"Object",test:function(e){return"object"==typeof e&&null!==e&&e.constructor===Object}},{name:"null",test:function(e){return null===e}},{name:"undefined",test:function(e){return void 0===e}}],i={name:"any",test:e},o=[],s=[],l={types:a,conversions:s,ignore:o};function u(e){var t=H(l.types,(function(t){return t.name===e}));if(t)return t;if("any"===e)return i;var n=H(l.types,(function(t){return t.name.toLowerCase()===e.toLowerCase()}));throw new TypeError('Unknown type "'+e+'"'+(n?'. Did you mean "'+n.name+'"?':""))}function c(e){return e===i?999:l.types.indexOf(e)}function p(e){var t=H(l.types,(function(t){return t.test(e)}));if(t)return t.name;throw new TypeError("Value has unknown type. Value: "+e)}function d(e){return e.map((function(e){var t=e.types.map(N);return(e.restParam?"...":"")+t.join("|")})).join(",")}function m(e,t){var n=0===e.indexOf("..."),r=(n?e.length>3?e.slice(3):"any":e).split("|").map(M).filter(F).filter(k),a=function(e,t){var n={};return e.forEach((function(e){-1!==t.indexOf(e.from)||-1===t.indexOf(e.to)||n[e.from]||(n[e.from]=e)})),Object.keys(n).map((function(e){return n[e]}))}(t,r),i=r.map((function(e){var t=u(e);return{name:e,typeIndex:c(t),test:t.test,conversion:null,conversionIndex:-1}})),o=a.map((function(e){var n=u(e.from);return{name:e.from,typeIndex:c(n),test:n.test,conversion:e,conversionIndex:t.indexOf(e)}}));return{types:i.concat(o),restParam:n}}function f(e,t,n){var r=[];return""!==e.trim()&&(r=e.split(",").map(M).map((function(e,t,r){var a=m(e,n);if(a.restParam&&t!==r.length-1)throw new SyntaxError('Unexpected rest parameter "'+e+'": only allowed for the last parameter');return a}))),r.some(L)?null:{params:r,fn:t}}function h(e){var t=j(e);return!!t&&t.restParam}function y(e){return e.types.some((function(e){return null!=e.conversion}))}function b(t){if(t&&0!==t.types.length){if(1===t.types.length)return u(t.types[0].name).test;if(2===t.types.length){var n=u(t.types[0].name).test,r=u(t.types[1].name).test;return function(e){return n(e)||r(e)}}var a=t.types.map((function(e){return u(e.name).test}));return function(e){for(var t=0;t=a+1}}return 0===e.length?function(e){return 0===e.length}:1===e.length?(n=b(e[0]),function(e){return n(e[0])&&1===e.length}):2===e.length?(n=b(e[0]),r=b(e[1]),function(e){return n(e[0])&&r(e[1])&&2===e.length}):(t=e.map(b),function(e){for(var n=0;n0){var u=p(t[i]);return(r=new TypeError("Unexpected type of argument in function "+o+" (expected: "+a.join(" or ")+", actual: "+u+", index: "+i+")")).data={category:"wrongType",fn:o,index:i,actual:u,expected:a},r}}else s=l}var c=s.map((function(e){return h(e.params)?1/0:e.params.length}));if(t.lengthd?((r=new TypeError("Too many arguments in function "+o+" (expected: "+d+", actual: "+t.length+")")).data={category:"tooManyArgs",fn:o,index:t.length,expectedLength:d},r):((r=new TypeError('Arguments of type "'+t.join(", ")+'" do not match any of the defined signatures of function '+o+".")).data={category:"mismatch",actual:t.map(p)},r)}function x(e){for(var t=999,n=0;n=a:s?a>=i:a===i}function R(e,r){if(0===Object.keys(r).length)throw new SyntaxError("No signatures provided");var a=[];Object.keys(r).map((function(e){return f(e,r[e],l.conversions)})).filter(B).forEach((function(e){var t=H(a,(function(t){return I(t,e)}));if(t)throw new TypeError('Conflicting signatures "'+d(t.params)+'" and "'+d(e.params)+'".');a.push(e)}));var i=q(a,(function(e){return(e?D(e.params,!1):[]).map((function(t){return{params:t,fn:e.fn}}))})).filter(B);i.sort(E);var o=i[0]&&i[0].params.length<=2&&!h(i[0].params),s=i[1]&&i[1].params.length<=2&&!h(i[1].params),u=i[2]&&i[2].params.length<=2&&!h(i[2].params),c=i[3]&&i[3].params.length<=2&&!h(i[3].params),p=i[4]&&i[4].params.length<=2&&!h(i[4].params),m=i[5]&&i[5].params.length<=2&&!h(i[5].params),y=o&&s&&u&&c&&p&&m,v=i.map((function(e){return g(e.params)})),T=o?b(i[0].params[0]):t,N=s?b(i[1].params[0]):t,C=u?b(i[2].params[0]):t,A=c?b(i[3].params[0]):t,S=p?b(i[4].params[0]):t,x=m?b(i[5].params[0]):t,w=o?b(i[0].params[1]):t,V=s?b(i[1].params[1]):t,_=u?b(i[2].params[1]):t,R=c?b(i[3].params[1]):t,P=p?b(i[4].params[1]):t,k=m?b(i[5].params[1]):t,M=i.map((function(e){return O(e.params,e.fn)})),F=o?M[0]:n,L=s?M[1]:n,j=u?M[2]:n,U=c?M[3]:n,z=p?M[4]:n,G=m?M[5]:n,W=o?i[0].params.length:-1,K=s?i[1].params.length:-1,X=u?i[2].params.length:-1,Z=c?i[3].params.length:-1,Y=p?i[4].params.length:-1,J=m?i[5].params.length:-1,Q=y?6:0,ee=i.length,te=function(){for(var t=Q;t0?1:e<0?-1:0},log2$1=Math.log2||function(e){return Math.log(e)/Math.LN2},log10$2=Math.log10||function(e){return Math.log(e)/Math.LN10},log1p$1=Math.log1p||function(e){return Math.log(e+1)},cbrt$1=Math.cbrt||function(e){if(0===e)return e;var t,n=e<0;return n&&(e=-e),t=isFinite(e)?(e/((t=Math.exp(Math.log(e)/3))*t)+2*t)/3:e,n?-t:t},expm1$1=Math.expm1||function(e){return e>=2e-4||e<=-2e-4?Math.exp(e)-1:e+e*e/2+e*e*e/6};function formatNumberToBase(e,t,n){var r={2:"0b",8:"0o",16:"0x"}[t],a="";if(n){if(n<1)throw new Error("size must be in greater than 0");if(!isInteger$1(n))throw new Error("size must be an integer");if(e>2**(n-1)-1||e<-(2**(n-1)))throw new Error("Value must be in range [-2^".concat(n-1,", 2^").concat(n-1,"-1]"));if(!isInteger$1(e))throw new Error("Value must be an integer");e<0&&(e+=2**n),a="i".concat(n)}var i="";return e<0&&(e=-e,i="-"),"".concat(i).concat(r).concat(e.toString(t)).concat(a)}function format$3(e,t){if("function"==typeof t)return t(e);if(e===1/0)return"Infinity";if(e===-1/0)return"-Infinity";if(isNaN(e))return"NaN";var n,r,a="auto";if(t&&(t.notation&&(a=t.notation),isNumber$1(t)?n=t:isNumber$1(t.precision)&&(n=t.precision),t.wordSize&&"number"!=typeof(r=t.wordSize)))throw new Error('Option "wordSize" must be a number');switch(a){case"fixed":return toFixed$2(e,n);case"exponential":return toExponential$1(e,n);case"engineering":return toEngineering$1(e,n);case"bin":return formatNumberToBase(e,2,r);case"oct":return formatNumberToBase(e,8,r);case"hex":return formatNumberToBase(e,16,r);case"auto":return toPrecision(e,n,t&&t).replace(/((\.\d*?)(0+))($|e)/,(function(){var e=arguments[2],t=arguments[4];return"."!==e?e+t:t}));default:throw new Error('Unknown notation "'+a+'". Choose "auto", "exponential", "fixed", "bin", "oct", or "hex.')}}function splitNumber(e){var t=String(e).toLowerCase().match(/^(-?)(\d+\.?\d*)(e([+-]?\d+))?$/);if(!t)throw new SyntaxError("Invalid number "+e);var n=t[1],r=t[2],a=parseFloat(t[4]||"0"),i=r.indexOf(".");a+=-1!==i?i-1:r.length-1;var o=r.replace(".","").replace(/^0*/,(function(e){return a-=e.length,""})).replace(/0*$/,"").split("").map((function(e){return parseInt(e)}));return 0===o.length&&(o.push(0),a++),{sign:n,coefficients:o,exponent:a}}function toEngineering$1(e,t){if(isNaN(e)||!isFinite(e))return String(e);var n=roundDigits(splitNumber(e),t),r=n.exponent,a=n.coefficients,i=r%3==0?r:r<0?r-3-r%3:r-r%3;if(isNumber$1(t))for(;t>a.length||r-i+1>a.length;)a.push(0);else for(var o=Math.abs(r-i)-(a.length-1),s=0;s0;)u++,l--;var c=a.slice(u).join(""),p=isNumber$1(t)&&c.length||c.match(/[1-9]/)?"."+c:"",d=a.slice(0,u).join("")+p+"e"+(r>=0?"+":"")+i.toString();return n.sign+d}function toFixed$2(e,t){if(isNaN(e)||!isFinite(e))return String(e);var n=splitNumber(e),r="number"==typeof t?roundDigits(n,n.exponent+1+t):n,a=r.coefficients,i=r.exponent+1,o=i+(t||0);return a.length0?"."+a.join(""):"")+"e"+(i>=0?"+":"")+i}function toPrecision(e,t,n){if(isNaN(e)||!isFinite(e))return String(e);var r=n&&void 0!==n.lowerExp?n.lowerExp:-3,a=n&&void 0!==n.upperExp?n.upperExp:5,i=splitNumber(e),o=t?roundDigits(i,t):i;if(o.exponent=a)return toExponential$1(e,t);var s=o.coefficients,l=o.exponent;s.length0?l:0;return u<(s=zeros$1(-l).concat(s)).length-1&&s.splice(u+1,0,"."),o.sign+s.join("")}function roundDigits(e,t){for(var n={sign:e.sign,coefficients:e.coefficients,exponent:e.exponent},r=n.coefficients;t<=0;)r.unshift(0),n.exponent++,t++;if(r.length>t&&r.splice(t,r.length-t)[0]>=5){var a=t-1;for(r[a]++;10===r[a];)r.pop(),0===a&&(r.unshift(0),n.exponent++,a++),r[--a]++}return n}function zeros$1(e){for(var t=[],n=0;n0||!(e<0)&&1/e==1/0)^(t>0||!(t<0)&&1/t==1/0)?-e:e}function formatBigNumberToBase(e,t,n){var r=new e.constructor(2),a="";if(n){if(n<1)throw new Error("size must be in greater than 0");if(!isInteger$1(n))throw new Error("size must be an integer");if(e.greaterThan(r.pow(n-1).sub(1))||e.lessThan(r.pow(n-1).mul(-1)))throw new Error("Value must be in range [-2^".concat(n-1,", 2^").concat(n-1,"-1]"));if(!e.isInteger())throw new Error("Value must be an integer");e.lessThan(0)&&(e=e.add(r.pow(n))),a="i".concat(n)}switch(t){case 2:return"".concat(e.toBinary()).concat(a);case 8:return"".concat(e.toOctal()).concat(a);case 16:return"".concat(e.toHexadecimal()).concat(a);default:throw new Error("Base ".concat(t," not supported "))}}function format$2(e,t){if("function"==typeof t)return t(e);if(!e.isFinite())return e.isNaN()?"NaN":e.gt(0)?"Infinity":"-Infinity";var n,r,a="auto";if(void 0!==t&&(t.notation&&(a=t.notation),"number"==typeof t?n=t:t.precision&&(n=t.precision),t.wordSize&&"number"!=typeof(r=t.wordSize)))throw new Error('Option "wordSize" must be a number');switch(a){case"fixed":return toFixed$1(e,n);case"exponential":return toExponential(e,n);case"engineering":return toEngineering(e,n);case"bin":return formatBigNumberToBase(e,2,r);case"oct":return formatBigNumberToBase(e,8,r);case"hex":return formatBigNumberToBase(e,16,r);case"auto":var i=t&&void 0!==t.lowerExp?t.lowerExp:-3,o=t&&void 0!==t.upperExp?t.upperExp:5;if(e.isZero())return"0";var s=e.toSignificantDigits(n),l=s.e;return(l>=i&&l=0?"+":"")+r.toString()}function toExponential(e,t){return void 0!==t?e.toExponential(t-1):e.toExponential()}function toFixed$1(e,t){return e.toFixed(t)}function endsWith(e,t){var n=e.length-t.length,r=e.length;return e.substring(n,r)===t}function format$1(e,t){var n=_format(e,t);return t&&"object"==typeof t&&"truncate"in t&&n.length>t.truncate?n.substring(0,t.truncate-3)+"...":n}function _format(e,t){return"number"==typeof e?format$3(e,t):isBigNumber(e)?format$2(e,t):looksLikeFraction(e)?t&&"decimal"===t.fraction?e.toString():e.s*e.n+"/"+e.d:Array.isArray(e)?formatArray(e,t):isString$1(e)?'"'+e+'"':"function"==typeof e?e.syntax?String(e.syntax):"function":e&&"object"==typeof e?"function"==typeof e.format?e.format(t):e&&e.toString(t)!=={}.toString()?e.toString(t):"{"+Object.keys(e).map((n=>'"'+n+'": '+format$1(e[n],t))).join(", ")+"}":String(e)}function stringify(e){for(var t=String(e),n="",r=0;r/g,">")}function formatArray(e,t){if(Array.isArray(e)){for(var n="[",r=e.length,a=0;at?1:-1}function DimensionError(e,t,n){if(!(this instanceof DimensionError))throw new SyntaxError("Constructor must be called with the new operator");this.actual=e,this.expected=t,this.relation=n,this.message="Dimension mismatch ("+(Array.isArray(e)?"["+e.join(", ")+"]":e)+" "+(this.relation||"!=")+" "+(Array.isArray(t)?"["+t.join(", ")+"]":t)+")",this.stack=(new Error).stack}function IndexError(e,t,n){if(!(this instanceof IndexError))throw new SyntaxError("Constructor must be called with the new operator");this.index=e,arguments.length<3?(this.min=0,this.max=t):(this.min=t,this.max=n),void 0!==this.min&&this.index=this.max?this.message="Index out of range ("+this.index+" > "+(this.max-1)+")":this.message="Index out of range ("+this.index+")",this.stack=(new Error).stack}function arraySize(e){for(var t=[];Array.isArray(e);)t.push(e.length),e=e[0];return t}function _validate(e,t,n){var r,a=e.length;if(a!==t[n])throw new DimensionError(a,t[n]);if(n")}function validate(e,t){if(0===t.length){if(Array.isArray(e))throw new DimensionError(e.length,0)}else _validate(e,t,0)}function validateIndex(e,t){if(!isNumber$1(e)||!isInteger$1(e))throw new TypeError("Index must be an integer (value: "+e+")");if(e<0||"number"==typeof t&&e>=t)throw new IndexError(e,t)}function resize$1(e,t,n){if(!Array.isArray(e)||!Array.isArray(t))throw new TypeError("Array expected");if(0===t.length)throw new Error("Resizing to scalar is not supported");return t.forEach((function(e){if(!isNumber$1(e)||!isInteger$1(e)||e<0)throw new TypeError("Invalid size, must contain positive integers (size: "+format$1(t)+")")})),_resize(e,t,0,void 0!==n?n:0),e}function _resize(e,t,n,r){var a,i,o=e.length,s=t[n],l=Math.min(o,s);if(e.length=s,n=0){if(t%n!=0)throw new Error("Could not replace wildcard, since "+t+" is no multiple of "+-n);r[a]=-t/n}return r}function product$1(e){return e.reduce(((e,t)=>e*t),1)}function _reshape(e,t){for(var n,r=e,a=t.length-1;a>0;a--){var i=t[a];n=[];for(var o=r.length/i,s=0;st.test(e)))}function join(e,t){return Array.prototype.join.call(e,t)}function identify(e){if(!Array.isArray(e))throw new TypeError("Array input expected");if(0===e.length)return e;var t=[],n=0;t[0]={value:e[0],identifier:0};for(var r=1;r!isOptionalDependency(e))).every((e=>void 0!==n[e]))){var r=t.filter((e=>void 0===n[e]));throw new Error('Cannot create function "'.concat(e,'", ')+"some dependencies are missing: ".concat(r.map((e=>'"'.concat(e,'"'))).join(", "),"."))}}function isOptionalDependency(e){return e&&"?"===e[0]}function stripOptionalNotation(e){return e&&"?"===e[0]?e.slice(1):e}function getSafeProperty(e,t){if(isPlainObject(e)&&isSafeProperty(e,t))return e[t];if("function"==typeof e[t]&&isSafeMethod(e,t))throw new Error('Cannot access method "'+t+'" as a property');throw new Error('No access to property "'+t+'"')}function setSafeProperty(e,t,n){if(isPlainObject(e)&&isSafeProperty(e,t))return e[t]=n,n;throw new Error('No access to property "'+t+'"')}function hasSafeProperty(e,t){return t in e}function isSafeProperty(e,t){return!(!e||"object"!=typeof e||!hasOwnProperty$2(safeNativeProperties,t)&&(t in Object.prototype||t in Function.prototype))}function validateSafeMethod(e,t){if(!isSafeMethod(e,t))throw new Error('No access to method "'+t+'"')}function isSafeMethod(e,t){return!(null==e||"function"!=typeof e[t]||hasOwnProperty$2(e,t)&&Object.getPrototypeOf&&t in Object.getPrototypeOf(e)||!hasOwnProperty$2(safeNativeMethods,t)&&(t in Object.prototype||t in Function.prototype))}function isPlainObject(e){return"object"==typeof e&&e&&e.constructor===Object}DimensionError.prototype=new RangeError,DimensionError.prototype.constructor=RangeError,DimensionError.prototype.name="DimensionError",DimensionError.prototype.isDimensionError=!0,IndexError.prototype=new RangeError,IndexError.prototype.constructor=RangeError,IndexError.prototype.name="IndexError",IndexError.prototype.isIndexError=!0;var safeNativeProperties={length:!0,name:!0},safeNativeMethods={toString:!0,valueOf:!0,toLocaleString:!0};class ObjectWrappingMap{constructor(e){this.wrappedObject=e}keys(){return Object.keys(this.wrappedObject)}get(e){return getSafeProperty(this.wrappedObject,e)}set(e,t){return setSafeProperty(this.wrappedObject,e,t),this}has(e){return hasSafeProperty(this.wrappedObject,e)}}function createEmptyMap(){return new Map}function createMap$1(e){if(!e)return createEmptyMap();if(isMap$1(e))return e;if(isObject$1(e))return new ObjectWrappingMap(e);throw new Error("createMap can create maps from objects or Maps")}function toObject(e){if(e instanceof ObjectWrappingMap)return e.wrappedObject;var t={};for(var n of e.keys())setSafeProperty(t,n,e.get(n));return t}function isMap$1(e){return!!e&&(e instanceof Map||e instanceof ObjectWrappingMap||"function"==typeof e.set&&"function"==typeof e.get&&"function"==typeof e.keys&&"function"==typeof e.has)}function assign(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r15)throw new TypeError("Cannot implicitly convert a number with >15 significant digits to BigNumber (value: "+e+"). Use function bignumber(x) to convert to BigNumber.");return new t(e)}},{from:"number",to:"Complex",convert:function(e){return n||throwNoComplex(e),new n(e,0)}},{from:"number",to:"string",convert:function(e){return e+""}},{from:"BigNumber",to:"Complex",convert:function(e){return n||throwNoComplex(e),new n(e.toNumber(),0)}},{from:"Fraction",to:"BigNumber",convert:function(e){throw new TypeError("Cannot implicitly convert a Fraction to BigNumber or vice versa. Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.")}},{from:"Fraction",to:"Complex",convert:function(e){return n||throwNoComplex(e),new n(e.valueOf(),0)}},{from:"number",to:"Fraction",convert:function(e){a||throwNoFraction(e);var t=new a(e);if(t.valueOf()!==e)throw new TypeError("Cannot implicitly convert a number to a Fraction when there will be a loss of precision (value: "+e+"). Use function fraction(x) to convert to Fraction.");return t}},{from:"string",to:"number",convert:function(e){var t=Number(e);if(isNaN(t))throw new Error('Cannot convert "'+e+'" to a number');return t}},{from:"string",to:"BigNumber",convert:function(e){t||throwNoBignumber(e);try{return new t(e)}catch(t){throw new Error('Cannot convert "'+e+'" to BigNumber')}}},{from:"string",to:"Fraction",convert:function(e){a||throwNoFraction(e);try{return new a(e)}catch(t){throw new Error('Cannot convert "'+e+'" to Fraction')}}},{from:"string",to:"Complex",convert:function(e){n||throwNoComplex(e);try{return new n(e)}catch(t){throw new Error('Cannot convert "'+e+'" to Complex')}}},{from:"boolean",to:"number",convert:function(e){return+e}},{from:"boolean",to:"BigNumber",convert:function(e){return t||throwNoBignumber(e),new t(+e)}},{from:"boolean",to:"Fraction",convert:function(e){return a||throwNoFraction(e),new a(+e)}},{from:"boolean",to:"string",convert:function(e){return String(e)}},{from:"Array",to:"Matrix",convert:function(e){return r||throwNoMatrix(),new r(e)}},{from:"Matrix",to:"Array",convert:function(e){return e.valueOf()}}],i}));function throwNoBignumber(e){throw new Error("Cannot convert value ".concat(e," into a BigNumber: no class 'BigNumber' provided"))}function throwNoComplex(e){throw new Error("Cannot convert value ".concat(e," into a Complex number: no class 'Complex' provided"))}function throwNoMatrix(){throw new Error("Cannot convert array into a Matrix: no class 'DenseMatrix' provided")}function throwNoFraction(e){throw new Error("Cannot convert value ".concat(e," into a Fraction, no class 'Fraction' provided."))}var name$4C="ResultSet",dependencies$4C=[],createResultSet=factory(name$4C,dependencies$4C,(()=>{function e(t){if(!(this instanceof e))throw new SyntaxError("Constructor must be called with the new operator");this.entries=t||[]}return e.prototype.type="ResultSet",e.prototype.isResultSet=!0,e.prototype.valueOf=function(){return this.entries},e.prototype.toString=function(){return"["+this.entries.join(", ")+"]"},e.prototype.toJSON=function(){return{mathjs:"ResultSet",entries:this.entries}},e.fromJSON=function(t){return new e(t.entries)},e}),{isClass:!0}),decimal={exports:{}};!function(e){!function(t){var n,r,a,i,o=9e15,s=1e9,l="0123456789abcdef",u="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",c="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",p={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-o,maxE:o,crypto:!1},d=!0,m="[DecimalError] ",f=m+"Invalid argument: ",h=m+"Precision limit exceeded",y=m+"crypto unavailable",b="[object Decimal]",g=Math.floor,v=Math.pow,T=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,N=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,C=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,A=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,S=1e7,x=u.length-1,w=c.length-1,V={toStringTag:b};function E(e){var t,n,r,a=e.length-1,i="",o=e[0];if(a>0){for(i+=o,t=1;tn)throw Error(f+e)}function _(e,t,n,r){var a,i,o,s;for(i=e[0];i>=10;i/=10)--t;return--t<0?(t+=7,a=0):(a=Math.ceil((t+1)/7),t%=7),i=v(10,7-t),s=e[a]%i|0,null==r?t<3?(0==t?s=s/100|0:1==t&&(s=s/10|0),o=n<4&&99999==s||n>3&&49999==s||5e4==s||0==s):o=(n<4&&s+1==i||n>3&&s+1==i/2)&&(e[a+1]/i/100|0)==v(10,t-2)-1||(s==i/2||0==s)&&0==(e[a+1]/i/100|0):t<4?(0==t?s=s/1e3|0:1==t?s=s/100|0:2==t&&(s=s/10|0),o=(r||n<4)&&9999==s||!r&&n>3&&4999==s):o=((r||n<4)&&s+1==i||!r&&n>3&&s+1==i/2)&&(e[a+1]/i/1e3|0)==v(10,t-3)-1,o}function $(e,t,n){for(var r,a,i=[0],o=0,s=e.length;on-1&&(void 0===i[r+1]&&(i[r+1]=0),i[r+1]+=i[r]/n|0,i[r]%=n)}return i.reverse()}V.absoluteValue=V.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),I(e)},V.ceil=function(){return I(new this.constructor(this),this.e+1,2)},V.clampedTo=V.clamp=function(e,t){var n=this,r=n.constructor;if(e=new r(e),t=new r(t),!e.s||!t.s)return new r(NaN);if(e.gt(t))throw Error(f+t);return n.cmp(e)<0?e:n.cmp(t)>0?t:new r(n)},V.comparedTo=V.cmp=function(e){var t,n,r,a,i=this,o=i.d,s=(e=new i.constructor(e)).d,l=i.s,u=e.s;if(!o||!s)return l&&u?l!==u?l:o===s?0:!o^l<0?1:-1:NaN;if(!o[0]||!s[0])return o[0]?l:s[0]?-u:0;if(l!==u)return l;if(i.e!==e.e)return i.e>e.e^l<0?1:-1;for(t=0,n=(r=o.length)<(a=s.length)?r:a;ts[t]^l<0?1:-1;return r===a?0:r>a^l<0?1:-1},V.cosine=V.cos=function(){var e,t,n=this,r=n.constructor;return n.d?n.d[0]?(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+7,r.rounding=1,n=function(e,t){var n,r,a;if(t.isZero())return t;(r=t.d.length)<32?a=(1/X(4,n=Math.ceil(r/3))).toString():(n=16,a="2.3283064365386962890625e-10"),e.precision+=n,t=K(e,1,t.times(a),new e(1));for(var i=n;i--;){var o=t.times(t);t=o.times(o).minus(o).times(8).plus(1)}return e.precision-=n,t}(r,Z(r,n)),r.precision=e,r.rounding=t,I(2==i||3==i?n.neg():n,e,t,!0)):new r(1):new r(NaN)},V.cubeRoot=V.cbrt=function(){var e,t,n,r,a,i,o,s,l,u,c=this,p=c.constructor;if(!c.isFinite()||c.isZero())return new p(c);for(d=!1,(i=c.s*v(c.s*c,1/3))&&Math.abs(i)!=1/0?r=new p(i.toString()):(n=E(c.d),(i=((e=c.e)-n.length+1)%3)&&(n+=1==i||-2==i?"0":"00"),i=v(n,1/3),e=g((e+1)/3)-(e%3==(e<0?-1:2)),(r=new p(n=i==1/0?"5e"+e:(n=i.toExponential()).slice(0,n.indexOf("e")+1)+e)).s=c.s),o=(e=p.precision)+3;;)if(u=(l=(s=r).times(s).times(s)).plus(c),r=D(u.plus(c).times(s),u.plus(l),o+2,1),E(s.d).slice(0,o)===(n=E(r.d)).slice(0,o)){if("9999"!=(n=n.slice(o-3,o+1))&&(a||"4999"!=n)){+n&&(+n.slice(1)||"5"!=n.charAt(0))||(I(r,e+1,1),t=!r.times(r).times(r).eq(c));break}if(!a&&(I(s,e+1,0),s.times(s).times(s).eq(c))){r=s;break}o+=4,a=1}return d=!0,I(r,e,p.rounding,t)},V.decimalPlaces=V.dp=function(){var e,t=this.d,n=NaN;if(t){if(n=7*((e=t.length-1)-g(this.e/7)),e=t[e])for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n},V.dividedBy=V.div=function(e){return D(this,new this.constructor(e))},V.dividedToIntegerBy=V.divToInt=function(e){var t=this.constructor;return I(D(this,new t(e),0,1,1),t.precision,t.rounding)},V.equals=V.eq=function(e){return 0===this.cmp(e)},V.floor=function(){return I(new this.constructor(this),this.e+1,3)},V.greaterThan=V.gt=function(e){return this.cmp(e)>0},V.greaterThanOrEqualTo=V.gte=function(e){var t=this.cmp(e);return 1==t||0===t},V.hyperbolicCosine=V.cosh=function(){var e,t,n,r,a,i=this,o=i.constructor,s=new o(1);if(!i.isFinite())return new o(i.s?1/0:NaN);if(i.isZero())return s;n=o.precision,r=o.rounding,o.precision=n+Math.max(i.e,i.sd())+4,o.rounding=1,(a=i.d.length)<32?t=(1/X(4,e=Math.ceil(a/3))).toString():(e=16,t="2.3283064365386962890625e-10"),i=K(o,1,i.times(t),new o(1),!0);for(var l,u=e,c=new o(8);u--;)l=i.times(i),i=s.minus(l.times(c.minus(l.times(c))));return I(i,o.precision=n,o.rounding=r,!0)},V.hyperbolicSine=V.sinh=function(){var e,t,n,r,a=this,i=a.constructor;if(!a.isFinite()||a.isZero())return new i(a);if(t=i.precision,n=i.rounding,i.precision=t+Math.max(a.e,a.sd())+4,i.rounding=1,(r=a.d.length)<3)a=K(i,2,a,a,!0);else{e=(e=1.4*Math.sqrt(r))>16?16:0|e,a=K(i,2,a=a.times(1/X(5,e)),a,!0);for(var o,s=new i(5),l=new i(16),u=new i(20);e--;)o=a.times(a),a=a.times(s.plus(o.times(l.times(o).plus(u))))}return i.precision=t,i.rounding=n,I(a,t,n,!0)},V.hyperbolicTangent=V.tanh=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+7,r.rounding=1,D(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)},V.inverseCosine=V.acos=function(){var e,t=this,n=t.constructor,r=t.abs().cmp(1),a=n.precision,i=n.rounding;return-1!==r?0===r?t.isNeg()?M(n,a,i):new n(0):new n(NaN):t.isZero()?M(n,a+4,i).times(.5):(n.precision=a+6,n.rounding=1,t=t.asin(),e=M(n,a+4,i).times(.5),n.precision=a,n.rounding=i,e.minus(t))},V.inverseHyperbolicCosine=V.acosh=function(){var e,t,n=this,r=n.constructor;return n.lte(1)?new r(n.eq(1)?0:NaN):n.isFinite()?(e=r.precision,t=r.rounding,r.precision=e+Math.max(Math.abs(n.e),n.sd())+4,r.rounding=1,d=!1,n=n.times(n).minus(1).sqrt().plus(n),d=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)},V.inverseHyperbolicSine=V.asinh=function(){var e,t,n=this,r=n.constructor;return!n.isFinite()||n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+2*Math.max(Math.abs(n.e),n.sd())+6,r.rounding=1,d=!1,n=n.times(n).plus(1).sqrt().plus(n),d=!0,r.precision=e,r.rounding=t,n.ln())},V.inverseHyperbolicTangent=V.atanh=function(){var e,t,n,r,a=this,i=a.constructor;return a.isFinite()?a.e>=0?new i(a.abs().eq(1)?a.s/0:a.isZero()?a:NaN):(e=i.precision,t=i.rounding,r=a.sd(),Math.max(r,e)<2*-a.e-1?I(new i(a),e,t,!0):(i.precision=n=r-a.e,a=D(a.plus(1),new i(1).minus(a),n+e,1),i.precision=e+4,i.rounding=1,a=a.ln(),i.precision=e,i.rounding=t,a.times(.5))):new i(NaN)},V.inverseSine=V.asin=function(){var e,t,n,r,a=this,i=a.constructor;return a.isZero()?new i(a):(t=a.abs().cmp(1),n=i.precision,r=i.rounding,-1!==t?0===t?((e=M(i,n+4,r).times(.5)).s=a.s,e):new i(NaN):(i.precision=n+6,i.rounding=1,a=a.div(new i(1).minus(a.times(a)).sqrt().plus(1)).atan(),i.precision=n,i.rounding=r,a.times(2)))},V.inverseTangent=V.atan=function(){var e,t,n,r,a,i,o,s,l,u=this,c=u.constructor,p=c.precision,m=c.rounding;if(u.isFinite()){if(u.isZero())return new c(u);if(u.abs().eq(1)&&p+4<=w)return(o=M(c,p+4,m).times(.25)).s=u.s,o}else{if(!u.s)return new c(NaN);if(p+4<=w)return(o=M(c,p+4,m).times(.5)).s=u.s,o}for(c.precision=s=p+10,c.rounding=1,e=n=Math.min(28,s/7+2|0);e;--e)u=u.div(u.times(u).plus(1).sqrt().plus(1));for(d=!1,t=Math.ceil(s/7),r=1,l=u.times(u),o=new c(u),a=u;-1!==e;)if(a=a.times(l),i=o.minus(a.div(r+=2)),a=a.times(l),void 0!==(o=i.plus(a.div(r+=2))).d[t])for(e=t;o.d[e]===i.d[e]&&e--;);return n&&(o=o.times(2<this.d.length-2},V.isNaN=function(){return!this.s},V.isNegative=V.isNeg=function(){return this.s<0},V.isPositive=V.isPos=function(){return this.s>0},V.isZero=function(){return!!this.d&&0===this.d[0]},V.lessThan=V.lt=function(e){return this.cmp(e)<0},V.lessThanOrEqualTo=V.lte=function(e){return this.cmp(e)<1},V.logarithm=V.log=function(e){var t,n,r,a,i,o,s,l,u=this,c=u.constructor,p=c.precision,m=c.rounding;if(null==e)e=new c(10),t=!0;else{if(n=(e=new c(e)).d,e.s<0||!n||!n[0]||e.eq(1))return new c(NaN);t=e.eq(10)}if(n=u.d,u.s<0||!n||!n[0]||u.eq(1))return new c(n&&!n[0]?-1/0:1!=u.s?NaN:n?0:1/0);if(t)if(n.length>1)i=!0;else{for(a=n[0];a%10==0;)a/=10;i=1!==a}if(d=!1,o=G(u,s=p+5),r=t?k(c,s+10):G(e,s),_((l=D(o,r,s,1)).d,a=p,m))do{if(o=G(u,s+=10),r=t?k(c,s+10):G(e,s),l=D(o,r,s,1),!i){+E(l.d).slice(a+1,a+15)+1==1e14&&(l=I(l,p+1,0));break}}while(_(l.d,a+=10,m));return d=!0,I(l,p,m)},V.minus=V.sub=function(e){var t,n,r,a,i,o,s,l,u,c,p,m,f=this,h=f.constructor;if(e=new h(e),!f.d||!e.d)return f.s&&e.s?f.d?e.s=-e.s:e=new h(e.d||f.s!==e.s?f:NaN):e=new h(NaN),e;if(f.s!=e.s)return e.s=-e.s,f.plus(e);if(u=f.d,m=e.d,s=h.precision,l=h.rounding,!u[0]||!m[0]){if(m[0])e.s=-e.s;else{if(!u[0])return new h(3===l?-0:0);e=new h(f)}return d?I(e,s,l):e}if(n=g(e.e/7),c=g(f.e/7),u=u.slice(),i=c-n){for((p=i<0)?(t=u,i=-i,o=m.length):(t=m,n=c,o=u.length),i>(r=Math.max(Math.ceil(s/7),o)+2)&&(i=r,t.length=1),t.reverse(),r=i;r--;)t.push(0);t.reverse()}else{for((p=(r=u.length)<(o=m.length))&&(o=r),r=0;r0;--r)u[o++]=0;for(r=m.length;r>i;){if(u[--r](o=(i=Math.ceil(s/7))>o?i+1:o+1)&&(a=o,n.length=1),n.reverse();a--;)n.push(0);n.reverse()}for((o=u.length)-(a=c.length)<0&&(a=o,n=c,c=u,u=n),t=0;a;)t=(u[--a]=u[a]+c[a]+t)/S|0,u[a]%=S;for(t&&(u.unshift(t),++r),o=u.length;0==u[--o];)u.pop();return e.d=u,e.e=P(u,r),d?I(e,s,l):e},V.precision=V.sd=function(e){var t,n=this;if(void 0!==e&&e!==!!e&&1!==e&&0!==e)throw Error(f+e);return n.d?(t=F(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t},V.round=function(){var e=this,t=e.constructor;return I(new t(e),e.e+1,t.rounding)},V.sine=V.sin=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+7,r.rounding=1,n=function(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:K(e,2,t,t);n=(n=1.4*Math.sqrt(r))>16?16:0|n,t=K(e,2,t=t.times(1/X(5,n)),t);for(var a,i=new e(5),o=new e(16),s=new e(20);n--;)a=t.times(t),t=t.times(i.plus(a.times(o.times(a).minus(s))));return t}(r,Z(r,n)),r.precision=e,r.rounding=t,I(i>2?n.neg():n,e,t,!0)):new r(NaN)},V.squareRoot=V.sqrt=function(){var e,t,n,r,a,i,o=this,s=o.d,l=o.e,u=o.s,c=o.constructor;if(1!==u||!s||!s[0])return new c(!u||u<0&&(!s||s[0])?NaN:s?o:1/0);for(d=!1,0==(u=Math.sqrt(+o))||u==1/0?(((t=E(s)).length+l)%2==0&&(t+="0"),u=Math.sqrt(t),l=g((l+1)/2)-(l<0||l%2),r=new c(t=u==1/0?"5e"+l:(t=u.toExponential()).slice(0,t.indexOf("e")+1)+l)):r=new c(u.toString()),n=(l=c.precision)+3;;)if(r=(i=r).plus(D(o,i,n+2,1)).times(.5),E(i.d).slice(0,n)===(t=E(r.d)).slice(0,n)){if("9999"!=(t=t.slice(n-3,n+1))&&(a||"4999"!=t)){+t&&(+t.slice(1)||"5"!=t.charAt(0))||(I(r,l+1,1),e=!r.times(r).eq(o));break}if(!a&&(I(i,l+1,0),i.times(i).eq(o))){r=i;break}n+=4,a=1}return d=!0,I(r,l,c.rounding,e)},V.tangent=V.tan=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+10,r.rounding=1,(n=n.sin()).s=1,n=D(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,I(2==i||4==i?n.neg():n,e,t,!0)):new r(NaN)},V.times=V.mul=function(e){var t,n,r,a,i,o,s,l,u,c=this,p=c.constructor,m=c.d,f=(e=new p(e)).d;if(e.s*=c.s,!(m&&m[0]&&f&&f[0]))return new p(!e.s||m&&!m[0]&&!f||f&&!f[0]&&!m?NaN:m&&f?0*e.s:e.s/0);for(n=g(c.e/7)+g(e.e/7),(l=m.length)<(u=f.length)&&(i=m,m=f,f=i,o=l,l=u,u=o),i=[],r=o=l+u;r--;)i.push(0);for(r=u;--r>=0;){for(t=0,a=l+r;a>r;)s=i[a]+f[r]*m[a-r-1]+t,i[a--]=s%S|0,t=s/S|0;i[a]=(i[a]+t)%S|0}for(;!i[--o];)i.pop();return t?++n:i.shift(),e.d=i,e.e=P(i,n),d?I(e,p.precision,p.rounding):e},V.toBinary=function(e,t){return Y(this,2,e,t)},V.toDecimalPlaces=V.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),void 0===e?n:(O(e,0,s),void 0===t?t=r.rounding:O(t,0,8),I(n,e+n.e+1,t))},V.toExponential=function(e,t){var n,r=this,a=r.constructor;return void 0===e?n=R(r,!0):(O(e,0,s),void 0===t?t=a.rounding:O(t,0,8),n=R(r=I(new a(r),e+1,t),!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n},V.toFixed=function(e,t){var n,r,a=this,i=a.constructor;return void 0===e?n=R(a):(O(e,0,s),void 0===t?t=i.rounding:O(t,0,8),n=R(r=I(new i(a),e+a.e+1,t),!1,e+r.e+1)),a.isNeg()&&!a.isZero()?"-"+n:n},V.toFraction=function(e){var t,n,r,a,i,o,s,l,u,c,p,m,h=this,y=h.d,b=h.constructor;if(!y)return new b(h);if(u=n=new b(1),r=l=new b(0),o=(i=(t=new b(r)).e=F(y)-h.e-1)%7,t.d[0]=v(10,o<0?7+o:o),null==e)e=i>0?t:u;else{if(!(s=new b(e)).isInt()||s.lt(u))throw Error(f+s);e=s.gt(t)?i>0?t:u:s}for(d=!1,s=new b(E(y)),c=b.precision,b.precision=i=7*y.length*2;p=D(s,t,0,1,1),1!=(a=n.plus(p.times(r))).cmp(e);)n=r,r=a,a=u,u=l.plus(p.times(a)),l=a,a=t,t=s.minus(p.times(a)),s=a;return a=D(e.minus(n),r,0,1,1),l=l.plus(a.times(u)),n=n.plus(a.times(r)),l.s=u.s=h.s,m=D(u,r,i,1).minus(h).abs().cmp(D(l,n,i,1).minus(h).abs())<1?[u,r]:[l,n],b.precision=c,d=!0,m},V.toHexadecimal=V.toHex=function(e,t){return Y(this,16,e,t)},V.toNearest=function(e,t){var n=this,r=n.constructor;if(n=new r(n),null==e){if(!n.d)return n;e=new r(1),t=r.rounding}else{if(e=new r(e),void 0===t?t=r.rounding:O(t,0,8),!n.d)return e.s?n:e;if(!e.d)return e.s&&(e.s=n.s),e}return e.d[0]?(d=!1,n=D(n,e,0,t,1).times(e),d=!0,I(n)):(e.s=n.s,n=e),n},V.toNumber=function(){return+this},V.toOctal=function(e,t){return Y(this,8,e,t)},V.toPower=V.pow=function(e){var t,n,r,a,i,o,s=this,l=s.constructor,u=+(e=new l(e));if(!(s.d&&e.d&&s.d[0]&&e.d[0]))return new l(v(+s,u));if((s=new l(s)).eq(1))return s;if(r=l.precision,i=l.rounding,e.eq(1))return I(s,r,i);if((t=g(e.e/7))>=e.d.length-1&&(n=u<0?-u:u)<=9007199254740991)return a=L(l,s,n,r),e.s<0?new l(1).div(a):I(a,r,i);if((o=s.s)<0){if(tl.maxE+1||t0?o/0:0):(d=!1,l.rounding=s.s=1,n=Math.min(12,(t+"").length),(a=z(e.times(G(s,r+n)),r)).d&&_((a=I(a,r+5,1)).d,r,i)&&(t=r+10,+E((a=I(z(e.times(G(s,t+n)),t),t+5,1)).d).slice(r+1,r+15)+1==1e14&&(a=I(a,r+1,0))),a.s=o,d=!0,l.rounding=i,I(a,r,i))},V.toPrecision=function(e,t){var n,r=this,a=r.constructor;return void 0===e?n=R(r,r.e<=a.toExpNeg||r.e>=a.toExpPos):(O(e,1,s),void 0===t?t=a.rounding:O(t,0,8),n=R(r=I(new a(r),e,t),e<=r.e||r.e<=a.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n},V.toSignificantDigits=V.toSD=function(e,t){var n=this.constructor;return void 0===e?(e=n.precision,t=n.rounding):(O(e,1,s),void 0===t?t=n.rounding:O(t,0,8)),I(new n(this),e,t)},V.toString=function(){var e=this,t=e.constructor,n=R(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+n:n},V.truncated=V.trunc=function(){return I(new this.constructor(this),this.e+1,1)},V.valueOf=V.toJSON=function(){var e=this,t=e.constructor,n=R(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+n:n};var D=function(){function e(e,t,n){var r,a=0,i=e.length;for(e=e.slice();i--;)r=e[i]*t+a,e[i]=r%n|0,a=r/n|0;return a&&e.unshift(a),e}function t(e,t,n,r){var a,i;if(n!=r)i=n>r?1:-1;else for(a=i=0;at[a]?1:-1;break}return i}function n(e,t,n,r){for(var a=0;n--;)e[n]-=a,a=e[n]1;)e.shift()}return function(a,i,o,s,l,u){var c,p,d,m,f,h,y,b,v,T,N,C,A,x,w,V,E,O,_,$,D=a.constructor,R=a.s==i.s?1:-1,P=a.d,k=i.d;if(!(P&&P[0]&&k&&k[0]))return new D(a.s&&i.s&&(P?!k||P[0]!=k[0]:k)?P&&0==P[0]||!k?0*R:R/0:NaN);for(u?(f=1,p=a.e-i.e):(u=S,f=7,p=g(a.e/f)-g(i.e/f)),_=k.length,E=P.length,T=(v=new D(R)).d=[],d=0;k[d]==(P[d]||0);d++);if(k[d]>(P[d]||0)&&p--,null==o?(x=o=D.precision,s=D.rounding):x=l?o+(a.e-i.e)+1:o,x<0)T.push(1),h=!0;else{if(x=x/f+2|0,d=0,1==_){for(m=0,k=k[0],x++;(d1&&(k=e(k,m,u),P=e(P,m,u),_=k.length,E=P.length),V=_,C=(N=P.slice(0,_)).length;C<_;)N[C++]=0;($=k.slice()).unshift(0),O=k[0],k[1]>=u/2&&++O;do{m=0,(c=t(k,N,_,C))<0?(A=N[0],_!=C&&(A=A*u+(N[1]||0)),(m=A/O|0)>1?(m>=u&&(m=u-1),1==(c=t(y=e(k,m,u),N,b=y.length,C=N.length))&&(m--,n(y,_=10;m/=10)d++;v.e=d+p*f-1,I(v,l?o+v.e+1:o,s,h)}return v}}();function I(e,t,n,r){var a,i,o,s,l,u,c,p,m,f=e.constructor;e:if(null!=t){if(!(p=e.d))return e;for(a=1,s=p[0];s>=10;s/=10)a++;if((i=t-a)<0)i+=7,o=t,l=(c=p[m=0])/v(10,a-o-1)%10|0;else if((m=Math.ceil((i+1)/7))>=(s=p.length)){if(!r)break e;for(;s++<=m;)p.push(0);c=l=0,a=1,o=(i%=7)-7+1}else{for(c=s=p[m],a=1;s>=10;s/=10)a++;l=(o=(i%=7)-7+a)<0?0:c/v(10,a-o-1)%10|0}if(r=r||t<0||void 0!==p[m+1]||(o<0?c:c%v(10,a-o-1)),u=n<4?(l||r)&&(0==n||n==(e.s<0?3:2)):l>5||5==l&&(4==n||r||6==n&&(i>0?o>0?c/v(10,a-o):0:p[m-1])%10&1||n==(e.s<0?8:7)),t<1||!p[0])return p.length=0,u?(t-=e.e+1,p[0]=v(10,(7-t%7)%7),e.e=-t||0):p[0]=e.e=0,e;if(0==i?(p.length=m,s=1,m--):(p.length=m+1,s=v(10,7-i),p[m]=o>0?(c/v(10,a-o)%v(10,o)|0)*s:0),u)for(;;){if(0==m){for(i=1,o=p[0];o>=10;o/=10)i++;for(o=p[0]+=s,s=1;o>=10;o/=10)s++;i!=s&&(e.e++,p[0]==S&&(p[0]=1));break}if(p[m]+=s,p[m]!=S)break;p[m--]=0,s=1}for(i=p.length;0===p[--i];)p.pop()}return d&&(e.e>f.maxE?(e.d=null,e.e=NaN):e.e0?i=i.charAt(0)+"."+i.slice(1)+B(r):o>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(e.e<0?"e":"e+")+e.e):a<0?(i="0."+B(-a-1)+i,n&&(r=n-o)>0&&(i+=B(r))):a>=o?(i+=B(a+1-o),n&&(r=n-a-1)>0&&(i=i+"."+B(r))):((r=a+1)0&&(a+1===o&&(i+="."),i+=B(r))),i}function P(e,t){var n=e[0];for(t*=7;n>=10;n/=10)t++;return t}function k(e,t,n){if(t>x)throw d=!0,n&&(e.precision=n),Error(h);return I(new e(u),t,1,!0)}function M(e,t,n){if(t>w)throw Error(h);return I(new e(c),t,n,!0)}function F(e){var t=e.length-1,n=7*t+1;if(t=e[t]){for(;t%10==0;t/=10)n--;for(t=e[0];t>=10;t/=10)n++}return n}function B(e){for(var t="";e--;)t+="0";return t}function L(e,t,n,r){var a,i=new e(1),o=Math.ceil(r/7+4);for(d=!1;;){if(n%2&&J((i=i.times(t)).d,o)&&(a=!0),0===(n=g(n/2))){n=i.d.length-1,a&&0===i.d[n]&&++i.d[n];break}J((t=t.times(t)).d,o)}return d=!0,i}function j(e){return 1&e.d[e.d.length-1]}function U(e,t,n){for(var r,a=new e(t[0]),i=0;++i17)return new m(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:NaN);for(null==t?(d=!1,l=h):l=t,s=new m(.03125);e.e>-2;)e=e.times(s),p+=5;for(l+=r=Math.log(v(2,p))/Math.LN10*2+5|0,n=i=o=new m(1),m.precision=l;;){if(i=I(i.times(e),l,1),n=n.times(++c),E((s=o.plus(D(i,n,l,1))).d).slice(0,l)===E(o.d).slice(0,l)){for(a=p;a--;)o=I(o.times(o),l,1);if(null!=t)return m.precision=h,o;if(!(u<3&&_(o.d,l-r,f,u)))return I(o,m.precision=h,f,d=!0);m.precision=l+=10,n=i=s=new m(1),c=0,u++}o=s}}function G(e,t){var n,r,a,i,o,s,l,u,c,p,m,f=1,h=e,y=h.d,b=h.constructor,g=b.rounding,v=b.precision;if(h.s<0||!y||!y[0]||!h.e&&1==y[0]&&1==y.length)return new b(y&&!y[0]?-1/0:1!=h.s?NaN:y?0:h);if(null==t?(d=!1,c=v):c=t,b.precision=c+=10,r=(n=E(y)).charAt(0),!(Math.abs(i=h.e)<15e14))return u=k(b,c+2,v).times(i+""),h=G(new b(r+"."+n.slice(1)),c-10).plus(u),b.precision=v,null==t?I(h,v,g,d=!0):h;for(;r<7&&1!=r||1==r&&n.charAt(1)>3;)r=(n=E((h=h.times(e)).d)).charAt(0),f++;for(i=h.e,r>1?(h=new b("0."+n),i++):h=new b(r+"."+n.slice(1)),p=h,l=o=h=D(h.minus(1),h.plus(1),c,1),m=I(h.times(h),c,1),a=3;;){if(o=I(o.times(m),c,1),E((u=l.plus(D(o,new b(a),c,1))).d).slice(0,c)===E(l.d).slice(0,c)){if(l=l.times(2),0!==i&&(l=l.plus(k(b,c+2,v).times(i+""))),l=D(l,new b(f),c,1),null!=t)return b.precision=v,l;if(!_(l.d,c-10,g,s))return I(l,b.precision=v,g,d=!0);b.precision=c+=10,u=o=h=D(p.minus(1),p.plus(1),c,1),m=I(h.times(h),c,1),a=s=1}l=u,a+=2}}function H(e){return String(e.s*e.s/0)}function q(e,t){var n,r,a;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;48===t.charCodeAt(r);r++);for(a=t.length;48===t.charCodeAt(a-1);--a);if(t=t.slice(r,a)){if(a-=r,e.e=n=n-r-1,e.d=[],r=(n+1)%7,n<0&&(r+=7),re.constructor.maxE?(e.d=null,e.e=NaN):e.e-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),A.test(t))return q(e,t)}else if("Infinity"===t||"NaN"===t)return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(N.test(t))r=16,t=t.toLowerCase();else if(T.test(t))r=2;else{if(!C.test(t))throw Error(f+t);r=8}for((o=t.search(/p/i))>0?(u=+t.slice(o+1),t=t.substring(2,o)):t=t.slice(2),s=(o=t.indexOf("."))>=0,a=e.constructor,s&&(o=(l=(t=t.replace(".","")).length)-o,i=L(a,new a(r),o,2*o)),o=p=(c=$(t,r,S)).length-1;0===c[o];--o)c.pop();return o<0?new a(0*e.s):(e.e=P(c,p),e.d=c,d=!1,s&&(e=D(e,i,4*l)),u&&(e=e.times(Math.abs(u)<54?v(2,u):n.pow(2,u))),d=!0,e)}function K(e,t,n,r,a){var i,o,s,l,u=e.precision,c=Math.ceil(u/7);for(d=!1,l=n.times(n),s=new e(r);;){if(o=D(s.times(l),new e(t++*t++),u,1),s=a?r.plus(o):r.minus(o),r=D(o.times(l),new e(t++*t++),u,1),void 0!==(o=s.plus(r)).d[c]){for(i=c;o.d[i]===s.d[i]&&i--;);if(-1==i)break}i=s,s=r,r=o,o=i}return d=!0,o.d.length=c+1,o}function X(e,t){for(var n=e;--t;)n*=e;return n}function Z(e,t){var n,r=t.s<0,a=M(e,e.precision,1),o=a.times(.5);if((t=t.abs()).lte(o))return i=r?4:1,t;if((n=t.divToInt(a)).isZero())i=r?3:2;else{if((t=t.minus(n.times(a))).lte(o))return i=j(n)?r?2:3:r?4:1,t;i=j(n)?r?1:4:r?3:2}return t.minus(a).abs()}function Y(e,t,n,a){var i,o,u,c,p,d,m,f,h,y=e.constructor,b=void 0!==n;if(b?(O(n,1,s),void 0===a?a=y.rounding:O(a,0,8)):(n=y.precision,a=y.rounding),e.isFinite()){for(b?(i=2,16==t?n=4*n-3:8==t&&(n=3*n-2)):i=t,(u=(m=R(e)).indexOf("."))>=0&&(m=m.replace(".",""),(h=new y(1)).e=m.length-u,h.d=$(R(h),10,i),h.e=h.d.length),o=p=(f=$(m,10,i)).length;0==f[--p];)f.pop();if(f[0]){if(u<0?o--:((e=new y(e)).d=f,e.e=o,f=(e=D(e,h,n,a,0,i)).d,o=e.e,d=r),u=f[n],c=i/2,d=d||void 0!==f[n+1],d=a<4?(void 0!==u||d)&&(0===a||a===(e.s<0?3:2)):u>c||u===c&&(4===a||d||6===a&&1&f[n-1]||a===(e.s<0?8:7)),f.length=n,d)for(;++f[--n]>i-1;)f[n]=0,n||(++o,f.unshift(1));for(p=f.length;!f[p-1];--p);for(u=0,m="";u1)if(16==t||8==t){for(u=16==t?4:3,--p;p%u;p++)m+="0";for(p=(f=$(m,i,t)).length;!f[p-1];--p);for(u=1,m="1.";up)for(o-=p;o--;)m+="0";else ot)return e.length=t,!0}function Q(e){return new this(e).abs()}function ee(e){return new this(e).acos()}function te(e){return new this(e).acosh()}function ne(e,t){return new this(e).plus(t)}function re(e){return new this(e).asin()}function ae(e){return new this(e).asinh()}function ie(e){return new this(e).atan()}function oe(e){return new this(e).atanh()}function se(e,t){e=new this(e),t=new this(t);var n,r=this.precision,a=this.rounding,i=r+4;return e.s&&t.s?e.d||t.d?!t.d||e.isZero()?(n=t.s<0?M(this,r,a):new this(0)).s=e.s:!e.d||t.isZero()?(n=M(this,i,1).times(.5)).s=e.s:t.s<0?(this.precision=i,this.rounding=1,n=this.atan(D(e,t,i,1)),t=M(this,i,1),this.precision=r,this.rounding=a,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(D(e,t,i,1)):(n=M(this,i,1).times(t.s>0?.25:.75)).s=e.s:n=new this(NaN),n}function le(e){return new this(e).cbrt()}function ue(e){return I(e=new this(e),e.e+1,2)}function ce(e,t,n){return new this(e).clamp(t,n)}function pe(e){if(!e||"object"!=typeof e)throw Error(m+"Object expected");var t,n,r,a=!0===e.defaults,i=["precision",1,s,"rounding",0,8,"toExpNeg",-o,0,"toExpPos",0,o,"maxE",0,o,"minE",-o,0,"modulo",0,9];for(t=0;t=i[t+1]&&r<=i[t+2]))throw Error(f+n+": "+r);this[n]=r}if(n="crypto",a&&(this[n]=p[n]),void 0!==(r=e[n])){if(!0!==r&&!1!==r&&0!==r&&1!==r)throw Error(f+n+": "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw Error(y);this[n]=!0}else this[n]=!1}return this}function de(e){return new this(e).cos()}function me(e){return new this(e).cosh()}function fe(e,t){return new this(e).div(t)}function he(e){return new this(e).exp()}function ye(e){return I(e=new this(e),e.e+1,3)}function be(){var e,t,n=new this(0);for(d=!1,e=0;e=429e7?t[i]=crypto.getRandomValues(new Uint32Array(1))[0]:l[i++]=a%1e7;else{if(!crypto.randomBytes)throw Error(y);for(t=crypto.randomBytes(r*=4);i=214e7?crypto.randomBytes(4).copy(t,i):(l.push(a%1e7),i+=4);i=r/4}else for(;i=10;a/=10)r++;r<7&&(n-=7-r)}return o.e=n,o.d=l,o}function Oe(e){return I(e=new this(e),e.e+1,this.rounding)}function _e(e){return(e=new this(e)).d?e.d[0]?e.s:0*e.s:e.s||NaN}function $e(e){return new this(e).sin()}function De(e){return new this(e).sinh()}function Ie(e){return new this(e).sqrt()}function Re(e,t){return new this(e).sub(t)}function Pe(){var e=0,t=arguments,n=new this(t[e]);for(d=!1;n.s&&++ei.maxE?(a.e=NaN,a.d=null):e.e=10;n/=10)t++;return void(d?t>i.maxE?(a.e=NaN,a.d=null):t{var{on:t,config:n}=e,r=Decimal.clone({precision:n.precision,modulo:Decimal.EUCLID});return r.prototype=Object.create(r.prototype),r.prototype.type="BigNumber",r.prototype.isBigNumber=!0,r.prototype.toJSON=function(){return{mathjs:"BigNumber",value:this.toString()}},r.fromJSON=function(e){return new r(e.value)},t&&t("config",(function(e,t){e.precision!==t.precision&&r.config({precision:e.precision})})),r}),{isClass:!0}),complex$1={exports:{}}; +var Core=function(){"use strict";class ParameterStack{constructor(e){this.stack=[{}],void 0!==e&&Object.assign(this.parameters,e)}get parameters(){return this.stack[this.stack.length-1]}push(e,t=!0){let n={};t?(Object.assign(n,this.parameters),void 0!==e&&Object.assign(n,e)):n=e,this.stack.push(n)}pop(){let e=this.stack.pop();return 0===this.stack.length&&(this.stack=[{}]),e}}class Numerics{constructor({maxIterationsRoot:e=80,maxIterationsMinimize:t=500,eps:n=1e-6}={}){this.maxIterationsRoot=e,this.maxIterationsMinimize=t,this.eps=n}fzero(e,t,n){var r,a,i,s,o,l,u,c,p,d,m,h,f,y,g,b,v,N,T,C,A=this.eps,V=this.maxIterationsRoot,x=0;if(Array.isArray(t)){if(t.length<2)throw new Error("fzero: length of array x0 has to be at least two.");r=t[0],s=e.call(n,r),a=t[1],o=e.call(n,a)}else{for(r=t,s=e.call(n,r),d=(c=[.9*(u=0===r?1:r),1.1*u,u-1,u+1,.5*u,1.5*u,-u,2*u,-10*u,10*u]).length,p=0;p0)return Array.isArray(t)?this.fminbr(e,[r,a],n).x:this.Newton(e,r,n);for(i=r,l=s;x=v&&Math.abs(s)>Math.abs(o)&&(g=i-a,r===i?(N=g*(y=o/s),T=1-y):(N=(b=o/s)*(g*(T=s/l)*(T-(y=o/l))-(a-r)*(y-1)),T=(T-1)*(y-1)*(b-1)),N>0?T=-T:N=-N,N<.75*g*T-.5*Math.abs(v*T)&&N0?v:-v),r=a,s=o,a+=C,((o=e.call(n,a))>0&&l>0||o<0&&l<0)&&(i=r,l=s),x++}return a}fminbr(e,t,n,r){let a=void 0!==r?r:this.eps;var i,s,o,l,u,c,p,d,m,h,f,y,g,b,v,N,T=.5*(3-Math.sqrt(5)),C=a,A=a,V=this.maxIterationsMinimize,x=0;if(!Array.isArray(t)||t.length<2)throw new Error("Numerics.fminbr: length of array x0 has to be at least two.");if(l=(i=t[0])+T*((s=t[1])-i),p=e.call(n,l),Number.isNaN(p))return{success:!1};for(o=l,u=l,c=p,d=p;x=f&&(g=(o-l)*(b=(o-l)*(c-d))-(o-u)*(v=(o-u)*(c-p)),(b=2*(b-v))>0?g=-g:b=-b,Math.abs(g)b*(i-o+2*f)&&g0?f:-f),v=o+y,N=e.call(n,v),Number.isNaN(N))return{success:!1};N<=c?(vi;)r=this.D(e,n)(t),Math.abs(r)>i?t-=s/r:t+=.2*Math.random()-1,s=e.apply(n,[t]),a+=1;return t}D(e,t){return null!=t?function(t){var n=1e-5;return(e(t+n)-e(t-n))/2e-5}:function(n){var r=1e-5;return(e.apply(t,[n+r])-e.apply(t,[n-r]))/2e-5}}}function _prng_restore(e,t,n){let r=n&&n.state;r&&("object"==typeof r&&t.copy(r,t),e.state=()=>t.copy(t,{}))}function prng_alea(e,t){let n=new AleaGen(e),r=()=>n.next();return r.double=()=>r()+11102230246251565e-32*(2097152*r()|0),r.int32=()=>4294967296*n.next()|0,r.quick=r,_prng_restore(r,n,t),r}class AleaGen{constructor(e){null==e&&(e=+new Date);let t=4022871197;function n(e){e=String(e);for(let n=0;n>>0,r-=t,r*=t,t=r>>>0,r-=t,t+=4294967296*r}return 2.3283064365386963e-10*(t>>>0)}this.c=1,this.s0=n(" "),this.s1=n(" "),this.s2=n(" "),this.s0-=n(e),this.s0<0&&(this.s0+=1),this.s1-=n(e),this.s1<0&&(this.s1+=1),this.s2-=n(e),this.s2<0&&(this.s2+=1)}next(){let{c:e,s0:t,s1:n,s2:r}=this,a=2091639*t+2.3283064365386963e-10*e;return this.s0=n,this.s1=r,this.s2=a-(this.c=0|a)}copy(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var mathExpressions_umd={exports:{}};(function(module,exports){!function(e,t){module.exports=t()}(0,(function(){const get_tree=function(e){if(null!=e)return void 0!==e.tree?e.tree:e};function*subsets(e,t){var n=e.length;if(void 0===t&&(t=n),0!==t){for(let t=0;t2?a=a.concat(r[i].slice(1)):a.push(r[i]);r=a}return[n].concat(r)}const unflattenRight=function(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if((r=r.map((function(e,t){return unflattenRight(e)}))).length>2&&is_associative$1[n]){for(var a=[n,r[0],void 0],i=a,s=1;s2&&is_associative$1[n]){for(var a=[n,void 0,r[r.length-1]],i=a,s=r.length-2;s>0;s--)i[1]=[n,void 0,r[s]],i=i[1];return i[1]=r[0],a}return[n].concat(r)},allChildren=function(e){if(!Array.isArray(e))return[];var t=e[0],n=e.slice(1);return is_associative$1[t]?n.reduce((function(e,n){return Array.isArray(n)&&n[0]===t?e.concat(allChildren(n)):e.concat([n])}),[]):n};function get_all_units(){return{"%":{scale:e=>["/",e,100],only_scales:!0},$:{prefix:!0,scale:e=>e},deg:{scale:e=>["/",["*",e,"pi"],180],only_scales:!0}}}let all_units$1=get_all_units();function get_unit_of_tree(e){if("unit"===e[0])for(let t in all_units$1)if(all_units$1[t].prefix){if(e[1]===t)return t}else if(e[2]===t)return t;return null}function get_unit_value_of_tree(e){if("unit"===e[0])for(let t in all_units$1)if(all_units$1[t].prefix){if(e[1]===t)return[t,e[2]]}else if(e[2]===t)return[t,e[1]];return null}function remove_duplicate_negatives(e){if(!Array.isArray(e))return e;var t=e[0],n=e.slice(1);return"-"===t&&"-"===n[0][0]?remove_duplicate_negatives(n[0][1]):(n=n.map(remove_duplicate_negatives),[t].concat(n))}function normalize_negatives_in_factors(e){if(!Array.isArray(e))return e;var t=e[0],n=e.slice(1);if(n=n.map(normalize_negatives_in_factors),"*"!==t&&"/"!==t)return[t].concat(n);for(var r=1,a=[],i=0;isort_key(e,t)))):o=[sort_key(i,t)],a.push([s,o]),a}if("unit"===n){let[n,r]=get_unit_value_of_tree(e);if(n){let e=sort_key(r,t);return e[1]+="_"+n,e}}var l=r.length,u=r.map(sort_key,t);return"*"===n?[4,"product",l,u]:"/"===n?[4,"quotient",l,u]:"+"===n?[5,"sum",l,u]:"-"===n?t.ignore_negatives?u[0]:[6,"minus",l,u]:[7,n,l,u]}function arrayCompare(e,t){if(Array.isArray(e)){if(Array.isArray(t)){let n=Math.min(e.length,t.length);for(let r=0;rt.length?1:0}return 1}return Array.isArray(t)||et?1:0}function compare_function(e,t,n={}){return arrayCompare(sort_key(e,n),sort_key(t,n))}function coeff_factors_from_term(e,t){if("string"==typeof e){let n=t.indexOf(e);-1===n&&(t.push(e),n=t.length-1);let r=[];return r[n]=1,{factor_contains:r,coeff:1}}if(Array.isArray(e)){let n=e[0],r=e.slice(1);if("*"===n){let e=[],n=[];for(let a of r)if("string"!=typeof a)if(Array.isArray(a)&&"^"===a[0]||"-"===a[0]){let r=coeff_factors_from_term(a,t);for(let e in r.factor_contains)void 0===n[e]&&(n[e]=0),n[e]+=r.factor_contains[e];1!==r.coeff&&e.push(r.coeff)}else e.push(a);else{let e=t.indexOf(a);-1===e&&(t.push(a),e=t.length-1),void 0===n[e]&&(n[e]=0),n[e]++}return e=0===e.length?1:1===e.length?e[0]:["*",...e],{factor_contains:n,coeff:e}}if("^"===n){let e=r[0],n=r[1],a=[];if("string"==typeof e&&Number.isFinite(n)){let r=t.indexOf(e);return-1===r&&(t.push(e),r=t.length-1),a[r]=n,{factor_contains:a,coeff:1}}}else{if("-"===n){let e=coeff_factors_from_term(r[0],t),n=-1;return"number"==typeof e.coeff?n*=e.coeff:n=["-",e.coeff],{factor_contains:e.factor_contains,coeff:n}}if("/"===n){let e=coeff_factors_from_term(r[0],t),n=["/",e.coeff,r[1]];return{factor_contains:e.factor_contains,coeff:n}}}}return{factor_contains:[],coeff:e}}function default_order(e,t){void 0===t&&(t={});var n=get_tree(e);return n=normalize_negatives(n=flatten$5(n)),normalize_negatives(function e(n){if(!Array.isArray(n))return n;var r=n[0],a=n.slice(1);if(a=a.map(e),"+"===r){let e=[],n=[],r=[];for(let t of a){let a=coeff_factors_from_term(t,e);n.push(a.factor_contains),r.push(a.coeff)}let i=[];for(let[t,r]of e.entries()){let e={varname:r,exponents_in_term:[]};for(let r=0;re.varname[...t,-n.exponents_in_term[e]]),[]);n.push(sort_key(r[e],t)),s.push(n)}let o=[];for(let[e,t]of a.entries())o.push({term:t,sort_key:s[e]});o.sort(((e,t)=>arrayCompare(e.sort_key,t.sort_key))),a=o.map((e=>e.term))}else if("*"===r){let e=[],n=[];for(let t of a)["tuple","list","vector","altvector","interval","set","array","matrix"].includes(t[0])?n.push(t):e.push(t);e.sort(((e,n)=>compare_function(e,n,t))),a=[...e,...n]}else if("="===r||"and"===r||"or"===r||"ne"===r||"union"===r||"intersect"===r)a.sort(((e,n)=>compare_function(e,n,t)));else if(">"===r||"ge"===r)a=a.reverse(),r=">"===r?"<":"le";else if("gts"===r){var i=a[0],s=a[1];if("tuple"!==i[0]||"tuple"!==s[0])throw new Error("Badly formed ast");r="lts",a=[i=["tuple"].concat(i.slice(1).reverse()),s=["tuple"].concat(s.slice(1).reverse())]}else if("ni"===r||"notni"===r||"superset"===r||"notsuperset"===r||"superseteq"===r||"notsuperseteq"===r)a=a.reverse(),"ni"===r?r="in":"notni"===r?r="notin":"superset"===r?r="subset":"notsuperset"===r?r="notsubset":"superseteq"===r?r="subseteq":"notsuperseteq"===r&&(r="notsubseteq");else if("-"===r&&"*"===a[0][0])return a[0][1]=["-",a[0][1]],a[0];return[r].concat(a)}(n))}function _extends$1(){return _extends$1=Object.assign?Object.assign.bind():function(e){for(var t=1;te[t]))}var MATRIX_OPTIONS=["Matrix","Array"],NUMBER_OPTIONS=["number","BigNumber","Fraction"];function configFactory(e,t){function n(n){if(n){var r=mapObject$1(e,clone$3);validateOption(n,"matrix",MATRIX_OPTIONS),validateOption(n,"number",NUMBER_OPTIONS),deepExtend(e,n);var a=mapObject$1(e,clone$3),i=mapObject$1(n,clone$3);return t("config",a,r,i),a}return mapObject$1(e,clone$3)}return n.MATRIX_OPTIONS=MATRIX_OPTIONS,n.NUMBER_OPTIONS=NUMBER_OPTIONS,Object.keys(DEFAULT_CONFIG).forEach((t=>{Object.defineProperty(n,t,{get:()=>e[t],enumerable:!0,configurable:!0})})),n}function contains$2(e,t){return-1!==e.indexOf(t)}function validateOption(e,t,n){void 0===e[t]||contains$2(n,e[t])||console.warn('Warning: Unknown value "'+e[t]+'" for configuration option "'+t+'". Available options: '+n.map((e=>JSON.stringify(e))).join(", ")+".")}var config$2=function(e){if(e)throw new Error("The global config is readonly. \nPlease create a mathjs instance if you want to change the default configuration. \nExample:\n\n import { create, all } from 'mathjs';\n const mathjs = create(all);\n mathjs.config({ number: 'BigNumber' });\n");return Object.freeze(DEFAULT_CONFIG)};_extends$1(config$2,DEFAULT_CONFIG,{MATRIX_OPTIONS:MATRIX_OPTIONS,NUMBER_OPTIONS:NUMBER_OPTIONS});var commonjsGlobal$1="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==commonjsGlobal?commonjsGlobal:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function getAugmentedNamespace(e){var t=e.default;if("function"==typeof t){var n=function(){return t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})})),n}var typedFunction$1={exports:{}};!function(e,t){e.exports=function(){function e(){return!0}function t(){return!1}function n(){}return function r(){var a=[{name:"number",test:function(e){return"number"==typeof e}},{name:"string",test:function(e){return"string"==typeof e}},{name:"boolean",test:function(e){return"boolean"==typeof e}},{name:"Function",test:function(e){return"function"==typeof e}},{name:"Array",test:Array.isArray},{name:"Date",test:function(e){return e instanceof Date}},{name:"RegExp",test:function(e){return e instanceof RegExp}},{name:"Object",test:function(e){return"object"==typeof e&&null!==e&&e.constructor===Object}},{name:"null",test:function(e){return null===e}},{name:"undefined",test:function(e){return void 0===e}}],i={name:"any",test:e},s=[],o=[],l={types:a,conversions:o,ignore:s};function u(e){var t=G(l.types,(function(t){return t.name===e}));if(t)return t;if("any"===e)return i;var n=G(l.types,(function(t){return t.name.toLowerCase()===e.toLowerCase()}));throw new TypeError('Unknown type "'+e+'"'+(n?'. Did you mean "'+n.name+'"?':""))}function c(e){return e===i?999:l.types.indexOf(e)}function p(e){var t=G(l.types,(function(t){return t.test(e)}));if(t)return t.name;throw new TypeError("Value has unknown type. Value: "+e)}function d(e){return e.map((function(e){var t=e.types.map(T);return(e.restParam?"...":"")+t.join("|")})).join(",")}function m(e,t){var n=0===e.indexOf("..."),r=(n?e.length>3?e.slice(3):"any":e).split("|").map(k).filter($).filter(F),a=function(e,t){var n={};return e.forEach((function(e){-1!==t.indexOf(e.from)||-1===t.indexOf(e.to)||n[e.from]||(n[e.from]=e)})),Object.keys(n).map((function(e){return n[e]}))}(t,r),i=r.map((function(e){var t=u(e);return{name:e,typeIndex:c(t),test:t.test,conversion:null,conversionIndex:-1}})),s=a.map((function(e){var n=u(e.from);return{name:e.from,typeIndex:c(n),test:n.test,conversion:e,conversionIndex:t.indexOf(e)}}));return{types:i.concat(s),restParam:n}}function h(e,t,n){var r=[];return""!==e.trim()&&(r=e.split(",").map(k).map((function(e,t,r){var a=m(e,n);if(a.restParam&&t!==r.length-1)throw new SyntaxError('Unexpected rest parameter "'+e+'": only allowed for the last parameter');return a}))),r.some(L)?null:{params:r,fn:t}}function f(e){var t=z(e);return!!t&&t.restParam}function y(e){return e.types.some((function(e){return null!=e.conversion}))}function g(t){if(t&&0!==t.types.length){if(1===t.types.length)return u(t.types[0].name).test;if(2===t.types.length){var n=u(t.types[0].name).test,r=u(t.types[1].name).test;return function(e){return n(e)||r(e)}}var a=t.types.map((function(e){return u(e.name).test}));return function(e){for(var t=0;t=a+1}}return 0===e.length?function(e){return 0===e.length}:1===e.length?(n=g(e[0]),function(e){return n(e[0])&&1===e.length}):2===e.length?(n=g(e[0]),r=g(e[1]),function(e){return n(e[0])&&r(e[1])&&2===e.length}):(t=e.map(g),function(e){for(var n=0;n0){var u=p(t[i]);return(r=new TypeError("Unexpected type of argument in function "+s+" (expected: "+a.join(" or ")+", actual: "+u+", index: "+i+")")).data={category:"wrongType",fn:s,index:i,actual:u,expected:a},r}}else o=l}var c=o.map((function(e){return f(e.params)?1/0:e.params.length}));if(t.lengthd?((r=new TypeError("Too many arguments in function "+s+" (expected: "+d+", actual: "+t.length+")")).data={category:"tooManyArgs",fn:s,index:t.length,expectedLength:d},r):((r=new TypeError('Arguments of type "'+t.join(", ")+'" do not match any of the defined signatures of function '+s+".")).data={category:"mismatch",actual:t.map(p)},r)}function x(e){for(var t=999,n=0;n=a:o?a>=i:a===i}function M(e,r){if(0===Object.keys(r).length)throw new SyntaxError("No signatures provided");var a=[];Object.keys(r).map((function(e){return h(e,r[e],l.conversions)})).filter(B).forEach((function(e){var t=G(a,(function(t){return _(t,e)}));if(t)throw new TypeError('Conflicting signatures "'+d(t.params)+'" and "'+d(e.params)+'".');a.push(e)}));var i=H(a,(function(e){return(e?R(e.params,!1):[]).map((function(t){return{params:t,fn:e.fn}}))})).filter(B);i.sort(E);var s=i[0]&&i[0].params.length<=2&&!f(i[0].params),o=i[1]&&i[1].params.length<=2&&!f(i[1].params),u=i[2]&&i[2].params.length<=2&&!f(i[2].params),c=i[3]&&i[3].params.length<=2&&!f(i[3].params),p=i[4]&&i[4].params.length<=2&&!f(i[4].params),m=i[5]&&i[5].params.length<=2&&!f(i[5].params),y=s&&o&&u&&c&&p&&m,v=i.map((function(e){return b(e.params)})),N=s?g(i[0].params[0]):t,T=o?g(i[1].params[0]):t,C=u?g(i[2].params[0]):t,A=c?g(i[3].params[0]):t,V=p?g(i[4].params[0]):t,x=m?g(i[5].params[0]):t,S=s?g(i[0].params[1]):t,w=o?g(i[1].params[1]):t,O=u?g(i[2].params[1]):t,M=c?g(i[3].params[1]):t,P=p?g(i[4].params[1]):t,F=m?g(i[5].params[1]):t,k=i.map((function(e){return D(e.params,e.fn)})),$=s?k[0]:n,L=o?k[1]:n,z=u?k[2]:n,U=c?k[3]:n,j=p?k[4]:n,q=m?k[5]:n,W=s?i[0].params.length:-1,K=o?i[1].params.length:-1,Z=u?i[2].params.length:-1,X=c?i[3].params.length:-1,Y=p?i[4].params.length:-1,Q=m?i[5].params.length:-1,J=y?6:0,ee=i.length,te=function(){for(var t=J;t0?1:e<0?-1:0},log2$2=Math.log2||function(e){return Math.log(e)/Math.LN2},log10$3=Math.log10||function(e){return Math.log(e)/Math.LN10},log1p$1=Math.log1p||function(e){return Math.log(e+1)},cbrt$2=Math.cbrt||function(e){if(0===e)return e;var t,n=e<0;return n&&(e=-e),t=isFinite(e)?(e/((t=Math.exp(Math.log(e)/3))*t)+2*t)/3:e,n?-t:t},expm1$1=Math.expm1||function(e){return e>=2e-4||e<=-2e-4?Math.exp(e)-1:e+e*e/2+e*e*e/6};function formatNumberToBase(e,t,n){var r={2:"0b",8:"0o",16:"0x"}[t],a="";if(n){if(n<1)throw new Error("size must be in greater than 0");if(!isInteger$1(n))throw new Error("size must be an integer");if(e>2**(n-1)-1||e<-(2**(n-1)))throw new Error("Value must be in range [-2^".concat(n-1,", 2^").concat(n-1,"-1]"));if(!isInteger$1(e))throw new Error("Value must be an integer");e<0&&(e+=2**n),a="i".concat(n)}var i="";return e<0&&(e=-e,i="-"),"".concat(i).concat(r).concat(e.toString(t)).concat(a)}function format$3(e,t){if("function"==typeof t)return t(e);if(e===1/0)return"Infinity";if(e===-1/0)return"-Infinity";if(isNaN(e))return"NaN";var n,r,a="auto";if(t&&(t.notation&&(a=t.notation),isNumber$1(t)?n=t:isNumber$1(t.precision)&&(n=t.precision),t.wordSize&&"number"!=typeof(r=t.wordSize)))throw new Error('Option "wordSize" must be a number');switch(a){case"fixed":return toFixed$2(e,n);case"exponential":return toExponential$1(e,n);case"engineering":return toEngineering$1(e,n);case"bin":return formatNumberToBase(e,2,r);case"oct":return formatNumberToBase(e,8,r);case"hex":return formatNumberToBase(e,16,r);case"auto":return toPrecision(e,n,t&&t).replace(/((\.\d*?)(0+))($|e)/,(function(){var e=arguments[2],t=arguments[4];return"."!==e?e+t:t}));default:throw new Error('Unknown notation "'+a+'". Choose "auto", "exponential", "fixed", "bin", "oct", or "hex.')}}function splitNumber(e){var t=String(e).toLowerCase().match(/^(-?)(\d+\.?\d*)(e([+-]?\d+))?$/);if(!t)throw new SyntaxError("Invalid number "+e);var n=t[1],r=t[2],a=parseFloat(t[4]||"0"),i=r.indexOf(".");a+=-1!==i?i-1:r.length-1;var s=r.replace(".","").replace(/^0*/,(function(e){return a-=e.length,""})).replace(/0*$/,"").split("").map((function(e){return parseInt(e)}));return 0===s.length&&(s.push(0),a++),{sign:n,coefficients:s,exponent:a}}function toEngineering$1(e,t){if(isNaN(e)||!isFinite(e))return String(e);var n=roundDigits(splitNumber(e),t),r=n.exponent,a=n.coefficients,i=r%3==0?r:r<0?r-3-r%3:r-r%3;if(isNumber$1(t))for(;t>a.length||r-i+1>a.length;)a.push(0);else for(var s=Math.abs(r-i)-(a.length-1),o=0;o0;)u++,l--;var c=a.slice(u).join(""),p=isNumber$1(t)&&c.length||c.match(/[1-9]/)?"."+c:"",d=a.slice(0,u).join("")+p+"e"+(r>=0?"+":"")+i.toString();return n.sign+d}function toFixed$2(e,t){if(isNaN(e)||!isFinite(e))return String(e);var n=splitNumber(e),r="number"==typeof t?roundDigits(n,n.exponent+1+t):n,a=r.coefficients,i=r.exponent+1,s=i+(t||0);return a.length0?"."+a.join(""):"")+"e"+(i>=0?"+":"")+i}function toPrecision(e,t,n){if(isNaN(e)||!isFinite(e))return String(e);var r=n&&void 0!==n.lowerExp?n.lowerExp:-3,a=n&&void 0!==n.upperExp?n.upperExp:5,i=splitNumber(e),s=t?roundDigits(i,t):i;if(s.exponent=a)return toExponential$1(e,t);var o=s.coefficients,l=s.exponent;o.length0?l:0;return u<(o=zeros$1(-l).concat(o)).length-1&&o.splice(u+1,0,"."),s.sign+o.join("")}function roundDigits(e,t){for(var n={sign:e.sign,coefficients:e.coefficients,exponent:e.exponent},r=n.coefficients;t<=0;)r.unshift(0),n.exponent++,t++;if(r.length>t&&r.splice(t,r.length-t)[0]>=5){var a=t-1;for(r[a]++;10===r[a];)r.pop(),0===a&&(r.unshift(0),n.exponent++,a++),r[--a]++}return n}function zeros$1(e){for(var t=[],n=0;n0||!(e<0)&&1/e==1/0)^(t>0||!(t<0)&&1/t==1/0)?-e:e}function formatBigNumberToBase(e,t,n){var r=new e.constructor(2),a="";if(n){if(n<1)throw new Error("size must be in greater than 0");if(!isInteger$1(n))throw new Error("size must be an integer");if(e.greaterThan(r.pow(n-1).sub(1))||e.lessThan(r.pow(n-1).mul(-1)))throw new Error("Value must be in range [-2^".concat(n-1,", 2^").concat(n-1,"-1]"));if(!e.isInteger())throw new Error("Value must be an integer");e.lessThan(0)&&(e=e.add(r.pow(n))),a="i".concat(n)}switch(t){case 2:return"".concat(e.toBinary()).concat(a);case 8:return"".concat(e.toOctal()).concat(a);case 16:return"".concat(e.toHexadecimal()).concat(a);default:throw new Error("Base ".concat(t," not supported "))}}function format$2(e,t){if("function"==typeof t)return t(e);if(!e.isFinite())return e.isNaN()?"NaN":e.gt(0)?"Infinity":"-Infinity";var n,r,a="auto";if(void 0!==t&&(t.notation&&(a=t.notation),"number"==typeof t?n=t:t.precision&&(n=t.precision),t.wordSize&&"number"!=typeof(r=t.wordSize)))throw new Error('Option "wordSize" must be a number');switch(a){case"fixed":return toFixed$1(e,n);case"exponential":return toExponential(e,n);case"engineering":return toEngineering(e,n);case"bin":return formatBigNumberToBase(e,2,r);case"oct":return formatBigNumberToBase(e,8,r);case"hex":return formatBigNumberToBase(e,16,r);case"auto":var i=t&&void 0!==t.lowerExp?t.lowerExp:-3,s=t&&void 0!==t.upperExp?t.upperExp:5;if(e.isZero())return"0";var o=e.toSignificantDigits(n),l=o.e;return(l>=i&&l=0?"+":"")+r.toString()}function toExponential(e,t){return void 0!==t?e.toExponential(t-1):e.toExponential()}function toFixed$1(e,t){return e.toFixed(t)}function endsWith(e,t){var n=e.length-t.length,r=e.length;return e.substring(n,r)===t}function format$1(e,t){var n=_format(e,t);return t&&"object"==typeof t&&"truncate"in t&&n.length>t.truncate?n.substring(0,t.truncate-3)+"...":n}function _format(e,t){return"number"==typeof e?format$3(e,t):isBigNumber(e)?format$2(e,t):looksLikeFraction(e)?t&&"decimal"===t.fraction?e.toString():e.s*e.n+"/"+e.d:Array.isArray(e)?formatArray(e,t):isString$1(e)?'"'+e+'"':"function"==typeof e?e.syntax?String(e.syntax):"function":e&&"object"==typeof e?"function"==typeof e.format?e.format(t):e&&e.toString(t)!=={}.toString()?e.toString(t):"{"+Object.keys(e).map((n=>'"'+n+'": '+format$1(e[n],t))).join(", ")+"}":String(e)}function stringify(e){for(var t=String(e),n="",r=0;r/g,">")}function formatArray(e,t){if(Array.isArray(e)){for(var n="[",r=e.length,a=0;at?1:-1}function DimensionError(e,t,n){if(!(this instanceof DimensionError))throw new SyntaxError("Constructor must be called with the new operator");this.actual=e,this.expected=t,this.relation=n,this.message="Dimension mismatch ("+(Array.isArray(e)?"["+e.join(", ")+"]":e)+" "+(this.relation||"!=")+" "+(Array.isArray(t)?"["+t.join(", ")+"]":t)+")",this.stack=(new Error).stack}function IndexError(e,t,n){if(!(this instanceof IndexError))throw new SyntaxError("Constructor must be called with the new operator");this.index=e,arguments.length<3?(this.min=0,this.max=t):(this.min=t,this.max=n),void 0!==this.min&&this.index=this.max?this.message="Index out of range ("+this.index+" > "+(this.max-1)+")":this.message="Index out of range ("+this.index+")",this.stack=(new Error).stack}function arraySize(e){for(var t=[];Array.isArray(e);)t.push(e.length),e=e[0];return t}function _validate(e,t,n){var r,a=e.length;if(a!==t[n])throw new DimensionError(a,t[n]);if(n")}function validate(e,t){if(0===t.length){if(Array.isArray(e))throw new DimensionError(e.length,0)}else _validate(e,t,0)}function validateIndex(e,t){if(!isNumber$1(e)||!isInteger$1(e))throw new TypeError("Index must be an integer (value: "+e+")");if(e<0||"number"==typeof t&&e>=t)throw new IndexError(e,t)}function resize$1(e,t,n){if(!Array.isArray(e)||!Array.isArray(t))throw new TypeError("Array expected");if(0===t.length)throw new Error("Resizing to scalar is not supported");return t.forEach((function(e){if(!isNumber$1(e)||!isInteger$1(e)||e<0)throw new TypeError("Invalid size, must contain positive integers (size: "+format$1(t)+")")})),_resize(e,t,0,void 0!==n?n:0),e}function _resize(e,t,n,r){var a,i,s=e.length,o=t[n],l=Math.min(s,o);if(e.length=o,n=0){if(t%n!=0)throw new Error("Could not replace wildcard, since "+t+" is no multiple of "+-n);r[a]=-t/n}return r}function product$1(e){return e.reduce(((e,t)=>e*t),1)}function _reshape(e,t){for(var n,r=e,a=t.length-1;a>0;a--){var i=t[a];n=[];for(var s=r.length/i,o=0;ot.test(e)))}function join(e,t){return Array.prototype.join.call(e,t)}function identify(e){if(!Array.isArray(e))throw new TypeError("Array input expected");if(0===e.length)return e;var t=[],n=0;t[0]={value:e[0],identifier:0};for(var r=1;r!isOptionalDependency(e))).every((e=>void 0!==n[e]))){var r=t.filter((e=>void 0===n[e]));throw new Error('Cannot create function "'.concat(e,'", ')+"some dependencies are missing: ".concat(r.map((e=>'"'.concat(e,'"'))).join(", "),"."))}}function isOptionalDependency(e){return e&&"?"===e[0]}function stripOptionalNotation(e){return e&&"?"===e[0]?e.slice(1):e}function getSafeProperty(e,t){if(isPlainObject(e)&&isSafeProperty(e,t))return e[t];if("function"==typeof e[t]&&isSafeMethod(e,t))throw new Error('Cannot access method "'+t+'" as a property');throw new Error('No access to property "'+t+'"')}function setSafeProperty(e,t,n){if(isPlainObject(e)&&isSafeProperty(e,t))return e[t]=n,n;throw new Error('No access to property "'+t+'"')}function hasSafeProperty(e,t){return t in e}function isSafeProperty(e,t){return!(!e||"object"!=typeof e||!hasOwnProperty$2(safeNativeProperties,t)&&(t in Object.prototype||t in Function.prototype))}function validateSafeMethod(e,t){if(!isSafeMethod(e,t))throw new Error('No access to method "'+t+'"')}function isSafeMethod(e,t){return!(null==e||"function"!=typeof e[t]||hasOwnProperty$2(e,t)&&Object.getPrototypeOf&&t in Object.getPrototypeOf(e)||!hasOwnProperty$2(safeNativeMethods,t)&&(t in Object.prototype||t in Function.prototype))}function isPlainObject(e){return"object"==typeof e&&e&&e.constructor===Object}DimensionError.prototype=new RangeError,DimensionError.prototype.constructor=RangeError,DimensionError.prototype.name="DimensionError",DimensionError.prototype.isDimensionError=!0,IndexError.prototype=new RangeError,IndexError.prototype.constructor=RangeError,IndexError.prototype.name="IndexError",IndexError.prototype.isIndexError=!0;var safeNativeProperties={length:!0,name:!0},safeNativeMethods={toString:!0,valueOf:!0,toLocaleString:!0};class ObjectWrappingMap{constructor(e){this.wrappedObject=e}keys(){return Object.keys(this.wrappedObject)}get(e){return getSafeProperty(this.wrappedObject,e)}set(e,t){return setSafeProperty(this.wrappedObject,e,t),this}has(e){return hasSafeProperty(this.wrappedObject,e)}}function createEmptyMap(){return new Map}function createMap$1(e){if(!e)return createEmptyMap();if(isMap$1(e))return e;if(isObject$1(e))return new ObjectWrappingMap(e);throw new Error("createMap can create maps from objects or Maps")}function toObject(e){if(e instanceof ObjectWrappingMap)return e.wrappedObject;var t={};for(var n of e.keys())setSafeProperty(t,n,e.get(n));return t}function isMap$1(e){return!!e&&(e instanceof Map||e instanceof ObjectWrappingMap||"function"==typeof e.set&&"function"==typeof e.get&&"function"==typeof e.keys&&"function"==typeof e.has)}function assign(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r15)throw new TypeError("Cannot implicitly convert a number with >15 significant digits to BigNumber (value: "+e+"). Use function bignumber(x) to convert to BigNumber.");return new t(e)}},{from:"number",to:"Complex",convert:function(e){return n||throwNoComplex(e),new n(e,0)}},{from:"number",to:"string",convert:function(e){return e+""}},{from:"BigNumber",to:"Complex",convert:function(e){return n||throwNoComplex(e),new n(e.toNumber(),0)}},{from:"Fraction",to:"BigNumber",convert:function(e){throw new TypeError("Cannot implicitly convert a Fraction to BigNumber or vice versa. Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.")}},{from:"Fraction",to:"Complex",convert:function(e){return n||throwNoComplex(e),new n(e.valueOf(),0)}},{from:"number",to:"Fraction",convert:function(e){a||throwNoFraction(e);var t=new a(e);if(t.valueOf()!==e)throw new TypeError("Cannot implicitly convert a number to a Fraction when there will be a loss of precision (value: "+e+"). Use function fraction(x) to convert to Fraction.");return t}},{from:"string",to:"number",convert:function(e){var t=Number(e);if(isNaN(t))throw new Error('Cannot convert "'+e+'" to a number');return t}},{from:"string",to:"BigNumber",convert:function(e){t||throwNoBignumber(e);try{return new t(e)}catch(t){throw new Error('Cannot convert "'+e+'" to BigNumber')}}},{from:"string",to:"Fraction",convert:function(e){a||throwNoFraction(e);try{return new a(e)}catch(t){throw new Error('Cannot convert "'+e+'" to Fraction')}}},{from:"string",to:"Complex",convert:function(e){n||throwNoComplex(e);try{return new n(e)}catch(t){throw new Error('Cannot convert "'+e+'" to Complex')}}},{from:"boolean",to:"number",convert:function(e){return+e}},{from:"boolean",to:"BigNumber",convert:function(e){return t||throwNoBignumber(e),new t(+e)}},{from:"boolean",to:"Fraction",convert:function(e){return a||throwNoFraction(e),new a(+e)}},{from:"boolean",to:"string",convert:function(e){return String(e)}},{from:"Array",to:"Matrix",convert:function(e){return r||throwNoMatrix(),new r(e)}},{from:"Matrix",to:"Array",convert:function(e){return e.valueOf()}}],i}));function throwNoBignumber(e){throw new Error("Cannot convert value ".concat(e," into a BigNumber: no class 'BigNumber' provided"))}function throwNoComplex(e){throw new Error("Cannot convert value ".concat(e," into a Complex number: no class 'Complex' provided"))}function throwNoMatrix(){throw new Error("Cannot convert array into a Matrix: no class 'DenseMatrix' provided")}function throwNoFraction(e){throw new Error("Cannot convert value ".concat(e," into a Fraction, no class 'Fraction' provided."))}var name$4C="ResultSet",dependencies$4C=[],createResultSet=factory(name$4C,dependencies$4C,(()=>{function e(t){if(!(this instanceof e))throw new SyntaxError("Constructor must be called with the new operator");this.entries=t||[]}return e.prototype.type="ResultSet",e.prototype.isResultSet=!0,e.prototype.valueOf=function(){return this.entries},e.prototype.toString=function(){return"["+this.entries.join(", ")+"]"},e.prototype.toJSON=function(){return{mathjs:"ResultSet",entries:this.entries}},e.fromJSON=function(t){return new e(t.entries)},e}),{isClass:!0}),EXP_LIMIT=9e15,MAX_DIGITS=1e9,NUMERALS="0123456789abcdef",LN10$1="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",PI="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",DEFAULTS={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-EXP_LIMIT,maxE:EXP_LIMIT,crypto:!1},inexact,quadrant,external=!0,decimalError="[DecimalError] ",invalidArgument=decimalError+"Invalid argument: ",precisionLimitExceeded=decimalError+"Precision limit exceeded",cryptoUnavailable=decimalError+"crypto unavailable",tag="[object Decimal]",mathfloor=Math.floor,mathpow=Math.pow,isBinary=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,isHex=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,isOctal=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,isDecimal=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,BASE=1e7,LOG_BASE=7,MAX_SAFE_INTEGER=9007199254740991,LN10_PRECISION=LN10$1.length-1,PI_PRECISION=PI.length-1,P$1={toStringTag:tag};function digitsToString(e){var t,n,r,a=e.length-1,i="",s=e[0];if(a>0){for(i+=s,t=1;tn)throw Error(invalidArgument+e)}function checkRoundingDigits(e,t,n,r){var a,i,s,o;for(i=e[0];i>=10;i/=10)--t;return--t<0?(t+=LOG_BASE,a=0):(a=Math.ceil((t+1)/LOG_BASE),t%=LOG_BASE),i=mathpow(10,LOG_BASE-t),o=e[a]%i|0,null==r?t<3?(0==t?o=o/100|0:1==t&&(o=o/10|0),s=n<4&&99999==o||n>3&&49999==o||5e4==o||0==o):s=(n<4&&o+1==i||n>3&&o+1==i/2)&&(e[a+1]/i/100|0)==mathpow(10,t-2)-1||(o==i/2||0==o)&&0==(e[a+1]/i/100|0):t<4?(0==t?o=o/1e3|0:1==t?o=o/100|0:2==t&&(o=o/10|0),s=(r||n<4)&&9999==o||!r&&n>3&&4999==o):s=((r||n<4)&&o+1==i||!r&&n>3&&o+1==i/2)&&(e[a+1]/i/1e3|0)==mathpow(10,t-3)-1,s}function convertBase(e,t,n){for(var r,a,i=[0],s=0,o=e.length;sn-1&&(void 0===i[r+1]&&(i[r+1]=0),i[r+1]+=i[r]/n|0,i[r]%=n)}return i.reverse()}function cosine(e,t){var n,r,a;if(t.isZero())return t;(r=t.d.length)<32?a=(1/tinyPow(4,n=Math.ceil(r/3))).toString():(n=16,a="2.3283064365386962890625e-10"),e.precision+=n,t=taylorSeries(e,1,t.times(a),new e(1));for(var i=n;i--;){var s=t.times(t);t=s.times(s).minus(s).times(8).plus(1)}return e.precision-=n,t}P$1.absoluteValue=P$1.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),finalise(e)},P$1.ceil=function(){return finalise(new this.constructor(this),this.e+1,2)},P$1.clampedTo=P$1.clamp=function(e,t){var n=this,r=n.constructor;if(e=new r(e),t=new r(t),!e.s||!t.s)return new r(NaN);if(e.gt(t))throw Error(invalidArgument+t);return n.cmp(e)<0?e:n.cmp(t)>0?t:new r(n)},P$1.comparedTo=P$1.cmp=function(e){var t,n,r,a,i=this,s=i.d,o=(e=new i.constructor(e)).d,l=i.s,u=e.s;if(!s||!o)return l&&u?l!==u?l:s===o?0:!s^l<0?1:-1:NaN;if(!s[0]||!o[0])return s[0]?l:o[0]?-u:0;if(l!==u)return l;if(i.e!==e.e)return i.e>e.e^l<0?1:-1;for(t=0,n=(r=s.length)<(a=o.length)?r:a;to[t]^l<0?1:-1;return r===a?0:r>a^l<0?1:-1},P$1.cosine=P$1.cos=function(){var e,t,n=this,r=n.constructor;return n.d?n.d[0]?(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+LOG_BASE,r.rounding=1,n=cosine(r,toLessThanHalfPi(r,n)),r.precision=e,r.rounding=t,finalise(2==quadrant||3==quadrant?n.neg():n,e,t,!0)):new r(1):new r(NaN)},P$1.cubeRoot=P$1.cbrt=function(){var e,t,n,r,a,i,s,o,l,u,c=this,p=c.constructor;if(!c.isFinite()||c.isZero())return new p(c);for(external=!1,(i=c.s*mathpow(c.s*c,1/3))&&Math.abs(i)!=1/0?r=new p(i.toString()):(n=digitsToString(c.d),(i=((e=c.e)-n.length+1)%3)&&(n+=1==i||-2==i?"0":"00"),i=mathpow(n,1/3),e=mathfloor((e+1)/3)-(e%3==(e<0?-1:2)),(r=new p(n=i==1/0?"5e"+e:(n=i.toExponential()).slice(0,n.indexOf("e")+1)+e)).s=c.s),s=(e=p.precision)+3;;)if(u=(l=(o=r).times(o).times(o)).plus(c),r=divide$2(u.plus(c).times(o),u.plus(l),s+2,1),digitsToString(o.d).slice(0,s)===(n=digitsToString(r.d)).slice(0,s)){if("9999"!=(n=n.slice(s-3,s+1))&&(a||"4999"!=n)){+n&&(+n.slice(1)||"5"!=n.charAt(0))||(finalise(r,e+1,1),t=!r.times(r).times(r).eq(c));break}if(!a&&(finalise(o,e+1,0),o.times(o).times(o).eq(c))){r=o;break}s+=4,a=1}return external=!0,finalise(r,e,p.rounding,t)},P$1.decimalPlaces=P$1.dp=function(){var e,t=this.d,n=NaN;if(t){if(n=((e=t.length-1)-mathfloor(this.e/LOG_BASE))*LOG_BASE,e=t[e])for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n},P$1.dividedBy=P$1.div=function(e){return divide$2(this,new this.constructor(e))},P$1.dividedToIntegerBy=P$1.divToInt=function(e){var t=this.constructor;return finalise(divide$2(this,new t(e),0,1,1),t.precision,t.rounding)},P$1.equals=P$1.eq=function(e){return 0===this.cmp(e)},P$1.floor=function(){return finalise(new this.constructor(this),this.e+1,3)},P$1.greaterThan=P$1.gt=function(e){return this.cmp(e)>0},P$1.greaterThanOrEqualTo=P$1.gte=function(e){var t=this.cmp(e);return 1==t||0===t},P$1.hyperbolicCosine=P$1.cosh=function(){var e,t,n,r,a,i=this,s=i.constructor,o=new s(1);if(!i.isFinite())return new s(i.s?1/0:NaN);if(i.isZero())return o;n=s.precision,r=s.rounding,s.precision=n+Math.max(i.e,i.sd())+4,s.rounding=1,(a=i.d.length)<32?t=(1/tinyPow(4,e=Math.ceil(a/3))).toString():(e=16,t="2.3283064365386962890625e-10"),i=taylorSeries(s,1,i.times(t),new s(1),!0);for(var l,u=e,c=new s(8);u--;)l=i.times(i),i=o.minus(l.times(c.minus(l.times(c))));return finalise(i,s.precision=n,s.rounding=r,!0)},P$1.hyperbolicSine=P$1.sinh=function(){var e,t,n,r,a=this,i=a.constructor;if(!a.isFinite()||a.isZero())return new i(a);if(t=i.precision,n=i.rounding,i.precision=t+Math.max(a.e,a.sd())+4,i.rounding=1,(r=a.d.length)<3)a=taylorSeries(i,2,a,a,!0);else{e=(e=1.4*Math.sqrt(r))>16?16:0|e,a=taylorSeries(i,2,a=a.times(1/tinyPow(5,e)),a,!0);for(var s,o=new i(5),l=new i(16),u=new i(20);e--;)s=a.times(a),a=a.times(o.plus(s.times(l.times(s).plus(u))))}return i.precision=t,i.rounding=n,finalise(a,t,n,!0)},P$1.hyperbolicTangent=P$1.tanh=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+7,r.rounding=1,divide$2(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)},P$1.inverseCosine=P$1.acos=function(){var e,t=this,n=t.constructor,r=t.abs().cmp(1),a=n.precision,i=n.rounding;return-1!==r?0===r?t.isNeg()?getPi(n,a,i):new n(0):new n(NaN):t.isZero()?getPi(n,a+4,i).times(.5):(n.precision=a+6,n.rounding=1,t=t.asin(),e=getPi(n,a+4,i).times(.5),n.precision=a,n.rounding=i,e.minus(t))},P$1.inverseHyperbolicCosine=P$1.acosh=function(){var e,t,n=this,r=n.constructor;return n.lte(1)?new r(n.eq(1)?0:NaN):n.isFinite()?(e=r.precision,t=r.rounding,r.precision=e+Math.max(Math.abs(n.e),n.sd())+4,r.rounding=1,external=!1,n=n.times(n).minus(1).sqrt().plus(n),external=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)},P$1.inverseHyperbolicSine=P$1.asinh=function(){var e,t,n=this,r=n.constructor;return!n.isFinite()||n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+2*Math.max(Math.abs(n.e),n.sd())+6,r.rounding=1,external=!1,n=n.times(n).plus(1).sqrt().plus(n),external=!0,r.precision=e,r.rounding=t,n.ln())},P$1.inverseHyperbolicTangent=P$1.atanh=function(){var e,t,n,r,a=this,i=a.constructor;return a.isFinite()?a.e>=0?new i(a.abs().eq(1)?a.s/0:a.isZero()?a:NaN):(e=i.precision,t=i.rounding,r=a.sd(),Math.max(r,e)<2*-a.e-1?finalise(new i(a),e,t,!0):(i.precision=n=r-a.e,a=divide$2(a.plus(1),new i(1).minus(a),n+e,1),i.precision=e+4,i.rounding=1,a=a.ln(),i.precision=e,i.rounding=t,a.times(.5))):new i(NaN)},P$1.inverseSine=P$1.asin=function(){var e,t,n,r,a=this,i=a.constructor;return a.isZero()?new i(a):(t=a.abs().cmp(1),n=i.precision,r=i.rounding,-1!==t?0===t?((e=getPi(i,n+4,r).times(.5)).s=a.s,e):new i(NaN):(i.precision=n+6,i.rounding=1,a=a.div(new i(1).minus(a.times(a)).sqrt().plus(1)).atan(),i.precision=n,i.rounding=r,a.times(2)))},P$1.inverseTangent=P$1.atan=function(){var e,t,n,r,a,i,s,o,l,u=this,c=u.constructor,p=c.precision,d=c.rounding;if(u.isFinite()){if(u.isZero())return new c(u);if(u.abs().eq(1)&&p+4<=PI_PRECISION)return(s=getPi(c,p+4,d).times(.25)).s=u.s,s}else{if(!u.s)return new c(NaN);if(p+4<=PI_PRECISION)return(s=getPi(c,p+4,d).times(.5)).s=u.s,s}for(c.precision=o=p+10,c.rounding=1,e=n=Math.min(28,o/LOG_BASE+2|0);e;--e)u=u.div(u.times(u).plus(1).sqrt().plus(1));for(external=!1,t=Math.ceil(o/LOG_BASE),r=1,l=u.times(u),s=new c(u),a=u;-1!==e;)if(a=a.times(l),i=s.minus(a.div(r+=2)),a=a.times(l),void 0!==(s=i.plus(a.div(r+=2))).d[t])for(e=t;s.d[e]===i.d[e]&&e--;);return n&&(s=s.times(2<this.d.length-2},P$1.isNaN=function(){return!this.s},P$1.isNegative=P$1.isNeg=function(){return this.s<0},P$1.isPositive=P$1.isPos=function(){return this.s>0},P$1.isZero=function(){return!!this.d&&0===this.d[0]},P$1.lessThan=P$1.lt=function(e){return this.cmp(e)<0},P$1.lessThanOrEqualTo=P$1.lte=function(e){return this.cmp(e)<1},P$1.logarithm=P$1.log=function(e){var t,n,r,a,i,s,o,l,u=this,c=u.constructor,p=c.precision,d=c.rounding;if(null==e)e=new c(10),t=!0;else{if(n=(e=new c(e)).d,e.s<0||!n||!n[0]||e.eq(1))return new c(NaN);t=e.eq(10)}if(n=u.d,u.s<0||!n||!n[0]||u.eq(1))return new c(n&&!n[0]?-1/0:1!=u.s?NaN:n?0:1/0);if(t)if(n.length>1)i=!0;else{for(a=n[0];a%10==0;)a/=10;i=1!==a}if(external=!1,s=naturalLogarithm(u,o=p+5),r=t?getLn10(c,o+10):naturalLogarithm(e,o),checkRoundingDigits((l=divide$2(s,r,o,1)).d,a=p,d))do{if(s=naturalLogarithm(u,o+=10),r=t?getLn10(c,o+10):naturalLogarithm(e,o),l=divide$2(s,r,o,1),!i){+digitsToString(l.d).slice(a+1,a+15)+1==1e14&&(l=finalise(l,p+1,0));break}}while(checkRoundingDigits(l.d,a+=10,d));return external=!0,finalise(l,p,d)},P$1.minus=P$1.sub=function(e){var t,n,r,a,i,s,o,l,u,c,p,d,m=this,h=m.constructor;if(e=new h(e),!m.d||!e.d)return m.s&&e.s?m.d?e.s=-e.s:e=new h(e.d||m.s!==e.s?m:NaN):e=new h(NaN),e;if(m.s!=e.s)return e.s=-e.s,m.plus(e);if(u=m.d,d=e.d,o=h.precision,l=h.rounding,!u[0]||!d[0]){if(d[0])e.s=-e.s;else{if(!u[0])return new h(3===l?-0:0);e=new h(m)}return external?finalise(e,o,l):e}if(n=mathfloor(e.e/LOG_BASE),c=mathfloor(m.e/LOG_BASE),u=u.slice(),i=c-n){for((p=i<0)?(t=u,i=-i,s=d.length):(t=d,n=c,s=u.length),i>(r=Math.max(Math.ceil(o/LOG_BASE),s)+2)&&(i=r,t.length=1),t.reverse(),r=i;r--;)t.push(0);t.reverse()}else{for((p=(r=u.length)<(s=d.length))&&(s=r),r=0;r0;--r)u[s++]=0;for(r=d.length;r>i;){if(u[--r](s=(i=Math.ceil(o/LOG_BASE))>s?i+1:s+1)&&(a=s,n.length=1),n.reverse();a--;)n.push(0);n.reverse()}for((s=u.length)-(a=c.length)<0&&(a=s,n=c,c=u,u=n),t=0;a;)t=(u[--a]=u[a]+c[a]+t)/BASE|0,u[a]%=BASE;for(t&&(u.unshift(t),++r),s=u.length;0==u[--s];)u.pop();return e.d=u,e.e=getBase10Exponent(u,r),external?finalise(e,o,l):e},P$1.precision=P$1.sd=function(e){var t,n=this;if(void 0!==e&&e!==!!e&&1!==e&&0!==e)throw Error(invalidArgument+e);return n.d?(t=getPrecision(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t},P$1.round=function(){var e=this,t=e.constructor;return finalise(new t(e),e.e+1,t.rounding)},P$1.sine=P$1.sin=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+LOG_BASE,r.rounding=1,n=sine(r,toLessThanHalfPi(r,n)),r.precision=e,r.rounding=t,finalise(quadrant>2?n.neg():n,e,t,!0)):new r(NaN)},P$1.squareRoot=P$1.sqrt=function(){var e,t,n,r,a,i,s=this,o=s.d,l=s.e,u=s.s,c=s.constructor;if(1!==u||!o||!o[0])return new c(!u||u<0&&(!o||o[0])?NaN:o?s:1/0);for(external=!1,0==(u=Math.sqrt(+s))||u==1/0?(((t=digitsToString(o)).length+l)%2==0&&(t+="0"),u=Math.sqrt(t),l=mathfloor((l+1)/2)-(l<0||l%2),r=new c(t=u==1/0?"5e"+l:(t=u.toExponential()).slice(0,t.indexOf("e")+1)+l)):r=new c(u.toString()),n=(l=c.precision)+3;;)if(r=(i=r).plus(divide$2(s,i,n+2,1)).times(.5),digitsToString(i.d).slice(0,n)===(t=digitsToString(r.d)).slice(0,n)){if("9999"!=(t=t.slice(n-3,n+1))&&(a||"4999"!=t)){+t&&(+t.slice(1)||"5"!=t.charAt(0))||(finalise(r,l+1,1),e=!r.times(r).eq(s));break}if(!a&&(finalise(i,l+1,0),i.times(i).eq(s))){r=i;break}n+=4,a=1}return external=!0,finalise(r,l,c.rounding,e)},P$1.tangent=P$1.tan=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+10,r.rounding=1,(n=n.sin()).s=1,n=divide$2(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,finalise(2==quadrant||4==quadrant?n.neg():n,e,t,!0)):new r(NaN)},P$1.times=P$1.mul=function(e){var t,n,r,a,i,s,o,l,u,c=this,p=c.constructor,d=c.d,m=(e=new p(e)).d;if(e.s*=c.s,!(d&&d[0]&&m&&m[0]))return new p(!e.s||d&&!d[0]&&!m||m&&!m[0]&&!d?NaN:d&&m?0*e.s:e.s/0);for(n=mathfloor(c.e/LOG_BASE)+mathfloor(e.e/LOG_BASE),(l=d.length)<(u=m.length)&&(i=d,d=m,m=i,s=l,l=u,u=s),i=[],r=s=l+u;r--;)i.push(0);for(r=u;--r>=0;){for(t=0,a=l+r;a>r;)o=i[a]+m[r]*d[a-r-1]+t,i[a--]=o%BASE|0,t=o/BASE|0;i[a]=(i[a]+t)%BASE|0}for(;!i[--s];)i.pop();return t?++n:i.shift(),e.d=i,e.e=getBase10Exponent(i,n),external?finalise(e,p.precision,p.rounding):e},P$1.toBinary=function(e,t){return toStringBinary(this,2,e,t)},P$1.toDecimalPlaces=P$1.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),void 0===e?n:(checkInt32(e,0,MAX_DIGITS),void 0===t?t=r.rounding:checkInt32(t,0,8),finalise(n,e+n.e+1,t))},P$1.toExponential=function(e,t){var n,r=this,a=r.constructor;return void 0===e?n=finiteToString(r,!0):(checkInt32(e,0,MAX_DIGITS),void 0===t?t=a.rounding:checkInt32(t,0,8),n=finiteToString(r=finalise(new a(r),e+1,t),!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n},P$1.toFixed=function(e,t){var n,r,a=this,i=a.constructor;return void 0===e?n=finiteToString(a):(checkInt32(e,0,MAX_DIGITS),void 0===t?t=i.rounding:checkInt32(t,0,8),n=finiteToString(r=finalise(new i(a),e+a.e+1,t),!1,e+r.e+1)),a.isNeg()&&!a.isZero()?"-"+n:n},P$1.toFraction=function(e){var t,n,r,a,i,s,o,l,u,c,p,d,m=this,h=m.d,f=m.constructor;if(!h)return new f(m);if(u=n=new f(1),r=l=new f(0),s=(i=(t=new f(r)).e=getPrecision(h)-m.e-1)%LOG_BASE,t.d[0]=mathpow(10,s<0?LOG_BASE+s:s),null==e)e=i>0?t:u;else{if(!(o=new f(e)).isInt()||o.lt(u))throw Error(invalidArgument+o);e=o.gt(t)?i>0?t:u:o}for(external=!1,o=new f(digitsToString(h)),c=f.precision,f.precision=i=h.length*LOG_BASE*2;p=divide$2(o,t,0,1,1),1!=(a=n.plus(p.times(r))).cmp(e);)n=r,r=a,a=u,u=l.plus(p.times(a)),l=a,a=t,t=o.minus(p.times(a)),o=a;return a=divide$2(e.minus(n),r,0,1,1),l=l.plus(a.times(u)),n=n.plus(a.times(r)),l.s=u.s=m.s,d=divide$2(u,r,i,1).minus(m).abs().cmp(divide$2(l,n,i,1).minus(m).abs())<1?[u,r]:[l,n],f.precision=c,external=!0,d},P$1.toHexadecimal=P$1.toHex=function(e,t){return toStringBinary(this,16,e,t)},P$1.toNearest=function(e,t){var n=this,r=n.constructor;if(n=new r(n),null==e){if(!n.d)return n;e=new r(1),t=r.rounding}else{if(e=new r(e),void 0===t?t=r.rounding:checkInt32(t,0,8),!n.d)return e.s?n:e;if(!e.d)return e.s&&(e.s=n.s),e}return e.d[0]?(external=!1,n=divide$2(n,e,0,t,1).times(e),external=!0,finalise(n)):(e.s=n.s,n=e),n},P$1.toNumber=function(){return+this},P$1.toOctal=function(e,t){return toStringBinary(this,8,e,t)},P$1.toPower=P$1.pow=function(e){var t,n,r,a,i,s,o=this,l=o.constructor,u=+(e=new l(e));if(!(o.d&&e.d&&o.d[0]&&e.d[0]))return new l(mathpow(+o,u));if((o=new l(o)).eq(1))return o;if(r=l.precision,i=l.rounding,e.eq(1))return finalise(o,r,i);if((t=mathfloor(e.e/LOG_BASE))>=e.d.length-1&&(n=u<0?-u:u)<=MAX_SAFE_INTEGER)return a=intPow(l,o,n,r),e.s<0?new l(1).div(a):finalise(a,r,i);if((s=o.s)<0){if(tl.maxE+1||t0?s/0:0):(external=!1,l.rounding=o.s=1,n=Math.min(12,(t+"").length),(a=naturalExponential(e.times(naturalLogarithm(o,r+n)),r)).d&&checkRoundingDigits((a=finalise(a,r+5,1)).d,r,i)&&(t=r+10,+digitsToString((a=finalise(naturalExponential(e.times(naturalLogarithm(o,t+n)),t),t+5,1)).d).slice(r+1,r+15)+1==1e14&&(a=finalise(a,r+1,0))),a.s=s,external=!0,l.rounding=i,finalise(a,r,i))},P$1.toPrecision=function(e,t){var n,r=this,a=r.constructor;return void 0===e?n=finiteToString(r,r.e<=a.toExpNeg||r.e>=a.toExpPos):(checkInt32(e,1,MAX_DIGITS),void 0===t?t=a.rounding:checkInt32(t,0,8),n=finiteToString(r=finalise(new a(r),e,t),e<=r.e||r.e<=a.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n},P$1.toSignificantDigits=P$1.toSD=function(e,t){var n=this.constructor;return void 0===e?(e=n.precision,t=n.rounding):(checkInt32(e,1,MAX_DIGITS),void 0===t?t=n.rounding:checkInt32(t,0,8)),finalise(new n(this),e,t)},P$1.toString=function(){var e=this,t=e.constructor,n=finiteToString(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+n:n},P$1.truncated=P$1.trunc=function(){return finalise(new this.constructor(this),this.e+1,1)},P$1.valueOf=P$1.toJSON=function(){var e=this,t=e.constructor,n=finiteToString(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+n:n};var divide$2=function(){function e(e,t,n){var r,a=0,i=e.length;for(e=e.slice();i--;)r=e[i]*t+a,e[i]=r%n|0,a=r/n|0;return a&&e.unshift(a),e}function t(e,t,n,r){var a,i;if(n!=r)i=n>r?1:-1;else for(a=i=0;at[a]?1:-1;break}return i}function n(e,t,n,r){for(var a=0;n--;)e[n]-=a,a=e[n]1;)e.shift()}return function(r,a,i,s,o,l){var u,c,p,d,m,h,f,y,g,b,v,N,T,C,A,V,x,S,w,E,D=r.constructor,O=r.s==a.s?1:-1,I=r.d,R=a.d;if(!(I&&I[0]&&R&&R[0]))return new D(r.s&&a.s&&(I?!R||I[0]!=R[0]:R)?I&&0==I[0]||!R?0*O:O/0:NaN);for(l?(m=1,c=r.e-a.e):(l=BASE,m=LOG_BASE,c=mathfloor(r.e/m)-mathfloor(a.e/m)),w=R.length,x=I.length,b=(g=new D(O)).d=[],p=0;R[p]==(I[p]||0);p++);if(R[p]>(I[p]||0)&&c--,null==i?(C=i=D.precision,s=D.rounding):C=o?i+(r.e-a.e)+1:i,C<0)b.push(1),h=!0;else{if(C=C/m+2|0,p=0,1==w){for(d=0,R=R[0],C++;(p1&&(R=e(R,d,l),I=e(I,d,l),w=R.length,x=I.length),V=w,N=(v=I.slice(0,w)).length;N=l/2&&++S;do{d=0,(u=t(R,v,w,N))<0?(T=v[0],w!=N&&(T=T*l+(v[1]||0)),(d=T/S|0)>1?(d>=l&&(d=l-1),1==(u=t(f=e(R,d,l),v,y=f.length,N=v.length))&&(d--,n(f,w=10;d/=10)p++;g.e=p+c*m-1,finalise(g,o?i+g.e+1:i,s,h)}return g}}();function finalise(e,t,n,r){var a,i,s,o,l,u,c,p,d,m=e.constructor;e:if(null!=t){if(!(p=e.d))return e;for(a=1,o=p[0];o>=10;o/=10)a++;if((i=t-a)<0)i+=LOG_BASE,s=t,l=(c=p[d=0])/mathpow(10,a-s-1)%10|0;else if((d=Math.ceil((i+1)/LOG_BASE))>=(o=p.length)){if(!r)break e;for(;o++<=d;)p.push(0);c=l=0,a=1,s=(i%=LOG_BASE)-LOG_BASE+1}else{for(c=o=p[d],a=1;o>=10;o/=10)a++;l=(s=(i%=LOG_BASE)-LOG_BASE+a)<0?0:c/mathpow(10,a-s-1)%10|0}if(r=r||t<0||void 0!==p[d+1]||(s<0?c:c%mathpow(10,a-s-1)),u=n<4?(l||r)&&(0==n||n==(e.s<0?3:2)):l>5||5==l&&(4==n||r||6==n&&(i>0?s>0?c/mathpow(10,a-s):0:p[d-1])%10&1||n==(e.s<0?8:7)),t<1||!p[0])return p.length=0,u?(t-=e.e+1,p[0]=mathpow(10,(LOG_BASE-t%LOG_BASE)%LOG_BASE),e.e=-t||0):p[0]=e.e=0,e;if(0==i?(p.length=d,o=1,d--):(p.length=d+1,o=mathpow(10,LOG_BASE-i),p[d]=s>0?(c/mathpow(10,a-s)%mathpow(10,s)|0)*o:0),u)for(;;){if(0==d){for(i=1,s=p[0];s>=10;s/=10)i++;for(s=p[0]+=o,o=1;s>=10;s/=10)o++;i!=o&&(e.e++,p[0]==BASE&&(p[0]=1));break}if(p[d]+=o,p[d]!=BASE)break;p[d--]=0,o=1}for(i=p.length;0===p[--i];)p.pop()}return external&&(e.e>m.maxE?(e.d=null,e.e=NaN):e.e0?i=i.charAt(0)+"."+i.slice(1)+getZeroString(r):s>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(e.e<0?"e":"e+")+e.e):a<0?(i="0."+getZeroString(-a-1)+i,n&&(r=n-s)>0&&(i+=getZeroString(r))):a>=s?(i+=getZeroString(a+1-s),n&&(r=n-a-1)>0&&(i=i+"."+getZeroString(r))):((r=a+1)0&&(a+1===s&&(i+="."),i+=getZeroString(r))),i}function getBase10Exponent(e,t){var n=e[0];for(t*=LOG_BASE;n>=10;n/=10)t++;return t}function getLn10(e,t,n){if(t>LN10_PRECISION)throw external=!0,n&&(e.precision=n),Error(precisionLimitExceeded);return finalise(new e(LN10$1),t,1,!0)}function getPi(e,t,n){if(t>PI_PRECISION)throw Error(precisionLimitExceeded);return finalise(new e(PI),t,n,!0)}function getPrecision(e){var t=e.length-1,n=t*LOG_BASE+1;if(t=e[t]){for(;t%10==0;t/=10)n--;for(t=e[0];t>=10;t/=10)n++}return n}function getZeroString(e){for(var t="";e--;)t+="0";return t}function intPow(e,t,n,r){var a,i=new e(1),s=Math.ceil(r/LOG_BASE+4);for(external=!1;;){if(n%2&&truncate((i=i.times(t)).d,s)&&(a=!0),0===(n=mathfloor(n/2))){n=i.d.length-1,a&&0===i.d[n]&&++i.d[n];break}truncate((t=t.times(t)).d,s)}return external=!0,i}function isOdd(e){return 1&e.d[e.d.length-1]}function maxOrMin(e,t,n){for(var r,a=new e(t[0]),i=0;++i17)return new d(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:NaN);for(null==t?(external=!1,l=h):l=t,o=new d(.03125);e.e>-2;)e=e.times(o),p+=5;for(l+=r=Math.log(mathpow(2,p))/Math.LN10*2+5|0,n=i=s=new d(1),d.precision=l;;){if(i=finalise(i.times(e),l,1),n=n.times(++c),digitsToString((o=s.plus(divide$2(i,n,l,1))).d).slice(0,l)===digitsToString(s.d).slice(0,l)){for(a=p;a--;)s=finalise(s.times(s),l,1);if(null!=t)return d.precision=h,s;if(!(u<3&&checkRoundingDigits(s.d,l-r,m,u)))return finalise(s,d.precision=h,m,external=!0);d.precision=l+=10,n=i=o=new d(1),c=0,u++}s=o}}function naturalLogarithm(e,t){var n,r,a,i,s,o,l,u,c,p,d,m=1,h=e,f=h.d,y=h.constructor,g=y.rounding,b=y.precision;if(h.s<0||!f||!f[0]||!h.e&&1==f[0]&&1==f.length)return new y(f&&!f[0]?-1/0:1!=h.s?NaN:f?0:h);if(null==t?(external=!1,c=b):c=t,y.precision=c+=10,r=(n=digitsToString(f)).charAt(0),!(Math.abs(i=h.e)<15e14))return u=getLn10(y,c+2,b).times(i+""),h=naturalLogarithm(new y(r+"."+n.slice(1)),c-10).plus(u),y.precision=b,null==t?finalise(h,b,g,external=!0):h;for(;r<7&&1!=r||1==r&&n.charAt(1)>3;)r=(n=digitsToString((h=h.times(e)).d)).charAt(0),m++;for(i=h.e,r>1?(h=new y("0."+n),i++):h=new y(r+"."+n.slice(1)),p=h,l=s=h=divide$2(h.minus(1),h.plus(1),c,1),d=finalise(h.times(h),c,1),a=3;;){if(s=finalise(s.times(d),c,1),digitsToString((u=l.plus(divide$2(s,new y(a),c,1))).d).slice(0,c)===digitsToString(l.d).slice(0,c)){if(l=l.times(2),0!==i&&(l=l.plus(getLn10(y,c+2,b).times(i+""))),l=divide$2(l,new y(m),c,1),null!=t)return y.precision=b,l;if(!checkRoundingDigits(l.d,c-10,g,o))return finalise(l,y.precision=b,g,external=!0);y.precision=c+=10,u=s=h=divide$2(p.minus(1),p.plus(1),c,1),d=finalise(h.times(h),c,1),a=o=1}l=u,a+=2}}function nonFiniteToString(e){return String(e.s*e.s/0)}function parseDecimal(e,t){var n,r,a;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;48===t.charCodeAt(r);r++);for(a=t.length;48===t.charCodeAt(a-1);--a);if(t=t.slice(r,a)){if(a-=r,e.e=n=n-r-1,e.d=[],r=(n+1)%LOG_BASE,n<0&&(r+=LOG_BASE),re.constructor.maxE?(e.d=null,e.e=NaN):e.e-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),isDecimal.test(t))return parseDecimal(e,t)}else if("Infinity"===t||"NaN"===t)return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(isHex.test(t))n=16,t=t.toLowerCase();else if(isBinary.test(t))n=2;else{if(!isOctal.test(t))throw Error(invalidArgument+t);n=8}for((i=t.search(/p/i))>0?(l=+t.slice(i+1),t=t.substring(2,i)):t=t.slice(2),s=(i=t.indexOf("."))>=0,r=e.constructor,s&&(i=(o=(t=t.replace(".","")).length)-i,a=intPow(r,new r(n),i,2*i)),i=c=(u=convertBase(t,n,BASE)).length-1;0===u[i];--i)u.pop();return i<0?new r(0*e.s):(e.e=getBase10Exponent(u,c),e.d=u,external=!1,s&&(e=divide$2(e,a,4*o)),l&&(e=e.times(Math.abs(l)<54?mathpow(2,l):Decimal.pow(2,l))),external=!0,e)}function sine(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:taylorSeries(e,2,t,t);n=(n=1.4*Math.sqrt(r))>16?16:0|n,t=taylorSeries(e,2,t=t.times(1/tinyPow(5,n)),t);for(var a,i=new e(5),s=new e(16),o=new e(20);n--;)a=t.times(t),t=t.times(i.plus(a.times(s.times(a).minus(o))));return t}function taylorSeries(e,t,n,r,a){var i,s,o,l,u=e.precision,c=Math.ceil(u/LOG_BASE);for(external=!1,l=n.times(n),o=new e(r);;){if(s=divide$2(o.times(l),new e(t++*t++),u,1),o=a?r.plus(s):r.minus(s),r=divide$2(s.times(l),new e(t++*t++),u,1),void 0!==(s=o.plus(r)).d[c]){for(i=c;s.d[i]===o.d[i]&&i--;);if(-1==i)break}i=o,o=r,r=s,s=i}return external=!0,s.d.length=c+1,s}function tinyPow(e,t){for(var n=e;--t;)n*=e;return n}function toLessThanHalfPi(e,t){var n,r=t.s<0,a=getPi(e,e.precision,1),i=a.times(.5);if((t=t.abs()).lte(i))return quadrant=r?4:1,t;if((n=t.divToInt(a)).isZero())quadrant=r?3:2;else{if((t=t.minus(n.times(a))).lte(i))return quadrant=isOdd(n)?r?2:3:r?4:1,t;quadrant=isOdd(n)?r?1:4:r?3:2}return t.minus(a).abs()}function toStringBinary(e,t,n,r){var a,i,s,o,l,u,c,p,d,m=e.constructor,h=void 0!==n;if(h?(checkInt32(n,1,MAX_DIGITS),void 0===r?r=m.rounding:checkInt32(r,0,8)):(n=m.precision,r=m.rounding),e.isFinite()){for(h?(a=2,16==t?n=4*n-3:8==t&&(n=3*n-2)):a=t,(s=(c=finiteToString(e)).indexOf("."))>=0&&(c=c.replace(".",""),(d=new m(1)).e=c.length-s,d.d=convertBase(finiteToString(d),10,a),d.e=d.d.length),i=l=(p=convertBase(c,10,a)).length;0==p[--l];)p.pop();if(p[0]){if(s<0?i--:((e=new m(e)).d=p,e.e=i,p=(e=divide$2(e,d,n,r,0,a)).d,i=e.e,u=inexact),s=p[n],o=a/2,u=u||void 0!==p[n+1],u=r<4?(void 0!==s||u)&&(0===r||r===(e.s<0?3:2)):s>o||s===o&&(4===r||u||6===r&&1&p[n-1]||r===(e.s<0?8:7)),p.length=n,u)for(;++p[--n]>a-1;)p[n]=0,n||(++i,p.unshift(1));for(l=p.length;!p[l-1];--l);for(s=0,c="";s1)if(16==t||8==t){for(s=16==t?4:3,--l;l%s;l++)c+="0";for(l=(p=convertBase(c,a,t)).length;!p[l-1];--l);for(s=1,c="1.";sl)for(i-=l;i--;)c+="0";else it)return e.length=t,!0}function abs$2(e){return new this(e).abs()}function acos$2(e){return new this(e).acos()}function acosh$2(e){return new this(e).acosh()}function add$2(e,t){return new this(e).plus(t)}function asin$2(e){return new this(e).asin()}function asinh$2(e){return new this(e).asinh()}function atan$2(e){return new this(e).atan()}function atanh$2(e){return new this(e).atanh()}function atan2$2(e,t){e=new this(e),t=new this(t);var n,r=this.precision,a=this.rounding,i=r+4;return e.s&&t.s?e.d||t.d?!t.d||e.isZero()?(n=t.s<0?getPi(this,r,a):new this(0)).s=e.s:!e.d||t.isZero()?(n=getPi(this,i,1).times(.5)).s=e.s:t.s<0?(this.precision=i,this.rounding=1,n=this.atan(divide$2(e,t,i,1)),t=getPi(this,i,1),this.precision=r,this.rounding=a,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(divide$2(e,t,i,1)):(n=getPi(this,i,1).times(t.s>0?.25:.75)).s=e.s:n=new this(NaN),n}function cbrt$1(e){return new this(e).cbrt()}function ceil$1(e){return finalise(e=new this(e),e.e+1,2)}function clamp(e,t,n){return new this(e).clamp(t,n)}function config$1(e){if(!e||"object"!=typeof e)throw Error(decimalError+"Object expected");var t,n,r,a=!0===e.defaults,i=["precision",1,MAX_DIGITS,"rounding",0,8,"toExpNeg",-EXP_LIMIT,0,"toExpPos",0,EXP_LIMIT,"maxE",0,EXP_LIMIT,"minE",-EXP_LIMIT,0,"modulo",0,9];for(t=0;t=i[t+1]&&r<=i[t+2]))throw Error(invalidArgument+n+": "+r);this[n]=r}if(n="crypto",a&&(this[n]=DEFAULTS[n]),void 0!==(r=e[n])){if(!0!==r&&!1!==r&&0!==r&&1!==r)throw Error(invalidArgument+n+": "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw Error(cryptoUnavailable);this[n]=!0}else this[n]=!1}return this}function cos$2(e){return new this(e).cos()}function cosh$2(e){return new this(e).cosh()}function clone$2(e){var t,n,r;function a(e){var t,n,r,i=this;if(!(i instanceof a))return new a(e);if(i.constructor=a,isDecimalInstance(e))return i.s=e.s,void(external?!e.d||e.e>a.maxE?(i.e=NaN,i.d=null):e.e=10;n/=10)t++;return void(external?t>a.maxE?(i.e=NaN,i.d=null):t=429e7?t[i]=crypto.getRandomValues(new Uint32Array(1))[0]:o[i++]=a%1e7;else{if(!crypto.randomBytes)throw Error(cryptoUnavailable);for(t=crypto.randomBytes(r*=4);i=214e7?crypto.randomBytes(4).copy(t,i):(o.push(a%1e7),i+=4);i=r/4}else for(;i=10;a/=10)r++;r{var{on:t,config:n}=e,r=Decimal.clone({precision:n.precision,modulo:Decimal.EUCLID});return r.prototype=Object.create(r.prototype),r.prototype.type="BigNumber",r.prototype.isBigNumber=!0,r.prototype.toJSON=function(){return{mathjs:"BigNumber",value:this.toString()}},r.fromJSON=function(e){return new r(e.value)},t&&t("config",(function(e,t){e.precision!==t.precision&&r.config({precision:e.precision})})),r}),{isClass:!0}),complex$1={exports:{}}; /** * @license Complex.js v2.1.1 12/05/2020 * * Copyright (c) 2020, Robert Eisele (robert@xarg.org) * Dual licensed under the MIT or GPL Version 2 licenses. - **/!function(e,t){!function(t){var n=Math.cosh||function(e){return Math.abs(e)<1e-9?1-e:.5*(Math.exp(e)+Math.exp(-e))},r=Math.sinh||function(e){return Math.abs(e)<1e-9?e:.5*(Math.exp(e)-Math.exp(-e))},a=function(){throw SyntaxError("Invalid Param")};function i(e,t){var n=Math.abs(e),r=Math.abs(t);return 0===e?Math.log(r):0===t?Math.log(n):n<3e3&&r<3e3?.5*Math.log(e*e+t*t):(e/=2,t/=2,.5*Math.log(e*e+t*t)+Math.LN2)}function o(e,t){if(!(this instanceof o))return new o(e,t);var n=function(e,t){var n={re:0,im:0};if(null==e)n.re=n.im=0;else if(void 0!==t)n.re=e,n.im=t;else switch(typeof e){case"object":if("im"in e&&"re"in e)n.re=e.re,n.im=e.im;else if("abs"in e&&"arg"in e){if(!Number.isFinite(e.abs)&&Number.isFinite(e.arg))return o.INFINITY;n.re=e.abs*Math.cos(e.arg),n.im=e.abs*Math.sin(e.arg)}else if("r"in e&&"phi"in e){if(!Number.isFinite(e.r)&&Number.isFinite(e.phi))return o.INFINITY;n.re=e.r*Math.cos(e.phi),n.im=e.r*Math.sin(e.phi)}else 2===e.length?(n.re=e[0],n.im=e[1]):a();break;case"string":n.im=n.re=0;var r=e.match(/\d+\.?\d*e[+-]?\d+|\d+\.?\d*|\.\d+|./g),i=1,s=0;null===r&&a();for(var l=0;l0&&a();break;case"number":n.im=0,n.re=e;break;default:a()}return isNaN(n.re)||isNaN(n.im),n}(e,t);this.re=n.re,this.im=n.im}o.prototype={re:0,im:0,sign:function(){var e=this.abs();return new o(this.re/e,this.im/e)},add:function(e,t){var n=new o(e,t);return this.isInfinite()&&n.isInfinite()?o.NAN:this.isInfinite()||n.isInfinite()?o.INFINITY:new o(this.re+n.re,this.im+n.im)},sub:function(e,t){var n=new o(e,t);return this.isInfinite()&&n.isInfinite()?o.NAN:this.isInfinite()||n.isInfinite()?o.INFINITY:new o(this.re-n.re,this.im-n.im)},mul:function(e,t){var n=new o(e,t);return this.isInfinite()&&n.isZero()||this.isZero()&&n.isInfinite()?o.NAN:this.isInfinite()||n.isInfinite()?o.INFINITY:0===n.im&&0===this.im?new o(this.re*n.re,0):new o(this.re*n.re-this.im*n.im,this.re*n.im+this.im*n.re)},div:function(e,t){var n=new o(e,t);if(this.isZero()&&n.isZero()||this.isInfinite()&&n.isInfinite())return o.NAN;if(this.isInfinite()||n.isZero())return o.INFINITY;if(this.isZero()||n.isInfinite())return o.ZERO;e=this.re,t=this.im;var r,a,i=n.re,s=n.im;return 0===s?new o(e/i,t/i):Math.abs(i)0)return new o(Math.pow(e,n.re),0);if(0===e)switch((n.re%4+4)%4){case 0:return new o(Math.pow(t,n.re),0);case 1:return new o(0,Math.pow(t,n.re));case 2:return new o(-Math.pow(t,n.re),0);case 3:return new o(0,-Math.pow(t,n.re))}}if(0===e&&0===t&&n.re>0&&n.im>=0)return o.ZERO;var r=Math.atan2(t,e),a=i(e,t);return e=Math.exp(n.re*a-n.im*r),t=n.im*a+n.re*r,new o(e*Math.cos(t),e*Math.sin(t))},sqrt:function(){var e,t,n=this.re,r=this.im,a=this.abs();if(n>=0){if(0===r)return new o(Math.sqrt(n),0);e=.5*Math.sqrt(2*(a+n))}else e=Math.abs(r)/Math.sqrt(2*(a-n));return t=n<=0?.5*Math.sqrt(2*(a-n)):Math.abs(r)/Math.sqrt(2*(a+n)),new o(e,r<0?-t:t)},exp:function(){var e=Math.exp(this.re);return this.im,new o(e*Math.cos(this.im),e*Math.sin(this.im))},expm1:function(){var e=this.re,t=this.im;return new o(Math.expm1(e)*Math.cos(t)+function(e){var t=Math.PI/4;if(-t>e||e>t)return Math.cos(e)-1;var n=e*e;return n*(n*(n*(n*(n*(n*(n*(n/20922789888e3-1/87178291200)+1/479001600)-1/3628800)+1/40320)-1/720)+1/24)-.5)}(t),Math.exp(e)*Math.sin(t))},log:function(){var e=this.re,t=this.im;return new o(i(e,t),Math.atan2(t,e))},abs:function(){return function(e,t){var n=Math.abs(e),r=Math.abs(t);return n<3e3&&r<3e3?Math.sqrt(n*n+r*r):(n1&&0===t,r=1-e,a=1+e,s=r*r+t*t,l=0!==s?new o((a*r-t*t)/s,(t*r+a*t)/s):new o(-1!==e?e/0:0,0!==t?t/0:0),u=l.re;return l.re=i(l.re,l.im)/2,l.im=Math.atan2(l.im,u)/2,n&&(l.im=-l.im),l},acoth:function(){var e=this.re,t=this.im;if(0===e&&0===t)return new o(0,Math.PI/2);var n=e*e+t*t;return 0!==n?new o(e/n,-t/n).atanh():new o(0!==e?e/0:0,0!==t?-t/0:0).atanh()},acsch:function(){var e=this.re,t=this.im;if(0===t)return new o(0!==e?Math.log(e+Math.sqrt(e*e+1)):1/0,0);var n=e*e+t*t;return 0!==n?new o(e/n,-t/n).asinh():new o(0!==e?e/0:0,0!==t?-t/0:0).asinh()},asech:function(){var e=this.re,t=this.im;if(this.isZero())return o.INFINITY;var n=e*e+t*t;return 0!==n?new o(e/n,-t/n).acosh():new o(0!==e?e/0:0,0!==t?-t/0:0).acosh()},inverse:function(){if(this.isZero())return o.INFINITY;if(this.isInfinite())return o.ZERO;var e=this.re,t=this.im,n=e*e+t*t;return new o(e/n,-t/n)},conjugate:function(){return new o(this.re,-this.im)},neg:function(){return new o(-this.re,-this.im)},ceil:function(e){return e=Math.pow(10,e||0),new o(Math.ceil(this.re*e)/e,Math.ceil(this.im*e)/e)},floor:function(e){return e=Math.pow(10,e||0),new o(Math.floor(this.re*e)/e,Math.floor(this.im*e)/e)},round:function(e){return e=Math.pow(10,e||0),new o(Math.round(this.re*e)/e,Math.round(this.im*e)/e)},equals:function(e,t){var n=new o(e,t);return Math.abs(n.re-this.re)<=o.EPSILON&&Math.abs(n.im-this.im)<=o.EPSILON},clone:function(){return new o(this.re,this.im)},toString:function(){var e=this.re,t=this.im,n="";return this.isNaN()?"NaN":this.isInfinite()?"Infinity":(Math.abs(e)(Complex$1.prototype.type="Complex",Complex$1.prototype.isComplex=!0,Complex$1.prototype.toJSON=function(){return{mathjs:"Complex",re:this.re,im:this.im}},Complex$1.prototype.toPolar=function(){return{r:this.abs(),phi:this.arg()}},Complex$1.prototype.format=function(e){var t=this.im,n=this.re,r=format$3(this.re,e),a=format$3(this.im,e),i=isNumber$1(e)?e:e?e.precision:null;if(null!==i){var o=Math.pow(10,-i);Math.abs(n/t)t.re?1:e.ret.im?1:e.im0&&a();break;case"number":n.im=0,n.re=e;break;default:a()}return isNaN(n.re)||isNaN(n.im),n}(e,t);this.re=n.re,this.im=n.im}s.prototype={re:0,im:0,sign:function(){var e=this.abs();return new s(this.re/e,this.im/e)},add:function(e,t){var n=new s(e,t);return this.isInfinite()&&n.isInfinite()?s.NAN:this.isInfinite()||n.isInfinite()?s.INFINITY:new s(this.re+n.re,this.im+n.im)},sub:function(e,t){var n=new s(e,t);return this.isInfinite()&&n.isInfinite()?s.NAN:this.isInfinite()||n.isInfinite()?s.INFINITY:new s(this.re-n.re,this.im-n.im)},mul:function(e,t){var n=new s(e,t);return this.isInfinite()&&n.isZero()||this.isZero()&&n.isInfinite()?s.NAN:this.isInfinite()||n.isInfinite()?s.INFINITY:0===n.im&&0===this.im?new s(this.re*n.re,0):new s(this.re*n.re-this.im*n.im,this.re*n.im+this.im*n.re)},div:function(e,t){var n=new s(e,t);if(this.isZero()&&n.isZero()||this.isInfinite()&&n.isInfinite())return s.NAN;if(this.isInfinite()||n.isZero())return s.INFINITY;if(this.isZero()||n.isInfinite())return s.ZERO;e=this.re,t=this.im;var r,a,i=n.re,o=n.im;return 0===o?new s(e/i,t/i):Math.abs(i)0)return new s(Math.pow(e,n.re),0);if(0===e)switch((n.re%4+4)%4){case 0:return new s(Math.pow(t,n.re),0);case 1:return new s(0,Math.pow(t,n.re));case 2:return new s(-Math.pow(t,n.re),0);case 3:return new s(0,-Math.pow(t,n.re))}}if(0===e&&0===t&&n.re>0&&n.im>=0)return s.ZERO;var r=Math.atan2(t,e),a=i(e,t);return e=Math.exp(n.re*a-n.im*r),t=n.im*a+n.re*r,new s(e*Math.cos(t),e*Math.sin(t))},sqrt:function(){var e,t,n=this.re,r=this.im,a=this.abs();if(n>=0){if(0===r)return new s(Math.sqrt(n),0);e=.5*Math.sqrt(2*(a+n))}else e=Math.abs(r)/Math.sqrt(2*(a-n));return t=n<=0?.5*Math.sqrt(2*(a-n)):Math.abs(r)/Math.sqrt(2*(a+n)),new s(e,r<0?-t:t)},exp:function(){var e=Math.exp(this.re);return this.im,new s(e*Math.cos(this.im),e*Math.sin(this.im))},expm1:function(){var e=this.re,t=this.im;return new s(Math.expm1(e)*Math.cos(t)+function(e){var t=Math.PI/4;if(-t>e||e>t)return Math.cos(e)-1;var n=e*e;return n*(n*(n*(n*(n*(n*(n*(n/20922789888e3-1/87178291200)+1/479001600)-1/3628800)+1/40320)-1/720)+1/24)-.5)}(t),Math.exp(e)*Math.sin(t))},log:function(){var e=this.re,t=this.im;return new s(i(e,t),Math.atan2(t,e))},abs:function(){return function(e,t){var n=Math.abs(e),r=Math.abs(t);return n<3e3&&r<3e3?Math.sqrt(n*n+r*r):(n1&&0===t,r=1-e,a=1+e,o=r*r+t*t,l=0!==o?new s((a*r-t*t)/o,(t*r+a*t)/o):new s(-1!==e?e/0:0,0!==t?t/0:0),u=l.re;return l.re=i(l.re,l.im)/2,l.im=Math.atan2(l.im,u)/2,n&&(l.im=-l.im),l},acoth:function(){var e=this.re,t=this.im;if(0===e&&0===t)return new s(0,Math.PI/2);var n=e*e+t*t;return 0!==n?new s(e/n,-t/n).atanh():new s(0!==e?e/0:0,0!==t?-t/0:0).atanh()},acsch:function(){var e=this.re,t=this.im;if(0===t)return new s(0!==e?Math.log(e+Math.sqrt(e*e+1)):1/0,0);var n=e*e+t*t;return 0!==n?new s(e/n,-t/n).asinh():new s(0!==e?e/0:0,0!==t?-t/0:0).asinh()},asech:function(){var e=this.re,t=this.im;if(this.isZero())return s.INFINITY;var n=e*e+t*t;return 0!==n?new s(e/n,-t/n).acosh():new s(0!==e?e/0:0,0!==t?-t/0:0).acosh()},inverse:function(){if(this.isZero())return s.INFINITY;if(this.isInfinite())return s.ZERO;var e=this.re,t=this.im,n=e*e+t*t;return new s(e/n,-t/n)},conjugate:function(){return new s(this.re,-this.im)},neg:function(){return new s(-this.re,-this.im)},ceil:function(e){return e=Math.pow(10,e||0),new s(Math.ceil(this.re*e)/e,Math.ceil(this.im*e)/e)},floor:function(e){return e=Math.pow(10,e||0),new s(Math.floor(this.re*e)/e,Math.floor(this.im*e)/e)},round:function(e){return e=Math.pow(10,e||0),new s(Math.round(this.re*e)/e,Math.round(this.im*e)/e)},equals:function(e,t){var n=new s(e,t);return Math.abs(n.re-this.re)<=s.EPSILON&&Math.abs(n.im-this.im)<=s.EPSILON},clone:function(){return new s(this.re,this.im)},toString:function(){var e=this.re,t=this.im,n="";return this.isNaN()?"NaN":this.isInfinite()?"Infinity":(Math.abs(e)(Complex$1.prototype.type="Complex",Complex$1.prototype.isComplex=!0,Complex$1.prototype.toJSON=function(){return{mathjs:"Complex",re:this.re,im:this.im}},Complex$1.prototype.toPolar=function(){return{r:this.abs(),phi:this.arg()}},Complex$1.prototype.format=function(e){var t=this.im,n=this.re,r=format$3(this.re,e),a=format$3(this.im,e),i=isNumber$1(e)?e:e?e.precision:null;if(null!==i){var s=Math.pow(10,-i);Math.abs(n/t)t.re?1:e.ret.im?1:e.im1&&(t[n]=(t[n]||0)+1):t[e]=(t[e]||0)+1,t}var o=function(e,t){var a,i=0,o=1,s=1,u=0,c=0,p=0,d=1,m=1,f=0,h=1,y=1,b=1,g=1e7;if(null==e);else if(void 0!==t){if(s=(i=e)*(o=t),i%1!=0||o%1!=0)throw l.NonIntegerParameter}else switch(typeof e){case"object":if("d"in e&&"n"in e)i=e.n,o=e.d,"s"in e&&(i*=e.s);else{if(!(0 in e))throw l.InvalidParameter;i=e[0],1 in e&&(o=e[1])}s=i*o;break;case"number":if(e<0&&(s=e,e=-e),e%1==0)i=e;else if(e>0){for(e>=1&&(e/=m=Math.pow(10,Math.floor(1+Math.log(e)/Math.LN10)));h<=g&&b<=g;){if(e===(a=(f+y)/(h+b))){h+b<=g?(i=f+y,o=h+b):b>h?(i=y,o=b):(i=f,o=h);break}e>a?(f+=y,h+=b):(y+=f,b+=h),h>g?(i=y,o=b):(i=f,o=h)}i*=m}else(isNaN(e)||isNaN(t))&&(o=i=NaN);break;case"string":if(null===(h=e.match(/\d+|./g)))throw l.InvalidParameter;if("-"===h[f]?(s=-1,f++):"+"===h[f]&&f++,h.length===f+1?c=r(h[f++],s):"."===h[f+1]||"."===h[f]?("."!==h[f]&&(u=r(h[f++],s)),(1+ ++f===h.length||"("===h[f+1]&&")"===h[f+3]||"'"===h[f+1]&&"'"===h[f+3])&&(c=r(h[f],s),d=Math.pow(10,h[f].length),f++),("("===h[f]&&")"===h[f+2]||"'"===h[f]&&"'"===h[f+2])&&(p=r(h[f+1],s),m=Math.pow(10,h[f+1].length)-1,f+=3)):"/"===h[f+1]||":"===h[f+1]?(c=r(h[f],s),d=r(h[f+2],1),f+=3):"/"===h[f+3]&&" "===h[f+1]&&(u=r(h[f],s),c=r(h[f+2],s),d=r(h[f+4],1),f+=5),h.length<=f){s=i=p+(o=d*m)*u+m*c;break}default:throw l.InvalidParameter}if(0===o)throw l.DivisionByZero;n.s=s<0?-1:1,n.n=Math.abs(i),n.d=Math.abs(o)};function s(e,t){if(!e)return t;if(!t)return e;for(;;){if(!(e%=t))return t;if(!(t%=e))return e}}function l(e,t){if(o(e,t),!(this instanceof l))return a(n.s*n.n,n.d);e=s(n.d,n.n),this.s=n.s,this.n=n.n/e,this.d=n.d/e}l.DivisionByZero=new Error("Division by Zero"),l.InvalidParameter=new Error("Invalid argument"),l.NonIntegerParameter=new Error("Parameters must be integer"),l.prototype={s:1,n:0,d:1,abs:function(){return a(this.n,this.d)},neg:function(){return a(-this.s*this.n,this.d)},add:function(e,t){return o(e,t),a(this.s*this.n*n.d+n.s*this.d*n.n,this.d*n.d)},sub:function(e,t){return o(e,t),a(this.s*this.n*n.d-n.s*this.d*n.n,this.d*n.d)},mul:function(e,t){return o(e,t),a(this.s*n.s*this.n*n.n,this.d*n.d)},div:function(e,t){return o(e,t),a(this.s*n.s*this.n*n.d,this.d*n.n)},clone:function(){return a(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new l(NaN);if(void 0===e)return a(this.s*this.n%this.d,1);if(o(e,t),0===n.n&&0===this.d)throw l.DivisionByZero;return a(this.s*(n.d*this.n)%(n.n*this.d),n.d*this.d)},gcd:function(e,t){return o(e,t),a(s(n.n,this.n)*s(n.d,this.d),n.d*this.d)},lcm:function(e,t){return o(e,t),0===n.n&&0===this.n?a(0,1):a(n.n*this.n,s(n.n,this.n)*s(n.d,this.d))},ceil:function(e){return e=Math.pow(10,e||0),isNaN(this.n)||isNaN(this.d)?new l(NaN):a(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=Math.pow(10,e||0),isNaN(this.n)||isNaN(this.d)?new l(NaN):a(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=Math.pow(10,e||0),isNaN(this.n)||isNaN(this.d)?new l(NaN):a(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return a(this.s*this.d,this.n)},pow:function(e,t){if(o(e,t),1===n.d)return n.s<0?a(Math.pow(this.s*this.d,n.n),Math.pow(this.n,n.n)):a(Math.pow(this.s*this.n,n.n),Math.pow(this.d,n.n));if(this.s<0)return null;var r=i(this.n),s=i(this.d),l=1,u=1;for(var c in r)if("1"!==c){if("0"===c){l=0;break}if(r[c]*=n.n,r[c]%n.d!=0)return null;r[c]/=n.d,l*=Math.pow(c,r[c])}for(var c in s)if("1"!==c){if(s[c]*=n.n,s[c]%n.d!=0)return null;s[c]/=n.d,u*=Math.pow(c,s[c])}return n.s<0?a(u,l):a(l,u)},equals:function(e,t){return o(e,t),this.s*this.n*n.d==n.s*n.n*this.d},compare:function(e,t){o(e,t);var r=this.s*this.n*n.d-n.s*n.n*this.d;return(0=0;o--)i=i.inverse().add(n[o]);if(i.sub(t).abs().valueOf()0&&(n+=t,n+=" ",r%=a),n+=r,n+="/",n+=a),n},toLatex:function(e){var t,n="",r=this.n,a=this.d;return this.s<0&&(n+="-"),1===a?n+=r:(e&&(t=Math.floor(r/a))>0&&(n+=t,r%=a),n+="\\frac{",n+=r,n+="}{",n+=a,n+="}"),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do{r.push(Math.floor(t/n)),e=t%n,t=n,n=e}while(1!==t);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return"NaN";e=e||15;var r=function(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(1===t)return 0;for(var n=10%t,r=1;1!==n;r++)if(n=10*n%t,r>2e3)return 0;return r}(0,n),a=function(e,t,n){for(var r=1,a=function(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)1&t&&(r=r*e%n);return r}(10,n,t),i=0;i<300;i++){if(r===a)return i;r=10*r%t,a=10*a%t}return 0}(0,n,r),i=this.s<0?"-":"";if(i+=t/n|0,t%=n,(t*=10)&&(i+="."),r){for(var o=a;o--;)i+=t/n|0,t%=n,t*=10;for(i+="(",o=r;o--;)i+=t/n|0,t%=n,t*=10;i+=")"}else for(o=e;t&&o--;)i+=t/n|0,t%=n,t*=10;return i}},Object.defineProperty(l,"__esModule",{value:!0}),l.default=l,l.Fraction=l,e.exports=l}()}(fraction$1);var Fraction$1=getDefaultExportFromCjs(fraction$1.exports),name$4z="Fraction",dependencies$4z=[],createFractionClass=factory(name$4z,dependencies$4z,(()=>(Fraction$1.prototype.type="Fraction",Fraction$1.prototype.isFraction=!0,Fraction$1.prototype.toJSON=function(){return{mathjs:"Fraction",n:this.s*this.n,d:this.d}},Fraction$1.fromJSON=function(e){return new Fraction$1(e)},Fraction$1)),{isClass:!0}),name$4y="Range",dependencies$4y=[],createRangeClass=factory(name$4y,dependencies$4y,(()=>{function e(t,n,r){if(!(this instanceof e))throw new SyntaxError("Constructor must be called with the new operator");var a=null!=t,i=null!=n,o=null!=r;if(a)if(isBigNumber(t))t=t.toNumber();else if("number"!=typeof t)throw new TypeError("Parameter start must be a number");if(i)if(isBigNumber(n))n=n.toNumber();else if("number"!=typeof n)throw new TypeError("Parameter end must be a number");if(o)if(isBigNumber(r))r=r.toNumber();else if("number"!=typeof r)throw new TypeError("Parameter step must be a number");this.start=a?parseFloat(t):0,this.end=i?parseFloat(n):0,this.step=o?parseFloat(r):1}return e.prototype.type="Range",e.prototype.isRange=!0,e.parse=function(t){if("string"!=typeof t)return null;var n=t.split(":").map((function(e){return parseFloat(e)}));if(n.some((function(e){return isNaN(e)})))return null;switch(n.length){case 2:return new e(n[0],n[1]);case 3:return new e(n[0],n[2],n[1]);default:return null}},e.prototype.clone=function(){return new e(this.start,this.end,this.step)},e.prototype.size=function(){var e=0,t=this.start,n=this.step,r=this.end-t;return sign$2(n)===sign$2(r)?e=Math.ceil(r/n):0===r&&(e=0),isNaN(e)&&(e=0),[e]},e.prototype.min=function(){var e=this.size()[0];return e>0?this.step>0?this.start:this.start+(e-1)*this.step:void 0},e.prototype.max=function(){var e=this.size()[0];return e>0?this.step>0?this.start+(e-1)*this.step:this.start:void 0},e.prototype.forEach=function(e){var t=this.start,n=this.step,r=this.end,a=0;if(n>0)for(;tr;)e(t,[a],this),t+=n,a++},e.prototype.map=function(e){var t=[];return this.forEach((function(n,r,a){t[r[0]]=e(n,r,a)})),t},e.prototype.toArray=function(){var e=[];return this.forEach((function(t,n){e[n[0]]=t})),e},e.prototype.valueOf=function(){return this.toArray()},e.prototype.format=function(e){var t=format$3(this.start,e);return 1!==this.step&&(t+=":"+format$3(this.step,e)),t+":"+format$3(this.end,e)},e.prototype.toString=function(){return this.format()},e.prototype.toJSON=function(){return{mathjs:"Range",start:this.start,end:this.end,step:this.step}},e.fromJSON=function(t){return new e(t.start,t.end,t.step)},e}),{isClass:!0}),name$4x="Matrix",dependencies$4x=[],createMatrixClass=factory(name$4x,dependencies$4x,(()=>{function e(){if(!(this instanceof e))throw new SyntaxError("Constructor must be called with the new operator")}return e.prototype.type="Matrix",e.prototype.isMatrix=!0,e.prototype.storage=function(){throw new Error("Cannot invoke storage on a Matrix interface")},e.prototype.datatype=function(){throw new Error("Cannot invoke datatype on a Matrix interface")},e.prototype.create=function(e,t){throw new Error("Cannot invoke create on a Matrix interface")},e.prototype.subset=function(e,t,n){throw new Error("Cannot invoke subset on a Matrix interface")},e.prototype.get=function(e){throw new Error("Cannot invoke get on a Matrix interface")},e.prototype.set=function(e,t,n){throw new Error("Cannot invoke set on a Matrix interface")},e.prototype.resize=function(e,t){throw new Error("Cannot invoke resize on a Matrix interface")},e.prototype.reshape=function(e,t){throw new Error("Cannot invoke reshape on a Matrix interface")},e.prototype.clone=function(){throw new Error("Cannot invoke clone on a Matrix interface")},e.prototype.size=function(){throw new Error("Cannot invoke size on a Matrix interface")},e.prototype.map=function(e,t){throw new Error("Cannot invoke map on a Matrix interface")},e.prototype.forEach=function(e){throw new Error("Cannot invoke forEach on a Matrix interface")},e.prototype[Symbol.iterator]=function(){throw new Error("Cannot iterate a Matrix interface")},e.prototype.toArray=function(){throw new Error("Cannot invoke toArray on a Matrix interface")},e.prototype.valueOf=function(){throw new Error("Cannot invoke valueOf on a Matrix interface")},e.prototype.format=function(e){throw new Error("Cannot invoke format on a Matrix interface")},e.prototype.toString=function(){throw new Error("Cannot invoke toString on a Matrix interface")},e}),{isClass:!0}),name$4w="DenseMatrix",dependencies$4w=["Matrix"],createDenseMatrixClass=factory(name$4w,dependencies$4w,(e=>{var{Matrix:t}=e;function n(e,t){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(t&&!isString$1(t))throw new Error("Invalid datatype: "+t);if(isMatrix(e))"DenseMatrix"===e.type?(this._data=clone$2(e._data),this._size=clone$2(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&isArray$1(e.data)&&isArray$1(e.size))this._data=e.data,this._size=e.size,validate(this._data,this._size),this._datatype=t||e.datatype;else if(isArray$1(e))this._data=u(e),this._size=arraySize(this._data),validate(this._data,this._size),this._datatype=t;else{if(e)throw new TypeError("Unsupported type of data ("+typeOf$1(e)+")");this._data=[],this._size=[0],this._datatype=t}}function r(e,t){if(!isIndex(t))throw new TypeError("Invalid index");if(t.isScalar())return e.get(t.min());var r=t.size();if(r.length!==e._size.length)throw new DimensionError(r.length,e._size.length);for(var i=t.min(),o=t.max(),s=0,l=e._size.length;s");var p=t.max().map((function(e){return e+1}));l(e,p,r);var d=i.length;o(e._data,t,n,d,0)}return e}function o(e,t,n,r,a){var i=a===r-1,s=t.dimension(a);i?s.forEach((function(t,r){validateIndex(t),e[t]=n[r[0]]})):s.forEach((function(i,s){validateIndex(i),o(e[i],t,n[s[0]],r,a+1)}))}function s(e,t,n){if(0===t.length){for(var r=e._data;isArray$1(r);)r=r[0];return r}return e._size=t.slice(0),e._data=resize$1(e._data,e._size,n),e}function l(e,t,n){for(var r=e._size.slice(0),a=!1;r.lengthr[i]&&(r[i]=t[i],a=!0);a&&s(e,r,n)}function u(e){for(var t=0,n=e.length;tArray.isArray(e)&&1===e.length?e[0]:e));return s(n?this.clone():this,r,t)},n.prototype.reshape=function(e,t){var n=t?this.clone():this;n._data=reshape$1(n._data,e);var r=n._size.reduce(((e,t)=>e*t));return n._size=processSizesWildcard(e,r),n},n.prototype.clone=function(){return new n({data:clone$2(this._data),size:clone$2(this._size),datatype:this._datatype})},n.prototype.size=function(){return this._size.slice(0)},n.prototype.map=function(e){var t=this,r=function n(r,a){return isArray$1(r)?r.map((function(e,t){return n(e,a.concat(t))})):e(r,a,t)}(this._data,[]);return new n(r,void 0!==this._datatype?getArrayDataType(r,typeOf$1):void 0)},n.prototype.forEach=function(e){var t=this;!function n(r,a){isArray$1(r)?r.forEach((function(e,t){n(e,a.concat(t))})):e(r,a,t)}(this._data,[])},n.prototype[Symbol.iterator]=function*(){yield*function*e(t,n){if(isArray$1(t))for(var r=0;r[e[r]]));t.push(new n(i,e._datatype))},o=0;o0?e:0,r=e<0?-e:0,a=this._size[0],i=this._size[1],o=Math.min(a-r,i-t),s=[],l=0;l0?r:0,s=r<0?-r:0,l=e[0],u=e[1],c=Math.min(l-s,u-o);if(isArray$1(t)){if(t.length!==c)throw new Error("Invalid value array length");i=function(e){return t[e]}}else if(isMatrix(t)){var p=t.size();if(1!==p.length||p[0]!==c)throw new Error("Invalid matrix length");i=function(e){return t.get([e])}}else i=function(){return t};a||(a=isBigNumber(i(0))?i(0).mul(0):0);var d=[];if(e.length>0){d=resize$1(d,e,a);for(var m=0;m{var{typed:t}=e;return t(name$4v,{any:clone$2})}));function _switch$1(e){var t,n,r=e.length,a=e[0].length,i=[];for(n=0;n=r.length)throw new IndexError(t,r.length);return isMatrix(e)?e.create(_reduce(e.valueOf(),t,n)):_reduce(e,t,n)}function _reduce(e,t,n){var r,a,i,o;if(t<=0){if(Array.isArray(e[0])){for(o=_switch$1(e),a=[],r=0;r{var{typed:t}=e;return t(name$4u,{number:isInteger$1,BigNumber:function(e){return e.isInt()},Fraction:function(e){return 1===e.d&&isFinite(e.n)},"Array | Matrix":function(e){return deepMap(e,this)}})})),n1$4="number",n2$2="number, number";function absNumber(e){return Math.abs(e)}function addNumber(e,t){return e+t}function multiplyNumber(e,t){return e*t}function unaryMinusNumber(e){return-e}function unaryPlusNumber(e){return e}function cbrtNumber(e){return cbrt$1(e)}function cubeNumber(e){return e*e*e}function expNumber(e){return Math.exp(e)}function expm1Number(e){return expm1$1(e)}function gcdNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Parameters in function gcd must be integer numbers");for(var n;0!==t;)n=e%t,e=t,t=n;return e<0?-e:e}function lcmNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Parameters in function lcm must be integer numbers");if(0===e||0===t)return 0;for(var n,r=e*t;0!==t;)t=e%(n=t),e=n;return Math.abs(r/e)}function logNumber(e,t){return t?Math.log(e)/Math.log(t):Math.log(e)}function log10Number(e){return log10$2(e)}function log2Number(e){return log2$1(e)}function modNumber(e,t){if(t>0)return e-t*Math.floor(e/t);if(0===t)return e;throw new Error("Cannot calculate mod for a negative divisor")}function nthRootNumber(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2,n=t<0;if(n&&(t=-t),0===t)throw new Error("Root must be non-zero");if(e<0&&Math.abs(t)%2!=1)throw new Error("Root must be odd when a is negative.");if(0===e)return n?1/0:0;if(!isFinite(e))return n?0:e;var r=Math.pow(Math.abs(e),1/t);return r=e<0?-r:r,n?1/r:r}function signNumber(e){return sign$2(e)}function squareNumber(e){return e*e}function xgcdNumber(e,t){var n,r,a,i=0,o=1,s=1,l=0;if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Parameters in function xgcd must be integer numbers");for(;t;)a=e-(r=Math.floor(e/t))*t,n=i,i=o-r*i,o=n,n=s,s=l-r*s,l=n,e=t,t=a;return e<0?[-e,-o,-l]:[e,e?o:0,l]}function powNumber(e,t){return e*e<1&&t===1/0||e*e>1&&t===-1/0?0:Math.pow(e,t)}function roundNumber(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!isInteger$1(t)||t<0||t>15)throw new Error("Number of decimals in function round must be an integer from 0 to 15 inclusive");return parseFloat(toFixed$2(e,t))}absNumber.signature=n1$4,addNumber.signature=n2$2,multiplyNumber.signature=n2$2,unaryMinusNumber.signature=n1$4,unaryPlusNumber.signature=n1$4,cbrtNumber.signature=n1$4,cubeNumber.signature=n1$4,expNumber.signature=n1$4,expm1Number.signature=n1$4,gcdNumber.signature=n2$2,lcmNumber.signature=n2$2,log10Number.signature=n1$4,log2Number.signature=n1$4,modNumber.signature=n2$2,signNumber.signature=n1$4,squareNumber.signature=n1$4,xgcdNumber.signature=n2$2,powNumber.signature=n2$2;var n1$3="number",n2$1="number, number";function bitAndNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function bitAnd");return e&t}function bitNotNumber(e){if(!isInteger$1(e))throw new Error("Integer expected in function bitNot");return~e}function bitOrNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function bitOr");return e|t}function bitXorNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function bitXor");return e^t}function leftShiftNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function leftShift");return e<>t}function rightLogShiftNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function rightLogShift");return e>>>t}function product(e,t){if(t>1;return product(e,n)*product(n+1,t)}function combinationsNumber(e,t){if(!isInteger$1(e)||e<0)throw new TypeError("Positive integer value expected in function combinations");if(!isInteger$1(t)||t<0)throw new TypeError("Positive integer value expected in function combinations");if(t>e)throw new TypeError("k must be less than or equal to n");for(var n=e-t,r=1,a=2,i=t171?1/0:product(1,e-1);if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*gammaNumber(1-e));if(e>=171.35)return 1/0;if(e>85){var n=e*e,r=n*e,a=r*e,i=a*e;return Math.sqrt(2*Math.PI/e)*Math.pow(e/Math.E,e)*(1+1/(12*e)+1/(288*n)-139/(51840*r)-571/(2488320*a)+163879/(209018880*i)+5246819/(75246796800*i*e))}--e,t=gammaP[0];for(var o=1;o=1;r--)n+=lgammaSeries[r]/(e+r);return lnSqrt2PI+(e+.5)*Math.log(t)-t+Math.log(n)}lgammaNumber.signature="number";var n1$1="number";function acoshNumber(e){return acosh$2(e)}function acotNumber(e){return Math.atan(1/e)}function acothNumber(e){return isFinite(e)?(Math.log((e+1)/e)+Math.log(e/(e-1)))/2:0}function acscNumber(e){return Math.asin(1/e)}function acschNumber(e){var t=1/e;return Math.log(t+Math.sqrt(t*t+1))}function asecNumber(e){return Math.acos(1/e)}function asechNumber(e){var t=1/e,n=Math.sqrt(t*t-1);return Math.log(n+t)}function asinhNumber(e){return asinh$2(e)}function atanhNumber(e){return atanh$2(e)}function cotNumber(e){return 1/Math.tan(e)}function cothNumber(e){var t=Math.exp(2*e);return(t+1)/(t-1)}function cscNumber(e){return 1/Math.sin(e)}function cschNumber(e){return 0===e?Number.POSITIVE_INFINITY:Math.abs(2/(Math.exp(e)-Math.exp(-e)))*sign$2(e)}function secNumber(e){return 1/Math.cos(e)}function sechNumber(e){return 2/(Math.exp(e)+Math.exp(-e))}function sinhNumber(e){return sinh$2(e)}acoshNumber.signature=n1$1,acotNumber.signature=n1$1,acothNumber.signature=n1$1,acscNumber.signature=n1$1,acschNumber.signature=n1$1,asecNumber.signature=n1$1,asechNumber.signature=n1$1,asinhNumber.signature=n1$1,atanhNumber.signature=n1$1,cotNumber.signature=n1$1,cothNumber.signature=n1$1,cscNumber.signature=n1$1,cschNumber.signature=n1$1,secNumber.signature=n1$1,sechNumber.signature=n1$1,sinhNumber.signature=n1$1;var n1="number";function isNegativeNumber(e){return e<0}function isPositiveNumber(e){return e>0}function isZeroNumber(e){return 0===e}function isNaNNumber(e){return Number.isNaN(e)}isNegativeNumber.signature=n1,isPositiveNumber.signature=n1,isZeroNumber.signature=n1,isNaNNumber.signature=n1;var name$4t="isNegative",dependencies$4t=["typed"],createIsNegative=factory(name$4t,dependencies$4t,(e=>{var{typed:t}=e;return t(name$4t,{number:isNegativeNumber,BigNumber:function(e){return e.isNeg()&&!e.isZero()&&!e.isNaN()},Fraction:function(e){return e.s<0},Unit:function(e){return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4s="isNumeric",dependencies$4s=["typed"],createIsNumeric=factory(name$4s,dependencies$4s,(e=>{var{typed:t}=e;return t(name$4s,{"number | BigNumber | Fraction | boolean":function(){return!0},"Complex | Unit | string | null | undefined | Node":function(){return!1},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4r="hasNumericValue",dependencies$4r=["typed","isNumeric"],createHasNumericValue=factory(name$4r,dependencies$4r,(e=>{var{typed:t,isNumeric:n}=e;return t(name$4r,{string:function(e){return e.trim().length>0&&!isNaN(Number(e))},any:function(e){return n(e)}})})),name$4q="isPositive",dependencies$4q=["typed"],createIsPositive=factory(name$4q,dependencies$4q,(e=>{var{typed:t}=e;return t(name$4q,{number:isPositiveNumber,BigNumber:function(e){return!e.isNeg()&&!e.isZero()&&!e.isNaN()},Fraction:function(e){return e.s>0&&e.n>0},Unit:function(e){return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4p="isZero",dependencies$4p=["typed"],createIsZero=factory(name$4p,dependencies$4p,(e=>{var{typed:t}=e;return t(name$4p,{number:isZeroNumber,BigNumber:function(e){return e.isZero()},Complex:function(e){return 0===e.re&&0===e.im},Fraction:function(e){return 1===e.d&&0===e.n},Unit:function(e){return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4o="isNaN",dependencies$4o=["typed"],createIsNaN=factory(name$4o,dependencies$4o,(e=>{var{typed:t}=e;return t(name$4o,{number:isNaNNumber,BigNumber:function(e){return e.isNaN()},Fraction:function(e){return!1},Complex:function(e){return e.isNaN()},Unit:function(e){return Number.isNaN(e.value)},"Array | Matrix":function(e){return deepMap(e,Number.isNaN)}})})),name$4n="typeOf",dependencies$4n=["typed"],createTypeOf=factory(name$4n,dependencies$4n,(e=>{var{typed:t}=e;return t(name$4n,{any:typeOf$1})}));function nearlyEqual(e,t,n){if(null==n)return e.eq(t);if(e.eq(t))return!0;if(e.isNaN()||t.isNaN())return!1;if(e.isFinite()&&t.isFinite()){var r=e.minus(t).abs();if(r.isZero())return!0;var a=e.constructor.max(e.abs(),t.abs());return r.lte(a.times(n))}return!1}function complexEquals(e,t,n){return nearlyEqual$1(e.re,t.re,n)&&nearlyEqual$1(e.im,t.im,n)}var name$4m="equalScalar",dependencies$4m=["typed","config"],createEqualScalar=factory(name$4m,dependencies$4m,(e=>{var{typed:t,config:n}=e;return t(name$4m,{"boolean, boolean":function(e,t){return e===t},"number, number":function(e,t){return nearlyEqual$1(e,t,n.epsilon)},"BigNumber, BigNumber":function(e,t){return e.eq(t)||nearlyEqual(e,t,n.epsilon)},"Fraction, Fraction":function(e,t){return e.equals(t)},"Complex, Complex":function(e,t){return complexEquals(e,t,n.epsilon)},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)}})}));factory(name$4m,["typed","config"],(e=>{var{typed:t,config:n}=e;return t(name$4m,{"number, number":function(e,t){return nearlyEqual$1(e,t,n.epsilon)}})}));var name$4l="SparseMatrix",dependencies$4l=["typed","equalScalar","Matrix"],createSparseMatrixClass=factory(name$4l,dependencies$4l,(e=>{var{typed:t,equalScalar:n,Matrix:r}=e;function a(e,t){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");if(t&&!isString$1(t))throw new Error("Invalid datatype: "+t);if(isMatrix(e))!function(e,t,n){"SparseMatrix"===t.type?(e._values=t._values?clone$2(t._values):void 0,e._index=clone$2(t._index),e._ptr=clone$2(t._ptr),e._size=clone$2(t._size),e._datatype=n||t._datatype):i(e,t.valueOf(),n||t._datatype)}(this,e,t);else if(e&&isArray$1(e.index)&&isArray$1(e.ptr)&&isArray$1(e.size))this._values=e.values,this._index=e.index,this._ptr=e.ptr,this._size=e.size,this._datatype=t||e.datatype;else if(isArray$1(e))i(this,e,t);else{if(e)throw new TypeError("Unsupported type of data ("+typeOf$1(e)+")");this._values=[],this._index=[],this._ptr=[0],this._size=[0,0],this._datatype=t}}function i(e,r,a){e._values=[],e._index=[],e._ptr=[],e._datatype=a;var i=r.length,o=0,s=n,l=0;if(isString$1(a)&&(s=t.find(n,[a,a])||n,l=t.convert(0,a)),i>0){var u=0;do{e._ptr.push(e._index.length);for(var c=0;c");if(1===i.length)t.dimension(0).forEach((function(t,a){validateIndex(t),e.set([t,0],n[a[0]],r)}));else{var u=t.dimension(0),c=t.dimension(1);u.forEach((function(t,a){validateIndex(t),c.forEach((function(i,o){validateIndex(i),e.set([t,i],n[a[0]][o[0]],r)}))}))}}return e}function l(e,t,n,r){if(n-t==0)return n;for(var a=t;af){for(c=f;cm){if(d){var h=0;for(c=0;cr-1&&(e._values.splice(p,1),e._index.splice(p,1),b++)}e._ptr[c]=e._values.length}return e._size[0]=r,e._size[1]=a,e}function p(e,t,n,r,a){var i,o,s=r[0],l=r[1],u=[];for(i=0;is-1||o>p-1)&&(c(this,Math.max(i+1,s),Math.max(o+1,p),a),s=this._size[0],p=this._size[1]),validateIndex(i,s),validateIndex(o,p);var f=l(i,this._ptr[o],this._ptr[o+1],this._index);return fArray.isArray(e)&&1===e.length?e[0]:e));if(2!==r.length)throw new Error("Only two dimensions matrix are supported");return r.forEach((function(e){if(!isNumber$1(e)||!isInteger$1(e)||e<0)throw new TypeError("Invalid size, must contain positive integers (size: "+format$1(r)+")")})),c(n?this.clone():this,r[0],r[1],t)},a.prototype.reshape=function(e,t){if(!isArray$1(e))throw new TypeError("Array expected");if(2!==e.length)throw new Error("Sparse matrices can only be reshaped in two dimensions");e.forEach((function(t){if(!isNumber$1(t)||!isInteger$1(t)||t<=-2||0===t)throw new TypeError("Invalid size, must contain positive integers or -1 (size: "+format$1(e)+")")}));var n=this._size[0]*this._size[1];if(n!==(e=processSizesWildcard(e,n))[0]*e[1])throw new Error("Reshaping sparse matrix will result in the wrong number of elements");var r=t?this.clone():this;if(this._size[0]===e[0]&&this._size[1]===e[1])return r;for(var a=[],i=0;i=0&&T<=i&&h(e._values[v],T-0,y-0)}else{for(var N={},C=b;C "+(this._values?format$1(this._values[l],e):"X");return a},a.prototype.toString=function(){return format$1(this.toArray())},a.prototype.toJSON=function(){return{mathjs:"SparseMatrix",values:this._values,index:this._index,ptr:this._ptr,size:this._size,datatype:this._datatype}},a.prototype.diagonal=function(e){if(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger$1(e))throw new TypeError("The parameter k must be an integer number")}else e=0;var t=e>0?e:0,n=e<0?-e:0,r=this._size[0],i=this._size[1],o=Math.min(r-n,i-t),s=[],l=[],u=[];u[0]=0;for(var c=t;c0?i:0,d=i<0?-i:0,m=e[0],f=e[1],h=Math.min(m-d,f-p);if(isArray$1(r)){if(r.length!==h)throw new Error("Invalid value array length");c=function(e){return r[e]}}else if(isMatrix(r)){var y=r.size();if(1!==y.length||y[0]!==h)throw new Error("Invalid matrix length");c=function(e){return r.get([e])}}else c=function(){return r};for(var b=[],g=[],v=[],T=0;T=0&&N=u||a[p]!==t)){var m=r?r[c]:void 0;a.splice(p,0,t),r&&r.splice(p,0,m),a.splice(p<=c?c+1:c,1),r&&r.splice(p<=c?c+1:c,1)}else if(p=u||a[c]!==e)){var f=r?r[p]:void 0;a.splice(c,0,e),r&&r.splice(c,0,f),a.splice(c<=p?p+1:p,1),r&&r.splice(c<=p?p+1:p,1)}}},a}),{isClass:!0}),name$4k="number",dependencies$4k=["typed"];function getNonDecimalNumberParts(e){var t=e.match(/(0[box])([0-9a-fA-F]*)\.([0-9a-fA-F]*)/);return t?{input:e,radix:{"0b":2,"0o":8,"0x":16}[t[1]],integerPart:t[2],fractionalPart:t[3]}:null}function makeNumberFromNonDecimalParts(e){for(var t=parseInt(e.integerPart,e.radix),n=0,r=0;r{var{typed:t}=e,n=t("number",{"":function(){return 0},number:function(e){return e},string:function(e){if("NaN"===e)return NaN;var t=getNonDecimalNumberParts(e);if(t)return makeNumberFromNonDecimalParts(t);var n=0,r=e.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);r&&(n=Number(r[2]),e=r[1]);var a=Number(e);if(isNaN(a))throw new SyntaxError('String "'+e+'" is no valid number');if(r){if(a>2**n-1)throw new SyntaxError('String "'.concat(e,'" is out of range'));a>=2**(n-1)&&(a-=2**n)}return a},BigNumber:function(e){return e.toNumber()},Fraction:function(e){return e.valueOf()},Unit:function(e){throw new Error("Second argument with valueless unit expected")},null:function(e){return 0},"Unit, string | Unit":function(e,t){return e.toNumber(t)},"Array | Matrix":function(e){return deepMap(e,this)}});return n.fromJSON=function(e){return parseFloat(e.value)},n})),name$4j="string",dependencies$4j=["typed"],createString=factory(name$4j,dependencies$4j,(e=>{var{typed:t}=e;return t(name$4j,{"":function(){return""},number:format$3,null:function(e){return"null"},boolean:function(e){return e+""},string:function(e){return e},"Array | Matrix":function(e){return deepMap(e,this)},any:function(e){return String(e)}})})),name$4i="boolean",dependencies$4i=["typed"],createBoolean=factory(name$4i,dependencies$4i,(e=>{var{typed:t}=e;return t(name$4i,{"":function(){return!1},boolean:function(e){return e},number:function(e){return!!e},null:function(e){return!1},BigNumber:function(e){return!e.isZero()},string:function(e){var t=e.toLowerCase();if("true"===t)return!0;if("false"===t)return!1;var n=Number(e);if(""!==e&&!isNaN(n))return!!n;throw new Error('Cannot convert "'+e+'" to a boolean')},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4h="bignumber",dependencies$4h=["typed","BigNumber"],createBignumber=factory(name$4h,dependencies$4h,(e=>{var{typed:t,BigNumber:n}=e;return t("bignumber",{"":function(){return new n(0)},number:function(e){return new n(e+"")},string:function(e){var t=e.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);if(t){var r=t[2],a=n(t[1]),i=new n(2).pow(Number(r));if(a.gt(i.sub(1)))throw new SyntaxError('String "'.concat(e,'" is out of range'));var o=new n(2).pow(Number(r)-1);return a.gte(o)?a.sub(i):a}return new n(e)},BigNumber:function(e){return e},Fraction:function(e){return new n(e.n).div(e.d).times(e.s)},null:function(e){return new n(0)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4g="complex",dependencies$4g=["typed","Complex"],createComplex=factory(name$4g,dependencies$4g,(e=>{var{typed:t,Complex:n}=e;return t("complex",{"":function(){return n.ZERO},number:function(e){return new n(e,0)},"number, number":function(e,t){return new n(e,t)},"BigNumber, BigNumber":function(e,t){return new n(e.toNumber(),t.toNumber())},Fraction:function(e){return new n(e.valueOf(),0)},Complex:function(e){return e.clone()},string:function(e){return n(e)},null:function(e){return n(0)},Object:function(e){if("re"in e&&"im"in e)return new n(e.re,e.im);if("r"in e&&"phi"in e||"abs"in e&&"arg"in e)return new n(e);throw new Error("Expected object with properties (re and im) or (r and phi) or (abs and arg)")},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4f="fraction",dependencies$4f=["typed","Fraction"],createFraction=factory(name$4f,dependencies$4f,(e=>{var{typed:t,Fraction:n}=e;return t("fraction",{number:function(e){if(!isFinite(e)||isNaN(e))throw new Error(e+" cannot be represented as a fraction");return new n(e)},string:function(e){return new n(e)},"number, number":function(e,t){return new n(e,t)},null:function(e){return new n(0)},BigNumber:function(e){return new n(e.toString())},Fraction:function(e){return e},Object:function(e){return new n(e)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4e="matrix",dependencies$4e=["typed","Matrix","DenseMatrix","SparseMatrix"],createMatrix=factory(name$4e,dependencies$4e,(e=>{var{typed:t,Matrix:n,DenseMatrix:r,SparseMatrix:a}=e;return t(name$4e,{"":function(){return i([])},string:function(e){return i([],e)},"string, string":function(e,t){return i([],e,t)},Array:function(e){return i(e)},Matrix:function(e){return i(e,e.storage())},"Array | Matrix, string":i,"Array | Matrix, string, string":i});function i(e,t,n){if("dense"===t||"default"===t||void 0===t)return new r(e,n);if("sparse"===t)return new a(e,n);throw new TypeError("Unknown matrix type "+JSON.stringify(t)+".")}})),name$4d="matrixFromFunction",dependencies$4d=["typed","matrix","isZero"],createMatrixFromFunction=factory(name$4d,dependencies$4d,(e=>{var{typed:t,matrix:n,isZero:r}=e;return t(name$4d,{"Array | Matrix, function, string, string":function(e,t,n,r){return a(e,t,n,r)},"Array | Matrix, function, string":function(e,t,n){return a(e,t,n)},"Matrix, function":function(e,t){return a(e,t,"dense")},"Array, function":function(e,t){return a(e,t,"dense").toArray()},"Array | Matrix, string, function":function(e,t,n){return a(e,n,t)},"Array | Matrix, string, string, function":function(e,t,n,r){return a(e,r,t,n)}});function a(e,t,a,i){var o;return(o=void 0!==i?n(a,i):n(a)).resize(e),o.forEach((function(e,n){var a=t(n);r(a)||o.set(n,a)})),o}})),name$4c="matrixFromRows",dependencies$4c=["typed","matrix","flatten","size"],createMatrixFromRows=factory(name$4c,dependencies$4c,(e=>{var{typed:t,matrix:n,flatten:r,size:a}=e;return t(name$4c,{"...Array":function(e){return i(e)},"...Matrix":function(e){return n(i(e.map((e=>e.toArray()))))}});function i(e){if(0===e.length)throw new TypeError("At least one row is needed to construct a matrix.");var t=o(e[0]),n=[];for(var a of e){var i=o(a);if(i!==t)throw new TypeError("The vectors had different length: "+(0|t)+" ≠ "+(0|i));n.push(r(a))}return n}function o(e){var t=a(e);if(1===t.length)return t[0];if(2===t.length){if(1===t[0])return t[1];if(1===t[1])return t[0];throw new TypeError("At least one of the arguments is not a vector.")}throw new TypeError("Only one- or two-dimensional vectors are supported.")}})),name$4b="matrixFromColumns",dependencies$4b=["typed","matrix","flatten","size"],createMatrixFromColumns=factory(name$4b,dependencies$4b,(e=>{var{typed:t,matrix:n,flatten:r,size:a}=e;return t(name$4b,{"...Array":function(e){return i(e)},"...Matrix":function(e){return n(i(e.map((e=>e.toArray()))))}});function i(e){if(0===e.length)throw new TypeError("At least one column is needed to construct a matrix.");for(var t=o(e[0]),n=[],a=0;a{var{typed:t}=e;return t(name$4a,{"Unit, Array":function(e,t){return e.splitUnit(t)}})})),name$49="unaryMinus",dependencies$49=["typed"],createUnaryMinus=factory(name$49,dependencies$49,(e=>{var{typed:t}=e;return t(name$49,{number:unaryMinusNumber,Complex:function(e){return e.neg()},BigNumber:function(e){return e.neg()},Fraction:function(e){return e.neg()},Unit:function(e){var t=e.clone();return t.value=this(e.value),t},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$48="unaryPlus",dependencies$48=["typed","config","BigNumber"],createUnaryPlus=factory(name$48,dependencies$48,(e=>{var{typed:t,config:n,BigNumber:r}=e;return t(name$48,{number:unaryPlusNumber,Complex:function(e){return e},BigNumber:function(e){return e},Fraction:function(e){return e},Unit:function(e){return e.clone()},"Array | Matrix":function(e){return deepMap(e,this)},"boolean | string":function(e){return"BigNumber"===n.number?new r(+e):+e}})})),name$47="abs",dependencies$47=["typed"],createAbs=factory(name$47,dependencies$47,(e=>{var{typed:t}=e;return t(name$47,{number:absNumber,Complex:function(e){return e.abs()},BigNumber:function(e){return e.abs()},Fraction:function(e){return e.abs()},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){return e.abs()}})})),name$46="apply",dependencies$46=["typed","isInteger"],createApply=factory(name$46,dependencies$46,(e=>{var{typed:t,isInteger:n}=e;return t(name$46,{"Array | Matrix, number | BigNumber, function":function(e,t,r){if(!n(t))throw new TypeError("Integer number expected for dimension");var a=Array.isArray(e)?arraySize(e):e.size();if(t<0||t>=a.length)throw new IndexError(t,a.length);return isMatrix(e)?e.create(_apply(e.valueOf(),t,r)):_apply(e,t,r)}})}));function _apply(e,t,n){var r,a,i;if(t<=0){if(Array.isArray(e[0])){for(i=_switch(e),a=[],r=0;r{var{typed:t}=e;return t(name$45,{"number, number":addNumber,"Complex, Complex":function(e,t){return e.add(t)},"BigNumber, BigNumber":function(e,t){return e.plus(t)},"Fraction, Fraction":function(e,t){return e.add(t)},"Unit, Unit":function(e,t){if(null===e.value||void 0===e.value)throw new Error("Parameter x contains a unit with undefined value");if(null===t.value||void 0===t.value)throw new Error("Parameter y contains a unit with undefined value");if(!e.equalBase(t))throw new Error("Units do not match");var n=e.clone();return n.value=this(n.value,t.value),n.fixPrefix=!1,n}})})),name$44="cbrt",dependencies$44=["config","typed","isNegative","unaryMinus","matrix","Complex","BigNumber","Fraction"],createCbrt=factory(name$44,dependencies$44,(e=>{var{config:t,typed:n,isNegative:r,unaryMinus:a,matrix:i,Complex:o,BigNumber:s,Fraction:l}=e;return n(name$44,{number:cbrtNumber,Complex:u,"Complex, boolean":u,BigNumber:function(e){return e.cbrt()},Unit:function(e){if(e.value&&isComplex(e.value)){var t=e.clone();return t.value=1,(t=t.pow(1/3)).value=u(e.value),t}var n,i=r(e.value);i&&(e.value=a(e.value)),n=isBigNumber(e.value)?new s(1).div(3):isFraction(e.value)?new l(1,3):1/3;var o=e.pow(n);return i&&(o.value=a(o.value)),o},"Array | Matrix":function(e){return deepMap(e,this)}});function u(e,n){var r=e.arg()/3,a=e.abs(),s=new o(cbrtNumber(a),0).mul(new o(0,r).exp());if(n){var l=[s,new o(cbrtNumber(a),0).mul(new o(0,r+2*Math.PI/3).exp()),new o(cbrtNumber(a),0).mul(new o(0,r-2*Math.PI/3).exp())];return"Array"===t.matrix?l:i(l)}return s}})),name$43="algorithm11",dependencies$43=["typed","equalScalar"],createAlgorithm11=factory(name$43,dependencies$43,(e=>{var{typed:t,equalScalar:n}=e;return function(e,r,a,i){var o=e._values,s=e._index,l=e._ptr,u=e._size,c=e._datatype;if(!o)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var p,d=u[0],m=u[1],f=n,h=0,y=a;"string"==typeof c&&(p=c,f=t.find(n,[p,p]),h=t.convert(0,p),r=t.convert(r,p),y=t.find(a,[p,p]));for(var b=[],g=[],v=[],T=0;T{var{typed:t,DenseMatrix:n}=e;return function(e,r,a,i){var o=e._values,s=e._index,l=e._ptr,u=e._size,c=e._datatype;if(!o)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var p,d=u[0],m=u[1],f=a;"string"==typeof c&&(p=c,r=t.convert(r,p),f=t.find(a,[p,p]));for(var h=[],y=[],b=[],g=0;g{var{typed:t}=e;return function(e,r,a,i){var o,s=e._data,l=e._size,u=e._datatype,c=a;"string"==typeof u&&(o=u,r=t.convert(r,o),c=t.find(a,[o,o]));var p=l.length>0?n(c,0,l,l[0],s,r,i):[];return e.createDenseMatrix({data:p,size:clone$2(l),datatype:o})};function n(e,t,r,a,i,o,s){var l=[];if(t===r.length-1)for(var u=0;u{var{typed:t,config:n,round:r}=e;return t(name$40,{number:function(e){return nearlyEqual$1(e,r(e),n.epsilon)?r(e):Math.ceil(e)},"number, number":function(e,t){if(nearlyEqual$1(e,r(e,t),n.epsilon))return r(e,t);var[a,i]="".concat(e,"e").split("e"),o=Math.ceil(Number("".concat(a,"e").concat(Number(i)+t)));return[a,i]="".concat(o,"e").split("e"),Number("".concat(a,"e").concat(Number(i)-t))}})})),createCeil=factory(name$40,dependencies$40,(e=>{var{typed:t,config:n,round:r,matrix:a,equalScalar:i,zeros:o,DenseMatrix:s}=e,l=createAlgorithm11({typed:t,equalScalar:i}),u=createAlgorithm12({typed:t,DenseMatrix:s}),c=createAlgorithm14({typed:t}),p=createCeilNumber({typed:t,config:n,round:r});return t("ceil",{number:p.signatures.number,"number,number":p.signatures["number,number"],Complex:function(e){return e.ceil()},"Complex, number":function(e,t){return e.ceil(t)},"Complex, BigNumber":function(e,t){return e.ceil(t.toNumber())},BigNumber:function(e){return nearlyEqual(e,r(e),n.epsilon)?r(e):e.ceil()},"BigNumber, BigNumber":function(e,t){return nearlyEqual(e,r(e,t),n.epsilon)?r(e,t):e.toDecimalPlaces(t.toNumber(),Decimal.ROUND_CEIL)},Fraction:function(e){return e.ceil()},"Fraction, number":function(e,t){return e.ceil(t)},"Fraction, BigNumber":function(e,t){return e.ceil(t.toNumber())},"Array | Matrix":function(e){return deepMap(e,this)},"Array, number | BigNumber":function(e,t){return deepMap(e,(e=>this(e,t)))},"SparseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return c(e,t,this,!1)},"number | Complex | Fraction | BigNumber, Array":function(e,t){return c(a(t),e,this,!0).valueOf()},"number | Complex | Fraction | BigNumber, Matrix":function(e,t){return i(e,0)?o(t.size(),t.storage()):"dense"===t.storage()?c(t,e,this,!0):u(t,e,this,!0)}})})),name$3$="cube",dependencies$3$=["typed"],createCube=factory(name$3$,dependencies$3$,(e=>{var{typed:t}=e;return t(name$3$,{number:cubeNumber,Complex:function(e){return e.mul(e).mul(e)},BigNumber:function(e){return e.times(e).times(e)},Fraction:function(e){return e.pow(3)},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){return e.pow(3)}})})),name$3_="exp",dependencies$3_=["typed"],createExp=factory(name$3_,dependencies$3_,(e=>{var{typed:t}=e;return t(name$3_,{number:expNumber,Complex:function(e){return e.exp()},BigNumber:function(e){return e.exp()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3Z="expm1",dependencies$3Z=["typed","Complex"],createExpm1=factory(name$3Z,dependencies$3Z,(e=>{var{typed:t,Complex:n}=e;return t(name$3Z,{number:expm1Number,Complex:function(e){var t=Math.exp(e.re);return new n(t*Math.cos(e.im)-1,t*Math.sin(e.im))},BigNumber:function(e){return e.exp().minus(1)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3Y="fix",dependencies$3Y=["typed","Complex","matrix","ceil","floor","equalScalar","zeros","DenseMatrix"],createFixNumber=factory(name$3Y,["typed","ceil","floor"],(e=>{var{typed:t,ceil:n,floor:r}=e;return t(name$3Y,{number:function(e){return e>0?r(e):n(e)},"number, number":function(e,t){return e>0?r(e,t):n(e,t)}})})),createFix=factory(name$3Y,dependencies$3Y,(e=>{var{typed:t,Complex:n,matrix:r,ceil:a,floor:i,equalScalar:o,zeros:s,DenseMatrix:l}=e,u=createAlgorithm12({typed:t,DenseMatrix:l}),c=createAlgorithm14({typed:t}),p=createFixNumber({typed:t,ceil:a,floor:i});return t("fix",{number:p.signatures.number,"number, number | BigNumber":p.signatures["number,number"],Complex:function(e){return new n(e.re>0?Math.floor(e.re):Math.ceil(e.re),e.im>0?Math.floor(e.im):Math.ceil(e.im))},"Complex, number":function(e,t){return new n(e.re>0?i(e.re,t):a(e.re,t),e.im>0?i(e.im,t):a(e.im,t))},"Complex, BigNumber":function(e,t){var r=t.toNumber();return new n(e.re>0?i(e.re,r):a(e.re,r),e.im>0?i(e.im,r):a(e.im,r))},BigNumber:function(e){return e.isNegative()?a(e):i(e)},"BigNumber, number | BigNumber":function(e,t){return e.isNegative()?a(e,t):i(e,t)},Fraction:function(e){return e.s<0?e.ceil():e.floor()},"Fraction, number | BigNumber":function(e,t){return e.s<0?a(e,t):i(e,t)},"Array | Matrix":function(e){return deepMap(e,this)},"Array | Matrix, number | BigNumber":function(e,t){return deepMap(e,(e=>this(e,t)))},"number | Complex | Fraction | BigNumber, Array":function(e,t){return c(r(t),e,this,!0).valueOf()},"number | Complex | Fraction | BigNumber, Matrix":function(e,t){return o(e,0)?s(t.size(),t.storage()):"dense"===t.storage()?c(t,e,this,!0):u(t,e,this,!0)}})})),name$3X="floor",dependencies$3X=["typed","config","round","matrix","equalScalar","zeros","DenseMatrix"],createFloorNumber=factory(name$3X,["typed","config","round"],(e=>{var{typed:t,config:n,round:r}=e;return t(name$3X,{number:function(e){return nearlyEqual$1(e,r(e),n.epsilon)?r(e):Math.floor(e)},"number, number":function(e,t){if(nearlyEqual$1(e,r(e,t),n.epsilon))return r(e,t);var[a,i]="".concat(e,"e").split("e"),o=Math.floor(Number("".concat(a,"e").concat(Number(i)+t)));return[a,i]="".concat(o,"e").split("e"),Number("".concat(a,"e").concat(Number(i)-t))}})})),createFloor=factory(name$3X,dependencies$3X,(e=>{var{typed:t,config:n,round:r,matrix:a,equalScalar:i,zeros:o,DenseMatrix:s}=e,l=createAlgorithm11({typed:t,equalScalar:i}),u=createAlgorithm12({typed:t,DenseMatrix:s}),c=createAlgorithm14({typed:t}),p=createFloorNumber({typed:t,config:n,round:r});return t("floor",{number:p.signatures.number,"number,number":p.signatures["number,number"],Complex:function(e){return e.floor()},"Complex, number":function(e,t){return e.floor(t)},"Complex, BigNumber":function(e,t){return e.floor(t.toNumber())},BigNumber:function(e){return nearlyEqual(e,r(e),n.epsilon)?r(e):e.floor()},"BigNumber, BigNumber":function(e,t){return nearlyEqual(e,r(e,t),n.epsilon)?r(e,t):e.toDecimalPlaces(t.toNumber(),Decimal.ROUND_FLOOR)},Fraction:function(e){return e.floor()},"Fraction, number":function(e,t){return e.floor(t)},"Fraction, BigNumber":function(e,t){return e.floor(t.toNumber())},"Array | Matrix":function(e){return deepMap(e,this)},"Array, number | BigNumber":function(e,t){return deepMap(e,(e=>this(e,t)))},"SparseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return c(e,t,this,!1)},"number | Complex | Fraction | BigNumber, Array":function(e,t){return c(a(t),e,this,!0).valueOf()},"number | Complex | Fraction | BigNumber, Matrix":function(e,t){return i(e,0)?o(t.size(),t.storage()):"dense"===t.storage()?c(t,e,this,!0):u(t,e,this,!0)}})})),name$3W="algorithm01",dependencies$3W=["typed"],createAlgorithm01=factory(name$3W,dependencies$3W,(e=>{var{typed:t}=e;return function(e,n,r,a){var i=e._data,o=e._size,s=e._datatype,l=n._values,u=n._index,c=n._ptr,p=n._size,d=n._datatype;if(o.length!==p.length)throw new DimensionError(o.length,p.length);if(o[0]!==p[0]||o[1]!==p[1])throw new RangeError("Dimension mismatch. Matrix A ("+o+") must match Matrix B ("+p+")");if(!l)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var m,f,h=o[0],y=o[1],b="string"==typeof s&&s===d?s:void 0,g=b?t.find(r,[b,b]):r,v=[];for(m=0;m{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,o=e._index,s=e._ptr,l=e._size,u=e._datatype,c=r._values,p=r._index,d=r._ptr,m=r._size,f=r._datatype;if(l.length!==m.length)throw new DimensionError(l.length,m.length);if(l[0]!==m[0]||l[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+l+") must match Matrix B ("+m+")");var h,y=l[0],b=l[1],g=n,v=0,T=a;"string"==typeof u&&u===f&&(h=u,g=t.find(n,[h,h]),v=t.convert(0,h),T=t.find(a,[h,h]));var N,C,A,S,x,w=i&&c?[]:void 0,V=[],E=[],O=i&&c?[]:void 0,_=i&&c?[]:void 0,$=[],D=[];for(C=0;C{var{typed:t,DenseMatrix:n}=e;return function(e,r,a,i){var o=e._values,s=e._index,l=e._ptr,u=e._size,c=e._datatype;if(!o)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var p,d=u[0],m=u[1],f=a;"string"==typeof c&&(p=c,r=t.convert(r,p),f=t.find(a,[p,p]));for(var h=[],y=[],b=[],g=0;g{var{typed:t}=e;return function(e,r,a){var i,o=e._data,s=e._size,l=e._datatype,u=r._data,c=r._size,p=r._datatype,d=[];if(s.length!==c.length)throw new DimensionError(s.length,c.length);for(var m=0;m0?n(f,0,d,d[0],o,u):[];return e.createDenseMatrix({data:h,size:d,datatype:i})};function n(e,t,r,a,i,o){var s=[];if(t===r.length-1)for(var l=0;l{var{typed:t,matrix:n,equalScalar:r,BigNumber:a,DenseMatrix:i}=e,o=createAlgorithm01({typed:t}),s=createAlgorithm04({typed:t,equalScalar:r}),l=createAlgorithm10({typed:t,DenseMatrix:i}),u=createAlgorithm13({typed:t}),c=createAlgorithm14({typed:t});return t(name$3S,{"number, number":gcdNumber,"BigNumber, BigNumber":function(e,t){if(!e.isInt()||!t.isInt())throw new Error("Parameters in function gcd must be integer numbers");for(var n=new a(0);!t.isZero();){var r=e.mod(t);e=t,t=r}return e.lt(n)?e.neg():e},"Fraction, Fraction":function(e,t){return e.gcd(t)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return o(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return u(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return c(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return l(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return c(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return c(n(e),t,this,!1).valueOf()},"number | BigNumber, Array":function(e,t){return c(n(t),e,this,!0).valueOf()},"Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber":function(e,t,n){for(var r=this(e,t),a=0;a{var{typed:t,equalScalar:n}=e;return function(e,r,a,i){var o=e._data,s=e._size,l=e._datatype,u=r._values,c=r._index,p=r._ptr,d=r._size,m=r._datatype;if(s.length!==d.length)throw new DimensionError(s.length,d.length);if(s[0]!==d[0]||s[1]!==d[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+d+")");if(!u)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var f,h=s[0],y=s[1],b=n,g=0,v=a;"string"==typeof l&&l===m&&(f=l,b=t.find(n,[f,f]),g=t.convert(0,f),v=t.find(a,[f,f]));for(var T=[],N=[],C=[],A=0;A{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,o=e._size,s=e._datatype,l=r._values,u=r._size,c=r._datatype;if(o.length!==u.length)throw new DimensionError(o.length,u.length);if(o[0]!==u[0]||o[1]!==u[1])throw new RangeError("Dimension mismatch. Matrix A ("+o+") must match Matrix B ("+u+")");var p,d=o[0],m=o[1],f=n,h=0,y=a;"string"==typeof s&&s===c&&(p=s,f=t.find(n,[p,p]),h=t.convert(0,p),y=t.find(a,[p,p]));for(var b=i&&l?[]:void 0,g=[],v=[],T=b?[]:void 0,N=[],C=[],A=0;A{var{typed:t,matrix:n,equalScalar:r}=e,a=createAlgorithm02({typed:t,equalScalar:r}),i=createAlgorithm06({typed:t,equalScalar:r}),o=createAlgorithm11({typed:t,equalScalar:r}),s=createAlgorithm13({typed:t}),l=createAlgorithm14({typed:t});return t(name$3P,{"number, number":lcmNumber,"BigNumber, BigNumber":function(e,t){if(!e.isInt()||!t.isInt())throw new Error("Parameters in function lcm must be integer numbers");if(e.isZero())return e;if(t.isZero())return t;for(var n=e.times(t);!t.isZero();){var r=t;t=e.mod(r),e=r}return n.div(e).abs()},"Fraction, Fraction":function(e,t){return e.lcm(t)},"SparseMatrix, SparseMatrix":function(e,t){return i(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return a(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return a(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return s(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return o(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return o(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return l(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return l(n(e),t,this,!1).valueOf()},"number | BigNumber, Array":function(e,t){return l(n(t),e,this,!0).valueOf()},"Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber":function(e,t,n){for(var r=this(e,t),a=0;a{var{typed:t,config:n,Complex:r}=e;return t(name$3O,{number:function(e){return e>=0||n.predictable?log10Number(e):new r(e,0).log().div(Math.LN10)},Complex:function(e){return new r(e).log().div(Math.LN10)},BigNumber:function(e){return!e.isNegative()||n.predictable?e.log():new r(e.toNumber(),0).log().div(Math.LN10)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3N="log2",dependencies$3N=["typed","config","Complex"],createLog2=factory(name$3N,dependencies$3N,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$3N,{number:function(e){return e>=0||n.predictable?log2Number(e):a(new r(e,0))},Complex:a,BigNumber:function(e){return!e.isNegative()||n.predictable?e.log(2):a(new r(e.toNumber(),0))},"Array | Matrix":function(e){return deepMap(e,this)}});function a(e){var t=Math.sqrt(e.re*e.re+e.im*e.im);return new r(Math.log2?Math.log2(t):Math.log(t)/Math.LN2,Math.atan2(e.im,e.re)/Math.LN2)}})),name$3M="algorithm03",dependencies$3M=["typed"],createAlgorithm03=factory(name$3M,dependencies$3M,(e=>{var{typed:t}=e;return function(e,n,r,a){var i=e._data,o=e._size,s=e._datatype,l=n._values,u=n._index,c=n._ptr,p=n._size,d=n._datatype;if(o.length!==p.length)throw new DimensionError(o.length,p.length);if(o[0]!==p[0]||o[1]!==p[1])throw new RangeError("Dimension mismatch. Matrix A ("+o+") must match Matrix B ("+p+")");if(!l)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var m,f=o[0],h=o[1],y=0,b=r;"string"==typeof s&&s===d&&(m=s,y=t.convert(0,m),b=t.find(r,[m,m]));for(var g=[],v=0;v{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,o=e._index,s=e._ptr,l=e._size,u=e._datatype,c=r._values,p=r._index,d=r._ptr,m=r._size,f=r._datatype;if(l.length!==m.length)throw new DimensionError(l.length,m.length);if(l[0]!==m[0]||l[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+l+") must match Matrix B ("+m+")");var h,y=l[0],b=l[1],g=n,v=0,T=a;"string"==typeof u&&u===f&&(h=u,g=t.find(n,[h,h]),v=t.convert(0,h),T=t.find(a,[h,h]));var N,C,A,S,x=i&&c?[]:void 0,w=[],V=[],E=x?[]:void 0,O=x?[]:void 0,_=[],$=[];for(C=0;C{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:a}=e,i=createAlgorithm02({typed:t,equalScalar:r}),o=createAlgorithm03({typed:t}),s=createAlgorithm05({typed:t,equalScalar:r}),l=createAlgorithm11({typed:t,equalScalar:r}),u=createAlgorithm12({typed:t,DenseMatrix:a}),c=createAlgorithm13({typed:t}),p=createAlgorithm14({typed:t});return t(name$3K,{"number, number":modNumber,"BigNumber, BigNumber":function(e,t){if(t.isNeg())throw new Error("Cannot calculate mod for a negative divisor");return t.isZero()?e:e.mod(t)},"Fraction, Fraction":function(e,t){if(t.compare(0)<0)throw new Error("Cannot calculate mod for a negative divisor");return e.compare(0)>=0?e.mod(t):e.mod(t).add(t).mod(t)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return o(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return c(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return l(e,t,this,!1)},"DenseMatrix, any":function(e,t){return p(e,t,this,!1)},"any, SparseMatrix":function(e,t){return u(t,e,this,!0)},"any, DenseMatrix":function(e,t){return p(t,e,this,!0)},"Array, any":function(e,t){return p(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return p(n(t),e,this,!0).valueOf()}})})),name$3J="multiplyScalar",dependencies$3J=["typed"],createMultiplyScalar=factory(name$3J,dependencies$3J,(e=>{var{typed:t}=e;return t("multiplyScalar",{"number, number":multiplyNumber,"Complex, Complex":function(e,t){return e.mul(t)},"BigNumber, BigNumber":function(e,t){return e.times(t)},"Fraction, Fraction":function(e,t){return e.mul(t)},"number | Fraction | BigNumber | Complex, Unit":function(e,t){var n=t.clone();return n.value=null===n.value?n._normalize(e):this(n.value,e),n},"Unit, number | Fraction | BigNumber | Complex":function(e,t){var n=e.clone();return n.value=null===n.value?n._normalize(t):this(n.value,t),n},"Unit, Unit":function(e,t){return e.multiply(t)}})})),name$3I="multiply",dependencies$3I=["typed","matrix","addScalar","multiplyScalar","equalScalar","dot"],createMultiply=factory(name$3I,dependencies$3I,(e=>{var{typed:t,matrix:n,addScalar:r,multiplyScalar:a,equalScalar:i,dot:o}=e,s=createAlgorithm11({typed:t,equalScalar:i}),l=createAlgorithm14({typed:t});function u(e,t){switch(e.length){case 1:switch(t.length){case 1:if(e[0]!==t[0])throw new RangeError("Dimension mismatch in multiplication. Vectors must have the same length");break;case 2:if(e[0]!==t[0])throw new RangeError("Dimension mismatch in multiplication. Vector length ("+e[0]+") must match Matrix rows ("+t[0]+")");break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix B has "+t.length+" dimensions)")}break;case 2:switch(t.length){case 1:if(e[1]!==t[0])throw new RangeError("Dimension mismatch in multiplication. Matrix columns ("+e[1]+") must match Vector length ("+t[0]+")");break;case 2:if(e[1]!==t[0])throw new RangeError("Dimension mismatch in multiplication. Matrix A columns ("+e[1]+") must match Matrix B rows ("+t[0]+")");break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix B has "+t.length+" dimensions)")}break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix A has "+e.length+" dimensions)")}}function c(e,n){if("dense"!==n.storage())throw new Error("Support for SparseMatrix not implemented");return function(e,n){var i,o=e._data,s=e._size,l=e._datatype,u=n._data,c=n._size,p=n._datatype,d=s[0],m=c[1],f=r,h=a;l&&p&&l===p&&"string"==typeof l&&(i=l,f=t.find(r,[i,i]),h=t.find(a,[i,i]));for(var y=[],b=0;bw)for(var E=0,O=0;O{var{typed:t,matrix:n,equalScalar:r,BigNumber:a}=e,i=createAlgorithm01({typed:t}),o=createAlgorithm02({typed:t,equalScalar:r}),s=createAlgorithm06({typed:t,equalScalar:r}),l=createAlgorithm11({typed:t,equalScalar:r}),u=createAlgorithm13({typed:t}),c=createAlgorithm14({typed:t}),p="Complex number not supported in function nthRoot. Use nthRoots instead.";return t(name$3H,{number:nthRootNumber,"number, number":nthRootNumber,BigNumber:function(e){return d(e,new a(2))},Complex:function(e){throw new Error(p)},"Complex, number":function(e,t){throw new Error(p)},"BigNumber, BigNumber":d,"Array | Matrix":function(e){return this(e,2)},"SparseMatrix, SparseMatrix":function(e,t){if(1===t.density())return s(e,t,this);throw new Error("Root must be non-zero")},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){if(1===t.density())return i(e,t,this,!1);throw new Error("Root must be non-zero")},"DenseMatrix, DenseMatrix":function(e,t){return u(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return c(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){if(1===t.density())return l(t,e,this,!0);throw new Error("Root must be non-zero")},"number | BigNumber, DenseMatrix":function(e,t){return c(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return this(n(e),t).valueOf()},"number | BigNumber, Array":function(e,t){return this(e,n(t)).valueOf()}});function d(e,t){var n=a.precision,r=a.clone({precision:n+2}),i=new a(0),o=new r(1),s=t.isNegative();if(s&&(t=t.neg()),t.isZero())throw new Error("Root must be non-zero");if(e.isNegative()&&!t.abs().mod(2).equals(1))throw new Error("Root must be odd when a is negative.");if(e.isZero())return s?new r(1/0):0;if(!e.isFinite())return s?i:e;var l=e.abs().pow(o.div(t));return l=e.isNeg()?l.neg():l,new a((s?o.div(l):l).toPrecision(n))}})),name$3G="sign",dependencies$3G=["typed","BigNumber","Fraction","complex"],createSign=factory(name$3G,dependencies$3G,(e=>{var{typed:t,BigNumber:n,complex:r,Fraction:a}=e;return t(name$3G,{number:signNumber,Complex:function(e){return 0===e.im?r(signNumber(e.re)):e.sign()},BigNumber:function(e){return new n(e.cmp(0))},Fraction:function(e){return new a(e.s,1)},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){if(!e._isDerived()&&0!==e.units[0].unit.offset)throw new TypeError("sign is ambiguous for units with offset");return this(e.value)}})})),name$3F="sqrt",dependencies$3F=["config","typed","Complex"],createSqrt=factory(name$3F,dependencies$3F,(e=>{var{config:t,typed:n,Complex:r}=e;return n("sqrt",{number:a,Complex:function(e){return e.sqrt()},BigNumber:function(e){return!e.isNegative()||t.predictable?e.sqrt():a(e.toNumber())},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){return e.pow(.5)}});function a(e){return isNaN(e)?NaN:e>=0||t.predictable?Math.sqrt(e):new r(e,0).sqrt()}})),name$3E="square",dependencies$3E=["typed"],createSquare=factory(name$3E,dependencies$3E,(e=>{var{typed:t}=e;return t(name$3E,{number:squareNumber,Complex:function(e){return e.mul(e)},BigNumber:function(e){return e.times(e)},Fraction:function(e){return e.mul(e)},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){return e.pow(2)}})})),name$3D="subtract",dependencies$3D=["typed","matrix","equalScalar","addScalar","unaryMinus","DenseMatrix"],createSubtract=factory(name$3D,dependencies$3D,(e=>{var{typed:t,matrix:n,equalScalar:r,addScalar:a,unaryMinus:i,DenseMatrix:o}=e,s=createAlgorithm01({typed:t}),l=createAlgorithm03({typed:t}),u=createAlgorithm05({typed:t,equalScalar:r}),c=createAlgorithm10({typed:t,DenseMatrix:o}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$3D,{"number, number":function(e,t){return e-t},"Complex, Complex":function(e,t){return e.sub(t)},"BigNumber, BigNumber":function(e,t){return e.minus(t)},"Fraction, Fraction":function(e,t){return e.sub(t)},"Unit, Unit":function(e,t){if(null===e.value)throw new Error("Parameter x contains a unit with undefined value");if(null===t.value)throw new Error("Parameter y contains a unit with undefined value");if(!e.equalBase(t))throw new Error("Units do not match");var n=e.clone();return n.value=this(n.value,t.value),n.fixPrefix=!1,n},"SparseMatrix, SparseMatrix":function(e,t){return checkEqualDimensions(e,t),u(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return checkEqualDimensions(e,t),l(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return checkEqualDimensions(e,t),s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return checkEqualDimensions(e,t),p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return c(e,i(t),a)},"DenseMatrix, any":function(e,t){return d(e,t,this)},"any, SparseMatrix":function(e,t){return c(t,e,this,!0)},"any, DenseMatrix":function(e,t){return d(t,e,this,!0)},"Array, any":function(e,t){return d(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return d(n(t),e,this,!0).valueOf()}})}));function checkEqualDimensions(e,t){var n=e.size(),r=t.size();if(n.length!==r.length)throw new DimensionError(n.length,r.length)}var name$3C="xgcd",dependencies$3C=["typed","config","matrix","BigNumber"],createXgcd=factory(name$3C,dependencies$3C,(e=>{var{typed:t,config:n,matrix:r,BigNumber:a}=e;return t(name$3C,{"number, number":function(e,t){var a=xgcdNumber(e,t);return"Array"===n.matrix?a:r(a)},"BigNumber, BigNumber":function(e,t){var i,o,s,l,u=new a(0),c=new a(1),p=u,d=c,m=c,f=u;if(!e.isInt()||!t.isInt())throw new Error("Parameters in function xgcd must be integer numbers");for(;!t.isZero();)o=e.div(t).floor(),s=e.mod(t),i=p,p=d.minus(o.times(p)),d=i,i=m,m=f.minus(o.times(m)),f=i,e=t,t=s;return l=e.lt(u)?[e.neg(),d.neg(),f.neg()]:[e,e.isZero()?0:d,f],"Array"===n.matrix?l:r(l)}})})),name$3B="invmod",dependencies$3B=["typed","config","BigNumber","xgcd","equal","smaller","mod","add","isInteger"],createInvmod=factory(name$3B,dependencies$3B,(e=>{var{typed:t,config:n,BigNumber:r,xgcd:a,equal:i,smaller:o,mod:s,add:l,isInteger:u}=e;return t(name$3B,{"number, number":c,"BigNumber, BigNumber":c});function c(e,t){if(!u(e)||!u(t))throw new Error("Parameters in function invmod must be integer numbers");if(e=s(e,t),i(t,0))throw new Error("Divisor must be non zero");var n=a(e,t);n=n.valueOf();var[c,p]=n;return i(c,r(1))?(p=s(p,t),o(p,r(0))&&(p=l(p,t)),p):NaN}})),name$3A="algorithm09",dependencies$3A=["typed","equalScalar"],createAlgorithm09=factory(name$3A,dependencies$3A,(e=>{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,o=e._index,s=e._ptr,l=e._size,u=e._datatype,c=r._values,p=r._index,d=r._ptr,m=r._size,f=r._datatype;if(l.length!==m.length)throw new DimensionError(l.length,m.length);if(l[0]!==m[0]||l[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+l+") must match Matrix B ("+m+")");var h,y=l[0],b=l[1],g=n,v=0,T=a;"string"==typeof u&&u===f&&(h=u,g=t.find(n,[h,h]),v=t.convert(0,h),T=t.find(a,[h,h]));var N,C,A,S,x,w=i&&c?[]:void 0,V=[],E=[],O=w?[]:void 0,_=[];for(C=0;C{var{typed:t,matrix:n,equalScalar:r,multiplyScalar:a}=e,i=createAlgorithm02({typed:t,equalScalar:r}),o=createAlgorithm09({typed:t,equalScalar:r}),s=createAlgorithm11({typed:t,equalScalar:r}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$3z,{"any, any":a,"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,a,!1)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,a,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,a,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,a)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return s(e,t,a,!1)},"DenseMatrix, any":function(e,t){return u(e,t,a,!1)},"any, SparseMatrix":function(e,t){return s(t,e,a,!0)},"any, DenseMatrix":function(e,t){return u(t,e,a,!0)},"Array, any":function(e,t){return u(n(e),t,a,!1).valueOf()},"any, Array":function(e,t){return u(n(t),e,a,!0).valueOf()}})}));function bitAndBigNumber(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function bitAnd");var n=e.constructor;if(e.isNaN()||t.isNaN())return new n(NaN);if(e.isZero()||t.eq(-1)||e.eq(t))return e;if(t.isZero()||e.eq(-1))return t;if(!e.isFinite()||!t.isFinite()){if(!e.isFinite()&&!t.isFinite())return e.isNegative()===t.isNegative()?e:new n(0);if(!e.isFinite())return t.isNegative()?e:e.isNegative()?new n(0):t;if(!t.isFinite())return e.isNegative()?t:t.isNegative()?new n(0):e}return bitwise(e,t,(function(e,t){return e&t}))}function bitNotBigNumber(e){if(e.isFinite()&&!e.isInteger())throw new Error("Integer expected in function bitNot");var t=e.constructor,n=t.precision;t.config({precision:1e9});var r=e.plus(new t(1));return r.s=-r.s||null,t.config({precision:n}),r}function bitOrBigNumber(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function bitOr");var n=e.constructor;if(e.isNaN()||t.isNaN())return new n(NaN);var r=new n(-1);return e.isZero()||t.eq(r)||e.eq(t)?t:t.isZero()||e.eq(r)?e:e.isFinite()&&t.isFinite()?bitwise(e,t,(function(e,t){return e|t})):!e.isFinite()&&!e.isNegative()&&t.isNegative()||e.isNegative()&&!t.isNegative()&&!t.isFinite()?r:e.isNegative()&&t.isNegative()?e.isFinite()?e:t:e.isFinite()?t:e}function bitwise(e,t,n){var r,a,i,o,s,l=e.constructor,u=+(e.s<0),c=+(t.s<0);if(u){r=decCoefficientToBinaryString(bitNotBigNumber(e));for(var p=0;p0;)n(i[--m],o[--f])===h&&(y=y.plus(b)),b=b.times(g);for(;f>0;)n(s,o[--f])===h&&(y=y.plus(b)),b=b.times(g);return l.config({precision:v}),0===h&&(y.s=-y.s),y}function decCoefficientToBinaryString(e){for(var t=e.d,n=t[0]+"",r=1;r0)if(++s>u)for(s-=u;s--;)l+="0";else s1&&(null!==c[m+1]&&void 0!==c[m+1]||(c[m+1]=0),c[m+1]+=c[m]>>1,c[m]&=1)}return c.reverse()}function bitXor$1(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function bitXor");var n=e.constructor;if(e.isNaN()||t.isNaN())return new n(NaN);if(e.isZero())return t;if(t.isZero())return e;if(e.eq(t))return new n(0);var r=new n(-1);return e.eq(r)?bitNotBigNumber(t):t.eq(r)?bitNotBigNumber(e):e.isFinite()&&t.isFinite()?bitwise(e,t,(function(e,t){return e^t})):e.isFinite()||t.isFinite()?new n(e.isNegative()===t.isNegative()?1/0:-1/0):r}function leftShiftBigNumber(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function leftShift");var n=e.constructor;return e.isNaN()||t.isNaN()||t.isNegative()&&!t.isZero()?new n(NaN):e.isZero()||t.isZero()?e:e.isFinite()||t.isFinite()?t.lt(55)?e.times(Math.pow(2,t.toNumber())+""):e.times(new n(2).pow(t)):new n(NaN)}function rightArithShiftBigNumber(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function rightArithShift");var n=e.constructor;return e.isNaN()||t.isNaN()||t.isNegative()&&!t.isZero()?new n(NaN):e.isZero()||t.isZero()?e:t.isFinite()?t.lt(55)?e.div(Math.pow(2,t.toNumber())+"").floor():e.div(new n(2).pow(t)).floor():e.isNegative()?new n(-1):e.isFinite()?new n(0):new n(NaN)}var name$3y="bitAnd",dependencies$3y=["typed","matrix","equalScalar"],createBitAnd=factory(name$3y,dependencies$3y,(e=>{var{typed:t,matrix:n,equalScalar:r}=e,a=createAlgorithm02({typed:t,equalScalar:r}),i=createAlgorithm06({typed:t,equalScalar:r}),o=createAlgorithm11({typed:t,equalScalar:r}),s=createAlgorithm13({typed:t}),l=createAlgorithm14({typed:t});return t(name$3y,{"number, number":bitAndNumber,"BigNumber, BigNumber":bitAndBigNumber,"SparseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return a(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return a(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return s(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return l(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return l(t,e,this,!0)},"Array, any":function(e,t){return l(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return l(n(t),e,this,!0).valueOf()}})})),name$3x="bitNot",dependencies$3x=["typed"],createBitNot=factory(name$3x,dependencies$3x,(e=>{var{typed:t}=e;return t(name$3x,{number:bitNotNumber,BigNumber:bitNotBigNumber,"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3w="bitOr",dependencies$3w=["typed","matrix","equalScalar","DenseMatrix"],createBitOr=factory(name$3w,dependencies$3w,(e=>{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:a}=e,i=createAlgorithm01({typed:t}),o=createAlgorithm04({typed:t,equalScalar:r}),s=createAlgorithm10({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$3w,{"number, number":bitOrNumber,"BigNumber, BigNumber":bitOrBigNumber,"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return s(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return s(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(n(t),e,this,!0).valueOf()}})})),name$3v="algorithm07",dependencies$3v=["typed","DenseMatrix"],createAlgorithm07=factory(name$3v,dependencies$3v,(e=>{var{typed:t,DenseMatrix:n}=e;return function(e,a,i){var o=e._size,s=e._datatype,l=a._size,u=a._datatype;if(o.length!==l.length)throw new DimensionError(o.length,l.length);if(o[0]!==l[0]||o[1]!==l[1])throw new RangeError("Dimension mismatch. Matrix A ("+o+") must match Matrix B ("+l+")");var c,p,d,m=o[0],f=o[1],h=0,y=i;"string"==typeof s&&s===u&&(c=s,h=t.convert(0,c),y=t.find(i,[c,c]));var b=[];for(p=0;p{var{typed:t,matrix:n,DenseMatrix:r}=e,a=createAlgorithm03({typed:t}),i=createAlgorithm07({typed:t,DenseMatrix:r}),o=createAlgorithm12({typed:t,DenseMatrix:r}),s=createAlgorithm13({typed:t}),l=createAlgorithm14({typed:t});return t(name$3u,{"number, number":bitXorNumber,"BigNumber, BigNumber":bitXor$1,"SparseMatrix, SparseMatrix":function(e,t){return i(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return a(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return a(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return s(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return l(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return l(t,e,this,!0)},"Array, any":function(e,t){return l(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return l(n(t),e,this,!0).valueOf()}})})),name$3t="arg",dependencies$3t=["typed"],createArg=factory(name$3t,dependencies$3t,(e=>{var{typed:t}=e;return t(name$3t,{number:function(e){return Math.atan2(0,e)},BigNumber:function(e){return e.constructor.atan2(0,e)},Complex:function(e){return e.arg()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3s="conj",dependencies$3s=["typed"],createConj=factory(name$3s,dependencies$3s,(e=>{var{typed:t}=e;return t(name$3s,{number:function(e){return e},BigNumber:function(e){return e},Complex:function(e){return e.conjugate()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3r="im",dependencies$3r=["typed"],createIm=factory(name$3r,dependencies$3r,(e=>{var{typed:t}=e;return t(name$3r,{number:function(e){return 0},BigNumber:function(e){return e.mul(0)},Fraction:function(e){return e.mul(0)},Complex:function(e){return e.im},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3q="re",dependencies$3q=["typed"],createRe=factory(name$3q,dependencies$3q,(e=>{var{typed:t}=e;return t(name$3q,{number:function(e){return e},BigNumber:function(e){return e},Fraction:function(e){return e},Complex:function(e){return e.re},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3p="not",dependencies$3p=["typed"],createNot=factory(name$3p,dependencies$3p,(e=>{var{typed:t}=e;return t(name$3p,{number:notNumber,Complex:function(e){return 0===e.re&&0===e.im},BigNumber:function(e){return e.isZero()||e.isNaN()},Unit:function(e){return null===e.value||this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3o="or",dependencies$3o=["typed","matrix","equalScalar","DenseMatrix"],createOr=factory(name$3o,dependencies$3o,(e=>{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),o=createAlgorithm05({typed:t,equalScalar:r}),s=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$3o,{"number, number":orNumber,"Complex, Complex":function(e,t){return 0!==e.re||0!==e.im||0!==t.re||0!==t.im},"BigNumber, BigNumber":function(e,t){return!e.isZero()&&!e.isNaN()||!t.isZero()&&!t.isNaN()},"Unit, Unit":function(e,t){return this(e.value||0,t.value||0)},"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return s(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return s(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(n(t),e,this,!0).valueOf()}})})),name$3n="xor",dependencies$3n=["typed","matrix","DenseMatrix"],createXor=factory(name$3n,dependencies$3n,(e=>{var{typed:t,matrix:n,DenseMatrix:r}=e,a=createAlgorithm03({typed:t}),i=createAlgorithm07({typed:t,DenseMatrix:r}),o=createAlgorithm12({typed:t,DenseMatrix:r}),s=createAlgorithm13({typed:t}),l=createAlgorithm14({typed:t});return t(name$3n,{"number, number":xorNumber,"Complex, Complex":function(e,t){return(0!==e.re||0!==e.im)!=(0!==t.re||0!==t.im)},"BigNumber, BigNumber":function(e,t){return(!e.isZero()&&!e.isNaN())!=(!t.isZero()&&!t.isNaN())},"Unit, Unit":function(e,t){return this(e.value||0,t.value||0)},"SparseMatrix, SparseMatrix":function(e,t){return i(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return a(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return a(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return s(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return l(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return l(t,e,this,!0)},"Array, any":function(e,t){return l(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return l(n(t),e,this,!0).valueOf()}})})),name$3m="concat",dependencies$3m=["typed","matrix","isInteger"],createConcat=factory(name$3m,dependencies$3m,(e=>{var{typed:t,matrix:n,isInteger:r}=e;return t(name$3m,{"...Array | Matrix | number | BigNumber":function(e){var t,a,i=e.length,o=-1,s=!1,l=[];for(t=0;t0&&o>a)throw new IndexError(o,a+1)}else{var c=clone$2(u).valueOf(),p=arraySize(c);if(l[t]=c,a=o,o=p.length-1,t>0&&o!==a)throw new DimensionError(a+1,o+1)}}if(0===l.length)throw new SyntaxError("At least one matrix expected");for(var d=l.shift();l.length;)d=_concat(d,l.shift(),o,0);return s?n(d):d},"...string":function(e){return e.join("")}})}));function _concat(e,t,n,r){if(r{var{typed:t,Index:n,matrix:r,range:a}=e;return t(name$3l,{"Matrix, number":i,"Array, number":function(e,t){return i(r(clone$2(e)),t).valueOf()}});function i(e,t){if(2!==e.size().length)throw new Error("Only two dimensional matrix is supported");validateIndex(t,e.size()[1]);var r=a(0,e.size()[0]),i=new n(r,t);return e.subset(i)}})),name$3k="count",dependencies$3k=["typed","size","prod"],createCount=factory(name$3k,dependencies$3k,(e=>{var{typed:t,size:n,prod:r}=e;return t(name$3k,{string:function(e){return e.length},"Matrix | Array":function(e){return r(n(e))}})})),name$3j="cross",dependencies$3j=["typed","matrix","subtract","multiply"],createCross=factory(name$3j,dependencies$3j,(e=>{var{typed:t,matrix:n,subtract:r,multiply:a}=e;return t(name$3j,{"Matrix, Matrix":function(e,t){return n(i(e.toArray(),t.toArray()))},"Matrix, Array":function(e,t){return n(i(e.toArray(),t))},"Array, Matrix":function(e,t){return n(i(e,t.toArray()))},"Array, Array":i});function i(e,t){var n=Math.max(arraySize(e).length,arraySize(t).length);e=squeeze$1(e),t=squeeze$1(t);var i=arraySize(e),o=arraySize(t);if(1!==i.length||1!==o.length||3!==i[0]||3!==o[0])throw new RangeError("Vectors with length 3 expected (Size A = ["+i.join(", ")+"], B = ["+o.join(", ")+"])");var s=[r(a(e[1],t[2]),a(e[2],t[1])),r(a(e[2],t[0]),a(e[0],t[2])),r(a(e[0],t[1]),a(e[1],t[0]))];return n>1?[s]:s}})),name$3i="diag",dependencies$3i=["typed","matrix","DenseMatrix","SparseMatrix"],createDiag=factory(name$3i,dependencies$3i,(e=>{var{typed:t,matrix:n,DenseMatrix:r,SparseMatrix:a}=e;return t(name$3i,{Array:function(e){return i(e,0,arraySize(e),null)},"Array, number":function(e,t){return i(e,t,arraySize(e),null)},"Array, BigNumber":function(e,t){return i(e,t.toNumber(),arraySize(e),null)},"Array, string":function(e,t){return i(e,0,arraySize(e),t)},"Array, number, string":function(e,t,n){return i(e,t,arraySize(e),n)},"Array, BigNumber, string":function(e,t,n){return i(e,t.toNumber(),arraySize(e),n)},Matrix:function(e){return i(e,0,e.size(),e.storage())},"Matrix, number":function(e,t){return i(e,t,e.size(),e.storage())},"Matrix, BigNumber":function(e,t){return i(e,t.toNumber(),e.size(),e.storage())},"Matrix, string":function(e,t){return i(e,0,e.size(),t)},"Matrix, number, string":function(e,t,n){return i(e,t,e.size(),n)},"Matrix, BigNumber, string":function(e,t,n){return i(e,t.toNumber(),e.size(),n)}});function i(e,t,i,o){if(!isInteger$1(t))throw new TypeError("Second parameter in function diag must be an integer");var s=t>0?t:0,l=t<0?-t:0;switch(i.length){case 1:return function(e,t,n,i,o,s){var l=[i+o,i+s];if(n&&"sparse"!==n&&"dense"!==n)throw new TypeError("Unknown matrix type ".concat(n,'"'));var u="sparse"===n?a.diagonal(l,e,t):r.diagonal(l,e,t);return null!==n?u:u.valueOf()}(e,t,o,i[0],l,s);case 2:return function(e,t,r,a,i,o){if(isMatrix(e)){var s=e.diagonal(t);return null!==r?r!==s.storage()?n(s,r):s:s.valueOf()}for(var l=Math.min(a[0]-i,a[1]-o),u=[],c=0;c1&&void 0!==arguments[1]?arguments[1]:{};return n=null==n?Number.POSITIVE_INFINITY:n,t=null==t?JSON.stringify:t,function r(){"object"!=typeof r.cache&&(r.cache={values:new Map,lru:lruQueue(n||Number.POSITIVE_INFINITY)});for(var a=[],i=0;i{var{typed:t}=e;return t("filter",{"Array, function":_filterCallback,"Matrix, function":function(e,t){return e.create(_filterCallback(e.toArray(),t))},"Array, RegExp":filterRegExp,"Matrix, RegExp":function(e,t){return e.create(filterRegExp(e.toArray(),t))}})}));function _filterCallback(e,t){var n=maxArgumentCount(t);return filter$2(e,(function(e,r,a){return 1===n?t(e):2===n?t(e,[r]):t(e,[r],a)}))}var name$3g="flatten",dependencies$3g=["typed","matrix"],createFlatten=factory(name$3g,dependencies$3g,(e=>{var{typed:t,matrix:n}=e;return t(name$3g,{Array:function(e){return flatten$4(clone$2(e))},Matrix:function(e){var t=flatten$4(clone$2(e.toArray()));return n(t)}})})),name$3f="forEach",dependencies$3f=["typed"],createForEach=factory(name$3f,dependencies$3f,(e=>{var{typed:t}=e;return t(name$3f,{"Array, function":_forEach,"Matrix, function":function(e,t){return e.forEach(t)}})}));function _forEach(e,t){var n=maxArgumentCount(t);!function r(a,i){Array.isArray(a)?forEach$1(a,(function(e,t){r(e,i.concat(t))})):1===n?t(a):2===n?t(a,i):t(a,i,e)}(e,[])}var name$3e="getMatrixDataType",dependencies$3e=["typed"],createGetMatrixDataType=factory(name$3e,dependencies$3e,(e=>{var{typed:t}=e;return t(name$3e,{Array:function(e){return getArrayDataType(e,typeOf$1)},Matrix:function(e){return e.getDataType()}})})),name$3d="identity",dependencies$3d=["typed","config","matrix","BigNumber","DenseMatrix","SparseMatrix"],createIdentity=factory(name$3d,dependencies$3d,(e=>{var{typed:t,config:n,matrix:r,BigNumber:a,DenseMatrix:i,SparseMatrix:o}=e;return t(name$3d,{"":function(){return"Matrix"===n.matrix?r([]):[]},string:function(e){return r(e)},"number | BigNumber":function(e){return l(e,e,"Matrix"===n.matrix?"dense":void 0)},"number | BigNumber, string":function(e,t){return l(e,e,t)},"number | BigNumber, number | BigNumber":function(e,t){return l(e,t,"Matrix"===n.matrix?"dense":void 0)},"number | BigNumber, number | BigNumber, string":function(e,t,n){return l(e,t,n)},Array:function(e){return s(e)},"Array, string":function(e,t){return s(e,t)},Matrix:function(e){return s(e.valueOf(),e.storage())},"Matrix, string":function(e,t){return s(e.valueOf(),t)}});function s(e,t){switch(e.length){case 0:return t?r(t):[];case 1:return l(e[0],e[0],t);case 2:return l(e[0],e[1],t);default:throw new Error("Vector containing two values expected")}}function l(e,t,n){var r=isBigNumber(e)||isBigNumber(t)?a:null;if(isBigNumber(e)&&(e=e.toNumber()),isBigNumber(t)&&(t=t.toNumber()),!isInteger$1(e)||e<1)throw new Error("Parameters in function identity must be positive integers");if(!isInteger$1(t)||t<1)throw new Error("Parameters in function identity must be positive integers");var s=r?new a(1):1,l=r?new r(0):0,u=[e,t];if(n){if("sparse"===n)return o.diagonal(u,s,0,l);if("dense"===n)return i.diagonal(u,s,0,l);throw new TypeError('Unknown matrix type "'.concat(n,'"'))}for(var c=resize$1([],u,l),p=e{var{typed:t,matrix:n,multiplyScalar:r}=e;return t(name$3c,{"Matrix, Matrix":function(e,t){return n(a(e.toArray(),t.toArray()))},"Matrix, Array":function(e,t){return n(a(e.toArray(),t))},"Array, Matrix":function(e,t){return n(a(e,t.toArray()))},"Array, Array":a});function a(e,t){if(1===arraySize(e).length&&(e=[e]),1===arraySize(t).length&&(t=[t]),arraySize(e).length>2||arraySize(t).length>2)throw new RangeError("Vectors with dimensions greater then 2 are not supported expected (Size x = "+JSON.stringify(e.length)+", y = "+JSON.stringify(t.length)+")");var n=[],a=[];return e.map((function(e){return t.map((function(t){return a=[],n.push(a),e.map((function(e){return t.map((function(t){return a.push(r(e,t))}))}))}))}))&&n}})),name$3b="map",dependencies$3b=["typed"],createMap=factory(name$3b,dependencies$3b,(e=>{var{typed:t}=e;return t(name$3b,{"Array, function":_map$1,"Matrix, function":function(e,t){return e.map(t)}})}));function _map$1(e,t){var n=maxArgumentCount(t);return function r(a,i){if(Array.isArray(a))return a.map((function(e,t){return r(e,i.concat(t))}));try{return 1===n?t(a):2===n?t(a,i):t(a,i,e)}catch(t){if(t instanceof TypeError&&"data"in t&&"wrongType"===t.data.category){var o="map attempted to call '".concat(t.data.fn,"(").concat(a),s=JSON.stringify(i);throw 2===n?o+=","+s:1!==n&&(o+=",".concat(s,",").concat(e)),o+=")' but argument ".concat(t.data.index+1," of type "),o+="".concat(t.data.actual," does not match expected type "),o+=t.data.expected.join(" or "),new TypeError(o)}throw t}}(e,[])}var name$3a="diff",dependencies$3a=["typed","matrix","subtract","number"],createDiff=factory(name$3a,dependencies$3a,(e=>{var{typed:t,matrix:n,subtract:r,number:a}=e;return t(name$3a,{"Array | Matrix":function(e){return isMatrix(e)?n(o(e.toArray())):o(e)},"Array | Matrix, number":function(e,t){if(!isInteger$1(t))throw new RangeError("Dimension must be a whole number");return isMatrix(e)?n(i(e.toArray(),t)):i(e,t)},"Array | Matrix, BigNumber":function(e,t){return this(e,a(t))}});function i(e,t){if(isMatrix(e)&&(e=e.toArray()),!Array.isArray(e))throw RangeError("Array/Matrix does not have that many dimensions");if(t>0){var n=[];return e.forEach((e=>{n.push(i(e,t-1))})),n}if(0===t)return o(e);throw RangeError("Cannot have negative dimension")}function o(e){var t=[],n=e.length;if(n<2)return e;for(var r=1;r{var{typed:t,config:n,matrix:r,BigNumber:a}=e;return t("ones",{"":function(){return"Array"===n.matrix?i([]):i([],"default")},"...number | BigNumber | string":function(e){if("string"==typeof e[e.length-1]){var t=e.pop();return i(e,t)}return"Array"===n.matrix?i(e):i(e,"default")},Array:i,Matrix:function(e){var t=e.storage();return i(e.valueOf(),t)},"Array | Matrix, string":function(e,t){return i(e.valueOf(),t)}});function i(e,t){var n=function(e){var t=!1;return e.forEach((function(e,n,r){isBigNumber(e)&&(t=!0,r[n]=e.toNumber())})),t}(e),i=n?new a(1):1;if(function(e){e.forEach((function(e){if("number"!=typeof e||!isInteger$1(e)||e<0)throw new Error("Parameters in function ones must be positive integers")}))}(e),t){var o=r(t);return e.length>0?o.resize(e,i):o}var s=[];return e.length>0?resize$1(s,e,i):s}}));function noBignumber(){throw new Error('No "bignumber" implementation available')}function noFraction(){throw new Error('No "fraction" implementation available')}function noMatrix(){throw new Error('No "matrix" implementation available')}var name$38="range",dependencies$38=["typed","config","?matrix","?bignumber","smaller","smallerEq","larger","largerEq"],createRange=factory(name$38,dependencies$38,(e=>{var{typed:t,config:n,matrix:r,bignumber:a,smaller:i,smallerEq:o,larger:s,largerEq:l}=e;return t(name$38,{string:c,"string, boolean":c,"number, number":function(e,t){return u(p(e,t,1))},"number, number, number":function(e,t,n){return u(p(e,t,n))},"number, number, boolean":function(e,t,n){return u(n?d(e,t,1):p(e,t,1))},"number, number, number, boolean":function(e,t,n,r){return u(r?d(e,t,n):p(e,t,n))},"BigNumber, BigNumber":function(e,t){return u(m(e,t,new e.constructor(1)))},"BigNumber, BigNumber, BigNumber":function(e,t,n){return u(m(e,t,n))},"BigNumber, BigNumber, boolean":function(e,t,n){var r=e.constructor;return u(n?f(e,t,new r(1)):m(e,t,new r(1)))},"BigNumber, BigNumber, BigNumber, boolean":function(e,t,n,r){return u(r?f(e,t,n):m(e,t,n))}});function u(e){return"Matrix"===n.matrix?r?r(e):noMatrix():e}function c(e,t){var r=function(e){var t=e.split(":").map((function(e){return Number(e)}));if(t.some((function(e){return isNaN(e)})))return null;switch(t.length){case 2:return{start:t[0],end:t[1],step:1};case 3:return{start:t[0],end:t[2],step:t[1]};default:return null}}(e);if(!r)throw new SyntaxError('String "'+e+'" is no valid range');return"BigNumber"===n.number?(void 0===a&&noBignumber(),u((t?f:m)(a(r.start),a(r.end),a(r.step)))):u((t?d:p)(r.start,r.end,r.step))}function p(e,t,n){var r=[],a=e;if(n>0)for(;i(a,t);)r.push(a),a+=n;else if(n<0)for(;s(a,t);)r.push(a),a+=n;return r}function d(e,t,n){var r=[],a=e;if(n>0)for(;o(a,t);)r.push(a),a+=n;else if(n<0)for(;l(a,t);)r.push(a),a+=n;return r}function m(e,t,n){var r=a(0),o=[],l=e;if(n.gt(r))for(;i(l,t);)o.push(l),l=l.plus(n);else if(n.lt(r))for(;s(l,t);)o.push(l),l=l.plus(n);return o}function f(e,t,n){var r=a(0),i=[],s=e;if(n.gt(r))for(;o(s,t);)i.push(s),s=s.plus(n);else if(n.lt(r))for(;l(s,t);)i.push(s),s=s.plus(n);return i}})),name$37="reshape",dependencies$37=["typed","isInteger","matrix"],createReshape=factory(name$37,dependencies$37,(e=>{var{typed:t,isInteger:n}=e;return t(name$37,{"Matrix, Array":function(e,t){return e.reshape(t)},"Array, Array":function(e,t){return t.forEach((function(e){if(!n(e))throw new TypeError("Invalid size for dimension: "+e)})),reshape$1(e,t)}})}));function ArgumentsError(e,t,n,r){if(!(this instanceof ArgumentsError))throw new SyntaxError("Constructor must be called with the new operator");this.fn=e,this.count=t,this.min=n,this.max=r,this.message="Wrong number of arguments in function "+e+" ("+t+" provided, "+n+(null!=r?"-"+r:"")+" expected)",this.stack=(new Error).stack}ArgumentsError.prototype=new Error,ArgumentsError.prototype.constructor=Error,ArgumentsError.prototype.name="ArgumentsError",ArgumentsError.prototype.isArgumentsError=!0;var name$36="resize",dependencies$36=["config","matrix"],createResize=factory(name$36,dependencies$36,(e=>{var{config:t,matrix:n}=e;return function(e,a,i){if(2!==arguments.length&&3!==arguments.length)throw new ArgumentsError("resize",arguments.length,2,3);if(isMatrix(a)&&(a=a.valueOf()),isBigNumber(a[0])&&(a=a.map((function(e){return isBigNumber(e)?e.toNumber():e}))),isMatrix(e))return e.resize(a,i,!0);if("string"==typeof e)return r(e,a,i);var o=!Array.isArray(e)&&"Array"!==t.matrix;if(0===a.length){for(;Array.isArray(e);)e=e[0];return clone$2(e)}Array.isArray(e)||(e=[e]);var s=resize$1(e=clone$2(e),a,i);return o?n(s):s};function r(e,t,n){if(void 0!==n){if("string"!=typeof n||1!==n.length)throw new TypeError("Single character expected as defaultValue")}else n=" ";if(1!==t.length)throw new DimensionError(t.length,1);var r=t[0];if("number"!=typeof r||!isInteger$1(r))throw new TypeError("Invalid size, must contain positive integers (size: "+format$1(t)+")");if(e.length>r)return e.substring(0,r);if(e.length{var{typed:t,multiply:n,rotationMatrix:r}=e;return t(name$35,{"Array , number | BigNumber | Complex | Unit":function(e,t){return a(e,2),n(r(t),e).toArray()},"Matrix , number | BigNumber | Complex | Unit":function(e,t){return a(e,2),n(r(t),e)},"Array, number | BigNumber | Complex | Unit, Array | Matrix":function(e,t,i){return a(e,3),n(r(t,i),e)},"Matrix, number | BigNumber | Complex | Unit, Array | Matrix":function(e,t,i){return a(e,3),n(r(t,i),e)}});function a(e,t){var n=Array.isArray(e)?arraySize(e):e.size();if(n.length>2)throw new RangeError("Vector must be of dimensions 1x".concat(t));if(2===n.length&&1!==n[1])throw new RangeError("Vector must be of dimensions 1x".concat(t));if(n[0]!==t)throw new RangeError("Vector must be of dimensions 1x".concat(t))}})),name$34="rotationMatrix",dependencies$34=["typed","config","multiplyScalar","addScalar","unaryMinus","norm","matrix","BigNumber","DenseMatrix","SparseMatrix","cos","sin"],createRotationMatrix=factory(name$34,dependencies$34,(e=>{var{typed:t,config:n,multiplyScalar:r,addScalar:a,unaryMinus:i,norm:o,BigNumber:s,matrix:l,DenseMatrix:u,SparseMatrix:c,cos:p,sin:d}=e;return t(name$34,{"":function(){return"Matrix"===n.matrix?l([]):[]},string:function(e){return l(e)},"number | BigNumber | Complex | Unit":function(e){return m(e,"Matrix"===n.matrix?"dense":void 0)},"number | BigNumber | Complex | Unit, string":function(e,t){return m(e,t)},"number | BigNumber | Complex | Unit, Array":function(e,t){var n=l(t);return f(n),b(e,n,void 0)},"number | BigNumber | Complex | Unit, Matrix":function(e,t){f(t);var r=t.storage()||("Matrix"===n.matrix?"dense":void 0);return b(e,t,r)},"number | BigNumber | Complex | Unit, Array, string":function(e,t,n){var r=l(t);return f(r),b(e,r,n)},"number | BigNumber | Complex | Unit, Matrix, string":function(e,t,n){return f(t),b(e,t,n)}});function m(e,t){var n=isBigNumber(e)?new s(-1):-1,a=p(e),i=d(e);return y([[a,r(n,i)],[i,a]],t)}function f(e){var t=e.size();if(t.length<1||3!==t[0])throw new RangeError("Vector must be of dimensions 1x3")}function h(e){return e.reduce(((e,t)=>r(e,t)))}function y(e,t){if(t){if("sparse"===t)return new c(e);if("dense"===t)return new u(e);throw new TypeError('Unknown matrix type "'.concat(t,'"'))}return e}function b(e,t,n){var r=o(t);if(0===r)throw new RangeError("Rotation around zero vector");var l=isBigNumber(e)?s:null,u=l?new l(1):1,c=l?new l(-1):-1,m=l?new l(t.get([0])/r):t.get([0])/r,f=l?new l(t.get([1])/r):t.get([1])/r,b=l?new l(t.get([2])/r):t.get([2])/r,g=p(e),v=a(u,i(g)),T=d(e);return y([[a(g,h([m,m,v])),a(h([m,f,v]),h([c,b,T])),a(h([m,b,v]),h([f,T]))],[a(h([m,f,v]),h([b,T])),a(g,h([f,f,v])),a(h([f,b,v]),h([c,m,T]))],[a(h([m,b,v]),h([c,f,T])),a(h([f,b,v]),h([m,T])),a(g,h([b,b,v]))]],n)}})),name$33="row",dependencies$33=["typed","Index","matrix","range"],createRow=factory(name$33,dependencies$33,(e=>{var{typed:t,Index:n,matrix:r,range:a}=e;return t(name$33,{"Matrix, number":i,"Array, number":function(e,t){return i(r(clone$2(e)),t).valueOf()}});function i(e,t){if(2!==e.size().length)throw new Error("Only two dimensional matrix is supported");validateIndex(t,e.size()[0]);var r=a(0,e.size()[1]),i=new n(t,r);return e.subset(i)}})),name$32="size",dependencies$32=["typed","config","?matrix"],createSize=factory(name$32,dependencies$32,(e=>{var{typed:t,config:n,matrix:r}=e;return t(name$32,{Matrix:function(e){return e.create(e.size())},Array:arraySize,string:function(e){return"Array"===n.matrix?[e.length]:r([e.length])},"number | Complex | BigNumber | Unit | boolean | null":function(e){return"Array"===n.matrix?[]:r?r([]):noMatrix()}})})),name$31="squeeze",dependencies$31=["typed","matrix"],createSqueeze=factory(name$31,dependencies$31,(e=>{var{typed:t,matrix:n}=e;return t(name$31,{Array:function(e){return squeeze$1(clone$2(e))},Matrix:function(e){var t=squeeze$1(e.toArray());return Array.isArray(t)?n(t):t},any:function(e){return clone$2(e)}})})),name$30="subset",dependencies$30=["typed","matrix"],createSubset=factory(name$30,dependencies$30,(e=>{var{typed:t,matrix:n}=e;return t(name$30,{"Array, Index":function(e,t){var r=n(e).subset(t);return t.isScalar()?r:r.valueOf()},"Matrix, Index":function(e,t){return e.subset(t)},"Object, Index":_getObjectProperty,"string, Index":_getSubstring,"Array, Index, any":function(e,t,r){return n(clone$2(e)).subset(t,r,void 0).valueOf()},"Array, Index, any, any":function(e,t,r,a){return n(clone$2(e)).subset(t,r,a).valueOf()},"Matrix, Index, any":function(e,t,n){return e.clone().subset(t,n)},"Matrix, Index, any, any":function(e,t,n,r){return e.clone().subset(t,n,r)},"string, Index, string":_setSubstring,"string, Index, string, string":_setSubstring,"Object, Index, any":_setObjectProperty})}));function _getSubstring(e,t){if(!isIndex(t))throw new TypeError("Index expected");if(1!==t.size().length)throw new DimensionError(t.size().length,1);var n=e.length;validateIndex(t.min()[0],n),validateIndex(t.max()[0],n);var r=t.dimension(0),a="";return r.forEach((function(t){a+=e.charAt(t)})),a}function _setSubstring(e,t,n,r){if(!t||!0!==t.isIndex)throw new TypeError("Index expected");if(1!==t.size().length)throw new DimensionError(t.size().length,1);if(void 0!==r){if("string"!=typeof r||1!==r.length)throw new TypeError("Single character expected as defaultValue")}else r=" ";var a=t.dimension(0);if(a.size()[0]!==n.length)throw new DimensionError(a.size()[0],n.length);var i=e.length;validateIndex(t.min()[0]),validateIndex(t.max()[0]);for(var o=[],s=0;si)for(var l=i-1,u=o.length;l{var{typed:t,matrix:n}=e;return t("transpose",{Array:function(e){return this(n(e)).valueOf()},Matrix:function(e){var t,n=e.size();switch(n.length){case 1:t=e.clone();break;case 2:var r=n[0],a=n[1];if(0===a)throw new RangeError("Cannot transpose a 2D matrix with no columns (size: "+format$1(n)+")");switch(e.storage()){case"dense":t=function(e,t,n){for(var r,a=e._data,i=[],o=0;o{var{typed:t,transpose:n,conj:r}=e;return t(name$2_,{any:function(e){return r(n(e))}})})),name$2Z="zeros",dependencies$2Z=["typed","config","matrix","BigNumber"],createZeros=factory(name$2Z,dependencies$2Z,(e=>{var{typed:t,config:n,matrix:r,BigNumber:a}=e;return t(name$2Z,{"":function(){return"Array"===n.matrix?i([]):i([],"default")},"...number | BigNumber | string":function(e){if("string"==typeof e[e.length-1]){var t=e.pop();return i(e,t)}return"Array"===n.matrix?i(e):i(e,"default")},Array:i,Matrix:function(e){var t=e.storage();return i(e.valueOf(),t)},"Array | Matrix, string":function(e,t){return i(e.valueOf(),t)}});function i(e,t){var n=function(e){var t=!1;return e.forEach((function(e,n,r){isBigNumber(e)&&(t=!0,r[n]=e.toNumber())})),t}(e),i=n?new a(0):0;if(function(e){e.forEach((function(e){if("number"!=typeof e||!isInteger$1(e)||e<0)throw new Error("Parameters in function zeros must be positive integers")}))}(e),t){var o=r(t);return e.length>0?o.resize(e,i):o}var s=[];return e.length>0?resize$1(s,e,i):s}})),name$2Y="fft",dependencies$2Y=["typed","matrix","addScalar","multiplyScalar","divideScalar","exp","tau","i"],createFft=factory(name$2Y,dependencies$2Y,(e=>{var{typed:t,matrix:n,addScalar:r,multiplyScalar:a,divideScalar:i,exp:o,tau:s,i:l}=e;return t(name$2Y,{Array:u,Matrix:function(e){return e.create(u(e.toArray()))}});function u(e){var t=arraySize(e);return 1===t.length?p(e,t[0]):c(e.map((e=>u(e,t.slice(1)))),0)}function c(e,t){var n=arraySize(e);if(0!==t)return new Array(n[0]).fill(0).map(((n,r)=>c(e[r],t-1)));if(1===n.length)return p(e);function r(e){var t=arraySize(e);return new Array(t[1]).fill(0).map(((n,r)=>new Array(t[0]).fill(0).map(((t,n)=>e[n][r]))))}return r(c(r(e),1))}function p(e){var t=e.length;if(1===t)return[e[0]];if(t%2==0){for(var n=[...p(e.filter(((e,t)=>t%2==0))),...p(e.filter(((e,t)=>t%2==1)))],u=0;u{var{typed:t,fft:n,dotDivide:r,conj:a}=e;return t(name$2X,{"Array | Matrix":function(e){var t=isMatrix(e)?e.size():arraySize(e);return r(a(n(a(e))),t.reduce(((e,t)=>e*t),1))}})})),name$2W="erf",dependencies$2W=["typed"],createErf=factory(name$2W,dependencies$2W,(e=>{var{typed:t}=e;return t("name",{number:function(e){var t=Math.abs(e);return t>=MAX_NUM?sign$2(e):t<=THRESH?sign$2(e)*function(e){var t,n=e*e,r=P[0][4]*n,a=n;for(t=0;t<3;t+=1)r=(r+P[0][t])*n,a=(a+Q[0][t])*n;return e*(r+P[0][3])/(a+Q[0][3])}(t):t<=4?sign$2(e)*(1-function(e){var t,n=P[1][8]*e,r=e;for(t=0;t<7;t+=1)n=(n+P[1][t])*e,r=(r+Q[1][t])*e;var a=(n+P[1][7])/(r+Q[1][7]),i=parseInt(16*e)/16,o=(e-i)*(e+i);return Math.exp(-i*i)*Math.exp(-o)*a}(t)):sign$2(e)*(1-function(e){var t,n=1/(e*e),r=P[2][5]*n,a=n;for(t=0;t<4;t+=1)r=(r+P[2][t])*n,a=(a+Q[2][t])*n;var i=n*(r+P[2][4])/(a+Q[2][4]);i=(SQRPI-i)/e;var o=(e-(n=parseInt(16*e)/16))*(e+n);return Math.exp(-n*n)*Math.exp(-o)*i}(t))},"Array | Matrix":function(e){return deepMap(e,this)}})})),THRESH=.46875,SQRPI=.5641895835477563,P=[[3.1611237438705655,113.86415415105016,377.485237685302,3209.3775891384694,.18577770618460315],[.5641884969886701,8.883149794388377,66.11919063714163,298.6351381974001,881.952221241769,1712.0476126340707,2051.0783778260716,1230.3393547979972,2.1531153547440383e-8],[.30532663496123236,.36034489994980445,.12578172611122926,.016083785148742275,.0006587491615298378,.016315387137302097]],Q=[[23.601290952344122,244.02463793444417,1282.6165260773723,2844.236833439171],[15.744926110709835,117.6939508913125,537.1811018620099,1621.3895745666903,3290.7992357334597,4362.619090143247,3439.3676741437216,1230.3393548037495],[2.568520192289822,1.8729528499234604,.5279051029514285,.06051834131244132,.0023352049762686918]],MAX_NUM=Math.pow(2,53),name$2V="mode",dependencies$2V=["typed","isNaN","isNumeric"],createMode=factory(name$2V,dependencies$2V,(e=>{var{typed:t,isNaN:n,isNumeric:r}=e;return t(name$2V,{"Array | Matrix":a,"...":function(e){return a(e)}});function a(e){if(0===(e=flatten$4(e.valueOf())).length)throw new Error("Cannot calculate mode of an empty array");for(var t={},a=[],i=0,o=0;oi&&(i=t[s],a=[s])}return a}}));function improveErrorMessage(e,t,n){var r;return-1!==String(e).indexOf("Unexpected type")?(r=arguments.length>2?" (type: "+typeOf$1(n)+", value: "+JSON.stringify(n)+")":" (type: "+e.data.actual+")",new TypeError("Cannot calculate "+t+", unexpected type of argument"+r)):-1!==String(e).indexOf("complex numbers")?(r=arguments.length>2?" (type: "+typeOf$1(n)+", value: "+JSON.stringify(n)+")":"",new TypeError("Cannot calculate "+t+", no ordering relation is defined for complex numbers"+r)):e}var name$2U="prod",dependencies$2U=["typed","config","multiplyScalar","numeric"],createProd=factory(name$2U,dependencies$2U,(e=>{var{typed:t,config:n,multiplyScalar:r,numeric:a}=e;return t(name$2U,{"Array | Matrix":i,"Array | Matrix, number | BigNumber":function(e,t){throw new Error("prod(A, dim) is not yet supported")},"...":function(e){return i(e)}});function i(e){var t;if(deepForEach(e,(function(e){try{t=void 0===t?e:r(t,e)}catch(t){throw improveErrorMessage(t,"prod",e)}})),"string"==typeof t&&(t=a(t,n.number)),void 0===t)throw new Error("Cannot calculate prod of an empty array");return t}})),name$2T="format",dependencies$2T=["typed"],createFormat=factory(name$2T,dependencies$2T,(e=>{var{typed:t}=e;return t(name$2T,{any:format$1,"any, Object | function | number":format$1})})),name$2S="bin",dependencies$2S=["typed","format"],createBin=factory(name$2S,dependencies$2S,(e=>{var{typed:t,format:n}=e;return t(name$2S,{"number | BigNumber":function(e){return n(e,{notation:"bin"})},"number | BigNumber, number":function(e,t){return n(e,{notation:"bin",wordSize:t})}})})),name$2R="oct",dependencies$2R=["typed","format"],createOct=factory(name$2R,dependencies$2R,(e=>{var{typed:t,format:n}=e;return t(name$2R,{"number | BigNumber":function(e){return n(e,{notation:"oct"})},"number | BigNumber, number":function(e,t){return n(e,{notation:"oct",wordSize:t})}})})),name$2Q="hex",dependencies$2Q=["typed","format"],createHex=factory(name$2Q,dependencies$2Q,(e=>{var{typed:t,format:n}=e;return t(name$2Q,{"number | BigNumber":function(e){return n(e,{notation:"hex"})},"number | BigNumber, number":function(e,t){return n(e,{notation:"hex",wordSize:t})}})})),name$2P="print",dependencies$2P=["typed"],createPrint=factory(name$2P,dependencies$2P,(e=>{var{typed:t}=e;return t(name$2P,{"string, Object | Array":_print,"string, Object | Array, number | Object":_print})}));function _print(e,t,n){return e.replace(/\$([\w.]+)/g,(function(e,r){for(var a=r.split("."),i=t[a.shift()];a.length&&void 0!==i;){var o=a.shift();i=o?i[o]:i+"."}return void 0!==i?isString$1(i)?i:format$1(i,n):e}))}var name$2O="to",dependencies$2O=["typed","matrix"],createTo=factory(name$2O,dependencies$2O,(e=>{var{typed:t,matrix:n}=e,r=createAlgorithm13({typed:t}),a=createAlgorithm14({typed:t});return t(name$2O,{"Unit, Unit | string":function(e,t){return e.to(t)},"Matrix, Matrix":function(e,t){return r(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"Matrix, any":function(e,t){return a(e,t,this,!1)},"any, Matrix":function(e,t){return a(t,e,this,!0)},"Array, any":function(e,t){return a(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return a(n(t),e,this,!0).valueOf()}})})),name$2N="isPrime",dependencies$2N=["typed"],createIsPrime=factory(name$2N,dependencies$2N,(e=>{var{typed:t}=e;return t(name$2N,{number:function(e){if(0*e!=0)return!1;if(e<=3)return e>1;if(e%2==0||e%3==0)return!1;for(var t=5;t*t<=e;t+=6)if(e%t==0||e%(t+2)==0)return!1;return!0},BigNumber:function(e){if(0*e.toNumber()!=0)return!1;if(e.lte(3))return e.gt(1);if(e.mod(2).eq(0)||e.mod(3).eq(0))return!1;if(e.lt(Math.pow(2,32))){for(var t=e.toNumber(),n=5;n*n<=t;n+=6)if(t%n==0||t%(n+2)==0)return!1;return!0}function r(e,t,n){for(var r=1;!t.eq(0);)t.mod(2).eq(0)?(t=t.div(2),e=e.mul(e).mod(n)):(t=t.sub(1),r=e.mul(r).mod(n));return r}for(var a=e.constructor.clone({precision:2*e.toFixed(0).length}),i=0,o=(e=new a(e)).sub(1);o.mod(2).eq(0);)o=o.div(2),i+=1;var s=null;if(e.lt("3317044064679887385961981"))s=[2,3,5,7,11,13,17,19,23,29,31,37,41].filter((t=>t{var{number:t,bignumber:n,fraction:r}=e,a={string:!0,number:!0,BigNumber:!0,Fraction:!0},i={number:e=>t(e),BigNumber:n?e=>n(e):noBignumber,Fraction:r?e=>r(e):noFraction};return function(e,t){var n=typeOf$1(e);if(!(n in a))throw new TypeError("Cannot convert "+e+' of type "'+n+'"; valid input types are '+Object.keys(a).join(", "));if(!(t in i))throw new TypeError("Cannot convert "+e+' to type "'+t+'"; valid output types are '+Object.keys(i).join(", "));return t===n?e:i[t](e)}})),name$2L="divideScalar",dependencies$2L=["typed","numeric"],createDivideScalar=factory(name$2L,dependencies$2L,(e=>{var{typed:t,numeric:n}=e;return t(name$2L,{"number, number":function(e,t){return e/t},"Complex, Complex":function(e,t){return e.div(t)},"BigNumber, BigNumber":function(e,t){return e.div(t)},"Fraction, Fraction":function(e,t){return e.div(t)},"Unit, number | Fraction | BigNumber":function(e,t){var r=e.clone(),a=n(1,typeOf$1(t));return r.value=this(null===r.value?r._normalize(a):r.value,t),r},"number | Fraction | BigNumber, Unit":function(e,t){var r=t.clone();r=r.pow(-1);var a=n(1,typeOf$1(e));return r.value=this(e,null===t.value?t._normalize(a):t.value),r},"Unit, Unit":function(e,t){return e.divide(t)}})})),name$2K="pow",dependencies$2K=["typed","config","identity","multiply","matrix","inv","fraction","number","Complex"],createPow=factory(name$2K,dependencies$2K,(e=>{var{typed:t,config:n,identity:r,multiply:a,matrix:i,inv:o,number:s,fraction:l,Complex:u}=e;return t(name$2K,{"number, number":c,"Complex, Complex":function(e,t){return e.pow(t)},"BigNumber, BigNumber":function(e,t){return t.isInteger()||e>=0||n.predictable?e.pow(t):new u(e.toNumber(),0).pow(t.toNumber(),0)},"Fraction, Fraction":function(e,t){var r=e.pow(t);if(null!=r)return r;if(n.predictable)throw new Error("Result of pow is non-rational and cannot be expressed as a fraction");return c(e.valueOf(),t.valueOf())},"Array, number":p,"Array, BigNumber":function(e,t){return p(e,t.toNumber())},"Matrix, number":d,"Matrix, BigNumber":function(e,t){return d(e,t.toNumber())},"Unit, number | BigNumber":function(e,t){return e.pow(t)}});function c(e,t){if(n.predictable&&!isInteger$1(t)&&e<0)try{var r=l(t),a=s(r);if((t===a||Math.abs((t-a)/t)<1e-14)&&r.d%2==1)return(r.n%2==0?1:-1)*Math.pow(-e,t)}catch(e){}return n.predictable&&(e<-1&&t===1/0||e>-1&&e<0&&t===-1/0)?NaN:isInteger$1(t)||e>=0||n.predictable?powNumber(e,t):e*e<1&&t===1/0||e*e>1&&t===-1/0?0:new u(e,0).pow(t,0)}function p(e,t){if(!isInteger$1(t))throw new TypeError("For A^b, b must be an integer (value is "+t+")");var n=arraySize(e);if(2!==n.length)throw new Error("For A^b, A must be 2 dimensional (A has "+n.length+" dimensions)");if(n[0]!==n[1])throw new Error("For A^b, A must be square (size is "+n[0]+"x"+n[1]+")");if(t<0)try{return p(o(e),-t)}catch(e){if("Cannot calculate inverse, determinant is zero"===e.message)throw new TypeError("For A^b, when A is not invertible, b must be a positive integer (value is "+t+")");throw e}for(var i=r(n[0]).valueOf(),s=e;t>=1;)1==(1&t)&&(i=a(s,i)),t>>=1,s=a(s,s);return i}function d(e,t){return i(p(e.valueOf(),t))}})),NO_INT="Number of decimals in function round must be an integer",name$2J="round",dependencies$2J=["typed","matrix","equalScalar","zeros","BigNumber","DenseMatrix"],createRound=factory(name$2J,dependencies$2J,(e=>{var{typed:t,matrix:n,equalScalar:r,zeros:a,BigNumber:i,DenseMatrix:o}=e,s=createAlgorithm11({typed:t,equalScalar:r}),l=createAlgorithm12({typed:t,DenseMatrix:o}),u=createAlgorithm14({typed:t});return t(name$2J,{number:roundNumber,"number, number":roundNumber,"number, BigNumber":function(e,t){if(!t.isInteger())throw new TypeError(NO_INT);return new i(e).toDecimalPlaces(t.toNumber())},Complex:function(e){return e.round()},"Complex, number":function(e,t){if(t%1)throw new TypeError(NO_INT);return e.round(t)},"Complex, BigNumber":function(e,t){if(!t.isInteger())throw new TypeError(NO_INT);var n=t.toNumber();return e.round(n)},BigNumber:function(e){return e.toDecimalPlaces(0)},"BigNumber, BigNumber":function(e,t){if(!t.isInteger())throw new TypeError(NO_INT);return e.toDecimalPlaces(t.toNumber())},Fraction:function(e){return e.round()},"Fraction, number":function(e,t){if(t%1)throw new TypeError(NO_INT);return e.round(t)},"Fraction, BigNumber":function(e,t){if(!t.isInteger())throw new TypeError(NO_INT);return e.round(t.toNumber())},"Array | Matrix":function(e){return deepMap(e,this)},"SparseMatrix, number | BigNumber":function(e,t){return s(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return u(e,t,this,!1)},"Array, number | BigNumber":function(e,t){return u(n(e),t,this,!1).valueOf()},"number | Complex | BigNumber | Fraction, SparseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):l(t,e,this,!0)},"number | Complex | BigNumber | Fraction, DenseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):u(t,e,this,!0)},"number | Complex | BigNumber | Fraction, Array":function(e,t){return u(n(t),e,this,!0).valueOf()}})})),name$2I="log",dependencies$2I=["config","typed","divideScalar","Complex"],createLog=factory(name$2I,dependencies$2I,(e=>{var{typed:t,config:n,divideScalar:r,Complex:a}=e;return t(name$2I,{number:function(e){return e>=0||n.predictable?logNumber(e):new a(e,0).log()},Complex:function(e){return e.log()},BigNumber:function(e){return!e.isNegative()||n.predictable?e.ln():new a(e.toNumber(),0).log()},"Array | Matrix":function(e){return deepMap(e,this)},"any, any":function(e,t){return r(this(e),this(t))}})})),name$2H="log1p",dependencies$2H=["typed","config","divideScalar","log","Complex"],createLog1p=factory(name$2H,dependencies$2H,(e=>{var{typed:t,config:n,divideScalar:r,log:a,Complex:i}=e;return t(name$2H,{number:function(e){return e>=-1||n.predictable?log1p$1(e):o(new i(e,0))},Complex:o,BigNumber:function(e){var t=e.plus(1);return!t.isNegative()||n.predictable?t.ln():o(new i(e.toNumber(),0))},"Array | Matrix":function(e){return deepMap(e,this)},"any, any":function(e,t){return r(this(e),a(t))}});function o(e){var t=e.re+1;return new i(Math.log(Math.sqrt(t*t+e.im*e.im)),Math.atan2(e.im,t))}})),name$2G="nthRoots",dependencies$2G=["config","typed","divideScalar","Complex"],createNthRoots=factory(name$2G,dependencies$2G,(e=>{var{typed:t,config:n,divideScalar:r,Complex:a}=e,i=[function(e){return new a(e,0)},function(e){return new a(0,e)},function(e){return new a(-e,0)},function(e){return new a(0,-e)}];function o(e,t){if(t<0)throw new Error("Root must be greater than zero");if(0===t)throw new Error("Root must be non-zero");if(t%1!=0)throw new Error("Root must be an integer");if(0===e||0===e.abs())return[new a(0,0)];var n,r="number"==typeof e;(r||0===e.re||0===e.im)&&(n=r?2*+(e<0):0===e.im?2*+(e.re<0):2*+(e.im<0)+1);for(var o=e.arg(),s=e.abs(),l=[],u=Math.pow(s,1/t),c=0;c{var{typed:t,equalScalar:n,matrix:r,pow:a,DenseMatrix:i}=e,o=createAlgorithm03({typed:t}),s=createAlgorithm07({typed:t,DenseMatrix:i}),l=createAlgorithm11({typed:t,equalScalar:n}),u=createAlgorithm12({typed:t,DenseMatrix:i}),c=createAlgorithm13({typed:t}),p=createAlgorithm14({typed:t});return t(name$2F,{"any, any":a,"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,a,!1)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,a,!0)},"DenseMatrix, SparseMatrix":function(e,t){return o(e,t,a,!1)},"DenseMatrix, DenseMatrix":function(e,t){return c(e,t,a)},"Array, Array":function(e,t){return this(r(e),r(t)).valueOf()},"Array, Matrix":function(e,t){return this(r(e),t)},"Matrix, Array":function(e,t){return this(e,r(t))},"SparseMatrix, any":function(e,t){return l(e,t,this,!1)},"DenseMatrix, any":function(e,t){return p(e,t,this,!1)},"any, SparseMatrix":function(e,t){return u(t,e,this,!0)},"any, DenseMatrix":function(e,t){return p(t,e,this,!0)},"Array, any":function(e,t){return p(r(e),t,this,!1).valueOf()},"any, Array":function(e,t){return p(r(t),e,this,!0).valueOf()}})})),name$2E="dotDivide",dependencies$2E=["typed","matrix","equalScalar","divideScalar","DenseMatrix"],createDotDivide=factory(name$2E,dependencies$2E,(e=>{var{typed:t,matrix:n,equalScalar:r,divideScalar:a,DenseMatrix:i}=e,o=createAlgorithm02({typed:t,equalScalar:r}),s=createAlgorithm03({typed:t}),l=createAlgorithm07({typed:t,DenseMatrix:i}),u=createAlgorithm11({typed:t,equalScalar:r}),c=createAlgorithm12({typed:t,DenseMatrix:i}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2E,{"any, any":a,"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,a,!1)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,a,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,a,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,a)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return u(e,t,a,!1)},"DenseMatrix, any":function(e,t){return d(e,t,a,!1)},"any, SparseMatrix":function(e,t){return c(t,e,a,!0)},"any, DenseMatrix":function(e,t){return d(t,e,a,!0)},"Array, any":function(e,t){return d(n(e),t,a,!1).valueOf()},"any, Array":function(e,t){return d(n(t),e,a,!0).valueOf()}})}));function createSolveValidation(e){var{DenseMatrix:t}=e;return function(e,n,r){var a=e.size();if(2!==a.length)throw new RangeError("Matrix must be two dimensional (size: "+format$1(a)+")");var i=a[0];if(i!==a[1])throw new RangeError("Matrix must be square (size: "+format$1(a)+")");var o=[];if(isMatrix(n)){var s=n.size(),l=n._data;if(1===s.length){if(s[0]!==i)throw new RangeError("Dimension mismatch. Matrix columns must match vector length.");for(var u=0;u{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:a,subtract:i,equalScalar:o,DenseMatrix:s}=e,l=createSolveValidation({DenseMatrix:s});return t(name$2D,{"SparseMatrix, Array | Matrix":function(e,t){return function(e,t){for(var n=(t=l(e,t,!0))._data,u=e._size[0],c=e._size[1],p=e._values,d=e._index,m=e._ptr,f=[],h=0;hh&&(g.push(p[C]),v.push(A))}if(o(b,0))throw new Error("Linear system cannot be solved since matrix is singular");for(var S=r(y,b),x=0,w=v.length;x{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:a,subtract:i,equalScalar:o,DenseMatrix:s}=e,l=createSolveValidation({DenseMatrix:s});return t(name$2C,{"SparseMatrix, Array | Matrix":function(e,t){return function(e,t){for(var n=(t=l(e,t,!0))._data,u=e._size[0],c=e._size[1],p=e._values,d=e._index,m=e._ptr,f=[],h=c-1;h>=0;h--){var y=n[h][0]||0;if(o(y,0))f[h]=[0];else{for(var b=0,g=[],v=[],T=m[h],N=m[h+1]-1;N>=T;N--){var C=d[N];C===h?b=p[N]:C=0;m--){var f=n[m][0]||0,h=void 0;if(o(f,0))h=0;else{var y=d[m][m];if(o(y,0))throw new Error("Linear system cannot be solved since matrix is singular");h=r(f,y);for(var b=m-1;b>=0;b--)n[b]=[i(n[b][0]||0,a(h,d[b][m]))]}p[m]=[h]}return new s({data:p,size:[u,1]})}})),name$2B="lsolveAll",dependencies$2B=["typed","matrix","divideScalar","multiplyScalar","subtract","equalScalar","DenseMatrix"],createLsolveAll=factory(name$2B,dependencies$2B,(e=>{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:a,subtract:i,equalScalar:o,DenseMatrix:s}=e,l=createSolveValidation({DenseMatrix:s});return t(name$2B,{"SparseMatrix, Array | Matrix":function(e,t){return function(e,t){for(var n=[l(e,t,!0)._data.map((e=>e[0]))],u=e._size[0],c=e._size[1],p=e._values,d=e._index,m=e._ptr,f=0;ff&&(g.push(p[A]),v.push(S))}if(o(C,0))if(o(b[f],0)){if(0===y){var x=[...b];x[f]=1;for(var w=0,V=v.length;wnew s({data:e.map((e=>[e])),size:[u,1]})))}(e,t)},"DenseMatrix, Array | Matrix":function(e,t){return u(e,t)},"Array, Array | Matrix":function(e,t){return u(n(e),t).map((e=>e.valueOf()))}});function u(e,t){for(var n=[l(e,t,!0)._data.map((e=>e[0]))],u=e._data,c=e._size[0],p=e._size[1],d=0;dnew s({data:e.map((e=>[e])),size:[c,1]})))}})),name$2A="usolveAll",dependencies$2A=["typed","matrix","divideScalar","multiplyScalar","subtract","equalScalar","DenseMatrix"],createUsolveAll=factory(name$2A,dependencies$2A,(e=>{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:a,subtract:i,equalScalar:o,DenseMatrix:s}=e,l=createSolveValidation({DenseMatrix:s});return t(name$2A,{"SparseMatrix, Array | Matrix":function(e,t){return function(e,t){for(var n=[l(e,t,!0)._data.map((e=>e[0]))],u=e._size[0],c=e._size[1],p=e._values,d=e._index,m=e._ptr,f=c-1;f>=0;f--)for(var h=n.length,y=0;y=T;C--){var A=d[C];A===f?N=p[C]:Anew s({data:e.map((e=>[e])),size:[u,1]})))}(e,t)},"DenseMatrix, Array | Matrix":function(e,t){return u(e,t)},"Array, Array | Matrix":function(e,t){return u(n(e),t).map((e=>e.valueOf()))}});function u(e,t){for(var n=[l(e,t,!0)._data.map((e=>e[0]))],u=e._data,c=e._size[0],p=e._size[1]-1;p>=0;p--)for(var d=n.length,m=0;m=0;y--)h[y]=i(h[y],u[y][p]);n.push(h)}}else{if(0===m)return[];n.splice(m,1),m-=1,d-=1}else{f[p]=r(f[p],u[p][p]);for(var b=p-1;b>=0;b--)f[b]=i(f[b],a(f[p],u[b][p]))}}return n.map((e=>new s({data:e.map((e=>[e])),size:[c,1]})))}})),name$2z="algorithm08",dependencies$2z=["typed","equalScalar"],createAlgorithm08=factory(name$2z,dependencies$2z,(e=>{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,o=e._index,s=e._ptr,l=e._size,u=e._datatype,c=r._values,p=r._index,d=r._ptr,m=r._size,f=r._datatype;if(l.length!==m.length)throw new DimensionError(l.length,m.length);if(l[0]!==m[0]||l[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+l+") must match Matrix B ("+m+")");if(!i||!c)throw new Error("Cannot perform operation on Pattern Sparse Matrices");var h,y=l[0],b=l[1],g=n,v=0,T=a;"string"==typeof u&&u===f&&(h=u,g=t.find(n,[h,h]),v=t.convert(0,h),T=t.find(a,[h,h]));for(var N,C,A,S,x=[],w=[],V=[],E=[],O=[],_=0;_{var{typed:t,matrix:n,equalScalar:r,zeros:a,DenseMatrix:i}=e,o=createAlgorithm01({typed:t}),s=createAlgorithm02({typed:t,equalScalar:r}),l=createAlgorithm08({typed:t,equalScalar:r}),u=createAlgorithm10({typed:t,DenseMatrix:i}),c=createAlgorithm11({typed:t,equalScalar:r}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2y,{"number, number":leftShiftNumber,"BigNumber, BigNumber":leftShiftBigNumber,"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return o(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():c(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():d(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):u(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):d(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return this(n(e),t).valueOf()},"number | BigNumber, Array":function(e,t){return this(e,n(t)).valueOf()}})})),name$2x="rightArithShift",dependencies$2x=["typed","matrix","equalScalar","zeros","DenseMatrix"],createRightArithShift=factory(name$2x,dependencies$2x,(e=>{var{typed:t,matrix:n,equalScalar:r,zeros:a,DenseMatrix:i}=e,o=createAlgorithm01({typed:t}),s=createAlgorithm02({typed:t,equalScalar:r}),l=createAlgorithm08({typed:t,equalScalar:r}),u=createAlgorithm10({typed:t,DenseMatrix:i}),c=createAlgorithm11({typed:t,equalScalar:r}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2x,{"number, number":rightArithShiftNumber,"BigNumber, BigNumber":rightArithShiftBigNumber,"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return o(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():c(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():d(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):u(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):d(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return this(n(e),t).valueOf()},"number | BigNumber, Array":function(e,t){return this(e,n(t)).valueOf()}})})),name$2w="rightLogShift",dependencies$2w=["typed","matrix","equalScalar","zeros","DenseMatrix"],createRightLogShift=factory(name$2w,dependencies$2w,(e=>{var{typed:t,matrix:n,equalScalar:r,zeros:a,DenseMatrix:i}=e,o=createAlgorithm01({typed:t}),s=createAlgorithm02({typed:t,equalScalar:r}),l=createAlgorithm08({typed:t,equalScalar:r}),u=createAlgorithm10({typed:t,DenseMatrix:i}),c=createAlgorithm11({typed:t,equalScalar:r}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2w,{"number, number":rightLogShiftNumber,"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return o(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():c(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():d(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):u(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):d(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return this(n(e),t).valueOf()},"number | BigNumber, Array":function(e,t){return this(e,n(t)).valueOf()}})})),name$2v="and",dependencies$2v=["typed","matrix","equalScalar","zeros","not"],createAnd=factory(name$2v,dependencies$2v,(e=>{var{typed:t,matrix:n,equalScalar:r,zeros:a,not:i}=e,o=createAlgorithm02({typed:t,equalScalar:r}),s=createAlgorithm06({typed:t,equalScalar:r}),l=createAlgorithm11({typed:t,equalScalar:r}),u=createAlgorithm13({typed:t}),c=createAlgorithm14({typed:t});return t(name$2v,{"number, number":andNumber,"Complex, Complex":function(e,t){return!(0===e.re&&0===e.im||0===t.re&&0===t.im)},"BigNumber, BigNumber":function(e,t){return!(e.isZero()||t.isZero()||e.isNaN()||t.isNaN())},"Unit, Unit":function(e,t){return this(e.value||0,t.value||0)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return o(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return u(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return i(t)?a(e.size(),e.storage()):l(e,t,this,!1)},"DenseMatrix, any":function(e,t){return i(t)?a(e.size(),e.storage()):c(e,t,this,!1)},"any, SparseMatrix":function(e,t){return i(e)?a(e.size(),e.storage()):l(t,e,this,!0)},"any, DenseMatrix":function(e,t){return i(e)?a(e.size(),e.storage()):c(t,e,this,!0)},"Array, any":function(e,t){return this(n(e),t).valueOf()},"any, Array":function(e,t){return this(e,n(t)).valueOf()}})})),name$2u="compare",dependencies$2u=["typed","config","matrix","equalScalar","BigNumber","Fraction","DenseMatrix"],createCompare=factory(name$2u,dependencies$2u,(e=>{var{typed:t,config:n,equalScalar:r,matrix:a,BigNumber:i,Fraction:o,DenseMatrix:s}=e,l=createAlgorithm03({typed:t}),u=createAlgorithm05({typed:t,equalScalar:r}),c=createAlgorithm12({typed:t,DenseMatrix:s}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2u,{"boolean, boolean":function(e,t){return e===t?0:e>t?1:-1},"number, number":function(e,t){return nearlyEqual$1(e,t,n.epsilon)?0:e>t?1:-1},"BigNumber, BigNumber":function(e,t){return nearlyEqual(e,t,n.epsilon)?new i(0):new i(e.cmp(t))},"Fraction, Fraction":function(e,t){return new o(e.compare(t))},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)},"SparseMatrix, SparseMatrix":function(e,t){return u(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return l(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(a(e),a(t)).valueOf()},"Array, Matrix":function(e,t){return this(a(e),t)},"Matrix, Array":function(e,t){return this(e,a(t))},"SparseMatrix, any":function(e,t){return c(e,t,this,!1)},"DenseMatrix, any":function(e,t){return d(e,t,this,!1)},"any, SparseMatrix":function(e,t){return c(t,e,this,!0)},"any, DenseMatrix":function(e,t){return d(t,e,this,!0)},"Array, any":function(e,t){return d(a(e),t,this,!1).valueOf()},"any, Array":function(e,t){return d(a(t),e,this,!0).valueOf()}})})),naturalSort=function e(t,n){var r,a,i=/(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi,o=/(^[ ]*|[ ]*$)/g,s=/(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,l=/^0x[0-9a-f]+$/i,u=/^0/,c=function(t){return e.insensitive&&(""+t).toLowerCase()||""+t},p=c(t).replace(o,"")||"",d=c(n).replace(o,"")||"",m=p.replace(i,"\0$1\0").replace(/\0$/,"").replace(/^\0/,"").split("\0"),f=d.replace(i,"\0$1\0").replace(/\0$/,"").replace(/^\0/,"").split("\0"),h=parseInt(p.match(l),16)||1!==m.length&&p.match(s)&&Date.parse(p),y=parseInt(d.match(l),16)||h&&d.match(s)&&Date.parse(d)||null;if(y){if(hy)return 1}for(var b=0,g=Math.max(m.length,f.length);ba)return 1}return 0},name$2t="compareNatural",dependencies$2t=["typed","compare"],createCompareNatural=factory(name$2t,dependencies$2t,(e=>{var{typed:t,compare:n}=e,r=n.signatures["boolean,boolean"];return t(name$2t,{"any, any":function(e,t){var o,s=typeOf$1(e),l=typeOf$1(t);if(!("number"!==s&&"BigNumber"!==s&&"Fraction"!==s||"number"!==l&&"BigNumber"!==l&&"Fraction"!==l))return"0"!==(o=n(e,t)).toString()?o>0?1:-1:naturalSort(s,l);if("Array"===s||"Matrix"===s||"Array"===l||"Matrix"===l)return 0!==(o=a(this,e,t))?o:naturalSort(s,l);if(s!==l)return naturalSort(s,l);if("Complex"===s)return compareComplexNumbers(e,t);if("Unit"===s)return e.equalBase(t)?this(e.value,t.value):i(this,e.formatUnits(),t.formatUnits());if("boolean"===s)return r(e,t);if("string"===s)return naturalSort(e,t);if("Object"===s)return function(e,t,n){var r=Object.keys(t),a=Object.keys(n);r.sort(naturalSort),a.sort(naturalSort);var o=i(e,r,a);if(0!==o)return o;for(var s=0;sn.length?1:t.lengtht.re?1:e.ret.im?1:e.im{var{typed:t,matrix:n}=e,r=createAlgorithm13({typed:t}),a=createAlgorithm14({typed:t});return t(name$2s,{"any, any":compareText$1,"DenseMatrix, DenseMatrix":function(e,t){return r(e,t,compareText$1)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"DenseMatrix, any":function(e,t){return a(e,t,compareText$1,!1)},"any, DenseMatrix":function(e,t){return a(t,e,compareText$1,!0)},"Array, any":function(e,t){return a(n(e),t,compareText$1,!1).valueOf()},"any, Array":function(e,t){return a(n(t),e,compareText$1,!0).valueOf()}})})),name$2r="equal",dependencies$2r=["typed","matrix","equalScalar","DenseMatrix"],createEqual=factory(name$2r,dependencies$2r,(e=>{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),o=createAlgorithm07({typed:t,DenseMatrix:a}),s=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2r,{"any, any":function(e,t){return null===e?null===t:null===t?null===e:void 0===e?void 0===t:void 0===t?void 0===e:r(e,t)},"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,r)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,r,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,r,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,r)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return s(e,t,r,!1)},"DenseMatrix, any":function(e,t){return u(e,t,r,!1)},"any, SparseMatrix":function(e,t){return s(t,e,r,!0)},"any, DenseMatrix":function(e,t){return u(t,e,r,!0)},"Array, any":function(e,t){return u(n(e),t,r,!1).valueOf()},"any, Array":function(e,t){return u(n(t),e,r,!0).valueOf()}})}));factory(name$2r,["typed","equalScalar"],(e=>{var{typed:t,equalScalar:n}=e;return t(name$2r,{"any, any":function(e,t){return null===e?null===t:null===t?null===e:void 0===e?void 0===t:void 0===t?void 0===e:n(e,t)}})}));var name$2q="equalText",dependencies$2q=["typed","compareText","isZero"],createEqualText=factory(name$2q,dependencies$2q,(e=>{var{typed:t,compareText:n,isZero:r}=e;return t(name$2q,{"any, any":function(e,t){return r(n(e,t))}})})),name$2p="smaller",dependencies$2p=["typed","config","matrix","DenseMatrix"],createSmaller=factory(name$2p,dependencies$2p,(e=>{var{typed:t,config:n,matrix:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),o=createAlgorithm07({typed:t,DenseMatrix:a}),s=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2p,{"boolean, boolean":function(e,t){return e{var{typed:t,config:n,matrix:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),o=createAlgorithm07({typed:t,DenseMatrix:a}),s=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2o,{"boolean, boolean":function(e,t){return e<=t},"number, number":function(e,t){return e<=t||nearlyEqual$1(e,t,n.epsilon)},"BigNumber, BigNumber":function(e,t){return e.lte(t)||nearlyEqual(e,t,n.epsilon)},"Fraction, Fraction":function(e,t){return 1!==e.compare(t)},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)},"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(r(e),r(t)).valueOf()},"Array, Matrix":function(e,t){return this(r(e),t)},"Matrix, Array":function(e,t){return this(e,r(t))},"SparseMatrix, any":function(e,t){return s(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return s(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(r(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(r(t),e,this,!0).valueOf()}})})),name$2n="larger",dependencies$2n=["typed","config","matrix","DenseMatrix"],createLarger=factory(name$2n,dependencies$2n,(e=>{var{typed:t,config:n,matrix:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),o=createAlgorithm07({typed:t,DenseMatrix:a}),s=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2n,{"boolean, boolean":function(e,t){return e>t},"number, number":function(e,t){return e>t&&!nearlyEqual$1(e,t,n.epsilon)},"BigNumber, BigNumber":function(e,t){return e.gt(t)&&!nearlyEqual(e,t,n.epsilon)},"Fraction, Fraction":function(e,t){return 1===e.compare(t)},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)},"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(r(e),r(t)).valueOf()},"Array, Matrix":function(e,t){return this(r(e),t)},"Matrix, Array":function(e,t){return this(e,r(t))},"SparseMatrix, any":function(e,t){return s(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return s(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(r(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(r(t),e,this,!0).valueOf()}})})),name$2m="largerEq",dependencies$2m=["typed","config","matrix","DenseMatrix"],createLargerEq=factory(name$2m,dependencies$2m,(e=>{var{typed:t,config:n,matrix:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),o=createAlgorithm07({typed:t,DenseMatrix:a}),s=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2m,{"boolean, boolean":function(e,t){return e>=t},"number, number":function(e,t){return e>=t||nearlyEqual$1(e,t,n.epsilon)},"BigNumber, BigNumber":function(e,t){return e.gte(t)||nearlyEqual(e,t,n.epsilon)},"Fraction, Fraction":function(e,t){return-1!==e.compare(t)},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)},"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(r(e),r(t)).valueOf()},"Array, Matrix":function(e,t){return this(r(e),t)},"Matrix, Array":function(e,t){return this(e,r(t))},"SparseMatrix, any":function(e,t){return s(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return s(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(r(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(r(t),e,this,!0).valueOf()}})})),name$2l="deepEqual",dependencies$2l=["typed","equal"],createDeepEqual=factory(name$2l,dependencies$2l,(e=>{var{typed:t,equal:n}=e;return t(name$2l,{"any, any":function(e,t){return r(e.valueOf(),t.valueOf())}});function r(e,t){if(Array.isArray(e)){if(Array.isArray(t)){var a=e.length;if(a!==t.length)return!1;for(var i=0;i{var{typed:t,config:n,equalScalar:r,matrix:a,DenseMatrix:i}=e,o=createAlgorithm03({typed:t}),s=createAlgorithm07({typed:t,DenseMatrix:i}),l=createAlgorithm12({typed:t,DenseMatrix:i}),u=createAlgorithm13({typed:t}),c=createAlgorithm14({typed:t});return t("unequal",{"any, any":function(e,t){return null===e?null!==t:null===t?null!==e:void 0===e?void 0!==t:void 0===t?void 0!==e:p(e,t)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,p)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,p,!0)},"DenseMatrix, SparseMatrix":function(e,t){return o(e,t,p,!1)},"DenseMatrix, DenseMatrix":function(e,t){return u(e,t,p)},"Array, Array":function(e,t){return this(a(e),a(t)).valueOf()},"Array, Matrix":function(e,t){return this(a(e),t)},"Matrix, Array":function(e,t){return this(e,a(t))},"SparseMatrix, any":function(e,t){return l(e,t,p,!1)},"DenseMatrix, any":function(e,t){return c(e,t,p,!1)},"any, SparseMatrix":function(e,t){return l(t,e,p,!0)},"any, DenseMatrix":function(e,t){return c(t,e,p,!0)},"Array, any":function(e,t){return c(a(e),t,p,!1).valueOf()},"any, Array":function(e,t){return c(a(t),e,p,!0).valueOf()}});function p(e,t){return!r(e,t)}}));factory(name$2k,["typed","equalScalar"],(e=>{var{typed:t,equalScalar:n}=e;return t(name$2k,{"any, any":function(e,t){return null===e?null!==t:null===t?null!==e:void 0===e?void 0!==t:void 0===t?void 0!==e:!n(e,t)}})}));var name$2j="partitionSelect",dependencies$2j=["typed","isNumeric","isNaN","compare"],createPartitionSelect=factory(name$2j,dependencies$2j,(e=>{var{typed:t,isNumeric:n,isNaN:r,compare:a}=e,i=a,o=(e,t)=>-a(e,t);return t(name$2j,{"Array | Matrix, number":function(e,t){return s(e,t,i)},"Array | Matrix, number, string":function(e,t,n){if("asc"===n)return s(e,t,i);if("desc"===n)return s(e,t,o);throw new Error('Compare string must be "asc" or "desc"')},"Array | Matrix, number, function":s});function s(e,t,n){if(!isInteger$1(t)||t<0)throw new Error("k must be a non-negative integer");if(isMatrix(e)){if(e.size().length>1)throw new Error("Only one dimensional matrices supported");return l(e.valueOf(),t,n)}if(Array.isArray(e))return l(e,t,n)}function l(e,t,a){if(t>=e.length)throw new Error("k out of bounds");for(var i=0;i=0){var p=e[u];e[u]=e[l],e[l]=p,--u}else++l;a(e[l],c)>0&&--l,t<=l?s=l:o=l+1}return e[t]}})),name$2i="sort",dependencies$2i=["typed","matrix","compare","compareNatural"],createSort=factory(name$2i,dependencies$2i,(e=>{var{typed:t,matrix:n,compare:r,compareNatural:a}=e,i=r,o=(e,t)=>-r(e,t);return t(name$2i,{Array:function(e){return l(e),e.sort(i)},Matrix:function(e){return u(e),n(e.toArray().sort(i),e.storage())},"Array, function":function(e,t){return l(e),e.sort(t)},"Matrix, function":function(e,t){return u(e),n(e.toArray().sort(t),e.storage())},"Array, string":function(e,t){return l(e),e.sort(s(t))},"Matrix, string":function(e,t){return u(e),n(e.toArray().sort(s(t)),e.storage())}});function s(e){if("asc"===e)return i;if("desc"===e)return o;if("natural"===e)return a;throw new Error('String "asc", "desc", or "natural" expected')}function l(e){if(1!==arraySize(e).length)throw new Error("One dimensional array expected")}function u(e){if(1!==e.size().length)throw new Error("One dimensional matrix expected")}})),name$2h="max",dependencies$2h=["typed","config","numeric","larger"],createMax=factory(name$2h,dependencies$2h,(e=>{var{typed:t,config:n,numeric:r,larger:a}=e;return t(name$2h,{"Array | Matrix":o,"Array | Matrix, number | BigNumber":function(e,t){return reduce$2(e,t.valueOf(),i)},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function max");return o(e)}});function i(e,t){try{return a(e,t)?e:t}catch(e){throw improveErrorMessage(e,"max",t)}}function o(e){var t;if(deepForEach(e,(function(e){try{isNaN(e)&&"number"==typeof e?t=NaN:(void 0===t||a(e,t))&&(t=e)}catch(t){throw improveErrorMessage(t,"max",e)}})),void 0===t)throw new Error("Cannot calculate max of an empty array");return"string"==typeof t&&(t=r(t,n.number)),t}})),name$2g="min",dependencies$2g=["typed","config","numeric","smaller"],createMin=factory(name$2g,dependencies$2g,(e=>{var{typed:t,config:n,numeric:r,smaller:a}=e;return t(name$2g,{"Array | Matrix":o,"Array | Matrix, number | BigNumber":function(e,t){return reduce$2(e,t.valueOf(),i)},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function min");return o(e)}});function i(e,t){try{return a(e,t)?e:t}catch(e){throw improveErrorMessage(e,"min",t)}}function o(e){var t;if(deepForEach(e,(function(e){try{isNaN(e)&&"number"==typeof e?t=NaN:(void 0===t||a(e,t))&&(t=e)}catch(t){throw improveErrorMessage(t,"min",e)}})),void 0===t)throw new Error("Cannot calculate min of an empty array");return"string"==typeof t&&(t=r(t,n.number)),t}})),name$2f="ImmutableDenseMatrix",dependencies$2f=["smaller","DenseMatrix"],createImmutableDenseMatrixClass=factory(name$2f,dependencies$2f,(e=>{var{smaller:t,DenseMatrix:n}=e;function r(e,t){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");if(t&&!isString$1(t))throw new Error("Invalid datatype: "+t);if(isMatrix(e)||isArray$1(e)){var a=new n(e,t);this._data=a._data,this._size=a._size,this._datatype=a._datatype,this._min=null,this._max=null}else if(e&&isArray$1(e.data)&&isArray$1(e.size))this._data=e.data,this._size=e.size,this._datatype=e.datatype,this._min=void 0!==e.min?e.min:null,this._max=void 0!==e.max?e.max:null;else{if(e)throw new TypeError("Unsupported type of data ("+typeOf$1(e)+")");this._data=[],this._size=[0],this._datatype=t,this._min=null,this._max=null}}return r.prototype=new n,r.prototype.type="ImmutableDenseMatrix",r.prototype.isImmutableDenseMatrix=!0,r.prototype.subset=function(e){switch(arguments.length){case 1:var t=n.prototype.subset.call(this,e);return isMatrix(t)?new r({data:t._data,size:t._size,datatype:t._datatype}):t;case 2:case 3:throw new Error("Cannot invoke set subset on an Immutable Matrix instance");default:throw new SyntaxError("Wrong number of arguments")}},r.prototype.set=function(){throw new Error("Cannot invoke set on an Immutable Matrix instance")},r.prototype.resize=function(){throw new Error("Cannot invoke resize on an Immutable Matrix instance")},r.prototype.reshape=function(){throw new Error("Cannot invoke reshape on an Immutable Matrix instance")},r.prototype.clone=function(){return new r({data:clone$2(this._data),size:clone$2(this._size),datatype:this._datatype})},r.prototype.toJSON=function(){return{mathjs:"ImmutableDenseMatrix",data:this._data,size:this._size,datatype:this._datatype}},r.fromJSON=function(e){return new r(e)},r.prototype.swapRows=function(){throw new Error("Cannot invoke swapRows on an Immutable Matrix instance")},r.prototype.min=function(){if(null===this._min){var e=null;this.forEach((function(n){(null===e||t(n,e))&&(e=n)})),this._min=null!==e?e:void 0}return this._min},r.prototype.max=function(){if(null===this._max){var e=null;this.forEach((function(n){(null===e||t(e,n))&&(e=n)})),this._max=null!==e?e:void 0}return this._max},r}),{isClass:!0}),name$2e="Index",dependencies$2e=["ImmutableDenseMatrix"],createIndexClass=factory(name$2e,dependencies$2e,(e=>{var{ImmutableDenseMatrix:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");this._dimensions=[],this._isScalar=!0;for(var t=0,a=arguments.length;t{var{smaller:t,larger:n}=e,r=1/Math.log((1+Math.sqrt(5))/2);function a(){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");this._minimum=null,this._size=0}function i(e,t,n){t.left.right=t.right,t.right.left=t.left,n.degree--,n.child===t&&(n.child=t.right),0===n.degree&&(n.child=null),t.left=e,t.right=e.right,e.right=t,t.right.left=t,t.parent=null,t.mark=!1}function o(e,t){var n=t.parent;n&&(t.mark?(i(e,t,n),o(n)):t.mark=!0)}a.prototype.type="FibonacciHeap",a.prototype.isFibonacciHeap=!0,a.prototype.insert=function(e,n){var r={key:e,value:n,degree:0};if(this._minimum){var a=this._minimum;r.left=a,r.right=a.right,a.right=r,r.right.left=r,t(e,a.key)&&(this._minimum=r)}else r.left=r,r.right=r,this._minimum=r;return this._size++,r},a.prototype.size=function(){return this._size},a.prototype.clear=function(){this._minimum=null,this._size=0},a.prototype.isEmpty=function(){return 0===this._size},a.prototype.extractMinimum=function(){var e=this._minimum;if(null===e)return e;for(var a=this._minimum,i=e.degree,o=e.child;i>0;){var l=o.right;o.left.right=o.right,o.right.left=o.left,o.left=a,o.right=a.right,a.right=o,o.right.left=o,o.parent=null,o=l,i--}return e.left.right=e.right,e.right.left=e.left,a=e===e.right?null:function(e,a){var i,o=Math.floor(Math.log(a)*r)+1,l=new Array(o),u=0,c=e;if(c)for(u++,c=c.right;c!==e;)u++,c=c.right;for(;u>0;){for(var p=c.degree,d=c.right;i=l[p];){if(n(c.key,i.key)){var m=i;i=c,c=m}s(i,c),l[p]=null,p++}l[p]=c,c=d,u--}e=null;for(var f=0;f{var{addScalar:t,equalScalar:n,FibonacciHeap:r}=e;function a(){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");this._values=[],this._heap=new r}return a.prototype.type="Spa",a.prototype.isSpa=!0,a.prototype.set=function(e,t){if(this._values[e])this._values[e].value=t;else{var n=this._heap.insert(e,t);this._values[e]=n}},a.prototype.get=function(e){var t=this._values[e];return t?t.value:0},a.prototype.accumulate=function(e,n){var r=this._values[e];r?r.value=t(r.value,n):(r=this._heap.insert(e,n),this._values[e]=r)},a.prototype.forEach=function(e,t,r){var a=this._heap,i=this._values,o=[],s=a.extractMinimum();for(s&&o.push(s);s&&s.key<=t;)s.key>=e&&(n(s.value,0)||r(s.key,s.value,this)),(s=a.extractMinimum())&&o.push(s);for(var l=0;l{var t,n,r,{on:a,config:i,addScalar:o,subtract:s,multiplyScalar:l,divideScalar:u,pow:c,abs:p,fix:d,round:m,equal:f,isNumeric:h,format:y,number:b,Complex:g,BigNumber:v,Fraction:T}=e,N=b;function C(e,t){if(!(this instanceof C))throw new Error("Constructor must be called with the new operator");if(null!=e&&!h(e)&&!isComplex(e))throw new TypeError("First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined");if(void 0!==t&&("string"!=typeof t||""===t))throw new TypeError("Second parameter in Unit constructor must be a string");if(void 0!==t){var n=C.parse(t);this.units=n.units,this.dimensions=n.dimensions}else{this.units=[{unit:k,prefix:D.NONE,power:0}],this.dimensions=[];for(var r=0;r="0"&&e<="9"}function x(){n++,r=t.charAt(n)}function w(e){n=e,r=t.charAt(n)}function V(){var e="",t=n;if("+"===r?x():"-"===r&&(e+=r,x()),!function(e){return e>="0"&&e<="9"||"."===e}(r))return w(t),null;if("."===r){if(e+=r,x(),!S(r))return w(t),null}else{for(;S(r);)e+=r,x();"."===r&&(e+=r,x())}for(;S(r);)e+=r,x();if("E"===r||"e"===r){var a="",i=n;if(a+=r,x(),"+"!==r&&"-"!==r||(a+=r,x()),!S(r))return w(i),e;for(e+=a;S(r);)e+=r,x()}return e}function E(){for(var e="";S(r)||C.isValidAlpha(r);)e+=r,x();var t=e.charAt(0);return C.isValidAlpha(t)?e:null}function O(e){return r===e?(x(),e):null}C.prototype.type="Unit",C.prototype.isUnit=!0,C.parse=function(e,a){if(a=a||{},n=-1,r="","string"!=typeof(t=e))throw new TypeError("Invalid argument in Unit.parse, string expected");var o=new C;o.units=[];var s=1,l=!1;x(),A();var u=V(),c=null;if(u){if("BigNumber"===i.number)c=new v(u);else if("Fraction"===i.number)try{c=new T(u)}catch(e){c=parseFloat(u)}else c=parseFloat(u);A(),O("*")?(s=1,l=!0):O("/")&&(s=-1,l=!0)}for(var p=[],d=1;;){for(A();"("===r;)p.push(s),d*=s,s=1,x(),A();var m;if(!r)break;var f=r;if(null===(m=E()))throw new SyntaxError('Unexpected "'+f+'" in "'+t+'" at index '+n.toString());var h=_(m);if(null===h)throw new SyntaxError('Unit "'+m+'" not found.');var y=s*d;if(A(),O("^")){A();var b=V();if(null===b)throw new SyntaxError('In "'+e+'", "^" must be followed by a floating-point number');y*=b}o.units.push({unit:h.unit,prefix:h.prefix,power:y});for(var g=0;g1||Math.abs(this.units[0].power-1)>1e-15)},C.prototype._normalize=function(e){if(null==e||0===this.units.length)return e;for(var t=e,n=C._getNumberConverter(typeOf$1(e)),r=0;r{if(hasOwnProperty$2(M,e)){var t=M[e];return{unit:t,prefix:t.prefixes[""]}}for(var n in M)if(hasOwnProperty$2(M,n)&&endsWith(e,n)){var r=M[n],a=e.length-n.length,i=e.substring(0,a),o=hasOwnProperty$2(r.prefixes,i)?r.prefixes[i]:void 0;if(void 0!==o)return{unit:r,prefix:o}}return null}),{hasher:e=>e[0],limit:100});function $(e){return e.equalBase(R.NONE)&&null!==e.value&&!i.predictable?e.value:e}C.isValuelessUnit=function(e){return null!==_(e)},C.prototype.hasBase=function(e){if("string"==typeof e&&(e=R[e]),!e)return!1;for(var t=0;t1e-12)return!1;return!0},C.prototype.equalBase=function(e){for(var t=0;t1e-12)return!1;return!0},C.prototype.equals=function(e){return this.equalBase(e)&&f(this.value,e.value)},C.prototype.multiply=function(e){for(var t=this.clone(),n=0;n1e-12&&(hasOwnProperty$2(j,s)?r.push({unit:j[s].unit,prefix:j[s].prefix,power:n.dimensions[o]||0}):i=!0)}r.length1e-12){if(!hasOwnProperty$2(L.si,r))throw new Error("Cannot express custom unit "+r+" in SI units");t.push({unit:L.si[r].unit,prefix:L.si[r].prefix,power:e.dimensions[n]||0})}}return e.units=t,e.fixPrefix=!0,e.skipAutomaticSimplification=!0,e},C.prototype.formatUnits=function(){for(var e="",t="",n=0,r=0,a=0;a0?(n++,e+=" "+this.units[a].prefix.name+this.units[a].unit.name,Math.abs(this.units[a].power-1)>1e-15&&(e+="^"+this.units[a].power)):this.units[a].power<0&&r++;if(r>0)for(var i=0;i0?(t+=" "+this.units[i].prefix.name+this.units[i].unit.name,Math.abs(this.units[i].power+1)>1e-15&&(t+="^"+-this.units[i].power)):(t+=" "+this.units[i].prefix.name+this.units[i].unit.name,t+="^"+this.units[i].power));e=e.substr(1),t=t.substr(1),n>1&&r>0&&(e="("+e+")"),r>1&&n>0&&(t="("+t+")");var o=e;return n>0&&r>0&&(o+=" / "),o+t},C.prototype.format=function(e){var t=this.skipAutomaticSimplification||null===this.value?this.clone():this.simplify(),n=!1;for(var r in void 0!==t.value&&null!==t.value&&isComplex(t.value)&&(n=Math.abs(t.value.re)<1e-14),t.units)hasOwnProperty$2(t.units,r)&&t.units[r].unit&&("VA"===t.units[r].unit.name&&n?t.units[r].unit=M.VAR:"VAR"!==t.units[r].unit.name||n||(t.units[r].unit=M.VA));1!==t.units.length||t.fixPrefix||Math.abs(t.units[0].power-Math.round(t.units[0].power))<1e-14&&(t.units[0].prefix=t._bestPrefix());var a=t._denormalize(t.value),i=null!==t.value?y(a,e||{}):"",o=t.formatUnits();return t.value&&isComplex(t.value)&&(i="("+i+")"),o.length>0&&i.length>0&&(i+=" "),i+o},C.prototype._bestPrefix=function(){if(1!==this.units.length)throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!");if(Math.abs(this.units[0].power-Math.round(this.units[0].power))>=1e-14)throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!");var e=null!==this.value?p(this.value):0,t=p(this.units[0].unit.value),n=this.units[0].prefix;if(0===e)return n;var r=this.units[0].power,a=Math.log(e/Math.pow(n.value*t,r))/Math.LN10-1.2;if(a>-2.200001&&a<1.800001)return n;a=Math.abs(a);var i=this.units[0].unit.prefixes;for(var o in i)if(hasOwnProperty$2(i,o)){var s=i[o];if(s.scientific){var l=Math.abs(Math.log(e/Math.pow(s.value*t,r))/Math.LN10-1.2);(l0))},M={meter:{name:"meter",base:R.LENGTH,prefixes:D.LONG,value:1,offset:0},inch:{name:"inch",base:R.LENGTH,prefixes:D.NONE,value:.0254,offset:0},foot:{name:"foot",base:R.LENGTH,prefixes:D.NONE,value:.3048,offset:0},yard:{name:"yard",base:R.LENGTH,prefixes:D.NONE,value:.9144,offset:0},mile:{name:"mile",base:R.LENGTH,prefixes:D.NONE,value:1609.344,offset:0},link:{name:"link",base:R.LENGTH,prefixes:D.NONE,value:.201168,offset:0},rod:{name:"rod",base:R.LENGTH,prefixes:D.NONE,value:5.0292,offset:0},chain:{name:"chain",base:R.LENGTH,prefixes:D.NONE,value:20.1168,offset:0},angstrom:{name:"angstrom",base:R.LENGTH,prefixes:D.NONE,value:1e-10,offset:0},m:{name:"m",base:R.LENGTH,prefixes:D.SHORT,value:1,offset:0},in:{name:"in",base:R.LENGTH,prefixes:D.NONE,value:.0254,offset:0},ft:{name:"ft",base:R.LENGTH,prefixes:D.NONE,value:.3048,offset:0},yd:{name:"yd",base:R.LENGTH,prefixes:D.NONE,value:.9144,offset:0},mi:{name:"mi",base:R.LENGTH,prefixes:D.NONE,value:1609.344,offset:0},li:{name:"li",base:R.LENGTH,prefixes:D.NONE,value:.201168,offset:0},rd:{name:"rd",base:R.LENGTH,prefixes:D.NONE,value:5.02921,offset:0},ch:{name:"ch",base:R.LENGTH,prefixes:D.NONE,value:20.1168,offset:0},mil:{name:"mil",base:R.LENGTH,prefixes:D.NONE,value:254e-7,offset:0},m2:{name:"m2",base:R.SURFACE,prefixes:D.SQUARED,value:1,offset:0},sqin:{name:"sqin",base:R.SURFACE,prefixes:D.NONE,value:64516e-8,offset:0},sqft:{name:"sqft",base:R.SURFACE,prefixes:D.NONE,value:.09290304,offset:0},sqyd:{name:"sqyd",base:R.SURFACE,prefixes:D.NONE,value:.83612736,offset:0},sqmi:{name:"sqmi",base:R.SURFACE,prefixes:D.NONE,value:2589988.110336,offset:0},sqrd:{name:"sqrd",base:R.SURFACE,prefixes:D.NONE,value:25.29295,offset:0},sqch:{name:"sqch",base:R.SURFACE,prefixes:D.NONE,value:404.6873,offset:0},sqmil:{name:"sqmil",base:R.SURFACE,prefixes:D.NONE,value:6.4516e-10,offset:0},acre:{name:"acre",base:R.SURFACE,prefixes:D.NONE,value:4046.86,offset:0},hectare:{name:"hectare",base:R.SURFACE,prefixes:D.NONE,value:1e4,offset:0},m3:{name:"m3",base:R.VOLUME,prefixes:D.CUBIC,value:1,offset:0},L:{name:"L",base:R.VOLUME,prefixes:D.SHORT,value:.001,offset:0},l:{name:"l",base:R.VOLUME,prefixes:D.SHORT,value:.001,offset:0},litre:{name:"litre",base:R.VOLUME,prefixes:D.LONG,value:.001,offset:0},cuin:{name:"cuin",base:R.VOLUME,prefixes:D.NONE,value:16387064e-12,offset:0},cuft:{name:"cuft",base:R.VOLUME,prefixes:D.NONE,value:.028316846592,offset:0},cuyd:{name:"cuyd",base:R.VOLUME,prefixes:D.NONE,value:.764554857984,offset:0},teaspoon:{name:"teaspoon",base:R.VOLUME,prefixes:D.NONE,value:5e-6,offset:0},tablespoon:{name:"tablespoon",base:R.VOLUME,prefixes:D.NONE,value:15e-6,offset:0},drop:{name:"drop",base:R.VOLUME,prefixes:D.NONE,value:5e-8,offset:0},gtt:{name:"gtt",base:R.VOLUME,prefixes:D.NONE,value:5e-8,offset:0},minim:{name:"minim",base:R.VOLUME,prefixes:D.NONE,value:6.161152e-8,offset:0},fluiddram:{name:"fluiddram",base:R.VOLUME,prefixes:D.NONE,value:36966911e-13,offset:0},fluidounce:{name:"fluidounce",base:R.VOLUME,prefixes:D.NONE,value:2957353e-11,offset:0},gill:{name:"gill",base:R.VOLUME,prefixes:D.NONE,value:.0001182941,offset:0},cc:{name:"cc",base:R.VOLUME,prefixes:D.NONE,value:1e-6,offset:0},cup:{name:"cup",base:R.VOLUME,prefixes:D.NONE,value:.0002365882,offset:0},pint:{name:"pint",base:R.VOLUME,prefixes:D.NONE,value:.0004731765,offset:0},quart:{name:"quart",base:R.VOLUME,prefixes:D.NONE,value:.0009463529,offset:0},gallon:{name:"gallon",base:R.VOLUME,prefixes:D.NONE,value:.003785412,offset:0},beerbarrel:{name:"beerbarrel",base:R.VOLUME,prefixes:D.NONE,value:.1173478,offset:0},oilbarrel:{name:"oilbarrel",base:R.VOLUME,prefixes:D.NONE,value:.1589873,offset:0},hogshead:{name:"hogshead",base:R.VOLUME,prefixes:D.NONE,value:.238481,offset:0},fldr:{name:"fldr",base:R.VOLUME,prefixes:D.NONE,value:36966911e-13,offset:0},floz:{name:"floz",base:R.VOLUME,prefixes:D.NONE,value:2957353e-11,offset:0},gi:{name:"gi",base:R.VOLUME,prefixes:D.NONE,value:.0001182941,offset:0},cp:{name:"cp",base:R.VOLUME,prefixes:D.NONE,value:.0002365882,offset:0},pt:{name:"pt",base:R.VOLUME,prefixes:D.NONE,value:.0004731765,offset:0},qt:{name:"qt",base:R.VOLUME,prefixes:D.NONE,value:.0009463529,offset:0},gal:{name:"gal",base:R.VOLUME,prefixes:D.NONE,value:.003785412,offset:0},bbl:{name:"bbl",base:R.VOLUME,prefixes:D.NONE,value:.1173478,offset:0},obl:{name:"obl",base:R.VOLUME,prefixes:D.NONE,value:.1589873,offset:0},g:{name:"g",base:R.MASS,prefixes:D.SHORT,value:.001,offset:0},gram:{name:"gram",base:R.MASS,prefixes:D.LONG,value:.001,offset:0},ton:{name:"ton",base:R.MASS,prefixes:D.SHORT,value:907.18474,offset:0},t:{name:"t",base:R.MASS,prefixes:D.SHORT,value:1e3,offset:0},tonne:{name:"tonne",base:R.MASS,prefixes:D.LONG,value:1e3,offset:0},grain:{name:"grain",base:R.MASS,prefixes:D.NONE,value:6479891e-11,offset:0},dram:{name:"dram",base:R.MASS,prefixes:D.NONE,value:.0017718451953125,offset:0},ounce:{name:"ounce",base:R.MASS,prefixes:D.NONE,value:.028349523125,offset:0},poundmass:{name:"poundmass",base:R.MASS,prefixes:D.NONE,value:.45359237,offset:0},hundredweight:{name:"hundredweight",base:R.MASS,prefixes:D.NONE,value:45.359237,offset:0},stick:{name:"stick",base:R.MASS,prefixes:D.NONE,value:.115,offset:0},stone:{name:"stone",base:R.MASS,prefixes:D.NONE,value:6.35029318,offset:0},gr:{name:"gr",base:R.MASS,prefixes:D.NONE,value:6479891e-11,offset:0},dr:{name:"dr",base:R.MASS,prefixes:D.NONE,value:.0017718451953125,offset:0},oz:{name:"oz",base:R.MASS,prefixes:D.NONE,value:.028349523125,offset:0},lbm:{name:"lbm",base:R.MASS,prefixes:D.NONE,value:.45359237,offset:0},cwt:{name:"cwt",base:R.MASS,prefixes:D.NONE,value:45.359237,offset:0},s:{name:"s",base:R.TIME,prefixes:D.SHORT,value:1,offset:0},min:{name:"min",base:R.TIME,prefixes:D.NONE,value:60,offset:0},h:{name:"h",base:R.TIME,prefixes:D.NONE,value:3600,offset:0},second:{name:"second",base:R.TIME,prefixes:D.LONG,value:1,offset:0},sec:{name:"sec",base:R.TIME,prefixes:D.LONG,value:1,offset:0},minute:{name:"minute",base:R.TIME,prefixes:D.NONE,value:60,offset:0},hour:{name:"hour",base:R.TIME,prefixes:D.NONE,value:3600,offset:0},day:{name:"day",base:R.TIME,prefixes:D.NONE,value:86400,offset:0},week:{name:"week",base:R.TIME,prefixes:D.NONE,value:604800,offset:0},month:{name:"month",base:R.TIME,prefixes:D.NONE,value:2629800,offset:0},year:{name:"year",base:R.TIME,prefixes:D.NONE,value:31557600,offset:0},decade:{name:"decade",base:R.TIME,prefixes:D.NONE,value:315576e3,offset:0},century:{name:"century",base:R.TIME,prefixes:D.NONE,value:315576e4,offset:0},millennium:{name:"millennium",base:R.TIME,prefixes:D.NONE,value:315576e5,offset:0},hertz:{name:"Hertz",base:R.FREQUENCY,prefixes:D.LONG,value:1,offset:0,reciprocal:!0},Hz:{name:"Hz",base:R.FREQUENCY,prefixes:D.SHORT,value:1,offset:0,reciprocal:!0},rad:{name:"rad",base:R.ANGLE,prefixes:D.SHORT,value:1,offset:0},radian:{name:"radian",base:R.ANGLE,prefixes:D.LONG,value:1,offset:0},deg:{name:"deg",base:R.ANGLE,prefixes:D.SHORT,value:null,offset:0},degree:{name:"degree",base:R.ANGLE,prefixes:D.LONG,value:null,offset:0},grad:{name:"grad",base:R.ANGLE,prefixes:D.SHORT,value:null,offset:0},gradian:{name:"gradian",base:R.ANGLE,prefixes:D.LONG,value:null,offset:0},cycle:{name:"cycle",base:R.ANGLE,prefixes:D.NONE,value:null,offset:0},arcsec:{name:"arcsec",base:R.ANGLE,prefixes:D.NONE,value:null,offset:0},arcmin:{name:"arcmin",base:R.ANGLE,prefixes:D.NONE,value:null,offset:0},A:{name:"A",base:R.CURRENT,prefixes:D.SHORT,value:1,offset:0},ampere:{name:"ampere",base:R.CURRENT,prefixes:D.LONG,value:1,offset:0},K:{name:"K",base:R.TEMPERATURE,prefixes:D.NONE,value:1,offset:0},degC:{name:"degC",base:R.TEMPERATURE,prefixes:D.NONE,value:1,offset:273.15},degF:{name:"degF",base:R.TEMPERATURE,prefixes:D.NONE,value:1/1.8,offset:459.67},degR:{name:"degR",base:R.TEMPERATURE,prefixes:D.NONE,value:1/1.8,offset:0},kelvin:{name:"kelvin",base:R.TEMPERATURE,prefixes:D.NONE,value:1,offset:0},celsius:{name:"celsius",base:R.TEMPERATURE,prefixes:D.NONE,value:1,offset:273.15},fahrenheit:{name:"fahrenheit",base:R.TEMPERATURE,prefixes:D.NONE,value:1/1.8,offset:459.67},rankine:{name:"rankine",base:R.TEMPERATURE,prefixes:D.NONE,value:1/1.8,offset:0},mol:{name:"mol",base:R.AMOUNT_OF_SUBSTANCE,prefixes:D.SHORT,value:1,offset:0},mole:{name:"mole",base:R.AMOUNT_OF_SUBSTANCE,prefixes:D.LONG,value:1,offset:0},cd:{name:"cd",base:R.LUMINOUS_INTENSITY,prefixes:D.SHORT,value:1,offset:0},candela:{name:"candela",base:R.LUMINOUS_INTENSITY,prefixes:D.LONG,value:1,offset:0},N:{name:"N",base:R.FORCE,prefixes:D.SHORT,value:1,offset:0},newton:{name:"newton",base:R.FORCE,prefixes:D.LONG,value:1,offset:0},dyn:{name:"dyn",base:R.FORCE,prefixes:D.SHORT,value:1e-5,offset:0},dyne:{name:"dyne",base:R.FORCE,prefixes:D.LONG,value:1e-5,offset:0},lbf:{name:"lbf",base:R.FORCE,prefixes:D.NONE,value:4.4482216152605,offset:0},poundforce:{name:"poundforce",base:R.FORCE,prefixes:D.NONE,value:4.4482216152605,offset:0},kip:{name:"kip",base:R.FORCE,prefixes:D.LONG,value:4448.2216,offset:0},kilogramforce:{name:"kilogramforce",base:R.FORCE,prefixes:D.NONE,value:9.80665,offset:0},J:{name:"J",base:R.ENERGY,prefixes:D.SHORT,value:1,offset:0},joule:{name:"joule",base:R.ENERGY,prefixes:D.SHORT,value:1,offset:0},erg:{name:"erg",base:R.ENERGY,prefixes:D.NONE,value:1e-7,offset:0},Wh:{name:"Wh",base:R.ENERGY,prefixes:D.SHORT,value:3600,offset:0},BTU:{name:"BTU",base:R.ENERGY,prefixes:D.BTU,value:1055.05585262,offset:0},eV:{name:"eV",base:R.ENERGY,prefixes:D.SHORT,value:1602176565e-28,offset:0},electronvolt:{name:"electronvolt",base:R.ENERGY,prefixes:D.LONG,value:1602176565e-28,offset:0},W:{name:"W",base:R.POWER,prefixes:D.SHORT,value:1,offset:0},watt:{name:"watt",base:R.POWER,prefixes:D.LONG,value:1,offset:0},hp:{name:"hp",base:R.POWER,prefixes:D.NONE,value:745.6998715386,offset:0},VAR:{name:"VAR",base:R.POWER,prefixes:D.SHORT,value:g.I,offset:0},VA:{name:"VA",base:R.POWER,prefixes:D.SHORT,value:1,offset:0},Pa:{name:"Pa",base:R.PRESSURE,prefixes:D.SHORT,value:1,offset:0},psi:{name:"psi",base:R.PRESSURE,prefixes:D.NONE,value:6894.75729276459,offset:0},atm:{name:"atm",base:R.PRESSURE,prefixes:D.NONE,value:101325,offset:0},bar:{name:"bar",base:R.PRESSURE,prefixes:D.SHORTLONG,value:1e5,offset:0},torr:{name:"torr",base:R.PRESSURE,prefixes:D.NONE,value:133.322,offset:0},mmHg:{name:"mmHg",base:R.PRESSURE,prefixes:D.NONE,value:133.322,offset:0},mmH2O:{name:"mmH2O",base:R.PRESSURE,prefixes:D.NONE,value:9.80665,offset:0},cmH2O:{name:"cmH2O",base:R.PRESSURE,prefixes:D.NONE,value:98.0665,offset:0},coulomb:{name:"coulomb",base:R.ELECTRIC_CHARGE,prefixes:D.LONG,value:1,offset:0},C:{name:"C",base:R.ELECTRIC_CHARGE,prefixes:D.SHORT,value:1,offset:0},farad:{name:"farad",base:R.ELECTRIC_CAPACITANCE,prefixes:D.LONG,value:1,offset:0},F:{name:"F",base:R.ELECTRIC_CAPACITANCE,prefixes:D.SHORT,value:1,offset:0},volt:{name:"volt",base:R.ELECTRIC_POTENTIAL,prefixes:D.LONG,value:1,offset:0},V:{name:"V",base:R.ELECTRIC_POTENTIAL,prefixes:D.SHORT,value:1,offset:0},ohm:{name:"ohm",base:R.ELECTRIC_RESISTANCE,prefixes:D.SHORTLONG,value:1,offset:0},henry:{name:"henry",base:R.ELECTRIC_INDUCTANCE,prefixes:D.LONG,value:1,offset:0},H:{name:"H",base:R.ELECTRIC_INDUCTANCE,prefixes:D.SHORT,value:1,offset:0},siemens:{name:"siemens",base:R.ELECTRIC_CONDUCTANCE,prefixes:D.LONG,value:1,offset:0},S:{name:"S",base:R.ELECTRIC_CONDUCTANCE,prefixes:D.SHORT,value:1,offset:0},weber:{name:"weber",base:R.MAGNETIC_FLUX,prefixes:D.LONG,value:1,offset:0},Wb:{name:"Wb",base:R.MAGNETIC_FLUX,prefixes:D.SHORT,value:1,offset:0},tesla:{name:"tesla",base:R.MAGNETIC_FLUX_DENSITY,prefixes:D.LONG,value:1,offset:0},T:{name:"T",base:R.MAGNETIC_FLUX_DENSITY,prefixes:D.SHORT,value:1,offset:0},b:{name:"b",base:R.BIT,prefixes:D.BINARY_SHORT,value:1,offset:0},bits:{name:"bits",base:R.BIT,prefixes:D.BINARY_LONG,value:1,offset:0},B:{name:"B",base:R.BIT,prefixes:D.BINARY_SHORT,value:8,offset:0},bytes:{name:"bytes",base:R.BIT,prefixes:D.BINARY_LONG,value:8,offset:0}},F={meters:"meter",inches:"inch",feet:"foot",yards:"yard",miles:"mile",links:"link",rods:"rod",chains:"chain",angstroms:"angstrom",lt:"l",litres:"litre",liter:"litre",liters:"litre",teaspoons:"teaspoon",tablespoons:"tablespoon",minims:"minim",fluiddrams:"fluiddram",fluidounces:"fluidounce",gills:"gill",cups:"cup",pints:"pint",quarts:"quart",gallons:"gallon",beerbarrels:"beerbarrel",oilbarrels:"oilbarrel",hogsheads:"hogshead",gtts:"gtt",grams:"gram",tons:"ton",tonnes:"tonne",grains:"grain",drams:"dram",ounces:"ounce",poundmasses:"poundmass",hundredweights:"hundredweight",sticks:"stick",lb:"lbm",lbs:"lbm",kips:"kip",kgf:"kilogramforce",acres:"acre",hectares:"hectare",sqfeet:"sqft",sqyard:"sqyd",sqmile:"sqmi",sqmiles:"sqmi",mmhg:"mmHg",mmh2o:"mmH2O",cmh2o:"cmH2O",seconds:"second",secs:"second",minutes:"minute",mins:"minute",hours:"hour",hr:"hour",hrs:"hour",days:"day",weeks:"week",months:"month",years:"year",decades:"decade",centuries:"century",millennia:"millennium",hertz:"hertz",radians:"radian",degrees:"degree",gradians:"gradian",cycles:"cycle",arcsecond:"arcsec",arcseconds:"arcsec",arcminute:"arcmin",arcminutes:"arcmin",BTUs:"BTU",watts:"watt",joules:"joule",amperes:"ampere",coulombs:"coulomb",volts:"volt",ohms:"ohm",farads:"farad",webers:"weber",teslas:"tesla",electronvolts:"electronvolt",moles:"mole",bit:"bits",byte:"bytes"};function B(e){if("BigNumber"===e.number){var t=createBigNumberPi(v);M.rad.value=new v(1),M.deg.value=t.div(180),M.grad.value=t.div(200),M.cycle.value=t.times(2),M.arcsec.value=t.div(648e3),M.arcmin.value=t.div(10800)}else M.rad.value=1,M.deg.value=Math.PI/180,M.grad.value=Math.PI/200,M.cycle.value=2*Math.PI,M.arcsec.value=Math.PI/648e3,M.arcmin.value=Math.PI/10800;M.radian.value=M.rad.value,M.degree.value=M.deg.value,M.gradian.value=M.grad.value}B(i),a&&a("config",(function(e,t){e.number!==t.number&&B(e)}));var L={si:{NONE:{unit:k,prefix:D.NONE[""]},LENGTH:{unit:M.m,prefix:D.SHORT[""]},MASS:{unit:M.g,prefix:D.SHORT.k},TIME:{unit:M.s,prefix:D.SHORT[""]},CURRENT:{unit:M.A,prefix:D.SHORT[""]},TEMPERATURE:{unit:M.K,prefix:D.SHORT[""]},LUMINOUS_INTENSITY:{unit:M.cd,prefix:D.SHORT[""]},AMOUNT_OF_SUBSTANCE:{unit:M.mol,prefix:D.SHORT[""]},ANGLE:{unit:M.rad,prefix:D.SHORT[""]},BIT:{unit:M.bits,prefix:D.SHORT[""]},FORCE:{unit:M.N,prefix:D.SHORT[""]},ENERGY:{unit:M.J,prefix:D.SHORT[""]},POWER:{unit:M.W,prefix:D.SHORT[""]},PRESSURE:{unit:M.Pa,prefix:D.SHORT[""]},ELECTRIC_CHARGE:{unit:M.C,prefix:D.SHORT[""]},ELECTRIC_CAPACITANCE:{unit:M.F,prefix:D.SHORT[""]},ELECTRIC_POTENTIAL:{unit:M.V,prefix:D.SHORT[""]},ELECTRIC_RESISTANCE:{unit:M.ohm,prefix:D.SHORT[""]},ELECTRIC_INDUCTANCE:{unit:M.H,prefix:D.SHORT[""]},ELECTRIC_CONDUCTANCE:{unit:M.S,prefix:D.SHORT[""]},MAGNETIC_FLUX:{unit:M.Wb,prefix:D.SHORT[""]},MAGNETIC_FLUX_DENSITY:{unit:M.T,prefix:D.SHORT[""]},FREQUENCY:{unit:M.Hz,prefix:D.SHORT[""]}}};L.cgs=JSON.parse(JSON.stringify(L.si)),L.cgs.LENGTH={unit:M.m,prefix:D.SHORT.c},L.cgs.MASS={unit:M.g,prefix:D.SHORT[""]},L.cgs.FORCE={unit:M.dyn,prefix:D.SHORT[""]},L.cgs.ENERGY={unit:M.erg,prefix:D.NONE[""]},L.us=JSON.parse(JSON.stringify(L.si)),L.us.LENGTH={unit:M.ft,prefix:D.NONE[""]},L.us.MASS={unit:M.lbm,prefix:D.NONE[""]},L.us.TEMPERATURE={unit:M.degF,prefix:D.NONE[""]},L.us.FORCE={unit:M.lbf,prefix:D.NONE[""]},L.us.ENERGY={unit:M.BTU,prefix:D.BTU[""]},L.us.POWER={unit:M.hp,prefix:D.NONE[""]},L.us.PRESSURE={unit:M.psi,prefix:D.NONE[""]},L.auto=JSON.parse(JSON.stringify(L.si));var j=L.auto;for(var U in C.setUnitSystem=function(e){if(!hasOwnProperty$2(L,e))throw new Error("Unit system "+e+" does not exist. Choices are: "+Object.keys(L).join(", "));j=L[e]},C.getUnitSystem=function(){for(var e in L)if(hasOwnProperty$2(L,e)&&L[e]===j)return e},C.typeConverters={BigNumber:function(e){return new v(e+"")},Fraction:function(e){return new T(e)},Complex:function(e){return e},number:function(e){return e}},C._getNumberConverter=function(e){if(!C.typeConverters[e])throw new TypeError('Unsupported type "'+e+'"');return C.typeConverters[e]},M)if(hasOwnProperty$2(M,U)){var z=M[U];z.dimensions=z.base.dimensions}for(var G in F)if(hasOwnProperty$2(F,G)){var H=M[F[G]],q={};for(var W in H)hasOwnProperty$2(H,W)&&(q[W]=H[W]);q.name=G,M[G]=q}return C.isValidAlpha=function(e){return/^[a-zA-Z]$/.test(e)},C.createUnit=function(e,t){if("object"!=typeof e)throw new TypeError("createUnit expects first parameter to be of type 'Object'");if(t&&t.override)for(var n in e)if(hasOwnProperty$2(e,n)&&C.deleteUnit(n),e[n].aliases)for(var r=0;r0&&!C.isValidAlpha(r)&&!S(r))throw new Error('Invalid unit name (only alphanumeric characters are allowed): "'+e+'"')}}(e);var a,i,o,s=null,l=[],u=0;if(t&&"Unit"===t.type)s=t.clone();else if("string"==typeof t)""!==t&&(a=t);else{if("object"!=typeof t)throw new TypeError('Cannot create unit "'+e+'" from "'+t.toString()+'": expecting "string" or "Unit" or "Object"');a=t.definition,i=t.prefixes,u=t.offset,o=t.baseName,t.aliases&&(l=t.aliases.valueOf())}if(l)for(var c=0;c1e-12){f=!1;break}if(f){d=!0,p.base=R[m];break}}if(!d){o=o||e+"_STUFF";var y={dimensions:s.dimensions.slice(0)};y.key=o,R[o]=y,j[o]={unit:p,prefix:D.NONE[""]},p.base=R[o]}}else{if(o=o||e+"_STUFF",I.indexOf(o)>=0)throw new Error('Cannot create new base unit "'+e+'": a base unit with that name already exists (and cannot be overridden)');for(var b in I.push(o),R)hasOwnProperty$2(R,b)&&(R[b].dimensions[I.length-1]=0);for(var g={dimensions:[]},v=0;v{var{typed:t,Unit:n}=e;return t(name$2a,{Unit:function(e){return e.clone()},string:function(e){return n.isValuelessUnit(e)?new n(null,e):n.parse(e,{allowNoUnits:!0})},"number | BigNumber | Fraction | Complex, string":function(e,t){return new n(e,t)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$29="sparse",dependencies$29=["typed","SparseMatrix"],createSparse=factory(name$29,dependencies$29,(e=>{var{typed:t,SparseMatrix:n}=e;return t(name$29,{"":function(){return new n([])},string:function(e){return new n([],e)},"Array | Matrix":function(e){return new n(e)},"Array | Matrix, string":function(e,t){return new n(e,t)}})})),name$28="createUnit",dependencies$28=["typed","Unit"],createCreateUnit=factory(name$28,dependencies$28,(e=>{var{typed:t,Unit:n}=e;return t(name$28,{"Object, Object":function(e,t){return n.createUnit(e,t)},Object:function(e){return n.createUnit(e,{})},"string, Unit | string | Object, Object":function(e,t,r){var a={};return a[e]=t,n.createUnit(a,r)},"string, Unit | string | Object":function(e,t){var r={};return r[e]=t,n.createUnit(r,{})},string:function(e){var t={};return t[e]={},n.createUnit(t,{})}})})),name$27="acos",dependencies$27=["typed","config","Complex"],createAcos=factory(name$27,dependencies$27,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$27,{number:function(e){return e>=-1&&e<=1||n.predictable?Math.acos(e):new r(e,0).acos()},Complex:function(e){return e.acos()},BigNumber:function(e){return e.acos()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$26="acosh",dependencies$26=["typed","config","Complex"],createAcosh=factory(name$26,dependencies$26,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$26,{number:function(e){return e>=1||n.predictable?acoshNumber(e):e<=-1?new r(Math.log(Math.sqrt(e*e-1)-e),Math.PI):new r(e,0).acosh()},Complex:function(e){return e.acosh()},BigNumber:function(e){return e.acosh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$25="acot",dependencies$25=["typed","BigNumber"],createAcot=factory(name$25,dependencies$25,(e=>{var{typed:t,BigNumber:n}=e;return t(name$25,{number:acotNumber,Complex:function(e){return e.acot()},BigNumber:function(e){return new n(1).div(e).atan()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$24="acoth",dependencies$24=["typed","config","Complex","BigNumber"],createAcoth=factory(name$24,dependencies$24,(e=>{var{typed:t,config:n,Complex:r,BigNumber:a}=e;return t(name$24,{number:function(e){return e>=1||e<=-1||n.predictable?acothNumber(e):new r(e,0).acoth()},Complex:function(e){return e.acoth()},BigNumber:function(e){return new a(1).div(e).atanh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$23="acsc",dependencies$23=["typed","config","Complex","BigNumber"],createAcsc=factory(name$23,dependencies$23,(e=>{var{typed:t,config:n,Complex:r,BigNumber:a}=e;return t(name$23,{number:function(e){return e<=-1||e>=1||n.predictable?acscNumber(e):new r(e,0).acsc()},Complex:function(e){return e.acsc()},BigNumber:function(e){return new a(1).div(e).asin()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$22="acsch",dependencies$22=["typed","BigNumber"],createAcsch=factory(name$22,dependencies$22,(e=>{var{typed:t,BigNumber:n}=e;return t(name$22,{number:acschNumber,Complex:function(e){return e.acsch()},BigNumber:function(e){return new n(1).div(e).asinh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$21="asec",dependencies$21=["typed","config","Complex","BigNumber"],createAsec=factory(name$21,dependencies$21,(e=>{var{typed:t,config:n,Complex:r,BigNumber:a}=e;return t(name$21,{number:function(e){return e<=-1||e>=1||n.predictable?asecNumber(e):new r(e,0).asec()},Complex:function(e){return e.asec()},BigNumber:function(e){return new a(1).div(e).acos()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$20="asech",dependencies$20=["typed","config","Complex","BigNumber"],createAsech=factory(name$20,dependencies$20,(e=>{var{typed:t,config:n,Complex:r,BigNumber:a}=e;return t(name$20,{number:function(e){if(e<=1&&e>=-1||n.predictable){var t=1/e;if(t>0||n.predictable)return asechNumber(e);var a=Math.sqrt(t*t-1);return new r(Math.log(a-t),Math.PI)}return new r(e,0).asech()},Complex:function(e){return e.asech()},BigNumber:function(e){return new a(1).div(e).acosh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1$="asin",dependencies$1$=["typed","config","Complex"],createAsin=factory(name$1$,dependencies$1$,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$1$,{number:function(e){return e>=-1&&e<=1||n.predictable?Math.asin(e):new r(e,0).asin()},Complex:function(e){return e.asin()},BigNumber:function(e){return e.asin()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1_="asinh",dependencies$1_=["typed"],createAsinh=factory(name$1_,dependencies$1_,(e=>{var{typed:t}=e;return t("asinh",{number:asinhNumber,Complex:function(e){return e.asinh()},BigNumber:function(e){return e.asinh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1Z="atan",dependencies$1Z=["typed"],createAtan=factory(name$1Z,dependencies$1Z,(e=>{var{typed:t}=e;return t("atan",{number:function(e){return Math.atan(e)},Complex:function(e){return e.atan()},BigNumber:function(e){return e.atan()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1Y="atan2",dependencies$1Y=["typed","matrix","equalScalar","BigNumber","DenseMatrix"],createAtan2=factory(name$1Y,dependencies$1Y,(e=>{var{typed:t,matrix:n,equalScalar:r,BigNumber:a,DenseMatrix:i}=e,o=createAlgorithm02({typed:t,equalScalar:r}),s=createAlgorithm03({typed:t}),l=createAlgorithm09({typed:t,equalScalar:r}),u=createAlgorithm11({typed:t,equalScalar:r}),c=createAlgorithm12({typed:t,DenseMatrix:i}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$1Y,{"number, number":Math.atan2,"BigNumber, BigNumber":function(e,t){return a.atan2(e,t)},"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return u(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return d(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return c(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return d(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return d(n(e),t,this,!1).valueOf()},"number | BigNumber, Array":function(e,t){return d(n(t),e,this,!0).valueOf()}})})),name$1X="atanh",dependencies$1X=["typed","config","Complex"],createAtanh=factory(name$1X,dependencies$1X,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$1X,{number:function(e){return e<=1&&e>=-1||n.predictable?atanhNumber(e):new r(e,0).atanh()},Complex:function(e){return e.atanh()},BigNumber:function(e){return e.atanh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1W="cos",dependencies$1W=["typed"],createCos=factory(name$1W,dependencies$1W,(e=>{var{typed:t}=e;return t(name$1W,{number:Math.cos,Complex:function(e){return e.cos()},BigNumber:function(e){return e.cos()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function cos is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1V="cosh",dependencies$1V=["typed"],createCosh=factory(name$1V,dependencies$1V,(e=>{var{typed:t}=e;return t(name$1V,{number:cosh$2,Complex:function(e){return e.cosh()},BigNumber:function(e){return e.cosh()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function cosh is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1U="cot",dependencies$1U=["typed","BigNumber"],createCot=factory(name$1U,dependencies$1U,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1U,{number:cotNumber,Complex:function(e){return e.cot()},BigNumber:function(e){return new n(1).div(e.tan())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function cot is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1T="coth",dependencies$1T=["typed","BigNumber"],createCoth=factory(name$1T,dependencies$1T,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1T,{number:cothNumber,Complex:function(e){return e.coth()},BigNumber:function(e){return new n(1).div(e.tanh())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function coth is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1S="csc",dependencies$1S=["typed","BigNumber"],createCsc=factory(name$1S,dependencies$1S,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1S,{number:cscNumber,Complex:function(e){return e.csc()},BigNumber:function(e){return new n(1).div(e.sin())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function csc is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1R="csch",dependencies$1R=["typed","BigNumber"],createCsch=factory(name$1R,dependencies$1R,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1R,{number:cschNumber,Complex:function(e){return e.csch()},BigNumber:function(e){return new n(1).div(e.sinh())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function csch is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1Q="sec",dependencies$1Q=["typed","BigNumber"],createSec=factory(name$1Q,dependencies$1Q,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1Q,{number:secNumber,Complex:function(e){return e.sec()},BigNumber:function(e){return new n(1).div(e.cos())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sec is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1P="sech",dependencies$1P=["typed","BigNumber"],createSech=factory(name$1P,dependencies$1P,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1P,{number:sechNumber,Complex:function(e){return e.sech()},BigNumber:function(e){return new n(1).div(e.cosh())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sech is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1O="sin",dependencies$1O=["typed"],createSin=factory(name$1O,dependencies$1O,(e=>{var{typed:t}=e;return t(name$1O,{number:Math.sin,Complex:function(e){return e.sin()},BigNumber:function(e){return e.sin()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sin is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1N="sinh",dependencies$1N=["typed"],createSinh=factory(name$1N,dependencies$1N,(e=>{var{typed:t}=e;return t(name$1N,{number:sinhNumber,Complex:function(e){return e.sinh()},BigNumber:function(e){return e.sinh()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sinh is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1M="tan",dependencies$1M=["typed"],createTan=factory(name$1M,dependencies$1M,(e=>{var{typed:t}=e;return t(name$1M,{number:Math.tan,Complex:function(e){return e.tan()},BigNumber:function(e){return e.tan()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function tan is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1L="tanh",dependencies$1L=["typed"],createTanh=factory(name$1L,dependencies$1L,(e=>{var{typed:t}=e;return t("tanh",{number:tanh$2,Complex:function(e){return e.tanh()},BigNumber:function(e){return e.tanh()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function tanh is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1K="setCartesian",dependencies$1K=["typed","size","subset","compareNatural","Index","DenseMatrix"],createSetCartesian=factory(name$1K,dependencies$1K,(e=>{var{typed:t,size:n,subset:r,compareNatural:a,Index:i,DenseMatrix:o}=e;return t(name$1K,{"Array | Matrix, Array | Matrix":function(e,t){var s=[];if(0!==r(n(e),new i(0))&&0!==r(n(t),new i(0))){var l=flatten$4(Array.isArray(e)?e:e.toArray()).sort(a),u=flatten$4(Array.isArray(t)?t:t.toArray()).sort(a);s=[];for(var c=0;c{var{typed:t,size:n,subset:r,compareNatural:a,Index:i,DenseMatrix:o}=e;return t(name$1J,{"Array | Matrix, Array | Matrix":function(e,t){var s;if(0===r(n(e),new i(0)))s=[];else{if(0===r(n(t),new i(0)))return flatten$4(e.toArray());var l,u=identify(flatten$4(Array.isArray(e)?e:e.toArray()).sort(a)),c=identify(flatten$4(Array.isArray(t)?t:t.toArray()).sort(a));s=[];for(var p=0;p{var{typed:t,size:n,subset:r,compareNatural:a,Index:i,DenseMatrix:o}=e;return t(name$1I,{"Array | Matrix":function(e){var t;if(0===r(n(e),new i(0)))t=[];else{var s=flatten$4(Array.isArray(e)?e:e.toArray()).sort(a);(t=[]).push(s[0]);for(var l=1;l{var{typed:t,size:n,subset:r,compareNatural:a,Index:i,DenseMatrix:o}=e;return t(name$1H,{"Array | Matrix, Array | Matrix":function(e,t){var s;if(0===r(n(e),new i(0))||0===r(n(t),new i(0)))s=[];else{var l=identify(flatten$4(Array.isArray(e)?e:e.toArray()).sort(a)),u=identify(flatten$4(Array.isArray(t)?t:t.toArray()).sort(a));s=[];for(var c=0;c{var{typed:t,size:n,subset:r,compareNatural:a,Index:i}=e;return t(name$1G,{"Array | Matrix, Array | Matrix":function(e,t){if(0===r(n(e),new i(0)))return!0;if(0===r(n(t),new i(0)))return!1;for(var o,s=identify(flatten$4(Array.isArray(e)?e:e.toArray()).sort(a)),l=identify(flatten$4(Array.isArray(t)?t:t.toArray()).sort(a)),u=0;u{var{typed:t,size:n,subset:r,compareNatural:a,Index:i}=e;return t(name$1F,{"number | BigNumber | Fraction | Complex, Array | Matrix":function(e,t){if(0===r(n(t),new i(0)))return 0;for(var o=flatten$4(Array.isArray(t)?t:t.toArray()),s=0,l=0;l{var{typed:t,size:n,subset:r,compareNatural:a,Index:i}=e;return t(name$1E,{"Array | Matrix":function(e){if(0===r(n(e),new i(0)))return[];for(var t=flatten$4(Array.isArray(e)?e:e.toArray()).sort(a),s=[],l=0;l.toString(2).length<=t.length;)s.push(o(t,l.toString(2).split("").reverse())),l++;return function(e){for(var t=[],n=e.length-1;n>0;n--)for(var r=0;re[r+1].length&&(t=e[r],e[r]=e[r+1],e[r+1]=t);return e}(s)}});function o(e,t){for(var n=[],r=0;r{var{typed:t,compareNatural:n}=e;return t(name$1D,{"Array | Matrix":function(e){return Array.isArray(e)?flatten$4(e).length:flatten$4(e.toArray()).length},"Array | Matrix, boolean":function(e,t){if(!1===t||0===e.length)return Array.isArray(e)?flatten$4(e).length:flatten$4(e.toArray()).length;for(var r=flatten$4(Array.isArray(e)?e:e.toArray()).sort(n),a=1,i=1;i{var{typed:t,size:n,concat:r,subset:a,setDifference:i,Index:o}=e;return t(name$1C,{"Array | Matrix, Array | Matrix":function(e,t){if(0===a(n(e),new o(0)))return flatten$4(t);if(0===a(n(t),new o(0)))return flatten$4(e);var s=flatten$4(e),l=flatten$4(t);return r(i(s,l),i(l,s))}})})),name$1B="setUnion",dependencies$1B=["typed","size","concat","subset","setIntersect","setSymDifference","Index"],createSetUnion=factory(name$1B,dependencies$1B,(e=>{var{typed:t,size:n,concat:r,subset:a,setIntersect:i,setSymDifference:o,Index:s}=e;return t(name$1B,{"Array | Matrix, Array | Matrix":function(e,t){if(0===a(n(e),new s(0)))return flatten$4(t);if(0===a(n(t),new s(0)))return flatten$4(e);var l=flatten$4(e),u=flatten$4(t);return r(o(l,u),i(l,u))}})})),name$1A="add",dependencies$1A=["typed","matrix","addScalar","equalScalar","DenseMatrix","SparseMatrix"],createAdd=factory(name$1A,dependencies$1A,(e=>{var{typed:t,matrix:n,addScalar:r,equalScalar:a,DenseMatrix:i,SparseMatrix:o}=e,s=createAlgorithm01({typed:t}),l=createAlgorithm04({typed:t,equalScalar:a}),u=createAlgorithm10({typed:t,DenseMatrix:i}),c=createAlgorithm13({typed:t}),p=createAlgorithm14({typed:t});return t(name$1A,extend$2({"DenseMatrix, DenseMatrix":function(e,t){return c(e,t,r)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,r,!1)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,r,!0)},"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,r)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"DenseMatrix, any":function(e,t){return p(e,t,r,!1)},"SparseMatrix, any":function(e,t){return u(e,t,r,!1)},"any, DenseMatrix":function(e,t){return p(t,e,r,!0)},"any, SparseMatrix":function(e,t){return u(t,e,r,!0)},"Array, any":function(e,t){return p(n(e),t,r,!1).valueOf()},"any, Array":function(e,t){return p(n(t),e,r,!0).valueOf()},"any, any":r,"any, any, ...any":function(e,t,n){for(var r=this(e,t),a=0;a{var{typed:t,abs:n,addScalar:r,divideScalar:a,multiplyScalar:i,sqrt:o,smaller:s,isPositive:l}=e;return t(name$1z,{"... number | BigNumber":function(e){for(var t=0,u=0,c=0;c{var{typed:t,abs:n,add:r,pow:a,conj:i,sqrt:o,multiply:s,equalScalar:l,larger:u,smaller:c,matrix:p,ctranspose:d,eigs:m}=e;return t(name$1y,{number:Math.abs,Complex:function(e){return e.abs()},BigNumber:function(e){return e.abs()},boolean:function(e){return Math.abs(e)},Array:function(e){return y(p(e),2)},Matrix:function(e){return y(e,2)},"number | Complex | BigNumber | boolean, number | BigNumber | string":function(e){return this(e)},"Array, number | BigNumber | string":function(e,t){return y(p(e),t)},"Matrix, number | BigNumber | string":function(e,t){return y(e,t)}});function f(e,t){if(t===Number.POSITIVE_INFINITY||"inf"===t)return function(e){var t=0;return e.forEach((function(e){var r=n(e);u(r,t)&&(t=r)}),!0),t}(e);if(t===Number.NEGATIVE_INFINITY||"-inf"===t)return function(e){var t;return e.forEach((function(e){var r=n(e);t&&!c(r,t)||(t=r)}),!0),t||0}(e);if("fro"===t)return y(e,2);if("number"==typeof t&&!isNaN(t)){if(!l(t,0)){var i=0;return e.forEach((function(e){i=r(a(n(e),t),i)}),!0),a(i,1/t)}return Number.POSITIVE_INFINITY}throw new Error("Unsupported parameter value")}function h(e,t){if(1===t)return function(e){var t=[],a=0;return e.forEach((function(e,i){var o=i[1],s=r(t[o]||0,n(e));u(s,a)&&(a=s),t[o]=s}),!0),a}(e);if(t===Number.POSITIVE_INFINITY||"inf"===t)return function(e){var t=[],a=0;return e.forEach((function(e,i){var o=i[0],s=r(t[o]||0,n(e));u(s,a)&&(a=s),t[o]=s}),!0),a}(e);if("fro"===t)return function(e){var t=0;return e.forEach((function(e,n){t=r(t,s(e,i(e)))})),n(o(t))}(e);if(2===t)return function(e){var t=e.size();if(t[0]!==t[1])throw new RangeError("Invalid matrix dimensions");var r=d(e),a=s(r,e),i=m(a).values.toArray(),l=i[i.length-1];return n(o(l))}(e);throw new Error("Unsupported parameter value "+t)}function y(e,t){var n=e.size();if(1===n.length)return f(e,t);if(2===n.length){if(n[0]&&n[1])return h(e,t);throw new RangeError("Invalid matrix dimensions")}}})),name$1x="dot",dependencies$1x=["typed","addScalar","multiplyScalar","conj","size"],createDot=factory(name$1x,dependencies$1x,(e=>{var{typed:t,addScalar:n,multiplyScalar:r,conj:a,size:i}=e;return t(name$1x,{"Array | DenseMatrix, Array | DenseMatrix":function(e,i){var l=o(e,i),u=isMatrix(e)?e._data:e,c=isMatrix(e)?e._datatype:void 0,p=isMatrix(i)?i._data:i,d=isMatrix(i)?i._datatype:void 0,m=2===s(e).length,f=2===s(i).length,h=n,y=r;if(c&&d&&c===d&&"string"==typeof c){var b=c;h=t.find(n,[b,b]),y=t.find(r,[b,b])}if(!m&&!f){for(var g=y(a(u[0]),p[0]),v=1;vh?m++:f===h&&(u=c(u,p(i[d],l[m])),d++,m++)}return u}});function o(e,t){var n,r,a=s(e),i=s(t);if(1===a.length)n=a[0];else{if(2!==a.length||1!==a[1])throw new RangeError("Expected a column vector, instead got a matrix of size ("+a.join(", ")+")");n=a[0]}if(1===i.length)r=i[0];else{if(2!==i.length||1!==i[1])throw new RangeError("Expected a column vector, instead got a matrix of size ("+i.join(", ")+")");r=i[0]}if(n!==r)throw new RangeError("Vectors must have equal length ("+n+" != "+r+")");if(0===n)throw new RangeError("Cannot calculate the dot product of empty vectors");return n}function s(e){return isMatrix(e)?e.size():i(e)}})),name$1w="trace",dependencies$1w=["typed","matrix","add"],createTrace=factory(name$1w,dependencies$1w,(e=>{var{typed:t,matrix:n,add:r}=e;return t("trace",{Array:function(e){return a(n(e))},SparseMatrix:function(e){var t=e._values,n=e._index,a=e._ptr,i=e._size,o=i[0],s=i[1];if(o===s){var l=0;if(t.length>0)for(var u=0;uu)break}return l}throw new RangeError("Matrix must be square (size: "+format$1(i)+")")},DenseMatrix:a,any:clone$2});function a(e){var t=e._size,n=e._data;switch(t.length){case 1:if(1===t[0])return clone$2(n[0]);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");case 2:var a=t[0];if(a===t[1]){for(var i=0,o=0;o{var{typed:t,Index:n}=e;return t(name$1v,{"...number | string | BigNumber | Range | Array | Matrix":function(e){var t=e.map((function(e){return isBigNumber(e)?e.toNumber():Array.isArray(e)||isMatrix(e)?e.map((function(e){return isBigNumber(e)?e.toNumber():e})):e})),r=new n;return n.apply(r,t),r}})})),keywords=new Set(["end"]),name$1u="Node",dependencies$1u=["mathWithTransform"],createNode=factory(name$1u,dependencies$1u,(e=>{var{mathWithTransform:t}=e;function n(){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator")}return n.prototype.evaluate=function(e){return this.compile().evaluate(e)},n.prototype.type="Node",n.prototype.isNode=!0,n.prototype.comment="",n.prototype.compile=function(){var e=this._compile(t,{}),n={};return{evaluate:function(t){var r=createMap$1(t);return function(e){for(var t of[...keywords])if(e.has(t))throw new Error('Scope contains an illegal symbol, "'+t+'" is a reserved keyword')}(r),e(r,n,null)}}},n.prototype._compile=function(e,t){throw new Error("Method _compile should be implemented by type "+this.type)},n.prototype.forEach=function(e){throw new Error("Cannot run forEach on a Node interface")},n.prototype.map=function(e){throw new Error("Cannot run map on a Node interface")},n.prototype._ifNode=function(e){if(!isNode(e))throw new TypeError("Callback function must return a Node");return e},n.prototype.traverse=function(e){e(this,null,null),function e(t,n){t.forEach((function(t,r,a){n(t,r,a),e(t,n)}))}(this,e)},n.prototype.transform=function(e){return function t(n,r,a){var i=e(n,r,a);return i!==n?i:n.map(t)}(this,null,null)},n.prototype.filter=function(e){var t=[];return this.traverse((function(n,r,a){e(n,r,a)&&t.push(n)})),t},n.prototype.clone=function(){throw new Error("Cannot clone a Node interface")},n.prototype.cloneDeep=function(){return this.map((function(e){return e.cloneDeep()}))},n.prototype.equals=function(e){return!!e&&deepStrictEqual(this,e)},n.prototype.toString=function(e){var t=this._getCustomString(e);return void 0!==t?t:this._toString(e)},n.prototype.toJSON=function(){throw new Error("Cannot serialize object: toJSON not implemented by "+this.type)},n.prototype.toHTML=function(e){var t=this._getCustomString(e);return void 0!==t?t:this.toHTML(e)},n.prototype._toString=function(){throw new Error("_toString not implemented for "+this.type)},n.prototype.toTex=function(e){var t=this._getCustomString(e);return void 0!==t?t:this._toTex(e)},n.prototype._toTex=function(e){throw new Error("_toTex not implemented for "+this.type)},n.prototype._getCustomString=function(e){if(e&&"object"==typeof e)switch(typeof e.handler){case"object":case"undefined":return;case"function":return e.handler(this,e);default:throw new TypeError("Object or function expected as callback")}},n.prototype.getIdentifier=function(){return this.type},n.prototype.getContent=function(){return this},n}),{isClass:!0,isNode:!0});function errorTransform(e){return e&&e.isIndexError?new IndexError(e.index+1,e.min+1,void 0!==e.max?e.max+1:void 0):e}function accessFactory(e){var{subset:t}=e;return function(e,n){try{if(Array.isArray(e))return t(e,n);if(e&&"function"==typeof e.subset)return e.subset(n);if("string"==typeof e)return t(e,n);if("object"==typeof e){if(!n.isObjectProperty())throw new TypeError("Cannot apply a numeric index as object property");return getSafeProperty(e,n.getObjectProperty())}throw new TypeError("Cannot apply index: unsupported type of object")}catch(e){throw errorTransform(e)}}}var name$1t="AccessorNode",dependencies$1t=["subset","Node"],createAccessorNode=factory(name$1t,dependencies$1t,(e=>{var{subset:t,Node:n}=e,r=accessFactory({subset:t});function a(e,t){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");if(!isNode(e))throw new TypeError('Node expected for parameter "object"');if(!isIndexNode(t))throw new TypeError('IndexNode expected for parameter "index"');this.object=e||null,this.index=t,Object.defineProperty(this,"name",{get:function(){return this.index?this.index.isObjectProperty()?this.index.getObjectProperty():"":this.object.name||""}.bind(this),set:function(){throw new Error("Cannot assign a new name, name is read-only")}})}function i(e){return!(isAccessorNode(e)||isArrayNode(e)||isConstantNode(e)||isFunctionNode(e)||isObjectNode(e)||isParenthesisNode(e)||isSymbolNode(e))}return a.prototype=new n,a.prototype.type="AccessorNode",a.prototype.isAccessorNode=!0,a.prototype._compile=function(e,t){var n=this.object._compile(e,t),a=this.index._compile(e,t);if(this.index.isObjectProperty()){var i=this.index.getObjectProperty();return function(e,t,r){return getSafeProperty(n(e,t,r),i)}}return function(e,t,i){var o=n(e,t,i),s=a(e,t,o);return r(o,s)}},a.prototype.forEach=function(e){e(this.object,"object",this),e(this.index,"index",this)},a.prototype.map=function(e){return new a(this._ifNode(e(this.object,"object",this)),this._ifNode(e(this.index,"index",this)))},a.prototype.clone=function(){return new a(this.object,this.index)},a.prototype._toString=function(e){var t=this.object.toString(e);return i(this.object)&&(t="("+t+")"),t+this.index.toString(e)},a.prototype.toHTML=function(e){var t=this.object.toHTML(e);return i(this.object)&&(t='('+t+')'),t+this.index.toHTML(e)},a.prototype._toTex=function(e){var t=this.object.toTex(e);return i(this.object)&&(t="\\left(' + object + '\\right)"),t+this.index.toTex(e)},a.prototype.toJSON=function(){return{mathjs:"AccessorNode",object:this.object,index:this.index}},a.fromJSON=function(e){return new a(e.object,e.index)},a}),{isClass:!0,isNode:!0}),name$1s="ArrayNode",dependencies$1s=["Node"],createArrayNode=factory(name$1s,dependencies$1s,(e=>{var{Node:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(this.items=e||[],!Array.isArray(this.items)||!this.items.every(isNode))throw new TypeError("Array containing Nodes expected")}return n.prototype=new t,n.prototype.type="ArrayNode",n.prototype.isArrayNode=!0,n.prototype._compile=function(e,t){var n=map$2(this.items,(function(n){return n._compile(e,t)}));if("Array"!==e.config.matrix){var r=e.matrix;return function(e,t,a){return r(map$2(n,(function(n){return n(e,t,a)})))}}return function(e,t,r){return map$2(n,(function(n){return n(e,t,r)}))}},n.prototype.forEach=function(e){for(var t=0;t['+this.items.map((function(t){return t.toHTML(e)})).join(',')+']'},n.prototype._toTex=function(e){return function t(n,r){var a=n.some(isArrayNode)&&!n.every(isArrayNode),i=r||a,o=i?"&":"\\\\",s=n.map((function(n){return n.items?t(n.items,!r):n.toTex(e)})).join(o);return a||!i||i&&!r?"\\begin{bmatrix}"+s+"\\end{bmatrix}":s}(this.items,!1)},n}),{isClass:!0,isNode:!0});function assignFactory(e){var{subset:t,matrix:n}=e;return function(e,r,a){try{if(Array.isArray(e))return n(e).subset(r,a).valueOf();if(e&&"function"==typeof e.subset)return e.subset(r,a);if("string"==typeof e)return t(e,r,a);if("object"==typeof e){if(!r.isObjectProperty())throw TypeError("Cannot apply a numeric index as object property");return setSafeProperty(e,r.getObjectProperty(),a),e}throw new TypeError("Cannot apply index: unsupported type of object")}catch(e){throw errorTransform(e)}}}var properties=[{AssignmentNode:{},FunctionAssignmentNode:{}},{ConditionalNode:{latexLeftParens:!1,latexRightParens:!1,latexParens:!1}},{"OperatorNode:or":{associativity:"left",associativeWith:[]}},{"OperatorNode:xor":{associativity:"left",associativeWith:[]}},{"OperatorNode:and":{associativity:"left",associativeWith:[]}},{"OperatorNode:bitOr":{associativity:"left",associativeWith:[]}},{"OperatorNode:bitXor":{associativity:"left",associativeWith:[]}},{"OperatorNode:bitAnd":{associativity:"left",associativeWith:[]}},{"OperatorNode:equal":{associativity:"left",associativeWith:[]},"OperatorNode:unequal":{associativity:"left",associativeWith:[]},"OperatorNode:smaller":{associativity:"left",associativeWith:[]},"OperatorNode:larger":{associativity:"left",associativeWith:[]},"OperatorNode:smallerEq":{associativity:"left",associativeWith:[]},"OperatorNode:largerEq":{associativity:"left",associativeWith:[]},RelationalNode:{associativity:"left",associativeWith:[]}},{"OperatorNode:leftShift":{associativity:"left",associativeWith:[]},"OperatorNode:rightArithShift":{associativity:"left",associativeWith:[]},"OperatorNode:rightLogShift":{associativity:"left",associativeWith:[]}},{"OperatorNode:to":{associativity:"left",associativeWith:[]}},{RangeNode:{}},{"OperatorNode:add":{associativity:"left",associativeWith:["OperatorNode:add","OperatorNode:subtract"]},"OperatorNode:subtract":{associativity:"left",associativeWith:[]}},{"OperatorNode:multiply":{associativity:"left",associativeWith:["OperatorNode:multiply","OperatorNode:divide","Operator:dotMultiply","Operator:dotDivide"]},"OperatorNode:divide":{associativity:"left",associativeWith:[],latexLeftParens:!1,latexRightParens:!1,latexParens:!1},"OperatorNode:dotMultiply":{associativity:"left",associativeWith:["OperatorNode:multiply","OperatorNode:divide","OperatorNode:dotMultiply","OperatorNode:doDivide"]},"OperatorNode:dotDivide":{associativity:"left",associativeWith:[]},"OperatorNode:mod":{associativity:"left",associativeWith:[]}},{"OperatorNode:unaryPlus":{associativity:"right"},"OperatorNode:unaryMinus":{associativity:"right"},"OperatorNode:bitNot":{associativity:"right"},"OperatorNode:not":{associativity:"right"}},{"OperatorNode:pow":{associativity:"right",associativeWith:[],latexRightParens:!1},"OperatorNode:dotPow":{associativity:"right",associativeWith:[]}},{"OperatorNode:factorial":{associativity:"left"}},{"OperatorNode:transpose":{associativity:"left"}}];function getPrecedence(e,t){var n=e;"keep"!==t&&(n=e.getContent());for(var r=n.getIdentifier(),a=0;a{var{subset:t,matrix:n,Node:r}=e,a=accessFactory({subset:t}),i=assignFactory({subset:t,matrix:n});function o(e,t,n){if(!(this instanceof o))throw new SyntaxError("Constructor must be called with the new operator");if(this.object=e,this.index=n?t:null,this.value=n||t,!isSymbolNode(e)&&!isAccessorNode(e))throw new TypeError('SymbolNode or AccessorNode expected as "object"');if(isSymbolNode(e)&&"end"===e.name)throw new Error('Cannot assign to symbol "end"');if(this.index&&!isIndexNode(this.index))throw new TypeError('IndexNode expected as "index"');if(!isNode(this.value))throw new TypeError('Node expected as "value"');Object.defineProperty(this,"name",{get:function(){return this.index?this.index.isObjectProperty()?this.index.getObjectProperty():"":this.object.name||""}.bind(this),set:function(){throw new Error("Cannot assign a new name, name is read-only")}})}function s(e,t){t||(t="keep");var n=getPrecedence(e,t),r=getPrecedence(e.value,t);return"all"===t||null!==r&&r<=n}return o.prototype=new r,o.prototype.type="AssignmentNode",o.prototype.isAssignmentNode=!0,o.prototype._compile=function(e,t){var n=this.object._compile(e,t),r=this.index?this.index._compile(e,t):null,o=this.value._compile(e,t),s=this.object.name;if(this.index){if(this.index.isObjectProperty()){var l=this.index.getObjectProperty();return function(e,t,r){var a=n(e,t,r),i=o(e,t,r);return setSafeProperty(a,l,i),i}}if(isSymbolNode(this.object))return function(e,t,a){var l=n(e,t,a),u=o(e,t,a),c=r(e,t,l);return e.set(s,i(l,c,u)),u};var u=this.object.object._compile(e,t);if(this.object.index.isObjectProperty()){var c=this.object.index.getObjectProperty();return function(e,t,n){var a=u(e,t,n),s=getSafeProperty(a,c),l=r(e,t,s),p=o(e,t,n);return setSafeProperty(a,c,i(s,l,p)),p}}var p=this.object.index._compile(e,t);return function(e,t,n){var s=u(e,t,n),l=p(e,t,s),c=a(s,l),d=r(e,t,c),m=o(e,t,n);return i(s,l,i(c,d,m)),m}}if(!isSymbolNode(this.object))throw new TypeError("SymbolNode expected as object");return function(e,t,n){var r=o(e,t,n);return e.set(s,r),r}},o.prototype.forEach=function(e){e(this.object,"object",this),this.index&&e(this.index,"index",this),e(this.value,"value",this)},o.prototype.map=function(e){return new o(this._ifNode(e(this.object,"object",this)),this.index?this._ifNode(e(this.index,"index",this)):null,this._ifNode(e(this.value,"value",this)))},o.prototype.clone=function(){return new o(this.object,this.index,this.value)},o.prototype._toString=function(e){var t=this.object.toString(e),n=this.index?this.index.toString(e):"",r=this.value.toString(e);return s(this,e&&e.parenthesis)&&(r="("+r+")"),t+n+" = "+r},o.prototype.toJSON=function(){return{mathjs:"AssignmentNode",object:this.object,index:this.index,value:this.value}},o.fromJSON=function(e){return new o(e.object,e.index,e.value)},o.prototype.toHTML=function(e){var t=this.object.toHTML(e),n=this.index?this.index.toHTML(e):"",r=this.value.toHTML(e);return s(this,e&&e.parenthesis)&&(r='('+r+')'),t+n+'='+r},o.prototype._toTex=function(e){var t=this.object.toTex(e),n=this.index?this.index.toTex(e):"",r=this.value.toTex(e);return s(this,e&&e.parenthesis)&&(r="\\left(".concat(r,"\\right)")),t+n+":="+r},o}),{isClass:!0,isNode:!0}),name$1q="BlockNode",dependencies$1q=["ResultSet","Node"],createBlockNode=factory(name$1q,dependencies$1q,(e=>{var{ResultSet:t,Node:n}=e;function r(e){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");if(!Array.isArray(e))throw new Error("Array expected");this.blocks=e.map((function(e){var t=e&&e.node,n=!e||void 0===e.visible||e.visible;if(!isNode(t))throw new TypeError('Property "node" must be a Node');if("boolean"!=typeof n)throw new TypeError('Property "visible" must be a boolean');return{node:t,visible:n}}))}return r.prototype=new n,r.prototype.type="BlockNode",r.prototype.isBlockNode=!0,r.prototype._compile=function(e,n){var r=map$2(this.blocks,(function(t){return{evaluate:t.node._compile(e,n),visible:t.visible}}));return function(e,n,a){var i=[];return forEach$1(r,(function(t){var r=t.evaluate(e,n,a);t.visible&&i.push(r)})),new t(i)}},r.prototype.forEach=function(e){for(var t=0;t;')})).join('
')},r.prototype._toTex=function(e){return this.blocks.map((function(t){return t.node.toTex(e)+(t.visible?"":";")})).join("\\;\\;\n")},r}),{isClass:!0,isNode:!0}),name$1p="ConditionalNode",dependencies$1p=["Node"],createConditionalNode=factory(name$1p,dependencies$1p,(e=>{var{Node:t}=e;function n(e,t,r){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!isNode(e))throw new TypeError("Parameter condition must be a Node");if(!isNode(t))throw new TypeError("Parameter trueExpr must be a Node");if(!isNode(r))throw new TypeError("Parameter falseExpr must be a Node");this.condition=e,this.trueExpr=t,this.falseExpr=r}return n.prototype=new t,n.prototype.type="ConditionalNode",n.prototype.isConditionalNode=!0,n.prototype._compile=function(e,t){var n=this.condition._compile(e,t),r=this.trueExpr._compile(e,t),a=this.falseExpr._compile(e,t);return function(e,t,i){return function(e){if("number"==typeof e||"boolean"==typeof e||"string"==typeof e)return!!e;if(e){if(isBigNumber(e))return!e.isZero();if(isComplex(e))return!(!e.re&&!e.im);if(isUnit(e))return!!e.value}if(null==e)return!1;throw new TypeError('Unsupported type of condition "'+typeOf$1(e)+'"')}(n(e,t,i))?r(e,t,i):a(e,t,i)}},n.prototype.forEach=function(e){e(this.condition,"condition",this),e(this.trueExpr,"trueExpr",this),e(this.falseExpr,"falseExpr",this)},n.prototype.map=function(e){return new n(this._ifNode(e(this.condition,"condition",this)),this._ifNode(e(this.trueExpr,"trueExpr",this)),this._ifNode(e(this.falseExpr,"falseExpr",this)))},n.prototype.clone=function(){return new n(this.condition,this.trueExpr,this.falseExpr)},n.prototype._toString=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=getPrecedence(this,t),r=this.condition.toString(e),a=getPrecedence(this.condition,t);("all"===t||"OperatorNode"===this.condition.type||null!==a&&a<=n)&&(r="("+r+")");var i=this.trueExpr.toString(e),o=getPrecedence(this.trueExpr,t);("all"===t||"OperatorNode"===this.trueExpr.type||null!==o&&o<=n)&&(i="("+i+")");var s=this.falseExpr.toString(e),l=getPrecedence(this.falseExpr,t);return("all"===t||"OperatorNode"===this.falseExpr.type||null!==l&&l<=n)&&(s="("+s+")"),r+" ? "+i+" : "+s},n.prototype.toJSON=function(){return{mathjs:"ConditionalNode",condition:this.condition,trueExpr:this.trueExpr,falseExpr:this.falseExpr}},n.fromJSON=function(e){return new n(e.condition,e.trueExpr,e.falseExpr)},n.prototype.toHTML=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=getPrecedence(this,t),r=this.condition.toHTML(e),a=getPrecedence(this.condition,t);("all"===t||"OperatorNode"===this.condition.type||null!==a&&a<=n)&&(r='('+r+')');var i=this.trueExpr.toHTML(e),o=getPrecedence(this.trueExpr,t);("all"===t||"OperatorNode"===this.trueExpr.type||null!==o&&o<=n)&&(i='('+i+')');var s=this.falseExpr.toHTML(e),l=getPrecedence(this.falseExpr,t);return("all"===t||"OperatorNode"===this.falseExpr.type||null!==l&&l<=n)&&(s='('+s+')'),r+'?'+i+':'+s},n.prototype._toTex=function(e){return"\\begin{cases} {"+this.trueExpr.toTex(e)+"}, &\\quad{\\text{if }\\;"+this.condition.toTex(e)+"}\\\\{"+this.falseExpr.toTex(e)+"}, &\\quad{\\text{otherwise}}\\end{cases}"},n}),{isClass:!0,isNode:!0}),_extends=Object.assign||function(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{},n=t.preserveFormatting,r=void 0!==n&&n,a=t.escapeMapFn,i=void 0===a?defaultEscapeMapFn:a,o=String(e),s="",l=i(_extends({},defaultEscapes),r?_extends({},formatEscapes):{}),u=Object.keys(l),c=function(){var e=!1;u.forEach((function(t,n){e||o.length>=t.length&&o.slice(0,t.length)===t&&(s+=l[u[n]],o=o.slice(t.length,o.length),e=!0)})),e||(s+=o.slice(0,1),o=o.slice(1,o.length))};o;)c();return s},latexSymbols={Alpha:"A",alpha:"\\alpha",Beta:"B",beta:"\\beta",Gamma:"\\Gamma",gamma:"\\gamma",Delta:"\\Delta",delta:"\\delta",Epsilon:"E",epsilon:"\\epsilon",varepsilon:"\\varepsilon",Zeta:"Z",zeta:"\\zeta",Eta:"H",eta:"\\eta",Theta:"\\Theta",theta:"\\theta",vartheta:"\\vartheta",Iota:"I",iota:"\\iota",Kappa:"K",kappa:"\\kappa",varkappa:"\\varkappa",Lambda:"\\Lambda",lambda:"\\lambda",Mu:"M",mu:"\\mu",Nu:"N",nu:"\\nu",Xi:"\\Xi",xi:"\\xi",Omicron:"O",omicron:"o",Pi:"\\Pi",pi:"\\pi",varpi:"\\varpi",Rho:"P",rho:"\\rho",varrho:"\\varrho",Sigma:"\\Sigma",sigma:"\\sigma",varsigma:"\\varsigma",Tau:"T",tau:"\\tau",Upsilon:"\\Upsilon",upsilon:"\\upsilon",Phi:"\\Phi",phi:"\\phi",varphi:"\\varphi",Chi:"X",chi:"\\chi",Psi:"\\Psi",psi:"\\psi",Omega:"\\Omega",omega:"\\omega",true:"\\mathrm{True}",false:"\\mathrm{False}",i:"i",inf:"\\infty",Inf:"\\infty",infinity:"\\infty",Infinity:"\\infty",oo:"\\infty",lim:"\\lim",undefined:"\\mathbf{?}"},latexOperators={transpose:"^\\top",ctranspose:"^H",factorial:"!",pow:"^",dotPow:".^\\wedge",unaryPlus:"+",unaryMinus:"-",bitNot:"\\~",not:"\\neg",multiply:"\\cdot",divide:"\\frac",dotMultiply:".\\cdot",dotDivide:".:",mod:"\\mod",add:"+",subtract:"-",to:"\\rightarrow",leftShift:"<<",rightArithShift:">>",rightLogShift:">>>",equal:"=",unequal:"\\neq",smaller:"<",larger:">",smallerEq:"\\leq",largerEq:"\\geq",bitAnd:"\\&",bitXor:"\\underline{|}",bitOr:"|",and:"\\wedge",xor:"\\veebar",or:"\\vee"},latexFunctions={abs:{1:"\\left|${args[0]}\\right|"},add:{2:"\\left(${args[0]}".concat(latexOperators.add,"${args[1]}\\right)")},cbrt:{1:"\\sqrt[3]{${args[0]}}"},ceil:{1:"\\left\\lceil${args[0]}\\right\\rceil"},cube:{1:"\\left(${args[0]}\\right)^3"},divide:{2:"\\frac{${args[0]}}{${args[1]}}"},dotDivide:{2:"\\left(${args[0]}".concat(latexOperators.dotDivide,"${args[1]}\\right)")},dotMultiply:{2:"\\left(${args[0]}".concat(latexOperators.dotMultiply,"${args[1]}\\right)")},dotPow:{2:"\\left(${args[0]}".concat(latexOperators.dotPow,"${args[1]}\\right)")},exp:{1:"\\exp\\left(${args[0]}\\right)"},expm1:"\\left(e".concat(latexOperators.pow,"{${args[0]}}-1\\right)"),fix:{1:"\\mathrm{${name}}\\left(${args[0]}\\right)"},floor:{1:"\\left\\lfloor${args[0]}\\right\\rfloor"},gcd:"\\gcd\\left(${args}\\right)",hypot:"\\hypot\\left(${args}\\right)",log:{1:"\\ln\\left(${args[0]}\\right)",2:"\\log_{${args[1]}}\\left(${args[0]}\\right)"},log10:{1:"\\log_{10}\\left(${args[0]}\\right)"},log1p:{1:"\\ln\\left(${args[0]}+1\\right)",2:"\\log_{${args[1]}}\\left(${args[0]}+1\\right)"},log2:"\\log_{2}\\left(${args[0]}\\right)",mod:{2:"\\left(${args[0]}".concat(latexOperators.mod,"${args[1]}\\right)")},multiply:{2:"\\left(${args[0]}".concat(latexOperators.multiply,"${args[1]}\\right)")},norm:{1:"\\left\\|${args[0]}\\right\\|",2:void 0},nthRoot:{2:"\\sqrt[${args[1]}]{${args[0]}}"},nthRoots:{2:"\\{y : $y^{args[1]} = {${args[0]}}\\}"},pow:{2:"\\left(${args[0]}\\right)".concat(latexOperators.pow,"{${args[1]}}")},round:{1:"\\left\\lfloor${args[0]}\\right\\rceil",2:void 0},sign:{1:"\\mathrm{${name}}\\left(${args[0]}\\right)"},sqrt:{1:"\\sqrt{${args[0]}}"},square:{1:"\\left(${args[0]}\\right)^2"},subtract:{2:"\\left(${args[0]}".concat(latexOperators.subtract,"${args[1]}\\right)")},unaryMinus:{1:"".concat(latexOperators.unaryMinus,"\\left(${args[0]}\\right)")},unaryPlus:{1:"".concat(latexOperators.unaryPlus,"\\left(${args[0]}\\right)")},bitAnd:{2:"\\left(${args[0]}".concat(latexOperators.bitAnd,"${args[1]}\\right)")},bitNot:{1:latexOperators.bitNot+"\\left(${args[0]}\\right)"},bitOr:{2:"\\left(${args[0]}".concat(latexOperators.bitOr,"${args[1]}\\right)")},bitXor:{2:"\\left(${args[0]}".concat(latexOperators.bitXor,"${args[1]}\\right)")},leftShift:{2:"\\left(${args[0]}".concat(latexOperators.leftShift,"${args[1]}\\right)")},rightArithShift:{2:"\\left(${args[0]}".concat(latexOperators.rightArithShift,"${args[1]}\\right)")},rightLogShift:{2:"\\left(${args[0]}".concat(latexOperators.rightLogShift,"${args[1]}\\right)")},bellNumbers:{1:"\\mathrm{B}_{${args[0]}}"},catalan:{1:"\\mathrm{C}_{${args[0]}}"},stirlingS2:{2:"\\mathrm{S}\\left(${args}\\right)"},arg:{1:"\\arg\\left(${args[0]}\\right)"},conj:{1:"\\left(${args[0]}\\right)^*"},im:{1:"\\Im\\left\\lbrace${args[0]}\\right\\rbrace"},re:{1:"\\Re\\left\\lbrace${args[0]}\\right\\rbrace"},and:{2:"\\left(${args[0]}".concat(latexOperators.and,"${args[1]}\\right)")},not:{1:latexOperators.not+"\\left(${args[0]}\\right)"},or:{2:"\\left(${args[0]}".concat(latexOperators.or,"${args[1]}\\right)")},xor:{2:"\\left(${args[0]}".concat(latexOperators.xor,"${args[1]}\\right)")},cross:{2:"\\left(${args[0]}\\right)\\times\\left(${args[1]}\\right)"},ctranspose:{1:"\\left(${args[0]}\\right)".concat(latexOperators.ctranspose)},det:{1:"\\det\\left(${args[0]}\\right)"},dot:{2:"\\left(${args[0]}\\cdot${args[1]}\\right)"},expm:{1:"\\exp\\left(${args[0]}\\right)"},inv:{1:"\\left(${args[0]}\\right)^{-1}"},pinv:{1:"\\left(${args[0]}\\right)^{+}"},sqrtm:{1:"{${args[0]}}".concat(latexOperators.pow,"{\\frac{1}{2}}")},trace:{1:"\\mathrm{tr}\\left(${args[0]}\\right)"},transpose:{1:"\\left(${args[0]}\\right)".concat(latexOperators.transpose)},combinations:{2:"\\binom{${args[0]}}{${args[1]}}"},combinationsWithRep:{2:"\\left(\\!\\!{\\binom{${args[0]}}{${args[1]}}}\\!\\!\\right)"},factorial:{1:"\\left(${args[0]}\\right)".concat(latexOperators.factorial)},gamma:{1:"\\Gamma\\left(${args[0]}\\right)"},lgamma:{1:"\\ln\\Gamma\\left(${args[0]}\\right)"},equal:{2:"\\left(${args[0]}".concat(latexOperators.equal,"${args[1]}\\right)")},larger:{2:"\\left(${args[0]}".concat(latexOperators.larger,"${args[1]}\\right)")},largerEq:{2:"\\left(${args[0]}".concat(latexOperators.largerEq,"${args[1]}\\right)")},smaller:{2:"\\left(${args[0]}".concat(latexOperators.smaller,"${args[1]}\\right)")},smallerEq:{2:"\\left(${args[0]}".concat(latexOperators.smallerEq,"${args[1]}\\right)")},unequal:{2:"\\left(${args[0]}".concat(latexOperators.unequal,"${args[1]}\\right)")},erf:{1:"erf\\left(${args[0]}\\right)"},max:"\\max\\left(${args}\\right)",min:"\\min\\left(${args}\\right)",variance:"\\mathrm{Var}\\left(${args}\\right)",acos:{1:"\\cos^{-1}\\left(${args[0]}\\right)"},acosh:{1:"\\cosh^{-1}\\left(${args[0]}\\right)"},acot:{1:"\\cot^{-1}\\left(${args[0]}\\right)"},acoth:{1:"\\coth^{-1}\\left(${args[0]}\\right)"},acsc:{1:"\\csc^{-1}\\left(${args[0]}\\right)"},acsch:{1:"\\mathrm{csch}^{-1}\\left(${args[0]}\\right)"},asec:{1:"\\sec^{-1}\\left(${args[0]}\\right)"},asech:{1:"\\mathrm{sech}^{-1}\\left(${args[0]}\\right)"},asin:{1:"\\sin^{-1}\\left(${args[0]}\\right)"},asinh:{1:"\\sinh^{-1}\\left(${args[0]}\\right)"},atan:{1:"\\tan^{-1}\\left(${args[0]}\\right)"},atan2:{2:"\\mathrm{atan2}\\left(${args}\\right)"},atanh:{1:"\\tanh^{-1}\\left(${args[0]}\\right)"},cos:{1:"\\cos\\left(${args[0]}\\right)"},cosh:{1:"\\cosh\\left(${args[0]}\\right)"},cot:{1:"\\cot\\left(${args[0]}\\right)"},coth:{1:"\\coth\\left(${args[0]}\\right)"},csc:{1:"\\csc\\left(${args[0]}\\right)"},csch:{1:"\\mathrm{csch}\\left(${args[0]}\\right)"},sec:{1:"\\sec\\left(${args[0]}\\right)"},sech:{1:"\\mathrm{sech}\\left(${args[0]}\\right)"},sin:{1:"\\sin\\left(${args[0]}\\right)"},sinh:{1:"\\sinh\\left(${args[0]}\\right)"},tan:{1:"\\tan\\left(${args[0]}\\right)"},tanh:{1:"\\tanh\\left(${args[0]}\\right)"},to:{2:"\\left(${args[0]}".concat(latexOperators.to,"${args[1]}\\right)")},numeric:function(e,t){return e.args[0].toTex()},number:{0:"0",1:"\\left(${args[0]}\\right)",2:"\\left(\\left(${args[0]}\\right)${args[1]}\\right)"},string:{0:'\\mathtt{""}',1:"\\mathrm{string}\\left(${args[0]}\\right)"},bignumber:{0:"0",1:"\\left(${args[0]}\\right)"},complex:{0:"0",1:"\\left(${args[0]}\\right)",2:"\\left(\\left(${args[0]}\\right)+".concat(latexSymbols.i,"\\cdot\\left(${args[1]}\\right)\\right)")},matrix:{0:"\\begin{bmatrix}\\end{bmatrix}",1:"\\left(${args[0]}\\right)",2:"\\left(${args[0]}\\right)"},sparse:{0:"\\begin{bsparse}\\end{bsparse}",1:"\\left(${args[0]}\\right)"},unit:{1:"\\left(${args[0]}\\right)",2:"\\left(\\left(${args[0]}\\right)${args[1]}\\right)"}},defaultTemplate="\\mathrm{${name}}\\left(${args}\\right)",latexUnits={deg:"^\\circ"};function escapeLatex(e){return dist(e,{preserveFormatting:!0})}function toSymbol(e,t){return(t=void 0!==t&&t)?hasOwnProperty$2(latexUnits,e)?latexUnits[e]:"\\mathrm{"+escapeLatex(e)+"}":hasOwnProperty$2(latexSymbols,e)?latexSymbols[e]:escapeLatex(e)}var name$1o="ConstantNode",dependencies$1o=["Node"],createConstantNode=factory(name$1o,dependencies$1o,(e=>{var{Node:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");this.value=e}return n.prototype=new t,n.prototype.type="ConstantNode",n.prototype.isConstantNode=!0,n.prototype._compile=function(e,t){var n=this.value;return function(){return n}},n.prototype.forEach=function(e){},n.prototype.map=function(e){return this.clone()},n.prototype.clone=function(){return new n(this.value)},n.prototype._toString=function(e){return format$1(this.value,e)},n.prototype.toHTML=function(e){var t=this._toString(e);switch(typeOf$1(this.value)){case"number":case"BigNumber":case"Fraction":return''+t+"";case"string":return''+t+"";case"boolean":return''+t+"";case"null":return''+t+"";case"undefined":return''+t+"";default:return''+t+""}},n.prototype.toJSON=function(){return{mathjs:"ConstantNode",value:this.value}},n.fromJSON=function(e){return new n(e.value)},n.prototype._toTex=function(e){var t=this._toString(e);switch(typeOf$1(this.value)){case"string":return"\\mathtt{"+escapeLatex(t)+"}";case"number":case"BigNumber":if(!isFinite(this.value))return this.value.valueOf()<0?"-\\infty":"\\infty";var n=t.toLowerCase().indexOf("e");return-1!==n?t.substring(0,n)+"\\cdot10^{"+t.substring(n+1)+"}":t;case"Fraction":return this.value.toLatex();default:return t}},n}),{isClass:!0,isNode:!0}),name$1n="FunctionAssignmentNode",dependencies$1n=["typed","Node"],createFunctionAssignmentNode=factory(name$1n,dependencies$1n,(e=>{var{typed:t,Node:n}=e;function r(e,t,n){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");if("string"!=typeof e)throw new TypeError('String expected for parameter "name"');if(!Array.isArray(t))throw new TypeError('Array containing strings or objects expected for parameter "params"');if(!isNode(n))throw new TypeError('Node expected for parameter "expr"');if(keywords.has(e))throw new Error('Illegal function name, "'+e+'" is a reserved keyword');this.name=e,this.params=t.map((function(e){return e&&e.name||e})),this.types=t.map((function(e){return e&&e.type||"any"})),this.expr=n}function a(e,t){var n=getPrecedence(e,t),r=getPrecedence(e.expr,t);return"all"===t||null!==r&&r<=n}return r.prototype=new n,r.prototype.type="FunctionAssignmentNode",r.prototype.isFunctionAssignmentNode=!0,r.prototype._compile=function(e,n){var r=Object.create(n);forEach$1(this.params,(function(e){r[e]=!0}));var a=this.expr._compile(e,r),i=this.name,o=this.params,s=join(this.types,","),l=i+"("+join(this.params,", ")+")";return function(e,n,r){var u={};u[s]=function(){for(var t=Object.create(n),i=0;i'+escape$1(this.params[r])+"");var i=this.expr.toHTML(e);return a(this,t)&&(i='('+i+')'),''+escape$1(this.name)+'('+n.join(',')+')='+i},r.prototype._toTex=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=this.expr.toTex(e);return a(this,t)&&(n="\\left(".concat(n,"\\right)")),"\\mathrm{"+this.name+"}\\left("+this.params.map(toSymbol).join(",")+"\\right):="+n},r}),{isClass:!0,isNode:!0}),name$1m="IndexNode",dependencies$1m=["Node","size"],createIndexNode=factory(name$1m,dependencies$1m,(e=>{var{Node:t,size:n}=e;function r(e,t){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");if(this.dimensions=e,this.dotNotation=t||!1,!Array.isArray(e)||!e.every(isNode))throw new TypeError('Array containing Nodes expected for parameter "dimensions"');if(this.dotNotation&&!this.isObjectProperty())throw new Error("dotNotation only applicable for object properties")}return r.prototype=new t,r.prototype.type="IndexNode",r.prototype.isIndexNode=!0,r.prototype._compile=function(e,t){var r=map$2(this.dimensions,(function(r,a){if(r.filter((e=>e.isSymbolNode&&"end"===e.name)).length>0){var i=Object.create(t);i.end=!0;var o=r._compile(e,i);return function(e,t,r){if(!isMatrix(r)&&!isArray$1(r)&&!isString$1(r))throw new TypeError('Cannot resolve "end": context must be a Matrix, Array, or string but is '+typeOf$1(r));var i=n(r).valueOf(),s=Object.create(t);return s.end=i[a],o(e,s,r)}}return r._compile(e,t)})),a=getSafeProperty(e,"index");return function(e,t,n){var i=map$2(r,(function(r){return r(e,t,n)}));return a(...i)}},r.prototype.forEach=function(e){for(var t=0;t.'+escape$1(this.getObjectProperty())+"":'['+t.join(',')+']'},r.prototype._toTex=function(e){var t=this.dimensions.map((function(t){return t.toTex(e)}));return this.dotNotation?"."+this.getObjectProperty():"_{"+t.join(",")+"}"},r}),{isClass:!0,isNode:!0}),name$1l="ObjectNode",dependencies$1l=["Node"],createObjectNode=factory(name$1l,dependencies$1l,(e=>{var{Node:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(this.properties=e||{},e&&("object"!=typeof e||!Object.keys(e).every((function(t){return isNode(e[t])}))))throw new TypeError("Object containing Nodes expected")}return n.prototype=new t,n.prototype.type="ObjectNode",n.prototype.isObjectNode=!0,n.prototype._compile=function(e,t){var n={};for(var r in this.properties)if(hasOwnProperty$2(this.properties,r)){var a=stringify(r),i=JSON.parse(a);if(!isSafeProperty(this.properties,i))throw new Error('No access to property "'+i+'"');n[i]=this.properties[r]._compile(e,t)}return function(e,t,r){var a={};for(var i in n)hasOwnProperty$2(n,i)&&(a[i]=n[i](e,t,r));return a}},n.prototype.forEach=function(e){for(var t in this.properties)hasOwnProperty$2(this.properties,t)&&e(this.properties[t],"properties["+stringify(t)+"]",this)},n.prototype.map=function(e){var t={};for(var r in this.properties)hasOwnProperty$2(this.properties,r)&&(t[r]=this._ifNode(e(this.properties[r],"properties["+stringify(r)+"]",this)));return new n(t)},n.prototype.clone=function(){var e={};for(var t in this.properties)hasOwnProperty$2(this.properties,t)&&(e[t]=this.properties[t]);return new n(e)},n.prototype._toString=function(e){var t=[];for(var n in this.properties)hasOwnProperty$2(this.properties,n)&&t.push(stringify(n)+": "+this.properties[n].toString(e));return"{"+t.join(", ")+"}"},n.prototype.toJSON=function(){return{mathjs:"ObjectNode",properties:this.properties}},n.fromJSON=function(e){return new n(e.properties)},n.prototype.toHTML=function(e){var t=[];for(var n in this.properties)hasOwnProperty$2(this.properties,n)&&t.push(''+escape$1(n)+':'+this.properties[n].toHTML(e));return'{'+t.join(',')+'}'},n.prototype._toTex=function(e){var t=[];for(var n in this.properties)hasOwnProperty$2(this.properties,n)&&t.push("\\mathbf{"+n+":} & "+this.properties[n].toTex(e)+"\\\\");return"\\left\\{\\begin{array}{ll}".concat(t.join("\n"),"\\end{array}\\right\\}")},n}),{isClass:!0,isNode:!0}),name$1k="OperatorNode",dependencies$1k=["Node"],createOperatorNode=factory(name$1k,dependencies$1k,(e=>{var{Node:t}=e;function n(e,t,r,a,i){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if("string"!=typeof e)throw new TypeError('string expected for parameter "op"');if("string"!=typeof t)throw new TypeError('string expected for parameter "fn"');if(!Array.isArray(r)||!r.every(isNode))throw new TypeError('Array containing Nodes expected for parameter "args"');this.implicit=!0===a,this.isPercentage=!0===i,this.op=e,this.fn=t,this.args=r||[]}function r(e,t,n,r,a){var i,o=getPrecedence(e,t),s=getAssociativity(e,t);if("all"===t||r.length>2&&"OperatorNode:add"!==e.getIdentifier()&&"OperatorNode:multiply"!==e.getIdentifier())return r.map((function(e){switch(e.getContent().type){case"ArrayNode":case"ConstantNode":case"SymbolNode":case"ParenthesisNode":return!1;default:return!0}}));switch(r.length){case 0:i=[];break;case 1:var l=getPrecedence(r[0],t);if(a&&null!==l){var u,c;if("keep"===t?(u=r[0].getIdentifier(),c=e.getIdentifier()):(u=r[0].getContent().getIdentifier(),c=e.getContent().getIdentifier()),!1===properties[o][c].latexLeftParens){i=[!1];break}if(!1===properties[l][u].latexParens){i=[!1];break}}if(null===l){i=[!1];break}if(l<=o){i=[!0];break}i=[!1];break;case 2:var p,d,m=getPrecedence(r[0],t),f=isAssociativeWith(e,r[0],t);p=null!==m&&(m===o&&"right"===s&&!f||m=2&&"OperatorNode:multiply"===e.getIdentifier()&&e.implicit&&"auto"===t&&"hide"===n&&(i=r.map((function(e,t){var n="ParenthesisNode"===e.getIdentifier();return!(!i[t]&&!n)}))),i}return n.prototype=new t,n.prototype.type="OperatorNode",n.prototype.isOperatorNode=!0,n.prototype._compile=function(e,t){if("string"!=typeof this.fn||!isSafeMethod(e,this.fn))throw e[this.fn]?new Error('No access to function "'+this.fn+'"'):new Error("Function "+this.fn+' missing in provided namespace "math"');var n=getSafeProperty(e,this.fn),r=map$2(this.args,(function(n){return n._compile(e,t)}));if(1===r.length){var a=r[0];return function(e,t,r){return n(a(e,t,r))}}if(2===r.length){var i=r[0],o=r[1];return function(e,t,r){return n(i(e,t,r),o(e,t,r))}}return function(e,t,a){return n.apply(null,map$2(r,(function(n){return n(e,t,a)})))}},n.prototype.forEach=function(e){for(var t=0;t2&&("OperatorNode:add"===this.getIdentifier()||"OperatorNode:multiply"===this.getIdentifier())){var p=a.map((function(t,n){return t=t.toString(e),i[n]&&(t="("+t+")"),t}));return this.implicit&&"OperatorNode:multiply"===this.getIdentifier()&&"hide"===n?p.join(" "):p.join(" "+this.op+" ")}return this.fn+"("+this.args.join(", ")+")"},n.prototype.toJSON=function(){return{mathjs:"OperatorNode",op:this.op,fn:this.fn,args:this.args,implicit:this.implicit,isPercentage:this.isPercentage}},n.fromJSON=function(e){return new n(e.op,e.fn,e.args,e.implicit,e.isPercentage)},n.prototype.toHTML=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=e&&e.implicit?e.implicit:"hide",a=this.args,i=r(this,t,n,a,!1);if(1===a.length){var o=getAssociativity(this,t),s=a[0].toHTML(e);return i[0]&&(s='('+s+')'),"right"===o?''+escape$1(this.op)+""+s:s+''+escape$1(this.op)+""}if(2===a.length){var l=a[0].toHTML(e),u=a[1].toHTML(e);return i[0]&&(l='('+l+')'),i[1]&&(u='('+u+')'),this.implicit&&"OperatorNode:multiply"===this.getIdentifier()&&"hide"===n?l+''+u:l+''+escape$1(this.op)+""+u}var c=a.map((function(t,n){return t=t.toHTML(e),i[n]&&(t='('+t+')'),t}));return a.length>2&&("OperatorNode:add"===this.getIdentifier()||"OperatorNode:multiply"===this.getIdentifier())?this.implicit&&"OperatorNode:multiply"===this.getIdentifier()&&"hide"===n?c.join(''):c.join(''+escape$1(this.op)+""):''+escape$1(this.fn)+'('+c.join(',')+')'},n.prototype._toTex=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=e&&e.implicit?e.implicit:"hide",a=this.args,i=r(this,t,n,a,!0),o=latexOperators[this.fn];if(o=void 0===o?this.op:o,1===a.length){var s=getAssociativity(this,t),l=a[0].toTex(e);return i[0]&&(l="\\left(".concat(l,"\\right)")),"right"===s?o+l:l+o}if(2===a.length){var u=a[0],c=u.toTex(e);i[0]&&(c="\\left(".concat(c,"\\right)"));var p,d=a[1].toTex(e);switch(i[1]&&(d="\\left(".concat(d,"\\right)")),p="keep"===t?u.getIdentifier():u.getContent().getIdentifier(),this.getIdentifier()){case"OperatorNode:divide":return o+"{"+c+"}{"+d+"}";case"OperatorNode:pow":switch(c="{"+c+"}",d="{"+d+"}",p){case"ConditionalNode":case"OperatorNode:divide":c="\\left(".concat(c,"\\right)")}break;case"OperatorNode:multiply":if(this.implicit&&"hide"===n)return c+"~"+d}return c+o+d}if(a.length>2&&("OperatorNode:add"===this.getIdentifier()||"OperatorNode:multiply"===this.getIdentifier())){var m=a.map((function(t,n){return t=t.toTex(e),i[n]&&(t="\\left(".concat(t,"\\right)")),t}));return"OperatorNode:multiply"===this.getIdentifier()&&this.implicit?m.join("~"):m.join(o)}return"\\mathrm{"+this.fn+"}\\left("+a.map((function(t){return t.toTex(e)})).join(",")+"\\right)"},n.prototype.getIdentifier=function(){return this.type+":"+this.fn},n}),{isClass:!0,isNode:!0}),name$1j="ParenthesisNode",dependencies$1j=["Node"],createParenthesisNode=factory(name$1j,dependencies$1j,(e=>{var{Node:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!isNode(e))throw new TypeError('Node expected for parameter "content"');this.content=e}return n.prototype=new t,n.prototype.type="ParenthesisNode",n.prototype.isParenthesisNode=!0,n.prototype._compile=function(e,t){return this.content._compile(e,t)},n.prototype.getContent=function(){return this.content.getContent()},n.prototype.forEach=function(e){e(this.content,"content",this)},n.prototype.map=function(e){return new n(e(this.content,"content",this))},n.prototype.clone=function(){return new n(this.content)},n.prototype._toString=function(e){return!e||e&&!e.parenthesis||e&&"keep"===e.parenthesis?"("+this.content.toString(e)+")":this.content.toString(e)},n.prototype.toJSON=function(){return{mathjs:"ParenthesisNode",content:this.content}},n.fromJSON=function(e){return new n(e.content)},n.prototype.toHTML=function(e){return!e||e&&!e.parenthesis||e&&"keep"===e.parenthesis?'('+this.content.toHTML(e)+')':this.content.toHTML(e)},n.prototype._toTex=function(e){return!e||e&&!e.parenthesis||e&&"keep"===e.parenthesis?"\\left(".concat(this.content.toTex(e),"\\right)"):this.content.toTex(e)},n}),{isClass:!0,isNode:!0}),name$1i="RangeNode",dependencies$1i=["Node"],createRangeNode=factory(name$1i,dependencies$1i,(e=>{var{Node:t}=e;function n(e,t,r){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!isNode(e))throw new TypeError("Node expected");if(!isNode(t))throw new TypeError("Node expected");if(r&&!isNode(r))throw new TypeError("Node expected");if(arguments.length>3)throw new Error("Too many arguments");this.start=e,this.end=t,this.step=r||null}function r(e,t){var n=getPrecedence(e,t),r={},a=getPrecedence(e.start,t);if(r.start=null!==a&&a<=n||"all"===t,e.step){var i=getPrecedence(e.step,t);r.step=null!==i&&i<=n||"all"===t}var o=getPrecedence(e.end,t);return r.end=null!==o&&o<=n||"all"===t,r}return n.prototype=new t,n.prototype.type="RangeNode",n.prototype.isRangeNode=!0,n.prototype.needsEnd=function(){return this.filter((function(e){return isSymbolNode(e)&&"end"===e.name})).length>0},n.prototype._compile=function(e,t){var n=e.range,r=this.start._compile(e,t),a=this.end._compile(e,t);if(this.step){var i=this.step._compile(e,t);return function(e,t,o){return n(r(e,t,o),a(e,t,o),i(e,t,o))}}return function(e,t,i){return n(r(e,t,i),a(e,t,i))}},n.prototype.forEach=function(e){e(this.start,"start",this),e(this.end,"end",this),this.step&&e(this.step,"step",this)},n.prototype.map=function(e){return new n(this._ifNode(e(this.start,"start",this)),this._ifNode(e(this.end,"end",this)),this.step&&this._ifNode(e(this.step,"step",this)))},n.prototype.clone=function(){return new n(this.start,this.end,this.step&&this.step)},n.prototype._toString=function(e){var t,n=r(this,e&&e.parenthesis?e.parenthesis:"keep"),a=this.start.toString(e);if(n.start&&(a="("+a+")"),t=a,this.step){var i=this.step.toString(e);n.step&&(i="("+i+")"),t+=":"+i}var o=this.end.toString(e);return n.end&&(o="("+o+")"),t+":"+o},n.prototype.toJSON=function(){return{mathjs:"RangeNode",start:this.start,end:this.end,step:this.step}},n.fromJSON=function(e){return new n(e.start,e.end,e.step)},n.prototype.toHTML=function(e){var t,n=r(this,e&&e.parenthesis?e.parenthesis:"keep"),a=this.start.toHTML(e);if(n.start&&(a='('+a+')'),t=a,this.step){var i=this.step.toHTML(e);n.step&&(i='('+i+')'),t+=':'+i}var o=this.end.toHTML(e);return n.end&&(o='('+o+')'),t+':'+o},n.prototype._toTex=function(e){var t=r(this,e&&e.parenthesis?e.parenthesis:"keep"),n=this.start.toTex(e);if(t.start&&(n="\\left(".concat(n,"\\right)")),this.step){var a=this.step.toTex(e);t.step&&(a="\\left(".concat(a,"\\right)")),n+=":"+a}var i=this.end.toTex(e);return t.end&&(i="\\left(".concat(i,"\\right)")),n+":"+i},n}),{isClass:!0,isNode:!0}),name$1h="RelationalNode",dependencies$1h=["Node"],createRelationalNode=factory(name$1h,dependencies$1h,(e=>{var{Node:t}=e;function n(e,t){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!Array.isArray(e))throw new TypeError("Parameter conditionals must be an array");if(!Array.isArray(t))throw new TypeError("Parameter params must be an array");if(e.length!==t.length-1)throw new TypeError("Parameter params must contain exactly one more element than parameter conditionals");this.conditionals=e,this.params=t}return n.prototype=new t,n.prototype.type="RelationalNode",n.prototype.isRelationalNode=!0,n.prototype._compile=function(e,t){var n=this,r=this.params.map((n=>n._compile(e,t)));return function(t,a,i){for(var o,s=r[0](t,a,i),l=0;le(t,"params["+n+"]",this)),this)},n.prototype.map=function(e){return new n(this.conditionals.slice(),this.params.map(((t,n)=>this._ifNode(e(t,"params["+n+"]",this))),this))},n.prototype.clone=function(){return new n(this.conditionals,this.params)},n.prototype._toString=function(e){for(var t=e&&e.parenthesis?e.parenthesis:"keep",n=getPrecedence(this,t),r=this.params.map((function(r,a){var i=getPrecedence(r,t);return"all"===t||null!==i&&i<=n?"("+r.toString(e)+")":r.toString(e)})),a={equal:"==",unequal:"!=",smaller:"<",larger:">",smallerEq:"<=",largerEq:">="},i=r[0],o=0;o('+r.toHTML(e)+')':r.toHTML(e)})),a={equal:"==",unequal:"!=",smaller:"<",larger:">",smallerEq:"<=",largerEq:">="},i=r[0],o=0;o'+escape$1(a[this.conditionals[o]])+""+r[o+1];return i},n.prototype._toTex=function(e){for(var t=e&&e.parenthesis?e.parenthesis:"keep",n=getPrecedence(this,t),r=this.params.map((function(r,a){var i=getPrecedence(r,t);return"all"===t||null!==i&&i<=n?"\\left("+r.toTex(e)+"\right)":r.toTex(e)})),a=r[0],i=0;i{var{math:t,Unit:n,Node:r}=e;function a(e){return!!n&&n.isValuelessUnit(e)}function i(e){if(!(this instanceof i))throw new SyntaxError("Constructor must be called with the new operator");if("string"!=typeof e)throw new TypeError('String expected for parameter "name"');this.name=e}return i.prototype=new r,i.prototype.type="SymbolNode",i.prototype.isSymbolNode=!0,i.prototype._compile=function(e,t){var r=this.name;if(!0===t[r])return function(e,t,n){return t[r]};if(r in e)return function(t,n,a){return t.has(r)?t.get(r):getSafeProperty(e,r)};var o=a(r);return function(e,t,a){return e.has(r)?e.get(r):o?new n(null,r):i.onUndefinedSymbol(r)}},i.prototype.forEach=function(e){},i.prototype.map=function(e){return this.clone()},i.onUndefinedSymbol=function(e){throw new Error("Undefined symbol "+e)},i.prototype.clone=function(){return new i(this.name)},i.prototype._toString=function(e){return this.name},i.prototype.toHTML=function(e){var t=escape$1(this.name);return"true"===t||"false"===t?''+t+"":"i"===t?''+t+"":"Infinity"===t?''+t+"":"NaN"===t?''+t+"":"null"===t?''+t+"":"undefined"===t?''+t+"":''+t+""},i.prototype.toJSON=function(){return{mathjs:"SymbolNode",name:this.name}},i.fromJSON=function(e){return new i(e.name)},i.prototype._toTex=function(e){var n=!1;void 0===t[this.name]&&a(this.name)&&(n=!0);var r=toSymbol(this.name,n);return"\\"===r[0]?r:" "+r},i}),{isClass:!0,isNode:!0});function createSubScope(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r{var{math:t,Node:n,SymbolNode:r}=e;function a(e,t){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");if("string"==typeof e&&(e=new r(e)),!isNode(e))throw new TypeError('Node expected as parameter "fn"');if(!Array.isArray(t)||!t.every(isNode))throw new TypeError('Array containing Nodes expected for parameter "args"');this.fn=e,this.args=t||[],Object.defineProperty(this,"name",{get:function(){return this.fn.name||""}.bind(this),set:function(){throw new Error("Cannot assign a new name, name is read-only")}})}a.prototype=new n,a.prototype.type="FunctionNode",a.prototype.isFunctionNode=!0;var i=e=>format$1(e,{truncate:78});a.prototype._compile=function(e,t){if(!(this instanceof a))throw new TypeError("No valid FunctionNode");var n=this.args.map((n=>n._compile(e,t)));if(!isSymbolNode(this.fn)){if(isAccessorNode(this.fn)&&isIndexNode(this.fn.index)&&this.fn.index.isObjectProperty()){var r=this.fn.object._compile(e,t),o=this.fn.index.getObjectProperty(),s=this.args;return function(t,a,i){var l=r(t,a,i);if(validateSafeMethod(l,o),l[o]&&l[o].rawArgs)return l[o](s,e,createSubScope(t,a),t);var u=n.map((e=>e(t,a,i)));return l[o].apply(l,u)}}var l=this.fn.toString(),u=this.fn._compile(e,t),c=this.args;return function(t,r,a){var o=u(t,r,a);if("function"!=typeof o)throw new TypeError("Expression '".concat(l,"' did not evaluate to a function; value is:")+"\n ".concat(i(o)));if(o.rawArgs)return o(c,e,createSubScope(t,r),t);var s=n.map((e=>e(t,r,a)));return o.apply(o,s)}}var p=this.fn.name;if(t[p]){var d=this.args;return function(t,r,a){var o=r[p];if("function"!=typeof o)throw new TypeError("Argument '".concat(p,"' was not a function; received: ").concat(i(o)));if(o.rawArgs)return o(d,e,createSubScope(t,r),t);var s=n.map((e=>e(t,r,a)));return o.apply(o,s)}}var m=p in e?getSafeProperty(e,p):void 0,f="function"==typeof m&&!0===m.rawArgs,h=t=>{var n;if(t.has(p))n=t.get(p);else{if(!(p in e))return a.onUndefinedFunction(p);n=getSafeProperty(e,p)}if("function"==typeof n)return n;throw new TypeError("'".concat(p,"' is not a function; its value is:\n ").concat(i(n)))};if(f){var y=this.args;return function(t,n,r){return h(t)(y,e,createSubScope(t,n),t)}}switch(n.length){case 0:return function(e,t,n){return h(e)()};case 1:return function(e,t,r){return h(e)((0,n[0])(e,t,r))};case 2:return function(e,t,r){var a=h(e),i=n[0],o=n[1];return a(i(e,t,r),o(e,t,r))};default:return function(e,t,r){return h(e)(...n.map((n=>n(e,t,r))))}}},a.prototype.forEach=function(e){e(this.fn,"fn",this);for(var t=0;t'+escape$1(this.fn)+'('+t.join(',')+')'};var l=a.prototype.toTex;return a.prototype.toTex=function(e){var t;return e&&"object"==typeof e.handler&&hasOwnProperty$2(e.handler,this.name)&&(t=e.handler[this.name](this,e)),void 0!==t?t:l.call(this,e)},a.prototype._toTex=function(e){var n,r,a=this.args.map((function(t){return t.toTex(e)}));switch(latexFunctions[this.name]&&(n=latexFunctions[this.name]),!t[this.name]||"function"!=typeof t[this.name].toTex&&"object"!=typeof t[this.name].toTex&&"string"!=typeof t[this.name].toTex||(n=t[this.name].toTex),typeof n){case"function":r=n(this,e);break;case"string":r=s(n,this,e);break;case"object":switch(typeof n[a.length]){case"function":r=n[a.length](this,e);break;case"string":r=s(n[a.length],this,e)}}return void 0!==r?r:s(defaultTemplate,this,e)},a.prototype.getIdentifier=function(){return this.type+":"+this.name},a}),{isClass:!0,isNode:!0}),name$1e="parse",dependencies$1e=["typed","numeric","config","AccessorNode","ArrayNode","AssignmentNode","BlockNode","ConditionalNode","ConstantNode","FunctionAssignmentNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","RangeNode","RelationalNode","SymbolNode"],createParse=factory(name$1e,dependencies$1e,(e=>{var{typed:t,numeric:n,config:r,AccessorNode:a,ArrayNode:i,AssignmentNode:o,BlockNode:s,ConditionalNode:l,ConstantNode:u,FunctionAssignmentNode:c,FunctionNode:p,IndexNode:d,ObjectNode:m,OperatorNode:f,ParenthesisNode:h,RangeNode:y,RelationalNode:b,SymbolNode:g}=e,v=t(name$1e,{string:function(e){return R(e,{})},"Array | Matrix":function(e){return T(e,{})},"string, Object":function(e,t){return R(e,void 0!==t.nodes?t.nodes:{})},"Array | Matrix, Object":T});function T(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=void 0!==t.nodes?t.nodes:{};return deepMap(e,(function(e){if("string"!=typeof e)throw new TypeError("String expected");return R(e,n)}))}var N={",":!0,"(":!0,")":!0,"[":!0,"]":!0,"{":!0,"}":!0,'"':!0,"'":!0,";":!0,"+":!0,"-":!0,"*":!0,".*":!0,"/":!0,"./":!0,"%":!0,"^":!0,".^":!0,"~":!0,"!":!0,"&":!0,"|":!0,"^|":!0,"=":!0,":":!0,"?":!0,"==":!0,"!=":!0,"<":!0,">":!0,"<=":!0,">=":!0,"<<":!0,">>":!0,">>>":!0},C={mod:!0,to:!0,in:!0,and:!0,xor:!0,or:!0,not:!0},A={true:!0,false:!1,null:null,undefined:void 0},S=["NaN","Infinity"];function x(e,t){return e.expression.substr(e.index,t)}function w(e){return x(e,1)}function V(e){e.index++}function E(e){return e.expression.charAt(e.index-1)}function O(e){return e.expression.charAt(e.index+1)}function _(e){for(e.tokenType=0,e.token="",e.comment="";;){if("#"===w(e))for(;"\n"!==w(e)&&""!==w(e);)e.comment+=w(e),V(e);if(!v.isWhitespace(w(e),e.nestingLevel))break;V(e)}if(""!==w(e)){if("\n"===w(e)&&!e.nestingLevel)return e.tokenType=1,e.token=w(e),void V(e);var t=w(e),n=x(e,2),r=x(e,3);if(3===r.length&&N[r])return e.tokenType=1,e.token=r,V(e),V(e),void V(e);if(2===n.length&&N[n])return e.tokenType=1,e.token=n,V(e),void V(e);if(N[t])return e.tokenType=1,e.token=t,void V(e);if(v.isDigitDot(t)){e.tokenType=2;var a=x(e,2);if("0b"===a||"0o"===a||"0x"===a){for(e.token+=w(e),V(e),e.token+=w(e),V(e);v.isHexDigit(w(e));)e.token+=w(e),V(e);if("."===w(e))for(e.token+=".",V(e);v.isHexDigit(w(e));)e.token+=w(e),V(e);else if("i"===w(e))for(e.token+="i",V(e);v.isDigit(w(e));)e.token+=w(e),V(e);return}if("."===w(e)){if(e.token+=w(e),V(e),!v.isDigit(w(e)))return void(e.tokenType=1)}else{for(;v.isDigit(w(e));)e.token+=w(e),V(e);v.isDecimalMark(w(e),O(e))&&(e.token+=w(e),V(e))}for(;v.isDigit(w(e));)e.token+=w(e),V(e);if("E"===w(e)||"e"===w(e))if(v.isDigit(O(e))||"-"===O(e)||"+"===O(e)){if(e.token+=w(e),V(e),"+"!==w(e)&&"-"!==w(e)||(e.token+=w(e),V(e)),!v.isDigit(w(e)))throw ne(e,'Digit expected, got "'+w(e)+'"');for(;v.isDigit(w(e));)e.token+=w(e),V(e);if(v.isDecimalMark(w(e),O(e)))throw ne(e,'Digit expected, got "'+w(e)+'"')}else if("."===O(e))throw V(e),ne(e,'Digit expected, got "'+w(e)+'"')}else{if(!v.isAlpha(w(e),E(e),O(e))){for(e.tokenType=4;""!==w(e);)e.token+=w(e),V(e);throw ne(e,'Syntax error in part "'+e.token+'"')}for(;v.isAlpha(w(e),E(e),O(e))||v.isDigit(w(e));)e.token+=w(e),V(e);hasOwnProperty$2(C,e.token)?e.tokenType=1:e.tokenType=3}}else e.tokenType=1}function $(e){do{_(e)}while("\n"===e.token)}function D(e){e.nestingLevel++}function I(e){e.nestingLevel--}function R(e,t){var n={extraNodes:{},expression:"",comment:"",index:0,token:"",tokenType:0,nestingLevel:0,conditionalLevel:null};_extends$1(n,{expression:e,extraNodes:t}),_(n);var r=function(e){var t,n,r=[];for(""!==e.token&&"\n"!==e.token&&";"!==e.token&&((t=P(e)).comment=e.comment);"\n"===e.token||";"===e.token;)0===r.length&&t&&(n=";"!==e.token,r.push({node:t,visible:n})),_(e),"\n"!==e.token&&";"!==e.token&&""!==e.token&&((t=P(e)).comment=e.comment,n=";"!==e.token,r.push({node:t,visible:n}));return r.length>0?new s(r):(t||((t=new u(void 0)).comment=e.comment),t)}(n);if(""!==n.token)throw 1===n.tokenType?re(n,"Unexpected operator "+n.token):ne(n,'Unexpected part "'+n.token+'"');return r}function P(e){var t,n,r,a,i=function(e){for(var t=function(e){for(var t=k(e);"or"===e.token;)$(e),t=new f("or","or",[t,k(e)]);return t}(e);"?"===e.token;){var n=e.conditionalLevel;e.conditionalLevel=e.nestingLevel,$(e);var r=t,a=P(e);if(":"!==e.token)throw ne(e,"False part of conditional expression expected");e.conditionalLevel=null,$(e);var i=P(e);t=new l(r,a,i),e.conditionalLevel=n}return t}(e);if("="===e.token){if(isSymbolNode(i))return t=i.name,$(e),r=P(e),new o(new g(t),r);if(isAccessorNode(i))return $(e),r=P(e),new o(i.object,i.index,r);if(isFunctionNode(i)&&isSymbolNode(i.fn)&&(a=!0,n=[],t=i.name,i.args.forEach((function(e,t){isSymbolNode(e)?n[t]=e.name:a=!1})),a))return $(e),r=P(e),new c(t,n,r);throw ne(e,"Invalid left hand side of assignment operator =")}return i}function k(e){for(var t=M(e);"xor"===e.token;)$(e),t=new f("xor","xor",[t,M(e)]);return t}function M(e){for(var t=F(e);"and"===e.token;)$(e),t=new f("and","and",[t,F(e)]);return t}function F(e){for(var t=B(e);"|"===e.token;)$(e),t=new f("|","bitOr",[t,B(e)]);return t}function B(e){for(var t=L(e);"^|"===e.token;)$(e),t=new f("^|","bitXor",[t,L(e)]);return t}function L(e){for(var t=j(e);"&"===e.token;)$(e),t=new f("&","bitAnd",[t,j(e)]);return t}function j(e){for(var t=[U(e)],n=[],r={"==":"equal","!=":"unequal","<":"smaller",">":"larger","<=":"smallerEq",">=":"largerEq"};hasOwnProperty$2(r,e.token);){var a={name:e.token,fn:r[e.token]};n.push(a),$(e),t.push(U(e))}return 1===t.length?t[0]:2===t.length?new f(n[0].name,n[0].fn,t):new b(n.map((e=>e.fn)),t)}function U(e){var t,n,r,a;t=z(e);for(var i={"<<":"leftShift",">>":"rightArithShift",">>>":"rightLogShift"};hasOwnProperty$2(i,e.token);)r=i[n=e.token],$(e),a=[t,z(e)],t=new f(n,r,a);return t}function z(e){var t,n,r,a;t=G(e);for(var i={to:"to",in:"to"};hasOwnProperty$2(i,e.token);)r=i[n=e.token],$(e),"in"===n&&""===e.token?t=new f("*","multiply",[t,new g("in")],!0):(a=[t,G(e)],t=new f(n,r,a));return t}function G(e){var t,n=[];if(t=":"===e.token?new u(1):H(e),":"===e.token&&e.conditionalLevel!==e.nestingLevel){for(n.push(t);":"===e.token&&n.length<3;)$(e),")"===e.token||"]"===e.token||","===e.token||""===e.token?n.push(new g("end")):n.push(H(e));t=3===n.length?new y(n[0],n[2],n[1]):new y(n[0],n[1])}return t}function H(e){var t,n,r,a;t=q(e);for(var i={"+":"add","-":"subtract"};hasOwnProperty$2(i,e.token);){r=i[n=e.token],$(e);var o=q(e);a=o.isPercentage?[t,new f("*","multiply",[t,o])]:[t,o],t=new f(n,r,a)}return t}function q(e){var t,n,r,a;n=t=W(e);for(var i={"*":"multiply",".*":"dotMultiply","/":"divide","./":"dotDivide"};hasOwnProperty$2(i,e.token);)a=i[r=e.token],$(e),n=W(e),t=new f(r,a,[t,n]);return t}function W(e){var t,n;for(n=t=K(e);3===e.tokenType||"in"===e.token&&isConstantNode(t)||!(2!==e.tokenType||isConstantNode(n)||isOperatorNode(n)&&"!"!==n.op)||"("===e.token;)n=K(e),t=new f("*","multiply",[t,n],!0);return t}function K(e){for(var t=X(e),n=t,r=[];"/"===e.token&&isConstantNode(n);){if(r.push(_extends$1({},e)),$(e),2!==e.tokenType){_extends$1(e,r.pop());break}if(r.push(_extends$1({},e)),$(e),3!==e.tokenType&&"("!==e.token){r.pop(),_extends$1(e,r.pop());break}_extends$1(e,r.pop()),r.pop(),n=X(e),t=new f("/","divide",[t,n])}return t}function X(e){var t,n,r,a;t=Z(e);for(var i={"%":"mod",mod:"mod"};hasOwnProperty$2(i,e.token);)r=i[n=e.token],$(e),"%"===n&&1===e.tokenType&&"("!==e.token?t=new f("/","divide",[t,new u(100)],!1,!0):(a=[t,Z(e)],t=new f(n,r,a));return t}function Z(e){var t,a,o,s={"-":"unaryMinus","+":"unaryPlus","~":"bitNot",not:"not"};return hasOwnProperty$2(s,e.token)?(o=s[e.token],t=e.token,$(e),a=[Z(e)],new f(t,o,a)):function(e){var t,a,o,s;return t=function(e){var t,a,o;t=function(e){var t=[];if(3===e.tokenType&&hasOwnProperty$2(e.extraNodes,e.token)){var a=e.extraNodes[e.token];if(_(e),"("===e.token){if(t=[],D(e),_(e),")"!==e.token)for(t.push(P(e));","===e.token;)_(e),t.push(P(e));if(")"!==e.token)throw ne(e,"Parenthesis ) expected");I(e),_(e)}return new a(t)}return function(e){var t;return 3===e.tokenType||1===e.tokenType&&e.token in C?(t=e.token,_(e),Y(e,hasOwnProperty$2(A,t)?new u(A[t]):-1!==S.indexOf(t)?new u(n(t,"number")):new g(t))):function(e){var t;return'"'===e.token?(t=J(e),Y(e,new u(t))):function(e){var t;return"'"===e.token?(t=Q(e),Y(e,new u(t))):function(e){var t,a,o,s;if("["===e.token){if(D(e),_(e),"]"!==e.token){var l=ee(e);if(";"===e.token){for(o=1,a=[l];";"===e.token;)_(e),a[o]=ee(e),o++;if("]"!==e.token)throw ne(e,"End of matrix ] expected");I(e),_(e),s=a[0].items.length;for(var c=1;c0},v.isDecimalMark=function(e,t){return"."===e&&"/"!==t&&"*"!==t&&"^"!==t},v.isDigitDot=function(e){return e>="0"&&e<="9"||"."===e},v.isDigit=function(e){return e>="0"&&e<="9"},v.isHexDigit=function(e){return e>="0"&&e<="9"||e>="a"&&e<="f"||e>="A"&&e<="F"},v})),name$1d="compile",dependencies$1d=["typed","parse"],createCompile=factory(name$1d,dependencies$1d,(e=>{var{typed:t,parse:n}=e;return t(name$1d,{string:function(e){return n(e).compile()},"Array | Matrix":function(e){return deepMap(e,(function(e){return n(e).compile()}))}})})),name$1c="evaluate",dependencies$1c=["typed","parse"],createEvaluate=factory(name$1c,dependencies$1c,(e=>{var{typed:t,parse:n}=e;return t(name$1c,{string:function(e){var t=createEmptyMap();return n(e).compile().evaluate(t)},"string, Map | Object":function(e,t){return n(e).compile().evaluate(t)},"Array | Matrix":function(e){var t=createEmptyMap();return deepMap(e,(function(e){return n(e).compile().evaluate(t)}))},"Array | Matrix, Map | Object":function(e,t){return deepMap(e,(function(e){return n(e).compile().evaluate(t)}))}})})),name$1b="Parser",dependencies$1b=["evaluate"],createParserClass=factory(name$1b,dependencies$1b,(e=>{var{evaluate:t}=e;function n(){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");Object.defineProperty(this,"scope",{value:createEmptyMap(),writable:!1})}return n.prototype.type="Parser",n.prototype.isParser=!0,n.prototype.evaluate=function(e){return t(e,this.scope)},n.prototype.get=function(e){if(this.scope.has(e))return this.scope.get(e)},n.prototype.getAll=function(){return toObject(this.scope)},n.prototype.getAllAsMap=function(){return this.scope},n.prototype.set=function(e,t){return this.scope.set(e,t),t},n.prototype.remove=function(e){this.scope.delete(e)},n.prototype.clear=function(){this.scope.clear()},n}),{isClass:!0}),name$1a="parser",dependencies$1a=["typed","Parser"],createParser=factory(name$1a,dependencies$1a,(e=>{var{typed:t,Parser:n}=e;return t(name$1a,{"":function(){return new n}})})),name$19="lup",dependencies$19=["typed","matrix","abs","addScalar","divideScalar","multiplyScalar","subtract","larger","equalScalar","unaryMinus","DenseMatrix","SparseMatrix","Spa"],createLup=factory(name$19,dependencies$19,(e=>{var{typed:t,matrix:n,abs:r,addScalar:a,divideScalar:i,multiplyScalar:o,subtract:s,larger:l,equalScalar:u,unaryMinus:c,DenseMatrix:p,SparseMatrix:d,Spa:m}=e;return t(name$19,{DenseMatrix:function(e){return f(e)},SparseMatrix:function(e){return function(e){var t,n,a,s=e._size[0],p=e._size[1],f=Math.min(s,p),h=e._values,y=e._index,b=e._ptr,g=[],v=[],T=[],N=[s,f],C=[],A=[],S=[],x=[f,p],w=[],V=[];for(t=0;t0&&e.forEach(0,n-1,(function(t,n){d._forEachRow(t,g,v,T,(function(r,a){r>t&&e.accumulate(r,c(o(a,n)))}))}));var E=n,O=e.get(n),_=r(O);e.forEach(n+1,s-1,(function(e,t){var n=r(t);l(n,_)&&(E=e,_=n,O=t)})),n!==E&&(d._swapRows(n,E,N[1],g,v,T),d._swapRows(n,E,x[1],C,A,S),e.swap(n,E),function(e,t){var n=V[e],r=V[t];w[n]=t,w[r]=e,V[e]=r,V[t]=n}(n,E)),e.forEach(0,s-1,(function(e,t){e<=n?(C.push(t),A.push(e)):(t=i(t,O),u(t,0)||(g.push(t),v.push(e)))}))};for(n=0;n0)for(t=0;t{var{typed:t,matrix:n,zeros:r,identity:a,isZero:i,equal:o,sign:s,sqrt:l,conj:u,unaryMinus:c,addScalar:p,divideScalar:d,multiplyScalar:m,subtract:f,complex:h}=e;return _extends$1(t(name$18,{DenseMatrix:function(e){return b(e)},SparseMatrix:function(e){return function(e){throw new Error("qr not implemented for sparse matrices yet")}()},Array:function(e){var t=b(n(e));return{Q:t.Q.valueOf(),R:t.R.valueOf()}}}),{_denseQRimpl:y});function y(e){var t,n,h,y=e._size[0],b=e._size[1],g=a([y],"dense"),v=g._data,T=e.clone(),N=T._data,C=r([y],"");for(h=0;h0)for(var r="Complex"===n[0][0].type?h(0):0,a=0;a=0;){var l=n[o+s],u=n[r+l];-1===u?(s--,i[t++]=l):(n[r+l]=n[a+u],n[o+ ++s]=u)}return t}function csPost(e,t){if(!e)return null;var n,r=0,a=[],i=[],o=t,s=2*t;for(n=0;n=0;n--)-1!==e[n]&&(i[o+n]=i[0+e[n]],i[0+e[n]]=n);for(n=0;n{var{add:t,multiply:n,transpose:r}=e;return function(e,o){if(!o||e<=0||e>3)return null;var s=o._size,l=s[0],u=s[1],c=0,p=Math.max(16,10*Math.sqrt(u)),d=function(e,a,i,o,s){var l=r(a);if(1===e&&o===i)return t(a,l);if(2===e){for(var u=l._index,c=l._ptr,p=0,d=0;ds))for(var f=c[d+1];mo)n[s+d]=0,n[a+d]=-1,p++,t[d]=csFlip(e),n[s+e]++;else{var f=n[l+m];-1!==f&&(u[f]=d),n[c+d]=n[l+m],n[l+m]=d}}return p}(u,_,I,F,M,B,p,R,k,j,P),G=0;zH?(g=h,v=K,T=I[0+h]-H):(v=_[g=O[K++]],T=I[0+g]),b=1;b<=T;b++)(N=I[R+(m=O[v++])])<=0||(W+=N,I[R+m]=-N,O[Z++]=m,-1!==I[P+m]&&(j[I[P+m]]=j[m]),-1!==j[m]?I[P+j[m]]=I[P+m]:I[k+I[F+m]]=I[P+m]);g!==h&&(_[g]=csFlip(h),I[B+g]=0)}for(0!==H&&($=Z),I[F+h]=W,_[h]=X,I[0+h]=Z-X,I[M+h]=-2,U=a(U,c,I,B,u),C=X;C=U?I[B+g]-=N:0!==I[B+g]&&(I[B+g]=I[F+g]+Y)}for(C=X;C0?(E+=J,O[w++]=g,V+=g):(_[g]=csFlip(h),I[B+g]=0)}I[M+m]=w-S+1;var Q=w,ee=S+I[0+m];for(K=x+1;K=0))for(m=I[L+(V=j[m])],I[L+V]=-1;-1!==m&&-1!==I[P+m];m=I[P+m],U++){for(T=I[0+m],A=I[M+m],K=_[m]+1;K<=_[m]+T-1;K++)I[B+O[K]]=U;var ne=m;for(f=I[P+m];-1!==f;){var re=I[0+f]===T&&I[M+f]===A;for(K=_[f]+1;re&&K<=_[f]+T-1;K++)I[B+O[K]]!==U&&(re=0);re?(_[f]=csFlip(m),I[R+m]+=I[R+f],I[R+f]=0,I[M+f]=-1,f=I[P+f],I[P+ne]=f):(ne=f,f=I[P+f])}}for(K=X,C=X;C=0;f--)I[R+f]>0||(I[P+f]=I[k+_[f]],I[k+_[f]]=f);for(g=u;g>=0;g--)I[R+g]<=0||-1!==_[g]&&(I[P+g]=I[k+_[g]],I[k+_[g]]=g);for(h=0,m=0;m<=u;m++)-1===_[m]&&(h=csTdfs(m,h,I,k,P,D,B));return D.splice(D.length-1,1),D};function a(e,t,n,r,a){if(e<2||e+t<0){for(var i=0;i{var{transpose:t}=e;return function(e,n,r,a){if(!e||!n||!r)return null;var i,o,s,l,u,c,p,d=e._size,m=d[0],f=d[1],h=4*f+(a?f+m+1:0),y=[],b=f,g=2*f,v=3*f,T=4*f,N=5*f+1;for(s=0;s=1&&C[o]++,2===w.jleaf&&C[w.q]--}-1!==n[o]&&(y[0+o]=n[o])}for(o=0;o{var{add:t,multiply:n,transpose:r}=e,a=createCsAmd({add:t,multiply:n,transpose:r}),i=createCsCounts({transpose:r});return function(e,t,n){var r,o=t._ptr,s=t._size[1],l={};if(l.q=a(e,t),e&&!l.q)return null;if(n){var u=e?csPermute(t,null,l.q,0):t;l.parent=csEtree(u,1);var c=csPost(l.parent,s);if(l.cp=i(u,l.parent,c,1),u&&l.parent&&l.cp&&function(e,t){var n=e._ptr,r=e._index,a=e._size,i=a[0],o=a[1];t.pinv=[],t.leftmost=[];var s,l,u,c,p,d=t.parent,m=t.pinv,f=t.leftmost,h=[],y=i,b=i+o,g=i+2*o;for(l=0;l=0;l--)for(c=n[l],p=n[l+1],u=c;u=0;s--)m[s]=-1,-1!==(l=f[s])&&(0==h[g+l]++&&(h[b+l]=s),h[0+s]=h[y+l],h[y+l]=s);for(t.lnz=0,t.m2=i,l=0;l=0;){e=r[p];var d=a?a[e]:e;csMarked(u,e)||(csMark(u,e),r[c+p]=d<0?0:csUnflip(u[d]));var m=1;for(o=r[c+p],s=d<0?0:csUnflip(u[d+1]);o{var{divideScalar:t,multiply:n,subtract:r}=e;return function(e,a,i,o,s,l,u){var c,p,d,m,f=e._values,h=e._index,y=e._ptr,b=e._size[1],g=a._values,v=a._index,T=a._ptr,N=csReach(e,a,i,o,l);for(c=N;c{var{abs:t,divideScalar:n,multiply:r,subtract:a,larger:i,largerEq:o,SparseMatrix:s}=e,l=createCsSpsolve({divideScalar:n,multiply:r,subtract:a});return function(e,a,u){if(!e)return null;var c,p=e._size[1],d=100,m=100;a&&(c=a.q,d=a.lnz||d,m=a.unz||m);var f,h,y=[],b=[],g=[],v=new s({values:y,index:b,ptr:g,size:[p,p]}),T=[],N=[],C=[],A=new s({values:T,index:N,ptr:C,size:[p,p]}),S=[],x=[],w=[];for(f=0;f{var{typed:t,abs:n,add:r,multiply:a,transpose:i,divideScalar:o,subtract:s,larger:l,largerEq:u,SparseMatrix:c}=e,p=createCsSqr({add:r,multiply:a,transpose:i}),d=createCsLu({abs:n,divideScalar:o,multiply:a,subtract:s,larger:l,largerEq:u,SparseMatrix:c});return t(name$12,{"SparseMatrix, number, number":function(e,t,n){if(!isInteger$1(t)||t<0||t>3)throw new Error("Symbolic Ordering and Analysis order must be an integer number in the interval [0, 3]");if(n<0||n>1)throw new Error("Partial pivoting threshold must be a number from 0 to 1");var r=p(t,e,!1),a=d(e,r,n);return{L:a.L,U:a.U,p:a.pinv,q:r.q,toString:function(){return"L: "+this.L.toString()+"\nU: "+this.U.toString()+"\np: "+this.p.toString()+(this.q?"\nq: "+this.q.toString():"")+"\n"}}}})}));function csIpvec(e,t){var n,r=t.length,a=[];if(e)for(n=0;n{var{typed:t,matrix:n,lup:r,slu:a,usolve:i,lsolve:o,DenseMatrix:s}=e,l=createSolveValidation({DenseMatrix:s});return t(name$11,{"Array, Array | Matrix":function(e,t){e=n(e);var a=r(e);return c(a.L,a.U,a.p,null,t).valueOf()},"DenseMatrix, Array | Matrix":function(e,t){var n=r(e);return c(n.L,n.U,n.p,null,t)},"SparseMatrix, Array | Matrix":function(e,t){var n=r(e);return c(n.L,n.U,n.p,null,t)},"SparseMatrix, Array | Matrix, number, number":function(e,t,n,r){var i=a(e,n,r);return c(i.L,i.U,i.p,i.q,t)},"Object, Array | Matrix":function(e,t){return c(e.L,e.U,e.p,e.q,t)}});function u(e){if(isMatrix(e))return e;if(isArray$1(e))return n(e);throw new TypeError("Invalid Matrix LU decomposition")}function c(e,t,n,r,a){e=u(e),t=u(t),n&&((a=l(e,a,!0))._data=csIpvec(n,a._data));var s=o(e,a),c=i(t,s);return r&&(c._data=csIpvec(r,c._data)),c}})),name$10="Help",dependencies$10=["parse"],createHelpClass=factory(name$10,dependencies$10,(e=>{var{parse:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!e)throw new Error('Argument "doc" missing');this.doc=e}return n.prototype.type="Help",n.prototype.isHelp=!0,n.prototype.toString=function(){var e=this.doc||{},n="\n";if(e.name&&(n+="Name: "+e.name+"\n\n"),e.category&&(n+="Category: "+e.category+"\n\n"),e.description&&(n+="Description:\n "+e.description+"\n\n"),e.syntax&&(n+="Syntax:\n "+e.syntax.join("\n ")+"\n\n"),e.examples){n+="Examples:\n";for(var r={},a=0;a"mathjs"!==e)).forEach((n=>{t[n]=e[n]})),new n(t)},n.prototype.valueOf=n.prototype.toString,n}),{isClass:!0}),name$$="Chain",dependencies$$=["?on","math"],createChainClass=factory(name$$,dependencies$$,(e=>{var{on:t,math:n}=e;function r(e){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");isChain(e)?this.value=e.value:this.value=e}function a(e,t){lazy(r.prototype,e,(function(){var e=t();if("function"==typeof e)return i(e)}))}function i(e){return function(){for(var t=[this.value],n=0;ne[t]))};for(var s in e)n(s)}};var o={expression:!0,docs:!0,type:!0,classes:!0,json:!0,error:!0,isChain:!0};return r.createProxy(n),t&&t("import",(function(e,t,n){n||a(e,t)})),r}),{isClass:!0}),eDocs={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"]},falseDocs={name:"false",category:"Constants",syntax:["false"],description:"Boolean value false",examples:["false"],seealso:["true"]},iDocs={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:[]},InfinityDocs={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:[]},LN10Docs={name:"LN10",category:"Constants",syntax:["LN10"],description:"Returns the natural logarithm of 10, approximately equal to 2.302",examples:["LN10","log(10)"],seealso:[]},LN2Docs={name:"LN2",category:"Constants",syntax:["LN2"],description:"Returns the natural logarithm of 2, approximately equal to 0.693",examples:["LN2","log(2)"],seealso:[]},LOG10EDocs={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:[]},LOG2EDocs={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:[]},NaNDocs={name:"NaN",category:"Constants",syntax:["NaN"],description:"Not a number",examples:["NaN","0 / 0"],seealso:[]},nullDocs={name:"null",category:"Constants",syntax:["null"],description:"Value null",examples:["null"],seealso:["true","false"]},phiDocs={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:[]},piDocs={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"]},SQRT12Docs={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:[]},SQRT2Docs={name:"SQRT2",category:"Constants",syntax:["SQRT2"],description:"Returns the square root of 2, approximately equal to 1.414",examples:["SQRT2","sqrt(2)"],seealso:[]},tauDocs={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"]},trueDocs={name:"true",category:"Constants",syntax:["true"],description:"Boolean value true",examples:["true"],seealso:["false"]},versionDocs={name:"version",category:"Constants",syntax:["version"],description:"A string with the version number of math.js",examples:["version"],seealso:[]},bignumberDocs={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","complex","fraction","index","matrix","string","unit"]},booleanDocs={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"]},complexDocs={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"]},createUnitDocs={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"]},fractionDocs={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"]},indexDocs={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:["[]","[1, 2, 3]","A = [1, 2, 3; 4, 5, 6]","A[1, :]","A[1, 2] = 50","A[0:2, 0:2] = ones(2, 2)"],seealso:["bignumber","boolean","complex","matrix,","number","range","string","unit"]},matrixDocs={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"]},numberDocs={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","boolean","complex","fraction","index","matrix","string","unit"]},sparseDocs={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"]},splitUnitDocs={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"]},stringDocs={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"]},unitDocs={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"]},configDocs={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:[]},importDocs={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:[]},typedDocs={name:"typed",category:"Core",syntax:["typed(signatures)","typed(name, signatures)"],description:"Create a typed function.",examples:['double = typed({ "number": f(x)=x+x })',"double(2)",'double("hello")'],seealso:[]},derivativeDocs={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"]},leafCountDocs={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"]},lsolveDocs={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"]},lsolveAllDocs={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"]},lupDocs={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"]},lusolveDocs={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"]},qrDocs={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"]},rationalizeDocs={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"]},resolveDocs={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"]},simplifyDocs={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"]},simplifyCoreDocs={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","evaluate"]},sluDocs={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"]},symbolicEqualDocs={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"]},usolveDocs={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"]},usolveAllDocs={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"]},absDocs={name:"abs",category:"Arithmetic",syntax:["abs(x)"],description:"Compute the absolute value.",examples:["abs(3.5)","abs(-4.2)"],seealso:["sign"]},addDocs={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"]},cbrtDocs={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"]},ceilDocs={name:"ceil",category:"Arithmetic",syntax:["ceil(x)"],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)"],seealso:["floor","fix","round"]},cubeDocs={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"]},divideDocs={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"]},dotDivideDocs={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"]},dotMultiplyDocs={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"]},dotPowDocs={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"]},expDocs={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"]},expmDocs={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"]},expm1Docs={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"]},fixDocs={name:"fix",category:"Arithmetic",syntax:["fix(x)"],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)"],seealso:["ceil","floor","round"]},floorDocs={name:"floor",category:"Arithmetic",syntax:["floor(x)"],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)"],seealso:["ceil","fix","round"]},gcdDocs={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"]},hypotDocs={name:"hypot",category:"Arithmetic",syntax:["hypot(a, b, c, ...)","hypot([a, b, c, ...])"],description:"Calculate the hypotenusa of a list with values. ",examples:["hypot(3, 4)","sqrt(3^2 + 4^2)","hypot(-2)","hypot([3, 4, 5])"],seealso:["abs","norm"]},invmodDocs={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)=NaN","invmod(7, 13)=2","math.invmod(15151, 15122)=10429"],seealso:["gcd","xgcd"]},lcmDocs={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"]},logDocs={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"]},log10Docs={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"]},log1pDocs={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"]},log2Docs={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"]},modDocs={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"]},multiplyDocs={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"]},normDocs={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")']},nthRootDocs={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"]},nthRootsDocs={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"]},powDocs={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)","math.pow([[1, 2], [4, 3]], 2)","math.pow([[1, 2], [4, 3]], -1)"],seealso:["multiply","nthRoot","nthRoots","sqrt"]},roundDocs={name:"round",category:"Arithmetic",syntax:["round(x)","round(x, n)"],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)"],seealso:["ceil","floor","fix"]},signDocs={name:"sign",category:"Arithmetic",syntax:["sign(x)"],description:"Compute the sign of a value. The sign of a value x is 1 when x>1, -1 when x<0, and 0 when x=0.",examples:["sign(3.5)","sign(-4.2)","sign(0)"],seealso:["abs"]},sqrtDocs={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"]},sqrtmDocs={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([[1, 2], [3, 4]])"],seealso:["sqrt","abs","square","multiply"]},squareDocs={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"]},subtractDocs={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"]},unaryMinusDocs={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"]},unaryPlusDocs={name:"unaryPlus",category:"Operators",syntax:["+x","unaryPlus(x)"],description:"Converts booleans and strings to numbers.",examples:["+true",'+"2"'],seealso:["add","subtract","unaryMinus"]},xgcdDocs={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"]},bitAndDocs={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"]},bitNotDocs={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"]},bitOrDocs={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"]},bitXorDocs={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"]},leftShiftDocs={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"]},rightArithShiftDocs={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"]},rightLogShiftDocs={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"]},bellNumbersDocs={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"]},catalanDocs={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"]},compositionDocs={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"]},stirlingS2Docs={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"]},argDocs={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"]},conjDocs={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"]},imDocs={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"]},reDocs={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"]},evaluateDocs={name:"evaluate",category:"Expression",syntax:["evaluate(expression)","evaluate([expr1, expr2, expr3, ...])"],description:"Evaluate an expression or an array with expressions.",examples:['evaluate("2 + 3")','evaluate("sqrt(" + 4 + ")")'],seealso:[]},helpDocs={name:"help",category:"Expression",syntax:["help(object)","help(string)"],description:"Display documentation on a function or data type.",examples:["help(sqrt)",'help("complex")'],seealso:[]},distanceDocs={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:[]},intersectDocs={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:[]},andDocs={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"]},notDocs={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"]},orDocs={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"]},xorDocs={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"]},columnDocs={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"]},concatDocs={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"]},countDocs={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"]},crossDocs={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"]},ctransposeDocs={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"]},detDocs={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"]},diagDocs={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"]},diffDocs={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 indicant 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:["diff([1, 2, 4, 7, 0])","diff([1, 2, 4, 7, 0], 0)","diff(matrix([1, 2, 4, 7, 0]))","diff([[1, 2], [3, 4]])","diff([[1, 2], [3, 4]], 0)","diff([[1, 2], [3, 4]], 1)","diff([[1, 2], [3, 4]], bignumber(1))","diff(matrix([[1, 2], [3, 4]]), 1)","diff([[1, 2], matrix([3, 4])], 1)"],seealso:["subtract","partitionSelect"]},dotDocs={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"]},eigsDocs={name:"eigs",category:"Matrix",syntax:["eigs(x)"],description:"Calculate the eigenvalues and eigenvectors of a real symmetric matrix",examples:["eigs([[5, 2.3], [2.3, 1]])"],seealso:["inv"]},filterDocs={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"]},flattenDocs={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"]},forEachDocs={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"]},getMatrixDataTypeDocs={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"]},identityDocs={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"]},invDocs={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"]},pinvDocs={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"]},kronDocs={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"]},mapDocs={name:"map",category:"Matrix",syntax:["map(x, callback)"],description:"Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array.",examples:["map([1, 2, 3], square)"],seealso:["filter","forEach"]},matrixFromColumnsDocs={name:"matrixFromColumns",category:"Matrix",syntax:["math.matrixFromColumns(...arr)","math.matrixFromColumns(row1, row2)","math.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"]},matrixFromFunctionDocs={name:"matrixFromFunction",category:"Matrix",syntax:["math.matrixFromFunction(size, fn)","math.matrixFromFunction(size, fn, format)","math.matrixFromFunction(size, fn, format, datatype)","math.matrixFromFunction(size, format, fn)","math.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"]},matrixFromRowsDocs={name:"matrixFromRows",category:"Matrix",syntax:["math.matrixFromRows(...arr)","math.matrixFromRows(row1, row2)","math.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"]},onesDocs={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"]},partitionSelectDocs={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)'],seealso:["sort"]},rangeDocs={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")',"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"]},reshapeDocs={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])"],seealso:["size","squeeze","resize"]},resizeDocs={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"]},rotateDocs={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], math.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"]},rotationMatrixDocs={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"]},rowDocs={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"]},sizeDocs={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"]},sortDocs={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"])',"sortByLength(a, b) = size(a)[1] - size(b)[1]",'sort(["Langdon", "Tom", "Sara"], sortByLength)','sort(["10", "1", "2"], "natural")'],seealso:["map","filter","forEach"]},squeezeDocs={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"]},subsetDocs={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"]},traceDocs={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"]},transposeDocs={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"]},zerosDocs={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"]},fftDocs={name:"fft",category:"Matrix",syntax:["fft(x)"],description:"Calculate N-dimensional fourier transform",examples:["fft([[1, 0], [1, 0]])"],seealso:["ifft"]},ifftDocs={name:"ifft",category:"Matrix",syntax:["ifft(x)"],description:"Calculate N-dimensional inverse fourier transform",examples:["ifft([[2, 2], [0, 0]])"],seealso:["fft"]},combinationsDocs={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"]},combinationsWithRepDocs={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"]},factorialDocs={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"]},gammaDocs={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"]},lgammaDocs={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(math.i)","lgamma(complex(1.1, 2))"],seealso:["gamma"]},kldivergenceDocs={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:[]},multinomialDocs={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"]},permutationsDocs={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"]},pickRandomDocs={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"]},randomDocs={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"]},randomIntDocs={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"]},compareDocs={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"]},compareNaturalDocs={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"]},compareTextDocs={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"]},deepEqualDocs={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"]},equalDocs={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"]},equalTextDocs={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"]},largerDocs={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.",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"]},largerEqDocs={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"]},smallerDocs={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.",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"]},smallerEqDocs={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"]},unequalDocs={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"]},setCartesianDocs={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"]},setDifferenceDocs={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"]},setDistinctDocs={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"]},setIntersectDocs={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"]},setIsSubsetDocs={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"]},setMultiplicityDocs={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"]},setPowersetDocs={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"]},setSizeDocs={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"]},setSymDifferenceDocs={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"]},setUnionDocs={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"]},erfDocs={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:[]},madDocs={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"]},maxDocs={name:"max",category:"Statistics",syntax:["max(a, b, c, ...)","max(A)","max(A, dim)"],description:"Compute the maximum value of a list of values.",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"]},meanDocs={name:"mean",category:"Statistics",syntax:["mean(a, b, c, ...)","mean(A)","mean(A, dim)"],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"]},medianDocs={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"]},minDocs={name:"min",category:"Statistics",syntax:["min(a, b, c, ...)","min(A)","min(A, dim)"],description:"Compute the minimum value of a list of values.",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"]},modeDocs={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"]},prodDocs={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"]},quantileSeqDocs={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 probablity are: Number, BigNumber. \n\nIn 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"]},stdDocs={name:"std",category:"Statistics",syntax:["std(a, b, c, ...)","std(A)","std(A, 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"]},cumSumDocs={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"]},sumDocs={name:"sum",category:"Statistics",syntax:["sum(a, b, c, ...)","sum(A)"],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","sum","variance"]},varianceDocs={name:"variance",category:"Statistics",syntax:["variance(a, b, c, ...)","variance(A)","variance(A, 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"]},acosDocs={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"]},acoshDocs={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"]},acotDocs={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"]},acothDocs={name:"acoth",category:"Trigonometry",syntax:["acoth(x)"],description:"Calculate the hyperbolic arccotangent 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"]},acscDocs={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"]},acschDocs={name:"acsch",category:"Trigonometry",syntax:["acsch(x)"],description:"Calculate the hyperbolic arccosecant of a value, defined as `acsch(x) = ln(1/x + sqrt(1/x^2 + 1))`.",examples:["acsch(0.5)"],seealso:["asech","acoth"]},asecDocs={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"]},asechDocs={name:"asech",category:"Trigonometry",syntax:["asech(x)"],description:"Calculate the inverse secant of a value.",examples:["asech(0.5)"],seealso:["acsch","acoth"]},asinDocs={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"]},asinhDocs={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"]},atanDocs={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"]},atan2Docs={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"]},atanhDocs={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"]},cosDocs={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"]},coshDocs={name:"cosh",category:"Trigonometry",syntax:["cosh(x)"],description:"Compute the hyperbolic cosine of x in radians.",examples:["cosh(0.5)"],seealso:["sinh","tanh","coth"]},cotDocs={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"]},cothDocs={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"]},cscDocs={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"]},cschDocs={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"]},secDocs={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"]},sechDocs={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"]},sinDocs={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"]},sinhDocs={name:"sinh",category:"Trigonometry",syntax:["sinh(x)"],description:"Compute the hyperbolic sine of x in radians.",examples:["sinh(0.5)"],seealso:["cosh","tanh"]},tanDocs={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"]},tanhDocs={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"]},toDocs={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:[]},binDocs={name:"bin",category:"Utils",syntax:["bin(value)"],description:"Format a number as binary",examples:["bin(2)"],seealso:["oct","hex"]},cloneDocs={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:[]},formatDocs={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"]},hasNumericValueDocs={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"]},hexDocs={name:"hex",category:"Utils",syntax:["hex(value)"],description:"Format a number as hexadecimal",examples:["hex(240)"],seealso:["bin","oct"]},isIntegerDocs={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"]},isNaNDocs={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"]},isNegativeDocs={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"]},isNumericDocs={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"]},isPositiveDocs={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"]},isPrimeDocs={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"]},isZeroDocs={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"]},numericDocs={name:"numeric",category:"Utils",syntax:["numeric(x)"],description:"Convert a numeric input to a specific numeric type: number, BigNumber, or Fraction.",examples:['numeric("4")','numeric("4", "number")','numeric("4", "BigNumber")','numeric("4", "Fraction)','numeric(4, "Fraction")','numeric(fraction(2, 5), "number)'],seealso:["number","fraction","bignumber","string","format"]},octDocs={name:"oct",category:"Utils",syntax:["oct(value)"],description:"Format a number as octal",examples:["oct(56)"],seealso:["bin","hex"]},printDocs={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: $0, $1, $2", [6, 9, 4])'],seealso:["format"]},typeOfDocs={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"]},embeddedDocs={bignumber:bignumberDocs,boolean:booleanDocs,complex:complexDocs,createUnit:createUnitDocs,fraction:fractionDocs,index:indexDocs,matrix:matrixDocs,number:numberDocs,sparse:sparseDocs,splitUnit:splitUnitDocs,string:stringDocs,unit:unitDocs,e:eDocs,E:eDocs,false:falseDocs,i:iDocs,Infinity:InfinityDocs,LN2:LN2Docs,LN10:LN10Docs,LOG2E:LOG2EDocs,LOG10E:LOG10EDocs,NaN:NaNDocs,null:nullDocs,pi:piDocs,PI:piDocs,phi:phiDocs,SQRT1_2:SQRT12Docs,SQRT2:SQRT2Docs,tau:tauDocs,true:trueDocs,version:versionDocs,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",examples:["coulomb"]},elementaryCharge:{description:"Elementary charge",examples:["elementaryCharge"]},bohrMagneton:{description:"Borh 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:"Borh 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:derivativeDocs,lsolve:lsolveDocs,lsolveAll:lsolveAllDocs,lup:lupDocs,lusolve:lusolveDocs,leafCount:leafCountDocs,resolve:resolveDocs,simplify:simplifyDocs,simplifyCore:simplifyCoreDocs,symbolicEqual:symbolicEqualDocs,rationalize:rationalizeDocs,slu:sluDocs,usolve:usolveDocs,usolveAll:usolveAllDocs,qr:qrDocs,abs:absDocs,add:addDocs,cbrt:cbrtDocs,ceil:ceilDocs,cube:cubeDocs,divide:divideDocs,dotDivide:dotDivideDocs,dotMultiply:dotMultiplyDocs,dotPow:dotPowDocs,exp:expDocs,expm:expmDocs,expm1:expm1Docs,fix:fixDocs,floor:floorDocs,gcd:gcdDocs,hypot:hypotDocs,lcm:lcmDocs,log:logDocs,log2:log2Docs,log1p:log1pDocs,log10:log10Docs,mod:modDocs,multiply:multiplyDocs,norm:normDocs,nthRoot:nthRootDocs,nthRoots:nthRootsDocs,pow:powDocs,round:roundDocs,sign:signDocs,sqrt:sqrtDocs,sqrtm:sqrtmDocs,square:squareDocs,subtract:subtractDocs,unaryMinus:unaryMinusDocs,unaryPlus:unaryPlusDocs,xgcd:xgcdDocs,invmod:invmodDocs,bitAnd:bitAndDocs,bitNot:bitNotDocs,bitOr:bitOrDocs,bitXor:bitXorDocs,leftShift:leftShiftDocs,rightArithShift:rightArithShiftDocs,rightLogShift:rightLogShiftDocs,bellNumbers:bellNumbersDocs,catalan:catalanDocs,composition:compositionDocs,stirlingS2:stirlingS2Docs,config:configDocs,import:importDocs,typed:typedDocs,arg:argDocs,conj:conjDocs,re:reDocs,im:imDocs,evaluate:evaluateDocs,help:helpDocs,distance:distanceDocs,intersect:intersectDocs,and:andDocs,not:notDocs,or:orDocs,xor:xorDocs,concat:concatDocs,count:countDocs,cross:crossDocs,column:columnDocs,ctranspose:ctransposeDocs,det:detDocs,diag:diagDocs,diff:diffDocs,dot:dotDocs,getMatrixDataType:getMatrixDataTypeDocs,identity:identityDocs,filter:filterDocs,flatten:flattenDocs,forEach:forEachDocs,inv:invDocs,pinv:pinvDocs,eigs:eigsDocs,kron:kronDocs,matrixFromFunction:matrixFromFunctionDocs,matrixFromRows:matrixFromRowsDocs,matrixFromColumns:matrixFromColumnsDocs,map:mapDocs,ones:onesDocs,partitionSelect:partitionSelectDocs,range:rangeDocs,resize:resizeDocs,reshape:reshapeDocs,rotate:rotateDocs,rotationMatrix:rotationMatrixDocs,row:rowDocs,size:sizeDocs,sort:sortDocs,squeeze:squeezeDocs,subset:subsetDocs,trace:traceDocs,transpose:transposeDocs,zeros:zerosDocs,fft:fftDocs,ifft:ifftDocs,combinations:combinationsDocs,combinationsWithRep:combinationsWithRepDocs,factorial:factorialDocs,gamma:gammaDocs,kldivergence:kldivergenceDocs,lgamma:lgammaDocs,multinomial:multinomialDocs,permutations:permutationsDocs,pickRandom:pickRandomDocs,random:randomDocs,randomInt:randomIntDocs,compare:compareDocs,compareNatural:compareNaturalDocs,compareText:compareTextDocs,deepEqual:deepEqualDocs,equal:equalDocs,equalText:equalTextDocs,larger:largerDocs,largerEq:largerEqDocs,smaller:smallerDocs,smallerEq:smallerEqDocs,unequal:unequalDocs,setCartesian:setCartesianDocs,setDifference:setDifferenceDocs,setDistinct:setDistinctDocs,setIntersect:setIntersectDocs,setIsSubset:setIsSubsetDocs,setMultiplicity:setMultiplicityDocs,setPowerset:setPowersetDocs,setSize:setSizeDocs,setSymDifference:setSymDifferenceDocs,setUnion:setUnionDocs,erf:erfDocs,cumsum:cumSumDocs,mad:madDocs,max:maxDocs,mean:meanDocs,median:medianDocs,min:minDocs,mode:modeDocs,prod:prodDocs,quantileSeq:quantileSeqDocs,std:stdDocs,sum:sumDocs,variance:varianceDocs,acos:acosDocs,acosh:acoshDocs,acot:acotDocs,acoth:acothDocs,acsc:acscDocs,acsch:acschDocs,asec:asecDocs,asech:asechDocs,asin:asinDocs,asinh:asinhDocs,atan:atanDocs,atanh:atanhDocs,atan2:atan2Docs,cos:cosDocs,cosh:coshDocs,cot:cotDocs,coth:cothDocs,csc:cscDocs,csch:cschDocs,sec:secDocs,sech:sechDocs,sin:sinDocs,sinh:sinhDocs,tan:tanDocs,tanh:tanhDocs,to:toDocs,clone:cloneDocs,format:formatDocs,bin:binDocs,oct:octDocs,hex:hexDocs,isNaN:isNaNDocs,isInteger:isIntegerDocs,isNegative:isNegativeDocs,isNumeric:isNumericDocs,hasNumericValue:hasNumericValueDocs,isPositive:isPositiveDocs,isPrime:isPrimeDocs,isZero:isZeroDocs,print:printDocs,typeOf:typeOfDocs,numeric:numericDocs},name$_="help",dependencies$_=["typed","mathWithTransform","Help"],createHelp=factory(name$_,dependencies$_,(e=>{var{typed:t,mathWithTransform:n,Help:r}=e;return t(name$_,{any:function(e){var t,a=e;if("string"!=typeof e)for(t in n)if(hasOwnProperty$2(n,t)&&e===n[t]){a=t;break}var i=getSafeProperty(embeddedDocs,a);if(!i){var o="function"==typeof a?a.name:a;throw new Error('No documentation found on "'+o+'"')}return new r(i)}})})),name$Z="chain",dependencies$Z=["typed","Chain"],createChain=factory(name$Z,dependencies$Z,(e=>{var{typed:t,Chain:n}=e;return t(name$Z,{"":function(){return new n},any:function(e){return new n(e)}})})),name$Y="det",dependencies$Y=["typed","matrix","subtract","multiply","divideScalar","isZero","unaryMinus"],createDet=factory(name$Y,dependencies$Y,(e=>{var{typed:t,matrix:n,subtract:r,multiply:a,divideScalar:i,isZero:o,unaryMinus:s}=e;return t(name$Y,{any:function(e){return clone$2(e)},"Array | Matrix":function(e){var t;switch((t=isMatrix(e)?e.size():Array.isArray(e)?(e=n(e)).size():[]).length){case 0:return clone$2(e);case 1:if(1===t[0])return clone$2(e.valueOf()[0]);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");case 2:var l=t[0];if(l===t[1])return function(e,t,n){if(1===t)return clone$2(e[0][0]);if(2===t)return r(a(e[0][0],e[1][1]),a(e[1][0],e[0][1]));for(var l=!1,u=new Array(t).fill(0).map(((e,t)=>t)),c=0;c{var{typed:t,matrix:n,divideScalar:r,addScalar:a,multiply:i,unaryMinus:o,det:s,identity:l,abs:u}=e;return t(name$X,{"Array | Matrix":function(e){var t=isMatrix(e)?e.size():arraySize(e);switch(t.length){case 1:if(1===t[0])return isMatrix(e)?n([r(1,e.valueOf()[0])]):[r(1,e[0])];throw new RangeError("Matrix must be square (size: "+format$1(t)+")");case 2:var a=t[0],i=t[1];if(a===i)return isMatrix(e)?n(c(e.valueOf(),a,i),e.storage()):c(e,a,i);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");default:throw new RangeError("Matrix must be two dimensional (size: "+format$1(t)+")")}},any:function(e){return r(1,e)}});function c(e,t,n){var c,p,d,m,f;if(1===t){if(0===(m=e[0][0]))throw Error("Cannot calculate inverse, determinant is zero");return[[r(1,m)]]}if(2===t){var h=s(e);if(0===h)throw Error("Cannot calculate inverse, determinant is zero");return[[r(e[1][1],h),r(o(e[0][1]),h)],[r(o(e[1][0]),h),r(e[0][0],h)]]}var y=e.concat();for(c=0;cv&&(v=u(y[c][g]),T=c),c++;if(0===v)throw Error("Cannot calculate inverse, determinant is zero");(c=T)!==g&&(f=y[g],y[g]=y[c],y[c]=f,f=b[g],b[g]=b[c],b[c]=f);var N=y[g],C=b[g];for(c=0;c{var{typed:t,matrix:n,inv:r,deepEqual:a,equal:i,dotDivide:o,dot:s,ctranspose:l,divideScalar:u,multiply:c,add:p,Complex:d}=e;return t(name$W,{"Array | Matrix":function(e){var t=isMatrix(e)?e.size():arraySize(e);switch(t.length){case 1:return h(e)?l(e):1===t[0]?r(e):o(l(e),s(e,e));case 2:if(h(e))return l(e);var a=t[0],i=t[1];if(a===i)try{return r(e)}catch(e){if(!(e instanceof Error&&e.message.match(/Cannot calculate inverse, determinant is zero/)))throw e}return isMatrix(e)?n(m(e.valueOf(),a,i),e.storage()):m(e,a,i);default:throw new RangeError("Matrix must be two dimensional (size: "+format$1(t)+")")}},any:function(e){return i(e,0)?clone$2(e):u(1,e)}});function m(e,t,n){var{C:a,F:i}=function(e,t,n){var r=function(e,t,n){for(var r=clone$2(e),a=0,i=0;ie.filter(((e,n)=>n!f(s(r[t],r[t]))));return{C:a,F:i}}(e,t,n),u=c(r(c(l(a),a)),l(a)),d=c(l(i),r(c(i,l(i))));return c(d,u)}function f(e){return i(p(e,d(1,1)),p(0,d(1,1)))}function h(e){return a(p(e,d(1,1)),p(c(e,0),d(1,1)))}}));function createComplexEigs(e){var{addScalar:t,subtract:n,flatten:r,multiply:a,multiplyScalar:i,divideScalar:o,sqrt:s,abs:l,bignumber:u,diag:c,inv:p,qr:d,usolve:m,usolveAll:f,equal:h,complex:y,larger:b,smaller:g,matrixFromColumns:v,dot:T}=e;function N(e,r,a,o){var l=t(e,o),u=n(i(e,o),i(r,a)),c=i(l,.5),p=i(s(n(i(l,l),i(4,u))),.5);return[t(c,p),n(c,p)]}function C(e,t,r,a,i,o,s,c){var p="BigNumber"===c,d="Complex"===c,m=p?u(0):d?y(0):0,f=p?u(1):d?y(1):1;if(g(l(r),s))return[[f,m],[m,f]];if(b(l(n(i,o)),s))return[[n(i,a),n(o,a)],[r,r]];var h=n(e,i),v=n(t,i),T=n(r,i),N=n(a,i);return g(l(v),s)?[[h,f],[T,m]]:[[v,m],[N,f]]}function A(e,t){for(var n=0;n=5)return null;for(s=0;;){var l=m(e,i);if(g(E(V(i,[l])),r))break;if(++s>=10)return null;i=O(l)}return i}function w(e,t,n){var r="BigNumber"===n,a="Complex"===n,i=Array(e).fill(0).map((e=>2*Math.random()-1));return r&&(i=i.map((e=>u(e)))),a&&(i=i.map((e=>y(e)))),O(i=V(i,t),n)}function V(e,t){for(var r of t)e=n(e,a(o(T(r,e),T(r,r)),r));return e}function E(e){return l(s(T(e,e)))}function O(e,t){var n="Complex"===t,r="BigNumber"===t?u(1):n?y(1):1;return a(o(r,E(e)),e)}return function(e,s,m,T,w){void 0===w&&(w=!0);var V=function(e,n,r,a,s){var p,d="BigNumber"===a,m="Complex"===a,f=d?u(0):0,v=d?u(1):m?y(1):1,T=d?u(1):1,N=d?u(10):2,C=i(N,N);s&&(p=Array(n).fill(v));for(var A=!1;!A;){A=!0;for(var S=0;S1&&(x=c(Array(v-1).fill(f)))),v-=1,h.pop();for(var $=0;$2&&(x=c(Array(v-2).fill(f)))),v-=2,h.pop(),h.pop();for(var I=0;I+n(l(e),l(t)))),w>100){var R=Error("The eigenvalues failed to converge. Only found these eigenvalues: "+b.join(", "));throw R.values=b,R.vectors=[],R}var P=s?a(S,function(e,t){for(var n=[],r=0;ra(h,e))),E.push(...c.map((e=>r(e))))},R=0;R=Math.abs(a);){var l=s[0][0],u=s[0][1];e=T(e,n=h(e[l][l],e[u][u],e[l][u]),l,u),i=b(i,n,l,u),s=N(e)}for(var c=S(r,0),p=0;p=a(i);){var u=l[0][0],c=l[0][1];e=v(e,n=y(e[u][u],e[c][c],e[u][c]),u,c),o=g(o,n,u,c),l=C(e)}for(var p=S(r,0),d=0;d2&&void 0!==arguments[2]?arguments[2]:t.epsilon,a=arguments.length>3?arguments[3]:void 0;if("number"===a)return m(e,r);if("BigNumber"===a)return f(e,r);throw TypeError("Unsupported data type: "+a)}}var name$V="eigs",dependencies$V=["config","typed","matrix","addScalar","equal","subtract","abs","atan","cos","sin","multiplyScalar","divideScalar","inv","bignumber","multiply","add","larger","column","flatten","number","complex","sqrt","diag","qr","usolve","usolveAll","im","re","smaller","matrixFromColumns","dot"],createEigs=factory(name$V,dependencies$V,(e=>{var{config:t,typed:n,matrix:r,addScalar:a,subtract:i,equal:o,abs:s,atan:l,cos:u,sin:c,multiplyScalar:p,divideScalar:d,inv:m,bignumber:f,multiply:h,add:y,larger:b,column:g,flatten:v,number:T,complex:N,sqrt:C,diag:A,qr:S,usolve:x,usolveAll:w,im:V,re:E,smaller:O,matrixFromColumns:_,dot:$}=e,D=createRealSymmetric({config:t,addScalar:a,subtract:i,column:g,flatten:v,equal:o,abs:s,atan:l,cos:u,sin:c,multiplyScalar:p,inv:m,bignumber:f,complex:N,multiply:h,add:y}),I=createComplexEigs({config:t,addScalar:a,subtract:i,multiply:h,multiplyScalar:p,flatten:v,divideScalar:d,sqrt:C,abs:s,bignumber:f,diag:A,qr:S,inv:m,usolve:x,usolveAll:w,equal:o,complex:N,larger:b,smaller:O,matrixFromColumns:_,dot:$});return n("eigs",{Array:function(e){return R(r(e))},"Array, number|BigNumber":function(e,t){return R(r(e),t)},Matrix:function(e){var{values:t,vectors:n}=R(e);return{values:r(t),vectors:r(n)}},"Matrix, number|BigNumber":function(e,t){var{values:n,vectors:a}=R(e,t);return{values:r(n),vectors:r(a)}}});function R(e,n){void 0===n&&(n=t.epsilon);var r=e.size();if(2!==r.length||r[0]!==r[1])throw new RangeError("Matrix must be square (size: "+format$1(r)+")");var a=e.toArray(),o=r[0];if(function(e,t,n){for(var r=0;r{var{typed:t,abs:n,add:r,identity:a,inv:i,multiply:o}=e;return t(name$U,{Matrix:function(e){var t=e.size();if(2!==t.length||t[0]!==t[1])throw new RangeError("Matrix must be square (size: "+format$1(t)+")");for(var l=t[0],u=function(e){for(var t=e.size()[0],r=0,a=0;a1&&(b=o(b,m),g=-g),f=r(f,o(y=y*(p-v+1)/((2*p-v+1)*v),b)),h=r(h,o(y*g,b));for(var T=o(i(h),f),N=0;N{var{typed:t,abs:n,add:r,multiply:a,sqrt:i,subtract:o,inv:s,size:l,max:u,identity:c}=e,p=1e-6;return t(name$T,{"Array | Matrix":function(e){var t=isMatrix(e)?e.size():arraySize(e);switch(t.length){case 1:if(1===t[0])return i(e);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");case 2:if(t[0]===t[1])return function(e){var t,i=0,d=e,m=c(l(e));do{var f=d;if(d=a(.5,r(f,s(m))),m=a(.5,r(m,s(f))),(t=u(n(o(d,f))))>p&&++i>1e3)throw new Error("computing square root of matrix: iterative method could not converge")}while(t>p);return d}(e);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");default:throw new RangeError("Matrix must be at most two dimensional (size: "+format$1(t)+")")}}})})),name$S="divide",dependencies$S=["typed","matrix","multiply","equalScalar","divideScalar","inv"],createDivide=factory(name$S,dependencies$S,(e=>{var{typed:t,matrix:n,multiply:r,equalScalar:a,divideScalar:i,inv:o}=e,s=createAlgorithm11({typed:t,equalScalar:a}),l=createAlgorithm14({typed:t});return t("divide",extend$2({"Array | Matrix, Array | Matrix":function(e,t){return r(e,o(t))},"DenseMatrix, any":function(e,t){return l(e,t,i,!1)},"SparseMatrix, any":function(e,t){return s(e,t,i,!1)},"Array, any":function(e,t){return l(n(e),t,i,!1).valueOf()},"any, Array | Matrix":function(e,t){return r(e,o(t))}},i.signatures))})),name$R="distance",dependencies$R=["typed","addScalar","subtract","divideScalar","multiplyScalar","unaryMinus","sqrt","abs"],createDistance=factory(name$R,dependencies$R,(e=>{var{typed:t,addScalar:n,subtract:r,multiplyScalar:a,divideScalar:i,unaryMinus:o,sqrt:s,abs:l}=e;return t(name$R,{"Array, Array, Array":function(e,t,n){if(2===e.length&&2===t.length&&2===n.length){if(!c(e))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!c(t))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");var s=i(r(n[1],n[0]),r(t[1],t[0])),l=a(a(s,s),t[0]),u=o(a(s,t[0])),p=e[1];return h(e[0],e[1],l,u,p)}throw new TypeError("Invalid Arguments: Try again")},"Object, Object, Object":function(e,t,n){if(2===Object.keys(e).length&&2===Object.keys(t).length&&2===Object.keys(n).length){if(!c(e))throw new TypeError("Values of pointX and pointY should be numbers or BigNumbers");if(!c(t))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("pointX"in e&&"pointY"in e&&"lineOnePtX"in t&&"lineOnePtY"in t&&"lineTwoPtX"in n&&"lineTwoPtY"in n){var s=i(r(n.lineTwoPtY,n.lineTwoPtX),r(t.lineOnePtY,t.lineOnePtX)),l=a(a(s,s),t.lineOnePtX),u=o(a(s,t.lineOnePtX)),p=e.pointX;return h(e.pointX,e.pointY,l,u,p)}throw new TypeError("Key names do not match")}throw new TypeError("Invalid Arguments: Try again")},"Array, Array":function(e,t){if(2===e.length&&3===t.length){if(!c(e))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!p(t))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");return h(e[0],e[1],t[0],t[1],t[2])}if(3===e.length&&6===t.length){if(!p(e))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!m(t))throw new TypeError("Array with 6 numbers or BigNumbers expected for second argument");return y(e[0],e[1],e[2],t[0],t[1],t[2],t[3],t[4],t[5])}if(e.length===t.length&&e.length>0){if(!d(e))throw new TypeError("All values of an array should be numbers or BigNumbers");if(!d(t))throw new TypeError("All values of an array should be numbers or BigNumbers");return b(e,t)}throw new TypeError("Invalid Arguments: Try again")},"Object, Object":function(e,t){if(2===Object.keys(e).length&&3===Object.keys(t).length){if(!c(e))throw new TypeError("Values of pointX and pointY should be numbers or BigNumbers");if(!p(t))throw new TypeError("Values of xCoeffLine, yCoeffLine and constant should be numbers or BigNumbers");if("pointX"in e&&"pointY"in e&&"xCoeffLine"in t&&"yCoeffLine"in t&&"constant"in t)return h(e.pointX,e.pointY,t.xCoeffLine,t.yCoeffLine,t.constant);throw new TypeError("Key names do not match")}if(3===Object.keys(e).length&&6===Object.keys(t).length){if(!p(e))throw new TypeError("Values of pointX, pointY and pointZ should be numbers or BigNumbers");if(!m(t))throw new TypeError("Values of x0, y0, z0, a, b and c should be numbers or BigNumbers");if("pointX"in e&&"pointY"in e&&"x0"in t&&"y0"in t&&"z0"in t&&"a"in t&&"b"in t&&"c"in t)return y(e.pointX,e.pointY,e.pointZ,t.x0,t.y0,t.z0,t.a,t.b,t.c);throw new TypeError("Key names do not match")}if(2===Object.keys(e).length&&2===Object.keys(t).length){if(!c(e))throw new TypeError("Values of pointOneX and pointOneY should be numbers or BigNumbers");if(!c(t))throw new TypeError("Values of pointTwoX and pointTwoY should be numbers or BigNumbers");if("pointOneX"in e&&"pointOneY"in e&&"pointTwoX"in t&&"pointTwoY"in t)return b([e.pointOneX,e.pointOneY],[t.pointTwoX,t.pointTwoY]);throw new TypeError("Key names do not match")}if(3===Object.keys(e).length&&3===Object.keys(t).length){if(!p(e))throw new TypeError("Values of pointOneX, pointOneY and pointOneZ should be numbers or BigNumbers");if(!p(t))throw new TypeError("Values of pointTwoX, pointTwoY and pointTwoZ should be numbers or BigNumbers");if("pointOneX"in e&&"pointOneY"in e&&"pointOneZ"in e&&"pointTwoX"in t&&"pointTwoY"in t&&"pointTwoZ"in t)return b([e.pointOneX,e.pointOneY,e.pointOneZ],[t.pointTwoX,t.pointTwoY,t.pointTwoZ]);throw new TypeError("Key names do not match")}throw new TypeError("Invalid Arguments: Try again")},Array:function(e){if(!function(e){if(2===e[0].length&&u(e[0][0])&&u(e[0][1])){if(e.some((e=>2!==e.length||!u(e[0])||!u(e[1]))))return!1}else{if(!(3===e[0].length&&u(e[0][0])&&u(e[0][1])&&u(e[0][2])))return!1;if(e.some((e=>3!==e.length||!u(e[0])||!u(e[1])||!u(e[2]))))return!1}return!0}(e))throw new TypeError("Incorrect array format entered for pairwise distance calculation");return function(e){for(var t=[],n=[],r=[],a=0;a{var{typed:t,config:n,abs:r,add:a,addScalar:i,matrix:o,multiply:s,multiplyScalar:l,divideScalar:u,subtract:c,smaller:p,equalScalar:d,flatten:m,isZero:f,isNumeric:h}=e;return t("intersect",{"Array, Array, Array":y,"Array, Array, Array, Array":b,"Matrix, Matrix, Matrix":function(e,t,n){var r=y(e.valueOf(),t.valueOf(),n.valueOf());return null===r?null:o(r)},"Matrix, Matrix, Matrix, Matrix":function(e,t,n,r){var a=b(e.valueOf(),t.valueOf(),n.valueOf(),r.valueOf());return null===a?null:o(a)}});function y(e,t,n){if(e=g(e),t=g(t),n=g(n),!T(e))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!T(t))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");if(!function(e){return 4===e.length&&h(e[0])&&h(e[1])&&h(e[2])&&h(e[3])}(n))throw new TypeError("Array with 4 numbers expected as third argument");return function(e,t,n,r,a,o,s,p,d,m){var f=l(e,s),h=l(r,s),y=l(t,p),b=l(a,p),g=l(n,d),v=l(o,d),T=c(c(c(m,f),y),g),N=c(c(c(i(i(h,b),v),f),y),g),C=u(T,N);return[i(e,l(C,c(r,e))),i(t,l(C,c(a,t))),i(n,l(C,c(o,n)))]}(e[0],e[1],e[2],t[0],t[1],t[2],n[0],n[1],n[2],n[3])}function b(e,t,o,m){if(e=g(e),t=g(t),o=g(o),m=g(m),2===e.length){if(!v(e))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!v(t))throw new TypeError("Array with 2 numbers or BigNumbers expected for second argument");if(!v(o))throw new TypeError("Array with 2 numbers or BigNumbers expected for third argument");if(!v(m))throw new TypeError("Array with 2 numbers or BigNumbers expected for fourth argument");return function(e,t,o,d){var m=e,h=o,y=c(m,t),b=c(h,d),g=c(l(y[0],b[1]),l(b[0],y[1]));if(f(g))return null;if(p(r(g),n.epsilon))return null;var v=l(b[0],m[1]),T=l(b[1],m[0]),N=l(b[0],h[1]),C=l(b[1],h[0]),A=u(i(c(c(v,T),N),C),g);return a(s(y,A),m)}(e,t,o,m)}if(3===e.length){if(!T(e))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!T(t))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");if(!T(o))throw new TypeError("Array with 3 numbers or BigNumbers expected for third argument");if(!T(m))throw new TypeError("Array with 3 numbers or BigNumbers expected for fourth argument");return function(e,t,n,r,a,o,s,p,m,h,y,b){var g=N(e,s,h,s,t,p,y,p,n,m,b,m),v=N(h,s,r,e,y,p,a,t,b,m,o,n),T=N(e,s,r,e,t,p,a,t,n,m,o,n),C=N(h,s,h,s,y,p,y,p,b,m,b,m),A=N(r,e,r,e,a,t,a,t,o,n,o,n),S=c(l(g,v),l(T,C)),x=c(l(A,C),l(v,v));if(f(x))return null;var w=u(S,x),V=u(i(g,l(w,v)),C),E=i(e,l(w,c(r,e))),O=i(t,l(w,c(a,t))),_=i(n,l(w,c(o,n))),$=i(s,l(V,c(h,s))),D=i(p,l(V,c(y,p))),I=i(m,l(V,c(b,m)));return d(E,$)&&d(O,D)&&d(_,I)?[E,O,_]:null}(e[0],e[1],e[2],t[0],t[1],t[2],o[0],o[1],o[2],m[0],m[1],m[2])}throw new TypeError("Arrays with two or thee dimensional points expected")}function g(e){return 1===e.length?e[0]:e.length>1&&Array.isArray(e[0])&&e.every((e=>Array.isArray(e)&&1===e.length))?m(e):e}function v(e){return 2===e.length&&h(e[0])&&h(e[1])}function T(e){return 3===e.length&&h(e[0])&&h(e[1])&&h(e[2])}function N(e,t,n,r,a,o,s,u,p,d,m,f){var h=l(c(e,t),c(n,r)),y=l(c(a,o),c(s,u)),b=l(c(p,d),c(m,f));return i(i(h,y),b)}})),name$P="sum",dependencies$P=["typed","config","add","numeric"],createSum=factory(name$P,dependencies$P,(e=>{var{typed:t,config:n,add:r,numeric:a}=e;return t(name$P,{"Array | Matrix":i,"Array | Matrix, number | BigNumber":function(e,t){try{return reduce$2(e,t,r)}catch(e){throw improveErrorMessage(e,"sum")}},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function sum");return i(e)}});function i(e){var t;return deepForEach(e,(function(e){try{t=void 0===t?e:r(t,e)}catch(t){throw improveErrorMessage(t,"sum",e)}})),void 0===t&&(t=a(0,n.number)),"string"==typeof t&&(t=a(t,n.number)),t}})),name$O="cumsum",dependencies$O=["typed","add","unaryPlus"],createCumSum=factory(name$O,dependencies$O,(e=>{var{typed:t,add:n,unaryPlus:r}=e;return t(name$O,{Array:a,Matrix:function(e){return e.create(a(e.valueOf()))},"Array, number | BigNumber":o,"Matrix, number | BigNumber":function(e,t){return e.create(o(e.valueOf(),t))},"...":function(e){if(containsCollections(e))throw new TypeError("All values expected to be scalar in function cumsum");return a(e)}});function a(e){try{return i(e)}catch(e){throw improveErrorMessage(e,name$O)}}function i(e){if(0===e.length)return[];for(var t=[r(e[0])],a=1;a=n.length)throw new IndexError(t,n.length);try{return s(e,t)}catch(e){throw improveErrorMessage(e,name$O)}}function s(e,t){var n,r,a;if(t<=0){var o=e[0][0];if(Array.isArray(o)){for(a=_switch$1(e),r=[],n=0;n{var{typed:t,add:n,divide:r}=e;return t(name$N,{"Array | Matrix":a,"Array | Matrix, number | BigNumber":function(e,t){try{var a=reduce$2(e,t,n),i=Array.isArray(e)?arraySize(e):e.size();return r(a,i[t])}catch(e){throw improveErrorMessage(e,"mean")}},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function mean");return a(e)}});function a(e){var t,a=0;if(deepForEach(e,(function(e){try{t=void 0===t?e:n(t,e),a++}catch(t){throw improveErrorMessage(t,"mean",e)}})),0===a)throw new Error("Cannot calculate the mean of an empty array");return r(t,a)}})),name$M="median",dependencies$M=["typed","add","divide","compare","partitionSelect"],createMedian=factory(name$M,dependencies$M,(e=>{var{typed:t,add:n,divide:r,compare:a,partitionSelect:i}=e;function o(e){try{var t=(e=flatten$4(e.valueOf())).length;if(0===t)throw new Error("Cannot calculate median of an empty array");if(t%2==0){for(var n=t/2-1,r=i(e,n+1),o=e[n],u=0;u0&&(o=e[u]);return l(o,r)}var c=i(e,(t-1)/2);return s(c)}catch(e){throw improveErrorMessage(e,"median")}}var s=t({"number | BigNumber | Complex | Unit":function(e){return e}}),l=t({"number | BigNumber | Complex | Unit, number | BigNumber | Complex | Unit":function(e,t){return r(n(e,t),2)}});return t(name$M,{"Array | Matrix":o,"Array | Matrix, number | BigNumber":function(e,t){throw new Error("median(A, dim) is not yet supported")},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function median");return o(e)}})})),name$L="mad",dependencies$L=["typed","abs","map","median","subtract"],createMad=factory(name$L,dependencies$L,(e=>{var{typed:t,abs:n,map:r,median:a,subtract:i}=e;return t(name$L,{"Array | Matrix":o,"...":function(e){return o(e)}});function o(e){if(0===(e=flatten$4(e.valueOf())).length)throw new Error("Cannot calculate median absolute deviation (mad) of an empty array");try{var t=a(e);return a(r(e,(function(e){return n(i(e,t))})))}catch(e){throw e instanceof TypeError&&-1!==e.message.indexOf("median")?new TypeError(e.message.replace("median","mad")):improveErrorMessage(e,"mad")}}})),DEFAULT_NORMALIZATION="unbiased",name$K="variance",dependencies$K=["typed","add","subtract","multiply","divide","apply","isNaN"],createVariance=factory(name$K,dependencies$K,(e=>{var{typed:t,add:n,subtract:r,multiply:a,divide:i,apply:o,isNaN:s}=e;return t(name$K,{"Array | Matrix":function(e){return l(e,DEFAULT_NORMALIZATION)},"Array | Matrix, string":l,"Array | Matrix, number | BigNumber":function(e,t){return u(e,t,DEFAULT_NORMALIZATION)},"Array | Matrix, number | BigNumber, string":u,"...":function(e){return l(e,DEFAULT_NORMALIZATION)}});function l(e,t){var o,l=0;if(0===e.length)throw new SyntaxError("Function variance requires one or more parameters (0 provided)");if(deepForEach(e,(function(e){try{o=void 0===o?e:n(o,e),l++}catch(t){throw improveErrorMessage(t,"variance",e)}})),0===l)throw new Error("Cannot calculate variance of an empty array");var u=i(o,l);if(o=void 0,deepForEach(e,(function(e){var t=r(e,u);o=void 0===o?a(t,t):n(o,a(t,t))})),s(o))return o;switch(t){case"uncorrected":return i(o,l);case"biased":return i(o,l+1);case"unbiased":var c=isBigNumber(o)?o.mul(0):0;return 1===l?c:i(o,l-1);default:throw new Error('Unknown normalization "'+t+'". Choose "unbiased" (default), "uncorrected", or "biased".')}}function u(e,t,n){try{if(0===e.length)throw new SyntaxError("Function variance requires one or more parameters (0 provided)");return o(e,t,(e=>l(e,n)))}catch(e){throw improveErrorMessage(e,"variance")}}})),name$J="quantileSeq",dependencies$J=["typed","add","multiply","partitionSelect","compare"],createQuantileSeq=factory(name$J,dependencies$J,(e=>{var{typed:t,add:n,multiply:r,partitionSelect:a,compare:i}=e;function o(e,t,o){var l=flatten$4(e),u=l.length;if(0===u)throw new Error("Cannot calculate quantile of an empty sequence");if(isNumber$1(t)){var c=t*(u-1),p=c%1;if(0===p){var d=o?l[c]:a(l,c);return s(d),d}var m,f,h=Math.floor(c);if(o)m=l[h],f=l[h+1];else{f=a(l,h+1),m=l[h];for(var y=0;y0&&(m=l[y])}return s(m),s(f),n(r(m,1-p),r(f,p))}var b=t.times(u-1);if(b.isInteger()){b=b.toNumber();var g=o?l[b]:a(l,b);return s(g),g}var v,T,N=b.floor(),C=b.minus(N),A=N.toNumber();if(o)v=l[A],T=l[A+1];else{T=a(l,A+1),v=l[A];for(var S=0;S0&&(v=l[S])}s(v),s(T);var x=new C.constructor(1);return n(r(v,x.minus(C)),r(T,C))}var s=t({"number | BigNumber | Unit":function(e){return e}});return function(e,t,n){var r,a,i;if(arguments.length<2||arguments.length>3)throw new SyntaxError("Function quantileSeq requires two or three parameters");if(isCollection(e)){if("boolean"==typeof(n=n||!1)){if(a=e.valueOf(),isNumber$1(t)){if(t<0)throw new Error("N/prob must be non-negative");if(t<=1)return o(a,t,n);if(t>1){if(!isInteger$1(t))throw new Error("N must be a positive integer");var s=t+1;r=new Array(t);for(var l=0;l4294967295)throw new Error("N must be less than or equal to 2^32-1, as that is the maximum length of an Array");var p=new u(c+1);r=new Array(c);for(var d=0;d1)throw new Error("Probability must be between 0 and 1, inclusive")}else{if(!isBigNumber(f))throw new TypeError("Unexpected type of argument in function quantileSeq");if(i=new f.constructor(1),f.isNegative()||f.gt(i))throw new Error("Probability must be between 0 and 1, inclusive")}r[m]=o(a,f,n)}return r}throw new TypeError("Unexpected type of argument in function quantileSeq")}throw new TypeError("Unexpected type of argument in function quantileSeq")}throw new TypeError("Unexpected type of argument in function quantileSeq")}})),name$I="std",dependencies$I=["typed","sqrt","variance"],createStd=factory(name$I,dependencies$I,(e=>{var{typed:t,sqrt:n,variance:r}=e;return t(name$I,{"Array | Matrix":a,"Array | Matrix, string":a,"Array | Matrix, number | BigNumber":a,"Array | Matrix, number | BigNumber, string":a,"...":function(e){return a(e)}});function a(e,t){if(0===e.length)throw new SyntaxError("Function std requires one or more parameters (0 provided)");try{return n(r.apply(null,arguments))}catch(e){throw e instanceof TypeError&&-1!==e.message.indexOf(" variance")?new TypeError(e.message.replace(" variance"," std")):e}}})),name$H="combinations",dependencies$H=["typed"],createCombinations=factory(name$H,dependencies$H,(e=>{var{typed:t}=e;return t(name$H,{"number, number":combinationsNumber,"BigNumber, BigNumber":function(e,t){var n,r,a=e.constructor,i=e.minus(t),o=new a(1);if(!isPositiveInteger$2(e)||!isPositiveInteger$2(t))throw new TypeError("Positive integer value expected in function combinations");if(t.gt(e))throw new TypeError("k must be less than n in function combinations");if(n=o,t.lt(i))for(r=o;r.lte(i);r=r.plus(o))n=n.times(t.plus(r)).dividedBy(r);else for(r=o;r.lte(t);r=r.plus(o))n=n.times(i.plus(r)).dividedBy(r);return n}})}));function isPositiveInteger$2(e){return e.isInteger()&&e.gte(0)}var name$G="combinationsWithRep",dependencies$G=["typed"],createCombinationsWithRep=factory(name$G,dependencies$G,(e=>{var{typed:t}=e;return t(name$G,{"number, number":function(e,t){if(!isInteger$1(e)||e<0)throw new TypeError("Positive integer value expected in function combinationsWithRep");if(!isInteger$1(t)||t<0)throw new TypeError("Positive integer value expected in function combinationsWithRep");if(e<1)throw new TypeError("k must be less than or equal to n + k - 1");return t{var{typed:t,config:n,multiplyScalar:r,pow:a,BigNumber:i,Complex:o}=e;return t(name$F,{number:gammaNumber,Complex:function(e){if(0===e.im)return this(e.re);if(e.re<.5){var t=new o(1-e.re,-e.im),n=new o(Math.PI*e.re,Math.PI*e.im);return new o(Math.PI).div(n.sin()).div(this(t))}e=new o(e.re-1,e.im);for(var r=new o(gammaP[0],0),a=1;a2;)l+=a-=2,o=o.times(l);return new i(o.toPrecision(i.precision))}})),name$E="lgamma",dependencies$E=["Complex","typed"],createLgamma=factory(name$E,dependencies$E,(e=>{var{Complex:t,typed:n}=e,r=[-.029550653594771242,.00641025641025641,-.0019175269175269176,.0008417508417508417,-.0005952380952380953,.0007936507936507937,-.002777777777777778,.08333333333333333];return n(name$E,{number:lgammaNumber,Complex:function(e){if(e.isNaN())return new t(NaN,NaN);if(0===e.im)return new t(lgammaNumber(e.re),0);if(e.re>=7||Math.abs(e.im)>=7)return a(e);if(e.re<=.1){var n=copysign(6.283185307179586,e.im)*Math.floor(.5*e.re+.25),r=e.mul(Math.PI).sin().log(),o=this(new t(1-e.re,-e.im));return new t(1.1447298858494002,n).sub(r).sub(o)}return e.im>=0?i(e):i(e.conjugate()).conjugate()},BigNumber:function(){throw new Error("mathjs doesn't yet provide an implementation of the algorithm lgamma for BigNumber")}});function a(e){for(var n=e.sub(.5).mul(e.log()).sub(e).add(lnSqrt2PI),a=new t(1,0).div(e),i=a.div(e),o=r[0],s=r[1],l=2*i.re,u=i.re*i.re+i.im*i.im,c=2;c<8;c++){var p=s;s=-u*o+r[c],o=l*o+p}var d=a.mul(i.mul(o).add(s));return n.add(d)}function i(e){var n=0,r=0,i=e;for(e=e.add(1);e.re<=7;){var o=(i=i.mul(e)).im<0?1:0;0!==o&&0===r&&n++,r=o,e=e.add(1)}return a(e).sub(i.log()).sub(new t(0,2*n*Math.PI*1))}})),name$D="factorial",dependencies$D=["typed","gamma"],createFactorial=factory(name$D,dependencies$D,(e=>{var{typed:t,gamma:n}=e;return t(name$D,{number:function(e){if(e<0)throw new Error("Value must be non-negative");return n(e+1)},BigNumber:function(e){if(e.isNegative())throw new Error("Value must be non-negative");return n(e.plus(1))},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$C="kldivergence",dependencies$C=["typed","matrix","divide","sum","multiply","dotDivide","log","isNumeric"],createKldivergence=factory(name$C,dependencies$C,(e=>{var{typed:t,matrix:n,divide:r,sum:a,multiply:i,dotDivide:o,log:s,isNumeric:l}=e;return t(name$C,{"Array, Array":function(e,t){return u(n(e),n(t))},"Matrix, Array":function(e,t){return u(e,n(t))},"Array, Matrix":function(e,t){return u(n(e),t)},"Matrix, Matrix":function(e,t){return u(e,t)}});function u(e,t){var n=t.size().length,u=e.size().length;if(n>1)throw new Error("first object must be one dimensional");if(u>1)throw new Error("second object must be one dimensional");if(n!==u)throw new Error("Length of two vectors must be equal");if(0===a(e))throw new Error("Sum of elements in first object must be non zero");if(0===a(t))throw new Error("Sum of elements in second object must be non zero");var c=r(e,a(e)),p=r(t,a(t)),d=a(i(c,s(o(c,p))));return l(d)?d:Number.NaN}})),name$B="multinomial",dependencies$B=["typed","add","divide","multiply","factorial","isInteger","isPositive"],createMultinomial=factory(name$B,dependencies$B,(e=>{var{typed:t,add:n,divide:r,multiply:a,factorial:i,isInteger:o,isPositive:s}=e;return t(name$B,{"Array | Matrix":function(e){var t=0,l=1;return deepForEach(e,(function(e){if(!o(e)||!s(e))throw new TypeError("Positive integer value expected in function multinomial");t=n(t,e),l=a(l,i(e))})),r(i(t),l)}})})),name$A="permutations",dependencies$A=["typed","factorial"],createPermutations=factory(name$A,dependencies$A,(e=>{var{typed:t,factorial:n}=e;return t(name$A,{"number | BigNumber":n,"number, number":function(e,t){if(!isInteger$1(e)||e<0)throw new TypeError("Positive integer value expected in function permutations");if(!isInteger$1(t)||t<0)throw new TypeError("Positive integer value expected in function permutations");if(t>e)throw new TypeError("second argument k must be less than or equal to first argument n");return product(e-t+1,e)},"BigNumber, BigNumber":function(e,t){var n,r;if(!isPositiveInteger(e)||!isPositiveInteger(t))throw new TypeError("Positive integer value expected in function permutations");if(t.gt(e))throw new TypeError("second argument k must be less than or equal to first argument n");for(n=e.mul(0).add(1),r=e.minus(t).plus(1);r.lte(e);r=r.plus(1))n=n.times(r);return n}})}));function isPositiveInteger(e){return e.isInteger()&&e.gte(0)}var alea$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this,n=function(){var e=4022871197;return function(t){t=String(t);for(var n=0;n>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)}}();t.next=function(){var e=2091639*t.s0+2.3283064365386963e-10*t.c;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=0|e)},t.c=1,t.s0=n(" "),t.s1=n(" "),t.s2=n(" "),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function a(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function i(e,t){var n=new r(e),i=t&&t.state,o=n.next;return o.int32=function(){return 4294967296*n.next()|0},o.double=function(){return o()+11102230246251565e-32*(2097152*o()|0)},o.quick=o,i&&("object"==typeof i&&a(i,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=i:this.alea=i}(0,e)}(alea$1);var xor128$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&a(i,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=i:this.xor128=i}(0,e)}(xor128$1);var xorwow$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r>>4),t.next()}function a(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function i(e,t){var n=new r(e),i=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&a(i,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=i:this.xorwow=i}(0,e)}(xorwow$1);var xorshift7$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.x,a=t.i;return e=r[a],n=(e^=e>>>7)^e<<24,n^=(e=r[a+1&7])^e>>>10,n^=(e=r[a+3&7])^e>>>3,n^=(e=r[a+4&7])^e<<7,e=r[a+7&7],n^=(e^=e<<13)^e<<9,r[a]=n,t.i=a+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n0;--n)e.next()}(t,e)}function a(e,t){return t.x=e.x.slice(),t.i=e.i,t}function i(e,t){null==e&&(e=+new Date);var n=new r(e),i=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,i&&(i.x&&a(i,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=i:this.xorshift7=i}(0,e)}(xorshift7$1);var xor4096$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.w,a=t.X,i=t.i;return t.w=r=r+1640531527|0,n=a[i+34&127],e=a[i=i+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=a[i]=n^e,t.i=i,n+(r^r>>>16)|0},function(e,t){var n,r,a,i,o,s=[],l=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,l=Math.max(l,t.length)),a=0,i=-32;i>>15,r^=r<<4,r^=r>>>13,i>=0&&(o=o+1640531527|0,a=0==(n=s[127&i]^=r+o)?a+1:0);for(a>=128&&(s[127&(t&&t.length||0)]=-1),a=127,i=512;i>0;--i)r=s[a+34&127],n=s[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[a]=r^n;e.w=o,e.X=s,e.i=a}(t,e)}function a(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function i(e,t){null==e&&(e=+new Date);var n=new r(e),i=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,i&&(i.X&&a(i,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=i:this.xor4096=i}(0,e)}(xor4096$1);var tychei$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,a=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^a,a=a-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^a,t.a=a-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&a(i,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=i:this.tychei=i}(0,e)}(tychei$1);var seedrandom$2={exports:{}},_nodeResolve_empty={},_nodeResolve_empty$1=Object.freeze({__proto__:null,default:_nodeResolve_empty}),require$$0=getAugmentedNamespace(_nodeResolve_empty$1);!function(e){!function(t,n,r){var a,i=256,o=r.pow(i,6),s=r.pow(2,52),l=2*s,u=255;function c(e,u,c){var y=[],b=f(m((u=1==u?{entropy:!0}:u||{}).entropy?[e,h(n)]:null==e?function(){try{var e;return a&&(e=a.randomBytes)?e=e(i):(e=new Uint8Array(i),(t.crypto||t.msCrypto).getRandomValues(e)),h(e)}catch(e){var r=t.navigator,o=r&&r.plugins;return[+new Date,t,o,t.screen,h(n)]}}():e,3),y),g=new p(y),v=function(){for(var e=g.g(6),t=o,n=0;e=l;)e/=2,t/=2,n>>>=1;return(e+n)/t};return v.int32=function(){return 0|g.g(4)},v.quick=function(){return g.g(4)/4294967296},v.double=v,f(h(g.S),n),(u.pass||c||function(e,t,n,a){return a&&(a.S&&d(a,g),e.state=function(){return d(g,{})}),n?(r.random=e,t):e})(v,b,"global"in u?u.global:this==r,u.state)}function p(e){var t,n=e.length,r=this,a=0,o=r.i=r.j=0,s=r.S=[];for(n||(e=[n++]);a{var{typed:t,config:n,on:r}=e,a=createRng(n.randomSeed);return r&&r("config",(function(e,t){e.randomSeed!==t.randomSeed&&(a=createRng(e.randomSeed))})),t(name$z,{"Array | Matrix":function(e){return i(e,{})},"Array | Matrix, Object":function(e,t){return i(e,t)},"Array | Matrix, number":function(e,t){return i(e,{number:t})},"Array | Matrix, Array | Matrix":function(e,t){return i(e,{weights:t})},"Array | Matrix, Array | Matrix, number":function(e,t,n){return i(e,{number:n,weights:t})},"Array | Matrix, number, Array | Matrix":function(e,t,n){return i(e,{number:t,weights:n})}});function i(e,t){var{number:n,weights:r,elementWise:i=!0}=t,o=void 0===n;o&&(n=1);var s=isMatrix(e)?e.create:isMatrix(r)?r.create:null;e=e.valueOf(),r&&(r=r.valueOf()),!0===i&&(e=flatten$4(e),r=flatten$4(r));var l=0;if(void 0!==r){if(r.length!==e.length)throw new Error("Weights must have the same length as possibles");for(var u=0,c=r.length;u1)for(var r=0,a=e.shift();r{var{typed:t,config:n,on:r}=e,a=createRng(n.randomSeed);return r&&r("config",(function(e,t){e.randomSeed!==t.randomSeed&&(a=createRng(e.randomSeed))})),t(name$y,{"":()=>o(0,1),number:e=>o(0,e),"number, number":(e,t)=>o(e,t),"Array | Matrix":e=>i(e,0,1),"Array | Matrix, number":(e,t)=>i(e,0,t),"Array | Matrix, number, number":(e,t,n)=>i(e,t,n)});function i(e,t,n){var r=randomMatrix(e.valueOf(),(()=>o(t,n)));return isMatrix(e)?e.create(r):r}function o(e,t){return e+a()*(t-e)}})),name$x="randomInt",dependencies$x=["typed","config","?on"],createRandomInt=factory(name$x,dependencies$x,(e=>{var{typed:t,config:n,on:r}=e,a=createRng(n.randomSeed);return r&&r("config",(function(e,t){e.randomSeed!==t.randomSeed&&(a=createRng(e.randomSeed))})),t(name$x,{"":()=>o(0,1),number:e=>o(0,e),"number, number":(e,t)=>o(e,t),"Array | Matrix":e=>i(e,0,1),"Array | Matrix, number":(e,t)=>i(e,0,t),"Array | Matrix, number, number":(e,t,n)=>i(e,t,n)});function i(e,t,n){var r=randomMatrix(e.valueOf(),(()=>o(t,n)));return isMatrix(e)?e.create(r):r}function o(e,t){return Math.floor(e+a()*(t-e))}})),name$w="stirlingS2",dependencies$w=["typed","addScalar","subtract","multiplyScalar","divideScalar","pow","factorial","combinations","isNegative","isInteger","number","?bignumber","larger"],createStirlingS2=factory(name$w,dependencies$w,(e=>{var{typed:t,addScalar:n,subtract:r,multiplyScalar:a,divideScalar:i,pow:o,factorial:s,combinations:l,isNegative:u,isInteger:c,number:p,bignumber:d,larger:m}=e,f=[],h=[];return t(name$w,{"number | BigNumber, number | BigNumber":function(e,t){if(!c(e)||u(e)||!c(t)||u(t))throw new TypeError("Non-negative integer value expected in function stirlingS2");if(m(t,e))throw new TypeError("k must be less than or equal to n in function stirlingS2");var r=!(isNumber$1(e)&&isNumber$1(t)),i=r?h:f,o=r?d:p,s=p(e),l=p(t);if(i[s]&&i[s].length>l)return i[s][l];for(var y=0;y<=s;++y)if(i[y]||(i[y]=[o(0===y?1:0)]),0!==y)for(var b=i[y],g=i[y-1],v=b.length;v<=y&&v<=l;++v)b[v]=v===y?1:n(a(o(v),g[v]),g[v-1]);return i[s][l]}})})),name$v="bellNumbers",dependencies$v=["typed","addScalar","isNegative","isInteger","stirlingS2"],createBellNumbers=factory(name$v,dependencies$v,(e=>{var{typed:t,addScalar:n,isNegative:r,isInteger:a,stirlingS2:i}=e;return t(name$v,{"number | BigNumber":function(e){if(!a(e)||r(e))throw new TypeError("Non-negative integer value expected in function bellNumbers");for(var t=0,o=0;o<=e;o++)t=n(t,i(e,o));return t}})})),name$u="catalan",dependencies$u=["typed","addScalar","divideScalar","multiplyScalar","combinations","isNegative","isInteger"],createCatalan=factory(name$u,dependencies$u,(e=>{var{typed:t,addScalar:n,divideScalar:r,multiplyScalar:a,combinations:i,isNegative:o,isInteger:s}=e;return t(name$u,{"number | BigNumber":function(e){if(!s(e)||o(e))throw new TypeError("Non-negative integer value expected in function catalan");return r(i(a(e,2),e),n(e,1))}})})),name$t="composition",dependencies$t=["typed","addScalar","combinations","isNegative","isPositive","isInteger","larger"],createComposition=factory(name$t,dependencies$t,(e=>{var{typed:t,addScalar:n,combinations:r,isPositive:a,isNegative:i,isInteger:o,larger:s}=e;return t(name$t,{"number | BigNumber, number | BigNumber":function(e,t){if(!(o(e)&&a(e)&&o(t)&&a(t)))throw new TypeError("Positive integer value expected in function composition");if(s(t,e))throw new TypeError("k must be less than or equal to n in function composition");return r(n(e,-1),n(t,-1))}})})),name$s="leafCount",dependencies$s=["parse","typed"],createLeafCount=factory(name$s,dependencies$s,(e=>{var{parse:t,typed:n}=e;function r(e){var t=0;return e.forEach((e=>{t+=r(e)})),t||1}return n(name$s,{string:function(e){return this(t(e))},Node:function(e){return r(e)}})}));function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _objectSpread(e){for(var t=1;t{var{FunctionNode:t,OperatorNode:n,SymbolNode:r}=e,a=!0,i=!1,o="defaultF",s={add:{trivial:a,total:a,commutative:a,associative:a},unaryPlus:{trivial:a,total:a,commutative:a,associative:a},subtract:{trivial:i,total:a,commutative:i,associative:i},multiply:{trivial:a,total:a,commutative:a,associative:a},divide:{trivial:i,total:a,commutative:i,associative:i},paren:{trivial:a,total:a,commutative:a,associative:i},defaultF:{trivial:i,total:a,commutative:i,associative:i}};function l(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:s,r=o;if("string"==typeof e?r=e:isOperatorNode(e)?r=e.fn.toString():isFunctionNode(e)?r=e.name:isParenthesisNode(e)&&(r="paren"),hasOwnProperty$2(n,r)){var a=n[r];if(hasOwnProperty$2(a,t))return a[t];if(hasOwnProperty$2(s,r))return s[r][t]}if(hasOwnProperty$2(n,o)){var i=n.defaultF;return hasOwnProperty$2(i,t)?i[t]:s.defaultF[t]}if(hasOwnProperty$2(s,r)){var l=s[r];if(hasOwnProperty$2(l,t))return l[t]}return s.defaultF[t]}function u(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s;return l(e,"associative",t)}function c(e,t){var n,r=[];return u(e,t)?(n=e.op,function e(t){for(var a=0;a1&&void 0!==arguments[1]?arguments[1]:s;return l(e,"commutative",t)},isAssociative:u,mergeContext:function(e,t){var n=_objectSpread({},e);for(var r in t)hasOwnProperty$2(e,r)?n[r]=_objectSpread(_objectSpread({},t[r]),e[r]):n[r]=t[r];return n},flatten:function e(t,n){if(!t.args||0===t.args.length)return t;t.args=c(t,n);for(var r=0;r2&&u(t,n)){for(var o=t.args.pop();t.args.length>0;)o=r([t.args.pop(),o]);t.args=o.args}}},unflattenl:function e(t,n){if(t.args&&0!==t.args.length){for(var r=p(t),a=t.args.length,i=0;i2&&u(t,n)){for(var o=t.args.shift();t.args.length>0;)o=r([o,t.args.shift()]);t.args=o.args}}},defaultContext:s,realContext:{divide:{total:i},log:{total:i}},positiveContext:{subtract:{total:i},abs:{trivial:a},log:{total:a}}}})),name$q="simplifyConstant",dependencies$q=["typed","config","mathWithTransform","matrix","?fraction","?bignumber","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","SymbolNode"],createSimplifyConstant=factory(name$q,dependencies$q,(e=>{var{typed:t,config:n,mathWithTransform:r,matrix:a,fraction:i,bignumber:o,AccessorNode:s,ArrayNode:l,ConstantNode:u,FunctionNode:c,IndexNode:p,ObjectNode:d,OperatorNode:m,SymbolNode:f}=e,{isCommutative:h,isAssociative:y,allChildren:b,createMakeNodeFunction:g}=createUtil({FunctionNode:c,OperatorNode:m,SymbolNode:f});function v(e,t){return A(E(e,t))}function T(e){return isFraction(e)?e.valueOf():e instanceof Array?e.map(T):isMatrix(e)?a(T(e.valueOf())):e}function N(e,t,n){try{return r[e].apply(null,t)}catch(a){return t=t.map(T),x(r[e].apply(null,t),n)}}var C=t({Fraction:function(e){var t,n=e.s*e.n;return t=n<0?new m("-","unaryMinus",[new u(-n)]):new u(n),1===e.d?t:new m("/","divide",[t,new u(e.d)])},number:function(e){return e<0?w(new u(-e)):new u(e)},BigNumber:function(e){return e<0?w(new u(-e)):new u(e)},Complex:function(e){throw new Error("Cannot convert Complex number to Node")},string:function(e){return new u(e)},Matrix:function(e){return new l(e.valueOf().map((e=>C(e))))}});function A(e){return isNode(e)?e:C(e)}function S(e,t){if(t&&!1!==t.exactFractions&&isFinite(e)&&i){var n=i(e),r=t&&"number"==typeof t.fractionsLimit?t.fractionsLimit:1/0;if(n.valueOf()===e&&n.nE(e,t)));if(!n.some(isNode))try{return N(e.name,n,t)}catch(e){}if("size"===e.name&&1===n.length&&isArrayNode(n[0])){for(var i=[],o=n[0];isArrayNode(o);)i.push(o.items.length),o=o.items[0];return a(i)}return new c(e.name,n.map(A))}case"OperatorNode":var m,f,T=e.fn.toString(),C=g(e);if(isOperatorNode(e)&&e.isUnary())f=isNode((m=[E(e.args[0],t)])[0])?C(m):N(T,m,t);else if(y(e,t.context))if(m=(m=b(e,t.context)).map((e=>E(e,t))),h(T,t.context)){for(var S=[],w=[],O=0;O1?(f=V(T,S,C,t),w.unshift(f),f=V(T,w,C,t)):f=V(T,m,C,t)}else f=V(T,m,C,t);else f=V(T,m=e.args.map((e=>E(e,t))),C,t);return f;case"ParenthesisNode":return E(e.content,t);case"AccessorNode":return function(e,t,n){if(!isIndexNode(t))return new s(A(e),A(t));if(isArrayNode(e)||isMatrix(e)){for(var r=Array.from(t.dimensions);r.length>0;)if(isConstantNode(r[0])&&"string"!=typeof r[0].value){var i=x(r.shift().value,n);isArrayNode(e)?e=e.items[i-1]:(e=e.valueOf()[i-1])instanceof Array&&(e=a(e))}else{if(!(r.length>1&&isConstantNode(r[1])&&"string"!=typeof r[1].value))break;var o=x(r[1].value,n),c=[],d=isArrayNode(e)?e.items:e.valueOf();for(var m of d)if(isArrayNode(m))c.push(m.items[o-1]);else{if(!isMatrix(e))break;c.push(m[o-1])}if(c.length!==d.length)break;e=isArrayNode(e)?new l(c):a(c),r.splice(1,1)}return r.length===t.dimensions.length?new s(A(e),t):r.length>0?(t=new p(r),new s(A(e),t)):e}if(isObjectNode(e)&&1===t.dimensions.length&&isConstantNode(t.dimensions[0])){var f=t.dimensions[0].value;return f in e.properties?e.properties[f]:new u}return new s(A(e),t)}(E(e.object,t),E(e.index,t),t);case"ArrayNode":var _=e.items.map((e=>E(e,t)));return _.some(isNode)?new l(_.map(A)):a(_);case"IndexNode":return new p(e.dimensions.map((e=>v(e,t))));case"ObjectNode":var $={};for(var D in e.properties)$[D]=v(e.properties[D],t);return new d($);default:throw new Error("Unimplemented node type in simplifyConstant: ".concat(e.type))}}return v})),name$p="simplify",dependencies$p=["config","typed","parse","add","subtract","multiply","divide","pow","isZero","equal","resolve","simplifyCore","?fraction","?bignumber","mathWithTransform","matrix","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","SymbolNode"],createSimplify=factory(name$p,dependencies$p,(e=>{var{config:t,typed:n,parse:r,add:a,subtract:i,multiply:o,divide:s,pow:l,isZero:u,equal:c,resolve:p,simplifyCore:d,fraction:m,bignumber:f,mathWithTransform:h,matrix:y,AccessorNode:b,ArrayNode:g,ConstantNode:v,FunctionNode:T,IndexNode:N,ObjectNode:C,OperatorNode:A,ParenthesisNode:S,SymbolNode:x}=e,w=createSimplifyConstant({typed:n,config:t,mathWithTransform:h,matrix:y,fraction:m,bignumber:f,AccessorNode:b,ArrayNode:g,ConstantNode:v,FunctionNode:T,IndexNode:N,ObjectNode:C,OperatorNode:A,SymbolNode:x}),{hasProperty:V,isCommutative:E,isAssociative:O,mergeContext:_,flatten:$,unflattenr:D,unflattenl:I,createMakeNodeFunction:R,defaultContext:P,realContext:k,positiveContext:M}=createUtil({FunctionNode:T,OperatorNode:A,SymbolNode:x}),F=n("simplify",{string:function(e){return this(r(e),this.rules,createEmptyMap(),{})},"string, Map | Object":function(e,t){return this(r(e),this.rules,t,{})},"string, Map | Object, Object":function(e,t,n){return this(r(e),this.rules,t,n)},"string, Array":function(e,t){return this(r(e),t,createEmptyMap(),{})},"string, Array, Map | Object":function(e,t,n){return this(r(e),t,n,{})},"string, Array, Map | Object, Object":function(e,t,n,a){return this(r(e),t,n,a)},"Node, Map | Object":function(e,t){return this(e,this.rules,t,{})},"Node, Map | Object, Object":function(e,t,n){return this(e,this.rules,t,n)},Node:function(e){return this(e,this.rules,createEmptyMap(),{})},"Node, Array":function(e,t){return this(e,t,createEmptyMap(),{})},"Node, Array, Map | Object":function(e,t,n){return this(e,t,n,{})},"Node, Array, Object, Object":function(e,t,n,r){return this(e,t,createMap$1(n),r)},"Node, Array, Map, Object":function(e,t,n,r){var a=r.consoleDebug;t=function(e,t){for(var n=[],r=0;r ").concat(t[u].r.toString()))),a){var d=i.toString({parenthesis:"all"});d!==l&&(console.log("Applying",c,"produced",d),l=d)}I(i,r.context)}s=i.toString({parenthesis:"all"})}return i}});function B(e){return e.transform((function(e,t,n){return isParenthesisNode(e)?B(e.content):e}))}F.defaultContext=P,F.realContext=k,F.positiveContext=M;var L={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};function j(e,t){var n={};if(e.s){var a=e.s.split("->");if(2!==a.length)throw SyntaxError("Could not parse rule: "+e.s);n.l=a[0],n.r=a[1]}else n.l=e.l,n.r=e.r;for(var i of(n.l=B(r(n.l)),n.r=B(r(n.r)),["imposeContext","repeat","assuming"]))i in e&&(n[i]=e[i]);if(e.evaluate&&(n.evaluate=r(e.evaluate)),O(n.l,t)){var o=R(n.l),s=new x("_p"+U++);n.expanded={},n.expanded.l=o([n.l.clone(),s]),$(n.expanded.l,t),D(n.expanded.l,t),n.expanded.r=o([n.r,s])}return n}F.rules=[d,{l:"log(e)",r:"1"},{s:"n-n1 -> n+-n1",assuming:{subtract:{total:!0}}},{s:"n-n -> 0",assuming:{subtract:{total:!1}}},{s:"-(c*v) -> v * (-c)",assuming:{multiply:{commutative:!0},subtract:{total:!0}}},{s:"-(c*v) -> (-c) * v",assuming:{multiply:{commutative:!1},subtract:{total:!0}}},{s:"-(v*c) -> v * (-c)",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:" v * ( v * n1 + n2)",r:"v^2 * n1 + v * n2"},{s:" v * (v^n4 * n1 + n2) -> v^(1+n4) * n1 + v * n2",assuming:{divide:{total:!0}}},{s:"v^n3 * ( v * n1 + n2) -> v^(n3+1) * n1 + v^n3 * n2",assuming:{divide:{total:!0}}},{s:"v^n3 * (v^n4 * n1 + n2) -> v^(n3+n4) * n1 + v^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}}},w,{s:"n+n -> 2*n",assuming:{add:{total:!0}}},{l:"n+-n",r:"0"},{l:"v*n + v",r:"v*(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*v + v -> (n+1)*v",assuming:{multiply:{commutative:!1}}},{s:"n1*n3 + n2*n3 -> (n1+n2)*n3",assuming:{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*c + c",r:"(n+1)*c"},{s:"c*n + c -> c*(n+1)",assuming:{multiply:{commutative:!1}}},w,{s:"(-n)*n1 -> -(n*n1)",assuming:{subtract:{total:!0}}},{s:"n1*(-n) -> -(n1*n)",assuming:{subtract:{total:!0},multiply:{commutative:!1}}},{s:"c+v -> v+c",assuming:{add:{commutative:!0}},imposeContext:{add:{commutative:!1}}},{s:"v*c -> c*v",assuming:{multiply:{commutative:!0}},imposeContext:{multiply:{commutative:!1}}},{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"}];var U=0;function z(e,t,n){var r=e;if(e)for(var a=0;a=2&&2===e.args.length){for(var i=function(e,t){var n,r,a=[],i=R(e);if(E(e,t))for(var o=0;o1&&(l=i(e.args.slice(0,s))),n=1===(r=e.args.slice(s)).length?r[0]:i(r),a.push(i([l,n]))}return a}(t,n),o=[],s=0;s2)throw Error("Unexpected non-binary associative function: "+e.toString());return[]}for(var u=[],p=0;p2)throw new Error("permuting >2 commutative non-associative rule arguments not yet implemented");var m=W(e.args[0],t.args[1],n);if(0===m.length)return[];var f=W(e.args[1],t.args[0],n);if(0===f.length)return[];u=[m,f]}a=function(e){if(0===e.length)return e;for(var t=e.reduce(q),n=[],r={},a=0;a{var{equal:t,isZero:n,add:r,subtract:a,multiply:i,divide:o,pow:s,AccessorNode:l,ArrayNode:u,ConstantNode:c,FunctionNode:p,IndexNode:d,ObjectNode:m,OperatorNode:f,ParenthesisNode:h,SymbolNode:y}=e,b=new c(0),g=new c(1),{hasProperty:v,isCommutative:T}=createUtil({FunctionNode:p,OperatorNode:f,SymbolNode:y});return function e(h,y){var N=y?y.context:void 0;if(v(h,"trivial",N)){if(isFunctionNode(h)&&1===h.args.length)return e(h.args[0],y);var C=!1,A=0;if(h.forEach((t=>{1==++A&&(C=e(t,y))})),1===A)return C}if(isOperatorNode(h)&&h.isUnary()){var S=e(h.args[0],y);if("-"===h.op){if(isOperatorNode(S)){if(S.isUnary()&&"-"===S.op)return S.args[0];if(S.isBinary()&&"subtract"===S.fn)return new f("-","subtract",[S.args[1],S.args[0]])}return new f(h.op,h.fn,[S])}}else{if(isOperatorNode(h)&&h.isBinary()){var x=e(h.args[0],y),w=e(h.args[1],y);if("+"===h.op){if(isConstantNode(x)){if(n(x.value))return w;if(isConstantNode(w))return new c(r(x.value,w.value))}return isConstantNode(w)&&n(w.value)?x:isOperatorNode(w)&&w.isUnary()&&"-"===w.op?new f("-","subtract",[x,w.args[0]]):new f(h.op,h.fn,w?[x,w]:[x])}if("-"===h.op){if(isConstantNode(x)&&w){if(isConstantNode(w))return new c(a(x.value,w.value));if(n(x.value))return new f("-","unaryMinus",[w])}if("subtract"===h.fn)return isConstantNode(w)&&n(w.value)?x:isOperatorNode(w)&&w.isUnary()&&"-"===w.op?e(new f("+","add",[x,w.args[0]]),y):new f(h.op,h.fn,[x,w])}else{if("*"===h.op){if(isConstantNode(x)){if(n(x.value))return b;if(t(x.value,1))return w;if(isConstantNode(w))return new c(i(x.value,w.value))}if(isConstantNode(w)){if(n(w.value))return b;if(t(w.value,1))return x;if(isOperatorNode(x)&&x.isBinary()&&x.op===h.op&&T(h,N)){var V=x.args[0];if(isConstantNode(V)){var E=new c(i(V.value,w.value));return new f(h.op,h.fn,[E,x.args[1]],h.implicit)}}return T(h,N)?new f(h.op,h.fn,[w,x],h.implicit):new f(h.op,h.fn,[x,w],h.implicit)}return new f(h.op,h.fn,[x,w],h.implicit)}if("/"===h.op){if(isConstantNode(x)){if(n(x.value))return b;if(isConstantNode(w)&&(t(w.value,1)||t(w.value,2)||t(w.value,4)))return new c(o(x.value,w.value))}return new f(h.op,h.fn,[x,w])}if("^"===h.op&&isConstantNode(w)){if(n(w.value))return g;if(t(w.value,1))return x;if(isConstantNode(x))return new c(s(x.value,w.value));if(isOperatorNode(x)&&x.isBinary()&&"^"===x.op){var O=x.args[1];if(isConstantNode(O))return new f(h.op,h.fn,[x.args[0],new c(i(O.value,w.value))])}}}return new f(h.op,h.fn,[x,w])}if(isFunctionNode(h))return new p(e(h.fn),h.args.map((t=>e(t,y))));if(isArrayNode(h))return new u(h.items.map((t=>e(t,y))));if(isAccessorNode(h))return new l(e(h.object,y),e(h.index,y));if(isIndexNode(h))return new d(h.dimensions.map((t=>e(t,y))));if(isObjectNode(h)){var _={};for(var $ in h.properties)_[$]=e(h.properties[$],y);return new m(_)}}return h}})),name$n="resolve",dependencies$n=["parse","ConstantNode","FunctionNode","OperatorNode","ParenthesisNode"],createResolve=factory(name$n,dependencies$n,(e=>{var{parse:t,ConstantNode:n,FunctionNode:r,OperatorNode:a,ParenthesisNode:i}=e;return function e(o,s){var l=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Set;if(!s)return o;if(isMap$1(s)||(s=createMap$1(s)),isSymbolNode(o)){if(l.has(o.name)){var u=Array.from(l).join(", ");throw new ReferenceError("recursive loop of variable definitions among {".concat(u,"}"))}var c=s.get(o.name);if(isNode(c)){var p=new Set(l);return p.add(o.name),e(c,s,p)}return"number"==typeof c?t(String(c)):void 0!==c?new n(c):o}if(isOperatorNode(o)){var d=o.args.map((function(t){return e(t,s,l)}));return new a(o.op,o.fn,d,o.implicit)}if(isParenthesisNode(o))return new i(e(o.content,s,l));if(isFunctionNode(o)){var m=o.args.map((function(t){return e(t,s,l)}));return new r(o.name,m)}return o.map((t=>e(t,s,l)))}})),name$m="symbolicEqual",dependencies$m=["parse","simplify","typed","OperatorNode"],createSymbolicEqual=factory(name$m,dependencies$m,(e=>{var{parse:t,simplify:n,typed:r,OperatorNode:a}=e;return r(name$m,{"string, string":function(e,n){return this(t(e),t(n),{})},"string, string, Object":function(e,n,r){return this(t(e),t(n),r)},"Node, string":function(e,n){return this(e,t(n),{})},"Node, string, Object":function(e,n,r){return this(e,t(n),r)},"string, Node":function(e,n){return this(t(e),n,{})},"string, Node, Object":function(e,n,r){return this(t(e),n,r)},"Node, Node":function(e,t){return this(e,t,{})},"Node, Node, Object":function(e,t,r){var i=new a("-","subtract",[e,t]),o=n(i,{},r);return isConstantNode(o)&&!o.value}})})),name$l="derivative",dependencies$l=["typed","config","parse","simplify","equal","isZero","numeric","ConstantNode","FunctionNode","OperatorNode","ParenthesisNode","SymbolNode"],createDerivative=factory(name$l,dependencies$l,(e=>{var{typed:t,config:n,parse:r,simplify:a,equal:i,isZero:o,numeric:s,ConstantNode:l,FunctionNode:u,OperatorNode:c,ParenthesisNode:p,SymbolNode:d}=e,m=t("derivative",{"Node, SymbolNode, Object":function(e,t,n){var r={};h(r,e,t.name);var i=y(e,r);return n.simplify?a(i):i},"Node, SymbolNode":function(e,t){return this(e,t,{simplify:!0})},"string, SymbolNode":function(e,t){return this(r(e),t)},"string, SymbolNode, Object":function(e,t,n){return this(r(e),t,n)},"string, string":function(e,t){return this(r(e),r(t))},"string, string, Object":function(e,t,n){return this(r(e),r(t),n)},"Node, string":function(e,t){return this(e,r(t))},"Node, string, Object":function(e,t,n){return this(e,r(t),n)}});m._simplify=!0,m.toTex=function(e){return f.apply(null,e.args)};var f=t("_derivTex",{"Node, SymbolNode":function(e,t){return isConstantNode(e)&&"string"===typeOf$1(e.value)?f(r(e.value).toString(),t.toString(),1):f(e.toTex(),t.toString(),1)},"Node, ConstantNode":function(e,t){if("string"===typeOf$1(t.value))return f(e,r(t.value));throw new Error("The second parameter to 'derivative' is a non-string constant")},"Node, SymbolNode, ConstantNode":function(e,t,n){return f(e.toString(),t.name,n.value)},"string, string, number":function(e,t,n){return(1===n?"{d\\over d"+t+"}":"{d^{"+n+"}\\over d"+t+"^{"+n+"}}")+"\\left[".concat(e,"\\right]")}}),h=t("constTag",{"Object, ConstantNode, string":function(e,t){return e[t]=!0,!0},"Object, SymbolNode, string":function(e,t,n){return t.name!==n&&(e[t]=!0,!0)},"Object, ParenthesisNode, string":function(e,t,n){return h(e,t.content,n)},"Object, FunctionAssignmentNode, string":function(e,t,n){return-1===t.params.indexOf(n)?(e[t]=!0,!0):h(e,t.expr,n)},"Object, FunctionNode | OperatorNode, string":function(e,t,n){if(t.args.length>0){for(var r=h(e,t.args[0],n),a=1;a0){var r=e.args.filter((function(e){return void 0===t[e]})),a=1===r.length?r[0]:new c("*","multiply",r),s=n.concat(y(a,t));return new c("*","multiply",s)}return new c("+","add",e.args.map((function(n){return new c("*","multiply",e.args.map((function(e){return e===n?y(e,t):e.clone()})))})))}if("/"===e.op&&e.isBinary()){var l=e.args[0],p=e.args[1];return void 0!==t[p]?new c("/","divide",[y(l,t),p]):void 0!==t[l]?new c("*","multiply",[new c("-","unaryMinus",[l]),new c("/","divide",[y(p,t),new c("^","pow",[p.clone(),b(2)])])]):new c("/","divide",[new c("-","subtract",[new c("*","multiply",[y(l,t),p.clone()]),new c("*","multiply",[l.clone(),y(p,t)])]),new c("^","pow",[p.clone(),b(2)])])}if("^"===e.op&&e.isBinary()){var d=e.args[0],m=e.args[1];if(void 0!==t[d])return isConstantNode(d)&&(o(d.value)||i(d.value,1))?b(0):new c("*","multiply",[e,new c("*","multiply",[new u("log",[d.clone()]),y(m.clone(),t)])]);if(void 0!==t[m]){if(isConstantNode(m)){if(o(m.value))return b(0);if(i(m.value,1))return y(d,t)}var f=new c("^","pow",[d.clone(),new c("-","subtract",[m,b(1)])]);return new c("*","multiply",[m.clone(),new c("*","multiply",[y(d,t),f])])}return new c("*","multiply",[new c("^","pow",[d.clone(),m.clone()]),new c("+","add",[new c("*","multiply",[y(d,t),new c("/","divide",[m.clone(),d.clone()])]),new c("*","multiply",[y(m,t),new u("log",[d.clone()])])])])}throw new Error('Operator "'+e.op+'" is not supported by derivative, or a wrong number of arguments is passed')}});function b(e,t){return new l(s(e,t||n.number))}return m})),name$k="rationalize",dependencies$k=["config","typed","equal","isZero","add","subtract","multiply","divide","pow","parse","simplifyCore","simplify","?bignumber","?fraction","mathWithTransform","matrix","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","SymbolNode","ParenthesisNode"],createRationalize=factory(name$k,dependencies$k,(e=>{var{config:t,typed:n,equal:r,isZero:a,add:i,subtract:o,multiply:s,divide:l,pow:u,parse:c,simplifyCore:p,simplify:d,fraction:m,bignumber:f,mathWithTransform:h,matrix:y,AccessorNode:b,ArrayNode:g,ConstantNode:v,FunctionNode:T,IndexNode:N,ObjectNode:C,OperatorNode:A,SymbolNode:S,ParenthesisNode:x}=e,w=createSimplifyConstant({typed:n,config:t,mathWithTransform:h,matrix:y,fraction:m,bignumber:f,AccessorNode:b,ArrayNode:g,ConstantNode:v,FunctionNode:T,IndexNode:N,ObjectNode:C,OperatorNode:A,SymbolNode:S});return n(name$k,{string:function(e){return this(c(e),{},!1)},"string, boolean":function(e,t){return this(c(e),{},t)},"string, Object":function(e,t){return this(c(e),t,!1)},"string, Object, boolean":function(e,t,n){return this(c(e),t,n)},Node:function(e){return this(e,{},!1)},"Node, boolean":function(e,t){return this(e,{},t)},"Node, Object":function(e,t){return this(e,t,!1)},"Node, Object, boolean":function(e,t,n){var r=function(){var e=[p,{l:"n+n",r:"2*n"},{l:"n+-n",r:"0"},w,{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"}],t=[{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)"}],n=[{l:"(n1/(n2/n3))",r:"((n1*n3)/n2)"},{l:"(n1/n2/n3)",r:"(n1/(n2*n3))"}],r={};return r.firstRules=e.concat(t,n),r.distrDivRules=[{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)"}],r.sucDivRules=n,r.firstRulesAgain=e.concat(t),r.finalRules=[p,{l:"n*-n",r:"-n^2"},{l:"n*n",r:"n^2"},w,{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))"}],r}(),a=function(e,t,n,r){var a=[],i=d(e,r,t,{exactFractions:!1}),o="+-*"+((n=!!n)?"/":"");!function e(t){var n=t.type;if("FunctionNode"===n)throw new Error("There is an unsolved function call");if("OperatorNode"===n)if("^"===t.op){if("ConstantNode"!==t.args[1].type||!isInteger$1(parseFloat(t.args[1].value)))throw new Error("There is a non-integer exponent");e(t.args[0])}else{if(-1===o.indexOf(t.op))throw new Error("Operator "+t.op+" invalid in polynomial expression");for(var r=0;r=1){var l,u;e=V(e);var c,m=!0,f=!1;for(e=d(e,r.firstRules,{},o);u=m?r.distrDivRules:r.sucDivRules,m=!m,(c=(e=d(e,u,{},s)).toString())!==l;)f=!0,l=c;f&&(e=d(e,r.firstRulesAgain,{},o)),e=d(e,r.finalRules,{},o)}var h=[],y={};return"OperatorNode"===e.type&&e.isBinary()&&"/"===e.op?(1===i&&(e.args[0]=E(e.args[0],h),e.args[1]=E(e.args[1])),n&&(y.numerator=e.args[0],y.denominator=e.args[1])):(1===i&&(e=E(e,h)),n&&(y.numerator=e,y.denominator=null)),n?(y.coefficients=h,y.variables=a.variables,y.expression=e,y):e}});function V(e,t,n){var r=e.type,a=arguments.length>1;if("OperatorNode"===r&&e.isBinary()){var i,o=!1;if("^"===e.op&&("ParenthesisNode"!==e.args[0].type&&"OperatorNode"!==e.args[0].type||"ConstantNode"!==e.args[1].type||(o=(i=parseFloat(e.args[1].value))>=2&&isInteger$1(i))),o){if(i>2){var s=e.args[0],l=new A("^","pow",[e.args[0].cloneDeep(),new v(i-1)]);e=new A("*","multiply",[s,l])}else e=new A("*","multiply",[e.args[0],e.args[0].cloneDeep()]);a&&("content"===n?t.content=e:t.args[n]=e)}}if("ParenthesisNode"===r)V(e.content,e,"content");else if("ConstantNode"!==r&&"SymbolNode"!==r)for(var u=0;un&&(t[u]=0),t[u]+=o.cte*("+"===o.oper?1:-1),void(n=Math.max(u,n))}o.cte=u,""===o.fire&&(t[0]+=o.cte*("+"===o.oper?1:-1))}}(e,null,{cte:1,oper:"+",fire:""});for(var a,i=!0,o=n=t.length-1;o>=0;o--)if(0!==t[o]){var s=new v(i?t[o]:Math.abs(t[o])),l=t[o]<0?"-":"+";if(o>0){var u=new S(r);if(o>1){var c=new v(o);u=new A("^","pow",[u,c])}s=-1===t[o]&&i?new A("-","unaryMinus",[u]):1===Math.abs(t[o])?u:new A("*","multiply",[s,u])}a=i?s:"+"===l?new A("+","add",[a,s]):new A("-","subtract",[a,s]),i=!1}return i?new v(0):a}})),name$j="reviver",dependencies$j=["classes"],createReviver=factory(name$j,dependencies$j,(e=>{var{classes:t}=e;return function(e,n){var r=t[n&&n.mathjs];return r&&"function"==typeof r.fromJSON?r.fromJSON(n):n}})),name$i="replacer",dependencies$i=[],createReplacer=factory(name$i,dependencies$i,(()=>function(e,t){return"number"!=typeof t||isFinite(t)&&!isNaN(t)?t:{mathjs:"number",value:String(t)}})),version$2="10.6.4",createTrue=factory("true",[],(()=>!0)),createFalse=factory("false",[],(()=>!1)),createNull=factory("null",[],(()=>null)),createInfinity=recreateFactory("Infinity",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(1/0):1/0})),createNaN=recreateFactory("NaN",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(NaN):NaN})),createPi=recreateFactory("pi",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?createBigNumberPi(n):pi$1})),createTau=recreateFactory("tau",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?createBigNumberTau(n):tau$1})),createE=recreateFactory("e",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?createBigNumberE(n):e$1})),createPhi=recreateFactory("phi",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?createBigNumberPhi(n):phi$1})),createLN2=recreateFactory("LN2",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(2).ln():Math.LN2})),createLN10=recreateFactory("LN10",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(10).ln():Math.LN10})),createLOG2E=recreateFactory("LOG2E",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(1).div(new n(2).ln()):Math.LOG2E})),createLOG10E=recreateFactory("LOG10E",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(1).div(new n(10).ln()):Math.LOG10E})),createSQRT1_2=recreateFactory("SQRT1_2",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n("0.5").sqrt():Math.SQRT1_2})),createSQRT2=recreateFactory("SQRT2",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(2).sqrt():Math.SQRT2})),createI=recreateFactory("i",["Complex"],(e=>{var{Complex:t}=e;return t.I})),createUppercasePi=factory("PI",["pi"],(e=>{var{pi:t}=e;return t})),createUppercaseE=factory("E",["e"],(e=>{var{e:t}=e;return t})),createVersion=factory("version",[],(()=>version$2));function recreateFactory(e,t,n){return factory(e,t,n,{recreateOnConfigChange:!0})}var createSpeedOfLight=unitFactory("speedOfLight","299792458","m s^-1"),createGravitationConstant=unitFactory("gravitationConstant","6.67430e-11","m^3 kg^-1 s^-2"),createPlanckConstant=unitFactory("planckConstant","6.62607015e-34","J s"),createReducedPlanckConstant=unitFactory("reducedPlanckConstant","1.0545718176461565e-34","J s"),createMagneticConstant=unitFactory("magneticConstant","1.25663706212e-6","N A^-2"),createElectricConstant=unitFactory("electricConstant","8.8541878128e-12","F m^-1"),createVacuumImpedance=unitFactory("vacuumImpedance","376.730313667","ohm"),createCoulomb=unitFactory("coulomb","8.987551792261171e9","N m^2 C^-2"),createElementaryCharge=unitFactory("elementaryCharge","1.602176634e-19","C"),createBohrMagneton=unitFactory("bohrMagneton","9.2740100783e-24","J T^-1"),createConductanceQuantum=unitFactory("conductanceQuantum","7.748091729863649e-5","S"),createInverseConductanceQuantum=unitFactory("inverseConductanceQuantum","12906.403729652257","ohm"),createMagneticFluxQuantum=unitFactory("magneticFluxQuantum","2.0678338484619295e-15","Wb"),createNuclearMagneton=unitFactory("nuclearMagneton","5.0507837461e-27","J T^-1"),createKlitzing=unitFactory("klitzing","25812.807459304513","ohm"),createBohrRadius=unitFactory("bohrRadius","5.29177210903e-11","m"),createClassicalElectronRadius=unitFactory("classicalElectronRadius","2.8179403262e-15","m"),createElectronMass=unitFactory("electronMass","9.1093837015e-31","kg"),createFermiCoupling=unitFactory("fermiCoupling","1.1663787e-5","GeV^-2"),createFineStructure=numberFactory("fineStructure",.0072973525693),createHartreeEnergy=unitFactory("hartreeEnergy","4.3597447222071e-18","J"),createProtonMass=unitFactory("protonMass","1.67262192369e-27","kg"),createDeuteronMass=unitFactory("deuteronMass","3.3435830926e-27","kg"),createNeutronMass=unitFactory("neutronMass","1.6749271613e-27","kg"),createQuantumOfCirculation=unitFactory("quantumOfCirculation","3.6369475516e-4","m^2 s^-1"),createRydberg=unitFactory("rydberg","10973731.568160","m^-1"),createThomsonCrossSection=unitFactory("thomsonCrossSection","6.6524587321e-29","m^2"),createWeakMixingAngle=numberFactory("weakMixingAngle",.2229),createEfimovFactor=numberFactory("efimovFactor",22.7),createAtomicMass=unitFactory("atomicMass","1.66053906660e-27","kg"),createAvogadro=unitFactory("avogadro","6.02214076e23","mol^-1"),createBoltzmann=unitFactory("boltzmann","1.380649e-23","J K^-1"),createFaraday=unitFactory("faraday","96485.33212331001","C mol^-1"),createFirstRadiation=unitFactory("firstRadiation","3.7417718521927573e-16","W m^2"),createLoschmidt=unitFactory("loschmidt","2.686780111798444e25","m^-3"),createGasConstant=unitFactory("gasConstant","8.31446261815324","J K^-1 mol^-1"),createMolarPlanckConstant=unitFactory("molarPlanckConstant","3.990312712893431e-10","J s mol^-1"),createMolarVolume=unitFactory("molarVolume","0.022413969545014137","m^3 mol^-1"),createSackurTetrode=numberFactory("sackurTetrode",-1.16487052358),createSecondRadiation=unitFactory("secondRadiation","0.014387768775039337","m K"),createStefanBoltzmann=unitFactory("stefanBoltzmann","5.67037441918443e-8","W m^-2 K^-4"),createWienDisplacement=unitFactory("wienDisplacement","2.897771955e-3","m K"),createMolarMass=unitFactory("molarMass","0.99999999965e-3","kg mol^-1"),createMolarMassC12=unitFactory("molarMassC12","11.9999999958e-3","kg mol^-1"),createGravity=unitFactory("gravity","9.80665","m s^-2"),createPlanckLength=unitFactory("planckLength","1.616255e-35","m"),createPlanckMass=unitFactory("planckMass","2.176435e-8","kg"),createPlanckTime=unitFactory("planckTime","5.391245e-44","s"),createPlanckCharge=unitFactory("planckCharge","1.87554603778e-18","C"),createPlanckTemperature=unitFactory("planckTemperature","1.416785e+32","K");function unitFactory(e,t,n){return factory(e,["config","Unit","BigNumber"],(e=>{var{config:r,Unit:a,BigNumber:i}=e,o=new a("BigNumber"===r.number?new i(t):parseFloat(t),n);return o.fixPrefix=!0,o}))}function numberFactory(e,t){return factory(e,["config","BigNumber"],(e=>{var{config:n,BigNumber:r}=e;return"BigNumber"===n.number?new r(t):t}))}var name$h="apply",dependencies$h=["typed","isInteger"],createApplyTransform=factory(name$h,dependencies$h,(e=>{var{typed:t,isInteger:n}=e,r=createApply({typed:t,isInteger:n});return t("apply",{"...any":function(e){var t=e[1];isNumber$1(t)?e[1]=t-1:isBigNumber(t)&&(e[1]=t.minus(1));try{return r.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$g="column",dependencies$g=["typed","Index","matrix","range"],createColumnTransform=factory(name$g,dependencies$g,(e=>{var{typed:t,Index:n,matrix:r,range:a}=e,i=createColumn({typed:t,Index:n,matrix:r,range:a});return t("column",{"...any":function(e){var t=e.length-1,n=e[t];isNumber$1(n)&&(e[t]=n-1);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0});function compileInlineExpression(e,t,n){var r=e.filter((function(e){return isSymbolNode(e)&&!(e.name in t)&&!n.has(e.name)}))[0];if(!r)throw new Error('No undefined variable found in inline expression "'+e+'"');var a=r.name,i=createSubScope(n),o=e.compile();return function(e){return i.set(a,e),o.evaluate(i)}}var name$f="filter",dependencies$f=["typed"],createFilterTransform=factory(name$f,dependencies$f,(e=>{var{typed:t}=e;function n(e,t,n){var a,i;return e[0]&&(a=e[0].compile().evaluate(n)),e[1]&&(i=isSymbolNode(e[1])||isFunctionAssignmentNode(e[1])?e[1].compile().evaluate(n):compileInlineExpression(e[1],t,n)),r(a,i)}n.rawArgs=!0;var r=t("filter",{"Array, function":_filter,"Matrix, function":function(e,t){return e.create(_filter(e.toArray(),t))},"Array, RegExp":filterRegExp,"Matrix, RegExp":function(e,t){return e.create(filterRegExp(e.toArray(),t))}});return n}),{isTransformFunction:!0});function _filter(e,t){var n=maxArgumentCount(t);return filter$2(e,(function(e,r,a){return 1===n?t(e):2===n?t(e,[r+1]):t(e,[r+1],a)}))}var name$e="forEach",dependencies$e=["typed"],createForEachTransform=factory(name$e,dependencies$e,(e=>{var{typed:t}=e;function n(e,t,n){var a,i;return e[0]&&(a=e[0].compile().evaluate(n)),e[1]&&(i=isSymbolNode(e[1])||isFunctionAssignmentNode(e[1])?e[1].compile().evaluate(n):compileInlineExpression(e[1],t,n)),r(a,i)}n.rawArgs=!0;var r=t("forEach",{"Array | Matrix, function":function(e,t){var n=maxArgumentCount(t);!function r(a,i){Array.isArray(a)?forEach$1(a,(function(e,t){r(e,i.concat(t+1))})):1===n?t(a):2===n?t(a,i):t(a,i,e)}(e.valueOf(),[])}});return n}),{isTransformFunction:!0}),name$d="index",dependencies$d=["Index"],createIndexTransform=factory(name$d,dependencies$d,(e=>{var{Index:t}=e;return function(){for(var e=[],n=0,r=arguments.length;n0?0:2;else if(a&&!0===a.isSet)a=a.map((function(e){return e-1}));else if(isArray$1(a)||isMatrix(a))a=a.map((function(e){return e-1}));else if(isNumber$1(a))a--;else if(isBigNumber(a))a=a.toNumber()-1;else if("string"!=typeof a)throw new TypeError("Dimension must be an Array, Matrix, number, string, or Range");e[n]=a}var i=new t;return t.apply(i,e),i}}),{isTransformFunction:!0}),name$c="map",dependencies$c=["typed"],createMapTransform=factory(name$c,dependencies$c,(e=>{var{typed:t}=e;function n(e,t,n){var a,i;return e[0]&&(a=e[0].compile().evaluate(n)),e[1]&&(i=isSymbolNode(e[1])||isFunctionAssignmentNode(e[1])?e[1].compile().evaluate(n):compileInlineExpression(e[1],t,n)),r(a,i)}n.rawArgs=!0;var r=t("map",{"Array, function":function(e,t){return _map(e,t,e)},"Matrix, function":function(e,t){return e.create(_map(e.valueOf(),t,e))}});return n}),{isTransformFunction:!0});function _map(e,t,n){var r=maxArgumentCount(t);return function e(a,i){return Array.isArray(a)?map$2(a,(function(t,n){return e(t,i.concat(n+1))})):1===r?t(a):2===r?t(a,i):t(a,i,n)}(e,[])}function lastDimToZeroBase(e){if(2===e.length&&isCollection(e[0])){var t=(e=e.slice())[1];isNumber$1(t)?e[1]=t-1:isBigNumber(t)&&(e[1]=t.minus(1))}return e}var name$b="max",dependencies$b=["typed","config","numeric","larger"],createMaxTransform=factory(name$b,dependencies$b,(e=>{var{typed:t,config:n,numeric:r,larger:a}=e,i=createMax({typed:t,config:n,numeric:r,larger:a});return t("max",{"...any":function(e){e=lastDimToZeroBase(e);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$a="mean",dependencies$a=["typed","add","divide"],createMeanTransform=factory(name$a,dependencies$a,(e=>{var{typed:t,add:n,divide:r}=e,a=createMean({typed:t,add:n,divide:r});return t("mean",{"...any":function(e){e=lastDimToZeroBase(e);try{return a.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$9="min",dependencies$9=["typed","config","numeric","smaller"],createMinTransform=factory(name$9,dependencies$9,(e=>{var{typed:t,config:n,numeric:r,smaller:a}=e,i=createMin({typed:t,config:n,numeric:r,smaller:a});return t("min",{"...any":function(e){e=lastDimToZeroBase(e);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$8="range",dependencies$8=["typed","config","?matrix","?bignumber","smaller","smallerEq","larger","largerEq"],createRangeTransform=factory(name$8,dependencies$8,(e=>{var{typed:t,config:n,matrix:r,bignumber:a,smaller:i,smallerEq:o,larger:s,largerEq:l}=e,u=createRange({typed:t,config:n,matrix:r,bignumber:a,smaller:i,smallerEq:o,larger:s,largerEq:l});return t("range",{"...any":function(e){return"boolean"!=typeof e[e.length-1]&&e.push(!0),u.apply(null,e)}})}),{isTransformFunction:!0}),name$7="row",dependencies$7=["typed","Index","matrix","range"],createRowTransform=factory(name$7,dependencies$7,(e=>{var{typed:t,Index:n,matrix:r,range:a}=e,i=createRow({typed:t,Index:n,matrix:r,range:a});return t("row",{"...any":function(e){var t=e.length-1,n=e[t];isNumber$1(n)&&(e[t]=n-1);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$6="subset",dependencies$6=["typed","matrix"],createSubsetTransform=factory(name$6,dependencies$6,(e=>{var{typed:t,matrix:n}=e,r=createSubset({typed:t,matrix:n});return t("subset",{"...any":function(e){try{return r.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$5="concat",dependencies$5=["typed","matrix","isInteger"],createConcatTransform=factory(name$5,dependencies$5,(e=>{var{typed:t,matrix:n,isInteger:r}=e,a=createConcat({typed:t,matrix:n,isInteger:r});return t("concat",{"...any":function(e){var t=e.length-1,n=e[t];isNumber$1(n)?e[t]=n-1:isBigNumber(n)&&(e[t]=n.minus(1));try{return a.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$4="diff",dependencies$4=["typed","matrix","subtract","number","bignumber"],createDiffTransform=factory(name$4,dependencies$4,(e=>{var{typed:t,matrix:n,subtract:r,number:a,bignumber:i}=e,o=createDiff({typed:t,matrix:n,subtract:r,number:a,bignumber:i});return t(name$4,{"...any":function(e){e=lastDimToZeroBase(e);try{return o.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$3="std",dependencies$3=["typed","sqrt","variance"],createStdTransform=factory(name$3,dependencies$3,(e=>{var{typed:t,sqrt:n,variance:r}=e,a=createStd({typed:t,sqrt:n,variance:r});return t("std",{"...any":function(e){e=lastDimToZeroBase(e);try{return a.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$2="sum",dependencies$2=["typed","config","add","numeric"],createSumTransform=factory(name$2,dependencies$2,(e=>{var{typed:t,config:n,add:r,numeric:a}=e,i=createSum({typed:t,config:n,add:r,numeric:a});return t(name$2,{"...any":function(e){e=lastDimToZeroBase(e);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$1="cumsum",dependencies$1=["typed","add","unaryPlus"],createCumSumTransform=factory(name$1,dependencies$1,(e=>{var{typed:t,add:n,unaryPlus:r}=e,a=createCumSum({typed:t,add:n,unaryPlus:r});return t(name$1,{"...any":function(e){if(2===e.length&&isCollection(e[0])){var t=e[1];isNumber$1(t)?e[1]=t-1:isBigNumber(t)&&(e[1]=t.minus(1))}try{return a.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name="variance",dependencies=["typed","add","subtract","multiply","divide","apply","isNaN"],createVarianceTransform=factory(name,dependencies,(e=>{var{typed:t,add:n,subtract:r,multiply:a,divide:i,apply:o,isNaN:s}=e,l=createVariance({typed:t,add:n,subtract:r,multiply:a,divide:i,apply:o,isNaN:s});return t(name,{"...any":function(e){e=lastDimToZeroBase(e);try{return l.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),allFactories=Object.freeze({__proto__:null,createTyped:createTyped,createResultSet:createResultSet,createBigNumberClass:createBigNumberClass,createComplexClass:createComplexClass,createFractionClass:createFractionClass,createRangeClass:createRangeClass,createMatrixClass:createMatrixClass,createDenseMatrixClass:createDenseMatrixClass,createClone:createClone,createIsInteger:createIsInteger,createIsNegative:createIsNegative,createIsNumeric:createIsNumeric,createHasNumericValue:createHasNumericValue,createIsPositive:createIsPositive,createIsZero:createIsZero,createIsNaN:createIsNaN,createTypeOf:createTypeOf,createEqualScalar:createEqualScalar,createSparseMatrixClass:createSparseMatrixClass,createNumber:createNumber,createString:createString,createBoolean:createBoolean,createBignumber:createBignumber,createComplex:createComplex,createFraction:createFraction,createMatrix:createMatrix,createMatrixFromFunction:createMatrixFromFunction,createMatrixFromRows:createMatrixFromRows,createMatrixFromColumns:createMatrixFromColumns,createSplitUnit:createSplitUnit,createUnaryMinus:createUnaryMinus,createUnaryPlus:createUnaryPlus,createAbs:createAbs,createApply:createApply,createAddScalar:createAddScalar,createCbrt:createCbrt,createCeil:createCeil,createCube:createCube,createExp:createExp,createExpm1:createExpm1,createFix:createFix,createFloor:createFloor,createGcd:createGcd,createLcm:createLcm,createLog10:createLog10,createLog2:createLog2,createMod:createMod,createMultiplyScalar:createMultiplyScalar,createMultiply:createMultiply,createNthRoot:createNthRoot,createSign:createSign,createSqrt:createSqrt,createSquare:createSquare,createSubtract:createSubtract,createXgcd:createXgcd,createInvmod:createInvmod,createDotMultiply:createDotMultiply,createBitAnd:createBitAnd,createBitNot:createBitNot,createBitOr:createBitOr,createBitXor:createBitXor,createArg:createArg,createConj:createConj,createIm:createIm,createRe:createRe,createNot:createNot,createOr:createOr,createXor:createXor,createConcat:createConcat,createColumn:createColumn,createCount:createCount,createCross:createCross,createDiag:createDiag,createFilter:createFilter,createFlatten:createFlatten,createForEach:createForEach,createGetMatrixDataType:createGetMatrixDataType,createIdentity:createIdentity,createKron:createKron,createMap:createMap,createDiff:createDiff,createOnes:createOnes,createRange:createRange,createReshape:createReshape,createResize:createResize,createRotate:createRotate,createRotationMatrix:createRotationMatrix,createRow:createRow,createSize:createSize,createSqueeze:createSqueeze,createSubset:createSubset,createTranspose:createTranspose,createCtranspose:createCtranspose,createZeros:createZeros,createFft:createFft,createIfft:createIfft,createErf:createErf,createMode:createMode,createProd:createProd,createFormat:createFormat,createBin:createBin,createOct:createOct,createHex:createHex,createPrint:createPrint,createTo:createTo,createIsPrime:createIsPrime,createNumeric:createNumeric,createDivideScalar:createDivideScalar,createPow:createPow,createRound:createRound,createLog:createLog,createLog1p:createLog1p,createNthRoots:createNthRoots,createDotPow:createDotPow,createDotDivide:createDotDivide,createLsolve:createLsolve,createUsolve:createUsolve,createLsolveAll:createLsolveAll,createUsolveAll:createUsolveAll,createLeftShift:createLeftShift,createRightArithShift:createRightArithShift,createRightLogShift:createRightLogShift,createAnd:createAnd,createCompare:createCompare,createCompareNatural:createCompareNatural,createCompareText:createCompareText,createEqual:createEqual,createEqualText:createEqualText,createSmaller:createSmaller,createSmallerEq:createSmallerEq,createLarger:createLarger,createLargerEq:createLargerEq,createDeepEqual:createDeepEqual,createUnequal:createUnequal,createPartitionSelect:createPartitionSelect,createSort:createSort,createMax:createMax,createMin:createMin,createImmutableDenseMatrixClass:createImmutableDenseMatrixClass,createIndexClass:createIndexClass,createFibonacciHeapClass:createFibonacciHeapClass,createSpaClass:createSpaClass,createUnitClass:createUnitClass,createUnitFunction:createUnitFunction,createSparse:createSparse,createCreateUnit:createCreateUnit,createAcos:createAcos,createAcosh:createAcosh,createAcot:createAcot,createAcoth:createAcoth,createAcsc:createAcsc,createAcsch:createAcsch,createAsec:createAsec,createAsech:createAsech,createAsin:createAsin,createAsinh:createAsinh,createAtan:createAtan,createAtan2:createAtan2,createAtanh:createAtanh,createCos:createCos,createCosh:createCosh,createCot:createCot,createCoth:createCoth,createCsc:createCsc,createCsch:createCsch,createSec:createSec,createSech:createSech,createSin:createSin,createSinh:createSinh,createTan:createTan,createTanh:createTanh,createSetCartesian:createSetCartesian,createSetDifference:createSetDifference,createSetDistinct:createSetDistinct,createSetIntersect:createSetIntersect,createSetIsSubset:createSetIsSubset,createSetMultiplicity:createSetMultiplicity,createSetPowerset:createSetPowerset,createSetSize:createSetSize,createSetSymDifference:createSetSymDifference,createSetUnion:createSetUnion,createAdd:createAdd,createHypot:createHypot,createNorm:createNorm,createDot:createDot,createTrace:createTrace,createIndex:createIndex,createNode:createNode,createAccessorNode:createAccessorNode,createArrayNode:createArrayNode,createAssignmentNode:createAssignmentNode,createBlockNode:createBlockNode,createConditionalNode:createConditionalNode,createConstantNode:createConstantNode,createFunctionAssignmentNode:createFunctionAssignmentNode,createIndexNode:createIndexNode,createObjectNode:createObjectNode,createOperatorNode:createOperatorNode,createParenthesisNode:createParenthesisNode,createRangeNode:createRangeNode,createRelationalNode:createRelationalNode,createSymbolNode:createSymbolNode,createFunctionNode:createFunctionNode,createParse:createParse,createCompile:createCompile,createEvaluate:createEvaluate,createParserClass:createParserClass,createParser:createParser,createLup:createLup,createQr:createQr,createSlu:createSlu,createLusolve:createLusolve,createHelpClass:createHelpClass,createChainClass:createChainClass,createHelp:createHelp,createChain:createChain,createDet:createDet,createInv:createInv,createPinv:createPinv,createEigs:createEigs,createExpm:createExpm,createSqrtm:createSqrtm,createDivide:createDivide,createDistance:createDistance,createIntersect:createIntersect,createSum:createSum,createCumSum:createCumSum,createMean:createMean,createMedian:createMedian,createMad:createMad,createVariance:createVariance,createQuantileSeq:createQuantileSeq,createStd:createStd,createCombinations:createCombinations,createCombinationsWithRep:createCombinationsWithRep,createGamma:createGamma,createLgamma:createLgamma,createFactorial:createFactorial,createKldivergence:createKldivergence,createMultinomial:createMultinomial,createPermutations:createPermutations,createPickRandom:createPickRandom,createRandom:createRandom,createRandomInt:createRandomInt,createStirlingS2:createStirlingS2,createBellNumbers:createBellNumbers,createCatalan:createCatalan,createComposition:createComposition,createLeafCount:createLeafCount,createSimplify:createSimplify,createSimplifyCore:createSimplifyCore,createResolve:createResolve,createSymbolicEqual:createSymbolicEqual,createDerivative:createDerivative,createRationalize:createRationalize,createReviver:createReviver,createReplacer:createReplacer,createE:createE,createUppercaseE:createUppercaseE,createFalse:createFalse,createI:createI,createInfinity:createInfinity,createLN10:createLN10,createLN2:createLN2,createLOG10E:createLOG10E,createLOG2E:createLOG2E,createNaN:createNaN,createNull:createNull,createPhi:createPhi,createPi:createPi,createUppercasePi:createUppercasePi,createSQRT1_2:createSQRT1_2,createSQRT2:createSQRT2,createTau:createTau,createTrue:createTrue,createVersion:createVersion,createAtomicMass:createAtomicMass,createAvogadro:createAvogadro,createBohrMagneton:createBohrMagneton,createBohrRadius:createBohrRadius,createBoltzmann:createBoltzmann,createClassicalElectronRadius:createClassicalElectronRadius,createConductanceQuantum:createConductanceQuantum,createCoulomb:createCoulomb,createDeuteronMass:createDeuteronMass,createEfimovFactor:createEfimovFactor,createElectricConstant:createElectricConstant,createElectronMass:createElectronMass,createElementaryCharge:createElementaryCharge,createFaraday:createFaraday,createFermiCoupling:createFermiCoupling,createFineStructure:createFineStructure,createFirstRadiation:createFirstRadiation,createGasConstant:createGasConstant,createGravitationConstant:createGravitationConstant,createGravity:createGravity,createHartreeEnergy:createHartreeEnergy,createInverseConductanceQuantum:createInverseConductanceQuantum,createKlitzing:createKlitzing,createLoschmidt:createLoschmidt,createMagneticConstant:createMagneticConstant,createMagneticFluxQuantum:createMagneticFluxQuantum,createMolarMass:createMolarMass,createMolarMassC12:createMolarMassC12,createMolarPlanckConstant:createMolarPlanckConstant,createMolarVolume:createMolarVolume,createNeutronMass:createNeutronMass,createNuclearMagneton:createNuclearMagneton,createPlanckCharge:createPlanckCharge,createPlanckConstant:createPlanckConstant,createPlanckLength:createPlanckLength,createPlanckMass:createPlanckMass,createPlanckTemperature:createPlanckTemperature,createPlanckTime:createPlanckTime,createProtonMass:createProtonMass,createQuantumOfCirculation:createQuantumOfCirculation,createReducedPlanckConstant:createReducedPlanckConstant,createRydberg:createRydberg,createSackurTetrode:createSackurTetrode,createSecondRadiation:createSecondRadiation,createSpeedOfLight:createSpeedOfLight,createStefanBoltzmann:createStefanBoltzmann,createThomsonCrossSection:createThomsonCrossSection,createVacuumImpedance:createVacuumImpedance,createWeakMixingAngle:createWeakMixingAngle,createWienDisplacement:createWienDisplacement,createApplyTransform:createApplyTransform,createColumnTransform:createColumnTransform,createFilterTransform:createFilterTransform,createForEachTransform:createForEachTransform,createIndexTransform:createIndexTransform,createMapTransform:createMapTransform,createMaxTransform:createMaxTransform,createMeanTransform:createMeanTransform,createMinTransform:createMinTransform,createRangeTransform:createRangeTransform,createRowTransform:createRowTransform,createSubsetTransform:createSubsetTransform,createConcatTransform:createConcatTransform,createDiffTransform:createDiffTransform,createStdTransform:createStdTransform,createSumTransform:createSumTransform,createCumSumTransform:createCumSumTransform,createVarianceTransform:createVarianceTransform}),BigNumber=createBigNumberClass({config:config$1}),Complex=createComplexClass({}),e=createE({BigNumber:BigNumber,config:config$1}),_false=createFalse({}),fineStructure=createFineStructure({BigNumber:BigNumber,config:config$1}),Fraction=createFractionClass({}),i=createI({Complex:Complex}),_Infinity=createInfinity({BigNumber:BigNumber,config:config$1}),LN10=createLN10({BigNumber:BigNumber,config:config$1}),LOG10E=createLOG10E({BigNumber:BigNumber,config:config$1}),Matrix=createMatrixClass({}),_NaN=createNaN({BigNumber:BigNumber,config:config$1}),_null=createNull({}),phi=createPhi({BigNumber:BigNumber,config:config$1}),Range=createRangeClass({}),ResultSet=createResultSet({}),SQRT1_2=createSQRT1_2({BigNumber:BigNumber,config:config$1}),sackurTetrode=createSackurTetrode({BigNumber:BigNumber,config:config$1}),tau=createTau({BigNumber:BigNumber,config:config$1}),_true=createTrue({}),version$1=createVersion({}),DenseMatrix=createDenseMatrixClass({Matrix:Matrix}),efimovFactor=createEfimovFactor({BigNumber:BigNumber,config:config$1}),LN2=createLN2({BigNumber:BigNumber,config:config$1}),pi=createPi({BigNumber:BigNumber,config:config$1}),replacer=createReplacer({}),SQRT2=createSQRT2({BigNumber:BigNumber,config:config$1}),typed=createTyped({BigNumber:BigNumber,Complex:Complex,DenseMatrix:DenseMatrix,Fraction:Fraction}),unaryPlus=createUnaryPlus({BigNumber:BigNumber,config:config$1,typed:typed}),weakMixingAngle=createWeakMixingAngle({BigNumber:BigNumber,config:config$1}),abs$1=createAbs({typed:typed}),acos$1=createAcos({Complex:Complex,config:config$1,typed:typed}),acot$1=createAcot({BigNumber:BigNumber,typed:typed}),acsc$1=createAcsc({BigNumber:BigNumber,Complex:Complex,config:config$1,typed:typed}),addScalar=createAddScalar({typed:typed}),arg=createArg({typed:typed}),asech$1=createAsech({BigNumber:BigNumber,Complex:Complex,config:config$1,typed:typed}),asinh$1=createAsinh({typed:typed}),atan$1=createAtan({typed:typed}),atanh$1=createAtanh({Complex:Complex,config:config$1,typed:typed}),bignumber=createBignumber({BigNumber:BigNumber,typed:typed}),bitNot=createBitNot({typed:typed}),boolean=createBoolean({typed:typed}),clone$1=createClone({typed:typed}),combinations=createCombinations({typed:typed}),complex=createComplex({Complex:Complex,typed:typed}),conj$1=createConj({typed:typed}),cosh$1=createCosh({typed:typed}),coth$1=createCoth({BigNumber:BigNumber,typed:typed}),csc$1=createCsc({BigNumber:BigNumber,typed:typed}),cube=createCube({typed:typed}),equalScalar=createEqualScalar({config:config$1,typed:typed}),erf$1=createErf({typed:typed}),exp$1=createExp({typed:typed}),expm1=createExpm1({Complex:Complex,typed:typed}),filter$1=createFilter({typed:typed}),forEach=createForEach({typed:typed}),format=createFormat({typed:typed}),getMatrixDataType=createGetMatrixDataType({typed:typed}),hex=createHex({format:format,typed:typed}),im$1=createIm({typed:typed}),isInteger=createIsInteger({typed:typed}),isNegative=createIsNegative({typed:typed}),isPositive=createIsPositive({typed:typed}),isZero=createIsZero({typed:typed}),LOG2E=createLOG2E({BigNumber:BigNumber,config:config$1}),lgamma=createLgamma({Complex:Complex,typed:typed}),log10$1=createLog10({Complex:Complex,config:config$1,typed:typed}),log2=createLog2({Complex:Complex,config:config$1,typed:typed}),map$1=createMap({typed:typed}),multiplyScalar=createMultiplyScalar({typed:typed}),not=createNot({typed:typed}),number=createNumber({typed:typed}),oct=createOct({format:format,typed:typed}),pickRandom=createPickRandom({config:config$1,typed:typed}),print=createPrint({typed:typed}),random$1=createRandom({config:config$1,typed:typed}),re$1=createRe({typed:typed}),sec$1=createSec({BigNumber:BigNumber,typed:typed}),sign$1=createSign({BigNumber:BigNumber,Fraction:Fraction,complex:complex,typed:typed}),sin$1=createSin({typed:typed}),SparseMatrix=createSparseMatrixClass({Matrix:Matrix,equalScalar:equalScalar,typed:typed}),splitUnit=createSplitUnit({typed:typed}),square=createSquare({typed:typed}),string=createString({typed:typed}),tan$1=createTan({typed:typed}),typeOf=createTypeOf({typed:typed}),acosh$1=createAcosh({Complex:Complex,config:config$1,typed:typed}),acsch$1=createAcsch({BigNumber:BigNumber,typed:typed}),apply=createApply({isInteger:isInteger,typed:typed}),asec$1=createAsec({BigNumber:BigNumber,Complex:Complex,config:config$1,typed:typed}),bin=createBin({format:format,typed:typed}),combinationsWithRep=createCombinationsWithRep({typed:typed}),cos$1=createCos({typed:typed}),csch$1=createCsch({BigNumber:BigNumber,typed:typed}),isNaN$2=createIsNaN({typed:typed}),isPrime=createIsPrime({typed:typed}),randomInt=createRandomInt({config:config$1,typed:typed}),sech$1=createSech({BigNumber:BigNumber,typed:typed}),sinh$1=createSinh({typed:typed}),sparse=createSparse({SparseMatrix:SparseMatrix,typed:typed}),sqrt$1=createSqrt({Complex:Complex,config:config$1,typed:typed}),tanh$1=createTanh({typed:typed}),unaryMinus=createUnaryMinus({typed:typed}),acoth$1=createAcoth({BigNumber:BigNumber,Complex:Complex,config:config$1,typed:typed}),cot$1=createCot({BigNumber:BigNumber,typed:typed}),fraction=createFraction({Fraction:Fraction,typed:typed}),isNumeric=createIsNumeric({typed:typed}),matrix$2=createMatrix({DenseMatrix:DenseMatrix,Matrix:Matrix,SparseMatrix:SparseMatrix,typed:typed}),matrixFromFunction=createMatrixFromFunction({isZero:isZero,matrix:matrix$2,typed:typed}),mod$1=createMod({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),nthRoot=createNthRoot({BigNumber:BigNumber,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),numeric=createNumeric({bignumber:bignumber,fraction:fraction,number:number}),or=createOr({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),prod=createProd({config:config$1,multiplyScalar:multiplyScalar,numeric:numeric,typed:typed}),reshape=createReshape({isInteger:isInteger,matrix:matrix$2,typed:typed}),size$1=createSize({matrix:matrix$2,config:config$1,typed:typed}),smaller=createSmaller({DenseMatrix:DenseMatrix,config:config$1,matrix:matrix$2,typed:typed}),squeeze=createSqueeze({matrix:matrix$2,typed:typed}),subset=createSubset({matrix:matrix$2,typed:typed}),subtract$1=createSubtract({DenseMatrix:DenseMatrix,addScalar:addScalar,equalScalar:equalScalar,matrix:matrix$2,typed:typed,unaryMinus:unaryMinus}),to=createTo({matrix:matrix$2,typed:typed}),transpose=createTranspose({matrix:matrix$2,typed:typed}),xgcd=createXgcd({BigNumber:BigNumber,config:config$1,matrix:matrix$2,typed:typed}),zeros=createZeros({BigNumber:BigNumber,config:config$1,matrix:matrix$2,typed:typed}),and=createAnd({equalScalar:equalScalar,matrix:matrix$2,not:not,typed:typed,zeros:zeros}),bitAnd=createBitAnd({equalScalar:equalScalar,matrix:matrix$2,typed:typed}),bitXor=createBitXor({DenseMatrix:DenseMatrix,matrix:matrix$2,typed:typed}),cbrt=createCbrt({BigNumber:BigNumber,Complex:Complex,Fraction:Fraction,config:config$1,isNegative:isNegative,matrix:matrix$2,typed:typed,unaryMinus:unaryMinus}),compare=createCompare({BigNumber:BigNumber,DenseMatrix:DenseMatrix,Fraction:Fraction,config:config$1,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),compareText=createCompareText({matrix:matrix$2,typed:typed}),concat=createConcat({isInteger:isInteger,matrix:matrix$2,typed:typed}),count=createCount({prod:prod,size:size$1,typed:typed}),ctranspose=createCtranspose({conj:conj$1,transpose:transpose,typed:typed}),diag=createDiag({DenseMatrix:DenseMatrix,SparseMatrix:SparseMatrix,matrix:matrix$2,typed:typed}),divideScalar=createDivideScalar({numeric:numeric,typed:typed}),dotDivide=createDotDivide({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),equal$1=createEqual({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),fft=createFft({addScalar:addScalar,divideScalar:divideScalar,exp:exp$1,i:i,matrix:matrix$2,multiplyScalar:multiplyScalar,tau:tau,typed:typed}),flatten$3=createFlatten({matrix:matrix$2,typed:typed}),gcd=createGcd({BigNumber:BigNumber,DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),hasNumericValue=createHasNumericValue({isNumeric:isNumeric,typed:typed}),hypot=createHypot({abs:abs$1,addScalar:addScalar,divideScalar:divideScalar,isPositive:isPositive,multiplyScalar:multiplyScalar,smaller:smaller,sqrt:sqrt$1,typed:typed}),ifft=createIfft({conj:conj$1,dotDivide:dotDivide,fft:fft,typed:typed}),kron=createKron({matrix:matrix$2,multiplyScalar:multiplyScalar,typed:typed}),largerEq=createLargerEq({DenseMatrix:DenseMatrix,config:config$1,matrix:matrix$2,typed:typed}),leftShift=createLeftShift({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed,zeros:zeros}),lsolve=createLsolve({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed}),matrixFromColumns=createMatrixFromColumns({flatten:flatten$3,matrix:matrix$2,size:size$1,typed:typed}),min$1=createMin({config:config$1,numeric:numeric,smaller:smaller,typed:typed}),mode=createMode({isNaN:isNaN$2,isNumeric:isNumeric,typed:typed}),nthRoots=createNthRoots({Complex:Complex,config:config$1,divideScalar:divideScalar,typed:typed}),ones=createOnes({BigNumber:BigNumber,config:config$1,matrix:matrix$2,typed:typed}),partitionSelect=createPartitionSelect({compare:compare,isNaN:isNaN$2,isNumeric:isNumeric,typed:typed}),resize=createResize({config:config$1,matrix:matrix$2}),rightArithShift=createRightArithShift({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed,zeros:zeros}),round$1=createRound({BigNumber:BigNumber,DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed,zeros:zeros}),smallerEq=createSmallerEq({DenseMatrix:DenseMatrix,config:config$1,matrix:matrix$2,typed:typed}),unequal=createUnequal({DenseMatrix:DenseMatrix,config:config$1,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),usolve=createUsolve({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed}),xor=createXor({DenseMatrix:DenseMatrix,matrix:matrix$2,typed:typed}),add$1=createAdd({DenseMatrix:DenseMatrix,SparseMatrix:SparseMatrix,addScalar:addScalar,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),atan2$1=createAtan2({BigNumber:BigNumber,DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),bitOr=createBitOr({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),catalan=createCatalan({addScalar:addScalar,combinations:combinations,divideScalar:divideScalar,isInteger:isInteger,isNegative:isNegative,multiplyScalar:multiplyScalar,typed:typed}),compareNatural=createCompareNatural({compare:compare,typed:typed}),cumsum=createCumSum({add:add$1,typed:typed,unaryPlus:unaryPlus}),deepEqual=createDeepEqual({equal:equal$1,typed:typed}),diff=createDiff({matrix:matrix$2,number:number,subtract:subtract$1,typed:typed}),dot=createDot({addScalar:addScalar,conj:conj$1,multiplyScalar:multiplyScalar,size:size$1,typed:typed}),equalText=createEqualText({compareText:compareText,isZero:isZero,typed:typed}),floor=createFloor({DenseMatrix:DenseMatrix,config:config$1,equalScalar:equalScalar,matrix:matrix$2,round:round$1,typed:typed,zeros:zeros}),identity$1=createIdentity({BigNumber:BigNumber,DenseMatrix:DenseMatrix,SparseMatrix:SparseMatrix,config:config$1,matrix:matrix$2,typed:typed}),invmod=createInvmod({BigNumber:BigNumber,add:add$1,config:config$1,equal:equal$1,isInteger:isInteger,mod:mod$1,smaller:smaller,typed:typed,xgcd:xgcd}),larger=createLarger({DenseMatrix:DenseMatrix,config:config$1,matrix:matrix$2,typed:typed}),log$1=createLog({Complex:Complex,config:config$1,divideScalar:divideScalar,typed:typed}),lsolveAll=createLsolveAll({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed}),matrixFromRows=createMatrixFromRows({flatten:flatten$3,matrix:matrix$2,size:size$1,typed:typed}),multiply$1=createMultiply({addScalar:addScalar,dot:dot,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,typed:typed}),qr=createQr({addScalar:addScalar,complex:complex,conj:conj$1,divideScalar:divideScalar,equal:equal$1,identity:identity$1,isZero:isZero,matrix:matrix$2,multiplyScalar:multiplyScalar,sign:sign$1,sqrt:sqrt$1,subtract:subtract$1,typed:typed,unaryMinus:unaryMinus,zeros:zeros}),range$1=createRange({bignumber:bignumber,matrix:matrix$2,config:config$1,larger:larger,largerEq:largerEq,smaller:smaller,smallerEq:smallerEq,typed:typed}),rightLogShift=createRightLogShift({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed,zeros:zeros}),setSize=createSetSize({compareNatural:compareNatural,typed:typed}),slu=createSlu({SparseMatrix:SparseMatrix,abs:abs$1,add:add$1,divideScalar:divideScalar,larger:larger,largerEq:largerEq,multiply:multiply$1,subtract:subtract$1,transpose:transpose,typed:typed}),sum=createSum({add:add$1,config:config$1,numeric:numeric,typed:typed}),trace=createTrace({add:add$1,matrix:matrix$2,typed:typed}),usolveAll=createUsolveAll({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed}),asin$1=createAsin({Complex:Complex,config:config$1,typed:typed}),ceil=createCeil({DenseMatrix:DenseMatrix,config:config$1,equalScalar:equalScalar,matrix:matrix$2,round:round$1,typed:typed,zeros:zeros}),composition=createComposition({addScalar:addScalar,combinations:combinations,isInteger:isInteger,isNegative:isNegative,isPositive:isPositive,larger:larger,typed:typed}),cross=createCross({matrix:matrix$2,multiply:multiply$1,subtract:subtract$1,typed:typed}),det=createDet({divideScalar:divideScalar,isZero:isZero,matrix:matrix$2,multiply:multiply$1,subtract:subtract$1,typed:typed,unaryMinus:unaryMinus}),distance=createDistance({abs:abs$1,addScalar:addScalar,divideScalar:divideScalar,multiplyScalar:multiplyScalar,sqrt:sqrt$1,subtract:subtract$1,typed:typed,unaryMinus:unaryMinus}),dotMultiply=createDotMultiply({equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,typed:typed}),FibonacciHeap=createFibonacciHeapClass({larger:larger,smaller:smaller}),fix=createFix({Complex:Complex,DenseMatrix:DenseMatrix,ceil:ceil,equalScalar:equalScalar,floor:floor,matrix:matrix$2,typed:typed,zeros:zeros}),ImmutableDenseMatrix=createImmutableDenseMatrixClass({DenseMatrix:DenseMatrix,smaller:smaller}),Index=createIndexClass({ImmutableDenseMatrix:ImmutableDenseMatrix}),intersect=createIntersect({abs:abs$1,add:add$1,addScalar:addScalar,config:config$1,divideScalar:divideScalar,equalScalar:equalScalar,flatten:flatten$3,isNumeric:isNumeric,isZero:isZero,matrix:matrix$2,multiply:multiply$1,multiplyScalar:multiplyScalar,smaller:smaller,subtract:subtract$1,typed:typed}),lcm=createLcm({equalScalar:equalScalar,matrix:matrix$2,typed:typed}),log1p=createLog1p({Complex:Complex,config:config$1,divideScalar:divideScalar,log:log$1,typed:typed}),max$1=createMax({config:config$1,larger:larger,numeric:numeric,typed:typed}),quantileSeq=createQuantileSeq({add:add$1,compare:compare,multiply:multiply$1,partitionSelect:partitionSelect,typed:typed}),row=createRow({Index:Index,matrix:matrix$2,range:range$1,typed:typed}),setCartesian=createSetCartesian({DenseMatrix:DenseMatrix,Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),setDistinct=createSetDistinct({DenseMatrix:DenseMatrix,Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),setIsSubset=createSetIsSubset({Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),setPowerset=createSetPowerset({Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),sort=createSort({compare:compare,compareNatural:compareNatural,matrix:matrix$2,typed:typed}),column=createColumn({Index:Index,matrix:matrix$2,range:range$1,typed:typed}),index=createIndex({Index:Index,typed:typed}),inv=createInv({abs:abs$1,addScalar:addScalar,det:det,divideScalar:divideScalar,identity:identity$1,matrix:matrix$2,multiply:multiply$1,typed:typed,unaryMinus:unaryMinus}),pinv=createPinv({Complex:Complex,add:add$1,ctranspose:ctranspose,deepEqual:deepEqual,divideScalar:divideScalar,dot:dot,dotDivide:dotDivide,equal:equal$1,inv:inv,matrix:matrix$2,multiply:multiply$1,typed:typed}),pow$1=createPow({Complex:Complex,config:config$1,fraction:fraction,identity:identity$1,inv:inv,matrix:matrix$2,multiply:multiply$1,number:number,typed:typed}),setDifference=createSetDifference({DenseMatrix:DenseMatrix,Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),setMultiplicity=createSetMultiplicity({Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),Spa=createSpaClass({FibonacciHeap:FibonacciHeap,addScalar:addScalar,equalScalar:equalScalar}),sqrtm=createSqrtm({abs:abs$1,add:add$1,identity:identity$1,inv:inv,max:max$1,multiply:multiply$1,size:size$1,sqrt:sqrt$1,subtract:subtract$1,typed:typed}),Unit=createUnitClass({BigNumber:BigNumber,Complex:Complex,Fraction:Fraction,abs:abs$1,addScalar:addScalar,config:config$1,divideScalar:divideScalar,equal:equal$1,fix:fix,format:format,isNumeric:isNumeric,multiplyScalar:multiplyScalar,number:number,pow:pow$1,round:round$1,subtract:subtract$1}),vacuumImpedance=createVacuumImpedance({BigNumber:BigNumber,Unit:Unit,config:config$1}),wienDisplacement=createWienDisplacement({BigNumber:BigNumber,Unit:Unit,config:config$1}),atomicMass=createAtomicMass({BigNumber:BigNumber,Unit:Unit,config:config$1}),bohrMagneton=createBohrMagneton({BigNumber:BigNumber,Unit:Unit,config:config$1}),boltzmann=createBoltzmann({BigNumber:BigNumber,Unit:Unit,config:config$1}),conductanceQuantum=createConductanceQuantum({BigNumber:BigNumber,Unit:Unit,config:config$1}),createUnit=createCreateUnit({Unit:Unit,typed:typed}),deuteronMass=createDeuteronMass({BigNumber:BigNumber,Unit:Unit,config:config$1}),dotPow=createDotPow({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,pow:pow$1,typed:typed}),electricConstant=createElectricConstant({BigNumber:BigNumber,Unit:Unit,config:config$1}),elementaryCharge=createElementaryCharge({BigNumber:BigNumber,Unit:Unit,config:config$1}),expm=createExpm({abs:abs$1,add:add$1,identity:identity$1,inv:inv,multiply:multiply$1,typed:typed}),faraday=createFaraday({BigNumber:BigNumber,Unit:Unit,config:config$1}),firstRadiation=createFirstRadiation({BigNumber:BigNumber,Unit:Unit,config:config$1}),gamma$1=createGamma({BigNumber:BigNumber,Complex:Complex,config:config$1,multiplyScalar:multiplyScalar,pow:pow$1,typed:typed}),gravitationConstant=createGravitationConstant({BigNumber:BigNumber,Unit:Unit,config:config$1}),hartreeEnergy=createHartreeEnergy({BigNumber:BigNumber,Unit:Unit,config:config$1}),klitzing=createKlitzing({BigNumber:BigNumber,Unit:Unit,config:config$1}),loschmidt=createLoschmidt({BigNumber:BigNumber,Unit:Unit,config:config$1}),magneticConstant=createMagneticConstant({BigNumber:BigNumber,Unit:Unit,config:config$1}),molarMass=createMolarMass({BigNumber:BigNumber,Unit:Unit,config:config$1}),molarPlanckConstant=createMolarPlanckConstant({BigNumber:BigNumber,Unit:Unit,config:config$1}),neutronMass=createNeutronMass({BigNumber:BigNumber,Unit:Unit,config:config$1}),nuclearMagneton=createNuclearMagneton({BigNumber:BigNumber,Unit:Unit,config:config$1}),planckCharge=createPlanckCharge({BigNumber:BigNumber,Unit:Unit,config:config$1}),planckLength=createPlanckLength({BigNumber:BigNumber,Unit:Unit,config:config$1}),planckTemperature=createPlanckTemperature({BigNumber:BigNumber,Unit:Unit,config:config$1}),protonMass=createProtonMass({BigNumber:BigNumber,Unit:Unit,config:config$1}),reducedPlanckConstant=createReducedPlanckConstant({BigNumber:BigNumber,Unit:Unit,config:config$1}),rydberg=createRydberg({BigNumber:BigNumber,Unit:Unit,config:config$1}),setIntersect=createSetIntersect({DenseMatrix:DenseMatrix,Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),speedOfLight=createSpeedOfLight({BigNumber:BigNumber,Unit:Unit,config:config$1}),stefanBoltzmann=createStefanBoltzmann({BigNumber:BigNumber,Unit:Unit,config:config$1}),thomsonCrossSection=createThomsonCrossSection({BigNumber:BigNumber,Unit:Unit,config:config$1}),avogadro=createAvogadro({BigNumber:BigNumber,Unit:Unit,config:config$1}),bohrRadius=createBohrRadius({BigNumber:BigNumber,Unit:Unit,config:config$1}),coulomb=createCoulomb({BigNumber:BigNumber,Unit:Unit,config:config$1}),divide$1=createDivide({divideScalar:divideScalar,equalScalar:equalScalar,inv:inv,matrix:matrix$2,multiply:multiply$1,typed:typed}),electronMass=createElectronMass({BigNumber:BigNumber,Unit:Unit,config:config$1}),factorial$1=createFactorial({gamma:gamma$1,typed:typed}),gravity=createGravity({BigNumber:BigNumber,Unit:Unit,config:config$1}),inverseConductanceQuantum=createInverseConductanceQuantum({BigNumber:BigNumber,Unit:Unit,config:config$1}),lup=createLup({DenseMatrix:DenseMatrix,Spa:Spa,SparseMatrix:SparseMatrix,abs:abs$1,addScalar:addScalar,divideScalar:divideScalar,equalScalar:equalScalar,larger:larger,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed,unaryMinus:unaryMinus}),magneticFluxQuantum=createMagneticFluxQuantum({BigNumber:BigNumber,Unit:Unit,config:config$1}),molarMassC12=createMolarMassC12({BigNumber:BigNumber,Unit:Unit,config:config$1}),multinomial=createMultinomial({add:add$1,divide:divide$1,factorial:factorial$1,isInteger:isInteger,isPositive:isPositive,multiply:multiply$1,typed:typed}),permutations=createPermutations({factorial:factorial$1,typed:typed}),planckMass=createPlanckMass({BigNumber:BigNumber,Unit:Unit,config:config$1}),quantumOfCirculation=createQuantumOfCirculation({BigNumber:BigNumber,Unit:Unit,config:config$1}),secondRadiation=createSecondRadiation({BigNumber:BigNumber,Unit:Unit,config:config$1}),stirlingS2=createStirlingS2({bignumber:bignumber,addScalar:addScalar,combinations:combinations,divideScalar:divideScalar,factorial:factorial$1,isInteger:isInteger,isNegative:isNegative,larger:larger,multiplyScalar:multiplyScalar,number:number,pow:pow$1,subtract:subtract$1,typed:typed}),unit=createUnitFunction({Unit:Unit,typed:typed}),bellNumbers=createBellNumbers({addScalar:addScalar,isInteger:isInteger,isNegative:isNegative,stirlingS2:stirlingS2,typed:typed}),eigs=createEigs({abs:abs$1,add:add$1,addScalar:addScalar,atan:atan$1,bignumber:bignumber,column:column,complex:complex,config:config$1,cos:cos$1,diag:diag,divideScalar:divideScalar,dot:dot,equal:equal$1,flatten:flatten$3,im:im$1,inv:inv,larger:larger,matrix:matrix$2,matrixFromColumns:matrixFromColumns,multiply:multiply$1,multiplyScalar:multiplyScalar,number:number,qr:qr,re:re$1,sin:sin$1,smaller:smaller,sqrt:sqrt$1,subtract:subtract$1,typed:typed,usolve:usolve,usolveAll:usolveAll}),fermiCoupling=createFermiCoupling({BigNumber:BigNumber,Unit:Unit,config:config$1}),mean=createMean({add:add$1,divide:divide$1,typed:typed}),molarVolume=createMolarVolume({BigNumber:BigNumber,Unit:Unit,config:config$1}),planckConstant=createPlanckConstant({BigNumber:BigNumber,Unit:Unit,config:config$1}),setSymDifference=createSetSymDifference({Index:Index,concat:concat,setDifference:setDifference,size:size$1,subset:subset,typed:typed}),classicalElectronRadius=createClassicalElectronRadius({BigNumber:BigNumber,Unit:Unit,config:config$1}),lusolve=createLusolve({DenseMatrix:DenseMatrix,lsolve:lsolve,lup:lup,matrix:matrix$2,slu:slu,typed:typed,usolve:usolve}),median=createMedian({add:add$1,compare:compare,divide:divide$1,partitionSelect:partitionSelect,typed:typed}),setUnion=createSetUnion({Index:Index,concat:concat,setIntersect:setIntersect,setSymDifference:setSymDifference,size:size$1,subset:subset,typed:typed}),variance=createVariance({add:add$1,apply:apply,divide:divide$1,isNaN:isNaN$2,multiply:multiply$1,subtract:subtract$1,typed:typed}),kldivergence=createKldivergence({divide:divide$1,dotDivide:dotDivide,isNumeric:isNumeric,log:log$1,matrix:matrix$2,multiply:multiply$1,sum:sum,typed:typed}),norm=createNorm({abs:abs$1,add:add$1,conj:conj$1,ctranspose:ctranspose,eigs:eigs,equalScalar:equalScalar,larger:larger,matrix:matrix$2,multiply:multiply$1,pow:pow$1,smaller:smaller,sqrt:sqrt$1,typed:typed}),planckTime=createPlanckTime({BigNumber:BigNumber,Unit:Unit,config:config$1}),rotationMatrix=createRotationMatrix({BigNumber:BigNumber,DenseMatrix:DenseMatrix,SparseMatrix:SparseMatrix,addScalar:addScalar,config:config$1,cos:cos$1,matrix:matrix$2,multiplyScalar:multiplyScalar,norm:norm,sin:sin$1,typed:typed,unaryMinus:unaryMinus}),gasConstant=createGasConstant({BigNumber:BigNumber,Unit:Unit,config:config$1}),std=createStd({sqrt:sqrt$1,typed:typed,variance:variance}),mad=createMad({abs:abs$1,map:map$1,median:median,subtract:subtract$1,typed:typed}),rotate=createRotate({multiply:multiply$1,rotationMatrix:rotationMatrix,typed:typed}),math$2={},mathWithTransform={},classes={},Chain=createChainClass({math:math$2}),Node=createNode({mathWithTransform:mathWithTransform}),ObjectNode=createObjectNode({Node:Node}),OperatorNode=createOperatorNode({Node:Node}),ParenthesisNode=createParenthesisNode({Node:Node}),RelationalNode=createRelationalNode({Node:Node}),ArrayNode=createArrayNode({Node:Node}),BlockNode=createBlockNode({Node:Node,ResultSet:ResultSet}),ConditionalNode=createConditionalNode({Node:Node}),ConstantNode=createConstantNode({Node:Node}),RangeNode=createRangeNode({Node:Node}),reviver=createReviver({classes:classes}),chain$1=createChain({Chain:Chain,typed:typed}),FunctionAssignmentNode=createFunctionAssignmentNode({Node:Node,typed:typed}),AccessorNode=createAccessorNode({Node:Node,subset:subset}),AssignmentNode=createAssignmentNode({matrix:matrix$2,Node:Node,subset:subset}),IndexNode=createIndexNode({Node:Node,size:size$1}),SymbolNode=createSymbolNode({Unit:Unit,Node:Node,math:math$2}),FunctionNode=createFunctionNode({Node:Node,SymbolNode:SymbolNode,math:math$2}),parse$2=createParse({AccessorNode:AccessorNode,ArrayNode:ArrayNode,AssignmentNode:AssignmentNode,BlockNode:BlockNode,ConditionalNode:ConditionalNode,ConstantNode:ConstantNode,FunctionAssignmentNode:FunctionAssignmentNode,FunctionNode:FunctionNode,IndexNode:IndexNode,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,RangeNode:RangeNode,RelationalNode:RelationalNode,SymbolNode:SymbolNode,config:config$1,numeric:numeric,typed:typed}),resolve=createResolve({ConstantNode:ConstantNode,FunctionNode:FunctionNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,parse:parse$2}),simplifyCore=createSimplifyCore({AccessorNode:AccessorNode,ArrayNode:ArrayNode,ConstantNode:ConstantNode,FunctionNode:FunctionNode,IndexNode:IndexNode,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,SymbolNode:SymbolNode,add:add$1,divide:divide$1,equal:equal$1,isZero:isZero,multiply:multiply$1,pow:pow$1,subtract:subtract$1}),compile=createCompile({parse:parse$2,typed:typed}),Help=createHelpClass({parse:parse$2}),leafCount=createLeafCount({parse:parse$2,typed:typed}),simplify$2=createSimplify({bignumber:bignumber,fraction:fraction,AccessorNode:AccessorNode,ArrayNode:ArrayNode,ConstantNode:ConstantNode,FunctionNode:FunctionNode,IndexNode:IndexNode,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,SymbolNode:SymbolNode,add:add$1,config:config$1,divide:divide$1,equal:equal$1,isZero:isZero,mathWithTransform:mathWithTransform,matrix:matrix$2,multiply:multiply$1,parse:parse$2,pow:pow$1,resolve:resolve,simplifyCore:simplifyCore,subtract:subtract$1,typed:typed}),symbolicEqual=createSymbolicEqual({OperatorNode:OperatorNode,parse:parse$2,simplify:simplify$2,typed:typed}),evaluate$1=createEvaluate({parse:parse$2,typed:typed}),help=createHelp({Help:Help,mathWithTransform:mathWithTransform,typed:typed}),Parser=createParserClass({evaluate:evaluate$1}),rationalize=createRationalize({bignumber:bignumber,fraction:fraction,AccessorNode:AccessorNode,ArrayNode:ArrayNode,ConstantNode:ConstantNode,FunctionNode:FunctionNode,IndexNode:IndexNode,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,SymbolNode:SymbolNode,add:add$1,config:config$1,divide:divide$1,equal:equal$1,isZero:isZero,mathWithTransform:mathWithTransform,matrix:matrix$2,multiply:multiply$1,parse:parse$2,pow:pow$1,simplify:simplify$2,simplifyCore:simplifyCore,subtract:subtract$1,typed:typed}),derivative$1=createDerivative({ConstantNode:ConstantNode,FunctionNode:FunctionNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,SymbolNode:SymbolNode,config:config$1,equal:equal$1,isZero:isZero,numeric:numeric,parse:parse$2,simplify:simplify$2,typed:typed}),parser=createParser({Parser:Parser,typed:typed});_extends$1(math$2,{e:e,false:_false,fineStructure:fineStructure,i:i,Infinity:_Infinity,LN10:LN10,LOG10E:LOG10E,NaN:_NaN,null:_null,phi:phi,SQRT1_2:SQRT1_2,sackurTetrode:sackurTetrode,tau:tau,true:_true,E:e,version:version$1,efimovFactor:efimovFactor,LN2:LN2,pi:pi,replacer:replacer,reviver:reviver,SQRT2:SQRT2,typed:typed,unaryPlus:unaryPlus,PI:pi,weakMixingAngle:weakMixingAngle,abs:abs$1,acos:acos$1,acot:acot$1,acsc:acsc$1,addScalar:addScalar,arg:arg,asech:asech$1,asinh:asinh$1,atan:atan$1,atanh:atanh$1,bignumber:bignumber,bitNot:bitNot,boolean:boolean,chain:chain$1,clone:clone$1,combinations:combinations,complex:complex,conj:conj$1,cosh:cosh$1,coth:coth$1,csc:csc$1,cube:cube,equalScalar:equalScalar,erf:erf$1,exp:exp$1,expm1:expm1,filter:filter$1,forEach:forEach,format:format,getMatrixDataType:getMatrixDataType,hex:hex,im:im$1,isInteger:isInteger,isNegative:isNegative,isPositive:isPositive,isZero:isZero,LOG2E:LOG2E,lgamma:lgamma,log10:log10$1,log2:log2,map:map$1,multiplyScalar:multiplyScalar,not:not,number:number,oct:oct,pickRandom:pickRandom,print:print,random:random$1,re:re$1,sec:sec$1,sign:sign$1,sin:sin$1,splitUnit:splitUnit,square:square,string:string,tan:tan$1,typeOf:typeOf,acosh:acosh$1,acsch:acsch$1,apply:apply,asec:asec$1,bin:bin,combinationsWithRep:combinationsWithRep,cos:cos$1,csch:csch$1,isNaN:isNaN$2,isPrime:isPrime,randomInt:randomInt,sech:sech$1,sinh:sinh$1,sparse:sparse,sqrt:sqrt$1,tanh:tanh$1,unaryMinus:unaryMinus,acoth:acoth$1,cot:cot$1,fraction:fraction,isNumeric:isNumeric,matrix:matrix$2,matrixFromFunction:matrixFromFunction,mod:mod$1,nthRoot:nthRoot,numeric:numeric,or:or,prod:prod,reshape:reshape,size:size$1,smaller:smaller,squeeze:squeeze,subset:subset,subtract:subtract$1,to:to,transpose:transpose,xgcd:xgcd,zeros:zeros,and:and,bitAnd:bitAnd,bitXor:bitXor,cbrt:cbrt,compare:compare,compareText:compareText,concat:concat,count:count,ctranspose:ctranspose,diag:diag,divideScalar:divideScalar,dotDivide:dotDivide,equal:equal$1,fft:fft,flatten:flatten$3,gcd:gcd,hasNumericValue:hasNumericValue,hypot:hypot,ifft:ifft,kron:kron,largerEq:largerEq,leftShift:leftShift,lsolve:lsolve,matrixFromColumns:matrixFromColumns,min:min$1,mode:mode,nthRoots:nthRoots,ones:ones,partitionSelect:partitionSelect,resize:resize,rightArithShift:rightArithShift,round:round$1,smallerEq:smallerEq,unequal:unequal,usolve:usolve,xor:xor,add:add$1,atan2:atan2$1,bitOr:bitOr,catalan:catalan,compareNatural:compareNatural,cumsum:cumsum,deepEqual:deepEqual,diff:diff,dot:dot,equalText:equalText,floor:floor,identity:identity$1,invmod:invmod,larger:larger,log:log$1,lsolveAll:lsolveAll,matrixFromRows:matrixFromRows,multiply:multiply$1,qr:qr,range:range$1,rightLogShift:rightLogShift,setSize:setSize,slu:slu,sum:sum,trace:trace,usolveAll:usolveAll,asin:asin$1,ceil:ceil,composition:composition,cross:cross,det:det,distance:distance,dotMultiply:dotMultiply,fix:fix,intersect:intersect,lcm:lcm,log1p:log1p,max:max$1,quantileSeq:quantileSeq,row:row,setCartesian:setCartesian,setDistinct:setDistinct,setIsSubset:setIsSubset,setPowerset:setPowerset,sort:sort,column:column,index:index,inv:inv,pinv:pinv,pow:pow$1,setDifference:setDifference,setMultiplicity:setMultiplicity,sqrtm:sqrtm,vacuumImpedance:vacuumImpedance,wienDisplacement:wienDisplacement,atomicMass:atomicMass,bohrMagneton:bohrMagneton,boltzmann:boltzmann,conductanceQuantum:conductanceQuantum,createUnit:createUnit,deuteronMass:deuteronMass,dotPow:dotPow,electricConstant:electricConstant,elementaryCharge:elementaryCharge,expm:expm,faraday:faraday,firstRadiation:firstRadiation,gamma:gamma$1,gravitationConstant:gravitationConstant,hartreeEnergy:hartreeEnergy,klitzing:klitzing,loschmidt:loschmidt,magneticConstant:magneticConstant,molarMass:molarMass,molarPlanckConstant:molarPlanckConstant,neutronMass:neutronMass,nuclearMagneton:nuclearMagneton,planckCharge:planckCharge,planckLength:planckLength,planckTemperature:planckTemperature,protonMass:protonMass,reducedPlanckConstant:reducedPlanckConstant,rydberg:rydberg,setIntersect:setIntersect,speedOfLight:speedOfLight,stefanBoltzmann:stefanBoltzmann,thomsonCrossSection:thomsonCrossSection,avogadro:avogadro,bohrRadius:bohrRadius,coulomb:coulomb,divide:divide$1,electronMass:electronMass,factorial:factorial$1,gravity:gravity,inverseConductanceQuantum:inverseConductanceQuantum,lup:lup,magneticFluxQuantum:magneticFluxQuantum,molarMassC12:molarMassC12,multinomial:multinomial,parse:parse$2,permutations:permutations,planckMass:planckMass,quantumOfCirculation:quantumOfCirculation,resolve:resolve,secondRadiation:secondRadiation,simplifyCore:simplifyCore,stirlingS2:stirlingS2,unit:unit,bellNumbers:bellNumbers,compile:compile,eigs:eigs,fermiCoupling:fermiCoupling,leafCount:leafCount,mean:mean,molarVolume:molarVolume,planckConstant:planckConstant,setSymDifference:setSymDifference,simplify:simplify$2,symbolicEqual:symbolicEqual,classicalElectronRadius:classicalElectronRadius,evaluate:evaluate$1,help:help,lusolve:lusolve,median:median,rationalize:rationalize,setUnion:setUnion,variance:variance,derivative:derivative$1,kldivergence:kldivergence,norm:norm,planckTime:planckTime,rotationMatrix:rotationMatrix,gasConstant:gasConstant,parser:parser,std:std,mad:mad,rotate:rotate,config:config$1}),_extends$1(mathWithTransform,math$2,{filter:createFilterTransform({typed:typed}),forEach:createForEachTransform({typed:typed}),map:createMapTransform({typed:typed}),apply:createApplyTransform({isInteger:isInteger,typed:typed}),diff:createDiffTransform({bignumber:bignumber,matrix:matrix$2,number:number,subtract:subtract$1,typed:typed}),subset:createSubsetTransform({matrix:matrix$2,typed:typed}),concat:createConcatTransform({isInteger:isInteger,matrix:matrix$2,typed:typed}),max:createMaxTransform({config:config$1,larger:larger,numeric:numeric,typed:typed}),min:createMinTransform({config:config$1,numeric:numeric,smaller:smaller,typed:typed}),range:createRangeTransform({bignumber:bignumber,matrix:matrix$2,config:config$1,larger:larger,largerEq:largerEq,smaller:smaller,smallerEq:smallerEq,typed:typed}),sum:createSumTransform({add:add$1,config:config$1,numeric:numeric,typed:typed}),cumsum:createCumSumTransform({add:add$1,typed:typed,unaryPlus:unaryPlus}),row:createRowTransform({Index:Index,matrix:matrix$2,range:range$1,typed:typed}),column:createColumnTransform({Index:Index,matrix:matrix$2,range:range$1,typed:typed}),index:createIndexTransform({Index:Index}),mean:createMeanTransform({add:add$1,divide:divide$1,typed:typed}),variance:createVarianceTransform({add:add$1,apply:apply,divide:divide$1,isNaN:isNaN$2,multiply:multiply$1,subtract:subtract$1,typed:typed}),std:createStdTransform({sqrt:sqrt$1,typed:typed,variance:variance})}),_extends$1(classes,{BigNumber:BigNumber,Chain:Chain,Complex:Complex,Fraction:Fraction,Matrix:Matrix,Node:Node,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,Range:Range,RelationalNode:RelationalNode,ResultSet:ResultSet,ArrayNode:ArrayNode,BlockNode:BlockNode,ConditionalNode:ConditionalNode,ConstantNode:ConstantNode,DenseMatrix:DenseMatrix,RangeNode:RangeNode,FunctionAssignmentNode:FunctionAssignmentNode,SparseMatrix:SparseMatrix,AccessorNode:AccessorNode,AssignmentNode:AssignmentNode,IndexNode:IndexNode,FibonacciHeap:FibonacciHeap,ImmutableDenseMatrix:ImmutableDenseMatrix,Index:Index,Spa:Spa,Unit:Unit,SymbolNode:SymbolNode,FunctionNode:FunctionNode,Help:Help,Parser:Parser}),Chain.createProxy(math$2);var all=allFactories;Number.isFinite=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Number.isNaN=Number.isNaN||function(e){return e!=e};var tinyEmitter={exports:{}};function E(){}function mixin$1(e){var t=new tinyEmitter.exports;return e.on=t.on.bind(t),e.off=t.off.bind(t),e.once=t.once.bind(t),e.emit=t.emit.bind(t),e}function importFactory(e,t,n,r){function a(t,a,o){var s;if(o.wrap&&"function"==typeof a&&(a=function(e){var t=function(){for(var t=[],r=0,a=arguments.length;r2&&void 0!==arguments[2]?arguments[2]:t.fn;if(contains$1(i,"."))throw new Error("Factory name should not contain a nested path. Name: "+JSON.stringify(i));var s=d(t)?n.expression.transform:n,l=i in n.expression.transform,c=hasOwnProperty$2(s,i)?s[i]:void 0,m=function(){var r={};t.dependencies.map(stripOptionalNotation).forEach((e=>{if(contains$1(e,"."))throw new Error("Factory dependency should not contain a nested path. Name: "+JSON.stringify(e));"math"===e?r.math=n:"mathWithTransform"===e?r.mathWithTransform=n.expression.mathWithTransform:"classes"===e?r.classes=n:r[e]=n[e]}));var o=t(r);if(o&&"function"==typeof o.transform)throw new Error('Transforms cannot be attached to factory functions. Please create a separate function for it with exports.path="expression.transform"');if(void 0===c||a.override)return o;if(u(c)&&u(o))return e(c,o);if(a.silent)return c;throw new Error('Cannot import "'+i+'": already exists')};t.meta&&!1===t.meta.lazy?(s[i]=m(),c&&l?o(i):(d(t)||p(t))&&lazy(n.expression.mathWithTransform,i,(()=>s[i]))):(lazy(s,i,m),c&&l?o(i):(d(t)||p(t))&&lazy(n.expression.mathWithTransform,i,(()=>s[i]))),r[i]=t,n.emit("import",i,m)}function l(e){return"function"==typeof e||"number"==typeof e||"string"==typeof e||"boolean"==typeof e||null===e||isUnit(e)||isComplex(e)||isBigNumber(e)||isFraction(e)||isMatrix(e)||Array.isArray(e)}function u(e){return"function"==typeof e&&"object"==typeof e.signatures}function c(e){return!hasOwnProperty$2(m,e)}function p(e){return!(-1!==e.fn.indexOf(".")||hasOwnProperty$2(m,e.fn)||e.meta&&e.meta.isClass)}function d(e){return void 0!==e&&void 0!==e.meta&&!0===e.meta.isTransformFunction||!1}var m={expression:!0,type:!0,docs:!0,error:!0,json:!0,chain:!0};return function(e,t){var n=arguments.length;if(1!==n&&2!==n)throw new ArgumentsError("import",n,1,2);function r(e,n,a){if(Array.isArray(n))n.forEach((t=>r(e,t)));else if("object"==typeof n)for(var i in n)hasOwnProperty$2(n,i)&&r(e,n[i],i);else if(isFactory(n)||void 0!==a){var o=isFactory(n)?d(n)?n.fn+".transform":n.fn:a;if(hasOwnProperty$2(e,o)&&e[o]!==n&&!t.silent)throw new Error('Cannot import "'+o+'" twice');e[o]=n}else if(!t.silent)throw new TypeError("Factory, Object, or Array expected")}t||(t={});var i={};for(var o in r(i,e),i)if(hasOwnProperty$2(i,o)){var u=i[o];if(isFactory(u))s(u,t);else if(l(u))a(o,u,t);else if(!t.silent)throw new TypeError("Factory, Object, or Array expected")}}}function create$1(e,t){var n=_extends$1({},DEFAULT_CONFIG,t);if("function"!=typeof Object.create)throw new Error("ES5 not supported by this JavaScript engine. Please load the es5-shim and es5-sham library for compatibility.");var r=mixin$1({isNumber:isNumber$1,isComplex:isComplex,isBigNumber:isBigNumber,isFraction:isFraction,isUnit:isUnit,isString:isString$1,isArray:isArray$1,isMatrix:isMatrix,isCollection:isCollection,isDenseMatrix:isDenseMatrix,isSparseMatrix:isSparseMatrix,isRange:isRange,isIndex:isIndex,isBoolean:isBoolean$1,isResultSet:isResultSet,isHelp:isHelp,isFunction:isFunction$2,isDate:isDate$1,isRegExp:isRegExp$1,isObject:isObject$1,isNull:isNull$1,isUndefined:isUndefined$1,isAccessorNode:isAccessorNode,isArrayNode:isArrayNode,isAssignmentNode:isAssignmentNode,isBlockNode:isBlockNode,isConditionalNode:isConditionalNode,isConstantNode:isConstantNode,isFunctionAssignmentNode:isFunctionAssignmentNode,isFunctionNode:isFunctionNode,isIndexNode:isIndexNode,isNode:isNode,isObjectNode:isObjectNode,isOperatorNode:isOperatorNode,isParenthesisNode:isParenthesisNode,isRangeNode:isRangeNode,isSymbolNode:isSymbolNode,isChain:isChain});r.config=configFactory(n,r.emit),r.expression={transform:{},mathWithTransform:{config:r.config}};var a=[],i=[],o={},s=importFactory((function(){for(var e=arguments.length,t=new Array(e),n=0;n{values$1(o).forEach((e=>{e&&e.meta&&e.meta.recreateOnConfigChange&&s(e,{override:!0})}))})),r.create=create$1.bind(null,e),r.factory=factory,r.import(values$1(deepFlatten(e))),r.ArgumentsError=ArgumentsError,r.DimensionError=DimensionError,r.IndexError=IndexError,r}E.prototype={on:function(e,t,n){var r=this.e||(this.e={});return(r[e]||(r[e]=[])).push({fn:t,ctx:n}),this},once:function(e,t,n){var r=this;function a(){r.off(e,a),t.apply(n,arguments)}return a._=t,this.on(e,a,n)},emit:function(e){for(var t=[].slice.call(arguments,1),n=((this.e||(this.e={}))[e]||[]).slice(),r=0,a=n.length;r3;a-=4)e(),e(),e(),e();for(;a>0;)e(),a--;if(new Date-n>t)break}for(a=r;a>3;a-=4)e(),e(),e(),e();for(;a>0;)e(),a--;return 1e3*(3*r-1)/(new Date-n)},numeric._myIndexOf=function(e){var t,n=this.length;for(t=0;tnumeric.largeArray)return n.push("...Large Array..."),!0;for(u=!1,n.push("["),a=0;a0&&(n.push(","),u&&n.push("\n ")),u=e(r[a]);return n.push("]"),!0}for(a in n.push("{"),u=!1,r)r.hasOwnProperty(a)&&(u&&n.push(",\n"),u=!0,n.push(a),n.push(": \n"),e(r[a]));return n.push("}"),!0}(e),n.join("")},numeric.parseDate=function(e){return function e(t){if("string"==typeof t)return Date.parse(t.replace(/-/g,"/"));if(!(t instanceof Array))throw new Error("parseDate: parameter must be arrays of strings");var n,r=[];for(n=0;n0){for(i[l]=[],t=0;t>>8^a[255&(i^e[r])];return-1^i}var n,r,a,i,o,s,l,u,c,p,d=e[0].length,m=e[0][0].length,f=[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,m>>24&255,m>>16&255,m>>8&255,255&m,d>>24&255,d>>16&255,d>>8&255,255&d,8,2,0,0,0,-1,-2,-3,-4,-5,-6,-7,-8,73,68,65,84,8,29];for(p=t(f,12,29),f[29]=p>>24&255,f[30]=p>>16&255,f[31]=p>>8&255,f[32]=255&p,n=1,r=0,l=0;l>8&255,f.push(o),f.push(s),f.push(255&~o),f.push(255&~s),0===l&&f.push(0),u=0;u255?255:o<0?0:Math.round(o)))%65521))%65521,f.push(o);f.push(0)}return c=(r<<16)+n,f.push(c>>24&255),f.push(c>>16&255),f.push(c>>8&255),f.push(255&c),i=f.length-41,f[33]=i>>24&255,f[34]=i>>16&255,f[35]=i>>8&255,f[36]=255&i,p=t(f,37),f.push(p>>24&255),f.push(p>>16&255),f.push(p>>8&255),f.push(255&p),f.push(0),f.push(0),f.push(0),f.push(0),f.push(73),f.push(69),f.push(78),f.push(68),f.push(174),f.push(66),f.push(96),f.push(130),"data:image/png;base64,"+function(e){var t,n,r,a,i,o,s,l=e.length,u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",c="";for(t=0;t>4),o=((15&r)<<2)+((a=e[t+2])>>6),s=63&a,t+1>=l?o=s=64:t+2>=l&&(s=64),c+=u.charAt(n>>2)+u.charAt(i)+u.charAt(o)+u.charAt(s);return c}(f)},numeric._dim=function(e){for(var t=[];"object"==typeof e;)t.push(e.length),e=e[0];return t},numeric.dim=function(e){var t;return"object"==typeof e?"object"==typeof(t=e[0])?"object"==typeof t[0]?numeric._dim(e):[e.length,t.length]:[e.length]:[]},numeric.mapreduce=function(e,t){return Function("x","accum","_s","_k",'if(typeof accum === "undefined") accum = '+t+';\nif(typeof x === "number") { var xi = x; '+e+'; return accum; }\nif(typeof _s === "undefined") _s = numeric.dim(x);\nif(typeof _k === "undefined") _k = 0;\nvar _n = _s[_k];\nvar i,xi;\nif(_k < _s.length-1) {\n for(i=_n-1;i>=0;i--) {\n accum = arguments.callee(x[i],accum,_s,_k+1);\n } return accum;\n}\nfor(i=_n-1;i>=1;i-=2) { \n xi = x[i];\n '+e+";\n xi = x[i-1];\n "+e+";\n}\nif(i === 0) {\n xi = x[i];\n "+e+"\n}\nreturn accum;")},numeric.mapreduce2=function(e,t){return Function("x","var n = x.length;\nvar i,xi;\n"+t+";\nfor(i=n-1;i!==-1;--i) { \n xi = x[i];\n "+e+";\n}\nreturn accum;")},numeric.same=function e(t,n){var r,a;if(!(t instanceof Array&&n instanceof Array))return!1;if((a=t.length)!==n.length)return!1;for(r=0;r=0;r-=2)i[r+1]=t,i[r]=t;return-1===r&&(i[0]=t),i}for(r=a-1;r>=0;r--)i[r]=numeric.rep(e,t,n+1);return i},numeric.dotMMsmall=function(e,t){var n,r,a,i,o,s,l,u,c,p,d;for(i=e.length,o=t.length,s=t[0].length,l=Array(i),n=i-1;n>=0;n--){for(u=Array(s),c=e[n],a=s-1;a>=0;a--){for(p=c[o-1]*t[o-1][a],r=o-2;r>=1;r-=2)d=r-1,p+=c[r]*t[r][a]+c[d]*t[d][a];0===r&&(p+=c[0]*t[0][a]),u[a]=p}l[n]=u}return l},numeric._getCol=function(e,t,n){var r;for(r=e.length-1;r>0;--r)n[r]=e[r][t],n[--r]=e[r][t];0===r&&(n[0]=e[0][t])},numeric.dotMMbig=function(e,t){var n,r,a,i=numeric._getCol,o=t.length,s=Array(o),l=e.length,u=t[0].length,c=new Array(l),p=numeric.dotVV;for(--o,r=--l;-1!==r;--r)c[r]=Array(u);for(r=--u;-1!==r;--r)for(i(t,r,s),a=l;-1!==a;--a)n=e[a],c[a][r]=p(n,s);return c},numeric.dotMV=function(e,t){var n,r=e.length;t.length;var a=Array(r),i=numeric.dotVV;for(n=r-1;n>=0;n--)a[n]=i(e[n],t);return a},numeric.dotVM=function(e,t){var n,r,a,i,o,s,l;for(a=e.length,i=t[0].length,o=Array(i),r=i-1;r>=0;r--){for(s=e[a-1]*t[a-1][r],n=a-2;n>=1;n-=2)l=n-1,s+=e[n]*t[n][r]+e[l]*t[l][r];0===n&&(s+=e[0]*t[0][r]),o[r]=s}return o},numeric.dotVV=function(e,t){var n,r,a=e.length,i=e[a-1]*t[a-1];for(n=a-2;n>=1;n-=2)r=n-1,i+=e[n]*t[n]+e[r]*t[r];return 0===n&&(i+=e[0]*t[0]),i},numeric.dot=function(e,t){var n=numeric.dim;switch(1e3*n(e).length+n(t).length){case 2002:return t.length<10?numeric.dotMMsmall(e,t):numeric.dotMMbig(e,t);case 2001:return numeric.dotMV(e,t);case 1002:return numeric.dotVM(e,t);case 1001:return numeric.dotVV(e,t);case 1e3:return numeric.mulVS(e,t);case 1:return numeric.mulSV(e,t);case 0:return e*t;default:throw new Error("numeric.dot only works on vectors and matrices")}},numeric.diag=function(e){var t,n,r,a,i=e.length,o=Array(i);for(t=i-1;t>=0;t--){for(a=Array(i),n=t+2,r=i-1;r>=n;r-=2)a[r]=0,a[r-1]=0;for(r>t&&(a[r]=0),a[t]=e[t],r=t-1;r>=1;r-=2)a[r]=0,a[r-1]=0;0===r&&(a[0]=0),o[t]=a}return o},numeric.getDiag=function(e){var t,n=Math.min(e.length,e[0].length),r=Array(n);for(t=n-1;t>=1;--t)r[t]=e[t][t],r[--t]=e[t][t];return 0===t&&(r[0]=e[0][0]),r},numeric.identity=function(e){return numeric.diag(numeric.rep([e],1))},numeric.pointwise=function(e,t,n){void 0===n&&(n="");var r,a,i=[],o=/\[i\]$/,s="",l=!1;for(r=0;r=0;i--) ret[i] = arguments.callee("+e.join(",")+",_s,_k+1);\n return ret;\n}\n"+n+"\nfor(i=_n-1;i!==-1;--i) {\n "+t+"\n}\nreturn ret;",Function.apply(null,i)},numeric.pointwise2=function(e,t,n){void 0===n&&(n="");var r,a,i=[],o=/\[i\]$/,s="",l=!1;for(r=0;r=0;o--)e("object"==typeof t?t[o]:t,"object"==typeof n?n[o]:n,r,a+1,i);else i(t,n)},numeric._biforeach2=function e(t,n,r,a,i){if(a===r.length-1)return i(t,n);var o,s=r[a],l=Array(s);for(o=s-1;o>=0;--o)l[o]=e("object"==typeof t?t[o]:t,"object"==typeof n?n[o]:n,r,a+1,i);return l},numeric._foreach=function e(t,n,r,a){var i;if(r!==n.length-1)for(i=n[r]-1;i>=0;i--)e(t[i],n,r+1,a);else a(t)},numeric._foreach2=function e(t,n,r,a){if(r===n.length-1)return a(t);var i,o=n[r],s=Array(o);for(i=o-1;i>=0;i--)s[i]=e(t[i],n,r+1,a);return s},numeric.ops2={add:"+",sub:"-",mul:"*",div:"/",mod:"%",and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">=",band:"&",bor:"|",bxor:"^",lshift:"<<",rshift:">>",rrshift:">>>"},numeric.opseq={addeq:"+=",subeq:"-=",muleq:"*=",diveq:"/=",modeq:"%=",lshifteq:"<<=",rshifteq:">>=",rrshifteq:">>>=",bandeq:"&=",boreq:"|=",bxoreq:"^="},numeric.mathfuns=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan","isNaN","isFinite"],numeric.mathfuns2=["atan2","pow","max","min"],numeric.ops1={neg:"-",not:"!",bnot:"~",clone:""},numeric.mapreducers={any:["if(xi) return true;","var accum = false;"],all:["if(!xi) return false;","var accum = true;"],sum:["accum += xi;","var accum = 0;"],prod:["accum *= xi;","var accum = 1;"],norm2Squared:["accum += xi*xi;","var accum = 0;"],norminf:["accum = max(accum,abs(xi));","var accum = 0, max = Math.max, abs = Math.abs;"],norm1:["accum += abs(xi)","var accum = 0, abs = Math.abs;"],sup:["accum = max(accum,xi);","var accum = -Infinity, max = Math.max;"],inf:["accum = min(accum,xi);","var accum = Infinity, min = Math.min;"]},function(){var e,t;for(e=0;eh&&(f=i,h=s);for(n=d[f],d[f]=d[o],d[o]=n,a=m[f],m[f]=m[o],m[o]=a,e=n[o],s=o;s!==p;++s)n[s]/=e;for(s=p-1;-1!==s;--s)a[s]/=e;for(i=c-1;-1!==i;--i)if(i!==o){for(t=d[i],r=m[i],e=t[o],s=o+1;s!==p;++s)t[s]-=n[s]*e;for(s=p-1;s>0;--s)r[s]-=a[s]*e,r[--s]-=a[s]*e;0===s&&(r[0]-=a[0]*e)}}return m},numeric.det=function(e){var t=numeric.dim(e);if(2!==t.length||t[0]!==t[1])throw new Error("numeric: det() only works on square matrices");var n,r,a,i,o,s,l,u,c=t[0],p=1,d=numeric.clone(e);for(r=0;rMath.abs(d[a][r])&&(a=n);for(a!==r&&(l=d[a],d[a]=d[r],d[r]=l,p*=-1),i=d[r],n=r+1;n=1;t-=2){for(a=e[t],r=e[t-1],n=s-1;n>=1;--n)(i=l[n])[t]=a[n],i[t-1]=r[n],(i=l[--n])[t]=a[n],i[t-1]=r[n];0===n&&((i=l[0])[t]=a[0],i[t-1]=r[0])}if(0===t){for(r=e[0],n=s-1;n>=1;--n)l[n][0]=r[n],l[--n][0]=r[n];0===n&&(l[0][0]=r[0])}return l},numeric.negtranspose=function(e){var t,n,r,a,i,o=e.length,s=e[0].length,l=Array(s);for(n=0;n=1;t-=2){for(a=e[t],r=e[t-1],n=s-1;n>=1;--n)(i=l[n])[t]=-a[n],i[t-1]=-r[n],(i=l[--n])[t]=-a[n],i[t-1]=-r[n];0===n&&((i=l[0])[t]=-a[0],i[t-1]=-r[0])}if(0===t){for(r=e[0],n=s-1;n>=1;--n)l[n][0]=-r[n],l[--n][0]=-r[n];0===n&&(l[0][0]=-r[0])}return l},numeric._random=function e(t,n){var r,a,i=t[n],o=Array(i);if(n===t.length-1){for(a=Math.random,r=i-1;r>=1;r-=2)o[r]=a(),o[r-1]=a();return 0===r&&(o[0]=a()),o}for(r=i-1;r>=0;r--)o[r]=e(t,n+1);return o},numeric.random=function(e){return numeric._random(e,0)},numeric.norm2=function(e){return Math.sqrt(numeric.norm2Squared(e))},numeric.linspace=function(e,t,n){if(void 0===n&&(n=Math.max(Math.round(t-e)+1,1)),n<2)return 1===n?[e]:[];var r,a=Array(n);for(r=--n;r>=0;r--)a[r]=(r*t+(n-r)*e)/n;return a},numeric.getBlock=function(e,t,n){var r=numeric.dim(e);return function e(a,i){var o,s=t[i],l=n[i]-s,u=Array(l);if(i===r.length-1){for(o=l;o>=0;o--)u[o]=a[o+s];return u}for(o=l;o>=0;o--)u[o]=e(a[o+s],i+1);return u}(e,0)},numeric.setBlock=function(e,t,n,r){var a=numeric.dim(e);return function e(r,i,o){var s,l=t[o],u=n[o]-l;if(o===a.length-1)for(s=u;s>=0;s--)r[s+l]=i[s];for(s=u;s>=0;s--)e(r[s+l],i[s],o+1)}(e,r,0),e},numeric.getRange=function(e,t,n){var r,a,i,o,s=t.length,l=n.length,u=Array(s);for(r=s-1;-1!==r;--r)for(u[r]=Array(l),i=u[r],o=e[t[r]],a=l-1;-1!==a;--a)i[a]=o[n[a]];return u},numeric.blockMatrix=function(e){var t=numeric.dim(e);if(t.length<4)return numeric.blockMatrix([e]);var n,r,a,i,o,s=t[0],l=t[1];for(n=0,r=0,a=0;a=0;i--){for(a=Array(u),s=e[i],o=u-1;o>=3;--o)a[o]=s*t[o],a[--o]=s*t[o],a[--o]=s*t[o],a[--o]=s*t[o];for(;o>=0;)a[o]=s*t[o],--o;c[i]=a}return c},numeric.T=function(e,t){this.x=e,this.y=t},numeric.t=function(e,t){return new numeric.T(e,t)},numeric.Tbinop=function(e,t,n,r,a){var i;if(numeric.indexOf,"string"!=typeof a)for(i in a="",numeric)numeric.hasOwnProperty(i)&&(e.indexOf(i)>=0||t.indexOf(i)>=0||n.indexOf(i)>=0||r.indexOf(i)>=0)&&i.length>1&&(a+="var "+i+" = numeric."+i+";\n");return Function(["y"],"var x = this;\nif(!(y instanceof numeric.T)) { y = new numeric.T(y); }\n"+a+"\nif(x.y) { if(y.y) { return new numeric.T("+r+");\n }\n return new numeric.T("+n+");\n}\nif(y.y) {\n return new numeric.T("+t+");\n}\nreturn new numeric.T("+e+");\n")},numeric.T.prototype.add=numeric.Tbinop("add(x.x,y.x)","add(x.x,y.x),y.y","add(x.x,y.x),x.y","add(x.x,y.x),add(x.y,y.y)"),numeric.T.prototype.sub=numeric.Tbinop("sub(x.x,y.x)","sub(x.x,y.x),neg(y.y)","sub(x.x,y.x),x.y","sub(x.x,y.x),sub(x.y,y.y)"),numeric.T.prototype.mul=numeric.Tbinop("mul(x.x,y.x)","mul(x.x,y.x),mul(x.x,y.y)","mul(x.x,y.x),mul(x.y,y.x)","sub(mul(x.x,y.x),mul(x.y,y.y)),add(mul(x.x,y.y),mul(x.y,y.x))"),numeric.T.prototype.reciprocal=function(){var e=numeric.mul,t=numeric.div;if(this.y){var n=numeric.add(e(this.x,this.x),e(this.y,this.y));return new numeric.T(t(this.x,n),t(numeric.neg(this.y),n))}return new T(t(1,this.x))},numeric.T.prototype.div=function(e){if(e instanceof numeric.T||(e=new numeric.T(e)),e.y)return this.mul(e.reciprocal());var t=numeric.div;return this.y?new numeric.T(t(this.x,e.x),t(this.y,e.x)):new numeric.T(t(this.x,e.x))},numeric.T.prototype.dot=numeric.Tbinop("dot(x.x,y.x)","dot(x.x,y.x),dot(x.x,y.y)","dot(x.x,y.x),dot(x.y,y.x)","sub(dot(x.x,y.x),dot(x.y,y.y)),add(dot(x.x,y.y),dot(x.y,y.x))"),numeric.T.prototype.transpose=function(){var e=numeric.transpose,t=this.x,n=this.y;return n?new numeric.T(e(t),e(n)):new numeric.T(e(t))},numeric.T.prototype.transjugate=function(){var e=numeric.transpose,t=this.x,n=this.y;return n?new numeric.T(e(t),numeric.negtranspose(n)):new numeric.T(e(t))},numeric.Tunop=function(e,t,n){return"string"!=typeof n&&(n=""),Function("var x = this;\n"+n+"\nif(x.y) { "+t+";\n}\n"+e+";\n")},numeric.T.prototype.exp=numeric.Tunop("return new numeric.T(ex)","return new numeric.T(mul(cos(x.y),ex),mul(sin(x.y),ex))","var ex = numeric.exp(x.x), cos = numeric.cos, sin = numeric.sin, mul = numeric.mul;"),numeric.T.prototype.conj=numeric.Tunop("return new numeric.T(x.x);","return new numeric.T(x.x,numeric.neg(x.y));"),numeric.T.prototype.neg=numeric.Tunop("return new numeric.T(neg(x.x));","return new numeric.T(neg(x.x),neg(x.y));","var neg = numeric.neg;"),numeric.T.prototype.sin=numeric.Tunop("return new numeric.T(numeric.sin(x.x))","return x.exp().sub(x.neg().exp()).div(new numeric.T(0,2));"),numeric.T.prototype.cos=numeric.Tunop("return new numeric.T(numeric.cos(x.x))","return x.exp().add(x.neg().exp()).div(2);"),numeric.T.prototype.abs=numeric.Tunop("return new numeric.T(numeric.abs(x.x));","return new numeric.T(numeric.sqrt(numeric.add(mul(x.x,x.x),mul(x.y,x.y))));","var mul = numeric.mul;"),numeric.T.prototype.log=numeric.Tunop("return new numeric.T(numeric.log(x.x));","var theta = new numeric.T(numeric.atan2(x.y,x.x)), r = x.abs();\nreturn new numeric.T(numeric.log(r.x),theta.x);"),numeric.T.prototype.norm2=numeric.Tunop("return numeric.norm2(x.x);","var f = numeric.norm2Squared;\nreturn Math.sqrt(f(x.x)+f(x.y));"),numeric.T.prototype.inv=function(){var e=this;if(void 0===e.y)return new numeric.T(numeric.inv(e.x));var t,n,r,a,i,o,s,l,u,c,p,d,m,f,h,y,b,g,v=e.x.length,T=numeric.identity(v),N=numeric.rep([v,v],0),C=numeric.clone(e.x),A=numeric.clone(e.y);for(u=0;ud&&(p=c,d=m);for(p!==u&&(g=C[u],C[u]=C[p],C[p]=g,g=A[u],A[u]=A[p],A[p]=g,g=T[u],T[u]=T[p],T[p]=g,g=N[u],N[u]=N[p],N[p]=g),t=C[u],n=A[u],i=T[u],o=N[u],f=t[u],h=n[u],c=u+1;c0;u--)for(i=T[u],o=N[u],c=u-1;c>=0;c--)for(s=T[c],l=N[c],f=C[c][u],h=A[c][u],p=v-1;p>=0;p--)y=i[p],b=o[p],s[p]-=f*y-h*b,l[p]-=f*b+h*y;return new numeric.T(T,N)},numeric.T.prototype.get=function(e){var t,n=this.x,r=this.y,a=0,i=e.length;if(r){for(;a=0?1:-1)*numeric.norm2(e);t[0]+=n;var r=numeric.norm2(t);if(0===r)throw new Error("eig: internal error");return numeric.div(t,r)},numeric.toUpperHessenberg=function(e){var t=numeric.dim(e);if(2!==t.length||t[0]!==t[1])throw new Error("numeric: toUpperHessenberg() only works on square matrices");var n,r,a,i,o,s,l,u,c,p,d=t[0],m=numeric.clone(e),f=numeric.identity(d);for(r=0;r0){for(o=numeric.house(i),s=numeric.getBlock(m,[r+1,r],[d-1,d-1]),l=numeric.tensor(o,numeric.dot(o,s)),n=r+1;n=4*l?(x=.5*(u+Math.sqrt(u*u-4*l)),w=.5*(u-Math.sqrt(u*u-4*l)),c=numeric.add(numeric.sub(numeric.dot(c,c),numeric.mul(c,x+w)),numeric.diag(numeric.rep([3],x*w)))):c=numeric.add(numeric.sub(numeric.dot(c,c),numeric.mul(c,u)),numeric.diag(numeric.rep([3],l))),n=[c[0][0],c[1][0],c[2][0]],r=numeric.house(n),m=[e[0],e[1],e[2]],f=numeric.tensor(r,numeric.dot(r,m)),y=0;y<3;y++)for(d=e[y],h=f[y],g=0;g=0?((y=(o-(d=c<0?-.5*(c-w(p)):-.5*(c+w(p))))*(o-d)+s*s)>(b=l*l+(u-d)*(u-d))?(f=(o-d)/(y=w(y)),h=s/y):(f=l/(b=w(b)),h=(u-d)/b),a=new T([[h,-f],[f,h]]),S.setRows(n,i,a.dot(S.getRows(n,i)))):(d=-.5*c,m=.5*w(-p),(y=(o-d)*(o-d)+s*s)>(b=l*l+(u-d)*(u-d))?(f=(o-d)/(y=w(y+m*m)),h=s/y,d=0,m/=y):(f=l/(b=w(b+m*m)),h=(u-d)/b,d=m/b,m=0),a=new T([[h,-f],[f,h]],[[d,m],[m,-d]]),S.setRows(n,i,a.dot(S.getRows(n,i))))}var V=S.dot(e).dot(S.transjugate()),E=(N=e.length,numeric.T.identity(N));for(i=0;i0)for(r=i-1;r>=0;r--){var O=V.get([r,r]),_=V.get([i,i]);numeric.neq(O.x,_.x)||numeric.neq(O.y,_.y)?(d=V.getRow(r).getBlock([r],[i-1]),m=E.getRow(i).getBlock([r],[i-1]),E.set([i,r],V.get([r,i]).neg().sub(d.dot(m)).div(O.sub(_)))):E.setRow(i,E.getRow(r))}for(i=0;i=i.length;)i[i.length]=0;0!==t[r]&&i[r]++}var o=i.length,s=Array(o+1);for(s[0]=0,n=0;n=l){if(a[c]=m[u],0===u)return;++c,s=p[--u],l=d[u]}else 0===r[o=i[n[s]]]?(r[o]=1,p[u]=s,m[++u]=o,s=t[o],d[u]=l=t[o+1]):++s},numeric.ccsLPSolve=function(e,t,n,r,a,i,o){var s=e[0],l=e[1],u=e[2];s.length;var c,p,d,m,f,h,y,b,g,v=t[0],T=t[1],N=t[2];for(p=v[a],d=v[a+1],r.length=0,c=p;ci&&(o=a,i=s);for(N(g[n])=u){if(a[p]=i[f[c]],0===c)return;++p,l=d[--c],u=m[c]}else 0===r[s=n[l]]?(r[s]=1,d[c]=l,f[++c]=s,l=t[s=i[s]],m[c]=u=t[s+1]):++l}},numeric.ccsLPSolve0=function(e,t,n,r,a,i,o,s){var l=e[0],u=e[1],c=e[2];l.length;var p,d,m,f,h,y,b,g,v,T=t[0],N=t[1],C=t[2];for(d=T[a],m=T[a+1],r.length=0,p=d;pi&&(o=a,i=s);for(N(g[C[n]])n[r]&&(n[r]=t.length),t)t.hasOwnProperty(a)&&e(t[a],n,r+1);return n},numeric.sclone=function e(t,n,r){void 0===n&&(n=0),void 0===r&&(r=numeric.sdim(t).length);var a,i=Array(t.length);if(n===r-1){for(a in t)t.hasOwnProperty(a)&&(i[a]=t[a]);return i}for(a in t)t.hasOwnProperty(a)&&(i[a]=e(t[a],n+1,r));return i},numeric.sdiag=function(e){var t,n,r=e.length,a=Array(r);for(t=r-1;t>=1;t-=2)n=t-1,a[t]=[],a[t][t]=e[t],a[n]=[],a[n][n]=e[n];return 0===t&&(a[0]=[],a[0][0]=e[t]),a},numeric.sidentity=function(e){return numeric.sdiag(numeric.rep([e],1))},numeric.stranspose=function(e){var t,n,r,a=[];for(t in e.length,e)if(e.hasOwnProperty(t))for(n in r=e[t])r.hasOwnProperty(n)&&("object"!=typeof a[n]&&(a[n]=[]),a[n][t]=r[n]);return a},numeric.sLUP=function(e,t){throw new Error("The function numeric.sLUP had a bug in it and has been removed. Please use the new numeric.ccsLUP function instead.")},numeric.sdotMM=function(e,t){var n=e.length;t.length;var r,a,i,o,s,l,u,c=numeric.stranspose(t),p=c.length,d=Array(n);for(i=n-1;i>=0;i--){for(u=[],r=e[i],s=p-1;s>=0;s--){for(o in l=0,a=c[s],r)r.hasOwnProperty(o)&&o in a&&(l+=r[o]*a[o]);l&&(u[s]=l)}d[i]=u}return d},numeric.sdotMV=function(e,t){var n,r,a,i,o=e.length,s=Array(o);for(r=o-1;r>=0;r--){for(a in i=0,n=e[r])n.hasOwnProperty(a)&&t[a]&&(i+=n[a]*t[a]);i&&(s[r]=i)}return s},numeric.sdotVM=function(e,t){var n,r,a,i,o=[];for(n in e)if(e.hasOwnProperty(n))for(r in a=t[n],i=e[n],a)a.hasOwnProperty(r)&&(o[r]||(o[r]=0),o[r]+=i*a[r]);return o},numeric.sdotVV=function(e,t){var n,r=0;for(n in e)e[n]&&t[n]&&(r+=e[n]*t[n]);return r},numeric.sdot=function(e,t){var n=numeric.sdim(e).length,r=numeric.sdim(t).length;switch(1e3*n+r){case 0:return e*t;case 1001:return numeric.sdotVV(e,t);case 2001:return numeric.sdotMV(e,t);case 1002:return numeric.sdotVM(e,t);case 2002:return numeric.sdotMM(e,t);default:throw new Error("numeric.sdot not implemented for tensors of order "+n+" and "+r)}},numeric.sscatter=function(e){var t,n,r,a,i=e[0].length,o=e.length,s=[];for(n=i-1;n>=0;--n)if(e[o-1][n]){for(a=s,r=0;r=0;--i)n[i]=[];for(i=a;i>=0;--i)n[i].push(r[i]);n[a+1].push(o)}}else e(o,n,r);return r.length>a&&r.pop(),n},numeric.cLU=function(e){var t,n,r,a,i,o,s=e[0],l=e[1],u=e[2],c=s.length,p=0;for(t=0;tp&&(p=s[t]);p++;var d,m=Array(p),f=Array(p),h=numeric.rep([p],1/0),y=numeric.rep([p],-1/0);for(r=0;ry[t]&&(y[t]=n);for(t=0;ty[t+1]&&(y[t+1]=y[t]);for(t=p-1;t>=1;t--)h[t]=0;d--){for(;u[m]>d;)a[d]-=c[m]*a[u[m]],m--;a[d]/=c[m],m--}return a},numeric.cgrid=function(e,t){"number"==typeof e&&(e=[e,e]);var n,r,a,i=numeric.rep(e,-1);for("function"!=typeof t&&(t="L"===t?function(t,n){return t>=e[0]/2||na&&(a=i[r]);for(a++,n=numeric.rep([a],0),r=0;r1;)a[r=o((t+n)/2)]<=e?t=r:n=r;return this._at(e,t)}i=e.length;var s,l=Array(i);for(s=i-1;-1!==s;--s)l[s]=this.at(e[s]);return l},numeric.Spline.prototype.diff=function(){var e,t,n,r=this.x,a=this.yl,i=this.yr,o=this.kl,s=this.kr,l=a.length,u=o,c=s,p=Array(l),d=Array(l),m=numeric.add,f=numeric.mul,h=numeric.div,y=numeric.sub;for(e=l-1;-1!==e;--e)t=r[e+1]-r[e],n=y(i[e+1],a[e]),p[e]=h(m(f(n,6),f(o[e],-4*t),f(s[e+1],-2*t)),t*t),d[e+1]=h(m(f(n,-6),f(o[e],2*t),f(s[e+1],4*t)),t*t);return new numeric.Spline(r,u,c,p,d)},numeric.Spline.prototype.roots=function(){function e(e){return e*e}var t=[],n=this.x,r=this.yl,a=this.yr,i=this.kl,o=this.kr;"number"==typeof r[0]&&(r=[r],a=[a],i=[i],o=[o]);var s,l,u,c,p,d,m,f,h,y,b,g,v,T,N,C,A,S,x,w,V,E,O,_=r.length,$=n.length-1,D=(t=Array(_),Math.sqrt);for(s=0;s!==_;++s){for(c=r[s],p=a[s],d=i[s],m=o[s],f=[],l=0;l!==$;l++){for(l>0&&p[l]*c[l]<0&&f.push(n[l]),C=n[l+1]-n[l],n[l],b=c[l],g=p[l+1],h=d[l]/C,v=(y=m[l+1]/C)+3*b+2*h-3*g,T=3*(y+h+2*(b-g)),(N=e(h-y+3*(b-g))+12*y*b)<=0?A=(S=v/T)>n[l]&&Sn[l]&&Sn[l]&&x0)V=E,S=x;else{for(var I=0;!((O=(S*E-x*V)/(S-x))<=V||O>=E);)if((w=this._at(O,l))*x>0)E=O,x=w,-1===I&&(S*=.5),I=-1;else{if(!(w*S>0))break;V=O,S=w,1===I&&(x*=.5),I=1}f.push(O),V=A[u+1],S=this._at(V,l)}else f.push(V),V=E,S=x;0===x&&f.push(E)}t[s]=f}return"number"==typeof this.yl[0]?t[0]:t},numeric.spline=function(e,t,n,r){var a,i=e.length,o=[],s=[],l=[],u=numeric.sub,c=numeric.mul,p=numeric.add;for(a=i-2;a>=0;a--)s[a]=e[a+1]-e[a],l[a]=u(t[a+1],t[a]);"string"!=typeof n&&"string"!=typeof r||(n=r="periodic");var d=[[],[],[]];switch(typeof n){case"undefined":o[0]=c(3/(s[0]*s[0]),l[0]),d[0].push(0,0),d[1].push(0,1),d[2].push(2/s[0],1/s[0]);break;case"string":o[0]=p(c(3/(s[i-2]*s[i-2]),l[i-2]),c(3/(s[0]*s[0]),l[0])),d[0].push(0,0,0),d[1].push(i-2,0,1),d[2].push(1/s[i-2],2/s[i-2]+2/s[0],1/s[0]);break;default:o[0]=n,d[0].push(0),d[1].push(0),d[2].push(1)}for(a=1;a20)throw new Error("Numerical gradient fails");if(l[a]=t[a]+v,i=e(l),l[a]=t[a]-v,o=e(l),l[a]=t[a],isNaN(i)||isNaN(o))v/=16;else{if(u[a]=(i-o)/(2*v),c=t[a]-v,p=t[a],d=t[a]+v,m=(i-r)/v,f=(r-o)/v,h=s(y(u[a]),y(r),y(i),y(o),y(c),y(p),y(d),1e-8),!(b(s(y(m-u[a]),y(f-u[a]),y(m-f))/h,v/h)>.001))break;v/=16}}return u},numeric.uncmin=function(e,t,n,r,a,i,o){var s=numeric.gradient;void 0===o&&(o={}),void 0===n&&(n=1e-8),void 0===r&&(r=function(t){return s(e,t)}),void 0===a&&(a=1e3);var l,u,c=(t=numeric.clone(t)).length,p=e(t);if(isNaN(p))throw new Error("uncmin: f(x0) is a NaN!");var d=Math.max,m=numeric.norm2;n=d(n,numeric.epsilon);var f,h,y,b=o.Hinv||numeric.identity(c),g=numeric.dot;numeric.inv;var v,T,N,C,A,S,x,w=numeric.sub,V=numeric.add,E=numeric.tensor,O=numeric.div,_=numeric.mul,$=numeric.all,D=numeric.isFinite,I=numeric.neg,R=0,P="";for(h=r(t);R=.1*S*u||isNaN(l));)S*=.5,++R;if(S*x1;)s[r=a(.5*(t+n))]<=e?t=r:n=r;return this._at(e,t)},numeric.dopri=function(e,t,n,r,a,i,o){void 0===a&&(a=1e-6),void 0===i&&(i=1e3);var s,l,u,c,p,d,m,f,h,y,b,g,v,T=[e],N=[n],C=[r(e,n)],A=[],S=[3/40,9/40],x=[44/45,-56/15,32/9],w=[19372/6561,-25360/2187,64448/6561,-212/729],V=[9017/3168,-355/33,46732/5247,49/176,-5103/18656],E=[35/384,0,500/1113,125/192,-2187/6784,11/84],O=[.10013431883002395,0,.3918321794184259,-.02982460176594817,.05893268337240795,-.04497888809104361,5618549.5/235043384],_=[.2,.3,.8,8/9,1,1],$=[-71/57600,0,71/16695,-71/1920,17253/339200,-22/525,1/40],D=0,I=(t-e)/10,R=0,P=numeric.add,k=numeric.mul,M=Math.min,F=Math.abs,B=numeric.norminf,L=Math.pow,j=numeric.any,U=numeric.lt,z=numeric.and;numeric.sub;var G=new numeric.Dopri(T,N,C,A,-1,"");for("function"==typeof o&&(b=o(e,n));et&&(I=t-e),s=r(e+_[0]*I,P(n,k(.2*I,C[D]))),l=r(e+_[1]*I,P(P(n,k(S[0]*I,C[D])),k(S[1]*I,s))),u=r(e+_[2]*I,P(P(P(n,k(x[0]*I,C[D])),k(x[1]*I,s)),k(x[2]*I,l))),c=r(e+_[3]*I,P(P(P(P(n,k(w[0]*I,C[D])),k(w[1]*I,s)),k(w[2]*I,l)),k(w[3]*I,u))),p=r(e+_[4]*I,P(P(P(P(P(n,k(V[0]*I,C[D])),k(V[1]*I,s)),k(V[2]*I,l)),k(V[3]*I,u)),k(V[4]*I,c))),d=r(e+I,h=P(P(P(P(P(n,k(C[D],I*E[0])),k(l,I*E[2])),k(u,I*E[3])),k(c,I*E[4])),k(p,I*E[5]))),(y="number"==typeof(m=P(P(P(P(P(k(C[D],I*$[0]),k(l,I*$[2])),k(u,I*$[3])),k(c,I*$[4])),k(p,I*$[5])),k(d,I*$[6])))?F(m):B(m))>a){if(e+(I=.2*I*L(a/y,.25))===e){G.msg="Step size became too small";break}}else{if(A[D]=P(P(P(P(P(P(n,k(C[D],I*O[0])),k(l,I*O[2])),k(u,I*O[3])),k(c,I*O[4])),k(p,I*O[5])),k(d,I*O[6])),T[++D]=e+I,N[D]=h,C[D]=d,"function"==typeof o){var H,q,W=e,K=e+.5*I;if(g=o(K,A[D-1]),j(v=z(U(b,0),U(0,g)))||(W=K,b=g,g=o(K=e+I,h),v=z(U(b,0),U(0,g))),j(v)){for(var X,Z,Y=0,J=1,Q=1;;){if("number"==typeof b)q=(Q*g*W-J*b*K)/(Q*g-J*b);else for(q=K,f=b.length-1;-1!==f;--f)b[f]<0&&g[f]>0&&(q=M(q,(Q*g[f]*W-J*b[f]*K)/(Q*g[f]-J*b[f])));if(q<=W||q>=K)break;Z=o(q,H=G._at(q,D-1)),j(X=z(U(b,0),U(0,Z)))?(K=q,g=Z,v=X,Q=1,-1===Y?J*=.5:J=1,Y=-1):(W=q,b=Z,J=1,1===Y?Q*=.5:Q=1,Y=1)}return h=G._at(.5*(e+q),D-1),G.f[D]=r(q,H),G.x[D]=q,G.y[D]=H,G.ymid[D-1]=h,G.events=v,G.iterations=R,G}}e+=I,n=h,b=g,I=M(.8*I*L(a/y,.25),4*I)}return G.iterations=R,G},numeric.LU=function(e,t){t=t||!1;var n,r,a,i,o,s,l,u,c,p=Math.abs,d=e.length,m=d-1,f=new Array(d);for(t||(e=numeric.clone(e)),a=0;a=0;--n){for(i=s[n],r=n+1;rP)&&(b=P),E=m(e,u(b,x)),N=p(R,w),D=f-1;-1!==D;--D)N[D][D]+=1;I=O(N,d(E,b),!0);var k=d(_,p(t,I)),M=1;for(D=h-1;-1!==D;--D)k[D]<0&&(M=C(M,-.999*k[D]));if(l=c(i,u(I,M)),!A(S(_=c(n,p(t,l)),0)))return{solution:i,message:"",iterations:V};if(i=l,b=0);if(y)return{solution:l,message:"Unbounded",iterations:V}}return{solution:i,message:"maximum iteration count exceeded",iterations:V}},numeric._solveLP=function(e,t,n,r,a){var i=e.length,o=n.length;numeric.sum,numeric.log,numeric.mul;var s=numeric.sub,l=numeric.dot;numeric.div,numeric.add;var u=numeric.rep([i],0).concat([1]),c=numeric.rep([o,1],-1),p=numeric.blockMatrix([[t,c]]),d=n,m=numeric.rep([i],0).concat(Math.max(0,numeric.sup(numeric.neg(n)))+1),f=numeric.__solveLP(u,p,d,r,a,m,!1),h=numeric.clone(f.solution);if(h.length=i,numeric.inf(s(n,l(t,h)))<0)return{solution:NaN,message:"Infeasible",iterations:f.iterations};var y=numeric.__solveLP(e,t,n,r,a-f.iterations,h,!0);return y.iterations+=f.iterations,y},numeric.solveLP=function(e,t,n,r,a,i,o){if(void 0===o&&(o=1e3),void 0===i&&(i=numeric.epsilon),void 0===r)return numeric._solveLP(e,t,n,i,o);var s,l=r.length,u=r[0].length,c=t.length,p=numeric.echelonize(r),d=numeric.rep([u],0),m=p.P,f=[];for(s=m.length-1;-1!==s;--s)d[m[s]]=1;for(s=u-1;-1!==s;--s)0===d[s]&&f.push(s);var h=numeric.getRange,y=numeric.linspace(0,l-1),b=numeric.linspace(0,c-1),g=h(r,y,f),v=h(t,b,m),T=h(t,b,f),N=numeric.dot,C=numeric.sub,A=N(v,p.I),S=C(T,N(A,g)),x=C(n,N(A,a)),w=Array(m.length),V=Array(f.length);for(s=m.length-1;-1!==s;--s)w[s]=e[m[s]];for(s=f.length-1;-1!==s;--s)V[s]=e[f[s]];var E=C(V,N(w,N(p.I,g))),O=numeric._solveLP(E,S,x,i,o),_=O.solution;if(_!=_)return O;var $=N(p.I,C(a,N(g,_))),D=Array(e.length);for(s=m.length-1;-1!==s;--s)D[m[s]]=$[s];for(s=f.length-1;-1!==s;--s)D[f[s]]=_[s];return{solution:D,message:O.message,iterations:O.iterations}},numeric.MPStoLP=function(e){e instanceof String&&e.split("\n");var t,n,r,a,i=0,o=["Initial state","NAME","ROWS","COLUMNS","RHS","BOUNDS","ENDATA"],s=e.length,l=0,u={},c=[],p=0,d={},m=0,f=[],h=[],y=[];function b(n){throw new Error("MPStoLP: "+n+"\nLine "+t+": "+e[t]+"\nCurrent state: "+o[i]+"\n")}for(t=0;t=i;)e/=2,t/=2,r>>>=1;return(e+r)/t},r},o=t.pow(n,6),a=t.pow(2,a),i=2*a,u(t.random(),e)}([],numeric.seedrandom,256,0,52),function(e){function t(e){if("object"!=typeof e)return e;var n,r=[],a=e.length;for(n=0;nc)f[g]=$;else if(f[g]=-Math.abs($),$>0){for(b=1;b<=r;b+=1)o[b][y]=-o[b][y];s[y]=-s[y]}}for(y=1;y<=d;y+=1)f[x+p[y]]=0;for(V=0,_=0,y=1;y<=u;y+=1)f[x+y]<_*f[O+y]&&(V=y,_=f[x+y]/f[O+y]);return 0===V?999:0}function G(){for(y=1;y<=r;y+=1){for($=0,b=1;b<=r;b+=1)$+=e[b][y]*o[b][V];f[y]=$}for(v=C,y=1;y<=r;y+=1)f[v+y]=0;for(b=d+1;b<=r;b+=1)for(y=1;y<=r;y+=1)f[v+y]=f[v+y]+e[y][b]*f[b];for(M=!0,y=d;y>=1;y-=1){for($=f[y],v=(g=S+y*(y+3)/2)-y,b=y+1;b<=d;b+=1)$-=f[g]*f[A+b],g+=b;if($/=f[v],f[A+y]=$,p[y]c)f[x+V]=$;else if(f[x+V]=-Math.abs($),$>0){for(b=1;b<=r;b+=1)o[b][V]=-o[b][V];s[V]=-s[V]}return 700}for(p[d+=1]=V,g=S+(d-1)*d/2+1,y=1;y<=d-1;y+=1)f[g]=f[y],g+=1;if(d===r)f[g]=f[r];else{for(y=r;y>=d+1&&0!==f[y]&&(R=Math.max(Math.abs(f[y-1]),Math.abs(f[y])),P=Math.min(Math.abs(f[y-1]),Math.abs(f[y])),_=f[y-1]>=0?Math.abs(R*Math.sqrt(1+P*P/(R*R))):-Math.abs(R*Math.sqrt(1+P*P/(R*R))),R=f[y-1]/_,P=f[y]/_,1!==R);y-=1)if(0===R)for(f[y-1]=P*_,b=1;b<=r;b+=1)_=e[b][y-1],e[b][y-1]=e[b][y],e[b][y]=_;else for(f[y-1]=_,k=P/(1+R),b=1;b<=r;b+=1)_=R*e[b][y-1]+P*e[b][y],e[b][y]=k*(e[b][y-1]+_)-e[b][y],e[b][y-1]=_;f[g]=f[d]}return 0}function H(){if(0===f[v=(g=S+N*(N+1)/2+1)+N])return 798;if(R=Math.max(Math.abs(f[v-1]),Math.abs(f[v])),P=Math.min(Math.abs(f[v-1]),Math.abs(f[v])),_=f[v-1]>=0?Math.abs(R*Math.sqrt(1+P*P/(R*R))):-Math.abs(R*Math.sqrt(1+P*P/(R*R))),R=f[v-1]/_,P=f[v]/_,1===R)return 798;if(0===R){for(y=N+1;y<=d;y+=1)_=f[v-1],f[v-1]=f[v],f[v]=_,v+=y;for(y=1;y<=r;y+=1)_=e[y][N],e[y][N]=e[y][N+1],e[y][N+1]=_}else{for(k=P/(1+R),y=N+1;y<=d;y+=1)_=R*f[v-1]+P*f[v],f[v]=k*(f[v-1]+_)-f[v],f[v-1]=_,v+=y;for(y=1;y<=r;y+=1)_=R*e[y][N]+P*e[y][N+1],e[y][N+1]=k*(e[y][N]+_)-e[y][N+1],e[y][N]=_}return 0}function q(){for(v=g-N,y=1;y<=N;y+=1)f[v]=f[g],g+=1,v+=1;return f[w+N]=f[w+N+1],p[N]=p[N+1],(N+=1)(t=Math.abs(t))?e*Math.sqrt(1+t*t/e/e):0==t?e:t*Math.sqrt(1+e*e/t/t)}var y=0,b=0,g=0,v=0,T=0,N=0,C=0;for(i=0;i=0&&(b=-b),g=y*b-C,u[i][i]=y-b,o=l;o=0&&(b=-b),g=y*b-C,u[i][i+1]=y-b,o=l;ov&&(v=T)}for(i=p-1;-1!=i;i+=-1){if(0!=b){for(g=b*u[i][i+1],o=l;o=49)throw"Error: no convergence.";for(v=m[l],b=h(y=(((T=m[s-1])-N)*(T+N)+((b=d[s-1])-(g=d[s]))*(b+g))/(2*g*T),1),y=y<0?((v-N)*(v+N)+g*(T/(y-b)-g))/v:((v-N)*(v+N)+g*(T/(y+b)-g))/v,a=1,C=1,i=l+1;i=0;o--)if(m[o]=0&&n<=MAX_ARRAY_INDEX}}function shallowProperty(e){return function(t){return null==t?void 0:t[e]}}var getByteLength=shallowProperty("byteLength"),isBufferLike=createSizePropertyCheck(getByteLength),typedArrayPattern=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;function isTypedArray(e){return nativeIsView?nativeIsView(e)&&!isDataView$1(e):isBufferLike(e)&&typedArrayPattern.test(toString$1.call(e))}var isTypedArray$1=supportsArrayBuffer?isTypedArray:constant(!1),getLength=shallowProperty("length");function emulatedSet(e){for(var t={},n=e.length,r=0;r":">",'"':""","'":"'","`":"`"},escape=createEscaper(escapeMap),unescapeMap=invert(escapeMap),unescape=createEscaper(unescapeMap),templateSettings=_$1.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},noMatch=/(.)^/,escapes={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},escapeRegExp=/\\|'|\r|\n|\u2028|\u2029/g;function escapeChar(e){return"\\"+escapes[e]}var bareIdentifier=/^\s*(\w|\$)+\s*$/;function template(e,t,n){!t&&n&&(t=n),t=defaults({},t,_$1.templateSettings);var r=RegExp([(t.escape||noMatch).source,(t.interpolate||noMatch).source,(t.evaluate||noMatch).source].join("|")+"|$","g"),a=0,i="__p+='";e.replace(r,(function(t,n,r,o,s){return i+=e.slice(a,s).replace(escapeRegExp,escapeChar),a=s+t.length,n?i+="'+\n((__t=("+n+"))==null?'':_.escape(__t))+\n'":r?i+="'+\n((__t=("+r+"))==null?'':__t)+\n'":o&&(i+="';\n"+o+"\n__p+='"),t})),i+="';\n";var o,s=t.variable;if(s){if(!bareIdentifier.test(s))throw new Error("variable is not a bare identifier: "+s)}else i="with(obj||{}){\n"+i+"}\n",s="obj";i="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{o=new Function(s,"_",i)}catch(e){throw e.source=i,e}var l=function(e){return o.call(this,e,_$1)};return l.source="function("+s+"){\n"+i+"}",l}function result(e,t,n){var r=(t=toPath(t)).length;if(!r)return isFunction$1(n)?n.call(e):n;for(var a=0;a1)flatten$2(s,t-1,n,r),a=r.length;else for(var l=0,u=s.length;lt?(r&&(clearTimeout(r),r=null),s=u,o=e.apply(a,i),r||(a=i=null)):r||!1===n.trailing||(r=setTimeout(l,c)),o};return u.cancel=function(){clearTimeout(r),s=0,r=a=i=null},u}function debounce(e,t,n){var r,a,i,o,s,l=function(){var u=now()-a;t>u?r=setTimeout(l,t-u):(r=null,n||(o=e.apply(s,i)),r||(i=s=null))},u=restArguments((function(u){return s=this,i=u,a=now(),r||(r=setTimeout(l,t),n&&(o=e.apply(s,i))),o}));return u.cancel=function(){clearTimeout(r),r=i=s=null},u}function wrap(e,t){return partial(t,e)}function negate(e){return function(){return!e.apply(this,arguments)}}function compose(){var e=arguments,t=e.length-1;return function(){for(var n=t,r=e[t].apply(this,arguments);n--;)r=e[n].call(this,r);return r}}function after(e,t){return function(){if(--e<1)return t.apply(this,arguments)}}function before(e,t){var n;return function(){return--e>0&&(n=t.apply(this,arguments)),e<=1&&(t=null),n}}var once$1=partial(before,2);function findKey(e,t,n){t=cb(t,n);for(var r,a=keys(e),i=0,o=a.length;i0?0:a-1;i>=0&&i0?o=i>=0?i:Math.max(i+s,o):s=i>=0?Math.min(i+1,s):i+s+1;else if(n&&i&&s)return r[i=n(r,a)]===a?i:-1;if(a!=a)return(i=t(slice.call(r,o,s),isNaN$1))>=0?i+o:-1;for(i=e>0?o:s-1;i>=0&&i0?0:o-1;for(a||(r=t[i?i[s]:s],s+=e);s>=0&&s=3;return t(e,optimizeCb(n,a,4),r,i)}}var reduce$1=createReduce(1),reduceRight=createReduce(-1);function filter(e,t,n){var r=[];return t=cb(t,n),each(e,(function(e,n,a){t(e,n,a)&&r.push(e)})),r}function reject(e,t,n){return filter(e,negate(cb(t)),n)}function every(e,t,n){t=cb(t,n);for(var r=!isArrayLike(e)&&keys(e),a=(r||e).length,i=0;i=0}var invoke=restArguments((function(e,t,n){var r,a;return isFunction$1(t)?a=t:(t=toPath(t),r=t.slice(0,-1),t=t[t.length-1]),map(e,(function(e){var i=a;if(!i){if(r&&r.length&&(e=deepGet(e,r)),null==e)return;i=e[t]}return null==i?i:i.apply(e,n)}))}));function pluck(e,t){return map(e,property(t))}function where(e,t){return filter(e,matcher(t))}function max(e,t,n){var r,a,i=-1/0,o=-1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var s=0,l=(e=isArrayLike(e)?e:values(e)).length;si&&(i=r);else t=cb(t,n),each(e,(function(e,n,r){((a=t(e,n,r))>o||a===-1/0&&i===-1/0)&&(i=e,o=a)}));return i}function min(e,t,n){var r,a,i=1/0,o=1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var s=0,l=(e=isArrayLike(e)?e:values(e)).length;sr||void 0===n)return 1;if(n1&&(r=optimizeCb(r,t[1])),t=allKeys(e)):(r=keyInObj,t=flatten$2(t,!1,!1),e=Object(e));for(var a=0,i=t.length;a1&&(n=t[1])):(t=map(flatten$2(t,!1,!1),String),r=function(e,n){return!contains(t,n)}),pick(e,r,n)}));function initial(e,t,n){return slice.call(e,0,Math.max(0,e.length-(null==t||n?1:t)))}function first(e,t,n){return null==e||e.length<1?null==t||n?void 0:[]:null==t||n?e[0]:initial(e,e.length-t)}function rest(e,t,n){return slice.call(e,null==t||n?1:t)}function last(e,t,n){return null==e||e.length<1?null==t||n?void 0:[]:null==t||n?e[e.length-1]:rest(e,Math.max(0,e.length-t))}function compact(e){return filter(e,Boolean)}function flatten$1(e,t){return flatten$2(e,t,!1)}var difference=restArguments((function(e,t){return t=flatten$2(t,!0,!0),filter(e,(function(e){return!contains(t,e)}))})),without=restArguments((function(e,t){return difference(e,t)}));function uniq(e,t,n,r){isBoolean(t)||(r=n,n=t,t=!1),null!=n&&(n=cb(n,r));for(var a=[],i=[],o=0,s=getLength(e);or&&(r=n)):(n>r&&(r=n),r*=i),Math.abs(e-t)<=r}return e===t}var i=e[0],o=e.slice(1),s=t[0],l=t.slice(1);return i===s&&(o.length===l.length&&(n>0&&!r&&"^"===i?!!equal(o[0],l[0],{allowed_error_in_numbers:n,include_error_in_number_exponents:r,allowed_error_is_absolute:a})&&equal(o[1],l[1]):_.every(_.zip(o,l),(function(e){return equal(e[0],e[1],{allowed_error_in_numbers:n,include_error_in_number_exponents:r,allowed_error_is_absolute:a})}))))},match$2=function(e,t,n){var r=!1;void 0===n?n={}:n.allow_extended_match&&(r=!0,delete(n=Object.assign({},n)).allow_extended_match);var a=n.variables;if(void 0===a){a={};let e=variables(t);for(let t=0;tObject())),o=n.length,s=!1;function l(u,c,p){let d,m=1,f=1;if((is_associative$1[e]||["tuple","vector"].includes(e))&&(m=u.length-(o-c-1),f=u.length),void 0!==r.max_group&&(m=r.max_group1?[e].concat(o):o[0],s=match$2(o,n[c],r),i[c][a]=s}if(!s)continue;if(!_.every(_.intersection(Object.keys(p),Object.keys(s)),(function(e){return equal(p[e],s[e])})))continue;let d=Object.assign({},s);Object.assign(d,p);let m=u.filter((e=>!a.includes(e)));if(c===o-1)return{matches:d,skipped:m.reduce((function(e,n){return e.concat([t[n]])}),[])};let f=l(m,c+1,d);if(f)return f}return!1}r.allow_permutations&&("*"===e?s=![...t,...n].some((e=>["tuple","list","vector","interval","set","array","matrix"].includes(e[0]))):"+"!==e&&"="!==e&&"and"!==e&&"or"!==e&&"ne"!==e&&"union"!==e&&"intersect"!==e||(s=!0));var u={},c=[...Array(t.length).keys()];if(s){let e=l(c,0,{});return!!e&&(u=e.matches,e.skipped.length>0&&(u._skipped=e.skipped),u)}{let e,n=a?t.length-o:0,r=[];for(let a=0;a<=n&&(e=l(c,0,{}),!e);a++)c=c.slice(1),r.push(t[a]);return!!e&&(u=e.matches,e.skipped.length>0&&(u._skipped=e.skipped),r.length>0&&(u._skipped_before=r),u)}}function matchImplicitIdentity(e,t,n){var r=t[0],a=t.slice(1);if("+"!==r&&"*"!==r&&"^"!==r)return!1;var i=[];for(let e=0;e0;n--){r=a;for(let e=0;e0||a.length>0)&&(Array.isArray(e)&&(e=e[0]===n[0]?e.slice(1):[e]),e=[n[0]].concat(o,e,a)),i.evaluate_numbers&&(e=evaluate_numbers(e,{max_digits:i.max_digits})),e}return e}))}if(equal(r,a))return a}return a};var math=math$1;const operators$2={"+":function(e){return 1===e.length?e[0]:new math.OperatorNode("+","add",e)},"*":function(e){return new math.OperatorNode("*","multiply",e)},"/":function(e){return new math.OperatorNode("/","divide",e)},"-":function(e){return new math.OperatorNode("-","unaryMinus",[e[0]])},"^":function(e){return new math.OperatorNode("^","pow",e)},vector:function(e){return new math.ArrayNode(e)},and:function(e){return new math.OperatorNode("and","and",e)},or:function(e){return new math.OperatorNode("or","or",e)},not:function(e){return new math.OperatorNode("not","not",[e[0]])},"<":function(e){return new math.OperatorNode("<","smaller",e)},">":function(e){return new math.OperatorNode(">","larger",e)},le:function(e){return new math.OperatorNode("<=","smallerEq",e)},ge:function(e){return new math.OperatorNode(">=","largerEq",e)},ne:function(e){return new math.OperatorNode("!=","unequal",e)}};class astToMathjs$1{constructor({mathjs:e=null}={}){e&&(math=e)}convert(e){if("number"==typeof e)return Number.isFinite(e)?new math.ConstantNode(e):Number.isNaN(e)?new math.SymbolNode("NaN"):e<0?operators$2["-"]([new math.SymbolNode("Infinity")]):new math.SymbolNode("Infinity");if("string"==typeof e)return new math.SymbolNode(e);if("boolean"==typeof e)throw Error("no support for boolean");if(!Array.isArray(e))throw Error("Invalid ast");const t=e[0],n=e.slice(1);if("apply"===t){if("string"!=typeof n[0])throw Error("Non string functions not implemented for conversion to mathjs");if("factorial"===n[0])return new math.OperatorNode("!","factorial",[this.convert(n[1])]);const e=new math.SymbolNode(n[0]),t=n[1];let r;return r="tuple"===t[0]?t.slice(1).map(function(e,t){return this.convert(e)}.bind(this)):[this.convert(t)],new math.FunctionNode(e,r)}if("lts"===t||"gts"===t){const e=n[0],r=n[1];if("tuple"!==e[0]||"tuple"!==r[0])throw new Error("Badly formed ast");const a=e.slice(1).map(function(e,t){return this.convert(e)}.bind(this));let i=[];for(let n=1;n","larger",a.slice(n-1,n+1))):"lts"===t?i.push(new math.OperatorNode("<=","smallerEq",a.slice(n-1,n+1))):i.push(new math.OperatorNode(">=","largerEq",a.slice(n-1,n+1)));let o=new math.OperatorNode("and","and",i.slice(0,2));for(let e=2;e=","largerEq",[e,o])):l.push(new math.OperatorNode(">","larger",[e,o])),i[2]?l.push(new math.OperatorNode("<=","smallerEq",[e,s])):l.push(new math.OperatorNode("<","smaller",[e,s]));let u=new math.OperatorNode("and","and",l);return"notin"!==t&&"notni"!==t||(u=new math.OperatorNode("not","not",[u])),u}if("subset"===t||"notsubset"===t||"superset"===t||"notsuperset"===t){let e,r;if("subset"===t||"notsubset"===t?(r=n[0],e=n[1]):(r=n[1],e=n[0]),"interval"!==r[0]||"interval"!==e[0])throw Error("Set containment of non-intervals not implemented for conversion to mathjs");let a=r[1],i=r[2],o=e[1],s=e[2];if("tuple"!==a[0]||"tuple"!==i[0]||"tuple"!==o[0]||"tuple"!==s[0])throw Error("Badly formed ast");let l=this.convert(a[1]),u=this.convert(a[2]),c=this.convert(o[1]),p=this.convert(o[2]),d=[];i[1]&&!s[1]?d.push(new math.OperatorNode(">","larger",[l,c])):d.push(new math.OperatorNode(">=","largerEq",[l,c])),i[2]&&!s[2]?d.push(new math.OperatorNode("<","smaller",[u,p])):d.push(new math.OperatorNode("<=","smallerEq",[u,p]));let m=new math.OperatorNode("and","and",d);return"notsubset"!==t&&"notsuperset"!==t||(m=new math.OperatorNode("not","not",[m])),m}if("matrix"===t){let e=n[0],t=e[1],r=e[2],a=n[1];if(!Number.isInteger(t)||!Number.isInteger(r))throw Error("Matrix must have integer dimensions");let i=[];for(let e=1;e<=t;e++){let t=[];for(let n=1;n<=r;n++)t.push(this.convert(a[e][n]));i.push(new math.ArrayNode(t))}return new math.ArrayNode(i)}if(t in operators$2)return operators$2[t](n.map(function(e,t){return this.convert(e)}.bind(this)));throw Error("Operator "+t+" not implemented for conversion to mathjs")}}var function_normalizations={ln:"log",arccos:"acos",arccosh:"acosh",arcsin:"asin",arcsinh:"asinh",arctan:"atan",arctanh:"atanh",arcsec:"asec",arcsech:"asech",arccsc:"acsc",arccsch:"acsch",arccot:"acot",arccoth:"acoth",cosec:"csc"};function normalize_function_names(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if("apply"===n){if("sqrt"===r[0])return["^",normalize_function_names(r[1]),.5];var a=normalize_function_names_sub(r[0]);a=["apply",a];var i=r.slice(1).map((function(e){return normalize_function_names(e)}));return i=i.length>1?["tuple"].concat(i):i[0],a.push(i),a}return"^"===n&&"e"===r[0]&&math$1.define_e?["apply","exp",normalize_function_names(r[1])]:[n].concat(r.map((function(e){return normalize_function_names(e)})))}function normalize_function_names_sub(e){if("string"==typeof e)return e in function_normalizations?function_normalizations[e]:e;if(!Array.isArray(e))return e;var t=e[0],n=e.slice(1);return[t].concat(n.map((function(e){return normalize_function_names_sub(e)})))}function normalize_applied_functions(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if("apply"===n){let e=strip_function_names(r[0]),t=["apply",e.tree,r[1]];for(let n=0;n2&&(r=unflattenRight(r),o=r.slice(1)),simple_assumption_combination(i,is_integer_ast(e,o[0],n),is_integer_ast(e,o[1],n))}if(Array.isArray(e)){let r;r=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let a=e[0],i=e.slice(1);if("-"===a)return is_integer_ast(i[0],r,n);if("*"===a)return!!i.every((function(e){return is_integer_ast(e,r,n)}))||void 0;if("^"===a){let e=is_nonzero_ast(i[0],r,n);if(e){if(!1===is_nonzero_ast(i[1],r,n))return i[0]!==1/0&&i[0]!==-1/0}else{if(Number.isNaN(i[0]))return!1;if(!is_positive_ast(i[1],r,!0,n))return;if(!1===e)return!0}let t=is_integer_ast(i[0],r,n),a=is_integer_ast(i[1],r,n);if(!t)return t;if(!a)return;return!!is_positive_ast(i[1],r,!1,n)||void 0}if("+"===a){let e=0;for(let t=0;t0)return;e+=1}if(void 0===a)return}return 0===e}if("apply"===a)return!!(functions.C.Z&&functions.C.Z.includes(i[0])&&is_complex_ast(i[1],r,n))||!!(functions.R.Z&&functions.R.Z.includes(i[0])&&is_real_ast(i[1],r,n))||!!(functions.nonzeroC.Z&&functions.nonzeroC.Z.includes(i[0])&&is_nonzero_ast(i[1],r,n)&&is_complex_ast(i[1],r,n))||!!(functions.nonneg.Z&&functions.nonneg.Z.includes(i[0])&&is_positive_ast(i[1],r,!1,n))||!!(functions.pos.Z&&functions.pos.Z.includes(i[0])&&is_positive_ast(i[1],r,!0,n))||void 0;if("/"===a||"prime"===a)return;return!1}return!1}function is_real_ast(e,t,n){if("object"!=typeof t&&(t=[]),void 0===n&&(n=t),"number"==typeof e)return Number.isFinite(e);var r=evaluate_to_constant(e);if(null!==r)return"number"==typeof r&&Number.isFinite(r);if("string"==typeof e){let r;if(r=Array.isArray(t)?t:t.get_assumptions(e),!Array.isArray(r))return;let a=r,i=r[0],o=r.slice(1),s=!1;for(;"not"===i;){if(s=!s,r=o[0],!Array.isArray(r))return;i=r[0],o=r.slice(1)}if("in"===i&&o[0]===e&&"R"===o[1])return negate_adjust(!0,s);if("notin"===i&&o[0]===e&&"R"===o[1])return negate_adjust(!1,s);if(!1===s){if("in"===i&&o[0]===e&&"Z"===o[1])return!0}else if("notin"===i&&o[0]===e&&"Z"===o[1])return!0;if("<"===i||"le"===i){let t=variables(r),n=functions$2(r);if(-1!==t.indexOf(e)&&0===n.length)return!0}if("="===i&&!s||"ne"===i&&s){let t=narrow_assumptions(a,n);if(o[0]===e)return is_real_ast(o[1],t);if(o[1]===e)return is_real_ast(o[0],t)}if("and"!==i&&"or"!==i)return;if(s)return;return o.length>2&&(r=unflattenRight(r),o=r.slice(1)),simple_assumption_combination(i,is_real_ast(e,o[0],n),is_real_ast(e,o[1],n))}if(Array.isArray(e)){let r;r=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let a=e[0],i=e.slice(1);if("-"===a)return is_real_ast(i[0],r,n);if("*"===a||"+"===a){if(i.length>2&&(i=(e=unflattenRight(e)).slice(1)),"*"===a&&(!1===is_nonzero_ast(i[0],r,n)||!1===is_nonzero_ast(i[1],r,n)))return!0;let t=is_real_ast(i[0],r,n),o=is_real_ast(i[1],r,n);return!(!t||!o)||!(t&&!1===o||o&&!1===t)&&void 0}if("^"===a){let e=is_nonzero_ast(i[0],r,n),t=is_positive_ast(i[1],r,!0,n);if(e){if(!1===is_nonzero_ast(i[1],r,n))return i[0]!==1/0&&i[0]!==-1/0}else{if(Number.isNaN(i[0]))return!1;if(!t)return;if(!1===e)return!0}let a=is_real_ast(i[0],r,n),o=is_real_ast(i[1],r,n);if(!a||!o)return;return is_positive_ast(i[0],r,!1,n)?!!is_positive_ast(i[0],r,!0,n)||!!t||void 0:!!is_integer_ast(i[1],r,n)||void 0}if("/"===a){if(!is_nonzero_ast(i[1],r,n))return;if(!1===is_nonzero_ast(i[0],r,n))return!0;if(!is_real_ast(i[0],r,n)||!is_real_ast(i[1],r,n))return;return!0}if("apply"===a)return!!(functions.C.R&&functions.C.R.includes(i[0])&&is_complex_ast(i[1],r,n))||!!(functions.R.R&&functions.R.R.includes(i[0])&&is_real_ast(i[1],r,n))||!!(functions.nonzeroC.R&&functions.nonzeroC.R.includes(i[0])&&is_nonzero_ast(i[1],r,n)&&is_complex_ast(i[1],r,n))||!!(functions.nonneg.R&&functions.nonneg.R.includes(i[0])&&is_positive_ast(i[1],r,!1,n))||!!(functions.pos.R&&functions.pos.R.includes(i[0])&&is_positive_ast(i[1],r,!0,n))||void 0;if("prime"===a)return;return!1}return!1}function is_complex_ast(e,t,n){if("object"!=typeof t&&(t=[]),void 0===n&&(n=t),"number"==typeof e)return Number.isFinite(e);var r=evaluate_to_constant(e);if(null!==r)return"number"==typeof r?Number.isFinite(r):!(void 0===r.re||!Number.isFinite(r.re)||void 0===r.im||!Number.isFinite(r.im));if("string"==typeof e){let r;if(r=Array.isArray(t)?t:t.get_assumptions(e),!Array.isArray(r))return;let a=r,i=r[0],o=r.slice(1),s=!1;for(;"not"===i;){if(s=!s,r=o[0],!Array.isArray(r))return;i=r[0],o=r.slice(1)}if("in"===i&&o[0]===e&&"C"===o[1])return negate_adjust(!0,s);if("notin"===i&&o[0]===e&&"C"===o[1])return negate_adjust(!1,s);if(!1===s){if("in"===i){if(o[0]===e&&"Z"===o[1])return!0;if(o[0]===e&&"R"===o[1])return!0}}else if("notin"===i){if(o[0]===e&&"Z"===o[1])return!0;if(o[0]===e&&"R"===o[1])return!0}if("<"===i||"le"===i){let t=variables(r),n=functions$2(r);if(-1!==t.indexOf(e)&&0===n.length)return!0}if("="===i&&!s||"ne"===i&&s){let t=narrow_assumptions(a,n);if(o[0]===e)return is_complex_ast(o[1],t);if(o[1]===e)return is_complex_ast(o[0],t)}if("and"!==i&&"or"!==i)return;if(s)return;return o.length>2&&(r=unflattenRight(r),o=r.slice(1)),simple_assumption_combination(i,is_complex_ast(e,o[0],n),is_complex_ast(e,o[1],n))}if(Array.isArray(e)){let r;r=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let a=e[0],i=e.slice(1);if("-"===a)return is_complex_ast(i[0],r,n);if("*"===a||"+"===a)return"*"===a&&!i.every((e=>!1!==is_nonzero_ast(e,r,n)))||(!!i.every((e=>is_complex_ast(e,r,n)))||void 0);if("^"===a){let e=is_nonzero_ast(i[0],r,n),t=is_positive_ast(i[1],r,!0,n);if(e){if(!1===is_nonzero_ast(i[1],r,n))return i[0]!==1/0&&i[0]!==-1/0}else{if(Number.isNaN(i[0]))return!1;if(!t)return;if(!1===e)return!0}let a=is_complex_ast(i[0],r,n),o=is_complex_ast(i[1],r,n);return!(!a||!o)||void 0}if("/"===a){if(!is_nonzero_ast(i[1],r,n))return;if(!1===is_nonzero_ast(i[0],r,n))return!0;if(!is_complex_ast(i[0],r,n)||!is_complex_ast(i[1],r,n))return;return!0}if("apply"===a)return!!(functions.C.C&&functions.C.C.includes(i[0])&&is_complex_ast(i[1],r,n))||!!(functions.R.C&&functions.R.C.includes(i[0])&&is_real_ast(i[1],r,n))||!!(functions.nonzeroC.C&&functions.nonzeroC.C.includes(i[0])&&is_nonzero_ast(i[1],r,n)&&is_complex_ast(i[1],r,n))||!!(functions.nonneg.C&&functions.nonneg.C.includes(i[0])&&is_positive_ast(i[1],r,!1,n))||!!(functions.pos.C&&functions.pos.C.includes(i[0])&&is_positive_ast(i[1],r,!0,n))||void 0;if("prime"===a)return;return!1}return!1}function is_nonzero_ast(e,t,n){if("object"!=typeof t&&(t=[]),void 0===n&&(n=t),"number"==typeof e){if(Number.isFinite(e))return 0!==e;if(Number.isNaN(e))return;return!0}var r=evaluate_to_constant(e);if(null!==r){if("number"==typeof r){if(Number.isFinite(r))return 0!==r;if(Number.isNaN(r))return;return!0}return void 0!==r.re&&void 0!==r.im&&(0!==r.re||0!==r.im)||void 0}if("string"==typeof e){let r;if(r=Array.isArray(t)?t:t.get_assumptions(e),!Array.isArray(r))return;let a=r,i=r[0],o=r.slice(1),s=!1;for(;"not"===i;){if(s=!s,r=o[0],!Array.isArray(r))return;i=r[0],o=r.slice(1)}let l=narrow_assumptions(a,n);if("="===i&&!s||"ne"===i&&s){if(o[0]===e)return is_nonzero_ast(o[1],l);if(o[1]===e)return is_nonzero_ast(o[0],l)}if("ne"===i&&!s||"="===i&&s){if(o[0]===e&&!1===is_nonzero_ast(o[1],l))return!0;if(o[1]===e&&!1===is_nonzero_ast(o[0],l))return!0}if("<"===i)if(s){if(o[0]===e&&is_positive_ast(o[1],l,!0))return!0;if(o[1]===e&&is_negative_ast(o[0],l,!0))return!0}else{if(o[0]===e&&is_negative_ast(o[1],l,!1))return!0;if(o[1]===e&&is_positive_ast(o[0],l,!1))return!0}if("le"===i)if(s){if(o[0]===e&&is_positive_ast(o[1],l,!1))return!0;if(o[1]===e&&is_negative_ast(o[0],l,!1))return!0}else{if(o[0]===e&&is_negative_ast(o[1],l,!0))return!0;if(o[1]===e&&is_positive_ast(o[0],l,!0))return!0}if("and"!==i&&"or"!==i)return;if(s)return;return o.length>2&&(r=unflattenRight(r),o=r.slice(1)),simple_assumption_combination(i,is_nonzero_ast(e,o[0],n),is_nonzero_ast(e,o[1],n))}if(Array.isArray(e)){let r;r=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let a=e[0],i=e.slice(1);if("-"===a)return is_nonzero_ast(i[0],r,n);if("+"===a){if(i.length>2&&(i=(e=unflattenRight(e)).slice(1)),equal(i[0],simplify(["-",i[1]],n)))return!1;let t=is_nonzero_ast(i[0],r,n),a=is_nonzero_ast(i[1],r,n);if(!1===t)return a;if(!1===a)return t;let o=is_real_ast(i[0],r,n),s=is_real_ast(i[1],r,n);if(!o||!s)return!0===o?!1===s||void 0:!0===s&&!1===o||void 0;let l=is_positive_ast(i[0],r,!1,n),u=is_positive_ast(i[1],r,!1,n),c=is_positive_ast(i[0],r,!0,n),p=is_positive_ast(i[1],r,!0,n);return!!(l&&p||c&&u)||!1===l&&!1===p||!1===c&&!1===u||void 0}if("*"===a){let e=!0;for(let t=0;t0:e>=0);var a=is_real_ast(e,t,r);if(!a)return a;var i=evaluate_to_constant(e);if(null!==i)return"number"==typeof i&&!!Number.isFinite(i)&&(n?i>0:i>=0);if("string"==typeof e){let a;if(a=Array.isArray(t)?t:t.get_assumptions(e),!Array.isArray(a))return;let i=a,o=a[0],s=a.slice(1),l=!1;for(;"not"===o;){if(l=!l,a=s[0],!Array.isArray(a))return;o=a[0],s=a.slice(1)}let u=narrow_assumptions(i,r);if("="===o&&!l||"ne"===o&&l){if(s[0]===e)return is_positive_ast(s[1],u,n);if(s[1]===e)return is_positive_ast(s[0],u,n)}if("<"===o)if(l){if(s[0]===e&&is_positive_ast(s[1],u,n))return!0;if(s[1]===e&&is_negative_ast(s[0],u,!n))return!1}else{if(s[0]===e&&is_negative_ast(s[1],u,!1))return!1;if(s[1]===e&&is_positive_ast(s[0],u,!1))return!0}if("le"===o)if(l){if(s[0]===e&&is_positive_ast(s[1],u,!1))return!0;if(s[1]===e&&is_negative_ast(s[0],u,!1))return!1}else{if(s[0]===e&&is_negative_ast(s[1],u,!n))return!1;if(s[1]===e&&is_positive_ast(s[0],u,n))return!0}if("and"!==o&&"or"!==o)return;if(l)return;return s.length>2&&(a=unflattenRight(a),s=a.slice(1)),simple_assumption_combination(o,is_positive_ast(e,s[0],n,r),is_positive_ast(e,s[1],n,r))}if(Array.isArray(e)){let a;a=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let i=e[0],o=e.slice(1);if("-"===i)return is_negative_ast(o[0],a,n,r);if("+"===i){o.length>2&&(o=(e=unflattenRight(e)).slice(1));let t=is_positive_ast(o[0],a,!1,r),i=is_positive_ast(o[1],a,!1,r),s=is_positive_ast(o[0],a,!0,r),l=is_positive_ast(o[1],a,!0,r);if(n){if(t&&l||s&&i)return!0}else if(t&&i)return!0;if(n){if(!1===s&&!1===l)return!1}else if(!1===t&&!1===l||!1===s&&!1===i)return!1;return}if("*"===i){if(!o.every((e=>!1!==is_nonzero_ast(e,a,r))))return!n;o.length>2&&(o=(e=unflattenRight(e)).slice(1));let t=is_real_ast(o[0],a,r),i=is_real_ast(o[1],a,r);if(void 0===t||void 0===i)return;if(!1===t)return!1===i&&void 0;if(!1===i)return!1;let s=is_positive_ast(o[0],a,!1,r),l=is_positive_ast(o[1],a,!1,r),u=is_positive_ast(o[0],a,!0,r),c=is_positive_ast(o[1],a,!0,r);if(n){if(u&&c||!1===s&&!1===l)return!0;if(!1===u&&l||s&&!1===c)return!1}else{if(s&&l||!1===u&&!1===c)return!0;if(u&&!1===l||!1===s&&c)return!1}return}if("/"===i){if(!is_nonzero_ast(o[1],a,r))return;if(!1===is_nonzero_ast(o[0],a,r))return!n;let e=is_positive_ast(o[1],a,!0,r);if(void 0===e)return;let t=e?n:!n,i=is_positive_ast(o[0],a,t,r);if(void 0===i)return;return!0===i?!0===e:!0!==e}if("^"===i){let e=is_nonzero_ast(o[0],a,r);if(e){if(!1===is_nonzero_ast(o[1],a,r)){if(o[0]===1/0||o[0]===-1/0)return;return!0}}else{if(!is_positive_ast(o[1],a,!0,r))return;if(!1===e)return!n;if(n)return}if(!0!==is_real_ast(o[0],a,r))return;return is_positive_ast(o[0],a,n,r)?!!is_real_ast(o[1],a,r)||void 0:!!is_integer_ast(simplify(["/",o[1],2],r),a,r)||void 0}if("apply"===i&&!n)return!!(functions.C.nonneg&&functions.C.nonneg.includes(o[0])&&is_complex_ast(o[1],a,r))||!!(functions.R.nonneg&&functions.R.nonneg.includes(o[0])&&is_real_ast(o[1],a,r))||!!(functions.nonzeroC.nonneg&&functions.nonzeroC.nonneg.includes(o[0])&&is_nonzero_ast(o[1],a,r)&&is_complex_ast(o[1],a,r))||!!(functions.nonneg.nonneg&&functions.nonneg.nonneg.includes(o[0])&&is_positive_ast(o[1],a,!1,r))||!!(functions.pos.nonneg&&functions.pos.nonneg.includes(o[0])&&is_positive_ast(o[1],a,!0,r))||void 0;if("apply"===i&&n)return!!(functions.C.pos&&functions.C.pos.includes(o[0])&&is_complex_ast(o[1],a,r))||!!(functions.R.pos&&functions.R.pos.includes(o[0])&&is_real_ast(o[1],a,r))||!!(functions.nonzeroC.pos&&functions.nonzeroC.pos.includes(o[0])&&is_nonzero_ast(o[1],a,r)&&is_complex_ast(o[1],a,r))||!!(functions.nonneg.pos&&functions.nonneg.pos.includes(o[0])&&is_positive_ast(o[1],a,!1,r))||!!(functions.pos.pos&&functions.pos.pos.includes(o[0])&&is_positive_ast(o[1],a,!0,r))||void 0;if("prime"===i)return;return!1}return!1}function is_negative_ast(e,t,n,r){void 0===n&&(n=!0);var a=is_real_ast(e,t,r);if(!0===a){let a=is_positive_ast(e,t,!n,r);return!1===a||!0!==a&&void 0}return a}function tuples_to_vectors(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if("tuple"===n)return["vector"].concat(r.map((function(e,t){return tuples_to_vectors(e)})));if("apply"===n){if("tuple"===r[1][0]){let e=tuples_to_vectors(r[0]),t=r[1].slice(1);return["apply",e,["tuple"].concat(t.map((function(e,t){return tuples_to_vectors(e)})))]}}else if("gts"===n||"lts"===n||"interval"===n){let e=r[0],t=r[1];if("tuple"!==e[0]||"tuple"!==t[0])throw new Error("Badly formed ast");return[n,["tuple"].concat(e.slice(1).map((function(e,t){return tuples_to_vectors(e)}))),t]}return[n].concat(r.map((function(e,t){return tuples_to_vectors(e)})))}function to_intervals(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if("tuple"===n&&2===r.length){let e=["tuple"].concat(r.map((function(e,t){return to_intervals(e)})));return e=["interval",e,["tuple",!1,!1]],e}if("array"===n&&2===r.length){let e=["tuple"].concat(r.map((function(e,t){return to_intervals(e)})));return e=["interval",e,["tuple",!0,!0]],e}if("apply"===n){if("tuple"===r[1][0]){let e=to_intervals(r[0]),t=r[1].slice(1);return["apply",e,["tuple"].concat(t.map((function(e,t){return to_intervals(e)})))]}}else if("gts"===n||"lts"===n||"interval"===n){let e=r[0],t=r[1];if("tuple"!==e[0]||"tuple"!==t[0])throw new Error("Badly formed ast");return[n,["tuple"].concat(e.slice(1).map((function(e,t){return to_intervals(e)}))),t]}return[n].concat(r.map((function(e,t){return to_intervals(e)})))}function ParseError(e,t){this.name="ParseError",this.message=e||"Error parsing input",this.stack=(new Error).stack,this.location=t}functions.C.nonneg=["abs"],functions.C.nonzero=["exp"],functions.C.R=["abs","arg"],functions.C.C=["abs","arg","exp","sign","cos","cosh","sin","sinh","erf","sqrt","log","ln","log10"],functions.R.pos=["exp"],functions.R.nonneg=["abs","exp","arg"],functions.R.R=["abs","arg","exp","sign","cos","cosh","sin","sinh","erf"],functions.R.Z=["sign"],functions.nonzeroC.pos=["abs"],functions.nonneg.nonneg=["abs","exp","arg","sqrt","erf"],functions.nonzeroC.nonzero=["abs"],functions.nonneg.R=[...new Set(functions.R.R.concat(functions.nonneg.nonneg))],functions.pos.pos=["abs","exp","sqrt","erf"],functions.pos.nonneg=functions.pos.pos,functions.pos.nonzero=["abs","exp","sqrt","erf"],functions.pos.R=functions.nonneg.R.concat(["log","ln","log10"]),ParseError.prototype=Object.create(Error.prototype),ParseError.prototype.constructor=ParseError;class lexer{constructor(e,t="\\s"){this.input="",this.location=0,this.token_rules=[],this.initial_whitespace=new RegExp("^("+t+")+");for(let t of e)this.token_rules.push([new RegExp("^"+t[0])].concat(t.slice(1)))}set_input(e){if("string"!=typeof e)throw new Error("Input must be a string");this.input=e,this.location=0}return_state(){return{input:this.input,location:this.location}}set_state({input:e=null,location:t=0}={}){null!==e&&(this.input=e,this.location=t)}advance({remove_initial_space:e=!0}={}){let t=this.initial_whitespace.exec(this.input);if(t){let n=t[0].length;if(this.input=this.input.slice(n),this.location+=n,!e)return{token_type:"SPACE",token_text:t[0],original_text:t[0]}}if(0===this.input.length)return{token_type:"EOF",token_text:"",original_text:""};for(var n of(t=null,this.token_rules))if(t=n[0].exec(this.input),t){let e=t[0].length;this.input=this.input.slice(e),this.location+=e;break}return null===t?{token_type:"INVALID",token_text:this.input[0],original_text:this.input[0]}:n.length>2?{token_type:n[1],token_text:n[2],original_text:t[0]}:{token_type:n[1],token_text:t[0],original_text:t[0]}}unput(e){if("string"!=typeof e)throw new Error("Input must be a string");this.location-=e.length,this.input=e+this.input}}var is_associative={"+":!0,"*":!0,and:!0,or:!0,union:!0,intersect:!0};function flatten(e){if(!Array.isArray(e))return e;var t=e[0],n=e.slice(1);if(n=n.map((function(e,t){return flatten(e)})),is_associative[t]){for(var r=[],a=0;a2?r=r.concat(n[a].slice(1)):r.push(n[a]);n=r}return[t].concat(n)}const sci_notat_exp_regex$1="(E[+\\-]?[0-9]+\\s*($|(?=\\,|\\||\\)|\\}|\\])))?",number_rules_sci$1=[["[0-9]+(\\.[0-9]*)?"+sci_notat_exp_regex$1,"NUMBER"],["\\.[0-9]+"+sci_notat_exp_regex$1,"NUMBER"]],number_rules_non_sci$1=[["[0-9]+(\\.[0-9]*)?","NUMBER"],["\\.[0-9]+","NUMBER"]],base_text_rules=[["\\*\\*","^"],["\\*","*"],["\\xB7","*"],["·","*"],["•","*"],["⋅","*"],["×","*"],["/","/"],["-","-"],["֊","-"],["־","-"],["᠆","-"],["‐","-"],["‑","-"],["‒","-"],["–","-"],["—","-"],["―","-"],["⁻","-"],["₋","-"],["−","-"],["⸺","-"],["⸻","-"],["﹘","-"],["﹣","-"],["-","-"],["\\+","+"],["\\^","^"],["‸","^"],["ʌ","^"],["\\|","|"],["\\(","("],["\\)",")"],["\\[","["],["\\]","]"],["\\{","{"],["\\}","}"],[",",","],[":",":"],["α","VARMULTICHAR","alpha"],["β","VARMULTICHAR","beta"],["ϐ","VARMULTICHAR","beta"],["Γ","VARMULTICHAR","Gamma"],["γ","VARMULTICHAR","gamma"],["Δ","VARMULTICHAR","Delta"],["δ","VARMULTICHAR","delta"],["ε","VARMULTICHAR","epsilon"],["ϵ","VARMULTICHAR","epsilon"],["ζ","VARMULTICHAR","zeta"],["η","VARMULTICHAR","eta"],["Θ","VARMULTICHAR","Theta"],["ϴ","VARMULTICHAR","Theta"],["θ","VARMULTICHAR","theta"],["ᶿ","VARMULTICHAR","theta"],["ϑ","VARMULTICHAR","theta"],["ι","VARMULTICHAR","iota"],["κ","VARMULTICHAR","kappa"],["Λ","VARMULTICHAR","Lambda"],["λ","VARMULTICHAR","lambda"],["μ","VARMULTICHAR","mu"],["µ","VARMULTICHAR","mu"],["ν","VARMULTICHAR","nu"],["Ξ","VARMULTICHAR","Xi"],["ξ","VARMULTICHAR","xi"],["Π","VARMULTICHAR","Pi"],["π","VARMULTICHAR","pi"],["ϖ","VARMULTICHAR","pi"],["ρ","VARMULTICHAR","rho"],["ϱ","VARMULTICHAR","rho"],["Σ","VARMULTICHAR","Sigma"],["σ","VARMULTICHAR","sigma"],["ς","VARMULTICHAR","sigma"],["τ","VARMULTICHAR","tau"],["Υ","VARMULTICHAR","Upsilon"],["υ","VARMULTICHAR","upsilon"],["Φ","VARMULTICHAR","Phi"],["φ","VARMULTICHAR","phi"],["ϕ","VARMULTICHAR","phi"],["Ψ","VARMULTICHAR","Psi"],["ψ","VARMULTICHAR","psi"],["Ω","VARMULTICHAR","Omega"],["ω","VARMULTICHAR","omega"],["oo\\b","INFINITY"],["OO\\b","INFINITY"],["infty\\b","INFINITY"],["infinity\\b","INFINITY"],["Infinity\\b","INFINITY"],["∞","INFINITY"],["ℯ","VAR","e"],["♠","VARMULTICHAR","spade"],["♡","VARMULTICHAR","heart"],["♢","VARMULTICHAR","diamond"],["♣","VARMULTICHAR","club"],["★","VARMULTICHAR","bigstar"],["◯","VARMULTICHAR","bigcirc"],["◊","VARMULTICHAR","lozenge"],["△","VARMULTICHAR","bigtriangleup"],["▽","VARMULTICHAR","bigtriangledown"],["⧫","VARMULTICHAR","blacklozenge"],["■","VARMULTICHAR","blacksquare"],["▲","VARMULTICHAR","blacktriangle"],["▼","VARMULTICHAR","blacktriangledown"],["◀","VARMULTICHAR","blacktriangleleft"],["▶","VARMULTICHAR","blacktriangleright"],["□","VARMULTICHAR","Box"],["∘","VARMULTICHAR","circ"],["⋆","VARMULTICHAR","star"],["and\\b","AND"],["\\&\\&?","AND"],["∧","AND"],["or\\b","OR"],["∨","OR"],["not\\b","NOT"],["¬","NOT"],["=","="],["᐀","="],["゠","="],["!=","NE"],["≠","NE"],["<=","LE"],["≤","LE"],[">=","GE"],["≥","GE"],["<","<"],[">",">"],["elementof\\b","IN"],["∈","IN"],["notelementof\\b","NOTIN"],["∉","NOTIN"],["containselement\\b","NI"],["∋","NI"],["notcontainselement\\b","NOTNI"],["∌","NOTNI"],["subset\\b","SUBSET"],["⊂","SUBSET"],["notsubset\\b","NOTSUBSET"],["⊄","NOTSUBSET"],["superset\\b","SUPERSET"],["⊃","SUPERSET"],["notsuperset\\b","NOTSUPERSET"],["⊅","NOTSUPERSET"],["union\\b","UNION"],["∪","UNION"],["intersect\\b","INTERSECT"],["∩","INTERSECT"],["!","!"],["'","'"],["_","_"],["\\.\\.\\.","LDOTS"],["[a-zA-Z∂][a-zA-Z∂0-9]*","VAR"],["_","VAR"]],allowSimplifiedFunctionApplicationDefault$1=!0,splitSymbolsDefault=!0,unsplitSymbolsDefault=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega"],appliedFunctionSymbolsDefault$1=["abs","exp","log","ln","log10","sign","sqrt","erf","acos","acosh","acot","acoth","acsc","acsch","asec","asech","asin","asinh","atan","atanh","cos","cosh","cot","coth","csc","csch","sec","sech","sin","sinh","tan","tanh","arcsin","arccos","arctan","arccsc","arcsec","arccot","cosec","arg","conj","re","im","det","trace"],functionSymbolsDefault$1=["f","g"],parseLeibnizNotationDefault$1=!0;class textToAst$4{constructor({allowSimplifiedFunctionApplication:e=allowSimplifiedFunctionApplicationDefault$1,splitSymbols:t=splitSymbolsDefault,unsplitSymbols:n=unsplitSymbolsDefault,appliedFunctionSymbols:r=appliedFunctionSymbolsDefault$1,functionSymbols:a=functionSymbolsDefault$1,parseLeibnizNotation:i=parseLeibnizNotationDefault$1,parseScientificNotation:o=!0}={}){this.allowSimplifiedFunctionApplication=e,this.splitSymbols=t,this.unsplitSymbols=n,this.appliedFunctionSymbols=r,this.functionSymbols=a,this.parseLeibnizNotation=i;let s=base_text_rules;s=o?[...number_rules_sci$1,...s]:[...number_rules_non_sci$1,...s],this.lexer=new lexer(s)}advance(e){if(this.token=this.lexer.advance(e),"INVALID"===this.token.token_type)throw new ParseError("Invalid symbol '"+this.token.original_text+"'",this.lexer.location)}return_state(){return{lexer_state:this.lexer.return_state(),token:Object.assign({},this.token)}}set_state(e){this.lexer.set_state(e.lexer_state),this.token=Object.assign({},e.token)}convert(e){this.lexer.set_input(e),this.advance();var t=this.statement_list();if("EOF"!==this.token.token_type)throw new ParseError("Invalid location of '"+this.token.original_text+"'",this.lexer.location);return flatten(t)}statement_list(){for(var e=[this.statement()];","===this.token.token_type;)this.advance(),e.push(this.statement());return e.length>1?["list"].concat(e):e[0]}statement({inside_absolute_value:e=0}={}){if("LDOTS"===this.token.token_type)return this.advance(),["ldots"];var t;try{t=this.return_state();let n=this.statement_a({inside_absolute_value:e});return":"!==this.token.token_type?n:(this.advance(),[":",n,this.statement_a()])}catch(e){try{this.set_state(t);let n=this.statement_a({parse_absolute_value:!1});if("|"!==this.token.token_type)throw e;return this.advance(),["|",n,this.statement_a({parse_absolute_value:!1})]}catch(t){throw e}}}statement_a({inside_absolute_value:e=0,parse_absolute_value:t=!0}={}){for(var n=this.statement_b({inside_absolute_value:e,parse_absolute_value:t});"OR"===this.token.token_type;){let r=this.token.token_type.toLowerCase();this.advance(),n=[r,n,this.statement_b({inside_absolute_value:e,parse_absolute_value:t})]}return n}statement_b(e){for(var t=this.relation(e);"AND"===this.token.token_type;){let n=this.token.token_type.toLowerCase();this.advance(),t=[n,t,this.relation(e)]}return t}relation(e){if("NOT"===this.token.token_type||"!"===this.token.token_type)return this.advance(),["not",this.relation(e)];for(var t=this.expression(e);"="===this.token.token_type||"NE"===this.token.token_type||"<"===this.token.token_type||">"===this.token.token_type||"LE"===this.token.token_type||"GE"===this.token.token_type||"IN"===this.token.token_type||"NOTIN"===this.token.token_type||"NI"===this.token.token_type||"NOTNI"===this.token.token_type||"SUBSET"===this.token.token_type||"NOTSUBSET"===this.token.token_type||"SUPERSET"===this.token.token_type||"NOTSUPERSET"===this.token.token_type;){let n=this.token.token_type.toLowerCase(),r=0;"<"===this.token.token_type||"LE"===this.token.token_type?r=-1:">"!==this.token.token_type&&"GE"!==this.token.token_type||(r=1),this.advance();let a=this.expression(e);if(-1===r)if("<"===this.token.token_type||"LE"===this.token.token_type){let r=["tuple"];"<"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;"<"===this.token.token_type||"LE"===this.token.token_type;)"<"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["lts",i,r]}else t=[n,t,a];else if(1===r)if(">"===this.token.token_type||"GE"===this.token.token_type){let r=["tuple"];">"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;">"===this.token.token_type||"GE"===this.token.token_type;)">"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["gts",i,r]}else t=[n,t,a];else if("="===n)for(t=["=",t,a];"="===this.token.token_type;)this.advance(),t.push(this.expression(e));else t=[n,t,a]}return t}expression(e){let t=!1;"+"===this.token.token_type&&(t=!0,this.advance());let n=!1;"-"===this.token.token_type&&(n=!0,this.advance());var r=this.term(e);if(n||t){if(!1===r)return(t?"+":"")+(n?"-":"");if("string"==typeof r&&[...r].every((e=>["+","-"].includes(e))))return(t?"+":"")+(n?"-":"")+r}for(!1===r&&(r="_"),n&&(r=r>0?-r:["-",r]);"+"===this.token.token_type||"-"===this.token.token_type||"UNION"===this.token.token_type||"INTERSECT"===this.token.token_type;){let t=this.token.token_type.toLowerCase(),n=!1,a=!1;"-"===this.token.token_type?(t="+",n=!0,this.advance()):(this.advance(),"+"===t&&"-"===this.token.token_type&&(n=!0,a=!0,this.advance()));let i=this.term(e);if("+"===t){if(!1===i&&("number"==typeof r||"string"==typeof r))return a?r+"+-":n?r+"-":r+"+";if("string"==typeof i&&[...i].every((e=>["+","-"].includes(e)))&&("number"==typeof r||"string"==typeof r))return a?r+"+-"+i:n?r+"-"+i:r+"+"+i}!1===i&&(i="_"),n&&(i=i>0?-i:["-",i]),r=[t,r,i]}return r}term(e){var t=this.factor(e),n=!1;do{if(n=!1,"*"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["*",t,r],n=!0}else if("/"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["/",t,r],n=!0}else{let r=Object.assign({},e);r.allow_absolute_value_closing=!0;let a=this.nonMinusFactor(r);!1!==a&&(!1===t&&(t="_"),t=["*",t,a],n=!0)}}while(n);return t}factor(e){if("+"===this.token.token_text){if(this.advance(),e.dont_append_to_plus_minus)return"+";let t=this.factor(e);return!1===t?"+":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"+"+t:["+",t]}if("-"===this.token.token_type){if(this.advance(),e.dont_append_to_plus_minus)return"-";let t=this.factor(e);return t>0?-t:!1===t?"-":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"-"+t:["-",t]}return this.nonMinusFactor(e)}nonMinusFactor(e){var t=this.baseFactor(e);if("!"===this.token.token_type||"'"===this.token.token_type)for(!1===t&&(t="_");"!"===this.token.token_type||"'"===this.token.token_type;)t="!"===this.token.token_type?["apply","factorial",t]:["prime",t],this.advance();if("^"===this.token.token_type){!1===t&&(t="_"),this.advance();let n=Object.assign({},e);delete n.allow_absolute_value_closing,delete n.inside_absolute_value,delete n.return_false_if_found_nothing,n.dont_append_to_plus_minus=!0;let r=this.factor(n);return!1===r&&(r="_"),["^",t,r]}return t}baseFactor({inside_absolute_value:e=0,parse_absolute_value:t=!0,allow_absolute_value_closing:n=!1}={}){var r=!1;if("NUMBER"===this.token.token_type)r=parseFloat(this.token.token_text),this.advance();else if("INFINITY"===this.token.token_type)r=1/0,this.advance();else if("VAR"===this.token.token_type||"VARMULTICHAR"===this.token.token_type)if(r=this.token.token_text,this.appliedFunctionSymbols.includes(r)||this.functionSymbols.includes(r)){let e=!1;if(this.appliedFunctionSymbols.includes(r)&&(e=!0),this.advance(),"_"===this.token.token_type){this.advance();let e=this.baseFactor({parse_absolute_value:t});!1===e&&(e="_"),r="log"===r&&10===e?"log10":["_",r,e]}for(;"'"===this.token.token_type;)r=["prime",r],this.advance();if("^"===this.token.token_type){this.advance();let e=this.factor({parse_absolute_value:t});!1===e&&(e="_"),r=["^",r,e]}if("("===this.token.token_type){this.advance();let e=this.statement_list();if(")"!==this.token.token_type)throw new ParseError("Expecting )",this.lexer.location);this.advance(),"list"===e[0]&&(e[0]="tuple"),r=["apply",r,e]}else if(e){if(!this.allowSimplifiedFunctionApplication)throw new ParseError("Expecting ( after function",this.lexer.location);let e=this.factor({parse_absolute_value:t});!1===e&&(e="_"),r=["apply",r,e]}}else{if(this.parseLeibnizNotation){let e=this.return_state(),t=this.leibniz_notation();if(t)return t;this.set_state(e)}let a=this.splitSymbols;if(a&&("VARMULTICHAR"===this.token.token_type||this.unsplitSymbols.includes(r)||1===r.length||r.match(/[\d]/g))&&(a=!1),a){for(let e=r.length-1;e>=0;e--)this.lexer.unput(" "),this.lexer.unput(r[e]);return this.advance(),this.baseFactor({inside_absolute_value:e,parse_absolute_value:t,allow_absolute_value_closing:n})}this.advance()}else if("("===this.token.token_type||"["===this.token.token_type||"{"===this.token.token_type){let e,t,n=this.token.token_type;"("===this.token.token_type?(e=")",t="]"):"["===this.token.token_type?(e="]",t=")"):(e="}",t=null),this.advance();let a=1;if("list"===(r=this.statement_list())[0]&&(a=r.length-1),this.token.token_type!==e){if(2!==a||null===t)throw new ParseError("Expecting "+e,this.lexer.location);if(this.token.token_type!==t)throw new ParseError("Expecting ) or ]",this.lexer.location);let i;r[0]="tuple",i="("===n?["tuple",!1,!0]:["tuple",!0,!1],(r=["interval",r]).push(i)}else a>=2?r[0]="("===n?"tuple":"["===n?"array":"set":"{"===n&&("|"===r[0]||r[0],r=["set",r]);this.advance()}else if("|"===this.token.token_type&&t&&(0===e||!n)){if(e+=1,this.advance(),r=["apply","abs",r=this.statement({inside_absolute_value:e})],"|"!==this.token.token_type)throw new ParseError("Expecting |",this.lexer.location);this.advance()}if("_"===this.token.token_type){let e;return!1===r&&(r="_"),this.advance(),["+","-"].includes(this.token.token_text)?(e=this.token.token_text,this.advance()):(e=this.baseFactor({parse_absolute_value:t}),!1===e&&(e="_")),["_",r,e]}return r}leibniz_notation(){var e=this.token.token_text;if("VAR"!==this.token.token_type||"d"!==e[0]&&"∂"!==e[0]||!(1===e.length||2===e.length&&/[a-zA-Z]/.exec(e[1])))return!1;let t=e[0],n=1,r="",a=[],i=[];if(2===e.length)r=e[1];else if(this.advance(),"VARMULTICHAR"===this.token.token_type||"VAR"===this.token.token_type&&!this.token.token_text.includes("∂"))r=this.token.token_text;else{if("^"!==this.token.token_type)return!1;if(this.advance(),"NUMBER"!==this.token.token_type)return!1;if(n=parseFloat(this.token.token_text),!Number.isInteger(n))return!1;if(this.advance(),("VAR"!==this.token.token_type||this.token.token_text.includes("∂"))&&"VARMULTICHAR"!==this.token.token_type)return!1;r=this.token.token_text}if(this.advance(),"/"!==this.token.token_type)return!1;let o=0;for(this.advance();;){if("VAR"!==this.token.token_type||this.token.token_text[0]!==t)return!1;this.token.token_text.length>2&&(this.lexer.unput(this.token.token_text.slice(2)),this.token.token_text=this.token.token_text.slice(0,2));let s=this.token.token_text;if(2===s.length){if(!/[a-zA-Z]/.exec(s[1]))return!1;a.push(s[1])}else{if(this.advance(),("VAR"!==this.token.token_type||this.token.token_text.includes("∂"))&&"VARMULTICHAR"!==this.token.token_type)return!1;a.push(this.token.token_text)}let l=1,u=!1;if(this.advance({remove_initial_space:!1}),"SPACE"===this.token.token_type&&(u=!0,this.advance()),"^"===this.token.token_type){if(this.advance(),"NUMBER"!==this.token.token_type)return!1;if(l=parseFloat(this.token.token_text),!Number.isInteger(l))return!1;u=!1,this.advance({remove_initial_space:!1}),"SPACE"===this.token.token_type&&(u=!0,this.advance())}if(i.push(l),o+=l,o>n)return!1;if(o===n){if(!u&&("VAR"===this.token.token_type||"VARMULTICHAR"===this.token.token_type))return!1;"SPACE"===this.token.token_type&&this.advance();let o="derivative_leibniz";"∂"===t&&(o="partial_"+o),e=[o],1===n?e.push(r):e.push(["tuple",r,n]);let s=[];for(let e=0;et[e+1]));if(t.length!==r||a.length!==r)return subtree;let i=["+",...t.map(((e,t)=>["*",e,a[t]]))];n.push(i)}s.push(n)}return{success:!0,newMatrix:["matrix",["tuple",n,a],s]}}function i(e,t){let n=e[1][1],r=e[1][2],a=e[2],i=["tuple"];for(let e=0;e=0;t--){let r=n[t][0];if("matrix"===r){let r=a(n[t],e);if(!r.success)break;e=r.newMatrix,n.pop()}else{if(["tuple","list","vector","interval","set","array"].includes(r))break;1!==n[t]&&(e=i(e,n[t])),n.pop()}}for(;r.length>0;){let t=r[0][0];if("matrix"===t){let t=a(e,r[0]);if(!t.success)break;e=t.newMatrix,r.splice(0,1)}else{if(["tuple","list","vector","interval","set","array"].includes(t))break;1!==r[0]&&(e=i(e,r[0])),r.splice(0,1)}}return n.length>0||r.length>0?["*",...n,e,...r]:e}return e})),(t||n)&&(o=["*",["matrix",["tuple","m","n"],"matrixData"],"b"],s={variables:{n:Number.isInteger,m:Number.isInteger,matrixData:!0,b:!0}},r=transform(r,(function(e){let r=match$2(e,o,s);if(r){let a,i=r.m,o=r.n,s=r.b,l=r.matrixData,u=[];t&&u.push("vector"),n&&u.push("tuple");let c=[];if(u.includes(s[0]))a=s;else{if(!Array.isArray(s)||"*"!==s[0]||!u.includes(s[1][0]))return e;a=s[1],c=s.slice(2)}let p=a.slice(1);if(p.length!==o)return e;let d=[a[0]];for(let e=0;e["*",e,p[t]]))];d.push(t)}return c.length>0?["*",d,...c]:d}return e}))),r}function perform_vector_scalar_multiplications(e,t=!0){var n=get_tree(e);let r=function(e,t){let n=["*","a",[t,"vectorData"],"b"],r={allow_implicit_identities:["a","b"]};return e=transform(e,(function(e){let a=match$2(e,n,r);if(a){if(1===a.a&&1===a.b)return e;let n=a.vectorData;n=Array.isArray(n)&&n[0]===t?n.slice(1):[n];let r=[],i=[];Array.isArray(a.a)&&"*"===a.a[0]?r.push(...a.a.slice(1)):r.push(a.a),Array.isArray(a.b)&&"*"===a.b[0]?i.push(...a.b.slice(1)):i.push(a.b);for(let e=r.length-1;e>=0;e--){let t=r[e][0];if(["tuple","list","vector","interval","set","array","matrix"].includes(t))break;1!==r[e]&&(n=n.map((t=>["*",t,r[e]]))),r.pop()}for(;i.length>0;){let e=i[0][0];if(["tuple","list","vector","interval","set","array","matrix"].includes(e))break;1!==i[0]&&(n=n.map((e=>["*",e,i[0]]))),i.splice(0,1)}let o=[t,...n];return r.length>0||i.length>0?["*",...r,o,...i]:o}return e})),e};return n=r(n,"vector"),t&&(n=r(n,"tuple")),n}function perform_matrix_scalar_multiplications(e){var t=get_tree(e);let n=["*","a",["matrix","size","matrixData"],"b"],r={allow_implicit_identities:["a","b"]};return t=transform(t,(function(e){let t=match$2(e,n,r);if(t){if(1===t.a&&1===t.b)return e;let n=t.matrixData,r=[],a=[];Array.isArray(t.a)&&"*"===t.a[0]?r.push(...t.a.slice(1)):r.push(t.a),Array.isArray(t.b)&&"*"===t.b[0]?a.push(...t.b.slice(1)):a.push(t.b);for(let e=r.length-1;e>=0;e--){let t=r[e][0];if(["tuple","list","vector","interval","set","array","matrix"].includes(t))break;1!==r[e]&&(n=n.map((t=>"tuple"===t?t:t.map((t=>"tuple"===t?t:["*",t,r[e]]))))),r.pop()}for(;a.length>0;){let e=a[0][0];if(["tuple","list","vector","interval","set","array","matrix"].includes(e))break;1!==a[0]&&(n=n.map((e=>"tuple"===e?e:e.map((e=>"tuple"===e?e:["*",e,a[0]]))))),a.splice(0,1)}let i=["matrix",t.size,n];return r.length>0||a.length>0?["*",...r,i,...a]:i}return e})),t}function expand_relations(e){var t=get_tree(e);return transform(t,expand_relations_transform)}function expand_relations_transform(e){if(!Array.isArray(e))return e;var t=e[0],n=e.slice(1);if("="===t){if(n.length<=2)return e;let t=["and"];for(let e=0;e":"lts"===t?"le":"ge",a.push([i,e[n],e[n+1]])}let i=["and",a[0],a[1]];for(let e=2;e",r,u]),s[2]?i?p.push([">",r,c]):p.push(["le",r,c]):i?p.push(["ge",r,c]):p.push(["<",r,c]),l=i?["or"].concat(p):["and"].concat(p),l}if("subset"===t||"notsubset"===t||"superset"===t||"notsuperset"===t){let r,a,i=!1;if("notsubset"!==t&&"notsuperset"!==t||(i=!0),"subset"===t||"notsubset"===t?(r=n[0],a=n[1]):(r=n[1],a=n[0]),r=to_intervals(r),a=to_intervals(a),"interval"!==r[0]||"interval"!==a[0])return e;let o=r[1],s=r[2],l=a[1],u=a[2];if("tuple"!==o[0]||"tuple"!==s[0]||"tuple"!==l[0]||"tuple"!==u[0])throw new Error("Badly formed ast");let c,p=o[1],d=o[2],m=l[1],f=l[2],h=[];return s[1]&&!u[1]?i?h.push(["le",p,m]):h.push([">",p,m]):i?h.push(["<",p,m]):h.push(["ge",p,m]),s[2]&&!u[2]?i?h.push(["ge",d,f]):h.push(["<",d,f]):i?h.push([">",d,f]):h.push(["le",d,f]),c=i?["or"].concat(h):["and"].concat(h),c}return e}function substitute(e,t){var n=get_tree(e),r={};for(let e in t)r[e]=get_tree(t[e]);return substitute$1(n,r)}function substitute_component(e,t,n){let r=get_tree(e);if(get_tree(n),"number"==typeof t)t=[t];else if(!Array.isArray(t))throw Error("Invalid substitute_component: "+t);let a=["list","tuple","vector","array"];return function e(t,r,i){if(0===r.length)return n;if(!Array.isArray(t))throw Error("Invalid substitute_component: expected list, tuple, vector, or array");let o=t[0],s=t.slice(1);if(!a.includes(o))throw Error("Invalid substitute_component: expected list, tuple, vector, or array");let l=r[0];if(l<0||l>s.length-1)throw Error("Invalid substitute_component: component out of range");let u=r.slice(1),c=e(s[l],u);return[o,...s.slice(0,l),c,...s.slice(l+1)]}(r,t)}function get_component(e,t){let n=get_tree(e);if("number"==typeof t)t=[t];else if(!Array.isArray(t))throw Error("Invalid get_component: "+t);let r=["list","tuple","vector","array"];return function e(t,n){if(0===n.length)return t;if(!Array.isArray(t))throw Error("Invalid get_component: expected list, tuple, vector, or array");let a=t[0],i=t.slice(1);if(!r.includes(a))throw Error("Invalid get_component: expected list, tuple, vector, or array");let o=n[0];if(o<0||o>i.length-1)throw Error("Invalid get_component: component out of range");let s=n.slice(1);return e(i[o],s)}(n,t)}var transformation=Object.freeze({__proto__:null,expand:expand,expand_relations:expand_relations,substitute:substitute,substitute_component:substitute_component,get_component:get_component,perform_vector_scalar_multiplications:perform_vector_scalar_multiplications,perform_matrix_scalar_multiplications:perform_matrix_scalar_multiplications,perform_matrix_multiplications:perform_matrix_multiplications});function clean(e){return flatten$5(get_tree(e))}function evalf(e,t){return parseFloat(math$1.format(e,{notation:"exponential",precision:t}))}function collapse_unary_minus(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if(r=r.map((e=>collapse_unary_minus(e))),"-"===n){if("number"==typeof r[0])return-r[0];if(Array.isArray(r[0])&&"*"===r[0][0]&&"number"==typeof r[0][1])return["*",-r[0][1]].concat(r[0].slice(2));if(Array.isArray(r[0])&&"/"===r[0][0]){if("number"==typeof r[0][1])return["/",-r[0][1],r[0][2]];if(Array.isArray(r[0][1])&&"*"===r[0][1][0]&&"number"==typeof r[0][1][1])return["/",["*",-r[0][1][1]].concat(r[0][1].slice(2)),r[0][2]]}}return[n].concat(r)}function simplify(e,t,n){var r=get_tree(e);return contains_blank(r)?r:(void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),r=evaluate_numbers(r,{assumptions:t,max_digits:n,evaluate_functions:!0}),Array.isArray(r)?r=collect_like_terms_factors(r=perform_vector_matrix_additions_scalar_multiplications(r=simplify_logical(r,t)),t,n):r)}function simplify_logical(e,t){var n=get_tree(e);if(contains_blank(n))return n;void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),n=evaluate_numbers(n,{assumptions:t}),n=unflattenRight(n);var r=[];return r.push([["not",["not","a"]],"a"]),r.push([["not",["and","a","b"]],["or",["not","a"],["not","b"]]]),r.push([["not",["or","a","b"]],["and",["not","a"],["not","b"]]]),r.push([["not",["=","a","b"]],["ne","a","b"]]),r.push([["not",["ne","a","b"]],["=","a","b"]]),r.push([["not",["<","a","b"]],["le","b","a"]]),r.push([["not",["le","a","b"]],["not",["le","a","b"]]]),r.push([["not",["in","a","b"]],["notin","a","b"]]),r.push([["not",["subset","a","b"]],["notsubset","a","b"]]),flatten$5(n=applyAllTransformations(n,r,20))}function perform_vector_matrix_additions_scalar_multiplications(e,t=!0){var n=get_tree(e);n=perform_vector_scalar_multiplications(n=perform_matrix_scalar_multiplications(n),t);let r=["+","a","b"];return n=transform(n,(function(e){let n=match$2(e,r,{allow_permutations:!0});if(n){let r=["vector"];t&&r.push("tuple");let a={},i={},o=[];if(r.includes(n.a[0])){let e=n.a.length-1;a[e]||(a[e]=[]),a[e].push(n.a)}else if("matrix"===n.a[0]){let e=n.a[1].slice(1).toString();i[e]||(i[e]=[]),i[e].push(n.a)}else o.push(n.a);if(r.includes(n.b[0])){let e=n.b.length-1;a[e]||(a[e]=[]),a[e].push(n.b)}else if("matrix"===n.b[0]){let e=n.b[1].slice(1).toString();i[e]||(i[e]=[]),i[e].push(n.b)}else if("+"===n.b[0])for(let e of n.b.slice(1))if(r.includes(e[0])){let t=e.length-1;a[t]||(a[t]=[]),a[t].push(e)}else if("matrix"===e[0]){let t=e[1].slice(1).toString();i[t]||(i[t]=[]),i[t].push(e)}else o.push(e);else o.push(n.b);if(Object.values(a).every((e=>e.length<2))&&Object.values(i).every((e=>e.length<2)))return e;let s=o;for(let e in a)if(a[e].length<2)s.push(...a[e]);else{let t=a[e].some((e=>"vector"===e[0]))?["vector"]:["tuple"];for(let n=0;ne[n+1]))]);s.push(t)}for(let e in i)if(i[e].length<2)s.push(...i[e]);else{let[t,n]=e.split(",").map(Number),r=["tuple"];for(let a=0;ae[2][a+1][r+1]))]);r.push(t)}let a=["matrix",["tuple",t,n],r];s.push(a)}return 1===s.length?s[0]:["+",...s]}return e})),n}function contains_decimal_number(e){return"string"!=typeof e&&("number"==typeof e?!(!Number.isFinite(e)||Number.isInteger(e)):!!Array.isArray(e)&&e.slice(1).some((e=>contains_decimal_number(e))))}function contains_only_numbers(e,{include_number_symbols:t=!1,evaluate_functions:n=!1}={}){if("string"==typeof e){if(t){if("e"===e&&math$1.define_e)return!0;if("pi"===e&&math$1.define_pi)return!0}return!("i"!==e||!math$1.define_i)}return"number"==typeof e||!!Array.isArray(e)&&(n&&"apply"===e[0]?e.slice(2).every((e=>contains_only_numbers(e,{include_number_symbols:t}))):e.slice(1).every((e=>contains_only_numbers(e,{include_number_symbols:t}))))}function evaluate_numbers_sub(e,t,n,r,a,i){if(void 0===e)return e;if("number"==typeof e)return i>0&&math$1.abs(e)0&&math$1.abs(t)evaluate_numbers_sub(e,t,n,r,a,i)));if("+"===s){let e=l[0],t=l[1];if(void 0===t)return e;if("number"==typeof e){if(0===e)return t;if("number"==typeof t)return e+t;if(Array.isArray(t)&&"+"===t[0]&&"number"==typeof t[1])return["+",e+t[1],t[2]];if(!r&&Array.isArray(t)&&"+"===t[0]&&"number"==typeof t[2])return["+",e+t[2],t[1]]}return"number"==typeof t&&0===t?e:[s].concat(l)}if("-"===s){if("number"==typeof l[0])return-l[0];if(Array.isArray(l[0])&&"*"===l[0][0]&&"number"==typeof l[0][1])return["*",-l[0][1]].concat(l[0].slice(2));if(Array.isArray(l[0])&&"/"===l[0][0]){if("number"==typeof l[0][1])return["/",-l[0][1],l[0][2]];if(Array.isArray(l[0][1])&&"*"===l[0][1][0]&&"number"==typeof l[0][1][1])return["/",["*",-l[0][1][1]].concat(l[0][1].slice(2)),l[0][2]]}return[s].concat(l)}if("*"===s){let e=l[0],t=l[1];if(void 0===t)return e;if("number"==typeof e){if(isNaN(e))return NaN;if("number"==typeof t)return e*t;if(!isFinite(e))return e===1/0&&is_negative_ast(t)||e===-1/0&&is_positive_ast(t)?-1/0:!1===is_nonzero_ast(t)?NaN:1/0;if(0===e)return 0;if(1===e)return t;if(-1===e)return["-",t];if(Array.isArray(t)&&"*"===t[0]&&"number"==typeof t[1])return e*=t[1],t=t[2],1===e?t:-1===e?["-",t]:["*",e,t]}if("number"==typeof t){if(isNaN(t))return NaN;if(!isFinite(t))return t===1/0&&is_negative_ast(e)||t===-1/0&&is_positive_ast(e)?-1/0:!1===is_nonzero_ast(e)?NaN:1/0;if(0===t)return 0;if(1===t)return e;if(-1===t)return["-",e];if(Array.isArray(e)&&"*"===e[0]&&"number"==typeof e[1])return t*=e[1],e=e[2],1===t?e:-1===t?["-",e]:["*",e,t]}if(math$1.define_i&&"i"===e){if("i"===t)return-1;if(Array.isArray(t)&&"*"===t[0]&&"i"===t[1])return["-",t[2]]}else if(math$1.define_i&&"i"===t&&Array.isArray(e)&&"*"===e[0]&&"i"===e[1])return["-",e[2]];return[s].concat(l)}if("/"===s){let e=l[0],r=l[1];if("number"==typeof e){if(0===e){let e=is_nonzero_ast(r,t);if(e)return 0;if(!1===e)return NaN}if("number"==typeof r){let t=e/r;if(n===1/0||math$1.round(t,n)===t)return t;if(r<0)return["/",-e,-r]}if(Array.isArray(r)&&"*"===r[0]&&"number"==typeof r[1]){let t=e/r[1];if(n===1/0||math$1.round(t,n)===t)return["/",t,r[2]]}}else if("number"==typeof r){if(Array.isArray(e)&&"*"===e[0]&&"number"==typeof e[1]){let t=e[1]/r;if(n===1/0||math$1.round(t,n)===t)return 1===t?e[2]:["*",t,e[2]];if(r<0)return["/",["*",-e[1],e[2]],-r]}let t=1/r;if(n===1/0||math$1.round(t,n)===t)return["*",t,e];if(r<0)return Array.isArray(e)&&"-"===e[0]?["/",e[1],-r]:["-",["/",e,-r]]}return[s].concat(l)}if("^"===s){let e=l[0],r=l[1];if("number"==typeof r)if(0===r){if(!math$1.pow_strict)return 1;let n=is_nonzero_ast(e,t);if(n&&e!==1/0&&e!==-1/0)return 1;if(!1===n)return NaN}else{if(1===r)return e;if("number"==typeof e){let t=math$1.pow(e,r);if(n===1/0||math$1.round(t,n)===t)return t}}else if(1===e)return 1;return[s].concat(l)}return[s].concat(l)}function evaluate_numbers(e,{assumptions:t,max_digits:n,skip_ordering:r=!1,evaluate_functions:a=!1,set_small_zero:i=0}={}){(void 0===n||!Number.isInteger(n)&&n!==1/0)&&(n=0),!0===i&&(i=1e-14);var o,s=get_tree(e);return contains_blank(s)?s:(void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),r?o=evaluate_numbers_sub(s=unflattenRight(flatten$5(s)),t,n,r,a,i):(s=unflattenRight(default_order(flatten$5(s))),o=default_order(evaluate_numbers_sub(s,t,n,r,a,i)),o=default_order(evaluate_numbers_sub(unflattenRight(o),t,n,r,a,i))),flatten$5(o=set_negative_zeros_to_zero(o)))}function set_negative_zeros_to_zero(e){return 0===e?0:Array.isArray(e)?[e[0],...e.slice(1).map(set_negative_zeros_to_zero)]:e}function collect_like_terms_factors(e,t,n){function r(e){return"number"==typeof e||!(!Array.isArray(e)||"-"!==e[0]||"number"!=typeof e[1])}function a(e){return"number"==typeof e&&e<0||!(!Array.isArray(e)||"-"!==e[0]||"number"!=typeof e[1])}function i(e){if("number"==typeof e)return!0;if(Array.isArray(e)&&"-"===e[0]&&"number"==typeof e[1])return!0;let t=evaluate_to_constant(e);return!("number"!=typeof t||!Number.isFinite(t))}var o=get_tree(e);if(contains_blank(o))return o;void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),o=evaluate_numbers(o,{assumptions:t,max_digits:n,evaluate_functions:!0});var s=[];return s.push([["/","x",["^","y","a"]],["*","x",["^","y",["-","a"]]],{evaluate_numbers:!0,max_digits:n}]),s.push([["/","x",["apply","exp","a"]],["*","x",["apply","exp",["-","a"]]],{evaluate_numbers:!0,max_digits:n,variables:{x:!0,a:!0}}]),s.push([["/","x","y"],["*","x",["^","y",["-",1]]],{evaluate_numbers:!0,max_digits:n}]),o=applyAllTransformations(o,s,40),(s=[]).push([["*",["^","x","n"],["^","x","m"]],["^","x",["+","n","m"]],{variables:{x:e=>is_nonzero_ast(e,t),n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s.push([["*",["^","x","n"],["^","x","m"]],["^","x",["+","n","m"]],{variables:{x:!0,n:e=>r(e)&&is_positive_ast(e,t),m:e=>r(e)&&is_positive_ast(e,t)},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s.push([["*",["^","x","n"],["^","x","m"]],["^","x",["+","n","m"]],{variables:{x:!0,n:e=>r(e)&&is_negative_ast(e,t),m:e=>r(e)&&is_negative_ast(e,t)},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s.push([["*",["apply","exp","n"],["apply","exp","m"]],["apply","exp",["+","n","m"]],{variables:{n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s.push([["+",["*","n","x"],["*","m","x"]],["*",["+","n","m"],"x"],{variables:{x:!0,n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s.push([["+",["*","n1","x"],["*",["/","n2","m2"],"x"]],["*",["+","n1",["/","n2","m2"]],"x"],{variables:{x:!0,n1:r,n2:r,m2:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m2","n1","n2"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s.push([["+",["*","n1","x"],["*",["-",["/","n2","m2"]],"x"]],["*",["+","n1",["-",["/","n2","m2"]]],"x"],{variables:{x:!0,n1:r,n2:r,m2:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m2","n1","n2"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s.push([["+",["*",["/","n1","m1"],"x"],["*",["/","n2","m2"],"x"]],["*",["+",["/","n1","m1"],["/","n2","m2"]],"x"],{variables:{x:!0,n1:r,m1:r,n2:r,m2:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m1","m2","n1","n2"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s.push([["+",["*",["/","n1","m1"],"x"],["*",["-",["/","n2","m2"]],"x"]],["*",["+",["/","n1","m1"],["-",["/","n2","m2"]]],"x"],{variables:{x:!0,n1:r,m1:r,n2:r,m2:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m1","m2","n1","n2"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s.push([["+",["*","n","x"],["-",["*","m","x"]]],["*",["+","n",["-","m"]],"x"],{variables:{x:!0,n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s.push([["^",["*","x","y"],"a"],["*",["^","x","a"],["^","y","a"]],{allow_permutations:!0}]),s.push([["^",["^","x","n"],"m"],["^","x",["*","n","m"]],{variables:{x:!0,n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_permutations:!0}]),s.push([["-",["+","a","b"]],["+",["-","a"],["-","b"]]]),s.push([["*","x","y"],["*","x","y"],{variables:{x:i,y:i},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o=applyAllTransformations(o,s,40),(s=[]).push([["*","x",["^","y",["-","a"]]],["/","x",["^","y","a"]],{allow_extended_match:!0,allow_permutations:!0,evaluate_numbers:!0,max_digits:n,max_group:1}]),s.push([["*","x",["apply","exp",["-","a"]]],["/","x",["apply","exp","a"]],{allow_extended_match:!0,allow_permutations:!0,evaluate_numbers:!0,max_digits:n,max_group:1,variables:{x:!0,a:!0}}]),s.push([["*","x",["^","y","n"]],["/","x",["^","y",["-","n"]]],{variables:{x:!0,y:!0,n:a},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s.push([["*","x",["apply","exp","n"]],["/","x",["apply","exp",["-","n"]]],{variables:{x:!0,n:a},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o=applyAllTransformations(o,s,40),(s=[]).push([["^","y","n"],["/",1,["^","y",["-","n"]]],{variables:{y:!0,n:a},evaluate_numbers:!0,max_digits:n}]),s.push([["apply","exp","n"],["/",1,["apply","exp",["-","n"]]],{variables:{n:a},evaluate_numbers:!0,max_digits:n}]),o=applyAllTransformations(o,s,40),(s=[]).push([["*","x",["/","y","z"]],["/",["*","x","y"],"z"],{allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s.push([["/",["/","x","y"],"z"],["/","x",["*","y","z"]],{allow_extended_match:!0,allow_permutations:!0}]),s.push([["/","x",["/","y","z"]],["/",["*","x","z"],"y"],{allow_extended_match:!0,allow_permutations:!0}]),evaluate_numbers(o=applyAllTransformations(o,s,40),{assumptions:t,max_digits:n})}function simplify_ratios(e,t){function n(e){var t=1;return e=e.map((function(e){if("number"==typeof e)return e<0?(t*=-1,-e):e;if(!Array.isArray(e))return e;if("-"===e[0])return t*=-1,e[1];if("+"!==e[0])return e;var n=!1;if(("number"==typeof e[1]&&e[1]<0||Array.isArray(e[1])&&"-"===e[1][0]||Array.isArray(e[1])&&"*"===e[1][0]&&Number(e[1][1])<0)&&(n=!0),n){t*=-1;var r=e.slice(1).map((e=>["-",e]));return evaluate_numbers(["+"].concat(r))}return e})),{factors:e,sign_change:t}}var r=get_tree(e);return contains_blank(r)?r:(void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),function e(t,r){if(!Array.isArray(t))return r?["-",t]:t;var a=t[0];if("-"===a)return e(t[1],r=!0);var i=t.slice(1).map((t=>e(t)));if("/"!==a)return r?["-",[a,...i]]:[a,...i];var o,s=i[0],l=i[1];s=default_order(s,{ignore_negatives:!0});var u,c=n(o=Array.isArray(s)&&"*"===s[0]?s.slice(1):[s]);o=c.factors,r&&(c.sign_change*=-1),l=default_order(l,{ignore_negatives:!0});var p=n(Array.isArray(l)&&"*"===l[0]?l.slice(1):[l]);return u=p.factors,c.sign_change*p.sign_change<0&&(o[0]=["-",o[0]]),["/",s=1===o.length?o[0]:["*"].concat(o),l=1===u.length?u[0]:["*"].concat(u)]}(r))}function contains_blank(e){return"_"===e||!!Array.isArray(e)&&e.some(contains_blank)}var simplify$1=Object.freeze({__proto__:null,clean:clean,simplify:simplify,simplify_logical:simplify_logical,evaluate_numbers:evaluate_numbers,collect_like_terms_factors:collect_like_terms_factors,collapse_unary_minus:collapse_unary_minus,simplify_ratios:simplify_ratios,default_order:default_order,perform_vector_matrix_additions_scalar_multiplications:perform_vector_matrix_additions_scalar_multiplications});function solve_linear(e,t,n){if("string"==typeof t){void 0===n&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(n=e.context.get_assumptions([e.variables()]));var r=simplify(get_tree(e),n);if(Array.isArray(r)){var a=r[0],i=r.slice(1);if("="===a||"ne"===a||"<"===a||"le"===a||">"===a||"ge"===a){var o=simplify(["+",i[0],["-",i[1]]],n),s=e=>!variables(e).includes(t);if(variables(o=simplify(applyAllTransformations(o,[[["+",["*","_a",t],["*","_b",t]],["*",["+","_a","_b"],t],{variables:{_a:s,_b:s},allow_permutations:!0,allow_extended_match:!0,allow_implicit_identities:["_a","_b"],evaluate_numbers:!0}]],20))).includes(t)){var l=match$2(o,["+",["*","_a",t],"_b"],{variables:{_a:s,_b:s},allow_permutations:!0,allow_implicit_identities:["_a","_b"]});if(l){var u=simplify(l._a),c=simplify(l._b);if(is_nonzero_ast(u,n)){if("="===a||"ne"===a||is_positive_ast(u,n)){let e=simplify(["/",["-",c],u]);return[a,t,e]}if(is_negative_ast(u,n)){var p=simplify(["/",["-",c],u]);return[a="<"===a?">":"le"===a?"ge":">"===a?"<":"le",t,p]}}}}}}}}var solve=Object.freeze({__proto__:null,solve_linear:solve_linear});function clean_assumptions(e,t){if(!Array.isArray(e)||0===e.length)return e;var n=(e=flatten$5(default_order(simplify_logical(expand_relations(e)))))[0],r=e.slice(1);if("and"===n||"or"===n){if(r=r.reduce((function(e,t){return e.every((function(e){return!equal(e,t)}))&&e.push(t),e}),[]),"and"===n&&t&&Array.isArray(t)){let e;e="and"===t[0]?t.slice(1):[t],r=r.filter((t=>e.every((e=>!equal(e,t)))))}e=1===r.length?r[0]:[n].concat(r)}if("and"!==n&&t&&Array.isArray(t)){let n;if(n="and"===t[0]?t.slice(1):[t],!n.every((t=>!equal(t,e))))return}return e}function calculate_derived_assumptions(e,t){if(void 0===t){t=[];for(let n in e.byvar){let r=e.byvar[n];r.length>0&&t.push(r)}if(0===t.length)return{};t=clean_assumptions(t=1===t.length?t[0]:["and"].concat(t))}if(!Array.isArray(t)||0===t.length)return{};var n=t[0],r=t.slice(1);if("and"===n||"or"===n){let t=r.map((function(t){return calculate_derived_assumptions(e,t)})),a=[...new Set(t.reduce(((e,t)=>[...e,...Object.keys(t)]),[]))],i={};for(let r of a){let a=t.reduce((function(e,t){return void 0!==t[r]&&e.push(t[r]),e}),[]);if("and"===n||a.length===t.length){let t=i[r];t=void 0===t?a.length>1?[n].concat(a):a[0]:a.length>1?["and",t,[n].concat(a)]:["and",t,a[0]],i[r]=clean_assumptions(t,get_assumptions(e,r,{omit_derived:!0}))}}return i}let a={};if("="===n||"ne"===n||"<"===n||"le"===n||"in"===n||"subset"===n||"notin"===n||"notsubset"===n){var i=!1;for(let t=0;t<2;t++){let s=r[t],l=r[1-t],u=variables(l);if("string"!=typeof s||0===u.length||u.includes(s))continue;i=!0;var o=n;1===t&&("<"===n?o=">":"le"===n?o="ge":"in"===n?o="ni":"subset"===n?o="superset":"notin"===n?o="notni":"notsubset"===n&&(o="notsuperset"));let c=get_assumptions_for_expr(e,l,[s]);if(c=combine_assumptions(s,o,l,c),void 0!==c){let t=a[s];t=void 0===t?c:["and",t,c],a[s]=clean_assumptions(t,get_assumptions(e,s,{omit_derived:!0}))}}if(i)return a}let s=[];for(let t of r){let n=get_assumptions_for_expr(e,t,[]);void 0!==n&&s.push(n)}if(0===s.length)return{};s=1===s.length?s[0]:["and"].concat(s);for(let n of variables(t))a[n]=clean_assumptions(s,get_assumptions(e,n,{omit_derived:!0}));return a}function get_assumptions_for_expr(e,t,n){let r=variables(t);if(r=r.filter((e=>!n.includes(e))),0===r.length)return;function a(e){return"number"==typeof e||!(!Array.isArray(e)||"-"!==e[0]||"number"!=typeof e[1])}var i=["_b"],o=["_b"],s={_b:a},l={};for(let e=0;evoid 0!==e));if(0===e.length)return;return"or"===o?e.length===s.length?["or"].concat(e):void 0:1===e.length?e[0]:["and"].concat(e)}if(!(["=","ne","<","le"].includes(o)||["in","notin","subset","notsubset"].includes(o)&&c)){let r=n.concat(variables(t)),a=[];for(let t of variables(i)){if(r.includes(t))continue;let n=get_assumptions_for_expr(e,t,r);void 0!==n&&a.push(n)}return 0===a.length?i:1===a.length?["and",i,a[0]]:["and",i].concat(a)}let u=[];for(let a=0;a<=1;a++){let i=s[a],c=s[1-a];if("string"==typeof i&&r.includes(i)){var p={};p[i]=c;var d=simplify(substitute$1(t,p)),m=!1,f=o;(1===a&&l[i]>0||0===a&&l[i]<0)&&("<"===o?(m=!0,f=">"):"le"===o?(m=!0,f="ge"):"in"===o?(m=!0,f="ni"):"subset"===o?(m=!0,f="superset"):"notin"===o?(m=!0,f="notni"):"notsubset"===o&&(m=!0,f="notsuperset")),m?u.push([o,d,t]):u.push([o,t,d]);let r=n.concat([i]),s=get_assumptions_for_expr(e,d,r);s=combine_assumptions(t,f,d,s),void 0!==s&&u.push(s)}}if(1===u.length)return u[0];if(u.length>1)return["and"].concat(u);let h=n.concat(variables(t));u=[];for(let t of variables(i)){if(h.includes(t))continue;let n=get_assumptions_for_expr(e,t,h);void 0!==n&&u.push(n)}return 0===u.length?i:1===u.length?["and",i,u[0]]:["and",i].concat(u)}(p)):void 0}function combine_assumptions(e,t,n,r){if(!["=","ne","<","le",">","ge","in","notin","ni","notni","subset","notsubset","superset","notsuperset"].includes(t))return r;if(Array.isArray(r)){var a=r[0],i=r.slice(1);if("and"===a||"or"===a){let r=i.map((r=>combine_assumptions(e,t,n,r))).filter((e=>void 0!==e));if(0===r.length)return;return"or"===a?r.length===i.length?[["or"].concat(r)]:void 0:1===r.length?r[0]:["and"].concat(r)}if(!["=","ne","<","le","in","notin","subset","notsubset"].includes(a))return r;var o,s,l=a;if(equal(i[0],n))o=i[1];else{if(!equal(i[1],n))return r;o=i[0],"<"===a?l=">":"le"===a?l="ge":"in"===a?l="ni":"notin"===a?l="notni":"subset"===a?l="superset":"notsubset"===a&&(l="notsuperset")}if("="===t)s=l;else if("="===l)s=t;else if("<"===t){if("<"!==l&&"le"!==l)return"in"===l||"notin"===l?r:void 0;s="<"}else if("le"===t)if("<"===l)s="<";else{if("le"!==l)return"in"===l||"notin"===l?r:void 0;s="le"}else if(">"===t){if(">"!==l&&"ge"!==l)return"in"===l||"notin"===l?r:void 0;s=">"}else if("ge"===t)if(">"===l)s=">";else{if("ge"!==l)return"in"===l||"notin"===l?r:void 0;s="ge"}else if("in"===t){if("subset"!==l)return;s="in"}else if("notin"===t){if("superset"!==l)return;s="notin"}else if("ni"===t){if("notin"!==l)return;s="notsubset"}else if("notni"===t){if("in"!==l)return;s="notsuperset"}else if("subset"===t)if("subset"===l)s="subset";else if("notni"===l)s="notni";else{if("notsuperset"!==l)return;s="notsuperset"}else if("notsubset"===t){if("superset"!==l)return;s="notsubset"}else if("superset"===t)if("superset"===l)s="superset";else if("ni"===l)s="ni";else{if("notsubset"!==l)return;s="notsubset"}else{if("notsuperset"!==t)return;if("subset"!==l)return;s="notsuperset"}return">"===s?["<",o,e]:"ge"===s?["le",o,e]:"ni"===s?["in",o,e]:"notni"===s?["notin",o,e]:"superset"===s?["subset",o,e]:"notsuperset"===s?["notsubset",o,e]:[s,e,o]}}function filter_assumptions_from_tree(e,t){if(Array.isArray(e)&&0!==e.length){Array.isArray(t)||(t=[t]);var n=e[0],r=e.slice(1);if("and"===n){var a=r.map((function(e){return filter_assumptions_from_tree(e,t)}));return 0===(a=a.filter((e=>void 0!==e))).length?void 0:1===a.length?a[0]:["and"].concat(a)}var i=variables(e);return t.filter((e=>i.includes(e))).length>0?void 0:e}}function get_assumptions_sub(e,t,n,r){Array.isArray(t)||(t=[t]);var a=[];return t.forEach((function(t){if(e.byvar[t]||e.derived[t]){if(e.byvar[t]&&e.byvar[t].length>0){var i=filter_assumptions_from_tree(e.byvar[t],n);void 0!==i&&a.push(i)}if(e.derived[t]&&e.derived[t].length>0&&!r){var o=filter_assumptions_from_tree(e.derived[t],n);void 0!==o&&a.push(o)}}else e.generic.length>0&&("x"!==t&&variables(e.generic).includes(t)||a.push(substitute$1(e.generic,{x:t})))})),1===a.length?a=a[0]:a.length>1&&(a=["and"].concat(a)),a.length>0?clean_assumptions(a):void 0}function get_assumptions(e,t,n){void 0===n&&(n={});var r,a=n.exclude_variables;void 0===a?a=[]:Array.isArray(a)||(a=[a]);var i=get_tree(t);if("string"==typeof i)r=[i];else{if(!Array.isArray(i))return;Array.isArray(i[0])&&(r=i[0])}return r?get_assumptions_sub(e,r,a,n.omit_derived):get_assumptions_for_expr(e,i,a)}function add_assumption(e,t,n){var r=get_tree(t);if(!Array.isArray(r))return 0;var a=add_assumption_sub(e,r=clean_assumptions(simplify(r,e)),n);return a&&(e.derived=calculate_derived_assumptions(e)),a}function add_assumption_sub(e,t,n){if("and"===t[0])return t.slice(1).map((t=>add_assumption_sub(e,t,n))).reduce((function(e,t){return e+t}));var r=variables(t);if(0===r.length)return 0;let a=0;!n&&e.generic.length>0&&r.forEach((function(t){void 0===e.byvar[t]&&("x"!==t&&variables(e.generic).includes(t)||(add_assumption_sub(e,substitute$1(e.generic,{x:t}),!0),a+=1))}));for(let n of r){let r=solve_linear(t,n,e),i=t;r&&(i=r);let o=e.byvar[n];void 0!==o&&0!==o.length&&(i=["and",o,i]),i=clean_assumptions(i),equal(i,o)||(e.byvar[n]=i,a+=1)}return a}function add_generic_assumption(e,t){var n=get_tree(t);if(!Array.isArray(n))return 0;var r=add_generic_assumption_sub(e,n=clean_assumptions(simplify(n,e)));return r&&(e.derived=calculate_derived_assumptions(e)),r}function add_generic_assumption_sub(e,t){if("and"===t[0])return t.slice(1).map((t=>add_generic_assumption_sub(e,t))).reduce((function(e,t){return e+t}));if(!variables(t).includes("x"))return 0;let n=solve_linear(t,"x",e),r=t;n&&(r=n);let a=e.generic;return 0!==a.length&&(r=["and",a,r]),r=clean_assumptions(r),equal(r,a)?0:(e.generic=r,1)}function remove_assumption(e,t){var n=get_tree(t);if(!Array.isArray(n))return 0;var r=remove_assumption_sub(e,n=clean_assumptions(simplify(n,e)));return r&&(e.derived=calculate_derived_assumptions(e)),r}function remove_assumption_sub(e,t){if("and"===t[0])return t.slice(1).map((t=>remove_assumption_sub(e,t))).reduce((function(e,t){return e+t}));var n=variables(t);if(0===n.length)return 0;var r=0;for(let a of n){let n=solve_linear(t,a,e),i=e.byvar[a];if(!i||0===i.length)continue;let o,s=i[0],l=i.slice(1),u=l.length;if("and"===s)if(l=l.filter((e=>!(equal(e,t)||equal(e,n)))),0===l.length)o=[];else if(1===l.length)o=l[0];else{if(!(l.lengthremove_generic_assumption_sub(e,t))).reduce((function(e,t){return e+t}));if(!variables(t).includes("x"))return 0;var n=e.generic;if(0===n.length)return 0;let r=solve_linear(t,"x",e);var a,i=n[0],o=n.slice(1),s=o.length;if("and"===i)if(0===(o=o.filter((e=>!(equal(e,t)||equal(e,r))))).length)a=[];else if(1===o.length)a=o[0];else{if(!(o.length0)if(e.includes(".")){if("0"!==e[0]?n++:n+=e.match(/^0\.0*/)[0].length,e.length0)if(e.includes(".")){let t=e.match(/\.\d*$/)[0].length-1;t":function(e){return e.join(" > ")},lts:function(e){return e.join(" < ")},gts:function(e){return e.join(" > ")},le:function(e){return e.join(" \\le ")},ge:function(e){return e.join(" \\ge ")},ne:function(e){return e.join(" \\ne ")},in:function(e){return e[0]+" \\in "+e[1]},notin:function(e){return e[0]+" \\notin "+e[1]},ni:function(e){return e[0]+" \\ni "+e[1]},notni:function(e){return e[0]+" \\not\\ni "+e[1]},subset:function(e){return e[0]+" \\subset "+e[1]},notsubset:function(e){return e[0]+" \\not\\subset "+e[1]},superset:function(e){return e[0]+" \\supset "+e[1]},notsuperset:function(e){return e[0]+" \\not\\supset "+e[1]},union:function(e){return e.join(" \\cup ")},intersect:function(e){return e.join(" \\cap ")},derivative_leibniz:function(e){return"\\frac{d"+e[0]+"}{d"+e[1]+"}"},partial_derivative_leibniz:function(e){return"\\frac{d"+e[0]+"}{d"+e[1]+"}"},"|":function(e){return e[0]+" \\mid "+e[1]},":":function(e){return e[0]+" : "+e[1]}},allowedLatexSymbolsDefault$1=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","abs","exp","log","ln","log10","sign","sqrt","erf","acos","acosh","acot","acoth","acsc","acsch","asec","asech","asin","asinh","atan","atanh","cos","cosh","cot","coth","csc","csch","sec","sech","sin","sinh","tan","tanh","arcsin","arccos","arctan","arccsc","arcsec","arccot","cosec","arg","Re","Im","det","trace"],matrixEnvironmentDefault="bmatrix";class astToLatex$1{constructor({allowedLatexSymbols:e=allowedLatexSymbolsDefault$1,matrixEnvironment:t=matrixEnvironmentDefault,padToDigits:n=null,padToDecimals:r=null,showBlanks:a=!0}={}){this.allowedLatexSymbols=e,this.matrixEnvironment=t,this.padToDigits=n,this.padToDecimals=r,this.showBlanks=a}convert(e){return this.statement(e)}statement(e){if(!Array.isArray(e))return this.single_statement(e);var t=e[0],n=e.slice(1);if("ldots"===t)return"\\ldots";if(!(t in operators$1)&&"apply"!==t)throw new Error("Badly formed ast: operator "+t+" not recognized.");return"and"===t||"or"===t?operators$1[t](n.map(function(e,t){let n=this.single_statement(e);return n.toString().match(/ /)&&!n.toString().match(/^\\left\(.*\\right\)$/)?"\\left("+n+"\\right)":n}.bind(this))):this.single_statement(e)}single_statement(e){if(!Array.isArray(e))return this.expression(e);var t=e[0],n=e.slice(1);if("not"===t)return operators$1[t](n.map(function(e,t){let n=this.single_statement(e);return n.toString().match(/ /)&&!n.toString().match(/^\\left\(.*\\right\)$/)?"\\left("+n+"\\right)":n}.bind(this)));if("="===t||"ne"===t||"<"===t||">"===t||"le"===t||"ge"===t||"in"===t||"notin"===t||"ni"===t||"notni"===t||"subset"===t||"notsubset"===t||"superset"===t||"notsuperset"===t)return operators$1[t](n.map(function(e,t){return this.expression(e)}.bind(this)));if("lts"===t||"gts"===t){let e=n[0],r=n[1];if("tuple"!==e[0]||"tuple"!==r[0])throw new Error("Badly formed ast");let a=this.expression(e[1]);for(let n=1;n ":a+="lts"===t?" \\le ":" \\ge ",a+=this.expression(e[n+1]);return a}return this.expression(e)}expression(e){if(!Array.isArray(e))return this.term(e);var t=e[0],n=e.slice(1);return"+"===t?operators$1[t](n.map(function(e,t){return t>0?this.termWithPlusIfNotNegated(e):this.term(e)}.bind(this))):"union"===t||"intersect"===t?operators$1[t](n.map(function(e,t){return this.term(e)}.bind(this))):this.term(e)}term(e){if(!Array.isArray(e))return this.factor(e);var t=e[0],n=e.slice(1);return"-"===t?operators$1[t](n.map(function(e,t){return this.term(e)}.bind(this))):"*"===t?operators$1[t](n.map(function(e,t){let n;return t>0?(n=this.factorWithParenthesesIfNegated(e),n.toString().match(/^[0-9]/)?"\\cdot "+n:"\\, "+n):this.factor(e)}.bind(this))):"/"===t?operators$1[t](n.map(function(e,t){return this.expression(e)}.bind(this))):this.factor(e)}simple_factor_or_function_or_parens(e){var t=this.factor(e);return!!(t.toString().length<=1||"string"==typeof e&&e.match(/^\w+$/)||Array.isArray(e)&&"apply"===e[0]&&"sqrt"!==e[1]||t.toString().match(/^\\left\(.*\\right\)$/))||"number"==typeof e&&e>=0&&!e.toString().includes("e")}stringConvert(e){return e.length>1?this.allowedLatexSymbols.includes(e)?"\\"+e:"\\var{"+e+"}":"_"!==e||this.showBlanks?e:""}factor(e){if("string"==typeof e)return this.stringConvert(e);if("number"==typeof e){if(e===1/0)return"\\infty";if(e===-1/0)return"-\\infty";if(Number.isNaN(e))return"NaN";{let t=e.toString(),n=t.indexOf("e");if(-1===n)return null!==this.padToDigits?t=padNumberStringToDigits(t,this.padToDigits):null!==this.padToDecimals&&(t=padNumberStringToDecimals(t,this.padToDecimals)),t;let r=t.substring(0,n),a=t.substring(n+1);if("+"===a[0]&&(a=a.slice(1)),null!==this.padToDigits)r=padNumberStringToDigits(r,this.padToDigits);else if(null!==this.padToDecimals){let n=Number(a);if(n>0)return t=e.toLocaleString("fullwide",{useGrouping:!1}),padNumberStringToDecimals(t,this.padToDecimals);r=padNumberStringToDecimals(r,this.padToDecimals+n)}return r+" \\cdot 10^{"+a+"}"}}if(!Array.isArray(e))return"";var t=e[0],n=e.slice(1);if("^"===t){if(Number.isInteger(n[0])&&Number.isInteger(n[1]))return n[0]<0?"\\left("+n[0].toString()+"\\right)^{"+n[1].toString()+"}":n[0].toString()+"^{"+n[1].toString()+"}";let e=this.factor(n[0]),t=n[0];for(;"prime"===t[0];)t=t[1];return this.simple_factor_or_function_or_parens(t)||"_"===t[0]&&"string"==typeof t[1]||(e="\\left("+e.toString()+"\\right)"),e+"^{"+this.statement(n[1])+"}"}if("_"===t){let e=this.factor(n[0]);return this.simple_factor_or_function_or_parens(n[0])||(e="\\left("+e.toString()+"\\right)"),e+"_{"+this.statement(n[1])+"}"}if("prime"===t){let e=n[0],t=1;for(;"prime"===e[0];)t+=1,e=e[1];let r=this.factor(e);this.simple_factor_or_function_or_parens(e)||"_"===e[0]&&"string"==typeof e[1]||(r="\\left("+r.toString()+"\\right)");for(let e=0;e1?s=s.trimRight()+"^{"+i+"}"+this.stringConvert(o):s+=this.stringConvert(o),s="\\frac{ "+s+" }{ ";let l=1;Array.isArray(a)&&(l=a.length-1);for(let t=1;t<=l;t++){let n=a[t],r=1,i="";Array.isArray(n)?(i=n[1],r=n[2]):i=n,s=s+e+this.stringConvert(i),r>1&&(s=s+"^{"+r+"}"),s+=" "}return s+="}",s}if("apply"===t){if("abs"===n[0])return"\\left|"+this.statement(n[1])+"\\right|";if("factorial"===n[0]){let e=this.factor(n[1]);return this.simple_factor_or_function_or_parens(n[1])||"_"===n[1][0]&&"string"==typeof n[1][1]?e+"!":"\\left("+e.toString()+"\\right)!"}if("sqrt"===n[0])return"\\sqrt{"+this.statement(n[1])+"}";let e;e="log10"===n[0]?"\\log_{10}":"re"===n[0]?"\\Re":"im"===n[0]?"\\Im":this.factor(n[0]);let t=this.statement(n[1]);return"tuple"!==n[1][0]&&(t="\\left("+t+"\\right)"),e+t}return"+"===t&&2===e.length?"+ "+this.factor(e[1]):"\\left("+this.statement(e)+"\\right)"}factorWithParenthesesIfNegated(e){var t=this.factor(e);return t.toString().match(/^-/)?"\\left("+t.toString()+"\\right)":t}termWithPlusIfNotNegated(e){var t=this.term(e);let n=t.toString();return n.match(/^-/)?n.match(/^-[^ ]/)?"- "+n.slice(1):t:"+ "+n}}const textToAst$2=new textToAst$4,astToLatex=new astToLatex$1;var derivatives={sin:textToAst$2.convert("cos x"),cos:textToAst$2.convert("-(sin x)"),tan:textToAst$2.convert("(sec x)^2"),cot:textToAst$2.convert("-((csc x)^2)"),sec:textToAst$2.convert("(sec x)*(tan x)"),csc:textToAst$2.convert("-(csc x)*(cot x)"),sqrt:textToAst$2.convert("1/(2*sqrt(x))"),log:textToAst$2.convert("1/x"),ln:textToAst$2.convert("1/x"),exp:textToAst$2.convert("exp(x)"),arcsin:textToAst$2.convert("1/sqrt(1 - x^2)"),arccos:textToAst$2.convert("-1/sqrt(1 - x^2)"),arctan:textToAst$2.convert("1/(1 + x^2)"),arccsc:textToAst$2.convert("-1/(sqrt(-1/x^2 + 1)*x^2)"),arcsec:textToAst$2.convert("1/(sqrt(-1/x^2 + 1)*x^2)"),arccot:textToAst$2.convert("-1/(1 + x^2)"),abs:textToAst$2.convert("abs(x)/x")};function derivative(e,t,n=[]){var r=get_tree(e),a="\\frac{d}{d"+t+"} ";if("number"==typeof r)return n.push("The derivative of a constant is zero, that is, \\("+a+astToLatex.convert(r)+" = 0\\)."),0;if(variables(r).indexOf(t)<0)return n.push("The derivative of a constant is zero, that is, \\("+a+astToLatex.convert(r)+" = 0\\)."),0;if("string"==typeof r)return t===r?(n.push("We know the derivative of the identity function is one, that is, \\("+a+astToLatex.convert(r)+" = 1\\)."),1):(n.push("As far as \\("+astToLatex.convert(t)+"\\) is concerned, \\("+astToLatex.convert(r)+"\\) is constant, so "+a+astToLatex.convert(r)+" = 0\\)."),0);if(!Array.isArray(r))return null;var i=r[0],o=r.slice(1);if("+"===i||"-"===i||"~"===i){n.push("Using the sum rule, \\("+a+astToLatex.convert(r)+" = "+o.map((function(e,t){return a+astToLatex.convert(e)})).join(" + ")+"\\).");let e=[i].concat(o.map((function(e,r){return derivative(e,t,n)})));return e=simplify(e),n.push("So using the sum rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\)."),e}if("*"===i){let e=[],i=[];for(let n=0;n0){if(0===e.length)return n.push("Since the derivative of a constant is zero, \\("+a+astToLatex.convert(r)+" = 0.\\)"),0;let o=["*"].concat(e);if(1===e.length&&(o=e[0]),o===t){n.push("By the constant multiple rule, \\("+a+astToLatex.convert(r)+" = "+i.map((function(e,t){return astToLatex.convert(e)})).join(" \\cdot ")+"\\).");let e=["*"].concat(i);return e=simplify(e),e}n.push("By the constant multiple rule, \\("+a+astToLatex.convert(r)+" = "+i.map((function(e,t){return astToLatex.convert(e)})).join(" \\cdot ")+" \\cdot "+a+"\\left("+astToLatex.convert(o)+"\\right)\\).");let s=derivative(o,t,n),l=["*"].concat(i.concat([s]));return l=simplify(l),n.push("And so \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}n.push("Using the product rule, \\("+a+astToLatex.convert(r)+" = "+o.map((function(e,t){return o.map((function(n,r){return t===r?a+"\\left("+astToLatex.convert(e)+"\\right)":astToLatex.convert(n)})).join(" \\cdot ")})).join(" + ")+"\\).");let s=o.slice(),l=["+"].concat(o.map((function(e,r){return["*"].concat(s.map((function(e,a){if(r===a){let r=derivative(e,t,n);return 1===r?null:r}return e})).filter((function(e){return null!=e})))})));return l=simplify(l),n.push("So using the product rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}if("/"===i){let e=o[0],i=o[1];if(variables(i).indexOf(t)<0){n.push("By the constant multiple rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(["/",1,i])+" \\cdot "+a+"\\left("+astToLatex.convert(e)+"\\right)\\).");let o=derivative(e,t,n),s=textToAst$2.convert("(1/g)*d"),l=substitute$1(s,{d:o,g:i});return l=simplify(l),n.push("So \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}if(variables(e).indexOf(t)<0){1!==e&&n.push("By the constant multiple rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+" \\cdot "+a+"\\left("+astToLatex.convert(["/",1,i])+"\\right)\\)."),n.push("Since \\(\\frac{d}{du} \\frac{1}{u}\\) is \\(\\frac{-1}{u^2}\\), the chain rule gives \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\cdot \\frac{-1}{ "+astToLatex.convert(i)+"^2} \\cdot "+a+astToLatex.convert(i)+"\\).");let o=derivative(i,t,n),s=textToAst$2.convert("f * (-a/(g^2))"),l=substitute$1(s,{f:e,a:o,g:i});return l=simplify(l),n.push("So since \\(\\frac{d}{du} \\frac{1}{u}\\) is \\(\\frac{-1}{u^2}\\), the chain rule gives \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}n.push("Using the quotient rule, \\("+a+astToLatex.convert(r)+" = \\frac{"+a+"\\left("+astToLatex.convert(e)+"\\right) \\cdot "+astToLatex.convert(i)+" - "+astToLatex.convert(e)+"\\cdot "+a+"\\left("+astToLatex.convert(i)+"\\right)}{ \\left( "+astToLatex.convert(i)+" \\right)^2} \\).");let s=derivative(e,t,n),l=derivative(i,t,n),u=textToAst$2.convert("(a * g - f * b)/(g^2)"),c=substitute$1(u,{a:s,b:l,f:e,g:i});return c=simplify(c),n.push("So using the quotient rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(c)+"\\)."),c}if("^"===i){let e=o[0],i=o[1];if(variables(i).indexOf(t)<0){if("string"==typeof e&&"x"===e){if("number"==typeof i){let t=textToAst$2.convert("n * (f^m)"),o=substitute$1(t,{n:i,m:i-1,f:e});return o=simplify(o),n.push("By the power rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(i)+" \\cdot \\left("+astToLatex.convert(e)+"\\right)^{"+astToLatex.convert(["-",i,1])+"}\\)."),o}let t=textToAst$2.convert("n * (f^(n-1))"),o=substitute$1(t,{n:i,f:e});return o=simplify(o),n.push("By the power rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(i)+" \\cdot \\left("+astToLatex.convert(e)+"\\right)^{"+astToLatex.convert(["-",i,1])+"}\\)."),o}1!==i&&n.push("By the power rule and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(i)+" \\cdot \\left("+astToLatex.convert(e)+"\\right)^{"+astToLatex.convert(["-",i,1])+"} \\cdot "+a+astToLatex.convert(e)+"\\).");let o=derivative(e,t,n);if(1===i)return o;if("number"==typeof i){let t=textToAst$2.convert("n * (f^m) * a"),s=substitute$1(t,{n:i,m:i-1,f:e,a:o});return s=simplify(s),n.push("So by the power rule and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(s)+"\\)."),s}let s=textToAst$2.convert("n * (f^(n-1)) * a"),l=substitute$1(s,{n:i,f:e,a:o});return l=simplify(l),n.push("So by the power rule and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}if("e"===e&&math$1.define_e){if("string"==typeof i&&i===t){let e=textToAst$2.convert("e^(f)"),o=substitute$1(e,{f:i});return o=simplify(o),n.push("The derivative of \\(e^"+astToLatex.convert(t)+"\\) is itself, that is, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(r)+"\\)."),o}n.push("Using the rule for \\(e^x\\) and the chain rule, we know \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(r)+" \\cdot "+a+astToLatex.convert(i)+"\\).");let e=textToAst$2.convert("e^(f)*d"),o=derivative(i,t,n),s=substitute$1(e,{f:i,d:o});return s=simplify(s),n.push("So using the rule for \\(e^x\\) and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(s)+"\\)."),s}if("number"==typeof e){if("string"==typeof i&&i===t){let o=textToAst$2.convert("a^(f) * log(a)"),s=substitute$1(o,{a:e,f:i});return s=simplify(s),n.push("The derivative of \\(a^"+astToLatex.convert(t)+"\\) is \\(a^{"+astToLatex.convert(t)+"} \\, \\log a\\), that is, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(s)+"\\)."),s}let o=textToAst$2.convert("a^(f) * log(a)"),s=substitute$1(o,{a:e,f:i});n.push("Using the rule for \\(a^x\\) and the chain rule, we know \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(s)+" \\cdot "+a+astToLatex.convert(i)+"\\).");let l=textToAst$2.convert("a^(b)*log(a)*d"),u=derivative(i,t,n),c=substitute$1(l,{a:e,b:i,d:u});return c=simplify(c),n.push("So using the rule for \\(a^x\\) and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(c)+"\\)."),c}let s=e,l=i;n.push("Recall the general rule for exponents, namely that \\(\\frac{d}{dx} u(x)^{v(x)} = u(x)^{v(x)} \\cdot \\left( v'(x) \\cdot \\log u(x) + \\frac{v(x) \\cdot u'(x)}{u(x)} \\right)\\). In this case, \\(u(x) = "+astToLatex.convert(s)+"\\) and \\(v(x) = "+astToLatex.convert(l)+"\\).");let u=derivative(s,t,n),c=derivative(l,t,n),p=textToAst$2.convert("(f^g)*(b * log(f) + (g * a)/f)"),d=substitute$1(p,{a:u,b:c,f:s,g:l});return d=simplify(d),n.push("So by the general rule for exponents, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(d)+"\\)."),d}if("apply"===i&&!(o[0]in derivatives)){let e=o[1];n.push("By the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(substitute$1(["apply",o[0]+"'","x"],{x:e}))+" \\cdot "+a+astToLatex.convert(e)+"\\).");let i=["*",substitute$1(["apply",o[0]+"'","x"],{x:e}),derivative(e,t,n)];return i=simplify(i),n.push("So by the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(i)+"\\)."),i}if("apply"===i&&o[0]in derivatives||i in derivatives){let e=!1;"apply"===i&&(i=o[0],o=o.slice(1),e=!0);let s=o[0];if("number"==typeof s){let e=0;return n.push("The derivative of a constant is zero so \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\)."),e}if("string"==typeof s&&s===t){let e=["*",substitute$1(derivatives[i],{x:s})];return e=simplify(e),n.push("It is the case that \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\)."),e}if("string"==typeof s&&s!==t){let e=0;return n.push("Since the derivative of a constant is zero, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\)."),e}{let o=[i,"u"];e&&(o=["apply"].concat(o)),n.push("Recall \\(\\frac{d}{du}"+astToLatex.convert(o)+" = "+astToLatex.convert(derivative(o,"u",[]))+"\\)."),n.push("By the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(substitute$1(derivatives[i],{x:s}))+" \\cdot "+a+astToLatex.convert(s)+"\\).");let l=["*",substitute$1(derivatives[i],{x:s}),derivative(s,t,n)];return l=simplify(l),n.push("So by the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}}return 0}function lowercaseFirstLetter(e){return e.charAt(0).toLowerCase()+e.slice(1)}function simplify_story(e){for(let t=e.length-1;t>=1;t--)e[t]===e[t-1]&&e.splice(t,1);for(let t=0;t":function(e){return e.join(" > ")},lts:function(e){return e.join(" < ")},gts:function(e){return e.join(" > ")},le:function(e){return e.join(" ≤ ")},ge:function(e){return e.join(" ≥ ")},ne:function(e){return e.join(" ≠ ")},in:function(e){return e[0]+" ∈ "+e[1]},notin:function(e){return e[0]+" ∉ "+e[1]},ni:function(e){return e[0]+" ∋ "+e[1]},notni:function(e){return e[0]+" ∌ "+e[1]},subset:function(e){return e[0]+" ⊂ "+e[1]},notsubset:function(e){return e[0]+" ⊄ "+e[1]},superset:function(e){return e[0]+" ⊃ "+e[1]},notsuperset:function(e){return e[0]+" ⊅ "+e[1]},union:function(e){return e.join(" ∪ ")},intersect:function(e){return e.join(" ∩ ")},derivative_leibniz:function(e){return"d"+e[0]+"/d"+e[1]},partial_derivative_leibniz:function(e){return"∂"+e[0]+"/∂"+e[1]},"|":function(e){return e[0]+" | "+e[1]},":":function(e){return e[0]+" : "+e[1]}},nonunicode_operators={"+":function(e){return e.join(" ")},"-":function(e){return"-"+e[0]},"*":function(e){return e.join(" ")},"/":function(e){return e[0]+"/"+e[1]},_:function(e){return e[0]+"_"+e[1]},"^":function(e){return e[0]+"^"+e[1]},prime:function(e){return e[0]+"'"},tuple:function(e){return"( "+e.join(", ")+" )"},array:function(e){return"[ "+e.join(", ")+" ]"},list:function(e){return e.join(", ")},set:function(e){return"{ "+e.join(", ")+" }"},vector:function(e){return"( "+e.join(", ")+" )"},interval:function(e){return"( "+e.join(", ")+" )"},matrix:function(e){return"( "+e.join(", ")+" )"},and:function(e){return e.join(" and ")},or:function(e){return e.join(" or ")},not:function(e){return"not "+e[0]},"=":function(e){return e.join(" = ")},"<":function(e){return e.join(" < ")},">":function(e){return e.join(" > ")},lts:function(e){return e.join(" < ")},gts:function(e){return e.join(" > ")},le:function(e){return e.join(" <= ")},ge:function(e){return e.join(" >= ")},ne:function(e){return e.join(" ne ")},in:function(e){return e[0]+" elementof "+e[1]},notin:function(e){return e[0]+" notelementof "+e[1]},ni:function(e){return e[0]+" containselement "+e[1]},notni:function(e){return e[0]+" notcontainselement "+e[1]},subset:function(e){return e[0]+" subset "+e[1]},notsubset:function(e){return e[0]+" notsubset "+e[1]},superset:function(e){return e[0]+" superset "+e[1]},notsuperset:function(e){return e[0]+" notsuperset "+e[1]},union:function(e){return e.join(" union ")},intersect:function(e){return e.join(" intersect ")},derivative_leibniz:function(e){return"d"+e[0]+"/d"+e[1]},partial_derivative_leibniz:function(e){return"∂"+e[0]+"/∂"+e[1]},"|":function(e){return e[0]+" | "+e[1]},":":function(e){return e[0]+" : "+e[1]}},output_unicodeDefault=!0;class astToText$1{constructor({output_unicode:e=output_unicodeDefault,padToDigits:t=null,padToDecimals:n=null,showBlanks:r=!0}={}){this.output_unicode=e,this.operators=unicode_operators,e||(this.operators=nonunicode_operators),this.padToDigits=t,this.padToDecimals=n,this.showBlanks=r}convert(e){return this.statement(e)}statement(e){if(!Array.isArray(e))return this.single_statement(e);let t=e[0],n=e.slice(1);if("ldots"===t)return"...";if(!(t in this.operators)&&"apply"!==t)throw new Error("Badly formed ast: operator "+t+" not recognized.");return"and"===t||"or"===t?this.operators[t](n.map(function(e,t){let n=this.single_statement(e);return n.toString().match(/ /)&&!n.toString().match(/^\(.*\)$/)?"("+n+")":n}.bind(this))):this.single_statement(e)}single_statement(e){if(!Array.isArray(e))return this.expression(e);let t=e[0],n=e.slice(1);if("not"===t)return this.operators[t](n.map(function(e,t){let n=this.single_statement(e);return n.toString().match(/ /)&&!n.toString().match(/^\(.*\)$/)?"("+n+")":n}.bind(this)));if("="===t||"ne"===t||"<"===t||">"===t||"le"===t||"ge"===t||"in"===t||"notin"===t||"ni"===t||"notni"===t||"subset"===t||"notsubset"===t||"superset"===t||"notsuperset"===t)return this.operators[t](n.map(function(e,t){return this.expression(e)}.bind(this)));if("lts"===t||"gts"===t){let e=n[0],r=n[1];if("tuple"!==e[0]||"tuple"!==r[0])throw new Error("Badly formed ast");let a=this.expression(e[1]);for(let n=1;n ":"lts"===t?this.output_unicode?a+=" ≤ ":a+=" <= ":this.output_unicode?a+=" ≥ ":a+=" >= ",a+=this.expression(e[n+1]);return a}return this.expression(e)}expression(e){if(!Array.isArray(e))return this.term(e);let t=e[0],n=e.slice(1);return"+"===t?this.operators[t](n.map(function(e,t){return t>0?this.termWithPlusIfNotNegated(e):this.term(e)}.bind(this))):"union"===t||"intersect"===t?this.operators[t](n.map(function(e,t){return this.term(e)}.bind(this))):this.term(e)}term(e){if(!Array.isArray(e))return this.factor(e);let t=e[0],n=e.slice(1);if("-"===t)return this.operators[t](n.map(function(e,t){return this.term(e)}.bind(this)));if("*"===t)return this.operators[t](n.map(function(e,t){let n;return t>0?(n=this.factorWithParenthesesIfNegated(e),n.toString().match(/^[0-9]/)?"* "+n:n):this.factor(e)}.bind(this)));if("/"===t){let e=this.factor(n[0]),r=this.factor(n[1]);return this.simple_factor_or_function_or_parens(n[0])||(e="("+e+")"),this.simple_factor_or_function_or_parens(n[1])||(r="("+r+")"),this.operators[t]([e,r])}return this.factor(e)}symbolConvert(e){let t={alpha:"α",beta:"β",Gamma:"Γ",gamma:"γ",Delta:"Δ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",Theta:"ϴ",theta:"θ",iota:"ι",kappa:"κ",Lambda:"Λ",lambda:"λ",mu:"μ",nu:"ν",Xi:"Ξ",xi:"ξ",Pi:"Π",pi:"π",rho:"ρ",Sigma:"Σ",sigma:"σ",tau:"τ",Upsilon:"Υ",upsilon:"υ",Phi:"Φ",phi:"ϕ",Psi:"Ψ",psi:"ψ",Omega:"Ω",omega:"ω"};return this.output_unicode&&e in t?t[e]:this.showBlanks||"_"!==e?e:""}simple_factor_or_function_or_parens(e){let t=this.factor(e);return!!(t.toString().length<=1||"string"==typeof e&&e.match(/^\w+$/)||Array.isArray(e)&&"apply"===e[0]||t.toString().match(/^\(.*\)$/))||"number"==typeof e&&e>=0&&!e.toString().includes("e")}factor(e){if("string"==typeof e)return this.symbolConvert(e);if("number"==typeof e){if(e===1/0)return this.output_unicode?"∞":"infinity";if(e===-1/0)return this.output_unicode?"-∞":"-infinity";if(Number.isNaN(e))return"NaN";{let t=e.toString(),n=t.indexOf("e");if(-1===n)return null!==this.padToDigits?t=padNumberStringToDigits(t,this.padToDigits):null!==this.padToDecimals&&(t=padNumberStringToDecimals(t,this.padToDecimals)),t;let r=t.substring(0,n),a=t.substring(n+1);if(null!==this.padToDigits)r=padNumberStringToDigits(r,this.padToDigits);else if(null!==this.padToDecimals){let n=Number(a);if(n>0)return t=e.toLocaleString("fullwide",{useGrouping:!1}),padNumberStringToDecimals(t,this.padToDecimals);r=padNumberStringToDecimals(r,this.padToDecimals+n)}return"+"===a[0]?r+" * 10^"+a.substring(1):r+" * 10^("+a+")"}}if(!Array.isArray(e))return"";let t=e[0],n=e.slice(1);if("^"===t){if(Number.isInteger(n[0])&&Number.isInteger(n[1])){let e;return e=n[0]<0?"("+n[0].toString()+")":n[0].toString(),n[1]<0?e+"^("+n[1].toString()+")":e+"^"+n[1].toString()}let e=this.factor(n[0]),t=n[0];for(;"prime"===t[0];)t=t[1];this.simple_factor_or_function_or_parens(t)||"_"===t[0]&&"string"==typeof t[1]||(e="("+e.toString()+")");let r=this.factor(n[1]);return this.simple_factor_or_function_or_parens(n[1])||(r="("+r.toString()+")"),e+"^"+r}if("_"===t)return this.operators[t](n.map(function(e,t){let n=this.factor(e);return this.simple_factor_or_function_or_parens(e)?n:"("+n.toString()+")"}.bind(this)));if("prime"===t){let e=n[0],t=1;for(;"prime"===e[0];)t+=1,e=e[1];let r=this.factor(e);this.simple_factor_or_function_or_parens(e)||"_"===e[0]&&"string"==typeof e[1]||(r="("+r.toString()+")");for(let e=0;e1&&(s=s+"^"+i),s=s+this.symbolConvert(o)+"/";let l=1;Array.isArray(a)&&(l=a.length-1);for(let t=1;t<=l;t++){let n=a[t],r=1,i="";Array.isArray(n)?(i=n[1],r=n[2]):i=n,s=s+e+this.symbolConvert(i),r>1&&(s=s+"^"+r)}return s}if("apply"===t){if("abs"===n[0])return"|"+this.statement(n[1])+"|";if("factorial"===n[0]){let e=this.factor(n[1]);return this.simple_factor_or_function_or_parens(n[1])||"_"===n[1][0]&&"string"==typeof n[1][1]?e+"!":"("+e.toString()+")!"}let e=this.factor(n[0]),t=this.statement(n[1]);return"tuple"!==n[1][0]&&(t="("+t+")"),e+t}return"+"===t&&2===e.length?"+ "+this.factor(e[1]):"("+this.statement(e)+")"}factorWithParenthesesIfNegated(e){let t=this.factor(e);return t.toString().match(/^-/)?"("+t.toString()+")":t}termWithPlusIfNotNegated(e){let t=this.term(e),n=t.toString();return n.match(/^-/)?n.match(/^-[^ ]/)?"- "+n.slice(1):t:"+ "+n}}var astToText=new astToText$1;function subscripts_to_strings(e,t=!1){var n=get_tree(e);if(!Array.isArray(n))return n;let r=n[0],a=n.slice(1);return"_"===r&&(t||a.every((e=>["number","string"].includes(typeof e))))?astToText.convert(n):[r].concat(a.map((e=>subscripts_to_strings(e,t))))}function strings_to_subscripts(e){var t=get_tree(e);if("string"==typeof t){let e=t.match(/^([0-9a-zA-Z]+)_([a-zA-Z]+|[0-9]+)$/);if(e){let t=Number(e[1]);isNaN(t)&&(t=e[1]);let n=Number(e[2]);return isNaN(n)&&(n=e[2]),["_",t,n]}return t}if(!Array.isArray(t))return t;let n=t[0],r=t.slice(1);return[n].concat(r.map(strings_to_subscripts))}var normalization=Object.freeze({__proto__:null,normalize_function_names:normalize_function_names,normalize_applied_functions:normalize_applied_functions,substitute_abs:substitute_abs,default_order:default_order,constants_to_floats:constants_to_floats,tuples_to_vectors:tuples_to_vectors,to_intervals:to_intervals,subscripts_to_strings:subscripts_to_strings,strings_to_subscripts:strings_to_subscripts});function generate_random_integer(e,t,n){return e=math$1.ceil(e),t=math$1.floor(t),math$1.floor(n()*(t-e+1))+e}const equals$5=function({expr:e,other:t,randomBindings:n,expr_context:r,other_context:a,relative_tolerance:i=1e-12,absolute_tolerance:o=0,tolerance_for_zero:s=1e-15,allowed_error_in_numbers:l=0,include_error_in_number_exponents:u=!1,allowed_error_is_absolute:c=!1,rng:p}){if(Array.isArray(e.tree)&&Array.isArray(t.tree)){let d=e.tree[0],m=e.tree.slice(1),f=t.tree[0],h=t.tree.slice(1);if("tuple"===d||"vector"===d||"list"===d||"array"===d||"matrix"===d||"interval"===d){if(f!==d)return!1;if(h.length!==m.length)return!1;for(let e=0;e","<","ge","le"].includes(d)){if(2!==h.length)return!1;if(">"===d?(d="<",m=[m[1],m[0]]):"ge"===d&&(d="le",m=[m[1],m[0]]),">"===f?(f="<",h=[h[1],h[0]]):"ge"===f&&(f="le",h=[h[1],h[0]]),d!==f)return!1;let e=["+",m[0],["-",m[1]]],t=["+",h[0],["-",h[1]]],y="="!==d;return component_equals({expr:r.fromAst(e),other:a.fromAst(t),randomBindings:n,expr_context:r,other_context:a,allow_proportional:!0,require_positive_proportion:y,relative_tolerance:i,absolute_tolerance:o,tolerance_for_zero:s,allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,rng:p})}}return component_equals({expr:e,other:t,randomBindings:n,expr_context:r,other_context:a,relative_tolerance:i,absolute_tolerance:o,tolerance_for_zero:s,allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,rng:p})},component_equals=function({expr:e,other:t,randomBindings:n,expr_context:r,other_context:a,allow_proportional:i=!1,require_positive_proportion:o=!1,relative_tolerance:s,absolute_tolerance:l,tolerance_for_zero:u,allowed_error_in_numbers:c,include_error_in_number_exponents:p,allowed_error_is_absolute:d,rng:m}){var f=1e-20*Number.MAX_VALUE;e=e.normalize_function_names(),t=t.normalize_function_names(),e=e.subscripts_to_strings(),t=t.subscripts_to_strings();var h=[e.variables(),t.variables()];h=(h=h.reduce((function(e,t){return e.concat(t)}))).reduce((function(e,t){return e.indexOf(t)<0&&e.push(t),e}),[]),math$1.define_pi&&(h=h.filter((function(e){return"pi"!==e}))),math$1.define_i&&(h=h.filter((function(e){return"i"!==e}))),math$1.define_e&&(h=h.filter((function(e){return"e"!==e})));var y=[];for(let e=0;e0){let t=replace_numbers_with_parameters({expr:e,variables:h,include_exponents:p});T=r.fromAst(t.expr_with_params),N=t.parameters;let n=Object.keys(N);if(n.length>0){let t=T.derivative(n[0]);if(d||(t=t.multiply(N[n[0]])),n.length>1)for(let e of n.slice(1)){let n=T.derivative(e);d||(n=n.multiply(N[e])),t=t.add(n)}let r=t.multiply(c);try{C=r.f()}catch(e){}}}var A=[10,1,100,.1,1e3,.01],S=0;let x=0,w=!0,V=0;for(let t=0;t<1e3;t++){try{var E=O(A[S],m)}catch(e){continue}if(!1===E.always_zero&&(w=!1),!E.equal&&!E.out_of_bounds&&!E.always_zero&&!1!==E.sufficient_finite_values&&(V++,V>100))return!1;if(E.equal){if(E.always_zero){if(!w)continue;if(x+=1,x>5&&(S+=1,x=0),S>=A.length)return!0;continue}return!0}}return!1;function O(e,t){var r,a=n(t,h,e);for(let e=0;e0)||!(0===S||S>0))return{out_of_bounds:!0,always_zero:!1};var x=Math.min(A,S),w=Math.max(A,S),V=1;let E=0;if(C){try{E=math$1.abs(C(r))}catch(e){return{equal_at_start:!1,always_zero:!1}}if(!Number.isFinite(E))return{equal_at_start:!1,always_zero:!1}}if(E+=x*s,E=Math.min(E,.1*x),E+=0!==E||0!==m&&0!==T?l:u,!(0===w||math$1.abs(math$1.subtract(m,T))0))return{equal_at_start:!1,always_zero:!1}}var O=0===w,_=0;for(let r=0;r<100;r++){var $,D=n(t,h,.01,a);for(let e=0;e=10)return{equal:!0,always_zero:O}}}return{sufficient_finite_values:!1,always_zero:O}}};function replace_numbers_with_parameters({expr:e,variables:t,include_exponents:n=!1}){let r={},a=0;function i(){a++;let e="par"+a;for(;t.includes(e);)a++,e="par"+a;return e}return{expr_with_params:function e(t){if("number"==typeof t){if(0===t)return t;{let e=i();return r[e]=t,e}}if("string"==typeof t){if("pi"===t){if(math$1.define_pi){let e=i();return r[e]=math$1.PI,e}}else if("e"===t&&math$1.define_e){let e=i();return r[e]=math$1.e,e}return t}if(!Array.isArray(t))return t;let a=t[0],o=t.slice(1);return"^"!==a||n?[a,...o.map(e)]:[a,e(o[0]),o[1]]}((e=e.evaluate_numbers({max_digits:1/0})).tree),parameters:r}}function randomComplexBindings(e,t,n,r){var a={};return void 0===r?t.forEach((function(t){a[t]=math$1.complex(2*e()*n-n,2*e()*n-n)})):t.forEach((function(t){a[t]=math$1.complex(r[t].re+2*e()*n-n,r[t].im+2*e()*n-n)})),a}const equals$4=function(e,t,{relative_tolerance:n=1e-12,absolute_tolerance:r=0,tolerance_for_zero:a=1e-15,allowed_error_in_numbers:i=0,include_error_in_number_exponents:o=!1,allowed_error_is_absolute:s=!1,allow_blanks:l=!1}={}){if(!l&&(e.variables().includes("_")||t.variables().includes("_")))return!1;let u=seedrandom$1("complex_seed");return!(!e.isAnalytic({allow_abs:!0,allow_relation:!0})||!t.isAnalytic({allow_abs:!0,allow_relation:!0}))&&equals$5({expr:e,other:t,randomBindings:randomComplexBindings,expr_context:e.context,other_context:t.context,relative_tolerance:n,absolute_tolerance:r,tolerance_for_zero:a,allowed_error_in_numbers:i,include_error_in_number_exponents:o,allowed_error_is_absolute:s,rng:u})};function randomRealBindings(e,t,n,r){var a={};return void 0===r?t.forEach((function(t){a[t]=2*e()*n-n})):t.forEach((function(t){a[t]=r[t]+2*e()*n-n})),a}const equals$3=function(e,t,{relative_tolerance:n=1e-12,absolute_tolerance:r=0,tolerance_for_zero:a=1e-15,allowed_error_in_numbers:i=0,include_error_in_number_exponents:o=!1,allowed_error_is_absolute:s=!1}={}){if(!e.isAnalytic()||!t.isAnalytic())return!1;let l=seedrandom("real_seed");return equals$5({expr:e,other:t,randomBindings:randomRealBindings,expr_context:e.context,other_content:t.context,relative_tolerance:n,absolute_tolerance:r,tolerance_for_zero:a,allowed_error_in_numbers:i,include_error_in_number_exponents:o,allowed_error_is_absolute:s,rng:l})},equals$2=function(e,t,{allowed_error_in_numbers:n=0,include_error_in_number_exponents:r=!1,allowed_error_is_absolute:a=!1,allow_blanks:i=!1}={}){return!(!i&&(e.variables().includes("_")||t.variables().includes("_")))&&equal(e.tree,t.tree,{allowed_error_in_numbers:n,include_error_in_number_exponents:r,allowed_error_is_absolute:a})},equals$1=function(e,t,{min_elements_match:n=3,match_partial:r=!1}={}){if(!is_discrete_infinite_set(e))return!1;if(is_discrete_infinite_set(t)){var a=[];let n=e.context.get_assumptions(e);if(void 0!==n&&a.push(n),n=t.context.get_assumptions(t),void 0!==n&&a.push(n),a=0===a.length?void 0:1===a.length?a[0]:clean_assumptions(["and"].concat(a)),r){let n=contained_in(e.tree,t.tree,a,r);if(!1===n)return 0;let i=contained_in(t.tree,e.tree,a,r);return!1===i?0:!0===n?!0===i?1:i:!0===i?n:Math.min(n,i)}return contained_in(e.tree,t.tree,a,r)&&contained_in(t.tree,e.tree,a,r)}{let r=t.tree;if("list"!==r[0])return!1;let a=r.length-2;if("ldots"!==r[a+1][0])return!1;if(acontained_in(e,t,n)))}var a=e[1],i=e[2],o=e[3],s=e[4];if(!Array.isArray(o)||"-"!==o[0]||o[1]!==1/0||s!==1/0)return!1;a=simplify(["/",a,i],n,1/0);var l=t.slice(1),u=[];for(let e=0;ee[0])))];let p=0;for(let e of c){let t=u.map((function(t,n){let r=e/t[0];return Number.isInteger(r)?[t[0],r,n]:void 0})).filter((e=>e)),i=[];for(let r of t){let t=r[0],o=r[1],s=r[2],l=u[s][2],c=u[s][3];for(let r=0;rp&&(p=t)}}return!!(r&&p>0)&&p}function sequence_from_discrete_infinite(e,t){var n=e.tree.slice(1);if(n.length>1)return;let r=n[0][1],a=n[0][2],i=evaluate_numbers(n[0][3]),o=n[0][4];if(!Number.isInteger(i)||o!==1/0)return;let s=[];for(let e=0;e0))throw Error(`Have not implemented equality check with ${r} sign errors.`);if(r>1){let e=n;n=function(t,n){return equalSpecifiedSignErrors(t,n,{equalityFunction:e,n_sign_errors:r-1})}}var a,i,o=e.tree,s=[[o]],l=0;e.tree=["-",o];var u=n(e,t);if(e.tree=o,u)return!0;for(;a=s[l++];)if(a=a[0],Array.isArray(a))for(i=1;i"];function isAnalytic(e,{allow_abs:t=!1,allow_relation:n=!1}={}){var r=normalize_applied_functions(normalize_function_names(e)),a=operators$3(r=subscripts_to_strings(r));for(let e=0;e+")},"-":function(e){return"-"+e.join("-")+""},"*":function(e){return e.join('\\cdot*')},"/":function(e){return astToGuppy$1.dfrac(e[0],e[1])},"^":function(e){return astToGuppy$1.power(e[0],e[1])},sin:function(e){return astToGuppy$1.trig("sin",e[0])},cos:function(e){return astToGuppy$1.trig("cos",e[0])},tan:function(e){return astToGuppy$1.trig("tan",e[0])},arcsin:function(e){return astToGuppy$1.trig("arcsin",e[0])},arccos:function(e){return astToGuppy$1.trig("arccos",e[0])},arctan:function(e){return astToGuppy$1.trig("arctan",e[0])},arccsc:function(e){return astToGuppy$1.trig("arccsc",e[0])},arcsec:function(e){return astToGuppy$1.trig("arcsec",e[0])},arccot:function(e){return astToGuppy$1.trig("arccot",e[0])},csc:function(e){return astToGuppy$1.trig("csc",e[0])},sec:function(e){return astToGuppy$1.trig("sec",e[0])},cot:function(e){return astToGuppy$1.trig("cot",e[0])},log:function(e){return astToGuppy$1.trig("log",e[0])},exp:function(e){return astToGuppy$1.trig("exp",e[0])},ln:function(e){return astToGuppy$1.trig("ln",e[0])},sqrt:function(e){return astToGuppy$1.sqrt(e[0])},abs:function(e){return astToGuppy$1.abs(e[0])}}}static dfrac(e,t){return'\\dfrac{}{}\\frac{}{}()/()'+e+''+t+""}static trig(e,t){return'\\'+e+'\\left(\\right) '+e+'()'+t+""}static sqrt(e){return'\\sqrt{}sqrt()'+e+""}static power(e,t){return'{}^{}()^()'+e+''+t+""}static abs(e){return'\\left|\\right|abs()'+e+""}static paren(e){return'\\left(\\right)()'+e+""}static isFunctionSymbol(e){return-1!==["sin","cos","tan","csc","sec","cot","arcsin","arccos","arctan","arccsc","arcsec","arccot","log","ln","exp","sqrt","abs","this.factorial"].indexOf(e)}static isGreekLetterSymbol(e){return-1!==["pi","theta","theta","Theta","alpha","nu","beta","xi","Xi","gamma","Gamma","delta","Delta","pi","Pi","epsilon","epsilon","rho","rho","zeta","sigma","Sigma","eta","tau","upsilon","Upsilon","iota","phi","phi","Phi","kappa","chi","lambda","Lambda","psi","Psi","omega","Omega"].indexOf(e)}factorWithParenthesesIfNegated(e){var t=this.factor(e);return t.toString().match(/^-/)?astToGuppy$1.paren(t.toString()):t}factor(e){if("string"==typeof e)return astToGuppy$1.isGreekLetterSymbol(e)?'\\'+e+' $'+e+"":""+e+"";if("number"==typeof e)return""+e+"";if(!Array.isArray(e))return"";var t=e[0],n=e.slice(1);return"apply"===t&&(t=e[1],n=e.slice(2)),"abs"===t?this.operators[t](n.map(function(e,t){return this.expression(e)}.bind(this))):astToGuppy$1.isFunctionSymbol(t)?"this.factorial"!==t||1!==n[0].toString().length&&!n[0].toString().match(/^[0-9]*$/)?this.operators[t](n.map(function(e,t){return this.factor(e)}.bind(this))):this.operators[t](n):"^"===t||"~"===t?this.operators[t](n.map(function(e,t){return this.factor(e)}.bind(this))):astToGuppy$1.paren(this.expression(e))}term(e){if(!Array.isArray(e))return this.factor(e);var t=e[0],n=e.slice(1);return"*"===t?this.operators[t](n.map(function(e,t){var n=this.factorWithParenthesesIfNegated(e);return n.toString().match(/^[0-9]/)&&t>0?" * "+n:n}.bind(this))):"/"===t?this.operators[t](n.map(function(e,t){return this.factor(e)}.bind(this))):this.factor(e)}expression(e){if(!Array.isArray(e))return this.term(e);var t=e[0],n=e.slice(1);return"+"===t||"-"===t?this.operators[t](n.map(function(e,t){return this.factorWithParenthesesIfNegated(e)}.bind(this))):this.term(e)}convert(e){return(""+this.expression(e)+"").replace(/<\/e>/g,"")}}const glslOperators={"+":function(e){var t=e[0];return e.slice(1).forEach((function(e){t=t+"+"+e})),t},"-":function(e){var t="-"+e[0];return e.slice(1).forEach((function(e){t=t+"-"+e})),t},"~":function(e){var t="vec2(0.0,0.0)";return e.forEach((function(e){t=t+"-"+e})),t},"*":function(e){var t=e[0];return e.slice(1).forEach((function(e){t="cmul("+t+","+e+")"})),t},"/":function(e){var t=e[0];return e.slice(1).forEach((function(e){t="cdiv("+t+","+e+")"})),t},sin:function(e){return"csin("+e[0]+")"},cos:function(e){return"ccos("+e[0]+")"},tan:function(e){return"ctan("+e[0]+")"},sinh:function(e){return"csinh("+e[0]+")"},cosh:function(e){return"ccosh("+e[0]+")"},arcsin:function(e){return"carcsin("+e[0]+")"},arccos:function(e){return"carccos("+e[0]+")"},arctan:function(e){return"carctan("+e[0]+")"},arccsc:function(e){return"carcsin(cdiv(vec2(1.0,0),"+e[0]+"))"},arcsec:function(e){return"carccos(cdiv(vec2(1.0,0),"+e[0]+"))"},arccot:function(e){return"carctan(cdiv(vec2(1.0,0),"+e[0]+"))"},csc:function(e){return"ccsc("+e[0]+")"},sec:function(e){return"csec("+e[0]+")"},cot:function(e){return"ccot("+e[0]+")"},exp:function(e){return"cexp("+e[0]+")"},conj:function(e){return"conjugate("+e[0]+")"},sqrt:function(e){return"cpower("+e[0]+",vec2(0.5,0.0))"},log:function(e){return"clog("+e[0]+")"},ln:function(e){return"clog("+e[0]+")"},"^":function(e){return"cpower("+e[0]+","+e[1]+")"},abs:function(e){return"cabs("+e[0]+")"},apply:function(e){return"vec2(NaN,NaN)"}};class astToGLSL$1{constructor(){}convert(e){if("boolean"==typeof e)throw Error("no support for boolean");if("string"==typeof e)return"e"===e?"vec2(2.71828182845905,0.0)":"pi"===e?"vec2(3.14159265358979,0.0)":"i"===e?"vec2(0.0,1.0)":String(e);if("number"==typeof e)return"vec2("+String(e)+",0.0)";if("real"in e&&"imaginary"in e)return e;if(!Array.isArray(e))throw Error("Invalid ast");var t=e[0],n=e.slice(1);if("apply"===t){if("string"!=typeof n[0])throw Error("Non string functions not implemented for conversion to GLSL");return t=n[0],n=n.slice(1),glslOperators[t](n.map(function(e,t){return this.convert(e)}.bind(this)))}if(t in glslOperators)return glslOperators[t](n.map(function(e,t){return this.convert(e)}.bind(this)));throw Error("Operator "+t+" not implemented for conversion to mathjs")}}var astToGuppy=new astToGuppy$1,astToGLSL=new astToGLSL$1;const tex=function(e,t){return new astToLatex$1(t).convert(e.tree)},toLatex=tex,toString=function(e,t){return new astToText$1(t).convert(e.tree)},toGLSL=function(e){return astToGLSL.convert(e.tree)},toXML=function(e){return astToGuppy.convert(e.tree)};var printing=Object.freeze({__proto__:null,tex:tex,toLatex:toLatex,toString:toString,toXML:toXML,toGLSL:toGLSL});const integrateNumerically=function(e,t,n,r){for(var a=0,i={},o=0;o<100;o++){var s=n+(r-n)*(o+.5)/100;i[t]=s,a+=e.evaluate(i)}return a*(r-n)/100};var integration=Object.freeze({__proto__:null,integrateNumerically:integrateNumerically});function expression_to_polynomial(e){var t=get_tree(e);if("string"==typeof t)return"pi"===t&&math$1.define_pi||"i"===t&&math$1.define_i||"e"===t&&math$1.define_e?t:["polynomial",t,[[1,1]]];if("number"==typeof t)return t;let n=evaluate_to_constant(t);if(null!==n&&Number.isFinite(n))return simplify(t);if(!Array.isArray(t))return!1;if(!operators$3(t).every((e=>["+","-","*","^","/","_","prime"].includes(e))))return!1;var r=t[0],a=t.slice(1);if("+"===r){let e=a.map(expression_to_polynomial);return!!e.every((e=>!1!==e))&&e.reduce(((e,t)=>polynomial_add(e,t)))}if("-"===r){let e=expression_to_polynomial(a[0]);return!!e&&polynomial_neg(e)}if("*"===r){let e=a.map(expression_to_polynomial);return!!e.every((e=>!1!==e))&&e.reduce(((e,t)=>polynomial_mul(e,t)))}if("^"===r){let e=a[0],n=expression_to_polynomial(e);if(!1===n)return!1;let r=simplify(a[1]);if("number"!=typeof r||r<0||!Number.isInteger(r)){let n=evaluate_to_constant(r);if(null!==n||Number.isFinite(n)){let t=math$1.fraction(n);if(t.d<=100){e=t.s<0?["^",e,["/",-1,t.d]]:["^",e,["/",1,t.d]];var i=["polynomial",simplify(e),[]];return i[2].push([t.n,1]),i}}return["polynomial",t,[[1,1]]]}return 0===r?1:1===r?n:polynomial_pow(n,r)}if("/"===r){var o=a[1],s=evaluate_to_constant(o);return null!==s&&Number.isFinite(s)?polynomial_mul(expression_to_polynomial(a[0]),["/",1,s]):["polynomial",t,[[1,1]]]}return["polynomial",t,[[1,1]]]}function polynomials_in_same_leading_variable(e,t){return e[1]!==t[1]&&(compare_function(e[1],t[1])<0?t=["polynomial",e[1],[[0,t]]]:e=["polynomial",t[1],[[0,e]]]),[e,t]}function polynomial_add(e,t){if("polynomial"!==e[0]){if("polynomial"!==t[0])return simplify(["+",e,t]);e=["polynomial",t[1],[[0,e]]]}else if("polynomial"!==t[0])t=["polynomial",e[1],[[0,t]]];else{let n=polynomials_in_same_leading_variable(e,t);e=n[0],t=n[1]}let n=["polynomial",e[1],[]],r=e[2],a=t[2],i=n[2],o=r.length,s=a.length,l=0,u=0;for(;l0;)1&t&&(n=polynomial_mul(n,e)),e=polynomial_mul(e,e),t>>=1;return n}function polynomial_to_expression(e){if(!Array.isArray(e)||"polynomial"!==e[0])return e;let t=e[1],n=e[2],r=[],a=n.length;for(var i=0;ir[s][1])return!1}return a!==i&&o!==i}function mono_gcd(e,t){if(!Array.isArray(e)||!Array.isArray(t)||"monomial"!==e[0]||"monomial"!==t[0])return 1;let n=e[2],r=t[2],a=[],i=n.length,o=r.length,s=0,l=0;for(;s1&&(t[n]=(t[n]||0)+1):t[e]=(t[e]||0)+1,t}var s=function(e,t){var a,i=0,s=1,o=1,u=0,c=0,p=0,d=1,m=1,h=0,f=1,y=1,g=1,b=1e7;if(null==e);else if(void 0!==t){if(o=(i=e)*(s=t),i%1!=0||s%1!=0)throw l.NonIntegerParameter}else switch(typeof e){case"object":if("d"in e&&"n"in e)i=e.n,s=e.d,"s"in e&&(i*=e.s);else{if(!(0 in e))throw l.InvalidParameter;i=e[0],1 in e&&(s=e[1])}o=i*s;break;case"number":if(e<0&&(o=e,e=-e),e%1==0)i=e;else if(e>0){for(e>=1&&(e/=m=Math.pow(10,Math.floor(1+Math.log(e)/Math.LN10)));f<=b&&g<=b;){if(e===(a=(h+y)/(f+g))){f+g<=b?(i=h+y,s=f+g):g>f?(i=y,s=g):(i=h,s=f);break}e>a?(h+=y,f+=g):(y+=h,g+=f),f>b?(i=y,s=g):(i=h,s=f)}i*=m}else(isNaN(e)||isNaN(t))&&(s=i=NaN);break;case"string":if(null===(f=e.match(/\d+|./g)))throw l.InvalidParameter;if("-"===f[h]?(o=-1,h++):"+"===f[h]&&h++,f.length===h+1?c=r(f[h++],o):"."===f[h+1]||"."===f[h]?("."!==f[h]&&(u=r(f[h++],o)),(1+ ++h===f.length||"("===f[h+1]&&")"===f[h+3]||"'"===f[h+1]&&"'"===f[h+3])&&(c=r(f[h],o),d=Math.pow(10,f[h].length),h++),("("===f[h]&&")"===f[h+2]||"'"===f[h]&&"'"===f[h+2])&&(p=r(f[h+1],o),m=Math.pow(10,f[h+1].length)-1,h+=3)):"/"===f[h+1]||":"===f[h+1]?(c=r(f[h],o),d=r(f[h+2],1),h+=3):"/"===f[h+3]&&" "===f[h+1]&&(u=r(f[h],o),c=r(f[h+2],o),d=r(f[h+4],1),h+=5),f.length<=h){o=i=p+(s=d*m)*u+m*c;break}default:throw l.InvalidParameter}if(0===s)throw l.DivisionByZero;n.s=o<0?-1:1,n.n=Math.abs(i),n.d=Math.abs(s)};function o(e,t){if(!e)return t;if(!t)return e;for(;;){if(!(e%=t))return t;if(!(t%=e))return e}}function l(e,t){if(s(e,t),!(this instanceof l))return a(n.s*n.n,n.d);e=o(n.d,n.n),this.s=n.s,this.n=n.n/e,this.d=n.d/e}l.DivisionByZero=new Error("Division by Zero"),l.InvalidParameter=new Error("Invalid argument"),l.NonIntegerParameter=new Error("Parameters must be integer"),l.prototype={s:1,n:0,d:1,abs:function(){return a(this.n,this.d)},neg:function(){return a(-this.s*this.n,this.d)},add:function(e,t){return s(e,t),a(this.s*this.n*n.d+n.s*this.d*n.n,this.d*n.d)},sub:function(e,t){return s(e,t),a(this.s*this.n*n.d-n.s*this.d*n.n,this.d*n.d)},mul:function(e,t){return s(e,t),a(this.s*n.s*this.n*n.n,this.d*n.d)},div:function(e,t){return s(e,t),a(this.s*n.s*this.n*n.d,this.d*n.n)},clone:function(){return a(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new l(NaN);if(void 0===e)return a(this.s*this.n%this.d,1);if(s(e,t),0===n.n&&0===this.d)throw l.DivisionByZero;return a(this.s*(n.d*this.n)%(n.n*this.d),n.d*this.d)},gcd:function(e,t){return s(e,t),a(o(n.n,this.n)*o(n.d,this.d),n.d*this.d)},lcm:function(e,t){return s(e,t),0===n.n&&0===this.n?a(0,1):a(n.n*this.n,o(n.n,this.n)*o(n.d,this.d))},ceil:function(e){return e=Math.pow(10,e||0),isNaN(this.n)||isNaN(this.d)?new l(NaN):a(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=Math.pow(10,e||0),isNaN(this.n)||isNaN(this.d)?new l(NaN):a(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=Math.pow(10,e||0),isNaN(this.n)||isNaN(this.d)?new l(NaN):a(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return a(this.s*this.d,this.n)},pow:function(e,t){if(s(e,t),1===n.d)return n.s<0?a(Math.pow(this.s*this.d,n.n),Math.pow(this.n,n.n)):a(Math.pow(this.s*this.n,n.n),Math.pow(this.d,n.n));if(this.s<0)return null;var r=i(this.n),o=i(this.d),l=1,u=1;for(var c in r)if("1"!==c){if("0"===c){l=0;break}if(r[c]*=n.n,r[c]%n.d!=0)return null;r[c]/=n.d,l*=Math.pow(c,r[c])}for(var c in o)if("1"!==c){if(o[c]*=n.n,o[c]%n.d!=0)return null;o[c]/=n.d,u*=Math.pow(c,o[c])}return n.s<0?a(u,l):a(l,u)},equals:function(e,t){return s(e,t),this.s*this.n*n.d==n.s*n.n*this.d},compare:function(e,t){s(e,t);var r=this.s*this.n*n.d-n.s*n.n*this.d;return(0=0;s--)i=i.inverse().add(n[s]);if(i.sub(t).abs().valueOf()0&&(n+=t,n+=" ",r%=a),n+=r,n+="/",n+=a),n},toLatex:function(e){var t,n="",r=this.n,a=this.d;return this.s<0&&(n+="-"),1===a?n+=r:(e&&(t=Math.floor(r/a))>0&&(n+=t,r%=a),n+="\\frac{",n+=r,n+="}{",n+=a,n+="}"),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do{r.push(Math.floor(t/n)),e=t%n,t=n,n=e}while(1!==t);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return"NaN";e=e||15;var r=function(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(1===t)return 0;for(var n=10%t,r=1;1!==n;r++)if(n=10*n%t,r>2e3)return 0;return r}(0,n),a=function(e,t,n){for(var r=1,a=function(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)1&t&&(r=r*e%n);return r}(10,n,t),i=0;i<300;i++){if(r===a)return i;r=10*r%t,a=10*a%t}return 0}(0,n,r),i=this.s<0?"-":"";if(i+=t/n|0,t%=n,(t*=10)&&(i+="."),r){for(var s=a;s--;)i+=t/n|0,t%=n,t*=10;for(i+="(",s=r;s--;)i+=t/n|0,t%=n,t*=10;i+=")"}else for(s=e;t&&s--;)i+=t/n|0,t%=n,t*=10;return i}},Object.defineProperty(l,"__esModule",{value:!0}),l.default=l,l.Fraction=l,e.exports=l}()}(fraction$1);var Fraction$1=getDefaultExportFromCjs(fraction$1.exports),name$4z="Fraction",dependencies$4z=[],createFractionClass=factory(name$4z,dependencies$4z,(()=>(Fraction$1.prototype.type="Fraction",Fraction$1.prototype.isFraction=!0,Fraction$1.prototype.toJSON=function(){return{mathjs:"Fraction",n:this.s*this.n,d:this.d}},Fraction$1.fromJSON=function(e){return new Fraction$1(e)},Fraction$1)),{isClass:!0}),name$4y="Range",dependencies$4y=[],createRangeClass=factory(name$4y,dependencies$4y,(()=>{function e(t,n,r){if(!(this instanceof e))throw new SyntaxError("Constructor must be called with the new operator");var a=null!=t,i=null!=n,s=null!=r;if(a)if(isBigNumber(t))t=t.toNumber();else if("number"!=typeof t)throw new TypeError("Parameter start must be a number");if(i)if(isBigNumber(n))n=n.toNumber();else if("number"!=typeof n)throw new TypeError("Parameter end must be a number");if(s)if(isBigNumber(r))r=r.toNumber();else if("number"!=typeof r)throw new TypeError("Parameter step must be a number");this.start=a?parseFloat(t):0,this.end=i?parseFloat(n):0,this.step=s?parseFloat(r):1}return e.prototype.type="Range",e.prototype.isRange=!0,e.parse=function(t){if("string"!=typeof t)return null;var n=t.split(":").map((function(e){return parseFloat(e)}));if(n.some((function(e){return isNaN(e)})))return null;switch(n.length){case 2:return new e(n[0],n[1]);case 3:return new e(n[0],n[2],n[1]);default:return null}},e.prototype.clone=function(){return new e(this.start,this.end,this.step)},e.prototype.size=function(){var e=0,t=this.start,n=this.step,r=this.end-t;return sign$3(n)===sign$3(r)?e=Math.ceil(r/n):0===r&&(e=0),isNaN(e)&&(e=0),[e]},e.prototype.min=function(){var e=this.size()[0];return e>0?this.step>0?this.start:this.start+(e-1)*this.step:void 0},e.prototype.max=function(){var e=this.size()[0];return e>0?this.step>0?this.start+(e-1)*this.step:this.start:void 0},e.prototype.forEach=function(e){var t=this.start,n=this.step,r=this.end,a=0;if(n>0)for(;tr;)e(t,[a],this),t+=n,a++},e.prototype.map=function(e){var t=[];return this.forEach((function(n,r,a){t[r[0]]=e(n,r,a)})),t},e.prototype.toArray=function(){var e=[];return this.forEach((function(t,n){e[n[0]]=t})),e},e.prototype.valueOf=function(){return this.toArray()},e.prototype.format=function(e){var t=format$3(this.start,e);return 1!==this.step&&(t+=":"+format$3(this.step,e)),t+":"+format$3(this.end,e)},e.prototype.toString=function(){return this.format()},e.prototype.toJSON=function(){return{mathjs:"Range",start:this.start,end:this.end,step:this.step}},e.fromJSON=function(t){return new e(t.start,t.end,t.step)},e}),{isClass:!0}),name$4x="Matrix",dependencies$4x=[],createMatrixClass=factory(name$4x,dependencies$4x,(()=>{function e(){if(!(this instanceof e))throw new SyntaxError("Constructor must be called with the new operator")}return e.prototype.type="Matrix",e.prototype.isMatrix=!0,e.prototype.storage=function(){throw new Error("Cannot invoke storage on a Matrix interface")},e.prototype.datatype=function(){throw new Error("Cannot invoke datatype on a Matrix interface")},e.prototype.create=function(e,t){throw new Error("Cannot invoke create on a Matrix interface")},e.prototype.subset=function(e,t,n){throw new Error("Cannot invoke subset on a Matrix interface")},e.prototype.get=function(e){throw new Error("Cannot invoke get on a Matrix interface")},e.prototype.set=function(e,t,n){throw new Error("Cannot invoke set on a Matrix interface")},e.prototype.resize=function(e,t){throw new Error("Cannot invoke resize on a Matrix interface")},e.prototype.reshape=function(e,t){throw new Error("Cannot invoke reshape on a Matrix interface")},e.prototype.clone=function(){throw new Error("Cannot invoke clone on a Matrix interface")},e.prototype.size=function(){throw new Error("Cannot invoke size on a Matrix interface")},e.prototype.map=function(e,t){throw new Error("Cannot invoke map on a Matrix interface")},e.prototype.forEach=function(e){throw new Error("Cannot invoke forEach on a Matrix interface")},e.prototype[Symbol.iterator]=function(){throw new Error("Cannot iterate a Matrix interface")},e.prototype.toArray=function(){throw new Error("Cannot invoke toArray on a Matrix interface")},e.prototype.valueOf=function(){throw new Error("Cannot invoke valueOf on a Matrix interface")},e.prototype.format=function(e){throw new Error("Cannot invoke format on a Matrix interface")},e.prototype.toString=function(){throw new Error("Cannot invoke toString on a Matrix interface")},e}),{isClass:!0}),name$4w="DenseMatrix",dependencies$4w=["Matrix"],createDenseMatrixClass=factory(name$4w,dependencies$4w,(e=>{var{Matrix:t}=e;function n(e,t){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(t&&!isString$1(t))throw new Error("Invalid datatype: "+t);if(isMatrix(e))"DenseMatrix"===e.type?(this._data=clone$3(e._data),this._size=clone$3(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&isArray$1(e.data)&&isArray$1(e.size))this._data=e.data,this._size=e.size,validate(this._data,this._size),this._datatype=t||e.datatype;else if(isArray$1(e))this._data=o(e),this._size=arraySize(this._data),validate(this._data,this._size),this._datatype=t;else{if(e)throw new TypeError("Unsupported type of data ("+typeOf$1(e)+")");this._data=[],this._size=[0],this._datatype=t}}function r(e,t,n,a){var i=a===n-1,s=t.dimension(a);return i?s.map((function(t){return validateIndex(t,e.length),e[t]})).valueOf():s.map((function(i){return validateIndex(i,e.length),r(e[i],t,n,a+1)})).valueOf()}function a(e,t,n,r,i){var s=i===r-1,o=t.dimension(i);s?o.forEach((function(t,r){validateIndex(t),e[t]=n[r[0]]})):o.forEach((function(s,o){validateIndex(s),a(e[s],t,n[o[0]],r,i+1)}))}function i(e,t,n){if(0===t.length){for(var r=e._data;isArray$1(r);)r=r[0];return r}return e._size=t.slice(0),e._data=resize$1(e._data,e._size,n),e}function s(e,t,n){for(var r=e._size.slice(0),a=!1;r.lengthr[s]&&(r[s]=t[s],a=!0);a&&i(e,r,n)}function o(e){for(var t=0,n=e.length;t");var p=t.max().map((function(e){return e+1}));s(e,p,r);var d=o.length;a(e._data,t,n,d,0)}return e}(this,e,t,i);default:throw new SyntaxError("Wrong number of arguments")}},n.prototype.get=function(e){if(!isArray$1(e))throw new TypeError("Array expected");if(e.length!==this._size.length)throw new DimensionError(e.length,this._size.length);for(var t=0;tArray.isArray(e)&&1===e.length?e[0]:e));return i(n?this.clone():this,r,t)},n.prototype.reshape=function(e,t){var n=t?this.clone():this;n._data=reshape$1(n._data,e);var r=n._size.reduce(((e,t)=>e*t));return n._size=processSizesWildcard(e,r),n},n.prototype.clone=function(){return new n({data:clone$3(this._data),size:clone$3(this._size),datatype:this._datatype})},n.prototype.size=function(){return this._size.slice(0)},n.prototype.map=function(e){var t=this,r=function n(r,a){return isArray$1(r)?r.map((function(e,t){return n(e,a.concat(t))})):e(r,a,t)}(this._data,[]);return new n(r,void 0!==this._datatype?getArrayDataType(r,typeOf$1):void 0)},n.prototype.forEach=function(e){var t=this;!function n(r,a){isArray$1(r)?r.forEach((function(e,t){n(e,a.concat(t))})):e(r,a,t)}(this._data,[])},n.prototype[Symbol.iterator]=function*(){yield*function*e(t,n){if(isArray$1(t))for(var r=0;r[e[r]]));t.push(new n(i,e._datatype))},s=0;s0?e:0,r=e<0?-e:0,a=this._size[0],i=this._size[1],s=Math.min(a-r,i-t),o=[],l=0;l0?r:0,o=r<0?-r:0,l=e[0],u=e[1],c=Math.min(l-o,u-s);if(isArray$1(t)){if(t.length!==c)throw new Error("Invalid value array length");i=function(e){return t[e]}}else if(isMatrix(t)){var p=t.size();if(1!==p.length||p[0]!==c)throw new Error("Invalid matrix length");i=function(e){return t.get([e])}}else i=function(){return t};a||(a=isBigNumber(i(0))?i(0).mul(0):0);var d=[];if(e.length>0){d=resize$1(d,e,a);for(var m=0;m{var{typed:t}=e;return t(name$4v,{any:clone$3})}));function _switch$1(e){var t,n,r=e.length,a=e[0].length,i=[];for(n=0;n=r.length)throw new IndexError(t,r.length);return isMatrix(e)?e.create(_reduce(e.valueOf(),t,n)):_reduce(e,t,n)}function _reduce(e,t,n){var r,a,i,s;if(t<=0){if(Array.isArray(e[0])){for(s=_switch$1(e),a=[],r=0;r{var{typed:t}=e;return t(name$4u,{number:isInteger$1,BigNumber:function(e){return e.isInt()},Fraction:function(e){return 1===e.d&&isFinite(e.n)},"Array | Matrix":function(e){return deepMap(e,this)}})})),n1$4="number",n2$2="number, number";function absNumber(e){return Math.abs(e)}function addNumber(e,t){return e+t}function multiplyNumber(e,t){return e*t}function unaryMinusNumber(e){return-e}function unaryPlusNumber(e){return e}function cbrtNumber(e){return cbrt$2(e)}function cubeNumber(e){return e*e*e}function expNumber(e){return Math.exp(e)}function expm1Number(e){return expm1$1(e)}function gcdNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Parameters in function gcd must be integer numbers");for(var n;0!==t;)n=e%t,e=t,t=n;return e<0?-e:e}function lcmNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Parameters in function lcm must be integer numbers");if(0===e||0===t)return 0;for(var n,r=e*t;0!==t;)t=e%(n=t),e=n;return Math.abs(r/e)}function logNumber(e,t){return t?Math.log(e)/Math.log(t):Math.log(e)}function log10Number(e){return log10$3(e)}function log2Number(e){return log2$2(e)}function modNumber(e,t){if(t>0)return e-t*Math.floor(e/t);if(0===t)return e;throw new Error("Cannot calculate mod for a negative divisor")}function nthRootNumber(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2,n=t<0;if(n&&(t=-t),0===t)throw new Error("Root must be non-zero");if(e<0&&Math.abs(t)%2!=1)throw new Error("Root must be odd when a is negative.");if(0===e)return n?1/0:0;if(!isFinite(e))return n?0:e;var r=Math.pow(Math.abs(e),1/t);return r=e<0?-r:r,n?1/r:r}function signNumber(e){return sign$3(e)}function squareNumber(e){return e*e}function xgcdNumber(e,t){var n,r,a,i=0,s=1,o=1,l=0;if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Parameters in function xgcd must be integer numbers");for(;t;)a=e-(r=Math.floor(e/t))*t,n=i,i=s-r*i,s=n,n=o,o=l-r*o,l=n,e=t,t=a;return e<0?[-e,-s,-l]:[e,e?s:0,l]}function powNumber(e,t){return e*e<1&&t===1/0||e*e>1&&t===-1/0?0:Math.pow(e,t)}function roundNumber(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!isInteger$1(t)||t<0||t>15)throw new Error("Number of decimals in function round must be an integer from 0 to 15 inclusive");return parseFloat(toFixed$2(e,t))}absNumber.signature=n1$4,addNumber.signature=n2$2,multiplyNumber.signature=n2$2,unaryMinusNumber.signature=n1$4,unaryPlusNumber.signature=n1$4,cbrtNumber.signature=n1$4,cubeNumber.signature=n1$4,expNumber.signature=n1$4,expm1Number.signature=n1$4,gcdNumber.signature=n2$2,lcmNumber.signature=n2$2,log10Number.signature=n1$4,log2Number.signature=n1$4,modNumber.signature=n2$2,signNumber.signature=n1$4,squareNumber.signature=n1$4,xgcdNumber.signature=n2$2,powNumber.signature=n2$2;var n1$3="number",n2$1="number, number";function bitAndNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function bitAnd");return e&t}function bitNotNumber(e){if(!isInteger$1(e))throw new Error("Integer expected in function bitNot");return~e}function bitOrNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function bitOr");return e|t}function bitXorNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function bitXor");return e^t}function leftShiftNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function leftShift");return e<>t}function rightLogShiftNumber(e,t){if(!isInteger$1(e)||!isInteger$1(t))throw new Error("Integers expected in function rightLogShift");return e>>>t}function product(e,t){if(t>1;return product(e,n)*product(n+1,t)}function combinationsNumber(e,t){if(!isInteger$1(e)||e<0)throw new TypeError("Positive integer value expected in function combinations");if(!isInteger$1(t)||t<0)throw new TypeError("Positive integer value expected in function combinations");if(t>e)throw new TypeError("k must be less than or equal to n");for(var n=e-t,r=1,a=2,i=t171?1/0:product(1,e-1);if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*gammaNumber(1-e));if(e>=171.35)return 1/0;if(e>85){var n=e*e,r=n*e,a=r*e,i=a*e;return Math.sqrt(2*Math.PI/e)*Math.pow(e/Math.E,e)*(1+1/(12*e)+1/(288*n)-139/(51840*r)-571/(2488320*a)+163879/(209018880*i)+5246819/(75246796800*i*e))}--e,t=gammaP[0];for(var s=1;s=1;r--)n+=lgammaSeries[r]/(e+r);return lnSqrt2PI+(e+.5)*Math.log(t)-t+Math.log(n)}lgammaNumber.signature="number";var n1$1="number";function acoshNumber(e){return acosh$3(e)}function acotNumber(e){return Math.atan(1/e)}function acothNumber(e){return isFinite(e)?(Math.log((e+1)/e)+Math.log(e/(e-1)))/2:0}function acscNumber(e){return Math.asin(1/e)}function acschNumber(e){var t=1/e;return Math.log(t+Math.sqrt(t*t+1))}function asecNumber(e){return Math.acos(1/e)}function asechNumber(e){var t=1/e,n=Math.sqrt(t*t-1);return Math.log(n+t)}function asinhNumber(e){return asinh$3(e)}function atanhNumber(e){return atanh$3(e)}function cotNumber(e){return 1/Math.tan(e)}function cothNumber(e){var t=Math.exp(2*e);return(t+1)/(t-1)}function cscNumber(e){return 1/Math.sin(e)}function cschNumber(e){return 0===e?Number.POSITIVE_INFINITY:Math.abs(2/(Math.exp(e)-Math.exp(-e)))*sign$3(e)}function secNumber(e){return 1/Math.cos(e)}function sechNumber(e){return 2/(Math.exp(e)+Math.exp(-e))}function sinhNumber(e){return sinh$3(e)}acoshNumber.signature=n1$1,acotNumber.signature=n1$1,acothNumber.signature=n1$1,acscNumber.signature=n1$1,acschNumber.signature=n1$1,asecNumber.signature=n1$1,asechNumber.signature=n1$1,asinhNumber.signature=n1$1,atanhNumber.signature=n1$1,cotNumber.signature=n1$1,cothNumber.signature=n1$1,cscNumber.signature=n1$1,cschNumber.signature=n1$1,secNumber.signature=n1$1,sechNumber.signature=n1$1,sinhNumber.signature=n1$1;var n1="number";function isNegativeNumber(e){return e<0}function isPositiveNumber(e){return e>0}function isZeroNumber(e){return 0===e}function isNaNNumber(e){return Number.isNaN(e)}isNegativeNumber.signature=n1,isPositiveNumber.signature=n1,isZeroNumber.signature=n1,isNaNNumber.signature=n1;var name$4t="isNegative",dependencies$4t=["typed"],createIsNegative=factory(name$4t,dependencies$4t,(e=>{var{typed:t}=e;return t(name$4t,{number:isNegativeNumber,BigNumber:function(e){return e.isNeg()&&!e.isZero()&&!e.isNaN()},Fraction:function(e){return e.s<0},Unit:function(e){return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4s="isNumeric",dependencies$4s=["typed"],createIsNumeric=factory(name$4s,dependencies$4s,(e=>{var{typed:t}=e;return t(name$4s,{"number | BigNumber | Fraction | boolean":function(){return!0},"Complex | Unit | string | null | undefined | Node":function(){return!1},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4r="hasNumericValue",dependencies$4r=["typed","isNumeric"],createHasNumericValue=factory(name$4r,dependencies$4r,(e=>{var{typed:t,isNumeric:n}=e;return t(name$4r,{string:function(e){return e.trim().length>0&&!isNaN(Number(e))},any:function(e){return n(e)}})})),name$4q="isPositive",dependencies$4q=["typed"],createIsPositive=factory(name$4q,dependencies$4q,(e=>{var{typed:t}=e;return t(name$4q,{number:isPositiveNumber,BigNumber:function(e){return!e.isNeg()&&!e.isZero()&&!e.isNaN()},Fraction:function(e){return e.s>0&&e.n>0},Unit:function(e){return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4p="isZero",dependencies$4p=["typed"],createIsZero=factory(name$4p,dependencies$4p,(e=>{var{typed:t}=e;return t(name$4p,{number:isZeroNumber,BigNumber:function(e){return e.isZero()},Complex:function(e){return 0===e.re&&0===e.im},Fraction:function(e){return 1===e.d&&0===e.n},Unit:function(e){return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4o="isNaN",dependencies$4o=["typed"],createIsNaN=factory(name$4o,dependencies$4o,(e=>{var{typed:t}=e;return t(name$4o,{number:isNaNNumber,BigNumber:function(e){return e.isNaN()},Fraction:function(e){return!1},Complex:function(e){return e.isNaN()},Unit:function(e){return Number.isNaN(e.value)},"Array | Matrix":function(e){return deepMap(e,Number.isNaN)}})})),name$4n="typeOf",dependencies$4n=["typed"],createTypeOf=factory(name$4n,dependencies$4n,(e=>{var{typed:t}=e;return t(name$4n,{any:typeOf$1})}));function nearlyEqual(e,t,n){if(null==n)return e.eq(t);if(e.eq(t))return!0;if(e.isNaN()||t.isNaN())return!1;if(e.isFinite()&&t.isFinite()){var r=e.minus(t).abs();if(r.isZero())return!0;var a=e.constructor.max(e.abs(),t.abs());return r.lte(a.times(n))}return!1}function complexEquals(e,t,n){return nearlyEqual$1(e.re,t.re,n)&&nearlyEqual$1(e.im,t.im,n)}var name$4m="equalScalar",dependencies$4m=["typed","config"],createEqualScalar=factory(name$4m,dependencies$4m,(e=>{var{typed:t,config:n}=e;return t(name$4m,{"boolean, boolean":function(e,t){return e===t},"number, number":function(e,t){return nearlyEqual$1(e,t,n.epsilon)},"BigNumber, BigNumber":function(e,t){return e.eq(t)||nearlyEqual(e,t,n.epsilon)},"Fraction, Fraction":function(e,t){return e.equals(t)},"Complex, Complex":function(e,t){return complexEquals(e,t,n.epsilon)},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)}})}));factory(name$4m,["typed","config"],(e=>{var{typed:t,config:n}=e;return t(name$4m,{"number, number":function(e,t){return nearlyEqual$1(e,t,n.epsilon)}})}));var name$4l="SparseMatrix",dependencies$4l=["typed","equalScalar","Matrix"],createSparseMatrixClass=factory(name$4l,dependencies$4l,(e=>{var{typed:t,equalScalar:n,Matrix:r}=e;function a(e,t){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");if(t&&!isString$1(t))throw new Error("Invalid datatype: "+t);if(isMatrix(e))!function(e,t,n){"SparseMatrix"===t.type?(e._values=t._values?clone$3(t._values):void 0,e._index=clone$3(t._index),e._ptr=clone$3(t._ptr),e._size=clone$3(t._size),e._datatype=n||t._datatype):i(e,t.valueOf(),n||t._datatype)}(this,e,t);else if(e&&isArray$1(e.index)&&isArray$1(e.ptr)&&isArray$1(e.size))this._values=e.values,this._index=e.index,this._ptr=e.ptr,this._size=e.size,this._datatype=t||e.datatype;else if(isArray$1(e))i(this,e,t);else{if(e)throw new TypeError("Unsupported type of data ("+typeOf$1(e)+")");this._values=[],this._index=[],this._ptr=[0],this._size=[0,0],this._datatype=t}}function i(e,r,a){e._values=[],e._index=[],e._ptr=[],e._datatype=a;var i=r.length,s=0,o=n,l=0;if(isString$1(a)&&(o=t.find(n,[a,a])||n,l=t.convert(0,a)),i>0){var u=0;do{e._ptr.push(e._index.length);for(var c=0;ch){for(c=h;cm){if(d){var f=0;for(c=0;cr-1&&(e._values.splice(p,1),e._index.splice(p,1),g++)}e._ptr[c]=e._values.length}return e._size[0]=r,e._size[1]=a,e}function u(e,t,n,r,a){var i,s,o=r[0],l=r[1],u=[];for(i=0;i");if(1===i.length)t.dimension(0).forEach((function(t,a){validateIndex(t),e.set([t,0],n[a[0]],r)}));else{var u=t.dimension(0),c=t.dimension(1);u.forEach((function(t,a){validateIndex(t),c.forEach((function(i,s){validateIndex(i),e.set([t,i],n[a[0]][s[0]],r)}))}))}}return e}(this,e,t,n);default:throw new SyntaxError("Wrong number of arguments")}},a.prototype.get=function(e){if(!isArray$1(e))throw new TypeError("Array expected");if(e.length!==this._size.length)throw new DimensionError(e.length,this._size.length);if(!this._values)throw new Error("Cannot invoke get on a Pattern only matrix");var t=e[0],n=e[1];validateIndex(t,this._size[0]),validateIndex(n,this._size[1]);var r=s(t,this._ptr[n],this._ptr[n+1],this._index);return rc-1||u>p-1)&&(l(this,Math.max(i+1,c),Math.max(u+1,p),a),c=this._size[0],p=this._size[1]),validateIndex(i,c),validateIndex(u,p);var h=s(i,this._ptr[u],this._ptr[u+1],this._index);return hArray.isArray(e)&&1===e.length?e[0]:e));if(2!==r.length)throw new Error("Only two dimensions matrix are supported");return r.forEach((function(e){if(!isNumber$1(e)||!isInteger$1(e)||e<0)throw new TypeError("Invalid size, must contain positive integers (size: "+format$1(r)+")")})),l(n?this.clone():this,r[0],r[1],t)},a.prototype.reshape=function(e,t){if(!isArray$1(e))throw new TypeError("Array expected");if(2!==e.length)throw new Error("Sparse matrices can only be reshaped in two dimensions");e.forEach((function(t){if(!isNumber$1(t)||!isInteger$1(t)||t<=-2||0===t)throw new TypeError("Invalid size, must contain positive integers or -1 (size: "+format$1(e)+")")}));var n=this._size[0]*this._size[1];if(n!==(e=processSizesWildcard(e,n))[0]*e[1])throw new Error("Reshaping sparse matrix will result in the wrong number of elements");var r=t?this.clone():this;if(this._size[0]===e[0]&&this._size[1]===e[1])return r;for(var a=[],i=0;i=0&&N<=i&&f(e._values[v],N-0,y-0)}else{for(var T={},C=g;C "+(this._values?format$1(this._values[l],e):"X");return a},a.prototype.toString=function(){return format$1(this.toArray())},a.prototype.toJSON=function(){return{mathjs:"SparseMatrix",values:this._values,index:this._index,ptr:this._ptr,size:this._size,datatype:this._datatype}},a.prototype.diagonal=function(e){if(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger$1(e))throw new TypeError("The parameter k must be an integer number")}else e=0;var t=e>0?e:0,n=e<0?-e:0,r=this._size[0],i=this._size[1],s=Math.min(r-n,i-t),o=[],l=[],u=[];u[0]=0;for(var c=t;c0?i:0,d=i<0?-i:0,m=e[0],h=e[1],f=Math.min(m-d,h-p);if(isArray$1(r)){if(r.length!==f)throw new Error("Invalid value array length");c=function(e){return r[e]}}else if(isMatrix(r)){var y=r.size();if(1!==y.length||y[0]!==f)throw new Error("Invalid matrix length");c=function(e){return r.get([e])}}else c=function(){return r};for(var g=[],b=[],v=[],N=0;N=0&&T=u||a[p]!==t)){var m=r?r[c]:void 0;a.splice(p,0,t),r&&r.splice(p,0,m),a.splice(p<=c?c+1:c,1),r&&r.splice(p<=c?c+1:c,1)}else if(p=u||a[c]!==e)){var h=r?r[p]:void 0;a.splice(c,0,e),r&&r.splice(c,0,h),a.splice(c<=p?p+1:p,1),r&&r.splice(c<=p?p+1:p,1)}}},a}),{isClass:!0}),name$4k="number",dependencies$4k=["typed"];function getNonDecimalNumberParts(e){var t=e.match(/(0[box])([0-9a-fA-F]*)\.([0-9a-fA-F]*)/);return t?{input:e,radix:{"0b":2,"0o":8,"0x":16}[t[1]],integerPart:t[2],fractionalPart:t[3]}:null}function makeNumberFromNonDecimalParts(e){for(var t=parseInt(e.integerPart,e.radix),n=0,r=0;r{var{typed:t}=e,n=t("number",{"":function(){return 0},number:function(e){return e},string:function(e){if("NaN"===e)return NaN;var t=getNonDecimalNumberParts(e);if(t)return makeNumberFromNonDecimalParts(t);var n=0,r=e.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);r&&(n=Number(r[2]),e=r[1]);var a=Number(e);if(isNaN(a))throw new SyntaxError('String "'+e+'" is no valid number');if(r){if(a>2**n-1)throw new SyntaxError('String "'.concat(e,'" is out of range'));a>=2**(n-1)&&(a-=2**n)}return a},BigNumber:function(e){return e.toNumber()},Fraction:function(e){return e.valueOf()},Unit:function(e){throw new Error("Second argument with valueless unit expected")},null:function(e){return 0},"Unit, string | Unit":function(e,t){return e.toNumber(t)},"Array | Matrix":function(e){return deepMap(e,this)}});return n.fromJSON=function(e){return parseFloat(e.value)},n})),name$4j="string",dependencies$4j=["typed"],createString=factory(name$4j,dependencies$4j,(e=>{var{typed:t}=e;return t(name$4j,{"":function(){return""},number:format$3,null:function(e){return"null"},boolean:function(e){return e+""},string:function(e){return e},"Array | Matrix":function(e){return deepMap(e,this)},any:function(e){return String(e)}})})),name$4i="boolean",dependencies$4i=["typed"],createBoolean=factory(name$4i,dependencies$4i,(e=>{var{typed:t}=e;return t(name$4i,{"":function(){return!1},boolean:function(e){return e},number:function(e){return!!e},null:function(e){return!1},BigNumber:function(e){return!e.isZero()},string:function(e){var t=e.toLowerCase();if("true"===t)return!0;if("false"===t)return!1;var n=Number(e);if(""!==e&&!isNaN(n))return!!n;throw new Error('Cannot convert "'+e+'" to a boolean')},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4h="bignumber",dependencies$4h=["typed","BigNumber"],createBignumber=factory(name$4h,dependencies$4h,(e=>{var{typed:t,BigNumber:n}=e;return t("bignumber",{"":function(){return new n(0)},number:function(e){return new n(e+"")},string:function(e){var t=e.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);if(t){var r=t[2],a=n(t[1]),i=new n(2).pow(Number(r));if(a.gt(i.sub(1)))throw new SyntaxError('String "'.concat(e,'" is out of range'));var s=new n(2).pow(Number(r)-1);return a.gte(s)?a.sub(i):a}return new n(e)},BigNumber:function(e){return e},Fraction:function(e){return new n(e.n).div(e.d).times(e.s)},null:function(e){return new n(0)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4g="complex",dependencies$4g=["typed","Complex"],createComplex=factory(name$4g,dependencies$4g,(e=>{var{typed:t,Complex:n}=e;return t("complex",{"":function(){return n.ZERO},number:function(e){return new n(e,0)},"number, number":function(e,t){return new n(e,t)},"BigNumber, BigNumber":function(e,t){return new n(e.toNumber(),t.toNumber())},Fraction:function(e){return new n(e.valueOf(),0)},Complex:function(e){return e.clone()},string:function(e){return n(e)},null:function(e){return n(0)},Object:function(e){if("re"in e&&"im"in e)return new n(e.re,e.im);if("r"in e&&"phi"in e||"abs"in e&&"arg"in e)return new n(e);throw new Error("Expected object with properties (re and im) or (r and phi) or (abs and arg)")},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4f="fraction",dependencies$4f=["typed","Fraction"],createFraction=factory(name$4f,dependencies$4f,(e=>{var{typed:t,Fraction:n}=e;return t("fraction",{number:function(e){if(!isFinite(e)||isNaN(e))throw new Error(e+" cannot be represented as a fraction");return new n(e)},string:function(e){return new n(e)},"number, number":function(e,t){return new n(e,t)},null:function(e){return new n(0)},BigNumber:function(e){return new n(e.toString())},Fraction:function(e){return e},Object:function(e){return new n(e)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$4e="matrix",dependencies$4e=["typed","Matrix","DenseMatrix","SparseMatrix"],createMatrix=factory(name$4e,dependencies$4e,(e=>{var{typed:t,Matrix:n,DenseMatrix:r,SparseMatrix:a}=e;return t(name$4e,{"":function(){return i([])},string:function(e){return i([],e)},"string, string":function(e,t){return i([],e,t)},Array:function(e){return i(e)},Matrix:function(e){return i(e,e.storage())},"Array | Matrix, string":i,"Array | Matrix, string, string":i});function i(e,t,n){if("dense"===t||"default"===t||void 0===t)return new r(e,n);if("sparse"===t)return new a(e,n);throw new TypeError("Unknown matrix type "+JSON.stringify(t)+".")}})),name$4d="matrixFromFunction",dependencies$4d=["typed","matrix","isZero"],createMatrixFromFunction=factory(name$4d,dependencies$4d,(e=>{var{typed:t,matrix:n,isZero:r}=e;return t(name$4d,{"Array | Matrix, function, string, string":function(e,t,n,r){return a(e,t,n,r)},"Array | Matrix, function, string":function(e,t,n){return a(e,t,n)},"Matrix, function":function(e,t){return a(e,t,"dense")},"Array, function":function(e,t){return a(e,t,"dense").toArray()},"Array | Matrix, string, function":function(e,t,n){return a(e,n,t)},"Array | Matrix, string, string, function":function(e,t,n,r){return a(e,r,t,n)}});function a(e,t,a,i){var s;return(s=void 0!==i?n(a,i):n(a)).resize(e),s.forEach((function(e,n){var a=t(n);r(a)||s.set(n,a)})),s}})),name$4c="matrixFromRows",dependencies$4c=["typed","matrix","flatten","size"],createMatrixFromRows=factory(name$4c,dependencies$4c,(e=>{var{typed:t,matrix:n,flatten:r,size:a}=e;return t(name$4c,{"...Array":function(e){return i(e)},"...Matrix":function(e){return n(i(e.map((e=>e.toArray()))))}});function i(e){if(0===e.length)throw new TypeError("At least one row is needed to construct a matrix.");var t=s(e[0]),n=[];for(var a of e){var i=s(a);if(i!==t)throw new TypeError("The vectors had different length: "+(0|t)+" ≠ "+(0|i));n.push(r(a))}return n}function s(e){var t=a(e);if(1===t.length)return t[0];if(2===t.length){if(1===t[0])return t[1];if(1===t[1])return t[0];throw new TypeError("At least one of the arguments is not a vector.")}throw new TypeError("Only one- or two-dimensional vectors are supported.")}})),name$4b="matrixFromColumns",dependencies$4b=["typed","matrix","flatten","size"],createMatrixFromColumns=factory(name$4b,dependencies$4b,(e=>{var{typed:t,matrix:n,flatten:r,size:a}=e;return t(name$4b,{"...Array":function(e){return i(e)},"...Matrix":function(e){return n(i(e.map((e=>e.toArray()))))}});function i(e){if(0===e.length)throw new TypeError("At least one column is needed to construct a matrix.");for(var t=s(e[0]),n=[],a=0;a{var{typed:t}=e;return t(name$4a,{"Unit, Array":function(e,t){return e.splitUnit(t)}})})),name$49="unaryMinus",dependencies$49=["typed"],createUnaryMinus=factory(name$49,dependencies$49,(e=>{var{typed:t}=e;return t(name$49,{number:unaryMinusNumber,Complex:function(e){return e.neg()},BigNumber:function(e){return e.neg()},Fraction:function(e){return e.neg()},Unit:function(e){var t=e.clone();return t.value=this(e.value),t},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$48="unaryPlus",dependencies$48=["typed","config","BigNumber"],createUnaryPlus=factory(name$48,dependencies$48,(e=>{var{typed:t,config:n,BigNumber:r}=e;return t(name$48,{number:unaryPlusNumber,Complex:function(e){return e},BigNumber:function(e){return e},Fraction:function(e){return e},Unit:function(e){return e.clone()},"Array | Matrix":function(e){return deepMap(e,this)},"boolean | string":function(e){return"BigNumber"===n.number?new r(+e):+e}})})),name$47="abs",dependencies$47=["typed"],createAbs=factory(name$47,dependencies$47,(e=>{var{typed:t}=e;return t(name$47,{number:absNumber,Complex:function(e){return e.abs()},BigNumber:function(e){return e.abs()},Fraction:function(e){return e.abs()},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){return e.abs()}})})),name$46="apply",dependencies$46=["typed","isInteger"],createApply=factory(name$46,dependencies$46,(e=>{var{typed:t,isInteger:n}=e;return t(name$46,{"Array | Matrix, number | BigNumber, function":function(e,t,r){if(!n(t))throw new TypeError("Integer number expected for dimension");var a=Array.isArray(e)?arraySize(e):e.size();if(t<0||t>=a.length)throw new IndexError(t,a.length);return isMatrix(e)?e.create(_apply(e.valueOf(),t,r)):_apply(e,t,r)}})}));function _apply(e,t,n){var r,a,i;if(t<=0){if(Array.isArray(e[0])){for(i=_switch(e),a=[],r=0;r{var{typed:t}=e;return t(name$45,{"number, number":addNumber,"Complex, Complex":function(e,t){return e.add(t)},"BigNumber, BigNumber":function(e,t){return e.plus(t)},"Fraction, Fraction":function(e,t){return e.add(t)},"Unit, Unit":function(e,t){if(null===e.value||void 0===e.value)throw new Error("Parameter x contains a unit with undefined value");if(null===t.value||void 0===t.value)throw new Error("Parameter y contains a unit with undefined value");if(!e.equalBase(t))throw new Error("Units do not match");var n=e.clone();return n.value=this(n.value,t.value),n.fixPrefix=!1,n}})})),name$44="cbrt",dependencies$44=["config","typed","isNegative","unaryMinus","matrix","Complex","BigNumber","Fraction"],createCbrt=factory(name$44,dependencies$44,(e=>{var{config:t,typed:n,isNegative:r,unaryMinus:a,matrix:i,Complex:s,BigNumber:o,Fraction:l}=e;return n(name$44,{number:cbrtNumber,Complex:u,"Complex, boolean":u,BigNumber:function(e){return e.cbrt()},Unit:function(e){if(e.value&&isComplex(e.value)){var t=e.clone();return t.value=1,(t=t.pow(1/3)).value=u(e.value),t}var n,i=r(e.value);i&&(e.value=a(e.value)),n=isBigNumber(e.value)?new o(1).div(3):isFraction(e.value)?new l(1,3):1/3;var s=e.pow(n);return i&&(s.value=a(s.value)),s},"Array | Matrix":function(e){return deepMap(e,this)}});function u(e,n){var r=e.arg()/3,a=e.abs(),o=new s(cbrtNumber(a),0).mul(new s(0,r).exp());if(n){var l=[o,new s(cbrtNumber(a),0).mul(new s(0,r+2*Math.PI/3).exp()),new s(cbrtNumber(a),0).mul(new s(0,r-2*Math.PI/3).exp())];return"Array"===t.matrix?l:i(l)}return o}})),name$43="algorithm11",dependencies$43=["typed","equalScalar"],createAlgorithm11=factory(name$43,dependencies$43,(e=>{var{typed:t,equalScalar:n}=e;return function(e,r,a,i){var s=e._values,o=e._index,l=e._ptr,u=e._size,c=e._datatype;if(!s)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var p,d=u[0],m=u[1],h=n,f=0,y=a;"string"==typeof c&&(p=c,h=t.find(n,[p,p]),f=t.convert(0,p),r=t.convert(r,p),y=t.find(a,[p,p]));for(var g=[],b=[],v=[],N=0;N{var{typed:t,DenseMatrix:n}=e;return function(e,r,a,i){var s=e._values,o=e._index,l=e._ptr,u=e._size,c=e._datatype;if(!s)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var p,d=u[0],m=u[1],h=a;"string"==typeof c&&(p=c,r=t.convert(r,p),h=t.find(a,[p,p]));for(var f=[],y=[],g=[],b=0;b{var{typed:t}=e;return function(e,r,a,i){var s,o=e._data,l=e._size,u=e._datatype,c=a;"string"==typeof u&&(s=u,r=t.convert(r,s),c=t.find(a,[s,s]));var p=l.length>0?n(c,0,l,l[0],o,r,i):[];return e.createDenseMatrix({data:p,size:clone$3(l),datatype:s})};function n(e,t,r,a,i,s,o){var l=[];if(t===r.length-1)for(var u=0;u{var{typed:t,config:n,round:r}=e;return t(name$40,{number:function(e){return nearlyEqual$1(e,r(e),n.epsilon)?r(e):Math.ceil(e)},"number, number":function(e,t){if(nearlyEqual$1(e,r(e,t),n.epsilon))return r(e,t);var[a,i]="".concat(e,"e").split("e"),s=Math.ceil(Number("".concat(a,"e").concat(Number(i)+t)));return[a,i]="".concat(s,"e").split("e"),Number("".concat(a,"e").concat(Number(i)-t))}})})),createCeil=factory(name$40,dependencies$40,(e=>{var{typed:t,config:n,round:r,matrix:a,equalScalar:i,zeros:s,DenseMatrix:o}=e,l=createAlgorithm11({typed:t,equalScalar:i}),u=createAlgorithm12({typed:t,DenseMatrix:o}),c=createAlgorithm14({typed:t}),p=createCeilNumber({typed:t,config:n,round:r});return t("ceil",{number:p.signatures.number,"number,number":p.signatures["number,number"],Complex:function(e){return e.ceil()},"Complex, number":function(e,t){return e.ceil(t)},"Complex, BigNumber":function(e,t){return e.ceil(t.toNumber())},BigNumber:function(e){return nearlyEqual(e,r(e),n.epsilon)?r(e):e.ceil()},"BigNumber, BigNumber":function(e,t){return nearlyEqual(e,r(e,t),n.epsilon)?r(e,t):e.toDecimalPlaces(t.toNumber(),Decimal.ROUND_CEIL)},Fraction:function(e){return e.ceil()},"Fraction, number":function(e,t){return e.ceil(t)},"Fraction, BigNumber":function(e,t){return e.ceil(t.toNumber())},"Array | Matrix":function(e){return deepMap(e,this)},"Array, number | BigNumber":function(e,t){return deepMap(e,(e=>this(e,t)))},"SparseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return c(e,t,this,!1)},"number | Complex | Fraction | BigNumber, Array":function(e,t){return c(a(t),e,this,!0).valueOf()},"number | Complex | Fraction | BigNumber, Matrix":function(e,t){return i(e,0)?s(t.size(),t.storage()):"dense"===t.storage()?c(t,e,this,!0):u(t,e,this,!0)}})})),name$3$="cube",dependencies$3$=["typed"],createCube=factory(name$3$,dependencies$3$,(e=>{var{typed:t}=e;return t(name$3$,{number:cubeNumber,Complex:function(e){return e.mul(e).mul(e)},BigNumber:function(e){return e.times(e).times(e)},Fraction:function(e){return e.pow(3)},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){return e.pow(3)}})})),name$3_="exp",dependencies$3_=["typed"],createExp=factory(name$3_,dependencies$3_,(e=>{var{typed:t}=e;return t(name$3_,{number:expNumber,Complex:function(e){return e.exp()},BigNumber:function(e){return e.exp()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3Z="expm1",dependencies$3Z=["typed","Complex"],createExpm1=factory(name$3Z,dependencies$3Z,(e=>{var{typed:t,Complex:n}=e;return t(name$3Z,{number:expm1Number,Complex:function(e){var t=Math.exp(e.re);return new n(t*Math.cos(e.im)-1,t*Math.sin(e.im))},BigNumber:function(e){return e.exp().minus(1)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3Y="fix",dependencies$3Y=["typed","Complex","matrix","ceil","floor","equalScalar","zeros","DenseMatrix"],createFixNumber=factory(name$3Y,["typed","ceil","floor"],(e=>{var{typed:t,ceil:n,floor:r}=e;return t(name$3Y,{number:function(e){return e>0?r(e):n(e)},"number, number":function(e,t){return e>0?r(e,t):n(e,t)}})})),createFix=factory(name$3Y,dependencies$3Y,(e=>{var{typed:t,Complex:n,matrix:r,ceil:a,floor:i,equalScalar:s,zeros:o,DenseMatrix:l}=e,u=createAlgorithm12({typed:t,DenseMatrix:l}),c=createAlgorithm14({typed:t}),p=createFixNumber({typed:t,ceil:a,floor:i});return t("fix",{number:p.signatures.number,"number, number | BigNumber":p.signatures["number,number"],Complex:function(e){return new n(e.re>0?Math.floor(e.re):Math.ceil(e.re),e.im>0?Math.floor(e.im):Math.ceil(e.im))},"Complex, number":function(e,t){return new n(e.re>0?i(e.re,t):a(e.re,t),e.im>0?i(e.im,t):a(e.im,t))},"Complex, BigNumber":function(e,t){var r=t.toNumber();return new n(e.re>0?i(e.re,r):a(e.re,r),e.im>0?i(e.im,r):a(e.im,r))},BigNumber:function(e){return e.isNegative()?a(e):i(e)},"BigNumber, number | BigNumber":function(e,t){return e.isNegative()?a(e,t):i(e,t)},Fraction:function(e){return e.s<0?e.ceil():e.floor()},"Fraction, number | BigNumber":function(e,t){return e.s<0?a(e,t):i(e,t)},"Array | Matrix":function(e){return deepMap(e,this)},"Array | Matrix, number | BigNumber":function(e,t){return deepMap(e,(e=>this(e,t)))},"number | Complex | Fraction | BigNumber, Array":function(e,t){return c(r(t),e,this,!0).valueOf()},"number | Complex | Fraction | BigNumber, Matrix":function(e,t){return s(e,0)?o(t.size(),t.storage()):"dense"===t.storage()?c(t,e,this,!0):u(t,e,this,!0)}})})),name$3X="floor",dependencies$3X=["typed","config","round","matrix","equalScalar","zeros","DenseMatrix"],createFloorNumber=factory(name$3X,["typed","config","round"],(e=>{var{typed:t,config:n,round:r}=e;return t(name$3X,{number:function(e){return nearlyEqual$1(e,r(e),n.epsilon)?r(e):Math.floor(e)},"number, number":function(e,t){if(nearlyEqual$1(e,r(e,t),n.epsilon))return r(e,t);var[a,i]="".concat(e,"e").split("e"),s=Math.floor(Number("".concat(a,"e").concat(Number(i)+t)));return[a,i]="".concat(s,"e").split("e"),Number("".concat(a,"e").concat(Number(i)-t))}})})),createFloor=factory(name$3X,dependencies$3X,(e=>{var{typed:t,config:n,round:r,matrix:a,equalScalar:i,zeros:s,DenseMatrix:o}=e,l=createAlgorithm11({typed:t,equalScalar:i}),u=createAlgorithm12({typed:t,DenseMatrix:o}),c=createAlgorithm14({typed:t}),p=createFloorNumber({typed:t,config:n,round:r});return t("floor",{number:p.signatures.number,"number,number":p.signatures["number,number"],Complex:function(e){return e.floor()},"Complex, number":function(e,t){return e.floor(t)},"Complex, BigNumber":function(e,t){return e.floor(t.toNumber())},BigNumber:function(e){return nearlyEqual(e,r(e),n.epsilon)?r(e):e.floor()},"BigNumber, BigNumber":function(e,t){return nearlyEqual(e,r(e,t),n.epsilon)?r(e,t):e.toDecimalPlaces(t.toNumber(),Decimal.ROUND_FLOOR)},Fraction:function(e){return e.floor()},"Fraction, number":function(e,t){return e.floor(t)},"Fraction, BigNumber":function(e,t){return e.floor(t.toNumber())},"Array | Matrix":function(e){return deepMap(e,this)},"Array, number | BigNumber":function(e,t){return deepMap(e,(e=>this(e,t)))},"SparseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return c(e,t,this,!1)},"number | Complex | Fraction | BigNumber, Array":function(e,t){return c(a(t),e,this,!0).valueOf()},"number | Complex | Fraction | BigNumber, Matrix":function(e,t){return i(e,0)?s(t.size(),t.storage()):"dense"===t.storage()?c(t,e,this,!0):u(t,e,this,!0)}})})),name$3W="algorithm01",dependencies$3W=["typed"],createAlgorithm01=factory(name$3W,dependencies$3W,(e=>{var{typed:t}=e;return function(e,n,r,a){var i=e._data,s=e._size,o=e._datatype,l=n._values,u=n._index,c=n._ptr,p=n._size,d=n._datatype;if(s.length!==p.length)throw new DimensionError(s.length,p.length);if(s[0]!==p[0]||s[1]!==p[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+p+")");if(!l)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var m,h,f=s[0],y=s[1],g="string"==typeof o&&o===d?o:void 0,b=g?t.find(r,[g,g]):r,v=[];for(m=0;m{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,s=e._index,o=e._ptr,l=e._size,u=e._datatype,c=r._values,p=r._index,d=r._ptr,m=r._size,h=r._datatype;if(l.length!==m.length)throw new DimensionError(l.length,m.length);if(l[0]!==m[0]||l[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+l+") must match Matrix B ("+m+")");var f,y=l[0],g=l[1],b=n,v=0,N=a;"string"==typeof u&&u===h&&(f=u,b=t.find(n,[f,f]),v=t.convert(0,f),N=t.find(a,[f,f]));var T,C,A,V,x,S=i&&c?[]:void 0,w=[],E=[],D=i&&c?[]:void 0,O=i&&c?[]:void 0,I=[],R=[];for(C=0;C{var{typed:t,DenseMatrix:n}=e;return function(e,r,a,i){var s=e._values,o=e._index,l=e._ptr,u=e._size,c=e._datatype;if(!s)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var p,d=u[0],m=u[1],h=a;"string"==typeof c&&(p=c,r=t.convert(r,p),h=t.find(a,[p,p]));for(var f=[],y=[],g=[],b=0;b{var{typed:t}=e;return function(e,r,a){var i,s=e._data,o=e._size,l=e._datatype,u=r._data,c=r._size,p=r._datatype,d=[];if(o.length!==c.length)throw new DimensionError(o.length,c.length);for(var m=0;m0?n(h,0,d,d[0],s,u):[];return e.createDenseMatrix({data:f,size:d,datatype:i})};function n(e,t,r,a,i,s){var o=[];if(t===r.length-1)for(var l=0;l{var{typed:t,matrix:n,equalScalar:r,BigNumber:a,DenseMatrix:i}=e,s=createAlgorithm01({typed:t}),o=createAlgorithm04({typed:t,equalScalar:r}),l=createAlgorithm10({typed:t,DenseMatrix:i}),u=createAlgorithm13({typed:t}),c=createAlgorithm14({typed:t});return t(name$3S,{"number, number":gcdNumber,"BigNumber, BigNumber":function(e,t){if(!e.isInt()||!t.isInt())throw new Error("Parameters in function gcd must be integer numbers");for(var n=new a(0);!t.isZero();){var r=e.mod(t);e=t,t=r}return e.lt(n)?e.neg():e},"Fraction, Fraction":function(e,t){return e.gcd(t)},"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return u(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return c(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return l(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return c(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return c(n(e),t,this,!1).valueOf()},"number | BigNumber, Array":function(e,t){return c(n(t),e,this,!0).valueOf()},"Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber":function(e,t,n){for(var r=this(e,t),a=0;a{var{typed:t,equalScalar:n}=e;return function(e,r,a,i){var s=e._data,o=e._size,l=e._datatype,u=r._values,c=r._index,p=r._ptr,d=r._size,m=r._datatype;if(o.length!==d.length)throw new DimensionError(o.length,d.length);if(o[0]!==d[0]||o[1]!==d[1])throw new RangeError("Dimension mismatch. Matrix A ("+o+") must match Matrix B ("+d+")");if(!u)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var h,f=o[0],y=o[1],g=n,b=0,v=a;"string"==typeof l&&l===m&&(h=l,g=t.find(n,[h,h]),b=t.convert(0,h),v=t.find(a,[h,h]));for(var N=[],T=[],C=[],A=0;A{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,s=e._size,o=e._datatype,l=r._values,u=r._size,c=r._datatype;if(s.length!==u.length)throw new DimensionError(s.length,u.length);if(s[0]!==u[0]||s[1]!==u[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+u+")");var p,d=s[0],m=s[1],h=n,f=0,y=a;"string"==typeof o&&o===c&&(p=o,h=t.find(n,[p,p]),f=t.convert(0,p),y=t.find(a,[p,p]));for(var g=i&&l?[]:void 0,b=[],v=[],N=g?[]:void 0,T=[],C=[],A=0;A{var{typed:t,matrix:n,equalScalar:r}=e,a=createAlgorithm02({typed:t,equalScalar:r}),i=createAlgorithm06({typed:t,equalScalar:r}),s=createAlgorithm11({typed:t,equalScalar:r}),o=createAlgorithm13({typed:t}),l=createAlgorithm14({typed:t});return t(name$3P,{"number, number":lcmNumber,"BigNumber, BigNumber":function(e,t){if(!e.isInt()||!t.isInt())throw new Error("Parameters in function lcm must be integer numbers");if(e.isZero())return e;if(t.isZero())return t;for(var n=e.times(t);!t.isZero();){var r=t;t=e.mod(r),e=r}return n.div(e).abs()},"Fraction, Fraction":function(e,t){return e.lcm(t)},"SparseMatrix, SparseMatrix":function(e,t){return i(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return a(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return a(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return o(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return s(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return s(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return l(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return l(n(e),t,this,!1).valueOf()},"number | BigNumber, Array":function(e,t){return l(n(t),e,this,!0).valueOf()},"Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber":function(e,t,n){for(var r=this(e,t),a=0;a{var{typed:t,config:n,Complex:r}=e;return t(name$3O,{number:function(e){return e>=0||n.predictable?log10Number(e):new r(e,0).log().div(Math.LN10)},Complex:function(e){return new r(e).log().div(Math.LN10)},BigNumber:function(e){return!e.isNegative()||n.predictable?e.log():new r(e.toNumber(),0).log().div(Math.LN10)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3N="log2",dependencies$3N=["typed","config","Complex"],createLog2=factory(name$3N,dependencies$3N,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$3N,{number:function(e){return e>=0||n.predictable?log2Number(e):a(new r(e,0))},Complex:a,BigNumber:function(e){return!e.isNegative()||n.predictable?e.log(2):a(new r(e.toNumber(),0))},"Array | Matrix":function(e){return deepMap(e,this)}});function a(e){var t=Math.sqrt(e.re*e.re+e.im*e.im);return new r(Math.log2?Math.log2(t):Math.log(t)/Math.LN2,Math.atan2(e.im,e.re)/Math.LN2)}})),name$3M="algorithm03",dependencies$3M=["typed"],createAlgorithm03=factory(name$3M,dependencies$3M,(e=>{var{typed:t}=e;return function(e,n,r,a){var i=e._data,s=e._size,o=e._datatype,l=n._values,u=n._index,c=n._ptr,p=n._size,d=n._datatype;if(s.length!==p.length)throw new DimensionError(s.length,p.length);if(s[0]!==p[0]||s[1]!==p[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+p+")");if(!l)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var m,h=s[0],f=s[1],y=0,g=r;"string"==typeof o&&o===d&&(m=o,y=t.convert(0,m),g=t.find(r,[m,m]));for(var b=[],v=0;v{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,s=e._index,o=e._ptr,l=e._size,u=e._datatype,c=r._values,p=r._index,d=r._ptr,m=r._size,h=r._datatype;if(l.length!==m.length)throw new DimensionError(l.length,m.length);if(l[0]!==m[0]||l[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+l+") must match Matrix B ("+m+")");var f,y=l[0],g=l[1],b=n,v=0,N=a;"string"==typeof u&&u===h&&(f=u,b=t.find(n,[f,f]),v=t.convert(0,f),N=t.find(a,[f,f]));var T,C,A,V,x=i&&c?[]:void 0,S=[],w=[],E=x?[]:void 0,D=x?[]:void 0,O=[],I=[];for(C=0;C{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:a}=e,i=createAlgorithm02({typed:t,equalScalar:r}),s=createAlgorithm03({typed:t}),o=createAlgorithm05({typed:t,equalScalar:r}),l=createAlgorithm11({typed:t,equalScalar:r}),u=createAlgorithm12({typed:t,DenseMatrix:a}),c=createAlgorithm13({typed:t}),p=createAlgorithm14({typed:t});return t(name$3K,{"number, number":modNumber,"BigNumber, BigNumber":function(e,t){if(t.isNeg())throw new Error("Cannot calculate mod for a negative divisor");return t.isZero()?e:e.mod(t)},"Fraction, Fraction":function(e,t){if(t.compare(0)<0)throw new Error("Cannot calculate mod for a negative divisor");return e.compare(0)>=0?e.mod(t):e.mod(t).add(t).mod(t)},"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return c(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return l(e,t,this,!1)},"DenseMatrix, any":function(e,t){return p(e,t,this,!1)},"any, SparseMatrix":function(e,t){return u(t,e,this,!0)},"any, DenseMatrix":function(e,t){return p(t,e,this,!0)},"Array, any":function(e,t){return p(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return p(n(t),e,this,!0).valueOf()}})})),name$3J="multiplyScalar",dependencies$3J=["typed"],createMultiplyScalar=factory(name$3J,dependencies$3J,(e=>{var{typed:t}=e;return t("multiplyScalar",{"number, number":multiplyNumber,"Complex, Complex":function(e,t){return e.mul(t)},"BigNumber, BigNumber":function(e,t){return e.times(t)},"Fraction, Fraction":function(e,t){return e.mul(t)},"number | Fraction | BigNumber | Complex, Unit":function(e,t){var n=t.clone();return n.value=null===n.value?n._normalize(e):this(n.value,e),n},"Unit, number | Fraction | BigNumber | Complex":function(e,t){var n=e.clone();return n.value=null===n.value?n._normalize(t):this(n.value,t),n},"Unit, Unit":function(e,t){return e.multiply(t)}})})),name$3I="multiply",dependencies$3I=["typed","matrix","addScalar","multiplyScalar","equalScalar","dot"],createMultiply=factory(name$3I,dependencies$3I,(e=>{var{typed:t,matrix:n,addScalar:r,multiplyScalar:a,equalScalar:i,dot:s}=e,o=createAlgorithm11({typed:t,equalScalar:i}),l=createAlgorithm14({typed:t});function u(e,t){switch(e.length){case 1:switch(t.length){case 1:if(e[0]!==t[0])throw new RangeError("Dimension mismatch in multiplication. Vectors must have the same length");break;case 2:if(e[0]!==t[0])throw new RangeError("Dimension mismatch in multiplication. Vector length ("+e[0]+") must match Matrix rows ("+t[0]+")");break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix B has "+t.length+" dimensions)")}break;case 2:switch(t.length){case 1:if(e[1]!==t[0])throw new RangeError("Dimension mismatch in multiplication. Matrix columns ("+e[1]+") must match Vector length ("+t[0]+")");break;case 2:if(e[1]!==t[0])throw new RangeError("Dimension mismatch in multiplication. Matrix A columns ("+e[1]+") must match Matrix B rows ("+t[0]+")");break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix B has "+t.length+" dimensions)")}break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix A has "+e.length+" dimensions)")}}function c(e,n){if("dense"!==n.storage())throw new Error("Support for SparseMatrix not implemented");return function(e,n){var i,s=e._data,o=e._size,l=e._datatype,u=n._data,c=n._size,p=n._datatype,d=o[0],m=c[1],h=r,f=a;l&&p&&l===p&&"string"==typeof l&&(i=l,h=t.find(r,[i,i]),f=t.find(a,[i,i]));for(var y=[],g=0;gS)for(var E=0,D=0;D{var{typed:t,matrix:n,equalScalar:r,BigNumber:a}=e,i=createAlgorithm01({typed:t}),s=createAlgorithm02({typed:t,equalScalar:r}),o=createAlgorithm06({typed:t,equalScalar:r}),l=createAlgorithm11({typed:t,equalScalar:r}),u=createAlgorithm13({typed:t}),c=createAlgorithm14({typed:t}),p="Complex number not supported in function nthRoot. Use nthRoots instead.";return t(name$3H,{number:nthRootNumber,"number, number":nthRootNumber,BigNumber:function(e){return d(e,new a(2))},Complex:function(e){throw new Error(p)},"Complex, number":function(e,t){throw new Error(p)},"BigNumber, BigNumber":d,"Array | Matrix":function(e){return this(e,2)},"SparseMatrix, SparseMatrix":function(e,t){if(1===t.density())return o(e,t,this);throw new Error("Root must be non-zero")},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){if(1===t.density())return i(e,t,this,!1);throw new Error("Root must be non-zero")},"DenseMatrix, DenseMatrix":function(e,t){return u(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return l(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return c(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){if(1===t.density())return l(t,e,this,!0);throw new Error("Root must be non-zero")},"number | BigNumber, DenseMatrix":function(e,t){return c(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return this(n(e),t).valueOf()},"number | BigNumber, Array":function(e,t){return this(e,n(t)).valueOf()}});function d(e,t){var n=a.precision,r=a.clone({precision:n+2}),i=new a(0),s=new r(1),o=t.isNegative();if(o&&(t=t.neg()),t.isZero())throw new Error("Root must be non-zero");if(e.isNegative()&&!t.abs().mod(2).equals(1))throw new Error("Root must be odd when a is negative.");if(e.isZero())return o?new r(1/0):0;if(!e.isFinite())return o?i:e;var l=e.abs().pow(s.div(t));return l=e.isNeg()?l.neg():l,new a((o?s.div(l):l).toPrecision(n))}})),name$3G="sign",dependencies$3G=["typed","BigNumber","Fraction","complex"],createSign=factory(name$3G,dependencies$3G,(e=>{var{typed:t,BigNumber:n,complex:r,Fraction:a}=e;return t(name$3G,{number:signNumber,Complex:function(e){return 0===e.im?r(signNumber(e.re)):e.sign()},BigNumber:function(e){return new n(e.cmp(0))},Fraction:function(e){return new a(e.s,1)},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){if(!e._isDerived()&&0!==e.units[0].unit.offset)throw new TypeError("sign is ambiguous for units with offset");return this(e.value)}})})),name$3F="sqrt",dependencies$3F=["config","typed","Complex"],createSqrt=factory(name$3F,dependencies$3F,(e=>{var{config:t,typed:n,Complex:r}=e;return n("sqrt",{number:a,Complex:function(e){return e.sqrt()},BigNumber:function(e){return!e.isNegative()||t.predictable?e.sqrt():a(e.toNumber())},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){return e.pow(.5)}});function a(e){return isNaN(e)?NaN:e>=0||t.predictable?Math.sqrt(e):new r(e,0).sqrt()}})),name$3E="square",dependencies$3E=["typed"],createSquare=factory(name$3E,dependencies$3E,(e=>{var{typed:t}=e;return t(name$3E,{number:squareNumber,Complex:function(e){return e.mul(e)},BigNumber:function(e){return e.times(e)},Fraction:function(e){return e.mul(e)},"Array | Matrix":function(e){return deepMap(e,this)},Unit:function(e){return e.pow(2)}})})),name$3D="subtract",dependencies$3D=["typed","matrix","equalScalar","addScalar","unaryMinus","DenseMatrix"],createSubtract=factory(name$3D,dependencies$3D,(e=>{var{typed:t,matrix:n,equalScalar:r,addScalar:a,unaryMinus:i,DenseMatrix:s}=e,o=createAlgorithm01({typed:t}),l=createAlgorithm03({typed:t}),u=createAlgorithm05({typed:t,equalScalar:r}),c=createAlgorithm10({typed:t,DenseMatrix:s}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$3D,{"number, number":function(e,t){return e-t},"Complex, Complex":function(e,t){return e.sub(t)},"BigNumber, BigNumber":function(e,t){return e.minus(t)},"Fraction, Fraction":function(e,t){return e.sub(t)},"Unit, Unit":function(e,t){if(null===e.value)throw new Error("Parameter x contains a unit with undefined value");if(null===t.value)throw new Error("Parameter y contains a unit with undefined value");if(!e.equalBase(t))throw new Error("Units do not match");var n=e.clone();return n.value=this(n.value,t.value),n.fixPrefix=!1,n},"SparseMatrix, SparseMatrix":function(e,t){return checkEqualDimensions(e,t),u(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return checkEqualDimensions(e,t),l(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return checkEqualDimensions(e,t),o(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return checkEqualDimensions(e,t),p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return c(e,i(t),a)},"DenseMatrix, any":function(e,t){return d(e,t,this)},"any, SparseMatrix":function(e,t){return c(t,e,this,!0)},"any, DenseMatrix":function(e,t){return d(t,e,this,!0)},"Array, any":function(e,t){return d(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return d(n(t),e,this,!0).valueOf()}})}));function checkEqualDimensions(e,t){var n=e.size(),r=t.size();if(n.length!==r.length)throw new DimensionError(n.length,r.length)}var name$3C="xgcd",dependencies$3C=["typed","config","matrix","BigNumber"],createXgcd=factory(name$3C,dependencies$3C,(e=>{var{typed:t,config:n,matrix:r,BigNumber:a}=e;return t(name$3C,{"number, number":function(e,t){var a=xgcdNumber(e,t);return"Array"===n.matrix?a:r(a)},"BigNumber, BigNumber":function(e,t){var i,s,o,l,u=new a(0),c=new a(1),p=u,d=c,m=c,h=u;if(!e.isInt()||!t.isInt())throw new Error("Parameters in function xgcd must be integer numbers");for(;!t.isZero();)s=e.div(t).floor(),o=e.mod(t),i=p,p=d.minus(s.times(p)),d=i,i=m,m=h.minus(s.times(m)),h=i,e=t,t=o;return l=e.lt(u)?[e.neg(),d.neg(),h.neg()]:[e,e.isZero()?0:d,h],"Array"===n.matrix?l:r(l)}})})),name$3B="invmod",dependencies$3B=["typed","config","BigNumber","xgcd","equal","smaller","mod","add","isInteger"],createInvmod=factory(name$3B,dependencies$3B,(e=>{var{typed:t,config:n,BigNumber:r,xgcd:a,equal:i,smaller:s,mod:o,add:l,isInteger:u}=e;return t(name$3B,{"number, number":c,"BigNumber, BigNumber":c});function c(e,t){if(!u(e)||!u(t))throw new Error("Parameters in function invmod must be integer numbers");if(e=o(e,t),i(t,0))throw new Error("Divisor must be non zero");var n=a(e,t);n=n.valueOf();var[c,p]=n;return i(c,r(1))?(p=o(p,t),s(p,r(0))&&(p=l(p,t)),p):NaN}})),name$3A="algorithm09",dependencies$3A=["typed","equalScalar"],createAlgorithm09=factory(name$3A,dependencies$3A,(e=>{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,s=e._index,o=e._ptr,l=e._size,u=e._datatype,c=r._values,p=r._index,d=r._ptr,m=r._size,h=r._datatype;if(l.length!==m.length)throw new DimensionError(l.length,m.length);if(l[0]!==m[0]||l[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+l+") must match Matrix B ("+m+")");var f,y=l[0],g=l[1],b=n,v=0,N=a;"string"==typeof u&&u===h&&(f=u,b=t.find(n,[f,f]),v=t.convert(0,f),N=t.find(a,[f,f]));var T,C,A,V,x,S=i&&c?[]:void 0,w=[],E=[],D=S?[]:void 0,O=[];for(C=0;C{var{typed:t,matrix:n,equalScalar:r,multiplyScalar:a}=e,i=createAlgorithm02({typed:t,equalScalar:r}),s=createAlgorithm09({typed:t,equalScalar:r}),o=createAlgorithm11({typed:t,equalScalar:r}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$3z,{"any, any":a,"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,a,!1)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,a,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,a,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,a)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return o(e,t,a,!1)},"DenseMatrix, any":function(e,t){return u(e,t,a,!1)},"any, SparseMatrix":function(e,t){return o(t,e,a,!0)},"any, DenseMatrix":function(e,t){return u(t,e,a,!0)},"Array, any":function(e,t){return u(n(e),t,a,!1).valueOf()},"any, Array":function(e,t){return u(n(t),e,a,!0).valueOf()}})}));function bitAndBigNumber(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function bitAnd");var n=e.constructor;if(e.isNaN()||t.isNaN())return new n(NaN);if(e.isZero()||t.eq(-1)||e.eq(t))return e;if(t.isZero()||e.eq(-1))return t;if(!e.isFinite()||!t.isFinite()){if(!e.isFinite()&&!t.isFinite())return e.isNegative()===t.isNegative()?e:new n(0);if(!e.isFinite())return t.isNegative()?e:e.isNegative()?new n(0):t;if(!t.isFinite())return e.isNegative()?t:t.isNegative()?new n(0):e}return bitwise(e,t,(function(e,t){return e&t}))}function bitNotBigNumber(e){if(e.isFinite()&&!e.isInteger())throw new Error("Integer expected in function bitNot");var t=e.constructor,n=t.precision;t.config({precision:1e9});var r=e.plus(new t(1));return r.s=-r.s||null,t.config({precision:n}),r}function bitOrBigNumber(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function bitOr");var n=e.constructor;if(e.isNaN()||t.isNaN())return new n(NaN);var r=new n(-1);return e.isZero()||t.eq(r)||e.eq(t)?t:t.isZero()||e.eq(r)?e:e.isFinite()&&t.isFinite()?bitwise(e,t,(function(e,t){return e|t})):!e.isFinite()&&!e.isNegative()&&t.isNegative()||e.isNegative()&&!t.isNegative()&&!t.isFinite()?r:e.isNegative()&&t.isNegative()?e.isFinite()?e:t:e.isFinite()?t:e}function bitwise(e,t,n){var r,a,i,s,o,l=e.constructor,u=+(e.s<0),c=+(t.s<0);if(u){r=decCoefficientToBinaryString(bitNotBigNumber(e));for(var p=0;p0;)n(i[--m],s[--h])===f&&(y=y.plus(g)),g=g.times(b);for(;h>0;)n(o,s[--h])===f&&(y=y.plus(g)),g=g.times(b);return l.config({precision:v}),0===f&&(y.s=-y.s),y}function decCoefficientToBinaryString(e){for(var t=e.d,n=t[0]+"",r=1;r0)if(++o>u)for(o-=u;o--;)l+="0";else o1&&(null!==c[m+1]&&void 0!==c[m+1]||(c[m+1]=0),c[m+1]+=c[m]>>1,c[m]&=1)}return c.reverse()}function bitXor$1(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function bitXor");var n=e.constructor;if(e.isNaN()||t.isNaN())return new n(NaN);if(e.isZero())return t;if(t.isZero())return e;if(e.eq(t))return new n(0);var r=new n(-1);return e.eq(r)?bitNotBigNumber(t):t.eq(r)?bitNotBigNumber(e):e.isFinite()&&t.isFinite()?bitwise(e,t,(function(e,t){return e^t})):e.isFinite()||t.isFinite()?new n(e.isNegative()===t.isNegative()?1/0:-1/0):r}function leftShiftBigNumber(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function leftShift");var n=e.constructor;return e.isNaN()||t.isNaN()||t.isNegative()&&!t.isZero()?new n(NaN):e.isZero()||t.isZero()?e:e.isFinite()||t.isFinite()?t.lt(55)?e.times(Math.pow(2,t.toNumber())+""):e.times(new n(2).pow(t)):new n(NaN)}function rightArithShiftBigNumber(e,t){if(e.isFinite()&&!e.isInteger()||t.isFinite()&&!t.isInteger())throw new Error("Integers expected in function rightArithShift");var n=e.constructor;return e.isNaN()||t.isNaN()||t.isNegative()&&!t.isZero()?new n(NaN):e.isZero()||t.isZero()?e:t.isFinite()?t.lt(55)?e.div(Math.pow(2,t.toNumber())+"").floor():e.div(new n(2).pow(t)).floor():e.isNegative()?new n(-1):e.isFinite()?new n(0):new n(NaN)}var name$3y="bitAnd",dependencies$3y=["typed","matrix","equalScalar"],createBitAnd=factory(name$3y,dependencies$3y,(e=>{var{typed:t,matrix:n,equalScalar:r}=e,a=createAlgorithm02({typed:t,equalScalar:r}),i=createAlgorithm06({typed:t,equalScalar:r}),s=createAlgorithm11({typed:t,equalScalar:r}),o=createAlgorithm13({typed:t}),l=createAlgorithm14({typed:t});return t(name$3y,{"number, number":bitAndNumber,"BigNumber, BigNumber":bitAndBigNumber,"SparseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return a(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return a(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return o(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return s(e,t,this,!1)},"DenseMatrix, any":function(e,t){return l(e,t,this,!1)},"any, SparseMatrix":function(e,t){return s(t,e,this,!0)},"any, DenseMatrix":function(e,t){return l(t,e,this,!0)},"Array, any":function(e,t){return l(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return l(n(t),e,this,!0).valueOf()}})})),name$3x="bitNot",dependencies$3x=["typed"],createBitNot=factory(name$3x,dependencies$3x,(e=>{var{typed:t}=e;return t(name$3x,{number:bitNotNumber,BigNumber:bitNotBigNumber,"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3w="bitOr",dependencies$3w=["typed","matrix","equalScalar","DenseMatrix"],createBitOr=factory(name$3w,dependencies$3w,(e=>{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:a}=e,i=createAlgorithm01({typed:t}),s=createAlgorithm04({typed:t,equalScalar:r}),o=createAlgorithm10({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$3w,{"number, number":bitOrNumber,"BigNumber, BigNumber":bitOrBigNumber,"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(n(t),e,this,!0).valueOf()}})})),name$3v="algorithm07",dependencies$3v=["typed","DenseMatrix"],createAlgorithm07=factory(name$3v,dependencies$3v,(e=>{var{typed:t,DenseMatrix:n}=e;return function(e,a,i){var s=e._size,o=e._datatype,l=a._size,u=a._datatype;if(s.length!==l.length)throw new DimensionError(s.length,l.length);if(s[0]!==l[0]||s[1]!==l[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+l+")");var c,p,d,m=s[0],h=s[1],f=0,y=i;"string"==typeof o&&o===u&&(c=o,f=t.convert(0,c),y=t.find(i,[c,c]));var g=[];for(p=0;p{var{typed:t,matrix:n,DenseMatrix:r}=e,a=createAlgorithm03({typed:t}),i=createAlgorithm07({typed:t,DenseMatrix:r}),s=createAlgorithm12({typed:t,DenseMatrix:r}),o=createAlgorithm13({typed:t}),l=createAlgorithm14({typed:t});return t(name$3u,{"number, number":bitXorNumber,"BigNumber, BigNumber":bitXor$1,"SparseMatrix, SparseMatrix":function(e,t){return i(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return a(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return a(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return o(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return s(e,t,this,!1)},"DenseMatrix, any":function(e,t){return l(e,t,this,!1)},"any, SparseMatrix":function(e,t){return s(t,e,this,!0)},"any, DenseMatrix":function(e,t){return l(t,e,this,!0)},"Array, any":function(e,t){return l(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return l(n(t),e,this,!0).valueOf()}})})),name$3t="arg",dependencies$3t=["typed"],createArg=factory(name$3t,dependencies$3t,(e=>{var{typed:t}=e;return t(name$3t,{number:function(e){return Math.atan2(0,e)},BigNumber:function(e){return e.constructor.atan2(0,e)},Complex:function(e){return e.arg()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3s="conj",dependencies$3s=["typed"],createConj=factory(name$3s,dependencies$3s,(e=>{var{typed:t}=e;return t(name$3s,{number:function(e){return e},BigNumber:function(e){return e},Complex:function(e){return e.conjugate()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3r="im",dependencies$3r=["typed"],createIm=factory(name$3r,dependencies$3r,(e=>{var{typed:t}=e;return t(name$3r,{number:function(e){return 0},BigNumber:function(e){return e.mul(0)},Fraction:function(e){return e.mul(0)},Complex:function(e){return e.im},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3q="re",dependencies$3q=["typed"],createRe=factory(name$3q,dependencies$3q,(e=>{var{typed:t}=e;return t(name$3q,{number:function(e){return e},BigNumber:function(e){return e},Fraction:function(e){return e},Complex:function(e){return e.re},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3p="not",dependencies$3p=["typed"],createNot=factory(name$3p,dependencies$3p,(e=>{var{typed:t}=e;return t(name$3p,{number:notNumber,Complex:function(e){return 0===e.re&&0===e.im},BigNumber:function(e){return e.isZero()||e.isNaN()},Unit:function(e){return null===e.value||this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$3o="or",dependencies$3o=["typed","matrix","equalScalar","DenseMatrix"],createOr=factory(name$3o,dependencies$3o,(e=>{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm05({typed:t,equalScalar:r}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$3o,{"number, number":orNumber,"Complex, Complex":function(e,t){return 0!==e.re||0!==e.im||0!==t.re||0!==t.im},"BigNumber, BigNumber":function(e,t){return!e.isZero()&&!e.isNaN()||!t.isZero()&&!t.isNaN()},"Unit, Unit":function(e,t){return this(e.value||0,t.value||0)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(n(t),e,this,!0).valueOf()}})})),name$3n="xor",dependencies$3n=["typed","matrix","DenseMatrix"],createXor=factory(name$3n,dependencies$3n,(e=>{var{typed:t,matrix:n,DenseMatrix:r}=e,a=createAlgorithm03({typed:t}),i=createAlgorithm07({typed:t,DenseMatrix:r}),s=createAlgorithm12({typed:t,DenseMatrix:r}),o=createAlgorithm13({typed:t}),l=createAlgorithm14({typed:t});return t(name$3n,{"number, number":xorNumber,"Complex, Complex":function(e,t){return(0!==e.re||0!==e.im)!=(0!==t.re||0!==t.im)},"BigNumber, BigNumber":function(e,t){return(!e.isZero()&&!e.isNaN())!=(!t.isZero()&&!t.isNaN())},"Unit, Unit":function(e,t){return this(e.value||0,t.value||0)},"SparseMatrix, SparseMatrix":function(e,t){return i(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return a(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return a(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return o(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return s(e,t,this,!1)},"DenseMatrix, any":function(e,t){return l(e,t,this,!1)},"any, SparseMatrix":function(e,t){return s(t,e,this,!0)},"any, DenseMatrix":function(e,t){return l(t,e,this,!0)},"Array, any":function(e,t){return l(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return l(n(t),e,this,!0).valueOf()}})})),name$3m="concat",dependencies$3m=["typed","matrix","isInteger"],createConcat=factory(name$3m,dependencies$3m,(e=>{var{typed:t,matrix:n,isInteger:r}=e;return t(name$3m,{"...Array | Matrix | number | BigNumber":function(e){var t,a,i=e.length,s=-1,o=!1,l=[];for(t=0;t0&&s>a)throw new IndexError(s,a+1)}else{var c=clone$3(u).valueOf(),p=arraySize(c);if(l[t]=c,a=s,s=p.length-1,t>0&&s!==a)throw new DimensionError(a+1,s+1)}}if(0===l.length)throw new SyntaxError("At least one matrix expected");for(var d=l.shift();l.length;)d=_concat(d,l.shift(),s,0);return o?n(d):d},"...string":function(e){return e.join("")}})}));function _concat(e,t,n,r){if(r{var{typed:t,Index:n,matrix:r,range:a}=e;return t(name$3l,{"Matrix, number":i,"Array, number":function(e,t){return i(r(clone$3(e)),t).valueOf()}});function i(e,t){if(2!==e.size().length)throw new Error("Only two dimensional matrix is supported");validateIndex(t,e.size()[1]);var r=a(0,e.size()[0]),i=new n(r,t);return e.subset(i)}})),name$3k="count",dependencies$3k=["typed","size","prod"],createCount=factory(name$3k,dependencies$3k,(e=>{var{typed:t,size:n,prod:r}=e;return t(name$3k,{string:function(e){return e.length},"Matrix | Array":function(e){return r(n(e))}})})),name$3j="cross",dependencies$3j=["typed","matrix","subtract","multiply"],createCross=factory(name$3j,dependencies$3j,(e=>{var{typed:t,matrix:n,subtract:r,multiply:a}=e;return t(name$3j,{"Matrix, Matrix":function(e,t){return n(i(e.toArray(),t.toArray()))},"Matrix, Array":function(e,t){return n(i(e.toArray(),t))},"Array, Matrix":function(e,t){return n(i(e,t.toArray()))},"Array, Array":i});function i(e,t){var n=Math.max(arraySize(e).length,arraySize(t).length);e=squeeze$1(e),t=squeeze$1(t);var i=arraySize(e),s=arraySize(t);if(1!==i.length||1!==s.length||3!==i[0]||3!==s[0])throw new RangeError("Vectors with length 3 expected (Size A = ["+i.join(", ")+"], B = ["+s.join(", ")+"])");var o=[r(a(e[1],t[2]),a(e[2],t[1])),r(a(e[2],t[0]),a(e[0],t[2])),r(a(e[0],t[1]),a(e[1],t[0]))];return n>1?[o]:o}})),name$3i="diag",dependencies$3i=["typed","matrix","DenseMatrix","SparseMatrix"],createDiag=factory(name$3i,dependencies$3i,(e=>{var{typed:t,matrix:n,DenseMatrix:r,SparseMatrix:a}=e;return t(name$3i,{Array:function(e){return i(e,0,arraySize(e),null)},"Array, number":function(e,t){return i(e,t,arraySize(e),null)},"Array, BigNumber":function(e,t){return i(e,t.toNumber(),arraySize(e),null)},"Array, string":function(e,t){return i(e,0,arraySize(e),t)},"Array, number, string":function(e,t,n){return i(e,t,arraySize(e),n)},"Array, BigNumber, string":function(e,t,n){return i(e,t.toNumber(),arraySize(e),n)},Matrix:function(e){return i(e,0,e.size(),e.storage())},"Matrix, number":function(e,t){return i(e,t,e.size(),e.storage())},"Matrix, BigNumber":function(e,t){return i(e,t.toNumber(),e.size(),e.storage())},"Matrix, string":function(e,t){return i(e,0,e.size(),t)},"Matrix, number, string":function(e,t,n){return i(e,t,e.size(),n)},"Matrix, BigNumber, string":function(e,t,n){return i(e,t.toNumber(),e.size(),n)}});function i(e,t,i,s){if(!isInteger$1(t))throw new TypeError("Second parameter in function diag must be an integer");var o=t>0?t:0,l=t<0?-t:0;switch(i.length){case 1:return function(e,t,n,i,s,o){var l=[i+s,i+o];if(n&&"sparse"!==n&&"dense"!==n)throw new TypeError("Unknown matrix type ".concat(n,'"'));var u="sparse"===n?a.diagonal(l,e,t):r.diagonal(l,e,t);return null!==n?u:u.valueOf()}(e,t,s,i[0],l,o);case 2:return function(e,t,r,a,i,s){if(isMatrix(e)){var o=e.diagonal(t);return null!==r?r!==o.storage()?n(o,r):o:o.valueOf()}for(var l=Math.min(a[0]-i,a[1]-s),u=[],c=0;c1&&void 0!==arguments[1]?arguments[1]:{};return n=null==n?Number.POSITIVE_INFINITY:n,t=null==t?JSON.stringify:t,function r(){"object"!=typeof r.cache&&(r.cache={values:new Map,lru:lruQueue(n||Number.POSITIVE_INFINITY)});for(var a=[],i=0;i{var{typed:t}=e;return t("filter",{"Array, function":_filterCallback,"Matrix, function":function(e,t){return e.create(_filterCallback(e.toArray(),t))},"Array, RegExp":filterRegExp,"Matrix, RegExp":function(e,t){return e.create(filterRegExp(e.toArray(),t))}})}));function _filterCallback(e,t){var n=maxArgumentCount(t);return filter$2(e,(function(e,r,a){return 1===n?t(e):2===n?t(e,[r]):t(e,[r],a)}))}var name$3g="flatten",dependencies$3g=["typed","matrix"],createFlatten=factory(name$3g,dependencies$3g,(e=>{var{typed:t,matrix:n}=e;return t(name$3g,{Array:function(e){return flatten$4(clone$3(e))},Matrix:function(e){var t=flatten$4(clone$3(e.toArray()));return n(t)}})})),name$3f="forEach",dependencies$3f=["typed"],createForEach=factory(name$3f,dependencies$3f,(e=>{var{typed:t}=e;return t(name$3f,{"Array, function":_forEach,"Matrix, function":function(e,t){return e.forEach(t)}})}));function _forEach(e,t){var n=maxArgumentCount(t);!function r(a,i){Array.isArray(a)?forEach$1(a,(function(e,t){r(e,i.concat(t))})):1===n?t(a):2===n?t(a,i):t(a,i,e)}(e,[])}var name$3e="getMatrixDataType",dependencies$3e=["typed"],createGetMatrixDataType=factory(name$3e,dependencies$3e,(e=>{var{typed:t}=e;return t(name$3e,{Array:function(e){return getArrayDataType(e,typeOf$1)},Matrix:function(e){return e.getDataType()}})})),name$3d="identity",dependencies$3d=["typed","config","matrix","BigNumber","DenseMatrix","SparseMatrix"],createIdentity=factory(name$3d,dependencies$3d,(e=>{var{typed:t,config:n,matrix:r,BigNumber:a,DenseMatrix:i,SparseMatrix:s}=e;return t(name$3d,{"":function(){return"Matrix"===n.matrix?r([]):[]},string:function(e){return r(e)},"number | BigNumber":function(e){return l(e,e,"Matrix"===n.matrix?"dense":void 0)},"number | BigNumber, string":function(e,t){return l(e,e,t)},"number | BigNumber, number | BigNumber":function(e,t){return l(e,t,"Matrix"===n.matrix?"dense":void 0)},"number | BigNumber, number | BigNumber, string":function(e,t,n){return l(e,t,n)},Array:function(e){return o(e)},"Array, string":function(e,t){return o(e,t)},Matrix:function(e){return o(e.valueOf(),e.storage())},"Matrix, string":function(e,t){return o(e.valueOf(),t)}});function o(e,t){switch(e.length){case 0:return t?r(t):[];case 1:return l(e[0],e[0],t);case 2:return l(e[0],e[1],t);default:throw new Error("Vector containing two values expected")}}function l(e,t,n){var r=isBigNumber(e)||isBigNumber(t)?a:null;if(isBigNumber(e)&&(e=e.toNumber()),isBigNumber(t)&&(t=t.toNumber()),!isInteger$1(e)||e<1)throw new Error("Parameters in function identity must be positive integers");if(!isInteger$1(t)||t<1)throw new Error("Parameters in function identity must be positive integers");var o=r?new a(1):1,l=r?new r(0):0,u=[e,t];if(n){if("sparse"===n)return s.diagonal(u,o,0,l);if("dense"===n)return i.diagonal(u,o,0,l);throw new TypeError('Unknown matrix type "'.concat(n,'"'))}for(var c=resize$1([],u,l),p=e{var{typed:t,matrix:n,multiplyScalar:r}=e;return t(name$3c,{"Matrix, Matrix":function(e,t){return n(a(e.toArray(),t.toArray()))},"Matrix, Array":function(e,t){return n(a(e.toArray(),t))},"Array, Matrix":function(e,t){return n(a(e,t.toArray()))},"Array, Array":a});function a(e,t){if(1===arraySize(e).length&&(e=[e]),1===arraySize(t).length&&(t=[t]),arraySize(e).length>2||arraySize(t).length>2)throw new RangeError("Vectors with dimensions greater then 2 are not supported expected (Size x = "+JSON.stringify(e.length)+", y = "+JSON.stringify(t.length)+")");var n=[],a=[];return e.map((function(e){return t.map((function(t){return a=[],n.push(a),e.map((function(e){return t.map((function(t){return a.push(r(e,t))}))}))}))}))&&n}})),name$3b="map",dependencies$3b=["typed"],createMap=factory(name$3b,dependencies$3b,(e=>{var{typed:t}=e;return t(name$3b,{"Array, function":_map$1,"Matrix, function":function(e,t){return e.map(t)}})}));function _map$1(e,t){var n=maxArgumentCount(t);return function r(a,i){if(Array.isArray(a))return a.map((function(e,t){return r(e,i.concat(t))}));try{return 1===n?t(a):2===n?t(a,i):t(a,i,e)}catch(t){if(t instanceof TypeError&&"data"in t&&"wrongType"===t.data.category){var s="map attempted to call '".concat(t.data.fn,"(").concat(a),o=JSON.stringify(i);throw 2===n?s+=","+o:1!==n&&(s+=",".concat(o,",").concat(e)),s+=")' but argument ".concat(t.data.index+1," of type "),s+="".concat(t.data.actual," does not match expected type "),s+=t.data.expected.join(" or "),new TypeError(s)}throw t}}(e,[])}var name$3a="diff",dependencies$3a=["typed","matrix","subtract","number"],createDiff=factory(name$3a,dependencies$3a,(e=>{var{typed:t,matrix:n,subtract:r,number:a}=e;return t(name$3a,{"Array | Matrix":function(e){return isMatrix(e)?n(s(e.toArray())):s(e)},"Array | Matrix, number":function(e,t){if(!isInteger$1(t))throw new RangeError("Dimension must be a whole number");return isMatrix(e)?n(i(e.toArray(),t)):i(e,t)},"Array | Matrix, BigNumber":function(e,t){return this(e,a(t))}});function i(e,t){if(isMatrix(e)&&(e=e.toArray()),!Array.isArray(e))throw RangeError("Array/Matrix does not have that many dimensions");if(t>0){var n=[];return e.forEach((e=>{n.push(i(e,t-1))})),n}if(0===t)return s(e);throw RangeError("Cannot have negative dimension")}function s(e){var t=[],n=e.length;if(n<2)return e;for(var r=1;r{var{typed:t,config:n,matrix:r,BigNumber:a}=e;return t("ones",{"":function(){return"Array"===n.matrix?i([]):i([],"default")},"...number | BigNumber | string":function(e){if("string"==typeof e[e.length-1]){var t=e.pop();return i(e,t)}return"Array"===n.matrix?i(e):i(e,"default")},Array:i,Matrix:function(e){var t=e.storage();return i(e.valueOf(),t)},"Array | Matrix, string":function(e,t){return i(e.valueOf(),t)}});function i(e,t){var n=function(e){var t=!1;return e.forEach((function(e,n,r){isBigNumber(e)&&(t=!0,r[n]=e.toNumber())})),t}(e),i=n?new a(1):1;if(function(e){e.forEach((function(e){if("number"!=typeof e||!isInteger$1(e)||e<0)throw new Error("Parameters in function ones must be positive integers")}))}(e),t){var s=r(t);return e.length>0?s.resize(e,i):s}var o=[];return e.length>0?resize$1(o,e,i):o}}));function noBignumber(){throw new Error('No "bignumber" implementation available')}function noFraction(){throw new Error('No "fraction" implementation available')}function noMatrix(){throw new Error('No "matrix" implementation available')}var name$38="range",dependencies$38=["typed","config","?matrix","?bignumber","smaller","smallerEq","larger","largerEq"],createRange=factory(name$38,dependencies$38,(e=>{var{typed:t,config:n,matrix:r,bignumber:a,smaller:i,smallerEq:s,larger:o,largerEq:l}=e;return t(name$38,{string:c,"string, boolean":c,"number, number":function(e,t){return u(p(e,t,1))},"number, number, number":function(e,t,n){return u(p(e,t,n))},"number, number, boolean":function(e,t,n){return u(n?d(e,t,1):p(e,t,1))},"number, number, number, boolean":function(e,t,n,r){return u(r?d(e,t,n):p(e,t,n))},"BigNumber, BigNumber":function(e,t){return u(m(e,t,new e.constructor(1)))},"BigNumber, BigNumber, BigNumber":function(e,t,n){return u(m(e,t,n))},"BigNumber, BigNumber, boolean":function(e,t,n){var r=e.constructor;return u(n?h(e,t,new r(1)):m(e,t,new r(1)))},"BigNumber, BigNumber, BigNumber, boolean":function(e,t,n,r){return u(r?h(e,t,n):m(e,t,n))}});function u(e){return"Matrix"===n.matrix?r?r(e):noMatrix():e}function c(e,t){var r=function(e){var t=e.split(":").map((function(e){return Number(e)}));if(t.some((function(e){return isNaN(e)})))return null;switch(t.length){case 2:return{start:t[0],end:t[1],step:1};case 3:return{start:t[0],end:t[2],step:t[1]};default:return null}}(e);if(!r)throw new SyntaxError('String "'+e+'" is no valid range');return"BigNumber"===n.number?(void 0===a&&noBignumber(),u((t?h:m)(a(r.start),a(r.end),a(r.step)))):u((t?d:p)(r.start,r.end,r.step))}function p(e,t,n){var r=[],a=e;if(n>0)for(;i(a,t);)r.push(a),a+=n;else if(n<0)for(;o(a,t);)r.push(a),a+=n;return r}function d(e,t,n){var r=[],a=e;if(n>0)for(;s(a,t);)r.push(a),a+=n;else if(n<0)for(;l(a,t);)r.push(a),a+=n;return r}function m(e,t,n){var r=a(0),s=[],l=e;if(n.gt(r))for(;i(l,t);)s.push(l),l=l.plus(n);else if(n.lt(r))for(;o(l,t);)s.push(l),l=l.plus(n);return s}function h(e,t,n){var r=a(0),i=[],o=e;if(n.gt(r))for(;s(o,t);)i.push(o),o=o.plus(n);else if(n.lt(r))for(;l(o,t);)i.push(o),o=o.plus(n);return i}})),name$37="reshape",dependencies$37=["typed","isInteger","matrix"],createReshape=factory(name$37,dependencies$37,(e=>{var{typed:t,isInteger:n}=e;return t(name$37,{"Matrix, Array":function(e,t){return e.reshape(t)},"Array, Array":function(e,t){return t.forEach((function(e){if(!n(e))throw new TypeError("Invalid size for dimension: "+e)})),reshape$1(e,t)}})}));function ArgumentsError(e,t,n,r){if(!(this instanceof ArgumentsError))throw new SyntaxError("Constructor must be called with the new operator");this.fn=e,this.count=t,this.min=n,this.max=r,this.message="Wrong number of arguments in function "+e+" ("+t+" provided, "+n+(null!=r?"-"+r:"")+" expected)",this.stack=(new Error).stack}ArgumentsError.prototype=new Error,ArgumentsError.prototype.constructor=Error,ArgumentsError.prototype.name="ArgumentsError",ArgumentsError.prototype.isArgumentsError=!0;var name$36="resize",dependencies$36=["config","matrix"],createResize=factory(name$36,dependencies$36,(e=>{var{config:t,matrix:n}=e;return function(e,r,a){if(2!==arguments.length&&3!==arguments.length)throw new ArgumentsError("resize",arguments.length,2,3);if(isMatrix(r)&&(r=r.valueOf()),isBigNumber(r[0])&&(r=r.map((function(e){return isBigNumber(e)?e.toNumber():e}))),isMatrix(e))return e.resize(r,a,!0);if("string"==typeof e)return function(e,t,n){if(void 0!==n){if("string"!=typeof n||1!==n.length)throw new TypeError("Single character expected as defaultValue")}else n=" ";if(1!==t.length)throw new DimensionError(t.length,1);var r=t[0];if("number"!=typeof r||!isInteger$1(r))throw new TypeError("Invalid size, must contain positive integers (size: "+format$1(t)+")");if(e.length>r)return e.substring(0,r);if(e.length{var{typed:t,multiply:n,rotationMatrix:r}=e;return t(name$35,{"Array , number | BigNumber | Complex | Unit":function(e,t){return a(e,2),n(r(t),e).toArray()},"Matrix , number | BigNumber | Complex | Unit":function(e,t){return a(e,2),n(r(t),e)},"Array, number | BigNumber | Complex | Unit, Array | Matrix":function(e,t,i){return a(e,3),n(r(t,i),e)},"Matrix, number | BigNumber | Complex | Unit, Array | Matrix":function(e,t,i){return a(e,3),n(r(t,i),e)}});function a(e,t){var n=Array.isArray(e)?arraySize(e):e.size();if(n.length>2)throw new RangeError("Vector must be of dimensions 1x".concat(t));if(2===n.length&&1!==n[1])throw new RangeError("Vector must be of dimensions 1x".concat(t));if(n[0]!==t)throw new RangeError("Vector must be of dimensions 1x".concat(t))}})),name$34="rotationMatrix",dependencies$34=["typed","config","multiplyScalar","addScalar","unaryMinus","norm","matrix","BigNumber","DenseMatrix","SparseMatrix","cos","sin"],createRotationMatrix=factory(name$34,dependencies$34,(e=>{var{typed:t,config:n,multiplyScalar:r,addScalar:a,unaryMinus:i,norm:s,BigNumber:o,matrix:l,DenseMatrix:u,SparseMatrix:c,cos:p,sin:d}=e;return t(name$34,{"":function(){return"Matrix"===n.matrix?l([]):[]},string:function(e){return l(e)},"number | BigNumber | Complex | Unit":function(e){return m(e,"Matrix"===n.matrix?"dense":void 0)},"number | BigNumber | Complex | Unit, string":function(e,t){return m(e,t)},"number | BigNumber | Complex | Unit, Array":function(e,t){var n=l(t);return h(n),g(e,n,void 0)},"number | BigNumber | Complex | Unit, Matrix":function(e,t){h(t);var r=t.storage()||("Matrix"===n.matrix?"dense":void 0);return g(e,t,r)},"number | BigNumber | Complex | Unit, Array, string":function(e,t,n){var r=l(t);return h(r),g(e,r,n)},"number | BigNumber | Complex | Unit, Matrix, string":function(e,t,n){return h(t),g(e,t,n)}});function m(e,t){var n=isBigNumber(e)?new o(-1):-1,a=p(e),i=d(e);return y([[a,r(n,i)],[i,a]],t)}function h(e){var t=e.size();if(t.length<1||3!==t[0])throw new RangeError("Vector must be of dimensions 1x3")}function f(e){return e.reduce(((e,t)=>r(e,t)))}function y(e,t){if(t){if("sparse"===t)return new c(e);if("dense"===t)return new u(e);throw new TypeError('Unknown matrix type "'.concat(t,'"'))}return e}function g(e,t,n){var r=s(t);if(0===r)throw new RangeError("Rotation around zero vector");var l=isBigNumber(e)?o:null,u=l?new l(1):1,c=l?new l(-1):-1,m=l?new l(t.get([0])/r):t.get([0])/r,h=l?new l(t.get([1])/r):t.get([1])/r,g=l?new l(t.get([2])/r):t.get([2])/r,b=p(e),v=a(u,i(b)),N=d(e);return y([[a(b,f([m,m,v])),a(f([m,h,v]),f([c,g,N])),a(f([m,g,v]),f([h,N]))],[a(f([m,h,v]),f([g,N])),a(b,f([h,h,v])),a(f([h,g,v]),f([c,m,N]))],[a(f([m,g,v]),f([c,h,N])),a(f([h,g,v]),f([m,N])),a(b,f([g,g,v]))]],n)}})),name$33="row",dependencies$33=["typed","Index","matrix","range"],createRow=factory(name$33,dependencies$33,(e=>{var{typed:t,Index:n,matrix:r,range:a}=e;return t(name$33,{"Matrix, number":i,"Array, number":function(e,t){return i(r(clone$3(e)),t).valueOf()}});function i(e,t){if(2!==e.size().length)throw new Error("Only two dimensional matrix is supported");validateIndex(t,e.size()[0]);var r=a(0,e.size()[1]),i=new n(t,r);return e.subset(i)}})),name$32="size",dependencies$32=["typed","config","?matrix"],createSize=factory(name$32,dependencies$32,(e=>{var{typed:t,config:n,matrix:r}=e;return t(name$32,{Matrix:function(e){return e.create(e.size())},Array:arraySize,string:function(e){return"Array"===n.matrix?[e.length]:r([e.length])},"number | Complex | BigNumber | Unit | boolean | null":function(e){return"Array"===n.matrix?[]:r?r([]):noMatrix()}})})),name$31="squeeze",dependencies$31=["typed","matrix"],createSqueeze=factory(name$31,dependencies$31,(e=>{var{typed:t,matrix:n}=e;return t(name$31,{Array:function(e){return squeeze$1(clone$3(e))},Matrix:function(e){var t=squeeze$1(e.toArray());return Array.isArray(t)?n(t):t},any:function(e){return clone$3(e)}})})),name$30="subset",dependencies$30=["typed","matrix"],createSubset=factory(name$30,dependencies$30,(e=>{var{typed:t,matrix:n}=e;return t(name$30,{"Array, Index":function(e,t){var r=n(e).subset(t);return t.isScalar()?r:r.valueOf()},"Matrix, Index":function(e,t){return e.subset(t)},"Object, Index":_getObjectProperty,"string, Index":_getSubstring,"Array, Index, any":function(e,t,r){return n(clone$3(e)).subset(t,r,void 0).valueOf()},"Array, Index, any, any":function(e,t,r,a){return n(clone$3(e)).subset(t,r,a).valueOf()},"Matrix, Index, any":function(e,t,n){return e.clone().subset(t,n)},"Matrix, Index, any, any":function(e,t,n,r){return e.clone().subset(t,n,r)},"string, Index, string":_setSubstring,"string, Index, string, string":_setSubstring,"Object, Index, any":_setObjectProperty})}));function _getSubstring(e,t){if(!isIndex(t))throw new TypeError("Index expected");if(1!==t.size().length)throw new DimensionError(t.size().length,1);var n=e.length;validateIndex(t.min()[0],n),validateIndex(t.max()[0],n);var r=t.dimension(0),a="";return r.forEach((function(t){a+=e.charAt(t)})),a}function _setSubstring(e,t,n,r){if(!t||!0!==t.isIndex)throw new TypeError("Index expected");if(1!==t.size().length)throw new DimensionError(t.size().length,1);if(void 0!==r){if("string"!=typeof r||1!==r.length)throw new TypeError("Single character expected as defaultValue")}else r=" ";var a=t.dimension(0);if(a.size()[0]!==n.length)throw new DimensionError(a.size()[0],n.length);var i=e.length;validateIndex(t.min()[0]),validateIndex(t.max()[0]);for(var s=[],o=0;oi)for(var l=i-1,u=s.length;l{var{typed:t,matrix:n}=e;return t("transpose",{Array:function(e){return this(n(e)).valueOf()},Matrix:function(e){var t,n=e.size();switch(n.length){case 1:t=e.clone();break;case 2:var r=n[0],a=n[1];if(0===a)throw new RangeError("Cannot transpose a 2D matrix with no columns (size: "+format$1(n)+")");switch(e.storage()){case"dense":t=function(e,t,n){for(var r,a=e._data,i=[],s=0;s{var{typed:t,transpose:n,conj:r}=e;return t(name$2_,{any:function(e){return r(n(e))}})})),name$2Z="zeros",dependencies$2Z=["typed","config","matrix","BigNumber"],createZeros=factory(name$2Z,dependencies$2Z,(e=>{var{typed:t,config:n,matrix:r,BigNumber:a}=e;return t(name$2Z,{"":function(){return"Array"===n.matrix?i([]):i([],"default")},"...number | BigNumber | string":function(e){if("string"==typeof e[e.length-1]){var t=e.pop();return i(e,t)}return"Array"===n.matrix?i(e):i(e,"default")},Array:i,Matrix:function(e){var t=e.storage();return i(e.valueOf(),t)},"Array | Matrix, string":function(e,t){return i(e.valueOf(),t)}});function i(e,t){var n=function(e){var t=!1;return e.forEach((function(e,n,r){isBigNumber(e)&&(t=!0,r[n]=e.toNumber())})),t}(e),i=n?new a(0):0;if(function(e){e.forEach((function(e){if("number"!=typeof e||!isInteger$1(e)||e<0)throw new Error("Parameters in function zeros must be positive integers")}))}(e),t){var s=r(t);return e.length>0?s.resize(e,i):s}var o=[];return e.length>0?resize$1(o,e,i):o}})),name$2Y="fft",dependencies$2Y=["typed","matrix","addScalar","multiplyScalar","divideScalar","exp","tau","i"],createFft=factory(name$2Y,dependencies$2Y,(e=>{var{typed:t,matrix:n,addScalar:r,multiplyScalar:a,divideScalar:i,exp:s,tau:o,i:l}=e;return t(name$2Y,{Array:u,Matrix:function(e){return e.create(u(e.toArray()))}});function u(e){var t=arraySize(e);return 1===t.length?p(e,t[0]):c(e.map((e=>u(e,t.slice(1)))),0)}function c(e,t){var n=arraySize(e);if(0!==t)return new Array(n[0]).fill(0).map(((n,r)=>c(e[r],t-1)));if(1===n.length)return p(e);function r(e){var t=arraySize(e);return new Array(t[1]).fill(0).map(((n,r)=>new Array(t[0]).fill(0).map(((t,n)=>e[n][r]))))}return r(c(r(e),1))}function p(e){var t=e.length;if(1===t)return[e[0]];if(t%2==0){for(var n=[...p(e.filter(((e,t)=>t%2==0))),...p(e.filter(((e,t)=>t%2==1)))],u=0;u{var{typed:t,fft:n,dotDivide:r,conj:a}=e;return t(name$2X,{"Array | Matrix":function(e){var t=isMatrix(e)?e.size():arraySize(e);return r(a(n(a(e))),t.reduce(((e,t)=>e*t),1))}})})),name$2W="erf",dependencies$2W=["typed"],createErf=factory(name$2W,dependencies$2W,(e=>{var{typed:t}=e;return t("name",{number:function(e){var t=Math.abs(e);return t>=MAX_NUM?sign$3(e):t<=THRESH?sign$3(e)*function(e){var t,n=e*e,r=P[0][4]*n,a=n;for(t=0;t<3;t+=1)r=(r+P[0][t])*n,a=(a+Q[0][t])*n;return e*(r+P[0][3])/(a+Q[0][3])}(t):t<=4?sign$3(e)*(1-function(e){var t,n=P[1][8]*e,r=e;for(t=0;t<7;t+=1)n=(n+P[1][t])*e,r=(r+Q[1][t])*e;var a=(n+P[1][7])/(r+Q[1][7]),i=parseInt(16*e)/16,s=(e-i)*(e+i);return Math.exp(-i*i)*Math.exp(-s)*a}(t)):sign$3(e)*(1-function(e){var t,n=1/(e*e),r=P[2][5]*n,a=n;for(t=0;t<4;t+=1)r=(r+P[2][t])*n,a=(a+Q[2][t])*n;var i=n*(r+P[2][4])/(a+Q[2][4]);i=(SQRPI-i)/e;var s=(e-(n=parseInt(16*e)/16))*(e+n);return Math.exp(-n*n)*Math.exp(-s)*i}(t))},"Array | Matrix":function(e){return deepMap(e,this)}})})),THRESH=.46875,SQRPI=.5641895835477563,P=[[3.1611237438705655,113.86415415105016,377.485237685302,3209.3775891384694,.18577770618460315],[.5641884969886701,8.883149794388377,66.11919063714163,298.6351381974001,881.952221241769,1712.0476126340707,2051.0783778260716,1230.3393547979972,2.1531153547440383e-8],[.30532663496123236,.36034489994980445,.12578172611122926,.016083785148742275,.0006587491615298378,.016315387137302097]],Q=[[23.601290952344122,244.02463793444417,1282.6165260773723,2844.236833439171],[15.744926110709835,117.6939508913125,537.1811018620099,1621.3895745666903,3290.7992357334597,4362.619090143247,3439.3676741437216,1230.3393548037495],[2.568520192289822,1.8729528499234604,.5279051029514285,.06051834131244132,.0023352049762686918]],MAX_NUM=Math.pow(2,53),name$2V="mode",dependencies$2V=["typed","isNaN","isNumeric"],createMode=factory(name$2V,dependencies$2V,(e=>{var{typed:t,isNaN:n,isNumeric:r}=e;return t(name$2V,{"Array | Matrix":a,"...":function(e){return a(e)}});function a(e){if(0===(e=flatten$4(e.valueOf())).length)throw new Error("Cannot calculate mode of an empty array");for(var t={},a=[],i=0,s=0;si&&(i=t[o],a=[o])}return a}}));function improveErrorMessage(e,t,n){var r;return-1!==String(e).indexOf("Unexpected type")?(r=arguments.length>2?" (type: "+typeOf$1(n)+", value: "+JSON.stringify(n)+")":" (type: "+e.data.actual+")",new TypeError("Cannot calculate "+t+", unexpected type of argument"+r)):-1!==String(e).indexOf("complex numbers")?(r=arguments.length>2?" (type: "+typeOf$1(n)+", value: "+JSON.stringify(n)+")":"",new TypeError("Cannot calculate "+t+", no ordering relation is defined for complex numbers"+r)):e}var name$2U="prod",dependencies$2U=["typed","config","multiplyScalar","numeric"],createProd=factory(name$2U,dependencies$2U,(e=>{var{typed:t,config:n,multiplyScalar:r,numeric:a}=e;return t(name$2U,{"Array | Matrix":i,"Array | Matrix, number | BigNumber":function(e,t){throw new Error("prod(A, dim) is not yet supported")},"...":function(e){return i(e)}});function i(e){var t;if(deepForEach(e,(function(e){try{t=void 0===t?e:r(t,e)}catch(t){throw improveErrorMessage(t,"prod",e)}})),"string"==typeof t&&(t=a(t,n.number)),void 0===t)throw new Error("Cannot calculate prod of an empty array");return t}})),name$2T="format",dependencies$2T=["typed"],createFormat=factory(name$2T,dependencies$2T,(e=>{var{typed:t}=e;return t(name$2T,{any:format$1,"any, Object | function | number":format$1})})),name$2S="bin",dependencies$2S=["typed","format"],createBin=factory(name$2S,dependencies$2S,(e=>{var{typed:t,format:n}=e;return t(name$2S,{"number | BigNumber":function(e){return n(e,{notation:"bin"})},"number | BigNumber, number":function(e,t){return n(e,{notation:"bin",wordSize:t})}})})),name$2R="oct",dependencies$2R=["typed","format"],createOct=factory(name$2R,dependencies$2R,(e=>{var{typed:t,format:n}=e;return t(name$2R,{"number | BigNumber":function(e){return n(e,{notation:"oct"})},"number | BigNumber, number":function(e,t){return n(e,{notation:"oct",wordSize:t})}})})),name$2Q="hex",dependencies$2Q=["typed","format"],createHex=factory(name$2Q,dependencies$2Q,(e=>{var{typed:t,format:n}=e;return t(name$2Q,{"number | BigNumber":function(e){return n(e,{notation:"hex"})},"number | BigNumber, number":function(e,t){return n(e,{notation:"hex",wordSize:t})}})})),name$2P="print",dependencies$2P=["typed"],createPrint=factory(name$2P,dependencies$2P,(e=>{var{typed:t}=e;return t(name$2P,{"string, Object | Array":_print,"string, Object | Array, number | Object":_print})}));function _print(e,t,n){return e.replace(/\$([\w.]+)/g,(function(e,r){for(var a=r.split("."),i=t[a.shift()];a.length&&void 0!==i;){var s=a.shift();i=s?i[s]:i+"."}return void 0!==i?isString$1(i)?i:format$1(i,n):e}))}var name$2O="to",dependencies$2O=["typed","matrix"],createTo=factory(name$2O,dependencies$2O,(e=>{var{typed:t,matrix:n}=e,r=createAlgorithm13({typed:t}),a=createAlgorithm14({typed:t});return t(name$2O,{"Unit, Unit | string":function(e,t){return e.to(t)},"Matrix, Matrix":function(e,t){return r(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"Matrix, any":function(e,t){return a(e,t,this,!1)},"any, Matrix":function(e,t){return a(t,e,this,!0)},"Array, any":function(e,t){return a(n(e),t,this,!1).valueOf()},"any, Array":function(e,t){return a(n(t),e,this,!0).valueOf()}})})),name$2N="isPrime",dependencies$2N=["typed"],createIsPrime=factory(name$2N,dependencies$2N,(e=>{var{typed:t}=e;return t(name$2N,{number:function(e){if(0*e!=0)return!1;if(e<=3)return e>1;if(e%2==0||e%3==0)return!1;for(var t=5;t*t<=e;t+=6)if(e%t==0||e%(t+2)==0)return!1;return!0},BigNumber:function(e){if(0*e.toNumber()!=0)return!1;if(e.lte(3))return e.gt(1);if(e.mod(2).eq(0)||e.mod(3).eq(0))return!1;if(e.lt(Math.pow(2,32))){for(var t=e.toNumber(),n=5;n*n<=t;n+=6)if(t%n==0||t%(n+2)==0)return!1;return!0}function r(e,t,n){for(var r=1;!t.eq(0);)t.mod(2).eq(0)?(t=t.div(2),e=e.mul(e).mod(n)):(t=t.sub(1),r=e.mul(r).mod(n));return r}for(var a=e.constructor.clone({precision:2*e.toFixed(0).length}),i=0,s=(e=new a(e)).sub(1);s.mod(2).eq(0);)s=s.div(2),i+=1;var o=null;if(e.lt("3317044064679887385961981"))o=[2,3,5,7,11,13,17,19,23,29,31,37,41].filter((t=>t{var{number:t,bignumber:n,fraction:r}=e,a={string:!0,number:!0,BigNumber:!0,Fraction:!0},i={number:e=>t(e),BigNumber:n?e=>n(e):noBignumber,Fraction:r?e=>r(e):noFraction};return function(e,t){var n=typeOf$1(e);if(!(n in a))throw new TypeError("Cannot convert "+e+' of type "'+n+'"; valid input types are '+Object.keys(a).join(", "));if(!(t in i))throw new TypeError("Cannot convert "+e+' to type "'+t+'"; valid output types are '+Object.keys(i).join(", "));return t===n?e:i[t](e)}})),name$2L="divideScalar",dependencies$2L=["typed","numeric"],createDivideScalar=factory(name$2L,dependencies$2L,(e=>{var{typed:t,numeric:n}=e;return t(name$2L,{"number, number":function(e,t){return e/t},"Complex, Complex":function(e,t){return e.div(t)},"BigNumber, BigNumber":function(e,t){return e.div(t)},"Fraction, Fraction":function(e,t){return e.div(t)},"Unit, number | Fraction | BigNumber":function(e,t){var r=e.clone(),a=n(1,typeOf$1(t));return r.value=this(null===r.value?r._normalize(a):r.value,t),r},"number | Fraction | BigNumber, Unit":function(e,t){var r=t.clone();r=r.pow(-1);var a=n(1,typeOf$1(e));return r.value=this(e,null===t.value?t._normalize(a):t.value),r},"Unit, Unit":function(e,t){return e.divide(t)}})})),name$2K="pow",dependencies$2K=["typed","config","identity","multiply","matrix","inv","fraction","number","Complex"],createPow=factory(name$2K,dependencies$2K,(e=>{var{typed:t,config:n,identity:r,multiply:a,matrix:i,inv:s,number:o,fraction:l,Complex:u}=e;return t(name$2K,{"number, number":c,"Complex, Complex":function(e,t){return e.pow(t)},"BigNumber, BigNumber":function(e,t){return t.isInteger()||e>=0||n.predictable?e.pow(t):new u(e.toNumber(),0).pow(t.toNumber(),0)},"Fraction, Fraction":function(e,t){var r=e.pow(t);if(null!=r)return r;if(n.predictable)throw new Error("Result of pow is non-rational and cannot be expressed as a fraction");return c(e.valueOf(),t.valueOf())},"Array, number":p,"Array, BigNumber":function(e,t){return p(e,t.toNumber())},"Matrix, number":d,"Matrix, BigNumber":function(e,t){return d(e,t.toNumber())},"Unit, number | BigNumber":function(e,t){return e.pow(t)}});function c(e,t){if(n.predictable&&!isInteger$1(t)&&e<0)try{var r=l(t),a=o(r);if((t===a||Math.abs((t-a)/t)<1e-14)&&r.d%2==1)return(r.n%2==0?1:-1)*Math.pow(-e,t)}catch(e){}return n.predictable&&(e<-1&&t===1/0||e>-1&&e<0&&t===-1/0)?NaN:isInteger$1(t)||e>=0||n.predictable?powNumber(e,t):e*e<1&&t===1/0||e*e>1&&t===-1/0?0:new u(e,0).pow(t,0)}function p(e,t){if(!isInteger$1(t))throw new TypeError("For A^b, b must be an integer (value is "+t+")");var n=arraySize(e);if(2!==n.length)throw new Error("For A^b, A must be 2 dimensional (A has "+n.length+" dimensions)");if(n[0]!==n[1])throw new Error("For A^b, A must be square (size is "+n[0]+"x"+n[1]+")");if(t<0)try{return p(s(e),-t)}catch(e){if("Cannot calculate inverse, determinant is zero"===e.message)throw new TypeError("For A^b, when A is not invertible, b must be a positive integer (value is "+t+")");throw e}for(var i=r(n[0]).valueOf(),o=e;t>=1;)1==(1&t)&&(i=a(o,i)),t>>=1,o=a(o,o);return i}function d(e,t){return i(p(e.valueOf(),t))}})),NO_INT="Number of decimals in function round must be an integer",name$2J="round",dependencies$2J=["typed","matrix","equalScalar","zeros","BigNumber","DenseMatrix"],createRound=factory(name$2J,dependencies$2J,(e=>{var{typed:t,matrix:n,equalScalar:r,zeros:a,BigNumber:i,DenseMatrix:s}=e,o=createAlgorithm11({typed:t,equalScalar:r}),l=createAlgorithm12({typed:t,DenseMatrix:s}),u=createAlgorithm14({typed:t});return t(name$2J,{number:roundNumber,"number, number":roundNumber,"number, BigNumber":function(e,t){if(!t.isInteger())throw new TypeError(NO_INT);return new i(e).toDecimalPlaces(t.toNumber())},Complex:function(e){return e.round()},"Complex, number":function(e,t){if(t%1)throw new TypeError(NO_INT);return e.round(t)},"Complex, BigNumber":function(e,t){if(!t.isInteger())throw new TypeError(NO_INT);var n=t.toNumber();return e.round(n)},BigNumber:function(e){return e.toDecimalPlaces(0)},"BigNumber, BigNumber":function(e,t){if(!t.isInteger())throw new TypeError(NO_INT);return e.toDecimalPlaces(t.toNumber())},Fraction:function(e){return e.round()},"Fraction, number":function(e,t){if(t%1)throw new TypeError(NO_INT);return e.round(t)},"Fraction, BigNumber":function(e,t){if(!t.isInteger())throw new TypeError(NO_INT);return e.round(t.toNumber())},"Array | Matrix":function(e){return deepMap(e,this)},"SparseMatrix, number | BigNumber":function(e,t){return o(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return u(e,t,this,!1)},"Array, number | BigNumber":function(e,t){return u(n(e),t,this,!1).valueOf()},"number | Complex | BigNumber | Fraction, SparseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):l(t,e,this,!0)},"number | Complex | BigNumber | Fraction, DenseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):u(t,e,this,!0)},"number | Complex | BigNumber | Fraction, Array":function(e,t){return u(n(t),e,this,!0).valueOf()}})})),name$2I="log",dependencies$2I=["config","typed","divideScalar","Complex"],createLog=factory(name$2I,dependencies$2I,(e=>{var{typed:t,config:n,divideScalar:r,Complex:a}=e;return t(name$2I,{number:function(e){return e>=0||n.predictable?logNumber(e):new a(e,0).log()},Complex:function(e){return e.log()},BigNumber:function(e){return!e.isNegative()||n.predictable?e.ln():new a(e.toNumber(),0).log()},"Array | Matrix":function(e){return deepMap(e,this)},"any, any":function(e,t){return r(this(e),this(t))}})})),name$2H="log1p",dependencies$2H=["typed","config","divideScalar","log","Complex"],createLog1p=factory(name$2H,dependencies$2H,(e=>{var{typed:t,config:n,divideScalar:r,log:a,Complex:i}=e;return t(name$2H,{number:function(e){return e>=-1||n.predictable?log1p$1(e):s(new i(e,0))},Complex:s,BigNumber:function(e){var t=e.plus(1);return!t.isNegative()||n.predictable?t.ln():s(new i(e.toNumber(),0))},"Array | Matrix":function(e){return deepMap(e,this)},"any, any":function(e,t){return r(this(e),a(t))}});function s(e){var t=e.re+1;return new i(Math.log(Math.sqrt(t*t+e.im*e.im)),Math.atan2(e.im,t))}})),name$2G="nthRoots",dependencies$2G=["config","typed","divideScalar","Complex"],createNthRoots=factory(name$2G,dependencies$2G,(e=>{var{typed:t,config:n,divideScalar:r,Complex:a}=e,i=[function(e){return new a(e,0)},function(e){return new a(0,e)},function(e){return new a(-e,0)},function(e){return new a(0,-e)}];function s(e,t){if(t<0)throw new Error("Root must be greater than zero");if(0===t)throw new Error("Root must be non-zero");if(t%1!=0)throw new Error("Root must be an integer");if(0===e||0===e.abs())return[new a(0,0)];var n,r="number"==typeof e;(r||0===e.re||0===e.im)&&(n=r?2*+(e<0):0===e.im?2*+(e.re<0):2*+(e.im<0)+1);for(var s=e.arg(),o=e.abs(),l=[],u=Math.pow(o,1/t),c=0;c{var{typed:t,equalScalar:n,matrix:r,pow:a,DenseMatrix:i}=e,s=createAlgorithm03({typed:t}),o=createAlgorithm07({typed:t,DenseMatrix:i}),l=createAlgorithm11({typed:t,equalScalar:n}),u=createAlgorithm12({typed:t,DenseMatrix:i}),c=createAlgorithm13({typed:t}),p=createAlgorithm14({typed:t});return t(name$2F,{"any, any":a,"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,a,!1)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,a,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,a,!1)},"DenseMatrix, DenseMatrix":function(e,t){return c(e,t,a)},"Array, Array":function(e,t){return this(r(e),r(t)).valueOf()},"Array, Matrix":function(e,t){return this(r(e),t)},"Matrix, Array":function(e,t){return this(e,r(t))},"SparseMatrix, any":function(e,t){return l(e,t,this,!1)},"DenseMatrix, any":function(e,t){return p(e,t,this,!1)},"any, SparseMatrix":function(e,t){return u(t,e,this,!0)},"any, DenseMatrix":function(e,t){return p(t,e,this,!0)},"Array, any":function(e,t){return p(r(e),t,this,!1).valueOf()},"any, Array":function(e,t){return p(r(t),e,this,!0).valueOf()}})})),name$2E="dotDivide",dependencies$2E=["typed","matrix","equalScalar","divideScalar","DenseMatrix"],createDotDivide=factory(name$2E,dependencies$2E,(e=>{var{typed:t,matrix:n,equalScalar:r,divideScalar:a,DenseMatrix:i}=e,s=createAlgorithm02({typed:t,equalScalar:r}),o=createAlgorithm03({typed:t}),l=createAlgorithm07({typed:t,DenseMatrix:i}),u=createAlgorithm11({typed:t,equalScalar:r}),c=createAlgorithm12({typed:t,DenseMatrix:i}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2E,{"any, any":a,"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,a,!1)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,a,!0)},"DenseMatrix, SparseMatrix":function(e,t){return o(e,t,a,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,a)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return u(e,t,a,!1)},"DenseMatrix, any":function(e,t){return d(e,t,a,!1)},"any, SparseMatrix":function(e,t){return c(t,e,a,!0)},"any, DenseMatrix":function(e,t){return d(t,e,a,!0)},"Array, any":function(e,t){return d(n(e),t,a,!1).valueOf()},"any, Array":function(e,t){return d(n(t),e,a,!0).valueOf()}})}));function createSolveValidation(e){var{DenseMatrix:t}=e;return function(e,n,r){var a=e.size();if(2!==a.length)throw new RangeError("Matrix must be two dimensional (size: "+format$1(a)+")");var i=a[0];if(i!==a[1])throw new RangeError("Matrix must be square (size: "+format$1(a)+")");var s=[];if(isMatrix(n)){var o=n.size(),l=n._data;if(1===o.length){if(o[0]!==i)throw new RangeError("Dimension mismatch. Matrix columns must match vector length.");for(var u=0;u{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:a,subtract:i,equalScalar:s,DenseMatrix:o}=e,l=createSolveValidation({DenseMatrix:o});return t(name$2D,{"SparseMatrix, Array | Matrix":function(e,t){return function(e,t){for(var n=(t=l(e,t,!0))._data,u=e._size[0],c=e._size[1],p=e._values,d=e._index,m=e._ptr,h=[],f=0;ff&&(b.push(p[C]),v.push(A))}if(s(g,0))throw new Error("Linear system cannot be solved since matrix is singular");for(var V=r(y,g),x=0,S=v.length;x{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:a,subtract:i,equalScalar:s,DenseMatrix:o}=e,l=createSolveValidation({DenseMatrix:o});return t(name$2C,{"SparseMatrix, Array | Matrix":function(e,t){return function(e,t){for(var n=(t=l(e,t,!0))._data,u=e._size[0],c=e._size[1],p=e._values,d=e._index,m=e._ptr,h=[],f=c-1;f>=0;f--){var y=n[f][0]||0;if(s(y,0))h[f]=[0];else{for(var g=0,b=[],v=[],N=m[f],T=m[f+1]-1;T>=N;T--){var C=d[T];C===f?g=p[T]:C=0;m--){var h=n[m][0]||0,f=void 0;if(s(h,0))f=0;else{var y=d[m][m];if(s(y,0))throw new Error("Linear system cannot be solved since matrix is singular");f=r(h,y);for(var g=m-1;g>=0;g--)n[g]=[i(n[g][0]||0,a(f,d[g][m]))]}p[m]=[f]}return new o({data:p,size:[u,1]})}})),name$2B="lsolveAll",dependencies$2B=["typed","matrix","divideScalar","multiplyScalar","subtract","equalScalar","DenseMatrix"],createLsolveAll=factory(name$2B,dependencies$2B,(e=>{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:a,subtract:i,equalScalar:s,DenseMatrix:o}=e,l=createSolveValidation({DenseMatrix:o});return t(name$2B,{"SparseMatrix, Array | Matrix":function(e,t){return function(e,t){for(var n=[l(e,t,!0)._data.map((e=>e[0]))],u=e._size[0],c=e._size[1],p=e._values,d=e._index,m=e._ptr,h=0;hh&&(b.push(p[A]),v.push(V))}if(s(C,0))if(s(g[h],0)){if(0===y){var x=[...g];x[h]=1;for(var S=0,w=v.length;Snew o({data:e.map((e=>[e])),size:[u,1]})))}(e,t)},"DenseMatrix, Array | Matrix":function(e,t){return u(e,t)},"Array, Array | Matrix":function(e,t){return u(n(e),t).map((e=>e.valueOf()))}});function u(e,t){for(var n=[l(e,t,!0)._data.map((e=>e[0]))],u=e._data,c=e._size[0],p=e._size[1],d=0;dnew o({data:e.map((e=>[e])),size:[c,1]})))}})),name$2A="usolveAll",dependencies$2A=["typed","matrix","divideScalar","multiplyScalar","subtract","equalScalar","DenseMatrix"],createUsolveAll=factory(name$2A,dependencies$2A,(e=>{var{typed:t,matrix:n,divideScalar:r,multiplyScalar:a,subtract:i,equalScalar:s,DenseMatrix:o}=e,l=createSolveValidation({DenseMatrix:o});return t(name$2A,{"SparseMatrix, Array | Matrix":function(e,t){return function(e,t){for(var n=[l(e,t,!0)._data.map((e=>e[0]))],u=e._size[0],c=e._size[1],p=e._values,d=e._index,m=e._ptr,h=c-1;h>=0;h--)for(var f=n.length,y=0;y=N;C--){var A=d[C];A===h?T=p[C]:Anew o({data:e.map((e=>[e])),size:[u,1]})))}(e,t)},"DenseMatrix, Array | Matrix":function(e,t){return u(e,t)},"Array, Array | Matrix":function(e,t){return u(n(e),t).map((e=>e.valueOf()))}});function u(e,t){for(var n=[l(e,t,!0)._data.map((e=>e[0]))],u=e._data,c=e._size[0],p=e._size[1]-1;p>=0;p--)for(var d=n.length,m=0;m=0;y--)f[y]=i(f[y],u[y][p]);n.push(f)}}else{if(0===m)return[];n.splice(m,1),m-=1,d-=1}else{h[p]=r(h[p],u[p][p]);for(var g=p-1;g>=0;g--)h[g]=i(h[g],a(h[p],u[g][p]))}}return n.map((e=>new o({data:e.map((e=>[e])),size:[c,1]})))}})),name$2z="algorithm08",dependencies$2z=["typed","equalScalar"],createAlgorithm08=factory(name$2z,dependencies$2z,(e=>{var{typed:t,equalScalar:n}=e;return function(e,r,a){var i=e._values,s=e._index,o=e._ptr,l=e._size,u=e._datatype,c=r._values,p=r._index,d=r._ptr,m=r._size,h=r._datatype;if(l.length!==m.length)throw new DimensionError(l.length,m.length);if(l[0]!==m[0]||l[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+l+") must match Matrix B ("+m+")");if(!i||!c)throw new Error("Cannot perform operation on Pattern Sparse Matrices");var f,y=l[0],g=l[1],b=n,v=0,N=a;"string"==typeof u&&u===h&&(f=u,b=t.find(n,[f,f]),v=t.convert(0,f),N=t.find(a,[f,f]));for(var T,C,A,V,x=[],S=[],w=[],E=[],D=[],O=0;O{var{typed:t,matrix:n,equalScalar:r,zeros:a,DenseMatrix:i}=e,s=createAlgorithm01({typed:t}),o=createAlgorithm02({typed:t,equalScalar:r}),l=createAlgorithm08({typed:t,equalScalar:r}),u=createAlgorithm10({typed:t,DenseMatrix:i}),c=createAlgorithm11({typed:t,equalScalar:r}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2y,{"number, number":leftShiftNumber,"BigNumber, BigNumber":leftShiftBigNumber,"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():c(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():d(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):u(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):d(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return this(n(e),t).valueOf()},"number | BigNumber, Array":function(e,t){return this(e,n(t)).valueOf()}})})),name$2x="rightArithShift",dependencies$2x=["typed","matrix","equalScalar","zeros","DenseMatrix"],createRightArithShift=factory(name$2x,dependencies$2x,(e=>{var{typed:t,matrix:n,equalScalar:r,zeros:a,DenseMatrix:i}=e,s=createAlgorithm01({typed:t}),o=createAlgorithm02({typed:t,equalScalar:r}),l=createAlgorithm08({typed:t,equalScalar:r}),u=createAlgorithm10({typed:t,DenseMatrix:i}),c=createAlgorithm11({typed:t,equalScalar:r}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2x,{"number, number":rightArithShiftNumber,"BigNumber, BigNumber":rightArithShiftBigNumber,"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():c(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():d(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):u(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):d(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return this(n(e),t).valueOf()},"number | BigNumber, Array":function(e,t){return this(e,n(t)).valueOf()}})})),name$2w="rightLogShift",dependencies$2w=["typed","matrix","equalScalar","zeros","DenseMatrix"],createRightLogShift=factory(name$2w,dependencies$2w,(e=>{var{typed:t,matrix:n,equalScalar:r,zeros:a,DenseMatrix:i}=e,s=createAlgorithm01({typed:t}),o=createAlgorithm02({typed:t,equalScalar:r}),l=createAlgorithm08({typed:t,equalScalar:r}),u=createAlgorithm10({typed:t,DenseMatrix:i}),c=createAlgorithm11({typed:t,equalScalar:r}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2w,{"number, number":rightLogShiftNumber,"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():c(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return r(t,0)?e.clone():d(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):u(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return r(e,0)?a(t.size(),t.storage()):d(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return this(n(e),t).valueOf()},"number | BigNumber, Array":function(e,t){return this(e,n(t)).valueOf()}})})),name$2v="and",dependencies$2v=["typed","matrix","equalScalar","zeros","not"],createAnd=factory(name$2v,dependencies$2v,(e=>{var{typed:t,matrix:n,equalScalar:r,zeros:a,not:i}=e,s=createAlgorithm02({typed:t,equalScalar:r}),o=createAlgorithm06({typed:t,equalScalar:r}),l=createAlgorithm11({typed:t,equalScalar:r}),u=createAlgorithm13({typed:t}),c=createAlgorithm14({typed:t});return t(name$2v,{"number, number":andNumber,"Complex, Complex":function(e,t){return!(0===e.re&&0===e.im||0===t.re&&0===t.im)},"BigNumber, BigNumber":function(e,t){return!(e.isZero()||t.isZero()||e.isNaN()||t.isNaN())},"Unit, Unit":function(e,t){return this(e.value||0,t.value||0)},"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return u(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return i(t)?a(e.size(),e.storage()):l(e,t,this,!1)},"DenseMatrix, any":function(e,t){return i(t)?a(e.size(),e.storage()):c(e,t,this,!1)},"any, SparseMatrix":function(e,t){return i(e)?a(e.size(),e.storage()):l(t,e,this,!0)},"any, DenseMatrix":function(e,t){return i(e)?a(e.size(),e.storage()):c(t,e,this,!0)},"Array, any":function(e,t){return this(n(e),t).valueOf()},"any, Array":function(e,t){return this(e,n(t)).valueOf()}})})),name$2u="compare",dependencies$2u=["typed","config","matrix","equalScalar","BigNumber","Fraction","DenseMatrix"],createCompare=factory(name$2u,dependencies$2u,(e=>{var{typed:t,config:n,equalScalar:r,matrix:a,BigNumber:i,Fraction:s,DenseMatrix:o}=e,l=createAlgorithm03({typed:t}),u=createAlgorithm05({typed:t,equalScalar:r}),c=createAlgorithm12({typed:t,DenseMatrix:o}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$2u,{"boolean, boolean":function(e,t){return e===t?0:e>t?1:-1},"number, number":function(e,t){return nearlyEqual$1(e,t,n.epsilon)?0:e>t?1:-1},"BigNumber, BigNumber":function(e,t){return nearlyEqual(e,t,n.epsilon)?new i(0):new i(e.cmp(t))},"Fraction, Fraction":function(e,t){return new s(e.compare(t))},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)},"SparseMatrix, SparseMatrix":function(e,t){return u(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return l(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(a(e),a(t)).valueOf()},"Array, Matrix":function(e,t){return this(a(e),t)},"Matrix, Array":function(e,t){return this(e,a(t))},"SparseMatrix, any":function(e,t){return c(e,t,this,!1)},"DenseMatrix, any":function(e,t){return d(e,t,this,!1)},"any, SparseMatrix":function(e,t){return c(t,e,this,!0)},"any, DenseMatrix":function(e,t){return d(t,e,this,!0)},"Array, any":function(e,t){return d(a(e),t,this,!1).valueOf()},"any, Array":function(e,t){return d(a(t),e,this,!0).valueOf()}})})),naturalSort=function e(t,n){var r,a,i=/(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi,s=/(^[ ]*|[ ]*$)/g,o=/(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,l=/^0x[0-9a-f]+$/i,u=/^0/,c=function(t){return e.insensitive&&(""+t).toLowerCase()||""+t},p=c(t).replace(s,"")||"",d=c(n).replace(s,"")||"",m=p.replace(i,"\0$1\0").replace(/\0$/,"").replace(/^\0/,"").split("\0"),h=d.replace(i,"\0$1\0").replace(/\0$/,"").replace(/^\0/,"").split("\0"),f=parseInt(p.match(l),16)||1!==m.length&&p.match(o)&&Date.parse(p),y=parseInt(d.match(l),16)||f&&d.match(o)&&Date.parse(d)||null;if(y){if(fy)return 1}for(var g=0,b=Math.max(m.length,h.length);ga)return 1}return 0},name$2t="compareNatural",dependencies$2t=["typed","compare"],createCompareNatural=factory(name$2t,dependencies$2t,(e=>{var{typed:t,compare:n}=e,r=n.signatures["boolean,boolean"];return t(name$2t,{"any, any":function(e,t){var s,o=typeOf$1(e),l=typeOf$1(t);if(!("number"!==o&&"BigNumber"!==o&&"Fraction"!==o||"number"!==l&&"BigNumber"!==l&&"Fraction"!==l))return"0"!==(s=n(e,t)).toString()?s>0?1:-1:naturalSort(o,l);if("Array"===o||"Matrix"===o||"Array"===l||"Matrix"===l)return 0!==(s=a(this,e,t))?s:naturalSort(o,l);if(o!==l)return naturalSort(o,l);if("Complex"===o)return compareComplexNumbers(e,t);if("Unit"===o)return e.equalBase(t)?this(e.value,t.value):i(this,e.formatUnits(),t.formatUnits());if("boolean"===o)return r(e,t);if("string"===o)return naturalSort(e,t);if("Object"===o)return function(e,t,n){var r=Object.keys(t),a=Object.keys(n);r.sort(naturalSort),a.sort(naturalSort);var s=i(e,r,a);if(0!==s)return s;for(var o=0;on.length?1:t.lengtht.re?1:e.ret.im?1:e.im{var{typed:t,matrix:n}=e,r=createAlgorithm13({typed:t}),a=createAlgorithm14({typed:t});return t(name$2s,{"any, any":compareText$1,"DenseMatrix, DenseMatrix":function(e,t){return r(e,t,compareText$1)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"DenseMatrix, any":function(e,t){return a(e,t,compareText$1,!1)},"any, DenseMatrix":function(e,t){return a(t,e,compareText$1,!0)},"Array, any":function(e,t){return a(n(e),t,compareText$1,!1).valueOf()},"any, Array":function(e,t){return a(n(t),e,compareText$1,!0).valueOf()}})})),name$2r="equal",dependencies$2r=["typed","matrix","equalScalar","DenseMatrix"],createEqual=factory(name$2r,dependencies$2r,(e=>{var{typed:t,matrix:n,equalScalar:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm07({typed:t,DenseMatrix:a}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2r,{"any, any":function(e,t){return null===e?null===t:null===t?null===e:void 0===e?void 0===t:void 0===t?void 0===e:r(e,t)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,r)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,r,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,r,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,r)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, any":function(e,t){return o(e,t,r,!1)},"DenseMatrix, any":function(e,t){return u(e,t,r,!1)},"any, SparseMatrix":function(e,t){return o(t,e,r,!0)},"any, DenseMatrix":function(e,t){return u(t,e,r,!0)},"Array, any":function(e,t){return u(n(e),t,r,!1).valueOf()},"any, Array":function(e,t){return u(n(t),e,r,!0).valueOf()}})}));factory(name$2r,["typed","equalScalar"],(e=>{var{typed:t,equalScalar:n}=e;return t(name$2r,{"any, any":function(e,t){return null===e?null===t:null===t?null===e:void 0===e?void 0===t:void 0===t?void 0===e:n(e,t)}})}));var name$2q="equalText",dependencies$2q=["typed","compareText","isZero"],createEqualText=factory(name$2q,dependencies$2q,(e=>{var{typed:t,compareText:n,isZero:r}=e;return t(name$2q,{"any, any":function(e,t){return r(n(e,t))}})})),name$2p="smaller",dependencies$2p=["typed","config","matrix","DenseMatrix"],createSmaller=factory(name$2p,dependencies$2p,(e=>{var{typed:t,config:n,matrix:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm07({typed:t,DenseMatrix:a}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2p,{"boolean, boolean":function(e,t){return e{var{typed:t,config:n,matrix:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm07({typed:t,DenseMatrix:a}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2o,{"boolean, boolean":function(e,t){return e<=t},"number, number":function(e,t){return e<=t||nearlyEqual$1(e,t,n.epsilon)},"BigNumber, BigNumber":function(e,t){return e.lte(t)||nearlyEqual(e,t,n.epsilon)},"Fraction, Fraction":function(e,t){return 1!==e.compare(t)},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(r(e),r(t)).valueOf()},"Array, Matrix":function(e,t){return this(r(e),t)},"Matrix, Array":function(e,t){return this(e,r(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(r(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(r(t),e,this,!0).valueOf()}})})),name$2n="larger",dependencies$2n=["typed","config","matrix","DenseMatrix"],createLarger=factory(name$2n,dependencies$2n,(e=>{var{typed:t,config:n,matrix:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm07({typed:t,DenseMatrix:a}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2n,{"boolean, boolean":function(e,t){return e>t},"number, number":function(e,t){return e>t&&!nearlyEqual$1(e,t,n.epsilon)},"BigNumber, BigNumber":function(e,t){return e.gt(t)&&!nearlyEqual(e,t,n.epsilon)},"Fraction, Fraction":function(e,t){return 1===e.compare(t)},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(r(e),r(t)).valueOf()},"Array, Matrix":function(e,t){return this(r(e),t)},"Matrix, Array":function(e,t){return this(e,r(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(r(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(r(t),e,this,!0).valueOf()}})})),name$2m="largerEq",dependencies$2m=["typed","config","matrix","DenseMatrix"],createLargerEq=factory(name$2m,dependencies$2m,(e=>{var{typed:t,config:n,matrix:r,DenseMatrix:a}=e,i=createAlgorithm03({typed:t}),s=createAlgorithm07({typed:t,DenseMatrix:a}),o=createAlgorithm12({typed:t,DenseMatrix:a}),l=createAlgorithm13({typed:t}),u=createAlgorithm14({typed:t});return t(name$2m,{"boolean, boolean":function(e,t){return e>=t},"number, number":function(e,t){return e>=t||nearlyEqual$1(e,t,n.epsilon)},"BigNumber, BigNumber":function(e,t){return e.gte(t)||nearlyEqual(e,t,n.epsilon)},"Fraction, Fraction":function(e,t){return-1!==e.compare(t)},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")},"Unit, Unit":function(e,t){if(!e.equalBase(t))throw new Error("Cannot compare units with different base");return this(e.value,t.value)},"SparseMatrix, SparseMatrix":function(e,t){return s(e,t,this)},"SparseMatrix, DenseMatrix":function(e,t){return i(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return i(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return l(e,t,this)},"Array, Array":function(e,t){return this(r(e),r(t)).valueOf()},"Array, Matrix":function(e,t){return this(r(e),t)},"Matrix, Array":function(e,t){return this(e,r(t))},"SparseMatrix, any":function(e,t){return o(e,t,this,!1)},"DenseMatrix, any":function(e,t){return u(e,t,this,!1)},"any, SparseMatrix":function(e,t){return o(t,e,this,!0)},"any, DenseMatrix":function(e,t){return u(t,e,this,!0)},"Array, any":function(e,t){return u(r(e),t,this,!1).valueOf()},"any, Array":function(e,t){return u(r(t),e,this,!0).valueOf()}})})),name$2l="deepEqual",dependencies$2l=["typed","equal"],createDeepEqual=factory(name$2l,dependencies$2l,(e=>{var{typed:t,equal:n}=e;return t(name$2l,{"any, any":function(e,t){return r(e.valueOf(),t.valueOf())}});function r(e,t){if(Array.isArray(e)){if(Array.isArray(t)){var a=e.length;if(a!==t.length)return!1;for(var i=0;i{var{typed:t,config:n,equalScalar:r,matrix:a,DenseMatrix:i}=e,s=createAlgorithm03({typed:t}),o=createAlgorithm07({typed:t,DenseMatrix:i}),l=createAlgorithm12({typed:t,DenseMatrix:i}),u=createAlgorithm13({typed:t}),c=createAlgorithm14({typed:t});return t("unequal",{"any, any":function(e,t){return null===e?null!==t:null===t?null!==e:void 0===e?void 0!==t:void 0===t?void 0!==e:p(e,t)},"SparseMatrix, SparseMatrix":function(e,t){return o(e,t,p)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,p,!0)},"DenseMatrix, SparseMatrix":function(e,t){return s(e,t,p,!1)},"DenseMatrix, DenseMatrix":function(e,t){return u(e,t,p)},"Array, Array":function(e,t){return this(a(e),a(t)).valueOf()},"Array, Matrix":function(e,t){return this(a(e),t)},"Matrix, Array":function(e,t){return this(e,a(t))},"SparseMatrix, any":function(e,t){return l(e,t,p,!1)},"DenseMatrix, any":function(e,t){return c(e,t,p,!1)},"any, SparseMatrix":function(e,t){return l(t,e,p,!0)},"any, DenseMatrix":function(e,t){return c(t,e,p,!0)},"Array, any":function(e,t){return c(a(e),t,p,!1).valueOf()},"any, Array":function(e,t){return c(a(t),e,p,!0).valueOf()}});function p(e,t){return!r(e,t)}}));factory(name$2k,["typed","equalScalar"],(e=>{var{typed:t,equalScalar:n}=e;return t(name$2k,{"any, any":function(e,t){return null===e?null!==t:null===t?null!==e:void 0===e?void 0!==t:void 0===t?void 0!==e:!n(e,t)}})}));var name$2j="partitionSelect",dependencies$2j=["typed","isNumeric","isNaN","compare"],createPartitionSelect=factory(name$2j,dependencies$2j,(e=>{var{typed:t,isNumeric:n,isNaN:r,compare:a}=e,i=a,s=(e,t)=>-a(e,t);return t(name$2j,{"Array | Matrix, number":function(e,t){return o(e,t,i)},"Array | Matrix, number, string":function(e,t,n){if("asc"===n)return o(e,t,i);if("desc"===n)return o(e,t,s);throw new Error('Compare string must be "asc" or "desc"')},"Array | Matrix, number, function":o});function o(e,t,n){if(!isInteger$1(t)||t<0)throw new Error("k must be a non-negative integer");if(isMatrix(e)){if(e.size().length>1)throw new Error("Only one dimensional matrices supported");return l(e.valueOf(),t,n)}if(Array.isArray(e))return l(e,t,n)}function l(e,t,a){if(t>=e.length)throw new Error("k out of bounds");for(var i=0;i=0){var p=e[u];e[u]=e[l],e[l]=p,--u}else++l;a(e[l],c)>0&&--l,t<=l?o=l:s=l+1}return e[t]}})),name$2i="sort",dependencies$2i=["typed","matrix","compare","compareNatural"],createSort=factory(name$2i,dependencies$2i,(e=>{var{typed:t,matrix:n,compare:r,compareNatural:a}=e,i=r,s=(e,t)=>-r(e,t);return t(name$2i,{Array:function(e){return l(e),e.sort(i)},Matrix:function(e){return u(e),n(e.toArray().sort(i),e.storage())},"Array, function":function(e,t){return l(e),e.sort(t)},"Matrix, function":function(e,t){return u(e),n(e.toArray().sort(t),e.storage())},"Array, string":function(e,t){return l(e),e.sort(o(t))},"Matrix, string":function(e,t){return u(e),n(e.toArray().sort(o(t)),e.storage())}});function o(e){if("asc"===e)return i;if("desc"===e)return s;if("natural"===e)return a;throw new Error('String "asc", "desc", or "natural" expected')}function l(e){if(1!==arraySize(e).length)throw new Error("One dimensional array expected")}function u(e){if(1!==e.size().length)throw new Error("One dimensional matrix expected")}})),name$2h="max",dependencies$2h=["typed","config","numeric","larger"],createMax=factory(name$2h,dependencies$2h,(e=>{var{typed:t,config:n,numeric:r,larger:a}=e;return t(name$2h,{"Array | Matrix":s,"Array | Matrix, number | BigNumber":function(e,t){return reduce$2(e,t.valueOf(),i)},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function max");return s(e)}});function i(e,t){try{return a(e,t)?e:t}catch(e){throw improveErrorMessage(e,"max",t)}}function s(e){var t;if(deepForEach(e,(function(e){try{isNaN(e)&&"number"==typeof e?t=NaN:(void 0===t||a(e,t))&&(t=e)}catch(t){throw improveErrorMessage(t,"max",e)}})),void 0===t)throw new Error("Cannot calculate max of an empty array");return"string"==typeof t&&(t=r(t,n.number)),t}})),name$2g="min",dependencies$2g=["typed","config","numeric","smaller"],createMin=factory(name$2g,dependencies$2g,(e=>{var{typed:t,config:n,numeric:r,smaller:a}=e;return t(name$2g,{"Array | Matrix":s,"Array | Matrix, number | BigNumber":function(e,t){return reduce$2(e,t.valueOf(),i)},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function min");return s(e)}});function i(e,t){try{return a(e,t)?e:t}catch(e){throw improveErrorMessage(e,"min",t)}}function s(e){var t;if(deepForEach(e,(function(e){try{isNaN(e)&&"number"==typeof e?t=NaN:(void 0===t||a(e,t))&&(t=e)}catch(t){throw improveErrorMessage(t,"min",e)}})),void 0===t)throw new Error("Cannot calculate min of an empty array");return"string"==typeof t&&(t=r(t,n.number)),t}})),name$2f="ImmutableDenseMatrix",dependencies$2f=["smaller","DenseMatrix"],createImmutableDenseMatrixClass=factory(name$2f,dependencies$2f,(e=>{var{smaller:t,DenseMatrix:n}=e;function r(e,t){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");if(t&&!isString$1(t))throw new Error("Invalid datatype: "+t);if(isMatrix(e)||isArray$1(e)){var a=new n(e,t);this._data=a._data,this._size=a._size,this._datatype=a._datatype,this._min=null,this._max=null}else if(e&&isArray$1(e.data)&&isArray$1(e.size))this._data=e.data,this._size=e.size,this._datatype=e.datatype,this._min=void 0!==e.min?e.min:null,this._max=void 0!==e.max?e.max:null;else{if(e)throw new TypeError("Unsupported type of data ("+typeOf$1(e)+")");this._data=[],this._size=[0],this._datatype=t,this._min=null,this._max=null}}return r.prototype=new n,r.prototype.type="ImmutableDenseMatrix",r.prototype.isImmutableDenseMatrix=!0,r.prototype.subset=function(e){switch(arguments.length){case 1:var t=n.prototype.subset.call(this,e);return isMatrix(t)?new r({data:t._data,size:t._size,datatype:t._datatype}):t;case 2:case 3:throw new Error("Cannot invoke set subset on an Immutable Matrix instance");default:throw new SyntaxError("Wrong number of arguments")}},r.prototype.set=function(){throw new Error("Cannot invoke set on an Immutable Matrix instance")},r.prototype.resize=function(){throw new Error("Cannot invoke resize on an Immutable Matrix instance")},r.prototype.reshape=function(){throw new Error("Cannot invoke reshape on an Immutable Matrix instance")},r.prototype.clone=function(){return new r({data:clone$3(this._data),size:clone$3(this._size),datatype:this._datatype})},r.prototype.toJSON=function(){return{mathjs:"ImmutableDenseMatrix",data:this._data,size:this._size,datatype:this._datatype}},r.fromJSON=function(e){return new r(e)},r.prototype.swapRows=function(){throw new Error("Cannot invoke swapRows on an Immutable Matrix instance")},r.prototype.min=function(){if(null===this._min){var e=null;this.forEach((function(n){(null===e||t(n,e))&&(e=n)})),this._min=null!==e?e:void 0}return this._min},r.prototype.max=function(){if(null===this._max){var e=null;this.forEach((function(n){(null===e||t(e,n))&&(e=n)})),this._max=null!==e?e:void 0}return this._max},r}),{isClass:!0}),name$2e="Index",dependencies$2e=["ImmutableDenseMatrix"],createIndexClass=factory(name$2e,dependencies$2e,(e=>{var{ImmutableDenseMatrix:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");this._dimensions=[],this._isScalar=!0;for(var t=0,a=arguments.length;t{var{smaller:t,larger:n}=e,r=1/Math.log((1+Math.sqrt(5))/2);function a(){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");this._minimum=null,this._size=0}function i(e,t,n){t.left.right=t.right,t.right.left=t.left,n.degree--,n.child===t&&(n.child=t.right),0===n.degree&&(n.child=null),t.left=e,t.right=e.right,e.right=t,t.right.left=t,t.parent=null,t.mark=!1}function s(e,t){var n=t.parent;n&&(t.mark?(i(e,t,n),s(n)):t.mark=!0)}a.prototype.type="FibonacciHeap",a.prototype.isFibonacciHeap=!0,a.prototype.insert=function(e,n){var r={key:e,value:n,degree:0};if(this._minimum){var a=this._minimum;r.left=a,r.right=a.right,a.right=r,r.right.left=r,t(e,a.key)&&(this._minimum=r)}else r.left=r,r.right=r,this._minimum=r;return this._size++,r},a.prototype.size=function(){return this._size},a.prototype.clear=function(){this._minimum=null,this._size=0},a.prototype.isEmpty=function(){return 0===this._size},a.prototype.extractMinimum=function(){var e=this._minimum;if(null===e)return e;for(var a=this._minimum,i=e.degree,s=e.child;i>0;){var l=s.right;s.left.right=s.right,s.right.left=s.left,s.left=a,s.right=a.right,a.right=s,s.right.left=s,s.parent=null,s=l,i--}return e.left.right=e.right,e.right.left=e.left,a=e===e.right?null:function(e,a){var i,s=Math.floor(Math.log(a)*r)+1,l=new Array(s),u=0,c=e;if(c)for(u++,c=c.right;c!==e;)u++,c=c.right;for(;u>0;){for(var p=c.degree,d=c.right;i=l[p];){if(n(c.key,i.key)){var m=i;i=c,c=m}o(i,c),l[p]=null,p++}l[p]=c,c=d,u--}e=null;for(var h=0;h{var{addScalar:t,equalScalar:n,FibonacciHeap:r}=e;function a(){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");this._values=[],this._heap=new r}return a.prototype.type="Spa",a.prototype.isSpa=!0,a.prototype.set=function(e,t){if(this._values[e])this._values[e].value=t;else{var n=this._heap.insert(e,t);this._values[e]=n}},a.prototype.get=function(e){var t=this._values[e];return t?t.value:0},a.prototype.accumulate=function(e,n){var r=this._values[e];r?r.value=t(r.value,n):(r=this._heap.insert(e,n),this._values[e]=r)},a.prototype.forEach=function(e,t,r){var a=this._heap,i=this._values,s=[],o=a.extractMinimum();for(o&&s.push(o);o&&o.key<=t;)o.key>=e&&(n(o.value,0)||r(o.key,o.value,this)),(o=a.extractMinimum())&&s.push(o);for(var l=0;l{var t,n,r,{on:a,config:i,addScalar:s,subtract:o,multiplyScalar:l,divideScalar:u,pow:c,abs:p,fix:d,round:m,equal:h,isNumeric:f,format:y,number:g,Complex:b,BigNumber:v,Fraction:N}=e,T=g;function C(e,t){if(!(this instanceof C))throw new Error("Constructor must be called with the new operator");if(null!=e&&!f(e)&&!isComplex(e))throw new TypeError("First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined");if(void 0!==t&&("string"!=typeof t||""===t))throw new TypeError("Second parameter in Unit constructor must be a string");if(void 0!==t){var n=C.parse(t);this.units=n.units,this.dimensions=n.dimensions}else{this.units=[{unit:F,prefix:R.NONE,power:0}],this.dimensions=[];for(var r=0;r<_.length;r++)this.dimensions[r]=0}this.value=null!=e?this._normalize(e):null,this.fixPrefix=!1,this.skipAutomaticSimplification=!0}function A(){for(;" "===r||"\t"===r;)x()}function V(e){return e>="0"&&e<="9"}function x(){n++,r=t.charAt(n)}function S(e){n=e,r=t.charAt(n)}function w(){var e="",t=n;if("+"===r?x():"-"===r&&(e+=r,x()),!function(e){return e>="0"&&e<="9"||"."===e}(r))return S(t),null;if("."===r){if(e+=r,x(),!V(r))return S(t),null}else{for(;V(r);)e+=r,x();"."===r&&(e+=r,x())}for(;V(r);)e+=r,x();if("E"===r||"e"===r){var a="",i=n;if(a+=r,x(),"+"!==r&&"-"!==r||(a+=r,x()),!V(r))return S(i),e;for(e+=a;V(r);)e+=r,x()}return e}function E(){for(var e="";V(r)||C.isValidAlpha(r);)e+=r,x();var t=e.charAt(0);return C.isValidAlpha(t)?e:null}function D(e){return r===e?(x(),e):null}C.prototype.type="Unit",C.prototype.isUnit=!0,C.parse=function(e,a){if(a=a||{},n=-1,r="","string"!=typeof(t=e))throw new TypeError("Invalid argument in Unit.parse, string expected");var s=new C;s.units=[];var o=1,l=!1;x(),A();var u=w(),c=null;if(u){if("BigNumber"===i.number)c=new v(u);else if("Fraction"===i.number)try{c=new N(u)}catch(e){c=parseFloat(u)}else c=parseFloat(u);A(),D("*")?(o=1,l=!0):D("/")&&(o=-1,l=!0)}for(var p=[],d=1;;){for(A();"("===r;)p.push(o),d*=o,o=1,x(),A();var m;if(!r)break;var h=r;if(null===(m=E()))throw new SyntaxError('Unexpected "'+h+'" in "'+t+'" at index '+n.toString());var f=O(m);if(null===f)throw new SyntaxError('Unit "'+m+'" not found.');var y=o*d;if(A(),D("^")){A();var g=w();if(null===g)throw new SyntaxError('In "'+e+'", "^" must be followed by a floating-point number');y*=g}s.units.push({unit:f.unit,prefix:f.prefix,power:y});for(var b=0;b<_.length;b++)s.dimensions[b]+=(f.unit.dimensions[b]||0)*y;for(A();")"===r;){if(0===p.length)throw new SyntaxError('Unmatched ")" in "'+t+'" at index '+n.toString());d/=p.pop(),x(),A()}if(l=!1,D("*")?(o=1,l=!0):D("/")?(o=-1,l=!0):o=1,f.unit.base){var T=f.unit.base.key;L.auto[T]={unit:f.unit,prefix:f.prefix}}}if(A(),r)throw new SyntaxError('Could not parse: "'+e+'"');if(l)throw new SyntaxError('Trailing characters: "'+e+'"');if(0!==p.length)throw new SyntaxError('Unmatched "(" in "'+t+'"');if(0===s.units.length&&!a.allowNoUnits)throw new SyntaxError('"'+e+'" contains no units');return s.value=void 0!==c?s._normalize(c):null,s},C.prototype.clone=function(){var e=new C;e.fixPrefix=this.fixPrefix,e.skipAutomaticSimplification=this.skipAutomaticSimplification,e.value=clone$3(this.value),e.dimensions=this.dimensions.slice(0),e.units=[];for(var t=0;t1||Math.abs(this.units[0].power-1)>1e-15)},C.prototype._normalize=function(e){if(null==e||0===this.units.length)return e;for(var t=e,n=C._getNumberConverter(typeOf$1(e)),r=0;r{if(hasOwnProperty$2(k,e)){var t=k[e];return{unit:t,prefix:t.prefixes[""]}}for(var n in k)if(hasOwnProperty$2(k,n)&&endsWith(e,n)){var r=k[n],a=e.length-n.length,i=e.substring(0,a),s=hasOwnProperty$2(r.prefixes,i)?r.prefixes[i]:void 0;if(void 0!==s)return{unit:r,prefix:s}}return null}),{hasher:e=>e[0],limit:100});function I(e){return e.equalBase(M.NONE)&&null!==e.value&&!i.predictable?e.value:e}C.isValuelessUnit=function(e){return null!==O(e)},C.prototype.hasBase=function(e){if("string"==typeof e&&(e=M[e]),!e)return!1;for(var t=0;t<_.length;t++)if(Math.abs((this.dimensions[t]||0)-(e.dimensions[t]||0))>1e-12)return!1;return!0},C.prototype.equalBase=function(e){for(var t=0;t<_.length;t++)if(Math.abs((this.dimensions[t]||0)-(e.dimensions[t]||0))>1e-12)return!1;return!0},C.prototype.equals=function(e){return this.equalBase(e)&&h(this.value,e.value)},C.prototype.multiply=function(e){for(var t=this.clone(),n=0;n<_.length;n++)t.dimensions[n]=(this.dimensions[n]||0)+(e.dimensions[n]||0);for(var r=0;r1e-12&&(hasOwnProperty$2(z,o)?r.push({unit:z[o].unit,prefix:z[o].prefix,power:n.dimensions[s]||0}):i=!0)}r.length1e-12){if(!hasOwnProperty$2(L.si,r))throw new Error("Cannot express custom unit "+r+" in SI units");t.push({unit:L.si[r].unit,prefix:L.si[r].prefix,power:e.dimensions[n]||0})}}return e.units=t,e.fixPrefix=!0,e.skipAutomaticSimplification=!0,e},C.prototype.formatUnits=function(){for(var e="",t="",n=0,r=0,a=0;a0?(n++,e+=" "+this.units[a].prefix.name+this.units[a].unit.name,Math.abs(this.units[a].power-1)>1e-15&&(e+="^"+this.units[a].power)):this.units[a].power<0&&r++;if(r>0)for(var i=0;i0?(t+=" "+this.units[i].prefix.name+this.units[i].unit.name,Math.abs(this.units[i].power+1)>1e-15&&(t+="^"+-this.units[i].power)):(t+=" "+this.units[i].prefix.name+this.units[i].unit.name,t+="^"+this.units[i].power));e=e.substr(1),t=t.substr(1),n>1&&r>0&&(e="("+e+")"),r>1&&n>0&&(t="("+t+")");var s=e;return n>0&&r>0&&(s+=" / "),s+t},C.prototype.format=function(e){var t=this.skipAutomaticSimplification||null===this.value?this.clone():this.simplify(),n=!1;for(var r in void 0!==t.value&&null!==t.value&&isComplex(t.value)&&(n=Math.abs(t.value.re)<1e-14),t.units)hasOwnProperty$2(t.units,r)&&t.units[r].unit&&("VA"===t.units[r].unit.name&&n?t.units[r].unit=k.VAR:"VAR"!==t.units[r].unit.name||n||(t.units[r].unit=k.VA));1!==t.units.length||t.fixPrefix||Math.abs(t.units[0].power-Math.round(t.units[0].power))<1e-14&&(t.units[0].prefix=t._bestPrefix());var a=t._denormalize(t.value),i=null!==t.value?y(a,e||{}):"",s=t.formatUnits();return t.value&&isComplex(t.value)&&(i="("+i+")"),s.length>0&&i.length>0&&(i+=" "),i+s},C.prototype._bestPrefix=function(){if(1!==this.units.length)throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!");if(Math.abs(this.units[0].power-Math.round(this.units[0].power))>=1e-14)throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!");var e=null!==this.value?p(this.value):0,t=p(this.units[0].unit.value),n=this.units[0].prefix;if(0===e)return n;var r=this.units[0].power,a=Math.log(e/Math.pow(n.value*t,r))/Math.LN10-1.2;if(a>-2.200001&&a<1.800001)return n;a=Math.abs(a);var i=this.units[0].unit.prefixes;for(var s in i)if(hasOwnProperty$2(i,s)){var o=i[s];if(o.scientific){var l=Math.abs(Math.log(e/Math.pow(o.value*t,r))/Math.LN10-1.2);(l0))},k={meter:{name:"meter",base:M.LENGTH,prefixes:R.LONG,value:1,offset:0},inch:{name:"inch",base:M.LENGTH,prefixes:R.NONE,value:.0254,offset:0},foot:{name:"foot",base:M.LENGTH,prefixes:R.NONE,value:.3048,offset:0},yard:{name:"yard",base:M.LENGTH,prefixes:R.NONE,value:.9144,offset:0},mile:{name:"mile",base:M.LENGTH,prefixes:R.NONE,value:1609.344,offset:0},link:{name:"link",base:M.LENGTH,prefixes:R.NONE,value:.201168,offset:0},rod:{name:"rod",base:M.LENGTH,prefixes:R.NONE,value:5.0292,offset:0},chain:{name:"chain",base:M.LENGTH,prefixes:R.NONE,value:20.1168,offset:0},angstrom:{name:"angstrom",base:M.LENGTH,prefixes:R.NONE,value:1e-10,offset:0},m:{name:"m",base:M.LENGTH,prefixes:R.SHORT,value:1,offset:0},in:{name:"in",base:M.LENGTH,prefixes:R.NONE,value:.0254,offset:0},ft:{name:"ft",base:M.LENGTH,prefixes:R.NONE,value:.3048,offset:0},yd:{name:"yd",base:M.LENGTH,prefixes:R.NONE,value:.9144,offset:0},mi:{name:"mi",base:M.LENGTH,prefixes:R.NONE,value:1609.344,offset:0},li:{name:"li",base:M.LENGTH,prefixes:R.NONE,value:.201168,offset:0},rd:{name:"rd",base:M.LENGTH,prefixes:R.NONE,value:5.02921,offset:0},ch:{name:"ch",base:M.LENGTH,prefixes:R.NONE,value:20.1168,offset:0},mil:{name:"mil",base:M.LENGTH,prefixes:R.NONE,value:254e-7,offset:0},m2:{name:"m2",base:M.SURFACE,prefixes:R.SQUARED,value:1,offset:0},sqin:{name:"sqin",base:M.SURFACE,prefixes:R.NONE,value:64516e-8,offset:0},sqft:{name:"sqft",base:M.SURFACE,prefixes:R.NONE,value:.09290304,offset:0},sqyd:{name:"sqyd",base:M.SURFACE,prefixes:R.NONE,value:.83612736,offset:0},sqmi:{name:"sqmi",base:M.SURFACE,prefixes:R.NONE,value:2589988.110336,offset:0},sqrd:{name:"sqrd",base:M.SURFACE,prefixes:R.NONE,value:25.29295,offset:0},sqch:{name:"sqch",base:M.SURFACE,prefixes:R.NONE,value:404.6873,offset:0},sqmil:{name:"sqmil",base:M.SURFACE,prefixes:R.NONE,value:6.4516e-10,offset:0},acre:{name:"acre",base:M.SURFACE,prefixes:R.NONE,value:4046.86,offset:0},hectare:{name:"hectare",base:M.SURFACE,prefixes:R.NONE,value:1e4,offset:0},m3:{name:"m3",base:M.VOLUME,prefixes:R.CUBIC,value:1,offset:0},L:{name:"L",base:M.VOLUME,prefixes:R.SHORT,value:.001,offset:0},l:{name:"l",base:M.VOLUME,prefixes:R.SHORT,value:.001,offset:0},litre:{name:"litre",base:M.VOLUME,prefixes:R.LONG,value:.001,offset:0},cuin:{name:"cuin",base:M.VOLUME,prefixes:R.NONE,value:16387064e-12,offset:0},cuft:{name:"cuft",base:M.VOLUME,prefixes:R.NONE,value:.028316846592,offset:0},cuyd:{name:"cuyd",base:M.VOLUME,prefixes:R.NONE,value:.764554857984,offset:0},teaspoon:{name:"teaspoon",base:M.VOLUME,prefixes:R.NONE,value:5e-6,offset:0},tablespoon:{name:"tablespoon",base:M.VOLUME,prefixes:R.NONE,value:15e-6,offset:0},drop:{name:"drop",base:M.VOLUME,prefixes:R.NONE,value:5e-8,offset:0},gtt:{name:"gtt",base:M.VOLUME,prefixes:R.NONE,value:5e-8,offset:0},minim:{name:"minim",base:M.VOLUME,prefixes:R.NONE,value:6.161152e-8,offset:0},fluiddram:{name:"fluiddram",base:M.VOLUME,prefixes:R.NONE,value:36966911e-13,offset:0},fluidounce:{name:"fluidounce",base:M.VOLUME,prefixes:R.NONE,value:2957353e-11,offset:0},gill:{name:"gill",base:M.VOLUME,prefixes:R.NONE,value:.0001182941,offset:0},cc:{name:"cc",base:M.VOLUME,prefixes:R.NONE,value:1e-6,offset:0},cup:{name:"cup",base:M.VOLUME,prefixes:R.NONE,value:.0002365882,offset:0},pint:{name:"pint",base:M.VOLUME,prefixes:R.NONE,value:.0004731765,offset:0},quart:{name:"quart",base:M.VOLUME,prefixes:R.NONE,value:.0009463529,offset:0},gallon:{name:"gallon",base:M.VOLUME,prefixes:R.NONE,value:.003785412,offset:0},beerbarrel:{name:"beerbarrel",base:M.VOLUME,prefixes:R.NONE,value:.1173478,offset:0},oilbarrel:{name:"oilbarrel",base:M.VOLUME,prefixes:R.NONE,value:.1589873,offset:0},hogshead:{name:"hogshead",base:M.VOLUME,prefixes:R.NONE,value:.238481,offset:0},fldr:{name:"fldr",base:M.VOLUME,prefixes:R.NONE,value:36966911e-13,offset:0},floz:{name:"floz",base:M.VOLUME,prefixes:R.NONE,value:2957353e-11,offset:0},gi:{name:"gi",base:M.VOLUME,prefixes:R.NONE,value:.0001182941,offset:0},cp:{name:"cp",base:M.VOLUME,prefixes:R.NONE,value:.0002365882,offset:0},pt:{name:"pt",base:M.VOLUME,prefixes:R.NONE,value:.0004731765,offset:0},qt:{name:"qt",base:M.VOLUME,prefixes:R.NONE,value:.0009463529,offset:0},gal:{name:"gal",base:M.VOLUME,prefixes:R.NONE,value:.003785412,offset:0},bbl:{name:"bbl",base:M.VOLUME,prefixes:R.NONE,value:.1173478,offset:0},obl:{name:"obl",base:M.VOLUME,prefixes:R.NONE,value:.1589873,offset:0},g:{name:"g",base:M.MASS,prefixes:R.SHORT,value:.001,offset:0},gram:{name:"gram",base:M.MASS,prefixes:R.LONG,value:.001,offset:0},ton:{name:"ton",base:M.MASS,prefixes:R.SHORT,value:907.18474,offset:0},t:{name:"t",base:M.MASS,prefixes:R.SHORT,value:1e3,offset:0},tonne:{name:"tonne",base:M.MASS,prefixes:R.LONG,value:1e3,offset:0},grain:{name:"grain",base:M.MASS,prefixes:R.NONE,value:6479891e-11,offset:0},dram:{name:"dram",base:M.MASS,prefixes:R.NONE,value:.0017718451953125,offset:0},ounce:{name:"ounce",base:M.MASS,prefixes:R.NONE,value:.028349523125,offset:0},poundmass:{name:"poundmass",base:M.MASS,prefixes:R.NONE,value:.45359237,offset:0},hundredweight:{name:"hundredweight",base:M.MASS,prefixes:R.NONE,value:45.359237,offset:0},stick:{name:"stick",base:M.MASS,prefixes:R.NONE,value:.115,offset:0},stone:{name:"stone",base:M.MASS,prefixes:R.NONE,value:6.35029318,offset:0},gr:{name:"gr",base:M.MASS,prefixes:R.NONE,value:6479891e-11,offset:0},dr:{name:"dr",base:M.MASS,prefixes:R.NONE,value:.0017718451953125,offset:0},oz:{name:"oz",base:M.MASS,prefixes:R.NONE,value:.028349523125,offset:0},lbm:{name:"lbm",base:M.MASS,prefixes:R.NONE,value:.45359237,offset:0},cwt:{name:"cwt",base:M.MASS,prefixes:R.NONE,value:45.359237,offset:0},s:{name:"s",base:M.TIME,prefixes:R.SHORT,value:1,offset:0},min:{name:"min",base:M.TIME,prefixes:R.NONE,value:60,offset:0},h:{name:"h",base:M.TIME,prefixes:R.NONE,value:3600,offset:0},second:{name:"second",base:M.TIME,prefixes:R.LONG,value:1,offset:0},sec:{name:"sec",base:M.TIME,prefixes:R.LONG,value:1,offset:0},minute:{name:"minute",base:M.TIME,prefixes:R.NONE,value:60,offset:0},hour:{name:"hour",base:M.TIME,prefixes:R.NONE,value:3600,offset:0},day:{name:"day",base:M.TIME,prefixes:R.NONE,value:86400,offset:0},week:{name:"week",base:M.TIME,prefixes:R.NONE,value:604800,offset:0},month:{name:"month",base:M.TIME,prefixes:R.NONE,value:2629800,offset:0},year:{name:"year",base:M.TIME,prefixes:R.NONE,value:31557600,offset:0},decade:{name:"decade",base:M.TIME,prefixes:R.NONE,value:315576e3,offset:0},century:{name:"century",base:M.TIME,prefixes:R.NONE,value:315576e4,offset:0},millennium:{name:"millennium",base:M.TIME,prefixes:R.NONE,value:315576e5,offset:0},hertz:{name:"Hertz",base:M.FREQUENCY,prefixes:R.LONG,value:1,offset:0,reciprocal:!0},Hz:{name:"Hz",base:M.FREQUENCY,prefixes:R.SHORT,value:1,offset:0,reciprocal:!0},rad:{name:"rad",base:M.ANGLE,prefixes:R.SHORT,value:1,offset:0},radian:{name:"radian",base:M.ANGLE,prefixes:R.LONG,value:1,offset:0},deg:{name:"deg",base:M.ANGLE,prefixes:R.SHORT,value:null,offset:0},degree:{name:"degree",base:M.ANGLE,prefixes:R.LONG,value:null,offset:0},grad:{name:"grad",base:M.ANGLE,prefixes:R.SHORT,value:null,offset:0},gradian:{name:"gradian",base:M.ANGLE,prefixes:R.LONG,value:null,offset:0},cycle:{name:"cycle",base:M.ANGLE,prefixes:R.NONE,value:null,offset:0},arcsec:{name:"arcsec",base:M.ANGLE,prefixes:R.NONE,value:null,offset:0},arcmin:{name:"arcmin",base:M.ANGLE,prefixes:R.NONE,value:null,offset:0},A:{name:"A",base:M.CURRENT,prefixes:R.SHORT,value:1,offset:0},ampere:{name:"ampere",base:M.CURRENT,prefixes:R.LONG,value:1,offset:0},K:{name:"K",base:M.TEMPERATURE,prefixes:R.NONE,value:1,offset:0},degC:{name:"degC",base:M.TEMPERATURE,prefixes:R.NONE,value:1,offset:273.15},degF:{name:"degF",base:M.TEMPERATURE,prefixes:R.NONE,value:1/1.8,offset:459.67},degR:{name:"degR",base:M.TEMPERATURE,prefixes:R.NONE,value:1/1.8,offset:0},kelvin:{name:"kelvin",base:M.TEMPERATURE,prefixes:R.NONE,value:1,offset:0},celsius:{name:"celsius",base:M.TEMPERATURE,prefixes:R.NONE,value:1,offset:273.15},fahrenheit:{name:"fahrenheit",base:M.TEMPERATURE,prefixes:R.NONE,value:1/1.8,offset:459.67},rankine:{name:"rankine",base:M.TEMPERATURE,prefixes:R.NONE,value:1/1.8,offset:0},mol:{name:"mol",base:M.AMOUNT_OF_SUBSTANCE,prefixes:R.SHORT,value:1,offset:0},mole:{name:"mole",base:M.AMOUNT_OF_SUBSTANCE,prefixes:R.LONG,value:1,offset:0},cd:{name:"cd",base:M.LUMINOUS_INTENSITY,prefixes:R.SHORT,value:1,offset:0},candela:{name:"candela",base:M.LUMINOUS_INTENSITY,prefixes:R.LONG,value:1,offset:0},N:{name:"N",base:M.FORCE,prefixes:R.SHORT,value:1,offset:0},newton:{name:"newton",base:M.FORCE,prefixes:R.LONG,value:1,offset:0},dyn:{name:"dyn",base:M.FORCE,prefixes:R.SHORT,value:1e-5,offset:0},dyne:{name:"dyne",base:M.FORCE,prefixes:R.LONG,value:1e-5,offset:0},lbf:{name:"lbf",base:M.FORCE,prefixes:R.NONE,value:4.4482216152605,offset:0},poundforce:{name:"poundforce",base:M.FORCE,prefixes:R.NONE,value:4.4482216152605,offset:0},kip:{name:"kip",base:M.FORCE,prefixes:R.LONG,value:4448.2216,offset:0},kilogramforce:{name:"kilogramforce",base:M.FORCE,prefixes:R.NONE,value:9.80665,offset:0},J:{name:"J",base:M.ENERGY,prefixes:R.SHORT,value:1,offset:0},joule:{name:"joule",base:M.ENERGY,prefixes:R.SHORT,value:1,offset:0},erg:{name:"erg",base:M.ENERGY,prefixes:R.NONE,value:1e-7,offset:0},Wh:{name:"Wh",base:M.ENERGY,prefixes:R.SHORT,value:3600,offset:0},BTU:{name:"BTU",base:M.ENERGY,prefixes:R.BTU,value:1055.05585262,offset:0},eV:{name:"eV",base:M.ENERGY,prefixes:R.SHORT,value:1602176565e-28,offset:0},electronvolt:{name:"electronvolt",base:M.ENERGY,prefixes:R.LONG,value:1602176565e-28,offset:0},W:{name:"W",base:M.POWER,prefixes:R.SHORT,value:1,offset:0},watt:{name:"watt",base:M.POWER,prefixes:R.LONG,value:1,offset:0},hp:{name:"hp",base:M.POWER,prefixes:R.NONE,value:745.6998715386,offset:0},VAR:{name:"VAR",base:M.POWER,prefixes:R.SHORT,value:b.I,offset:0},VA:{name:"VA",base:M.POWER,prefixes:R.SHORT,value:1,offset:0},Pa:{name:"Pa",base:M.PRESSURE,prefixes:R.SHORT,value:1,offset:0},psi:{name:"psi",base:M.PRESSURE,prefixes:R.NONE,value:6894.75729276459,offset:0},atm:{name:"atm",base:M.PRESSURE,prefixes:R.NONE,value:101325,offset:0},bar:{name:"bar",base:M.PRESSURE,prefixes:R.SHORTLONG,value:1e5,offset:0},torr:{name:"torr",base:M.PRESSURE,prefixes:R.NONE,value:133.322,offset:0},mmHg:{name:"mmHg",base:M.PRESSURE,prefixes:R.NONE,value:133.322,offset:0},mmH2O:{name:"mmH2O",base:M.PRESSURE,prefixes:R.NONE,value:9.80665,offset:0},cmH2O:{name:"cmH2O",base:M.PRESSURE,prefixes:R.NONE,value:98.0665,offset:0},coulomb:{name:"coulomb",base:M.ELECTRIC_CHARGE,prefixes:R.LONG,value:1,offset:0},C:{name:"C",base:M.ELECTRIC_CHARGE,prefixes:R.SHORT,value:1,offset:0},farad:{name:"farad",base:M.ELECTRIC_CAPACITANCE,prefixes:R.LONG,value:1,offset:0},F:{name:"F",base:M.ELECTRIC_CAPACITANCE,prefixes:R.SHORT,value:1,offset:0},volt:{name:"volt",base:M.ELECTRIC_POTENTIAL,prefixes:R.LONG,value:1,offset:0},V:{name:"V",base:M.ELECTRIC_POTENTIAL,prefixes:R.SHORT,value:1,offset:0},ohm:{name:"ohm",base:M.ELECTRIC_RESISTANCE,prefixes:R.SHORTLONG,value:1,offset:0},henry:{name:"henry",base:M.ELECTRIC_INDUCTANCE,prefixes:R.LONG,value:1,offset:0},H:{name:"H",base:M.ELECTRIC_INDUCTANCE,prefixes:R.SHORT,value:1,offset:0},siemens:{name:"siemens",base:M.ELECTRIC_CONDUCTANCE,prefixes:R.LONG,value:1,offset:0},S:{name:"S",base:M.ELECTRIC_CONDUCTANCE,prefixes:R.SHORT,value:1,offset:0},weber:{name:"weber",base:M.MAGNETIC_FLUX,prefixes:R.LONG,value:1,offset:0},Wb:{name:"Wb",base:M.MAGNETIC_FLUX,prefixes:R.SHORT,value:1,offset:0},tesla:{name:"tesla",base:M.MAGNETIC_FLUX_DENSITY,prefixes:R.LONG,value:1,offset:0},T:{name:"T",base:M.MAGNETIC_FLUX_DENSITY,prefixes:R.SHORT,value:1,offset:0},b:{name:"b",base:M.BIT,prefixes:R.BINARY_SHORT,value:1,offset:0},bits:{name:"bits",base:M.BIT,prefixes:R.BINARY_LONG,value:1,offset:0},B:{name:"B",base:M.BIT,prefixes:R.BINARY_SHORT,value:8,offset:0},bytes:{name:"bytes",base:M.BIT,prefixes:R.BINARY_LONG,value:8,offset:0}},$={meters:"meter",inches:"inch",feet:"foot",yards:"yard",miles:"mile",links:"link",rods:"rod",chains:"chain",angstroms:"angstrom",lt:"l",litres:"litre",liter:"litre",liters:"litre",teaspoons:"teaspoon",tablespoons:"tablespoon",minims:"minim",fluiddrams:"fluiddram",fluidounces:"fluidounce",gills:"gill",cups:"cup",pints:"pint",quarts:"quart",gallons:"gallon",beerbarrels:"beerbarrel",oilbarrels:"oilbarrel",hogsheads:"hogshead",gtts:"gtt",grams:"gram",tons:"ton",tonnes:"tonne",grains:"grain",drams:"dram",ounces:"ounce",poundmasses:"poundmass",hundredweights:"hundredweight",sticks:"stick",lb:"lbm",lbs:"lbm",kips:"kip",kgf:"kilogramforce",acres:"acre",hectares:"hectare",sqfeet:"sqft",sqyard:"sqyd",sqmile:"sqmi",sqmiles:"sqmi",mmhg:"mmHg",mmh2o:"mmH2O",cmh2o:"cmH2O",seconds:"second",secs:"second",minutes:"minute",mins:"minute",hours:"hour",hr:"hour",hrs:"hour",days:"day",weeks:"week",months:"month",years:"year",decades:"decade",centuries:"century",millennia:"millennium",hertz:"hertz",radians:"radian",degrees:"degree",gradians:"gradian",cycles:"cycle",arcsecond:"arcsec",arcseconds:"arcsec",arcminute:"arcmin",arcminutes:"arcmin",BTUs:"BTU",watts:"watt",joules:"joule",amperes:"ampere",coulombs:"coulomb",volts:"volt",ohms:"ohm",farads:"farad",webers:"weber",teslas:"tesla",electronvolts:"electronvolt",moles:"mole",bit:"bits",byte:"bytes"};function B(e){if("BigNumber"===e.number){var t=createBigNumberPi(v);k.rad.value=new v(1),k.deg.value=t.div(180),k.grad.value=t.div(200),k.cycle.value=t.times(2),k.arcsec.value=t.div(648e3),k.arcmin.value=t.div(10800)}else k.rad.value=1,k.deg.value=Math.PI/180,k.grad.value=Math.PI/200,k.cycle.value=2*Math.PI,k.arcsec.value=Math.PI/648e3,k.arcmin.value=Math.PI/10800;k.radian.value=k.rad.value,k.degree.value=k.deg.value,k.gradian.value=k.grad.value}B(i),a&&a("config",(function(e,t){e.number!==t.number&&B(e)}));var L={si:{NONE:{unit:F,prefix:R.NONE[""]},LENGTH:{unit:k.m,prefix:R.SHORT[""]},MASS:{unit:k.g,prefix:R.SHORT.k},TIME:{unit:k.s,prefix:R.SHORT[""]},CURRENT:{unit:k.A,prefix:R.SHORT[""]},TEMPERATURE:{unit:k.K,prefix:R.SHORT[""]},LUMINOUS_INTENSITY:{unit:k.cd,prefix:R.SHORT[""]},AMOUNT_OF_SUBSTANCE:{unit:k.mol,prefix:R.SHORT[""]},ANGLE:{unit:k.rad,prefix:R.SHORT[""]},BIT:{unit:k.bits,prefix:R.SHORT[""]},FORCE:{unit:k.N,prefix:R.SHORT[""]},ENERGY:{unit:k.J,prefix:R.SHORT[""]},POWER:{unit:k.W,prefix:R.SHORT[""]},PRESSURE:{unit:k.Pa,prefix:R.SHORT[""]},ELECTRIC_CHARGE:{unit:k.C,prefix:R.SHORT[""]},ELECTRIC_CAPACITANCE:{unit:k.F,prefix:R.SHORT[""]},ELECTRIC_POTENTIAL:{unit:k.V,prefix:R.SHORT[""]},ELECTRIC_RESISTANCE:{unit:k.ohm,prefix:R.SHORT[""]},ELECTRIC_INDUCTANCE:{unit:k.H,prefix:R.SHORT[""]},ELECTRIC_CONDUCTANCE:{unit:k.S,prefix:R.SHORT[""]},MAGNETIC_FLUX:{unit:k.Wb,prefix:R.SHORT[""]},MAGNETIC_FLUX_DENSITY:{unit:k.T,prefix:R.SHORT[""]},FREQUENCY:{unit:k.Hz,prefix:R.SHORT[""]}}};L.cgs=JSON.parse(JSON.stringify(L.si)),L.cgs.LENGTH={unit:k.m,prefix:R.SHORT.c},L.cgs.MASS={unit:k.g,prefix:R.SHORT[""]},L.cgs.FORCE={unit:k.dyn,prefix:R.SHORT[""]},L.cgs.ENERGY={unit:k.erg,prefix:R.NONE[""]},L.us=JSON.parse(JSON.stringify(L.si)),L.us.LENGTH={unit:k.ft,prefix:R.NONE[""]},L.us.MASS={unit:k.lbm,prefix:R.NONE[""]},L.us.TEMPERATURE={unit:k.degF,prefix:R.NONE[""]},L.us.FORCE={unit:k.lbf,prefix:R.NONE[""]},L.us.ENERGY={unit:k.BTU,prefix:R.BTU[""]},L.us.POWER={unit:k.hp,prefix:R.NONE[""]},L.us.PRESSURE={unit:k.psi,prefix:R.NONE[""]},L.auto=JSON.parse(JSON.stringify(L.si));var z=L.auto;for(var U in C.setUnitSystem=function(e){if(!hasOwnProperty$2(L,e))throw new Error("Unit system "+e+" does not exist. Choices are: "+Object.keys(L).join(", "));z=L[e]},C.getUnitSystem=function(){for(var e in L)if(hasOwnProperty$2(L,e)&&L[e]===z)return e},C.typeConverters={BigNumber:function(e){return new v(e+"")},Fraction:function(e){return new N(e)},Complex:function(e){return e},number:function(e){return e}},C._getNumberConverter=function(e){if(!C.typeConverters[e])throw new TypeError('Unsupported type "'+e+'"');return C.typeConverters[e]},k)if(hasOwnProperty$2(k,U)){var j=k[U];j.dimensions=j.base.dimensions}for(var q in $)if(hasOwnProperty$2($,q)){var G=k[$[q]],H={};for(var W in G)hasOwnProperty$2(G,W)&&(H[W]=G[W]);H.name=q,k[q]=H}return C.isValidAlpha=function(e){return/^[a-zA-Z]$/.test(e)},C.createUnit=function(e,t){if("object"!=typeof e)throw new TypeError("createUnit expects first parameter to be of type 'Object'");if(t&&t.override)for(var n in e)if(hasOwnProperty$2(e,n)&&C.deleteUnit(n),e[n].aliases)for(var r=0;r0&&!C.isValidAlpha(r)&&!V(r))throw new Error('Invalid unit name (only alphanumeric characters are allowed): "'+e+'"')}}(e);var a,i,s,o=null,l=[],u=0;if(t&&"Unit"===t.type)o=t.clone();else if("string"==typeof t)""!==t&&(a=t);else{if("object"!=typeof t)throw new TypeError('Cannot create unit "'+e+'" from "'+t.toString()+'": expecting "string" or "Unit" or "Object"');a=t.definition,i=t.prefixes,u=t.offset,s=t.baseName,t.aliases&&(l=t.aliases.valueOf())}if(l)for(var c=0;c1e-12){h=!1;break}if(h){d=!0,p.base=M[m];break}}if(!d){s=s||e+"_STUFF";var y={dimensions:o.dimensions.slice(0)};y.key=s,M[s]=y,z[s]={unit:p,prefix:R.NONE[""]},p.base=M[s]}}else{if(s=s||e+"_STUFF",_.indexOf(s)>=0)throw new Error('Cannot create new base unit "'+e+'": a base unit with that name already exists (and cannot be overridden)');for(var g in _.push(s),M)hasOwnProperty$2(M,g)&&(M[g].dimensions[_.length-1]=0);for(var b={dimensions:[]},v=0;v<_.length;v++)b.dimensions[v]=0;b.dimensions[_.length-1]=1,b.key=s,M[s]=b,p={name:e,value:1,dimensions:M[s].dimensions.slice(0),prefixes:i,offset:u,base:M[s]},z[s]={unit:p,prefix:R.NONE[""]}}C.UNITS[e]=p;for(var N=0;N{var{typed:t,Unit:n}=e;return t(name$2a,{Unit:function(e){return e.clone()},string:function(e){return n.isValuelessUnit(e)?new n(null,e):n.parse(e,{allowNoUnits:!0})},"number | BigNumber | Fraction | Complex, string":function(e,t){return new n(e,t)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$29="sparse",dependencies$29=["typed","SparseMatrix"],createSparse=factory(name$29,dependencies$29,(e=>{var{typed:t,SparseMatrix:n}=e;return t(name$29,{"":function(){return new n([])},string:function(e){return new n([],e)},"Array | Matrix":function(e){return new n(e)},"Array | Matrix, string":function(e,t){return new n(e,t)}})})),name$28="createUnit",dependencies$28=["typed","Unit"],createCreateUnit=factory(name$28,dependencies$28,(e=>{var{typed:t,Unit:n}=e;return t(name$28,{"Object, Object":function(e,t){return n.createUnit(e,t)},Object:function(e){return n.createUnit(e,{})},"string, Unit | string | Object, Object":function(e,t,r){var a={};return a[e]=t,n.createUnit(a,r)},"string, Unit | string | Object":function(e,t){var r={};return r[e]=t,n.createUnit(r,{})},string:function(e){var t={};return t[e]={},n.createUnit(t,{})}})})),name$27="acos",dependencies$27=["typed","config","Complex"],createAcos=factory(name$27,dependencies$27,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$27,{number:function(e){return e>=-1&&e<=1||n.predictable?Math.acos(e):new r(e,0).acos()},Complex:function(e){return e.acos()},BigNumber:function(e){return e.acos()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$26="acosh",dependencies$26=["typed","config","Complex"],createAcosh=factory(name$26,dependencies$26,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$26,{number:function(e){return e>=1||n.predictable?acoshNumber(e):e<=-1?new r(Math.log(Math.sqrt(e*e-1)-e),Math.PI):new r(e,0).acosh()},Complex:function(e){return e.acosh()},BigNumber:function(e){return e.acosh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$25="acot",dependencies$25=["typed","BigNumber"],createAcot=factory(name$25,dependencies$25,(e=>{var{typed:t,BigNumber:n}=e;return t(name$25,{number:acotNumber,Complex:function(e){return e.acot()},BigNumber:function(e){return new n(1).div(e).atan()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$24="acoth",dependencies$24=["typed","config","Complex","BigNumber"],createAcoth=factory(name$24,dependencies$24,(e=>{var{typed:t,config:n,Complex:r,BigNumber:a}=e;return t(name$24,{number:function(e){return e>=1||e<=-1||n.predictable?acothNumber(e):new r(e,0).acoth()},Complex:function(e){return e.acoth()},BigNumber:function(e){return new a(1).div(e).atanh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$23="acsc",dependencies$23=["typed","config","Complex","BigNumber"],createAcsc=factory(name$23,dependencies$23,(e=>{var{typed:t,config:n,Complex:r,BigNumber:a}=e;return t(name$23,{number:function(e){return e<=-1||e>=1||n.predictable?acscNumber(e):new r(e,0).acsc()},Complex:function(e){return e.acsc()},BigNumber:function(e){return new a(1).div(e).asin()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$22="acsch",dependencies$22=["typed","BigNumber"],createAcsch=factory(name$22,dependencies$22,(e=>{var{typed:t,BigNumber:n}=e;return t(name$22,{number:acschNumber,Complex:function(e){return e.acsch()},BigNumber:function(e){return new n(1).div(e).asinh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$21="asec",dependencies$21=["typed","config","Complex","BigNumber"],createAsec=factory(name$21,dependencies$21,(e=>{var{typed:t,config:n,Complex:r,BigNumber:a}=e;return t(name$21,{number:function(e){return e<=-1||e>=1||n.predictable?asecNumber(e):new r(e,0).asec()},Complex:function(e){return e.asec()},BigNumber:function(e){return new a(1).div(e).acos()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$20="asech",dependencies$20=["typed","config","Complex","BigNumber"],createAsech=factory(name$20,dependencies$20,(e=>{var{typed:t,config:n,Complex:r,BigNumber:a}=e;return t(name$20,{number:function(e){if(e<=1&&e>=-1||n.predictable){var t=1/e;if(t>0||n.predictable)return asechNumber(e);var a=Math.sqrt(t*t-1);return new r(Math.log(a-t),Math.PI)}return new r(e,0).asech()},Complex:function(e){return e.asech()},BigNumber:function(e){return new a(1).div(e).acosh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1$="asin",dependencies$1$=["typed","config","Complex"],createAsin=factory(name$1$,dependencies$1$,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$1$,{number:function(e){return e>=-1&&e<=1||n.predictable?Math.asin(e):new r(e,0).asin()},Complex:function(e){return e.asin()},BigNumber:function(e){return e.asin()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1_="asinh",dependencies$1_=["typed"],createAsinh=factory(name$1_,dependencies$1_,(e=>{var{typed:t}=e;return t("asinh",{number:asinhNumber,Complex:function(e){return e.asinh()},BigNumber:function(e){return e.asinh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1Z="atan",dependencies$1Z=["typed"],createAtan=factory(name$1Z,dependencies$1Z,(e=>{var{typed:t}=e;return t("atan",{number:function(e){return Math.atan(e)},Complex:function(e){return e.atan()},BigNumber:function(e){return e.atan()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1Y="atan2",dependencies$1Y=["typed","matrix","equalScalar","BigNumber","DenseMatrix"],createAtan2=factory(name$1Y,dependencies$1Y,(e=>{var{typed:t,matrix:n,equalScalar:r,BigNumber:a,DenseMatrix:i}=e,s=createAlgorithm02({typed:t,equalScalar:r}),o=createAlgorithm03({typed:t}),l=createAlgorithm09({typed:t,equalScalar:r}),u=createAlgorithm11({typed:t,equalScalar:r}),c=createAlgorithm12({typed:t,DenseMatrix:i}),p=createAlgorithm13({typed:t}),d=createAlgorithm14({typed:t});return t(name$1Y,{"number, number":Math.atan2,"BigNumber, BigNumber":function(e,t){return a.atan2(e,t)},"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,this,!1)},"SparseMatrix, DenseMatrix":function(e,t){return s(t,e,this,!0)},"DenseMatrix, SparseMatrix":function(e,t){return o(e,t,this,!1)},"DenseMatrix, DenseMatrix":function(e,t){return p(e,t,this)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"SparseMatrix, number | BigNumber":function(e,t){return u(e,t,this,!1)},"DenseMatrix, number | BigNumber":function(e,t){return d(e,t,this,!1)},"number | BigNumber, SparseMatrix":function(e,t){return c(t,e,this,!0)},"number | BigNumber, DenseMatrix":function(e,t){return d(t,e,this,!0)},"Array, number | BigNumber":function(e,t){return d(n(e),t,this,!1).valueOf()},"number | BigNumber, Array":function(e,t){return d(n(t),e,this,!0).valueOf()}})})),name$1X="atanh",dependencies$1X=["typed","config","Complex"],createAtanh=factory(name$1X,dependencies$1X,(e=>{var{typed:t,config:n,Complex:r}=e;return t(name$1X,{number:function(e){return e<=1&&e>=-1||n.predictable?atanhNumber(e):new r(e,0).atanh()},Complex:function(e){return e.atanh()},BigNumber:function(e){return e.atanh()},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1W="cos",dependencies$1W=["typed"],createCos=factory(name$1W,dependencies$1W,(e=>{var{typed:t}=e;return t(name$1W,{number:Math.cos,Complex:function(e){return e.cos()},BigNumber:function(e){return e.cos()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function cos is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1V="cosh",dependencies$1V=["typed"],createCosh=factory(name$1V,dependencies$1V,(e=>{var{typed:t}=e;return t(name$1V,{number:cosh$3,Complex:function(e){return e.cosh()},BigNumber:function(e){return e.cosh()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function cosh is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1U="cot",dependencies$1U=["typed","BigNumber"],createCot=factory(name$1U,dependencies$1U,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1U,{number:cotNumber,Complex:function(e){return e.cot()},BigNumber:function(e){return new n(1).div(e.tan())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function cot is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1T="coth",dependencies$1T=["typed","BigNumber"],createCoth=factory(name$1T,dependencies$1T,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1T,{number:cothNumber,Complex:function(e){return e.coth()},BigNumber:function(e){return new n(1).div(e.tanh())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function coth is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1S="csc",dependencies$1S=["typed","BigNumber"],createCsc=factory(name$1S,dependencies$1S,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1S,{number:cscNumber,Complex:function(e){return e.csc()},BigNumber:function(e){return new n(1).div(e.sin())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function csc is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1R="csch",dependencies$1R=["typed","BigNumber"],createCsch=factory(name$1R,dependencies$1R,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1R,{number:cschNumber,Complex:function(e){return e.csch()},BigNumber:function(e){return new n(1).div(e.sinh())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function csch is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1Q="sec",dependencies$1Q=["typed","BigNumber"],createSec=factory(name$1Q,dependencies$1Q,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1Q,{number:secNumber,Complex:function(e){return e.sec()},BigNumber:function(e){return new n(1).div(e.cos())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sec is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1P="sech",dependencies$1P=["typed","BigNumber"],createSech=factory(name$1P,dependencies$1P,(e=>{var{typed:t,BigNumber:n}=e;return t(name$1P,{number:sechNumber,Complex:function(e){return e.sech()},BigNumber:function(e){return new n(1).div(e.cosh())},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sech is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1O="sin",dependencies$1O=["typed"],createSin=factory(name$1O,dependencies$1O,(e=>{var{typed:t}=e;return t(name$1O,{number:Math.sin,Complex:function(e){return e.sin()},BigNumber:function(e){return e.sin()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sin is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1N="sinh",dependencies$1N=["typed"],createSinh=factory(name$1N,dependencies$1N,(e=>{var{typed:t}=e;return t(name$1N,{number:sinhNumber,Complex:function(e){return e.sinh()},BigNumber:function(e){return e.sinh()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sinh is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1M="tan",dependencies$1M=["typed"],createTan=factory(name$1M,dependencies$1M,(e=>{var{typed:t}=e;return t(name$1M,{number:Math.tan,Complex:function(e){return e.tan()},BigNumber:function(e){return e.tan()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function tan is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1L="tanh",dependencies$1L=["typed"],createTanh=factory(name$1L,dependencies$1L,(e=>{var{typed:t}=e;return t("tanh",{number:tanh$3,Complex:function(e){return e.tanh()},BigNumber:function(e){return e.tanh()},Unit:function(e){if(!e.hasBase(e.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function tanh is no angle");return this(e.value)},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$1K="setCartesian",dependencies$1K=["typed","size","subset","compareNatural","Index","DenseMatrix"],createSetCartesian=factory(name$1K,dependencies$1K,(e=>{var{typed:t,size:n,subset:r,compareNatural:a,Index:i,DenseMatrix:s}=e;return t(name$1K,{"Array | Matrix, Array | Matrix":function(e,t){var o=[];if(0!==r(n(e),new i(0))&&0!==r(n(t),new i(0))){var l=flatten$4(Array.isArray(e)?e:e.toArray()).sort(a),u=flatten$4(Array.isArray(t)?t:t.toArray()).sort(a);o=[];for(var c=0;c{var{typed:t,size:n,subset:r,compareNatural:a,Index:i,DenseMatrix:s}=e;return t(name$1J,{"Array | Matrix, Array | Matrix":function(e,t){var o;if(0===r(n(e),new i(0)))o=[];else{if(0===r(n(t),new i(0)))return flatten$4(e.toArray());var l,u=identify(flatten$4(Array.isArray(e)?e:e.toArray()).sort(a)),c=identify(flatten$4(Array.isArray(t)?t:t.toArray()).sort(a));o=[];for(var p=0;p{var{typed:t,size:n,subset:r,compareNatural:a,Index:i,DenseMatrix:s}=e;return t(name$1I,{"Array | Matrix":function(e){var t;if(0===r(n(e),new i(0)))t=[];else{var o=flatten$4(Array.isArray(e)?e:e.toArray()).sort(a);(t=[]).push(o[0]);for(var l=1;l{var{typed:t,size:n,subset:r,compareNatural:a,Index:i,DenseMatrix:s}=e;return t(name$1H,{"Array | Matrix, Array | Matrix":function(e,t){var o;if(0===r(n(e),new i(0))||0===r(n(t),new i(0)))o=[];else{var l=identify(flatten$4(Array.isArray(e)?e:e.toArray()).sort(a)),u=identify(flatten$4(Array.isArray(t)?t:t.toArray()).sort(a));o=[];for(var c=0;c{var{typed:t,size:n,subset:r,compareNatural:a,Index:i}=e;return t(name$1G,{"Array | Matrix, Array | Matrix":function(e,t){if(0===r(n(e),new i(0)))return!0;if(0===r(n(t),new i(0)))return!1;for(var s,o=identify(flatten$4(Array.isArray(e)?e:e.toArray()).sort(a)),l=identify(flatten$4(Array.isArray(t)?t:t.toArray()).sort(a)),u=0;u{var{typed:t,size:n,subset:r,compareNatural:a,Index:i}=e;return t(name$1F,{"number | BigNumber | Fraction | Complex, Array | Matrix":function(e,t){if(0===r(n(t),new i(0)))return 0;for(var s=flatten$4(Array.isArray(t)?t:t.toArray()),o=0,l=0;l{var{typed:t,size:n,subset:r,compareNatural:a,Index:i}=e;return t(name$1E,{"Array | Matrix":function(e){if(0===r(n(e),new i(0)))return[];for(var t=flatten$4(Array.isArray(e)?e:e.toArray()).sort(a),o=[],l=0;l.toString(2).length<=t.length;)o.push(s(t,l.toString(2).split("").reverse())),l++;return function(e){for(var t=[],n=e.length-1;n>0;n--)for(var r=0;re[r+1].length&&(t=e[r],e[r]=e[r+1],e[r+1]=t);return e}(o)}});function s(e,t){for(var n=[],r=0;r{var{typed:t,compareNatural:n}=e;return t(name$1D,{"Array | Matrix":function(e){return Array.isArray(e)?flatten$4(e).length:flatten$4(e.toArray()).length},"Array | Matrix, boolean":function(e,t){if(!1===t||0===e.length)return Array.isArray(e)?flatten$4(e).length:flatten$4(e.toArray()).length;for(var r=flatten$4(Array.isArray(e)?e:e.toArray()).sort(n),a=1,i=1;i{var{typed:t,size:n,concat:r,subset:a,setDifference:i,Index:s}=e;return t(name$1C,{"Array | Matrix, Array | Matrix":function(e,t){if(0===a(n(e),new s(0)))return flatten$4(t);if(0===a(n(t),new s(0)))return flatten$4(e);var o=flatten$4(e),l=flatten$4(t);return r(i(o,l),i(l,o))}})})),name$1B="setUnion",dependencies$1B=["typed","size","concat","subset","setIntersect","setSymDifference","Index"],createSetUnion=factory(name$1B,dependencies$1B,(e=>{var{typed:t,size:n,concat:r,subset:a,setIntersect:i,setSymDifference:s,Index:o}=e;return t(name$1B,{"Array | Matrix, Array | Matrix":function(e,t){if(0===a(n(e),new o(0)))return flatten$4(t);if(0===a(n(t),new o(0)))return flatten$4(e);var l=flatten$4(e),u=flatten$4(t);return r(s(l,u),i(l,u))}})})),name$1A="add",dependencies$1A=["typed","matrix","addScalar","equalScalar","DenseMatrix","SparseMatrix"],createAdd=factory(name$1A,dependencies$1A,(e=>{var{typed:t,matrix:n,addScalar:r,equalScalar:a,DenseMatrix:i,SparseMatrix:s}=e,o=createAlgorithm01({typed:t}),l=createAlgorithm04({typed:t,equalScalar:a}),u=createAlgorithm10({typed:t,DenseMatrix:i}),c=createAlgorithm13({typed:t}),p=createAlgorithm14({typed:t});return t(name$1A,extend$2({"DenseMatrix, DenseMatrix":function(e,t){return c(e,t,r)},"DenseMatrix, SparseMatrix":function(e,t){return o(e,t,r,!1)},"SparseMatrix, DenseMatrix":function(e,t){return o(t,e,r,!0)},"SparseMatrix, SparseMatrix":function(e,t){return l(e,t,r)},"Array, Array":function(e,t){return this(n(e),n(t)).valueOf()},"Array, Matrix":function(e,t){return this(n(e),t)},"Matrix, Array":function(e,t){return this(e,n(t))},"DenseMatrix, any":function(e,t){return p(e,t,r,!1)},"SparseMatrix, any":function(e,t){return u(e,t,r,!1)},"any, DenseMatrix":function(e,t){return p(t,e,r,!0)},"any, SparseMatrix":function(e,t){return u(t,e,r,!0)},"Array, any":function(e,t){return p(n(e),t,r,!1).valueOf()},"any, Array":function(e,t){return p(n(t),e,r,!0).valueOf()},"any, any":r,"any, any, ...any":function(e,t,n){for(var r=this(e,t),a=0;a{var{typed:t,abs:n,addScalar:r,divideScalar:a,multiplyScalar:i,sqrt:s,smaller:o,isPositive:l}=e;return t(name$1z,{"... number | BigNumber":function(e){for(var t=0,u=0,c=0;c{var{typed:t,abs:n,add:r,pow:a,conj:i,sqrt:s,multiply:o,equalScalar:l,larger:u,smaller:c,matrix:p,ctranspose:d,eigs:m}=e;return t(name$1y,{number:Math.abs,Complex:function(e){return e.abs()},BigNumber:function(e){return e.abs()},boolean:function(e){return Math.abs(e)},Array:function(e){return y(p(e),2)},Matrix:function(e){return y(e,2)},"number | Complex | BigNumber | boolean, number | BigNumber | string":function(e){return this(e)},"Array, number | BigNumber | string":function(e,t){return y(p(e),t)},"Matrix, number | BigNumber | string":function(e,t){return y(e,t)}});function h(e,t){if(t===Number.POSITIVE_INFINITY||"inf"===t)return function(e){var t=0;return e.forEach((function(e){var r=n(e);u(r,t)&&(t=r)}),!0),t}(e);if(t===Number.NEGATIVE_INFINITY||"-inf"===t)return function(e){var t;return e.forEach((function(e){var r=n(e);t&&!c(r,t)||(t=r)}),!0),t||0}(e);if("fro"===t)return y(e,2);if("number"==typeof t&&!isNaN(t)){if(!l(t,0)){var i=0;return e.forEach((function(e){i=r(a(n(e),t),i)}),!0),a(i,1/t)}return Number.POSITIVE_INFINITY}throw new Error("Unsupported parameter value")}function f(e,t){if(1===t)return function(e){var t=[],a=0;return e.forEach((function(e,i){var s=i[1],o=r(t[s]||0,n(e));u(o,a)&&(a=o),t[s]=o}),!0),a}(e);if(t===Number.POSITIVE_INFINITY||"inf"===t)return function(e){var t=[],a=0;return e.forEach((function(e,i){var s=i[0],o=r(t[s]||0,n(e));u(o,a)&&(a=o),t[s]=o}),!0),a}(e);if("fro"===t)return function(e){var t=0;return e.forEach((function(e,n){t=r(t,o(e,i(e)))})),n(s(t))}(e);if(2===t)return function(e){var t=e.size();if(t[0]!==t[1])throw new RangeError("Invalid matrix dimensions");var r=d(e),a=o(r,e),i=m(a).values.toArray(),l=i[i.length-1];return n(s(l))}(e);throw new Error("Unsupported parameter value "+t)}function y(e,t){var n=e.size();if(1===n.length)return h(e,t);if(2===n.length){if(n[0]&&n[1])return f(e,t);throw new RangeError("Invalid matrix dimensions")}}})),name$1x="dot",dependencies$1x=["typed","addScalar","multiplyScalar","conj","size"],createDot=factory(name$1x,dependencies$1x,(e=>{var{typed:t,addScalar:n,multiplyScalar:r,conj:a,size:i}=e;return t(name$1x,{"Array | DenseMatrix, Array | DenseMatrix":function(e,i){var l=s(e,i),u=isMatrix(e)?e._data:e,c=isMatrix(e)?e._datatype:void 0,p=isMatrix(i)?i._data:i,d=isMatrix(i)?i._datatype:void 0,m=2===o(e).length,h=2===o(i).length,f=n,y=r;if(c&&d&&c===d&&"string"==typeof c){var g=c;f=t.find(n,[g,g]),y=t.find(r,[g,g])}if(!m&&!h){for(var b=y(a(u[0]),p[0]),v=1;vf?m++:h===f&&(u=c(u,p(i[d],l[m])),d++,m++)}return u}});function s(e,t){var n,r,a=o(e),i=o(t);if(1===a.length)n=a[0];else{if(2!==a.length||1!==a[1])throw new RangeError("Expected a column vector, instead got a matrix of size ("+a.join(", ")+")");n=a[0]}if(1===i.length)r=i[0];else{if(2!==i.length||1!==i[1])throw new RangeError("Expected a column vector, instead got a matrix of size ("+i.join(", ")+")");r=i[0]}if(n!==r)throw new RangeError("Vectors must have equal length ("+n+" != "+r+")");if(0===n)throw new RangeError("Cannot calculate the dot product of empty vectors");return n}function o(e){return isMatrix(e)?e.size():i(e)}})),name$1w="trace",dependencies$1w=["typed","matrix","add"],createTrace=factory(name$1w,dependencies$1w,(e=>{var{typed:t,matrix:n,add:r}=e;return t("trace",{Array:function(e){return a(n(e))},SparseMatrix:function(e){var t=e._values,n=e._index,a=e._ptr,i=e._size,s=i[0],o=i[1];if(s===o){var l=0;if(t.length>0)for(var u=0;uu)break}return l}throw new RangeError("Matrix must be square (size: "+format$1(i)+")")},DenseMatrix:a,any:clone$3});function a(e){var t=e._size,n=e._data;switch(t.length){case 1:if(1===t[0])return clone$3(n[0]);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");case 2:var a=t[0];if(a===t[1]){for(var i=0,s=0;s{var{typed:t,Index:n}=e;return t(name$1v,{"...number | string | BigNumber | Range | Array | Matrix":function(e){var t=e.map((function(e){return isBigNumber(e)?e.toNumber():Array.isArray(e)||isMatrix(e)?e.map((function(e){return isBigNumber(e)?e.toNumber():e})):e})),r=new n;return n.apply(r,t),r}})})),keywords=new Set(["end"]),name$1u="Node",dependencies$1u=["mathWithTransform"],createNode=factory(name$1u,dependencies$1u,(e=>{var{mathWithTransform:t}=e;function n(){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator")}return n.prototype.evaluate=function(e){return this.compile().evaluate(e)},n.prototype.type="Node",n.prototype.isNode=!0,n.prototype.comment="",n.prototype.compile=function(){var e=this._compile(t,{}),n={};return{evaluate:function(t){var r=createMap$1(t);return function(e){for(var t of[...keywords])if(e.has(t))throw new Error('Scope contains an illegal symbol, "'+t+'" is a reserved keyword')}(r),e(r,n,null)}}},n.prototype._compile=function(e,t){throw new Error("Method _compile should be implemented by type "+this.type)},n.prototype.forEach=function(e){throw new Error("Cannot run forEach on a Node interface")},n.prototype.map=function(e){throw new Error("Cannot run map on a Node interface")},n.prototype._ifNode=function(e){if(!isNode(e))throw new TypeError("Callback function must return a Node");return e},n.prototype.traverse=function(e){e(this,null,null),function e(t,n){t.forEach((function(t,r,a){n(t,r,a),e(t,n)}))}(this,e)},n.prototype.transform=function(e){return function t(n,r,a){var i=e(n,r,a);return i!==n?i:n.map(t)}(this,null,null)},n.prototype.filter=function(e){var t=[];return this.traverse((function(n,r,a){e(n,r,a)&&t.push(n)})),t},n.prototype.clone=function(){throw new Error("Cannot clone a Node interface")},n.prototype.cloneDeep=function(){return this.map((function(e){return e.cloneDeep()}))},n.prototype.equals=function(e){return!!e&&deepStrictEqual(this,e)},n.prototype.toString=function(e){var t=this._getCustomString(e);return void 0!==t?t:this._toString(e)},n.prototype.toJSON=function(){throw new Error("Cannot serialize object: toJSON not implemented by "+this.type)},n.prototype.toHTML=function(e){var t=this._getCustomString(e);return void 0!==t?t:this.toHTML(e)},n.prototype._toString=function(){throw new Error("_toString not implemented for "+this.type)},n.prototype.toTex=function(e){var t=this._getCustomString(e);return void 0!==t?t:this._toTex(e)},n.prototype._toTex=function(e){throw new Error("_toTex not implemented for "+this.type)},n.prototype._getCustomString=function(e){if(e&&"object"==typeof e)switch(typeof e.handler){case"object":case"undefined":return;case"function":return e.handler(this,e);default:throw new TypeError("Object or function expected as callback")}},n.prototype.getIdentifier=function(){return this.type},n.prototype.getContent=function(){return this},n}),{isClass:!0,isNode:!0});function errorTransform(e){return e&&e.isIndexError?new IndexError(e.index+1,e.min+1,void 0!==e.max?e.max+1:void 0):e}function accessFactory(e){var{subset:t}=e;return function(e,n){try{if(Array.isArray(e))return t(e,n);if(e&&"function"==typeof e.subset)return e.subset(n);if("string"==typeof e)return t(e,n);if("object"==typeof e){if(!n.isObjectProperty())throw new TypeError("Cannot apply a numeric index as object property");return getSafeProperty(e,n.getObjectProperty())}throw new TypeError("Cannot apply index: unsupported type of object")}catch(e){throw errorTransform(e)}}}var name$1t="AccessorNode",dependencies$1t=["subset","Node"],createAccessorNode=factory(name$1t,dependencies$1t,(e=>{var{subset:t,Node:n}=e,r=accessFactory({subset:t});function a(e,t){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");if(!isNode(e))throw new TypeError('Node expected for parameter "object"');if(!isIndexNode(t))throw new TypeError('IndexNode expected for parameter "index"');this.object=e||null,this.index=t,Object.defineProperty(this,"name",{get:function(){return this.index?this.index.isObjectProperty()?this.index.getObjectProperty():"":this.object.name||""}.bind(this),set:function(){throw new Error("Cannot assign a new name, name is read-only")}})}function i(e){return!(isAccessorNode(e)||isArrayNode(e)||isConstantNode(e)||isFunctionNode(e)||isObjectNode(e)||isParenthesisNode(e)||isSymbolNode(e))}return a.prototype=new n,a.prototype.type="AccessorNode",a.prototype.isAccessorNode=!0,a.prototype._compile=function(e,t){var n=this.object._compile(e,t),a=this.index._compile(e,t);if(this.index.isObjectProperty()){var i=this.index.getObjectProperty();return function(e,t,r){return getSafeProperty(n(e,t,r),i)}}return function(e,t,i){var s=n(e,t,i),o=a(e,t,s);return r(s,o)}},a.prototype.forEach=function(e){e(this.object,"object",this),e(this.index,"index",this)},a.prototype.map=function(e){return new a(this._ifNode(e(this.object,"object",this)),this._ifNode(e(this.index,"index",this)))},a.prototype.clone=function(){return new a(this.object,this.index)},a.prototype._toString=function(e){var t=this.object.toString(e);return i(this.object)&&(t="("+t+")"),t+this.index.toString(e)},a.prototype.toHTML=function(e){var t=this.object.toHTML(e);return i(this.object)&&(t='('+t+')'),t+this.index.toHTML(e)},a.prototype._toTex=function(e){var t=this.object.toTex(e);return i(this.object)&&(t="\\left(' + object + '\\right)"),t+this.index.toTex(e)},a.prototype.toJSON=function(){return{mathjs:"AccessorNode",object:this.object,index:this.index}},a.fromJSON=function(e){return new a(e.object,e.index)},a}),{isClass:!0,isNode:!0}),name$1s="ArrayNode",dependencies$1s=["Node"],createArrayNode=factory(name$1s,dependencies$1s,(e=>{var{Node:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(this.items=e||[],!Array.isArray(this.items)||!this.items.every(isNode))throw new TypeError("Array containing Nodes expected")}return n.prototype=new t,n.prototype.type="ArrayNode",n.prototype.isArrayNode=!0,n.prototype._compile=function(e,t){var n=map$2(this.items,(function(n){return n._compile(e,t)}));if("Array"!==e.config.matrix){var r=e.matrix;return function(e,t,a){return r(map$2(n,(function(n){return n(e,t,a)})))}}return function(e,t,r){return map$2(n,(function(n){return n(e,t,r)}))}},n.prototype.forEach=function(e){for(var t=0;t['+this.items.map((function(t){return t.toHTML(e)})).join(',')+']'},n.prototype._toTex=function(e){return function t(n,r){var a=n.some(isArrayNode)&&!n.every(isArrayNode),i=r||a,s=i?"&":"\\\\",o=n.map((function(n){return n.items?t(n.items,!r):n.toTex(e)})).join(s);return a||!i||i&&!r?"\\begin{bmatrix}"+o+"\\end{bmatrix}":o}(this.items,!1)},n}),{isClass:!0,isNode:!0});function assignFactory(e){var{subset:t,matrix:n}=e;return function(e,r,a){try{if(Array.isArray(e))return n(e).subset(r,a).valueOf();if(e&&"function"==typeof e.subset)return e.subset(r,a);if("string"==typeof e)return t(e,r,a);if("object"==typeof e){if(!r.isObjectProperty())throw TypeError("Cannot apply a numeric index as object property");return setSafeProperty(e,r.getObjectProperty(),a),e}throw new TypeError("Cannot apply index: unsupported type of object")}catch(e){throw errorTransform(e)}}}var properties=[{AssignmentNode:{},FunctionAssignmentNode:{}},{ConditionalNode:{latexLeftParens:!1,latexRightParens:!1,latexParens:!1}},{"OperatorNode:or":{associativity:"left",associativeWith:[]}},{"OperatorNode:xor":{associativity:"left",associativeWith:[]}},{"OperatorNode:and":{associativity:"left",associativeWith:[]}},{"OperatorNode:bitOr":{associativity:"left",associativeWith:[]}},{"OperatorNode:bitXor":{associativity:"left",associativeWith:[]}},{"OperatorNode:bitAnd":{associativity:"left",associativeWith:[]}},{"OperatorNode:equal":{associativity:"left",associativeWith:[]},"OperatorNode:unequal":{associativity:"left",associativeWith:[]},"OperatorNode:smaller":{associativity:"left",associativeWith:[]},"OperatorNode:larger":{associativity:"left",associativeWith:[]},"OperatorNode:smallerEq":{associativity:"left",associativeWith:[]},"OperatorNode:largerEq":{associativity:"left",associativeWith:[]},RelationalNode:{associativity:"left",associativeWith:[]}},{"OperatorNode:leftShift":{associativity:"left",associativeWith:[]},"OperatorNode:rightArithShift":{associativity:"left",associativeWith:[]},"OperatorNode:rightLogShift":{associativity:"left",associativeWith:[]}},{"OperatorNode:to":{associativity:"left",associativeWith:[]}},{RangeNode:{}},{"OperatorNode:add":{associativity:"left",associativeWith:["OperatorNode:add","OperatorNode:subtract"]},"OperatorNode:subtract":{associativity:"left",associativeWith:[]}},{"OperatorNode:multiply":{associativity:"left",associativeWith:["OperatorNode:multiply","OperatorNode:divide","Operator:dotMultiply","Operator:dotDivide"]},"OperatorNode:divide":{associativity:"left",associativeWith:[],latexLeftParens:!1,latexRightParens:!1,latexParens:!1},"OperatorNode:dotMultiply":{associativity:"left",associativeWith:["OperatorNode:multiply","OperatorNode:divide","OperatorNode:dotMultiply","OperatorNode:doDivide"]},"OperatorNode:dotDivide":{associativity:"left",associativeWith:[]},"OperatorNode:mod":{associativity:"left",associativeWith:[]}},{"OperatorNode:unaryPlus":{associativity:"right"},"OperatorNode:unaryMinus":{associativity:"right"},"OperatorNode:bitNot":{associativity:"right"},"OperatorNode:not":{associativity:"right"}},{"OperatorNode:pow":{associativity:"right",associativeWith:[],latexRightParens:!1},"OperatorNode:dotPow":{associativity:"right",associativeWith:[]}},{"OperatorNode:factorial":{associativity:"left"}},{"OperatorNode:transpose":{associativity:"left"}}];function getPrecedence(e,t){var n=e;"keep"!==t&&(n=e.getContent());for(var r=n.getIdentifier(),a=0;a{var{subset:t,matrix:n,Node:r}=e,a=accessFactory({subset:t}),i=assignFactory({subset:t,matrix:n});function s(e,t,n){if(!(this instanceof s))throw new SyntaxError("Constructor must be called with the new operator");if(this.object=e,this.index=n?t:null,this.value=n||t,!isSymbolNode(e)&&!isAccessorNode(e))throw new TypeError('SymbolNode or AccessorNode expected as "object"');if(isSymbolNode(e)&&"end"===e.name)throw new Error('Cannot assign to symbol "end"');if(this.index&&!isIndexNode(this.index))throw new TypeError('IndexNode expected as "index"');if(!isNode(this.value))throw new TypeError('Node expected as "value"');Object.defineProperty(this,"name",{get:function(){return this.index?this.index.isObjectProperty()?this.index.getObjectProperty():"":this.object.name||""}.bind(this),set:function(){throw new Error("Cannot assign a new name, name is read-only")}})}function o(e,t){t||(t="keep");var n=getPrecedence(e,t),r=getPrecedence(e.value,t);return"all"===t||null!==r&&r<=n}return s.prototype=new r,s.prototype.type="AssignmentNode",s.prototype.isAssignmentNode=!0,s.prototype._compile=function(e,t){var n=this.object._compile(e,t),r=this.index?this.index._compile(e,t):null,s=this.value._compile(e,t),o=this.object.name;if(this.index){if(this.index.isObjectProperty()){var l=this.index.getObjectProperty();return function(e,t,r){var a=n(e,t,r),i=s(e,t,r);return setSafeProperty(a,l,i),i}}if(isSymbolNode(this.object))return function(e,t,a){var l=n(e,t,a),u=s(e,t,a),c=r(e,t,l);return e.set(o,i(l,c,u)),u};var u=this.object.object._compile(e,t);if(this.object.index.isObjectProperty()){var c=this.object.index.getObjectProperty();return function(e,t,n){var a=u(e,t,n),o=getSafeProperty(a,c),l=r(e,t,o),p=s(e,t,n);return setSafeProperty(a,c,i(o,l,p)),p}}var p=this.object.index._compile(e,t);return function(e,t,n){var o=u(e,t,n),l=p(e,t,o),c=a(o,l),d=r(e,t,c),m=s(e,t,n);return i(o,l,i(c,d,m)),m}}if(!isSymbolNode(this.object))throw new TypeError("SymbolNode expected as object");return function(e,t,n){var r=s(e,t,n);return e.set(o,r),r}},s.prototype.forEach=function(e){e(this.object,"object",this),this.index&&e(this.index,"index",this),e(this.value,"value",this)},s.prototype.map=function(e){return new s(this._ifNode(e(this.object,"object",this)),this.index?this._ifNode(e(this.index,"index",this)):null,this._ifNode(e(this.value,"value",this)))},s.prototype.clone=function(){return new s(this.object,this.index,this.value)},s.prototype._toString=function(e){var t=this.object.toString(e),n=this.index?this.index.toString(e):"",r=this.value.toString(e);return o(this,e&&e.parenthesis)&&(r="("+r+")"),t+n+" = "+r},s.prototype.toJSON=function(){return{mathjs:"AssignmentNode",object:this.object,index:this.index,value:this.value}},s.fromJSON=function(e){return new s(e.object,e.index,e.value)},s.prototype.toHTML=function(e){var t=this.object.toHTML(e),n=this.index?this.index.toHTML(e):"",r=this.value.toHTML(e);return o(this,e&&e.parenthesis)&&(r='('+r+')'),t+n+'='+r},s.prototype._toTex=function(e){var t=this.object.toTex(e),n=this.index?this.index.toTex(e):"",r=this.value.toTex(e);return o(this,e&&e.parenthesis)&&(r="\\left(".concat(r,"\\right)")),t+n+":="+r},s}),{isClass:!0,isNode:!0}),name$1q="BlockNode",dependencies$1q=["ResultSet","Node"],createBlockNode=factory(name$1q,dependencies$1q,(e=>{var{ResultSet:t,Node:n}=e;function r(e){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");if(!Array.isArray(e))throw new Error("Array expected");this.blocks=e.map((function(e){var t=e&&e.node,n=!e||void 0===e.visible||e.visible;if(!isNode(t))throw new TypeError('Property "node" must be a Node');if("boolean"!=typeof n)throw new TypeError('Property "visible" must be a boolean');return{node:t,visible:n}}))}return r.prototype=new n,r.prototype.type="BlockNode",r.prototype.isBlockNode=!0,r.prototype._compile=function(e,n){var r=map$2(this.blocks,(function(t){return{evaluate:t.node._compile(e,n),visible:t.visible}}));return function(e,n,a){var i=[];return forEach$1(r,(function(t){var r=t.evaluate(e,n,a);t.visible&&i.push(r)})),new t(i)}},r.prototype.forEach=function(e){for(var t=0;t;')})).join('
')},r.prototype._toTex=function(e){return this.blocks.map((function(t){return t.node.toTex(e)+(t.visible?"":";")})).join("\\;\\;\n")},r}),{isClass:!0,isNode:!0}),name$1p="ConditionalNode",dependencies$1p=["Node"],createConditionalNode=factory(name$1p,dependencies$1p,(e=>{var{Node:t}=e;function n(e,t,r){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!isNode(e))throw new TypeError("Parameter condition must be a Node");if(!isNode(t))throw new TypeError("Parameter trueExpr must be a Node");if(!isNode(r))throw new TypeError("Parameter falseExpr must be a Node");this.condition=e,this.trueExpr=t,this.falseExpr=r}return n.prototype=new t,n.prototype.type="ConditionalNode",n.prototype.isConditionalNode=!0,n.prototype._compile=function(e,t){var n=this.condition._compile(e,t),r=this.trueExpr._compile(e,t),a=this.falseExpr._compile(e,t);return function(e,t,i){return function(e){if("number"==typeof e||"boolean"==typeof e||"string"==typeof e)return!!e;if(e){if(isBigNumber(e))return!e.isZero();if(isComplex(e))return!(!e.re&&!e.im);if(isUnit(e))return!!e.value}if(null==e)return!1;throw new TypeError('Unsupported type of condition "'+typeOf$1(e)+'"')}(n(e,t,i))?r(e,t,i):a(e,t,i)}},n.prototype.forEach=function(e){e(this.condition,"condition",this),e(this.trueExpr,"trueExpr",this),e(this.falseExpr,"falseExpr",this)},n.prototype.map=function(e){return new n(this._ifNode(e(this.condition,"condition",this)),this._ifNode(e(this.trueExpr,"trueExpr",this)),this._ifNode(e(this.falseExpr,"falseExpr",this)))},n.prototype.clone=function(){return new n(this.condition,this.trueExpr,this.falseExpr)},n.prototype._toString=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=getPrecedence(this,t),r=this.condition.toString(e),a=getPrecedence(this.condition,t);("all"===t||"OperatorNode"===this.condition.type||null!==a&&a<=n)&&(r="("+r+")");var i=this.trueExpr.toString(e),s=getPrecedence(this.trueExpr,t);("all"===t||"OperatorNode"===this.trueExpr.type||null!==s&&s<=n)&&(i="("+i+")");var o=this.falseExpr.toString(e),l=getPrecedence(this.falseExpr,t);return("all"===t||"OperatorNode"===this.falseExpr.type||null!==l&&l<=n)&&(o="("+o+")"),r+" ? "+i+" : "+o},n.prototype.toJSON=function(){return{mathjs:"ConditionalNode",condition:this.condition,trueExpr:this.trueExpr,falseExpr:this.falseExpr}},n.fromJSON=function(e){return new n(e.condition,e.trueExpr,e.falseExpr)},n.prototype.toHTML=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=getPrecedence(this,t),r=this.condition.toHTML(e),a=getPrecedence(this.condition,t);("all"===t||"OperatorNode"===this.condition.type||null!==a&&a<=n)&&(r='('+r+')');var i=this.trueExpr.toHTML(e),s=getPrecedence(this.trueExpr,t);("all"===t||"OperatorNode"===this.trueExpr.type||null!==s&&s<=n)&&(i='('+i+')');var o=this.falseExpr.toHTML(e),l=getPrecedence(this.falseExpr,t);return("all"===t||"OperatorNode"===this.falseExpr.type||null!==l&&l<=n)&&(o='('+o+')'),r+'?'+i+':'+o},n.prototype._toTex=function(e){return"\\begin{cases} {"+this.trueExpr.toTex(e)+"}, &\\quad{\\text{if }\\;"+this.condition.toTex(e)+"}\\\\{"+this.falseExpr.toTex(e)+"}, &\\quad{\\text{otherwise}}\\end{cases}"},n}),{isClass:!0,isNode:!0}),_extends=Object.assign||function(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{},n=t.preserveFormatting,r=void 0!==n&&n,a=t.escapeMapFn,i=void 0===a?defaultEscapeMapFn:a,s=String(e),o="",l=i(_extends({},defaultEscapes),r?_extends({},formatEscapes):{}),u=Object.keys(l),c=function(){var e=!1;u.forEach((function(t,n){e||s.length>=t.length&&s.slice(0,t.length)===t&&(o+=l[u[n]],s=s.slice(t.length,s.length),e=!0)})),e||(o+=s.slice(0,1),s=s.slice(1,s.length))};s;)c();return o},latexSymbols={Alpha:"A",alpha:"\\alpha",Beta:"B",beta:"\\beta",Gamma:"\\Gamma",gamma:"\\gamma",Delta:"\\Delta",delta:"\\delta",Epsilon:"E",epsilon:"\\epsilon",varepsilon:"\\varepsilon",Zeta:"Z",zeta:"\\zeta",Eta:"H",eta:"\\eta",Theta:"\\Theta",theta:"\\theta",vartheta:"\\vartheta",Iota:"I",iota:"\\iota",Kappa:"K",kappa:"\\kappa",varkappa:"\\varkappa",Lambda:"\\Lambda",lambda:"\\lambda",Mu:"M",mu:"\\mu",Nu:"N",nu:"\\nu",Xi:"\\Xi",xi:"\\xi",Omicron:"O",omicron:"o",Pi:"\\Pi",pi:"\\pi",varpi:"\\varpi",Rho:"P",rho:"\\rho",varrho:"\\varrho",Sigma:"\\Sigma",sigma:"\\sigma",varsigma:"\\varsigma",Tau:"T",tau:"\\tau",Upsilon:"\\Upsilon",upsilon:"\\upsilon",Phi:"\\Phi",phi:"\\phi",varphi:"\\varphi",Chi:"X",chi:"\\chi",Psi:"\\Psi",psi:"\\psi",Omega:"\\Omega",omega:"\\omega",true:"\\mathrm{True}",false:"\\mathrm{False}",i:"i",inf:"\\infty",Inf:"\\infty",infinity:"\\infty",Infinity:"\\infty",oo:"\\infty",lim:"\\lim",undefined:"\\mathbf{?}"},latexOperators={transpose:"^\\top",ctranspose:"^H",factorial:"!",pow:"^",dotPow:".^\\wedge",unaryPlus:"+",unaryMinus:"-",bitNot:"\\~",not:"\\neg",multiply:"\\cdot",divide:"\\frac",dotMultiply:".\\cdot",dotDivide:".:",mod:"\\mod",add:"+",subtract:"-",to:"\\rightarrow",leftShift:"<<",rightArithShift:">>",rightLogShift:">>>",equal:"=",unequal:"\\neq",smaller:"<",larger:">",smallerEq:"\\leq",largerEq:"\\geq",bitAnd:"\\&",bitXor:"\\underline{|}",bitOr:"|",and:"\\wedge",xor:"\\veebar",or:"\\vee"},latexFunctions={abs:{1:"\\left|${args[0]}\\right|"},add:{2:"\\left(${args[0]}".concat(latexOperators.add,"${args[1]}\\right)")},cbrt:{1:"\\sqrt[3]{${args[0]}}"},ceil:{1:"\\left\\lceil${args[0]}\\right\\rceil"},cube:{1:"\\left(${args[0]}\\right)^3"},divide:{2:"\\frac{${args[0]}}{${args[1]}}"},dotDivide:{2:"\\left(${args[0]}".concat(latexOperators.dotDivide,"${args[1]}\\right)")},dotMultiply:{2:"\\left(${args[0]}".concat(latexOperators.dotMultiply,"${args[1]}\\right)")},dotPow:{2:"\\left(${args[0]}".concat(latexOperators.dotPow,"${args[1]}\\right)")},exp:{1:"\\exp\\left(${args[0]}\\right)"},expm1:"\\left(e".concat(latexOperators.pow,"{${args[0]}}-1\\right)"),fix:{1:"\\mathrm{${name}}\\left(${args[0]}\\right)"},floor:{1:"\\left\\lfloor${args[0]}\\right\\rfloor"},gcd:"\\gcd\\left(${args}\\right)",hypot:"\\hypot\\left(${args}\\right)",log:{1:"\\ln\\left(${args[0]}\\right)",2:"\\log_{${args[1]}}\\left(${args[0]}\\right)"},log10:{1:"\\log_{10}\\left(${args[0]}\\right)"},log1p:{1:"\\ln\\left(${args[0]}+1\\right)",2:"\\log_{${args[1]}}\\left(${args[0]}+1\\right)"},log2:"\\log_{2}\\left(${args[0]}\\right)",mod:{2:"\\left(${args[0]}".concat(latexOperators.mod,"${args[1]}\\right)")},multiply:{2:"\\left(${args[0]}".concat(latexOperators.multiply,"${args[1]}\\right)")},norm:{1:"\\left\\|${args[0]}\\right\\|",2:void 0},nthRoot:{2:"\\sqrt[${args[1]}]{${args[0]}}"},nthRoots:{2:"\\{y : $y^{args[1]} = {${args[0]}}\\}"},pow:{2:"\\left(${args[0]}\\right)".concat(latexOperators.pow,"{${args[1]}}")},round:{1:"\\left\\lfloor${args[0]}\\right\\rceil",2:void 0},sign:{1:"\\mathrm{${name}}\\left(${args[0]}\\right)"},sqrt:{1:"\\sqrt{${args[0]}}"},square:{1:"\\left(${args[0]}\\right)^2"},subtract:{2:"\\left(${args[0]}".concat(latexOperators.subtract,"${args[1]}\\right)")},unaryMinus:{1:"".concat(latexOperators.unaryMinus,"\\left(${args[0]}\\right)")},unaryPlus:{1:"".concat(latexOperators.unaryPlus,"\\left(${args[0]}\\right)")},bitAnd:{2:"\\left(${args[0]}".concat(latexOperators.bitAnd,"${args[1]}\\right)")},bitNot:{1:latexOperators.bitNot+"\\left(${args[0]}\\right)"},bitOr:{2:"\\left(${args[0]}".concat(latexOperators.bitOr,"${args[1]}\\right)")},bitXor:{2:"\\left(${args[0]}".concat(latexOperators.bitXor,"${args[1]}\\right)")},leftShift:{2:"\\left(${args[0]}".concat(latexOperators.leftShift,"${args[1]}\\right)")},rightArithShift:{2:"\\left(${args[0]}".concat(latexOperators.rightArithShift,"${args[1]}\\right)")},rightLogShift:{2:"\\left(${args[0]}".concat(latexOperators.rightLogShift,"${args[1]}\\right)")},bellNumbers:{1:"\\mathrm{B}_{${args[0]}}"},catalan:{1:"\\mathrm{C}_{${args[0]}}"},stirlingS2:{2:"\\mathrm{S}\\left(${args}\\right)"},arg:{1:"\\arg\\left(${args[0]}\\right)"},conj:{1:"\\left(${args[0]}\\right)^*"},im:{1:"\\Im\\left\\lbrace${args[0]}\\right\\rbrace"},re:{1:"\\Re\\left\\lbrace${args[0]}\\right\\rbrace"},and:{2:"\\left(${args[0]}".concat(latexOperators.and,"${args[1]}\\right)")},not:{1:latexOperators.not+"\\left(${args[0]}\\right)"},or:{2:"\\left(${args[0]}".concat(latexOperators.or,"${args[1]}\\right)")},xor:{2:"\\left(${args[0]}".concat(latexOperators.xor,"${args[1]}\\right)")},cross:{2:"\\left(${args[0]}\\right)\\times\\left(${args[1]}\\right)"},ctranspose:{1:"\\left(${args[0]}\\right)".concat(latexOperators.ctranspose)},det:{1:"\\det\\left(${args[0]}\\right)"},dot:{2:"\\left(${args[0]}\\cdot${args[1]}\\right)"},expm:{1:"\\exp\\left(${args[0]}\\right)"},inv:{1:"\\left(${args[0]}\\right)^{-1}"},pinv:{1:"\\left(${args[0]}\\right)^{+}"},sqrtm:{1:"{${args[0]}}".concat(latexOperators.pow,"{\\frac{1}{2}}")},trace:{1:"\\mathrm{tr}\\left(${args[0]}\\right)"},transpose:{1:"\\left(${args[0]}\\right)".concat(latexOperators.transpose)},combinations:{2:"\\binom{${args[0]}}{${args[1]}}"},combinationsWithRep:{2:"\\left(\\!\\!{\\binom{${args[0]}}{${args[1]}}}\\!\\!\\right)"},factorial:{1:"\\left(${args[0]}\\right)".concat(latexOperators.factorial)},gamma:{1:"\\Gamma\\left(${args[0]}\\right)"},lgamma:{1:"\\ln\\Gamma\\left(${args[0]}\\right)"},equal:{2:"\\left(${args[0]}".concat(latexOperators.equal,"${args[1]}\\right)")},larger:{2:"\\left(${args[0]}".concat(latexOperators.larger,"${args[1]}\\right)")},largerEq:{2:"\\left(${args[0]}".concat(latexOperators.largerEq,"${args[1]}\\right)")},smaller:{2:"\\left(${args[0]}".concat(latexOperators.smaller,"${args[1]}\\right)")},smallerEq:{2:"\\left(${args[0]}".concat(latexOperators.smallerEq,"${args[1]}\\right)")},unequal:{2:"\\left(${args[0]}".concat(latexOperators.unequal,"${args[1]}\\right)")},erf:{1:"erf\\left(${args[0]}\\right)"},max:"\\max\\left(${args}\\right)",min:"\\min\\left(${args}\\right)",variance:"\\mathrm{Var}\\left(${args}\\right)",acos:{1:"\\cos^{-1}\\left(${args[0]}\\right)"},acosh:{1:"\\cosh^{-1}\\left(${args[0]}\\right)"},acot:{1:"\\cot^{-1}\\left(${args[0]}\\right)"},acoth:{1:"\\coth^{-1}\\left(${args[0]}\\right)"},acsc:{1:"\\csc^{-1}\\left(${args[0]}\\right)"},acsch:{1:"\\mathrm{csch}^{-1}\\left(${args[0]}\\right)"},asec:{1:"\\sec^{-1}\\left(${args[0]}\\right)"},asech:{1:"\\mathrm{sech}^{-1}\\left(${args[0]}\\right)"},asin:{1:"\\sin^{-1}\\left(${args[0]}\\right)"},asinh:{1:"\\sinh^{-1}\\left(${args[0]}\\right)"},atan:{1:"\\tan^{-1}\\left(${args[0]}\\right)"},atan2:{2:"\\mathrm{atan2}\\left(${args}\\right)"},atanh:{1:"\\tanh^{-1}\\left(${args[0]}\\right)"},cos:{1:"\\cos\\left(${args[0]}\\right)"},cosh:{1:"\\cosh\\left(${args[0]}\\right)"},cot:{1:"\\cot\\left(${args[0]}\\right)"},coth:{1:"\\coth\\left(${args[0]}\\right)"},csc:{1:"\\csc\\left(${args[0]}\\right)"},csch:{1:"\\mathrm{csch}\\left(${args[0]}\\right)"},sec:{1:"\\sec\\left(${args[0]}\\right)"},sech:{1:"\\mathrm{sech}\\left(${args[0]}\\right)"},sin:{1:"\\sin\\left(${args[0]}\\right)"},sinh:{1:"\\sinh\\left(${args[0]}\\right)"},tan:{1:"\\tan\\left(${args[0]}\\right)"},tanh:{1:"\\tanh\\left(${args[0]}\\right)"},to:{2:"\\left(${args[0]}".concat(latexOperators.to,"${args[1]}\\right)")},numeric:function(e,t){return e.args[0].toTex()},number:{0:"0",1:"\\left(${args[0]}\\right)",2:"\\left(\\left(${args[0]}\\right)${args[1]}\\right)"},string:{0:'\\mathtt{""}',1:"\\mathrm{string}\\left(${args[0]}\\right)"},bignumber:{0:"0",1:"\\left(${args[0]}\\right)"},complex:{0:"0",1:"\\left(${args[0]}\\right)",2:"\\left(\\left(${args[0]}\\right)+".concat(latexSymbols.i,"\\cdot\\left(${args[1]}\\right)\\right)")},matrix:{0:"\\begin{bmatrix}\\end{bmatrix}",1:"\\left(${args[0]}\\right)",2:"\\left(${args[0]}\\right)"},sparse:{0:"\\begin{bsparse}\\end{bsparse}",1:"\\left(${args[0]}\\right)"},unit:{1:"\\left(${args[0]}\\right)",2:"\\left(\\left(${args[0]}\\right)${args[1]}\\right)"}},defaultTemplate="\\mathrm{${name}}\\left(${args}\\right)",latexUnits={deg:"^\\circ"};function escapeLatex(e){return dist(e,{preserveFormatting:!0})}function toSymbol(e,t){return(t=void 0!==t&&t)?hasOwnProperty$2(latexUnits,e)?latexUnits[e]:"\\mathrm{"+escapeLatex(e)+"}":hasOwnProperty$2(latexSymbols,e)?latexSymbols[e]:escapeLatex(e)}var name$1o="ConstantNode",dependencies$1o=["Node"],createConstantNode=factory(name$1o,dependencies$1o,(e=>{var{Node:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");this.value=e}return n.prototype=new t,n.prototype.type="ConstantNode",n.prototype.isConstantNode=!0,n.prototype._compile=function(e,t){var n=this.value;return function(){return n}},n.prototype.forEach=function(e){},n.prototype.map=function(e){return this.clone()},n.prototype.clone=function(){return new n(this.value)},n.prototype._toString=function(e){return format$1(this.value,e)},n.prototype.toHTML=function(e){var t=this._toString(e);switch(typeOf$1(this.value)){case"number":case"BigNumber":case"Fraction":return''+t+"";case"string":return''+t+"";case"boolean":return''+t+"";case"null":return''+t+"";case"undefined":return''+t+"";default:return''+t+""}},n.prototype.toJSON=function(){return{mathjs:"ConstantNode",value:this.value}},n.fromJSON=function(e){return new n(e.value)},n.prototype._toTex=function(e){var t=this._toString(e);switch(typeOf$1(this.value)){case"string":return"\\mathtt{"+escapeLatex(t)+"}";case"number":case"BigNumber":if(!isFinite(this.value))return this.value.valueOf()<0?"-\\infty":"\\infty";var n=t.toLowerCase().indexOf("e");return-1!==n?t.substring(0,n)+"\\cdot10^{"+t.substring(n+1)+"}":t;case"Fraction":return this.value.toLatex();default:return t}},n}),{isClass:!0,isNode:!0}),name$1n="FunctionAssignmentNode",dependencies$1n=["typed","Node"],createFunctionAssignmentNode=factory(name$1n,dependencies$1n,(e=>{var{typed:t,Node:n}=e;function r(e,t,n){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");if("string"!=typeof e)throw new TypeError('String expected for parameter "name"');if(!Array.isArray(t))throw new TypeError('Array containing strings or objects expected for parameter "params"');if(!isNode(n))throw new TypeError('Node expected for parameter "expr"');if(keywords.has(e))throw new Error('Illegal function name, "'+e+'" is a reserved keyword');this.name=e,this.params=t.map((function(e){return e&&e.name||e})),this.types=t.map((function(e){return e&&e.type||"any"})),this.expr=n}function a(e,t){var n=getPrecedence(e,t),r=getPrecedence(e.expr,t);return"all"===t||null!==r&&r<=n}return r.prototype=new n,r.prototype.type="FunctionAssignmentNode",r.prototype.isFunctionAssignmentNode=!0,r.prototype._compile=function(e,n){var r=Object.create(n);forEach$1(this.params,(function(e){r[e]=!0}));var a=this.expr._compile(e,r),i=this.name,s=this.params,o=join(this.types,","),l=i+"("+join(this.params,", ")+")";return function(e,n,r){var u={};u[o]=function(){for(var t=Object.create(n),i=0;i'+escape$1(this.params[r])+"");var i=this.expr.toHTML(e);return a(this,t)&&(i='('+i+')'),''+escape$1(this.name)+'('+n.join(',')+')='+i},r.prototype._toTex=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=this.expr.toTex(e);return a(this,t)&&(n="\\left(".concat(n,"\\right)")),"\\mathrm{"+this.name+"}\\left("+this.params.map(toSymbol).join(",")+"\\right):="+n},r}),{isClass:!0,isNode:!0}),name$1m="IndexNode",dependencies$1m=["Node","size"],createIndexNode=factory(name$1m,dependencies$1m,(e=>{var{Node:t,size:n}=e;function r(e,t){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");if(this.dimensions=e,this.dotNotation=t||!1,!Array.isArray(e)||!e.every(isNode))throw new TypeError('Array containing Nodes expected for parameter "dimensions"');if(this.dotNotation&&!this.isObjectProperty())throw new Error("dotNotation only applicable for object properties")}return r.prototype=new t,r.prototype.type="IndexNode",r.prototype.isIndexNode=!0,r.prototype._compile=function(e,t){var r=map$2(this.dimensions,(function(r,a){if(r.filter((e=>e.isSymbolNode&&"end"===e.name)).length>0){var i=Object.create(t);i.end=!0;var s=r._compile(e,i);return function(e,t,r){if(!isMatrix(r)&&!isArray$1(r)&&!isString$1(r))throw new TypeError('Cannot resolve "end": context must be a Matrix, Array, or string but is '+typeOf$1(r));var i=n(r).valueOf(),o=Object.create(t);return o.end=i[a],s(e,o,r)}}return r._compile(e,t)})),a=getSafeProperty(e,"index");return function(e,t,n){var i=map$2(r,(function(r){return r(e,t,n)}));return a(...i)}},r.prototype.forEach=function(e){for(var t=0;t.'+escape$1(this.getObjectProperty())+"":'['+t.join(',')+']'},r.prototype._toTex=function(e){var t=this.dimensions.map((function(t){return t.toTex(e)}));return this.dotNotation?"."+this.getObjectProperty():"_{"+t.join(",")+"}"},r}),{isClass:!0,isNode:!0}),name$1l="ObjectNode",dependencies$1l=["Node"],createObjectNode=factory(name$1l,dependencies$1l,(e=>{var{Node:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(this.properties=e||{},e&&("object"!=typeof e||!Object.keys(e).every((function(t){return isNode(e[t])}))))throw new TypeError("Object containing Nodes expected")}return n.prototype=new t,n.prototype.type="ObjectNode",n.prototype.isObjectNode=!0,n.prototype._compile=function(e,t){var n={};for(var r in this.properties)if(hasOwnProperty$2(this.properties,r)){var a=stringify(r),i=JSON.parse(a);if(!isSafeProperty(this.properties,i))throw new Error('No access to property "'+i+'"');n[i]=this.properties[r]._compile(e,t)}return function(e,t,r){var a={};for(var i in n)hasOwnProperty$2(n,i)&&(a[i]=n[i](e,t,r));return a}},n.prototype.forEach=function(e){for(var t in this.properties)hasOwnProperty$2(this.properties,t)&&e(this.properties[t],"properties["+stringify(t)+"]",this)},n.prototype.map=function(e){var t={};for(var r in this.properties)hasOwnProperty$2(this.properties,r)&&(t[r]=this._ifNode(e(this.properties[r],"properties["+stringify(r)+"]",this)));return new n(t)},n.prototype.clone=function(){var e={};for(var t in this.properties)hasOwnProperty$2(this.properties,t)&&(e[t]=this.properties[t]);return new n(e)},n.prototype._toString=function(e){var t=[];for(var n in this.properties)hasOwnProperty$2(this.properties,n)&&t.push(stringify(n)+": "+this.properties[n].toString(e));return"{"+t.join(", ")+"}"},n.prototype.toJSON=function(){return{mathjs:"ObjectNode",properties:this.properties}},n.fromJSON=function(e){return new n(e.properties)},n.prototype.toHTML=function(e){var t=[];for(var n in this.properties)hasOwnProperty$2(this.properties,n)&&t.push(''+escape$1(n)+':'+this.properties[n].toHTML(e));return'{'+t.join(',')+'}'},n.prototype._toTex=function(e){var t=[];for(var n in this.properties)hasOwnProperty$2(this.properties,n)&&t.push("\\mathbf{"+n+":} & "+this.properties[n].toTex(e)+"\\\\");return"\\left\\{\\begin{array}{ll}".concat(t.join("\n"),"\\end{array}\\right\\}")},n}),{isClass:!0,isNode:!0}),name$1k="OperatorNode",dependencies$1k=["Node"],createOperatorNode=factory(name$1k,dependencies$1k,(e=>{var{Node:t}=e;function n(e,t,r,a,i){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if("string"!=typeof e)throw new TypeError('string expected for parameter "op"');if("string"!=typeof t)throw new TypeError('string expected for parameter "fn"');if(!Array.isArray(r)||!r.every(isNode))throw new TypeError('Array containing Nodes expected for parameter "args"');this.implicit=!0===a,this.isPercentage=!0===i,this.op=e,this.fn=t,this.args=r||[]}function r(e,t,n,r,a){var i,s=getPrecedence(e,t),o=getAssociativity(e,t);if("all"===t||r.length>2&&"OperatorNode:add"!==e.getIdentifier()&&"OperatorNode:multiply"!==e.getIdentifier())return r.map((function(e){switch(e.getContent().type){case"ArrayNode":case"ConstantNode":case"SymbolNode":case"ParenthesisNode":return!1;default:return!0}}));switch(r.length){case 0:i=[];break;case 1:var l=getPrecedence(r[0],t);if(a&&null!==l){var u,c;if("keep"===t?(u=r[0].getIdentifier(),c=e.getIdentifier()):(u=r[0].getContent().getIdentifier(),c=e.getContent().getIdentifier()),!1===properties[s][c].latexLeftParens){i=[!1];break}if(!1===properties[l][u].latexParens){i=[!1];break}}if(null===l){i=[!1];break}if(l<=s){i=[!0];break}i=[!1];break;case 2:var p,d,m=getPrecedence(r[0],t),h=isAssociativeWith(e,r[0],t);p=null!==m&&(m===s&&"right"===o&&!h||m=2&&"OperatorNode:multiply"===e.getIdentifier()&&e.implicit&&"auto"===t&&"hide"===n&&(i=r.map((function(e,t){var n="ParenthesisNode"===e.getIdentifier();return!(!i[t]&&!n)}))),i}return n.prototype=new t,n.prototype.type="OperatorNode",n.prototype.isOperatorNode=!0,n.prototype._compile=function(e,t){if("string"!=typeof this.fn||!isSafeMethod(e,this.fn))throw e[this.fn]?new Error('No access to function "'+this.fn+'"'):new Error("Function "+this.fn+' missing in provided namespace "math"');var n=getSafeProperty(e,this.fn),r=map$2(this.args,(function(n){return n._compile(e,t)}));if(1===r.length){var a=r[0];return function(e,t,r){return n(a(e,t,r))}}if(2===r.length){var i=r[0],s=r[1];return function(e,t,r){return n(i(e,t,r),s(e,t,r))}}return function(e,t,a){return n.apply(null,map$2(r,(function(n){return n(e,t,a)})))}},n.prototype.forEach=function(e){for(var t=0;t2&&("OperatorNode:add"===this.getIdentifier()||"OperatorNode:multiply"===this.getIdentifier())){var p=a.map((function(t,n){return t=t.toString(e),i[n]&&(t="("+t+")"),t}));return this.implicit&&"OperatorNode:multiply"===this.getIdentifier()&&"hide"===n?p.join(" "):p.join(" "+this.op+" ")}return this.fn+"("+this.args.join(", ")+")"},n.prototype.toJSON=function(){return{mathjs:"OperatorNode",op:this.op,fn:this.fn,args:this.args,implicit:this.implicit,isPercentage:this.isPercentage}},n.fromJSON=function(e){return new n(e.op,e.fn,e.args,e.implicit,e.isPercentage)},n.prototype.toHTML=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=e&&e.implicit?e.implicit:"hide",a=this.args,i=r(this,t,n,a,!1);if(1===a.length){var s=getAssociativity(this,t),o=a[0].toHTML(e);return i[0]&&(o='('+o+')'),"right"===s?''+escape$1(this.op)+""+o:o+''+escape$1(this.op)+""}if(2===a.length){var l=a[0].toHTML(e),u=a[1].toHTML(e);return i[0]&&(l='('+l+')'),i[1]&&(u='('+u+')'),this.implicit&&"OperatorNode:multiply"===this.getIdentifier()&&"hide"===n?l+''+u:l+''+escape$1(this.op)+""+u}var c=a.map((function(t,n){return t=t.toHTML(e),i[n]&&(t='('+t+')'),t}));return a.length>2&&("OperatorNode:add"===this.getIdentifier()||"OperatorNode:multiply"===this.getIdentifier())?this.implicit&&"OperatorNode:multiply"===this.getIdentifier()&&"hide"===n?c.join(''):c.join(''+escape$1(this.op)+""):''+escape$1(this.fn)+'('+c.join(',')+')'},n.prototype._toTex=function(e){var t=e&&e.parenthesis?e.parenthesis:"keep",n=e&&e.implicit?e.implicit:"hide",a=this.args,i=r(this,t,n,a,!0),s=latexOperators[this.fn];if(s=void 0===s?this.op:s,1===a.length){var o=getAssociativity(this,t),l=a[0].toTex(e);return i[0]&&(l="\\left(".concat(l,"\\right)")),"right"===o?s+l:l+s}if(2===a.length){var u=a[0],c=u.toTex(e);i[0]&&(c="\\left(".concat(c,"\\right)"));var p,d=a[1].toTex(e);switch(i[1]&&(d="\\left(".concat(d,"\\right)")),p="keep"===t?u.getIdentifier():u.getContent().getIdentifier(),this.getIdentifier()){case"OperatorNode:divide":return s+"{"+c+"}{"+d+"}";case"OperatorNode:pow":switch(c="{"+c+"}",d="{"+d+"}",p){case"ConditionalNode":case"OperatorNode:divide":c="\\left(".concat(c,"\\right)")}break;case"OperatorNode:multiply":if(this.implicit&&"hide"===n)return c+"~"+d}return c+s+d}if(a.length>2&&("OperatorNode:add"===this.getIdentifier()||"OperatorNode:multiply"===this.getIdentifier())){var m=a.map((function(t,n){return t=t.toTex(e),i[n]&&(t="\\left(".concat(t,"\\right)")),t}));return"OperatorNode:multiply"===this.getIdentifier()&&this.implicit?m.join("~"):m.join(s)}return"\\mathrm{"+this.fn+"}\\left("+a.map((function(t){return t.toTex(e)})).join(",")+"\\right)"},n.prototype.getIdentifier=function(){return this.type+":"+this.fn},n}),{isClass:!0,isNode:!0}),name$1j="ParenthesisNode",dependencies$1j=["Node"],createParenthesisNode=factory(name$1j,dependencies$1j,(e=>{var{Node:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!isNode(e))throw new TypeError('Node expected for parameter "content"');this.content=e}return n.prototype=new t,n.prototype.type="ParenthesisNode",n.prototype.isParenthesisNode=!0,n.prototype._compile=function(e,t){return this.content._compile(e,t)},n.prototype.getContent=function(){return this.content.getContent()},n.prototype.forEach=function(e){e(this.content,"content",this)},n.prototype.map=function(e){return new n(e(this.content,"content",this))},n.prototype.clone=function(){return new n(this.content)},n.prototype._toString=function(e){return!e||e&&!e.parenthesis||e&&"keep"===e.parenthesis?"("+this.content.toString(e)+")":this.content.toString(e)},n.prototype.toJSON=function(){return{mathjs:"ParenthesisNode",content:this.content}},n.fromJSON=function(e){return new n(e.content)},n.prototype.toHTML=function(e){return!e||e&&!e.parenthesis||e&&"keep"===e.parenthesis?'('+this.content.toHTML(e)+')':this.content.toHTML(e)},n.prototype._toTex=function(e){return!e||e&&!e.parenthesis||e&&"keep"===e.parenthesis?"\\left(".concat(this.content.toTex(e),"\\right)"):this.content.toTex(e)},n}),{isClass:!0,isNode:!0}),name$1i="RangeNode",dependencies$1i=["Node"],createRangeNode=factory(name$1i,dependencies$1i,(e=>{var{Node:t}=e;function n(e,t,r){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!isNode(e))throw new TypeError("Node expected");if(!isNode(t))throw new TypeError("Node expected");if(r&&!isNode(r))throw new TypeError("Node expected");if(arguments.length>3)throw new Error("Too many arguments");this.start=e,this.end=t,this.step=r||null}function r(e,t){var n=getPrecedence(e,t),r={},a=getPrecedence(e.start,t);if(r.start=null!==a&&a<=n||"all"===t,e.step){var i=getPrecedence(e.step,t);r.step=null!==i&&i<=n||"all"===t}var s=getPrecedence(e.end,t);return r.end=null!==s&&s<=n||"all"===t,r}return n.prototype=new t,n.prototype.type="RangeNode",n.prototype.isRangeNode=!0,n.prototype.needsEnd=function(){return this.filter((function(e){return isSymbolNode(e)&&"end"===e.name})).length>0},n.prototype._compile=function(e,t){var n=e.range,r=this.start._compile(e,t),a=this.end._compile(e,t);if(this.step){var i=this.step._compile(e,t);return function(e,t,s){return n(r(e,t,s),a(e,t,s),i(e,t,s))}}return function(e,t,i){return n(r(e,t,i),a(e,t,i))}},n.prototype.forEach=function(e){e(this.start,"start",this),e(this.end,"end",this),this.step&&e(this.step,"step",this)},n.prototype.map=function(e){return new n(this._ifNode(e(this.start,"start",this)),this._ifNode(e(this.end,"end",this)),this.step&&this._ifNode(e(this.step,"step",this)))},n.prototype.clone=function(){return new n(this.start,this.end,this.step&&this.step)},n.prototype._toString=function(e){var t,n=r(this,e&&e.parenthesis?e.parenthesis:"keep"),a=this.start.toString(e);if(n.start&&(a="("+a+")"),t=a,this.step){var i=this.step.toString(e);n.step&&(i="("+i+")"),t+=":"+i}var s=this.end.toString(e);return n.end&&(s="("+s+")"),t+":"+s},n.prototype.toJSON=function(){return{mathjs:"RangeNode",start:this.start,end:this.end,step:this.step}},n.fromJSON=function(e){return new n(e.start,e.end,e.step)},n.prototype.toHTML=function(e){var t,n=r(this,e&&e.parenthesis?e.parenthesis:"keep"),a=this.start.toHTML(e);if(n.start&&(a='('+a+')'),t=a,this.step){var i=this.step.toHTML(e);n.step&&(i='('+i+')'),t+=':'+i}var s=this.end.toHTML(e);return n.end&&(s='('+s+')'),t+':'+s},n.prototype._toTex=function(e){var t=r(this,e&&e.parenthesis?e.parenthesis:"keep"),n=this.start.toTex(e);if(t.start&&(n="\\left(".concat(n,"\\right)")),this.step){var a=this.step.toTex(e);t.step&&(a="\\left(".concat(a,"\\right)")),n+=":"+a}var i=this.end.toTex(e);return t.end&&(i="\\left(".concat(i,"\\right)")),n+":"+i},n}),{isClass:!0,isNode:!0}),name$1h="RelationalNode",dependencies$1h=["Node"],createRelationalNode=factory(name$1h,dependencies$1h,(e=>{var{Node:t}=e;function n(e,t){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!Array.isArray(e))throw new TypeError("Parameter conditionals must be an array");if(!Array.isArray(t))throw new TypeError("Parameter params must be an array");if(e.length!==t.length-1)throw new TypeError("Parameter params must contain exactly one more element than parameter conditionals");this.conditionals=e,this.params=t}return n.prototype=new t,n.prototype.type="RelationalNode",n.prototype.isRelationalNode=!0,n.prototype._compile=function(e,t){var n=this,r=this.params.map((n=>n._compile(e,t)));return function(t,a,i){for(var s,o=r[0](t,a,i),l=0;le(t,"params["+n+"]",this)),this)},n.prototype.map=function(e){return new n(this.conditionals.slice(),this.params.map(((t,n)=>this._ifNode(e(t,"params["+n+"]",this))),this))},n.prototype.clone=function(){return new n(this.conditionals,this.params)},n.prototype._toString=function(e){for(var t=e&&e.parenthesis?e.parenthesis:"keep",n=getPrecedence(this,t),r=this.params.map((function(r,a){var i=getPrecedence(r,t);return"all"===t||null!==i&&i<=n?"("+r.toString(e)+")":r.toString(e)})),a={equal:"==",unequal:"!=",smaller:"<",larger:">",smallerEq:"<=",largerEq:">="},i=r[0],s=0;s('+r.toHTML(e)+')':r.toHTML(e)})),a={equal:"==",unequal:"!=",smaller:"<",larger:">",smallerEq:"<=",largerEq:">="},i=r[0],s=0;s'+escape$1(a[this.conditionals[s]])+""+r[s+1];return i},n.prototype._toTex=function(e){for(var t=e&&e.parenthesis?e.parenthesis:"keep",n=getPrecedence(this,t),r=this.params.map((function(r,a){var i=getPrecedence(r,t);return"all"===t||null!==i&&i<=n?"\\left("+r.toTex(e)+"\right)":r.toTex(e)})),a=r[0],i=0;i{var{math:t,Unit:n,Node:r}=e;function a(e){return!!n&&n.isValuelessUnit(e)}function i(e){if(!(this instanceof i))throw new SyntaxError("Constructor must be called with the new operator");if("string"!=typeof e)throw new TypeError('String expected for parameter "name"');this.name=e}return i.prototype=new r,i.prototype.type="SymbolNode",i.prototype.isSymbolNode=!0,i.prototype._compile=function(e,t){var r=this.name;if(!0===t[r])return function(e,t,n){return t[r]};if(r in e)return function(t,n,a){return t.has(r)?t.get(r):getSafeProperty(e,r)};var s=a(r);return function(e,t,a){return e.has(r)?e.get(r):s?new n(null,r):i.onUndefinedSymbol(r)}},i.prototype.forEach=function(e){},i.prototype.map=function(e){return this.clone()},i.onUndefinedSymbol=function(e){throw new Error("Undefined symbol "+e)},i.prototype.clone=function(){return new i(this.name)},i.prototype._toString=function(e){return this.name},i.prototype.toHTML=function(e){var t=escape$1(this.name);return"true"===t||"false"===t?''+t+"":"i"===t?''+t+"":"Infinity"===t?''+t+"":"NaN"===t?''+t+"":"null"===t?''+t+"":"undefined"===t?''+t+"":''+t+""},i.prototype.toJSON=function(){return{mathjs:"SymbolNode",name:this.name}},i.fromJSON=function(e){return new i(e.name)},i.prototype._toTex=function(e){var n=!1;void 0===t[this.name]&&a(this.name)&&(n=!0);var r=toSymbol(this.name,n);return"\\"===r[0]?r:" "+r},i}),{isClass:!0,isNode:!0});function createSubScope(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r{var{math:t,Node:n,SymbolNode:r}=e;function a(e,t){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");if("string"==typeof e&&(e=new r(e)),!isNode(e))throw new TypeError('Node expected as parameter "fn"');if(!Array.isArray(t)||!t.every(isNode))throw new TypeError('Array containing Nodes expected for parameter "args"');this.fn=e,this.args=t||[],Object.defineProperty(this,"name",{get:function(){return this.fn.name||""}.bind(this),set:function(){throw new Error("Cannot assign a new name, name is read-only")}})}a.prototype=new n,a.prototype.type="FunctionNode",a.prototype.isFunctionNode=!0;var i=e=>format$1(e,{truncate:78});a.prototype._compile=function(e,t){if(!(this instanceof a))throw new TypeError("No valid FunctionNode");var n=this.args.map((n=>n._compile(e,t)));if(!isSymbolNode(this.fn)){if(isAccessorNode(this.fn)&&isIndexNode(this.fn.index)&&this.fn.index.isObjectProperty()){var r=this.fn.object._compile(e,t),s=this.fn.index.getObjectProperty(),o=this.args;return function(t,a,i){var l=r(t,a,i);if(validateSafeMethod(l,s),l[s]&&l[s].rawArgs)return l[s](o,e,createSubScope(t,a),t);var u=n.map((e=>e(t,a,i)));return l[s].apply(l,u)}}var l=this.fn.toString(),u=this.fn._compile(e,t),c=this.args;return function(t,r,a){var s=u(t,r,a);if("function"!=typeof s)throw new TypeError("Expression '".concat(l,"' did not evaluate to a function; value is:")+"\n ".concat(i(s)));if(s.rawArgs)return s(c,e,createSubScope(t,r),t);var o=n.map((e=>e(t,r,a)));return s.apply(s,o)}}var p=this.fn.name;if(t[p]){var d=this.args;return function(t,r,a){var s=r[p];if("function"!=typeof s)throw new TypeError("Argument '".concat(p,"' was not a function; received: ").concat(i(s)));if(s.rawArgs)return s(d,e,createSubScope(t,r),t);var o=n.map((e=>e(t,r,a)));return s.apply(s,o)}}var m=p in e?getSafeProperty(e,p):void 0,h="function"==typeof m&&!0===m.rawArgs,f=t=>{var n;if(t.has(p))n=t.get(p);else{if(!(p in e))return a.onUndefinedFunction(p);n=getSafeProperty(e,p)}if("function"==typeof n)return n;throw new TypeError("'".concat(p,"' is not a function; its value is:\n ").concat(i(n)))};if(h){var y=this.args;return function(t,n,r){return f(t)(y,e,createSubScope(t,n),t)}}switch(n.length){case 0:return function(e,t,n){return f(e)()};case 1:return function(e,t,r){return f(e)((0,n[0])(e,t,r))};case 2:return function(e,t,r){var a=f(e),i=n[0],s=n[1];return a(i(e,t,r),s(e,t,r))};default:return function(e,t,r){return f(e)(...n.map((n=>n(e,t,r))))}}},a.prototype.forEach=function(e){e(this.fn,"fn",this);for(var t=0;t'+escape$1(this.fn)+'('+t.join(',')+')'};var l=a.prototype.toTex;return a.prototype.toTex=function(e){var t;return e&&"object"==typeof e.handler&&hasOwnProperty$2(e.handler,this.name)&&(t=e.handler[this.name](this,e)),void 0!==t?t:l.call(this,e)},a.prototype._toTex=function(e){var n,r,a=this.args.map((function(t){return t.toTex(e)}));switch(latexFunctions[this.name]&&(n=latexFunctions[this.name]),!t[this.name]||"function"!=typeof t[this.name].toTex&&"object"!=typeof t[this.name].toTex&&"string"!=typeof t[this.name].toTex||(n=t[this.name].toTex),typeof n){case"function":r=n(this,e);break;case"string":r=o(n,this,e);break;case"object":switch(typeof n[a.length]){case"function":r=n[a.length](this,e);break;case"string":r=o(n[a.length],this,e)}}return void 0!==r?r:o(defaultTemplate,this,e)},a.prototype.getIdentifier=function(){return this.type+":"+this.name},a}),{isClass:!0,isNode:!0}),name$1e="parse",dependencies$1e=["typed","numeric","config","AccessorNode","ArrayNode","AssignmentNode","BlockNode","ConditionalNode","ConstantNode","FunctionAssignmentNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","RangeNode","RelationalNode","SymbolNode"],createParse=factory(name$1e,dependencies$1e,(e=>{var{typed:t,numeric:n,config:r,AccessorNode:a,ArrayNode:i,AssignmentNode:s,BlockNode:o,ConditionalNode:l,ConstantNode:u,FunctionAssignmentNode:c,FunctionNode:p,IndexNode:d,ObjectNode:m,OperatorNode:h,ParenthesisNode:f,RangeNode:y,RelationalNode:g,SymbolNode:b}=e,v=t(name$1e,{string:function(e){return B(e,{})},"Array | Matrix":function(e){return N(e,{})},"string, Object":function(e,t){return B(e,void 0!==t.nodes?t.nodes:{})},"Array | Matrix, Object":N});function N(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=void 0!==t.nodes?t.nodes:{};return deepMap(e,(function(e){if("string"!=typeof e)throw new TypeError("String expected");return B(e,n)}))}var T=0,C=1,A=2,V=3,x=4,S={",":!0,"(":!0,")":!0,"[":!0,"]":!0,"{":!0,"}":!0,'"':!0,"'":!0,";":!0,"+":!0,"-":!0,"*":!0,".*":!0,"/":!0,"./":!0,"%":!0,"^":!0,".^":!0,"~":!0,"!":!0,"&":!0,"|":!0,"^|":!0,"=":!0,":":!0,"?":!0,"==":!0,"!=":!0,"<":!0,">":!0,"<=":!0,">=":!0,"<<":!0,">>":!0,">>>":!0},w={mod:!0,to:!0,in:!0,and:!0,xor:!0,or:!0,not:!0},E={true:!0,false:!1,null:null,undefined:void 0},D=["NaN","Infinity"];function O(e,t){return e.expression.substr(e.index,t)}function I(e){return O(e,1)}function R(e){e.index++}function _(e){return e.expression.charAt(e.index-1)}function M(e){return e.expression.charAt(e.index+1)}function P(e){for(e.tokenType=T,e.token="",e.comment="";;){if("#"===I(e))for(;"\n"!==I(e)&&""!==I(e);)e.comment+=I(e),R(e);if(!v.isWhitespace(I(e),e.nestingLevel))break;R(e)}if(""!==I(e)){if("\n"===I(e)&&!e.nestingLevel)return e.tokenType=C,e.token=I(e),void R(e);var t=I(e),n=O(e,2),r=O(e,3);if(3===r.length&&S[r])return e.tokenType=C,e.token=r,R(e),R(e),void R(e);if(2===n.length&&S[n])return e.tokenType=C,e.token=n,R(e),void R(e);if(S[t])return e.tokenType=C,e.token=t,void R(e);if(v.isDigitDot(t)){e.tokenType=A;var a=O(e,2);if("0b"===a||"0o"===a||"0x"===a){for(e.token+=I(e),R(e),e.token+=I(e),R(e);v.isHexDigit(I(e));)e.token+=I(e),R(e);if("."===I(e))for(e.token+=".",R(e);v.isHexDigit(I(e));)e.token+=I(e),R(e);else if("i"===I(e))for(e.token+="i",R(e);v.isDigit(I(e));)e.token+=I(e),R(e);return}if("."===I(e)){if(e.token+=I(e),R(e),!v.isDigit(I(e)))return void(e.tokenType=C)}else{for(;v.isDigit(I(e));)e.token+=I(e),R(e);v.isDecimalMark(I(e),M(e))&&(e.token+=I(e),R(e))}for(;v.isDigit(I(e));)e.token+=I(e),R(e);if("E"===I(e)||"e"===I(e))if(v.isDigit(M(e))||"-"===M(e)||"+"===M(e)){if(e.token+=I(e),R(e),"+"!==I(e)&&"-"!==I(e)||(e.token+=I(e),R(e)),!v.isDigit(I(e)))throw oe(e,'Digit expected, got "'+I(e)+'"');for(;v.isDigit(I(e));)e.token+=I(e),R(e);if(v.isDecimalMark(I(e),M(e)))throw oe(e,'Digit expected, got "'+I(e)+'"')}else if("."===M(e))throw R(e),oe(e,'Digit expected, got "'+I(e)+'"')}else{if(!v.isAlpha(I(e),_(e),M(e))){for(e.tokenType=x;""!==I(e);)e.token+=I(e),R(e);throw oe(e,'Syntax error in part "'+e.token+'"')}for(;v.isAlpha(I(e),_(e),M(e))||v.isDigit(I(e));)e.token+=I(e),R(e);hasOwnProperty$2(w,e.token)?e.tokenType=C:e.tokenType=V}}else e.tokenType=C}function F(e){do{P(e)}while("\n"===e.token)}function k(e){e.nestingLevel++}function $(e){e.nestingLevel--}function B(e,t){var n={extraNodes:{},expression:"",comment:"",index:0,token:"",tokenType:T,nestingLevel:0,conditionalLevel:null};_extends$1(n,{expression:e,extraNodes:t}),P(n);var r=function(e){var t,n,r=[];for(""!==e.token&&"\n"!==e.token&&";"!==e.token&&((t=L(e)).comment=e.comment);"\n"===e.token||";"===e.token;)0===r.length&&t&&(n=";"!==e.token,r.push({node:t,visible:n})),P(e),"\n"!==e.token&&";"!==e.token&&""!==e.token&&((t=L(e)).comment=e.comment,n=";"!==e.token,r.push({node:t,visible:n}));return r.length>0?new o(r):(t||((t=new u(void 0)).comment=e.comment),t)}(n);if(""!==n.token)throw n.tokenType===C?le(n,"Unexpected operator "+n.token):oe(n,'Unexpected part "'+n.token+'"');return r}function L(e){var t,n,r,a,i=function(e){for(var t=function(e){for(var t=z(e);"or"===e.token;)F(e),t=new h("or","or",[t,z(e)]);return t}(e);"?"===e.token;){var n=e.conditionalLevel;e.conditionalLevel=e.nestingLevel,F(e);var r=t,a=L(e);if(":"!==e.token)throw oe(e,"False part of conditional expression expected");e.conditionalLevel=null,F(e);var i=L(e);t=new l(r,a,i),e.conditionalLevel=n}return t}(e);if("="===e.token){if(isSymbolNode(i))return t=i.name,F(e),r=L(e),new s(new b(t),r);if(isAccessorNode(i))return F(e),r=L(e),new s(i.object,i.index,r);if(isFunctionNode(i)&&isSymbolNode(i.fn)&&(a=!0,n=[],t=i.name,i.args.forEach((function(e,t){isSymbolNode(e)?n[t]=e.name:a=!1})),a))return F(e),r=L(e),new c(t,n,r);throw oe(e,"Invalid left hand side of assignment operator =")}return i}function z(e){for(var t=U(e);"xor"===e.token;)F(e),t=new h("xor","xor",[t,U(e)]);return t}function U(e){for(var t=j(e);"and"===e.token;)F(e),t=new h("and","and",[t,j(e)]);return t}function j(e){for(var t=q(e);"|"===e.token;)F(e),t=new h("|","bitOr",[t,q(e)]);return t}function q(e){for(var t=G(e);"^|"===e.token;)F(e),t=new h("^|","bitXor",[t,G(e)]);return t}function G(e){for(var t=H(e);"&"===e.token;)F(e),t=new h("&","bitAnd",[t,H(e)]);return t}function H(e){for(var t=[W(e)],n=[],r={"==":"equal","!=":"unequal","<":"smaller",">":"larger","<=":"smallerEq",">=":"largerEq"};hasOwnProperty$2(r,e.token);){var a={name:e.token,fn:r[e.token]};n.push(a),F(e),t.push(W(e))}return 1===t.length?t[0]:2===t.length?new h(n[0].name,n[0].fn,t):new g(n.map((e=>e.fn)),t)}function W(e){var t,n,r,a;t=K(e);for(var i={"<<":"leftShift",">>":"rightArithShift",">>>":"rightLogShift"};hasOwnProperty$2(i,e.token);)r=i[n=e.token],F(e),a=[t,K(e)],t=new h(n,r,a);return t}function K(e){var t,n,r,a;t=Z(e);for(var i={to:"to",in:"to"};hasOwnProperty$2(i,e.token);)r=i[n=e.token],F(e),"in"===n&&""===e.token?t=new h("*","multiply",[t,new b("in")],!0):(a=[t,Z(e)],t=new h(n,r,a));return t}function Z(e){var t,n=[];if(t=":"===e.token?new u(1):X(e),":"===e.token&&e.conditionalLevel!==e.nestingLevel){for(n.push(t);":"===e.token&&n.length<3;)F(e),")"===e.token||"]"===e.token||","===e.token||""===e.token?n.push(new b("end")):n.push(X(e));t=3===n.length?new y(n[0],n[2],n[1]):new y(n[0],n[1])}return t}function X(e){var t,n,r,a;t=Y(e);for(var i={"+":"add","-":"subtract"};hasOwnProperty$2(i,e.token);){r=i[n=e.token],F(e);var s=Y(e);a=s.isPercentage?[t,new h("*","multiply",[t,s])]:[t,s],t=new h(n,r,a)}return t}function Y(e){var t,n,r,a;n=t=Q(e);for(var i={"*":"multiply",".*":"dotMultiply","/":"divide","./":"dotDivide"};hasOwnProperty$2(i,e.token);)a=i[r=e.token],F(e),n=Q(e),t=new h(r,a,[t,n]);return t}function Q(e){var t,n;for(n=t=J(e);e.tokenType===V||"in"===e.token&&isConstantNode(t)||!(e.tokenType!==A||isConstantNode(n)||isOperatorNode(n)&&"!"!==n.op)||"("===e.token;)n=J(e),t=new h("*","multiply",[t,n],!0);return t}function J(e){for(var t=ee(e),n=t,r=[];"/"===e.token&&isConstantNode(n);){if(r.push(_extends$1({},e)),F(e),e.tokenType!==A){_extends$1(e,r.pop());break}if(r.push(_extends$1({},e)),F(e),e.tokenType!==V&&"("!==e.token){r.pop(),_extends$1(e,r.pop());break}_extends$1(e,r.pop()),r.pop(),n=ee(e),t=new h("/","divide",[t,n])}return t}function ee(e){var t,n,r,a;t=te(e);for(var i={"%":"mod",mod:"mod"};hasOwnProperty$2(i,e.token);)r=i[n=e.token],F(e),"%"===n&&e.tokenType===C&&"("!==e.token?t=new h("/","divide",[t,new u(100)],!1,!0):(a=[t,te(e)],t=new h(n,r,a));return t}function te(e){var t,a,s,o={"-":"unaryMinus","+":"unaryPlus","~":"bitNot",not:"not"};return hasOwnProperty$2(o,e.token)?(s=o[e.token],t=e.token,F(e),a=[te(e)],new h(t,s,a)):function(e){var t,a,s,o;return t=function(e){var t,a,s;t=function(e){var t=[];if(e.tokenType===V&&hasOwnProperty$2(e.extraNodes,e.token)){var a=e.extraNodes[e.token];if(P(e),"("===e.token){if(t=[],k(e),P(e),")"!==e.token)for(t.push(L(e));","===e.token;)P(e),t.push(L(e));if(")"!==e.token)throw oe(e,"Parenthesis ) expected");$(e),P(e)}return new a(t)}return function(e){var t;return e.tokenType===V||e.tokenType===C&&e.token in w?(t=e.token,P(e),ne(e,hasOwnProperty$2(E,t)?new u(E[t]):-1!==D.indexOf(t)?new u(n(t,"number")):new b(t))):function(e){var t;return'"'===e.token?(t=re(e),ne(e,new u(t))):function(e){var t;return"'"===e.token?(t=ae(e),ne(e,new u(t))):function(e){var t,a,s,o;if("["===e.token){if(k(e),P(e),"]"!==e.token){var l=ie(e);if(";"===e.token){for(s=1,a=[l];";"===e.token;)P(e),a[s]=ie(e),s++;if("]"!==e.token)throw oe(e,"End of matrix ] expected");$(e),P(e),o=a[0].items.length;for(var c=1;c0},v.isDecimalMark=function(e,t){return"."===e&&"/"!==t&&"*"!==t&&"^"!==t},v.isDigitDot=function(e){return e>="0"&&e<="9"||"."===e},v.isDigit=function(e){return e>="0"&&e<="9"},v.isHexDigit=function(e){return e>="0"&&e<="9"||e>="a"&&e<="f"||e>="A"&&e<="F"},v})),name$1d="compile",dependencies$1d=["typed","parse"],createCompile=factory(name$1d,dependencies$1d,(e=>{var{typed:t,parse:n}=e;return t(name$1d,{string:function(e){return n(e).compile()},"Array | Matrix":function(e){return deepMap(e,(function(e){return n(e).compile()}))}})})),name$1c="evaluate",dependencies$1c=["typed","parse"],createEvaluate=factory(name$1c,dependencies$1c,(e=>{var{typed:t,parse:n}=e;return t(name$1c,{string:function(e){var t=createEmptyMap();return n(e).compile().evaluate(t)},"string, Map | Object":function(e,t){return n(e).compile().evaluate(t)},"Array | Matrix":function(e){var t=createEmptyMap();return deepMap(e,(function(e){return n(e).compile().evaluate(t)}))},"Array | Matrix, Map | Object":function(e,t){return deepMap(e,(function(e){return n(e).compile().evaluate(t)}))}})})),name$1b="Parser",dependencies$1b=["evaluate"],createParserClass=factory(name$1b,dependencies$1b,(e=>{var{evaluate:t}=e;function n(){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");Object.defineProperty(this,"scope",{value:createEmptyMap(),writable:!1})}return n.prototype.type="Parser",n.prototype.isParser=!0,n.prototype.evaluate=function(e){return t(e,this.scope)},n.prototype.get=function(e){if(this.scope.has(e))return this.scope.get(e)},n.prototype.getAll=function(){return toObject(this.scope)},n.prototype.getAllAsMap=function(){return this.scope},n.prototype.set=function(e,t){return this.scope.set(e,t),t},n.prototype.remove=function(e){this.scope.delete(e)},n.prototype.clear=function(){this.scope.clear()},n}),{isClass:!0}),name$1a="parser",dependencies$1a=["typed","Parser"],createParser=factory(name$1a,dependencies$1a,(e=>{var{typed:t,Parser:n}=e;return t(name$1a,{"":function(){return new n}})})),name$19="lup",dependencies$19=["typed","matrix","abs","addScalar","divideScalar","multiplyScalar","subtract","larger","equalScalar","unaryMinus","DenseMatrix","SparseMatrix","Spa"],createLup=factory(name$19,dependencies$19,(e=>{var{typed:t,matrix:n,abs:r,addScalar:a,divideScalar:i,multiplyScalar:s,subtract:o,larger:l,equalScalar:u,unaryMinus:c,DenseMatrix:p,SparseMatrix:d,Spa:m}=e;return t(name$19,{DenseMatrix:function(e){return h(e)},SparseMatrix:function(e){return function(e){var t,n,a,o=e._size[0],p=e._size[1],h=Math.min(o,p),f=e._values,y=e._index,g=e._ptr,b=[],v=[],N=[],T=[o,h],C=[],A=[],V=[],x=[h,p],S=[],w=[];for(t=0;t0&&e.forEach(0,n-1,(function(t,n){d._forEachRow(t,b,v,N,(function(r,a){r>t&&e.accumulate(r,c(s(a,n)))}))}));var E=n,D=e.get(n),O=r(D);e.forEach(n+1,o-1,(function(e,t){var n=r(t);l(n,O)&&(E=e,O=n,D=t)})),n!==E&&(d._swapRows(n,E,T[1],b,v,N),d._swapRows(n,E,x[1],C,A,V),e.swap(n,E),function(e,t){var n=w[e],r=w[t];S[n]=t,S[r]=e,w[e]=r,w[t]=n}(n,E)),e.forEach(0,o-1,(function(e,t){e<=n?(C.push(t),A.push(e)):(t=i(t,D),u(t,0)||(b.push(t),v.push(e)))}))};for(n=0;n0)for(t=0;t{var{typed:t,matrix:n,zeros:r,identity:a,isZero:i,equal:s,sign:o,sqrt:l,conj:u,unaryMinus:c,addScalar:p,divideScalar:d,multiplyScalar:m,subtract:h,complex:f}=e;return _extends$1(t(name$18,{DenseMatrix:function(e){return g(e)},SparseMatrix:function(e){return function(e){throw new Error("qr not implemented for sparse matrices yet")}()},Array:function(e){var t=g(n(e));return{Q:t.Q.valueOf(),R:t.R.valueOf()}}}),{_denseQRimpl:y});function y(e){var t,n,f,y=e._size[0],g=e._size[1],b=a([y],"dense"),v=b._data,N=e.clone(),T=N._data,C=r([y],"");for(f=0;f0)for(var r="Complex"===n[0][0].type?f(0):0,a=0;a=0;){var l=n[s+o],u=n[r+l];-1===u?(o--,i[t++]=l):(n[r+l]=n[a+u],n[s+ ++o]=u)}return t}function csPost(e,t){if(!e)return null;var n,r=0,a=[],i=[],s=t,o=2*t;for(n=0;n=0;n--)-1!==e[n]&&(i[s+n]=i[0+e[n]],i[0+e[n]]=n);for(n=0;n{var{add:t,multiply:n,transpose:r}=e;return function(e,s){if(!s||e<=0||e>3)return null;var o=s._size,l=o[0],u=o[1],c=0,p=Math.max(16,10*Math.sqrt(u)),d=function(e,a,i,s,o){var l=r(a);if(1===e&&s===i)return t(a,l);if(2===e){for(var u=l._index,c=l._ptr,p=0,d=0;do))for(var h=c[d+1];ms)n[o+d]=0,n[a+d]=-1,p++,t[d]=csFlip(e),n[o+e]++;else{var h=n[l+m];-1!==h&&(u[h]=d),n[c+d]=n[l+m],n[l+m]=d}}return p}(u,O,_,$,k,B,p,M,F,z,P),q=0;jG?(b=f,v=K,N=_[0+f]-G):(v=O[b=D[K++]],N=_[0+b]),g=1;g<=N;g++)(T=_[M+(m=D[v++])])<=0||(W+=T,_[M+m]=-T,D[X++]=m,-1!==_[P+m]&&(z[_[P+m]]=z[m]),-1!==z[m]?_[P+z[m]]=_[P+m]:_[F+_[$+m]]=_[P+m]);b!==f&&(O[b]=csFlip(f),_[B+b]=0)}for(0!==G&&(I=X),_[$+f]=W,O[f]=Z,_[0+f]=X-Z,_[k+f]=-2,U=a(U,c,_,B,u),C=Z;C=U?_[B+b]-=T:0!==_[B+b]&&(_[B+b]=_[$+b]+Y)}for(C=Z;C0?(E+=Q,D[S++]=b,w+=b):(O[b]=csFlip(f),_[B+b]=0)}_[k+m]=S-V+1;var J=S,ee=V+_[0+m];for(K=x+1;K=0))for(m=_[L+(w=z[m])],_[L+w]=-1;-1!==m&&-1!==_[P+m];m=_[P+m],U++){for(N=_[0+m],A=_[k+m],K=O[m]+1;K<=O[m]+N-1;K++)_[B+D[K]]=U;var ne=m;for(h=_[P+m];-1!==h;){var re=_[0+h]===N&&_[k+h]===A;for(K=O[h]+1;re&&K<=O[h]+N-1;K++)_[B+D[K]]!==U&&(re=0);re?(O[h]=csFlip(m),_[M+m]+=_[M+h],_[M+h]=0,_[k+h]=-1,h=_[P+h],_[P+ne]=h):(ne=h,h=_[P+h])}}for(K=Z,C=Z;C=0;h--)_[M+h]>0||(_[P+h]=_[F+O[h]],_[F+O[h]]=h);for(b=u;b>=0;b--)_[M+b]<=0||-1!==O[b]&&(_[P+b]=_[F+O[b]],_[F+O[b]]=b);for(f=0,m=0;m<=u;m++)-1===O[m]&&(f=csTdfs(m,f,_,F,P,R,B));return R.splice(R.length-1,1),R};function a(e,t,n,r,a){if(e<2||e+t<0){for(var i=0;i{var{transpose:t}=e;return function(e,n,r,a){if(!e||!n||!r)return null;var i,s,o,l,u,c,p,d=e._size,m=d[0],h=d[1],f=4*h+(a?h+m+1:0),y=[],g=h,b=2*h,v=3*h,N=4*h,T=5*h+1;for(o=0;o=1&&C[s]++,2===S.jleaf&&C[S.q]--}-1!==n[s]&&(y[0+s]=n[s])}for(s=0;s{var{add:t,multiply:n,transpose:r}=e,a=createCsAmd({add:t,multiply:n,transpose:r}),i=createCsCounts({transpose:r});return function(e,t,n){var r,s=t._ptr,o=t._size[1],l={};if(l.q=a(e,t),e&&!l.q)return null;if(n){var u=e?csPermute(t,null,l.q,0):t;l.parent=csEtree(u,1);var c=csPost(l.parent,o);if(l.cp=i(u,l.parent,c,1),u&&l.parent&&l.cp&&function(e,t){var n=e._ptr,r=e._index,a=e._size,i=a[0],s=a[1];t.pinv=[],t.leftmost=[];var o,l,u,c,p,d=t.parent,m=t.pinv,h=t.leftmost,f=[],y=i,g=i+s,b=i+2*s;for(l=0;l=0;l--)for(c=n[l],p=n[l+1],u=c;u=0;o--)m[o]=-1,-1!==(l=h[o])&&(0==f[b+l]++&&(f[g+l]=o),f[0+o]=f[y+l],f[y+l]=o);for(t.lnz=0,t.m2=i,l=0;l=0;){e=r[p];var d=a?a[e]:e;csMarked(u,e)||(csMark(u,e),r[c+p]=d<0?0:csUnflip(u[d]));var m=1;for(s=r[c+p],o=d<0?0:csUnflip(u[d+1]);s{var{divideScalar:t,multiply:n,subtract:r}=e;return function(e,a,i,s,o,l,u){var c,p,d,m,h=e._values,f=e._index,y=e._ptr,g=e._size[1],b=a._values,v=a._index,N=a._ptr,T=csReach(e,a,i,s,l);for(c=T;c{var{abs:t,divideScalar:n,multiply:r,subtract:a,larger:i,largerEq:s,SparseMatrix:o}=e,l=createCsSpsolve({divideScalar:n,multiply:r,subtract:a});return function(e,a,u){if(!e)return null;var c,p=e._size[1],d=100,m=100;a&&(c=a.q,d=a.lnz||d,m=a.unz||m);var h,f,y=[],g=[],b=[],v=new o({values:y,index:g,ptr:b,size:[p,p]}),N=[],T=[],C=[],A=new o({values:N,index:T,ptr:C,size:[p,p]}),V=[],x=[],S=[];for(h=0;h{var{typed:t,abs:n,add:r,multiply:a,transpose:i,divideScalar:s,subtract:o,larger:l,largerEq:u,SparseMatrix:c}=e,p=createCsSqr({add:r,multiply:a,transpose:i}),d=createCsLu({abs:n,divideScalar:s,multiply:a,subtract:o,larger:l,largerEq:u,SparseMatrix:c});return t(name$12,{"SparseMatrix, number, number":function(e,t,n){if(!isInteger$1(t)||t<0||t>3)throw new Error("Symbolic Ordering and Analysis order must be an integer number in the interval [0, 3]");if(n<0||n>1)throw new Error("Partial pivoting threshold must be a number from 0 to 1");var r=p(t,e,!1),a=d(e,r,n);return{L:a.L,U:a.U,p:a.pinv,q:r.q,toString:function(){return"L: "+this.L.toString()+"\nU: "+this.U.toString()+"\np: "+this.p.toString()+(this.q?"\nq: "+this.q.toString():"")+"\n"}}}})}));function csIpvec(e,t){var n,r=t.length,a=[];if(e)for(n=0;n{var{typed:t,matrix:n,lup:r,slu:a,usolve:i,lsolve:s,DenseMatrix:o}=e,l=createSolveValidation({DenseMatrix:o});return t(name$11,{"Array, Array | Matrix":function(e,t){e=n(e);var a=r(e);return c(a.L,a.U,a.p,null,t).valueOf()},"DenseMatrix, Array | Matrix":function(e,t){var n=r(e);return c(n.L,n.U,n.p,null,t)},"SparseMatrix, Array | Matrix":function(e,t){var n=r(e);return c(n.L,n.U,n.p,null,t)},"SparseMatrix, Array | Matrix, number, number":function(e,t,n,r){var i=a(e,n,r);return c(i.L,i.U,i.p,i.q,t)},"Object, Array | Matrix":function(e,t){return c(e.L,e.U,e.p,e.q,t)}});function u(e){if(isMatrix(e))return e;if(isArray$1(e))return n(e);throw new TypeError("Invalid Matrix LU decomposition")}function c(e,t,n,r,a){e=u(e),t=u(t),n&&((a=l(e,a,!0))._data=csIpvec(n,a._data));var o=s(e,a),c=i(t,o);return r&&(c._data=csIpvec(r,c._data)),c}})),name$10="Help",dependencies$10=["parse"],createHelpClass=factory(name$10,dependencies$10,(e=>{var{parse:t}=e;function n(e){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(!e)throw new Error('Argument "doc" missing');this.doc=e}return n.prototype.type="Help",n.prototype.isHelp=!0,n.prototype.toString=function(){var e=this.doc||{},n="\n";if(e.name&&(n+="Name: "+e.name+"\n\n"),e.category&&(n+="Category: "+e.category+"\n\n"),e.description&&(n+="Description:\n "+e.description+"\n\n"),e.syntax&&(n+="Syntax:\n "+e.syntax.join("\n ")+"\n\n"),e.examples){n+="Examples:\n";for(var r={},a=0;a"mathjs"!==e)).forEach((n=>{t[n]=e[n]})),new n(t)},n.prototype.valueOf=n.prototype.toString,n}),{isClass:!0}),name$$="Chain",dependencies$$=["?on","math"],createChainClass=factory(name$$,dependencies$$,(e=>{var{on:t,math:n}=e;function r(e){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");isChain(e)?this.value=e.value:this.value=e}function a(e,t){lazy(r.prototype,e,(function(){var e=t();if("function"==typeof e)return i(e)}))}function i(e){return function(){for(var t=[this.value],n=0;ne[t]))};for(var o in e)n(o)}};var s={expression:!0,docs:!0,type:!0,classes:!0,json:!0,error:!0,isChain:!0};return r.createProxy(n),t&&t("import",(function(e,t,n){n||a(e,t)})),r}),{isClass:!0}),eDocs={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"]},falseDocs={name:"false",category:"Constants",syntax:["false"],description:"Boolean value false",examples:["false"],seealso:["true"]},iDocs={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:[]},InfinityDocs={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:[]},LN10Docs={name:"LN10",category:"Constants",syntax:["LN10"],description:"Returns the natural logarithm of 10, approximately equal to 2.302",examples:["LN10","log(10)"],seealso:[]},LN2Docs={name:"LN2",category:"Constants",syntax:["LN2"],description:"Returns the natural logarithm of 2, approximately equal to 0.693",examples:["LN2","log(2)"],seealso:[]},LOG10EDocs={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:[]},LOG2EDocs={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:[]},NaNDocs={name:"NaN",category:"Constants",syntax:["NaN"],description:"Not a number",examples:["NaN","0 / 0"],seealso:[]},nullDocs={name:"null",category:"Constants",syntax:["null"],description:"Value null",examples:["null"],seealso:["true","false"]},phiDocs={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:[]},piDocs={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"]},SQRT12Docs={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:[]},SQRT2Docs={name:"SQRT2",category:"Constants",syntax:["SQRT2"],description:"Returns the square root of 2, approximately equal to 1.414",examples:["SQRT2","sqrt(2)"],seealso:[]},tauDocs={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"]},trueDocs={name:"true",category:"Constants",syntax:["true"],description:"Boolean value true",examples:["true"],seealso:["false"]},versionDocs={name:"version",category:"Constants",syntax:["version"],description:"A string with the version number of math.js",examples:["version"],seealso:[]},bignumberDocs={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","complex","fraction","index","matrix","string","unit"]},booleanDocs={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"]},complexDocs={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"]},createUnitDocs={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"]},fractionDocs={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"]},indexDocs={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:["[]","[1, 2, 3]","A = [1, 2, 3; 4, 5, 6]","A[1, :]","A[1, 2] = 50","A[0:2, 0:2] = ones(2, 2)"],seealso:["bignumber","boolean","complex","matrix,","number","range","string","unit"]},matrixDocs={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"]},numberDocs={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","boolean","complex","fraction","index","matrix","string","unit"]},sparseDocs={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"]},splitUnitDocs={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"]},stringDocs={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"]},unitDocs={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"]},configDocs={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:[]},importDocs={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:[]},typedDocs={name:"typed",category:"Core",syntax:["typed(signatures)","typed(name, signatures)"],description:"Create a typed function.",examples:['double = typed({ "number": f(x)=x+x })',"double(2)",'double("hello")'],seealso:[]},derivativeDocs={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"]},leafCountDocs={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"]},lsolveDocs={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"]},lsolveAllDocs={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"]},lupDocs={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"]},lusolveDocs={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"]},qrDocs={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"]},rationalizeDocs={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"]},resolveDocs={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"]},simplifyDocs={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"]},simplifyCoreDocs={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","evaluate"]},sluDocs={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"]},symbolicEqualDocs={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"]},usolveDocs={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"]},usolveAllDocs={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"]},absDocs={name:"abs",category:"Arithmetic",syntax:["abs(x)"],description:"Compute the absolute value.",examples:["abs(3.5)","abs(-4.2)"],seealso:["sign"]},addDocs={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"]},cbrtDocs={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"]},ceilDocs={name:"ceil",category:"Arithmetic",syntax:["ceil(x)"],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)"],seealso:["floor","fix","round"]},cubeDocs={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"]},divideDocs={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"]},dotDivideDocs={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"]},dotMultiplyDocs={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"]},dotPowDocs={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"]},expDocs={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"]},expmDocs={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"]},expm1Docs={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"]},fixDocs={name:"fix",category:"Arithmetic",syntax:["fix(x)"],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)"],seealso:["ceil","floor","round"]},floorDocs={name:"floor",category:"Arithmetic",syntax:["floor(x)"],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)"],seealso:["ceil","fix","round"]},gcdDocs={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"]},hypotDocs={name:"hypot",category:"Arithmetic",syntax:["hypot(a, b, c, ...)","hypot([a, b, c, ...])"],description:"Calculate the hypotenusa of a list with values. ",examples:["hypot(3, 4)","sqrt(3^2 + 4^2)","hypot(-2)","hypot([3, 4, 5])"],seealso:["abs","norm"]},invmodDocs={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)=NaN","invmod(7, 13)=2","math.invmod(15151, 15122)=10429"],seealso:["gcd","xgcd"]},lcmDocs={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"]},logDocs={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"]},log10Docs={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"]},log1pDocs={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"]},log2Docs={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"]},modDocs={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"]},multiplyDocs={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"]},normDocs={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")']},nthRootDocs={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"]},nthRootsDocs={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"]},powDocs={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)","math.pow([[1, 2], [4, 3]], 2)","math.pow([[1, 2], [4, 3]], -1)"],seealso:["multiply","nthRoot","nthRoots","sqrt"]},roundDocs={name:"round",category:"Arithmetic",syntax:["round(x)","round(x, n)"],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)"],seealso:["ceil","floor","fix"]},signDocs={name:"sign",category:"Arithmetic",syntax:["sign(x)"],description:"Compute the sign of a value. The sign of a value x is 1 when x>1, -1 when x<0, and 0 when x=0.",examples:["sign(3.5)","sign(-4.2)","sign(0)"],seealso:["abs"]},sqrtDocs={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"]},sqrtmDocs={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([[1, 2], [3, 4]])"],seealso:["sqrt","abs","square","multiply"]},squareDocs={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"]},subtractDocs={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"]},unaryMinusDocs={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"]},unaryPlusDocs={name:"unaryPlus",category:"Operators",syntax:["+x","unaryPlus(x)"],description:"Converts booleans and strings to numbers.",examples:["+true",'+"2"'],seealso:["add","subtract","unaryMinus"]},xgcdDocs={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"]},bitAndDocs={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"]},bitNotDocs={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"]},bitOrDocs={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"]},bitXorDocs={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"]},leftShiftDocs={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"]},rightArithShiftDocs={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"]},rightLogShiftDocs={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"]},bellNumbersDocs={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"]},catalanDocs={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"]},compositionDocs={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"]},stirlingS2Docs={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"]},argDocs={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"]},conjDocs={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"]},imDocs={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"]},reDocs={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"]},evaluateDocs={name:"evaluate",category:"Expression",syntax:["evaluate(expression)","evaluate([expr1, expr2, expr3, ...])"],description:"Evaluate an expression or an array with expressions.",examples:['evaluate("2 + 3")','evaluate("sqrt(" + 4 + ")")'],seealso:[]},helpDocs={name:"help",category:"Expression",syntax:["help(object)","help(string)"],description:"Display documentation on a function or data type.",examples:["help(sqrt)",'help("complex")'],seealso:[]},distanceDocs={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:[]},intersectDocs={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:[]},andDocs={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"]},notDocs={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"]},orDocs={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"]},xorDocs={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"]},columnDocs={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"]},concatDocs={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"]},countDocs={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"]},crossDocs={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"]},ctransposeDocs={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"]},detDocs={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"]},diagDocs={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"]},diffDocs={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 indicant 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:["diff([1, 2, 4, 7, 0])","diff([1, 2, 4, 7, 0], 0)","diff(matrix([1, 2, 4, 7, 0]))","diff([[1, 2], [3, 4]])","diff([[1, 2], [3, 4]], 0)","diff([[1, 2], [3, 4]], 1)","diff([[1, 2], [3, 4]], bignumber(1))","diff(matrix([[1, 2], [3, 4]]), 1)","diff([[1, 2], matrix([3, 4])], 1)"],seealso:["subtract","partitionSelect"]},dotDocs={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"]},eigsDocs={name:"eigs",category:"Matrix",syntax:["eigs(x)"],description:"Calculate the eigenvalues and eigenvectors of a real symmetric matrix",examples:["eigs([[5, 2.3], [2.3, 1]])"],seealso:["inv"]},filterDocs={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"]},flattenDocs={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"]},forEachDocs={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"]},getMatrixDataTypeDocs={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"]},identityDocs={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"]},invDocs={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"]},pinvDocs={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"]},kronDocs={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"]},mapDocs={name:"map",category:"Matrix",syntax:["map(x, callback)"],description:"Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array.",examples:["map([1, 2, 3], square)"],seealso:["filter","forEach"]},matrixFromColumnsDocs={name:"matrixFromColumns",category:"Matrix",syntax:["math.matrixFromColumns(...arr)","math.matrixFromColumns(row1, row2)","math.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"]},matrixFromFunctionDocs={name:"matrixFromFunction",category:"Matrix",syntax:["math.matrixFromFunction(size, fn)","math.matrixFromFunction(size, fn, format)","math.matrixFromFunction(size, fn, format, datatype)","math.matrixFromFunction(size, format, fn)","math.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"]},matrixFromRowsDocs={name:"matrixFromRows",category:"Matrix",syntax:["math.matrixFromRows(...arr)","math.matrixFromRows(row1, row2)","math.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"]},onesDocs={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"]},partitionSelectDocs={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)'],seealso:["sort"]},rangeDocs={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")',"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"]},reshapeDocs={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])"],seealso:["size","squeeze","resize"]},resizeDocs={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"]},rotateDocs={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], math.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"]},rotationMatrixDocs={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"]},rowDocs={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"]},sizeDocs={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"]},sortDocs={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"])',"sortByLength(a, b) = size(a)[1] - size(b)[1]",'sort(["Langdon", "Tom", "Sara"], sortByLength)','sort(["10", "1", "2"], "natural")'],seealso:["map","filter","forEach"]},squeezeDocs={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"]},subsetDocs={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"]},traceDocs={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"]},transposeDocs={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"]},zerosDocs={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"]},fftDocs={name:"fft",category:"Matrix",syntax:["fft(x)"],description:"Calculate N-dimensional fourier transform",examples:["fft([[1, 0], [1, 0]])"],seealso:["ifft"]},ifftDocs={name:"ifft",category:"Matrix",syntax:["ifft(x)"],description:"Calculate N-dimensional inverse fourier transform",examples:["ifft([[2, 2], [0, 0]])"],seealso:["fft"]},combinationsDocs={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"]},combinationsWithRepDocs={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"]},factorialDocs={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"]},gammaDocs={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"]},lgammaDocs={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(math.i)","lgamma(complex(1.1, 2))"],seealso:["gamma"]},kldivergenceDocs={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:[]},multinomialDocs={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"]},permutationsDocs={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"]},pickRandomDocs={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"]},randomDocs={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"]},randomIntDocs={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"]},compareDocs={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"]},compareNaturalDocs={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"]},compareTextDocs={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"]},deepEqualDocs={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"]},equalDocs={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"]},equalTextDocs={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"]},largerDocs={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.",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"]},largerEqDocs={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"]},smallerDocs={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.",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"]},smallerEqDocs={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"]},unequalDocs={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"]},setCartesianDocs={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"]},setDifferenceDocs={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"]},setDistinctDocs={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"]},setIntersectDocs={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"]},setIsSubsetDocs={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"]},setMultiplicityDocs={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"]},setPowersetDocs={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"]},setSizeDocs={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"]},setSymDifferenceDocs={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"]},setUnionDocs={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"]},erfDocs={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:[]},madDocs={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"]},maxDocs={name:"max",category:"Statistics",syntax:["max(a, b, c, ...)","max(A)","max(A, dim)"],description:"Compute the maximum value of a list of values.",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"]},meanDocs={name:"mean",category:"Statistics",syntax:["mean(a, b, c, ...)","mean(A)","mean(A, dim)"],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"]},medianDocs={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"]},minDocs={name:"min",category:"Statistics",syntax:["min(a, b, c, ...)","min(A)","min(A, dim)"],description:"Compute the minimum value of a list of values.",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"]},modeDocs={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"]},prodDocs={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"]},quantileSeqDocs={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 probablity are: Number, BigNumber. \n\nIn 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"]},stdDocs={name:"std",category:"Statistics",syntax:["std(a, b, c, ...)","std(A)","std(A, 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"]},cumSumDocs={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"]},sumDocs={name:"sum",category:"Statistics",syntax:["sum(a, b, c, ...)","sum(A)"],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","sum","variance"]},varianceDocs={name:"variance",category:"Statistics",syntax:["variance(a, b, c, ...)","variance(A)","variance(A, 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"]},acosDocs={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"]},acoshDocs={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"]},acotDocs={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"]},acothDocs={name:"acoth",category:"Trigonometry",syntax:["acoth(x)"],description:"Calculate the hyperbolic arccotangent 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"]},acscDocs={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"]},acschDocs={name:"acsch",category:"Trigonometry",syntax:["acsch(x)"],description:"Calculate the hyperbolic arccosecant of a value, defined as `acsch(x) = ln(1/x + sqrt(1/x^2 + 1))`.",examples:["acsch(0.5)"],seealso:["asech","acoth"]},asecDocs={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"]},asechDocs={name:"asech",category:"Trigonometry",syntax:["asech(x)"],description:"Calculate the inverse secant of a value.",examples:["asech(0.5)"],seealso:["acsch","acoth"]},asinDocs={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"]},asinhDocs={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"]},atanDocs={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"]},atan2Docs={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"]},atanhDocs={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"]},cosDocs={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"]},coshDocs={name:"cosh",category:"Trigonometry",syntax:["cosh(x)"],description:"Compute the hyperbolic cosine of x in radians.",examples:["cosh(0.5)"],seealso:["sinh","tanh","coth"]},cotDocs={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"]},cothDocs={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"]},cscDocs={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"]},cschDocs={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"]},secDocs={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"]},sechDocs={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"]},sinDocs={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"]},sinhDocs={name:"sinh",category:"Trigonometry",syntax:["sinh(x)"],description:"Compute the hyperbolic sine of x in radians.",examples:["sinh(0.5)"],seealso:["cosh","tanh"]},tanDocs={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"]},tanhDocs={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"]},toDocs={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:[]},binDocs={name:"bin",category:"Utils",syntax:["bin(value)"],description:"Format a number as binary",examples:["bin(2)"],seealso:["oct","hex"]},cloneDocs={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:[]},formatDocs={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"]},hasNumericValueDocs={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"]},hexDocs={name:"hex",category:"Utils",syntax:["hex(value)"],description:"Format a number as hexadecimal",examples:["hex(240)"],seealso:["bin","oct"]},isIntegerDocs={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"]},isNaNDocs={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"]},isNegativeDocs={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"]},isNumericDocs={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"]},isPositiveDocs={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"]},isPrimeDocs={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"]},isZeroDocs={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"]},numericDocs={name:"numeric",category:"Utils",syntax:["numeric(x)"],description:"Convert a numeric input to a specific numeric type: number, BigNumber, or Fraction.",examples:['numeric("4")','numeric("4", "number")','numeric("4", "BigNumber")','numeric("4", "Fraction)','numeric(4, "Fraction")','numeric(fraction(2, 5), "number)'],seealso:["number","fraction","bignumber","string","format"]},octDocs={name:"oct",category:"Utils",syntax:["oct(value)"],description:"Format a number as octal",examples:["oct(56)"],seealso:["bin","hex"]},printDocs={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: $0, $1, $2", [6, 9, 4])'],seealso:["format"]},typeOfDocs={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"]},embeddedDocs={bignumber:bignumberDocs,boolean:booleanDocs,complex:complexDocs,createUnit:createUnitDocs,fraction:fractionDocs,index:indexDocs,matrix:matrixDocs,number:numberDocs,sparse:sparseDocs,splitUnit:splitUnitDocs,string:stringDocs,unit:unitDocs,e:eDocs,E:eDocs,false:falseDocs,i:iDocs,Infinity:InfinityDocs,LN2:LN2Docs,LN10:LN10Docs,LOG2E:LOG2EDocs,LOG10E:LOG10EDocs,NaN:NaNDocs,null:nullDocs,pi:piDocs,PI:piDocs,phi:phiDocs,SQRT1_2:SQRT12Docs,SQRT2:SQRT2Docs,tau:tauDocs,true:trueDocs,version:versionDocs,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",examples:["coulomb"]},elementaryCharge:{description:"Elementary charge",examples:["elementaryCharge"]},bohrMagneton:{description:"Borh 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:"Borh 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:derivativeDocs,lsolve:lsolveDocs,lsolveAll:lsolveAllDocs,lup:lupDocs,lusolve:lusolveDocs,leafCount:leafCountDocs,resolve:resolveDocs,simplify:simplifyDocs,simplifyCore:simplifyCoreDocs,symbolicEqual:symbolicEqualDocs,rationalize:rationalizeDocs,slu:sluDocs,usolve:usolveDocs,usolveAll:usolveAllDocs,qr:qrDocs,abs:absDocs,add:addDocs,cbrt:cbrtDocs,ceil:ceilDocs,cube:cubeDocs,divide:divideDocs,dotDivide:dotDivideDocs,dotMultiply:dotMultiplyDocs,dotPow:dotPowDocs,exp:expDocs,expm:expmDocs,expm1:expm1Docs,fix:fixDocs,floor:floorDocs,gcd:gcdDocs,hypot:hypotDocs,lcm:lcmDocs,log:logDocs,log2:log2Docs,log1p:log1pDocs,log10:log10Docs,mod:modDocs,multiply:multiplyDocs,norm:normDocs,nthRoot:nthRootDocs,nthRoots:nthRootsDocs,pow:powDocs,round:roundDocs,sign:signDocs,sqrt:sqrtDocs,sqrtm:sqrtmDocs,square:squareDocs,subtract:subtractDocs,unaryMinus:unaryMinusDocs,unaryPlus:unaryPlusDocs,xgcd:xgcdDocs,invmod:invmodDocs,bitAnd:bitAndDocs,bitNot:bitNotDocs,bitOr:bitOrDocs,bitXor:bitXorDocs,leftShift:leftShiftDocs,rightArithShift:rightArithShiftDocs,rightLogShift:rightLogShiftDocs,bellNumbers:bellNumbersDocs,catalan:catalanDocs,composition:compositionDocs,stirlingS2:stirlingS2Docs,config:configDocs,import:importDocs,typed:typedDocs,arg:argDocs,conj:conjDocs,re:reDocs,im:imDocs,evaluate:evaluateDocs,help:helpDocs,distance:distanceDocs,intersect:intersectDocs,and:andDocs,not:notDocs,or:orDocs,xor:xorDocs,concat:concatDocs,count:countDocs,cross:crossDocs,column:columnDocs,ctranspose:ctransposeDocs,det:detDocs,diag:diagDocs,diff:diffDocs,dot:dotDocs,getMatrixDataType:getMatrixDataTypeDocs,identity:identityDocs,filter:filterDocs,flatten:flattenDocs,forEach:forEachDocs,inv:invDocs,pinv:pinvDocs,eigs:eigsDocs,kron:kronDocs,matrixFromFunction:matrixFromFunctionDocs,matrixFromRows:matrixFromRowsDocs,matrixFromColumns:matrixFromColumnsDocs,map:mapDocs,ones:onesDocs,partitionSelect:partitionSelectDocs,range:rangeDocs,resize:resizeDocs,reshape:reshapeDocs,rotate:rotateDocs,rotationMatrix:rotationMatrixDocs,row:rowDocs,size:sizeDocs,sort:sortDocs,squeeze:squeezeDocs,subset:subsetDocs,trace:traceDocs,transpose:transposeDocs,zeros:zerosDocs,fft:fftDocs,ifft:ifftDocs,combinations:combinationsDocs,combinationsWithRep:combinationsWithRepDocs,factorial:factorialDocs,gamma:gammaDocs,kldivergence:kldivergenceDocs,lgamma:lgammaDocs,multinomial:multinomialDocs,permutations:permutationsDocs,pickRandom:pickRandomDocs,random:randomDocs,randomInt:randomIntDocs,compare:compareDocs,compareNatural:compareNaturalDocs,compareText:compareTextDocs,deepEqual:deepEqualDocs,equal:equalDocs,equalText:equalTextDocs,larger:largerDocs,largerEq:largerEqDocs,smaller:smallerDocs,smallerEq:smallerEqDocs,unequal:unequalDocs,setCartesian:setCartesianDocs,setDifference:setDifferenceDocs,setDistinct:setDistinctDocs,setIntersect:setIntersectDocs,setIsSubset:setIsSubsetDocs,setMultiplicity:setMultiplicityDocs,setPowerset:setPowersetDocs,setSize:setSizeDocs,setSymDifference:setSymDifferenceDocs,setUnion:setUnionDocs,erf:erfDocs,cumsum:cumSumDocs,mad:madDocs,max:maxDocs,mean:meanDocs,median:medianDocs,min:minDocs,mode:modeDocs,prod:prodDocs,quantileSeq:quantileSeqDocs,std:stdDocs,sum:sumDocs,variance:varianceDocs,acos:acosDocs,acosh:acoshDocs,acot:acotDocs,acoth:acothDocs,acsc:acscDocs,acsch:acschDocs,asec:asecDocs,asech:asechDocs,asin:asinDocs,asinh:asinhDocs,atan:atanDocs,atanh:atanhDocs,atan2:atan2Docs,cos:cosDocs,cosh:coshDocs,cot:cotDocs,coth:cothDocs,csc:cscDocs,csch:cschDocs,sec:secDocs,sech:sechDocs,sin:sinDocs,sinh:sinhDocs,tan:tanDocs,tanh:tanhDocs,to:toDocs,clone:cloneDocs,format:formatDocs,bin:binDocs,oct:octDocs,hex:hexDocs,isNaN:isNaNDocs,isInteger:isIntegerDocs,isNegative:isNegativeDocs,isNumeric:isNumericDocs,hasNumericValue:hasNumericValueDocs,isPositive:isPositiveDocs,isPrime:isPrimeDocs,isZero:isZeroDocs,print:printDocs,typeOf:typeOfDocs,numeric:numericDocs},name$_="help",dependencies$_=["typed","mathWithTransform","Help"],createHelp=factory(name$_,dependencies$_,(e=>{var{typed:t,mathWithTransform:n,Help:r}=e;return t(name$_,{any:function(e){var t,a=e;if("string"!=typeof e)for(t in n)if(hasOwnProperty$2(n,t)&&e===n[t]){a=t;break}var i=getSafeProperty(embeddedDocs,a);if(!i){var s="function"==typeof a?a.name:a;throw new Error('No documentation found on "'+s+'"')}return new r(i)}})})),name$Z="chain",dependencies$Z=["typed","Chain"],createChain=factory(name$Z,dependencies$Z,(e=>{var{typed:t,Chain:n}=e;return t(name$Z,{"":function(){return new n},any:function(e){return new n(e)}})})),name$Y="det",dependencies$Y=["typed","matrix","subtract","multiply","divideScalar","isZero","unaryMinus"],createDet=factory(name$Y,dependencies$Y,(e=>{var{typed:t,matrix:n,subtract:r,multiply:a,divideScalar:i,isZero:s,unaryMinus:o}=e;return t(name$Y,{any:function(e){return clone$3(e)},"Array | Matrix":function(e){var t;switch((t=isMatrix(e)?e.size():Array.isArray(e)?(e=n(e)).size():[]).length){case 0:return clone$3(e);case 1:if(1===t[0])return clone$3(e.valueOf()[0]);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");case 2:var l=t[0];if(l===t[1])return function(e,t,n){if(1===t)return clone$3(e[0][0]);if(2===t)return r(a(e[0][0],e[1][1]),a(e[1][0],e[0][1]));for(var l=!1,u=new Array(t).fill(0).map(((e,t)=>t)),c=0;c{var{typed:t,matrix:n,divideScalar:r,addScalar:a,multiply:i,unaryMinus:s,det:o,identity:l,abs:u}=e;return t(name$X,{"Array | Matrix":function(e){var t=isMatrix(e)?e.size():arraySize(e);switch(t.length){case 1:if(1===t[0])return isMatrix(e)?n([r(1,e.valueOf()[0])]):[r(1,e[0])];throw new RangeError("Matrix must be square (size: "+format$1(t)+")");case 2:var a=t[0],i=t[1];if(a===i)return isMatrix(e)?n(c(e.valueOf(),a,i),e.storage()):c(e,a,i);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");default:throw new RangeError("Matrix must be two dimensional (size: "+format$1(t)+")")}},any:function(e){return r(1,e)}});function c(e,t,n){var c,p,d,m,h;if(1===t){if(0===(m=e[0][0]))throw Error("Cannot calculate inverse, determinant is zero");return[[r(1,m)]]}if(2===t){var f=o(e);if(0===f)throw Error("Cannot calculate inverse, determinant is zero");return[[r(e[1][1],f),r(s(e[0][1]),f)],[r(s(e[1][0]),f),r(e[0][0],f)]]}var y=e.concat();for(c=0;cv&&(v=u(y[c][b]),N=c),c++;if(0===v)throw Error("Cannot calculate inverse, determinant is zero");(c=N)!==b&&(h=y[b],y[b]=y[c],y[c]=h,h=g[b],g[b]=g[c],g[c]=h);var T=y[b],C=g[b];for(c=0;c{var{typed:t,matrix:n,inv:r,deepEqual:a,equal:i,dotDivide:s,dot:o,ctranspose:l,divideScalar:u,multiply:c,add:p,Complex:d}=e;return t(name$W,{"Array | Matrix":function(e){var t=isMatrix(e)?e.size():arraySize(e);switch(t.length){case 1:return f(e)?l(e):1===t[0]?r(e):s(l(e),o(e,e));case 2:if(f(e))return l(e);var a=t[0],i=t[1];if(a===i)try{return r(e)}catch(e){if(!(e instanceof Error&&e.message.match(/Cannot calculate inverse, determinant is zero/)))throw e}return isMatrix(e)?n(m(e.valueOf(),a,i),e.storage()):m(e,a,i);default:throw new RangeError("Matrix must be two dimensional (size: "+format$1(t)+")")}},any:function(e){return i(e,0)?clone$3(e):u(1,e)}});function m(e,t,n){var{C:a,F:i}=function(e,t,n){var r=function(e,t,n){for(var r=clone$3(e),a=0,i=0;ie.filter(((e,n)=>n!h(o(r[t],r[t]))));return{C:a,F:i}}(e,t,n),u=c(r(c(l(a),a)),l(a)),d=c(l(i),r(c(i,l(i))));return c(d,u)}function h(e){return i(p(e,d(1,1)),p(0,d(1,1)))}function f(e){return a(p(e,d(1,1)),p(c(e,0),d(1,1)))}}));function createComplexEigs(e){var{addScalar:t,subtract:n,flatten:r,multiply:a,multiplyScalar:i,divideScalar:s,sqrt:o,abs:l,bignumber:u,diag:c,inv:p,qr:d,usolve:m,usolveAll:h,equal:f,complex:y,larger:g,smaller:b,matrixFromColumns:v,dot:N}=e;function T(e,r,a,s){var l=t(e,s),u=n(i(e,s),i(r,a)),c=i(l,.5),p=i(o(n(i(l,l),i(4,u))),.5);return[t(c,p),n(c,p)]}function C(e,t,r,a,i,s,o,c){var p="BigNumber"===c,d="Complex"===c,m=p?u(0):d?y(0):0,h=p?u(1):d?y(1):1;if(b(l(r),o))return[[h,m],[m,h]];if(g(l(n(i,s)),o))return[[n(i,a),n(s,a)],[r,r]];var f=n(e,i),v=n(t,i),N=n(r,i),T=n(a,i);return b(l(v),o)?[[f,h],[N,m]]:[[v,m],[T,h]]}function A(e,t){for(var n=0;n=5)return null;for(o=0;;){var l=m(e,i);if(b(E(w(i,[l])),r))break;if(++o>=10)return null;i=D(l)}return i}function S(e,t,n){var r="BigNumber"===n,a="Complex"===n,i=Array(e).fill(0).map((e=>2*Math.random()-1));return r&&(i=i.map((e=>u(e)))),a&&(i=i.map((e=>y(e)))),D(i=w(i,t),n)}function w(e,t){for(var r of t)e=n(e,a(s(N(r,e),N(r,r)),r));return e}function E(e){return l(o(N(e,e)))}function D(e,t){var n="Complex"===t,r="BigNumber"===t?u(1):n?y(1):1;return a(s(r,E(e)),e)}return function(e,o,m,N,S){void 0===S&&(S=!0);var w=function(e,n,r,a,o){var p,d="BigNumber"===a,m="Complex"===a,h=d?u(0):0,v=d?u(1):m?y(1):1,N=d?u(1):1,T=d?u(10):2,C=i(T,T);o&&(p=Array(n).fill(v));for(var A=!1;!A;){A=!0;for(var V=0;V1&&(x=c(Array(v-1).fill(h)))),v-=1,f.pop();for(var I=0;I2&&(x=c(Array(v-2).fill(h)))),v-=2,f.pop(),f.pop();for(var _=0;_+n(l(e),l(t)))),S>100){var M=Error("The eigenvalues failed to converge. Only found these eigenvalues: "+g.join(", "));throw M.values=g,M.vectors=[],M}var P=o?a(V,function(e,t){for(var n=[],r=0;ra(f,e))),E.push(...c.map((e=>r(e))))},M=0;M2&&void 0!==arguments[2]?arguments[2]:t.epsilon,i=arguments.length>3?arguments[3]:void 0;if("number"===i)return function(e,t){for(var n,r=e.length,a=Math.abs(t/r),i=new Array(r),s=0;s=Math.abs(a);){var l=o[0][0],u=o[0][1];e=b(e,n=m(e[l][l],e[u][u],e[l][u]),l,u),i=f(i,n,l,u),o=v(e)}for(var c=C(r,0),p=0;p=a(i);){var u=l[0][0],c=l[0][1];e=g(e,n=h(e[u][u],e[c][c],e[u][c]),u,c),s=y(s,n,u,c),l=N(e)}for(var p=C(r,0),d=0;d{var{config:t,typed:n,matrix:r,addScalar:a,subtract:i,equal:s,abs:o,atan:l,cos:u,sin:c,multiplyScalar:p,divideScalar:d,inv:m,bignumber:h,multiply:f,add:y,larger:g,column:b,flatten:v,number:N,complex:T,sqrt:C,diag:A,qr:V,usolve:x,usolveAll:S,im:w,re:E,smaller:D,matrixFromColumns:O,dot:I}=e,R=createRealSymmetric({config:t,addScalar:a,subtract:i,column:b,flatten:v,equal:s,abs:o,atan:l,cos:u,sin:c,multiplyScalar:p,inv:m,bignumber:h,complex:T,multiply:f,add:y}),_=createComplexEigs({config:t,addScalar:a,subtract:i,multiply:f,multiplyScalar:p,flatten:v,divideScalar:d,sqrt:C,abs:o,bignumber:h,diag:A,qr:V,inv:m,usolve:x,usolveAll:S,equal:s,complex:T,larger:g,smaller:D,matrixFromColumns:O,dot:I});return n("eigs",{Array:function(e){return M(r(e))},"Array, number|BigNumber":function(e,t){return M(r(e),t)},Matrix:function(e){var{values:t,vectors:n}=M(e);return{values:r(t),vectors:r(n)}},"Matrix, number|BigNumber":function(e,t){var{values:n,vectors:a}=M(e,t);return{values:r(n),vectors:r(a)}}});function M(e,n){void 0===n&&(n=t.epsilon);var r=e.size();if(2!==r.length||r[0]!==r[1])throw new RangeError("Matrix must be square (size: "+format$1(r)+")");var a=e.toArray(),s=r[0];if(function(e,t,n){for(var r=0;r{var{typed:t,abs:n,add:r,identity:a,inv:i,multiply:s}=e;return t(name$U,{Matrix:function(e){var t=e.size();if(2!==t.length||t[0]!==t[1])throw new RangeError("Matrix must be square (size: "+format$1(t)+")");for(var l=t[0],u=function(e){for(var t=e.size()[0],r=0,a=0;a1&&(g=s(g,m),b=-b),h=r(h,s(y=y*(p-v+1)/((2*p-v+1)*v),g)),f=r(f,s(y*b,g));for(var N=s(i(f),h),T=0;T{var{typed:t,abs:n,add:r,multiply:a,sqrt:i,subtract:s,inv:o,size:l,max:u,identity:c}=e,p=1e-6;return t(name$T,{"Array | Matrix":function(e){var t=isMatrix(e)?e.size():arraySize(e);switch(t.length){case 1:if(1===t[0])return i(e);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");case 2:if(t[0]===t[1])return function(e){var t,i=0,d=e,m=c(l(e));do{var h=d;if(d=a(.5,r(h,o(m))),m=a(.5,r(m,o(h))),(t=u(n(s(d,h))))>p&&++i>1e3)throw new Error("computing square root of matrix: iterative method could not converge")}while(t>p);return d}(e);throw new RangeError("Matrix must be square (size: "+format$1(t)+")");default:throw new RangeError("Matrix must be at most two dimensional (size: "+format$1(t)+")")}}})})),name$S="divide",dependencies$S=["typed","matrix","multiply","equalScalar","divideScalar","inv"],createDivide=factory(name$S,dependencies$S,(e=>{var{typed:t,matrix:n,multiply:r,equalScalar:a,divideScalar:i,inv:s}=e,o=createAlgorithm11({typed:t,equalScalar:a}),l=createAlgorithm14({typed:t});return t("divide",extend$2({"Array | Matrix, Array | Matrix":function(e,t){return r(e,s(t))},"DenseMatrix, any":function(e,t){return l(e,t,i,!1)},"SparseMatrix, any":function(e,t){return o(e,t,i,!1)},"Array, any":function(e,t){return l(n(e),t,i,!1).valueOf()},"any, Array | Matrix":function(e,t){return r(e,s(t))}},i.signatures))})),name$R="distance",dependencies$R=["typed","addScalar","subtract","divideScalar","multiplyScalar","unaryMinus","sqrt","abs"],createDistance=factory(name$R,dependencies$R,(e=>{var{typed:t,addScalar:n,subtract:r,multiplyScalar:a,divideScalar:i,unaryMinus:s,sqrt:o,abs:l}=e;return t(name$R,{"Array, Array, Array":function(e,t,n){if(2===e.length&&2===t.length&&2===n.length){if(!c(e))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!c(t))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");var o=i(r(n[1],n[0]),r(t[1],t[0])),l=a(a(o,o),t[0]),u=s(a(o,t[0])),p=e[1];return f(e[0],e[1],l,u,p)}throw new TypeError("Invalid Arguments: Try again")},"Object, Object, Object":function(e,t,n){if(2===Object.keys(e).length&&2===Object.keys(t).length&&2===Object.keys(n).length){if(!c(e))throw new TypeError("Values of pointX and pointY should be numbers or BigNumbers");if(!c(t))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("pointX"in e&&"pointY"in e&&"lineOnePtX"in t&&"lineOnePtY"in t&&"lineTwoPtX"in n&&"lineTwoPtY"in n){var o=i(r(n.lineTwoPtY,n.lineTwoPtX),r(t.lineOnePtY,t.lineOnePtX)),l=a(a(o,o),t.lineOnePtX),u=s(a(o,t.lineOnePtX)),p=e.pointX;return f(e.pointX,e.pointY,l,u,p)}throw new TypeError("Key names do not match")}throw new TypeError("Invalid Arguments: Try again")},"Array, Array":function(e,t){if(2===e.length&&3===t.length){if(!c(e))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!p(t))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");return f(e[0],e[1],t[0],t[1],t[2])}if(3===e.length&&6===t.length){if(!p(e))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!m(t))throw new TypeError("Array with 6 numbers or BigNumbers expected for second argument");return y(e[0],e[1],e[2],t[0],t[1],t[2],t[3],t[4],t[5])}if(e.length===t.length&&e.length>0){if(!d(e))throw new TypeError("All values of an array should be numbers or BigNumbers");if(!d(t))throw new TypeError("All values of an array should be numbers or BigNumbers");return g(e,t)}throw new TypeError("Invalid Arguments: Try again")},"Object, Object":function(e,t){if(2===Object.keys(e).length&&3===Object.keys(t).length){if(!c(e))throw new TypeError("Values of pointX and pointY should be numbers or BigNumbers");if(!p(t))throw new TypeError("Values of xCoeffLine, yCoeffLine and constant should be numbers or BigNumbers");if("pointX"in e&&"pointY"in e&&"xCoeffLine"in t&&"yCoeffLine"in t&&"constant"in t)return f(e.pointX,e.pointY,t.xCoeffLine,t.yCoeffLine,t.constant);throw new TypeError("Key names do not match")}if(3===Object.keys(e).length&&6===Object.keys(t).length){if(!p(e))throw new TypeError("Values of pointX, pointY and pointZ should be numbers or BigNumbers");if(!m(t))throw new TypeError("Values of x0, y0, z0, a, b and c should be numbers or BigNumbers");if("pointX"in e&&"pointY"in e&&"x0"in t&&"y0"in t&&"z0"in t&&"a"in t&&"b"in t&&"c"in t)return y(e.pointX,e.pointY,e.pointZ,t.x0,t.y0,t.z0,t.a,t.b,t.c);throw new TypeError("Key names do not match")}if(2===Object.keys(e).length&&2===Object.keys(t).length){if(!c(e))throw new TypeError("Values of pointOneX and pointOneY should be numbers or BigNumbers");if(!c(t))throw new TypeError("Values of pointTwoX and pointTwoY should be numbers or BigNumbers");if("pointOneX"in e&&"pointOneY"in e&&"pointTwoX"in t&&"pointTwoY"in t)return g([e.pointOneX,e.pointOneY],[t.pointTwoX,t.pointTwoY]);throw new TypeError("Key names do not match")}if(3===Object.keys(e).length&&3===Object.keys(t).length){if(!p(e))throw new TypeError("Values of pointOneX, pointOneY and pointOneZ should be numbers or BigNumbers");if(!p(t))throw new TypeError("Values of pointTwoX, pointTwoY and pointTwoZ should be numbers or BigNumbers");if("pointOneX"in e&&"pointOneY"in e&&"pointOneZ"in e&&"pointTwoX"in t&&"pointTwoY"in t&&"pointTwoZ"in t)return g([e.pointOneX,e.pointOneY,e.pointOneZ],[t.pointTwoX,t.pointTwoY,t.pointTwoZ]);throw new TypeError("Key names do not match")}throw new TypeError("Invalid Arguments: Try again")},Array:function(e){if(!function(e){if(2===e[0].length&&u(e[0][0])&&u(e[0][1])){if(e.some((e=>2!==e.length||!u(e[0])||!u(e[1]))))return!1}else{if(!(3===e[0].length&&u(e[0][0])&&u(e[0][1])&&u(e[0][2])))return!1;if(e.some((e=>3!==e.length||!u(e[0])||!u(e[1])||!u(e[2]))))return!1}return!0}(e))throw new TypeError("Incorrect array format entered for pairwise distance calculation");return function(e){for(var t=[],n=[],r=[],a=0;a{var{typed:t,config:n,abs:r,add:a,addScalar:i,matrix:s,multiply:o,multiplyScalar:l,divideScalar:u,subtract:c,smaller:p,equalScalar:d,flatten:m,isZero:h,isNumeric:f}=e;return t("intersect",{"Array, Array, Array":y,"Array, Array, Array, Array":g,"Matrix, Matrix, Matrix":function(e,t,n){var r=y(e.valueOf(),t.valueOf(),n.valueOf());return null===r?null:s(r)},"Matrix, Matrix, Matrix, Matrix":function(e,t,n,r){var a=g(e.valueOf(),t.valueOf(),n.valueOf(),r.valueOf());return null===a?null:s(a)}});function y(e,t,n){if(e=b(e),t=b(t),n=b(n),!N(e))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!N(t))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");if(!function(e){return 4===e.length&&f(e[0])&&f(e[1])&&f(e[2])&&f(e[3])}(n))throw new TypeError("Array with 4 numbers expected as third argument");return function(e,t,n,r,a,s,o,p,d,m){var h=l(e,o),f=l(r,o),y=l(t,p),g=l(a,p),b=l(n,d),v=l(s,d),N=c(c(c(m,h),y),b),T=c(c(c(i(i(f,g),v),h),y),b),C=u(N,T);return[i(e,l(C,c(r,e))),i(t,l(C,c(a,t))),i(n,l(C,c(s,n)))]}(e[0],e[1],e[2],t[0],t[1],t[2],n[0],n[1],n[2],n[3])}function g(e,t,s,m){if(e=b(e),t=b(t),s=b(s),m=b(m),2===e.length){if(!v(e))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!v(t))throw new TypeError("Array with 2 numbers or BigNumbers expected for second argument");if(!v(s))throw new TypeError("Array with 2 numbers or BigNumbers expected for third argument");if(!v(m))throw new TypeError("Array with 2 numbers or BigNumbers expected for fourth argument");return function(e,t,s,d){var m=e,f=s,y=c(m,t),g=c(f,d),b=c(l(y[0],g[1]),l(g[0],y[1]));if(h(b))return null;if(p(r(b),n.epsilon))return null;var v=l(g[0],m[1]),N=l(g[1],m[0]),T=l(g[0],f[1]),C=l(g[1],f[0]),A=u(i(c(c(v,N),T),C),b);return a(o(y,A),m)}(e,t,s,m)}if(3===e.length){if(!N(e))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!N(t))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");if(!N(s))throw new TypeError("Array with 3 numbers or BigNumbers expected for third argument");if(!N(m))throw new TypeError("Array with 3 numbers or BigNumbers expected for fourth argument");return function(e,t,n,r,a,s,o,p,m,f,y,g){var b=T(e,o,f,o,t,p,y,p,n,m,g,m),v=T(f,o,r,e,y,p,a,t,g,m,s,n),N=T(e,o,r,e,t,p,a,t,n,m,s,n),C=T(f,o,f,o,y,p,y,p,g,m,g,m),A=T(r,e,r,e,a,t,a,t,s,n,s,n),V=c(l(b,v),l(N,C)),x=c(l(A,C),l(v,v));if(h(x))return null;var S=u(V,x),w=u(i(b,l(S,v)),C),E=i(e,l(S,c(r,e))),D=i(t,l(S,c(a,t))),O=i(n,l(S,c(s,n))),I=i(o,l(w,c(f,o))),R=i(p,l(w,c(y,p))),_=i(m,l(w,c(g,m)));return d(E,I)&&d(D,R)&&d(O,_)?[E,D,O]:null}(e[0],e[1],e[2],t[0],t[1],t[2],s[0],s[1],s[2],m[0],m[1],m[2])}throw new TypeError("Arrays with two or thee dimensional points expected")}function b(e){return 1===e.length?e[0]:e.length>1&&Array.isArray(e[0])&&e.every((e=>Array.isArray(e)&&1===e.length))?m(e):e}function v(e){return 2===e.length&&f(e[0])&&f(e[1])}function N(e){return 3===e.length&&f(e[0])&&f(e[1])&&f(e[2])}function T(e,t,n,r,a,s,o,u,p,d,m,h){var f=l(c(e,t),c(n,r)),y=l(c(a,s),c(o,u)),g=l(c(p,d),c(m,h));return i(i(f,y),g)}})),name$P="sum",dependencies$P=["typed","config","add","numeric"],createSum=factory(name$P,dependencies$P,(e=>{var{typed:t,config:n,add:r,numeric:a}=e;return t(name$P,{"Array | Matrix":i,"Array | Matrix, number | BigNumber":function(e,t){try{return reduce$2(e,t,r)}catch(e){throw improveErrorMessage(e,"sum")}},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function sum");return i(e)}});function i(e){var t;return deepForEach(e,(function(e){try{t=void 0===t?e:r(t,e)}catch(t){throw improveErrorMessage(t,"sum",e)}})),void 0===t&&(t=a(0,n.number)),"string"==typeof t&&(t=a(t,n.number)),t}})),name$O="cumsum",dependencies$O=["typed","add","unaryPlus"],createCumSum=factory(name$O,dependencies$O,(e=>{var{typed:t,add:n,unaryPlus:r}=e;return t(name$O,{Array:a,Matrix:function(e){return e.create(a(e.valueOf()))},"Array, number | BigNumber":s,"Matrix, number | BigNumber":function(e,t){return e.create(s(e.valueOf(),t))},"...":function(e){if(containsCollections(e))throw new TypeError("All values expected to be scalar in function cumsum");return a(e)}});function a(e){try{return i(e)}catch(e){throw improveErrorMessage(e,name$O)}}function i(e){if(0===e.length)return[];for(var t=[r(e[0])],a=1;a=n.length)throw new IndexError(t,n.length);try{return o(e,t)}catch(e){throw improveErrorMessage(e,name$O)}}function o(e,t){var n,r,a;if(t<=0){var s=e[0][0];if(Array.isArray(s)){for(a=_switch$1(e),r=[],n=0;n{var{typed:t,add:n,divide:r}=e;return t(name$N,{"Array | Matrix":a,"Array | Matrix, number | BigNumber":function(e,t){try{var a=reduce$2(e,t,n),i=Array.isArray(e)?arraySize(e):e.size();return r(a,i[t])}catch(e){throw improveErrorMessage(e,"mean")}},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function mean");return a(e)}});function a(e){var t,a=0;if(deepForEach(e,(function(e){try{t=void 0===t?e:n(t,e),a++}catch(t){throw improveErrorMessage(t,"mean",e)}})),0===a)throw new Error("Cannot calculate the mean of an empty array");return r(t,a)}})),name$M="median",dependencies$M=["typed","add","divide","compare","partitionSelect"],createMedian=factory(name$M,dependencies$M,(e=>{var{typed:t,add:n,divide:r,compare:a,partitionSelect:i}=e;function s(e){try{var t=(e=flatten$4(e.valueOf())).length;if(0===t)throw new Error("Cannot calculate median of an empty array");if(t%2==0){for(var n=t/2-1,r=i(e,n+1),s=e[n],u=0;u0&&(s=e[u]);return l(s,r)}var c=i(e,(t-1)/2);return o(c)}catch(e){throw improveErrorMessage(e,"median")}}var o=t({"number | BigNumber | Complex | Unit":function(e){return e}}),l=t({"number | BigNumber | Complex | Unit, number | BigNumber | Complex | Unit":function(e,t){return r(n(e,t),2)}});return t(name$M,{"Array | Matrix":s,"Array | Matrix, number | BigNumber":function(e,t){throw new Error("median(A, dim) is not yet supported")},"...":function(e){if(containsCollections(e))throw new TypeError("Scalar values expected in function median");return s(e)}})})),name$L="mad",dependencies$L=["typed","abs","map","median","subtract"],createMad=factory(name$L,dependencies$L,(e=>{var{typed:t,abs:n,map:r,median:a,subtract:i}=e;return t(name$L,{"Array | Matrix":s,"...":function(e){return s(e)}});function s(e){if(0===(e=flatten$4(e.valueOf())).length)throw new Error("Cannot calculate median absolute deviation (mad) of an empty array");try{var t=a(e);return a(r(e,(function(e){return n(i(e,t))})))}catch(e){throw e instanceof TypeError&&-1!==e.message.indexOf("median")?new TypeError(e.message.replace("median","mad")):improveErrorMessage(e,"mad")}}})),DEFAULT_NORMALIZATION="unbiased",name$K="variance",dependencies$K=["typed","add","subtract","multiply","divide","apply","isNaN"],createVariance=factory(name$K,dependencies$K,(e=>{var{typed:t,add:n,subtract:r,multiply:a,divide:i,apply:s,isNaN:o}=e;return t(name$K,{"Array | Matrix":function(e){return l(e,DEFAULT_NORMALIZATION)},"Array | Matrix, string":l,"Array | Matrix, number | BigNumber":function(e,t){return u(e,t,DEFAULT_NORMALIZATION)},"Array | Matrix, number | BigNumber, string":u,"...":function(e){return l(e,DEFAULT_NORMALIZATION)}});function l(e,t){var s,l=0;if(0===e.length)throw new SyntaxError("Function variance requires one or more parameters (0 provided)");if(deepForEach(e,(function(e){try{s=void 0===s?e:n(s,e),l++}catch(t){throw improveErrorMessage(t,"variance",e)}})),0===l)throw new Error("Cannot calculate variance of an empty array");var u=i(s,l);if(s=void 0,deepForEach(e,(function(e){var t=r(e,u);s=void 0===s?a(t,t):n(s,a(t,t))})),o(s))return s;switch(t){case"uncorrected":return i(s,l);case"biased":return i(s,l+1);case"unbiased":var c=isBigNumber(s)?s.mul(0):0;return 1===l?c:i(s,l-1);default:throw new Error('Unknown normalization "'+t+'". Choose "unbiased" (default), "uncorrected", or "biased".')}}function u(e,t,n){try{if(0===e.length)throw new SyntaxError("Function variance requires one or more parameters (0 provided)");return s(e,t,(e=>l(e,n)))}catch(e){throw improveErrorMessage(e,"variance")}}})),name$J="quantileSeq",dependencies$J=["typed","add","multiply","partitionSelect","compare"],createQuantileSeq=factory(name$J,dependencies$J,(e=>{var{typed:t,add:n,multiply:r,partitionSelect:a,compare:i}=e;function s(e,t,s){var l=flatten$4(e),u=l.length;if(0===u)throw new Error("Cannot calculate quantile of an empty sequence");if(isNumber$1(t)){var c=t*(u-1),p=c%1;if(0===p){var d=s?l[c]:a(l,c);return o(d),d}var m,h,f=Math.floor(c);if(s)m=l[f],h=l[f+1];else{h=a(l,f+1),m=l[f];for(var y=0;y0&&(m=l[y])}return o(m),o(h),n(r(m,1-p),r(h,p))}var g=t.times(u-1);if(g.isInteger()){g=g.toNumber();var b=s?l[g]:a(l,g);return o(b),b}var v,N,T=g.floor(),C=g.minus(T),A=T.toNumber();if(s)v=l[A],N=l[A+1];else{N=a(l,A+1),v=l[A];for(var V=0;V0&&(v=l[V])}o(v),o(N);var x=new C.constructor(1);return n(r(v,x.minus(C)),r(N,C))}var o=t({"number | BigNumber | Unit":function(e){return e}});return function(e,t,n){var r,a,i;if(arguments.length<2||arguments.length>3)throw new SyntaxError("Function quantileSeq requires two or three parameters");if(isCollection(e)){if("boolean"==typeof(n=n||!1)){if(a=e.valueOf(),isNumber$1(t)){if(t<0)throw new Error("N/prob must be non-negative");if(t<=1)return s(a,t,n);if(t>1){if(!isInteger$1(t))throw new Error("N must be a positive integer");var o=t+1;r=new Array(t);for(var l=0;l4294967295)throw new Error("N must be less than or equal to 2^32-1, as that is the maximum length of an Array");var p=new u(c+1);r=new Array(c);for(var d=0;d1)throw new Error("Probability must be between 0 and 1, inclusive")}else{if(!isBigNumber(h))throw new TypeError("Unexpected type of argument in function quantileSeq");if(i=new h.constructor(1),h.isNegative()||h.gt(i))throw new Error("Probability must be between 0 and 1, inclusive")}r[m]=s(a,h,n)}return r}throw new TypeError("Unexpected type of argument in function quantileSeq")}throw new TypeError("Unexpected type of argument in function quantileSeq")}throw new TypeError("Unexpected type of argument in function quantileSeq")}})),name$I="std",dependencies$I=["typed","sqrt","variance"],createStd=factory(name$I,dependencies$I,(e=>{var{typed:t,sqrt:n,variance:r}=e;return t(name$I,{"Array | Matrix":a,"Array | Matrix, string":a,"Array | Matrix, number | BigNumber":a,"Array | Matrix, number | BigNumber, string":a,"...":function(e){return a(e)}});function a(e,t){if(0===e.length)throw new SyntaxError("Function std requires one or more parameters (0 provided)");try{return n(r.apply(null,arguments))}catch(e){throw e instanceof TypeError&&-1!==e.message.indexOf(" variance")?new TypeError(e.message.replace(" variance"," std")):e}}})),name$H="combinations",dependencies$H=["typed"],createCombinations=factory(name$H,dependencies$H,(e=>{var{typed:t}=e;return t(name$H,{"number, number":combinationsNumber,"BigNumber, BigNumber":function(e,t){var n,r,a=e.constructor,i=e.minus(t),s=new a(1);if(!isPositiveInteger$2(e)||!isPositiveInteger$2(t))throw new TypeError("Positive integer value expected in function combinations");if(t.gt(e))throw new TypeError("k must be less than n in function combinations");if(n=s,t.lt(i))for(r=s;r.lte(i);r=r.plus(s))n=n.times(t.plus(r)).dividedBy(r);else for(r=s;r.lte(t);r=r.plus(s))n=n.times(i.plus(r)).dividedBy(r);return n}})}));function isPositiveInteger$2(e){return e.isInteger()&&e.gte(0)}var name$G="combinationsWithRep",dependencies$G=["typed"],createCombinationsWithRep=factory(name$G,dependencies$G,(e=>{var{typed:t}=e;return t(name$G,{"number, number":function(e,t){if(!isInteger$1(e)||e<0)throw new TypeError("Positive integer value expected in function combinationsWithRep");if(!isInteger$1(t)||t<0)throw new TypeError("Positive integer value expected in function combinationsWithRep");if(e<1)throw new TypeError("k must be less than or equal to n + k - 1");return t{var{typed:t,config:n,multiplyScalar:r,pow:a,BigNumber:i,Complex:s}=e;return t(name$F,{number:gammaNumber,Complex:function(e){if(0===e.im)return this(e.re);if(e.re<.5){var t=new s(1-e.re,-e.im),n=new s(Math.PI*e.re,Math.PI*e.im);return new s(Math.PI).div(n.sin()).div(this(t))}e=new s(e.re-1,e.im);for(var r=new s(gammaP[0],0),a=1;a2;)l+=a-=2,s=s.times(l);return new i(s.toPrecision(i.precision))}})),name$E="lgamma",dependencies$E=["Complex","typed"],createLgamma=factory(name$E,dependencies$E,(e=>{var{Complex:t,typed:n}=e,r=[-.029550653594771242,.00641025641025641,-.0019175269175269176,.0008417508417508417,-.0005952380952380953,.0007936507936507937,-.002777777777777778,.08333333333333333];return n(name$E,{number:lgammaNumber,Complex:function(e){if(e.isNaN())return new t(NaN,NaN);if(0===e.im)return new t(lgammaNumber(e.re),0);if(e.re>=7||Math.abs(e.im)>=7)return a(e);if(e.re<=.1){var n=copysign(6.283185307179586,e.im)*Math.floor(.5*e.re+.25),r=e.mul(Math.PI).sin().log(),s=this(new t(1-e.re,-e.im));return new t(1.1447298858494002,n).sub(r).sub(s)}return e.im>=0?i(e):i(e.conjugate()).conjugate()},BigNumber:function(){throw new Error("mathjs doesn't yet provide an implementation of the algorithm lgamma for BigNumber")}});function a(e){for(var n=e.sub(.5).mul(e.log()).sub(e).add(lnSqrt2PI),a=new t(1,0).div(e),i=a.div(e),s=r[0],o=r[1],l=2*i.re,u=i.re*i.re+i.im*i.im,c=2;c<8;c++){var p=o;o=-u*s+r[c],s=l*s+p}var d=a.mul(i.mul(s).add(o));return n.add(d)}function i(e){var n=0,r=0,i=e;for(e=e.add(1);e.re<=7;){var s=(i=i.mul(e)).im<0?1:0;0!==s&&0===r&&n++,r=s,e=e.add(1)}return a(e).sub(i.log()).sub(new t(0,2*n*Math.PI*1))}})),name$D="factorial",dependencies$D=["typed","gamma"],createFactorial=factory(name$D,dependencies$D,(e=>{var{typed:t,gamma:n}=e;return t(name$D,{number:function(e){if(e<0)throw new Error("Value must be non-negative");return n(e+1)},BigNumber:function(e){if(e.isNegative())throw new Error("Value must be non-negative");return n(e.plus(1))},"Array | Matrix":function(e){return deepMap(e,this)}})})),name$C="kldivergence",dependencies$C=["typed","matrix","divide","sum","multiply","dotDivide","log","isNumeric"],createKldivergence=factory(name$C,dependencies$C,(e=>{var{typed:t,matrix:n,divide:r,sum:a,multiply:i,dotDivide:s,log:o,isNumeric:l}=e;return t(name$C,{"Array, Array":function(e,t){return u(n(e),n(t))},"Matrix, Array":function(e,t){return u(e,n(t))},"Array, Matrix":function(e,t){return u(n(e),t)},"Matrix, Matrix":function(e,t){return u(e,t)}});function u(e,t){var n=t.size().length,u=e.size().length;if(n>1)throw new Error("first object must be one dimensional");if(u>1)throw new Error("second object must be one dimensional");if(n!==u)throw new Error("Length of two vectors must be equal");if(0===a(e))throw new Error("Sum of elements in first object must be non zero");if(0===a(t))throw new Error("Sum of elements in second object must be non zero");var c=r(e,a(e)),p=r(t,a(t)),d=a(i(c,o(s(c,p))));return l(d)?d:Number.NaN}})),name$B="multinomial",dependencies$B=["typed","add","divide","multiply","factorial","isInteger","isPositive"],createMultinomial=factory(name$B,dependencies$B,(e=>{var{typed:t,add:n,divide:r,multiply:a,factorial:i,isInteger:s,isPositive:o}=e;return t(name$B,{"Array | Matrix":function(e){var t=0,l=1;return deepForEach(e,(function(e){if(!s(e)||!o(e))throw new TypeError("Positive integer value expected in function multinomial");t=n(t,e),l=a(l,i(e))})),r(i(t),l)}})})),name$A="permutations",dependencies$A=["typed","factorial"],createPermutations=factory(name$A,dependencies$A,(e=>{var{typed:t,factorial:n}=e;return t(name$A,{"number | BigNumber":n,"number, number":function(e,t){if(!isInteger$1(e)||e<0)throw new TypeError("Positive integer value expected in function permutations");if(!isInteger$1(t)||t<0)throw new TypeError("Positive integer value expected in function permutations");if(t>e)throw new TypeError("second argument k must be less than or equal to first argument n");return product(e-t+1,e)},"BigNumber, BigNumber":function(e,t){var n,r;if(!isPositiveInteger(e)||!isPositiveInteger(t))throw new TypeError("Positive integer value expected in function permutations");if(t.gt(e))throw new TypeError("second argument k must be less than or equal to first argument n");for(n=e.mul(0).add(1),r=e.minus(t).plus(1);r.lte(e);r=r.plus(1))n=n.times(r);return n}})}));function isPositiveInteger(e){return e.isInteger()&&e.gte(0)}var alea$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this,n=function(){var e=4022871197;return function(t){t=String(t);for(var n=0;n>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)}}();t.next=function(){var e=2091639*t.s0+2.3283064365386963e-10*t.c;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=0|e)},t.c=1,t.s0=n(" "),t.s1=n(" "),t.s2=n(" "),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function a(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function i(e,t){var n=new r(e),i=t&&t.state,s=n.next;return s.int32=function(){return 4294967296*n.next()|0},s.double=function(){return s()+11102230246251565e-32*(2097152*s()|0)},s.quick=s,i&&("object"==typeof i&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.alea=i}(0,e)}(alea$1);var xor128$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,i&&("object"==typeof i&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.xor128=i}(0,e)}(xor128$1);var xorwow$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r>>4),t.next()}function a(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function i(e,t){var n=new r(e),i=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,i&&("object"==typeof i&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.xorwow=i}(0,e)}(xorwow$1);var xorshift7$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.x,a=t.i;return e=r[a],n=(e^=e>>>7)^e<<24,n^=(e=r[a+1&7])^e>>>10,n^=(e=r[a+3&7])^e>>>3,n^=(e=r[a+4&7])^e<<7,e=r[a+7&7],n^=(e^=e<<13)^e<<9,r[a]=n,t.i=a+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n0;--n)e.next()}(t,e)}function a(e,t){return t.x=e.x.slice(),t.i=e.i,t}function i(e,t){null==e&&(e=+new Date);var n=new r(e),i=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,i&&(i.x&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.xorshift7=i}(0,e)}(xorshift7$1);var xor4096$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.w,a=t.X,i=t.i;return t.w=r=r+1640531527|0,n=a[i+34&127],e=a[i=i+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=a[i]=n^e,t.i=i,n+(r^r>>>16)|0},function(e,t){var n,r,a,i,s,o=[],l=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,l=Math.max(l,t.length)),a=0,i=-32;i>>15,r^=r<<4,r^=r>>>13,i>=0&&(s=s+1640531527|0,a=0==(n=o[127&i]^=r+s)?a+1:0);for(a>=128&&(o[127&(t&&t.length||0)]=-1),a=127,i=512;i>0;--i)r=o[a+34&127],n=o[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,o[a]=r^n;e.w=s,e.X=o,e.i=a}(t,e)}function a(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function i(e,t){null==e&&(e=+new Date);var n=new r(e),i=t&&t.state,s=function(){return(n.next()>>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,i&&(i.X&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.xor4096=i}(0,e)}(xor4096$1);var tychei$1={exports:{}};!function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,a=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^a,a=a-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^a,t.a=a-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r>>0)/4294967296};return s.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},s.int32=n.next,s.quick=s,i&&("object"==typeof i&&a(i,n),s.state=function(){return a(n,{})}),s}t&&t.exports?t.exports=i:this.tychei=i}(0,e)}(tychei$1);var seedrandom$2={exports:{}},_nodeResolve_empty={},_nodeResolve_empty$1=Object.freeze({__proto__:null,default:_nodeResolve_empty}),require$$0=getAugmentedNamespace(_nodeResolve_empty$1);!function(e){!function(t,n,r){var a,i=256,s="random",o=r.pow(i,6),l=r.pow(2,52),u=2*l,c=255;function p(e,c,p){var g=[],b=f(h((c=1==c?{entropy:!0}:c||{}).entropy?[e,y(n)]:null==e?function(){try{var e;return a&&(e=a.randomBytes)?e=e(i):(e=new Uint8Array(i),(t.crypto||t.msCrypto).getRandomValues(e)),y(e)}catch(e){var r=t.navigator,s=r&&r.plugins;return[+new Date,t,s,t.screen,y(n)]}}():e,3),g),v=new d(g),N=function(){for(var e=v.g(6),t=o,n=0;e=u;)e/=2,t/=2,n>>>=1;return(e+n)/t};return N.int32=function(){return 0|v.g(4)},N.quick=function(){return v.g(4)/4294967296},N.double=N,f(y(v.S),n),(c.pass||p||function(e,t,n,a){return a&&(a.S&&m(a,v),e.state=function(){return m(v,{})}),n?(r[s]=e,t):e})(N,b,"global"in c?c.global:this==r,c.state)}function d(e){var t,n=e.length,r=this,a=0,s=r.i=r.j=0,o=r.S=[];for(n||(e=[n++]);a{var{typed:t,config:n,on:r}=e,a=createRng(n.randomSeed);return r&&r("config",(function(e,t){e.randomSeed!==t.randomSeed&&(a=createRng(e.randomSeed))})),t(name$z,{"Array | Matrix":function(e){return i(e,{})},"Array | Matrix, Object":function(e,t){return i(e,t)},"Array | Matrix, number":function(e,t){return i(e,{number:t})},"Array | Matrix, Array | Matrix":function(e,t){return i(e,{weights:t})},"Array | Matrix, Array | Matrix, number":function(e,t,n){return i(e,{number:n,weights:t})},"Array | Matrix, number, Array | Matrix":function(e,t,n){return i(e,{number:t,weights:n})}});function i(e,t){var{number:n,weights:r,elementWise:i=!0}=t,s=void 0===n;s&&(n=1);var o=isMatrix(e)?e.create:isMatrix(r)?r.create:null;e=e.valueOf(),r&&(r=r.valueOf()),!0===i&&(e=flatten$4(e),r=flatten$4(r));var l=0;if(void 0!==r){if(r.length!==e.length)throw new Error("Weights must have the same length as possibles");for(var u=0,c=r.length;u1)for(var r=0,a=e.shift();r{var{typed:t,config:n,on:r}=e,a=createRng(n.randomSeed);return r&&r("config",(function(e,t){e.randomSeed!==t.randomSeed&&(a=createRng(e.randomSeed))})),t(name$y,{"":()=>s(0,1),number:e=>s(0,e),"number, number":(e,t)=>s(e,t),"Array | Matrix":e=>i(e,0,1),"Array | Matrix, number":(e,t)=>i(e,0,t),"Array | Matrix, number, number":(e,t,n)=>i(e,t,n)});function i(e,t,n){var r=randomMatrix(e.valueOf(),(()=>s(t,n)));return isMatrix(e)?e.create(r):r}function s(e,t){return e+a()*(t-e)}})),name$x="randomInt",dependencies$x=["typed","config","?on"],createRandomInt=factory(name$x,dependencies$x,(e=>{var{typed:t,config:n,on:r}=e,a=createRng(n.randomSeed);return r&&r("config",(function(e,t){e.randomSeed!==t.randomSeed&&(a=createRng(e.randomSeed))})),t(name$x,{"":()=>s(0,1),number:e=>s(0,e),"number, number":(e,t)=>s(e,t),"Array | Matrix":e=>i(e,0,1),"Array | Matrix, number":(e,t)=>i(e,0,t),"Array | Matrix, number, number":(e,t,n)=>i(e,t,n)});function i(e,t,n){var r=randomMatrix(e.valueOf(),(()=>s(t,n)));return isMatrix(e)?e.create(r):r}function s(e,t){return Math.floor(e+a()*(t-e))}})),name$w="stirlingS2",dependencies$w=["typed","addScalar","subtract","multiplyScalar","divideScalar","pow","factorial","combinations","isNegative","isInteger","number","?bignumber","larger"],createStirlingS2=factory(name$w,dependencies$w,(e=>{var{typed:t,addScalar:n,subtract:r,multiplyScalar:a,divideScalar:i,pow:s,factorial:o,combinations:l,isNegative:u,isInteger:c,number:p,bignumber:d,larger:m}=e,h=[],f=[];return t(name$w,{"number | BigNumber, number | BigNumber":function(e,t){if(!c(e)||u(e)||!c(t)||u(t))throw new TypeError("Non-negative integer value expected in function stirlingS2");if(m(t,e))throw new TypeError("k must be less than or equal to n in function stirlingS2");var r=!(isNumber$1(e)&&isNumber$1(t)),i=r?f:h,s=r?d:p,o=p(e),l=p(t);if(i[o]&&i[o].length>l)return i[o][l];for(var y=0;y<=o;++y)if(i[y]||(i[y]=[s(0===y?1:0)]),0!==y)for(var g=i[y],b=i[y-1],v=g.length;v<=y&&v<=l;++v)g[v]=v===y?1:n(a(s(v),b[v]),b[v-1]);return i[o][l]}})})),name$v="bellNumbers",dependencies$v=["typed","addScalar","isNegative","isInteger","stirlingS2"],createBellNumbers=factory(name$v,dependencies$v,(e=>{var{typed:t,addScalar:n,isNegative:r,isInteger:a,stirlingS2:i}=e;return t(name$v,{"number | BigNumber":function(e){if(!a(e)||r(e))throw new TypeError("Non-negative integer value expected in function bellNumbers");for(var t=0,s=0;s<=e;s++)t=n(t,i(e,s));return t}})})),name$u="catalan",dependencies$u=["typed","addScalar","divideScalar","multiplyScalar","combinations","isNegative","isInteger"],createCatalan=factory(name$u,dependencies$u,(e=>{var{typed:t,addScalar:n,divideScalar:r,multiplyScalar:a,combinations:i,isNegative:s,isInteger:o}=e;return t(name$u,{"number | BigNumber":function(e){if(!o(e)||s(e))throw new TypeError("Non-negative integer value expected in function catalan");return r(i(a(e,2),e),n(e,1))}})})),name$t="composition",dependencies$t=["typed","addScalar","combinations","isNegative","isPositive","isInteger","larger"],createComposition=factory(name$t,dependencies$t,(e=>{var{typed:t,addScalar:n,combinations:r,isPositive:a,isNegative:i,isInteger:s,larger:o}=e;return t(name$t,{"number | BigNumber, number | BigNumber":function(e,t){if(!(s(e)&&a(e)&&s(t)&&a(t)))throw new TypeError("Positive integer value expected in function composition");if(o(t,e))throw new TypeError("k must be less than or equal to n in function composition");return r(n(e,-1),n(t,-1))}})})),name$s="leafCount",dependencies$s=["parse","typed"],createLeafCount=factory(name$s,dependencies$s,(e=>{var{parse:t,typed:n}=e;function r(e){var t=0;return e.forEach((e=>{t+=r(e)})),t||1}return n(name$s,{string:function(e){return this(t(e))},Node:function(e){return r(e)}})}));function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _objectSpread(e){for(var t=1;t{var{FunctionNode:t,OperatorNode:n,SymbolNode:r}=e,a=!0,i=!1,s="defaultF",o={add:{trivial:a,total:a,commutative:a,associative:a},unaryPlus:{trivial:a,total:a,commutative:a,associative:a},subtract:{trivial:i,total:a,commutative:i,associative:i},multiply:{trivial:a,total:a,commutative:a,associative:a},divide:{trivial:i,total:a,commutative:i,associative:i},paren:{trivial:a,total:a,commutative:a,associative:i},defaultF:{trivial:i,total:a,commutative:i,associative:i}};function l(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:o,r=s;if("string"==typeof e?r=e:isOperatorNode(e)?r=e.fn.toString():isFunctionNode(e)?r=e.name:isParenthesisNode(e)&&(r="paren"),hasOwnProperty$2(n,r)){var a=n[r];if(hasOwnProperty$2(a,t))return a[t];if(hasOwnProperty$2(o,r))return o[r][t]}if(hasOwnProperty$2(n,s)){var i=n[s];return hasOwnProperty$2(i,t)?i[t]:o[s][t]}if(hasOwnProperty$2(o,r)){var l=o[r];if(hasOwnProperty$2(l,t))return l[t]}return o[s][t]}function u(e){return l(e,"associative",arguments.length>1&&void 0!==arguments[1]?arguments[1]:o)}function c(e,t){var n,r=[];return u(e,t)?(n=e.op,function e(t){for(var a=0;a1&&void 0!==arguments[1]?arguments[1]:o)},isAssociative:u,mergeContext:function(e,t){var n=_objectSpread({},e);for(var r in t)hasOwnProperty$2(e,r)?n[r]=_objectSpread(_objectSpread({},t[r]),e[r]):n[r]=t[r];return n},flatten:function e(t,n){if(!t.args||0===t.args.length)return t;t.args=c(t,n);for(var r=0;r2&&u(t,n)){for(var s=t.args.pop();t.args.length>0;)s=r([t.args.pop(),s]);t.args=s.args}}},unflattenl:function e(t,n){if(t.args&&0!==t.args.length){for(var r=p(t),a=t.args.length,i=0;i2&&u(t,n)){for(var s=t.args.shift();t.args.length>0;)s=r([s,t.args.shift()]);t.args=s.args}}},defaultContext:o,realContext:{divide:{total:i},log:{total:i}},positiveContext:{subtract:{total:i},abs:{trivial:a},log:{total:a}}}})),name$q="simplifyConstant",dependencies$q=["typed","config","mathWithTransform","matrix","?fraction","?bignumber","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","SymbolNode"],createSimplifyConstant=factory(name$q,dependencies$q,(e=>{var{typed:t,config:n,mathWithTransform:r,matrix:a,fraction:i,bignumber:s,AccessorNode:o,ArrayNode:l,ConstantNode:u,FunctionNode:c,IndexNode:p,ObjectNode:d,OperatorNode:m,SymbolNode:h}=e,{isCommutative:f,isAssociative:y,allChildren:g,createMakeNodeFunction:b}=createUtil({FunctionNode:c,OperatorNode:m,SymbolNode:h});function v(e,t){return A(E(e,t))}function N(e){return isFraction(e)?e.valueOf():e instanceof Array?e.map(N):isMatrix(e)?a(N(e.valueOf())):e}function T(e,t,n){try{return r[e].apply(null,t)}catch(a){return t=t.map(N),x(r[e].apply(null,t),n)}}var C=t({Fraction:function(e){var t,n=e.s*e.n;return t=n<0?new m("-","unaryMinus",[new u(-n)]):new u(n),1===e.d?t:new m("/","divide",[t,new u(e.d)])},number:function(e){return e<0?S(new u(-e)):new u(e)},BigNumber:function(e){return e<0?S(new u(-e)):new u(e)},Complex:function(e){throw new Error("Cannot convert Complex number to Node")},string:function(e){return new u(e)},Matrix:function(e){return new l(e.valueOf().map((e=>C(e))))}});function A(e){return isNode(e)?e:C(e)}function V(e,t){if(t&&!1!==t.exactFractions&&isFinite(e)&&i){var n=i(e),r=t&&"number"==typeof t.fractionsLimit?t.fractionsLimit:1/0;if(n.valueOf()===e&&n.nE(e,t)));if(!n.some(isNode))try{return T(e.name,n,t)}catch(e){}if("size"===e.name&&1===n.length&&isArrayNode(n[0])){for(var i=[],s=n[0];isArrayNode(s);)i.push(s.items.length),s=s.items[0];return a(i)}return new c(e.name,n.map(A))}case"OperatorNode":var m,h,N=e.fn.toString(),C=b(e);if(isOperatorNode(e)&&e.isUnary())h=isNode((m=[E(e.args[0],t)])[0])?C(m):T(N,m,t);else if(y(e,t.context))if(m=(m=g(e,t.context)).map((e=>E(e,t))),f(N,t.context)){for(var V=[],S=[],D=0;D1?(h=w(N,V,C,t),S.unshift(h),h=w(N,S,C,t)):h=w(N,m,C,t)}else h=w(N,m,C,t);else h=w(N,m=e.args.map((e=>E(e,t))),C,t);return h;case"ParenthesisNode":return E(e.content,t);case"AccessorNode":return function(e,t,n){if(!isIndexNode(t))return new o(A(e),A(t));if(isArrayNode(e)||isMatrix(e)){for(var r=Array.from(t.dimensions);r.length>0;)if(isConstantNode(r[0])&&"string"!=typeof r[0].value){var i=x(r.shift().value,n);isArrayNode(e)?e=e.items[i-1]:(e=e.valueOf()[i-1])instanceof Array&&(e=a(e))}else{if(!(r.length>1&&isConstantNode(r[1])&&"string"!=typeof r[1].value))break;var s=x(r[1].value,n),c=[],d=isArrayNode(e)?e.items:e.valueOf();for(var m of d)if(isArrayNode(m))c.push(m.items[s-1]);else{if(!isMatrix(e))break;c.push(m[s-1])}if(c.length!==d.length)break;e=isArrayNode(e)?new l(c):a(c),r.splice(1,1)}return r.length===t.dimensions.length?new o(A(e),t):r.length>0?(t=new p(r),new o(A(e),t)):e}if(isObjectNode(e)&&1===t.dimensions.length&&isConstantNode(t.dimensions[0])){var h=t.dimensions[0].value;return h in e.properties?e.properties[h]:new u}return new o(A(e),t)}(E(e.object,t),E(e.index,t),t);case"ArrayNode":var O=e.items.map((e=>E(e,t)));return O.some(isNode)?new l(O.map(A)):a(O);case"IndexNode":return new p(e.dimensions.map((e=>v(e,t))));case"ObjectNode":var I={};for(var R in e.properties)I[R]=v(e.properties[R],t);return new d(I);default:throw new Error("Unimplemented node type in simplifyConstant: ".concat(e.type))}}return v})),name$p="simplify",dependencies$p=["config","typed","parse","add","subtract","multiply","divide","pow","isZero","equal","resolve","simplifyCore","?fraction","?bignumber","mathWithTransform","matrix","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","SymbolNode"],createSimplify=factory(name$p,dependencies$p,(e=>{var{config:t,typed:n,parse:r,add:a,subtract:i,multiply:s,divide:o,pow:l,isZero:u,equal:c,resolve:p,simplifyCore:d,fraction:m,bignumber:h,mathWithTransform:f,matrix:y,AccessorNode:g,ArrayNode:b,ConstantNode:v,FunctionNode:N,IndexNode:T,ObjectNode:C,OperatorNode:A,ParenthesisNode:V,SymbolNode:x}=e,S=createSimplifyConstant({typed:n,config:t,mathWithTransform:f,matrix:y,fraction:m,bignumber:h,AccessorNode:g,ArrayNode:b,ConstantNode:v,FunctionNode:N,IndexNode:T,ObjectNode:C,OperatorNode:A,SymbolNode:x}),{hasProperty:w,isCommutative:E,isAssociative:D,mergeContext:O,flatten:I,unflattenr:R,unflattenl:_,createMakeNodeFunction:M,defaultContext:P,realContext:F,positiveContext:k}=createUtil({FunctionNode:N,OperatorNode:A,SymbolNode:x}),$=n("simplify",{string:function(e){return this(r(e),this.rules,createEmptyMap(),{})},"string, Map | Object":function(e,t){return this(r(e),this.rules,t,{})},"string, Map | Object, Object":function(e,t,n){return this(r(e),this.rules,t,n)},"string, Array":function(e,t){return this(r(e),t,createEmptyMap(),{})},"string, Array, Map | Object":function(e,t,n){return this(r(e),t,n,{})},"string, Array, Map | Object, Object":function(e,t,n,a){return this(r(e),t,n,a)},"Node, Map | Object":function(e,t){return this(e,this.rules,t,{})},"Node, Map | Object, Object":function(e,t,n){return this(e,this.rules,t,n)},Node:function(e){return this(e,this.rules,createEmptyMap(),{})},"Node, Array":function(e,t){return this(e,t,createEmptyMap(),{})},"Node, Array, Map | Object":function(e,t,n){return this(e,t,n,{})},"Node, Array, Object, Object":function(e,t,n,r){return this(e,t,createMap$1(n),r)},"Node, Array, Map, Object":function(e,t,n,r){var a=r.consoleDebug;t=function(e,t){for(var n=[],r=0;r ").concat(t[u].r.toString()))),a){var d=i.toString({parenthesis:"all"});d!==l&&(console.log("Applying",c,"produced",d),l=d)}_(i,r.context)}o=i.toString({parenthesis:"all"})}return i}});function B(e){return e.transform((function(e,t,n){return isParenthesisNode(e)?B(e.content):e}))}$.defaultContext=P,$.realContext=F,$.positiveContext=k;var L={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};function z(e,t){var n={};if(e.s){var a=e.s.split("->");if(2!==a.length)throw SyntaxError("Could not parse rule: "+e.s);n.l=a[0],n.r=a[1]}else n.l=e.l,n.r=e.r;for(var i of(n.l=B(r(n.l)),n.r=B(r(n.r)),["imposeContext","repeat","assuming"]))i in e&&(n[i]=e[i]);if(e.evaluate&&(n.evaluate=r(e.evaluate)),D(n.l,t)){var s=M(n.l),o=new x("_p"+U++);n.expanded={},n.expanded.l=s([n.l.clone(),o]),I(n.expanded.l,t),R(n.expanded.l,t),n.expanded.r=s([n.r,o])}return n}$.rules=[d,{l:"log(e)",r:"1"},{s:"n-n1 -> n+-n1",assuming:{subtract:{total:!0}}},{s:"n-n -> 0",assuming:{subtract:{total:!1}}},{s:"-(c*v) -> v * (-c)",assuming:{multiply:{commutative:!0},subtract:{total:!0}}},{s:"-(c*v) -> (-c) * v",assuming:{multiply:{commutative:!1},subtract:{total:!0}}},{s:"-(v*c) -> v * (-c)",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:" v * ( v * n1 + n2)",r:"v^2 * n1 + v * n2"},{s:" v * (v^n4 * n1 + n2) -> v^(1+n4) * n1 + v * n2",assuming:{divide:{total:!0}}},{s:"v^n3 * ( v * n1 + n2) -> v^(n3+1) * n1 + v^n3 * n2",assuming:{divide:{total:!0}}},{s:"v^n3 * (v^n4 * n1 + n2) -> v^(n3+n4) * n1 + v^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:"v*n + v",r:"v*(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*v + v -> (n+1)*v",assuming:{multiply:{commutative:!1}}},{s:"n1*n3 + n2*n3 -> (n1+n2)*n3",assuming:{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*c + c",r:"(n+1)*c"},{s:"c*n + c -> c*(n+1)",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:"c+v -> v+c",assuming:{add:{commutative:!0}},imposeContext:{add:{commutative:!1}}},{s:"v*c -> c*v",assuming:{multiply:{commutative:!0}},imposeContext:{multiply:{commutative:!1}}},{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"}];var U=0;function j(e,t,n){var r=e;if(e)for(var a=0;a=2&&2===e.args.length){for(var i=function(e,t){var n,r,a=[],i=M(e);if(E(e,t))for(var s=0;s1&&(l=i(e.args.slice(0,o))),n=1===(r=e.args.slice(o)).length?r[0]:i(r),a.push(i([l,n]))}return a}(t,n),s=[],o=0;o2)throw Error("Unexpected non-binary associative function: "+e.toString());return[]}for(var u=[],p=0;p2)throw new Error("permuting >2 commutative non-associative rule arguments not yet implemented");var m=W(e.args[0],t.args[1],n);if(0===m.length)return[];var h=W(e.args[1],t.args[0],n);if(0===h.length)return[];u=[m,h]}a=function(e){if(0===e.length)return e;for(var t=e.reduce(H),n=[],r={},a=0;a{var{equal:t,isZero:n,add:r,subtract:a,multiply:i,divide:s,pow:o,AccessorNode:l,ArrayNode:u,ConstantNode:c,FunctionNode:p,IndexNode:d,ObjectNode:m,OperatorNode:h,ParenthesisNode:f,SymbolNode:y}=e,g=new c(0),b=new c(1),{hasProperty:v,isCommutative:N}=createUtil({FunctionNode:p,OperatorNode:h,SymbolNode:y});return function e(f,y){var T=y?y.context:void 0;if(v(f,"trivial",T)){if(isFunctionNode(f)&&1===f.args.length)return e(f.args[0],y);var C=!1,A=0;if(f.forEach((t=>{1==++A&&(C=e(t,y))})),1===A)return C}if(isOperatorNode(f)&&f.isUnary()){var V=e(f.args[0],y);if("-"===f.op){if(isOperatorNode(V)){if(V.isUnary()&&"-"===V.op)return V.args[0];if(V.isBinary()&&"subtract"===V.fn)return new h("-","subtract",[V.args[1],V.args[0]])}return new h(f.op,f.fn,[V])}}else{if(isOperatorNode(f)&&f.isBinary()){var x=e(f.args[0],y),S=e(f.args[1],y);if("+"===f.op){if(isConstantNode(x)){if(n(x.value))return S;if(isConstantNode(S))return new c(r(x.value,S.value))}return isConstantNode(S)&&n(S.value)?x:isOperatorNode(S)&&S.isUnary()&&"-"===S.op?new h("-","subtract",[x,S.args[0]]):new h(f.op,f.fn,S?[x,S]:[x])}if("-"===f.op){if(isConstantNode(x)&&S){if(isConstantNode(S))return new c(a(x.value,S.value));if(n(x.value))return new h("-","unaryMinus",[S])}if("subtract"===f.fn)return isConstantNode(S)&&n(S.value)?x:isOperatorNode(S)&&S.isUnary()&&"-"===S.op?e(new h("+","add",[x,S.args[0]]),y):new h(f.op,f.fn,[x,S])}else{if("*"===f.op){if(isConstantNode(x)){if(n(x.value))return g;if(t(x.value,1))return S;if(isConstantNode(S))return new c(i(x.value,S.value))}if(isConstantNode(S)){if(n(S.value))return g;if(t(S.value,1))return x;if(isOperatorNode(x)&&x.isBinary()&&x.op===f.op&&N(f,T)){var w=x.args[0];if(isConstantNode(w)){var E=new c(i(w.value,S.value));return new h(f.op,f.fn,[E,x.args[1]],f.implicit)}}return N(f,T)?new h(f.op,f.fn,[S,x],f.implicit):new h(f.op,f.fn,[x,S],f.implicit)}return new h(f.op,f.fn,[x,S],f.implicit)}if("/"===f.op){if(isConstantNode(x)){if(n(x.value))return g;if(isConstantNode(S)&&(t(S.value,1)||t(S.value,2)||t(S.value,4)))return new c(s(x.value,S.value))}return new h(f.op,f.fn,[x,S])}if("^"===f.op&&isConstantNode(S)){if(n(S.value))return b;if(t(S.value,1))return x;if(isConstantNode(x))return new c(o(x.value,S.value));if(isOperatorNode(x)&&x.isBinary()&&"^"===x.op){var D=x.args[1];if(isConstantNode(D))return new h(f.op,f.fn,[x.args[0],new c(i(D.value,S.value))])}}}return new h(f.op,f.fn,[x,S])}if(isFunctionNode(f))return new p(e(f.fn),f.args.map((t=>e(t,y))));if(isArrayNode(f))return new u(f.items.map((t=>e(t,y))));if(isAccessorNode(f))return new l(e(f.object,y),e(f.index,y));if(isIndexNode(f))return new d(f.dimensions.map((t=>e(t,y))));if(isObjectNode(f)){var O={};for(var I in f.properties)O[I]=e(f.properties[I],y);return new m(O)}}return f}})),name$n="resolve",dependencies$n=["parse","ConstantNode","FunctionNode","OperatorNode","ParenthesisNode"],createResolve=factory(name$n,dependencies$n,(e=>{var{parse:t,ConstantNode:n,FunctionNode:r,OperatorNode:a,ParenthesisNode:i}=e;return function e(s,o){var l=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Set;if(!o)return s;if(isMap$1(o)||(o=createMap$1(o)),isSymbolNode(s)){if(l.has(s.name)){var u=Array.from(l).join(", ");throw new ReferenceError("recursive loop of variable definitions among {".concat(u,"}"))}var c=o.get(s.name);if(isNode(c)){var p=new Set(l);return p.add(s.name),e(c,o,p)}return"number"==typeof c?t(String(c)):void 0!==c?new n(c):s}if(isOperatorNode(s)){var d=s.args.map((function(t){return e(t,o,l)}));return new a(s.op,s.fn,d,s.implicit)}if(isParenthesisNode(s))return new i(e(s.content,o,l));if(isFunctionNode(s)){var m=s.args.map((function(t){return e(t,o,l)}));return new r(s.name,m)}return s.map((t=>e(t,o,l)))}})),name$m="symbolicEqual",dependencies$m=["parse","simplify","typed","OperatorNode"],createSymbolicEqual=factory(name$m,dependencies$m,(e=>{var{parse:t,simplify:n,typed:r,OperatorNode:a}=e;return r(name$m,{"string, string":function(e,n){return this(t(e),t(n),{})},"string, string, Object":function(e,n,r){return this(t(e),t(n),r)},"Node, string":function(e,n){return this(e,t(n),{})},"Node, string, Object":function(e,n,r){return this(e,t(n),r)},"string, Node":function(e,n){return this(t(e),n,{})},"string, Node, Object":function(e,n,r){return this(t(e),n,r)},"Node, Node":function(e,t){return this(e,t,{})},"Node, Node, Object":function(e,t,r){var i=new a("-","subtract",[e,t]),s=n(i,{},r);return isConstantNode(s)&&!s.value}})})),name$l="derivative",dependencies$l=["typed","config","parse","simplify","equal","isZero","numeric","ConstantNode","FunctionNode","OperatorNode","ParenthesisNode","SymbolNode"],createDerivative=factory(name$l,dependencies$l,(e=>{var{typed:t,config:n,parse:r,simplify:a,equal:i,isZero:s,numeric:o,ConstantNode:l,FunctionNode:u,OperatorNode:c,ParenthesisNode:p,SymbolNode:d}=e,m=t("derivative",{"Node, SymbolNode, Object":function(e,t,n){var r={};f(r,e,t.name);var i=y(e,r);return n.simplify?a(i):i},"Node, SymbolNode":function(e,t){return this(e,t,{simplify:!0})},"string, SymbolNode":function(e,t){return this(r(e),t)},"string, SymbolNode, Object":function(e,t,n){return this(r(e),t,n)},"string, string":function(e,t){return this(r(e),r(t))},"string, string, Object":function(e,t,n){return this(r(e),r(t),n)},"Node, string":function(e,t){return this(e,r(t))},"Node, string, Object":function(e,t,n){return this(e,r(t),n)}});m._simplify=!0,m.toTex=function(e){return h.apply(null,e.args)};var h=t("_derivTex",{"Node, SymbolNode":function(e,t){return isConstantNode(e)&&"string"===typeOf$1(e.value)?h(r(e.value).toString(),t.toString(),1):h(e.toTex(),t.toString(),1)},"Node, ConstantNode":function(e,t){if("string"===typeOf$1(t.value))return h(e,r(t.value));throw new Error("The second parameter to 'derivative' is a non-string constant")},"Node, SymbolNode, ConstantNode":function(e,t,n){return h(e.toString(),t.name,n.value)},"string, string, number":function(e,t,n){return(1===n?"{d\\over d"+t+"}":"{d^{"+n+"}\\over d"+t+"^{"+n+"}}")+"\\left[".concat(e,"\\right]")}}),f=t("constTag",{"Object, ConstantNode, string":function(e,t){return e[t]=!0,!0},"Object, SymbolNode, string":function(e,t,n){return t.name!==n&&(e[t]=!0,!0)},"Object, ParenthesisNode, string":function(e,t,n){return f(e,t.content,n)},"Object, FunctionAssignmentNode, string":function(e,t,n){return-1===t.params.indexOf(n)?(e[t]=!0,!0):f(e,t.expr,n)},"Object, FunctionNode | OperatorNode, string":function(e,t,n){if(t.args.length>0){for(var r=f(e,t.args[0],n),a=1;a0){var r=e.args.filter((function(e){return void 0===t[e]})),a=1===r.length?r[0]:new c("*","multiply",r),o=n.concat(y(a,t));return new c("*","multiply",o)}return new c("+","add",e.args.map((function(n){return new c("*","multiply",e.args.map((function(e){return e===n?y(e,t):e.clone()})))})))}if("/"===e.op&&e.isBinary()){var l=e.args[0],p=e.args[1];return void 0!==t[p]?new c("/","divide",[y(l,t),p]):void 0!==t[l]?new c("*","multiply",[new c("-","unaryMinus",[l]),new c("/","divide",[y(p,t),new c("^","pow",[p.clone(),g(2)])])]):new c("/","divide",[new c("-","subtract",[new c("*","multiply",[y(l,t),p.clone()]),new c("*","multiply",[l.clone(),y(p,t)])]),new c("^","pow",[p.clone(),g(2)])])}if("^"===e.op&&e.isBinary()){var d=e.args[0],m=e.args[1];if(void 0!==t[d])return isConstantNode(d)&&(s(d.value)||i(d.value,1))?g(0):new c("*","multiply",[e,new c("*","multiply",[new u("log",[d.clone()]),y(m.clone(),t)])]);if(void 0!==t[m]){if(isConstantNode(m)){if(s(m.value))return g(0);if(i(m.value,1))return y(d,t)}var h=new c("^","pow",[d.clone(),new c("-","subtract",[m,g(1)])]);return new c("*","multiply",[m.clone(),new c("*","multiply",[y(d,t),h])])}return new c("*","multiply",[new c("^","pow",[d.clone(),m.clone()]),new c("+","add",[new c("*","multiply",[y(d,t),new c("/","divide",[m.clone(),d.clone()])]),new c("*","multiply",[y(m,t),new u("log",[d.clone()])])])])}throw new Error('Operator "'+e.op+'" is not supported by derivative, or a wrong number of arguments is passed')}});function g(e,t){return new l(o(e,t||n.number))}return m})),name$k="rationalize",dependencies$k=["config","typed","equal","isZero","add","subtract","multiply","divide","pow","parse","simplifyCore","simplify","?bignumber","?fraction","mathWithTransform","matrix","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","SymbolNode","ParenthesisNode"],createRationalize=factory(name$k,dependencies$k,(e=>{var{config:t,typed:n,equal:r,isZero:a,add:i,subtract:s,multiply:o,divide:l,pow:u,parse:c,simplifyCore:p,simplify:d,fraction:m,bignumber:h,mathWithTransform:f,matrix:y,AccessorNode:g,ArrayNode:b,ConstantNode:v,FunctionNode:N,IndexNode:T,ObjectNode:C,OperatorNode:A,SymbolNode:V,ParenthesisNode:x}=e,S=createSimplifyConstant({typed:n,config:t,mathWithTransform:f,matrix:y,fraction:m,bignumber:h,AccessorNode:g,ArrayNode:b,ConstantNode:v,FunctionNode:N,IndexNode:T,ObjectNode:C,OperatorNode:A,SymbolNode:V});return n(name$k,{string:function(e){return this(c(e),{},!1)},"string, boolean":function(e,t){return this(c(e),{},t)},"string, Object":function(e,t){return this(c(e),t,!1)},"string, Object, boolean":function(e,t,n){return this(c(e),t,n)},Node:function(e){return this(e,{},!1)},"Node, boolean":function(e,t){return this(e,{},t)},"Node, Object":function(e,t){return this(e,t,!1)},"Node, Object, boolean":function(e,t,n){var r=function(){var e=[p,{l:"n+n",r:"2*n"},{l:"n+-n",r:"0"},S,{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"}],t=[{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)"}],n=[{l:"(n1/(n2/n3))",r:"((n1*n3)/n2)"},{l:"(n1/n2/n3)",r:"(n1/(n2*n3))"}],r={};return r.firstRules=e.concat(t,n),r.distrDivRules=[{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)"}],r.sucDivRules=n,r.firstRulesAgain=e.concat(t),r.finalRules=[p,{l:"n*-n",r:"-n^2"},{l:"n*n",r:"n^2"},S,{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))"}],r}(),a=function(e,t,n,r){var a=[],i=d(e,r,t,{exactFractions:!1}),s="+-*"+((n=!!n)?"/":"");!function e(t){var n=t.type;if("FunctionNode"===n)throw new Error("There is an unsolved function call");if("OperatorNode"===n)if("^"===t.op){if("ConstantNode"!==t.args[1].type||!isInteger$1(parseFloat(t.args[1].value)))throw new Error("There is a non-integer exponent");e(t.args[0])}else{if(-1===s.indexOf(t.op))throw new Error("Operator "+t.op+" invalid in polynomial expression");for(var r=0;r=1){var l,u;e=w(e);var c,m=!0,h=!1;for(e=d(e,r.firstRules,{},s);u=m?r.distrDivRules:r.sucDivRules,m=!m,(c=(e=d(e,u,{},o)).toString())!==l;)h=!0,l=c;h&&(e=d(e,r.firstRulesAgain,{},s)),e=d(e,r.finalRules,{},s)}var f=[],y={};return"OperatorNode"===e.type&&e.isBinary()&&"/"===e.op?(1===i&&(e.args[0]=E(e.args[0],f),e.args[1]=E(e.args[1])),n&&(y.numerator=e.args[0],y.denominator=e.args[1])):(1===i&&(e=E(e,f)),n&&(y.numerator=e,y.denominator=null)),n?(y.coefficients=f,y.variables=a.variables,y.expression=e,y):e}});function w(e,t,n){var r=e.type,a=arguments.length>1;if("OperatorNode"===r&&e.isBinary()){var i,s=!1;if("^"===e.op&&("ParenthesisNode"!==e.args[0].type&&"OperatorNode"!==e.args[0].type||"ConstantNode"!==e.args[1].type||(s=(i=parseFloat(e.args[1].value))>=2&&isInteger$1(i))),s){if(i>2){var o=e.args[0],l=new A("^","pow",[e.args[0].cloneDeep(),new v(i-1)]);e=new A("*","multiply",[o,l])}else e=new A("*","multiply",[e.args[0],e.args[0].cloneDeep()]);a&&("content"===n?t.content=e:t.args[n]=e)}}if("ParenthesisNode"===r)w(e.content,e,"content");else if("ConstantNode"!==r&&"SymbolNode"!==r)for(var u=0;un&&(t[u]=0),t[u]+=s.cte*("+"===s.oper?1:-1),void(n=Math.max(u,n))}s.cte=u,""===s.fire&&(t[0]+=s.cte*("+"===s.oper?1:-1))}}(e,null,{cte:1,oper:"+",fire:""});for(var a,i=!0,s=n=t.length-1;s>=0;s--)if(0!==t[s]){var o=new v(i?t[s]:Math.abs(t[s])),l=t[s]<0?"-":"+";if(s>0){var u=new V(r);if(s>1){var c=new v(s);u=new A("^","pow",[u,c])}o=-1===t[s]&&i?new A("-","unaryMinus",[u]):1===Math.abs(t[s])?u:new A("*","multiply",[o,u])}a=i?o:"+"===l?new A("+","add",[a,o]):new A("-","subtract",[a,o]),i=!1}return i?new v(0):a}})),name$j="reviver",dependencies$j=["classes"],createReviver=factory(name$j,dependencies$j,(e=>{var{classes:t}=e;return function(e,n){var r=t[n&&n.mathjs];return r&&"function"==typeof r.fromJSON?r.fromJSON(n):n}})),name$i="replacer",dependencies$i=[],createReplacer=factory(name$i,dependencies$i,(()=>function(e,t){return"number"!=typeof t||isFinite(t)&&!isNaN(t)?t:{mathjs:"number",value:String(t)}})),version$2="10.6.4",createTrue=factory("true",[],(()=>!0)),createFalse=factory("false",[],(()=>!1)),createNull=factory("null",[],(()=>null)),createInfinity=recreateFactory("Infinity",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(1/0):1/0})),createNaN=recreateFactory("NaN",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(NaN):NaN})),createPi=recreateFactory("pi",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?createBigNumberPi(n):pi$1})),createTau=recreateFactory("tau",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?createBigNumberTau(n):tau$1})),createE=recreateFactory("e",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?createBigNumberE(n):e$1})),createPhi=recreateFactory("phi",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?createBigNumberPhi(n):phi$1})),createLN2=recreateFactory("LN2",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(2).ln():Math.LN2})),createLN10=recreateFactory("LN10",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(10).ln():Math.LN10})),createLOG2E=recreateFactory("LOG2E",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(1).div(new n(2).ln()):Math.LOG2E})),createLOG10E=recreateFactory("LOG10E",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(1).div(new n(10).ln()):Math.LOG10E})),createSQRT1_2=recreateFactory("SQRT1_2",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n("0.5").sqrt():Math.SQRT1_2})),createSQRT2=recreateFactory("SQRT2",["config","?BigNumber"],(e=>{var{config:t,BigNumber:n}=e;return"BigNumber"===t.number?new n(2).sqrt():Math.SQRT2})),createI=recreateFactory("i",["Complex"],(e=>{var{Complex:t}=e;return t.I})),createUppercasePi=factory("PI",["pi"],(e=>{var{pi:t}=e;return t})),createUppercaseE=factory("E",["e"],(e=>{var{e:t}=e;return t})),createVersion=factory("version",[],(()=>version$2));function recreateFactory(e,t,n){return factory(e,t,n,{recreateOnConfigChange:!0})}var createSpeedOfLight=unitFactory("speedOfLight","299792458","m s^-1"),createGravitationConstant=unitFactory("gravitationConstant","6.67430e-11","m^3 kg^-1 s^-2"),createPlanckConstant=unitFactory("planckConstant","6.62607015e-34","J s"),createReducedPlanckConstant=unitFactory("reducedPlanckConstant","1.0545718176461565e-34","J s"),createMagneticConstant=unitFactory("magneticConstant","1.25663706212e-6","N A^-2"),createElectricConstant=unitFactory("electricConstant","8.8541878128e-12","F m^-1"),createVacuumImpedance=unitFactory("vacuumImpedance","376.730313667","ohm"),createCoulomb=unitFactory("coulomb","8.987551792261171e9","N m^2 C^-2"),createElementaryCharge=unitFactory("elementaryCharge","1.602176634e-19","C"),createBohrMagneton=unitFactory("bohrMagneton","9.2740100783e-24","J T^-1"),createConductanceQuantum=unitFactory("conductanceQuantum","7.748091729863649e-5","S"),createInverseConductanceQuantum=unitFactory("inverseConductanceQuantum","12906.403729652257","ohm"),createMagneticFluxQuantum=unitFactory("magneticFluxQuantum","2.0678338484619295e-15","Wb"),createNuclearMagneton=unitFactory("nuclearMagneton","5.0507837461e-27","J T^-1"),createKlitzing=unitFactory("klitzing","25812.807459304513","ohm"),createBohrRadius=unitFactory("bohrRadius","5.29177210903e-11","m"),createClassicalElectronRadius=unitFactory("classicalElectronRadius","2.8179403262e-15","m"),createElectronMass=unitFactory("electronMass","9.1093837015e-31","kg"),createFermiCoupling=unitFactory("fermiCoupling","1.1663787e-5","GeV^-2"),createFineStructure=numberFactory("fineStructure",.0072973525693),createHartreeEnergy=unitFactory("hartreeEnergy","4.3597447222071e-18","J"),createProtonMass=unitFactory("protonMass","1.67262192369e-27","kg"),createDeuteronMass=unitFactory("deuteronMass","3.3435830926e-27","kg"),createNeutronMass=unitFactory("neutronMass","1.6749271613e-27","kg"),createQuantumOfCirculation=unitFactory("quantumOfCirculation","3.6369475516e-4","m^2 s^-1"),createRydberg=unitFactory("rydberg","10973731.568160","m^-1"),createThomsonCrossSection=unitFactory("thomsonCrossSection","6.6524587321e-29","m^2"),createWeakMixingAngle=numberFactory("weakMixingAngle",.2229),createEfimovFactor=numberFactory("efimovFactor",22.7),createAtomicMass=unitFactory("atomicMass","1.66053906660e-27","kg"),createAvogadro=unitFactory("avogadro","6.02214076e23","mol^-1"),createBoltzmann=unitFactory("boltzmann","1.380649e-23","J K^-1"),createFaraday=unitFactory("faraday","96485.33212331001","C mol^-1"),createFirstRadiation=unitFactory("firstRadiation","3.7417718521927573e-16","W m^2"),createLoschmidt=unitFactory("loschmidt","2.686780111798444e25","m^-3"),createGasConstant=unitFactory("gasConstant","8.31446261815324","J K^-1 mol^-1"),createMolarPlanckConstant=unitFactory("molarPlanckConstant","3.990312712893431e-10","J s mol^-1"),createMolarVolume=unitFactory("molarVolume","0.022413969545014137","m^3 mol^-1"),createSackurTetrode=numberFactory("sackurTetrode",-1.16487052358),createSecondRadiation=unitFactory("secondRadiation","0.014387768775039337","m K"),createStefanBoltzmann=unitFactory("stefanBoltzmann","5.67037441918443e-8","W m^-2 K^-4"),createWienDisplacement=unitFactory("wienDisplacement","2.897771955e-3","m K"),createMolarMass=unitFactory("molarMass","0.99999999965e-3","kg mol^-1"),createMolarMassC12=unitFactory("molarMassC12","11.9999999958e-3","kg mol^-1"),createGravity=unitFactory("gravity","9.80665","m s^-2"),createPlanckLength=unitFactory("planckLength","1.616255e-35","m"),createPlanckMass=unitFactory("planckMass","2.176435e-8","kg"),createPlanckTime=unitFactory("planckTime","5.391245e-44","s"),createPlanckCharge=unitFactory("planckCharge","1.87554603778e-18","C"),createPlanckTemperature=unitFactory("planckTemperature","1.416785e+32","K");function unitFactory(e,t,n){return factory(e,["config","Unit","BigNumber"],(e=>{var{config:r,Unit:a,BigNumber:i}=e,s=new a("BigNumber"===r.number?new i(t):parseFloat(t),n);return s.fixPrefix=!0,s}))}function numberFactory(e,t){return factory(e,["config","BigNumber"],(e=>{var{config:n,BigNumber:r}=e;return"BigNumber"===n.number?new r(t):t}))}var name$h="apply",dependencies$h=["typed","isInteger"],createApplyTransform=factory(name$h,dependencies$h,(e=>{var{typed:t,isInteger:n}=e,r=createApply({typed:t,isInteger:n});return t("apply",{"...any":function(e){var t=e[1];isNumber$1(t)?e[1]=t-1:isBigNumber(t)&&(e[1]=t.minus(1));try{return r.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$g="column",dependencies$g=["typed","Index","matrix","range"],createColumnTransform=factory(name$g,dependencies$g,(e=>{var{typed:t,Index:n,matrix:r,range:a}=e,i=createColumn({typed:t,Index:n,matrix:r,range:a});return t("column",{"...any":function(e){var t=e.length-1,n=e[t];isNumber$1(n)&&(e[t]=n-1);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0});function compileInlineExpression(e,t,n){var r=e.filter((function(e){return isSymbolNode(e)&&!(e.name in t)&&!n.has(e.name)}))[0];if(!r)throw new Error('No undefined variable found in inline expression "'+e+'"');var a=r.name,i=createSubScope(n),s=e.compile();return function(e){return i.set(a,e),s.evaluate(i)}}var name$f="filter",dependencies$f=["typed"],createFilterTransform=factory(name$f,dependencies$f,(e=>{var{typed:t}=e;function n(e,t,n){var a,i;return e[0]&&(a=e[0].compile().evaluate(n)),e[1]&&(i=isSymbolNode(e[1])||isFunctionAssignmentNode(e[1])?e[1].compile().evaluate(n):compileInlineExpression(e[1],t,n)),r(a,i)}n.rawArgs=!0;var r=t("filter",{"Array, function":_filter,"Matrix, function":function(e,t){return e.create(_filter(e.toArray(),t))},"Array, RegExp":filterRegExp,"Matrix, RegExp":function(e,t){return e.create(filterRegExp(e.toArray(),t))}});return n}),{isTransformFunction:!0});function _filter(e,t){var n=maxArgumentCount(t);return filter$2(e,(function(e,r,a){return 1===n?t(e):2===n?t(e,[r+1]):t(e,[r+1],a)}))}var name$e="forEach",dependencies$e=["typed"],createForEachTransform=factory(name$e,dependencies$e,(e=>{var{typed:t}=e;function n(e,t,n){var a,i;return e[0]&&(a=e[0].compile().evaluate(n)),e[1]&&(i=isSymbolNode(e[1])||isFunctionAssignmentNode(e[1])?e[1].compile().evaluate(n):compileInlineExpression(e[1],t,n)),r(a,i)}n.rawArgs=!0;var r=t("forEach",{"Array | Matrix, function":function(e,t){var n=maxArgumentCount(t);!function r(a,i){Array.isArray(a)?forEach$1(a,(function(e,t){r(e,i.concat(t+1))})):1===n?t(a):2===n?t(a,i):t(a,i,e)}(e.valueOf(),[])}});return n}),{isTransformFunction:!0}),name$d="index",dependencies$d=["Index"],createIndexTransform=factory(name$d,dependencies$d,(e=>{var{Index:t}=e;return function(){for(var e=[],n=0,r=arguments.length;n0?0:2;else if(a&&!0===a.isSet)a=a.map((function(e){return e-1}));else if(isArray$1(a)||isMatrix(a))a=a.map((function(e){return e-1}));else if(isNumber$1(a))a--;else if(isBigNumber(a))a=a.toNumber()-1;else if("string"!=typeof a)throw new TypeError("Dimension must be an Array, Matrix, number, string, or Range");e[n]=a}var i=new t;return t.apply(i,e),i}}),{isTransformFunction:!0}),name$c="map",dependencies$c=["typed"],createMapTransform=factory(name$c,dependencies$c,(e=>{var{typed:t}=e;function n(e,t,n){var a,i;return e[0]&&(a=e[0].compile().evaluate(n)),e[1]&&(i=isSymbolNode(e[1])||isFunctionAssignmentNode(e[1])?e[1].compile().evaluate(n):compileInlineExpression(e[1],t,n)),r(a,i)}n.rawArgs=!0;var r=t("map",{"Array, function":function(e,t){return _map(e,t,e)},"Matrix, function":function(e,t){return e.create(_map(e.valueOf(),t,e))}});return n}),{isTransformFunction:!0});function _map(e,t,n){var r=maxArgumentCount(t);return function e(a,i){return Array.isArray(a)?map$2(a,(function(t,n){return e(t,i.concat(n+1))})):1===r?t(a):2===r?t(a,i):t(a,i,n)}(e,[])}function lastDimToZeroBase(e){if(2===e.length&&isCollection(e[0])){var t=(e=e.slice())[1];isNumber$1(t)?e[1]=t-1:isBigNumber(t)&&(e[1]=t.minus(1))}return e}var name$b="max",dependencies$b=["typed","config","numeric","larger"],createMaxTransform=factory(name$b,dependencies$b,(e=>{var{typed:t,config:n,numeric:r,larger:a}=e,i=createMax({typed:t,config:n,numeric:r,larger:a});return t("max",{"...any":function(e){e=lastDimToZeroBase(e);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$a="mean",dependencies$a=["typed","add","divide"],createMeanTransform=factory(name$a,dependencies$a,(e=>{var{typed:t,add:n,divide:r}=e,a=createMean({typed:t,add:n,divide:r});return t("mean",{"...any":function(e){e=lastDimToZeroBase(e);try{return a.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$9="min",dependencies$9=["typed","config","numeric","smaller"],createMinTransform=factory(name$9,dependencies$9,(e=>{var{typed:t,config:n,numeric:r,smaller:a}=e,i=createMin({typed:t,config:n,numeric:r,smaller:a});return t("min",{"...any":function(e){e=lastDimToZeroBase(e);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$8="range",dependencies$8=["typed","config","?matrix","?bignumber","smaller","smallerEq","larger","largerEq"],createRangeTransform=factory(name$8,dependencies$8,(e=>{var{typed:t,config:n,matrix:r,bignumber:a,smaller:i,smallerEq:s,larger:o,largerEq:l}=e,u=createRange({typed:t,config:n,matrix:r,bignumber:a,smaller:i,smallerEq:s,larger:o,largerEq:l});return t("range",{"...any":function(e){return"boolean"!=typeof e[e.length-1]&&e.push(!0),u.apply(null,e)}})}),{isTransformFunction:!0}),name$7="row",dependencies$7=["typed","Index","matrix","range"],createRowTransform=factory(name$7,dependencies$7,(e=>{var{typed:t,Index:n,matrix:r,range:a}=e,i=createRow({typed:t,Index:n,matrix:r,range:a});return t("row",{"...any":function(e){var t=e.length-1,n=e[t];isNumber$1(n)&&(e[t]=n-1);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$6="subset",dependencies$6=["typed","matrix"],createSubsetTransform=factory(name$6,dependencies$6,(e=>{var{typed:t,matrix:n}=e,r=createSubset({typed:t,matrix:n});return t("subset",{"...any":function(e){try{return r.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$5="concat",dependencies$5=["typed","matrix","isInteger"],createConcatTransform=factory(name$5,dependencies$5,(e=>{var{typed:t,matrix:n,isInteger:r}=e,a=createConcat({typed:t,matrix:n,isInteger:r});return t("concat",{"...any":function(e){var t=e.length-1,n=e[t];isNumber$1(n)?e[t]=n-1:isBigNumber(n)&&(e[t]=n.minus(1));try{return a.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$4="diff",dependencies$4=["typed","matrix","subtract","number","bignumber"],createDiffTransform=factory(name$4,dependencies$4,(e=>{var{typed:t,matrix:n,subtract:r,number:a,bignumber:i}=e,s=createDiff({typed:t,matrix:n,subtract:r,number:a,bignumber:i});return t(name$4,{"...any":function(e){e=lastDimToZeroBase(e);try{return s.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$3="std",dependencies$3=["typed","sqrt","variance"],createStdTransform=factory(name$3,dependencies$3,(e=>{var{typed:t,sqrt:n,variance:r}=e,a=createStd({typed:t,sqrt:n,variance:r});return t("std",{"...any":function(e){e=lastDimToZeroBase(e);try{return a.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$2="sum",dependencies$2=["typed","config","add","numeric"],createSumTransform=factory(name$2,dependencies$2,(e=>{var{typed:t,config:n,add:r,numeric:a}=e,i=createSum({typed:t,config:n,add:r,numeric:a});return t(name$2,{"...any":function(e){e=lastDimToZeroBase(e);try{return i.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name$1="cumsum",dependencies$1=["typed","add","unaryPlus"],createCumSumTransform=factory(name$1,dependencies$1,(e=>{var{typed:t,add:n,unaryPlus:r}=e,a=createCumSum({typed:t,add:n,unaryPlus:r});return t(name$1,{"...any":function(e){if(2===e.length&&isCollection(e[0])){var t=e[1];isNumber$1(t)?e[1]=t-1:isBigNumber(t)&&(e[1]=t.minus(1))}try{return a.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),name="variance",dependencies=["typed","add","subtract","multiply","divide","apply","isNaN"],createVarianceTransform=factory(name,dependencies,(e=>{var{typed:t,add:n,subtract:r,multiply:a,divide:i,apply:s,isNaN:o}=e,l=createVariance({typed:t,add:n,subtract:r,multiply:a,divide:i,apply:s,isNaN:o});return t(name,{"...any":function(e){e=lastDimToZeroBase(e);try{return l.apply(null,e)}catch(e){throw errorTransform(e)}}})}),{isTransformFunction:!0}),allFactories=Object.freeze({__proto__:null,createTyped:createTyped,createResultSet:createResultSet,createBigNumberClass:createBigNumberClass,createComplexClass:createComplexClass,createFractionClass:createFractionClass,createRangeClass:createRangeClass,createMatrixClass:createMatrixClass,createDenseMatrixClass:createDenseMatrixClass,createClone:createClone,createIsInteger:createIsInteger,createIsNegative:createIsNegative,createIsNumeric:createIsNumeric,createHasNumericValue:createHasNumericValue,createIsPositive:createIsPositive,createIsZero:createIsZero,createIsNaN:createIsNaN,createTypeOf:createTypeOf,createEqualScalar:createEqualScalar,createSparseMatrixClass:createSparseMatrixClass,createNumber:createNumber,createString:createString,createBoolean:createBoolean,createBignumber:createBignumber,createComplex:createComplex,createFraction:createFraction,createMatrix:createMatrix,createMatrixFromFunction:createMatrixFromFunction,createMatrixFromRows:createMatrixFromRows,createMatrixFromColumns:createMatrixFromColumns,createSplitUnit:createSplitUnit,createUnaryMinus:createUnaryMinus,createUnaryPlus:createUnaryPlus,createAbs:createAbs,createApply:createApply,createAddScalar:createAddScalar,createCbrt:createCbrt,createCeil:createCeil,createCube:createCube,createExp:createExp,createExpm1:createExpm1,createFix:createFix,createFloor:createFloor,createGcd:createGcd,createLcm:createLcm,createLog10:createLog10,createLog2:createLog2,createMod:createMod,createMultiplyScalar:createMultiplyScalar,createMultiply:createMultiply,createNthRoot:createNthRoot,createSign:createSign,createSqrt:createSqrt,createSquare:createSquare,createSubtract:createSubtract,createXgcd:createXgcd,createInvmod:createInvmod,createDotMultiply:createDotMultiply,createBitAnd:createBitAnd,createBitNot:createBitNot,createBitOr:createBitOr,createBitXor:createBitXor,createArg:createArg,createConj:createConj,createIm:createIm,createRe:createRe,createNot:createNot,createOr:createOr,createXor:createXor,createConcat:createConcat,createColumn:createColumn,createCount:createCount,createCross:createCross,createDiag:createDiag,createFilter:createFilter,createFlatten:createFlatten,createForEach:createForEach,createGetMatrixDataType:createGetMatrixDataType,createIdentity:createIdentity,createKron:createKron,createMap:createMap,createDiff:createDiff,createOnes:createOnes,createRange:createRange,createReshape:createReshape,createResize:createResize,createRotate:createRotate,createRotationMatrix:createRotationMatrix,createRow:createRow,createSize:createSize,createSqueeze:createSqueeze,createSubset:createSubset,createTranspose:createTranspose,createCtranspose:createCtranspose,createZeros:createZeros,createFft:createFft,createIfft:createIfft,createErf:createErf,createMode:createMode,createProd:createProd,createFormat:createFormat,createBin:createBin,createOct:createOct,createHex:createHex,createPrint:createPrint,createTo:createTo,createIsPrime:createIsPrime,createNumeric:createNumeric,createDivideScalar:createDivideScalar,createPow:createPow,createRound:createRound,createLog:createLog,createLog1p:createLog1p,createNthRoots:createNthRoots,createDotPow:createDotPow,createDotDivide:createDotDivide,createLsolve:createLsolve,createUsolve:createUsolve,createLsolveAll:createLsolveAll,createUsolveAll:createUsolveAll,createLeftShift:createLeftShift,createRightArithShift:createRightArithShift,createRightLogShift:createRightLogShift,createAnd:createAnd,createCompare:createCompare,createCompareNatural:createCompareNatural,createCompareText:createCompareText,createEqual:createEqual,createEqualText:createEqualText,createSmaller:createSmaller,createSmallerEq:createSmallerEq,createLarger:createLarger,createLargerEq:createLargerEq,createDeepEqual:createDeepEqual,createUnequal:createUnequal,createPartitionSelect:createPartitionSelect,createSort:createSort,createMax:createMax,createMin:createMin,createImmutableDenseMatrixClass:createImmutableDenseMatrixClass,createIndexClass:createIndexClass,createFibonacciHeapClass:createFibonacciHeapClass,createSpaClass:createSpaClass,createUnitClass:createUnitClass,createUnitFunction:createUnitFunction,createSparse:createSparse,createCreateUnit:createCreateUnit,createAcos:createAcos,createAcosh:createAcosh,createAcot:createAcot,createAcoth:createAcoth,createAcsc:createAcsc,createAcsch:createAcsch,createAsec:createAsec,createAsech:createAsech,createAsin:createAsin,createAsinh:createAsinh,createAtan:createAtan,createAtan2:createAtan2,createAtanh:createAtanh,createCos:createCos,createCosh:createCosh,createCot:createCot,createCoth:createCoth,createCsc:createCsc,createCsch:createCsch,createSec:createSec,createSech:createSech,createSin:createSin,createSinh:createSinh,createTan:createTan,createTanh:createTanh,createSetCartesian:createSetCartesian,createSetDifference:createSetDifference,createSetDistinct:createSetDistinct,createSetIntersect:createSetIntersect,createSetIsSubset:createSetIsSubset,createSetMultiplicity:createSetMultiplicity,createSetPowerset:createSetPowerset,createSetSize:createSetSize,createSetSymDifference:createSetSymDifference,createSetUnion:createSetUnion,createAdd:createAdd,createHypot:createHypot,createNorm:createNorm,createDot:createDot,createTrace:createTrace,createIndex:createIndex,createNode:createNode,createAccessorNode:createAccessorNode,createArrayNode:createArrayNode,createAssignmentNode:createAssignmentNode,createBlockNode:createBlockNode,createConditionalNode:createConditionalNode,createConstantNode:createConstantNode,createFunctionAssignmentNode:createFunctionAssignmentNode,createIndexNode:createIndexNode,createObjectNode:createObjectNode,createOperatorNode:createOperatorNode,createParenthesisNode:createParenthesisNode,createRangeNode:createRangeNode,createRelationalNode:createRelationalNode,createSymbolNode:createSymbolNode,createFunctionNode:createFunctionNode,createParse:createParse,createCompile:createCompile,createEvaluate:createEvaluate,createParserClass:createParserClass,createParser:createParser,createLup:createLup,createQr:createQr,createSlu:createSlu,createLusolve:createLusolve,createHelpClass:createHelpClass,createChainClass:createChainClass,createHelp:createHelp,createChain:createChain,createDet:createDet,createInv:createInv,createPinv:createPinv,createEigs:createEigs,createExpm:createExpm,createSqrtm:createSqrtm,createDivide:createDivide,createDistance:createDistance,createIntersect:createIntersect,createSum:createSum,createCumSum:createCumSum,createMean:createMean,createMedian:createMedian,createMad:createMad,createVariance:createVariance,createQuantileSeq:createQuantileSeq,createStd:createStd,createCombinations:createCombinations,createCombinationsWithRep:createCombinationsWithRep,createGamma:createGamma,createLgamma:createLgamma,createFactorial:createFactorial,createKldivergence:createKldivergence,createMultinomial:createMultinomial,createPermutations:createPermutations,createPickRandom:createPickRandom,createRandom:createRandom,createRandomInt:createRandomInt,createStirlingS2:createStirlingS2,createBellNumbers:createBellNumbers,createCatalan:createCatalan,createComposition:createComposition,createLeafCount:createLeafCount,createSimplify:createSimplify,createSimplifyCore:createSimplifyCore,createResolve:createResolve,createSymbolicEqual:createSymbolicEqual,createDerivative:createDerivative,createRationalize:createRationalize,createReviver:createReviver,createReplacer:createReplacer,createE:createE,createUppercaseE:createUppercaseE,createFalse:createFalse,createI:createI,createInfinity:createInfinity,createLN10:createLN10,createLN2:createLN2,createLOG10E:createLOG10E,createLOG2E:createLOG2E,createNaN:createNaN,createNull:createNull,createPhi:createPhi,createPi:createPi,createUppercasePi:createUppercasePi,createSQRT1_2:createSQRT1_2,createSQRT2:createSQRT2,createTau:createTau,createTrue:createTrue,createVersion:createVersion,createAtomicMass:createAtomicMass,createAvogadro:createAvogadro,createBohrMagneton:createBohrMagneton,createBohrRadius:createBohrRadius,createBoltzmann:createBoltzmann,createClassicalElectronRadius:createClassicalElectronRadius,createConductanceQuantum:createConductanceQuantum,createCoulomb:createCoulomb,createDeuteronMass:createDeuteronMass,createEfimovFactor:createEfimovFactor,createElectricConstant:createElectricConstant,createElectronMass:createElectronMass,createElementaryCharge:createElementaryCharge,createFaraday:createFaraday,createFermiCoupling:createFermiCoupling,createFineStructure:createFineStructure,createFirstRadiation:createFirstRadiation,createGasConstant:createGasConstant,createGravitationConstant:createGravitationConstant,createGravity:createGravity,createHartreeEnergy:createHartreeEnergy,createInverseConductanceQuantum:createInverseConductanceQuantum,createKlitzing:createKlitzing,createLoschmidt:createLoschmidt,createMagneticConstant:createMagneticConstant,createMagneticFluxQuantum:createMagneticFluxQuantum,createMolarMass:createMolarMass,createMolarMassC12:createMolarMassC12,createMolarPlanckConstant:createMolarPlanckConstant,createMolarVolume:createMolarVolume,createNeutronMass:createNeutronMass,createNuclearMagneton:createNuclearMagneton,createPlanckCharge:createPlanckCharge,createPlanckConstant:createPlanckConstant,createPlanckLength:createPlanckLength,createPlanckMass:createPlanckMass,createPlanckTemperature:createPlanckTemperature,createPlanckTime:createPlanckTime,createProtonMass:createProtonMass,createQuantumOfCirculation:createQuantumOfCirculation,createReducedPlanckConstant:createReducedPlanckConstant,createRydberg:createRydberg,createSackurTetrode:createSackurTetrode,createSecondRadiation:createSecondRadiation,createSpeedOfLight:createSpeedOfLight,createStefanBoltzmann:createStefanBoltzmann,createThomsonCrossSection:createThomsonCrossSection,createVacuumImpedance:createVacuumImpedance,createWeakMixingAngle:createWeakMixingAngle,createWienDisplacement:createWienDisplacement,createApplyTransform:createApplyTransform,createColumnTransform:createColumnTransform,createFilterTransform:createFilterTransform,createForEachTransform:createForEachTransform,createIndexTransform:createIndexTransform,createMapTransform:createMapTransform,createMaxTransform:createMaxTransform,createMeanTransform:createMeanTransform,createMinTransform:createMinTransform,createRangeTransform:createRangeTransform,createRowTransform:createRowTransform,createSubsetTransform:createSubsetTransform,createConcatTransform:createConcatTransform,createDiffTransform:createDiffTransform,createStdTransform:createStdTransform,createSumTransform:createSumTransform,createCumSumTransform:createCumSumTransform,createVarianceTransform:createVarianceTransform}),BigNumber=createBigNumberClass({config:config$2}),Complex=createComplexClass({}),e=createE({BigNumber:BigNumber,config:config$2}),_false=createFalse({}),fineStructure=createFineStructure({BigNumber:BigNumber,config:config$2}),Fraction=createFractionClass({}),i=createI({Complex:Complex}),_Infinity=createInfinity({BigNumber:BigNumber,config:config$2}),LN10=createLN10({BigNumber:BigNumber,config:config$2}),LOG10E=createLOG10E({BigNumber:BigNumber,config:config$2}),Matrix=createMatrixClass({}),_NaN=createNaN({BigNumber:BigNumber,config:config$2}),_null=createNull({}),phi=createPhi({BigNumber:BigNumber,config:config$2}),Range=createRangeClass({}),ResultSet=createResultSet({}),SQRT1_2=createSQRT1_2({BigNumber:BigNumber,config:config$2}),sackurTetrode=createSackurTetrode({BigNumber:BigNumber,config:config$2}),tau=createTau({BigNumber:BigNumber,config:config$2}),_true=createTrue({}),version$1=createVersion({}),DenseMatrix=createDenseMatrixClass({Matrix:Matrix}),efimovFactor=createEfimovFactor({BigNumber:BigNumber,config:config$2}),LN2=createLN2({BigNumber:BigNumber,config:config$2}),pi=createPi({BigNumber:BigNumber,config:config$2}),replacer=createReplacer({}),SQRT2=createSQRT2({BigNumber:BigNumber,config:config$2}),typed=createTyped({BigNumber:BigNumber,Complex:Complex,DenseMatrix:DenseMatrix,Fraction:Fraction}),unaryPlus=createUnaryPlus({BigNumber:BigNumber,config:config$2,typed:typed}),weakMixingAngle=createWeakMixingAngle({BigNumber:BigNumber,config:config$2}),abs$1=createAbs({typed:typed}),acos$1=createAcos({Complex:Complex,config:config$2,typed:typed}),acot$1=createAcot({BigNumber:BigNumber,typed:typed}),acsc$1=createAcsc({BigNumber:BigNumber,Complex:Complex,config:config$2,typed:typed}),addScalar=createAddScalar({typed:typed}),arg=createArg({typed:typed}),asech$1=createAsech({BigNumber:BigNumber,Complex:Complex,config:config$2,typed:typed}),asinh$1=createAsinh({typed:typed}),atan$1=createAtan({typed:typed}),atanh$1=createAtanh({Complex:Complex,config:config$2,typed:typed}),bignumber=createBignumber({BigNumber:BigNumber,typed:typed}),bitNot=createBitNot({typed:typed}),boolean=createBoolean({typed:typed}),clone$1=createClone({typed:typed}),combinations=createCombinations({typed:typed}),complex=createComplex({Complex:Complex,typed:typed}),conj$1=createConj({typed:typed}),cosh$1=createCosh({typed:typed}),coth$1=createCoth({BigNumber:BigNumber,typed:typed}),csc$1=createCsc({BigNumber:BigNumber,typed:typed}),cube=createCube({typed:typed}),equalScalar=createEqualScalar({config:config$2,typed:typed}),erf$1=createErf({typed:typed}),exp$1=createExp({typed:typed}),expm1=createExpm1({Complex:Complex,typed:typed}),filter$1=createFilter({typed:typed}),forEach=createForEach({typed:typed}),format=createFormat({typed:typed}),getMatrixDataType=createGetMatrixDataType({typed:typed}),hex=createHex({format:format,typed:typed}),im$1=createIm({typed:typed}),isInteger=createIsInteger({typed:typed}),isNegative=createIsNegative({typed:typed}),isPositive=createIsPositive({typed:typed}),isZero=createIsZero({typed:typed}),LOG2E=createLOG2E({BigNumber:BigNumber,config:config$2}),lgamma=createLgamma({Complex:Complex,typed:typed}),log10$1=createLog10({Complex:Complex,config:config$2,typed:typed}),log2=createLog2({Complex:Complex,config:config$2,typed:typed}),map$1=createMap({typed:typed}),multiplyScalar=createMultiplyScalar({typed:typed}),not=createNot({typed:typed}),number=createNumber({typed:typed}),oct=createOct({format:format,typed:typed}),pickRandom=createPickRandom({config:config$2,typed:typed}),print=createPrint({typed:typed}),random$1=createRandom({config:config$2,typed:typed}),re$1=createRe({typed:typed}),sec$1=createSec({BigNumber:BigNumber,typed:typed}),sign$1=createSign({BigNumber:BigNumber,Fraction:Fraction,complex:complex,typed:typed}),sin$1=createSin({typed:typed}),SparseMatrix=createSparseMatrixClass({Matrix:Matrix,equalScalar:equalScalar,typed:typed}),splitUnit=createSplitUnit({typed:typed}),square=createSquare({typed:typed}),string=createString({typed:typed}),tan$1=createTan({typed:typed}),typeOf=createTypeOf({typed:typed}),acosh$1=createAcosh({Complex:Complex,config:config$2,typed:typed}),acsch$1=createAcsch({BigNumber:BigNumber,typed:typed}),apply=createApply({isInteger:isInteger,typed:typed}),asec$1=createAsec({BigNumber:BigNumber,Complex:Complex,config:config$2,typed:typed}),bin=createBin({format:format,typed:typed}),combinationsWithRep=createCombinationsWithRep({typed:typed}),cos$1=createCos({typed:typed}),csch$1=createCsch({BigNumber:BigNumber,typed:typed}),isNaN$2=createIsNaN({typed:typed}),isPrime=createIsPrime({typed:typed}),randomInt=createRandomInt({config:config$2,typed:typed}),sech$1=createSech({BigNumber:BigNumber,typed:typed}),sinh$1=createSinh({typed:typed}),sparse=createSparse({SparseMatrix:SparseMatrix,typed:typed}),sqrt$1=createSqrt({Complex:Complex,config:config$2,typed:typed}),tanh$1=createTanh({typed:typed}),unaryMinus=createUnaryMinus({typed:typed}),acoth$1=createAcoth({BigNumber:BigNumber,Complex:Complex,config:config$2,typed:typed}),cot$1=createCot({BigNumber:BigNumber,typed:typed}),fraction=createFraction({Fraction:Fraction,typed:typed}),isNumeric=createIsNumeric({typed:typed}),matrix$2=createMatrix({DenseMatrix:DenseMatrix,Matrix:Matrix,SparseMatrix:SparseMatrix,typed:typed}),matrixFromFunction=createMatrixFromFunction({isZero:isZero,matrix:matrix$2,typed:typed}),mod$1=createMod({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),nthRoot=createNthRoot({BigNumber:BigNumber,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),numeric=createNumeric({bignumber:bignumber,fraction:fraction,number:number}),or=createOr({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),prod=createProd({config:config$2,multiplyScalar:multiplyScalar,numeric:numeric,typed:typed}),reshape=createReshape({isInteger:isInteger,matrix:matrix$2,typed:typed}),size$1=createSize({matrix:matrix$2,config:config$2,typed:typed}),smaller=createSmaller({DenseMatrix:DenseMatrix,config:config$2,matrix:matrix$2,typed:typed}),squeeze=createSqueeze({matrix:matrix$2,typed:typed}),subset=createSubset({matrix:matrix$2,typed:typed}),subtract$1=createSubtract({DenseMatrix:DenseMatrix,addScalar:addScalar,equalScalar:equalScalar,matrix:matrix$2,typed:typed,unaryMinus:unaryMinus}),to=createTo({matrix:matrix$2,typed:typed}),transpose=createTranspose({matrix:matrix$2,typed:typed}),xgcd=createXgcd({BigNumber:BigNumber,config:config$2,matrix:matrix$2,typed:typed}),zeros=createZeros({BigNumber:BigNumber,config:config$2,matrix:matrix$2,typed:typed}),and=createAnd({equalScalar:equalScalar,matrix:matrix$2,not:not,typed:typed,zeros:zeros}),bitAnd=createBitAnd({equalScalar:equalScalar,matrix:matrix$2,typed:typed}),bitXor=createBitXor({DenseMatrix:DenseMatrix,matrix:matrix$2,typed:typed}),cbrt=createCbrt({BigNumber:BigNumber,Complex:Complex,Fraction:Fraction,config:config$2,isNegative:isNegative,matrix:matrix$2,typed:typed,unaryMinus:unaryMinus}),compare=createCompare({BigNumber:BigNumber,DenseMatrix:DenseMatrix,Fraction:Fraction,config:config$2,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),compareText=createCompareText({matrix:matrix$2,typed:typed}),concat=createConcat({isInteger:isInteger,matrix:matrix$2,typed:typed}),count=createCount({prod:prod,size:size$1,typed:typed}),ctranspose=createCtranspose({conj:conj$1,transpose:transpose,typed:typed}),diag=createDiag({DenseMatrix:DenseMatrix,SparseMatrix:SparseMatrix,matrix:matrix$2,typed:typed}),divideScalar=createDivideScalar({numeric:numeric,typed:typed}),dotDivide=createDotDivide({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),equal$1=createEqual({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),fft=createFft({addScalar:addScalar,divideScalar:divideScalar,exp:exp$1,i:i,matrix:matrix$2,multiplyScalar:multiplyScalar,tau:tau,typed:typed}),flatten$3=createFlatten({matrix:matrix$2,typed:typed}),gcd=createGcd({BigNumber:BigNumber,DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),hasNumericValue=createHasNumericValue({isNumeric:isNumeric,typed:typed}),hypot=createHypot({abs:abs$1,addScalar:addScalar,divideScalar:divideScalar,isPositive:isPositive,multiplyScalar:multiplyScalar,smaller:smaller,sqrt:sqrt$1,typed:typed}),ifft=createIfft({conj:conj$1,dotDivide:dotDivide,fft:fft,typed:typed}),kron=createKron({matrix:matrix$2,multiplyScalar:multiplyScalar,typed:typed}),largerEq=createLargerEq({DenseMatrix:DenseMatrix,config:config$2,matrix:matrix$2,typed:typed}),leftShift=createLeftShift({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed,zeros:zeros}),lsolve=createLsolve({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed}),matrixFromColumns=createMatrixFromColumns({flatten:flatten$3,matrix:matrix$2,size:size$1,typed:typed}),min$1=createMin({config:config$2,numeric:numeric,smaller:smaller,typed:typed}),mode=createMode({isNaN:isNaN$2,isNumeric:isNumeric,typed:typed}),nthRoots=createNthRoots({Complex:Complex,config:config$2,divideScalar:divideScalar,typed:typed}),ones=createOnes({BigNumber:BigNumber,config:config$2,matrix:matrix$2,typed:typed}),partitionSelect=createPartitionSelect({compare:compare,isNaN:isNaN$2,isNumeric:isNumeric,typed:typed}),resize=createResize({config:config$2,matrix:matrix$2}),rightArithShift=createRightArithShift({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed,zeros:zeros}),round$1=createRound({BigNumber:BigNumber,DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed,zeros:zeros}),smallerEq=createSmallerEq({DenseMatrix:DenseMatrix,config:config$2,matrix:matrix$2,typed:typed}),unequal=createUnequal({DenseMatrix:DenseMatrix,config:config$2,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),usolve=createUsolve({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed}),xor=createXor({DenseMatrix:DenseMatrix,matrix:matrix$2,typed:typed}),add$1=createAdd({DenseMatrix:DenseMatrix,SparseMatrix:SparseMatrix,addScalar:addScalar,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),atan2$1=createAtan2({BigNumber:BigNumber,DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),bitOr=createBitOr({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed}),catalan=createCatalan({addScalar:addScalar,combinations:combinations,divideScalar:divideScalar,isInteger:isInteger,isNegative:isNegative,multiplyScalar:multiplyScalar,typed:typed}),compareNatural=createCompareNatural({compare:compare,typed:typed}),cumsum=createCumSum({add:add$1,typed:typed,unaryPlus:unaryPlus}),deepEqual=createDeepEqual({equal:equal$1,typed:typed}),diff=createDiff({matrix:matrix$2,number:number,subtract:subtract$1,typed:typed}),dot=createDot({addScalar:addScalar,conj:conj$1,multiplyScalar:multiplyScalar,size:size$1,typed:typed}),equalText=createEqualText({compareText:compareText,isZero:isZero,typed:typed}),floor=createFloor({DenseMatrix:DenseMatrix,config:config$2,equalScalar:equalScalar,matrix:matrix$2,round:round$1,typed:typed,zeros:zeros}),identity$1=createIdentity({BigNumber:BigNumber,DenseMatrix:DenseMatrix,SparseMatrix:SparseMatrix,config:config$2,matrix:matrix$2,typed:typed}),invmod=createInvmod({BigNumber:BigNumber,add:add$1,config:config$2,equal:equal$1,isInteger:isInteger,mod:mod$1,smaller:smaller,typed:typed,xgcd:xgcd}),larger=createLarger({DenseMatrix:DenseMatrix,config:config$2,matrix:matrix$2,typed:typed}),log$1=createLog({Complex:Complex,config:config$2,divideScalar:divideScalar,typed:typed}),lsolveAll=createLsolveAll({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed}),matrixFromRows=createMatrixFromRows({flatten:flatten$3,matrix:matrix$2,size:size$1,typed:typed}),multiply$1=createMultiply({addScalar:addScalar,dot:dot,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,typed:typed}),qr=createQr({addScalar:addScalar,complex:complex,conj:conj$1,divideScalar:divideScalar,equal:equal$1,identity:identity$1,isZero:isZero,matrix:matrix$2,multiplyScalar:multiplyScalar,sign:sign$1,sqrt:sqrt$1,subtract:subtract$1,typed:typed,unaryMinus:unaryMinus,zeros:zeros}),range$1=createRange({bignumber:bignumber,matrix:matrix$2,config:config$2,larger:larger,largerEq:largerEq,smaller:smaller,smallerEq:smallerEq,typed:typed}),rightLogShift=createRightLogShift({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,typed:typed,zeros:zeros}),setSize=createSetSize({compareNatural:compareNatural,typed:typed}),slu=createSlu({SparseMatrix:SparseMatrix,abs:abs$1,add:add$1,divideScalar:divideScalar,larger:larger,largerEq:largerEq,multiply:multiply$1,subtract:subtract$1,transpose:transpose,typed:typed}),sum=createSum({add:add$1,config:config$2,numeric:numeric,typed:typed}),trace=createTrace({add:add$1,matrix:matrix$2,typed:typed}),usolveAll=createUsolveAll({DenseMatrix:DenseMatrix,divideScalar:divideScalar,equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed}),asin$1=createAsin({Complex:Complex,config:config$2,typed:typed}),ceil=createCeil({DenseMatrix:DenseMatrix,config:config$2,equalScalar:equalScalar,matrix:matrix$2,round:round$1,typed:typed,zeros:zeros}),composition=createComposition({addScalar:addScalar,combinations:combinations,isInteger:isInteger,isNegative:isNegative,isPositive:isPositive,larger:larger,typed:typed}),cross=createCross({matrix:matrix$2,multiply:multiply$1,subtract:subtract$1,typed:typed}),det=createDet({divideScalar:divideScalar,isZero:isZero,matrix:matrix$2,multiply:multiply$1,subtract:subtract$1,typed:typed,unaryMinus:unaryMinus}),distance=createDistance({abs:abs$1,addScalar:addScalar,divideScalar:divideScalar,multiplyScalar:multiplyScalar,sqrt:sqrt$1,subtract:subtract$1,typed:typed,unaryMinus:unaryMinus}),dotMultiply=createDotMultiply({equalScalar:equalScalar,matrix:matrix$2,multiplyScalar:multiplyScalar,typed:typed}),FibonacciHeap=createFibonacciHeapClass({larger:larger,smaller:smaller}),fix=createFix({Complex:Complex,DenseMatrix:DenseMatrix,ceil:ceil,equalScalar:equalScalar,floor:floor,matrix:matrix$2,typed:typed,zeros:zeros}),ImmutableDenseMatrix=createImmutableDenseMatrixClass({DenseMatrix:DenseMatrix,smaller:smaller}),Index=createIndexClass({ImmutableDenseMatrix:ImmutableDenseMatrix}),intersect=createIntersect({abs:abs$1,add:add$1,addScalar:addScalar,config:config$2,divideScalar:divideScalar,equalScalar:equalScalar,flatten:flatten$3,isNumeric:isNumeric,isZero:isZero,matrix:matrix$2,multiply:multiply$1,multiplyScalar:multiplyScalar,smaller:smaller,subtract:subtract$1,typed:typed}),lcm=createLcm({equalScalar:equalScalar,matrix:matrix$2,typed:typed}),log1p=createLog1p({Complex:Complex,config:config$2,divideScalar:divideScalar,log:log$1,typed:typed}),max$1=createMax({config:config$2,larger:larger,numeric:numeric,typed:typed}),quantileSeq=createQuantileSeq({add:add$1,compare:compare,multiply:multiply$1,partitionSelect:partitionSelect,typed:typed}),row=createRow({Index:Index,matrix:matrix$2,range:range$1,typed:typed}),setCartesian=createSetCartesian({DenseMatrix:DenseMatrix,Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),setDistinct=createSetDistinct({DenseMatrix:DenseMatrix,Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),setIsSubset=createSetIsSubset({Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),setPowerset=createSetPowerset({Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),sort=createSort({compare:compare,compareNatural:compareNatural,matrix:matrix$2,typed:typed}),column=createColumn({Index:Index,matrix:matrix$2,range:range$1,typed:typed}),index=createIndex({Index:Index,typed:typed}),inv=createInv({abs:abs$1,addScalar:addScalar,det:det,divideScalar:divideScalar,identity:identity$1,matrix:matrix$2,multiply:multiply$1,typed:typed,unaryMinus:unaryMinus}),pinv=createPinv({Complex:Complex,add:add$1,ctranspose:ctranspose,deepEqual:deepEqual,divideScalar:divideScalar,dot:dot,dotDivide:dotDivide,equal:equal$1,inv:inv,matrix:matrix$2,multiply:multiply$1,typed:typed}),pow$1=createPow({Complex:Complex,config:config$2,fraction:fraction,identity:identity$1,inv:inv,matrix:matrix$2,multiply:multiply$1,number:number,typed:typed}),setDifference=createSetDifference({DenseMatrix:DenseMatrix,Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),setMultiplicity=createSetMultiplicity({Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),Spa=createSpaClass({FibonacciHeap:FibonacciHeap,addScalar:addScalar,equalScalar:equalScalar}),sqrtm=createSqrtm({abs:abs$1,add:add$1,identity:identity$1,inv:inv,max:max$1,multiply:multiply$1,size:size$1,sqrt:sqrt$1,subtract:subtract$1,typed:typed}),Unit=createUnitClass({BigNumber:BigNumber,Complex:Complex,Fraction:Fraction,abs:abs$1,addScalar:addScalar,config:config$2,divideScalar:divideScalar,equal:equal$1,fix:fix,format:format,isNumeric:isNumeric,multiplyScalar:multiplyScalar,number:number,pow:pow$1,round:round$1,subtract:subtract$1}),vacuumImpedance=createVacuumImpedance({BigNumber:BigNumber,Unit:Unit,config:config$2}),wienDisplacement=createWienDisplacement({BigNumber:BigNumber,Unit:Unit,config:config$2}),atomicMass=createAtomicMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),bohrMagneton=createBohrMagneton({BigNumber:BigNumber,Unit:Unit,config:config$2}),boltzmann=createBoltzmann({BigNumber:BigNumber,Unit:Unit,config:config$2}),conductanceQuantum=createConductanceQuantum({BigNumber:BigNumber,Unit:Unit,config:config$2}),createUnit=createCreateUnit({Unit:Unit,typed:typed}),deuteronMass=createDeuteronMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),dotPow=createDotPow({DenseMatrix:DenseMatrix,equalScalar:equalScalar,matrix:matrix$2,pow:pow$1,typed:typed}),electricConstant=createElectricConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),elementaryCharge=createElementaryCharge({BigNumber:BigNumber,Unit:Unit,config:config$2}),expm=createExpm({abs:abs$1,add:add$1,identity:identity$1,inv:inv,multiply:multiply$1,typed:typed}),faraday=createFaraday({BigNumber:BigNumber,Unit:Unit,config:config$2}),firstRadiation=createFirstRadiation({BigNumber:BigNumber,Unit:Unit,config:config$2}),gamma$1=createGamma({BigNumber:BigNumber,Complex:Complex,config:config$2,multiplyScalar:multiplyScalar,pow:pow$1,typed:typed}),gravitationConstant=createGravitationConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),hartreeEnergy=createHartreeEnergy({BigNumber:BigNumber,Unit:Unit,config:config$2}),klitzing=createKlitzing({BigNumber:BigNumber,Unit:Unit,config:config$2}),loschmidt=createLoschmidt({BigNumber:BigNumber,Unit:Unit,config:config$2}),magneticConstant=createMagneticConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),molarMass=createMolarMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),molarPlanckConstant=createMolarPlanckConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),neutronMass=createNeutronMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),nuclearMagneton=createNuclearMagneton({BigNumber:BigNumber,Unit:Unit,config:config$2}),planckCharge=createPlanckCharge({BigNumber:BigNumber,Unit:Unit,config:config$2}),planckLength=createPlanckLength({BigNumber:BigNumber,Unit:Unit,config:config$2}),planckTemperature=createPlanckTemperature({BigNumber:BigNumber,Unit:Unit,config:config$2}),protonMass=createProtonMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),reducedPlanckConstant=createReducedPlanckConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),rydberg=createRydberg({BigNumber:BigNumber,Unit:Unit,config:config$2}),setIntersect=createSetIntersect({DenseMatrix:DenseMatrix,Index:Index,compareNatural:compareNatural,size:size$1,subset:subset,typed:typed}),speedOfLight=createSpeedOfLight({BigNumber:BigNumber,Unit:Unit,config:config$2}),stefanBoltzmann=createStefanBoltzmann({BigNumber:BigNumber,Unit:Unit,config:config$2}),thomsonCrossSection=createThomsonCrossSection({BigNumber:BigNumber,Unit:Unit,config:config$2}),avogadro=createAvogadro({BigNumber:BigNumber,Unit:Unit,config:config$2}),bohrRadius=createBohrRadius({BigNumber:BigNumber,Unit:Unit,config:config$2}),coulomb=createCoulomb({BigNumber:BigNumber,Unit:Unit,config:config$2}),divide$1=createDivide({divideScalar:divideScalar,equalScalar:equalScalar,inv:inv,matrix:matrix$2,multiply:multiply$1,typed:typed}),electronMass=createElectronMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),factorial$1=createFactorial({gamma:gamma$1,typed:typed}),gravity=createGravity({BigNumber:BigNumber,Unit:Unit,config:config$2}),inverseConductanceQuantum=createInverseConductanceQuantum({BigNumber:BigNumber,Unit:Unit,config:config$2}),lup=createLup({DenseMatrix:DenseMatrix,Spa:Spa,SparseMatrix:SparseMatrix,abs:abs$1,addScalar:addScalar,divideScalar:divideScalar,equalScalar:equalScalar,larger:larger,matrix:matrix$2,multiplyScalar:multiplyScalar,subtract:subtract$1,typed:typed,unaryMinus:unaryMinus}),magneticFluxQuantum=createMagneticFluxQuantum({BigNumber:BigNumber,Unit:Unit,config:config$2}),molarMassC12=createMolarMassC12({BigNumber:BigNumber,Unit:Unit,config:config$2}),multinomial=createMultinomial({add:add$1,divide:divide$1,factorial:factorial$1,isInteger:isInteger,isPositive:isPositive,multiply:multiply$1,typed:typed}),permutations=createPermutations({factorial:factorial$1,typed:typed}),planckMass=createPlanckMass({BigNumber:BigNumber,Unit:Unit,config:config$2}),quantumOfCirculation=createQuantumOfCirculation({BigNumber:BigNumber,Unit:Unit,config:config$2}),secondRadiation=createSecondRadiation({BigNumber:BigNumber,Unit:Unit,config:config$2}),stirlingS2=createStirlingS2({bignumber:bignumber,addScalar:addScalar,combinations:combinations,divideScalar:divideScalar,factorial:factorial$1,isInteger:isInteger,isNegative:isNegative,larger:larger,multiplyScalar:multiplyScalar,number:number,pow:pow$1,subtract:subtract$1,typed:typed}),unit=createUnitFunction({Unit:Unit,typed:typed}),bellNumbers=createBellNumbers({addScalar:addScalar,isInteger:isInteger,isNegative:isNegative,stirlingS2:stirlingS2,typed:typed}),eigs=createEigs({abs:abs$1,add:add$1,addScalar:addScalar,atan:atan$1,bignumber:bignumber,column:column,complex:complex,config:config$2,cos:cos$1,diag:diag,divideScalar:divideScalar,dot:dot,equal:equal$1,flatten:flatten$3,im:im$1,inv:inv,larger:larger,matrix:matrix$2,matrixFromColumns:matrixFromColumns,multiply:multiply$1,multiplyScalar:multiplyScalar,number:number,qr:qr,re:re$1,sin:sin$1,smaller:smaller,sqrt:sqrt$1,subtract:subtract$1,typed:typed,usolve:usolve,usolveAll:usolveAll}),fermiCoupling=createFermiCoupling({BigNumber:BigNumber,Unit:Unit,config:config$2}),mean=createMean({add:add$1,divide:divide$1,typed:typed}),molarVolume=createMolarVolume({BigNumber:BigNumber,Unit:Unit,config:config$2}),planckConstant=createPlanckConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),setSymDifference=createSetSymDifference({Index:Index,concat:concat,setDifference:setDifference,size:size$1,subset:subset,typed:typed}),classicalElectronRadius=createClassicalElectronRadius({BigNumber:BigNumber,Unit:Unit,config:config$2}),lusolve=createLusolve({DenseMatrix:DenseMatrix,lsolve:lsolve,lup:lup,matrix:matrix$2,slu:slu,typed:typed,usolve:usolve}),median=createMedian({add:add$1,compare:compare,divide:divide$1,partitionSelect:partitionSelect,typed:typed}),setUnion=createSetUnion({Index:Index,concat:concat,setIntersect:setIntersect,setSymDifference:setSymDifference,size:size$1,subset:subset,typed:typed}),variance=createVariance({add:add$1,apply:apply,divide:divide$1,isNaN:isNaN$2,multiply:multiply$1,subtract:subtract$1,typed:typed}),kldivergence=createKldivergence({divide:divide$1,dotDivide:dotDivide,isNumeric:isNumeric,log:log$1,matrix:matrix$2,multiply:multiply$1,sum:sum,typed:typed}),norm=createNorm({abs:abs$1,add:add$1,conj:conj$1,ctranspose:ctranspose,eigs:eigs,equalScalar:equalScalar,larger:larger,matrix:matrix$2,multiply:multiply$1,pow:pow$1,smaller:smaller,sqrt:sqrt$1,typed:typed}),planckTime=createPlanckTime({BigNumber:BigNumber,Unit:Unit,config:config$2}),rotationMatrix=createRotationMatrix({BigNumber:BigNumber,DenseMatrix:DenseMatrix,SparseMatrix:SparseMatrix,addScalar:addScalar,config:config$2,cos:cos$1,matrix:matrix$2,multiplyScalar:multiplyScalar,norm:norm,sin:sin$1,typed:typed,unaryMinus:unaryMinus}),gasConstant=createGasConstant({BigNumber:BigNumber,Unit:Unit,config:config$2}),std=createStd({sqrt:sqrt$1,typed:typed,variance:variance}),mad=createMad({abs:abs$1,map:map$1,median:median,subtract:subtract$1,typed:typed}),rotate=createRotate({multiply:multiply$1,rotationMatrix:rotationMatrix,typed:typed}),math$2={},mathWithTransform={},classes={},Chain=createChainClass({math:math$2}),Node=createNode({mathWithTransform:mathWithTransform}),ObjectNode=createObjectNode({Node:Node}),OperatorNode=createOperatorNode({Node:Node}),ParenthesisNode=createParenthesisNode({Node:Node}),RelationalNode=createRelationalNode({Node:Node}),ArrayNode=createArrayNode({Node:Node}),BlockNode=createBlockNode({Node:Node,ResultSet:ResultSet}),ConditionalNode=createConditionalNode({Node:Node}),ConstantNode=createConstantNode({Node:Node}),RangeNode=createRangeNode({Node:Node}),reviver=createReviver({classes:classes}),chain$1=createChain({Chain:Chain,typed:typed}),FunctionAssignmentNode=createFunctionAssignmentNode({Node:Node,typed:typed}),AccessorNode=createAccessorNode({Node:Node,subset:subset}),AssignmentNode=createAssignmentNode({matrix:matrix$2,Node:Node,subset:subset}),IndexNode=createIndexNode({Node:Node,size:size$1}),SymbolNode=createSymbolNode({Unit:Unit,Node:Node,math:math$2}),FunctionNode=createFunctionNode({Node:Node,SymbolNode:SymbolNode,math:math$2}),parse$2=createParse({AccessorNode:AccessorNode,ArrayNode:ArrayNode,AssignmentNode:AssignmentNode,BlockNode:BlockNode,ConditionalNode:ConditionalNode,ConstantNode:ConstantNode,FunctionAssignmentNode:FunctionAssignmentNode,FunctionNode:FunctionNode,IndexNode:IndexNode,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,RangeNode:RangeNode,RelationalNode:RelationalNode,SymbolNode:SymbolNode,config:config$2,numeric:numeric,typed:typed}),resolve=createResolve({ConstantNode:ConstantNode,FunctionNode:FunctionNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,parse:parse$2}),simplifyCore=createSimplifyCore({AccessorNode:AccessorNode,ArrayNode:ArrayNode,ConstantNode:ConstantNode,FunctionNode:FunctionNode,IndexNode:IndexNode,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,SymbolNode:SymbolNode,add:add$1,divide:divide$1,equal:equal$1,isZero:isZero,multiply:multiply$1,pow:pow$1,subtract:subtract$1}),compile=createCompile({parse:parse$2,typed:typed}),Help=createHelpClass({parse:parse$2}),leafCount=createLeafCount({parse:parse$2,typed:typed}),simplify$2=createSimplify({bignumber:bignumber,fraction:fraction,AccessorNode:AccessorNode,ArrayNode:ArrayNode,ConstantNode:ConstantNode,FunctionNode:FunctionNode,IndexNode:IndexNode,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,SymbolNode:SymbolNode,add:add$1,config:config$2,divide:divide$1,equal:equal$1,isZero:isZero,mathWithTransform:mathWithTransform,matrix:matrix$2,multiply:multiply$1,parse:parse$2,pow:pow$1,resolve:resolve,simplifyCore:simplifyCore,subtract:subtract$1,typed:typed}),symbolicEqual=createSymbolicEqual({OperatorNode:OperatorNode,parse:parse$2,simplify:simplify$2,typed:typed}),evaluate$1=createEvaluate({parse:parse$2,typed:typed}),help=createHelp({Help:Help,mathWithTransform:mathWithTransform,typed:typed}),Parser=createParserClass({evaluate:evaluate$1}),rationalize=createRationalize({bignumber:bignumber,fraction:fraction,AccessorNode:AccessorNode,ArrayNode:ArrayNode,ConstantNode:ConstantNode,FunctionNode:FunctionNode,IndexNode:IndexNode,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,SymbolNode:SymbolNode,add:add$1,config:config$2,divide:divide$1,equal:equal$1,isZero:isZero,mathWithTransform:mathWithTransform,matrix:matrix$2,multiply:multiply$1,parse:parse$2,pow:pow$1,simplify:simplify$2,simplifyCore:simplifyCore,subtract:subtract$1,typed:typed}),derivative$1=createDerivative({ConstantNode:ConstantNode,FunctionNode:FunctionNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,SymbolNode:SymbolNode,config:config$2,equal:equal$1,isZero:isZero,numeric:numeric,parse:parse$2,simplify:simplify$2,typed:typed}),parser=createParser({Parser:Parser,typed:typed});_extends$1(math$2,{e:e,false:_false,fineStructure:fineStructure,i:i,Infinity:_Infinity,LN10:LN10,LOG10E:LOG10E,NaN:_NaN,null:_null,phi:phi,SQRT1_2:SQRT1_2,sackurTetrode:sackurTetrode,tau:tau,true:_true,E:e,version:version$1,efimovFactor:efimovFactor,LN2:LN2,pi:pi,replacer:replacer,reviver:reviver,SQRT2:SQRT2,typed:typed,unaryPlus:unaryPlus,PI:pi,weakMixingAngle:weakMixingAngle,abs:abs$1,acos:acos$1,acot:acot$1,acsc:acsc$1,addScalar:addScalar,arg:arg,asech:asech$1,asinh:asinh$1,atan:atan$1,atanh:atanh$1,bignumber:bignumber,bitNot:bitNot,boolean:boolean,chain:chain$1,clone:clone$1,combinations:combinations,complex:complex,conj:conj$1,cosh:cosh$1,coth:coth$1,csc:csc$1,cube:cube,equalScalar:equalScalar,erf:erf$1,exp:exp$1,expm1:expm1,filter:filter$1,forEach:forEach,format:format,getMatrixDataType:getMatrixDataType,hex:hex,im:im$1,isInteger:isInteger,isNegative:isNegative,isPositive:isPositive,isZero:isZero,LOG2E:LOG2E,lgamma:lgamma,log10:log10$1,log2:log2,map:map$1,multiplyScalar:multiplyScalar,not:not,number:number,oct:oct,pickRandom:pickRandom,print:print,random:random$1,re:re$1,sec:sec$1,sign:sign$1,sin:sin$1,splitUnit:splitUnit,square:square,string:string,tan:tan$1,typeOf:typeOf,acosh:acosh$1,acsch:acsch$1,apply:apply,asec:asec$1,bin:bin,combinationsWithRep:combinationsWithRep,cos:cos$1,csch:csch$1,isNaN:isNaN$2,isPrime:isPrime,randomInt:randomInt,sech:sech$1,sinh:sinh$1,sparse:sparse,sqrt:sqrt$1,tanh:tanh$1,unaryMinus:unaryMinus,acoth:acoth$1,cot:cot$1,fraction:fraction,isNumeric:isNumeric,matrix:matrix$2,matrixFromFunction:matrixFromFunction,mod:mod$1,nthRoot:nthRoot,numeric:numeric,or:or,prod:prod,reshape:reshape,size:size$1,smaller:smaller,squeeze:squeeze,subset:subset,subtract:subtract$1,to:to,transpose:transpose,xgcd:xgcd,zeros:zeros,and:and,bitAnd:bitAnd,bitXor:bitXor,cbrt:cbrt,compare:compare,compareText:compareText,concat:concat,count:count,ctranspose:ctranspose,diag:diag,divideScalar:divideScalar,dotDivide:dotDivide,equal:equal$1,fft:fft,flatten:flatten$3,gcd:gcd,hasNumericValue:hasNumericValue,hypot:hypot,ifft:ifft,kron:kron,largerEq:largerEq,leftShift:leftShift,lsolve:lsolve,matrixFromColumns:matrixFromColumns,min:min$1,mode:mode,nthRoots:nthRoots,ones:ones,partitionSelect:partitionSelect,resize:resize,rightArithShift:rightArithShift,round:round$1,smallerEq:smallerEq,unequal:unequal,usolve:usolve,xor:xor,add:add$1,atan2:atan2$1,bitOr:bitOr,catalan:catalan,compareNatural:compareNatural,cumsum:cumsum,deepEqual:deepEqual,diff:diff,dot:dot,equalText:equalText,floor:floor,identity:identity$1,invmod:invmod,larger:larger,log:log$1,lsolveAll:lsolveAll,matrixFromRows:matrixFromRows,multiply:multiply$1,qr:qr,range:range$1,rightLogShift:rightLogShift,setSize:setSize,slu:slu,sum:sum,trace:trace,usolveAll:usolveAll,asin:asin$1,ceil:ceil,composition:composition,cross:cross,det:det,distance:distance,dotMultiply:dotMultiply,fix:fix,intersect:intersect,lcm:lcm,log1p:log1p,max:max$1,quantileSeq:quantileSeq,row:row,setCartesian:setCartesian,setDistinct:setDistinct,setIsSubset:setIsSubset,setPowerset:setPowerset,sort:sort,column:column,index:index,inv:inv,pinv:pinv,pow:pow$1,setDifference:setDifference,setMultiplicity:setMultiplicity,sqrtm:sqrtm,vacuumImpedance:vacuumImpedance,wienDisplacement:wienDisplacement,atomicMass:atomicMass,bohrMagneton:bohrMagneton,boltzmann:boltzmann,conductanceQuantum:conductanceQuantum,createUnit:createUnit,deuteronMass:deuteronMass,dotPow:dotPow,electricConstant:electricConstant,elementaryCharge:elementaryCharge,expm:expm,faraday:faraday,firstRadiation:firstRadiation,gamma:gamma$1,gravitationConstant:gravitationConstant,hartreeEnergy:hartreeEnergy,klitzing:klitzing,loschmidt:loschmidt,magneticConstant:magneticConstant,molarMass:molarMass,molarPlanckConstant:molarPlanckConstant,neutronMass:neutronMass,nuclearMagneton:nuclearMagneton,planckCharge:planckCharge,planckLength:planckLength,planckTemperature:planckTemperature,protonMass:protonMass,reducedPlanckConstant:reducedPlanckConstant,rydberg:rydberg,setIntersect:setIntersect,speedOfLight:speedOfLight,stefanBoltzmann:stefanBoltzmann,thomsonCrossSection:thomsonCrossSection,avogadro:avogadro,bohrRadius:bohrRadius,coulomb:coulomb,divide:divide$1,electronMass:electronMass,factorial:factorial$1,gravity:gravity,inverseConductanceQuantum:inverseConductanceQuantum,lup:lup,magneticFluxQuantum:magneticFluxQuantum,molarMassC12:molarMassC12,multinomial:multinomial,parse:parse$2,permutations:permutations,planckMass:planckMass,quantumOfCirculation:quantumOfCirculation,resolve:resolve,secondRadiation:secondRadiation,simplifyCore:simplifyCore,stirlingS2:stirlingS2,unit:unit,bellNumbers:bellNumbers,compile:compile,eigs:eigs,fermiCoupling:fermiCoupling,leafCount:leafCount,mean:mean,molarVolume:molarVolume,planckConstant:planckConstant,setSymDifference:setSymDifference,simplify:simplify$2,symbolicEqual:symbolicEqual,classicalElectronRadius:classicalElectronRadius,evaluate:evaluate$1,help:help,lusolve:lusolve,median:median,rationalize:rationalize,setUnion:setUnion,variance:variance,derivative:derivative$1,kldivergence:kldivergence,norm:norm,planckTime:planckTime,rotationMatrix:rotationMatrix,gasConstant:gasConstant,parser:parser,std:std,mad:mad,rotate:rotate,config:config$2}),_extends$1(mathWithTransform,math$2,{filter:createFilterTransform({typed:typed}),forEach:createForEachTransform({typed:typed}),map:createMapTransform({typed:typed}),apply:createApplyTransform({isInteger:isInteger,typed:typed}),diff:createDiffTransform({bignumber:bignumber,matrix:matrix$2,number:number,subtract:subtract$1,typed:typed}),subset:createSubsetTransform({matrix:matrix$2,typed:typed}),concat:createConcatTransform({isInteger:isInteger,matrix:matrix$2,typed:typed}),max:createMaxTransform({config:config$2,larger:larger,numeric:numeric,typed:typed}),min:createMinTransform({config:config$2,numeric:numeric,smaller:smaller,typed:typed}),range:createRangeTransform({bignumber:bignumber,matrix:matrix$2,config:config$2,larger:larger,largerEq:largerEq,smaller:smaller,smallerEq:smallerEq,typed:typed}),sum:createSumTransform({add:add$1,config:config$2,numeric:numeric,typed:typed}),cumsum:createCumSumTransform({add:add$1,typed:typed,unaryPlus:unaryPlus}),row:createRowTransform({Index:Index,matrix:matrix$2,range:range$1,typed:typed}),column:createColumnTransform({Index:Index,matrix:matrix$2,range:range$1,typed:typed}),index:createIndexTransform({Index:Index}),mean:createMeanTransform({add:add$1,divide:divide$1,typed:typed}),variance:createVarianceTransform({add:add$1,apply:apply,divide:divide$1,isNaN:isNaN$2,multiply:multiply$1,subtract:subtract$1,typed:typed}),std:createStdTransform({sqrt:sqrt$1,typed:typed,variance:variance})}),_extends$1(classes,{BigNumber:BigNumber,Chain:Chain,Complex:Complex,Fraction:Fraction,Matrix:Matrix,Node:Node,ObjectNode:ObjectNode,OperatorNode:OperatorNode,ParenthesisNode:ParenthesisNode,Range:Range,RelationalNode:RelationalNode,ResultSet:ResultSet,ArrayNode:ArrayNode,BlockNode:BlockNode,ConditionalNode:ConditionalNode,ConstantNode:ConstantNode,DenseMatrix:DenseMatrix,RangeNode:RangeNode,FunctionAssignmentNode:FunctionAssignmentNode,SparseMatrix:SparseMatrix,AccessorNode:AccessorNode,AssignmentNode:AssignmentNode,IndexNode:IndexNode,FibonacciHeap:FibonacciHeap,ImmutableDenseMatrix:ImmutableDenseMatrix,Index:Index,Spa:Spa,Unit:Unit,SymbolNode:SymbolNode,FunctionNode:FunctionNode,Help:Help,Parser:Parser}),Chain.createProxy(math$2);var all=allFactories;Number.isFinite=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Number.isNaN=Number.isNaN||function(e){return e!=e};var tinyEmitter={exports:{}};function E(){}function mixin$1(e){var t=new tinyEmitter.exports;return e.on=t.on.bind(t),e.off=t.off.bind(t),e.once=t.once.bind(t),e.emit=t.emit.bind(t),e}function importFactory(e,t,n,r){function a(t,a,s){var o;if(s.wrap&&"function"==typeof a&&(a=function(e){var t=function(){for(var t=[],r=0,a=arguments.length;r2&&void 0!==arguments[2]?arguments[2]:t.fn;if(contains$1(i,"."))throw new Error("Factory name should not contain a nested path. Name: "+JSON.stringify(i));var o=d(t)?n.expression.transform:n,l=i in n.expression.transform,c=hasOwnProperty$2(o,i)?o[i]:void 0,m=function(){var r={};t.dependencies.map(stripOptionalNotation).forEach((e=>{if(contains$1(e,"."))throw new Error("Factory dependency should not contain a nested path. Name: "+JSON.stringify(e));"math"===e?r.math=n:"mathWithTransform"===e?r.mathWithTransform=n.expression.mathWithTransform:"classes"===e?r.classes=n:r[e]=n[e]}));var s=t(r);if(s&&"function"==typeof s.transform)throw new Error('Transforms cannot be attached to factory functions. Please create a separate function for it with exports.path="expression.transform"');if(void 0===c||a.override)return s;if(u(c)&&u(s))return e(c,s);if(a.silent)return c;throw new Error('Cannot import "'+i+'": already exists')};t.meta&&!1===t.meta.lazy?(o[i]=m(),c&&l?s(i):(d(t)||p(t))&&lazy(n.expression.mathWithTransform,i,(()=>o[i]))):(lazy(o,i,m),c&&l?s(i):(d(t)||p(t))&&lazy(n.expression.mathWithTransform,i,(()=>o[i]))),r[i]=t,n.emit("import",i,m)}function l(e){return"function"==typeof e||"number"==typeof e||"string"==typeof e||"boolean"==typeof e||null===e||isUnit(e)||isComplex(e)||isBigNumber(e)||isFraction(e)||isMatrix(e)||Array.isArray(e)}function u(e){return"function"==typeof e&&"object"==typeof e.signatures}function c(e){return!hasOwnProperty$2(m,e)}function p(e){return!(-1!==e.fn.indexOf(".")||hasOwnProperty$2(m,e.fn)||e.meta&&e.meta.isClass)}function d(e){return void 0!==e&&void 0!==e.meta&&!0===e.meta.isTransformFunction||!1}var m={expression:!0,type:!0,docs:!0,error:!0,json:!0,chain:!0};return function(e,t){var n=arguments.length;if(1!==n&&2!==n)throw new ArgumentsError("import",n,1,2);t||(t={});var r={};for(var i in function e(n,r,a){if(Array.isArray(r))r.forEach((t=>e(n,t)));else if("object"==typeof r)for(var i in r)hasOwnProperty$2(r,i)&&e(n,r[i],i);else if(isFactory(r)||void 0!==a){var s=isFactory(r)?d(r)?r.fn+".transform":r.fn:a;if(hasOwnProperty$2(n,s)&&n[s]!==r&&!t.silent)throw new Error('Cannot import "'+s+'" twice');n[s]=r}else if(!t.silent)throw new TypeError("Factory, Object, or Array expected")}(r,e),r)if(hasOwnProperty$2(r,i)){var s=r[i];if(isFactory(s))o(s,t);else if(l(s))a(i,s,t);else if(!t.silent)throw new TypeError("Factory, Object, or Array expected")}}}function create$1(e,t){var n=_extends$1({},DEFAULT_CONFIG,t);if("function"!=typeof Object.create)throw new Error("ES5 not supported by this JavaScript engine. Please load the es5-shim and es5-sham library for compatibility.");var r=mixin$1({isNumber:isNumber$1,isComplex:isComplex,isBigNumber:isBigNumber,isFraction:isFraction,isUnit:isUnit,isString:isString$1,isArray:isArray$1,isMatrix:isMatrix,isCollection:isCollection,isDenseMatrix:isDenseMatrix,isSparseMatrix:isSparseMatrix,isRange:isRange,isIndex:isIndex,isBoolean:isBoolean$1,isResultSet:isResultSet,isHelp:isHelp,isFunction:isFunction$2,isDate:isDate$1,isRegExp:isRegExp$1,isObject:isObject$1,isNull:isNull$1,isUndefined:isUndefined$1,isAccessorNode:isAccessorNode,isArrayNode:isArrayNode,isAssignmentNode:isAssignmentNode,isBlockNode:isBlockNode,isConditionalNode:isConditionalNode,isConstantNode:isConstantNode,isFunctionAssignmentNode:isFunctionAssignmentNode,isFunctionNode:isFunctionNode,isIndexNode:isIndexNode,isNode:isNode,isObjectNode:isObjectNode,isOperatorNode:isOperatorNode,isParenthesisNode:isParenthesisNode,isRangeNode:isRangeNode,isSymbolNode:isSymbolNode,isChain:isChain});r.config=configFactory(n,r.emit),r.expression={transform:{},mathWithTransform:{config:r.config}};var a=[],i=[],s={},o=importFactory((function(){for(var e=arguments.length,t=new Array(e),n=0;n{values$1(s).forEach((e=>{e&&e.meta&&e.meta.recreateOnConfigChange&&o(e,{override:!0})}))})),r.create=create$1.bind(null,e),r.factory=factory,r.import(values$1(deepFlatten(e))),r.ArgumentsError=ArgumentsError,r.DimensionError=DimensionError,r.IndexError=IndexError,r}E.prototype={on:function(e,t,n){var r=this.e||(this.e={});return(r[e]||(r[e]=[])).push({fn:t,ctx:n}),this},once:function(e,t,n){var r=this;function a(){r.off(e,a),t.apply(n,arguments)}return a._=t,this.on(e,a,n)},emit:function(e){for(var t=[].slice.call(arguments,1),n=((this.e||(this.e={}))[e]||[]).slice(),r=0,a=n.length;r3;a-=4)e(),e(),e(),e();for(;a>0;)e(),a--;if(new Date-n>t)break}for(a=r;a>3;a-=4)e(),e(),e(),e();for(;a>0;)e(),a--;return 1e3*(3*r-1)/(new Date-n)},numeric._myIndexOf=function(e){var t,n=this.length;for(t=0;tnumeric.largeArray)return n.push("...Large Array..."),!0;for(u=!1,n.push("["),a=0;a0&&(n.push(","),u&&n.push("\n ")),u=e(r[a]);return n.push("]"),!0}for(a in n.push("{"),u=!1,r)r.hasOwnProperty(a)&&(u&&n.push(",\n"),u=!0,n.push(a),n.push(": \n"),e(r[a]));return n.push("}"),!0}(e),n.join("")},numeric.parseDate=function(e){return function e(t){if("string"==typeof t)return Date.parse(t.replace(/-/g,"/"));if(!(t instanceof Array))throw new Error("parseDate: parameter must be arrays of strings");var n,r=[];for(n=0;n0){for(i[l]=[],t=0;t>>8^a[255&(i^e[r])];return-1^i}var n,r,a,i,s,o,l,u,c,p,d=e[0].length,m=e[0][0].length,h=[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,m>>24&255,m>>16&255,m>>8&255,255&m,d>>24&255,d>>16&255,d>>8&255,255&d,8,2,0,0,0,-1,-2,-3,-4,-5,-6,-7,-8,73,68,65,84,8,29];for(p=t(h,12,29),h[29]=p>>24&255,h[30]=p>>16&255,h[31]=p>>8&255,h[32]=255&p,n=1,r=0,l=0;l>8&255,h.push(s),h.push(o),h.push(255&~s),h.push(255&~o),0===l&&h.push(0),u=0;u255?255:s<0?0:Math.round(s)))%65521))%65521,h.push(s);h.push(0)}return c=(r<<16)+n,h.push(c>>24&255),h.push(c>>16&255),h.push(c>>8&255),h.push(255&c),i=h.length-41,h[33]=i>>24&255,h[34]=i>>16&255,h[35]=i>>8&255,h[36]=255&i,p=t(h,37),h.push(p>>24&255),h.push(p>>16&255),h.push(p>>8&255),h.push(255&p),h.push(0),h.push(0),h.push(0),h.push(0),h.push(73),h.push(69),h.push(78),h.push(68),h.push(174),h.push(66),h.push(96),h.push(130),"data:image/png;base64,"+function(e){var t,n,r,a,i,s,o,l=e.length,u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",c="";for(t=0;t>4),s=((15&r)<<2)+((a=e[t+2])>>6),o=63&a,t+1>=l?s=o=64:t+2>=l&&(o=64),c+=u.charAt(n>>2)+u.charAt(i)+u.charAt(s)+u.charAt(o);return c}(h)},numeric._dim=function(e){for(var t=[];"object"==typeof e;)t.push(e.length),e=e[0];return t},numeric.dim=function(e){var t;return"object"==typeof e?"object"==typeof(t=e[0])?"object"==typeof t[0]?numeric._dim(e):[e.length,t.length]:[e.length]:[]},numeric.mapreduce=function(e,t){return Function("x","accum","_s","_k",'if(typeof accum === "undefined") accum = '+t+';\nif(typeof x === "number") { var xi = x; '+e+'; return accum; }\nif(typeof _s === "undefined") _s = numeric.dim(x);\nif(typeof _k === "undefined") _k = 0;\nvar _n = _s[_k];\nvar i,xi;\nif(_k < _s.length-1) {\n for(i=_n-1;i>=0;i--) {\n accum = arguments.callee(x[i],accum,_s,_k+1);\n } return accum;\n}\nfor(i=_n-1;i>=1;i-=2) { \n xi = x[i];\n '+e+";\n xi = x[i-1];\n "+e+";\n}\nif(i === 0) {\n xi = x[i];\n "+e+"\n}\nreturn accum;")},numeric.mapreduce2=function(e,t){return Function("x","var n = x.length;\nvar i,xi;\n"+t+";\nfor(i=n-1;i!==-1;--i) { \n xi = x[i];\n "+e+";\n}\nreturn accum;")},numeric.same=function e(t,n){var r,a;if(!(t instanceof Array&&n instanceof Array))return!1;if((a=t.length)!==n.length)return!1;for(r=0;r=0;r-=2)i[r+1]=t,i[r]=t;return-1===r&&(i[0]=t),i}for(r=a-1;r>=0;r--)i[r]=numeric.rep(e,t,n+1);return i},numeric.dotMMsmall=function(e,t){var n,r,a,i,s,o,l,u,c,p,d;for(i=e.length,s=t.length,o=t[0].length,l=Array(i),n=i-1;n>=0;n--){for(u=Array(o),c=e[n],a=o-1;a>=0;a--){for(p=c[s-1]*t[s-1][a],r=s-2;r>=1;r-=2)d=r-1,p+=c[r]*t[r][a]+c[d]*t[d][a];0===r&&(p+=c[0]*t[0][a]),u[a]=p}l[n]=u}return l},numeric._getCol=function(e,t,n){var r;for(r=e.length-1;r>0;--r)n[r]=e[r][t],n[--r]=e[r][t];0===r&&(n[0]=e[0][t])},numeric.dotMMbig=function(e,t){var n,r,a,i=numeric._getCol,s=t.length,o=Array(s),l=e.length,u=t[0].length,c=new Array(l),p=numeric.dotVV;for(--s,r=--l;-1!==r;--r)c[r]=Array(u);for(r=--u;-1!==r;--r)for(i(t,r,o),a=l;-1!==a;--a)n=e[a],c[a][r]=p(n,o);return c},numeric.dotMV=function(e,t){var n,r=e.length;t.length;var a=Array(r),i=numeric.dotVV;for(n=r-1;n>=0;n--)a[n]=i(e[n],t);return a},numeric.dotVM=function(e,t){var n,r,a,i,s,o,l;for(a=e.length,i=t[0].length,s=Array(i),r=i-1;r>=0;r--){for(o=e[a-1]*t[a-1][r],n=a-2;n>=1;n-=2)l=n-1,o+=e[n]*t[n][r]+e[l]*t[l][r];0===n&&(o+=e[0]*t[0][r]),s[r]=o}return s},numeric.dotVV=function(e,t){var n,r,a=e.length,i=e[a-1]*t[a-1];for(n=a-2;n>=1;n-=2)r=n-1,i+=e[n]*t[n]+e[r]*t[r];return 0===n&&(i+=e[0]*t[0]),i},numeric.dot=function(e,t){var n=numeric.dim;switch(1e3*n(e).length+n(t).length){case 2002:return t.length<10?numeric.dotMMsmall(e,t):numeric.dotMMbig(e,t);case 2001:return numeric.dotMV(e,t);case 1002:return numeric.dotVM(e,t);case 1001:return numeric.dotVV(e,t);case 1e3:return numeric.mulVS(e,t);case 1:return numeric.mulSV(e,t);case 0:return e*t;default:throw new Error("numeric.dot only works on vectors and matrices")}},numeric.diag=function(e){var t,n,r,a,i=e.length,s=Array(i);for(t=i-1;t>=0;t--){for(a=Array(i),n=t+2,r=i-1;r>=n;r-=2)a[r]=0,a[r-1]=0;for(r>t&&(a[r]=0),a[t]=e[t],r=t-1;r>=1;r-=2)a[r]=0,a[r-1]=0;0===r&&(a[0]=0),s[t]=a}return s},numeric.getDiag=function(e){var t,n=Math.min(e.length,e[0].length),r=Array(n);for(t=n-1;t>=1;--t)r[t]=e[t][t],r[--t]=e[t][t];return 0===t&&(r[0]=e[0][0]),r},numeric.identity=function(e){return numeric.diag(numeric.rep([e],1))},numeric.pointwise=function(e,t,n){void 0===n&&(n="");var r,a,i=[],s=/\[i\]$/,o="",l=!1;for(r=0;r=0;i--) ret[i] = arguments.callee("+e.join(",")+",_s,_k+1);\n return ret;\n}\n"+n+"\nfor(i=_n-1;i!==-1;--i) {\n "+t+"\n}\nreturn ret;",Function.apply(null,i)},numeric.pointwise2=function(e,t,n){void 0===n&&(n="");var r,a,i=[],s=/\[i\]$/,o="",l=!1;for(r=0;r=0;s--)e("object"==typeof t?t[s]:t,"object"==typeof n?n[s]:n,r,a+1,i);else i(t,n)},numeric._biforeach2=function e(t,n,r,a,i){if(a===r.length-1)return i(t,n);var s,o=r[a],l=Array(o);for(s=o-1;s>=0;--s)l[s]=e("object"==typeof t?t[s]:t,"object"==typeof n?n[s]:n,r,a+1,i);return l},numeric._foreach=function e(t,n,r,a){var i;if(r!==n.length-1)for(i=n[r]-1;i>=0;i--)e(t[i],n,r+1,a);else a(t)},numeric._foreach2=function e(t,n,r,a){if(r===n.length-1)return a(t);var i,s=n[r],o=Array(s);for(i=s-1;i>=0;i--)o[i]=e(t[i],n,r+1,a);return o},numeric.ops2={add:"+",sub:"-",mul:"*",div:"/",mod:"%",and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">=",band:"&",bor:"|",bxor:"^",lshift:"<<",rshift:">>",rrshift:">>>"},numeric.opseq={addeq:"+=",subeq:"-=",muleq:"*=",diveq:"/=",modeq:"%=",lshifteq:"<<=",rshifteq:">>=",rrshifteq:">>>=",bandeq:"&=",boreq:"|=",bxoreq:"^="},numeric.mathfuns=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan","isNaN","isFinite"],numeric.mathfuns2=["atan2","pow","max","min"],numeric.ops1={neg:"-",not:"!",bnot:"~",clone:""},numeric.mapreducers={any:["if(xi) return true;","var accum = false;"],all:["if(!xi) return false;","var accum = true;"],sum:["accum += xi;","var accum = 0;"],prod:["accum *= xi;","var accum = 1;"],norm2Squared:["accum += xi*xi;","var accum = 0;"],norminf:["accum = max(accum,abs(xi));","var accum = 0, max = Math.max, abs = Math.abs;"],norm1:["accum += abs(xi)","var accum = 0, abs = Math.abs;"],sup:["accum = max(accum,xi);","var accum = -Infinity, max = Math.max;"],inf:["accum = min(accum,xi);","var accum = Infinity, min = Math.min;"]},function(){var e,t;for(e=0;ef&&(h=i,f=o);for(n=d[h],d[h]=d[s],d[s]=n,a=m[h],m[h]=m[s],m[s]=a,e=n[s],o=s;o!==p;++o)n[o]/=e;for(o=p-1;-1!==o;--o)a[o]/=e;for(i=c-1;-1!==i;--i)if(i!==s){for(t=d[i],r=m[i],e=t[s],o=s+1;o!==p;++o)t[o]-=n[o]*e;for(o=p-1;o>0;--o)r[o]-=a[o]*e,r[--o]-=a[o]*e;0===o&&(r[0]-=a[0]*e)}}return m},numeric.det=function(e){var t=numeric.dim(e);if(2!==t.length||t[0]!==t[1])throw new Error("numeric: det() only works on square matrices");var n,r,a,i,s,o,l,u,c=t[0],p=1,d=numeric.clone(e);for(r=0;rMath.abs(d[a][r])&&(a=n);for(a!==r&&(l=d[a],d[a]=d[r],d[r]=l,p*=-1),i=d[r],n=r+1;n=1;t-=2){for(a=e[t],r=e[t-1],n=o-1;n>=1;--n)(i=l[n])[t]=a[n],i[t-1]=r[n],(i=l[--n])[t]=a[n],i[t-1]=r[n];0===n&&((i=l[0])[t]=a[0],i[t-1]=r[0])}if(0===t){for(r=e[0],n=o-1;n>=1;--n)l[n][0]=r[n],l[--n][0]=r[n];0===n&&(l[0][0]=r[0])}return l},numeric.negtranspose=function(e){var t,n,r,a,i,s=e.length,o=e[0].length,l=Array(o);for(n=0;n=1;t-=2){for(a=e[t],r=e[t-1],n=o-1;n>=1;--n)(i=l[n])[t]=-a[n],i[t-1]=-r[n],(i=l[--n])[t]=-a[n],i[t-1]=-r[n];0===n&&((i=l[0])[t]=-a[0],i[t-1]=-r[0])}if(0===t){for(r=e[0],n=o-1;n>=1;--n)l[n][0]=-r[n],l[--n][0]=-r[n];0===n&&(l[0][0]=-r[0])}return l},numeric._random=function e(t,n){var r,a,i=t[n],s=Array(i);if(n===t.length-1){for(a=Math.random,r=i-1;r>=1;r-=2)s[r]=a(),s[r-1]=a();return 0===r&&(s[0]=a()),s}for(r=i-1;r>=0;r--)s[r]=e(t,n+1);return s},numeric.random=function(e){return numeric._random(e,0)},numeric.norm2=function(e){return Math.sqrt(numeric.norm2Squared(e))},numeric.linspace=function(e,t,n){if(void 0===n&&(n=Math.max(Math.round(t-e)+1,1)),n<2)return 1===n?[e]:[];var r,a=Array(n);for(r=--n;r>=0;r--)a[r]=(r*t+(n-r)*e)/n;return a},numeric.getBlock=function(e,t,n){var r=numeric.dim(e);return function e(a,i){var s,o=t[i],l=n[i]-o,u=Array(l);if(i===r.length-1){for(s=l;s>=0;s--)u[s]=a[s+o];return u}for(s=l;s>=0;s--)u[s]=e(a[s+o],i+1);return u}(e,0)},numeric.setBlock=function(e,t,n,r){var a=numeric.dim(e);return function e(r,i,s){var o,l=t[s],u=n[s]-l;if(s===a.length-1)for(o=u;o>=0;o--)r[o+l]=i[o];for(o=u;o>=0;o--)e(r[o+l],i[o],s+1)}(e,r,0),e},numeric.getRange=function(e,t,n){var r,a,i,s,o=t.length,l=n.length,u=Array(o);for(r=o-1;-1!==r;--r)for(u[r]=Array(l),i=u[r],s=e[t[r]],a=l-1;-1!==a;--a)i[a]=s[n[a]];return u},numeric.blockMatrix=function(e){var t=numeric.dim(e);if(t.length<4)return numeric.blockMatrix([e]);var n,r,a,i,s,o=t[0],l=t[1];for(n=0,r=0,a=0;a=0;i--){for(a=Array(u),o=e[i],s=u-1;s>=3;--s)a[s]=o*t[s],a[--s]=o*t[s],a[--s]=o*t[s],a[--s]=o*t[s];for(;s>=0;)a[s]=o*t[s],--s;c[i]=a}return c},numeric.T=function(e,t){this.x=e,this.y=t},numeric.t=function(e,t){return new numeric.T(e,t)},numeric.Tbinop=function(e,t,n,r,a){var i;if(numeric.indexOf,"string"!=typeof a)for(i in a="",numeric)numeric.hasOwnProperty(i)&&(e.indexOf(i)>=0||t.indexOf(i)>=0||n.indexOf(i)>=0||r.indexOf(i)>=0)&&i.length>1&&(a+="var "+i+" = numeric."+i+";\n");return Function(["y"],"var x = this;\nif(!(y instanceof numeric.T)) { y = new numeric.T(y); }\n"+a+"\nif(x.y) { if(y.y) { return new numeric.T("+r+");\n }\n return new numeric.T("+n+");\n}\nif(y.y) {\n return new numeric.T("+t+");\n}\nreturn new numeric.T("+e+");\n")},numeric.T.prototype.add=numeric.Tbinop("add(x.x,y.x)","add(x.x,y.x),y.y","add(x.x,y.x),x.y","add(x.x,y.x),add(x.y,y.y)"),numeric.T.prototype.sub=numeric.Tbinop("sub(x.x,y.x)","sub(x.x,y.x),neg(y.y)","sub(x.x,y.x),x.y","sub(x.x,y.x),sub(x.y,y.y)"),numeric.T.prototype.mul=numeric.Tbinop("mul(x.x,y.x)","mul(x.x,y.x),mul(x.x,y.y)","mul(x.x,y.x),mul(x.y,y.x)","sub(mul(x.x,y.x),mul(x.y,y.y)),add(mul(x.x,y.y),mul(x.y,y.x))"),numeric.T.prototype.reciprocal=function(){var e=numeric.mul,t=numeric.div;if(this.y){var n=numeric.add(e(this.x,this.x),e(this.y,this.y));return new numeric.T(t(this.x,n),t(numeric.neg(this.y),n))}return new T(t(1,this.x))},numeric.T.prototype.div=function(e){if(e instanceof numeric.T||(e=new numeric.T(e)),e.y)return this.mul(e.reciprocal());var t=numeric.div;return this.y?new numeric.T(t(this.x,e.x),t(this.y,e.x)):new numeric.T(t(this.x,e.x))},numeric.T.prototype.dot=numeric.Tbinop("dot(x.x,y.x)","dot(x.x,y.x),dot(x.x,y.y)","dot(x.x,y.x),dot(x.y,y.x)","sub(dot(x.x,y.x),dot(x.y,y.y)),add(dot(x.x,y.y),dot(x.y,y.x))"),numeric.T.prototype.transpose=function(){var e=numeric.transpose,t=this.x,n=this.y;return n?new numeric.T(e(t),e(n)):new numeric.T(e(t))},numeric.T.prototype.transjugate=function(){var e=numeric.transpose,t=this.x,n=this.y;return n?new numeric.T(e(t),numeric.negtranspose(n)):new numeric.T(e(t))},numeric.Tunop=function(e,t,n){return"string"!=typeof n&&(n=""),Function("var x = this;\n"+n+"\nif(x.y) { "+t+";\n}\n"+e+";\n")},numeric.T.prototype.exp=numeric.Tunop("return new numeric.T(ex)","return new numeric.T(mul(cos(x.y),ex),mul(sin(x.y),ex))","var ex = numeric.exp(x.x), cos = numeric.cos, sin = numeric.sin, mul = numeric.mul;"),numeric.T.prototype.conj=numeric.Tunop("return new numeric.T(x.x);","return new numeric.T(x.x,numeric.neg(x.y));"),numeric.T.prototype.neg=numeric.Tunop("return new numeric.T(neg(x.x));","return new numeric.T(neg(x.x),neg(x.y));","var neg = numeric.neg;"),numeric.T.prototype.sin=numeric.Tunop("return new numeric.T(numeric.sin(x.x))","return x.exp().sub(x.neg().exp()).div(new numeric.T(0,2));"),numeric.T.prototype.cos=numeric.Tunop("return new numeric.T(numeric.cos(x.x))","return x.exp().add(x.neg().exp()).div(2);"),numeric.T.prototype.abs=numeric.Tunop("return new numeric.T(numeric.abs(x.x));","return new numeric.T(numeric.sqrt(numeric.add(mul(x.x,x.x),mul(x.y,x.y))));","var mul = numeric.mul;"),numeric.T.prototype.log=numeric.Tunop("return new numeric.T(numeric.log(x.x));","var theta = new numeric.T(numeric.atan2(x.y,x.x)), r = x.abs();\nreturn new numeric.T(numeric.log(r.x),theta.x);"),numeric.T.prototype.norm2=numeric.Tunop("return numeric.norm2(x.x);","var f = numeric.norm2Squared;\nreturn Math.sqrt(f(x.x)+f(x.y));"),numeric.T.prototype.inv=function(){var e=this;if(void 0===e.y)return new numeric.T(numeric.inv(e.x));var t,n,r,a,i,s,o,l,u,c,p,d,m,h,f,y,g,b,v=e.x.length,N=numeric.identity(v),T=numeric.rep([v,v],0),C=numeric.clone(e.x),A=numeric.clone(e.y);for(u=0;ud&&(p=c,d=m);for(p!==u&&(b=C[u],C[u]=C[p],C[p]=b,b=A[u],A[u]=A[p],A[p]=b,b=N[u],N[u]=N[p],N[p]=b,b=T[u],T[u]=T[p],T[p]=b),t=C[u],n=A[u],i=N[u],s=T[u],h=t[u],f=n[u],c=u+1;c0;u--)for(i=N[u],s=T[u],c=u-1;c>=0;c--)for(o=N[c],l=T[c],h=C[c][u],f=A[c][u],p=v-1;p>=0;p--)y=i[p],g=s[p],o[p]-=h*y-f*g,l[p]-=h*g+f*y;return new numeric.T(N,T)},numeric.T.prototype.get=function(e){var t,n=this.x,r=this.y,a=0,i=e.length;if(r){for(;a=0?1:-1)*numeric.norm2(e);t[0]+=n;var r=numeric.norm2(t);if(0===r)throw new Error("eig: internal error");return numeric.div(t,r)},numeric.toUpperHessenberg=function(e){var t=numeric.dim(e);if(2!==t.length||t[0]!==t[1])throw new Error("numeric: toUpperHessenberg() only works on square matrices");var n,r,a,i,s,o,l,u,c,p,d=t[0],m=numeric.clone(e),h=numeric.identity(d);for(r=0;r0){for(s=numeric.house(i),o=numeric.getBlock(m,[r+1,r],[d-1,d-1]),l=numeric.tensor(s,numeric.dot(s,o)),n=r+1;n=4*l?(x=.5*(u+Math.sqrt(u*u-4*l)),S=.5*(u-Math.sqrt(u*u-4*l)),c=numeric.add(numeric.sub(numeric.dot(c,c),numeric.mul(c,x+S)),numeric.diag(numeric.rep([3],x*S)))):c=numeric.add(numeric.sub(numeric.dot(c,c),numeric.mul(c,u)),numeric.diag(numeric.rep([3],l))),n=[c[0][0],c[1][0],c[2][0]],r=numeric.house(n),m=[e[0],e[1],e[2]],h=numeric.tensor(r,numeric.dot(r,m)),y=0;y<3;y++)for(d=e[y],f=h[y],b=0;b=0?((y=(s-(d=c<0?-.5*(c-S(p)):-.5*(c+S(p))))*(s-d)+o*o)>(g=l*l+(u-d)*(u-d))?(h=(s-d)/(y=S(y)),f=o/y):(h=l/(g=S(g)),f=(u-d)/g),a=new N([[f,-h],[h,f]]),V.setRows(n,i,a.dot(V.getRows(n,i)))):(d=-.5*c,m=.5*S(-p),(y=(s-d)*(s-d)+o*o)>(g=l*l+(u-d)*(u-d))?(h=(s-d)/(y=S(y+m*m)),f=o/y,d=0,m/=y):(h=l/(g=S(g+m*m)),f=(u-d)/g,d=m/g,m=0),a=new N([[f,-h],[h,f]],[[d,m],[m,-d]]),V.setRows(n,i,a.dot(V.getRows(n,i))))}var w=V.dot(e).dot(V.transjugate()),E=(T=e.length,numeric.T.identity(T));for(i=0;i0)for(r=i-1;r>=0;r--){var D=w.get([r,r]),O=w.get([i,i]);numeric.neq(D.x,O.x)||numeric.neq(D.y,O.y)?(d=w.getRow(r).getBlock([r],[i-1]),m=E.getRow(i).getBlock([r],[i-1]),E.set([i,r],w.get([r,i]).neg().sub(d.dot(m)).div(D.sub(O)))):E.setRow(i,E.getRow(r))}for(i=0;i=i.length;)i[i.length]=0;0!==t[r]&&i[r]++}var s=i.length,o=Array(s+1);for(o[0]=0,n=0;n=l){if(a[c]=m[u],0===u)return;++c,o=p[--u],l=d[u]}else 0===r[s=i[n[o]]]?(r[s]=1,p[u]=o,m[++u]=s,o=t[s],d[u]=l=t[s+1]):++o},numeric.ccsLPSolve=function(e,t,n,r,a,i,s){var o=e[0],l=e[1],u=e[2];o.length;var c,p,d,m,h,f,y,g,b,v=t[0],N=t[1],T=t[2];for(p=v[a],d=v[a+1],r.length=0,c=p;ci&&(s=a,i=o);for(T(b[n])=u){if(a[p]=i[h[c]],0===c)return;++p,l=d[--c],u=m[c]}else 0===r[o=n[l]]?(r[o]=1,d[c]=l,h[++c]=o,l=t[o=i[o]],m[c]=u=t[o+1]):++l}},numeric.ccsLPSolve0=function(e,t,n,r,a,i,s,o){var l=e[0],u=e[1],c=e[2];l.length;var p,d,m,h,f,y,g,b,v,N=t[0],T=t[1],C=t[2];for(d=N[a],m=N[a+1],r.length=0,p=d;pi&&(s=a,i=o);for(T(b[C[n]])n[r]&&(n[r]=t.length),t)t.hasOwnProperty(a)&&e(t[a],n,r+1);return n},numeric.sclone=function e(t,n,r){void 0===n&&(n=0),void 0===r&&(r=numeric.sdim(t).length);var a,i=Array(t.length);if(n===r-1){for(a in t)t.hasOwnProperty(a)&&(i[a]=t[a]);return i}for(a in t)t.hasOwnProperty(a)&&(i[a]=e(t[a],n+1,r));return i},numeric.sdiag=function(e){var t,n,r=e.length,a=Array(r);for(t=r-1;t>=1;t-=2)n=t-1,a[t]=[],a[t][t]=e[t],a[n]=[],a[n][n]=e[n];return 0===t&&(a[0]=[],a[0][0]=e[t]),a},numeric.sidentity=function(e){return numeric.sdiag(numeric.rep([e],1))},numeric.stranspose=function(e){var t,n,r,a=[];for(t in e.length,e)if(e.hasOwnProperty(t))for(n in r=e[t])r.hasOwnProperty(n)&&("object"!=typeof a[n]&&(a[n]=[]),a[n][t]=r[n]);return a},numeric.sLUP=function(e,t){throw new Error("The function numeric.sLUP had a bug in it and has been removed. Please use the new numeric.ccsLUP function instead.")},numeric.sdotMM=function(e,t){var n=e.length;t.length;var r,a,i,s,o,l,u,c=numeric.stranspose(t),p=c.length,d=Array(n);for(i=n-1;i>=0;i--){for(u=[],r=e[i],o=p-1;o>=0;o--){for(s in l=0,a=c[o],r)r.hasOwnProperty(s)&&s in a&&(l+=r[s]*a[s]);l&&(u[o]=l)}d[i]=u}return d},numeric.sdotMV=function(e,t){var n,r,a,i,s=e.length,o=Array(s);for(r=s-1;r>=0;r--){for(a in i=0,n=e[r])n.hasOwnProperty(a)&&t[a]&&(i+=n[a]*t[a]);i&&(o[r]=i)}return o},numeric.sdotVM=function(e,t){var n,r,a,i,s=[];for(n in e)if(e.hasOwnProperty(n))for(r in a=t[n],i=e[n],a)a.hasOwnProperty(r)&&(s[r]||(s[r]=0),s[r]+=i*a[r]);return s},numeric.sdotVV=function(e,t){var n,r=0;for(n in e)e[n]&&t[n]&&(r+=e[n]*t[n]);return r},numeric.sdot=function(e,t){var n=numeric.sdim(e).length,r=numeric.sdim(t).length;switch(1e3*n+r){case 0:return e*t;case 1001:return numeric.sdotVV(e,t);case 2001:return numeric.sdotMV(e,t);case 1002:return numeric.sdotVM(e,t);case 2002:return numeric.sdotMM(e,t);default:throw new Error("numeric.sdot not implemented for tensors of order "+n+" and "+r)}},numeric.sscatter=function(e){var t,n,r,a,i=e[0].length,s=e.length,o=[];for(n=i-1;n>=0;--n)if(e[s-1][n]){for(a=o,r=0;r=0;--i)n[i]=[];for(i=a;i>=0;--i)n[i].push(r[i]);n[a+1].push(s)}}else e(s,n,r);return r.length>a&&r.pop(),n},numeric.cLU=function(e){var t,n,r,a,i,s,o=e[0],l=e[1],u=e[2],c=o.length,p=0;for(t=0;tp&&(p=o[t]);p++;var d,m=Array(p),h=Array(p),f=numeric.rep([p],1/0),y=numeric.rep([p],-1/0);for(r=0;ry[t]&&(y[t]=n);for(t=0;ty[t+1]&&(y[t+1]=y[t]);for(t=p-1;t>=1;t--)f[t]=0;d--){for(;u[m]>d;)a[d]-=c[m]*a[u[m]],m--;a[d]/=c[m],m--}return a},numeric.cgrid=function(e,t){"number"==typeof e&&(e=[e,e]);var n,r,a,i=numeric.rep(e,-1);for("function"!=typeof t&&(t="L"===t?function(t,n){return t>=e[0]/2||na&&(a=i[r]);for(a++,n=numeric.rep([a],0),r=0;r1;)a[r=s((t+n)/2)]<=e?t=r:n=r;return this._at(e,t)}i=e.length;var o,l=Array(i);for(o=i-1;-1!==o;--o)l[o]=this.at(e[o]);return l},numeric.Spline.prototype.diff=function(){var e,t,n,r=this.x,a=this.yl,i=this.yr,s=this.kl,o=this.kr,l=a.length,u=s,c=o,p=Array(l),d=Array(l),m=numeric.add,h=numeric.mul,f=numeric.div,y=numeric.sub;for(e=l-1;-1!==e;--e)t=r[e+1]-r[e],n=y(i[e+1],a[e]),p[e]=f(m(h(n,6),h(s[e],-4*t),h(o[e+1],-2*t)),t*t),d[e+1]=f(m(h(n,-6),h(s[e],2*t),h(o[e+1],4*t)),t*t);return new numeric.Spline(r,u,c,p,d)},numeric.Spline.prototype.roots=function(){function e(e){return e*e}var t=[],n=this.x,r=this.yl,a=this.yr,i=this.kl,s=this.kr;"number"==typeof r[0]&&(r=[r],a=[a],i=[i],s=[s]);var o,l,u,c,p,d,m,h,f,y,g,b,v,N,T,C,A,V,x,S,w,E,D,O=r.length,I=n.length-1,R=(t=Array(O),Math.sqrt);for(o=0;o!==O;++o){for(c=r[o],p=a[o],d=i[o],m=s[o],h=[],l=0;l!==I;l++){for(l>0&&p[l]*c[l]<0&&h.push(n[l]),C=n[l+1]-n[l],n[l],g=c[l],b=p[l+1],f=d[l]/C,v=(y=m[l+1]/C)+3*g+2*f-3*b,N=3*(y+f+2*(g-b)),(T=e(f-y+3*(g-b))+12*y*g)<=0?A=(V=v/N)>n[l]&&Vn[l]&&Vn[l]&&x0)w=E,V=x;else{for(var _=0;!((D=(V*E-x*w)/(V-x))<=w||D>=E);)if((S=this._at(D,l))*x>0)E=D,x=S,-1===_&&(V*=.5),_=-1;else{if(!(S*V>0))break;w=D,V=S,1===_&&(x*=.5),_=1}h.push(D),w=A[u+1],V=this._at(w,l)}else h.push(w),w=E,V=x;0===x&&h.push(E)}t[o]=h}return"number"==typeof this.yl[0]?t[0]:t},numeric.spline=function(e,t,n,r){var a,i=e.length,s=[],o=[],l=[],u=numeric.sub,c=numeric.mul,p=numeric.add;for(a=i-2;a>=0;a--)o[a]=e[a+1]-e[a],l[a]=u(t[a+1],t[a]);"string"!=typeof n&&"string"!=typeof r||(n=r="periodic");var d=[[],[],[]];switch(typeof n){case"undefined":s[0]=c(3/(o[0]*o[0]),l[0]),d[0].push(0,0),d[1].push(0,1),d[2].push(2/o[0],1/o[0]);break;case"string":s[0]=p(c(3/(o[i-2]*o[i-2]),l[i-2]),c(3/(o[0]*o[0]),l[0])),d[0].push(0,0,0),d[1].push(i-2,0,1),d[2].push(1/o[i-2],2/o[i-2]+2/o[0],1/o[0]);break;default:s[0]=n,d[0].push(0),d[1].push(0),d[2].push(1)}for(a=1;a20)throw new Error("Numerical gradient fails");if(l[a]=t[a]+v,i=e(l),l[a]=t[a]-v,s=e(l),l[a]=t[a],isNaN(i)||isNaN(s))v/=16;else{if(u[a]=(i-s)/(2*v),c=t[a]-v,p=t[a],d=t[a]+v,m=(i-r)/v,h=(r-s)/v,f=o(y(u[a]),y(r),y(i),y(s),y(c),y(p),y(d),1e-8),!(g(o(y(m-u[a]),y(h-u[a]),y(m-h))/f,v/f)>.001))break;v/=16}}return u},numeric.uncmin=function(e,t,n,r,a,i,s){var o=numeric.gradient;void 0===s&&(s={}),void 0===n&&(n=1e-8),void 0===r&&(r=function(t){return o(e,t)}),void 0===a&&(a=1e3);var l,u,c=(t=numeric.clone(t)).length,p=e(t);if(isNaN(p))throw new Error("uncmin: f(x0) is a NaN!");var d=Math.max,m=numeric.norm2;n=d(n,numeric.epsilon);var h,f,y,g=s.Hinv||numeric.identity(c),b=numeric.dot;numeric.inv;var v,N,T,C,A,V,x,S=numeric.sub,w=numeric.add,E=numeric.tensor,D=numeric.div,O=numeric.mul,I=numeric.all,R=numeric.isFinite,_=numeric.neg,M=0,P="";for(f=r(t);M=.1*V*u||isNaN(l));)V*=.5,++M;if(V*x1;)o[r=a(.5*(t+n))]<=e?t=r:n=r;return this._at(e,t)},numeric.dopri=function(e,t,n,r,a,i,s){void 0===a&&(a=1e-6),void 0===i&&(i=1e3);var o,l,u,c,p,d,m,h,f,y,g,b,v,N=[e],T=[n],C=[r(e,n)],A=[],V=[3/40,9/40],x=[44/45,-56/15,32/9],S=[19372/6561,-25360/2187,64448/6561,-212/729],w=[9017/3168,-355/33,46732/5247,49/176,-5103/18656],E=[35/384,0,500/1113,125/192,-2187/6784,11/84],D=[.10013431883002395,0,.3918321794184259,-.02982460176594817,.05893268337240795,-.04497888809104361,5618549.5/235043384],O=[.2,.3,.8,8/9,1,1],I=[-71/57600,0,71/16695,-71/1920,17253/339200,-22/525,1/40],R=0,_=(t-e)/10,M=0,P=numeric.add,F=numeric.mul,k=Math.min,$=Math.abs,B=numeric.norminf,L=Math.pow,z=numeric.any,U=numeric.lt,j=numeric.and;numeric.sub;var q=new numeric.Dopri(N,T,C,A,-1,"");for("function"==typeof s&&(g=s(e,n));et&&(_=t-e),o=r(e+O[0]*_,P(n,F(.2*_,C[R]))),l=r(e+O[1]*_,P(P(n,F(V[0]*_,C[R])),F(V[1]*_,o))),u=r(e+O[2]*_,P(P(P(n,F(x[0]*_,C[R])),F(x[1]*_,o)),F(x[2]*_,l))),c=r(e+O[3]*_,P(P(P(P(n,F(S[0]*_,C[R])),F(S[1]*_,o)),F(S[2]*_,l)),F(S[3]*_,u))),p=r(e+O[4]*_,P(P(P(P(P(n,F(w[0]*_,C[R])),F(w[1]*_,o)),F(w[2]*_,l)),F(w[3]*_,u)),F(w[4]*_,c))),d=r(e+_,f=P(P(P(P(P(n,F(C[R],_*E[0])),F(l,_*E[2])),F(u,_*E[3])),F(c,_*E[4])),F(p,_*E[5]))),(y="number"==typeof(m=P(P(P(P(P(F(C[R],_*I[0]),F(l,_*I[2])),F(u,_*I[3])),F(c,_*I[4])),F(p,_*I[5])),F(d,_*I[6])))?$(m):B(m))>a){if(e+(_=.2*_*L(a/y,.25))===e){q.msg="Step size became too small";break}}else{if(A[R]=P(P(P(P(P(P(n,F(C[R],_*D[0])),F(l,_*D[2])),F(u,_*D[3])),F(c,_*D[4])),F(p,_*D[5])),F(d,_*D[6])),N[++R]=e+_,T[R]=f,C[R]=d,"function"==typeof s){var G,H,W=e,K=e+.5*_;if(b=s(K,A[R-1]),z(v=j(U(g,0),U(0,b)))||(W=K,g=b,b=s(K=e+_,f),v=j(U(g,0),U(0,b))),z(v)){for(var Z,X,Y=0,Q=1,J=1;;){if("number"==typeof g)H=(J*b*W-Q*g*K)/(J*b-Q*g);else for(H=K,h=g.length-1;-1!==h;--h)g[h]<0&&b[h]>0&&(H=k(H,(J*b[h]*W-Q*g[h]*K)/(J*b[h]-Q*g[h])));if(H<=W||H>=K)break;X=s(H,G=q._at(H,R-1)),z(Z=j(U(g,0),U(0,X)))?(K=H,b=X,v=Z,J=1,-1===Y?Q*=.5:Q=1,Y=-1):(W=H,g=X,Q=1,1===Y?J*=.5:J=1,Y=1)}return f=q._at(.5*(e+H),R-1),q.f[R]=r(H,G),q.x[R]=H,q.y[R]=G,q.ymid[R-1]=f,q.events=v,q.iterations=M,q}}e+=_,n=f,g=b,_=k(.8*_*L(a/y,.25),4*_)}return q.iterations=M,q},numeric.LU=function(e,t){t=t||!1;var n,r,a,i,s,o,l,u,c,p=Math.abs,d=e.length,m=d-1,h=new Array(d);for(t||(e=numeric.clone(e)),a=0;a=0;--n){for(i=o[n],r=n+1;rP)&&(g=P),E=m(e,u(g,x)),T=p(M,S),R=h-1;-1!==R;--R)T[R][R]+=1;_=D(T,d(E,g),!0);var F=d(O,p(t,_)),k=1;for(R=f-1;-1!==R;--R)F[R]<0&&(k=C(k,-.999*F[R]));if(l=c(i,u(_,k)),!A(V(O=c(n,p(t,l)),0)))return{solution:i,message:"",iterations:w};if(i=l,g=0);if(y)return{solution:l,message:"Unbounded",iterations:w}}return{solution:i,message:"maximum iteration count exceeded",iterations:w}},numeric._solveLP=function(e,t,n,r,a){var i=e.length,s=n.length;numeric.sum,numeric.log,numeric.mul;var o=numeric.sub,l=numeric.dot;numeric.div,numeric.add;var u=numeric.rep([i],0).concat([1]),c=numeric.rep([s,1],-1),p=numeric.blockMatrix([[t,c]]),d=n,m=numeric.rep([i],0).concat(Math.max(0,numeric.sup(numeric.neg(n)))+1),h=numeric.__solveLP(u,p,d,r,a,m,!1),f=numeric.clone(h.solution);if(f.length=i,numeric.inf(o(n,l(t,f)))<0)return{solution:NaN,message:"Infeasible",iterations:h.iterations};var y=numeric.__solveLP(e,t,n,r,a-h.iterations,f,!0);return y.iterations+=h.iterations,y},numeric.solveLP=function(e,t,n,r,a,i,s){if(void 0===s&&(s=1e3),void 0===i&&(i=numeric.epsilon),void 0===r)return numeric._solveLP(e,t,n,i,s);var o,l=r.length,u=r[0].length,c=t.length,p=numeric.echelonize(r),d=numeric.rep([u],0),m=p.P,h=[];for(o=m.length-1;-1!==o;--o)d[m[o]]=1;for(o=u-1;-1!==o;--o)0===d[o]&&h.push(o);var f=numeric.getRange,y=numeric.linspace(0,l-1),g=numeric.linspace(0,c-1),b=f(r,y,h),v=f(t,g,m),N=f(t,g,h),T=numeric.dot,C=numeric.sub,A=T(v,p.I),V=C(N,T(A,b)),x=C(n,T(A,a)),S=Array(m.length),w=Array(h.length);for(o=m.length-1;-1!==o;--o)S[o]=e[m[o]];for(o=h.length-1;-1!==o;--o)w[o]=e[h[o]];var E=C(w,T(S,T(p.I,b))),D=numeric._solveLP(E,V,x,i,s),O=D.solution;if(O!=O)return D;var I=T(p.I,C(a,T(b,O))),R=Array(e.length);for(o=m.length-1;-1!==o;--o)R[m[o]]=I[o];for(o=h.length-1;-1!==o;--o)R[h[o]]=O[o];return{solution:R,message:D.message,iterations:D.iterations}},numeric.MPStoLP=function(e){e instanceof String&&e.split("\n");var t,n,r,a,i=0,s=["Initial state","NAME","ROWS","COLUMNS","RHS","BOUNDS","ENDATA"],o=e.length,l=0,u={},c=[],p=0,d={},m=0,h=[],f=[],y=[];function g(n){throw new Error("MPStoLP: "+n+"\nLine "+t+": "+e[t]+"\nCurrent state: "+s[i]+"\n")}for(t=0;t=i;)e/=2,t/=2,r>>>=1;return(e+r)/t},r},s=t.pow(n,6),a=t.pow(2,a),i=2*a,u(t.random(),e)}([],numeric.seedrandom,256,0,52),function(e){function t(e){if("object"!=typeof e)return e;var n,r=[],a=e.length;for(n=0;nc)h[b]=I;else if(h[b]=-Math.abs(I),I>0){for(g=1;g<=r;g+=1)s[g][y]=-s[g][y];o[y]=-o[y]}}for(y=1;y<=d;y+=1)h[x+p[y]]=0;for(w=0,O=0,y=1;y<=u;y+=1)h[x+y]=1;y-=1){for(I=h[y],v=(b=V+y*(y+3)/2)-y,g=y+1;g<=d;g+=1)I-=h[b]*h[A+g],b+=g;if(I/=h[v],h[A+y]=I,p[y]c)h[x+w]=I;else if(h[x+w]=-Math.abs(I),I>0){for(g=1;g<=r;g+=1)s[g][w]=-s[g][w];o[w]=-o[w]}return 700}for(p[d+=1]=w,b=V+(d-1)*d/2+1,y=1;y<=d-1;y+=1)h[b]=h[y],b+=1;if(d===r)h[b]=h[r];else{for(y=r;y>=d+1&&0!==h[y]&&(M=Math.max(Math.abs(h[y-1]),Math.abs(h[y])),P=Math.min(Math.abs(h[y-1]),Math.abs(h[y])),O=h[y-1]>=0?Math.abs(M*Math.sqrt(1+P*P/(M*M))):-Math.abs(M*Math.sqrt(1+P*P/(M*M))),M=h[y-1]/O,P=h[y]/O,1!==M);y-=1)if(0===M)for(h[y-1]=P*O,g=1;g<=r;g+=1)O=e[g][y-1],e[g][y-1]=e[g][y],e[g][y]=O;else for(h[y-1]=O,F=P/(1+M),g=1;g<=r;g+=1)O=M*e[g][y-1]+P*e[g][y],e[g][y]=F*(e[g][y-1]+O)-e[g][y],e[g][y-1]=O;h[b]=h[d]}return 0}function G(){if(0===h[v=(b=V+T*(T+1)/2+1)+T])return 798;if(M=Math.max(Math.abs(h[v-1]),Math.abs(h[v])),P=Math.min(Math.abs(h[v-1]),Math.abs(h[v])),O=h[v-1]>=0?Math.abs(M*Math.sqrt(1+P*P/(M*M))):-Math.abs(M*Math.sqrt(1+P*P/(M*M))),M=h[v-1]/O,P=h[v]/O,1===M)return 798;if(0===M){for(y=T+1;y<=d;y+=1)O=h[v-1],h[v-1]=h[v],h[v]=O,v+=y;for(y=1;y<=r;y+=1)O=e[y][T],e[y][T]=e[y][T+1],e[y][T+1]=O}else{for(F=P/(1+M),y=T+1;y<=d;y+=1)O=M*h[v-1]+P*h[v],h[v]=F*(h[v-1]+O)-h[v],h[v-1]=O,v+=y;for(y=1;y<=r;y+=1)O=M*e[y][T]+P*e[y][T+1],e[y][T+1]=F*(e[y][T]+O)-e[y][T+1],e[y][T]=O}return 0}function H(){for(v=b-T,y=1;y<=T;y+=1)h[v]=h[b],b+=1,v+=1;return h[S+T]=h[S+T+1],p[T]=p[T+1],(T+=1)(t=Math.abs(t))?e*Math.sqrt(1+t*t/e/e):0==t?e:t*Math.sqrt(1+e*e/t/t)}var y=0,g=0,b=0,v=0,N=0,T=0,C=0;for(i=0;i=0&&(g=-g),b=y*g-C,u[i][i]=y-g,s=l;s=0&&(g=-g),b=y*g-C,u[i][i+1]=y-g,s=l;sv&&(v=N)}for(i=p-1;-1!=i;i+=-1){if(0!=g){for(b=g*u[i][i+1],s=l;s=49)throw"Error: no convergence.";for(v=m[l],g=f(y=(((N=m[o-1])-T)*(N+T)+((g=d[o-1])-(b=d[o]))*(g+b))/(2*b*N),1),y=y<0?((v-T)*(v+T)+b*(N/(y-g)-b))/v:((v-T)*(v+T)+b*(N/(y+g)-b))/v,a=1,C=1,i=l+1;i=0;s--)if(m[s]=0&&n<=MAX_ARRAY_INDEX}}function shallowProperty(e){return function(t){return null==t?void 0:t[e]}}var getByteLength=shallowProperty("byteLength"),isBufferLike=createSizePropertyCheck(getByteLength),typedArrayPattern=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;function isTypedArray(e){return nativeIsView?nativeIsView(e)&&!isDataView$1(e):isBufferLike(e)&&typedArrayPattern.test(toString$1.call(e))}var isTypedArray$1=supportsArrayBuffer?isTypedArray:constant(!1),getLength=shallowProperty("length");function emulatedSet(e){for(var t={},n=e.length,r=0;r":">",'"':""","'":"'","`":"`"},escape=createEscaper(escapeMap),unescapeMap=invert(escapeMap),unescape=createEscaper(unescapeMap),templateSettings=_$1.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},noMatch=/(.)^/,escapes={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},escapeRegExp=/\\|'|\r|\n|\u2028|\u2029/g;function escapeChar(e){return"\\"+escapes[e]}var bareIdentifier=/^\s*(\w|\$)+\s*$/;function template(e,t,n){!t&&n&&(t=n),t=defaults({},t,_$1.templateSettings);var r=RegExp([(t.escape||noMatch).source,(t.interpolate||noMatch).source,(t.evaluate||noMatch).source].join("|")+"|$","g"),a=0,i="__p+='";e.replace(r,(function(t,n,r,s,o){return i+=e.slice(a,o).replace(escapeRegExp,escapeChar),a=o+t.length,n?i+="'+\n((__t=("+n+"))==null?'':_.escape(__t))+\n'":r?i+="'+\n((__t=("+r+"))==null?'':__t)+\n'":s&&(i+="';\n"+s+"\n__p+='"),t})),i+="';\n";var s,o=t.variable;if(o){if(!bareIdentifier.test(o))throw new Error("variable is not a bare identifier: "+o)}else i="with(obj||{}){\n"+i+"}\n",o="obj";i="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{s=new Function(o,"_",i)}catch(e){throw e.source=i,e}var l=function(e){return s.call(this,e,_$1)};return l.source="function("+o+"){\n"+i+"}",l}function result(e,t,n){var r=(t=toPath(t)).length;if(!r)return isFunction$1(n)?n.call(e):n;for(var a=0;a1)flatten$2(o,t-1,n,r),a=r.length;else for(var l=0,u=o.length;lt?(r&&(clearTimeout(r),r=null),o=u,s=e.apply(a,i),r||(a=i=null)):r||!1===n.trailing||(r=setTimeout(l,c)),s};return u.cancel=function(){clearTimeout(r),o=0,r=a=i=null},u}function debounce(e,t,n){var r,a,i,s,o,l=function(){var u=now()-a;t>u?r=setTimeout(l,t-u):(r=null,n||(s=e.apply(o,i)),r||(i=o=null))},u=restArguments((function(u){return o=this,i=u,a=now(),r||(r=setTimeout(l,t),n&&(s=e.apply(o,i))),s}));return u.cancel=function(){clearTimeout(r),r=i=o=null},u}function wrap(e,t){return partial(t,e)}function negate(e){return function(){return!e.apply(this,arguments)}}function compose(){var e=arguments,t=e.length-1;return function(){for(var n=t,r=e[t].apply(this,arguments);n--;)r=e[n].call(this,r);return r}}function after(e,t){return function(){if(--e<1)return t.apply(this,arguments)}}function before(e,t){var n;return function(){return--e>0&&(n=t.apply(this,arguments)),e<=1&&(t=null),n}}var once$1=partial(before,2);function findKey(e,t,n){t=cb(t,n);for(var r,a=keys(e),i=0,s=a.length;i0?0:a-1;i>=0&&i0?s=i>=0?i:Math.max(i+o,s):o=i>=0?Math.min(i+1,o):i+o+1;else if(n&&i&&o)return r[i=n(r,a)]===a?i:-1;if(a!=a)return(i=t(slice.call(r,s,o),isNaN$1))>=0?i+s:-1;for(i=e>0?s:o-1;i>=0&&i0?0:s-1;for(a||(r=t[i?i[o]:o],o+=e);o>=0&&o=3;return t(e,optimizeCb(n,a,4),r,i)}}var reduce$1=createReduce(1),reduceRight=createReduce(-1);function filter(e,t,n){var r=[];return t=cb(t,n),each(e,(function(e,n,a){t(e,n,a)&&r.push(e)})),r}function reject(e,t,n){return filter(e,negate(cb(t)),n)}function every(e,t,n){t=cb(t,n);for(var r=!isArrayLike(e)&&keys(e),a=(r||e).length,i=0;i=0}var invoke=restArguments((function(e,t,n){var r,a;return isFunction$1(t)?a=t:(t=toPath(t),r=t.slice(0,-1),t=t[t.length-1]),map(e,(function(e){var i=a;if(!i){if(r&&r.length&&(e=deepGet(e,r)),null==e)return;i=e[t]}return null==i?i:i.apply(e,n)}))}));function pluck(e,t){return map(e,property(t))}function where(e,t){return filter(e,matcher(t))}function max(e,t,n){var r,a,i=-1/0,s=-1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var o=0,l=(e=isArrayLike(e)?e:values(e)).length;oi&&(i=r);else t=cb(t,n),each(e,(function(e,n,r){((a=t(e,n,r))>s||a===-1/0&&i===-1/0)&&(i=e,s=a)}));return i}function min(e,t,n){var r,a,i=1/0,s=1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var o=0,l=(e=isArrayLike(e)?e:values(e)).length;or||void 0===n)return 1;if(n1&&(r=optimizeCb(r,t[1])),t=allKeys(e)):(r=keyInObj,t=flatten$2(t,!1,!1),e=Object(e));for(var a=0,i=t.length;a1&&(n=t[1])):(t=map(flatten$2(t,!1,!1),String),r=function(e,n){return!contains(t,n)}),pick(e,r,n)}));function initial(e,t,n){return slice.call(e,0,Math.max(0,e.length-(null==t||n?1:t)))}function first(e,t,n){return null==e||e.length<1?null==t||n?void 0:[]:null==t||n?e[0]:initial(e,e.length-t)}function rest(e,t,n){return slice.call(e,null==t||n?1:t)}function last(e,t,n){return null==e||e.length<1?null==t||n?void 0:[]:null==t||n?e[e.length-1]:rest(e,Math.max(0,e.length-t))}function compact(e){return filter(e,Boolean)}function flatten$1(e,t){return flatten$2(e,t,!1)}var difference=restArguments((function(e,t){return t=flatten$2(t,!0,!0),filter(e,(function(e){return!contains(t,e)}))})),without=restArguments((function(e,t){return difference(e,t)}));function uniq(e,t,n,r){isBoolean(t)||(r=n,n=t,t=!1),null!=n&&(n=cb(n,r));for(var a=[],i=[],s=0,o=getLength(e);sr&&(r=n)):(n>r&&(r=n),r*=i),Math.abs(e-t)<=r}return e===t}var i=e[0],s=e.slice(1),o=t[0],l=t.slice(1);return i===o&&(s.length===l.length&&(n>0&&!r&&"^"===i?!!equal(s[0],l[0],{allowed_error_in_numbers:n,include_error_in_number_exponents:r,allowed_error_is_absolute:a})&&equal(s[1],l[1]):_.every(_.zip(s,l),(function(e){return equal(e[0],e[1],{allowed_error_in_numbers:n,include_error_in_number_exponents:r,allowed_error_is_absolute:a})}))))},match$2=function(e,t,n){var r=!1;void 0===n?n={}:n.allow_extended_match&&(r=!0,delete(n=Object.assign({},n)).allow_extended_match);var a=n.variables;if(void 0===a){a={};let e=variables(t);for(let t=0;tObject())),s=n.length,o=!1;function l(u,c,p){let d,m=1,h=1;if((is_associative$1[e]||["tuple","vector","altvector"].includes(e))&&(m=u.length-(s-c-1),h=u.length),void 0!==r.max_group&&(m=r.max_group1?[e].concat(s):s[0],o=match$2(s,n[c],r),i[c][a]=o}if(!o)continue;if(!_.every(_.intersection(Object.keys(p),Object.keys(o)),(function(e){return equal(p[e],o[e])})))continue;let d=Object.assign({},o);Object.assign(d,p);let m=u.filter((e=>!a.includes(e)));if(c===s-1)return{matches:d,skipped:m.reduce((function(e,n){return e.concat([t[n]])}),[])};let h=l(m,c+1,d);if(h)return h}return!1}r.allow_permutations&&("*"===e?o=![...t,...n].some((e=>["tuple","list","vector","altvector","interval","set","array","matrix"].includes(e[0]))):"+"!==e&&"="!==e&&"and"!==e&&"or"!==e&&"ne"!==e&&"union"!==e&&"intersect"!==e||(o=!0));var u={},c=[...Array(t.length).keys()];if(o){let e=l(c,0,{});return!!e&&(u=e.matches,e.skipped.length>0&&(u._skipped=e.skipped),u)}{let e,n=a?t.length-s:0,r=[];for(let a=0;a<=n&&(e=l(c,0,{}),!e);a++)c=c.slice(1),r.push(t[a]);return!!e&&(u=e.matches,e.skipped.length>0&&(u._skipped=e.skipped),r.length>0&&(u._skipped_before=r),u)}}function matchImplicitIdentity(e,t,n){var r=t[0],a=t.slice(1);if("+"!==r&&"*"!==r&&"^"!==r)return!1;var i=[];for(let e=0;e0;n--){r=a;for(let e=0;e0||a.length>0)&&(Array.isArray(e)&&(e=e[0]===n[0]?e.slice(1):[e]),e=[n[0]].concat(s,e,a)),i.evaluate_numbers&&(e=evaluate_numbers(e,{max_digits:i.max_digits})),e}return e}))}if(equal(r,a))return a}return a};var math=math$1;const operators$2={"+":function(e){return 1===e.length?e[0]:new math.OperatorNode("+","add",e)},"*":function(e){return new math.OperatorNode("*","multiply",e)},"/":function(e){return new math.OperatorNode("/","divide",e)},"-":function(e){return new math.OperatorNode("-","unaryMinus",[e[0]])},"^":function(e){return new math.OperatorNode("^","pow",e)},vector:function(e){return new math.ArrayNode(e)},altvector:function(e){return new math.ArrayNode(e)},and:function(e){return new math.OperatorNode("and","and",e)},or:function(e){return new math.OperatorNode("or","or",e)},not:function(e){return new math.OperatorNode("not","not",[e[0]])},"<":function(e){return new math.OperatorNode("<","smaller",e)},">":function(e){return new math.OperatorNode(">","larger",e)},le:function(e){return new math.OperatorNode("<=","smallerEq",e)},ge:function(e){return new math.OperatorNode(">=","largerEq",e)},ne:function(e){return new math.OperatorNode("!=","unequal",e)},binom:function(e){const t=new math.SymbolNode("combinations");return new math.FunctionNode(t,e)}},functionConverstions={nCr:"combinations",nPr:"permutations",binom:"combinations"};class astToMathjs$1{constructor({mathjs:e=null}={}){e&&(math=e)}convert(e){if("number"==typeof e)return Number.isFinite(e)?new math.ConstantNode(e):Number.isNaN(e)?new math.SymbolNode("NaN"):e<0?operators$2["-"]([new math.SymbolNode("Infinity")]):new math.SymbolNode("Infinity");if("string"==typeof e)return new math.SymbolNode(e);if("boolean"==typeof e)throw Error("no support for boolean");if(!Array.isArray(e))throw Error("Invalid ast");const t=e[0],n=e.slice(1);if("apply"===t){if("string"!=typeof n[0])throw Error("Non string functions not implemented for conversion to mathjs");if("factorial"===n[0])return new math.OperatorNode("!","factorial",[this.convert(n[1])]);let e=functionConverstions[n[0]];e||(e=n[0]);const t=new math.SymbolNode(e),r=n[1];let a;return a="tuple"===r[0]?r.slice(1).map(function(e,t){return this.convert(e)}.bind(this)):[this.convert(r)],new math.FunctionNode(t,a)}if("lts"===t||"gts"===t){const e=n[0],r=n[1];if("tuple"!==e[0]||"tuple"!==r[0])throw new Error("Badly formed ast");const a=e.slice(1).map(function(e,t){return this.convert(e)}.bind(this));let i=[];for(let n=1;n","larger",a.slice(n-1,n+1))):"lts"===t?i.push(new math.OperatorNode("<=","smallerEq",a.slice(n-1,n+1))):i.push(new math.OperatorNode(">=","largerEq",a.slice(n-1,n+1)));let s=new math.OperatorNode("and","and",i.slice(0,2));for(let e=2;e=","largerEq",[e,s])):l.push(new math.OperatorNode(">","larger",[e,s])),i[2]?l.push(new math.OperatorNode("<=","smallerEq",[e,o])):l.push(new math.OperatorNode("<","smaller",[e,o]));let u=new math.OperatorNode("and","and",l);return"notin"!==t&&"notni"!==t||(u=new math.OperatorNode("not","not",[u])),u}if("subset"===t||"notsubset"===t||"superset"===t||"notsuperset"===t){let e,r;if("subset"===t||"notsubset"===t?(r=n[0],e=n[1]):(r=n[1],e=n[0]),"interval"!==r[0]||"interval"!==e[0])throw Error("Set containment of non-intervals not implemented for conversion to mathjs");let a=r[1],i=r[2],s=e[1],o=e[2];if("tuple"!==a[0]||"tuple"!==i[0]||"tuple"!==s[0]||"tuple"!==o[0])throw Error("Badly formed ast");let l=this.convert(a[1]),u=this.convert(a[2]),c=this.convert(s[1]),p=this.convert(s[2]),d=[];i[1]&&!o[1]?d.push(new math.OperatorNode(">","larger",[l,c])):d.push(new math.OperatorNode(">=","largerEq",[l,c])),i[2]&&!o[2]?d.push(new math.OperatorNode("<","smaller",[u,p])):d.push(new math.OperatorNode("<=","smallerEq",[u,p]));let m=new math.OperatorNode("and","and",d);return"notsubset"!==t&&"notsuperset"!==t||(m=new math.OperatorNode("not","not",[m])),m}if("matrix"===t){let e=n[0],t=e[1],r=e[2],a=n[1];if(!Number.isInteger(t)||!Number.isInteger(r))throw Error("Matrix must have integer dimensions");let i=[];for(let e=1;e<=t;e++){let t=[];for(let n=1;n<=r;n++)t.push(this.convert(a[e][n]));i.push(new math.ArrayNode(t))}return new math.ArrayNode(i)}if(t in operators$2)return operators$2[t](n.map(function(e,t){return this.convert(e)}.bind(this)));throw Error("Operator "+t+" not implemented for conversion to mathjs")}}var function_normalizations={ln:"log",arccos:"acos",arccosh:"acosh",arcsin:"asin",arcsinh:"asinh",arctan:"atan",arctanh:"atanh",arcsec:"asec",arcsech:"asech",arccsc:"acsc",arccsch:"acsch",arccot:"acot",arccoth:"acoth",cosec:"csc"},create_trig_inverses_for=["cos","cosh","sin","sinh","tan","tanh","sec","sech","csc","csch","cot","coth"],move_exponents_outside_for=["cos","cosh","sin","sinh","tan","tanh","sec","sech","csc","csch","cot","coth"];function normalize_function_names(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if("apply"===n){if("sqrt"===r[0])return["^",normalize_function_names(r[1]),.5];var a=normalize_function_names_sub(r[0]);a=["apply",a];var i=r.slice(1).map((function(e){return normalize_function_names(e)}));return i=i.length>1?["tuple"].concat(i):i[0],a.push(i),a}return"^"===n&&"e"===r[0]&&math$1.define_e?["apply","exp",normalize_function_names(r[1])]:"binom"===n?["apply","nCr",["tuple",normalize_function_names(r[0]),normalize_function_names(r[1])]]:[n].concat(r.map((function(e){return normalize_function_names(e)})))}function normalize_function_names_sub(e){if("string"==typeof e)return e in function_normalizations?function_normalizations[e]:e;if(!Array.isArray(e))return e;var t=e[0],n=e.slice(1);if("^"===t&&2===n.length&&-1===n[1]){let e=normalize_function_names_sub(n[0]);if(create_trig_inverses_for.includes(e))return"a"+e}return[t].concat(n.map((function(e){return normalize_function_names_sub(e)})))}function normalize_applied_functions(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if("apply"===n){let e=r[0];if("^"===e[0]){let t=e[1],n=e[2];return-1!==n&&move_exponents_outside_for.includes(t)?["^",["apply",t,normalize_applied_functions(r[1])],n]:["apply",e,normalize_applied_functions(r[1])]}let t=0;for(;"prime"===e[0];)t+=1,e=e[1];let n=["apply",e,normalize_applied_functions(r[1])];for(let e=0;e2&&(r=unflattenRight(r),s=r.slice(1)),simple_assumption_combination(i,is_integer_ast(e,s[0],n),is_integer_ast(e,s[1],n))}if(Array.isArray(e)){let r;r=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let a=e[0],i=e.slice(1);if("-"===a)return is_integer_ast(i[0],r,n);if("*"===a)return!!i.every((function(e){return is_integer_ast(e,r,n)}))||void 0;if("^"===a){let e=is_nonzero_ast(i[0],r,n);if(e){if(!1===is_nonzero_ast(i[1],r,n))return i[0]!==1/0&&i[0]!==-1/0}else{if(Number.isNaN(i[0]))return!1;if(!is_positive_ast(i[1],r,!0,n))return;if(!1===e)return!0}let t=is_integer_ast(i[0],r,n),a=is_integer_ast(i[1],r,n);if(!t)return t;if(!a)return;return!!is_positive_ast(i[1],r,!1,n)||void 0}if("+"===a){let e=0;for(let t=0;t0)return;e+=1}if(void 0===a)return}return 0===e}if("apply"===a)return!!(functions.C.Z&&functions.C.Z.includes(i[0])&&is_complex_ast(i[1],r,n))||!!(functions.R.Z&&functions.R.Z.includes(i[0])&&is_real_ast(i[1],r,n))||!!(functions.nonzeroC.Z&&functions.nonzeroC.Z.includes(i[0])&&is_nonzero_ast(i[1],r,n)&&is_complex_ast(i[1],r,n))||!!(functions.nonneg.Z&&functions.nonneg.Z.includes(i[0])&&is_positive_ast(i[1],r,!1,n))||!!(functions.pos.Z&&functions.pos.Z.includes(i[0])&&is_positive_ast(i[1],r,!0,n))||void 0;if("/"===a||"prime"===a)return;return!1}return!1}function is_real_ast(e,t,n){if("object"!=typeof t&&(t=[]),void 0===n&&(n=t),"number"==typeof e)return Number.isFinite(e);var r=evaluate_to_constant(e,!1);if(null!==r)return"number"==typeof r&&Number.isFinite(r);if("string"==typeof e){let r;if(r=Array.isArray(t)?t:t.get_assumptions(e),!Array.isArray(r))return;let a=r,i=r[0],s=r.slice(1),o=!1;for(;"not"===i;){if(o=!o,r=s[0],!Array.isArray(r))return;i=r[0],s=r.slice(1)}if("in"===i&&s[0]===e&&"R"===s[1])return negate_adjust(!0,o);if("notin"===i&&s[0]===e&&"R"===s[1])return negate_adjust(!1,o);if(!1===o){if("in"===i&&s[0]===e&&"Z"===s[1])return!0}else if("notin"===i&&s[0]===e&&"Z"===s[1])return!0;if("<"===i||"le"===i){let t=variables(r),n=functions$2(r);if(-1!==t.indexOf(e)&&0===n.length)return!0}if("="===i&&!o||"ne"===i&&o){let t=narrow_assumptions(a,n);if(s[0]===e)return is_real_ast(s[1],t);if(s[1]===e)return is_real_ast(s[0],t)}if("and"!==i&&"or"!==i)return;if(o)return;return s.length>2&&(r=unflattenRight(r),s=r.slice(1)),simple_assumption_combination(i,is_real_ast(e,s[0],n),is_real_ast(e,s[1],n))}if(Array.isArray(e)){let r;r=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let a=e[0],i=e.slice(1);if("-"===a)return is_real_ast(i[0],r,n);if("*"===a||"+"===a){if(i.length>2&&(i=(e=unflattenRight(e)).slice(1)),"*"===a&&(!1===is_nonzero_ast(i[0],r,n)||!1===is_nonzero_ast(i[1],r,n)))return!0;let t=is_real_ast(i[0],r,n),s=is_real_ast(i[1],r,n);return!(!t||!s)||!(t&&!1===s||s&&!1===t)&&void 0}if("^"===a){let e=is_nonzero_ast(i[0],r,n),t=is_positive_ast(i[1],r,!0,n);if(e){if(!1===is_nonzero_ast(i[1],r,n))return i[0]!==1/0&&i[0]!==-1/0}else{if(Number.isNaN(i[0]))return!1;if(!t)return;if(!1===e)return!0}let a=is_real_ast(i[0],r,n),s=is_real_ast(i[1],r,n);if(!a||!s)return;return is_positive_ast(i[0],r,!1,n)?!!is_positive_ast(i[0],r,!0,n)||!!t||void 0:!!is_integer_ast(i[1],r,n)||void 0}if("/"===a){if(!is_nonzero_ast(i[1],r,n))return;if(!1===is_nonzero_ast(i[0],r,n))return!0;if(!is_real_ast(i[0],r,n)||!is_real_ast(i[1],r,n))return;return!0}if("apply"===a)return!!(functions.C.R&&functions.C.R.includes(i[0])&&is_complex_ast(i[1],r,n))||!!(functions.R.R&&functions.R.R.includes(i[0])&&is_real_ast(i[1],r,n))||!!(functions.nonzeroC.R&&functions.nonzeroC.R.includes(i[0])&&is_nonzero_ast(i[1],r,n)&&is_complex_ast(i[1],r,n))||!!(functions.nonneg.R&&functions.nonneg.R.includes(i[0])&&is_positive_ast(i[1],r,!1,n))||!!(functions.pos.R&&functions.pos.R.includes(i[0])&&is_positive_ast(i[1],r,!0,n))||void 0;if("prime"===a)return;return!1}return!1}function is_complex_ast(e,t,n){if("object"!=typeof t&&(t=[]),void 0===n&&(n=t),"number"==typeof e)return Number.isFinite(e);var r=evaluate_to_constant(e,!1);if(null!==r)return"number"==typeof r?Number.isFinite(r):!(void 0===r.re||!Number.isFinite(r.re)||void 0===r.im||!Number.isFinite(r.im));if("string"==typeof e){let r;if(r=Array.isArray(t)?t:t.get_assumptions(e),!Array.isArray(r))return;let a=r,i=r[0],s=r.slice(1),o=!1;for(;"not"===i;){if(o=!o,r=s[0],!Array.isArray(r))return;i=r[0],s=r.slice(1)}if("in"===i&&s[0]===e&&"C"===s[1])return negate_adjust(!0,o);if("notin"===i&&s[0]===e&&"C"===s[1])return negate_adjust(!1,o);if(!1===o){if("in"===i){if(s[0]===e&&"Z"===s[1])return!0;if(s[0]===e&&"R"===s[1])return!0}}else if("notin"===i){if(s[0]===e&&"Z"===s[1])return!0;if(s[0]===e&&"R"===s[1])return!0}if("<"===i||"le"===i){let t=variables(r),n=functions$2(r);if(-1!==t.indexOf(e)&&0===n.length)return!0}if("="===i&&!o||"ne"===i&&o){let t=narrow_assumptions(a,n);if(s[0]===e)return is_complex_ast(s[1],t);if(s[1]===e)return is_complex_ast(s[0],t)}if("and"!==i&&"or"!==i)return;if(o)return;return s.length>2&&(r=unflattenRight(r),s=r.slice(1)),simple_assumption_combination(i,is_complex_ast(e,s[0],n),is_complex_ast(e,s[1],n))}if(Array.isArray(e)){let r;r=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let a=e[0],i=e.slice(1);if("-"===a)return is_complex_ast(i[0],r,n);if("*"===a||"+"===a)return"*"===a&&!i.every((e=>!1!==is_nonzero_ast(e,r,n)))||(!!i.every((e=>is_complex_ast(e,r,n)))||void 0);if("^"===a){let e=is_nonzero_ast(i[0],r,n),t=is_positive_ast(i[1],r,!0,n);if(e){if(!1===is_nonzero_ast(i[1],r,n))return i[0]!==1/0&&i[0]!==-1/0}else{if(Number.isNaN(i[0]))return!1;if(!t)return;if(!1===e)return!0}let a=is_complex_ast(i[0],r,n),s=is_complex_ast(i[1],r,n);return!(!a||!s)||void 0}if("/"===a){if(!is_nonzero_ast(i[1],r,n))return;if(!1===is_nonzero_ast(i[0],r,n))return!0;if(!is_complex_ast(i[0],r,n)||!is_complex_ast(i[1],r,n))return;return!0}if("apply"===a)return!!(functions.C.C&&functions.C.C.includes(i[0])&&is_complex_ast(i[1],r,n))||!!(functions.R.C&&functions.R.C.includes(i[0])&&is_real_ast(i[1],r,n))||!!(functions.nonzeroC.C&&functions.nonzeroC.C.includes(i[0])&&is_nonzero_ast(i[1],r,n)&&is_complex_ast(i[1],r,n))||!!(functions.nonneg.C&&functions.nonneg.C.includes(i[0])&&is_positive_ast(i[1],r,!1,n))||!!(functions.pos.C&&functions.pos.C.includes(i[0])&&is_positive_ast(i[1],r,!0,n))||void 0;if("prime"===a)return;return!1}return!1}function is_nonzero_ast(e,t,n){if("object"!=typeof t&&(t=[]),void 0===n&&(n=t),"number"==typeof e){if(Number.isFinite(e))return 0!==e;if(Number.isNaN(e))return;return!0}var r=evaluate_to_constant(e,!1);if(null!==r){if("number"==typeof r){if(Number.isFinite(r))return 0!==r;if(Number.isNaN(r))return;return!0}return void 0!==r.re&&void 0!==r.im&&(0!==r.re||0!==r.im)||void 0}if("string"==typeof e){let r;if(r=Array.isArray(t)?t:t.get_assumptions(e),!Array.isArray(r))return;let a=r,i=r[0],s=r.slice(1),o=!1;for(;"not"===i;){if(o=!o,r=s[0],!Array.isArray(r))return;i=r[0],s=r.slice(1)}let l=narrow_assumptions(a,n);if("="===i&&!o||"ne"===i&&o){if(s[0]===e)return is_nonzero_ast(s[1],l);if(s[1]===e)return is_nonzero_ast(s[0],l)}if("ne"===i&&!o||"="===i&&o){if(s[0]===e&&!1===is_nonzero_ast(s[1],l))return!0;if(s[1]===e&&!1===is_nonzero_ast(s[0],l))return!0}if("<"===i)if(o){if(s[0]===e&&is_positive_ast(s[1],l,!0))return!0;if(s[1]===e&&is_negative_ast(s[0],l,!0))return!0}else{if(s[0]===e&&is_negative_ast(s[1],l,!1))return!0;if(s[1]===e&&is_positive_ast(s[0],l,!1))return!0}if("le"===i)if(o){if(s[0]===e&&is_positive_ast(s[1],l,!1))return!0;if(s[1]===e&&is_negative_ast(s[0],l,!1))return!0}else{if(s[0]===e&&is_negative_ast(s[1],l,!0))return!0;if(s[1]===e&&is_positive_ast(s[0],l,!0))return!0}if("and"!==i&&"or"!==i)return;if(o)return;return s.length>2&&(r=unflattenRight(r),s=r.slice(1)),simple_assumption_combination(i,is_nonzero_ast(e,s[0],n),is_nonzero_ast(e,s[1],n))}if(Array.isArray(e)){let r;r=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let a=e[0],i=e.slice(1);if("-"===a)return is_nonzero_ast(i[0],r,n);if("+"===a){if(i.length>2&&(i=(e=unflattenRight(e)).slice(1)),equal(i[0],simplify(["-",i[1]],n)))return!1;let t=is_nonzero_ast(i[0],r,n),a=is_nonzero_ast(i[1],r,n);if(!1===t)return a;if(!1===a)return t;let s=is_real_ast(i[0],r,n),o=is_real_ast(i[1],r,n);if(!s||!o)return!0===s?!1===o||void 0:!0===o&&!1===s||void 0;let l=is_positive_ast(i[0],r,!1,n),u=is_positive_ast(i[1],r,!1,n),c=is_positive_ast(i[0],r,!0,n),p=is_positive_ast(i[1],r,!0,n);return!!(l&&p||c&&u)||!1===l&&!1===p||!1===c&&!1===u||void 0}if("*"===a){let e=!0;for(let t=0;t0:e>=0);var a=is_real_ast(e,t,r);if(!a)return a;var i=evaluate_to_constant(e,!1);if(null!==i)return"number"==typeof i&&!!Number.isFinite(i)&&(n?i>0:i>=0);if("string"==typeof e){let a;if(a=Array.isArray(t)?t:t.get_assumptions(e),!Array.isArray(a))return;let i=a,s=a[0],o=a.slice(1),l=!1;for(;"not"===s;){if(l=!l,a=o[0],!Array.isArray(a))return;s=a[0],o=a.slice(1)}let u=narrow_assumptions(i,r);if("="===s&&!l||"ne"===s&&l){if(o[0]===e)return is_positive_ast(o[1],u,n);if(o[1]===e)return is_positive_ast(o[0],u,n)}if("<"===s)if(l){if(o[0]===e&&is_positive_ast(o[1],u,n))return!0;if(o[1]===e&&is_negative_ast(o[0],u,!n))return!1}else{if(o[0]===e&&is_negative_ast(o[1],u,!1))return!1;if(o[1]===e&&is_positive_ast(o[0],u,!1))return!0}if("le"===s)if(l){if(o[0]===e&&is_positive_ast(o[1],u,!1))return!0;if(o[1]===e&&is_negative_ast(o[0],u,!1))return!1}else{if(o[0]===e&&is_negative_ast(o[1],u,!n))return!1;if(o[1]===e&&is_positive_ast(o[0],u,n))return!0}if("and"!==s&&"or"!==s)return;if(l)return;return o.length>2&&(a=unflattenRight(a),o=a.slice(1)),simple_assumption_combination(s,is_positive_ast(e,o[0],n,r),is_positive_ast(e,o[1],n,r))}if(Array.isArray(e)){let a;a=Array.isArray(t)?t:t.get_assumptions([variables(e)]);let i=e[0],s=e.slice(1);if("-"===i)return is_negative_ast(s[0],a,n,r);if("+"===i){s.length>2&&(s=(e=unflattenRight(e)).slice(1));let t=is_positive_ast(s[0],a,!1,r),i=is_positive_ast(s[1],a,!1,r),o=is_positive_ast(s[0],a,!0,r),l=is_positive_ast(s[1],a,!0,r);if(n){if(t&&l||o&&i)return!0}else if(t&&i)return!0;if(n){if(!1===o&&!1===l)return!1}else if(!1===t&&!1===l||!1===o&&!1===i)return!1;return}if("*"===i){if(!s.every((e=>!1!==is_nonzero_ast(e,a,r))))return!n;s.length>2&&(s=(e=unflattenRight(e)).slice(1));let t=is_real_ast(s[0],a,r),i=is_real_ast(s[1],a,r);if(void 0===t||void 0===i)return;if(!1===t)return!1===i&&void 0;if(!1===i)return!1;let o=is_positive_ast(s[0],a,!1,r),l=is_positive_ast(s[1],a,!1,r),u=is_positive_ast(s[0],a,!0,r),c=is_positive_ast(s[1],a,!0,r);if(n){if(u&&c||!1===o&&!1===l)return!0;if(!1===u&&l||o&&!1===c)return!1}else{if(o&&l||!1===u&&!1===c)return!0;if(u&&!1===l||!1===o&&c)return!1}return}if("/"===i){if(!is_nonzero_ast(s[1],a,r))return;if(!1===is_nonzero_ast(s[0],a,r))return!n;let e=is_positive_ast(s[1],a,!0,r);if(void 0===e)return;let t=e?n:!n,i=is_positive_ast(s[0],a,t,r);if(void 0===i)return;return!0===i?!0===e:!0!==e}if("^"===i){let e=is_nonzero_ast(s[0],a,r);if(e){if(!1===is_nonzero_ast(s[1],a,r)){if(s[0]===1/0||s[0]===-1/0)return;return!0}}else{if(!is_positive_ast(s[1],a,!0,r))return;if(!1===e)return!n;if(n)return}if(!0!==is_real_ast(s[0],a,r))return;return is_positive_ast(s[0],a,n,r)?!!is_real_ast(s[1],a,r)||void 0:!!is_integer_ast(simplify(["/",s[1],2],r),a,r)||void 0}if("apply"===i&&!n)return!!(functions.C.nonneg&&functions.C.nonneg.includes(s[0])&&is_complex_ast(s[1],a,r))||!!(functions.R.nonneg&&functions.R.nonneg.includes(s[0])&&is_real_ast(s[1],a,r))||!!(functions.nonzeroC.nonneg&&functions.nonzeroC.nonneg.includes(s[0])&&is_nonzero_ast(s[1],a,r)&&is_complex_ast(s[1],a,r))||!!(functions.nonneg.nonneg&&functions.nonneg.nonneg.includes(s[0])&&is_positive_ast(s[1],a,!1,r))||!!(functions.pos.nonneg&&functions.pos.nonneg.includes(s[0])&&is_positive_ast(s[1],a,!0,r))||void 0;if("apply"===i&&n)return!!(functions.C.pos&&functions.C.pos.includes(s[0])&&is_complex_ast(s[1],a,r))||!!(functions.R.pos&&functions.R.pos.includes(s[0])&&is_real_ast(s[1],a,r))||!!(functions.nonzeroC.pos&&functions.nonzeroC.pos.includes(s[0])&&is_nonzero_ast(s[1],a,r)&&is_complex_ast(s[1],a,r))||!!(functions.nonneg.pos&&functions.nonneg.pos.includes(s[0])&&is_positive_ast(s[1],a,!1,r))||!!(functions.pos.pos&&functions.pos.pos.includes(s[0])&&is_positive_ast(s[1],a,!0,r))||void 0;if("prime"===i)return;return!1}return!1}function is_negative_ast(e,t,n,r){void 0===n&&(n=!0);var a=is_real_ast(e,t,r);if(!0===a){let a=is_positive_ast(e,t,!n,r);return!1===a||!0!==a&&void 0}return a}function tuples_to_vectors(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if("tuple"===n)return["vector"].concat(r.map((function(e,t){return tuples_to_vectors(e)})));if("apply"===n){if("tuple"===r[1][0]){let e=tuples_to_vectors(r[0]),t=r[1].slice(1);return["apply",e,["tuple"].concat(t.map((function(e,t){return tuples_to_vectors(e)})))]}}else if("gts"===n||"lts"===n||"interval"===n){let e=r[0],t=r[1];if("tuple"!==e[0]||"tuple"!==t[0])throw new Error("Badly formed ast");return[n,["tuple"].concat(e.slice(1).map((function(e,t){return tuples_to_vectors(e)}))),t]}return[n].concat(r.map((function(e,t){return tuples_to_vectors(e)})))}function to_intervals(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if("tuple"===n&&2===r.length){let e=["tuple"].concat(r.map((function(e,t){return to_intervals(e)})));return e=["interval",e,["tuple",!1,!1]],e}if("array"===n&&2===r.length){let e=["tuple"].concat(r.map((function(e,t){return to_intervals(e)})));return e=["interval",e,["tuple",!0,!0]],e}if("apply"===n){if("tuple"===r[1][0]){let e=to_intervals(r[0]),t=r[1].slice(1);return["apply",e,["tuple"].concat(t.map((function(e,t){return to_intervals(e)})))]}}else if("gts"===n||"lts"===n||"interval"===n){let e=r[0],t=r[1];if("tuple"!==e[0]||"tuple"!==t[0])throw new Error("Badly formed ast");return[n,["tuple"].concat(e.slice(1).map((function(e,t){return to_intervals(e)}))),t]}return[n].concat(r.map((function(e,t){return to_intervals(e)})))}function altvectors_to_vectors(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);return"altvector"===n?["vector"].concat(r.map((function(e,t){return altvectors_to_vectors(e)}))):[n].concat(r.map((function(e,t){return altvectors_to_vectors(e)})))}function ParseError(e,t){this.name="ParseError",this.message=e||"Error parsing input",this.stack=(new Error).stack,this.location=t}functions.C.nonneg=["abs"],functions.C.nonzero=["exp"],functions.C.R=["abs","arg"],functions.C.C=["abs","arg","exp","sign","cos","cosh","sin","sinh","erf","sqrt","log","ln","log10"],functions.R.pos=["exp"],functions.R.nonneg=["abs","exp","arg"],functions.R.R=["abs","arg","exp","sign","cos","cosh","sin","sinh","erf"],functions.R.Z=["sign"],functions.nonzeroC.pos=["abs"],functions.nonneg.nonneg=["abs","exp","arg","sqrt","erf"],functions.nonzeroC.nonzero=["abs"],functions.nonneg.R=[...new Set(functions.R.R.concat(functions.nonneg.nonneg))],functions.pos.pos=["abs","exp","sqrt","erf"],functions.pos.nonneg=functions.pos.pos,functions.pos.nonzero=["abs","exp","sqrt","erf"],functions.pos.R=functions.nonneg.R.concat(["log","ln","log10"]),ParseError.prototype=Object.create(Error.prototype),ParseError.prototype.constructor=ParseError;class lexer{constructor(e,t="\\s"){this.input="",this.location=0,this.token_rules=[],this.initial_whitespace=new RegExp("^("+t+")+");for(let t of e)this.token_rules.push([new RegExp("^"+t[0])].concat(t.slice(1)))}set_input(e){if("string"!=typeof e)throw new Error("Input must be a string");this.input=e,this.location=0}return_state(){return{input:this.input,location:this.location}}set_state({input:e=null,location:t=0}={}){null!==e&&(this.input=e,this.location=t)}advance({remove_initial_space:e=!0}={}){let t=this.initial_whitespace.exec(this.input);if(t){let n=t[0].length;if(this.input=this.input.slice(n),this.location+=n,!e)return{token_type:"SPACE",token_text:t[0],original_text:t[0]}}if(0===this.input.length)return{token_type:"EOF",token_text:"",original_text:""};for(var n of(t=null,this.token_rules))if(t=n[0].exec(this.input),t){let e=t[0].length;this.input=this.input.slice(e),this.location+=e;break}return null===t?{token_type:"INVALID",token_text:this.input[0],original_text:this.input[0]}:n.length>2?{token_type:n[1],token_text:n[2],original_text:t[0]}:{token_type:n[1],token_text:t[0],original_text:t[0]}}unput(e){if("string"!=typeof e)throw new Error("Input must be a string");this.location-=e.length,this.input=e+this.input}}var is_associative={"+":!0,"*":!0,and:!0,or:!0,union:!0,intersect:!0};function flatten(e){if(!Array.isArray(e))return e;var t=e[0],n=e.slice(1);if(n=n.map((function(e,t){return flatten(e)})),is_associative[t]){for(var r=[],a=0;a2?r=r.concat(n[a].slice(1)):r.push(n[a]);n=r}return[t].concat(n)}const sci_notat_exp_regex$1="(E[+\\-]?[0-9]+\\s*($|(?=\\,|\\||\\)|\\}|\\])))?",number_rules_sci$1=[["[0-9]+(\\.[0-9]*)?"+sci_notat_exp_regex$1,"NUMBER"],["\\.[0-9]+"+sci_notat_exp_regex$1,"NUMBER"]],number_rules_non_sci$1=[["[0-9]+(\\.[0-9]*)?","NUMBER"],["\\.[0-9]+","NUMBER"]],base_text_rules=[["\\*\\*","^"],["\\*","*"],["\\xB7","*"],["·","*"],["•","*"],["⋅","*"],["×","*"],["/","/"],["-","-"],["֊","-"],["־","-"],["᠆","-"],["‐","-"],["‑","-"],["‒","-"],["–","-"],["—","-"],["―","-"],["⁻","-"],["₋","-"],["−","-"],["⸺","-"],["⸻","-"],["﹘","-"],["﹣","-"],["-","-"],["\\+","+"],["\\^","^"],["‸","^"],["ʌ","^"],["\\|","|"],["\\(","("],["\\)",")"],["\\[","["],["\\]","]"],["\\{","{"],["\\}","}"],["⟨","LANGLE"],["⟩","RANGLE"],["〈","LANGLE"],["〉","RANGLE"],[",",","],[":",":"],["α","VARMULTICHAR","alpha"],["β","VARMULTICHAR","beta"],["ϐ","VARMULTICHAR","beta"],["Γ","VARMULTICHAR","Gamma"],["γ","VARMULTICHAR","gamma"],["Δ","VARMULTICHAR","Delta"],["δ","VARMULTICHAR","delta"],["ε","VARMULTICHAR","epsilon"],["ϵ","VARMULTICHAR","epsilon"],["ζ","VARMULTICHAR","zeta"],["η","VARMULTICHAR","eta"],["Θ","VARMULTICHAR","Theta"],["ϴ","VARMULTICHAR","Theta"],["θ","VARMULTICHAR","theta"],["ᶿ","VARMULTICHAR","theta"],["ϑ","VARMULTICHAR","theta"],["ι","VARMULTICHAR","iota"],["κ","VARMULTICHAR","kappa"],["Λ","VARMULTICHAR","Lambda"],["λ","VARMULTICHAR","lambda"],["μ","VARMULTICHAR","mu"],["µ","VARMULTICHAR","mu"],["ν","VARMULTICHAR","nu"],["Ξ","VARMULTICHAR","Xi"],["ξ","VARMULTICHAR","xi"],["Π","VARMULTICHAR","Pi"],["π","VARMULTICHAR","pi"],["ϖ","VARMULTICHAR","pi"],["ρ","VARMULTICHAR","rho"],["ϱ","VARMULTICHAR","rho"],["Σ","VARMULTICHAR","Sigma"],["σ","VARMULTICHAR","sigma"],["ς","VARMULTICHAR","sigma"],["τ","VARMULTICHAR","tau"],["Υ","VARMULTICHAR","Upsilon"],["υ","VARMULTICHAR","upsilon"],["Φ","VARMULTICHAR","Phi"],["φ","VARMULTICHAR","phi"],["ϕ","VARMULTICHAR","phi"],["Ψ","VARMULTICHAR","Psi"],["ψ","VARMULTICHAR","psi"],["Ω","VARMULTICHAR","Omega"],["ω","VARMULTICHAR","omega"],["oo(?![a-zA-Z0-9])","INFINITY"],["OO(?![a-zA-Z0-9])","INFINITY"],["infty(?![a-zA-Z0-9])","INFINITY"],["infinity(?![a-zA-Z0-9])","INFINITY"],["Infinity(?![a-zA-Z0-9])","INFINITY"],["∞","INFINITY"],["ℯ","VAR","e"],["♠","VARMULTICHAR","spade"],["♡","VARMULTICHAR","heart"],["♢","VARMULTICHAR","diamond"],["♣","VARMULTICHAR","club"],["★","VARMULTICHAR","bigstar"],["◯","VARMULTICHAR","bigcirc"],["◊","VARMULTICHAR","lozenge"],["△","VARMULTICHAR","bigtriangleup"],["▽","VARMULTICHAR","bigtriangledown"],["⧫","VARMULTICHAR","blacklozenge"],["■","VARMULTICHAR","blacksquare"],["▲","VARMULTICHAR","blacktriangle"],["▼","VARMULTICHAR","blacktriangledown"],["◀","VARMULTICHAR","blacktriangleleft"],["▶","VARMULTICHAR","blacktriangleright"],["□","VARMULTICHAR","Box"],["∘","VARMULTICHAR","circ"],["⋆","VARMULTICHAR","star"],["and(?![a-zA-Z0-9])","AND"],["\\&\\&?","AND"],["∧","AND"],["or(?![a-zA-Z0-9])","OR"],["∨","OR"],["not(?![a-zA-Z0-9])","NOT"],["¬","NOT"],["=","="],["᐀","="],["゠","="],["!=","NE"],["≠","NE"],["<=","LE"],["≤","LE"],[">=","GE"],["≥","GE"],["<","<"],[">",">"],["elementof(?![a-zA-Z0-9])","IN"],["∈","IN"],["notelementof(?![a-zA-Z0-9])","NOTIN"],["∉","NOTIN"],["containselement(?![a-zA-Z0-9])","NI"],["∋","NI"],["notcontainselement(?![a-zA-Z0-9])","NOTNI"],["∌","NOTNI"],["subset(?![a-zA-Z0-9])","SUBSET"],["⊂","SUBSET"],["subseteq(?![a-zA-Z0-9])","SUBSETEQ"],["⊆","SUBSETEQ"],["notsubset(?![a-zA-Z0-9])","NOTSUBSET"],["⊄","NOTSUBSET"],["notsubseteq(?![a-zA-Z0-9])","NOTSUBSETEQ"],["⊈","NOTSUBSETEQ"],["superset(?![a-zA-Z0-9])","SUPERSET"],["⊃","SUPERSET"],["superseteq(?![a-zA-Z0-9])","SUPERSETEQ"],["⊇","SUPERSETEQ"],["notsuperset(?![a-zA-Z0-9])","NOTSUPERSET"],["⊅","NOTSUPERSET"],["notsuperseteq(?![a-zA-Z0-9])","NOTSUPERSETEQ"],["⊉","NOTSUPERSETEQ"],["union(?![a-zA-Z0-9])","UNION"],["∪","UNION"],["intersect(?![a-zA-Z0-9])","INTERSECT"],["∩","INTERSECT"],["perp(?![a-zA-Z0-9])","PERP"],["⟂","PERP"],["parallel(?![a-zA-Z0-9])","PARALLEL"],["∥","PARALLEL"],["angle(?![a-zA-Z0-9])","ANGLE"],["∠","ANGLE"],["int(?![a-zA-Z0-9])","INT"],["∫","INT"],["!","!"],["'","'"],["_","_"],["\\.\\.\\.","LDOTS"],["[a-zA-Z∂][a-zA-Z∂0-9]*","VAR"],["[_$%]","VAR"]],allowSimplifiedFunctionApplicationDefault$1=!0,splitSymbolsDefault=!0,unsplitSymbolsDefault=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","angle","deg"],appliedFunctionSymbolsDefault$1=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","conj","re","im","det","trace","nPr","nCr","floor","ceil","round"],functionSymbolsDefault$1=["f","g"],operatorSymbolsDefault$1=["binom","vec","linesegment"],unitsDefault$1=get_all_units(),parseLeibnizNotationDefault$1=!0;class textToAst$4{constructor({allowSimplifiedFunctionApplication:e=allowSimplifiedFunctionApplicationDefault$1,splitSymbols:t=splitSymbolsDefault,unsplitSymbols:n=unsplitSymbolsDefault,appliedFunctionSymbols:r=appliedFunctionSymbolsDefault$1,functionSymbols:a=functionSymbolsDefault$1,operatorSymbols:i=operatorSymbolsDefault$1,units:s=unitsDefault$1,parseLeibnizNotation:o=parseLeibnizNotationDefault$1,parseScientificNotation:l=!0}={}){this.allowSimplifiedFunctionApplication=e,this.splitSymbols=t,this.unsplitSymbols=n,this.appliedFunctionSymbols=r,this.functionSymbols=a,this.operatorSymbols=i,this.units=s,this.parseLeibnizNotation=o;let u=base_text_rules;u=l?[...number_rules_sci$1,...u]:[...number_rules_non_sci$1,...u],this.lexer=new lexer(u)}advance(e){if(this.token=this.lexer.advance(e),"INVALID"===this.token.token_type)throw new ParseError("Invalid symbol '"+this.token.original_text+"'",this.lexer.location)}return_state(){return{lexer_state:this.lexer.return_state(),token:Object.assign({},this.token)}}set_state(e){this.lexer.set_state(e.lexer_state),this.token=Object.assign({},e.token)}convert(e){this.lexer.set_input(e),this.advance();var t=this.statement_list();if("EOF"!==this.token.token_type)throw new ParseError("Invalid location of '"+this.token.original_text+"'",this.lexer.location);return flatten(t)}statement_list(){for(var e=[this.statement()];","===this.token.token_type;)this.advance(),e.push(this.statement());return e.length>1?["list"].concat(e):e[0]}statement({inside_absolute_value:e=0}={}){if("LDOTS"===this.token.token_type)return this.advance(),["ldots"];var t;try{t=this.return_state();let n=this.statement_a({inside_absolute_value:e});return":"!==this.token.token_type?n:(this.advance(),[":",n,this.statement_a()])}catch(e){try{this.set_state(t);let n=this.statement_a({parse_absolute_value:!1});if("|"!==this.token.token_type)throw e;return this.advance(),["|",n,this.statement_a({parse_absolute_value:!1})]}catch(t){throw e}}}statement_a({inside_absolute_value:e=0,parse_absolute_value:t=!0}={}){for(var n=this.statement_b({inside_absolute_value:e,parse_absolute_value:t});"OR"===this.token.token_type;){let r=this.token.token_type.toLowerCase();this.advance(),n=[r,n,this.statement_b({inside_absolute_value:e,parse_absolute_value:t})]}return n}statement_b(e){for(var t=this.relation(e);"AND"===this.token.token_type;){let n=this.token.token_type.toLowerCase();this.advance(),t=[n,t,this.relation(e)]}return t}relation(e){if("NOT"===this.token.token_type||"!"===this.token.token_type)return this.advance(),["not",this.relation(e)];for(var t=this.expression(e);"="===this.token.token_type||"NE"===this.token.token_type||"<"===this.token.token_type||">"===this.token.token_type||"LE"===this.token.token_type||"GE"===this.token.token_type||"IN"===this.token.token_type||"NOTIN"===this.token.token_type||"NI"===this.token.token_type||"NOTNI"===this.token.token_type||"SUBSET"===this.token.token_type||"NOTSUBSET"===this.token.token_type||"SUBSETEQ"===this.token.token_type||"NOTSUBSETEQ"===this.token.token_type||"SUPERSET"===this.token.token_type||"NOTSUPERSET"===this.token.token_type||"SUPERSETEQ"===this.token.token_type||"NOTSUPERSETEQ"===this.token.token_type;){let n=this.token.token_type.toLowerCase(),r=0;"<"===this.token.token_type||"LE"===this.token.token_type?r=-1:">"!==this.token.token_type&&"GE"!==this.token.token_type||(r=1),this.advance();let a=this.expression(e);if(-1===r)if("<"===this.token.token_type||"LE"===this.token.token_type){let r=["tuple"];"<"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;"<"===this.token.token_type||"LE"===this.token.token_type;)"<"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["lts",i,r]}else t=[n,t,a];else if(1===r)if(">"===this.token.token_type||"GE"===this.token.token_type){let r=["tuple"];">"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;">"===this.token.token_type||"GE"===this.token.token_type;)">"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["gts",i,r]}else t=[n,t,a];else if("="===n)for(t=["=",t,a];"="===this.token.token_type;)this.advance(),t.push(this.expression(e));else t=[n,t,a]}return t}expression(e){let t=!1;"+"===this.token.token_type&&(t=!0,this.advance());let n=!1;"-"===this.token.token_type&&(n=!0,this.advance());var r=this.term(e);if(n||t){if(!1===r)return(t?"+":"")+(n?"-":"");if("string"==typeof r&&[...r].every((e=>["+","-"].includes(e))))return(t?"+":"")+(n?"-":"")+r}for(!1===r&&(r="_"),n&&(r=r>0?-r:["-",r]),t&&(r=["+",r]);["+","-","UNION","INTERSECT","PERP","PARALLEL"].includes(this.token.token_type);){let t=this.token.token_type.toLowerCase(),n=!1,a=!1;"-"===this.token.token_type?(t="+",n=!0,this.advance()):(this.advance(),"+"===t&&"-"===this.token.token_type&&(n=!0,a=!0,this.advance()));let i=this.term(e);if("+"===t){if(!1===i&&("number"==typeof r||"string"==typeof r))return a?r+"+-":n?r+"-":r+"+";if("string"==typeof i&&[...i].every((e=>["+","-"].includes(e)))&&("number"==typeof r||"string"==typeof r))return a?r+"+-"+i:n?r+"-"+i:r+"+"+i}!1===i&&(i="_"),n&&(i=i>0?-i:["-",i]),r=[t,r,i]}return r}term(e){var t=this.factor(e),n=!1;do{if(n=!1,"*"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["*",t,r],n=!0}else if("/"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["/",t,r],n=!0}else{let r=Object.assign({},e);r.allow_absolute_value_closing=!0;let a=this.nonMinusFactor(r);!1!==a&&(!1===t&&(t="_"),t=["*",t,a],n=!0)}}while(n);return this.convert_units_in_term(flatten(t))}convert_units_in_term(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);if("*"===t){let t=n.length;for(let[e,r]of n.entries()){let a=this.units[r];if(a){if(a.prefix&&e0){let i,s=r;return a.substitute&&(s=a.substitute),i=1===e?["unit",n[0],s]:["unit",["*",...n.slice(0,e)],s],e===t-1?i:this.convert_units_in_term(["*",i,...n.slice(e+1)])}}}return e}return"/"===t?["/",this.convert_units_in_term(n[0]),this.convert_units_in_term(n[1])]:e}factor(e){if("+"===this.token.token_text){this.advance();let t=this.factor(e);return!1===t?"+":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"+"+t:["+",t]}if("-"===this.token.token_type){this.advance();let t=this.factor(e);return t>0?-t:!1===t?"-":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"-"+t:["-",t]}let t=this.nonMinusFactor(e);return!1===t&&"PERP"===this.token.token_type&&(t="perp",this.advance()),t}nonMinusFactor(e){for(var t=this.baseFactor(e);"^"===this.token.token_type||"!"===this.token.token_type||"'"===this.token.token_type;)!1===t&&(t="_"),"^"===this.token.token_type?(this.advance(),t=["^",t,this.get_subsuperscript(e)]):"!"===this.token.token_type?(t=["apply","factorial",t],this.advance()):(t=["prime",t],this.advance());return t}get_subsuperscript({parse_absolute_value:e}){if(["+","-","PERP"].includes(this.token.token_type)){let e=this.token.token_type.toLowerCase();return this.advance(),e}{let t=this.baseFactor({parse_absolute_value:e,in_subsuperscript_with_no_delimiters:!0});return!1===t&&(t="_"),t}}baseFactor({inside_absolute_value:e=0,parse_absolute_value:t=!0,allow_absolute_value_closing:n=!1,in_subsuperscript_with_no_delimiters:r=!1}={}){var a=!1;if("NUMBER"===this.token.token_type)a=parseFloat(this.token.token_text),this.advance();else if("INFINITY"===this.token.token_type)a=1/0,this.advance();else if("VAR"===this.token.token_type||"VARMULTICHAR"===this.token.token_type){if(a=this.token.token_text,this.appliedFunctionSymbols.includes(a)||this.functionSymbols.includes(a)){let e=!1;if(this.appliedFunctionSymbols.includes(a)&&(e=!0),this.advance(),"_"===this.token.token_type){this.advance();let e=this.get_subsuperscript({parse_absolute_value:t});a="log"===a&&10===e?"log10":["_",a,e]}if(r)e&&(a=["apply",a,"_"]);else{for(;"'"===this.token.token_type;)a=["prime",a],this.advance();for(;"^"===this.token.token_type;)this.advance(),a=["^",a,this.get_subsuperscript({parse_absolute_value:t})];if("("===this.token.token_type){this.advance();let e=this.statement_list();if(")"!==this.token.token_type)throw new ParseError("Expecting )",this.lexer.location);this.advance(),"list"===e[0]&&(e[0]="tuple"),a=["apply",a,e]}else if(e){if(!this.allowSimplifiedFunctionApplication)throw new ParseError("Expecting ( after function",this.lexer.location);let e=this.factor({parse_absolute_value:t});!1===e&&(e="_"),a=["apply",a,e]}}return a}if(this.operatorSymbols.includes(a))if(this.advance(),"("===this.token.token_type){this.advance();let e=this.statement_list();if(")"!==this.token.token_type)throw new ParseError("Expecting )",this.lexer.location);this.advance(),a="list"===e[0]?[a,...e.slice(1)]:[a,e]}else{let e=this.factor({parse_absolute_value:t});!1===e&&(e="_"),a=[a,e]}else{if(this.parseLeibnizNotation){let e=this.return_state(),t=this.leibniz_notation();if(t)return t;this.set_state(e)}let r=this.splitSymbols;if(r&&("VARMULTICHAR"===this.token.token_type||this.unsplitSymbols.includes(a)||1===a.length||a.match(/[\d]/g))&&(r=!1),r){for(let e=a.length-1;e>=0;e--)this.lexer.unput(" "),this.lexer.unput(a[e]);return this.advance(),this.baseFactor({inside_absolute_value:e,parse_absolute_value:t,allow_absolute_value_closing:n})}this.advance()}}else if("("===this.token.token_type||"["===this.token.token_type||"{"===this.token.token_type||"LANGLE"===this.token.token_type){let e,t,n=this.token.token_type;"("===this.token.token_type?(e=")",t="]"):"["===this.token.token_type?(e="]",t=")"):"{"===this.token.token_type?(e="}",t=null):(e="RANGLE",t=null),this.advance();let r=1;if("list"===(a=this.statement_list())[0]&&(r=a.length-1),this.token.token_type!==e){if(2!==r||null===t)throw new ParseError("Expecting "+e,this.lexer.location);if(this.token.token_type!==t)throw new ParseError("Expecting ) or ]",this.lexer.location);let i;a[0]="tuple",i="("===n?["tuple",!1,!0]:["tuple",!0,!1],(a=["interval",a]).push(i)}else r>=2?a[0]="("===n?"tuple":"["===n?"array":"{"===n?"set":"altvector":"{"===n&&("|"===a[0]||a[0],a=["set",a]);this.advance()}else if("|"!==this.token.token_type||!t||0!==e&&n){if("ANGLE"===this.token.token_type)if(this.advance(),"("===this.token.token_type){this.advance();let e=this.statement_list();if(")"!==this.token.token_type)throw new ParseError("Expecting )",this.lexer.location);this.advance(),"list"===e[0]?a=["angle",...e.slice(1)]:"*"===e[0]&&(a=["angle",e])}else{let e=[],n=this.nonMinusFactor({parse_absolute_value:t});for(;!1!==n;)e.push(n),n=this.nonMinusFactor({parse_absolute_value:t});a=0===e.length?"angle":["angle",...e]}else if("INT"===this.token.token_type){this.advance();let e="int";"_"===this.token.token_type&&(this.advance(),e=["_",e,this.get_subsuperscript({parse_absolute_value:t})]),"^"===this.token.token_type&&(this.advance(),e=["^",e,this.get_subsuperscript({parse_absolute_value:t})]);let n=flatten(this.term({parse_absolute_value:t}));if(Array.isArray(n)&&"*"===n[0]){let e=[];for(let t=0;t2&&(this.lexer.unput(this.token.token_text.slice(2)),this.token.token_text=this.token.token_text.slice(0,2));let o=this.token.token_text;if(2===o.length){if(!/[a-zA-Z]/.exec(o[1]))return!1;a.push(o[1])}else{if(this.advance(),("VAR"!==this.token.token_type||this.token.token_text.includes("∂"))&&"VARMULTICHAR"!==this.token.token_type)return!1;a.push(this.token.token_text)}let l=1,u=!1;if(this.advance({remove_initial_space:!1}),"SPACE"===this.token.token_type&&(u=!0,this.advance()),"^"===this.token.token_type){if(this.advance(),"NUMBER"!==this.token.token_type)return!1;if(l=parseFloat(this.token.token_text),!Number.isInteger(l))return!1;u=!1,this.advance({remove_initial_space:!1}),"SPACE"===this.token.token_type&&(u=!0,this.advance())}if(i.push(l),s+=l,s>n)return!1;if(s===n){if(!u&&("VAR"===this.token.token_type||"VARMULTICHAR"===this.token.token_type))return!1;"SPACE"===this.token.token_type&&this.advance();let s="derivative_leibniz";"∂"===t&&(s="partial_"+s),e=[s],1===n?e.push(r):e.push(["tuple",r,n]);let o=[];for(let e=0;et[e+1]));if(t.length!==r||a.length!==r)return subtree;let i=["+",...t.map(((e,t)=>["*",e,a[t]]))];n.push(i)}o.push(n)}return{success:!0,newMatrix:["matrix",["tuple",n,a],o]}}function i(e,t){let n=e[1][1],r=e[1][2],a=e[2],i=["tuple"];for(let e=0;e=0;t--){let r=n[t][0];if("matrix"===r){let r=a(n[t],e);if(!r.success)break;e=r.newMatrix,n.pop()}else{if(["tuple","list","vector","altvector","interval","set","array"].includes(r))break;1!==n[t]&&(e=i(e,n[t])),n.pop()}}for(;r.length>0;){let t=r[0][0];if("matrix"===t){let t=a(e,r[0]);if(!t.success)break;e=t.newMatrix,r.splice(0,1)}else{if(["tuple","list","vector","altvector","interval","set","array"].includes(t))break;1!==r[0]&&(e=i(e,r[0])),r.splice(0,1)}}return n.length>0||r.length>0?["*",...n,e,...r]:e}return e})),(t||n)&&(s=["*",["matrix",["tuple","m","n"],"matrixData"],"b"],o={variables:{n:Number.isInteger,m:Number.isInteger,matrixData:!0,b:!0}},r=transform(r,(function(e){let r=match$2(e,s,o);if(r){let a,i=r.m,s=r.n,o=r.b,l=r.matrixData,u=[];t&&(u.push("vector"),u.push("altvector")),n&&u.push("tuple");let c=[];if(u.includes(o[0]))a=o;else{if(!Array.isArray(o)||"*"!==o[0]||!u.includes(o[1][0]))return e;a=o[1],c=o.slice(2)}let p=a.slice(1);if(p.length!==s)return e;let d=[a[0]];for(let e=0;e["*",e,p[t]]))];d.push(t)}return c.length>0?["*",d,...c]:d}return e}))),r}function perform_vector_scalar_multiplications(e,t=!0){var n=get_tree(e);let r=function(e,t){let n=["*","a",[t,"vectorData"],"b"],r={allow_implicit_identities:["a","b"]};return e=transform(e,(function(e){let a=match$2(e,n,r);if(a){if(1===a.a&&1===a.b)return e;let n=a.vectorData;n=Array.isArray(n)&&n[0]===t?n.slice(1):[n];let r=[],i=[];Array.isArray(a.a)&&"*"===a.a[0]?r.push(...a.a.slice(1)):r.push(a.a),Array.isArray(a.b)&&"*"===a.b[0]?i.push(...a.b.slice(1)):i.push(a.b);for(let e=r.length-1;e>=0;e--){let t=r[e][0];if(["tuple","list","vector","altvector","interval","set","array","matrix"].includes(t))break;1!==r[e]&&(n=n.map((t=>["*",t,r[e]]))),r.pop()}for(;i.length>0;){let e=i[0][0];if(["tuple","list","vector","altvector","interval","set","array","matrix"].includes(e))break;1!==i[0]&&(n=n.map((e=>["*",e,i[0]]))),i.splice(0,1)}let s=[t,...n];return r.length>0||i.length>0?["*",...r,s,...i]:s}return e})),e};return n=r(n,"vector"),n=r(n,"altvector"),t&&(n=r(n,"tuple")),n}function perform_matrix_scalar_multiplications(e){var t=get_tree(e);let n=["*","a",["matrix","size","matrixData"],"b"],r={allow_implicit_identities:["a","b"]};return t=transform(t,(function(e){let t=match$2(e,n,r);if(t){if(1===t.a&&1===t.b)return e;let n=t.matrixData,r=[],a=[];Array.isArray(t.a)&&"*"===t.a[0]?r.push(...t.a.slice(1)):r.push(t.a),Array.isArray(t.b)&&"*"===t.b[0]?a.push(...t.b.slice(1)):a.push(t.b);for(let e=r.length-1;e>=0;e--){let t=r[e][0];if(["tuple","list","vector","altvector","interval","set","array","matrix"].includes(t))break;1!==r[e]&&(n=n.map((t=>"tuple"===t?t:t.map((t=>"tuple"===t?t:["*",t,r[e]]))))),r.pop()}for(;a.length>0;){let e=a[0][0];if(["tuple","list","vector","altvector","interval","set","array","matrix"].includes(e))break;1!==a[0]&&(n=n.map((e=>"tuple"===e?e:e.map((e=>"tuple"===e?e:["*",e,a[0]]))))),a.splice(0,1)}let i=["matrix",t.size,n];return r.length>0||a.length>0?["*",...r,i,...a]:i}return e})),t}function expand_relations(e){var t=get_tree(e);return transform(t,expand_relations_transform)}function expand_relations_transform(e){if(!Array.isArray(e))return e;var t=e[0],n=e.slice(1);if("="===t){if(n.length<=2)return e;let t=["and"];for(let e=0;e":"lts"===t?"le":"ge",a.push([i,e[n],e[n+1]])}let i=["and",a[0],a[1]];for(let e=2;e",r,u]),o[2]?i?p.push([">",r,c]):p.push(["le",r,c]):i?p.push(["ge",r,c]):p.push(["<",r,c]),l=i?["or"].concat(p):["and"].concat(p),l}if("subset"===t||"notsubset"===t||"superset"===t||"notsuperset"===t){let r,a,i=!1;if("notsubset"!==t&&"notsuperset"!==t||(i=!0),"subset"===t||"notsubset"===t?(r=n[0],a=n[1]):(r=n[1],a=n[0]),r=to_intervals(r),a=to_intervals(a),"interval"!==r[0]||"interval"!==a[0])return e;let s=r[1],o=r[2],l=a[1],u=a[2];if("tuple"!==s[0]||"tuple"!==o[0]||"tuple"!==l[0]||"tuple"!==u[0])throw new Error("Badly formed ast");let c,p=s[1],d=s[2],m=l[1],h=l[2],f=[];return o[1]&&!u[1]?i?f.push(["le",p,m]):f.push([">",p,m]):i?f.push(["<",p,m]):f.push(["ge",p,m]),o[2]&&!u[2]?i?f.push(["ge",d,h]):f.push(["<",d,h]):i?f.push([">",d,h]):f.push(["le",d,h]),c=i?["or"].concat(f):["and"].concat(f),c}return e}function substitute(e,t){var n=get_tree(e),r={};for(let e in t)r[e]=get_tree(t[e]);return substitute$1(n,r)}function substitute_component(e,t,n){let r=get_tree(e);if(get_tree(n),"number"==typeof t)t=[t];else if(!Array.isArray(t))throw Error("Invalid substitute_component: "+t);let a=["list","tuple","vector","altvector","array"];return function e(t,r,i){if(0===r.length)return n;if(!Array.isArray(t))throw Error("Invalid substitute_component: expected list, tuple, vector, or array");let s=t[0],o=t.slice(1);if(!a.includes(s))throw Error("Invalid substitute_component: expected list, tuple, vector, or array");let l=r[0];if(l<0||l>o.length-1)throw Error("Invalid substitute_component: component out of range");let u=r.slice(1),c=e(o[l],u);return[s,...o.slice(0,l),c,...o.slice(l+1)]}(r,t)}function get_component(e,t){let n=get_tree(e);if("number"==typeof t)t=[t];else if(!Array.isArray(t))throw Error("Invalid get_component: "+t);let r=["list","tuple","vector","altvector","array"];return function e(t,n){if(0===n.length)return t;if(!Array.isArray(t))throw Error("Invalid get_component: expected list, tuple, vector, or array");let a=t[0],i=t.slice(1);if(!r.includes(a))throw Error("Invalid get_component: expected list, tuple, vector, or array");let s=n[0];if(s<0||s>i.length-1)throw Error("Invalid get_component: component out of range");let o=n.slice(1);return e(i[s],o)}(n,t)}var transformation=Object.freeze({__proto__:null,expand:expand,expand_relations:expand_relations,substitute:substitute,substitute_component:substitute_component,get_component:get_component,perform_vector_scalar_multiplications:perform_vector_scalar_multiplications,perform_matrix_scalar_multiplications:perform_matrix_scalar_multiplications,perform_matrix_multiplications:perform_matrix_multiplications});function clean(e){return flatten$5(get_tree(e))}function evalf(e,t){return parseFloat(math$1.format(e,{notation:"exponential",precision:t}))}function collapse_unary_minus(e){var t=get_tree(e);if(!Array.isArray(t))return t;var n=t[0],r=t.slice(1);if(r=r.map((e=>collapse_unary_minus(e))),"-"===n){if("number"==typeof r[0])return-r[0];if(Array.isArray(r[0])&&"*"===r[0][0]&&"number"==typeof r[0][1])return["*",-r[0][1]].concat(r[0].slice(2));if(Array.isArray(r[0])&&"/"===r[0][0]){if("number"==typeof r[0][1])return["/",-r[0][1],r[0][2]];if(Array.isArray(r[0][1])&&"*"===r[0][1][0]&&"number"==typeof r[0][1][1])return["/",["*",-r[0][1][1]].concat(r[0][1].slice(2)),r[0][2]]}}return[n].concat(r)}function simplify(e,t,n){var r=get_tree(e);return contains_blank(r)?r:(void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),r=evaluate_numbers(r,{assumptions:t,max_digits:n,evaluate_functions:!0}),Array.isArray(r)?r=collect_like_terms_factors(r=perform_vector_matrix_additions_scalar_multiplications(r=simplify_logical(r,t)),t,n):r)}function simplify_logical(e,t){var n=get_tree(e);if(contains_blank(n))return n;void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),n=evaluate_numbers(n,{assumptions:t}),n=unflattenRight(n);var r=[];return r.push([["not",["not","a"]],"a"]),r.push([["not",["and","a","b"]],["or",["not","a"],["not","b"]]]),r.push([["not",["or","a","b"]],["and",["not","a"],["not","b"]]]),r.push([["not",["=","a","b"]],["ne","a","b"]]),r.push([["not",["ne","a","b"]],["=","a","b"]]),r.push([["not",["<","a","b"]],["le","b","a"]]),r.push([["not",["le","a","b"]],["not",["le","a","b"]]]),r.push([["not",["in","a","b"]],["notin","a","b"]]),r.push([["not",["subset","a","b"]],["notsubset","a","b"]]),flatten$5(n=applyAllTransformations(n,r,20))}function perform_vector_matrix_additions_scalar_multiplications(e,t=!0){var n=get_tree(e);n=perform_vector_scalar_multiplications(n=perform_matrix_scalar_multiplications(n),t);let r=["+","a","b"];return n=transform(n,(function(e){let n=match$2(e,r,{allow_permutations:!0});if(n){let r=["vector","altvector"];t&&r.push("tuple");let a={},i={},s=[];if(r.includes(n.a[0])){let e=n.a.length-1;a[e]||(a[e]=[]),a[e].push(n.a)}else if("matrix"===n.a[0]){let e=n.a[1].slice(1).toString();i[e]||(i[e]=[]),i[e].push(n.a)}else s.push(n.a);if(r.includes(n.b[0])){let e=n.b.length-1;a[e]||(a[e]=[]),a[e].push(n.b)}else if("matrix"===n.b[0]){let e=n.b[1].slice(1).toString();i[e]||(i[e]=[]),i[e].push(n.b)}else if("+"===n.b[0])for(let e of n.b.slice(1))if(r.includes(e[0])){let t=e.length-1;a[t]||(a[t]=[]),a[t].push(e)}else if("matrix"===e[0]){let t=e[1].slice(1).toString();i[t]||(i[t]=[]),i[t].push(e)}else s.push(e);else s.push(n.b);if(Object.values(a).every((e=>e.length<2))&&Object.values(i).every((e=>e.length<2)))return e;let o=s;for(let e in a)if(a[e].length<2)o.push(...a[e]);else{let t,n=a[e].some((e=>"vector"===e[0])),r=a[e].some((e=>"tuple"===e[0])),i=a[e].some((e=>"altvector"===e[0]));t=n||r&&i?["vector"]:i?["altvector"]:["tuple"];for(let n=0;ne[n+1]))]);o.push(t)}for(let e in i)if(i[e].length<2)o.push(...i[e]);else{let[t,n]=e.split(",").map(Number),r=["tuple"];for(let a=0;ae[2][a+1][r+1]))]);r.push(t)}let a=["matrix",["tuple",t,n],r];o.push(a)}return 1===o.length?o[0]:["+",...o]}return e})),n}function contains_decimal_number(e){return"string"!=typeof e&&("number"==typeof e?!(!Number.isFinite(e)||Number.isInteger(e)):!!Array.isArray(e)&&e.slice(1).some((e=>contains_decimal_number(e))))}function contains_only_numbers(e,{include_number_symbols:t=!1,evaluate_functions:n=!1}={}){if("string"==typeof e){if(t){if("e"===e&&math$1.define_e)return!0;if("pi"===e&&math$1.define_pi)return!0}return!("i"!==e||!math$1.define_i)}return"number"==typeof e||!!Array.isArray(e)&&(n&&"apply"===e[0]?e.slice(2).every((e=>contains_only_numbers(e,{include_number_symbols:t}))):e.slice(1).every((e=>contains_only_numbers(e,{include_number_symbols:t}))))}function try_evaluate_sum_of_numbers(e,t,n){if("number"==typeof e){if(0===e)return t;if("number"==typeof t)return e+t;if(Array.isArray(t)&&"+"===t[0]&&"number"==typeof t[1])return["+",e+t[1],t[2]];if(!n&&Array.isArray(t)&&"+"===t[0]&&"number"==typeof t[2])return["+",e+t[2],t[1]]}return"number"==typeof t&&0===t?e:null}function try_evaluate_negate_number(e){if("number"==typeof e)return-e;if(Array.isArray(e)&&"*"===e[0]&&"number"==typeof e[1])return["*",-e[1]].concat(e.slice(2));if(Array.isArray(e)&&"/"===e[0]){if("number"==typeof e[1])return["/",-e[1],e[2]];if(Array.isArray(e[1])&&"*"===e[1][0]&&"number"==typeof e[1][1])return["/",["*",-e[1][1]].concat(e[1].slice(2)),e[2]]}return null}function try_evaluate_product_of_numbers(e,t){if("number"==typeof e){if(isNaN(e))return NaN;if("number"==typeof t)return e*t;if(!isFinite(e))return e===1/0&&is_negative_ast(t)||e===-1/0&&is_positive_ast(t)?-1/0:!1===is_nonzero_ast(t)?NaN:1/0;if(0===e)return 0;if(1===e)return t;if(-1===e)return["-",t];if(Array.isArray(t)&&"*"===t[0]&&"number"==typeof t[1])return e*=t[1],t=t[2],1===e?t:-1===e?["-",t]:["*",e,t]}if("number"==typeof t){if(isNaN(t))return NaN;if(!isFinite(t))return t===1/0&&is_negative_ast(e)||t===-1/0&&is_positive_ast(e)?-1/0:!1===is_nonzero_ast(e)?NaN:1/0;if(0===t)return 0;if(1===t)return e;if(-1===t)return["-",e];if(Array.isArray(e)&&"*"===e[0]&&"number"==typeof e[1])return t*=e[1],e=e[2],1===t?e:-1===t?["-",e]:["*",e,t]}if(math$1.define_i&&"i"===e){if("i"===t)return-1;if(Array.isArray(t)&&"*"===t[0]&&"i"===t[1])return["-",t[2]]}else if(math$1.define_i&&"i"===t&&Array.isArray(e)&&"*"===e[0]&&"i"===e[1])return["-",e[2]];return null}function try_evaluate_quotient_of_numbers(e,t,n,r){if("number"==typeof e){if(0===e){let e=is_nonzero_ast(t,n);if(e)return 0;if(!1===e)return NaN}if("number"==typeof t){let n=e/t;if(r===1/0||math$1.round(n,r)===n)return n;if(t<0)return["/",-e,-t]}if(Array.isArray(t)&&"*"===t[0]&&"number"==typeof t[1]){let n=e/t[1];if(r===1/0||math$1.round(n,r)===n)return["/",n,t[2]]}}else if("number"==typeof t){if(Array.isArray(e)&&"*"===e[0]&&"number"==typeof e[1]){let n=e[1]/t;if(r===1/0||math$1.round(n,r)===n)return 1===n?e[2]:["*",n,e[2]];if(t<0)return["/",["*",-e[1],e[2]],-t]}let n=1/t;if(r===1/0||math$1.round(n,r)===n)return["*",n,e];if(t<0)return Array.isArray(e)&&"-"===e[0]?["/",e[1],-t]:["-",["/",e,-t]]}return null}function evaluate_numbers_sub(e,t,n,r,a,i){if(void 0===e)return e;if("number"==typeof e)return i>0&&math$1.abs(e)0&&math$1.abs(t)evaluate_numbers_sub(e,t,n,r,a,i)));if("+"===o){let e=l[0],t=l[1];if(void 0===t)return e;let n=try_evaluate_sum_of_numbers(e,t,r);if(null!==n)return n;if("unit"===e[0]&&"unit"===t[0]){let n=get_unit_of_tree(e),a=get_unit_of_tree(t);if(n&&n===a){let a=try_evaluate_sum_of_numbers(remove_units(e,!1),remove_units(t,!1),r);if(null!==a)return add_unit(a,n)}}return[o].concat(l)}if("-"===o){let e=try_evaluate_negate_number(l[0]);if(null!==e)return e;if("unit"===l[0][0]){let e=get_unit_of_tree(l[0]);if(e){let t=try_evaluate_negate_number(remove_units(l[0],!1));if(null!==t)return add_unit(t,e)}}return[o].concat(l)}if("*"===o){let e=l[0],t=l[1];if(void 0===t)return e;let n=try_evaluate_product_of_numbers(e,t);if(null!==n)return n;if("unit"===e[0]&&"unit"!==t[0]){let n=get_unit_of_tree(e);if(n){let r=try_evaluate_product_of_numbers(remove_units(e,!1),t);if(null!==r)return add_unit(r,n)}}if("unit"!==e[0]&&"unit"===t[0]){let n=get_unit_of_tree(t);if(n){let r=try_evaluate_product_of_numbers(e,remove_units(t,!1));if(null!==r)return add_unit(r,n)}}return[o].concat(l)}if("/"===o){let e=l[0],r=l[1],a=try_evaluate_quotient_of_numbers(e,r,t,n);if(null!==a)return a;if("unit"===e[0]&&"unit"!==r[0]){let a=get_unit_of_tree(e);if(a){let i=try_evaluate_quotient_of_numbers(remove_units(e,!1),r,t,n);if(null!==i)return add_unit(i,a)}}return[o].concat(l)}if("^"===o){let e=l[0],r=l[1];if("number"==typeof r)if(0===r){if(!math$1.pow_strict)return 1;let n=is_nonzero_ast(e,t);if(n&&e!==1/0&&e!==-1/0)return 1;if(!1===n)return NaN}else{if(1===r)return e;if("number"==typeof e){let t=math$1.pow(e,r);if(n===1/0||math$1.round(t,n)===t)return t}}else if(1===e)return 1;return[o].concat(l)}return[o].concat(l)}function evaluate_numbers(e,{assumptions:t,max_digits:n,skip_ordering:r=!1,evaluate_functions:a=!1,set_small_zero:i=0}={}){(void 0===n||!Number.isInteger(n)&&n!==1/0)&&(n=0),!0===i&&(i=1e-14);var s,o=get_tree(e);return contains_blank(o)?o:(void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),r?s=evaluate_numbers_sub(o=unflattenRight(flatten$5(o)),t,n,r,a,i):(o=move_units_outside_products(o),o=unflattenRight(default_order(flatten$5(o))),s=default_order(evaluate_numbers_sub(o,t,n,r,a,i)),s=default_order(evaluate_numbers_sub(unflattenRight(s),t,n,r,a,i))),flatten$5(s=set_negative_zeros_to_zero(s)))}function set_negative_zeros_to_zero(e){return 0===e?0:Array.isArray(e)?[e[0],...e.slice(1).map(set_negative_zeros_to_zero)]:e}function collect_like_terms_factors(e,t,n){function r(e){return"number"==typeof e||!(!Array.isArray(e)||"-"!==e[0]||"number"!=typeof e[1])}function a(e){return"number"==typeof e&&e<0||!(!Array.isArray(e)||"-"!==e[0]||"number"!=typeof e[1])}function i(e){if("number"==typeof e)return!0;if(Array.isArray(e)&&"-"===e[0]&&"number"==typeof e[1])return!0;let t=evaluate_to_constant(e,!1);return!("number"!=typeof t||!Number.isFinite(t))}var s=get_tree(e);if(contains_blank(s))return s;void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),s=evaluate_numbers(s,{assumptions:t,max_digits:n,evaluate_functions:!0});var o=[];o.push([["/","x",["^","y","a"]],["*","x",["^","y",["-","a"]]],{evaluate_numbers:!0,max_digits:n}]),o.push([["/","x",["apply","exp","a"]],["*","x",["apply","exp",["-","a"]]],{evaluate_numbers:!0,max_digits:n,variables:{x:!0,a:!0}}]),o.push([["/","x","y"],["*","x",["^","y",["-",1]]],{evaluate_numbers:!0,max_digits:n}]),s=applyAllTransformations(s,o,40),o=[];for(let e in all_units)all_units[e].prefix?(o.push([["+",["unit",e,"x"],["unit",e,"y"]],["unit",e,["+","x","y"]],{variables:{x:!0,y:!0},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["unit",e,"x"],["-",["unit",e,"y"]]],["unit",e,["+","x",["-","y"]]],{variables:{x:!0,y:!0},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}])):(o.push([["+",["unit","x",e],["unit","y",e]],["unit",["+","x","y"],e],{variables:{x:!0,y:!0},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["unit","x",e],["-",["unit","y",e]]],["unit",["+","x",["-","y"]],e],{variables:{x:!0,y:!0},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]));return o.push([["*",["^","x","n"],["^","x","m"]],["^","x",["+","n","m"]],{variables:{x:e=>is_nonzero_ast(e,t),n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["*",["^","x","n"],["^","x","m"]],["^","x",["+","n","m"]],{variables:{x:!0,n:e=>r(e)&&is_positive_ast(e,t),m:e=>r(e)&&is_positive_ast(e,t)},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["*",["^","x","n"],["^","x","m"]],["^","x",["+","n","m"]],{variables:{x:!0,n:e=>r(e)&&is_negative_ast(e,t),m:e=>r(e)&&is_negative_ast(e,t)},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["*",["apply","exp","n"],["apply","exp","m"]],["apply","exp",["+","n","m"]],{variables:{n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*","n","x"],["*","m","x"]],["*",["+","n","m"],"x"],{variables:{x:!0,n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*","n1","x"],["*",["/","n2","m2"],"x"]],["*",["+","n1",["/","n2","m2"]],"x"],{variables:{x:!0,n1:r,n2:r,m2:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m2","n1","n2"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*","n1","x"],["*",["-",["/","n2","m2"]],"x"]],["*",["+","n1",["-",["/","n2","m2"]]],"x"],{variables:{x:!0,n1:r,n2:r,m2:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m2","n1","n2"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*",["/","n1","m1"],"x"],["*",["/","n2","m2"],"x"]],["*",["+",["/","n1","m1"],["/","n2","m2"]],"x"],{variables:{x:!0,n1:r,m1:r,n2:r,m2:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m1","m2","n1","n2"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*",["/","n1","m1"],"x"],["*",["-",["/","n2","m2"]],"x"]],["*",["+",["/","n1","m1"],["-",["/","n2","m2"]]],"x"],{variables:{x:!0,n1:r,m1:r,n2:r,m2:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m1","m2","n1","n2"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["+",["*","n","x"],["-",["*","m","x"]]],["*",["+","n",["-","m"]],"x"],{variables:{x:!0,n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_implicit_identities:["m","n"],allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["^",["*","x","y"],"a"],["*",["^","x","a"],["^","y","a"]],{allow_permutations:!0}]),o.push([["^",["^","x","n"],"m"],["^","x",["*","n","m"]],{variables:{x:!0,n:r,m:r},evaluate_numbers:!0,max_digits:n,allow_permutations:!0}]),o.push([["-",["+","a","b"]],["+",["-","a"],["-","b"]]]),o.push([["*","x","y"],["*","x","y"],{variables:{x:i,y:i},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s=applyAllTransformations(s,o,40),(o=[]).push([["*","x",["^","y",["-","a"]]],["/","x",["^","y","a"]],{allow_extended_match:!0,allow_permutations:!0,evaluate_numbers:!0,max_digits:n,max_group:1}]),o.push([["*","x",["apply","exp",["-","a"]]],["/","x",["apply","exp","a"]],{allow_extended_match:!0,allow_permutations:!0,evaluate_numbers:!0,max_digits:n,max_group:1,variables:{x:!0,a:!0}}]),o.push([["*","x",["^","y","n"]],["/","x",["^","y",["-","n"]]],{variables:{x:!0,y:!0,n:a},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["*","x",["apply","exp","n"]],["/","x",["apply","exp",["-","n"]]],{variables:{x:!0,n:a},evaluate_numbers:!0,max_digits:n,allow_extended_match:!0,allow_permutations:!0,max_group:1}]),s=applyAllTransformations(s,o,40),(o=[]).push([["^","y","n"],["/",1,["^","y",["-","n"]]],{variables:{y:!0,n:a},evaluate_numbers:!0,max_digits:n}]),o.push([["apply","exp","n"],["/",1,["apply","exp",["-","n"]]],{variables:{n:a},evaluate_numbers:!0,max_digits:n}]),s=applyAllTransformations(s,o,40),(o=[]).push([["*","x",["/","y","z"]],["/",["*","x","y"],"z"],{allow_extended_match:!0,allow_permutations:!0,max_group:1}]),o.push([["/",["/","x","y"],"z"],["/","x",["*","y","z"]],{allow_extended_match:!0,allow_permutations:!0}]),o.push([["/","x",["/","y","z"]],["/",["*","x","z"],"y"],{allow_extended_match:!0,allow_permutations:!0}]),evaluate_numbers(s=applyAllTransformations(s,o,40),{assumptions:t,max_digits:n})}function simplify_ratios(e,t){function n(e){var t=1;return e=e.map((function(e){if("number"==typeof e)return e<0?(t*=-1,-e):e;if(!Array.isArray(e))return e;if("-"===e[0])return t*=-1,e[1];if("+"!==e[0])return e;var n=!1;if(("number"==typeof e[1]&&e[1]<0||Array.isArray(e[1])&&"-"===e[1][0]||Array.isArray(e[1])&&"*"===e[1][0]&&Number(e[1][1])<0)&&(n=!0),n){t*=-1;var r=e.slice(1).map((e=>["-",e]));return evaluate_numbers(["+"].concat(r))}return e})),{factors:e,sign_change:t}}var r=get_tree(e);return contains_blank(r)?r:(void 0===t&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(t=e.context.get_assumptions([e.variables()])),function e(t,r){if(!Array.isArray(t))return r?["-",t]:t;var a=t[0];if("-"===a)return e(t[1],r=!0);var i=t.slice(1).map((t=>e(t)));if("/"!==a)return r?["-",[a,...i]]:[a,...i];var s,o=i[0],l=i[1];o=default_order(o,{ignore_negatives:!0});var u,c=n(s=Array.isArray(o)&&"*"===o[0]?o.slice(1):[o]);s=c.factors,r&&(c.sign_change*=-1),l=default_order(l,{ignore_negatives:!0});var p=n(Array.isArray(l)&&"*"===l[0]?l.slice(1):[l]);return u=p.factors,c.sign_change*p.sign_change<0&&(s[0]=["-",s[0]]),["/",o=1===s.length?s[0]:["*"].concat(s),l=1===u.length?u[0]:["*"].concat(u)]}(r))}function contains_blank(e){return"_"===e||!!Array.isArray(e)&&e.some(contains_blank)}let all_units=get_all_units();function remove_units(e,t=!0){var n=get_tree(e);if(!Array.isArray(n))return n;let r=n[0],a=n.slice(1);if("unit"===r){let e=all_units[get_unit_of_tree(n)];if(!e)return n;let r=remove_units(e.prefix?a[1]:a[0],t);return t?e.scale(r):r}return[r,...a.map((e=>remove_units(e,t)))]}function remove_scaling_units(e){var t=get_tree(e);if(!Array.isArray(t))return t;let n=t[0],r=t.slice(1);if("unit"===n){let e=all_units[get_unit_of_tree(t)];if(!e||!e.only_scales)return t;let n=remove_scaling_units(e.prefix?r[1]:r[0]);return e.scale(n)}return[n,...r.map((e=>remove_scaling_units(e)))]}function add_unit(e,t){var n=get_tree(e);let r=all_units[t];return r?r.prefix?["unit",t,n]:["unit",n,t]:n}function move_units_outside_products(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);if("*"===t){let e=[],t=[];for(let r of n){let n=get_unit_value_of_tree(r);n?(e.push(n[0]),t.push(n[1])):t.push(r)}let r=["*",...t];for(let t of e)r=add_unit(r,t);return r}return[t,...n.map(move_units_outside_products)]}var simplify$1=Object.freeze({__proto__:null,clean:clean,simplify:simplify,simplify_logical:simplify_logical,evaluate_numbers:evaluate_numbers,collect_like_terms_factors:collect_like_terms_factors,collapse_unary_minus:collapse_unary_minus,simplify_ratios:simplify_ratios,default_order:default_order,perform_vector_matrix_additions_scalar_multiplications:perform_vector_matrix_additions_scalar_multiplications,remove_units:remove_units,add_unit:add_unit,remove_scaling_units:remove_scaling_units});function solve_linear(e,t,n){if("string"==typeof t){void 0===n&&void 0!==e.context&&void 0!==e.context.get_assumptions&&(n=e.context.get_assumptions([e.variables()]));var r=simplify(get_tree(e),n);if(Array.isArray(r)){var a=r[0],i=r.slice(1);if("="===a||"ne"===a||"<"===a||"le"===a||">"===a||"ge"===a){var s=simplify(["+",i[0],["-",i[1]]],n),o=e=>!variables(e).includes(t);if(variables(s=simplify(applyAllTransformations(s,[[["+",["*","_a",t],["*","_b",t]],["*",["+","_a","_b"],t],{variables:{_a:o,_b:o},allow_permutations:!0,allow_extended_match:!0,allow_implicit_identities:["_a","_b"],evaluate_numbers:!0}]],20))).includes(t)){var l=match$2(s,["+",["*","_a",t],"_b"],{variables:{_a:o,_b:o},allow_permutations:!0,allow_implicit_identities:["_a","_b"]});if(l){var u=simplify(l._a),c=simplify(l._b);if(is_nonzero_ast(u,n)){if("="===a||"ne"===a||is_positive_ast(u,n)){let e=simplify(["/",["-",c],u]);return[a,t,e]}if(is_negative_ast(u,n)){var p=simplify(["/",["-",c],u]);return[a="<"===a?">":"le"===a?"ge":">"===a?"<":"le",t,p]}}}}}}}}var solve=Object.freeze({__proto__:null,solve_linear:solve_linear});function clean_assumptions(e,t){if(!Array.isArray(e)||0===e.length)return e;var n=(e=flatten$5(default_order(simplify_logical(expand_relations(e)))))[0],r=e.slice(1);if("and"===n||"or"===n){if(r=r.reduce((function(e,t){return e.every((function(e){return!equal(e,t)}))&&e.push(t),e}),[]),"and"===n&&t&&Array.isArray(t)){let e;e="and"===t[0]?t.slice(1):[t],r=r.filter((t=>e.every((e=>!equal(e,t)))))}e=1===r.length?r[0]:[n].concat(r)}if("and"!==n&&t&&Array.isArray(t)){let n;if(n="and"===t[0]?t.slice(1):[t],!n.every((t=>!equal(t,e))))return}return e}function calculate_derived_assumptions(e,t){if(void 0===t){t=[];for(let n in e.byvar){let r=e.byvar[n];r.length>0&&t.push(r)}if(0===t.length)return{};t=clean_assumptions(t=1===t.length?t[0]:["and"].concat(t))}if(!Array.isArray(t)||0===t.length)return{};var n=t[0],r=t.slice(1);if("and"===n||"or"===n){let t=r.map((function(t){return calculate_derived_assumptions(e,t)})),a=[...new Set(t.reduce(((e,t)=>[...e,...Object.keys(t)]),[]))],i={};for(let r of a){let a=t.reduce((function(e,t){return void 0!==t[r]&&e.push(t[r]),e}),[]);if("and"===n||a.length===t.length){let t=i[r];t=void 0===t?a.length>1?[n].concat(a):a[0]:a.length>1?["and",t,[n].concat(a)]:["and",t,a[0]],i[r]=clean_assumptions(t,get_assumptions(e,r,{omit_derived:!0}))}}return i}let a={};if("="===n||"ne"===n||"<"===n||"le"===n||"in"===n||"subset"===n||"notin"===n||"notsubset"===n){var i=!1;for(let t=0;t<2;t++){let o=r[t],l=r[1-t],u=variables(l);if("string"!=typeof o||0===u.length||u.includes(o))continue;i=!0;var s=n;1===t&&("<"===n?s=">":"le"===n?s="ge":"in"===n?s="ni":"subset"===n?s="superset":"notin"===n?s="notni":"notsubset"===n&&(s="notsuperset"));let c=get_assumptions_for_expr(e,l,[o]);if(c=combine_assumptions(o,s,l,c),void 0!==c){let t=a[o];t=void 0===t?c:["and",t,c],a[o]=clean_assumptions(t,get_assumptions(e,o,{omit_derived:!0}))}}if(i)return a}let o=[];for(let t of r){let n=get_assumptions_for_expr(e,t,[]);void 0!==n&&o.push(n)}if(0===o.length)return{};o=1===o.length?o[0]:["and"].concat(o);for(let n of variables(t))a[n]=clean_assumptions(o,get_assumptions(e,n,{omit_derived:!0}));return a}function get_assumptions_for_expr(e,t,n){let r=variables(t);if(r=r.filter((e=>!n.includes(e))),0===r.length)return;function a(e){return"number"==typeof e||!(!Array.isArray(e)||"-"!==e[0]||"number"!=typeof e[1])}var i=["_b"],s=["_b"],o={_b:a},l={};for(let e=0;evoid 0!==e));if(0===e.length)return;return"or"===s?e.length===o.length?["or"].concat(e):void 0:1===e.length?e[0]:["and"].concat(e)}if(!(["=","ne","<","le"].includes(s)||["in","notin","subset","notsubset"].includes(s)&&c)){let r=n.concat(variables(t)),a=[];for(let t of variables(i)){if(r.includes(t))continue;let n=get_assumptions_for_expr(e,t,r);void 0!==n&&a.push(n)}return 0===a.length?i:1===a.length?["and",i,a[0]]:["and",i].concat(a)}let u=[];for(let a=0;a<=1;a++){let i=o[a],c=o[1-a];if("string"==typeof i&&r.includes(i)){var p={};p[i]=c;var d=simplify(substitute$1(t,p)),m=!1,h=s;(1===a&&l[i]>0||0===a&&l[i]<0)&&("<"===s?(m=!0,h=">"):"le"===s?(m=!0,h="ge"):"in"===s?(m=!0,h="ni"):"subset"===s?(m=!0,h="superset"):"notin"===s?(m=!0,h="notni"):"notsubset"===s&&(m=!0,h="notsuperset")),m?u.push([s,d,t]):u.push([s,t,d]);let r=n.concat([i]),o=get_assumptions_for_expr(e,d,r);o=combine_assumptions(t,h,d,o),void 0!==o&&u.push(o)}}if(1===u.length)return u[0];if(u.length>1)return["and"].concat(u);let f=n.concat(variables(t));u=[];for(let t of variables(i)){if(f.includes(t))continue;let n=get_assumptions_for_expr(e,t,f);void 0!==n&&u.push(n)}return 0===u.length?i:1===u.length?["and",i,u[0]]:["and",i].concat(u)}(p)):void 0}function combine_assumptions(e,t,n,r){if(!["=","ne","<","le",">","ge","in","notin","ni","notni","subset","notsubset","superset","notsuperset"].includes(t))return r;if(Array.isArray(r)){var a=r[0],i=r.slice(1);if("and"===a||"or"===a){let r=i.map((r=>combine_assumptions(e,t,n,r))).filter((e=>void 0!==e));if(0===r.length)return;return"or"===a?r.length===i.length?[["or"].concat(r)]:void 0:1===r.length?r[0]:["and"].concat(r)}if(!["=","ne","<","le","in","notin","subset","notsubset"].includes(a))return r;var s,o,l=a;if(equal(i[0],n))s=i[1];else{if(!equal(i[1],n))return r;s=i[0],"<"===a?l=">":"le"===a?l="ge":"in"===a?l="ni":"notin"===a?l="notni":"subset"===a?l="superset":"notsubset"===a&&(l="notsuperset")}if("="===t)o=l;else if("="===l)o=t;else if("<"===t){if("<"!==l&&"le"!==l)return"in"===l||"notin"===l?r:void 0;o="<"}else if("le"===t)if("<"===l)o="<";else{if("le"!==l)return"in"===l||"notin"===l?r:void 0;o="le"}else if(">"===t){if(">"!==l&&"ge"!==l)return"in"===l||"notin"===l?r:void 0;o=">"}else if("ge"===t)if(">"===l)o=">";else{if("ge"!==l)return"in"===l||"notin"===l?r:void 0;o="ge"}else if("in"===t){if("subset"!==l)return;o="in"}else if("notin"===t){if("superset"!==l)return;o="notin"}else if("ni"===t){if("notin"!==l)return;o="notsubset"}else if("notni"===t){if("in"!==l)return;o="notsuperset"}else if("subset"===t)if("subset"===l)o="subset";else if("notni"===l)o="notni";else{if("notsuperset"!==l)return;o="notsuperset"}else if("notsubset"===t){if("superset"!==l)return;o="notsubset"}else if("superset"===t)if("superset"===l)o="superset";else if("ni"===l)o="ni";else{if("notsubset"!==l)return;o="notsubset"}else{if("notsuperset"!==t)return;if("subset"!==l)return;o="notsuperset"}return">"===o?["<",s,e]:"ge"===o?["le",s,e]:"ni"===o?["in",s,e]:"notni"===o?["notin",s,e]:"superset"===o?["subset",s,e]:"notsuperset"===o?["notsubset",s,e]:[o,e,s]}}function filter_assumptions_from_tree(e,t){if(Array.isArray(e)&&0!==e.length){Array.isArray(t)||(t=[t]);var n=e[0],r=e.slice(1);if("and"===n){var a=r.map((function(e){return filter_assumptions_from_tree(e,t)}));return 0===(a=a.filter((e=>void 0!==e))).length?void 0:1===a.length?a[0]:["and"].concat(a)}var i=variables(e);return t.filter((e=>i.includes(e))).length>0?void 0:e}}function get_assumptions_sub(e,t,n,r){Array.isArray(t)||(t=[t]);var a=[];return t.forEach((function(t){if(e.byvar[t]||e.derived[t]){if(e.byvar[t]&&e.byvar[t].length>0){var i=filter_assumptions_from_tree(e.byvar[t],n);void 0!==i&&a.push(i)}if(e.derived[t]&&e.derived[t].length>0&&!r){var s=filter_assumptions_from_tree(e.derived[t],n);void 0!==s&&a.push(s)}}else e.generic.length>0&&("x"!==t&&variables(e.generic).includes(t)||a.push(substitute$1(e.generic,{x:t})))})),1===a.length?a=a[0]:a.length>1&&(a=["and"].concat(a)),a.length>0?clean_assumptions(a):void 0}function get_assumptions(e,t,n){void 0===n&&(n={});var r,a=n.exclude_variables;void 0===a?a=[]:Array.isArray(a)||(a=[a]);var i=get_tree(t);if("string"==typeof i)r=[i];else{if(!Array.isArray(i))return;Array.isArray(i[0])&&(r=i[0])}return r?get_assumptions_sub(e,r,a,n.omit_derived):get_assumptions_for_expr(e,i,a)}function add_assumption(e,t,n){var r=get_tree(t);if(!Array.isArray(r))return 0;var a=add_assumption_sub(e,r=clean_assumptions(simplify(r,e)),n);return a&&(e.derived=calculate_derived_assumptions(e)),a}function add_assumption_sub(e,t,n){if("and"===t[0])return t.slice(1).map((t=>add_assumption_sub(e,t,n))).reduce((function(e,t){return e+t}));var r=variables(t);if(0===r.length)return 0;let a=0;!n&&e.generic.length>0&&r.forEach((function(t){void 0===e.byvar[t]&&("x"!==t&&variables(e.generic).includes(t)||(add_assumption_sub(e,substitute$1(e.generic,{x:t}),!0),a+=1))}));for(let n of r){let r=solve_linear(t,n,e),i=t;r&&(i=r);let s=e.byvar[n];void 0!==s&&0!==s.length&&(i=["and",s,i]),i=clean_assumptions(i),equal(i,s)||(e.byvar[n]=i,a+=1)}return a}function add_generic_assumption(e,t){var n=get_tree(t);if(!Array.isArray(n))return 0;var r=add_generic_assumption_sub(e,n=clean_assumptions(simplify(n,e)));return r&&(e.derived=calculate_derived_assumptions(e)),r}function add_generic_assumption_sub(e,t){if("and"===t[0])return t.slice(1).map((t=>add_generic_assumption_sub(e,t))).reduce((function(e,t){return e+t}));if(!variables(t).includes("x"))return 0;let n=solve_linear(t,"x",e),r=t;n&&(r=n);let a=e.generic;return 0!==a.length&&(r=["and",a,r]),r=clean_assumptions(r),equal(r,a)?0:(e.generic=r,1)}function remove_assumption(e,t){var n=get_tree(t);if(!Array.isArray(n))return 0;var r=remove_assumption_sub(e,n=clean_assumptions(simplify(n,e)));return r&&(e.derived=calculate_derived_assumptions(e)),r}function remove_assumption_sub(e,t){if("and"===t[0])return t.slice(1).map((t=>remove_assumption_sub(e,t))).reduce((function(e,t){return e+t}));var n=variables(t);if(0===n.length)return 0;var r=0;for(let a of n){let n=solve_linear(t,a,e),i=e.byvar[a];if(!i||0===i.length)continue;let s,o=i[0],l=i.slice(1),u=l.length;if("and"===o)if(l=l.filter((e=>!(equal(e,t)||equal(e,n)))),0===l.length)s=[];else if(1===l.length)s=l[0];else{if(!(l.lengthremove_generic_assumption_sub(e,t))).reduce((function(e,t){return e+t}));if(!variables(t).includes("x"))return 0;var n=e.generic;if(0===n.length)return 0;let r=solve_linear(t,"x",e);var a,i=n[0],s=n.slice(1),o=s.length;if("and"===i)if(0===(s=s.filter((e=>!(equal(e,t)||equal(e,r))))).length)a=[];else if(1===s.length)a=s[0];else{if(!(s.length0)if(e.includes(".")){if("0"!==e[0]?n++:n+=e.match(/^0\.0*/)[0].length,e.length0)if(e.includes(".")){let t=e.match(/\.\d*$/)[0].length-1;t":function(e){return e.join(" > ")},lts:function(e){return e.join(" < ")},gts:function(e){return e.join(" > ")},le:function(e){return e.join(" \\le ")},ge:function(e){return e.join(" \\ge ")},ne:function(e){return e.join(" \\ne ")},in:function(e){return e[0]+" \\in "+e[1]},notin:function(e){return e[0]+" \\notin "+e[1]},ni:function(e){return e[0]+" \\ni "+e[1]},notni:function(e){return e[0]+" \\not\\ni "+e[1]},subset:function(e){return e[0]+" \\subset "+e[1]},subseteq:function(e){return e[0]+" \\subseteq "+e[1]},notsubset:function(e){return e[0]+" \\not\\subset "+e[1]},notsubseteq:function(e){return e[0]+" \\not\\subseteq "+e[1]},superset:function(e){return e[0]+" \\supset "+e[1]},superseteq:function(e){return e[0]+" \\supseteq "+e[1]},notsuperset:function(e){return e[0]+" \\not\\supset "+e[1]},notsuperseteq:function(e){return e[0]+" \\not\\supseteq "+e[1]},union:function(e){return e.join(" \\cup ")},intersect:function(e){return e.join(" \\cap ")},perp:function(e){return e.join(" \\perp ")},parallel:function(e){return e.join(" \\parallel ")},derivative_leibniz:function(e){return"\\frac{d"+e[0]+"}{d"+e[1]+"}"},partial_derivative_leibniz:function(e){return"\\frac{d"+e[0]+"}{d"+e[1]+"}"},"|":function(e){return e[0]+" \\mid "+e[1]},":":function(e){return e[0]+" : "+e[1]},binom:function(e){return"\\binom{"+e[0]+"}{"+e[1]+"}"},vec:function(e){return"\\vec{"+e[0]+"}"},linesegment:function(e){return"\\overline{"+e.join(" ")+"}"},angle:function(e,t){return t?"\\angle "+e.join(""):"\\angle\\left( "+e.join(", ")+" \\right)"},unit:function(e){return"\\circ"===e[1]?e[0]+"^{\\circ}":e[0]+" "+e[1]}},allowedLatexSymbolsDefault$1=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","cot","coth","csc","csch","sec","sech","sin","sinh","tan","tanh","arcsin","arccos","arctan","arccsc","arcsec","arccot","arg","Re","Im","det","angle","perp","circ","%","$","int"],convertLatexSymbolsDefault={acos:"arccos",acosh:"arccosh",acot:"arccot",acoth:"arccoth",acsc:"arccsc",acsch:"arccsch",asec:"arcsec",asech:"arcsech",asin:"arcsin",asinh:"arcsinh",atan:"arctan",atanh:"arctanh",deg:"circ"},matrixEnvironmentDefault="bmatrix";class astToLatex$1{constructor({allowedLatexSymbols:e=allowedLatexSymbolsDefault$1,convertLatexSymbols:t=convertLatexSymbolsDefault,matrixEnvironment:n=matrixEnvironmentDefault,padToDigits:r=null,padToDecimals:a=null,showBlanks:i=!0}={}){this.allowedLatexSymbols=e,this.convertLatexSymbols=t,this.matrixEnvironment=n,this.padToDigits=r,this.padToDecimals=a,this.showBlanks=i}convert(e){return this.statement(e)}statement(e){if(!Array.isArray(e))return this.single_statement(e);var t=e[0],n=e.slice(1);if("ldots"===t)return"\\ldots";if(!(t in operators$1)&&"apply"!==t)throw new Error("Badly formed ast: operator "+t+" not recognized.");return"and"===t||"or"===t?operators$1[t](n.map(function(e,t){let n=this.single_statement(e);return n.match(/ /)&&!n.match(/^\\left\(.*\\right\)$/)?"\\left("+n+"\\right)":n}.bind(this))):this.single_statement(e)}single_statement(e){if(!Array.isArray(e))return this.expression(e);var t=e[0],n=e.slice(1);if("not"===t)return operators$1[t](n.map(function(e,t){let n=this.single_statement(e);return n.match(/ /)&&!n.match(/^\\left\(.*\\right\)$/)?"\\left("+n+"\\right)":n}.bind(this)));if("="===t||"ne"===t||"<"===t||">"===t||"le"===t||"ge"===t||"in"===t||"notin"===t||"ni"===t||"notni"===t||"subset"===t||"notsubset"===t||"subseteq"===t||"notsubseteq"===t||"superset"===t||"notsuperset"===t||"superseteq"===t||"notsuperseteq"===t)return operators$1[t](n.map(function(e,t){return this.expression(e)}.bind(this)));if("lts"===t||"gts"===t){let e=n[0],r=n[1];if("tuple"!==e[0]||"tuple"!==r[0])throw new Error("Badly formed ast");let a=this.expression(e[1]);for(let n=1;n ":a+="lts"===t?" \\le ":" \\ge ",a+=this.expression(e[n+1]);return a}return this.expression(e)}expression(e){if(!Array.isArray(e))return this.term(e);var t=e[0],n=e.slice(1);return"+"===t?1===n.length?"+"+this.term(n[0]):operators$1[t](n.map(function(e,t){return t>0?this.termWithPlusIfNotNegated(e):this.term(e)}.bind(this))):["union","intersect","perp","parallel"].includes(t)?operators$1[t](n.map(function(e,t){return this.term(e)}.bind(this))):this.term(e)}term(e){if(!Array.isArray(e))return this.factor(e);var t=e[0],n=e.slice(1);return"-"===t?operators$1[t](n.map(function(e,t){return this.term(e)}.bind(this))):"*"===t?operators$1[t](n.map(function(e,t){let r;return t>0?(r=this.factorWithParenthesesIfNegatedOrExplicitPlus(e),r.match(/^[0-9]/)?"\\cdot "+r:"angle"===e[0]&&n.length>1?"\\left( "+r+" \\right)":r):(r=this.factor(e),"angle"===e[0]&&n.length>1?"\\left( "+r+" \\right)":r)}.bind(this))):"/"===t||"unit"===t?operators$1[t](n.map(function(e,t){return this.expression(e)}.bind(this))):this.factor(e)}simple_factor_or_function_or_parens(e){var t=this.factor(e);return!!(t.length<=1||"string"==typeof e&&e.match(/^\w+$/)||Array.isArray(e)&&"apply"===e[0]&&"sqrt"!==e[1]||t.match(/^\\left\(.*\\right\)$/)||t.match(/^\\left\\langle.*\\right\\rangle$/))||"number"==typeof e&&e>=0&&!e.toString().includes("e")}stringConvert(e){return e.length>1?(this.convertLatexSymbols[e]&&(e=this.convertLatexSymbols[e]),this.allowedLatexSymbols.includes(e)?"\\"+e:"\\operatorname{"+e+"}"):this.allowedLatexSymbols.includes(e)?"\\"+e:"_"!==e||this.showBlanks?e:""}factor(e){if("string"==typeof e)return this.stringConvert(e);if("number"==typeof e){if(e===1/0)return"\\infty";if(e===-1/0)return"-\\infty";if(Number.isNaN(e))return"NaN";{let t=e.toString(),n=t.indexOf("e");if(-1===n)return null!==this.padToDigits?t=padNumberStringToDigits(t,this.padToDigits):null!==this.padToDecimals&&(t=padNumberStringToDecimals(t,this.padToDecimals)),t;let r=t.substring(0,n),a=t.substring(n+1);if("+"===a[0]&&(a=a.slice(1)),null!==this.padToDigits)r=padNumberStringToDigits(r,this.padToDigits);else if(null!==this.padToDecimals){let n=Number(a);if(n>0)return t=e.toLocaleString("fullwide",{useGrouping:!1}),padNumberStringToDecimals(t,this.padToDecimals);r=padNumberStringToDecimals(r,this.padToDecimals+n)}return r+" \\cdot 10^{"+a+"}"}}if(!Array.isArray(e))return"";var t=e[0],n=e.slice(1);if("^"===t){if(Number.isInteger(n[0])&&Number.isInteger(n[1]))return n[0]<0?"\\left("+n[0].toString()+"\\right)^{"+n[1].toString()+"}":n[0].toString()+"^{"+n[1].toString()+"}";let e=this.factor(n[0]),t=n[0];for(;"prime"===t[0];)t=t[1];return this.simple_factor_or_function_or_parens(t)||"_"===t[0]&&"string"==typeof t[1]||(e="\\left("+e.toString()+"\\right)"),e+"^{"+this.statement(n[1])+"}"}if("_"===t){let e=this.factor(n[0]);return this.simple_factor_or_function_or_parens(n[0])||(e="\\left("+e.toString()+"\\right)"),e+"_{"+this.statement(n[1])+"}"}if("prime"===t){let e=n[0],t=1;for(;"prime"===e[0];)t+=1,e=e[1];let r=this.factor(e);this.simple_factor_or_function_or_parens(e)||"_"===e[0]&&"string"==typeof e[1]||(r="\\left("+r+"\\right)");for(let e=0;e1?o=o.trimRight()+"^{"+i+"}"+this.stringConvert(s):o+=this.stringConvert(s),o="\\frac{ "+o+" }{ ";let l=1;Array.isArray(a)&&(l=a.length-1);for(let t=1;t<=l;t++){let n=a[t],r=1,i="";Array.isArray(n)?(i=n[1],r=n[2]):i=n,o=o+e+this.stringConvert(i),r>1&&(o=o+"^{"+r+"}"),o+=" "}return o+="}",o}if("apply"===t){if("abs"===n[0])return"\\left|"+this.statement(n[1])+"\\right|";if("floor"===n[0])return"\\left\\lfloor "+this.statement(n[1])+" \\right\\rfloor";if("ceil"===n[0])return"\\left\\lceil "+this.statement(n[1])+" \\right\\rceil";if("factorial"===n[0]){let e=this.factor(n[1]);return this.simple_factor_or_function_or_parens(n[1])||"_"===n[1][0]&&"string"==typeof n[1][1]?e+"!":"\\left("+e+"\\right)!"}if("sqrt"===n[0])return"\\sqrt{"+this.statement(n[1])+"}";let e,t=n[0];if("^"===t[0]&&(t=t[1]),"_"===t[0]&&(t=t[1]),"int"===t){let e,t=this.factor(n[0]),r=n[1];if(Array.isArray(r)&&"*"===r[0]){let t=[],n=["*"];for(let e=1;e0&&(e[e.length-1].match(/[a-zA-Z]/)&&(e+="\\,"),e+=t.map((e=>"d"+this.factor(e[1]))).join("\\,"))}return e||(e=this.term(n[1])),t+" "+e}e="log10"===n[0]?"\\log_{10}":"re"===n[0]?"\\Re":"im"===n[0]?"\\Im":this.factor(n[0]);let r=this.statement(n[1]);return"tuple"!==n[1][0]&&(r="\\left("+r+"\\right)"),e+r}if("angle"===t){let e=n.every((e=>{if("string"==typeof e&&1===e.length)return!0;if(!Array.isArray(e))return!1;let t=e[0];return"_"===t||"^"===t||"prime"===t}));return operators$1[t](n.map(function(e,t){return this.statement(e)}.bind(this)),e)}return"+"===t&&2===e.length?"+ "+this.factor(e[1]):"\\left("+this.statement(e)+"\\right)"}factorWithParenthesesIfNegatedOrExplicitPlus(e){var t=this.factor(e);return t.match(/^-/)||t.match(/^\+/)?"\\left("+t+"\\right)":t}termWithPlusIfNotNegated(e){var t=this.term(e);return t.match(/^-/)?t.match(/^-[^ ]/)?"- "+t.slice(1):t:"+ "+t}}const textToAst$2=new textToAst$4,astToLatex=new astToLatex$1;var derivatives={sin:textToAst$2.convert("cos x"),cos:textToAst$2.convert("-(sin x)"),tan:textToAst$2.convert("(sec x)^2"),cot:textToAst$2.convert("-((csc x)^2)"),sec:textToAst$2.convert("(sec x)*(tan x)"),csc:textToAst$2.convert("-(csc x)*(cot x)"),sqrt:textToAst$2.convert("1/(2*sqrt(x))"),log:textToAst$2.convert("1/x"),ln:textToAst$2.convert("1/x"),exp:textToAst$2.convert("exp(x)"),arcsin:textToAst$2.convert("1/sqrt(1 - x^2)"),arccos:textToAst$2.convert("-1/sqrt(1 - x^2)"),arctan:textToAst$2.convert("1/(1 + x^2)"),arccsc:textToAst$2.convert("-1/(sqrt(-1/x^2 + 1)*x^2)"),arcsec:textToAst$2.convert("1/(sqrt(-1/x^2 + 1)*x^2)"),arccot:textToAst$2.convert("-1/(1 + x^2)"),abs:textToAst$2.convert("abs(x)/x")};function derivative(e,t,n=[]){var r=get_tree(e),a="\\frac{d}{d"+t+"} ";if("number"==typeof r)return n.push("The derivative of a constant is zero, that is, \\("+a+astToLatex.convert(r)+" = 0\\)."),0;if(variables(r).indexOf(t)<0)return n.push("The derivative of a constant is zero, that is, \\("+a+astToLatex.convert(r)+" = 0\\)."),0;if("string"==typeof r)return t===r?(n.push("We know the derivative of the identity function is one, that is, \\("+a+astToLatex.convert(r)+" = 1\\)."),1):(n.push("As far as \\("+astToLatex.convert(t)+"\\) is concerned, \\("+astToLatex.convert(r)+"\\) is constant, so "+a+astToLatex.convert(r)+" = 0\\)."),0);if(!Array.isArray(r))return null;var i=r[0],s=r.slice(1);if("+"===i||"-"===i||"~"===i){n.push("Using the sum rule, \\("+a+astToLatex.convert(r)+" = "+s.map((function(e,t){return a+astToLatex.convert(e)})).join(" + ")+"\\).");let e=[i].concat(s.map((function(e,r){return derivative(e,t,n)})));return e=simplify(e),n.push("So using the sum rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\)."),e}if("*"===i){let e=[],i=[];for(let n=0;n0){if(0===e.length)return n.push("Since the derivative of a constant is zero, \\("+a+astToLatex.convert(r)+" = 0.\\)"),0;let s=["*"].concat(e);if(1===e.length&&(s=e[0]),s===t){n.push("By the constant multiple rule, \\("+a+astToLatex.convert(r)+" = "+i.map((function(e,t){return astToLatex.convert(e)})).join(" \\cdot ")+"\\).");let e=["*"].concat(i);return e=simplify(e),e}n.push("By the constant multiple rule, \\("+a+astToLatex.convert(r)+" = "+i.map((function(e,t){return astToLatex.convert(e)})).join(" \\cdot ")+" \\cdot "+a+"\\left("+astToLatex.convert(s)+"\\right)\\).");let o=derivative(s,t,n),l=["*"].concat(i.concat([o]));return l=simplify(l),n.push("And so \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}n.push("Using the product rule, \\("+a+astToLatex.convert(r)+" = "+s.map((function(e,t){return s.map((function(n,r){return t===r?a+"\\left("+astToLatex.convert(e)+"\\right)":astToLatex.convert(n)})).join(" \\cdot ")})).join(" + ")+"\\).");let o=s.slice(),l=["+"].concat(s.map((function(e,r){return["*"].concat(o.map((function(e,a){if(r===a){let r=derivative(e,t,n);return 1===r?null:r}return e})).filter((function(e){return null!=e})))})));return l=simplify(l),n.push("So using the product rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}if("/"===i){let e=s[0],i=s[1];if(variables(i).indexOf(t)<0){n.push("By the constant multiple rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(["/",1,i])+" \\cdot "+a+"\\left("+astToLatex.convert(e)+"\\right)\\).");let s=derivative(e,t,n),o=textToAst$2.convert("(1/g)*d"),l=substitute$1(o,{d:s,g:i});return l=simplify(l),n.push("So \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}if(variables(e).indexOf(t)<0){1!==e&&n.push("By the constant multiple rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+" \\cdot "+a+"\\left("+astToLatex.convert(["/",1,i])+"\\right)\\)."),n.push("Since \\(\\frac{d}{du} \\frac{1}{u}\\) is \\(\\frac{-1}{u^2}\\), the chain rule gives \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\cdot \\frac{-1}{ "+astToLatex.convert(i)+"^2} \\cdot "+a+astToLatex.convert(i)+"\\).");let s=derivative(i,t,n),o=textToAst$2.convert("f * (-a/(g^2))"),l=substitute$1(o,{f:e,a:s,g:i});return l=simplify(l),n.push("So since \\(\\frac{d}{du} \\frac{1}{u}\\) is \\(\\frac{-1}{u^2}\\), the chain rule gives \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}n.push("Using the quotient rule, \\("+a+astToLatex.convert(r)+" = \\frac{"+a+"\\left("+astToLatex.convert(e)+"\\right) \\cdot "+astToLatex.convert(i)+" - "+astToLatex.convert(e)+"\\cdot "+a+"\\left("+astToLatex.convert(i)+"\\right)}{ \\left( "+astToLatex.convert(i)+" \\right)^2} \\).");let o=derivative(e,t,n),l=derivative(i,t,n),u=textToAst$2.convert("(a * g - f * b)/(g^2)"),c=substitute$1(u,{a:o,b:l,f:e,g:i});return c=simplify(c),n.push("So using the quotient rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(c)+"\\)."),c}if("^"===i){let e=s[0],i=s[1];if(variables(i).indexOf(t)<0){if("string"==typeof e&&"x"===e){if("number"==typeof i){let t=textToAst$2.convert("n * (f^m)"),s=substitute$1(t,{n:i,m:i-1,f:e});return s=simplify(s),n.push("By the power rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(i)+" \\cdot \\left("+astToLatex.convert(e)+"\\right)^{"+astToLatex.convert(["-",i,1])+"}\\)."),s}let t=textToAst$2.convert("n * (f^(n-1))"),s=substitute$1(t,{n:i,f:e});return s=simplify(s),n.push("By the power rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(i)+" \\cdot \\left("+astToLatex.convert(e)+"\\right)^{"+astToLatex.convert(["-",i,1])+"}\\)."),s}1!==i&&n.push("By the power rule and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(i)+" \\cdot \\left("+astToLatex.convert(e)+"\\right)^{"+astToLatex.convert(["-",i,1])+"} \\cdot "+a+astToLatex.convert(e)+"\\).");let s=derivative(e,t,n);if(1===i)return s;if("number"==typeof i){let t=textToAst$2.convert("n * (f^m) * a"),o=substitute$1(t,{n:i,m:i-1,f:e,a:s});return o=simplify(o),n.push("So by the power rule and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(o)+"\\)."),o}let o=textToAst$2.convert("n * (f^(n-1)) * a"),l=substitute$1(o,{n:i,f:e,a:s});return l=simplify(l),n.push("So by the power rule and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}if("e"===e&&math$1.define_e){if("string"==typeof i&&i===t){let e=textToAst$2.convert("e^(f)"),s=substitute$1(e,{f:i});return s=simplify(s),n.push("The derivative of \\(e^"+astToLatex.convert(t)+"\\) is itself, that is, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(r)+"\\)."),s}n.push("Using the rule for \\(e^x\\) and the chain rule, we know \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(r)+" \\cdot "+a+astToLatex.convert(i)+"\\).");let e=textToAst$2.convert("e^(f)*d"),s=derivative(i,t,n),o=substitute$1(e,{f:i,d:s});return o=simplify(o),n.push("So using the rule for \\(e^x\\) and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(o)+"\\)."),o}if("number"==typeof e){if("string"==typeof i&&i===t){let s=textToAst$2.convert("a^(f) * log(a)"),o=substitute$1(s,{a:e,f:i});return o=simplify(o),n.push("The derivative of \\(a^"+astToLatex.convert(t)+"\\) is \\(a^{"+astToLatex.convert(t)+"} \\, \\log a\\), that is, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(o)+"\\)."),o}let s=textToAst$2.convert("a^(f) * log(a)"),o=substitute$1(s,{a:e,f:i});n.push("Using the rule for \\(a^x\\) and the chain rule, we know \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(o)+" \\cdot "+a+astToLatex.convert(i)+"\\).");let l=textToAst$2.convert("a^(b)*log(a)*d"),u=derivative(i,t,n),c=substitute$1(l,{a:e,b:i,d:u});return c=simplify(c),n.push("So using the rule for \\(a^x\\) and the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(c)+"\\)."),c}let o=e,l=i;n.push("Recall the general rule for exponents, namely that \\(\\frac{d}{dx} u(x)^{v(x)} = u(x)^{v(x)} \\cdot \\left( v'(x) \\cdot \\log u(x) + \\frac{v(x) \\cdot u'(x)}{u(x)} \\right)\\). In this case, \\(u(x) = "+astToLatex.convert(o)+"\\) and \\(v(x) = "+astToLatex.convert(l)+"\\).");let u=derivative(o,t,n),c=derivative(l,t,n),p=textToAst$2.convert("(f^g)*(b * log(f) + (g * a)/f)"),d=substitute$1(p,{a:u,b:c,f:o,g:l});return d=simplify(d),n.push("So by the general rule for exponents, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(d)+"\\)."),d}if("apply"===i&&!(s[0]in derivatives)){let e=s[1];n.push("By the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(substitute$1(["apply",s[0]+"'","x"],{x:e}))+" \\cdot "+a+astToLatex.convert(e)+"\\).");let i=["*",substitute$1(["apply",s[0]+"'","x"],{x:e}),derivative(e,t,n)];return i=simplify(i),n.push("So by the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(i)+"\\)."),i}if("apply"===i&&s[0]in derivatives||i in derivatives){let e=!1;"apply"===i&&(i=s[0],s=s.slice(1),e=!0);let o=s[0];if("number"==typeof o){let e=0;return n.push("The derivative of a constant is zero so \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\)."),e}if("string"==typeof o&&o===t){let e=["*",substitute$1(derivatives[i],{x:o})];return e=simplify(e),n.push("It is the case that \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\)."),e}if("string"==typeof o&&o!==t){let e=0;return n.push("Since the derivative of a constant is zero, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(e)+"\\)."),e}{let s=[i,"u"];e&&(s=["apply"].concat(s)),n.push("Recall \\(\\frac{d}{du}"+astToLatex.convert(s)+" = "+astToLatex.convert(derivative(s,"u",[]))+"\\)."),n.push("By the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(substitute$1(derivatives[i],{x:o}))+" \\cdot "+a+astToLatex.convert(o)+"\\).");let l=["*",substitute$1(derivatives[i],{x:o}),derivative(o,t,n)];return l=simplify(l),n.push("So by the chain rule, \\("+a+astToLatex.convert(r)+" = "+astToLatex.convert(l)+"\\)."),l}}return 0}function lowercaseFirstLetter(e){return e.charAt(0).toLowerCase()+e.slice(1)}function simplify_story(e){for(let t=e.length-1;t>=1;t--)e[t]===e[t-1]&&e.splice(t,1);for(let t=0;t":function(e){return e.join(" > ")},lts:function(e){return e.join(" < ")},gts:function(e){return e.join(" > ")},le:function(e){return e.join(" ≤ ")},ge:function(e){return e.join(" ≥ ")},ne:function(e){return e.join(" ≠ ")},in:function(e){return e[0]+" ∈ "+e[1]},notin:function(e){return e[0]+" ∉ "+e[1]},ni:function(e){return e[0]+" ∋ "+e[1]},notni:function(e){return e[0]+" ∌ "+e[1]},subset:function(e){return e[0]+" ⊂ "+e[1]},subseteq:function(e){return e[0]+" ⊆ "+e[1]},notsubset:function(e){return e[0]+" ⊄ "+e[1]},notsubseteq:function(e){return e[0]+" ⊈ "+e[1]},superset:function(e){return e[0]+" ⊃ "+e[1]},superseteq:function(e){return e[0]+" ⊇ "+e[1]},notsuperset:function(e){return e[0]+" ⊅ "+e[1]},notsuperseteq:function(e){return e[0]+" ⊉ "+e[1]},union:function(e){return e.join(" ∪ ")},intersect:function(e){return e.join(" ∩ ")},perp:function(e){return e.join(" ⟂ ")},parallel:function(e){return e.join(" ∥ ")},derivative_leibniz:function(e){return"d"+e[0]+"/d"+e[1]},partial_derivative_leibniz:function(e){return"∂"+e[0]+"/∂"+e[1]},"|":function(e){return e[0]+" | "+e[1]},":":function(e){return e[0]+" : "+e[1]},binom:function(e){return"binom( "+e[0]+", "+e[1]+" )"},vec:function(e){return"vec("+e[0]+")"},linesegment:function(e){return"linesegment( "+e.join(", ")+" )"},angle:function(e,t){return t?"∠"+e.join(""):"∠( "+e.join(", ")+" )"},unit:function(e){return e[0]+" "+e[1]}},nonunicode_operators={"+":function(e){return e.join(" ")},"-":function(e){return"-"+e[0]},"*":function(e){return e.join(" ")},"/":function(e){return e[0]+"/"+e[1]},_:function(e){return e[0]+"_"+e[1]},"^":function(e){return e[0]+"^"+e[1]},prime:function(e){return e[0]+"'"},tuple:function(e){return"( "+e.join(", ")+" )"},array:function(e){return"[ "+e.join(", ")+" ]"},list:function(e){return e.join(", ")},set:function(e){return"{ "+e.join(", ")+" }"},vector:function(e){return"( "+e.join(", ")+" )"},altvector:function(e){return"( "+e.join(", ")+" )"},interval:function(e){return"( "+e.join(", ")+" )"},matrix:function(e){return"( "+e.join(", ")+" )"},and:function(e){return e.join(" and ")},or:function(e){return e.join(" or ")},not:function(e){return"not "+e[0]},"=":function(e){return e.join(" = ")},"<":function(e){return e.join(" < ")},">":function(e){return e.join(" > ")},lts:function(e){return e.join(" < ")},gts:function(e){return e.join(" > ")},le:function(e){return e.join(" <= ")},ge:function(e){return e.join(" >= ")},ne:function(e){return e.join(" ne ")},in:function(e){return e[0]+" elementof "+e[1]},notin:function(e){return e[0]+" notelementof "+e[1]},ni:function(e){return e[0]+" containselement "+e[1]},notni:function(e){return e[0]+" notcontainselement "+e[1]},subset:function(e){return e[0]+" subset "+e[1]},subseteq:function(e){return e[0]+" subseteq "+e[1]},notsubset:function(e){return e[0]+" notsubset "+e[1]},notsubseteq:function(e){return e[0]+" notsubseteq "+e[1]},superset:function(e){return e[0]+" superset "+e[1]},superseteq:function(e){return e[0]+" superseteq "+e[1]},notsuperset:function(e){return e[0]+" notsuperset "+e[1]},notsuperseteq:function(e){return e[0]+" notsuperseteq "+e[1]},union:function(e){return e.join(" union ")},intersect:function(e){return e.join(" intersect ")},perp:function(e){return e.join(" perp ")},parallel:function(e){return e.join(" parallel ")},derivative_leibniz:function(e){return"d"+e[0]+"/d"+e[1]},partial_derivative_leibniz:function(e){return"∂"+e[0]+"/∂"+e[1]},"|":function(e){return e[0]+" | "+e[1]},":":function(e){return e[0]+" : "+e[1]},binom:function(e){return"binom( "+e[0]+", "+e[1]+" )"},vec:function(e){return"vec("+e[0]+")"},linesegment:function(e){return"linesegment( "+e.join(", ")+" )"},angle:function(e,t){return t?"angle "+e.join(""):"angle( "+e.join(", ")+" )"},unit:function(e){return e[0]+" "+e[1]}},output_unicodeDefault=!0;class astToText$2{constructor({output_unicode:e=output_unicodeDefault,padToDigits:t=null,padToDecimals:n=null,showBlanks:r=!0}={}){this.output_unicode=e,this.operators=unicode_operators,e||(this.operators=nonunicode_operators),this.padToDigits=t,this.padToDecimals=n,this.showBlanks=r}convert(e){return this.statement(e)}statement(e){if(!Array.isArray(e))return this.single_statement(e);let t=e[0],n=e.slice(1);if("ldots"===t)return"...";if(!(t in this.operators)&&"apply"!==t)throw new Error("Badly formed ast: operator "+t+" not recognized.");return"and"===t||"or"===t?this.operators[t](n.map(function(e,t){let n=this.single_statement(e);return n.match(/ /)&&!n.match(/^\(.*\)$/)?"("+n+")":n}.bind(this))):this.single_statement(e)}single_statement(e){if(!Array.isArray(e))return this.expression(e);let t=e[0],n=e.slice(1);if("not"===t)return this.operators[t](n.map(function(e,t){let n=this.single_statement(e);return n.match(/ /)&&!n.match(/^\(.*\)$/)?"("+n+")":n}.bind(this)));if("="===t||"ne"===t||"<"===t||">"===t||"le"===t||"ge"===t||"in"===t||"notin"===t||"ni"===t||"notni"===t||"subset"===t||"notsubset"===t||"subseteq"===t||"notsubseteq"===t||"superset"===t||"notsuperset"===t||"superseteq"===t||"notsuperseteq"===t)return this.operators[t](n.map(function(e,t){return this.expression(e)}.bind(this)));if("lts"===t||"gts"===t){let e=n[0],r=n[1];if("tuple"!==e[0]||"tuple"!==r[0])throw new Error("Badly formed ast");let a=this.expression(e[1]);for(let n=1;n ":"lts"===t?this.output_unicode?a+=" ≤ ":a+=" <= ":this.output_unicode?a+=" ≥ ":a+=" >= ",a+=this.expression(e[n+1]);return a}return this.expression(e)}expression(e){if(!Array.isArray(e))return this.term(e);let t=e[0],n=e.slice(1);return"+"===t?1===n.length?"+"+this.term(n[0]):this.operators[t](n.map(function(e,t){return t>0?this.termWithPlusIfNotNegated(e):this.term(e)}.bind(this))):["union","intersect","perp","parallel"].includes(t)?this.operators[t](n.map(function(e,t){return this.term(e)}.bind(this))):this.term(e)}term(e){if(!Array.isArray(e))return this.factor(e);let t=e[0],n=e.slice(1);if("-"===t)return this.operators[t](n.map(function(e,t){return this.term(e)}.bind(this)));if("*"===t)return this.operators[t](n.map(function(e,t){let r;return t>0?(r=this.factorWithParenthesesIfNegatedOrExplicitPlus(e),r.match(/^[0-9]/)?"* "+r:"angle"===e[0]&&n.length>1?"( "+r+" )":r):(r=this.factor(e),"angle"===e[0]&&n.length>1?"( "+r+" )":r)}.bind(this)));if("/"===t){let e=this.factor(n[0]),r=this.factor(n[1]);return this.simple_factor_or_function_or_parens(n[0])||(e="("+e+")"),this.simple_factor_or_function_or_parens(n[1])||(r="("+r+")"),this.operators[t]([e,r])}return"unit"===t?this.operators[t](n.map(function(e,t){return this.expression(e)}.bind(this))):this.factor(e)}symbolConvert(e){let t={alpha:"α",beta:"β",Gamma:"Γ",gamma:"γ",Delta:"Δ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",Theta:"ϴ",theta:"θ",iota:"ι",kappa:"κ",Lambda:"Λ",lambda:"λ",mu:"μ",nu:"ν",Xi:"Ξ",xi:"ξ",Pi:"Π",pi:"π",rho:"ρ",Sigma:"Σ",sigma:"σ",tau:"τ",Upsilon:"Υ",upsilon:"υ",Phi:"Φ",phi:"ϕ",Psi:"Ψ",psi:"ψ",Omega:"Ω",omega:"ω",perp:"⟂",int:"∫"};return this.output_unicode&&e in t?t[e]:this.showBlanks||"_"!==e?e:""}simple_factor_or_function_or_parens(e){let t=this.factor(e);return!!(t.length<=1||"string"==typeof e&&e.match(/^\w+$/)||Array.isArray(e)&&"apply"===e[0]||t.match(/^\(.*\)$/)||t.match(/^⟨.*⟩$/))||"number"==typeof e&&e>=0&&!e.toString().includes("e")}factor(e){if("string"==typeof e)return this.symbolConvert(e);if("number"==typeof e){if(e===1/0)return this.output_unicode?"∞":"infinity";if(e===-1/0)return this.output_unicode?"-∞":"-infinity";if(Number.isNaN(e))return"NaN";{let t=e.toString(),n=t.indexOf("e");if(-1===n)return null!==this.padToDigits?t=padNumberStringToDigits(t,this.padToDigits):null!==this.padToDecimals&&(t=padNumberStringToDecimals(t,this.padToDecimals)),t;let r=t.substring(0,n),a=t.substring(n+1);if(null!==this.padToDigits)r=padNumberStringToDigits(r,this.padToDigits);else if(null!==this.padToDecimals){let n=Number(a);if(n>0)return t=e.toLocaleString("fullwide",{useGrouping:!1}),padNumberStringToDecimals(t,this.padToDecimals);r=padNumberStringToDecimals(r,this.padToDecimals+n)}return"+"===a[0]?r+" * 10^"+a.substring(1):r+" * 10^("+a+")"}}if(!Array.isArray(e))return"";let t=e[0],n=e.slice(1);if("^"===t){if(Number.isInteger(n[0])&&Number.isInteger(n[1])){let e;return e=n[0]<0?"("+n[0].toString()+")":n[0].toString(),n[1]<0?e+"^("+n[1].toString()+")":e+"^"+n[1].toString()}let e=this.factor(n[0]),t=n[0];for(;"prime"===t[0];)t=t[1];this.simple_factor_or_function_or_parens(t)||"_"===t[0]&&"string"==typeof t[1]||(e="("+e.toString()+")");let r=this.factor(n[1]);return this.simple_factor_or_function_or_parens(n[1])||(r="("+r.toString()+")"),e+"^"+r}if("_"===t)return this.operators[t](n.map(function(e,t){let n=this.factor(e);return this.simple_factor_or_function_or_parens(e)?n:"("+n+")"}.bind(this)));if("prime"===t){let e=n[0],t=1;for(;"prime"===e[0];)t+=1,e=e[1];let r=this.factor(e);this.simple_factor_or_function_or_parens(e)||"_"===e[0]&&"string"==typeof e[1]||(r="("+r+")");for(let e=0;e1&&(o=o+"^"+i),o=o+this.symbolConvert(s)+"/";let l=1;Array.isArray(a)&&(l=a.length-1);for(let t=1;t<=l;t++){let n=a[t],r=1,i="";Array.isArray(n)?(i=n[1],r=n[2]):i=n,o=o+e+this.symbolConvert(i),r>1&&(o=o+"^"+r)}return o}if("apply"===t){if("abs"===n[0])return"|"+this.statement(n[1])+"|";if("factorial"===n[0]){let e=this.factor(n[1]);return this.simple_factor_or_function_or_parens(n[1])||"_"===n[1][0]&&"string"==typeof n[1][1]?e+"!":"("+e+")!"}let e=n[0];if("^"===e[0]&&(e=e[1]),"_"===e[0]&&(e=e[1]),"int"===e){let e,t=this.factor(n[0]),r=n[1];if(Array.isArray(r)&&"*"===r[0]){let t=[],n=["*"];for(let e=1;e0&&(e+=" "+t.map((e=>"d"+this.factor(e[1]))).join(" "))}return e||(e=this.term(n[1])),t+" "+e}let t=this.factor(n[0]),r=this.statement(n[1]);return"tuple"!==n[1][0]&&(r="("+r+")"),t+r}if("angle"===t){let e=n.every((e=>{if("string"==typeof e&&1===e.length)return!0;if(!Array.isArray(e))return!1;let t=e[0];return"_"===t||"^"===t||"prime"===t}));return this.operators[t](n.map(function(e,t){return this.statement(e)}.bind(this)),e)}return"+"===t&&2===e.length?"+ "+this.factor(e[1]):"("+this.statement(e)+")"}factorWithParenthesesIfNegatedOrExplicitPlus(e){var t=this.factor(e);return t.match(/^-/)||t.match(/^\+/)?"("+t+")":t}termWithPlusIfNotNegated(e){let t=this.term(e);return t.match(/^-/)?t.match(/^-[^ ]/)?"- "+t.slice(1):t:"+ "+t}}var astToText$1=new astToText$2;function subscripts_to_strings(e,t=!1){var n=get_tree(e);if(!Array.isArray(n))return n;let r=n[0],a=n.slice(1);return"_"===r&&(t||a.every((e=>["number","string"].includes(typeof e))))?astToText$1.convert(n):[r].concat(a.map((e=>subscripts_to_strings(e,t))))}function strings_to_subscripts(e){var t=get_tree(e);if("string"==typeof t){let e=t.match(/^([0-9a-zA-Z]+)_([a-zA-Z]+|[0-9]+)$/);if(e){let t=Number(e[1]);isNaN(t)&&(t=e[1]);let n=Number(e[2]);return isNaN(n)&&(n=e[2]),["_",t,n]}return t}if(!Array.isArray(t))return t;let n=t[0],r=t.slice(1);return[n].concat(r.map(strings_to_subscripts))}var normalization=Object.freeze({__proto__:null,normalize_function_names:normalize_function_names,normalize_applied_functions:normalize_applied_functions,log_subscript_to_two_arg_log:log_subscript_to_two_arg_log,substitute_abs:substitute_abs,default_order:default_order,constants_to_floats:constants_to_floats,normalize_angle_linesegment_arg_order:normalize_angle_linesegment_arg_order,tuples_to_vectors:tuples_to_vectors,to_intervals:to_intervals,altvectors_to_vectors:altvectors_to_vectors,subscripts_to_strings:subscripts_to_strings,strings_to_subscripts:strings_to_subscripts}),astToText=new astToText$2;function generate_random_integer(e,t,n){return e=math$1.ceil(e),t=math$1.floor(t),math$1.floor(n()*(t-e+1))+e}const equals$5=function({expr:e,other:t,randomBindings:n,expr_context:r,other_context:a,relative_tolerance:i=1e-12,absolute_tolerance:s=0,tolerance_for_zero:o=1e-15,allowed_error_in_numbers:l=0,include_error_in_number_exponents:u=!1,allowed_error_is_absolute:c=!1,rng:p}){if(Array.isArray(e.tree)&&Array.isArray(t.tree)){let d=e.tree[0],m=e.tree.slice(1),h=t.tree[0],f=t.tree.slice(1);if("tuple"===d||"vector"===d||"altvector"===d||"list"===d||"array"===d||"matrix"===d||"interval"===d){if(h!==d)return!1;if(f.length!==m.length)return!1;for(let e=0;e","<","ge","le"].includes(d)){if(2!==f.length)return!1;if(">"===d?(d="<",m=[m[1],m[0]]):"ge"===d&&(d="le",m=[m[1],m[0]]),">"===h?(h="<",f=[f[1],f[0]]):"ge"===h&&(h="le",f=[f[1],f[0]]),d!==h)return!1;let e=["+",m[0],["-",m[1]]],t=["+",f[0],["-",f[1]]],y="="!==d;return component_equals({expr:r.fromAst(e),other:a.fromAst(t),randomBindings:n,expr_context:r,other_context:a,allow_proportional:!0,require_positive_proportion:y,relative_tolerance:i,absolute_tolerance:s,tolerance_for_zero:o,allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,rng:p})}}return component_equals({expr:e,other:t,randomBindings:n,expr_context:r,other_context:a,relative_tolerance:i,absolute_tolerance:s,tolerance_for_zero:o,allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,rng:p})},component_equals=function({expr:e,other:t,randomBindings:n,expr_context:r,other_context:a,allow_proportional:i=!1,require_positive_proportion:s=!1,relative_tolerance:o,absolute_tolerance:l,tolerance_for_zero:u,allowed_error_in_numbers:c,include_error_in_number_exponents:p,allowed_error_is_absolute:d,rng:m}){var h=1e-20*Number.MAX_VALUE;e=e.normalize_function_names(),t=t.normalize_function_names(),e=e.log_subscript_to_two_arg_log(),t=t.log_subscript_to_two_arg_log(),e=e.subscripts_to_strings(),t=t.subscripts_to_strings(),e=e.normalize_applied_functions(),t=t.normalize_applied_functions();let f=rename_functions_with_exponents(e.tree),y=rename_functions_with_exponents(t.tree);e=r.fromAst(rename_vecs(f)),t=a.fromAst(rename_vecs(y));var g=[...new Set([...e.variables(),...t.variables()])];math$1.define_pi&&(g=g.filter((function(e){return"pi"!==e}))),math$1.define_i&&(g=g.filter((function(e){return"i"!==e}))),math$1.define_e&&(g=g.filter((function(e){return"e"!==e})));var b=[];for(let e=0;e1===e.length||e.includes("_")||e.includes("^"))),N=v.filter((e=>g.includes(e)));if(v=v.filter((e=>!g.includes(e))),N.length>0){let n=e.tree,i=t.tree,s="x1";for(;[...v,...g].includes(s);)s+="x1";let o="x2";for(;[...v,...g].includes(o);)o+="x2";for(let e of N){let t=e+e;for(;[...v,...g].includes(t);)t+=e;let r=[[["apply",e,s],["apply",t,s],{variables:{[s]:!0}}]];n=applyAllTransformations(n,r),i=applyAllTransformations(i,r),v.push(t)}e=r.fromAst(n),t=a.fromAst(i)}try{var T=e.f(),C=t.f()}catch(n){return e.equalsViaSyntax(t,{allow_blanks:!0})}let A,V,x;if(c>0){let t=replace_numbers_with_parameters({expr:e,variables:g,include_exponents:p});A=r.fromAst(t.expr_with_params),V=t.parameters;let n=Object.keys(V);if(n.length>0){let t=A.derivative(n[0]);if(d||(t=t.multiply(V[n[0]])),n.length>1)for(let e of n.slice(1)){let n=A.derivative(e);d||(n=n.multiply(V[e])),t=t.add(n)}let r=t.multiply(c);try{x=r.f()}catch(e){}}}var S=[10,1,100,.1,1e3,.01],w=0;let E=0,D=!0,O=0;for(let t=0;t<1e3;t++){try{var I=R(S[w],m)}catch(e){continue}if(!1===I.always_zero&&(D=!1),!I.equal&&!I.out_of_bounds&&!I.always_zero&&!1!==I.sufficient_finite_values&&(O++,O>100))return!1;if(I.equal){if(I.always_zero){if(!D)continue;if(E+=1,E>5&&(w+=1,E=0),w>=S.length)return!0;continue}return!0}}return!1;function R(e,t){var r,a=n(t,g,e);for(let e=0;e0)||!(0===m||m>0))return{out_of_bounds:!0,always_zero:!1};var f=Math.min(d,m),y=Math.max(d,m),N=1;let A=0;if(x){try{A=math$1.abs(x(r))}catch(e){return{equal_at_start:!1,always_zero:!1}}if(!Number.isFinite(A))return{equal_at_start:!1,always_zero:!1}}if(A+=f*o,A=Math.min(A,.1*f),A+=0!==A||0!==c&&0!==p?l:u,!(0===y||math$1.abs(math$1.subtract(c,p))0))return{equal_at_start:!1,always_zero:!1}}var S=0===y,w=0;for(let r=0;r<100;r++){var E,D=n(t,g,.01,a);for(let e=0;e=10)return{equal:!0,always_zero:S}}}return{sufficient_finite_values:!1,always_zero:S}}};function replace_numbers_with_parameters({expr:e,variables:t,include_exponents:n=!1}){let r={},a=0;function i(){a++;let e="par"+a;for(;t.includes(e);)a++,e="par"+a;return e}return{expr_with_params:function e(t){if("number"==typeof t){if(0===t)return t;{let e=i();return r[e]=t,e}}if("string"==typeof t){if("pi"===t){if(math$1.define_pi){let e=i();return r[e]=math$1.PI,e}}else if("e"===t&&math$1.define_e){let e=i();return r[e]=math$1.e,e}return t}if(!Array.isArray(t))return t;let a=t[0],s=t.slice(1);return"^"!==a||n?[a,...s.map(e)]:[a,e(s[0]),s[1]]}((e=e.evaluate_numbers({max_digits:1/0})).tree),parameters:r}}function rename_functions_with_exponents(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);if("apply"===t){let e=n[0];return Array.isArray(e)&&"^"===e[0]&&e.slice(1).every((e=>["number","string"].includes(typeof e)))&&(e=astToText.convert(e)),["apply",e,n[1]]}return[t,...n.map(rename_functions_with_exponents)]}function rename_vecs(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);return"vec"===t&&1===n.length?"__vec_"+astToText.convert(n[0]):[t,...n.map(rename_vecs)]}function randomComplexBindings(e,t,n,r){var a={};return void 0===r?t.forEach((function(t){a[t]=math$1.complex(2*e()*n-n,2*e()*n-n)})):t.forEach((function(t){a[t]=math$1.complex(r[t].re+2*e()*n-n,r[t].im+2*e()*n-n)})),a}const equals$4=function(e,t,{relative_tolerance:n=1e-12,absolute_tolerance:r=0,tolerance_for_zero:a=1e-15,allowed_error_in_numbers:i=0,include_error_in_number_exponents:s=!1,allowed_error_is_absolute:o=!1,allow_blanks:l=!1}={}){if(!l&&(e.variables().includes("_")||t.variables().includes("_")))return!1;let u=seedrandom$1("complex_seed");return e=e.remove_scaling_units(),t=t.remove_scaling_units(),!(!e.isAnalytic({allow_abs:!0,allow_arg:!0,allow_relation:!0})||!t.isAnalytic({allow_abs:!0,allow_arg:!0,allow_relation:!0}))&&equals$5({expr:e,other:t,randomBindings:randomComplexBindings,expr_context:e.context,other_context:t.context,relative_tolerance:n,absolute_tolerance:r,tolerance_for_zero:a,allowed_error_in_numbers:i,include_error_in_number_exponents:s,allowed_error_is_absolute:o,rng:u})};function randomRealBindings(e,t,n,r){var a={};return void 0===r?t.forEach((function(t){a[t]=2*e()*n-n})):t.forEach((function(t){a[t]=r[t]+2*e()*n-n})),a}const equals$3=function(e,t,{relative_tolerance:n=1e-12,absolute_tolerance:r=0,tolerance_for_zero:a=1e-15,allowed_error_in_numbers:i=0,include_error_in_number_exponents:s=!1,allowed_error_is_absolute:o=!1}={}){if(!e.isAnalytic()||!t.isAnalytic())return!1;let l=seedrandom("real_seed");return equals$5({expr:e,other:t,randomBindings:randomRealBindings,expr_context:e.context,other_content:t.context,relative_tolerance:n,absolute_tolerance:r,tolerance_for_zero:a,allowed_error_in_numbers:i,include_error_in_number_exponents:s,allowed_error_is_absolute:o,rng:l})},equals$2=function(e,t,{allowed_error_in_numbers:n=0,include_error_in_number_exponents:r=!1,allowed_error_is_absolute:a=!1,allow_blanks:i=!1}={}){if(!i&&(e.variables().includes("_")||t.variables().includes("_")))return!1;let s=e.normalize_function_names().normalize_applied_functions().normalize_angle_linesegment_arg_order(),o=t.normalize_function_names().normalize_applied_functions().normalize_angle_linesegment_arg_order();return equal(s.tree,o.tree,{allowed_error_in_numbers:n,include_error_in_number_exponents:r,allowed_error_is_absolute:a})},equals$1=function(e,t,{min_elements_match:n=3,match_partial:r=!1}={}){if(!is_discrete_infinite_set(e))return!1;if(is_discrete_infinite_set(t)){var a=[];let n=e.context.get_assumptions(e);if(void 0!==n&&a.push(n),n=t.context.get_assumptions(t),void 0!==n&&a.push(n),a=0===a.length?void 0:1===a.length?a[0]:clean_assumptions(["and"].concat(a)),r){let n=contained_in(e.tree,t.tree,a,r);if(!1===n)return 0;let i=contained_in(t.tree,e.tree,a,r);return!1===i?0:!0===n?!0===i?1:i:!0===i?n:Math.min(n,i)}return contained_in(e.tree,t.tree,a,r)&&contained_in(t.tree,e.tree,a,r)}{let r=t.tree;if("list"!==r[0])return!1;let a=r.length-2;if("ldots"!==r[a+1][0])return!1;if(acontained_in(e,t,n)))}var a=e[1],i=e[2],s=e[3],o=e[4];if(!Array.isArray(s)||"-"!==s[0]||s[1]!==1/0||o!==1/0)return!1;a=simplify(["/",a,i],n,1/0);var l=t.slice(1),u=[];for(let e=0;ee[0])))];let p=0;for(let e of c){let t=u.map((function(t,n){let r=e/t[0];return Number.isInteger(r)?[t[0],r,n]:void 0})).filter((e=>e)),i=[];for(let r of t){let t=r[0],s=r[1],o=r[2],l=u[o][2],c=u[o][3];for(let r=0;rp&&(p=t)}}return!!(r&&p>0)&&p}function sequence_from_discrete_infinite(e,t){var n=e.tree.slice(1);if(n.length>1)return;let r=n[0][1],a=n[0][2],i=evaluate_numbers(n[0][3]),s=n[0][4];if(!Number.isInteger(i)||s!==1/0)return;let o=[];for(let e=0;e0))throw Error(`Have not implemented equality check with ${r} sign errors.`);if(r>1){let e=n;n=function(t,n){return equalSpecifiedSignErrors(t,n,{equalityFunction:e,n_sign_errors:r-1})}}var a,i,s=e.tree,o=[[s]],l=0;e.tree=["-",s];var u=n(e,t);if(e.tree=s,u)return!0;for(;a=o[l++];)if(a=a[0],Array.isArray(a))for(i=1;i"];function isAnalytic(e,{allow_abs:t=!1,allow_arg:n=!1,allow_relation:r=!1}={}){var a=normalize_applied_functions(normalize_function_names(e)),i=operators$3(a=subscripts_to_strings(a));for(let e=0;e+
")},"-":function(e){return"-"+e.join("-")+""},"*":function(e){return e.join('\\cdot*')},"/":function(e){return astToGuppy$1.dfrac(e[0],e[1])},"^":function(e){return astToGuppy$1.power(e[0],e[1])},sin:function(e){return astToGuppy$1.trig("sin",e[0])},cos:function(e){return astToGuppy$1.trig("cos",e[0])},tan:function(e){return astToGuppy$1.trig("tan",e[0])},arcsin:function(e){return astToGuppy$1.trig("arcsin",e[0])},arccos:function(e){return astToGuppy$1.trig("arccos",e[0])},arctan:function(e){return astToGuppy$1.trig("arctan",e[0])},arccsc:function(e){return astToGuppy$1.trig("arccsc",e[0])},arcsec:function(e){return astToGuppy$1.trig("arcsec",e[0])},arccot:function(e){return astToGuppy$1.trig("arccot",e[0])},csc:function(e){return astToGuppy$1.trig("csc",e[0])},sec:function(e){return astToGuppy$1.trig("sec",e[0])},cot:function(e){return astToGuppy$1.trig("cot",e[0])},log:function(e){return astToGuppy$1.trig("log",e[0])},exp:function(e){return astToGuppy$1.trig("exp",e[0])},ln:function(e){return astToGuppy$1.trig("ln",e[0])},sqrt:function(e){return astToGuppy$1.sqrt(e[0])},abs:function(e){return astToGuppy$1.abs(e[0])}}}static dfrac(e,t){return'\\dfrac{}{}\\frac{}{}()/()'+e+''+t+""}static trig(e,t){return'\\'+e+'\\left(\\right) '+e+'()'+t+""}static sqrt(e){return'\\sqrt{}sqrt()'+e+""}static power(e,t){return'{}^{}()^()'+e+''+t+""}static abs(e){return'\\left|\\right|abs()'+e+""}static paren(e){return'\\left(\\right)()'+e+""}static isFunctionSymbol(e){return-1!==["sin","cos","tan","csc","sec","cot","arcsin","arccos","arctan","arccsc","arcsec","arccot","log","ln","exp","sqrt","abs","this.factorial"].indexOf(e)}static isGreekLetterSymbol(e){return-1!==["pi","theta","theta","Theta","alpha","nu","beta","xi","Xi","gamma","Gamma","delta","Delta","pi","Pi","epsilon","epsilon","rho","rho","zeta","sigma","Sigma","eta","tau","upsilon","Upsilon","iota","phi","phi","Phi","kappa","chi","lambda","Lambda","psi","Psi","omega","Omega"].indexOf(e)}factorWithParenthesesIfNegated(e){var t=this.factor(e);return t.toString().match(/^-/)?astToGuppy$1.paren(t.toString()):t}factor(e){if("string"==typeof e)return astToGuppy$1.isGreekLetterSymbol(e)?'\\'+e+' $'+e+"":""+e+"";if("number"==typeof e)return""+e+"";if(!Array.isArray(e))return"";var t=e[0],n=e.slice(1);return"apply"===t&&(t=e[1],n=e.slice(2)),"abs"===t?this.operators[t](n.map(function(e,t){return this.expression(e)}.bind(this))):astToGuppy$1.isFunctionSymbol(t)?"this.factorial"!==t||1!==n[0].toString().length&&!n[0].toString().match(/^[0-9]*$/)?this.operators[t](n.map(function(e,t){return this.factor(e)}.bind(this))):this.operators[t](n):"^"===t||"~"===t?this.operators[t](n.map(function(e,t){return this.factor(e)}.bind(this))):astToGuppy$1.paren(this.expression(e))}term(e){if(!Array.isArray(e))return this.factor(e);var t=e[0],n=e.slice(1);return"*"===t?this.operators[t](n.map(function(e,t){var n=this.factorWithParenthesesIfNegated(e);return n.toString().match(/^[0-9]/)&&t>0?" * "+n:n}.bind(this))):"/"===t?this.operators[t](n.map(function(e,t){return this.factor(e)}.bind(this))):this.factor(e)}expression(e){if(!Array.isArray(e))return this.term(e);var t=e[0],n=e.slice(1);return"+"===t||"-"===t?this.operators[t](n.map(function(e,t){return this.factorWithParenthesesIfNegated(e)}.bind(this))):this.term(e)}convert(e){return(""+this.expression(e)+"").replace(/<\/e>/g,"")}}const glslOperators={"+":function(e){var t=e[0];return e.slice(1).forEach((function(e){t=t+"+"+e})),t},"-":function(e){var t="-"+e[0];return e.slice(1).forEach((function(e){t=t+"-"+e})),t},"~":function(e){var t="vec2(0.0,0.0)";return e.forEach((function(e){t=t+"-"+e})),t},"*":function(e){var t=e[0];return e.slice(1).forEach((function(e){t="cmul("+t+","+e+")"})),t},"/":function(e){var t=e[0];return e.slice(1).forEach((function(e){t="cdiv("+t+","+e+")"})),t},sin:function(e){return"csin("+e[0]+")"},cos:function(e){return"ccos("+e[0]+")"},tan:function(e){return"ctan("+e[0]+")"},sinh:function(e){return"csinh("+e[0]+")"},cosh:function(e){return"ccosh("+e[0]+")"},arcsin:function(e){return"carcsin("+e[0]+")"},arccos:function(e){return"carccos("+e[0]+")"},arctan:function(e){return"carctan("+e[0]+")"},arccsc:function(e){return"carcsin(cdiv(vec2(1.0,0),"+e[0]+"))"},arcsec:function(e){return"carccos(cdiv(vec2(1.0,0),"+e[0]+"))"},arccot:function(e){return"carctan(cdiv(vec2(1.0,0),"+e[0]+"))"},csc:function(e){return"ccsc("+e[0]+")"},sec:function(e){return"csec("+e[0]+")"},cot:function(e){return"ccot("+e[0]+")"},exp:function(e){return"cexp("+e[0]+")"},conj:function(e){return"conjugate("+e[0]+")"},sqrt:function(e){return"cpower("+e[0]+",vec2(0.5,0.0))"},log:function(e){return"clog("+e[0]+")"},ln:function(e){return"clog("+e[0]+")"},"^":function(e){return"cpower("+e[0]+","+e[1]+")"},abs:function(e){return"cabs("+e[0]+")"},apply:function(e){return"vec2(NaN,NaN)"}};class astToGLSL$1{constructor(){}convert(e){if("boolean"==typeof e)throw Error("no support for boolean");if("string"==typeof e)return"e"===e?"vec2(2.71828182845905,0.0)":"pi"===e?"vec2(3.14159265358979,0.0)":"i"===e?"vec2(0.0,1.0)":String(e);if("number"==typeof e)return"vec2("+String(e)+",0.0)";if("real"in e&&"imaginary"in e)return e;if(!Array.isArray(e))throw Error("Invalid ast");var t=e[0],n=e.slice(1);if("apply"===t){if("string"!=typeof n[0])throw Error("Non string functions not implemented for conversion to GLSL");return t=n[0],n=n.slice(1),glslOperators[t](n.map(function(e,t){return this.convert(e)}.bind(this)))}if(t in glslOperators)return glslOperators[t](n.map(function(e,t){return this.convert(e)}.bind(this)));throw Error("Operator "+t+" not implemented for conversion to mathjs")}}var astToGuppy=new astToGuppy$1,astToGLSL=new astToGLSL$1;const tex=function(e,t){return new astToLatex$1(t).convert(e.tree)},toLatex=tex,toString=function(e,t){return new astToText$2(t).convert(e.tree)},toGLSL=function(e){return astToGLSL.convert(e.tree)},toXML=function(e){return astToGuppy.convert(e.tree)};var printing=Object.freeze({__proto__:null,tex:tex,toLatex:toLatex,toString:toString,toXML:toXML,toGLSL:toGLSL});const integrateNumerically=function(e,t,n,r){for(var a=0,i={},s=0;s<100;s++){var o=n+(r-n)*(s+.5)/100;i[t]=o,a+=e.evaluate(i)}return a*(r-n)/100};var integration=Object.freeze({__proto__:null,integrateNumerically:integrateNumerically});function expression_to_polynomial(e){var t=get_tree(e);if("string"==typeof t)return"pi"===t&&math$1.define_pi||"i"===t&&math$1.define_i||"e"===t&&math$1.define_e?t:["polynomial",t,[[1,1]]];if("number"==typeof t)return t;let n=evaluate_to_constant(t,!1);if(null!==n&&Number.isFinite(n))return simplify(t);if(!Array.isArray(t))return!1;if(!operators$3(t).every((e=>["+","-","*","^","/","_","prime"].includes(e))))return!1;var r=t[0],a=t.slice(1);if("+"===r){let e=a.map(expression_to_polynomial);return!!e.every((e=>!1!==e))&&e.reduce(((e,t)=>polynomial_add(e,t)))}if("-"===r){let e=expression_to_polynomial(a[0]);return!!e&&polynomial_neg(e)}if("*"===r){let e=a.map(expression_to_polynomial);return!!e.every((e=>!1!==e))&&e.reduce(((e,t)=>polynomial_mul(e,t)))}if("^"===r){let e=a[0],n=expression_to_polynomial(e);if(!1===n)return!1;let r=simplify(a[1]);if("number"!=typeof r||r<0||!Number.isInteger(r)){let n=evaluate_to_constant(r,!1);if(null!==n||Number.isFinite(n)){let t=math$1.fraction(n);if(t.d<=100){e=t.s<0?["^",e,["/",-1,t.d]]:["^",e,["/",1,t.d]];var i=["polynomial",simplify(e),[]];return i[2].push([t.n,1]),i}}return["polynomial",t,[[1,1]]]}return 0===r?1:1===r?n:polynomial_pow(n,r)}if("/"===r){var s=a[1],o=evaluate_to_constant(s,!1);return null!==o&&Number.isFinite(o)?polynomial_mul(expression_to_polynomial(a[0]),["/",1,o]):["polynomial",t,[[1,1]]]}return["polynomial",t,[[1,1]]]}function polynomials_in_same_leading_variable(e,t){return e[1]!==t[1]&&(compare_function(e[1],t[1])<0?t=["polynomial",e[1],[[0,t]]]:e=["polynomial",t[1],[[0,e]]]),[e,t]}function polynomial_add(e,t){if("polynomial"!==e[0]){if("polynomial"!==t[0])return simplify(["+",e,t]);e=["polynomial",t[1],[[0,e]]]}else if("polynomial"!==t[0])t=["polynomial",e[1],[[0,t]]];else{let n=polynomials_in_same_leading_variable(e,t);e=n[0],t=n[1]}let n=["polynomial",e[1],[]],r=e[2],a=t[2],i=n[2],s=r.length,o=a.length,l=0,u=0;for(;l0;)1&t&&(n=polynomial_mul(n,e)),e=polynomial_mul(e,e),t>>=1;return n}function polynomial_to_expression(e){if(!Array.isArray(e)||"polynomial"!==e[0])return e;let t=e[1],n=e[2],r=[],a=n.length;for(var i=0;ir[o][1])return!1}return a!==i&&s!==i}function mono_gcd(e,t){if(!Array.isArray(e)||!Array.isArray(t)||"monomial"!==e[0]||"monomial"!==t[0])return 1;let n=e[2],r=t[2],a=[],i=n.length,s=r.length,o=0,l=0;for(;o=0;){var r=[];r.push([e[2][t][1],n]),n=["polynomial",e[2][t][0],r],t-=1}return n}function max_div_init(e,t){if(0===e)return 0;let n=e,r=[];for(;Array.isArray(n)&&"polynomial"===n[0];){let e=n[1],t=n[2],a=t[t.length-1][0];n=t[t.length-1][1],r.push([e,a])}let a=["monomial",n,r],i=t.length;for(var o=0;o0?choice_lowest_degree(i):0}function update_hij_table(e,t,n){let r=t.length;t.push(n);let a=0,i=1,o=[];for(;i0?choice_lowest_degree(o):0}function choice_lowest_degree(e){let t=[],n=e.length;for(a=0;a=0;){var r=[];r.push([e[2][t][1],n]),n=["polynomial",e[2][t][0],r],t-=1}return n}function max_div_init(e,t){if(0===e)return 0;let n=e,r=[];for(;Array.isArray(n)&&"polynomial"===n[0];){let e=n[1],t=n[2],a=t[t.length-1][0];n=t[t.length-1][1],r.push([e,a])}let a=["monomial",n,r],i=t.length;for(var s=0;s0?choice_lowest_degree(i):0}function update_hij_table(e,t,n){let r=t.length;t.push(n);let a=0,i=1,s=[];for(;i0?choice_lowest_degree(s):0}function choice_lowest_degree(e){let t=[],n=e.length;for(a=0;a15?n:(t=Math.round(t),round_numbers_to_precision_sub(n,t))}const round_numbers_to_precision_sub=function(e,t=14){if("number"==typeof e&&Number.isFinite(e)&&0!==e){const n=math$1.floor(math$1.log10(math$1.abs(e))),r=t-n-1;return r<0?parseFloat(toFixed(e,r)+"0".repeat(math$1.abs(r))):parseFloat(toFixed(e,r))}return Array.isArray(e)?[e[0],...e.slice(1).map((e=>round_numbers_to_precision_sub(e,t)))]:e};function round_numbers_to_decimals(e,t=14){var n=get_tree(e);if(!Number.isFinite(t))throw Error("For round_numbers_to_decimals, ndecimals must be a number");return t=Math.round(t),t=Math.max(-330,Math.min(330,t)),round_numbers_to_decimals_sub(n,t)}const round_numbers_to_decimals_sub=function(e,t=0){return"number"==typeof e?t<0?parseFloat(toFixed(e,t)+"0".repeat(math$1.abs(t))):parseFloat(toFixed(e,t)):Array.isArray(e)?[e[0],...e.slice(1).map((e=>round_numbers_to_decimals_sub(e,t)))]:e};var round=Object.freeze({__proto__:null,round_numbers_to_precision:round_numbers_to_precision,round_numbers_to_decimals:round_numbers_to_decimals});const match=function(e,t,n){let r=get_tree(e),a=get_tree(t);return match$2(r,a,n)};var match$1=Object.freeze({__proto__:null,match:match});const expression_to_tree$1=[simplify$1,differentiation,normalization,arithmetic,transformation,solve,sets,matrix$1,rational,round],expression_to_other=[variables$1,printing,equality,integration,evaluation,analytic,sign_error,match$1];function abs(e){return["apply","abs",get_tree(e)]}function exp(e){return["apply","exp",get_tree(e)]}function log(e){return["apply","log",get_tree(e)]}function log10(e){return["apply","log10",get_tree(e)]}function sign(e){return["apply","sign",get_tree(e)]}function sqrt(e){return["apply","sqrt",get_tree(e)]}function conj(e){return["apply","conj",get_tree(e)]}function im(e){return["apply","im",get_tree(e)]}function re(e){return["apply","re",get_tree(e)]}function factorial(e){return["apply","factorial",get_tree(e)]}function gamma(e){return["apply","gamma",get_tree(e)]}function erf(e){return["apply","erf",get_tree(e)]}function acos(e){return["apply","acos",get_tree(e)]}function acosh(e){return["apply","acosh",get_tree(e)]}function acot(e){return["apply","acot",get_tree(e)]}function acoth(e){return["apply","acoth",get_tree(e)]}function acsc(e){return["apply","acsc",get_tree(e)]}function acsch(e){return["apply","acsch",get_tree(e)]}function asec(e){return["apply","asec",get_tree(e)]}function asech(e){return["apply","asech",get_tree(e)]}function asin(e){return["apply","asin",get_tree(e)]}function asinh(e){return["apply","asinh",get_tree(e)]}function atan(e){return["apply","atan",get_tree(e)]}function atanh(e){return["apply","atanh",get_tree(e)]}function cos(e){return["apply","cos",get_tree(e)]}function cosh(e){return["apply","cosh",get_tree(e)]}function cot(e){return["apply","cot",get_tree(e)]}function coth(e){return["apply","coth",get_tree(e)]}function csc(e){return["apply","csc",get_tree(e)]}function csch(e){return["apply","csch",get_tree(e)]}function sec(e){return["apply","sec",get_tree(e)]}function sech(e){return["apply","sech",get_tree(e)]}function sin(e){return["apply","sin",get_tree(e)]}function sinh(e){return["apply","sinh",get_tree(e)]}function tan(e){return["apply","tan",get_tree(e)]}function tanh(e){return["apply","tanh",get_tree(e)]}function atan2(e,t){return["apply","atan2",["tuple",get_tree(e),get_tree(t)]]}var standard=Object.freeze({__proto__:null,abs:abs,exp:exp,log:log,log10:log10,sign:sign,sqrt:sqrt,conj:conj,im:im,re:re,factorial:factorial,gamma:gamma,erf:erf,acos:acos,acosh:acosh,acot:acot,acoth:acoth,acsc:acsc,acsch:acsch,asec:asec,asech:asech,asin:asin,asinh:asinh,atan:atan,atanh:atanh,cos:cos,cosh:cosh,cot:cot,coth:coth,csc:csc,csch:csch,sec:sec,sech:sech,sin:sin,sinh:sinh,tan:tan,tanh:tanh,atan2:atan2});const expression_to_tree=[standard],whitespace_rule="\\s|\\\\,|\\\\!|\\\\ |\\\\>|\\\\;|\\\\:|\\\\quad\\b|\\\\qquad\\b",sci_notat_exp_regex="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))?",number_rules_sci=[["[0-9]+(\\.[0-9]*)?"+sci_notat_exp_regex,"NUMBER"],["\\.[0-9]+"+sci_notat_exp_regex,"NUMBER"]],number_rules_non_sci=[["[0-9]+(\\.[0-9]*)?","NUMBER"],["\\.[0-9]+","NUMBER"]],base_latex_rules=[["\\*","*"],["\\/","/"],["-","-"],["\\+","+"],["\\^","^"],["\\(","("],["\\\\left\\s*\\(","("],["\\\\bigl\\s*\\(","("],["\\\\Bigl\\s*\\(","("],["\\\\biggl\\s*\\(","("],["\\\\Biggl\\s*\\(","("],["\\)",")"],["\\\\right\\s*\\)",")"],["\\\\bigr\\s*\\)",")"],["\\\\Bigr\\s*\\)",")"],["\\\\biggr\\s*\\)",")"],["\\\\Biggr\\s*\\)",")"],["\\[","["],["\\\\left\\s*\\[","["],["\\\\bigl\\s*\\[","["],["\\\\Bigl\\s*\\[","["],["\\\\biggl\\s*\\[","["],["\\\\Biggl\\s*\\[","["],["\\]","]"],["\\\\right\\s*\\]","]"],["\\\\bigr\\s*\\]","]"],["\\\\Bigr\\s*\\]","]"],["\\\\biggr\\s*\\]","]"],["\\\\Biggr\\s*\\]","]"],["\\|","|"],["\\\\left\\s*\\|","|L"],["\\\\bigl\\s*\\|","|L"],["\\\\Bigl\\s*\\|","|L"],["\\\\biggl\\s*\\|","|L"],["\\\\Biggl\\s*\\|","|L"],["\\\\right\\s*\\|","|"],["\\\\bigr\\s*\\|","|"],["\\\\Bigr\\s*\\|","|"],["\\\\biggr\\s*\\|","|"],["\\\\Biggr\\s*\\|","|"],["\\\\big\\s*\\|","|"],["\\\\Big\\s*\\|","|"],["\\\\bigg\\s*\\|","|"],["\\\\Bigg\\s*\\|","|"],["{","{"],["}","}"],["\\\\{","LBRACE"],["\\\\left\\s*\\\\{","LBRACE"],["\\\\bigl\\s*\\\\{","LBRACE"],["\\\\Bigl\\s*\\\\{","LBRACE"],["\\\\biggl\\s*\\\\{","LBRACE"],["\\\\Biggl\\s*\\\\{","LBRACE"],["\\\\}","RBRACE"],["\\\\right\\s*\\\\}","RBRACE"],["\\\\bigr\\s*\\\\}","RBRACE"],["\\\\Bigr\\s*\\\\}","RBRACE"],["\\\\biggr\\s*\\\\}","RBRACE"],["\\\\Biggr\\s*\\\\}","RBRACE"],["\\\\cdot(?![a-zA-Z])","*"],["\\\\div(?![a-zA-Z])","/"],["\\\\times(?![a-zA-Z])","*"],["\\\\frac(?![a-zA-Z])","FRAC"],[",",","],[":",":"],["\\\\mid","MID"],["\\\\vartheta(?![a-zA-Z])","LATEXCOMMAND","\\theta"],["\\\\varepsilon(?![a-zA-Z])","LATEXCOMMAND","\\epsilon"],["\\\\varrho(?![a-zA-Z])","LATEXCOMMAND","\\rho"],["\\\\varphi(?![a-zA-Z])","LATEXCOMMAND","\\phi"],["\\\\infty(?![a-zA-Z])","INFINITY"],["\\\\asin(?![a-zA-Z])","LATEXCOMMAND","\\arcsin"],["\\\\acos(?![a-zA-Z])","LATEXCOMMAND","\\arccos"],["\\\\atan(?![a-zA-Z])","LATEXCOMMAND","\\arctan"],["\\\\sqrt(?![a-zA-Z])","SQRT"],["\\\\land(?![a-zA-Z])","AND"],["\\\\wedge(?![a-zA-Z])","AND"],["\\\\lor(?![a-zA-Z])","OR"],["\\\\vee(?![a-zA-Z])","OR"],["\\\\lnot(?![a-zA-Z])","NOT"],["=","="],["\\\\neq(?![a-zA-Z])","NE"],["\\\\ne(?![a-zA-Z])","NE"],["\\\\not\\s*=","NE"],["\\\\leq(?![a-zA-Z])","LE"],["\\\\le(?![a-zA-Z])","LE"],["\\\\geq(?![a-zA-Z])","GE"],["\\\\ge(?![a-zA-Z])","GE"],["<","<"],["\\\\lt(?![a-zA-Z])","<"],[">",">"],["\\\\gt(?![a-zA-Z])",">"],["\\\\in(?![a-zA-Z])","IN"],["\\\\notin(?![a-zA-Z])","NOTIN"],["\\\\not\\s*\\\\in(?![a-zA-Z])","NOTIN"],["\\\\ni(?![a-zA-Z])","NI"],["\\\\not\\s*\\\\ni(?![a-zA-Z])","NOTNI"],["\\\\subset(?![a-zA-Z])","SUBSET"],["\\\\not\\s*\\\\subset(?![a-zA-Z])","NOTSUBSET"],["\\\\supset(?![a-zA-Z])","SUPERSET"],["\\\\not\\s*\\\\supset(?![a-zA-Z])","NOTSUPERSET"],["\\\\cup(?![a-zA-Z])","UNION"],["\\\\cap(?![a-zA-Z])","INTERSECT"],["!","!"],["'","'"],["_","_"],["&","&"],["\\\\ldots","LDOTS"],["\\\\\\\\","LINEBREAK"],["\\\\begin\\s*{\\s*[a-zA-Z0-9]+\\s*}","BEGINENVIRONMENT"],["\\\\end\\s*{\\s*[a-zA-Z0-9]+\\s*}","ENDENVIRONMENT"],["\\\\var\\s*{\\s*[a-zA-Z0-9\\+\\-]+\\s*}","VARMULTICHAR"],["\\\\[a-zA-Z]+(?![a-zA-Z])","LATEXCOMMAND"],["[a-zA-Z_]","VAR"]],allowSimplifiedFunctionApplicationDefault=!0,allowedLatexSymbolsDefault=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial"],appliedFunctionSymbolsDefault=["abs","exp","log","ln","log10","sign","sqrt","erf","acos","acosh","acot","acoth","acsc","acsch","asec","asech","asin","asinh","atan","atanh","cos","cosh","cot","coth","csc","csch","sec","sech","sin","sinh","tan","tanh","arcsin","arccos","arctan","arccsc","arcsec","arccot","cosec","arg","Re","Im","det","trace"],functionSymbolsDefault=["f","g"],parseLeibnizNotationDefault=!0;class latexToAst$1{constructor({allowSimplifiedFunctionApplication:e=allowSimplifiedFunctionApplicationDefault,allowedLatexSymbols:t=allowedLatexSymbolsDefault,appliedFunctionSymbols:n=appliedFunctionSymbolsDefault,functionSymbols:r=functionSymbolsDefault,parseLeibnizNotation:a=parseLeibnizNotationDefault,parseScientificNotation:i=!0}={}){this.allowSimplifiedFunctionApplication=e,this.allowedLatexSymbols=t,this.appliedFunctionSymbols=n,this.functionSymbols=r,this.parseLeibnizNotation=a;let o=base_latex_rules;o=i?[...number_rules_sci,...o]:[...number_rules_non_sci,...o],this.lexer=new lexer(o,whitespace_rule)}advance(e){if(this.token=this.lexer.advance(e),"INVALID"===this.token.token_type)throw new ParseError("Invalid symbol '"+this.token.original_text+"'",this.lexer.location)}return_state(){return{lexer_state:this.lexer.return_state(),token:Object.assign({},this.token)}}set_state(e){this.lexer.set_state(e.lexer_state),this.token=Object.assign({},e.token)}convert(e){this.lexer.set_input(e),this.advance();var t=this.statement_list();if("EOF"!==this.token.token_type)throw new ParseError("Invalid location of '"+this.token.original_text+"'",this.lexer.location);return flatten(t)}statement_list(){for(var e=[this.statement()];","===this.token.token_type;)this.advance(),e.push(this.statement());return e.length>1?["list"].concat(e):e[0]}statement({inside_absolute_value:e=0}={}){if("LDOTS"===this.token.token_type)return this.advance(),["ldots"];var t;try{t=this.return_state();let n=this.statement_a({inside_absolute_value:e});if(":"!==this.token.token_type&&"MID"!==this.token.token_type)return n;let r=":"===this.token.token_type?":":"|";return this.advance(),[r,n,this.statement_a()]}catch(e){try{this.set_state(t);let n=this.statement_a({parse_absolute_value:!1});if("|"!==this.token.token_type[0])throw e;return this.advance(),["|",n,this.statement_a({parse_absolute_value:!1})]}catch(t){throw e}}}statement_a({inside_absolute_value:e=0,parse_absolute_value:t=!0}={}){for(var n=this.statement_b({inside_absolute_value:e,parse_absolute_value:t});"OR"===this.token.token_type;){let r=this.token.token_type.toLowerCase();this.advance(),n=[r,n,this.statement_b({inside_absolute_value:e,parse_absolute_value:t})]}return n}statement_b(e){for(var t=this.relation(e);"AND"===this.token.token_type;){let n=this.token.token_type.toLowerCase();this.advance(),t=[n,t,this.relation(e)]}return t}relation(e){if("NOT"===this.token.token_type||"!"===this.token.token_type)return this.advance(),["not",this.relation(e)];for(var t=this.expression(e);"="===this.token.token_type||"NE"===this.token.token_type||"<"===this.token.token_type||">"===this.token.token_type||"LE"===this.token.token_type||"GE"===this.token.token_type||"IN"===this.token.token_type||"NOTIN"===this.token.token_type||"NI"===this.token.token_type||"NOTNI"===this.token.token_type||"SUBSET"===this.token.token_type||"NOTSUBSET"===this.token.token_type||"SUPERSET"===this.token.token_type||"NOTSUPERSET"===this.token.token_type;){let n=this.token.token_type.toLowerCase(),r=0;"<"===this.token.token_type||"LE"===this.token.token_type?r=-1:">"!==this.token.token_type&&"GE"!==this.token.token_type||(r=1),this.advance();let a=this.expression(e);if(-1===r)if("<"===this.token.token_type||"LE"===this.token.token_type){let r=["tuple"];"<"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;"<"===this.token.token_type||"LE"===this.token.token_type;)"<"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["lts",i,r]}else t=[n,t,a];else if(1===r)if(">"===this.token.token_type||"GE"===this.token.token_type){let r=["tuple"];">"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;">"===this.token.token_type||"GE"===this.token.token_type;)">"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["gts",i,r]}else t=[n,t,a];else if("="===n)for(t=["=",t,a];"="===this.token.token_type;)this.advance(),t.push(this.expression(e));else t=[n,t,a]}return t}expression(e){let t=!1;"+"===this.token.token_type&&(t=!0,this.advance());let n=!1;"-"===this.token.token_type&&(n=!0,this.advance());var r=this.term(e);if(n||t){if(!1===r)return(t?"+":"")+(n?"-":"");if("string"==typeof r&&[...r].every((e=>["+","-"].includes(e))))return(t?"+":"")+(n?"-":"")+r}for(!1===r&&(r="_"),n&&(r=r>0?-r:["-",r]);"+"===this.token.token_type||"-"===this.token.token_type||"UNION"===this.token.token_type||"INTERSECT"===this.token.token_type;){let t=this.token.token_type.toLowerCase(),n=!1,a=!1;"-"===this.token.token_type?(t="+",n=!0,this.advance()):(this.advance(),"+"===t&&"-"===this.token.token_type&&(n=!0,a=!0,this.advance()));let i=this.term(e);if("+"===t){if(!1===i&&("number"==typeof r||"string"==typeof r))return a?r+"+-":n?r+"-":r+"+";if("string"==typeof i&&[...i].every((e=>["+","-"].includes(e)))&&("number"==typeof r||"string"==typeof r))return a?r+"+-"+i:n?r+"-"+i:r+"+"+i}!1===i&&(i="_"),n&&(i=i>0?-i:["-",i]),r=[t,r,i]}return r}term(e){var t=this.factor(e),n=!1;do{if(n=!1,"*"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["*",t,r],n=!0}else if("/"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["/",t,r],n=!0}else{let r=Object.assign({},e);r.allow_absolute_value_closing=!0;let a=this.nonMinusFactor(r);!1!==a&&(!1===t&&(t="_"),t=["*",t,a],n=!0)}}while(n);return t}factor(e){if("+"===this.token.token_text){if(this.advance(),e.dont_append_to_plus_minus)return"+";let t=this.factor(e);return!1===t?"+":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"+"+t:["+",t]}if("-"===this.token.token_type){if(this.advance(),e.dont_append_to_plus_minus)return"-";let t=this.factor(e);return t>0?-t:!1===t?"-":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"-"+t:["-",t]}return this.nonMinusFactor(e)}nonMinusFactor(e){var t=this.baseFactor(e);if("!"===this.token.token_type||"'"===this.token.token_type)for(!1===t&&(t="_");"!"===this.token.token_type||"'"===this.token.token_type;)t="!"===this.token.token_type?["apply","factorial",t]:["prime",t],this.advance();if("^"===this.token.token_type){if(!1===t&&(t="_"),this.advance(),"NUMBER"===this.token.token_type&&this.token.token_text.length>1&&"."!==this.token.token_text[0]){let e=Number(this.token.token_text[0]);return this.lexer.unput(this.token.token_text.slice(1)),this.advance(),["^",t,e]}let n=Object.assign({},e);delete n.allow_absolute_value_closing,delete n.inside_absolute_value,n.dont_append_to_plus_minus=!0;let r=this.factor(n);return!1===r&&(r="_"),["^",t,r]}return t}baseFactor({inside_absolute_value:e=0,parse_absolute_value:t=!0,allow_absolute_value_closing:n=!1}={}){var r=!1;if("FRAC"===this.token.token_type){if(this.advance(),"{"!==this.token.token_type)throw new ParseError("Expecting {",this.lexer.location);if(this.advance(),this.parseLeibnizNotation){let e=this.return_state(),t=this.leibniz_notation();if(t)return t;this.set_state(e)}let e=this.statement({parse_absolute_value:t});if("}"!==this.token.token_type)throw new ParseError("Expecting }",this.lexer.location);if(this.advance(),"{"!==this.token.token_type)throw new ParseError("Expecting {",this.lexer.location);this.advance();let n=this.statement({parse_absolute_value:t});if("}"!==this.token.token_type)throw new ParseError("Expecting }",this.lexer.location);return this.advance(),["/",e,n]}if("BEGINENVIRONMENT"===this.token.token_type){let e=/\\begin\s*{\s*([a-zA-Z0-9]+)\s*}/.exec(this.token.token_text)[1];if(["matrix","pmatrix","bmatrix"].includes(e)){let n=0,a=0,i=[],o=[],s=0,l=this.token.token_type;for(this.advance();"ENDENVIRONMENT"!==this.token.token_type;)"&"===this.token.token_type?("&"!==l&&"LINEBREAK"!==l||(o.push(0),s+=1),l=this.token.token_type,this.advance()):"LINEBREAK"===this.token.token_type?("&"!==l&&"LINEBREAK"!==l||(o.push(0),s+=1),i.push(o),s>a&&(a=s),n+=1,s=0,o=[],l=this.token.token_type,this.advance()):(o.push(this.statement({parse_absolute_value:t})),s+=1,l=" ");if(/\\end\s*{\s*([a-zA-Z0-9]+)\s*}/.exec(this.token.token_text)[1]!==e)throw new ParseError("Expecting \\end{"+e+"}",this.lexer.location);"&"===l&&(o.push(0),s+=1),i.push(o),s>a&&(a=s),n+=1,this.advance(),r=["matrix",["tuple",n,a]];let u=["tuple"];for(let e of i){let t=["tuple"].concat(e);for(let n=e.length;n1&&"."!==this.token.token_text[0]){let e=Number(this.token.token_text[0]);this.lexer.unput(this.token.token_text.slice(1)),this.advance(),r=["_",r,e]}else{let e=this.baseFactor({parse_absolute_value:t});!1===e&&(e="_"),r="log"===r&&10===e?"log10":["_",r,e]}for(;"'"===this.token.token_type;)r=["prime",r],this.advance();if("^"===this.token.token_type)if(this.advance(),"NUMBER"===this.token.token_type&&this.token.token_text.length>1&&"."!==this.token.token_text[0]){let e=Number(this.token.token_text[0]);this.lexer.unput(this.token.token_text.slice(1)),this.advance(),r=["^",r,e]}else{let e=this.factor({parse_absolute_value:t});!1===e&&(e="_"),r=["^",r,e]}if("{"===this.token.token_type||"("===this.token.token_type){let e;e="{"===this.token.token_type?"}":")",this.advance();let t=this.statement_list();if(this.token.token_type!==e)throw new ParseError("Expecting "+e,this.lexer.location);this.advance(),"list"===t[0]&&(t[0]="tuple"),r=["apply",r,t]}else if(e){if(!this.allowSimplifiedFunctionApplication)throw new ParseError("Expecting ( after function",this.lexer.location);let e=this.factor({parse_absolute_value:t});!1===e&&(e="_"),r=["apply",r,e]}}else this.advance()}else if("("===this.token.token_type||"["===this.token.token_type||"{"===this.token.token_type||"LBRACE"===this.token.token_type){let e,t,n=this.token.token_type;"("===this.token.token_type?(e=")",t="]"):"["===this.token.token_type?(e="]",t=")"):"{"===this.token.token_type?(e="}",t=null):(e="RBRACE",t=null),this.advance();let a=1;if("list"===(r=this.statement_list())[0]&&(a=r.length-1),this.token.token_type!==e){if(2!==a||null===t)throw new ParseError("Expecting "+e,this.lexer.location);if(this.token.token_type!==t)throw new ParseError("Expecting ) or ]",this.lexer.location);let i;r[0]="tuple",i="("===n?["tuple",!1,!0]:["tuple",!0,!1],(r=["interval",r]).push(i)}else a>=2?r[0]="("===n||"{"===n?"tuple":"["===n?"array":"set":"LBRACE"===n&&("|"===r[0]||r[0],r=["set",r]);this.advance()}else if("|"===this.token.token_type[0]&&t&&(0===e||!n||"L"===this.token.token_type[1])){if(e+=1,this.advance(),r=["apply","abs",r=this.statement({inside_absolute_value:e})],"|"!==this.token.token_type)throw new ParseError("Expecting |",this.lexer.location);this.advance()}if("_"===this.token.token_type){if(!1===r&&(r="_"),this.advance(),"NUMBER"===this.token.token_type&&this.token.token_text.length>1&&"."!==this.token.token_text[0]){let e=Number(this.token.token_text[0]);return this.lexer.unput(this.token.token_text.slice(1)),this.advance(),["_",r,e]}let e;return["+","-"].includes(this.token.token_text)?(e=this.token.token_text,this.advance()):(e=this.baseFactor({parse_absolute_value:t}),!1===e&&(e="_")),["_",r,e]}return r}leibniz_notation(){var e=this.token.token_text;let t="",n=1,r="",a=[],i=[];if("LATEXCOMMAND"===this.token.token_type&&"partial"===e.slice(1))t="∂";else{if("VAR"!==this.token.token_type||"d"!==e)return!1;t="d"}if(this.advance(),"^"===this.token.token_type){this.advance();let e=!1;if("{"===this.token.token_type&&(e=!0,this.advance()),"NUMBER"!==this.token.token_type)return!1;if(n=parseFloat(this.token.token_text),!Number.isInteger(n))return!1;if(e&&(this.advance(),"}"!==this.token.token_type))return!1;this.advance()}if("VAR"===this.token.token_type)r=this.token.token_text;else if("VARMULTICHAR"===this.token.token_type)r=/\\var\s*\{\s*([a-zA-Z0-9\+\-]+)\s*\}/.exec(this.token.token_text)[1];else if("LATEXCOMMAND"===this.token.token_type){if(e=this.token.token_text.slice(1),!this.allowedLatexSymbols.includes(e))return!1;r=e}if(this.advance(),"}"!==this.token.token_type)return!1;if(this.advance(),"{"!==this.token.token_type)return!1;this.advance();let o=0;for(;;){if(!("d"===t&&"VAR"===this.token.token_type&&"d"===this.token.token_text||"∂"===t&&"LATEXCOMMAND"===this.token.token_type&&"partial"===this.token.token_text.slice(1)))return!1;if(this.advance(),"VAR"===this.token.token_type)a.push(this.token.token_text);else if("VARMULTICHAR"===this.token.token_type)a.push(/\\var\s*\{\s*([a-zA-Z0-9\+\-]+)\s*\}/.exec(this.token.token_text)[1]);else{if("LATEXCOMMAND"!==this.token.token_type)return!1;{let e=this.token.token_text.slice(1);if(!this.allowedLatexSymbols.includes(e))return!1;a.push(e)}}let s=1;if(this.advance(),"^"===this.token.token_type){this.advance();let e=!1;if("{"===this.token.token_type&&(e=!0,this.advance()),"NUMBER"!==this.token.token_type)return!1;if(s=parseFloat(this.token.token_text),!Number.isInteger(s))return!1;if(e&&(this.advance(),"}"!==this.token.token_type))return!1;this.advance()}if(i.push(s),o+=s,o>n)return!1;if(o===n){if("}"!==this.token.token_type)return!1;this.advance();let o="derivative_leibniz";"∂"===t&&(o="partial_"+o),e=[o],1===n?e.push(r):e.push(["tuple",r,n]);let s=[];for(let e=0;e,larger":function(e){return[">",e[0],e[1]]},"<=,smallerEq":function(e){return["le",e[0],e[1]]},">=,largerEq":function(e){return["ge",e[0],e[1]]},"!=,unequal":function(e){return["ne",e[0],e[1]]},"!,factorial":function(e){return["apply","factorial",e[0]]}};class mathjsToAst{convert(e){if(e.isConstantNode)return e.value;if(e.isSymbolNode)return e.name;if(e.isOperatorNode){var t=[e.op,e.fn].join(",");if(t in operators)return operators[t](e.args.map(function(e,t){return this.convert(e)}.bind(this)));throw Error("Unsupported operator: "+e.op+", "+e.fn)}if(e.isFunctionNode){var n=e.args.map(function(e,t){return this.convert(e)}.bind(this));n=n.length>1?["tuple"].concat(n):n[0];var r=["apply",e.name];return r.push(n),r}if(e.isArrayNode)return["vector"].concat(e.args.map(function(e,t){return this.convert(e)}.bind(this)));if(e.isParenthesisNode)return this.convert(e.content);throw Error("Unsupported node type: "+e.type)}}class mathjsToGuppy{constructor(){this.mathjsToAst=new mathjsToAst,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.mathjsToAst.convert(e))}}class mathjsToLatex{constructor(){this.mathjsToAst=new mathjsToAst,this.astToLatex=new astToLatex$1}convert(e){return this.astToLatex.convert(this.mathjsToAst.convert(e))}}class mathjsToText{constructor(){this.mathjsToAst=new mathjsToAst,this.astToText=new astToText$1}convert(e){return this.astToText.convert(this.mathjsToAst.convert(e))}}function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex1)for(var n=1;n0)return parse$1(e);if("number"===n&&!1===isNaN(e))return t.long?fmtLong(e):fmtShort(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse$1(e){if(!((e=String(e)).length>100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function fmtShort(e){return e>=d?Math.round(e/d)+"d":e>=h?Math.round(e/h)+"h":e>=m?Math.round(e/m)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function fmtLong(e){return plural(e,d,"day")||plural(e,h,"hour")||plural(e,m,"minute")||plural(e,s,"second")||e+" ms"}function plural(e,t,n){if(!(e=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(n())}(browser,browser.exports);var debug=browser.exports("xml-parser"),xmlParser=parse;function parse(e){return e=(e=e.trim()).replace(//g,""),{declaration:function(){if(n(/^<\?xml\s*/)){for(var e={attributes:{}};!r()&&!a("?>");){var i=t();if(!i)return e;e.attributes[i.name]=i.value}return n(/\?>\s*/),e}}(),root:function i(){debug("tag %j",e);var o=n(/^<([\w-:.]+)\s*/);if(o){for(var s,l={name:o[1],attributes:{},children:[]};!(r()||a(">")||a("?>")||a("/>"));){var u=t();if(!u)return l;l.attributes[u.name]=u.value}if(n(/^\s*\/>\s*/))return l;for(n(/\??>\s*/),l.content=function(){debug("content %j",e);var t=n(/^([^<]*)/);return t?t[1]:""}();s=i();)l.children.push(s);return n(/^<\/[\w-:.]+>\s*/),l}}()};function t(){debug("attribute %j",e);var t,r=n(/([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/);if(r)return{name:r[1],value:(t=r[2],t.replace(/^['"]|['"]$/g,""))}}function n(t){var n=e.match(t);if(n)return e=e.slice(n[0].length),n}function r(){return 0==e.length}function a(t){return 0==e.indexOf(t)}}const entities={"Α":"\\Alpha","Α":"\\Alpha","Α":"\\Alpha","\\u0391;":"\\Alpha","Β":"\\Beta","Β":"\\Beta","Β":"\\Beta","\\u0392;":"\\Beta","Γ":"\\Gamma","Γ":"\\Gamma","Γ":"\\Gamma","\\u0393;":"\\Gamma","Δ":"\\Delta","Δ":"\\Delta","Δ":"\\Delta","\\u0394;":"\\Delta","Ε":"\\Epsilon","Ε":"\\Epsilon","Ε":"\\Epsilon","\\u0395;":"\\Epsilon","Ζ":"\\Zeta","Ζ":"\\Zeta","Ζ":"\\Zeta","\\u0396;":"\\Zeta","Η":"\\Eta","Η":"\\Eta","Η":"\\Eta","\\u0397;":"\\Eta","Θ":"\\Theta","Θ":"\\Theta","Θ":"\\Theta","\\u0398;":"\\Theta","Ι":"\\Iota","Ι":"\\Iota","Ι":"\\Iota","\\u0399;":"\\Iota","Κ":"\\Kappa","Κ":"\\Kappa","Κ":"\\Kappa","\\u039A;":"\\Kappa","Λ":"\\Lambda","Λ":"\\Lambda","Λ":"\\Lambda","\\u039B;":"\\Lambda","Μ":"\\Mu","Μ":"\\Mu","Μ":"\\Mu","\\u039C;":"\\Mu","Ν":"\\Nu","Ν":"\\Nu","Ν":"\\Nu","\\u039D;":"\\Nu","Ξ":"\\Xi","Ξ":"\\Xi","Ξ":"\\Xi","\\u039E;":"\\Xi","Ο":"\\Omicron","Ο":"\\Omicron","Ο":"\\Omicron","\\u039F;":"\\Omicron","Π":"\\Pi","Π":"\\Pi","Π":"\\Pi","\\u03A0;":"\\Pi","Ρ":"\\Rho","Ρ":"\\Rho","Ρ":"\\Rho","\\u03A1;":"\\Rho","Σ":"\\Sigma","Σ":"\\Sigma","Σ":"\\Sigma","\\u03A3;":"\\Sigma","Τ":"\\Tau","Τ":"\\Tau","Τ":"\\Tau","\\u03A4;":"\\Tau","Υ":"\\Upsilon","Υ":"\\Upsilon","Υ":"\\Upsilon","\\u03A5;":"\\Upsilon","Φ":"\\Phi","Φ":"\\Phi","Φ":"\\Phi","\\u03A6;":"\\Phi","Χ":"\\Chi","Χ":"\\Chi","Χ":"\\Chi","\\u03A7;":"\\Chi","Ψ":"\\Psi","Ψ":"\\Psi","Ψ":"\\Psi","\\u03A8;":"\\Psi","Ω":"\\Omega","Ω":"\\Omega","Ω":"\\Omega","\\u03A9;":"\\Omega","α":"\\alpha","α":"\\alpha","α":"\\alpha","\\u03B1;":"\\alpha","β":"\\beta","β":"\\beta","β":"\\beta","\\u03B2;":"\\beta","γ":"\\gamma","γ":"\\gamma","γ":"\\gamma","\\u03B3;":"\\gamma","δ":"\\delta","δ":"\\delta","δ":"\\delta","\\u03B4;":"\\delta","ε":"\\epsilon","ε":"\\epsilon","ε":"\\epsilon","\\u03B5;":"\\epsilon","ζ":"\\zeta","ζ":"\\zeta","ζ":"\\zeta","\\u03B6;":"\\zeta","η":"\\eta","η":"\\eta","η":"\\eta","\\u03B7;":"\\eta","θ":"\\theta","θ":"\\theta","θ":"\\theta","\\u03B8;":"\\theta","ι":"\\iota","ι":"\\iota","ι":"\\iota","\\u03B9;":"\\iota","κ":"\\kappa","κ":"\\kappa","κ":"\\kappa","\\u03BA;":"\\kappa","λ":"\\lambda","λ":"\\lambda","λ":"\\lambda","\\u03BB;":"\\lambda","μ":"\\mu","μ":"\\mu","μ":"\\mu","\\u03BC;":"\\mu","ν":"\\nu","ν":"\\nu","ν":"\\nu","\\u03BD;":"\\nu","ξ":"\\xi","ξ":"\\xi","ξ":"\\xi","\\u03BE;":"\\xi","ο":"\\omicron","ο":"\\omicron","ο":"\\omicron","\\u03BF;":"\\omicron","π":"\\pi","π":"\\pi","π":"\\pi","\\u03C0;":"\\pi","ρ":"\\rho","ρ":"\\rho","ρ":"\\rho","\\u03C1;":"\\rho","ς":"\\sigma",";":"\\sigma","ς":"\\sigma","\\u03C2;":"\\sigma","σ":"\\sigma","σ":"\\sigma","σ":"\\sigma","\\u03C3;":"\\sigma","τ":"\\tau","τ":"\\tau","τ":"\\tau","\\u03C4;":"\\tau","υ":"\\upsilon","υ":"\\upsilon","υ":"\\upsilon","\\u03C5;":"\\upsilon","φ":"\\phi","φ":"\\phi","φ":"\\phi","\\u03C6;":"\\phi","χ":"\\chi","χ":"\\chi","χ":"\\chi","\\u03C7;":"\\chi","ψ":"\\psi","ψ":"\\psi","ψ":"\\psi","\\u03C8;":"\\psi","ω":"\\omega","ω":"\\omega","ω":"\\omega","\\u03C9;":"\\omega","−":"-","−":"-","∞":"\\infty","∞":"\\infty","∞":"\\infty","⋅":"\\cdot","⋅":"\\cdot","⋅":"\\cdot","×":"\\times","×":"\\times","×":"\\times"};class mmlToLatex{parse(e){return"mi"===e.name?entities[e.content]?entities[e.content]:e.content.length>1?"\\"+e.content:e.content:"mn"===e.name?e.content:"msup"===e.name?this.parse(e.children[0])+"^{"+this.parse(e.children[1])+"}":"mroot"===e.name?"\\sqrt["+this.parse(e.children[1])+"]{"+this.parse(e.children[1])+"}":"mfrac"===e.name?"\\frac{"+this.parse(e.children[0])+"}{"+this.parse(e.children[1])+"}":"msqrt"===e.name?"\\sqrt{"+e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" ")+"}":"mo"===e.name?entities[e.content]?entities[e.content]:"⁡"===e.content?" ":e.content:"mrow"===e.name&&"MJX-TeXAtom-ORD"===e.attributes.class?e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" "):"math"===e.name||"mrow"===e.name?"("+e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" ")+")":void 0}convert(e){return this.parse(xmlParser(e).root)}}class mmlToAst$1{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1}convert(e){return this.latexToAst.convert(this.mmlToLatex.convert(e))}}class mmlToGuppy{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class mmlToMathjs{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToMathjs=new astToMathjs$1}convert(e){return this.astToMathjs.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class mmlToText{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToText=new astToText$1}convert(e){return this.astToText.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class textToGuppy{constructor(){this.textToAst=new textToAst$4,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.textToAst.convert(e))}}class textToLatex{constructor(){this.textToAst=new textToAst$4,this.astToLatex=new astToLatex$1}convert(e){return this.astToLatex.convert(this.textToAst.convert(e))}}class textToMathjs{constructor(){this.textToAst=new textToAst$4,this.astToMathjs=new astToMathjs$1}convert(e){return this.astToMathjs.convert(this.textToAst.convert(e))}}var converters=Object.freeze({__proto__:null,astToLatexObj:astToLatex$1,astToTextObj:astToText$1,astToGuppyObj:astToGuppy$1,astToMathjsObj:astToMathjs$1,latexToAstObj:latexToAst$1,latexToGuppyObj:latexToGuppy,latexToMathjsObj:latexToMathjs,latexToTextObj:latexToText,mathjsToAstObj:mathjsToAst,mathjsToGuppyObj:mathjsToGuppy,mathjsToLatexObj:mathjsToLatex,mathjsToTextObj:mathjsToText,mmlToAstObj:mmlToAst$1,mmlToGuppyObj:mmlToGuppy,mmlToLatexObj:mmlToLatex,mmlToMathjsObj:mmlToMathjs,mmlToTextObj:mmlToText,textToAstObj:textToAst$4,textToGuppyObj:textToGuppy,textToLatexObj:textToLatex,textToMathjsObj:textToMathjs,astToGLSL:astToGLSL$1}),textToAst=new textToAst$4,latexToAst=new latexToAst$1,mmlToAst=new mmlToAst$1,utils={match:match$2,flatten:flatten$5,unflattenLeft:unflattenLeft,unflattenRight:unflattenRight};function Expression(e,t){this.tree=flatten$5(e),this.context=t,this.toJSON=function(){let e={objectType:"math-expression",tree:this.tree},t={};for(let e in this.context.assumptions)Object.keys(this.context.assumptions[e]).length>0&&(t[e]=this.context.assumptions[e]);return Object.keys(t).length>0&&(e.assumptions=t),e}}function extend(e,t){var n=flatten_array(Array.prototype.slice.call(arguments,2));return n.forEach((function(n){if(n)for(var r in n)t?function(){var t=r;e[t]=function(){return this.fromAst(n[t].apply(null,arguments))}}():e[r]=n[r]})),e}function extend_prototype(e,t){var n=flatten_array(Array.prototype.slice.call(arguments,2));return n.forEach((function(n){if(n)for(var r in n)!function(){var a=r;e[a]=function(){var e=[this].concat(Array.prototype.slice.call(arguments));return t?this.context.fromAst(n[a].apply(null,e)):n[a].apply(null,e)}}()})),e}function create_from_multiple(e,t){if(Array.isArray(e)||"number"==typeof e)return new Expression(e,Context);if("string"==typeof e)try{return new Expression(textToAst.convert(e),Context)}catch(t){try{return new Expression(latexToAst.convert(e),Context)}catch(n){try{return new Expression(mmlToAst.convert(e),Context)}catch(r){if(-1!==e.indexOf("\\"))throw n;if(-1!==e.indexOf(">>2]>>>24-i%4*8&255;t[r+i>>>2]|=o<<24-(r+i)%4*8}else for(i=0;i>>2]=n[i>>>2];return this.sigBytes+=a,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n,r=[],a=function(t){var n=987654321,r=4294967295;return function(){var a=((n=36969*(65535&n)+(n>>16)&r)<<16)+(t=18e3*(65535&t)+(t>>16)&r)&r;return a/=4294967296,(a+=.5)*(e.random()>.5?1:-1)}},i=0;i>>2]>>>24-a%4*8&255;r.push((i>>>4).toString(16)),r.push((15&i).toString(16))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new o.init(n,t/2)}},u=s.Latin1={stringify:function(e){for(var t=e.words,n=e.sigBytes,r=[],a=0;a>>2]>>>24-a%4*8&255;r.push(String.fromCharCode(i))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new o.init(n,t)}},c=s.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},p=a.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new o.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=c.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,a=n.sigBytes,i=this.blockSize,s=a/(4*i),l=(s=t?e.ceil(s):e.max((0|s)-this._minBufferSize,0))*i,u=e.min(4*l,a);if(l){for(var c=0;c>>31}var p=(r<<5|r>>>27)+l+i[u];p+=u<20?1518500249+(a&o|~a&s):u<40?1859775393+(a^o^s):u<60?(a&o|a&s|o&s)-1894007588:(a^o^s)-899497514,l=s,s=o,o=a<<30|a>>>2,a=r,r=p}n[0]=n[0]+r|0,n[1]=n[1]+a|0,n[2]=n[2]+o|0,n[3]=n[3]+s|0,n[4]=n[4]+l|0},_doFinalize:function(){var e=this._data,t=e.words,n=8*this._nDataBytes,r=8*e.sigBytes;return t[r>>>5]|=128<<24-r%32,t[14+(r+64>>>9<<4)]=Math.floor(n/4294967296),t[15+(r+64>>>9<<4)]=n,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});e.SHA1=r._createHelper(o),e.HmacSHA1=r._createHmacHelper(o)}(),CryptoJS.SHA1);var sha1=sha1$1.exports,encBase64={exports:{}};!function(e,t){e.exports=function(e){return function(){var t=e,n=t.lib.WordArray;function r(e,t,r){for(var a=[],i=0,o=0;o>>6-o%4*2;a[i>>>2]|=(s|l)<<24-i%4*8,i++}return n.create(a,i)}t.enc.Base64={stringify:function(e){var t=e.words,n=e.sigBytes,r=this._map;e.clamp();for(var a=[],i=0;i>>2]>>>24-i%4*8&255)<<16|(t[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|t[i+2>>>2]>>>24-(i+2)%4*8&255,s=0;s<4&&i+.75*s>>6*(3-s)&63));var l=r.charAt(64);if(l)for(;a.length%4;)a.push(l);return a.join("")},parse:function(e){var t=e.length,n=this._map,a=this._reverseMap;if(!a){a=this._reverseMap=[];for(var i=0;iArray.isArray(t)?e.concat(flattenDeep(t)):e.concat(t)),[])}function flattenLevels(e,t){return console.log(`levels: ${t}`),e.reduce(((e,n)=>Array.isArray(n)&&t>1?e.concat(flattenLevels(n,t-1)):e.concat(n)),[])}class Subset{union(e){return this.complement().intersect(e.complement()).complement()}intersectWithOpenInterval(e){return this.intersect(e)}setMinus(e){return this.intersect(e.complement())}symmetricDifference(e){return this.setMinus(e).union(e.setMinus(this))}equals(e){return this.symmetricDifference(e).isEmpty()}toJSON(){return{objectType:"subset",data:Object.assign({},this),subsetType:this.constructor.subsetType}}static reviver(e,t){if(t&&"subset"===t.objectType&&void 0!==t.subsetType){if("emptySet"===t.subsetType)return new EmptySet;if("realLine"===t.subsetType)return new RealLine;if("singleton"===t.subsetType)return new Singleton(t.data.element);if("union"===t.subsetType)return new Union(t.data.subsets);if("openInterval"===t.subsetType)return new OpenInterval(t.data.left,t.data.right)}return t}copy(){return this.constructor.reviver(null,this.toJSON())}}class EmptySet extends Subset{static subsetType="emptySet";union(e){return e}intersect(){return new EmptySet}contains(){return!1}isEmpty(){return!0}complement(){return new RealLine}toString(){return"∅"}toMathExpression(){return me$3.fromAst("∅")}}class RealLine extends Subset{static subsetType="realLine";union(){return new RealLine}intersect(e){return e}contains(){return!0}complement(){return new EmptySet}isEmpty(){return!1}toString(){return"ℝ"}toMathExpression(){return me$3.fromAst("R")}}class Singleton extends Subset{static subsetType="singleton";constructor(e){if(super(),!Number.isFinite(e))return new EmptySet;this.element=e}union(e){return e.contains(this.element)?e:new Union([e,this])}intersect(e){return e.contains(this.element)?new Singleton(this.element):new EmptySet}isEmpty(){return!1}contains(e){return e===this.element}complement(){return new Union([new OpenInterval(-1/0,this.element),new OpenInterval(this.element,1/0)])}toString(){return`{${this.element}}`}toMathExpression(){return me$3.fromAst(["set",this.element])}}class Union extends Subset{static subsetType="union";intersect(e){return new Union(this.subsets.map((t=>e.intersect(t))))}toString(){return this.subsets.map((e=>e.toString())).join(" U ")}toMathExpression(){return me$3.fromAst(["union",...this.subsets.map((e=>e.toMathExpression().tree))])}constructor(e){super();let t=e.filter((e=>!e.isEmpty()));if(0===t.length)return new EmptySet;t=t.reduce(((e,t)=>t instanceof Union?e.concat(t.subsets):e.concat(t)),[]),this.subsets=[];for(let e=0;ea&&o.elementi.left&&at.contains(e)))}isEmpty(){return this.subsets.every((e=>e.isEmpty()))}complement(){return this.subsets.map((e=>e.complement())).reduce(((e,t)=>e.intersect(t)))}}class Interval$1 extends Subset{constructor(e,t){return super(),this.left=e,this.right=t,this.left<=this.right?this.left===-1/0&&this.right===1/0?new RealLine:this:new EmptySet}}class OpenInterval extends Interval$1{static subsetType="openInterval";constructor(e,t){return super(e,t),e===t?new EmptySet:this}intersect(e){return e.intersectWithOpenInterval(this)}intersectWithOpenInterval(e){return new OpenInterval(Math.max(this.left,e.left),Math.min(this.right,e.right))}complement(){return new Union([new OpenClosedInterval(-1/0,this.left),new ClosedOpenInterval(this.right,1/0)])}isEmpty(){return this.left>=this.right}contains(e){return e>this.left&&ebuildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new EmptySet:1===n.length?n[0]:new Union(n)}if("intersect"===n||"and"===n){let n=e.slice(1).map((e=>buildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new RealLine:n.reduce(((e,t)=>e.intersect(t)))}if("set"===n){let n=e.slice(1).map((e=>buildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new EmptySet:1===n.length?n[0]:new Union(n)}if(["<","le",">","ge","=","ne"].includes(n)){let r=e[1],a=!1;if(!Number.isFinite(r))if(deepCompare(r,t))a=!0;else if(r=me$3.fromAst(r).evaluate_to_constant(),!Number.isFinite(r)&&r!==1/0&&r!==-1/0)return new EmptySet;let i=e[2],o=!1;if(!Number.isFinite(i))if(deepCompare(i,t))o=!0;else if(i=me$3.fromAst(i).evaluate_to_constant(),!Number.isFinite(i)&&i!==1/0&&i!==-1/0)return new EmptySet;return a?o?new EmptySet:"<"===n?new OpenInterval(-1/0,i):"le"===n?new OpenClosedInterval(-1/0,i):">"===n?new OpenInterval(i,1/0):"ge"===n?new ClosedOpenInterval(i,1/0):"="===n?Number.isFinite(i)?new Singleton(i):new EmptySet:Number.isFinite(i)?new Union([new OpenInterval(-1/0,i),new OpenInterval(i,1/0)]):new RealLine:o?"<"===n?new OpenInterval(r,1/0):"le"===n?new ClosedOpenInterval(r,1/0):">"===n?new OpenInterval(-1/0,r):"ge"===n?new OpenClosedInterval(-1/0,r):"="===n?Number.isFinite(r)?new Singleton(r):new EmptySet:Number.isFinite(r)?new Union([new OpenInterval(-1/0,r),new OpenInterval(r,1/0)]):new RealLine:new EmptySet}if(["lts","gts"].includes(n)){let r=e[1].slice(1),a=e[2].slice(1);if(3!==r.length||!deepCompare(r[1],t))return new EmptySet;"gts"===n&&(r.reverse(),a.reverse());let i=r[0];if(!Number.isFinite(i)&&(i=me$3.fromAst(i).evaluate_to_constant(),!Number.isFinite(i)&&i!==1/0&&i!==-1/0))return new EmptySet;let o=r[2];return Number.isFinite(o)||(o=me$3.fromAst(o).evaluate_to_constant(),Number.isFinite(o)||o===1/0||o===-1/0)?a[0]?a[1]?new OpenInterval(i,o):new OpenClosedInterval(i,o):a[1]?new ClosedOpenInterval(i,o):new ClosedInterval(i,o):new EmptySet}if("|"===n){let t=e[1];return buildSubsetFromIntervals(e[2],t)}if("^"!==n||"C"!==e[2]&&"c"!==e[2]){if("in"===n)return deepCompare(e[1],t)?buildSubsetFromIntervals(e[2],t):new EmptySet;if("ni"===n)return deepCompare(e[2],t)?buildSubsetFromIntervals(e[1],t):new EmptySet;if("notin"===n){if(deepCompare(e[1],t)){let n=buildSubsetFromIntervals(e[2],t);if(n)return n.complement()}return new EmptySet}if("notni"===n){if(deepCompare(e[2],t)){let n=buildSubsetFromIntervals(e[1],t);if(n)return n.complement()}return new EmptySet}{let t=me$3.fromAst(e).evaluate_to_constant();return Number.isFinite(t)?new Singleton(t):new EmptySet}}{let n=buildSubsetFromIntervals(e[1],t);return n?n.complement():new EmptySet}}function buildSubsetFromMathExpression(e,t){return buildSubsetFromIntervals(e.to_intervals().tree,t.tree)}function deepClone(e,t,n){if(Object(e)!==e||e instanceof Function)return e;if(void 0!==t&&e instanceof t)return e;if(e instanceof me$3.class||e instanceof theModule.Subset)return e.copy();if(void 0===n&&(n=new WeakMap),Array.isArray(e))return[...e.map((e=>deepClone(e,t,n)))];if(e.constructor===Object&&0===Object.entries(e).length)return{};if(n.has(e))return n.get(e);try{var r=new e.constructor}catch(t){r=Object.create(Object.getPrototypeOf(e))}return e instanceof Map?Array.from(e,(([e,a])=>r.set(deepClone(e,t,n),deepClone(a,t,n)))):e instanceof Set&&Array.from(e,(e=>r.add(deepClone(e,t,n)))),n.set(e,r),Object.assign(r,...Object.keys(e).map((r=>({[r]:deepClone(e[r],t,n)}))))}function deepCompare(e,t,n){var r,a;return r=[],a=[],function e(t,i){var o;if(Number.isNaN(t)&&Number.isNaN(i))return!0;if(t===i)return!0;if(void 0!==n&&t instanceof n&&i instanceof n)return t.componentName===i.componentName;if(t instanceof me$3.class&&i instanceof me$3.class)return e(t.tree,i.tree);if("function"==typeof t&&"function"==typeof i||t instanceof Date&&i instanceof Date||t instanceof RegExp&&i instanceof RegExp||t instanceof String&&i instanceof String||t instanceof Number&&i instanceof Number)return t.toString()===i.toString();if(!(t instanceof Object&&i instanceof Object))return!1;if(t.isPrototypeOf(i)||i.isPrototypeOf(t))return!1;if(t.constructor!==i.constructor)return!1;if(t.prototype!==i.prototype)return!1;if(r.indexOf(t)>-1||a.indexOf(i)>-1)return!1;for(o in i){if(i.hasOwnProperty(o)!==t.hasOwnProperty(o))return!1;if(typeof i[o]!=typeof t[o])return!1}for(o in t){if(i.hasOwnProperty(o)!==t.hasOwnProperty(o))return!1;if(typeof i[o]!=typeof t[o])return!1;switch(typeof t[o]){case"object":case"function":if(r.push(t),a.push(i),!e(t[o],i[o]))return!1;r.pop(),a.pop();break;default:if(!(t[o]===i[o]||Number.isNaN(t[o])&&Number.isNaN(i[o])))return!1}}return!0}(e,t)}function breakStringsAndOthersIntoComponentsByStringCommas(e){return null}function returnBreakStringsSugarFunction({childrenToComponentFunction:e,mustStripOffOuterParentheses:t=!1}){return function({matchedChildren:n}){let r=0,a=[],i=[],o=!1,s=n.length;if(t){let e=n[0];if("string"!=typeof e||"("!==e.trimLeft()[0])return{success:!1}}for(let[e,l]of n.entries()){if("string"!=typeof l){i.push(l);continue}let u=l.trim();if(0===e&&t&&"("===u[0]){let e=n[s-1];if("string"==typeof e){let t=e.trimRight();")"===t[t.length-1]&&(o=!0,u=u.substring(1))}}let c=0;for(let t=0;tc&&i.push(u.substring(c,t)),a.push(i),i=[],c=t+1)}u.length>c&&i.push(u.substring(c,u.length))}return 0!==r?{success:!1}:(a.push(i),{success:!0,newChildren:a.map(e)})}}function breakEmbeddedStringByCommas({childrenList:e}){let t=0,n=[],r=[];for(let a of e){if("string"!=typeof a){r.push(a);continue}let e=a.trim(),i=0;for(let a=0;ai){let t=e.substring(i,a).trim();r.push(t)}n.push(r),r=[],i=a+1}}if(e.length>i){let t=e.substring(i,e.length).trim();r.push(t)}}return 0!==t?{success:!1}:(n.push(r),{success:!0,pieces:n})}function breakEmbeddedStringsIntoParensPieces({componentList:e,removeParens:t=!1}){let n=0,r=[],a=[];for(let i of e){if("string"!=typeof i){0===n?r.push([i]):a.push(i);continue}let e=i.trim(),o=0;for(let i=0;io){let n=t?i:i+1,r=e.substring(o,n).trim();r.length>0&&a.push(r)}r.push(a),a=[],o=i+1}n--}else if(0===n&&!s.match(/\s/))return{success:!1}}if(e.length>o){let t=e.substring(o,e.length).trim();a.push(t)}}return 0!==n?{success:!1}:(a.length>0&&r.push(a),{success:!0,pieces:r})}var global$x="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$x.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$x.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue$2=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue$2=currentQueue.concat(queue$2):queueIndex=-1,queue$2.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue$2.length;t;){for(currentQueue=queue$2,queue$2=[];++queueIndex1)for(var n=1;n{throw new Error("This node type doesn't define a deserialize function")})}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return"function"!=typeof e&&(e=NodeType.match(e)),t=>{let n=e(t);return void 0===n?null:[this,n]}}}NodeProp.closedBy=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.openedBy=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.group=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.contextHash=new NodeProp({perNode:!0}),NodeProp.lookAhead=new NodeProp({perNode:!0}),NodeProp.mounted=new NodeProp({perNode:!0});const noProps=Object.create(null);class NodeType{constructor(e,t,n,r=0){this.name=e,this.props=t,this.id=n,this.flags=r}static define(e){let t=e.props&&e.props.length?Object.create(null):noProps,n=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(null==e.name?8:0),r=new NodeType(e.name||"",t,e.id,n);if(e.props)for(let n of e.props)if(Array.isArray(n)||(n=n(r)),n){if(n[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[n[0].id]=n[1]}return r}prop(e){return this.props[e.id]}get isTop(){return(1&this.flags)>0}get isSkipped(){return(2&this.flags)>0}get isError(){return(4&this.flags)>0}get isAnonymous(){return(8&this.flags)>0}is(e){if("string"==typeof e){if(this.name==e)return!0;let t=this.prop(NodeProp.group);return!!t&&t.indexOf(e)>-1}return this.id==e}static match(e){let t=Object.create(null);for(let n in e)for(let r of n.split(" "))t[r]=e[n];return e=>{for(let n=e.prop(NodeProp.group),r=-1;r<(n?n.length:0);r++){let a=t[r<0?e.name:n[r]];if(a)return a}}}}NodeType.none=new NodeType("",Object.create(null),0,8);class NodeSet{constructor(e){this.types=e;for(let t=0;te.node;;){let o=!1;if(e.from<=a&&e.to>=r&&(e.type.isAnonymous||!1!==t(e.type,e.from,e.to,i))){if(e.firstChild())continue;e.type.isAnonymous||(o=!0)}for(;o&&n&&n(e.type,e.from,e.to,i),o=e.type.isAnonymous,!e.nextSibling();){if(!e.parent())return;o=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:balanceRange(NodeType.none,this.children,this.positions,0,this.children.length,0,this.length,((e,t,n)=>new Tree(this.type,e,t,n,this.propValues)),e.makeTree||((e,t,n)=>new Tree(NodeType.none,e,t,n)))}static build(e){return buildTree(e)}}Tree.empty=new Tree(NodeType.none,[],[],0);class FlatBufferCursor{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new FlatBufferCursor(this.buffer,this.index)}}class TreeBuffer{constructor(e,t,n){this.buffer=e,this.length=t,this.set=n}get type(){return NodeType.none}toString(){let e=[];for(let t=0;t0));s=i[s+3]);return o}slice(e,t,n,r){let a=this.buffer,i=new Uint16Array(t-e);for(let r=e,o=0;r=t&&nt;case 1:return n<=t&&r>t;case 2:return r>t;case 4:return!0}}function enterUnfinishedNodesBefore(e,t){let n=e.childBefore(t);for(;n;){let t=n.lastChild;if(!t||t.to!=n.to)break;t.type.isError&&t.from==t.to?(e=n,n=t.prevSibling):n=t}return e}function resolveNode(e,t,n,r){for(var a;e.from==e.to||(n<1?e.from>=t:e.from>t)||(n>-1?e.to<=t:e.to0?o.length:-1;e!=l;e+=t){let l=o[e],u=s[e]+i._from;if(checkSide(r,n,u,u+l.length))if(l instanceof TreeBuffer){if(2&a)continue;let o=l.findChild(0,l.buffer.length,t,n-u,r);if(o>-1)return new BufferNode(new BufferContext(i,l,e,u),null,o)}else if(1&a||!l.type.isAnonymous||hasChild(l)){let o;if(!(1&a)&&l.props&&(o=l.prop(NodeProp.mounted))&&!o.overlay)return new TreeNode(o.tree,u,e,i);let s=new TreeNode(l,u,e,i);return 1&a||!s.type.isAnonymous?s:s.nextChild(t<0?l.children.length-1:0,t,n,r)}}if(1&a||!i.type.isAnonymous)return null;if(e=i.index>=0?i.index+t:t<0?-1:i._parent.node.children.length,i=i._parent,!i)return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this.node.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this.node.children.length-1,-1,e,-2)}enter(e,t,n=!0,r=!0){let a;if(n&&(a=this.node.prop(NodeProp.mounted))&&a.overlay){let n=e-this.from;for(let{from:e,to:r}of a.overlay)if((t>0?e<=n:e=n:r>n))return new TreeNode(a.tree,a.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,r?0:2)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get cursor(){return new TreeCursor(this)}get tree(){return this.node}toTree(){return this.node}resolve(e,t=0){return resolveNode(this,e,t,!1)}resolveInner(e,t=0){return resolveNode(this,e,t,!0)}enterUnfinishedNodesBefore(e){return enterUnfinishedNodesBefore(this,e)}getChild(e,t=null,n=null){let r=getChildren(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return getChildren(this,e,t,n)}toString(){return this.node.toString()}}function getChildren(e,t,n,r){let a=e.cursor,i=[];if(!a.firstChild())return i;if(null!=n)for(;!a.type.is(n);)if(!a.nextSibling())return i;for(;;){if(null!=r&&a.type.is(r))return i;if(a.type.is(t)&&i.push(a.node),!a.nextSibling())return null==r?i:[]}}class BufferContext{constructor(e,t,n,r){this.parent=e,this.buffer=t,this.index=n,this.start=r}}class BufferNode{constructor(e,t,n){this.context=e,this._parent=t,this.index=n,this.type=e.buffer.set.types[e.buffer.buffer[n]]}get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}child(e,t,n){let{buffer:r}=this.context,a=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.context.start,n);return a<0?null:new BufferNode(this.context,this,a)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}enter(e,t,n,r=!0){if(!r)return null;let{buffer:a}=this.context,i=a.findChild(this.index+4,a.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return i<0?null:new BufferNode(this.context,this,i)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new BufferNode(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new BufferNode(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get cursor(){return new TreeCursor(this)}get tree(){return null}toTree(){let e=[],t=[],{buffer:n}=this.context,r=this.index+4,a=n.buffer[this.index+3];if(a>r){let i=n.buffer[this.index+1],o=n.buffer[this.index+2];e.push(n.slice(r,a,i,o)),t.push(0)}return new Tree(this.type,e,t,this.to-this.from)}resolve(e,t=0){return resolveNode(this,e,t,!1)}resolveInner(e,t=0){return resolveNode(this,e,t,!0)}enterUnfinishedNodesBefore(e){return enterUnfinishedNodesBefore(this,e)}toString(){return this.context.buffer.childString(this.index)}getChild(e,t=null,n=null){let r=getChildren(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return getChildren(this,e,t,n)}}class TreeCursor{constructor(e,t=0){if(this.mode=t,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,e instanceof TreeNode)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let t=e._parent;t;t=t._parent)this.stack.unshift(t.index);this.bufferNode=e,this.yieldBuf(e.index)}}get name(){return this.type.name}yieldNode(e){return!!e&&(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0)}yieldBuf(e,t){this.index=e;let{start:n,buffer:r}=this.buffer;return this.type=t||r.set.types[r.buffer[e]],this.from=n+r.buffer[e+1],this.to=n+r.buffer[e+2],!0}yield(e){return!!e&&(e instanceof TreeNode?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)))}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,n){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree.node.children.length-1:0,e,t,n,this.mode));let{buffer:r}=this.buffer,a=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.buffer.start,n);return!(a<0)&&(this.stack.push(this.index),this.yieldBuf(a))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,n=!0,r=!0){return this.buffer?!!r&&this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,n&&!(1&this.mode),r))}parent(){if(!this.buffer)return this.yieldNode(1&this.mode?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=1&this.mode?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return!!this._tree._parent&&this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode));let{buffer:t}=this.buffer,n=this.stack.length-1;if(e<0){let e=n<0?0:this.stack[n]+4;if(this.index!=e)return this.yieldBuf(t.findChild(e,this.index,-1,0,4))}else{let e=t.buffer[this.index+3];if(e<(n<0?t.buffer.length:t.buffer[this.stack[n]+3]))return this.yieldBuf(e)}return n<0&&this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode))}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,n,{buffer:r}=this;if(r){if(e>0){if(this.index-1)for(let r=t+e,a=e<0?-1:n.node.children.length;r!=a;r+=e){let e=n.node.children[r];if(1&this.mode||e instanceof TreeBuffer||!e.type.isAnonymous||hasChild(e))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let i=e;i;i=i._parent)if(i.index==r){if(r==this.index)return i;t=i,n=a+1;break e}r=this.stack[--a]}for(let e=n;ee instanceof TreeBuffer||!e.type.isAnonymous||hasChild(e)))}function buildTree(e){var t;let{buffer:n,nodeSet:r,maxBufferLength:a=DefaultBufferLength,reused:i=[],minRepeatType:o=r.types.length}=e,s=Array.isArray(n)?new FlatBufferCursor(n,n.length):n,l=r.types,u=0,c=0;function p(e,t,n,h,y){let{id:b,start:g,end:v,size:T}=s,N=c;for(;T<0;){if(s.next(),-1==T){let t=i[b];return n.push(t),void h.push(g-e)}if(-3==T)return void(u=b);if(-4==T)return void(c=b);throw new RangeError(`Unrecognized record size: ${T}`)}let C,A,S=l[b],x=g-e;if(v-g<=a&&(A=function(e,t){let n=s.fork(),r=0,i=0,l=0,u=n.end-a,c={size:0,start:0,skip:0};e:for(let a=n.pos-e;n.pos>a;){let e=n.size;if(n.id==t&&e>=0){c.size=r,c.start=i,c.skip=l,l+=4,r+=4,n.next();continue}let s=n.pos-e;if(e<0||s=o?4:0,d=n.start;for(n.next();n.pos>s;){if(n.size<0){if(-3!=n.size)break e;p+=4}else n.id>=o&&(p+=4);n.next()}i=d,r+=e,l+=p}(t<0||r==e)&&(c.size=r,c.start=i,c.skip=l);return c.size>4?c:void 0}(s.pos-t,y))){let t=new Uint16Array(A.size-A.skip),n=s.pos-A.size,a=t.length;for(;s.pos>n;)a=f(A.start,t,a);C=new TreeBuffer(t,v-A.start,r),x=A.start-e}else{let e=s.pos-T;s.next();let t=[],n=[],r=b>=o?b:-1,i=0,l=v;for(;s.pos>e;)r>=0&&s.id==r&&s.size>=0?(s.end<=l-a&&(d(t,n,g,i,s.end,l,r,N),i=t.length,l=s.end),s.next()):p(g,e,t,n,r);if(r>=0&&i>0&&i-1&&i>0){let e=function(e){return(t,n,r)=>{let a,i,o=0,s=t.length-1;if(s>=0&&(a=t[s])instanceof Tree){if(!s&&a.type==e&&a.length==r)return a;(i=a.prop(NodeProp.lookAhead))&&(o=n[s]+a.length+i)}return m(e,t,n,r,o)}}(S);C=balanceRange(S,t,n,0,t.length,0,v-g,e,e)}else C=m(S,t,n,v-g,N-v)}n.push(C),h.push(x)}function d(e,t,n,a,i,o,s,l){let u=[],c=[];for(;e.length>a;)u.push(e.pop()),c.push(t.pop()+n-i);e.push(m(r.types[s],u,c,o-i,l-o)),t.push(i-n)}function m(e,t,n,r,a=0,i){if(u){let e=[NodeProp.contextHash,u];i=i?[e].concat(i):[e]}if(a>25){let e=[NodeProp.lookAhead,a];i=i?[e].concat(i):[e]}return new Tree(e,t,n,r,i)}function f(e,t,n){let{id:r,start:a,end:i,size:l}=s;if(s.next(),l>=0&&r4){let r=s.pos-(l-4);for(;s.pos>r;)n=f(e,t,n)}t[--n]=o,t[--n]=i-e,t[--n]=a-e,t[--n]=r}else-3==l?u=r:-4==l&&(c=r);return n}let h=[],y=[];for(;s.pos>0;)p(e.start||0,e.bufferStart||0,h,y,-1);let b=null!==(t=e.length)&&void 0!==t?t:h.length?y[0]+h[0].length:0;return new Tree(l[e.topID],h.reverse(),y.reverse(),b)}const nodeSizeCache=new WeakMap;function nodeSize(e,t){if(!e.isAnonymous||t instanceof TreeBuffer||t.type!=e)return 1;let n=nodeSizeCache.get(t);if(null==n){n=1;for(let r of t.children){if(r.type!=e||!(r instanceof Tree)){n=1;break}n+=nodeSize(e,r)}nodeSizeCache.set(t,n)}return n}function balanceRange(e,t,n,r,a,i,o,s,l){let u=0;for(let n=r;n=c)break;f+=t}if(u==a+1){if(f>c){let e=n[a];t(e.children,e.positions,0,e.children.length,r[a]+s);continue}p.push(n[a])}else{let t=r[u-1]+n[u-1].length-m;p.push(balanceRange(e,n,r,a,u,m,t,null,l))}d.push(m+s-i)}}(t,n,r,a,0),(s||l)(p,d,o)}class Parser$1{startParse(e,t,n){return"string"==typeof e&&(e=new StringInput(e)),n=n?n.length?n.map((e=>new Range(e.from,e.to))):[new Range(0,0)]:[new Range(0,e.length)],this.createParse(e,t||[],n)}parse(e,t,n){let r=this.startParse(e,t,n);for(;;){let e=r.advance();if(e)return e}}}class StringInput{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}new NodeProp({perNode:!0});class Stack$1{constructor(e,t,n,r,a,i,o,s,l,u=0,c){this.p=e,this.stack=t,this.state=n,this.reducePos=r,this.pos=a,this.score=i,this.buffer=o,this.bufferBase=s,this.curContext=l,this.lookAhead=u,this.parent=c}toString(){return`[${this.stack.filter(((e,t)=>t%3==0)).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,n=0){let r=e.parser.context;return new Stack$1(e,[],t,n,n,0,[],0,r?new StackContext(r,r.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){let t=e>>19,n=65535&e,{parser:r}=this.p,a=r.dynamicPrecedence(n);if(a&&(this.score+=a),0==t)return this.pushState(r.getGoto(this.state,n,!0),this.reducePos),ni;)this.stack.pop();this.reduceContext(n,o)}storeNode(e,t,n,r=4,a=!1){if(0==e){let e=this,r=this.buffer.length;if(0==r&&e.parent&&(r=e.bufferBase-e.parent.bufferBase,e=e.parent),r>0&&0==e.buffer[r-4]&&e.buffer[r-1]>-1){if(t==n)return;if(e.buffer[r-2]>=t)return void(e.buffer[r-2]=n)}}if(a&&this.pos!=n){let a=this.buffer.length;if(a>0&&0!=this.buffer[a-4])for(;a>0&&this.buffer[a-2]>n;)this.buffer[a]=this.buffer[a-4],this.buffer[a+1]=this.buffer[a-3],this.buffer[a+2]=this.buffer[a-2],this.buffer[a+3]=this.buffer[a-1],a-=4,r>4&&(r-=4);this.buffer[a]=e,this.buffer[a+1]=t,this.buffer[a+2]=n,this.buffer[a+3]=r}else this.buffer.push(e,t,n,r)}shift(e,t,n){let r=this.pos;if(131072&e)this.pushState(65535&e,this.pos);else if(0==(262144&e)){let a=e,{parser:i}=this.p;(n>this.pos||t<=i.maxNode)&&(this.pos=n,i.stateFlag(a,1)||(this.reducePos=n)),this.pushState(a,r),this.shiftContext(t,r),t<=i.maxNode&&this.buffer.push(t,r,n,4)}else this.pos=n,this.shiftContext(t,r),t<=this.p.parser.maxNode&&this.buffer.push(t,r,n,4)}apply(e,t,n){65536&e?this.reduce(e):this.shift(e,t,n)}useNode(e,t){let n=this.p.reused.length-1;(n<0||this.p.reused[n]!=e)&&(this.p.reused.push(e),n++);let r=this.pos;this.reducePos=this.pos=r+e.length,this.pushState(t,r),this.buffer.push(n,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(;t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let n=e.buffer.slice(t),r=e.bufferBase+t;for(;e&&r==e.bufferBase;)e=e.parent;return new Stack$1(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,n,r,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let n=e<=this.p.parser.maxNode;n&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,n?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new SimulatedStack(this);;){let n=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(0==(65536&n))return!0;if(0==n)return!1;t.reduce(n)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let n=[];for(let r,a=0;a1&t&&e==r))||n.push(t[e],r)}t=n}let n=[];for(let e=0;e>19,r=65535&e,a=this.stack.length-3*n;if(a<0||t.getGoto(this.stack[a],r,!1)<0)return!1;this.storeNode(0,this.reducePos,this.reducePos,4,!0),this.score-=100}return this.reduce(e),!0}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(3!=this.stack.length)return!1;let{parser:e}=this.p;return 65535==e.data[e.stateSlot(this.state,1)]&&!e.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;tthis.lookAhead&&(this.emitLookAhead(),this.lookAhead=e)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}}class StackContext{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}var Recover;!function(e){e[e.Insert=200]="Insert",e[e.Delete=190]="Delete",e[e.Reduce=100]="Reduce",e[e.MaxNext=4]="MaxNext",e[e.MaxInsertStackDepth=300]="MaxInsertStackDepth",e[e.DampenInsertStackDepth=120]="DampenInsertStackDepth"}(Recover||(Recover={}));class SimulatedStack{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=65535&e,n=e>>19;0==n?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=3*(n-1);let r=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=r}}class StackBufferCursor{constructor(e,t,n){this.stack=e,this.pos=t,this.index=n,this.buffer=e.buffer,0==this.index&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new StackBufferCursor(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;null!=e&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,0==this.index&&this.maybeNext()}fork(){return new StackBufferCursor(this.stack,this.pos,this.index)}}class CachedToken{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const nullToken=new CachedToken;class InputStream{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=nullToken,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let n=this.range,r=this.rangeIndex,a=this.pos+e;for(;an.to:a>=n.to;){if(r==this.ranges.length-1)return null;let e=this.ranges[++r];a+=e.from-n.to,n=e}return a}peek(e){let t,n,r=this.chunkOff+e;if(r>=0&&r=this.chunk2Pos&&tr.to&&(this.chunk2=this.chunk2.slice(0,r.to-t)),n=this.chunk2.charCodeAt(0)}}return t>=this.token.lookAhead&&(this.token.lookAhead=t+1),n}acceptToken(e,t=0){let n=t?this.resolveOffset(t,-1):this.pos;if(null==n||n=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=nullToken,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let n="";for(let r of this.ranges){if(r.from>=t)break;r.to>e&&(n+=this.input.read(Math.max(r.from,e),Math.min(r.to,t)))}return n}}class TokenGroup{constructor(e,t){this.data=e,this.id=t}token(e,t){readToken(this.data,e,t,this.id)}}TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1;class ExternalTokenizer{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function readToken(e,t,n,r){let a=0,i=1<0){let n=e[r];if(s.allows(n)&&(-1==t.token.value||t.token.value==n||o.overrides(n,t.token.value))){t.acceptToken(n);break}}for(let r=t.next,i=0,o=e[a+2];i>1,l=n+s+(s<<1),u=e[l],c=e[l+1];if(r=c)){a=e[l+2],t.advance();continue e}i=s+1}}break}}function decodeArray(e,t=Uint16Array){if("string"!=typeof e)return e;let n=null;for(let r=0,a=0;r=92&&t--,t>=34&&t--;let a=t-32;if(a>=46&&(a-=46,n=!0),i+=a,n)break;i*=46}n?n[a++]=i:n=new t(i)}return n}const verbose=void 0!==browser$1&&/\bparse\b/.test(browser$1.env.LOG);let stackIDs=null;var Safety,Rec;function cutAt(e,t,n){let r=e.fullCursor();for(r.moveTo(t);;)if(!(n<0?r.childBefore(t):r.childAfter(t)))for(;;){if((n<0?r.tot)&&!r.type.isError)return n<0?Math.max(0,Math.min(r.to-1,t-25)):Math.min(e.length,Math.max(r.from+1,t+25));if(n<0?r.prevSibling():r.nextSibling())break;if(!r.parent())return n<0?0:e.length}}!function(e){e[e.Margin=25]="Margin"}(Safety||(Safety={}));class FragmentCursor{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?cutAt(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?cutAt(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=i,null;if(a instanceof Tree){if(i==e){if(i=Math.max(this.safeFrom,e)&&(this.trees.push(a),this.start.push(i),this.index.push(0))}else this.index[t]++,this.nextStart=i+a.length}}}class TokenCache{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map((e=>new CachedToken))}getActions(e){let t=0,n=null,{parser:r}=e.p,{tokenizers:a}=r,i=r.stateSlot(e.state,3),o=e.curContext?e.curContext.hash:0,s=0;for(let r=0;ru.end+25&&(s=Math.max(u.lookAhead,s)),0!=u.value)){let r=t;if(u.extended>-1&&(t=this.addActions(e,u.extended,u.end,t)),t=this.addActions(e,u.value,u.end,t),!l.extend&&(n=u,t>r))break}}for(;this.actions.length>t;)this.actions.pop();return s&&e.setLookAhead(s),n||e.pos!=this.stream.end||(n=new CachedToken,n.value=e.p.parser.eofTerm,n.start=n.end=e.pos,t=this.addActions(e,n.value,n.end,t)),this.mainToken=n,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new CachedToken,{pos:n,p:r}=e;return t.start=n,t.end=Math.min(n+1,r.stream.end),t.value=n==r.stream.end?r.parser.eofTerm:0,t}updateCachedToken(e,t,n){if(t.token(this.stream.reset(n.pos,e),n),e.value>-1){let{parser:t}=n.p;for(let r=0;r=0&&n.p.parser.dialect.allows(a>>1)){0==(1&a)?e.value=a>>1:e.extended=a>>1;break}}}else e.value=0,e.end=Math.min(n.p.stream.end,n.pos+1)}putAction(e,t,n,r){for(let t=0;t4*e.bufferLength?new FragmentCursor(n,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e,t,n=this.stacks,r=this.minStackPos,a=this.stacks=[];for(let i=0;ir)a.push(o);else{if(this.advanceStack(o,a,n))continue;{e||(e=[],t=[]),e.push(o);let n=this.tokens.getMainToken(o);t.push(n.value,n.end)}}break}}if(!a.length){let t=e&&findFinished(e);if(t)return this.stackToTree(t);if(this.parser.strict)throw verbose&&e&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+r);this.recovering||(this.recovering=5)}if(this.recovering&&e){let n=null!=this.stoppedAt&&e[0].pos>this.stoppedAt?e[0]:this.runRecovery(e,t,a);if(n)return this.stackToTree(n.forceAll())}if(this.recovering){let e=1==this.recovering?1:3*this.recovering;if(a.length>e)for(a.sort(((e,t)=>t.score-e.score));a.length>e;)a.pop();a.some((e=>e.reducePos>r))&&this.recovering--}else if(a.length>1)e:for(let e=0;e500&&r.buffer.length>500){if(!((t.score-r.score||t.buffer.length-r.buffer.length)>0)){a.splice(e--,1);continue e}a.splice(n--,1)}}}this.minStackPos=a[0].pos;for(let e=1;e ":"";if(null!=this.stoppedAt&&r>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let t=e.curContext&&e.curContext.tracker.strict,n=t?e.curContext.hash:0;for(let o=this.fragments.nodeAt(r);o;){let r=this.parser.nodeSet.types[o.type.id]==o.type?a.getGoto(e.state,o.type.id):-1;if(r>-1&&o.length&&(!t||(o.prop(NodeProp.contextHash)||0)==n))return e.useNode(o,r),verbose&&console.log(i+this.stackID(e)+` (via reuse of ${a.getName(o.type.id)})`),!0;if(!(o instanceof Tree)||0==o.children.length||o.positions[0]>0)break;let s=o.children[0];if(!(s instanceof Tree&&0==o.positions[0]))break;o=s}}let o=a.stateSlot(e.state,4);if(o>0)return e.reduce(o),verbose&&console.log(i+this.stackID(e)+` (via always-reduce ${a.getName(65535&o)})`),!0;if(e.stack.length>=15e3)for(;e.stack.length>9e3&&e.forceReduce(););let s=this.tokens.getActions(e);for(let o=0;or?t.push(d):n.push(d)}return!1}advanceFully(e,t){let n=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>n)return pushStackDedup(e,t),!0}}runRecovery(e,t,n){let r=null,a=!1;for(let i=0;i ":"";if(o.deadEnd){if(a)continue;if(a=!0,o.restart(),verbose&&console.log(u+this.stackID(o)+" (restarted)"),this.advanceFully(o,n))continue}let c=o.split(),p=u;for(let e=0;c.forceReduce()&&e<10;e++){if(verbose&&console.log(p+this.stackID(c)+" (via force-reduce)"),this.advanceFully(c,n))break;verbose&&(p=this.stackID(c)+" -> ")}for(let e of o.recoverByInsert(s))verbose&&console.log(u+this.stackID(e)+" (via recover-insert)"),this.advanceFully(e,n);this.stream.end>o.pos?(l==o.pos&&(l++,s=0),o.recoverByDelete(s,l),verbose&&console.log(u+this.stackID(o)+` (via recover-delete ${this.parser.getName(s)})`),pushStackDedup(o,n)):(!r||r.scoree;class ContextTracker{constructor(e){this.start=e.start,this.shift=e.shift||id$3,this.reduce=e.reduce||id$3,this.reuse=e.reuse||id$3,this.hash=e.hash||(()=>0),this.strict=!1!==e.strict}}class LRParser extends Parser$1{constructor(e){if(super(),this.wrappers=[],13!=e.version)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (13)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let n=0;ne.topRules[t][1])),r=[];for(let e=0;e=0)a(r,e,t[n++]);else{let i=t[n+-r];for(let o=-r;o>0;o--)a(t[n++],e,i);n++}}}this.nodeSet=new NodeSet(t.map(((t,a)=>NodeType.define({name:a>=this.minRepeatTerm?void 0:t,id:a,props:r[a],top:n.indexOf(a)>-1,error:0==a,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1})))),this.strict=!1,this.bufferLength=DefaultBufferLength;let i=decodeArray(e.tokenData);if(this.context=e.context,this.specialized=new Uint16Array(e.specialized?e.specialized.length:0),this.specializers=[],e.specialized)for(let t=0;t"number"==typeof e?new TokenGroup(i,e):e)),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,n){let r=new Parse(this,e,t,n);for(let a of this.wrappers)r=a(r,e,t,n);return r}getGoto(e,t,n=!1){let r=this.goto;if(t>=r[0])return-1;for(let a=r[t+1];;){let t=r[a++],i=1&t,o=r[a++];if(i&&n)return o;for(let n=a+(t>>1);a0}validAction(e,t){if(t==this.stateSlot(e,4))return!0;for(let n=this.stateSlot(e,1);;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])return!1;n=pair(this.data,n+2)}if(t==pair(this.data,n+1))return!0}}nextStates(e){let t=[];for(let n=this.stateSlot(e,1);;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])break;n=pair(this.data,n+2)}if(0==(1&this.data[n+2])){let e=this.data[n+1];t.some(((t,n)=>1&n&&t==e))||t.push(this.data[n],e)}}return t}overrides(e,t){let n=findOffset(this.data,this.tokenPrecTable,t);return n<0||findOffset(this.data,this.tokenPrecTable,e){let n=e.tokenizers.find((e=>e.from==t));return n?n.to:t}))),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),null!=e.strict&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),null!=e.bufferLength&&(t.bufferLength=e.bufferLength),t}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return null==t?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),n=t.map((()=>!1));if(e)for(let r of e.split(" ")){let e=t.indexOf(r);e>=0&&(n[e]=!0)}let r=null;for(let e=0;ee)&&n.p.parser.stateFlag(n.state,2)&&(!t||t.score=65&&e<=90||95==e||e>=97&&e<=122||e>=161}function isSpace(e){return 9==e||10==e||13==e||32==e}let cachedName=null,cachedInput=null,cachedPos=0;function tagNameAfter(e,t){let n=e.pos+t;if(cachedInput==e&&cachedPos==n)return cachedName;for(;isSpace(e.peek(t));)t++;let r="";for(;;){let n=e.peek(t);if(!nameChar(n))break;r+=String.fromCharCode(n),t++}return cachedInput=e,cachedPos=n,cachedName=r||null}function ElementContext(e,t){this.name=e,this.parent=t,this.hash=t?t.hash:0;for(let t=0;tt==StartTag?new ElementContext(tagNameAfter(r,1)||"",e):e,reduce:(e,t)=>t==Element&&e?e.parent:e,reuse(e,t,n,r){let a=t.type.id;return a==StartTag||a==OpenTag?new ElementContext(tagNameAfter(r,1)||"",e):e},hash:e=>e?e.hash:0,strict:!1}),startTag=new ExternalTokenizer(((e,t)=>{if(60==e.next)if(e.advance(),47==e.next){e.advance();let n=tagNameAfter(e,0);if(!n)return e.acceptToken(incompleteStartCloseTag);if(t.context&&n.toLowerCase()==t.context.name.toLowerCase())return e.acceptToken(StartCloseTag);for(let r=t.context;r;r=r.parent)if(r.name==n)return e.acceptToken(MissingCloseTag,-2);e.acceptToken(mismatchedStartCloseTag)}else if(33!=e.next&&63!=e.next&&!isSpace(e.next))return e.acceptToken(StartTag)}),{contextual:!0});function scanTo(e,t){return new ExternalTokenizer((n=>{for(let r=0,a=0;;a++){if(n.next<0){a&&n.acceptToken(e);break}if(n.next==t.charCodeAt(r)){if(r++,r==t.length){a>t.length&&n.acceptToken(e,1-t.length);break}}else r=0;n.advance()}}))}const commentContent=scanTo(commentContent$1,"--\x3e"),parser=LRParser.deserialize({version:13,states:"*[OQOTOOO]OYO'#CdOeO`O'#CfO!OOTO'#CeOOOP'#Ce'#CeOOOP'#Cx'#CxOOOP'#Co'#CoQQOTOOOOOQ'#Cp'#CpO!VOYO,59OOOOP,59O,59OO!_OpO,59QO!mO`O'#ClOOOP'#DT'#DTOOOP'#Cu'#CuO!rOTO,59PO!yO`O'#CmOOOP,59P,59POOOP-E6m-E6mOOOQ-E6n-E6nOOOP1G.j1G.jOOOO'#Cq'#CqO#ROpO1G.lO#aOpO'#ChOOOO'#Cr'#CrO#rOpO1G.lOOOP1G.l1G.lOOOP1G.t1G.tO#}OWO,59WOOOP-E6s-E6sOOOP1G.k1G.kO$SO`O,59XO$[OWO,59XOOOO-E6o-E6oO$dOpO7+$WOOOP7+$W7+$WOOOP7+$`7+$`O$oOpO,59SO%QOWO,59SOOOO-E6p-E6pOOOP1G.r1G.rO%]OWO1G.sO%]OWO1G.sOOOP1G.s1G.sOOOP< tag. Found ${e.slice(a-1,i)}`)}n.firstChild();let t=e.substring(n.from,n.to);if(!1===n.nextSibling()){if(t in o)throw Error(`Duplicate attribute ${t}. Found in component of type ${r} at indices ${n.from}-${n.to}`);o[t]=!0}else{n.nextSibling();let a=e.substring(n.from+1,n.to-1);if(t in o)throw Error(`Duplicate attribute ${t}. Found in component of type ${r} at indices ${n.from}-${n.to}`);o[t]=a}n.parent()}n.parent();let s={componentType:r,props:{...o},children:[]};for(;n.nextSibling();)if("Text"===n.name){let t=e.substring(n.from,n.to);""!==t&&s.children.push(t)}else{if("Element"!==n.name){if("CloseTag"===n.name)break;if("Comment"===n.name)continue;throw"MismatchedCloseTag"===n.name?Error(`Invalid DoenetML at position ${n.from}. Mismatched closing tag. Expected . Found ${e.slice(n.from,n.to)}.`):Error(`Invalid DoenetML at position ${n.from}. Expected a closing tag. Instead found ${e.slice(n.from,n.to)}.`)}s.children.push(t(n.node.cursor))}return s.range={openBegin:a,openEnd:i,closeBegin:n.from,closeEnd:n.to},s}if("SelfClosingTag"===n.name){n.firstChild(),n.nextSibling();let t=e.substring(n.from,n.to),r=n.from,a={};for(;n.nextSibling();){if("Attribute"!==n.name)throw Error(`Invalid DoenetML at positions ${n.from} to ${n.to}. Error in self-closing <${t}/> tag.`);n.firstChild();let r=e.substring(n.from,n.to);if(!1===n.nextSibling()){if(r in a)throw Error(`Duplicate attribute ${r}. Found in component of type ${t} at indices ${n.from}-${n.to}`);a[r]=!0}else{if(n.nextSibling(),r in a)throw Error(`Duplicate attribute ${r}. Found in component of type ${t} at indices ${n.from}-${n.to}`);let i=e.substring(n.from+1,n.to-1);a[r]=i}n.parent()}let i={selfCloseBegin:r,selfCloseEnd:n.to+2};return{componentType:t,props:{...a},children:[],range:i}}throw Error("Non SelfClosingTag/OpenTag in Element. How did you do that?")}function n(n){if("Element"===n.node.name)return t(n.node.cursor);if("Comment"===n.node.name)return null;if("Text"!==n.node.name)throw Error(`Invalid DoenetML at positions ${n.node.from} to ${n.node.to}. Found ${e.substring(n.node.from,n.node.to)}`);{let t=e.substring(n.node.from,n.node.to);if(""!==t)return t}}if(!e)return[];let r=parse(e),a=[];if(!r.firstChild())return a;let i=n(r);for(null!=i&&a.push(i);r.nextSibling();){let e=n(r);null!=e&&a.push(e)}return a}var base32$1={exports:{}};!function(e){!function(){var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof browser$1&&browser$1.versions&&browser$1.versions.node&&(t=commonjsGlobal);var n=!t.HI_BASE32_NO_COMMON_JS&&e.exports,r="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),a={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},i=[0,0,0,0,0,0,0,0],o=function(e,t){t.length>10&&(t="..."+t.substr(-10));var n=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw n.position=e,n},s=function(e){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");for(var t,n,r,i,o,s,l,u,c=[],p=0,d=(e=e.replace(/=/g,"")).length,m=0,f=d>>3<<3;m>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|o>>>1),c[p++]=255&(o<<7|s<<2|l>>>3),c[p++]=255&(l<<5|u);var h=d-f;return 2===h?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2)):4===h?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4)):5===h?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],o=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|o>>>1)):7===h&&(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],o=a[e.charAt(m++)],s=a[e.charAt(m++)],l=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|o>>>1),c[p++]=255&(o<<7|s<<2|l>>>3)),c},l=function(e,t){if(!t)return function(e){for(var t,n,r="",a=e.length,i=0,s=0;i191&&t<=223?(n=31&t,s=1):t<=239?(n=15&t,s=2):t<=247?(n=7&t,s=3):o(i,r);for(var l=0;l191)&&o(i,r),n<<=6,n+=63&t;n>=55296&&n<=57343&&o(i,r),n>1114111&&o(i,r),n<=65535?r+=String.fromCharCode(n):(n-=65536,r+=String.fromCharCode(55296+(n>>10)),r+=String.fromCharCode(56320+(1023&n)))}return r}(s(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");var n,r,i,l,u,c,p,d,m="",f=e.indexOf("=");-1===f&&(f=e.length);for(var h=0,y=f>>3<<3;h>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|p>>>3))+String.fromCharCode(255&(p<<5|d));var b=f-y;return 2===b?(n=a[e.charAt(h++)],r=a[e.charAt(h++)],m+=String.fromCharCode(255&(n<<3|r>>>2))):4===b?(n=a[e.charAt(h++)],r=a[e.charAt(h++)],i=a[e.charAt(h++)],l=a[e.charAt(h++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))):5===b?(n=a[e.charAt(h++)],r=a[e.charAt(h++)],i=a[e.charAt(h++)],l=a[e.charAt(h++)],u=a[e.charAt(h++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))):7===b&&(n=a[e.charAt(h++)],r=a[e.charAt(h++)],i=a[e.charAt(h++)],l=a[e.charAt(h++)],u=a[e.charAt(h++)],c=a[e.charAt(h++)],p=a[e.charAt(h++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|p>>>3))),m},u={encode:function(e,t){var n="string"!=typeof e;return n&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),n?function(e){for(var t,n,a,i,o,s="",l=e.length,u=0,c=5*parseInt(l/5);u>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[31&(i<<3|o>>>5)]+r[31&o];var p=l-c;return 1===p?(t=e[u],s+=r[t>>>3]+r[t<<2&31]+"======"):2===p?(t=e[u++],n=e[u],s+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===p?(t=e[u++],n=e[u++],a=e[u],s+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):4===p&&(t=e[u++],n=e[u++],a=e[u++],i=e[u],s+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[i<<3&31]+"="),s}(e):t?function(e){for(var t,n,a,i,o,s="",l=e.length,u=0,c=5*parseInt(l/5);u>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[31&(i<<3|o>>>5)]+r[31&o];var p=l-c;return 1===p?(t=e.charCodeAt(u),s+=r[t>>>3]+r[t<<2&31]+"======"):2===p?(t=e.charCodeAt(u++),n=e.charCodeAt(u),s+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===p?(t=e.charCodeAt(u++),n=e.charCodeAt(u++),a=e.charCodeAt(u),s+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):4===p&&(t=e.charCodeAt(u++),n=e.charCodeAt(u++),a=e.charCodeAt(u++),i=e.charCodeAt(u),s+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[i<<3&31]+"="),s}(e):function(e){var t,n,a,o,s,l,u,c=!1,p="",d=0,m=0,f=e.length;if(""===e)return p;do{for(i[0]=i[5],i[1]=i[6],i[2]=i[7],u=m;d>6,i[u++]=128|63&l):l<55296||l>=57344?(i[u++]=224|l>>12,i[u++]=128|l>>6&63,i[u++]=128|63&l):(l=65536+((1023&l)<<10|1023&e.charCodeAt(++d)),i[u++]=240|l>>18,i[u++]=128|l>>12&63,i[u++]=128|l>>6&63,i[u++]=128|63&l);m=u-5,d===f&&++d,d>f&&u<6&&(c=!0),t=i[0],u>4?(n=i[1],a=i[2],o=i[3],s=i[4],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|o>>>7)]+r[o>>>2&31]+r[31&(o<<3|s>>>5)]+r[31&s]):1===u?p+=r[t>>>3]+r[t<<2&31]+"======":2===u?(n=i[1],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===u?(n=i[1],a=i[2],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):(n=i[1],a=i[2],o=i[3],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|o>>>7)]+r[o>>>2&31]+r[o<<3&31]+"=")}while(!c);return p}(e)},decode:l};l.asBytes=s,n?e.exports=u:t.base32=u}()}(base32$1);var base32=base32$1.exports;async function cidFromText(e){let t=(new TextEncoder).encode(e);return await cidFromArrayBuffer(t)}async function cidFromArrayBuffer(e){let t=await crypto.subtle.digest("SHA-256",e),n=new Uint8Array(36);return n.set([1,85,18,32]),n.set(new Uint8Array(t),4),"b"+base32.encode(n).toLowerCase().replace(/=+/,"")}const textByCid={};function retrieveTextFileForCid(e,t="doenet"){return void 0!==textByCid[e]?Promise.resolve(textByCid[e]):new Promise(((n,r)=>{let a,i,o=retrieveTextFileFromIPFS(e),s=o.promise,l=o.controller,u=!1,c=!1;s.then((t=>{clearTimeout(i),a&&!c&&a.abort(),textByCid[e]=t,n(t)})).catch((e=>{u=!0,c&&(clearTimeout(i),r(e))})),i=setTimeout((()=>{let o=retrieveTextFileFromServer(e,t),s=o.promise;a=o.controller,s.then((t=>{u||l.abort(),textByCid[e]=t,n(t)})).catch((e=>{c=!0,u?r(e):i=setTimeout((()=>{l.abort(),r(e)}),5e3)}))}),100)}))}function retrieveTextFileFromIPFS(e){let t=new AbortController,n=t.signal;return{promise:async function(){try{let t=await fetch(`https://${e}.ipfs.dweb.link/`,{signal:n});if(t.ok){let n=await t.text();return await cidFromText(n)===e?n:Promise.reject(new Error("cid mismatch"))}return Promise.reject(new Error(`cid not found: ${e}`))}catch(t){return Promise.reject(new Error(`cid not found: ${e}`))}}(),controller:t}}function retrieveTextFileFromServer(e,t){let n=new AbortController,r=n.signal;return{promise:async function(){try{let n=await fetch(`/media/${e}.${t}`,{signal:r});if(n.ok){let t=await n.text(),r=await cidFromText(t);return r===e?t:(console.warn(`cid mismatch, ${e}, ${r}`),Promise.reject(new Error("cid mismatch")))}return Promise.reject(new Error(`cid not found: ${e}`))}catch(t){return Promise.reject(new Error(`cid not found: ${e}`))}}(),controller:n}}async function expandDoenetMLsToFullSerializedComponents({cids:e,doenetMLs:t,componentInfoObjects:n}){let r=[],a={};for(let e of t){let t=parseAndCompile(e);t=cleanIfHaveJustDocument(t),substituteDeprecations(t),temporarilyRenameSourceBackToTarget(t),correctComponentTypeCapitalization(t,n.componentTypeLowerCaseMapping),copyTargetOrFromURIAttributeCreatesCopyComponent(t,n.isCompositeComponent),createAttributesFromProps(t,n),breakUpTargetIntoPropsAndIndices(t,n),applyMacros(t,n),removeBlankStringChildren(t,n),decodeXMLEntities(t),applySugar({serializedComponents:t,componentInfoObjects:n}),r.push(t);let i=findContentCopies({serializedComponents:t});for(let e in i.cidComponents)void 0===a[e]&&(a[e]=[]),a[e].push(...i.cidComponents[e])}let i=Object.keys(a);if(i.length>0){let{newDoenetMLs:e,newCids:t}=await cidsToDoenetMLs(i);for(let[e,n]of i.entries())if(t[e]&&t[e].substring(0,n.length)!==n)return Promise.reject(new Error(`Requested cid ${n} but got back ${t[e]}!`));let r=i.length;for(let n=0;n"string"!=typeof e||e.trim())),r=1===t.length&&"object"==typeof t[0],a=e.doenetAttributes?.fromCopyFromURI;if(a||r)if(a&&!r)console.warn("ignoring copyFromURI as it was not a single component");else{let n=t[0];n.attributes||(n.attributes={}),e.doenetAttributes||(e.doenetAttributes={}),e.doenetAttributes.keptNewNamespaceOfLastChild=Boolean(n.attributes.newNamespace?.primitive),n.attributes.newNamespace={primitive:!0},e.children=[n,...e.children],e.doenetAttributes.nameFirstChildIndependently=!0}else{let t={componentType:"externalContent",children:JSON.parse(JSON.stringify(n)),attributes:{newNamespace:{primitive:!0}},doenetAttributes:{createUniqueName:!0}};e.children=[t,...e.children]}}}}return{cids:e,fullSerializedComponents:r}}function cidsToDoenetMLs(e){let t=[],n=e;for(let n of e)t.push(retrieveTextFileForCid(n,"doenet"));return Promise.all(t).then((e=>Promise.resolve({newDoenetMLs:e,newCids:n}))).catch((e=>{let t;return t=1===n.length?`Could not retrieve cid ${n[0]}`:`Could not retrieve cids ${n.join(",")}`,t+=": "+e.message,console.error(t),Promise.reject(new Error(t))}))}function removeBlankStringChildren(e,t){for(let n of e){if(n.children){let e=t.allComponentClasses[n.componentType];e&&!e.includeBlankStringChildren&&(n.children=n.children.filter((e=>"string"!=typeof e||""!==e.trim()))),removeBlankStringChildren(n.children,t)}for(let e in n.attributes){let r=n.attributes[e].component;r&&r.children&&removeBlankStringChildren([r],t)}}}function findContentCopies({serializedComponents:e}){let t={};for(let n of e)if("copy"===n.componentType){if(n.attributes&&n.attributes.uri){let e=n.attributes.uri.primitive;if(e&&"doenet:"===e.substring(0,7).toLowerCase()){let r=e.match(/[:&]cid=([^&]+)/i);if(r){let e=r[1];void 0===t[e]&&(t[e]=[]),t[e].push(n)}}}}else if(void 0!==n.children){let e=findContentCopies({serializedComponents:n.children});for(let n in e.cidComponents)void 0===t[n]&&(t[n]=[]),t[n].push(...e.cidComponents[n])}return{cidComponents:t}}function addDocumentIfItsMissing(e){if(1!==e.length||"document"!==e[0].componentType){let t=e.splice(0);e.push({componentType:"document",children:t})}}function substituteDeprecations(e){let t={tname:"target",triggerwithtnames:"triggerWith",updatewithtname:"updateWith",paginatortname:"paginator",randomizeorder:"shuffleOrder",copytarget:"copySource",triggerwithtargets:"triggerWith",triggerwhentargetsclicked:"triggerWhenObjectsClicked",fortarget:"forObject",targetattributestoignore:"sourceAttributesToIgnore",targetattributestoignorerecursively:"sourceAttributesToIgnoreRecursively",targetsareresponses:"sourcesAreResponses",updatewithtarget:"updateWith",targetsarefunctionsymbols:"sourcesAreFunctionSymbols",selectforvariantnames:"selectForVariants"},n={copy:{target:"source",tname:"source"},collect:{target:"source",tname:"source"},summarystatistics:{target:"source"}};for(let r of e)if("object"==typeof r){if(r.props){let e=r.componentType,a=n[e.toLowerCase()];a||(a={});let i=!0;for(;i;){i=!1;for(let n in r.props){let o=n.toLowerCase();if(o in a){let t=a[o];console.warn(`Attribute ${n} of component type ${e} is deprecated. Use ${t} instead.`),r.props[t]=r.props[n],delete r.props[n],i=!0;break}if(o in t){let e=t[o];console.warn(`Attribute ${n} is deprecated. Use ${e} instead.`),r.props[e]=r.props[n],delete r.props[n],i=!0;break}}}}r.children&&substituteDeprecations(r.children)}}function temporarilyRenameSourceBackToTarget(e){let t={copysource:"copyTarget"},n={copy:{source:"target"},collect:{source:"target"}};for(let r of e)if("object"==typeof r){if(r.props){let e=n[r.componentType.toLowerCase()];e||(e={});let a=!0;for(;a;){a=!1;for(let n in r.props){let i=n.toLowerCase();if(i in e){let t=e[i];r.props[t]=r.props[n],delete r.props[n],a=!0;break}if(i in t){let e=t[i];r.props[e]=r.props[n],delete r.props[n],a=!0;break}}}}r.children&&temporarilyRenameSourceBackToTarget(r.children)}}function cleanIfHaveJustDocument(e){let t=e.filter((e=>"string"!=typeof e||""!==e.trim()));return 1===t.length&&"document"===t[0].componentType?t:e}function correctComponentTypeCapitalization(e,t){for(let n of e){if("object"!=typeof n)continue;let e=t[n.componentType.toLowerCase()];if(!e)throw Error(`Invalid component type${indexRangeString(n)}: ${n.componentType}`);n.componentType=e,n.children&&correctComponentTypeCapitalization(n.children,t)}}function copyTargetOrFromURIAttributeCreatesCopyComponent(e,t){for(let n of e){if(n.props){let e=!1,r=!1,a=!1,i=n.componentType,o=t({componentType:i,includeNonStandard:!1}),s=t({componentType:i,includeNonStandard:!0});for(let t of Object.keys(n.props)){let l=t.toLowerCase();if("copytarget"===l){if(e)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);if(r)throw Error(`Cannot combine copyTarget and copyFromURI attribiutes. For in component of type ${i}${indexRangeString(n)}`);if(a)throw s?Error(`A component of type ${i} cannot have both assignNames and copyTarget. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);if(e=!0,n.doenetAttributes||(n.doenetAttributes={}),o||(n.props.createComponentOfType=i,n.doenetAttributes.nameBecomesAssignNames=!0),n.componentType="copy",n.props.target=n.props[t],"string"!=typeof n.props.target)throw Error(`Must specify value for copyTarget. Found in component of type ${i}${indexRangeString(n)}`);delete n.props[t],n.doenetAttributes.fromCopyTarget=!0,n.doenetAttributes.createNameFromComponentType=i,n.props.assignNamesSkip="1"}else if("copyfromuri"===l){if(r)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);if(e)throw Error(`Cannot combine copyTarget and copyFromURI attribiutes. For in component of type ${i}${indexRangeString(n)}`);if(a)throw s?Error(`A component of type ${i} cannot have both assignNames and copyFromURI. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);if(r=!0,n.doenetAttributes||(n.doenetAttributes={}),o||(n.props.createComponentOfType=i,n.doenetAttributes.nameBecomesAssignNames=!0),n.componentType="copy",n.props.uri=n.props[t],"string"!=typeof n.props.uri)throw Error(`Must specify value for copyFromURI. Found in component of type ${i}${indexRangeString(n)}`);delete n.props[t],n.doenetAttributes.fromCopyFromURI=!0,n.doenetAttributes.createNameFromComponentType=i,n.props.assignNamesSkip="1"}else if("assignnames"===l&&!o){if(e||r)throw s?Error(`A component of type ${i} cannot have both assignNames and copyTarget. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);a=!0}}if(e){for(let e of Object.keys(n.props)){if("prop"===e.toLowerCase())throw Error(`Invalid attribute prop for component of type ${i}${indexRangeString(n)}`)}let e=!1;for(let t of Object.keys(n.props)){if("copyprop"===t.toLowerCase()){if(e)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);n.props.prop=n.props[t],delete n.props[t],e=!0}}}}n.children&©TargetOrFromURIAttributeCreatesCopyComponent(n.children,t)}}function breakUpTargetIntoPropsAndIndices(e,t){for(let n of e){if(n.props&&["copy","updateValue","animateFromSequence"].includes(n.componentType)){let r,a,i,o,s,l,u;for(let e of Object.keys(n.props)){if("target"===e.toLowerCase()){if(r)throw Error(`Cannot repeat attribute ${e}. Found in component type ${n.componentType}${indexRangeString(n)}`);r=e,u=n.props[e];let t=buildSourcePieces(u,!0);t.success&&t.matchLength===u.length&&(a=t.sourceName,i=t.componentIndex,o=t.componentAttributes,s=t.propArray,l=t.subNames)}}if(r&&a)if(i||o||s.length>0){if(n.attributes.prop)throw Error(`Cannot combine the prop attribute with an extended source attribute. Found in component type ${n.componentType}${indexRangeString(n)}`);if(n.attributes.propIndex)throw Error(`Cannot combine the propIndex attribute with an extended source attribute. Found in component type ${n.componentType}${indexRangeString(n)}`);if(n.attributes.componentIndex)throw Error(`Cannot combine the componentIndex attribute with an extended source attribute. Found in component type ${n.componentType}${indexRangeString(n)}`);let c=createComponentFromExtendedSource({sourceName:a,componentIndex:i,subNames:l,componentAttributes:o,propArray:s,componentInfoObjects:t});if(c.success){let t=c.newComponent;if("copy"===n.componentType)delete n.props[r],Object.assign(n.attributes,t.attributes),n.doenetAttributes||(n.doenetAttributes={}),Object.assign(n.doenetAttributes,t.doenetAttributes),n.doenetAttributes.createNameFromComponentType||(n.doenetAttributes.createNameFromComponentType=n.componentType),n.componentType=t.componentType,0!==s.length||n.attributes.prop||n.attributes.propIndex||(n.doenetAttributes.isPlainCopy=!0),t.children&&(n.children=t.children);else if("copy"===t.componentType)delete n.props[r],Object.assign(n.attributes,t.attributes),n.doenetAttributes||(n.doenetAttributes={}),Object.assign(n.doenetAttributes,t.doenetAttributes);else{let a=createUniqueName("extract","fromExtendedSource|"+e.length);t.doenetAttributes.prescribedName=a,t.doenetAttributes.createdFromMacro=!0;let i={componentType:"setup",children:[t],doenetAttributes:{createdFromMacro:!0}};e.push(i),delete n.props[r],n.doenetAttributes||(n.doenetAttributes={}),n.doenetAttributes.target=a,n.doenetAttributes.allowDoubleUnderscoreTarget=!0}}else"copy"===n.componentType?console.warn(`invalid copy source: ${u}`):console.warn(`invalid target: ${u}`)}else"copy"!==n.componentType||n.attributes.prop||n.attributes.propIndex||(n.doenetAttributes||(n.doenetAttributes={}),n.doenetAttributes.isPlainCopy=!0)}n.children&&breakUpTargetIntoPropsAndIndices(n.children,t)}}function createAttributesFromProps(e,t){for(let n of e){if("object"!=typeof n)continue;let e=t.allComponentClasses[n.componentType],r=e.createAttributesObject(),a={};for(let e in r)a[e.toLowerCase()]=e;let i={},o=Object.assign({},n.props);if(n.props)for(let s in n.props){let l=a[s.toLowerCase()],u=r[l];if(u){if(l in i)throw Error(`Cannot repeat attribute ${l}. Found in component type ${n.componentType}${indexRangeString(n)}`);i[l]=componentFromAttribute({attrObj:u,value:n.props[s],originalComponentProps:o,componentInfoObjects:t}),delete n.props[s]}else if(!["name","assignnames","target"].includes(s.toLowerCase())){if(!e.acceptAnyAttribute)throw Error(`Invalid attribute ${s} for component of type ${n.componentType}${indexRangeString(n)}`);i[s]=componentFromAttribute({value:n.props[s],originalComponentProps:o,componentInfoObjects:t}),delete n.props[s]}}for(let e in r){let n=r[e];n.createPrimitiveOfType&&"defaultPrimitiveValue"in n&&!(e in i)&&(i[e]=componentFromAttribute({attrObj:n,originalComponentProps:o,value:n.defaultPrimitiveValue.toString(),componentInfoObjects:t}))}n.attributes=i,void 0!==n.children&&createAttributesFromProps(n.children,t)}}function componentFromAttribute({attrObj:e,value:t,originalComponentProps:n,componentInfoObjects:r}){if("object"!=typeof t?t={rawString:t.toString()}:null===t&&(t={rawString:""}),e&&e.createComponentOfType){let a,i=t.rawString.trim().toLowerCase();if("true"===i&&void 0!==e.valueForTrue)a={componentType:e.createComponentOfType,state:{value:e.valueForTrue}};else if("false"===i&&void 0!==e.valueForFalse)a={componentType:e.createComponentOfType,state:{value:e.valueForFalse}};else if(r.isInheritedComponentType({inheritedComponentType:e.createComponentOfType,baseComponentType:"boolean"})&&["true","false"].includes(i))a={componentType:e.createComponentOfType,state:{value:"true"===i}};else{let n=t.childrenForComponent;n=n?JSON.parse(JSON.stringify(n)):[t.rawString],a={componentType:e.createComponentOfType,children:n},removeBlankStringChildren([a],r)}if(e.attributesForCreatedComponent||e.copyComponentAttributesForCreatedComponent){if(e.attributesForCreatedComponent?a.props=e.attributesForCreatedComponent:a.props={},e.copyComponentAttributesForCreatedComponent)for(let t of e.copyComponentAttributesForCreatedComponent)n[t]&&(a.props[t]=JSON.parse(JSON.stringify(n[t])));createAttributesFromProps([a],r)}let o={component:a};return e.ignoreFixed&&(o.ignoreFixed=!0),o}if(e&&e.createPrimitiveOfType){let n;if("boolean"===e.createPrimitiveOfType){n="true"===t.rawString.trim().toLowerCase()}else n="number"===e.createPrimitiveOfType?Number(t.rawString):"integer"===e.createPrimitiveOfType?Math.round(Number(t.rawString)):"stringArray"===e.createPrimitiveOfType?t.rawString.trim().split(/\s+/):"numberArray"===e.createPrimitiveOfType?t.rawString.split(/\s+/).map(Number):t.rawString;return e.validationFunction&&(n=e.validationFunction(n)),{primitive:n}}return t.childrenForComponent||(t.childrenForComponent=[t.rawString]),t}function findPreSugarIndsAndMarkFromSugar(e){let t=[];for(let n of e)if("object"==typeof n)if(void 0!==n.preSugarInd)t.push(n.preSugarInd);else if(n.doenetAttributes||(n.doenetAttributes={}),n.doenetAttributes.createdFromSugar=!0,n.children){let e=findPreSugarIndsAndMarkFromSugar(n.children);t.push(...e)}return t}function applyMacros(e,t){for(let n of e)if(n.children&&applyMacros(n.children,t),n.attributes)for(let e in n.attributes){let r=n.attributes[e];r.component?applyMacros([r.component],t):r.childrenForComponent&&applyMacros(r.childrenForComponent,t)}substituteMacros(e,t)}function substituteMacros(e,t){for(let n=0;n0&&e[n-1].range){let t=e[n-1].range;t.closeEnd?r+=t.closeEnd:t.selfCloseEnd&&(r+=t.selfCloseBegin)}throw Error(`${d.message}. At indices ${r}-${r+c}. Found: ${t}`)}l=d.newComponent,markCreatedFromMacro([l]),0===o.propArray.length&&(l.doenetAttributes.isPlainMacro=!0),s=[l];let m=1,f=i.substring(u+c);if(2===p){let r=i.slice(u+c).match(/^\s*\(/);if(!r){a=u+2;continue}let o=c+r[0].length,l=[],p=!1;i.length>u+o&&(p=!0,l.push(i.substring(u+o))),l.push(...e.slice(n+1));let d=createEvaluateIfFindMatchedClosingParens({componentsFromMacro:s,remainingComponents:l,includeFirstInRemaining:p,componentInfoObjects:t});if(!d.success){a=u+2;continue}s=d.componentsFromMacro,m=d.lastComponentIndMatched+1,p||m++,f=""}let h=[];u>0&&h.push(i.substring(0,u)),h.push(...s),f.length>0&&h.push(f),e.splice(n,m,...h),u>0&&n++;break}}}}function createComponentFromExtendedSource({sourceName:e,componentIndex:t,componentAttributes:n,propArray:r,subNames:a,componentInfoObjects:i}){let o={componentType:"copy",doenetAttributes:{target:e},attributes:{}};if(t){let e=[t];applyMacros(e,i),o.attributes.componentIndex={component:{componentType:"integer",children:e}}}if(a?.length>0){let e=[],t=[];for(let n of a)e.push(n.subName),void 0!==n.subNameComponentIndex&&(t.length0){let e=[t.join(" ")];applyMacros(e,i),o.attributes.sourceSubnamesComponentIndex={component:{componentType:"numberList",children:e}}}}let s=!1;if(n){s=!0;let e=createAttributesFromString(n,i);if(!e.success)return e;Object.assign(o.attributes,e.newAttributes),e.assignNames&&(o.props={assignNames:e.assignNames})}for(let e of r){if(s&&(o.doenetAttributes.createdFromMacro=!0,o={componentType:"extract",attributes:{},doenetAttributes:{},children:[o]}),o.attributes.prop={primitive:e.prop},e.propIndex){let t=[e.propIndex.join(" ")];applyMacros(t,i),o.attributes.propIndex={component:{componentType:"numberList",children:t}}}if(e.attributes){let t=createAttributesFromString(e.attributes,i);if(!t.success)return t;Object.assign(o.attributes,t.newAttributes),t.assignNames&&(o.props={assignNames:t.assignNames})}s=!0}return{success:!0,newComponent:o}}function createAttributesFromString(e,t){let n,r=``;try{n=parseAndCompile(r)}catch(e){return{success:!1,message:"Error in macro"}}createAttributesFromProps(n,t),markCreatedFromMacro(n),applyMacros(n,t);let a,i=n[0].attributes;if(i.prop||i.propIndex||i.componentIndex)return{success:!1,message:"Error in macro: macro cannot directly add attributes prop, propIndex, or componentIndex"};if(n[0].props)for(let e in n[0].props)if("assignnames"===e.toLowerCase()){if(a)return{success:!1,message:"Error in macro: cannot repeat assignNames"};a=n[0].props[e]}return{success:!0,newAttributes:i,assignNames:a}}function findFirstFullMacroInString(e){let t,n=0;for(;;){let r=e.substring(n).match(/(\$+)(.?)/);if(!r)return{success:!1};if(t=r[1].length,n+=r.index+t,t<=2){let r=!1,a=e.substring(n),i=0,o=findWordOrDelimitedGroup(a,r);"("===o.startDelim&&(r=!0,a=o.group,i=o.group.length);let s=buildSourcePieces(a,r);if(s.success){if(r){if(s.matchLength!==i)return{success:!1};s.matchLength+=2}return s.nDollarSigns=t,s.firstIndMatched=n-t,s.matchLength+=t,s}}}}function buildSourcePieces(e,t){let n=findWordOrDelimitedGroup(e,t),r=0;if(n.withPeriod||!n.word)return{success:!1};let a={sourceName:(n.withSlash?"/":"")+n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t),"["===n.startDelim&&(a.componentIndex=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t));let i=[];for(;n.withSlash;){let a={subName:n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t),"["===n.startDelim&&(a.subNameComponentIndex=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t)),i.push(a)}a.subNames=i,"{"===n.startDelim&&(a.componentAttributes=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t));let o=[];for(;n.withPeriod;){let a={prop:n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t);let i=[];for(;"["===n.startDelim;)i.push(n.group),r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t);i.length>0&&(a.propIndex=i),"{"===n.startDelim&&(a.attributes=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t)),o.push(a)}return a.propArray=o,a.matchLength=r,a.success=!0,a}function findWordOrDelimitedGroup(e,t=!1){let n,r=!1,a=!1;"."===e[0]&&"."!==e[1]&&(r=!0,e=e.substring(1)),t?r?n=/^[\w-]+/:("/"===e[0]&&e[1].match(/\w/)&&(a=!0,e=e.substring(1)),n=/^([\w\/-]|\.\.\/)+/):n=/^[a-zA-Z_]\w*/;let i=e.match(n);if(i)return{success:!0,withPeriod:r,withSlash:a,word:i[0],matchLength:i[0].length+(r?1:0)+(a?1:0)};if(r||a)return{success:!1};let o=[],s={"(":")","{":"}","[":"]"},l=Object.values(s),u=e[0],c=s[u];if(!c)return{success:!1};o.push(c);for(let t=1;t0?t[i]=o.substring(0,a.charInd):t=t.slice(0,i);let l=breakEmbeddedStringByCommas({childrenList:t});l.pieces.forEach((e=>applyMacros(e,r)));let u=l.pieces.map((e=>1===e.length&&"string"!=typeof e[0]?e[0]:{componentType:"math",doenetAttributes:{createdFromMacro:!0},children:e})),c=[{componentType:"evaluate",doenetAttributes:{createdFromMacro:!0},attributes:{function:{component:{componentType:"function",doenetAttributes:{createdFromMacro:!0},children:e}},input:{component:{componentType:"mathList",doenetAttributes:{createdFromMacro:!0},children:u}}}}];return s.length>0&&c.push(s),{success:!0,componentsFromMacro:c,lastComponentIndMatched:i}}function findFirstUnmatchedClosingParens(e){let t=0;for(let[n,r]of e.entries())if("string"==typeof r){let e=r;for(let r=0;r").replace(/</g,"<").replace(/$/g,"$").replace(/&/g,"&")}for(let[n,r]of e.entries())if("string"==typeof r)e[n]=t(r);else if(r.children&&decodeXMLEntities(r.children),r.attributes)for(let e in r.attributes){let n=r.attributes[e];n.component?decodeXMLEntities([n.component]):n.primitive?"string"==typeof n.primitive&&(n.primitive=t(n.primitive)):(n.childrenForComponent&&decodeXMLEntities(n.childrenForComponent),n.rawString&&(n.rawString=t(n.rawString)))}}function applySugar({serializedComponents:e,parentParametersFromSugar:t={},parentAttributes:n={},componentInfoObjects:r,parentUniqueId:a="",isAttributeComponent:i=!1}){for(let[o,s]of e.entries()){if("object"!=typeof s)continue;let e=s.componentType,l=r.allComponentClasses[e];if(!l)throw Error(`Unrecognized component type ${e}`);let u=a+"|"+e+o,c={};for(let e in s.attributes){let t=s.attributes[e];void 0!==t.primitive&&(c[e]=t.primitive)}if(s.children){let a={};if(!s.skipSugar)for(let[o,p]of l.returnSugarInstructions().entries()){let l=s.children.map((e=>"string"==typeof e?"s":"n")).join("");if(p.childrenRegex){let e=l.match(p.childrenRegex);if(!e||e[0].length!==s.children.length)continue}let d=deepClone(s.children),m=0;for(let e of d)"string"!=typeof e&&(e.preSugarInd=m,m++);let f=!1;s.doenetAttributes&&s.doenetAttributes.createdFromMacro&&(f=!0);let h=p.replacementFunction({matchedChildren:d,parentParametersFromSugar:t,parentAttributes:n,componentAttributes:c,uniqueId:u+"|sugar"+o,componentInfoObjects:r,isAttributeComponent:i,createdFromMacro:f});if(h.success){let t=h.newChildren,n=h.newAttributes,r=[],i=[];if(t&&(r=findPreSugarIndsAndMarkFromSugar(t)),n)for(let e in n){let t=n[e].component;t&&i.push(...findPreSugarIndsAndMarkFromSugar(t.children))}let o=[...r,...i];if(o.length!==m||!o.sort(((e,t)=>e-t)).every(((e,t)=>e===t)))throw Error(`Invalid sugar for ${e} as didn't return set of original components`);if(r.length>0){let t=[...r].sort(((e,t)=>e-t));if(!t.every(((e,t)=>e===r[t])))throw Error(`Invalid sugar for ${e} as didn't return original components in order`)}h.parametersForChildrenSugar&&Object.assign(a,h.parametersForChildrenSugar),s.children=t||[],n&&(s.attributes||(s.attributes={}),Object.assign(s.attributes,n))}}l.removeBlankStringChildrenPostSugar&&(s.children=s.children.filter((e=>"string"!=typeof e||/\S/.test(e)))),applySugar({serializedComponents:s.children,parentParametersFromSugar:a,parentAttributes:c,componentInfoObjects:r,parentUniqueId:u})}if(s.attributes)for(let e in s.attributes){let t=s.attributes[e];t.component&&applySugar({serializedComponents:[t.component],parentAttributes:c,componentInfoObjects:r,parentUniqueId:u,isAttributeComponent:!0})}}}function breakStringInPiecesBySpacesOrParens(e){if("string"!=typeof e)return{success:!1};let t=0,n=[];e=e.trim();let r=0;for(let a=0;a0&&n.push(t),r=a}t++}else if(")"===i){if(0===t)return{success:!1};if(1===t){let t=e.substring(r+1,a).trim();if(t.length>0){let e=breakStringInPiecesBySpacesOrParens(t);!0===e.success?n.push(e.pieces):n.push(t)}r=a+1}t--}else if(0===t&&i.match(/\s/)){let t=e.substring(r,a).trim();t.length>0&&n.push(t),r=a}}if(0!==t)return{success:!1};let a=e.substring(r,e.length).trim();return a.length>0&&n.push(a),{success:!0,pieces:n}}function countRegularComponentTypesInNamespace(e,t={}){for(let n of e)if("object"==typeof n){let e=n.componentType,r=t[e];void 0===r&&(r=0);let a=n.doenetAttributes;a?.isAttributeChild||a?.createdFromSugar||a?.createdFromMacro||(t[e]=++r),n.children&&!n.attributes?.newNamespace?.primitive&&(t=countRegularComponentTypesInNamespace(n.children,t))}return t}function renameAutonameBasedOnNewCounts(e,t={}){let n={...t};for(let t of e)if("object"==typeof t){let e=t.componentType,r=n[e];void 0===r&&(r=0);let a=t.doenetAttributes;if(!(a?.isAttributeChild||a?.createdFromSugar||a?.createdFromMacro)&&(n[e]=++r,t.componentName)){let n=t.componentName.lastIndexOf("/"),a=t.componentName.substring(n+1),i="_"+e.toLowerCase();a.substring(0,i.length)===i&&(t.componentName=t.componentName.substring(0,n+1)+i+r)}t.children&&!t.attributes?.newNamespace?.primitive&&(n=renameAutonameBasedOnNewCounts(t.children,n))}return n}function createComponentNames({serializedComponents:e,namespaceStack:t=[],componentInfoObjects:n,parentDoenetAttributes:r={},parentName:a,useOriginalNames:i=!1,doenetAttributesByTargetComponentName:o,indOffset:s=0,createNameContext:l="",initWithoutShadowingComposite:u=!1}){0===t.length&&t.push({namespace:"",componentCounts:{},namesUsed:{}});let c=t.length-1,p=t[c];for(let[r,d]of e.entries()){if("object"!=typeof d)continue;let e=d.componentType,m=n.allComponentClasses[e],f=d.doenetAttributes;void 0===f&&(f=d.doenetAttributes={});let h=d.attributes;h||(h=d.attributes={}),f.createNameFromComponentType&&(e=f.createNameFromComponentType);let y,b=f.prescribedName,g=f.assignNames,v=f.target,T=f.isAttributeChild||f.createdFromSugar||f.createdFromMacro||f.createUniqueName;(h.newNamespace?.primitive||i&&d.originalAttributes&&d.originalAttributes.newNamespace)&&(y=!0);let N=void 0!==b,C=d.props;if(void 0===C)C=d.props={};else for(let t in C){let n=t.toLowerCase();if("name"===n){if(void 0!==b)throw Error(`Cannot define name twice. Found in component of type ${e}${indexRangeString(d)}`);b=C[t],delete C[t]}else if("assignnames"===n){if(void 0!==g)throw Error(`Cannot define assignNames twice for a component. Found in component of type ${e}${indexRangeString(d)}`);{let n=breakStringInPiecesBySpacesOrParens(C[t]);if(!n.success)throw Error(`Invalid format for assignnames. Found in component of type ${e}${indexRangeString(d)}`);g=n.pieces,delete C[t]}}else if("target"===n){if(void 0!==v)throw Error(`Cannot define target twice for a component. Found in component of type ${e}${indexRangeString(d)}`);if("string"!=typeof C[t])throw Error(`Must specify value for target. Found in component of type ${e}${indexRangeString(d)}`);v=C[t].trim(),delete C[t]}}if(b){if(!N&&!f.createdFromSugar){if(!/[a-zA-Z]/.test(b.substring(0,1)))throw Error(`Invalid component name: ${b}. Component name must begin with a letter. Found in component of type ${e}${indexRangeString(d)}`);if(!/^[a-zA-Z0-9_\-]+$/.test(b))throw Error(`Invalid component name: ${b}. Component name can contain only letters, numbers, hyphens, and underscores. Found in component of type ${e}${indexRangeString(d)}`)}f.prescribedName=b}else if(T){let t=a+"|createUniqueName|";d.downstreamDependencies?t+=JSON.stringify(d.downstreamDependencies):t+=r+"|"+s+"|"+l,b=createUniqueName(e.toLowerCase(),t)}if(!g&&i&&d.originalDoenetAttributes&&d.originalDoenetAttributes.assignNames&&(g=d.originalDoenetAttributes.assignNames),g){if(!m.assignNamesToReplacements)throw Error(`Cannot assign names for component type ${e}${indexRangeString(d)}`);if(f.assignNames=g,!f.createUniqueAssignNames){let t=flattenDeep(g);if(!f.fromCopyTarget&&!f.fromCopyFromURI)for(let n of t){if(!/[a-zA-Z]/.test(n.substring(0,1)))throw Error(`All assigned names must begin with a letter. Found in component of type ${e}${indexRangeString(d)}`);if(!/^[a-zA-Z0-9_\-]+$/.test(n))throw Error(`Assigned names can contain only letters, numbers, hyphens, and underscores. Found in component of type ${e}${indexRangeString(d)}`)}if(t.length!==new Set(t).size)throw Error(`Duplicate assigned names. Found in component of type ${e}${indexRangeString(d)}`)}}y&&(h.newNamespace={primitive:y});let A=p.componentCounts[e];void 0===A&&(A=0),f.isAttributeChild||f.createdFromSugar||f.createdFromMacro||(p.componentCounts[e]=++A);let S="";for(let e=0;e<=c;e++)S+=t[e].namespace+"/";if(!b){if(i&&d.originalName){let e=d.originalName.lastIndexOf("/");b=d.originalName.substring(e+1)}b||(b="_"+e.toLowerCase()+A)}if(f.nameBecomesAssignNames){y&&(h.assignNewNamespaces={primitive:!0},delete h.newNamespace,y=!1),g=f.assignNames=[b],delete f.nameBecomesAssignNames;let e=a+"|createUniqueName|";f.createUniqueName=!0,delete f.prescribedName,d.downstreamDependencies?e+=JSON.stringify(d.downstreamDependencies):e+=r+"|"+s+"|"+l,b=createUniqueName("copy",e)}if(S+=b,d.componentName=S,b){if(b in p.namesUsed)throw Error(`Duplicate component name ${S}. Found in component of type ${e}${indexRangeString(d)}`);p.namesUsed[b]=!0}if(!y&&g)for(let t of flattenDeep(g)){if(t in p.namesUsed)throw Error(`Duplicate component name ${t} (from assignNames of ${S}). Found in component of type ${e}${indexRangeString(d)}`);p.namesUsed[t]=!0}if(d.doenetAttributes.createUniqueAssignNames&&d.originalName){let e=d.doenetAttributes.assignNames;e||(e=d.doenetAttributes.originalAssignNames);let n,r=S+"|createUniqueName|assignNames|",a="";if(y)a=S+"/",n=d.originalName+"/";else{for(let e=0;e<=c;e++)a+=t[e].namespace+"/";let e=d.originalName.lastIndexOf("/");n=d.originalName.slice(0,e+1)}let i=createNewAssignNamesAndRenameMatchingTNames({originalAssignNames:e,longNameIdBase:r,namespace:a,oldNamespace:n,doenetAttributesByTargetComponentName:o});g=d.doenetAttributes.assignNames=i}if(renameMatchingTNames(d,o),v){if(!m.acceptTarget)throw Error(`Component type ${e} does not accept a target attribute. Found in component ${S}${indexRangeString(d)}`);if(v.includes("|"))throw Error(`target cannot include |. Found in component of type ${e}${indexRangeString(d)}`);f.target=v,f.targetComponentName=convertComponentTarget({target:v,oldTargetComponentName:f.targetComponentName,namespaceStack:t,acceptDoubleUnderscore:f.createdFromSugar||f.allowDoubleUnderscoreTarget})}if(d.children)if(y||h.assignNewNamespaces?.primitive){let e={};g&&flattenDeep(g).forEach((t=>e[t]=!0));let r=d.children;if(f.nameFirstChildIndependently&&d.children.length>0){r=r.slice(1);let e={namespace:b,componentCounts:{},namesUsed:{}};t.push(e),createComponentNames({serializedComponents:[d.children[0]],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:f,parentName:S,useOriginalNames:i,doenetAttributesByTargetComponentName:o}),t.pop()}let a={namespace:b,componentCounts:{},namesUsed:e};if(f.haveNewNamespaceOnlyFromShadow){let e=!0,s=[...r];for(;s.length>0;){let r=[];for(let t of s){if(Boolean(t.doenetAttributes?.ignoreParentNewNamespace)===e)break;r.push(t)}s.splice(0,r.length),e?t.push(a):u&&r.forEach((e=>e.doenetAttributes.createUniqueName=!0)),createComponentNames({serializedComponents:r,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:f,parentName:S,useOriginalNames:i,doenetAttributesByTargetComponentName:o}),e&&t.pop(),e=!e}}else t.push(a),createComponentNames({serializedComponents:r,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:f,parentName:S,useOriginalNames:i,doenetAttributesByTargetComponentName:o}),t.pop()}else{let e=d.children;if(f.nameFirstChildIndependently&&e.length>0){e=e.slice(1);let r=p.namesUsed,a=p.componentCounts;p.namesUsed={},p.componentCounts={},createComponentNames({serializedComponents:[d.children[0]],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:f,parentName:S,useOriginalNames:i,doenetAttributesByTargetComponentName:o}),p.namesUsed=r,p.componentCounts=a}createComponentNames({serializedComponents:e,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:f,parentName:S,useOriginalNames:i,doenetAttributesByTargetComponentName:o})}if(d.attributes)for(let e in d.attributes){let r=d.attributes[e];if(r.component){let a=r.component;a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.isAttributeChild=!0,r.ignoreFixed&&(a.doenetAttributes.ignoreParentFixed=!0),createComponentNames({serializedComponents:[a],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:f,parentName:S,useOriginalNames:i,doenetAttributesByTargetComponentName:o,createNameContext:e})}else r.childrenForComponent&&createComponentNames({serializedComponents:r.childrenForComponent,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:f,parentName:S,useOriginalNames:i,doenetAttributesByTargetComponentName:o,createNameContext:e})}}return e}function createNewAssignNamesAndRenameMatchingTNames({originalAssignNames:e,longNameIdBase:t,namespace:n,oldNamespace:r,doenetAttributesByTargetComponentName:a}){let i=[];for(let[o,s]of e.entries())if(Array.isArray(s)){let e=createNewAssignNamesAndRenameMatchingTNames({originalAssignNames:s,longNameIdBase:t+o+"_",namespace:n,oldNamespace:r,doenetAttributesByTargetComponentName:a});i.push(e)}else{let e=createUniqueName("fromAssignNames",t+o);i.push(e),renameMatchingTNames({componentName:n+e,originalName:r+s},a,!0)}return i}function convertComponentTarget({target:e,oldTargetComponentName:t,namespaceStack:n,acceptDoubleUnderscore:r}){if(!t&&/__/.test(e)&&!r)throw Error("Invalid reference target: "+e);let a;if("/"===e.substring(0,1))a=e;else{let t=n.length-1;for(;"../"===e.substring(0,3);)e=e.substring(3),t--;t<0&&(t=0),a="";for(let e=0;e<=t;e++)a+=n[e].namespace+"/";a+=e}return a}function serializedComponentsReplacer(e,t){return t!=t?{objectType:"special-numeric",stringValue:"NaN"}:t===1/0?{objectType:"special-numeric",stringValue:"Infinity"}:t===-1/0?{objectType:"special-numeric",stringValue:"-Infinity"}:t}let nanInfinityReviver=function(e,t){if(t&&"special-numeric"===t.objectType){if("NaN"===t.stringValue)return NaN;if("Infinity"===t.stringValue)return 1/0;if("-Infinity"===t.stringValue)return-1/0}return t};function serializedComponentsReviver(e,t){return me$3.reviver(e,theModule.Subset.reviver(e,nanInfinityReviver(e,t)))}function processAssignNames({assignNames:e=[],assignNewNamespaces:t=!1,serializedComponents:n,parentName:r,parentCreatesNewNamespace:a,componentInfoObjects:i,indOffset:o=0,originalNamesAreConsistent:s=!1,shadowingComposite:l=!1}){let u=n.length;moveComponentNamesToOriginalNames(n);let c={},p=null;if(s){if(u>0){let e=n.filter((e=>"object"==typeof e))[0];if(e&&e.originalName){let t=e.originalName.lastIndexOf("/");p=e.originalName.substring(0,t)}}if(null!==p)for(let e of n)setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:p,components:[e],doenetAttributesByTargetComponentName:c})}else for(let e=0;e0&&t.originalName){let e=t.originalName.lastIndexOf("/");p=t.originalName.substring(0,e)}null!==p&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:p,components:[t],doenetAttributesByTargetComponentName:c})}}let d=[],m=0;for(let f=0;f0&&y.originalName)){let e=y.originalName.lastIndexOf("/");p=y.originalName.substring(0,e)}if(b)if(i.allComponentClasses[y.componentType].assignNamesSkipOver)b=[b];else if(y.attributes?.assignNamesSkip){let e=y.attributes.assignNamesSkip.primitive;if(e>0)for(let t=0;t({namespace:e,componentCounts:{},namesUsed:{}})));"/"!==e[0]&&c.splice(0,0,{componentCounts:{},namesUsed:{},namespace:""}),t.doenetAttributes||(t.doenetAttributes={}),t.attributes||(t.attributes={}),t.attributes.newNamespace?.primitive||o?u=!0:(u=!1,t.children&&markToCreateAllUniqueNames(t.children));for(let e in t.attributes){let n=t.attributes[e];n.component?markToCreateAllUniqueNames([n.component]):n.childrenForComponent&&markToCreateAllUniqueNames(n.childrenForComponent)}createComponentNames({serializedComponents:[t],namespaceStack:c,componentInfoObjects:a,parentName:e,useOriginalNames:u,doenetAttributesByTargetComponentName:i,indOffset:n,initWithoutShadowingComposite:!s})}function setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:t,doenetAttributesByTargetComponentName:n}){let r=e.length;for(let a of t)if("object"==typeof a){if(a.doenetAttributes&&a.doenetAttributes.target){let t=a.doenetAttributes.targetComponentName;void 0!==t&&(t.substring(0,r)!==e&&(a.doenetAttributes.target=t),n[t]||(n[t]=[]),n[t].push(a.doenetAttributes))}if(a.children&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:a.children,doenetAttributesByTargetComponentName:n}),a.attributes)for(let t in a.attributes){let r=a.attributes[t];r.component?setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:[r.component],doenetAttributesByTargetComponentName:n}):r.childrenForComponent&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:r.childrenForComponent,doenetAttributesByTargetComponentName:n})}}}function renameMatchingTNames(e,t,n=!1){if(e.originalName&&t&&e.componentName!==e.originalName){if(t[e.originalName])for(let n of t[e.originalName])n.target=e.componentName,n.targetComponentName=e.componentName;if(n){let n=e.originalName+"/",r=n.length;for(let a in t)if(a.substring(0,r)===n){let n=a.substring(r);for(let r of t[a])r.target=e.componentName+"/"+n,r.targetComponentName=e.componentName+"/"+n}}}}function moveComponentNamesToOriginalNames(e){for(let t of e)if(t.componentName&&(t.originalName=t.componentName,delete t.componentName),t.children&&moveComponentNamesToOriginalNames(t.children),t.attributes)for(let e in t.attributes){let n=t.attributes[e];n.component?moveComponentNamesToOriginalNames([n.component]):n.childrenForComponent&&moveComponentNamesToOriginalNames(n.childrenForComponent)}}function markToCreateAllUniqueNames(e){for(let t of e)if("object"==typeof t&&(t.doenetAttributes||(t.doenetAttributes={}),t.doenetAttributes.createUniqueName=!0,delete t.doenetAttributes.prescribedName,t.attributes?.newNamespace?.primitive||(t.doenetAttributes.assignNames?(t.doenetAttributes.createUniqueAssignNames=!0,t.doenetAttributes.originalAssignNames=t.doenetAttributes.assignNames,delete t.doenetAttributes.assignNames):t.originalDoenetAttributes&&t.originalDoenetAttributes.assignNames&&(t.doenetAttributes.createUniqueAssignNames=!0,t.doenetAttributes.originalAssignNames=t.originalDoenetAttributes.assignNames),t.children&&markToCreateAllUniqueNames(t.children)),t.attributes))for(let e in t.attributes){let n=t.attributes[e];n.component?markToCreateAllUniqueNames([n.component]):n.childrenForComponent&&markToCreateAllUniqueNames(n.childrenForComponent)}}function setTNamesToAbsolute(e){for(let t of e){if(t.doenetAttributes&&t.doenetAttributes.target){let e=t.doenetAttributes.targetComponentName;void 0!==e&&(t.doenetAttributes.target=e)}if(t.children&&setTNamesToAbsolute(t.children),t.attributes)for(let e in t.attributes){let n=t.attributes[e];n.component?setTNamesToAbsolute([n.component]):n.childrenForComponent&&setTNamesToAbsolute(n.childrenForComponent)}}}function restrictTNamesToNamespace({components:e,namespace:t,parentNamespace:n,parentIsCopy:r=!1,invalidateReferencesToBaseNamespace:a=!1}){void 0===n&&(n=t);let i=t.length;for(let o of e){if(o.doenetAttributes&&o.doenetAttributes.target){let e=o.doenetAttributes.target;if("/"===e[0]){if(e.substring(0,i)!==t){let n=t.split("/").slice(1),r=e.split("/").slice(1),a=!1,i=t+e.slice(1);for(;n.length>0&&n[0]===r[0];)n=n.slice(1),r=r.slice(1),a=!0;if(a)i=t+r.join("/");else{let n=t.split("/").slice(1);for(let t=1;tn){r&&t<=n&&a.push({begin:t,end:n,componentName:r}),o=!0;break}r&&s.indBegin>t&&a.push({begin:t,end:s.indBegin-1,componentName:r});let l=extractRangeIndexPieces({componentArray:e.slice(i+1),lastInd:s.indBegin,stopInd:s.indEnd,enclosingComponentName:s.componentName});i+=l.componentsConsumed+1,a.push(...l.rangePieces),t=s.indEnd+1}return!o&&Number.isFinite(n)&&n>=t&&a.push({begin:t,end:n,componentName:r}),{componentsConsumed:i,rangePieces:a}}function createStateProxyHandler(){return{get:function(e,t){let n=e[t];return void 0!==n&&(n=n.isArray&&(n.public||n.trackChanges)?new Proxy(n.value,createArrayProxyHandler({variable:t,nDimensions:n.nDimensions})):n.value),n},set:function(e,t,n){throw Error("Property "+t+" is read-only")},deleteProperty:function(e,t){throw Error("Property "+t+" is read-only")}}}function createArrayProxyHandler({variable:e,nDimensions:t,indicesSoFar:n=[]}){return{variable:e,nDimensions:t,indicesSoFar:n,get:function(e,n){if("then"===n&&e instanceof Promise)return t=>e.then.bind(e)((e=>t(null!==e&&"object"==typeof e?new Proxy(e,createArrayProxyHandler({variable:this.variable,nDimensions:this.nDimensions,indicesSoFar:this.indicesSoFar})):e)));let r=e[n];return null!==r&&"object"==typeof r&&t>1&&(r=new Proxy(r,createArrayProxyHandler({variable:this.variable,nDimensions:this.nDimensions-1,indicesSoFar:[...this.indicesSoFar,n]}))),r},set:function(e,t,n){throw Error("Property "+t+" is read-only")},deleteProperty:function(e,t){throw Error("Property "+t+" is read-only")}}}function postProcessCopy({serializedComponents:e,componentName:t,addShadowDependencies:n=!0,markAsPrimaryShadow:r=!1,uniqueIdentifiersUsed:a=[],identifierPrefix:i="",unlinkExternalCopies:o=!1,copiesByTargetComponentName:s={},componentNamesFound:l=[],assignNamesFound:u=[],activeAliases:c=[],init:p=!0}){for(let d in e){let m,f=e[d];if("object"==typeof f){if(f.originalName){if(o){if(l.push(f.originalName),f.originalDoenetAttributes&&f.originalDoenetAttributes.assignNames){let e;if(f.attributes.newNamespace?.primitive)e=f.originalName;else{let t=f.originalName.lastIndexOf("/");e=f.originalName.substring(0,t)}for(let t of f.originalDoenetAttributes.assignNames)l.push(e+"/"+t),u.push(e+"/"+t)}f.attributes&&(f.attributes.alias&&c.push(f.attributes.alias.primitive),f.attributes.indexAlias&&c.push(f.attributes.indexAlias.primitive))}if(m=i+f.originalName+"|shadow",!f.originalNameFromSerializedComponent)if(n){let e={[f.originalName]:[{dependencyType:"referenceShadow",compositeName:t}]};if(p&&(e[f.originalName][0].firstLevelReplacement=!0),r&&(e[f.originalName][0].isPrimaryShadow=!0),f.state){let t=Object.keys(f.state);e[f.originalName].downstreamStateVariables=t,e[f.originalName].upstreamStateVariables=t}f.downstreamDependencies=e}else f.unlinkedCopySource=f.originalName}else m=i+f.componentType+"|shadowUnnamed";if("copy"===f.componentType&&o){let e=f.doenetAttributes.targetComponentName;if(e)c.includes(f.doenetAttributes.target)?f.doenetAttributes.targetComponentName=f.doenetAttributes.target:(void 0===s[e]&&(s[e]=[]),s[e].push(f));else if(!f.attributes.uri)throw Error("we need to create a targetComponentName here, then.")}f.uniqueIdentifier=getUniqueIdentifierFromBase(m,a)}}for(let p in e){let d=e[p];if("object"==typeof d){postProcessCopy({serializedComponents:d.children,componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:o,copiesByTargetComponentName:s,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1});for(let e in d.attributes){let p=d.attributes[e];p.component&&(p.component=postProcessCopy({serializedComponents:[p.component],componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:o,copiesByTargetComponentName:s,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1})[0])}d.replacements&&postProcessCopy({serializedComponents:d.replacements,componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:o,copiesByTargetComponentName:s,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1})}}if(p&&o)for(let e in s)if(!l.includes(e)){let t=!1;for(let n of u){let r=n+"/",a=r.length;if(e.substring(0,a)===r){t=!0;break}}if(!t)for(let t of s[e])t.attributes||(t.attributes={}),t.attributes.link={primitive:!1},t.doenetAttributes.target=t.doenetAttributes.targetComponentName}return e}function convertAttributesForComponentType({attributes:e,componentType:t,componentInfoObjects:n,compositeAttributesObj:r={},compositeCreatesNewNamespace:a,flags:i}){let o=n.allComponentClasses[t],s=o.createAttributesObject(),l={};for(let e in s)l[e.toLowerCase()]=e;let u={};for(let t in e){if(t in r&&!r[t].leaveRaw)continue;let i=l[t.toLowerCase()],c=s[i];if(c){if(i in u)throw Error(`Cannot repeat prop ${i}`);if(u[i]=componentFromAttribute({attrObj:c,value:JSON.parse(JSON.stringify(e[t])),componentInfoObjects:n}),u[i].component?.children){let e=[u[i].component];if(applyMacros(e,n),removeBlankStringChildren(e,n),applySugar({serializedComponents:e,componentInfoObjects:n,isAttributeComponent:!0}),a)for(let e of u[i].component.children)if("copy"===e.componentType){let t=e.doenetAttributes.target;/[a-zA-Z_]/.test(t[0])&&(e.doenetAttributes.target="../"+t)}}}else o.acceptAnyAttribute&&(u[t]=JSON.parse(JSON.stringify(e[t])))}return u}async function verifyReplacementsMatchSpecifiedType({component:e,replacements:t,replacementChanges:n,assignNames:r,workspace:a={},componentInfoObjects:i,compositeAttributesObj:o,flags:s}){if(!e.attributes.createComponentOfType?.primitive&&!e.sharedParameters.compositesMustHaveAReplacement)return{replacements:t,replacementChanges:n};let l,u=e.replacementsToWithhold;if(n){l=e.replacements.map((e=>e.componentType));for(let e of n)if("add"===e.changeType){if(void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold),!e.changeTopLevelReplacements)continue;if(e.serializedReplacements){let t=e.numberReplacementsToReplace;t>0||(t=0);let n=e.firstReplacementInd,r=e.serializedReplacements.map((e=>e.componentType));l.splice(n,t,...r)}}else if("delete"===e.changeType){if(void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold),e.changeTopLevelReplacements){let t=e.firstReplacementInd,n=e.numberReplacementsToDelete;l.splice(t,n)}}else"changeReplacementsToWithhold"===e.changeType&&void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold)}else i.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"template"})&&(t=t.filter((e=>e.componentType||e.trim().length>0))),l=t.map((e=>e.componentType)),1===l.length&&"externalContent"===l[0]&&(l=t[0].children.filter((e=>e.componentType||e.trim().length>0)).map((e=>e.componentType)));if(u>0&&(l=l.slice(0,l.length-u)),!e.attributes.createComponentOfType?.primitive&&e.sharedParameters.compositesMustHaveAReplacement&&l.length>0)return{replacements:t,replacementChanges:n};let c=e.attributes.createComponentOfType?.primitive,p=await e.stateValues.nComponentsSpecified;if(!c){if(c=e.sharedParameters.compositesDefaultReplacementType,!c)throw Error("A component class specified descendantCompositesMustHaveAReplacement but didn't specify descendantCompositesDefaultReplacementType");p=1}if(c=i.componentTypeLowerCaseMapping[c.toLowerCase()],l.length!==p||!l.every((e=>e===c))){if(1===t?.length&&i.isInheritedComponentType({inheritedComponentType:t[0].componentType,baseComponentType:"template"}))return t[0].attributes||(t[0].attributes={}),t[0].attributes.createComponentOfType={primitive:c},t[0].attributes.nComponents={primitive:p},{replacements:t,replacementChanges:n};let d,m=l.length===p&&!(u>0)&&a.sourceNames?.length===p;m?d=t:(a.numReplacementsBySource=[],a.numNonStringReplacementsBySource=[],a.propVariablesCopiedBySource=[],a.sourceNames=[],a.uniqueIdentifiersUsedBySource={},a.uniqueIdentifiersUsedBySource[0]=[]);let f=e.attributes.newNamespace?.primitive;t=[];for(let n=0;n"string"!=typeof e)).length),n){n=[],e.replacementsToWithhold>0&&n.push({changeType:"changeReplacementsToWithhold",replacementsToWithhold:0});let r=0;e.replacements&&(r=e.replacements.length),n.push({changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:r,serializedReplacements:t})}}return{replacements:t,replacementChanges:n}}function gatherDescendants({ancestor:e,descendantTypes:t,recurseToMatchedChildren:n=!0,useReplacementsForComposites:r=!1,includeNonActiveChildren:a=!1,skipOverAdapters:i=!1,ignoreReplacementsOfMatchedComposites:o=!1,ignoreReplacementsOfEncounteredComposites:s=!1,init:l=!0,componentInfoObjects:u}){let c=e=>t.some((t=>u.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:t}))),p=[];if(r&&u.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"}))l&&p.push(...replacementsForComposites({composite:e,componentInfoObjects:u,includeComposites:a}).filter((e=>"object"==typeof e)));else for(let t of e.allChildrenOrdered){let n,r=e.allChildren[t],o=!1,s=!1;if(r)n=r.component,n.adaptedFrom&&(s=!0),e.activeChildren.includes(n)&&(o=!0);else for(let r of e.activeChildren){if(r.placeholderInd===t){n=r,o=!0,"string"==typeof t&&"adapt"===t.substring(t.length-5,t.length)&&(s=!0);break}if(r.adaptedFrom&&achild.adaptedFrom.placeholderInd===t){n=r.adaptedFrom;break}}n&&(s&&i?p.includes(n.adaptedFrom)||p.push(n.adaptedFrom):(o||a)&&p.push(n))}if(o||s){let e=[];for(let t of p){let n=c(t);s&&!n&&(n=!("copy"===t.componentType&&t.doenetAttributes.copiedURI)),n&&u.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:"_composite"})&&(e=[...e,...replacementsForComposites({composite:t,componentInfoObjects:u,includeComposites:!0}).filter((e=>"object"==typeof e)).map((e=>e.componentName?e.componentName:e.placeholderInd))])}e.length>0&&(p=p.filter((t=>!(e.includes(t.componentName)||e.includes(t.placeholderInd)))))}let d=[];for(let e of p){let l=c(e);if(l&&d.push({componentName:e.componentName?e.componentName:e.placeholderInd,componentType:e.componentType}),(!l||n)&&void 0===e.placeholderInd){let l=gatherDescendants({ancestor:e,descendantTypes:t,recurseToMatchedChildren:n,useReplacementsForComposites:r,includeNonActiveChildren:a,skipOverAdapters:i,ignoreReplacementsOfMatchedComposites:o,ignoreReplacementsOfEncounteredComposites:s,init:!1,componentInfoObjects:u});d.push(...l)}}return d}function replacementsForComposites({composite:e,includeComposites:t=!1,componentInfoObjects:n}){let r=[];if(e.replacements){let a;if(e.replacementsToWithhold){let t=e.replacements.length-e.replacementsToWithhold;a=e.replacements.slice(0,t)}else a=e.replacements;for(let e of a)n.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"})?(t&&r.push(e),r.push(...replacementsForComposites({composite:e,componentInfoObjects:n,includeComposites:t}))):r.push(e)}return r}function ancestorsIncludingComposites(e,t){if(void 0===e.ancestors||0===e.ancestors.length)return[];let n=[e.ancestors[0].componentName],r=t[e.ancestors[0].componentName];if(r&&n.push(...ancestorsIncludingComposites(r,t)),e.replacementOf){n.push(e.replacementOf.componentName);let r=ancestorsIncludingComposites(e.replacementOf,t);for(let e of r)n.includes(e)||n.push(e)}return n}const dependencyTypeArray=[];class DependencyHandler{constructor({_components:e,componentInfoObjects:t,core:n}){this.upstreamDependencies={},this.downstreamDependencies={},this.switchDependencies={},this.circularCheckPassed={},this.circularResolveBlockedCheckPassed={},this.dependencyTypes={},dependencyTypeArray.forEach((e=>this.dependencyTypes[e.dependencyType]=e)),this.core=n,this._components=e,this.componentInfoObjects=t,this.updateTriggers={descendantDependenciesByAncestor:{},ancestorDependenciesByPotentialAncestor:{},replacementDependenciesByComposite:{},childDependenciesByParent:{},parentDependenciesByParent:{},dependenciesMissingComponentBySpecifiedName:{},dependenciesBasedOnDependenciesOfStateVariables:{},primaryShadowDependencies:{}},this.resolveBlockers={neededToResolve:{},resolveBlockedBy:{}}}async setUpComponentDependencies(e){this.downstreamDependencies[e.componentName]&&this.deleteAllDownstreamDependencies({component:e}),this.downstreamDependencies[e.componentName]={},this.upstreamDependencies[e.componentName]||(this.upstreamDependencies[e.componentName]={});let t=[],n=[];for(let r in e.state)e.state[r].isArrayEntry||e.state[r].isAlias||n.includes(r)||(t.push(r),e.state[r].additionalStateVariablesDefined&&n.push(...e.state[r].additionalStateVariablesDefined));for(let n of t){let t=[n];e.state[n].additionalStateVariablesDefined&&t.push(...e.state[n].additionalStateVariablesDefined),await this.setUpStateVariableDependencies({component:e,stateVariable:n,allStateVariablesAffected:t})}}async setUpStateVariableDependencies({component:e,stateVariable:t,allStateVariablesAffected:n}){let r,a=e.state[t];a.stateVariablesDeterminingDependencies?(r={},a.stateVariablesDeterminingDependencies&&(r.__determine_dependencies={dependencyType:"determineDependencies",variableNames:a.stateVariablesDeterminingDependencies})):r=await a.returnDependencies({componentInfoObjects:this.componentInfoObjects,sharedParameters:e.sharedParameters});for(let a in r){let i=r[a];if(!(i.dependencyType in this.dependencyTypes))throw Error(`Unrecognized dependency type ${i.dependencyType} for ${a} of ${t} of ${e.componentName}`);let o=new this.dependencyTypes[i.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:n,dependencyName:a,dependencyDefinition:i,dependencyHandler:this,expandComposites:!1,forceExpandComposites:!1});await o.initialize(),o.checkForCircular()}}deleteAllDownstreamDependencies({component:e,stateVariables:t="__all__"}){let n,r=e.componentName;n="__all__"===t?Object.keys(this.downstreamDependencies[r]):t;for(let e of n){let t=this.downstreamDependencies[r][e];for(let e in t)t[e].deleteDependency();delete this.downstreamDependencies[r][e]}0!==Object.keys(this.downstreamDependencies[r]).length||this.components[r]||delete this.downstreamDependencies[r]}async deleteAllUpstreamDependencies({component:e,stateVariables:t="__all__",completelyDelete:n=!1}){let r,a=e.componentName;r="__all__"===t?Object.keys(this.upstreamDependencies[a]):t;for(let e of r){if(this.upstreamDependencies[a][e])for(let t of[...this.upstreamDependencies[a][e]])if(n){for(let e of t.upstreamVariableNames)this._components[t.upstreamComponentName].state[e].initiallyResolved&&await this.core.markStateVariableAndUpstreamDependentsStale({component:this.components[t.upstreamComponentName],varName:e});t.deleteDependency()}else await t.removeDownstreamComponent({indexToRemove:t.downstreamComponentNames.indexOf(a)});delete this.upstreamDependencies[a][e]}0!==Object.keys(this.upstreamDependencies[a]).length||this._components[a]||delete this.upstreamDependencies[a]}async addBlockersFromChangedStateVariableDependencies({componentName:e,stateVariables:t}){let n=this.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e];if(n)for(let r of t){let t=n[r];if(t)for(let n of t)if(n.gettingValue){let t=n.varsWithUpdatedDeps[e];t||(t=n.varsWithUpdatedDeps[e]=[]),t.includes(r)||t.push(r)}else for(let e of n.upstreamVariableNames)await this.addBlocker({blockerComponentName:n.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:n.dependencyName,componentNameBlocked:n.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e})}}async addBlockersFromChangedActiveChildren({parent:e}){if(await this.collateCountersAndPropagateToAncestors(e),this.updateTriggers.childDependenciesByParent[e.componentName])for(let t of this.updateTriggers.childDependenciesByParent[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}if(e.ancestors){if(this.updateTriggers.parentDependenciesByParent[e.componentName])for(let t of this.updateTriggers.parentDependenciesByParent[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}for(let t of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.addDescendantBlockersToAncestor(t);if(this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])for(let t of this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}}}async resolveBlockersFromChangedActiveChildren(e,t=!1){if(await this.collateCountersAndPropagateToAncestors(e),this.updateTriggers.childDependenciesByParent[e.componentName])for(let n of this.updateTriggers.childDependenciesByParent[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t});if(e.ancestors){if(this.updateTriggers.parentDependenciesByParent[e.componentName])for(let n of this.updateTriggers.parentDependenciesByParent[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t});for(let n of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.resolveDescendantBlockersToAncestor(n,t);if(this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])for(let n of this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t})}}async addDescendantBlockersToAncestor(e){if(this.updateTriggers.descendantDependenciesByAncestor[e])for(let t of this.updateTriggers.descendantDependenciesByAncestor[e]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}}async resolveDescendantBlockersToAncestor(e,t=!1){if(this.updateTriggers.descendantDependenciesByAncestor[e])for(let n of this.updateTriggers.descendantDependenciesByAncestor[e])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t})}async addBlockersFromChangedReplacements(e){if(this.updateTriggers.replacementDependenciesByComposite[e.componentName])for(let t of this.updateTriggers.replacementDependenciesByComposite[e.componentName])for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let t of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.addDescendantBlockersToAncestor(t)}checkForCircularDependency({componentName:e,varName:t,previouslyVisited:n=[]}){let r=e+":"+t;if(n.includes(r)){console.log("found circular",r,n);let e,t=/^(.*):/,a=n.map((e=>e.match(t)[1])),i=a.filter((e=>"__"!==e.slice(0,2))).reduce(((e,t)=>e.includes(t)?e:[...e,t]),[]);throw 0===i.length&&(i=[a[0]]),1===i.length?e=i[0]:2===i.length?e=i.join(" and "):(i[i.length-2]=i.slice(i.length-2).join(", and "),i.pop(),e=i.join(", ")),Error(`Circular dependency involving ${e}`)}if(n=[...n,r],!this.circularCheckPassed[r]&&(this.circularCheckPassed[r]=!0,e in this.downstreamDependencies)){let r=this.downstreamDependencies[e][t];for(let e in r){let t=r[e],a=t.downstreamComponentNames;if(!a)continue;let i=t.mappedDownstreamVariableNamesByComponent;if(i)for(let[e,t]of a.entries()){let r=i[e];for(let e of r)this.checkForCircularDependency({componentName:t,varName:e,previouslyVisited:n})}}}}resetCircularCheckPassed(e,t){let n=e+":"+t;if(this.circularCheckPassed[n]){delete this.circularCheckPassed[n];let r=this.upstreamDependencies[e][t];if(r)for(let e of r)for(let t of e.upstreamVariableNames)"__identity"!==t&&this.resetCircularCheckPassed(e.upstreamComponentName,t)}}async updateDependencies({componentName:e,stateVariable:t,dependency:n}){let r=this._components[e],a=r.state[t],i=[t];a.additionalStateVariablesDefined&&i.push(...a.additionalStateVariablesDefined);let o,s=this.downstreamDependencies[e][t].__determine_dependencies;if(s){let t=!0;if(s.originalDownstreamVariableNames.length>0)for(let[r,a]of s.downstreamComponentNames.entries()){let o=this._components[a];for(let l of s.mappedDownstreamVariableNamesByComponent[r]){let r=o.state[l].isResolved;if(!r){r=(await this.resolveItem({componentName:a,type:"stateVariable",stateVariable:l})).success}if(!r){t=!1;for(let t of i)await this.addBlocker({blockerComponentName:a,blockerType:"stateVariable",blockerStateVariable:l,componentNameBlocked:e,typeBlocked:"determineDependencies",stateVariableBlocked:t,dependencyBlocked:n})}}}if(!t)return{success:!1};o=await s.getValue()}else o={changes:{},value:{stateValues:{}}};if(0===Object.keys(o.changes).length&&void 0!==a._previousValue)return{success:!0};let l={stateValues:Object.assign({},o.value.stateValues),componentInfoObjects:this.componentInfoObjects,sharedParameters:r.sharedParameters},u=await a.returnDependencies(l);a.stateVariablesDeterminingDependencies&&(u.__determine_dependencies={dependencyType:"determineDependencies",variableNames:a.stateVariablesDeterminingDependencies});let c=await this.replaceDependenciesIfChanged({component:r,stateVariable:t,newDependencies:u,allStateVariablesAffected:i});if(!c.changedDependency&&!l.changedDependency)return{success:!0};for(let e of c.newlyCreatedDependencies)e.checkForCircular();for(let e of i)this.checkForCircularDependency({componentName:r.componentName,varName:e}),r.state[e].forceRecalculation=!0;a.initiallyResolved&&await this.core.markStateVariableAndUpstreamDependentsStale({component:r,varName:t});for(let e of i)r.state[e].initiallyResolved&&this.recordActualChangeInUpstreamDependencies({component:r,varName:e});return await this.addBlockersFromChangedStateVariableDependencies({componentName:e,stateVariables:i}),{success:!0}}async replaceDependenciesIfChanged({component:e,stateVariable:t,newDependencies:n,allStateVariablesAffected:r}){let a=this.downstreamDependencies[e.componentName][t],i=!1,o=[];for(let e in a)e in n||(i=!0,a[e].deleteDependency());for(let s in n)if(s in a){if(!deepCompare(n[s],a[s].definition)){i=!0,a[s].deleteDependency();let l=n[s],u=new this.dependencyTypes[l.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:r,dependencyName:s,dependencyDefinition:l,dependencyHandler:this});await u.initialize(),o.push(u)}}else{i=!0;let a=n[s],l=new this.dependencyTypes[a.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:r,dependencyName:s,dependencyDefinition:a,dependencyHandler:this});await l.initialize(),o.push(l)}return{changedDependency:i,newlyCreatedDependencies:o}}async checkForDependenciesOnNewComponent(e){let t=[],n={};if(this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]){for(let r of this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]){let a=this._components[r.upstreamComponentName];if(!a)continue;let i=!0;for(let e of r.upstreamVariableNames)if(!(e in a.state)){i=!1;break}if(i){for(let e of r.upstreamVariableNames){a.state[e].initiallyResolved&&(n[r.upstreamComponentName]&&n[r.upstreamComponentName][e]||t.push({componentName:r.upstreamComponentName,varName:e}))}for(let t of r.upstreamVariableNames)this.deleteFromNeededToResolve({componentNameBlocked:r.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:r.dependencyName,blockerComponentName:e,blockerType:"componentIdentity"});if((await this.resolveIfReady({componentName:r.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:r.representativeStateVariable,dependency:r.dependencyName,expandComposites:!1,recurseUpstream:!0})).success)for(let e of r.upstreamVariableNames)a.state[e].initiallyResolved||(n[r.upstreamComponentName]||(n[r.upstreamComponentName]={}),n[r.upstreamComponentName][e]=!0);else for(let e of r.upstreamVariableNames)await this.addBlocker({blockerComponentName:r.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:r.dependencyName,componentNameBlocked:r.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e})}}delete this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]}return t}async getStateVariableDependencyValues({component:e,stateVariable:t}){let n={},r={},a={},i=this.downstreamDependencies[e.componentName][t];for(let e in i){let{value:t,changes:o,usedDefault:s}=await i[e].getValue();n[e]=t,Object.keys(o).length>0&&(r[e]=o),s&&(a[e]=s)}return{dependencyValues:n,changes:r,usedDefault:a}}recordActualChangeInUpstreamDependencies({component:e,varName:t,changes:n}){let r=e.componentName,a=this.upstreamDependencies[r][t];if(a)for(let i of a)if(i.valuesChanged){let a=i.downstreamComponentNames.indexOf(r),o=i.valuesChanged[a][t];if(!o&&e.stateVarAliases)for(let n in e.stateVarAliases)e.stateVarAliases[n]===t&&n in upValuesChangedSub&&(o=upValuesChangedSub[n]);if(!o){if(!e.state[t].isArrayEntry)throw Error(`Something is wrong, as a variable ${t} of ${e.componentName} actually changed, but wasn't marked with a potential change`);o=upValuesChangedSub[t]={changed:{}}}e.state[t]&&e.state[t].isArray?(void 0===o.changed?o.changed={arrayKeysChanged:{}}:!0===o.changed&&(o.changed={allArrayKeysChanged:!0,arraySizeChanged:!0,arrayKeysChanged:{}}),n&&(n.allArrayKeysChanged&&(o.changed.allArrayKeysChanged=!0),n.arraySizeChanged&&(o.changed.arraySizeChanged=!0),Object.assign(o.changed.arrayKeysChanged,n.arrayKeysChanged))):o.changed=!0}}async collateCountersAndPropagateToAncestors(e){let t=Object.keys(e.counters);for(let n of e.allChildrenOrdered){let e=this._components[n];if(e)for(let n in e.counters)t.includes(n)||t.push(n)}let n=!1;for(let r of t){let t=e.counters[r];t||(t=e.counters[r]={dependencies:[],componentList:[]});let a=[];t.dependencies.length>0&&a.push(e.componentName);for(let t of e.allChildrenOrdered){let e=this._components[t];if(e){let t=e.counters[r];t&&a.push(...t.componentList)}}(a.length!==t.componentList.length||t.componentList.some(((e,t)=>e!=a[t])))&&(n=!0,t.componentList=a)}if(!n)return{foundChange:!1};if(!e.ancestors[0]){for(let n of t){let t=e.counters[n];for(let[e,r]of t.componentList.entries()){let t=this._components[r],a=t.counters[n];a.value=e+1;for(let e of a.dependencies)if(t.state[e.representativeStateVariable].initiallyResolved){await this.core.markStateVariableAndUpstreamDependentsStale({component:t,varName:e.representativeStateVariable});for(let n of e.upstreamVariableNames)t.state[n].forceRecalculation=!0,this.recordActualChangeInUpstreamDependencies({component:t,varName:n})}}}return{foundChange:!0,finishedPropagation:!0}}let r=this._components[e.ancestors[0].componentName];if(!r||!r.allChildrenOrdered.includes(e.componentName))return{foundChange:!0,finishedPropagation:!1};let a=await this.collateCountersAndPropagateToAncestors(r);return a.foundChange||console.error(`we found a change in propagating counters for ${e.componentName}, but no change for ancestors!`),{foundChange:!0,finishedPropagation:a.finishedPropagation}}getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.neededToResolve[e];a||(a=this.resolveBlockers.neededToResolve[e]={});let i=a[t];if(i||(i=a[t]={}),n){let e=i;if(i=e[n],i||(i=e[n]={}),r){let e=i;i=e[r],i||(i=e[r]={})}}return i}deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:t,stateVariableBlocked:n,dependencyBlocked:r,blockerType:a,blockerCode:i,deleteFromReciprocal:o=!0}){let s=e;n&&(s+="|"+n,r&&(s+="|"+r));let l=function(e){if(a){if(e[a])if(i){let n=e[a].indexOf(i);if(-1!==n&&e[a].splice(n,1),0===e[a].length&&delete e[a],o){let[e,n,r]=i.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:a,blockerStateVariable:n,blockerDependency:r,typeBlocked:t,codeBlocked:s,deleteFromReciprocal:!1})}}else{if(o)for(let n of e[a]){let[e,r,i]=n.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:a,blockerStateVariable:r,blockerDependency:i,typeBlocked:t,codeBlocked:s,deleteFromReciprocal:!1})}delete e[a]}}else if(o)for(let n in e)for(let r of e[n]){let[e,a,i]=r.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:n,blockerStateVariable:a,blockerDependency:i,typeBlocked:t,codeBlocked:s,deleteFromReciprocal:!1})}}.bind(this),u=this.resolveBlockers.neededToResolve[e];if(u){let i=u[t];if(i)if(n){let e=i[n];if(e)if(r){let t=e[r];t&&(l(t),a&&0!==Object.keys(t).length||delete e[r]),0===Object.keys(e).length&&delete i[n]}else l(e),a&&0!==Object.keys(e).length||delete i[n];0===Object.keys(i).length&&delete u[t]}else l(i),a&&0!==Object.keys(i).length||delete u[t];0===Object.keys(u).length&&delete this.resolveBlockers.neededToResolve[e]}}checkIfHaveNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.neededToResolve[e];if(!a)return!1;let i=a[t];if(!i)return!1;if(n){if(i=i[n],!i)return!1;if(r){if(i=i[r],!i)return!1}}return Object.keys(i).length>0}getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.resolveBlockedBy[e];a||(a=this.resolveBlockers.resolveBlockedBy[e]={});let i=a[t];if(i||(i=a[t]={}),n){let e=i;if(i=e[n],i||(i=e[n]={}),r){let e=i;i=e[r],i||(i=e[r]={})}}return i}deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,typeBlocked:a,codeBlocked:i,deleteFromReciprocal:o=!0}){let s=e;n&&(s+="|"+n,r&&(s+="|"+r));let l=function(e){if(a){if(e[a])if(i){let n=e[a].indexOf(i);if(-1!==n&&e[a].splice(n,1),0===e[a].length&&delete e[a],o){let[e,n,r]=i.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:a,stateVariableBlocked:n,dependencyBlocked:r,blockerType:t,blockerCode:s,deleteFromReciprocal:!1})}}else{if(o)for(let n of e[a]){let[e,r,i]=n.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:a,stateVariableBlocked:r,dependencyBlocked:i,blockerType:t,blockerCode:s,deleteFromReciprocal:!1})}delete e[a]}}else if(o)for(let n in e)for(let r of e[n]){let[e,a,i]=r.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:n,stateVariableBlocked:a,dependencyBlocked:i,blockerType:t,blockerCode:s,deleteFromReciprocal:!1})}}.bind(this),u=this.resolveBlockers.resolveBlockedBy[e];if(u){let i=u[t];if(i)if(n){let e=i[n];if(e)if(r){let t=e[r];t&&(l(t),a&&0!==Object.keys(t).length||delete e[r]),0===Object.keys(e).length&&delete i[n]}else l(e),a&&0!==Object.keys(e).length||delete i[n];0===Object.keys(i).length&&delete u[t]}else l(i),a&&0!==Object.keys(i).length||delete u[t];0===Object.keys(u).length&&delete this.resolveBlockers.resolveBlockedBy[e]}}async addBlocker({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,componentNameBlocked:a,typeBlocked:i,stateVariableBlocked:o,dependencyBlocked:s}){let l=e;n&&(l+="|"+n,r&&(l+="|"+r));let u=a;o&&(u+="|"+o,s&&(u+="|"+s));let c=this.getNeededToResolve({componentName:a,type:i,stateVariable:o,dependency:s}),p=c[t];if(p||(p=c[t]=[]),p.includes(l))return;if(p.push(l),"stateVariable"===i){let e=this._components[a];if(e){let t=e.state[o];if(t.isResolved=!1,t.initiallyResolved){await this.core.markStateVariableAndUpstreamDependentsStale({component:e,varName:o});let t=this.upstreamDependencies[a][o];if(t)for(let e of t)if(this._components[e.upstreamComponentName])for(let t of e.upstreamVariableNames)await this.addBlocker({blockerComponentName:a,blockerType:"stateVariable",blockerStateVariable:o,componentNameBlocked:e.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t})}}}let d=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r}),m=d[i];m||(m=d[i]=[]),m.includes(u)||m.push(u),this.resetCircularResolveBlockerCheckPassed({componentName:a,type:i,stateVariable:o,dependency:s}),this.checkForCircularResolveBlocker({componentName:a,type:i,stateVariable:o,dependency:s})}async processNewlyResolved({componentNameNewlyResolved:e,typeNewlyResolved:t,stateVariableNewlyResolved:n,dependencyNewlyResolved:r,expandComposites:a=!0,force:i=!1,recurseUpstream:o=!1}){if("stateVariable"===t){let t=this._components[e];if(t){t.state[n]&&(t.state[n].isResolved=!0,t.state[n].initiallyResolved=!0)}}else if("componentIdentity"===t){if(!(e in this._components)&&!i)return{success:!1}}else if("recalculateDownstreamComponents"===t){let t;try{t=this.downstreamDependencies[e][n][r]}catch(e){}if(t){let e=await t.recalculateDownstreamComponents({force:i});if(!e.success&&!i)return e;for(let e of t.upstreamVariableNames)this.deleteFromNeededToResolve({componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e,blockerType:"recalculateDownstreamComponents",blockerCode:t.upstreamComponentName+"|"+e+"|"+r});for(let e of t.upstreamVariableNames)await this.resolveIfReady({componentName:t.upstreamComponentName,type:"stateVariable",stateVariable:e,expandComposites:a,force:i,recurseUpstream:o});return{success:!0}}}else if("determineDependencies"===t){let t;try{t=this.downstreamDependencies[e][n][r]}catch(e){}if(t){let s=this.getNeededToResolve({componentName:e,type:"stateVariable",stateVariable:n}),l=!1,u=[];if(s.determineDependencies)for(let t of s.determineDependencies){let[r,a,i]=t.split("|");if(this.checkIfHaveNeededToResolve({componentName:e,type:"determineDependency",stateVariable:n,dependency:i})){l=!0;break}u.push(i)}if(l)return{success:!0};if(!(await this.updateDependencies({componentName:e,stateVariable:n,dependency:r})).success)return{success:!1};for(let n of t.upstreamVariableNames){for(let e of u)this.deleteFromResolveBlockedBy({blockerComponentName:t.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:n,blockerDependency:e});await this.resolveIfReady({componentName:e,type:"stateVariable",stateVariable:n,expandComposites:a,force:i,recurseUpstream:o})}return{success:!0}}}else if("childMatches"===t){let t=this._components[e];if(t&&!t.childrenMatched){if(!(await this.core.deriveChildResultsFromDefiningChildren({parent:t,expandComposites:a,forceExpandComposites:i})).skipping&&!t.childrenMatchedWithPlaceholders&&!i)return{success:!1}}}else{if("expandComposite"!==t)throw Error(`Unrecognized type newly resolved: ${t}`);if(!this._components[e].isExpanded){if(this.core.updateInfo.compositesBeingExpanded.includes(e))return{success:!1};await this.core.expandCompositeComponent(this._components[e])}}let s=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r});s=Object.assign({},s);for(let l in s)for(let u of[...s[l]])if(this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,typeBlocked:l,codeBlocked:u}),o){let[e,t,n]=u.split("|");await this.resolveIfReady({componentName:e,type:l,stateVariable:t,dependency:n,expandComposites:a,force:i,recurseUpstream:o})}return{success:!0}}async resolveStateVariablesIfReady({component:e,stateVariables:t}){let n=e.componentName;t||(await this.resolveIfReady({componentName:n,type:"componentIdentity",expandComposites:!1}),t=Object.keys(e.state));for(let r of t){let t=e.state[r];if(t&&t.determineDependenciesImmediately){let e=this.getNeededToResolve({componentName:n,type:"stateVariable",stateVariable:r}).determineDependencies;if(e)for(let t of e){let[e,n,r]=t.split("|");await this.resolveIfReady({componentName:e,type:"determineDependencies",stateVariable:n,dependency:r,expandComposites:!0})}}await this.resolveIfReady({componentName:n,type:"stateVariable",stateVariable:r,expandComposites:!1})}}async resolveIfReady({componentName:e,type:t,stateVariable:n,dependency:r,expandComposites:a=!0,force:i=!1,recurseUpstream:o=!1}){return this.checkIfHaveNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r})?{success:!1}:(this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:t,stateVariableBlocked:n,dependencyBlocked:r}),await this.processNewlyResolved({componentNameNewlyResolved:e,typeNewlyResolved:t,stateVariableNewlyResolved:n,dependencyNewlyResolved:r,expandComposites:a,force:i,recurseUpstream:o}))}async resolveItem({componentName:e,type:t,stateVariable:n,dependency:r,force:a=!1,recurseUpstream:i=!1,expandComposites:o=!0,numPreviouslyNeeded:s}){let l,u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}),c=u.determineDependencies;if(c&&c.length>0)for(let e of[...c]){let[t,n,r]=e.split("|"),i=await this.resolveItem({componentName:t,type:"determineDependencies",stateVariable:n,dependency:r,force:a,expandComposites:o});if(!i.success)return i}"stateVariable"===t&&this._components[e]&&(l=this._components[e].state[n],l&&(l.currentlyResolving=!0));let p=1/0,d=1/0;for(;(Object.keys(u).length>0||d>0)&&!(Number.isFinite(d)&&d>=p);){d>0&&(u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r})),p=d,d=0;for(let i in u){if("determineDependencies"===i)throw Error(`Shouldn't have determine dependencies blocker after determining dependencies: ${e}, ${t}, ${n}, ${r}`);for(let e of[...u[i]]){let[t,n,r]=e.split("|"),s=await this.resolveItem({componentName:t,type:i,stateVariable:n,dependency:r,expandComposites:o});if(!s.success){if(!a)return s;d++}}}}if(d>0)for(u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r});Object.keys(u).length>0;)for(let i in u){if("determineDependencies"===i)throw Error(`Shouldn't have determine dependencies blocker after determining dependencies: ${e}, ${t}, ${n}, ${r}`);for(let e of[...u[i]]){let[t,n,r]=e.split("|"),s=await this.resolveItem({componentName:t,type:i,stateVariable:n,dependency:r,force:a,expandComposites:o});if(!s.success)return s}}l&&(l.currentlyResolving=!1);let m=await this.resolveIfReady({componentName:e,type:t,stateVariable:n,dependency:r,force:a,recurseUpstream:i,expandComposites:o});if(!m.success){let l=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}),u=Object.keys(l).length;u>0&&(void 0===s||ue.match(t)[1])),r=n.filter((e=>"__"!==e.slice(0,2))).reduce(((e,t)=>e.includes(t)?e:[...e,t]),[]);0===r.length&&(r=[n[0]]),1===r.length?e=r[0]:2===r.length?e=r.join(" and "):(r[r.length-2]=r.slice(r.length-2).join(", and "),r.pop(),e=r.join(", "));let i=[],s=[];for(let e of a){let[t,n]=e.split("|"),r=this._components[t];if(r){this.componentInfoObjects.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})&&!r.attributes.createComponentOfType?.primitive&&("readyToExpandWhenResolved"===n?i.push(t):n===r.constructor.stateVariableToEvaluateAfterReplacements&&s.push(t))}}let l=!1;for(let e of i)if(s.includes(e)){l=!0;break}let u=`Circular dependency involving ${e}.`;throw l&&(u+=" Specifying the type of a composite component may address this circular dependency."),Error(u)}if(a=[...a,o],!this.circularResolveBlockedCheckPassed[o]){this.circularResolveBlockedCheckPassed[o]=!0;let i=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r});for(let e in i)for(let t of i[e]){let[n,r,i]=t.split("|");this.checkForCircularResolveBlocker({componentName:n,type:e,stateVariable:r,dependency:i,previouslyVisited:a})}}}resetCircularResolveBlockerCheckPassed({componentName:e,type:t,stateVariable:n,dependency:r}){let a=e;n&&(a+="|"+n,r&&(a+="|"+r));let i=a+"|"+t;if(this.circularResolveBlockedCheckPassed[i]){delete this.circularResolveBlockedCheckPassed[i];let a=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r});for(let e in a)for(let t of a[e]){let[n,r,a]=t.split("|");this.resetCircularResolveBlockerCheckPassed({componentName:n,type:e,stateVariable:r,dependency:a})}}}get components(){return this._components}set components(e){return null}}class Dependency{constructor({component:e,stateVariable:t,allStateVariablesAffected:n,dependencyName:r,dependencyDefinition:a,dependencyHandler:i}){this.dependencyName=r,this.dependencyHandler=i,this.upstreamComponentName=e.componentName,this.upstreamVariableNames=n,this.definition=Object.assign({},a),this.representativeStateVariable=t,a.doNotProxy&&(this.doNotProxy=!0),a.variablesOptional&&(this.variablesOptional=!0),a.publicStateVariablesOnly&&(this.publicStateVariablesOnly=!0),a.caseInsensitiveVariableMatch&&(this.caseInsensitiveVariableMatch=!0),a.useMappedVariableNames&&(this.useMappedVariableNames=!0),a.propIndex&&(a.propIndex.every(Number.isFinite)?this.propIndex=a.propIndex.map(Math.round):this.propIndex=[]),this.returnSingleVariableValue=!1,this.returnSingleComponent=!1,this.originalDownstreamVariableNames=[]}static dependencyType="_base";downstreamVariableNameIfNoVariables="__identity";static get rendererType(){return this.componentType}get dependencyType(){return this.constructor.dependencyType}setUpParameters(){}async determineDownstreamComponents(){return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async initialize(){this.setUpParameters();let e=await this.determineDownstreamComponents(),t=e.downstreamComponentNames,n=e.downstreamComponentTypes;this.componentIdentitiesChanged=!0;let r=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName];r||(r=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName]={});for(let e of this.upstreamVariableNames)r[e]||(r[e]={}),r[e][this.dependencyName]=this;0!==this.originalDownstreamVariableNames.length||this.originalVariablesByComponent?(this.mappedDownstreamVariableNamesByComponent=[],this.valuesChanged=[]):(delete this.mappedDownstreamVariableNamesByComponent,delete this.upValuesChanged),this.downstreamComponentNames=[],this.downstreamComponentTypes=[];for(let[e,r]of t.entries())await this.addDownstreamComponent({downstreamComponentName:r,downstreamComponentType:n[e],index:e})}async addDownstreamComponent({downstreamComponentName:e,downstreamComponentType:t,index:n}){this.componentIdentitiesChanged=!0,this.downstreamComponentNames.splice(n,0,e),this.downstreamComponentTypes.splice(n,0,t);let r=this.dependencyHandler._components[e];if(r){let t;t=this.originalVariablesByComponent?this.originalDownstreamVariableNamesByComponent[n]:this.originalDownstreamVariableNames,this.caseInsensitiveVariableMatch&&(t=this.dependencyHandler.core.findCaseInsensitiveMatches({stateVariables:t,componentClass:r.constructor})),this.publicStateVariablesOnly&&(t=this.dependencyHandler.core.matchPublicStateVariables({stateVariables:t,componentClass:r.constructor}));let a=this.dependencyHandler.core.substituteAliases({stateVariables:t,componentClass:r.constructor});this.constructor.convertToArraySize&&(a=a.map((function(e){let t=r.state[e];if(t)return t.arraySizeStateVariable?t.arraySizeStateVariable:`__${e}_is_not_an_array`;if(r.arrayEntryPrefixes){let t=Object.keys(r.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let n of t)if(e.substring(0,n.length)===n){let t=r.arrayEntryPrefixes[n],a=r.state[t];if(a.getArrayKeysFromVarName({arrayEntryPrefix:n,varEnding:e.substring(n.length),nDimensions:a.nDimensions}).length>0)return r.state[t].arraySizeStateVariable}}return`__${e}_is_not_an_array`}))),void 0!==this.propIndex&&(a=await this.dependencyHandler.core.arrayEntryNamesFromPropIndex({stateVariables:a,component:r,propIndex:this.propIndex}));let i=a;if(t.length>0||this.originalVariablesByComponent){this.mappedDownstreamVariableNamesByComponent.splice(n,0,a);let t={};for(let e of a)t[e]={changed:!0};this.valuesChanged.splice(n,0,t),this.variablesOptional&&(i=i.filter((e=>e in r.state||this.dependencyHandler.core.checkIfArrayEntry({stateVariable:e,component:r}))));for(let t of i)if(r.state[t]||await this.dependencyHandler.core.createFromArrayEntry({component:r,stateVariable:t}),!r.state[t].isResolved)for(let n of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:t,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:n}),"determineDependencies"===this.dependencyType&&await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:t,componentNameBlocked:this.upstreamComponentName,typeBlocked:"determineDependencies",stateVariableBlocked:n,dependencyBlocked:this.dependencyName})}0===i.length&&(i=[this.downstreamVariableNameIfNoVariables]);let o=this.dependencyHandler.upstreamDependencies[e];o||(o=this.dependencyHandler.upstreamDependencies[e]={});for(let e of i)if(void 0===o[e]&&(o[e]=[]),o[e].push(this),e!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}async removeDownstreamComponent({indexToRemove:e,recordChange:t=!0}){t&&(this.componentIdentitiesChanged=!0);let n=this.downstreamComponentNames[e];if(this.downstreamComponentNames.splice(e,1),this.downstreamComponentTypes.splice(e,1),n in this.dependencyHandler._components){let t;this.mappedDownstreamVariableNamesByComponent?(t=this.mappedDownstreamVariableNamesByComponent[e],this.mappedDownstreamVariableNamesByComponent.splice(e,1),this.valuesChanged.splice(e,1),this.variablesOptional&&t.push(this.downstreamVariableNameIfNoVariables)):t=[this.downstreamVariableNameIfNoVariables];for(let e of t){let t=this.dependencyHandler.upstreamDependencies[n][e];if(t){let r=t.indexOf(this);-1!==r&&(1===t.length?delete this.dependencyHandler.upstreamDependencies[n][e]:t.splice(r,1))}if(e!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}}if(t)for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}async swapDownstreamComponents(e,t){this.componentIdentitiesChanged=!0,[this.downstreamComponentNames[e],this.downstreamComponentNames[t]]=[this.downstreamComponentNames[t],this.downstreamComponentNames[e]],[this.downstreamComponentTypes[e],this.downstreamComponentTypes[t]]=[this.downstreamComponentTypes[t],this.downstreamComponentTypes[e]],(this.originalDownstreamVariableNames.length>0||this.originalVariablesByComponent)&&([this.mappedDownstreamVariableNamesByComponent[e],this.mappedDownstreamVariableNamesByComponent[t]]=[this.mappedDownstreamVariableNamesByComponent[t],this.mappedDownstreamVariableNamesByComponent[e]],[this.valuesChanged[e],this.valuesChanged[t]]=[this.valuesChanged[t],this.valuesChanged[e]]);for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}deleteDependency(){let e=[];if(this.mappedDownstreamVariableNamesByComponent){if(e=this.mappedDownstreamVariableNamesByComponent,this.variablesOptional){let t=[];for(let[n,r]of this.downstreamComponentNames.entries()){let a=[];for(let t of e[n])this.dependencyHandler.components[r].state[t]&&a.push(t);a.length>0?t.push(a):t.push([this.downstreamVariableNameIfNoVariables])}e=t}}else e=Array(this.downstreamComponentNames.length).fill([this.downstreamVariableNameIfNoVariables]);for(let[t,n]of this.downstreamComponentNames.entries())for(let r of e[t]){let e=this.dependencyHandler.upstreamDependencies[n][r];if(e){let t=e.indexOf(this);-1!==t&&(1===e.length?delete this.dependencyHandler.upstreamDependencies[n][r]:e.splice(t,1))}for(let e of this.upstreamVariableNames)this.dependencyHandler.deleteFromNeededToResolve({componentNameBlocked:this.componentName,typeBlocked:"stateVariable",stateVariableBlocked:e,blockerType:"stateVariable",blockerCode:n+"|"+r});if(r!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}this.deleteFromUpdateTriggers();let t=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName];for(let e of this.upstreamVariableNames)delete t[e][this.dependencyName]}deleteFromUpdateTriggers(){}async getValue({verbose:e=!1,skipProxy:t=!1}={}){let n=[],r={},a=[];this.componentIdentitiesChanged&&(r.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1);for(let[e,t]of this.downstreamComponentNames.entries()){let i=this.dependencyHandler._components[t];if(a[e]=!1,i){let o,s={componentType:i.componentType};if(this.skipComponentNames||(s.componentName=t),o=this.originalVariablesByComponent?this.originalDownstreamVariableNamesByComponent[e]:this.originalDownstreamVariableNames,o.length>0){s.stateValues={};let t={},n=!1;for(let[a,l]of o.entries()){let o=this.mappedDownstreamVariableNamesByComponent[e][a],u=this.useMappedVariableNames?o:l;if(!this.variablesOptional||o in i.state){let a=i.state[o];if(!a.deferred)if(s.stateValues[u]=await a.value,this.valuesChanged[e][o].changed&&(r.valuesChanged||(r.valuesChanged={}),r.valuesChanged[e]||(r.valuesChanged[e]={}),r.valuesChanged[e][u]=this.valuesChanged[e][o]),this.valuesChanged[e][o]={},a.usedDefault)t[u]=!0,n=!0;else if(a.isArrayEntry&&1===a.arrayKeys.length){i.state[a.arrayStateVariable].usedDefaultByArrayKey[a.arrayKeys[0]]&&(t[u]=!0,n=!0)}}}n&&(a[e]=t)}n.push(s)}else n.push({componentType:this.downstreamComponentTypes[e]})}if(!e)if(this.returnSingleVariableValue)if(1===n.length){n=n[0],r.valuesChanged&&r.valuesChanged[0]?r.valuesChanged=r.valuesChanged[0]:delete r.valuesChanged,a=a[0];let e=Object.keys(n.stateValues);if(1===e.length){let t=e[0];n=n.stateValues[t],r.valuesChanged&&r.valuesChanged[t]&&(r.valuesChanged=r.valuesChanged[t]),a&&(a=a[t])}else n=null,r={},a=!1}else n=null,r={},a=!1;else this.returnSingleComponent&&(1===n.length?(n=n[0],r.valuesChanged&&r.valuesChanged[0]?r.valuesChanged=r.valuesChanged[0]:delete r.valuesChanged,a=a[0]):(n=null,a=!1));return{value:n,changes:r,usedDefault:a}}checkForCircular(){for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e);for(let e of this.upstreamVariableNames)this.dependencyHandler.checkForCircularDependency({componentName:this.upstreamComponentName,varName:e})}async recalculateDownstreamComponents({force:e=!1}={}){let t=await this.determineDownstreamComponents({force:e}),n=t.downstreamComponentNames,r=n.length!==this.downstreamComponentNames.length||this.downstreamComponentNames.some(((e,t)=>e!=n[t]));if(r){this.componentIdentitiesChanged=!0;let e=0;for(let[t,r]of[...this.downstreamComponentNames].entries())n.includes(r)||(await this.removeDownstreamComponent({indexToRemove:t-e}),e++);for(let[e,r]of n.entries()){let n=this.downstreamComponentNames.indexOf(r);-1!==n?n!==e&&await this.swapDownstreamComponents(n,e):await this.addDownstreamComponent({downstreamComponentName:r,downstreamComponentType:t.downstreamComponentTypes[e],index:e})}}if(this.originalVariablesByComponent)for(let[e,n]of[...this.downstreamComponentNames].entries())(this.mappedDownstreamVariableNamesByComponent[e].length!==this.originalDownstreamVariableNamesByComponent[e].length||this.mappedDownstreamVariableNamesByComponent[e].some(((t,n)=>this.originalDownstreamVariableNamesByComponent[e][n]!==t)))&&(await this.removeDownstreamComponent({indexToRemove:e}),await this.addDownstreamComponent({downstreamComponentName:n,downstreamComponentType:t.downstreamComponentTypes[e],index:e}));return{success:t.success}}}class StateVariableDependency extends Dependency{static dependencyType="stateVariable";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,void 0===this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableName is not defined`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.returnAsComponentObject?this.returnSingleComponent=!0:this.returnSingleVariableValue=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(StateVariableDependency);class MultipleStateVariablesDependency extends Dependency{static dependencyType="multipleStateVariables";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(MultipleStateVariablesDependency);class StateVariableComponentTypeDependency extends StateVariableDependency{static dependencyType="stateVariableComponentType";async getValue({verbose:e=!1}={}){let t=[],n={};if(this.staticValue)t=[this.staticValue];else if(this.componentIdentitiesChanged&&(n.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let e=this.downstreamComponentNames[0],r=this.dependencyHandler.components[e],a={componentName:r.componentName,componentType:r.componentType,stateValues:{}},i=this.originalDownstreamVariableNames[0],o=this.mappedDownstreamVariableNamesByComponent[0][0],s=this.useMappedVariableNames?o:i;if((!this.variablesOptional||o in r.state)&&!r.state[o].deferred){let e=r.state[o];if(await e.value,a.stateValues[s]=e.componentType,e.isArray&&e.wrappingComponents?.length>0){let t=e.wrappingComponents[e.wrappingComponents.length-1][0];"object"==typeof t&&(t=t.componentType),a.stateValues[s]=t}this.valuesChanged[0][o].changed&&(n.valuesChanged||(n.valuesChanged={}),n.valuesChanged[0]||(n.valuesChanged[0]={}),n.valuesChanged[0][s]=this.valuesChanged[0][o]),this.valuesChanged[0][o]={};let t=e.shadowingInstructions?.hasVariableComponentType;if(!t&&e.isArrayEntry){t=r.state[e.arrayStateVariable].shadowingInstructions?.hasVariableComponentType}t||(this.staticValue=a,await this.removeDownstreamComponent({indexToRemove:0,recordChange:!1}))}t=[a]}if(!e)if(this.returnSingleVariableValue)if(1===t.length){t=t[0];let e=Object.keys(t.stateValues);n.valuesChanged&&n.valuesChanged[0]&&n.valuesChanged[0][0]&&(n.valuesChanged=n.valuesChanged[0][0]),t=1===e.length?t.stateValues[e[0]]:null}else t=null;else this.returnSingleComponent&&(1===t.length?(t=t[0],n.valuesChanged&&n.valuesChanged[0]&&(n.valuesChanged=n.valuesChanged[0])):t=null);return{value:t,changes:n,usedDefault:!1}}}dependencyTypeArray.push(StateVariableComponentTypeDependency);class StateVariableArraySizeDependency extends StateVariableDependency{static dependencyType="stateVariableArraySize";static convertToArraySize=!0}dependencyTypeArray.push(StateVariableArraySizeDependency);class RecursiveDependencyValuesDependency extends Dependency{static dependencyType="recursiveDependencyValues";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,void 0===this.definition.variableNames)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames is not defined`);this.startingVariableNames=this.definition.variableNames,this.originalVariablesByComponent=!0,this.includeImmediateValueWithValue=this.definition.includeImmediateValueWithValue,this.includeRawValueWithImmediateValue=this.definition.includeRawValueWithImmediateValue,this.includeOnlyEssentialValues=this.definition.includeOnlyEssentialValues,this.variablesOptional=!0}async determineDownstreamComponents({force:e=!1}={}){this.missingComponents=[],this.originalDownstreamVariableNamesByComponent=[];let t=await this.getRecursiveDependencyVariables({componentName:this.componentName,variableNames:this.startingVariableNames,force:e});if(!t.success)return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=[],r=[];for(let e in t.components)if(this.includeOnlyEssentialValues){let a=[],i=this.dependencyHandler._components[e];for(let n of t.components[e].variableNames)(i.state[n]?.hasEssential||i.state[n]?.isArrayEntry&&i.state[i.state[n].arrayStateVariable].hasEssential)&&a.push(n);a.length>0&&(n.push(e),r.push(t.components[e].componentType),this.originalDownstreamVariableNamesByComponent.push(a))}else n.push(e),r.push(t.components[e].componentType),this.originalDownstreamVariableNamesByComponent.push(t.components[e].variableNames);return{success:!0,downstreamComponentNames:n,downstreamComponentTypes:r}}async getRecursiveDependencyVariables({componentName:e,variableNames:t,force:n,components:r={}}){let a=this.dependencyHandler._components[e];if(!a){if(!this.missingComponents.includes(e)){let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];t||(t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]=[]),t.includes(this)||t.push(this)}for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});return{success:!1}}this.includeImmediateValueWithValue&&t.includes("value")&&!t.includes("immediateValue")&&"immediateValue"in a.state&&(t=[...t,"immediateValue"]),this.includeRawValueWithImmediateValue&&t.includes("immediateValue")&&!t.includes("rawRendererValue")&&"rawRendererValue"in a.state&&(t=[...t,"rawRendererValue"]);let i=r[e];i||(i=r[e]={componentName:e,componentType:a.componentType,variableNames:[]});let o=this.dependencyHandler.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e];o||(o=this.dependencyHandler.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e]={});for(let s of t)if(!i.variableNames.includes(s)){i.variableNames.push(s);let t=o[s];t||(t=o[s]=[]),t.includes(this)||t.push(this);let l=a.state[s];if(l){if(!l.isResolved){if(!n){for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:s,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});return{success:!1}}await l.value}let t=this.dependencyHandler.downstreamDependencies[a.componentName][s];for(let e in t){let a=t[e];for(let[e,t]of a.downstreamComponentNames.entries()){let i=[];if((a.originalDownstreamVariableNames.length>0||a.originalVariablesByComponent)&&(i=a.mappedDownstreamVariableNamesByComponent[e]),!(await this.getRecursiveDependencyVariables({componentName:t,variableNames:i,force:n,components:r})).success)return{success:!1}}}}}return{success:!0,components:r}}async getValue(){let e;this.gettingValue=!0,this.varsWithUpdatedDeps={};let t={},n=!0,r={};for(;n;){if(n=!1,e=await super.getValue(),e.changes.valuesChanged)if(r.valuesChanged)for(let t in e.changes.valuesChanged){let n=e.changes.valuesChanged[t];if(r.valuesChanged[t])for(let e in n)r.valuesChanged[t][e]=n[e];else r.valuesChanged[t]=n}else r.valuesChanged=e.changes.valuesChanged;for(let e in this.varsWithUpdatedDeps){let r=t[e];r||(r=t[e]=[]);for(let t of this.varsWithUpdatedDeps[e])r.includes(t)||(r.push(t),n=!0)}n&&await this.recalculateDownstreamComponents()}return this.gettingValue=!1,e.changes=r,e}deleteFromUpdateTriggers(){for(let e of this.missingComponents){let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}}dependencyTypeArray.push(RecursiveDependencyValuesDependency);class ComponentIdentityDependency extends Dependency{static dependencyType="componentIdentity";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ComponentIdentityDependency);class AttributeComponentDependency extends Dependency{static dependencyType="attributeComponent";setUpParameters(){if(this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.attributeName=this.definition.attributeName,this.returnSingleComponent=!0,this.shadowDepth=0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=e.attributes[this.attributeName];if(this.shadowDepth=0,t?.component)return{success:!0,downstreamComponentNames:[t.component.componentName],downstreamComponentTypes:[t.component.componentType]};let n=e;for(;n.shadows;){let e=n.shadows,r=n.shadows.propVariable;if(n=this.dependencyHandler._components[e.componentName],!n)break;if(r){if(!n.state[r]?.shadowingInstructions?.attributesToShadow?.includes(this.attributeName)&&!n.constructor.createAttributesObject()[this.attributeName]?.propagateToProps)break}else{let t=this.dependencyHandler._components[e.compositeName];if("sourceAttributesToIgnoreRecursively"in t.state){if((await t.stateValues.sourceAttributesToIgnoreRecursively).includes(this.attributeName))break}if(e.firstLevelReplacement&&"sourceAttributesToIgnore"in t.state){if((await t.stateValues.sourceAttributesToIgnore).includes(this.attributeName))break}}if(this.shadowDepth++,t=n.attributes[this.attributeName],t?.component)return{success:!0,downstreamComponentNames:[t.component.componentName],downstreamComponentTypes:[t.component.componentType]}}return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0});return t.value&&(t.value.shadowDepth=this.shadowDepth),t}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AttributeComponentDependency);class ChildDependency extends Dependency{static dependencyType="child";setUpParameters(){if(this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];if(this.childGroups=this.definition.childGroups,!Array.isArray(this.childGroups))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: childGroups must be an array`);void 0!==this.definition.childIndices&&(this.childIndices=this.definition.childIndices.map((e=>Number(e)))),this.skipComponentNames=this.definition.skipComponentNames,this.skipPlaceholders=this.definition.skipPlaceholders,this.proceedIfAllChildrenNotMatched=this.definition.proceedIfAllChildrenNotMatched}async determineDownstreamComponents(){this.downstreamPrimitives?this.previousDownstreamPrimitives=[...this.downstreamPrimitives]:this.previousDownstreamPrimitives=[],this.downstreamPrimitives=[];let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];t||(t=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName]=[]),t.includes(this)||t.push(this);let n=e.returnMatchedChildIndices(this.childGroups);if(void 0===n)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: childGroups ${this.childGroups} does not exist.`);if(this.childIndices&&(n=n.filter(((e,t)=>this.childIndices.includes(t)))),!e.childrenMatched&&!this.proceedIfAllChildrenNotMatched){let t=!1;if(e.childrenMatchedWithPlaceholders&&(this.skipPlaceholders&&(n=n.filter((t=>!e.placeholderActiveChildrenIndices.includes(t)))),t=!(!this.skipComponentNames||0!==this.originalDownstreamVariableNames.length)||n.every((t=>!e.placeholderActiveChildrenIndices.includes(t)))),!t){let t=e.unexpandedCompositesNotReady.length>0;if(!t&&e.unexpandedCompositesReady.length>0){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(t){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});let t=[],r=[];for(let a of e.unexpandedCompositesNotReady){if(e.childrenMatchedWithPlaceholders){if(e.placeholderActiveChildrenIndicesByComposite[a].every((e=>!n.includes(e))))continue}this.dependencyHandler._components[a].attributes.createComponentOfType?.primitive?t.push(a):r.push(a)}let a=r;0===a.length&&(a=t);for(let e of a)for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.upstreamComponentName,typeBlocked:"childMatches",stateVariableBlocked:t});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}}}let r=n.map((t=>e.activeChildren[t]));if(this.compositeReplacementRange=[],e.compositeReplacementActiveRange&&r.length>0){let t=0;for(;t=r){let e=t,i=t;for(;a.lastInd>r&&t=r);)i=t;if(this.compositeReplacementRange.push({compositeName:a.compositeName,target:a.target,firstInd:e,lastInd:i}),t++,t===n.length)break;r=n[t]}t++}}this.shadowDepthByChild=[];for(let t of r){let n=0,r=t,a=e;for(;r?.shadows&&r.shadows.compositeName===a?.shadows?.compositeName;)n++,a=this.dependencyHandler._components[a.shadows.componentName],r=this.dependencyHandler._components[r.shadows.componentName];this.shadowDepthByChild.push(n)}this.activeChildrenIndices=n;let a=[],i=[];for(let[e,t]of r.entries())"object"==typeof t?(this.downstreamPrimitives.push(null),a.push(t.componentName?t.componentName:`__placeholder_${e}`),i.push(t.componentType)):this.downstreamPrimitives.push(t);return{success:!0,downstreamComponentNames:a,downstreamComponentTypes:i}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0}),n=[],r=0;for(let[e,a]of this.downstreamPrimitives.entries())if(null===a){t.value[r].shadowDepth=this.shadowDepthByChild[e],n.push(t.value[r]),r++}else n.push(a);return n.compositeReplacementRange=this.compositeReplacementRange,t.value=n,(this.downstreamPrimitives.length!==this.previousDownstreamPrimitives.length||this.downstreamPrimitives.some(((e,t)=>e!==this.previousDownstreamPrimitives[t])))&&(t.changes.componentIdentitiesChanged=!0,this.previousDownstreamPrimitives=[...this.downstreamPrimitives]),t}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ChildDependency);class DescendantDependency extends Dependency{static dependencyType="descendant";setUpParameters(){if(this.definition.ancestorName?(this.ancestorName=this.definition.ancestorName,this.specifiedComponentName=this.ancestorName):this.ancestorName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.componentTypes=this.definition.componentTypes,this.recurseToMatchedChildren=this.definition.recurseToMatchedChildren,this.useReplacementsForComposites=this.definition.useReplacementsForComposites,this.includeNonActiveChildren=this.definition.includeNonActiveChildren,this.includeAttributeChildren=this.definition.includeAttributeChildren,this.skipOverAdapters=this.definition.skipOverAdapters,this.ignoreReplacementsOfMatchedComposites=this.definition.ignoreReplacementsOfMatchedComposites,this.ignoreReplacementsOfEncounteredComposites=this.definition.ignoreReplacementsOfEncounteredComposites,null!==this.definition.componentIndex&&void 0!==this.definition.componentIndex&&(Number.isInteger(this.definition.componentIndex)?this.componentIndex=this.definition.componentIndex:this.componentIndex=NaN)}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.ancestorName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.ancestorName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName];t||(t=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName]=[]),t.includes(this)||t.push(this);let n=this.gatherUnexpandedComposites(e);if(n.haveCompositesNotReady||n.haveUnexpandedCompositeReady){for(let e of this.upstreamVariableNames){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let t in n.unexpandedCompositesReadyByParentName)await this.dependencyHandler.addBlocker({blockerComponentName:t,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName});for(let t in n.unexpandedCompositesNotReadyByParentName)await this.dependencyHandler.addBlocker({blockerComponentName:t,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName})}return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let r=gatherDescendants({ancestor:e,descendantTypes:this.componentTypes,recurseToMatchedChildren:this.recurseToMatchedChildren,useReplacementsForComposites:this.useReplacementsForComposites,includeNonActiveChildren:this.includeNonActiveChildren,skipOverAdapters:this.skipOverAdapters,ignoreReplacementsOfMatchedComposites:this.ignoreReplacementsOfMatchedComposites,ignoreReplacementsOfEncounteredComposites:this.ignoreReplacementsOfEncounteredComposites,componentInfoObjects:this.dependencyHandler.componentInfoObjects});if(void 0!==this.componentIndex){let e=r[this.componentIndex-1];r=e?[e]:[]}return{success:!0,downstreamComponentNames:r.map((e=>e.componentName)),downstreamComponentTypes:r.map((e=>e.componentType))}}gatherUnexpandedComposites(e){let t={},n={},r=!1,a=!1,i=this.skipComponentNames&&0===this.originalDownstreamVariableNames.length;if(!e.childrenMatched)if(e.childrenMatchedWithPlaceholders){if(e.unexpandedCompositesReady.length>0){let n=this.unexpandedCompositesAdjustedForPlacedholders(e.unexpandedCompositesReady,i);n.length>0&&(t[e.componentName]=n,r=!0)}if(e.unexpandedCompositesNotReady.length>0){let t=this.unexpandedCompositesAdjustedForPlacedholders(e.unexpandedCompositesNotReady,i);t.length>0&&(n[e.componentName]=t,a=!0)}}else e.unexpandedCompositesReady.length>0&&(t[e.componentName]=e.unexpandedCompositesReady,r=!0),e.unexpandedCompositesNotReady.length>0&&(n[e.componentName]=e.unexpandedCompositesNotReady,a=!0);for(let i in e.allChildren){let o=e.allChildren[i].component;if("object"==typeof o){let e=this.gatherUnexpandedComposites(o);e.haveUnexpandedCompositeReady&&(Object.assign(t,e.unexpandedCompositesReadyByParentName),r=!0),e.haveCompositesNotReady&&(Object.assign(n,e.unexpandedCompositesNotReadyByParentName),a=!0)}}return{unexpandedCompositesReadyByParentName:t,haveUnexpandedCompositeReady:r,unexpandedCompositesNotReadyByParentName:n,haveCompositesNotReady:a}}unexpandedCompositesAdjustedForPlacedholders(e,t){let n=[];for(let r of e){let e=this.dependencyHandler._components[r];if(e.attributes.createComponentOfType){let a=this.dependencyHandler.componentInfoObjects.componentTypeLowerCaseMapping[e.attributes.createComponentOfType.primitive.toLowerCase()],i=this.componentTypes.some((e=>this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:a,baseComponentType:e})));i&&t||n.push(r)}else n.push(r)}return n}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(DescendantDependency);class ParentDependency extends Dependency{static dependencyType="parentStateVariable";setUpParameters(){if(this.definition.childName?(this.childName=this.definition.childName,this.specifiedComponentName=this.childName):this.childName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.parentComponentType&&(this.parentComponentType=this.definition.parentComponentType),this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.childName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.childName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(this.parentComponentType&&!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.parentComponentType}))return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];return n||(n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}dependencyTypeArray.push(ParentDependency);class ParentIdentityDependency extends Dependency{static dependencyType="parentIdentity";setUpParameters(){this.definition.childName?(this.childName=this.definition.childName,this.specifiedComponentName=this.childName):this.childName=this.upstreamComponentName,this.definition.parentComponentType&&(this.parentComponentType=this.definition.parentComponentType),this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.childName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.childName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(this.parentComponentType&&!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.parentComponentType}))return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];return n||(n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}dependencyTypeArray.push(ParentIdentityDependency);class AncestorDependency extends Dependency{static dependencyType="ancestor";setUpParameters(){if(this.definition.descendantName?(this.descendantName=this.definition.descendantName,this.specifiedComponentName=this.descendantName):this.descendantName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.definition.componentType&&(this.componentType=this.definition.componentType)}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.descendantName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.descendantName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.descendantName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.descendantName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!(this.dependencyHandler.core.documentName in this.dependencyHandler._components)){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e}),await this.dependencyHandler.addBlocker({blockerComponentName:this.dependencyHandler.core.documentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.findMatchingAncestor(e);if(t.missingComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[t.missingComponentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[t.missingComponentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:t.missingComponentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}for(let e of t.ancestorsExamined){let t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e];t||(t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e]=[]),t.includes(this)||t.push(this)}return this.ancestorResults=t,t.ancestorFound?{success:!0,downstreamComponentNames:[t.ancestorFound.componentName],downstreamComponentTypes:[t.ancestorFound.componentClass.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}findMatchingAncestor(e){let t=[];if(this.componentType){for(let n of e.ancestors){let e=this.dependencyHandler._components[n.componentName];if(!e)return{missingComponentName:n.componentName};if(t.push(n.componentName),this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:this.componentType}))return{ancestorsExamined:t,ancestorFound:n}}return{ancestorsExamined:t}}if(0===this.originalDownstreamVariableNames.length)return console.warn(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must specify componentType or variableNames to find ancestor`),{ancestorsExamined:t};let n=this.originalDownstreamVariableNames;for(let r of e.ancestors){let e=this.dependencyHandler._components[r.componentName];if(!e)return{missingComponentName:r.componentName};t.push(r.componentName);let a=!0;for(let t of n)if(!(t in e.state)&&!this.dependencyHandler.core.checkIfArrayEntry({stateVariable:t,component:e})){a=!1;break}if(a)return{ancestorsExamined:t,ancestorFound:r}}return{ancestorsExamined:t}}deleteFromUpdateTriggers(){for(let e of this.ancestorResults.ancestorsExamined){let t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}if(this.ancestorResults&&this.ancestorResults.missingComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorResults.missingComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AncestorDependency);class ReplacementDependency extends Dependency{static dependencyType="replacement";setUpParameters(){if(this.definition.compositeName?(this.compositeName=this.definition.compositeName,this.specifiedComponentName=this.compositeName):this.compositeName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.recursive=this.definition.recursive,this.recurseNonStandardComposites=this.definition.recurseNonStandardComposites,null!==this.definition.componentIndex&&void 0!==this.definition.componentIndex&&(Number.isInteger(this.definition.componentIndex)?this.componentIndex=this.definition.componentIndex:this.componentIndex=NaN),this.definition.targetSubnames&&(this.targetSubnames=this.definition.targetSubnames),this.definition.targetSubnamesComponentIndex&&(this.definition.targetSubnamesComponentIndex.every(Number.isInteger)?this.targetSubnamesComponentIndex=this.definition.targetSubnamesComponentIndex:this.targetSubnamesComponentIndex=[NaN]),this.includeWithheldReplacements=this.definition.includeWithheldReplacements,this.expandReplacements=!0}async determineDownstreamComponents(){this.replacementPrimitives?this.previousReplacementPrimitives=[...this.replacementPrimitives]:this.previousReplacementPrimitives=[],this.replacementPrimitives=[];let e=this.dependencyHandler._components[this.compositeName];if(!e){let a=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.compositeName];a||(a=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.compositeName]=[]),a.includes(this)||a.push(this);for(let i of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:i,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:i,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:i});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.isExpanded){for(let o of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:o,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:o}),await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"expandComposite",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:o,dependencyBlocked:this.dependencyName});return e.state.readyToExpandWhenResolved.isResolved||await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.compositeName,typeBlocked:"expandComposite"}),{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}this.compositesFound=[this.compositeName];let t=e.replacements;if(!this.includeWithheldReplacements&&e.replacementsToWithhold>0&&(t=t.slice(0,-e.replacementsToWithhold)),this.recursive){let s=this.dependencyHandler.core.recursivelyReplaceCompositesWithReplacements({replacements:t,recurseNonStandardComposites:this.recurseNonStandardComposites,includeWithheldReplacements:this.includeWithheldReplacements});if(s.unexpandedCompositesNotReady.length>0||s.unexpandedCompositesReady.length>0){for(let l of this.upstreamVariableNames){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:l,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:l});for(let u of[...s.unexpandedCompositesReady,...s.unexpandedCompositesNotReady])await this.dependencyHandler.addBlocker({blockerComponentName:u,blockerType:"expandComposite",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:l,dependencyBlocked:this.dependencyName})}for(let c of s.unexpandedCompositesNotReady)await this.dependencyHandler.addBlocker({blockerComponentName:c,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:c,typeBlocked:"expandComposite"});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}t=s.newReplacements,this.compositesFound.push(...s.compositesFound)}for(let p of this.compositesFound){let d=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[p];d||(d=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[p]=[]),d.includes(this)||d.push(this)}if(void 0!==this.componentIndex){let m=t[this.componentIndex-1];t=m?[m]:[]}if(this.targetSubnames){function f({components:e,subNames:t,subNamesComponentIndex:n,dep:r}){if(0===t.length)return e;let a=t.slice(1),i=[];for(let o of e){let e=o.componentName+"/"+t[0],s=r.dependencyHandler._components[e];if(s)r.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"_composite"})?console.warn("Have not yet implemented recursing subnames to multiple levels of composites"):0===a.length&&(n?.length,1)&&i.push(s);else{let t=r.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];t||(t=r.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]=[]),t.includes(r)||t.push(r)}}return i}t=f({components:t,subNames:this.targetSubnames,subNamesComponentIndex:this.targetSubnamesComponentIndex,dep:this})}let n=[],r=[];for(let h of t)"object"==typeof h?(this.replacementPrimitives.push(null),n.push(h.componentName),r.push(h.componentType)):this.replacementPrimitives.push(h);return{success:!0,downstreamComponentNames:n,downstreamComponentTypes:r}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0}),n=[],r=0;for(let e of this.replacementPrimitives)null===e?(n.push(t.value[r]),r++):n.push(e);return t.value=n,(this.replacementPrimitives.length!==this.previousReplacementPrimitives.length||this.replacementPrimitives.some(((e,t)=>e!==this.previousReplacementPrimitives[t])))&&(t.changes.componentIdentitiesChanged=!0,this.previousReplacementPrimitives=[...this.replacementPrimitives]),t}deleteFromUpdateTriggers(){if(this.compositesFound)for(let e of this.compositesFound){let t=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ReplacementDependency);class SourceCompositeStateVariableDependency extends Dependency{static dependencyType="sourceCompositeStateVariable";setUpParameters(){if(this.definition.replacementName?(this.replacementName=this.definition.replacementName,this.specifiedComponentName=this.replacementName):this.replacementName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.compositeComponentType&&(this.compositeComponentType=this.definition.compositeComponentType),this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.replacementName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.replacementName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.replacementOf;if(this.compositeComponentType)for(;!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.compositeComponentType});){if(!t.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};t=t.replacementOf}return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SourceCompositeStateVariableDependency);class SourceCompositeIdentityDependency extends Dependency{static dependencyType="sourceCompositeIdentity";setUpParameters(){this.definition.replacementName?(this.replacementName=this.definition.replacementName,this.specifiedComponentName=this.replacementName):this.replacementName=this.upstreamComponentName,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.replacementName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.replacementName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.replacementOf;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SourceCompositeIdentityDependency);class ShadowSourceDependency extends Dependency{static dependencyType="shadowSource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.shadows)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.shadows.componentName,n=this.dependencyHandler._components[t];return n?{success:!0,downstreamComponentNames:[n.componentName],downstreamComponentTypes:[n.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ShadowSourceDependency);class UnlinkedCopySourceDependency extends Dependency{static dependencyType="unlinkedCopySource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.unlinkedCopySource)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.unlinkedCopySource,n=this.dependencyHandler._components[t];return n?{success:!0,downstreamComponentNames:[n.componentName],downstreamComponentTypes:[n.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(UnlinkedCopySourceDependency);class PrimaryShadowDependency extends Dependency{static dependencyType="primaryShadow";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.primaryShadowDependencies[this.componentName];if(t||(t=this.dependencyHandler.updateTriggers.primaryShadowDependencies[this.componentName]=[]),t.includes(this)||t.push(this),!e.primaryShadow)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=e.primaryShadow,r=this.dependencyHandler._components[n];return r?{success:!0,downstreamComponentNames:[r.componentName],downstreamComponentTypes:[r.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(PrimaryShadowDependency);class AdapterSourceStateVariableDependency extends Dependency{static dependencyType="adapterSourceStateVariable";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.adaptedFrom)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.adaptedFrom;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AdapterSourceStateVariableDependency);class AdapterSourceDependency extends Dependency{static dependencyType="adapterSource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.adaptedFrom)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.adaptedFrom;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AdapterSourceDependency);class CountAmongSiblingsDependency extends Dependency{static dependencyType="countAmongSiblingsOfSameType";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return console.warn(`component ${this.componentName} does not have a parent for state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}.`),{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let n=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(n||(n=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),!t.childrenMatched){if(!t.childrenMatchedWithPlaceholders){let e=t.unexpandedCompositesNotReady.length>0;if(!e&&t.unexpandedCompositesReady.length>0){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(e){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let e of t.unexpandedCompositesNotReady)for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.upstreamComponentName,typeBlocked:"childMatches",stateVariableBlocked:t});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}}}return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}async getValue(){let e=this.dependencyHandler.components[this.upstreamComponentName].componentType,t=this.dependencyHandler.components[this.parentName].activeChildren.filter((t=>t.componentType===e)),n=t.map((e=>e.componentName)).indexOf(this.upstreamComponentName)+1;if(this.parentName===this.dependencyHandler.core.documentName){let t=this.dependencyHandler.core.previousComponentTypeCounts[e];t&&(n+=t)}return{value:n,changes:{}}}}dependencyTypeArray.push(CountAmongSiblingsDependency);class TargetComponentDependency extends Dependency{static dependencyType="targetComponent";setUpParameters(){let e=this.dependencyHandler._components[this.upstreamComponentName];if(this.target=e.doenetAttributes.target,this.target&&(this.targetComponentName=this.specifiedComponentName=e.doenetAttributes.targetComponentName),this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0}async determineDownstreamComponents(){if(!this.target)return{downstreamComponentNames:[],downstreamComponentTypes:[]};let e=this.dependencyHandler._components[this.targetComponentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.targetComponentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.targetComponentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.targetComponentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.targetComponentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}dependencyTypeArray.push(TargetComponentDependency);class ExpandTargetNameDependency extends Dependency{static dependencyType="expandTargetName";setUpParameters(){this.parentName=this.upstreamComponentName,this.target=this.definition.target}async getValue(){let e,t=this.dependencyHandler._components[this.parentName].attributes.newNamespace?.primitive,n=this.parentName.split("/").map((e=>({namespace:e})));t||(n=n.slice(0,n.length-1));try{e=convertComponentTarget({target:this.target,namespaceStack:n})}catch(t){e=null}return{value:e,changes:{}}}}dependencyTypeArray.push(ExpandTargetNameDependency);class ValueDependency extends Dependency{static dependencyType="value";setUpParameters(){this.value=this.definition.value}async getValue(){return{value:this.value,changes:{}}}}dependencyTypeArray.push(ValueDependency);class FlagDependency extends ValueDependency{static dependencyType="flag";setUpParameters(){this.flagName=this.definition.flagName,this.value=this.dependencyHandler.core.flags[this.flagName]}}dependencyTypeArray.push(FlagDependency);class DoenetAttributeDependency extends StateVariableDependency{static dependencyType="doenetAttribute";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){e=this.dependencyHandler.components[this.downstreamComponentNames[0]].doenetAttributes[this.attributeName]}return{value:e,changes:t}}}dependencyTypeArray.push(DoenetAttributeDependency);class AttributePrimitiveDependency extends StateVariableDependency{static dependencyType="attributePrimitive";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.parentName?(this.componentName=this.definition.parentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let t=this.dependencyHandler.components[this.componentName];t&&(e=t.attributes[this.attributeName],e=e?e.primitive:null)}return{value:e,changes:t}}}dependencyTypeArray.push(AttributePrimitiveDependency);class SerializedChildrenDependency extends Dependency{static dependencyType="serializedChildren";setUpParameters(){this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler._components[this.parentName].serializedChildren,changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SerializedChildrenDependency);class VariantsDependency extends Dependency{static dependencyType="variants";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler._components[this.componentName].variants,changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(VariantsDependency);class CounterDependency extends Dependency{static dependencyType="counter";setUpParameters(){this.counterName=this.definition.counterName,this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName],t=e.counters[this.counterName];return t||(t=e.counters[this.counterName]={dependencies:[],componentList:[],value:null}),t.dependencies.includes(this)||t.dependencies.push(this),await this.dependencyHandler.collateCountersAndPropagateToAncestors(e),{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async getValue(){return{value:this.dependencyHandler._components[this.componentName].counters[this.counterName].value,changes:{}}}}dependencyTypeArray.push(CounterDependency);class DetermineDependenciesDependency extends Dependency{static dependencyType="determineDependencies";setUpParameters(){if(this.recalculateDependencies=!0,this.definition.componentName?this.componentName=this.definition.componentName:this.componentName=this.upstreamComponentName,void 0===this.definition.variableNames)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames is not defined`);this.originalDownstreamVariableNames=this.definition.variableNames,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}async markStale(){let e=this.dependencyHandler._components[this.upstreamComponentName];for(let t of this.upstreamVariableNames)if(!(e&&e.state[t]&&e.state[t].currentlyResolving)){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});for(let e in this.dependencyHandler.downstreamDependencies[this.upstreamComponentName][t]){"determineDependencies"!==this.dependencyHandler.downstreamDependencies[this.upstreamComponentName][t][e].dependencyType&&await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:e})}}}}dependencyTypeArray.push(DetermineDependenciesDependency);class FileDependency extends Dependency{static dependencyType="file";setUpParameters(){this.cid=this.definition.cid,this.uri=this.definition.uri,this.fileType=this.definition.fileType}async getValue(){let e;if(this.cid){if("csv"!==this.fileType.toLowerCase())return{value:null,changes:{}};return e="csv",{value:await retrieveTextFileForCid(this.cid,e),changes:{}}}{let e=await fetch(this.uri);if(e.ok){return{value:await e.text(),changes:{}}}return{value:null,changes:{}}}}}dependencyTypeArray.push(FileDependency);var appliedFunctionSymbolsDefault=["abs","exp","log","ln","log10","sign","sqrt","erf","acos","acosh","acot","acoth","acsc","acsch","asec","asech","asin","asinh","atan","atanh","cos","cosh","cot","coth","csc","csch","sec","sech","sin","sinh","tan","tanh","arcsin","arccos","arctan","arccsc","arcsec","arccot","cosec","arg","min","max","mean","median","floor","ceil","round","sum","prod","variance","std","count","mod","re","im","det","trace"],appliedFunctionSymbolsDefaultLatex=["abs","exp","log","ln","log10","sign","sqrt","erf","acos","acosh","acot","acoth","acsc","acsch","asec","asech","asin","asinh","atan","atanh","cos","cosh","cot","coth","csc","csch","sec","sech","sin","sinh","tan","tanh","arcsin","arccos","arctan","arccsc","arcsec","arccot","cosec","arg","min","max","mean","median","floor","ceil","round","sum","prod","variance","std","count","mod","Re","Im","det","trace"];let allowedLatexSymbols=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","varnothing","emptyset"];var textToAst$1=new me$3.converters.textToAstObj({appliedFunctionSymbols:appliedFunctionSymbolsDefault});function getFromText({functionSymbols:e,appliedFunctionSymbols:t=appliedFunctionSymbolsDefault,splitSymbols:n=!0,parseScientificNotation:r=!1}){return a=>me$3.fromAst(new me$3.converters.textToAstObj({appliedFunctionSymbols:t,functionSymbols:e,splitSymbols:n,parseScientificNotation:r}).convert(a))}var latexToAst=new me$3.converters.latexToAstObj({appliedFunctionSymbols:appliedFunctionSymbolsDefaultLatex,allowedLatexSymbols:allowedLatexSymbols});function getFromLatex({functionSymbols:e,appliedFunctionSymbols:t=appliedFunctionSymbolsDefaultLatex,splitSymbols:n=!0,parseScientificNotation:r=!1}){return n?n=>me$3.fromAst(new me$3.converters.latexToAstObj({appliedFunctionSymbols:t,functionSymbols:e,allowedLatexSymbols:allowedLatexSymbols,parseScientificNotation:r}).convert(wrapWordIncludingNumberWithVar(n,r))):n=>me$3.fromAst(new me$3.converters.latexToAstObj({appliedFunctionSymbols:t,functionSymbols:e,allowedLatexSymbols:allowedLatexSymbols,parseScientificNotation:r}).convert(wrapWordWithVar(n,r)))}function normalizeMathExpression({value:e,simplify:t,expand:n=!1,createVectors:r=!1,createIntervals:a=!1}){return r&&(e=e.tuples_to_vectors()),a&&(e=e.to_intervals()),n&&(e=e.expand()),"full"===t?e.simplify():"numbers"===t?e.evaluate_numbers():"numberspreserveorder"===t?e.evaluate_numbers({skip_ordering:!0}):e}function findFiniteNumericalValue(e){if(void 0!==e)return Number.isFinite(e)||void 0!==e.evaluate_to_constant&&(e=e.evaluate_to_constant(),Number.isFinite(e))?e:null}function convertValueToMathExpression(e){return e instanceof me$3.class?e:"number"==typeof e||"string"==typeof e||Array.isArray(e)?me$3.fromAst(e):me$3.fromAst("_")}function returnNVariables(e,t){if(!Number.isInteger(e)||e<1)return[];let n=t.length;if(0===n){if(1===e)return[me$3.fromAst("x")];if(2===e)return[me$3.fromAst("x"),me$3.fromAst("y")];if(3===e)return[me$3.fromAst("x"),me$3.fromAst("y"),me$3.fromAst("z")];{let t=[];for(let n=1;n<=e;n++)t.push(me$3.fromAst(textToAst$1.convert(`x_${n}`)));return t}}if(new Set(t.map((e=>e.toString()))).sizee.toString()))],a=[...t];for(let t=n+1;t<=e;t++){let n;n=1==t?e>3?["x_1"]:["x"]:2==t?e>3?["x_2","y_2"]:["y","x_2"]:3==t?e>3?["x_3","y_3","z_3"]:["z","x_3","z_3"]:["x","y","z","u","v","w","X","Y","Z"].map((e=>`${e}_${t}`));let i=!1;for(let e of n)if(!r.includes(e)){a.push(me$3.fromAst(textToAst$1.convert(e))),r.push(e),i=!0;break}if(!i){let e=n[0];a.push(me$3.fromAst(textToAst$1.convert(e))),r.push(e),console.warn("Variables added were not unique")}}return a}async function preprocessMathInverseDefinition({desiredValue:e,stateValues:t,variableName:n="value",arrayKey:r,workspace:a}){if("tuple"!==e.tree[0]&&"vector"!==e.tree[0]||!e.tree.includes())return{desiredValue:e};let i,o=n+"Ast";if(void 0!==r&&(o+=`_${r}`),a[o])i=a[o].slice(0,e.tree.length);else{let a=await t[n];a&&void 0!==r&&(a=a[r]),!a||"tuple"!==a.tree[0]&&"vector"!==a.tree[0]||(i=a.tree.slice(0,e.tree.length))}if(i){let t=[],n=!1;for(let[r,a]of e.tree.entries())void 0===a?(n=!0,t.push(r)):i[r]=a;return e=me$3.fromAst(i),a[o]=i,n?{desiredValue:e,vectorComponentsNotAffected:t}:{desiredValue:e}}{let t=[];for(let n of e.tree.slice(1))void 0===n?t.push("_"):t.push(n);return{desiredValue:e=me$3.fromAst([e.tree[0],...t])}}}function normalizeLatexString(e,{unionFromU:t=!1}={}){let n=[["α","\\alpha "],["β","\\beta "],["ϐ","\\beta "],["Γ","\\Gamma "],["γ","\\gamma "],["Δ","\\Delta "],["δ","\\delta "],["ε","\\epsilon "],["ϵ","\\epsilon "],["ζ","\\zeta "],["η","\\eta "],["Θ","\\Theta "],["ϴ","\\Theta "],["θ","\\theta "],["ᶿ","\\theta "],["ϑ","\\theta "],["ι","\\iota "],["κ","\\kappa "],["Λ","\\Lambda "],["λ","\\lambda "],["μ","\\mu "],["µ","\\mu "],["ν","\\nu "],["Ξ","\\Xi "],["ξ","\\xi "],["Π","\\Pi "],["π","\\pi "],["ϖ","\\pi "],["ρ","\\rho "],["ϱ","\\rho "],["Σ","\\Sigma "],["σ","\\sigma "],["ς","\\sigma "],["τ","\\tau "],["Υ","\\Upsilon "],["υ","\\upsilon "],["Φ","\\Phi "],["φ","\\phi "],["ϕ","\\phi "],["Ψ","\\Psi "],["ψ","\\psi "],["Ω","\\Omega "],["ω","\\omega "],["−","-"],["⋅"," \\cdot "],["·"," \\cdot "],["∪"," \\cup "],["∩"," \\cap "],["∞"," \\infty "],["∅"," \\emptyset "]];for(let t of n)e=e.replaceAll(t[0],t[1]);let r=e.match(/^(\\ )*(\\ldots|\.(\\ )*\.(\\ )*\.)(\\ )*(.*)$/);if(r){let t=r[6];e=","!==t[0]?"\\ldots,"+t:"\\ldots"+t}let a=e.match(/^(.*?)(\\ )*(\\ldots|\.(\\ )*\.(\\ )*\.)(\\ )*$/);if(a){let t=a[1];e=","!==t[t.length-1]?t+",\\ldots":t+"\\ldots"}return e=(e=e.replaceAll(/(\b|\\ )or(\b|\\ )/g,"$1\\lor$2")).replaceAll(/(\b|\\ )and(\b|\\ )/g,"$1\\land$2"),t&&(e=e.replaceAll(/(\b|\\ )U(\b|\\ )/g,"$1\\cup$2")),e}function isValidVariable(e){let t=e.tree,n=!0;return"string"==typeof t?"_"===t&&(n=!1):(!Array.isArray(t)||"_"!==t[0]||"string"!=typeof t[1]||"string"!=typeof t[2]&&"number"!=typeof t[2])&&(n=!1),n}function mathStateVariableFromNumberStateVariable({numberVariableName:e="number",mathVariableName:t="math",isPublic:n=!1}={}){let r={returnDependencies:()=>({number:{dependencyType:"stateVariable",variableName:e}}),definition:function({dependencyValues:e}){return{setValue:{[t]:numberToMathExpression(e.number)}}},inverseDefinition:function({desiredStateVariableValues:e}){let n=e[t].evaluate_to_constant();return null===n&&(n=NaN),{success:!0,instructions:[{setDependency:"number",desiredValue:n}]}}};return n&&(r.public=!0,r.shadowingInstructions={createComponentOfType:"math"}),r}function numberToMathExpression(e){let t;if("number"==typeof e?.re&&"number"==typeof e?.im)if(0===e.im)t=e.re;else{let n;n=1===e.im?"i":-1===e.im?["-","i"]:["*",e.im,"i"],t=0===e.re?n:["+",e.re,n]}else t=e;return me$3.fromAst(t)}function roundForDisplay({value:e,dependencyValues:t,usedDefault:n}){let r;return!n.displayDigits&&t.displayDigits>=1||n.displayDecimals||!Number.isFinite(t.displayDecimals)?(r=t.displayDigits>=1?me$3.round_numbers_to_precision(e,t.displayDigits):me$3.round_numbers_to_precision(e,10),t.displaySmallAsZero>0&&(r=me$3.evaluate_numbers(r,{skip_ordering:!0,set_small_zero:t.displaySmallAsZero}))):r=me$3.round_numbers_to_decimals(e,t.displayDecimals),r}function mergeListsWithOtherContainers(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);return["tuple","vector","list","set"].includes(t)&&(n=n.reduce(((e,t)=>Array.isArray(t)&&"list"===t[0]?[...e,...t.slice(1)]:[...e,t]),[])),n=n.map((e=>mergeListsWithOtherContainers(e))),[t,...n]}function wrapWordWithVar(e,t){let n="",r=/\\var\s*{[^{}]*}/,a=e.match(r);for(;a;){let i=a.index,o=i+a[0].length;n+=wrapWordWithVarSub(e.substring(0,i),t),n+=e.substring(i,o),a=(e=e.substring(o)).match(r)}return n+=wrapWordWithVarSub(e,t),n}function wrapWordWithVarSub(e,t){let n="";const r=/([^a-zA-Z0-9]?)([a-zA-Z][a-zA-Z0-9]+)([^a-zA-Z0-9]?)/;let a;if(t){const e="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))";a=new RegExp("([0-9]+(\\.[0-9]*)?"+e+")|(\\.[0-9]+"+e+")")}let i=e.match(r);for(;i;){let o=i.index,s=o+i[0].length-i[3].length;if(t){let t=e.match(a);if(t&&t.indexo){n+=e.substring(0,s),i=(e=e.substring(s)).match(r);continue}}if("\\"===i[1])n+=e.substring(0,s),e=e.substring(s);else{let t=o+i[1].length;n+=e.substring(0,t),n+=`\\var{${i[2]}}`,e=e.substring(s)}i=e.match(r)}return n+=e,n}function wrapWordIncludingNumberWithVar(e,t){let n="",r=/\\var\s*{[^{}]*}/,a=e.match(r);for(;a;){let i=a.index,o=i+a[0].length;n+=wrapWordIncludingNumberWithVarSub(e.substring(0,i),t),n+=e.substring(i,o),a=(e=e.substring(o)).match(r)}return n+=wrapWordIncludingNumberWithVarSub(e,t),n}function wrapWordIncludingNumberWithVarSub(e,t){let n="";const r=/([^a-zA-Z0-9\s]?\s*)([a-zA-Z][a-zA-Z0-9]*[0-9][a-zA-Z0-9]*)([^a-zA-Z0-9]?)/;let a;if(t){const e="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))";a=new RegExp("([0-9]+(\\.[0-9]*)?"+e+")|(\\.[0-9]+"+e+")")}let i=e.match(r);for(;i;){let o=i.index,s=o+i[0].length-i[3].length;if(t){let t=e.match(a);if(t&&t.indexo){n+=e.substring(0,s),i=(e=e.substring(s)).match(r);continue}}if("\\"===i[1]||"^"===i[1][0]||"_"===i[1][0])n+=e.substring(0,s),e=e.substring(s);else{let t=o+i[1].length;n+=e.substring(0,t),n+=`\\var{${i[2]}}`,e=e.substring(s)}i=e.match(r)}return n+=e,n}function stripLatex(e){return e.replaceAll("\\,","").replaceAll(/\\var{([^{}]*)}/g,"$1")}function superSubscriptsToUnicode(e){let t={0:"₀",1:"₁",2:"₂",3:"₃",4:"₄",5:"₅",6:"₆",7:"₇",8:"₈",9:"₉","+":"₊","-":"₋"," ":""},n={0:"⁰",1:"¹",2:"²",3:"³",4:"⁴",5:"⁵",6:"⁶",7:"⁷",8:"⁸",9:"⁹","+":"⁺","-":"⁻"," ":""};function r(e,n){let r="";for(let e of n)r+=t[e];return r}function a(e,t){let r="";for(let e of t)r+=n[e];return r}return e=(e=(e=(e=e.replaceAll(/_(\d+)/g,r)).replaceAll(/_\(([\d +-]+)\)/g,r)).replaceAll(/\^(\d+)/g,a)).replaceAll(/\^\(([\d +-]+)\)/g,a)}function unicodeToSuperSubscripts(e){let t={"₀":"0","₁":"1","₂":"2","₃":"3","₄":"4","₅":"5","₆":"6","₇":"7","₈":"8","₉":"9","₊":"+","₋":"-"},n={"⁰":"0","¹":"1","²":"2","³":"3","⁴":"4","⁵":"5","⁶":"6","⁷":"7","⁸":"8","⁹":"9","⁺":"+","⁻":"-"};return e=(e=e.replaceAll(/([\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u208A\u208B]+)/g,(function(e,n){let r="";for(let e of n)r+=t[e];return"_("+r+")"}))).replaceAll(/([\u2070\u00B9\u00B2\u00B3\u2074\u2075\u2076\u2077\u2078\u2079\u207A\u207B]+)/g,(function(e,t){let r="";for(let e of t)r+=n[e];return"^("+r+")"}))}function renameStateVariable({stateVariableDefinitions:e,oldName:t,newName:n}){let r=e[n]=e[t];if(delete e[t],r.additionalStateVariablesDefined){let e=r.additionalStateVariablesDefined.indexOf(t);-1!==e&&(r.additionalStateVariablesDefined[e]=n)}let a=r.definition,i=["setValue","useEssentialOrDefaultValue","setEssentialValue"],o=["noChanges"];r.definition=function(e){let r=a(e);for(let e of i)r[e]&&t in r[e]&&(r[e][n]=r[e][t],delete r[e][t]);for(let e of o)if(r[e]){let a=r[e].indexOf(t);-1!==a&&(r[e][a]=n)}return r};let s=r.inverseDefinition;s&&(r.inverseDefinition=async function(e){let r=e.desiredStateVariableValues;r[t]=r[n],delete r[n];let a=await s(e);if(a.success)for(let e of a.instructions)e.setEssentialValue===t&&(e.setEssentialValue=n);return a})}function returnDefaultGetArrayKeysFromVarName(e){return e>1?function({arrayEntryPrefix:e,varEnding:t,arraySize:n,nDimensions:r}){let a=t.split("_").map((e=>Number(e)-1));return a.length===r&&a.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?a.every(((e,t)=>e=0?n?r{let t="",n=crypto.getRandomValues(new Uint8Array(e));for(;e--;){let r=63&n[e];t+=r<36?r.toString(36):r<62?(r-26).toString(36).toUpperCase():r<63?"_":"-"}return t},core,queuedRequestActions=[];async function createCore(e){core=new Core(e),core.getInitializedPromise().then((()=>{for(let e of queuedRequestActions)core.requestAction(e);queuedRequestActions=[]}))}async function returnAllStateVariables(e){if(!e.components)return{};let t={};for(let n in e.components){let r=e.components[n],a=t[n]={componentName:n,componentType:r.componentType,stateValues:{}};for(let e in r.state)a.stateValues[e]=removeFunctionsMathExpressionClass(await r.state[e].value);a.activeChildren=r.activeChildren.map((e=>e.componentName?{componentName:e.componentName,componentType:e.componentType}:e)),r.replacements&&(a.replacements=r.replacements.map((e=>e.componentName?{componentName:e.componentName,componentType:e.componentType}:e)),void 0!==r.replacementsToWithhold&&(a.replacementsToWithhold=r.replacementsToWithhold)),a.sharedParameters=removeFunctionsMathExpressionClass(r.sharedParameters)}return t}function removeFunctionsMathExpressionClass(e){if(e instanceof me$3.class)e=e.tree;else if("function"==typeof e)e=void 0;else if(Array.isArray(e))e=e.map((e=>removeFunctionsMathExpressionClass(e)));else if("object"==typeof e&&null!==e){let t={};for(let n in e)t[n]=removeFunctionsMathExpressionClass(e[n]);e=t}return e}onmessage=function(e){"createCore"===e.data.messageType?createCore(e.data.args):"requestAction"===e.data.messageType?core?.initialized?core.requestAction(e.data.args):queuedRequestActions.push(e.data.args):"returnAllStateVariables"===e.data.messageType?(console.log("all components"),console.log(core._components),returnAllStateVariables(core).then((e=>{postMessage({messageType:"returnAllStateVariables",args:e})}))):"visibilityChange"===e.data.messageType?core.handleVisibilityChange(e.data.args):"terminate"===e.data.messageType?core.terminate().then((()=>{postMessage({messageType:"terminated"})})):"navigatingToComponent"===e.data.messageType?core.handleNavigatingToComponent(e.data.args.componentName):"submitAllAnswers"===e.data.messageType&&core.requestAction({componentName:core.documentName,actionName:"submitAllAnswers",args:e.data.args})};let styleAttributes={lineColor:{componentType:"text"},lineColorWord:{componentType:"text"},lineOpacity:{componentType:"number"},lineWidth:{componentType:"number"},lineWidthWord:{componentType:"text"},lineStyle:{componentType:"text"},lineStyleWord:{componentType:"text"},markerColor:{componentType:"text"},markerColorWord:{componentType:"text"},markerStyle:{componentType:"text"},markerStyleWord:{componentType:"text"},markerSize:{componentType:"number"},fillColor:{componentType:"text"},fillColorWord:{componentType:"text"},fillOpacity:{componentType:"number"}},defaultStyle={lineColor:"#648FFF",lineColorWord:"blue",lineOpacity:.7,lineWidth:4,lineWidthWord:"thick",lineStyle:"solid",lineStyleWord:"",markerColor:"#648FFF",markerColorWord:"blue",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"#648FFF",fillColorWord:"blue",fillOpacity:.3};function returnDefaultStyleDefinitions(){return{1:{lineColor:"#648FFF",lineColorWord:"blue",lineOpacity:.7,lineWidth:4,lineWidthWord:"thick",lineStyle:"solid",lineStyleWord:"",markerColor:"#648FFF",markerColorWord:"blue",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"#648FFF",fillColorWord:"blue",fillOpacity:.3},2:{lineColor:"#D4042D",lineColorWord:"red",lineOpacity:.7,lineWidth:2,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#D4042D",markerColorWord:"red",markerStyle:"square",markerStyleWord:"square",markerSize:5,fillColor:"#D4042D",fillColorWord:"red",fillOpacity:.3},3:{lineColor:"#F19143",lineColorWord:"orange",lineOpacity:.7,lineWidth:3,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#F19143",markerColorWord:"orange",markerStyle:"triangle",markerStyleWord:"triangle",markerSize:5,fillColor:"#F19143",fillColorWord:"orange",fillOpacity:.3},4:{lineColor:"#644CD6",lineColorWord:"purple",lineOpacity:.7,lineWidth:2,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#644CD6",markerColorWord:"purple",markerStyle:"diamond",markerStyleWord:"diamond",markerSize:5,fillColor:"#644CD6",fillColorWord:"purple",fillOpacity:.3},5:{lineColor:"black",lineColorWord:"black",lineOpacity:.7,lineWidth:1,lineWidthWord:"thin",lineStyle:"solid",lineStyleWord:"",markerColor:"black",markerColorWord:"black",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"black",fillColorWord:"black",fillOpacity:.3},6:{lineColor:"gray",lineColorWord:"gray",lineOpacity:.7,lineWidth:1,lineWidthWord:"thin",lineStyle:"dotted",lineStyleWord:"dotted",markerColor:"gray",markerColorWord:"gray",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"gray",fillColorWord:"gray",fillOpacity:.3}}}function returnStyleDefinitionStateVariables(){let e={setupChildren:{returnDependencies:()=>({setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}}),definition:({dependencyValues:e})=>({setValue:{setupChildren:e.setupChildren}})}};return e.styleDefinitions={stateVariablesDeterminingDependencies:["setupChildren"],returnDependencies({stateValues:e}){let t={ancestorWithStyle:{dependencyType:"ancestor",variableNames:["styleDefinitions"]},setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}};for(let n of e.setupChildren)t[`styleDefinitionsOf${n.componentName}`]={dependencyType:"child",parentName:n.componentName,childGroups:["styleDefinitions"],variableNames:["value"]};return t},definition({dependencyValues:e}){let t,n={};e.ancestorWithStyle&&(t=e.ancestorWithStyle.stateValues.styleDefinitions),t||(t=returnDefaultStyleDefinitions());for(let e in t)n[e]=Object.assign({},t[e]);let r=[];for(let t of e.setupChildren)r.push(...e[`styleDefinitionsOf${t.componentName}`]);for(let e of r){let t=e.stateValues.value;for(let e in t){let r=n[e];r||(r=n[e]=Object.assign({},defaultStyle));let a=Object.assign({},t[e]);"markerColor"in a&&!("markerColorWord"in a)&&(a.markerColorWord=a.markerColor),"markerStyle"in a&&!("markerStyleWord"in a)&&(a.markerStyleWord=a.markerStyle,"circle"===a.markerStyleWord?a.markerStyleWord="point":"triangle"===a.markerStyleWord.slice(0,8)&&(a.markerStyleWord="triangle")),"lineColor"in a&&!("lineColorWord"in a)&&(a.lineColorWord=a.lineColor),"fillColor"in a&&!("fillColorWord"in a)&&(a.fillColorWord=a.fillColor),"lineWidth"in a&&!("lineWidthWord"in a)&&(a.lineWidth>=4?a.lineWidthWord="thick":a.lineWidth<=1?a.lineWidthWord="thin":a.lineWidthWord=""),"lineStyle"in a&&!("lineStyleWord"in a)&&("dashed"===a.lineStyle?a.lineStyleWord="dashed":"dotted"===a.lineStyle?a.lineStyleWord="dotted":a.lineStyleWord=""),Object.assign(r,a)}}return{setValue:{styleDefinitions:n}}}},e}function returnSelectedStyleStateVariableDefinition(){return{selectedStyle:{forRenderer:!0,willNeverBeEssential:!0,returnDependencies:()=>({styleNumber:{dependencyType:"stateVariable",variableName:"styleNumber"},ancestorWithStyle:{dependencyType:"ancestor",variableNames:["styleDefinitions"]}}),definition:function({dependencyValues:e}){let t=e.ancestorWithStyle.stateValues.styleDefinitions;t||(t=returnDefaultStyleDefinitions());let n=t[e.styleNumber];return void 0===n&&(n=defaultStyle),{setValue:{selectedStyle:n}}}}}}function enumerateSelectionCombinations({numberOfIndices:e,numberOfOptions:t,maxNumber:n=1/0,withReplacement:r=!1,skipZero:a=!1}){if(1===e){let e=[...Array(t).keys()];return e=e.slice(1),a||(e=[...e,0]),e=e.slice(0,n),e=e.map((e=>[e])),e}let i=enumerateSelectionCombinations({numberOfIndices:e-1,numberOfOptions:t,maxNumber:n,withReplacement:r,skipZero:!r}),o=[],s=0;for(let e of i)for(let r=1;r<=t;r++){let i=[r%t,...e.map((e=>(r+e)%t))];if((!a||!i.includes(0))&&(o.push(i),s++,s>=n))return o}return o}function enumerateCombinations({numberOfOptionsByIndex:e,maxNumber:t=1/0}){let n=e.length;if(0===n)return[];let r=[];for(let t=0;t[...t,...e]),[]).reduce(((e,t)=>Math.max(e,t)),1);if(1===a){let n=e.reduce(((e,t)=>e*t));n=Math.min(n,t);let r=[];for(let t=0;tt%e));r.push(n)}return r}if(2===n){let n=a,r=me$3.math.lcm(...e),i=[],o=0;for(let a=0;a=t)return i}return i}let i=[];for(let t=0;t1?n.push(me$3.math.lcm(e[t],e[a])):n.push(null);i.push(n)}let o,s=i.reduce(((e,t)=>[...t,...e]),[]).filter((e=>null!==e)).reduce(((e,t)=>Math.min(e,t)),1/0);for(let e=0;e{if(0===e.length)n.push(a);else for(let i=0;i=t)return}};return r(e),n}function returnStandardSequenceAttributes(){return{type:{createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"number",toLowerCase:!0,validValues:["number","math","letters"]},from:{createComponentOfType:"_componentWithSelectableType"},to:{createComponentOfType:"_componentWithSelectableType"},step:{createComponentOfType:"math"},length:{createComponentOfType:"number"},exclude:{createComponentOfType:"_componentListWithSelectableType"}}}function returnStandardSequenceStateVariableDefinitions(){let e={specifiedFrom:{returnDependencies:()=>({fromAttr:{dependencyType:"attributeComponent",attributeName:"from",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"from",definition:function({dependencyValues:e}){return null===e.fromAttr?{useEssentialOrDefaultValue:{specifiedFrom:!0}}:null===e.fromAttr.stateValues.value?{setValue:{specifiedFrom:NaN}}:{setValue:{specifiedFrom:e.fromAttr.stateValues.value}}}},specifiedTo:{returnDependencies:()=>({toAttr:{dependencyType:"attributeComponent",attributeName:"to",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"to",definition:function({dependencyValues:e}){return null===e.toAttr?{useEssentialOrDefaultValue:{specifiedTo:!0}}:null===e.toAttr.stateValues.value?{setValue:{specifiedTo:NaN}}:{setValue:{specifiedTo:e.toAttr.stateValues.value}}}},specifiedLength:{returnDependencies:()=>({lengthAttr:{dependencyType:"attributeComponent",attributeName:"length",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"length",definition:function({dependencyValues:e}){return null===e.lengthAttr?{useEssentialOrDefaultValue:{specifiedLength:!0}}:null===e.lengthAttr.stateValues.value?{setValue:{specifiedLength:NaN}}:{setValue:{specifiedLength:e.lengthAttr.stateValues.value}}}},specifiedStep:{returnDependencies:()=>({stepAttr:{dependencyType:"attributeComponent",attributeName:"step",variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"}}),defaultValue:null,hasEssential:!0,essentialVarName:"step",definition:function({dependencyValues:e}){if(null===e.stepAttr)return{useEssentialOrDefaultValue:{specifiedStep:!0}};let t=e.stepAttr.stateValues.value;return null===t?{setValue:{specifiedStep:NaN}}:{setValue:{specifiedStep:t}}}},specifiedExclude:{returnDependencies:()=>({excludeAttr:{dependencyType:"attributeComponent",attributeName:"exclude",variableNames:["values"]}}),defaultValue:[],hasEssential:!0,essentialVarName:"exclude",definition:function({dependencyValues:e}){return null===e.excludeAttr?{useEssentialOrDefaultValue:{specifiedExclude:!0}}:{setValue:{specifiedExclude:e.excludeAttr.stateValues.values}}}},lowercase:{returnDependencies:()=>({specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"}}),definition:function({dependencyValues:e}){let t=/^[A-Z]*$/,n=!0;return null!==e.specifiedFrom?t.test(e.specifiedFrom)&&(n=!1):null!==e.specifiedTo&&t.test(e.specifiedTo)&&(n=!1),{setValue:{lowercase:n}}}}};return e.validSequence={returnDependencies:()=>({specifiedLength:{dependencyType:"stateVariable",variableName:"specifiedLength"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},type:{dependencyType:"stateVariable",variableName:"type"},lowercase:{dependencyType:"stateVariable",variableName:"lowercase"}}),definition:function({dependencyValues:e}){let t=!0;if(null!==e.specifiedLength&&(!Number.isInteger(e.specifiedLength)||e.specifiedLength<0)&&(console.warn("Invalid length of sequence. Must be a non-negative integer."),t=!1),null!==e.specifiedStep&&"math"!==e.type){let n=findFiniteNumericalValue(e.specifiedStep);Number.isFinite(n)||(console.warn("Invalid step of sequence. Must be a number for sequence of type "+e.type+"."),t=!1)}if(null!==e.specifiedFrom)if("number"===e.type){let n=findFiniteNumericalValue(e.specifiedFrom);Number.isFinite(n)||(console.warn("Invalid from of number sequence. Must be a number"),t=!1)}else Number.isNaN(e.specifiedFrom)&&(console.warn("Invalid from of sequence"),t=!1);if(null!==e.specifiedTo)if("number"===e.type){let n=findFiniteNumericalValue(e.specifiedTo);Number.isFinite(n)||(console.warn("Invalid to of number sequence. Must be a number"),t=!1)}else Number.isNaN(e.specifiedTo)&&(console.warn("Invalid to of sequence"),t=!1);return{setValue:{validSequence:t}}}},e.from={additionalStateVariablesDefined:["step","length","exclude"],returnDependencies:()=>({specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},specifiedLength:{dependencyType:"stateVariable",variableName:"specifiedLength"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"},type:{dependencyType:"stateVariable",variableName:"type"},specifiedExclude:{dependencyType:"stateVariable",variableName:"specifiedExclude"},validSequence:{dependencyType:"stateVariable",variableName:"validSequence"}}),definition:function({dependencyValues:e}){let t=e.specifiedFrom,n=e.specifiedTo,r=e.specifiedStep,a=e.specifiedLength,i=[...e.specifiedExclude],o=e.type;if("math"===e.type)null!==n&&(n instanceof me$3.class||(n=me$3.fromAst(n))),null!==t&&(t instanceof me$3.class||(t=me$3.fromAst(t))),null!==r&&(r instanceof me$3.class||(r=me$3.fromAst(r)));else if(null!==r&&r instanceof me$3.class&&(r=r.evaluate_to_constant()),"letters"===e.type)null!==t&&(t=lettersToNumber$1(t)),null!==n&&(n=lettersToNumber$1(n)),i=i.map(lettersToNumber$1);else if("number"===e.type){null!==n&&(n=n instanceof me$3.class?n.evaluate_to_constant():Number(n)),null!==t&&(t=t instanceof me$3.class?t.evaluate_to_constant():Number(t));for(let[e,t]of i.entries())t instanceof me$3.class?i[e]=t.evaluate_to_constant():i[e]=Number(t)}if(e.validSequence){let e=calculateSequenceParameters({from:t,to:n,step:r,length:a,type:o});return e.exclude=i,{setValue:e}}return(!Number.isInteger(a)||a<0)&&(a=0),{setValue:{from:t,step:r,length:a,exclude:i}}}},e}function calculateSequenceParameters({from:e,to:t,step:n,length:r,type:a}){if(null===e)null===t?(e="math"===a?me$3.fromAst(1):1,null===n?(n="math"===a?me$3.fromAst(1):1,null===r&&(r=10)):null===r&&(r=10)):(null===n&&(n="math"===a?me$3.fromAst(1):1),null===r&&(r="math"===a?Math.floor((t.subtract(1).divide(n).evaluate_to_constant()+1)*(1+1e-14)):Math.floor(((t-1)/n+1)*(1+1e-14))),"math"===a?e=t.subtract(n.multiply(r-1)).simplify():(e=t-n*(r-1),"letters"===a&&e<1&&(e=t-n*((r=Math.floor(((t-1)/n+1)*(1+1e-14)))-1))));else if(null===t)null===n&&(n="math"===a?me$3.fromAst(1):1),null===r&&(r=10);else if(null===n)null===r?"math"===a?(n=me$3.fromAst(1),r=Math.floor(t.subtract(e).add(1).evaluate_to_constant()*(1+1e-14))):(n=1,r=Math.floor((t-e+1)*(1+1e-14))):"math"===a?n=t.subtract(e).divide(r-1):(n=(t-e)/(r-1),"letters"===a&&(n=Math.floor(n)));else{if(null!==r)throw Error("Can't define from, to, step, and length for sequence");r="math"===a?Math.floor(t.subtract(e).divide(n).add(1).evaluate_to_constant()*(1+1e-14)):Math.floor(((t-e)/n+1)*(1+1e-14))}return(!Number.isInteger(r)||r<0)&&(console.warn("Invalid length of sequence. Must be a non-negative integer."),r=0),{from:e,step:n,length:r}}function returnSequenceValues({from:e,step:t,length:n,exclude:r,type:a,lowercase:i,maxNum:o},s=!1){let l=[],u=0;for(let c=0;c0&&("math"===a?n=n.add(t.multiply(me$3.fromAst(c))).expand().simplify():n+=t*c),"math"===a){if(r.some((e=>e&&e.equals(n))))continue}else if("number"===a){if(r.some((e=>Math.abs(e-n)<=1e-14*Math.max(Math.abs(e),Math.abs(n)))))continue}else if(r.includes(n))continue;if("letters"===a&&(n=numberToLetters(n,i)),s?l.push({value:n,originalIndex:c}):l.push(n),u++,u===o)break}return l}function returnSequenceValueForIndex({index:e,from:t,step:n,length:r,exclude:a,type:i,lowercase:o}){if(!(e>=0&&(void 0===r||e0&&("math"===i?s=s.add(n.multiply(me$3.fromAst(e))).expand().simplify():s+=n*e),"math"===i){if(a.some((e=>e&&e.equals(s))))return null}else if("number"===i){if(a.some((e=>Math.abs(e-s)<=1e-14*Math.max(Math.abs(e),Math.abs(s)))))return null}else if(a.includes(s))return null;return"letters"===i&&(s=numberToLetters(s,o)),s}function lettersToNumber$1(e){try{e=e.toUpperCase()}catch(t){return void console.warn("Cannot convert "+e+" to a number")}let t=0,n=e.length,r=n;for(;(r-=1)>-1;){let a=e.charCodeAt(r)-64;if(a<1||a>26)return void console.warn("Cannot convert "+e+" to a number");t+=a*Math.pow(26,n-1-r)}return t}function numberToLetters(e,t){e--;let n=65;t&&(n=97);let r="";for(;;){let t=e%26;if(r=String.fromCharCode(n+t)+r,e<26)break;e=Math.floor(e/26)-1}return r}function getVariantsForDescendantsForUniqueVariants({variantIndex:e,serializedComponent:t,componentInfoObjects:n}){let r=t.variants?.descendantVariantComponents;if(void 0===r)return{success:!1};let a=r.map((e=>e.variants.numberOfVariants)),i=enumerateCombinations({numberOfOptionsByIndex:a,maxNumber:e})[e-1],o=[];for(let[e,t]of r.entries()){let r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:i[e]+1,componentInfoObjects:n});if(!r.success)return{succss:!1};o.push(r.desiredVariant)}return{success:!0,desiredVariants:o}}function setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:r=!1}){let a,i;if(e.variants&&(i=e.variants.desiredVariant),a=void 0!==i?.seed?i.seed.toString():r?t.subpartVariantRng().toString().slice(2):t.variantRng().toString().slice(2),t.variantSeed=a,t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}function gatherVariantComponents({serializedComponents:e,componentInfoObjects:t}){let n=[];for(let r of e){if("object"!=typeof r)continue;if(r.variants||(r.variants={}),r.variants.isVariantComponent){n.push(r);continue}if(r.componentType in t.componentTypesCreatingVariants){r.variants.isVariantComponent=!0,n.push(r);continue}if(!r.children)continue;if(r.children.some((e=>"variantControl"===e.componentType))){r.variants.isVariantComponent=!0,n.push(r);continue}let e=gatherVariantComponents({serializedComponents:r.children,componentInfoObjects:t});e.length>0&&(r.variants.descendantVariantComponents=e,n.push(...e))}return n}function getNumberOfVariants({serializedComponent:e,componentInfoObjects:t}){let n;e.variants||(e.variants={});for(let t of e.children)if("variantControl"===t.componentType){n=t;break}let r="document"===e.componentType;if(!n){if(!r)return{success:!1};let n=e.children.filter((e=>e.componentType||""!==e.trim()));if(1===n.length&&t.isInheritedComponentType({inheritedComponentType:n[0].componentType,baseComponentType:"_sectioningComponent"})){let r=n[0],a=getNumberOfVariants({serializedComponent:r,componentInfoObjects:t});if(a.success)return e.variants.descendantVariantComponents=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t}),e.variants.uniqueVariants=!0,e.variants.numberOfVariants=r.variants.numberOfVariants,e.variants.allPossibleVariants=r.variants.allPossibleVariants,e.variants.allVariantNames=r.variants.allVariantNames,e.variants.allPossibleVariantUniqueIndices=[...r.variants.allPossibleVariants.keys()].map((e=>e+1)),e.variants.allPossibleVariantSeeds=[...r.variants.allPossibleVariants.keys()].map((e=>(e+1).toString())),a}}return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:r})}function determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:n=!1}){let r;void 0===e.variants&&(e.variants={});for(let t of e.children)if("variantControl"===t.componentType){r=t;break}if(!r&&!n){return t.allComponentClasses._base.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t})}let a=[];if(r?.attributes.variantNames&&(a=r.attributes.variantNames.component.children.map((e=>e.toLowerCase()))),a.length!==[...new Set(a)].length)throw Error("Duplicate variant names specified");let i=r?.attributes.nVariants?.primitive;Number.isFinite(i)||(i=100),i=Math.min(Math.max(i,1),1e3);let o=[...a];if(o.lengthe.toLowerCase())),s=[...new Set(s)];for(let e of s)if(!o.includes(e))throw Error(`Cannot include variant ${e} as ${e} is a not variant name`)}let l=r?.attributes.variantsToExclude?.component.children;if(l){l=l.map((e=>e.toLowerCase()));for(let e of l)if(!o.includes(e))throw Error(`Cannot exclude variant ${e} as ${e} is not a variant name`)}else l=[];s=s?s.filter((e=>!l.includes(e))):[...o].filter((e=>!l.includes(e)));let u=s.map((e=>o.indexOf(e)+1)),c=[];r?.attributes.seeds&&(c=r.attributes.seeds.component.children);let p=[...c];if(p.lengthp[e-1])),f=void 0!==r?.attributes.uniqueVariants,h=r?.attributes.uniqueVariants?.primitive;if(h||!f){d=t.allComponentClasses._base.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}),h=!!d.success&&(h||d.numberOfVariants<=i)}let y=[],b=[],g=[];if(h)for(let[e,t]of u.entries())t<=d.numberOfVariants&&(b.push(t),y.push(s[e]),g.push(m[e]));else y=s,b=u,g=m;let v=y.length;if(0===v)throw Error("No variants selected based on variantsToInclude, variantsToExclude, and the number of variants available");return e.variants.uniqueVariants=h,e.variants.numberOfVariants=v,e.variants.allPossibleVariants=y,e.variants.allVariantNames=o,e.variants.allPossibleVariantUniqueIndices=b,e.variants.allPossibleVariantSeeds=g,{success:!0,numberOfVariants:v}}function indexToLowercaseLetters(e){return numberToLetters(e,!0)}class BaseComponent{constructor({componentName:e,ancestors:t,serializedComponent:n,definingChildren:r,serializedChildren:a,attributes:i,stateVariableDefinitions:o,componentInfoObjects:s,coreFunctions:l,flags:u,shadow:c,numerics:p,parentSharedParameters:d,sharedParameters:m}){this.numerics=p,this.parentSharedParameters=d,this.sharedParameters=m,this.componentName=e,this.ancestors=t,this.counters={},this.componentInfoObjects=s,this.coreFunctions=l,this.flags=u,!0===c&&(this.isShadow=!0),this.definingChildren=r,void 0===this.definingChildren&&(this.definingChildren=[]),this.serializedChildren=a,this.attributes=i,this.state={};for(let e in o)this.state[e]=Object.assign({},o[e]);this.stateValues=new Proxy(this.state,createStateProxyHandler()),this.essentialState={},n.state&&(this.essentialState=deepClone(n.state)),this.doenetAttributes={},void 0!==n.doenetAttributes&&Object.assign(this.doenetAttributes,n.doenetAttributes),void 0!==n.variants&&(this.variants=n.variants)}static componentType="_base";static get rendererType(){return this.componentType}get componentType(){return this.constructor.componentType}get componentOrAdaptedName(){return this.adaptedFrom?this.adaptedFrom.componentOrAdaptedName:this.componentName}get rendererType(){return this.constructor.rendererType}get allPotentialRendererTypes(){let e=[];this.rendererType&&e.push(this.rendererType);for(let t in this.state){let n=this.state[t];if(n.public){let t=n.componentType;Array.isArray(t)||(t=[t]),n.wrappingComponents&&t.push(...flattenDeep(n.wrappingComponents).map((e=>"object"==typeof e?e.componentType:e)));for(let n of t){let t=this.componentInfoObjects.allComponentClasses[n];if(t){let n=t.rendererType;n&&!e.includes(n)&&e.push(n)}}}}if(this.constructor.adapters)for(let t of this.constructor.adapters){let n;n="string"==typeof t?t:t.componentType;let r=this.componentInfoObjects.allComponentClasses[n];if(r){let t=r.rendererType;t&&!e.includes(t)&&e.push(t)}}if(!this.rendererType)return e;for(let t in this.allChildren){let n=this.allChildren[t].component;if("object"==typeof n)for(let t of n.allPotentialRendererTypes)e.includes(t)||e.push(t)}return e}potentialRendererTypesFromSerializedComponents(e){let t=[];for(let n of e){let e=this.componentInfoObjects.allComponentClasses[n.componentType];if(e){let n=e.rendererType;n&&!t.includes(n)&&t.push(n);let r=e.returnStateVariableInfo({onlyPublic:!0}).stateVariableDescriptions;for(let e in r){let n=r[e],a=n.shadowingInstructions?.createComponentOfType;Array.isArray(a)||(a=[a]),n.wrappingComponents&&a.push(...flattenDeep(n.wrappingComponents).map((e=>"object"==typeof e?e.componentType:e)));for(let e of a){let n=this.componentInfoObjects.allComponentClasses[e];if(n){let e=n.rendererType;e&&!t.includes(e)&&t.push(e)}}}if(e.adapters)for(let n of e.adapters){let e;e="string"==typeof n?n:n.componentType;let r=this.componentInfoObjects.allComponentClasses[e];if(r){let e=r.rendererType;e&&!t.includes(e)&&t.push(e)}}}if(n.children){let e=this.potentialRendererTypesFromSerializedComponents(n.children);for(let n of e)t.includes(n)||t.push(n)}}return t}get childrenMatched(){return this.childrenMatchedWithPlaceholders&&!this.placeholderActiveChildrenIndices}static createAttributesObject(){return{hide:{createComponentOfType:"boolean",createStateVariable:"hide",defaultValue:!1,public:!0},disabled:{createComponentOfType:"boolean"},fixed:{createComponentOfType:"boolean",ignoreFixed:!0},modifyIndirectly:{createComponentOfType:"boolean",createStateVariable:"modifyIndirectly",defaultValue:!0,public:!0,propagateToProps:!0},styleNumber:{createComponentOfType:"number",createStateVariable:"styleNumber",defaultValue:1,public:!0,fallBackToParentStateVariable:"styleNumber"},isResponse:{createPrimitiveOfType:"boolean",createStateVariable:"isResponse",defaultValue:!1,public:!0},newNamespace:{createPrimitiveOfType:"boolean",createStateVariable:"newNamespace",defaultValue:!1,public:!0}}}static returnSugarInstructions(){return[]}static returnChildGroups(){return[]}static get childGroups(){return this.hasOwnProperty("childGroupsData")||(this.childGroupsData=this.returnChildGroups()),this.childGroupsData}static childGroupOfComponentTypeData;static get childGroupOfComponentType(){return this.hasOwnProperty("childGroupOfComponentTypeData")||(this.childGroupOfComponentTypeData={}),this.childGroupOfComponentTypeData}static childGroupIndsByNameData;static get childGroupIndsByName(){if(this.hasOwnProperty("childGroupIndsByNameData"))return Object.assign({},this.childGroupIndsByNameData);this.childGroupIndsByNameData={};for(let[e,t]of this.childGroups.entries()){if(t.group in this.childGroupIndsByNameData)throw Error(`Invalid childGroups for componentClass ${this.componentType}: ${t} is repeated`);this.childGroupIndsByNameData[t.group]=e}return Object.assign({},this.childGroupIndsByNameData)}returnMatchedChildIndices(e){let t=[];for(let n of e){let e=this.childMatchesByGroup[n];if(!e)return;t.push(...e)}return t.sort(((e,t)=>e-t))}static returnStateVariableDefinitions(){let e={};return e.hidden={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({hide:{dependencyType:"stateVariable",variableName:"hide",variablesOptional:!0},parentHidden:{dependencyType:"parentStateVariable",variableName:"hidden"},sourceCompositeHidden:{dependencyType:"sourceCompositeStateVariable",variableName:"hidden"},adapterSourceHidden:{dependencyType:"adapterSourceStateVariable",variableName:"hidden"}}),definition:({dependencyValues:e})=>({setValue:{hidden:Boolean(e.parentHidden||e.sourceCompositeHidden||e.adapterSourceHidden||e.hide)}}),markStale:()=>({updateParentRenderedChildren:!0}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"hide",desiredValue:e.hidden}]})},e.disabled={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,hasEssential:!0,doNotShadowEssential:!0,defaultValue:!1,provideEssentialValuesInDefinition:!0,returnDependencies:()=>({disabledAttr:{dependencyType:"attributeComponent",attributeName:"disabled",variableNames:["value"]},readOnly:{dependencyType:"flag",flagName:"readOnly"},parentDisabled:{dependencyType:"parentStateVariable",variableName:"disabled"},sourceCompositeDisabled:{dependencyType:"sourceCompositeStateVariable",variableName:"disabled"},adapterSourceDisabled:{dependencyType:"adapterSourceStateVariable",variableName:"disabled"}}),definition({dependencyValues:e,usedDefault:t,essentialValues:n}){if(e.readOnly)return{setValue:{disabled:!0}};if(null!==e.disabledAttr)return{setValue:{disabled:e.disabledAttr.stateValues.value}};if(void 0!==n.disabled)return{useEssentialOrDefaultValue:{disabled:!0}};let r=!1,a=!0;return null===e.parentDisabled||t.parentDisabled||(r=r||e.parentDisabled,a=!1),null===e.sourceCompositeDisabled||t.sourceCompositeDisabled||(r=r||e.sourceCompositeDisabled,a=!1),null===e.adapterSourceDisabled||t.adapterSourceDisabled||(r=r||e.adapterSourceDisabled,a=!1),a?{useEssentialOrDefaultValue:{disabled:!0}}:{setValue:{disabled:r}}},inverseDefinition:({dependencyValues:e,desiredStateVariableValues:t})=>null!==e.disabledAttr?{success:!0,instructions:[{setDependency:"disabledAttr",desiredValue:t.disabled,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"disabled",value:t.disabled}]}},e.fixed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,ignoreFixed:!0,provideEssentialValuesInDefinition:!0,returnDependencies:()=>({fixedAttr:{dependencyType:"attributeComponent",attributeName:"fixed",variableNames:["value"]},parentFixed:{dependencyType:"parentStateVariable",variableName:"fixed"},sourceCompositeFixed:{dependencyType:"sourceCompositeStateVariable",variableName:"fixed"},adapterSourceFixed:{dependencyType:"adapterSourceStateVariable",variableName:"fixed"},ignoreParentFixed:{dependencyType:"doenetAttribute",attributeName:"ignoreParentFixed"}}),definition({dependencyValues:e,usedDefault:t,essentialValues:n}){if(null!==e.fixedAttr)return{setValue:{fixed:e.fixedAttr.stateValues.value}};if(void 0!==n.fixed)return{useEssentialOrDefaultValue:{fixed:!0}};let r=!1,a=!0;return null===e.parentFixed||t.parentFixed||e.ignoreParentFixed||(r=r||e.parentFixed,a=!1),null===e.sourceCompositeFixed||t.sourceCompositeFixed||(r=r||e.sourceCompositeFixed,a=!1),null===e.adapterSourceFixed||t.adapterSourceFixed||(r=r||e.adapterSourceFixed,a=!1),a?{useEssentialOrDefaultValue:{fixed:!0}}:{setValue:{fixed:r}}},inverseDefinition:({dependencyValues:e,desiredStateVariableValues:t})=>null!==e.fixedAttr?{success:!0,instructions:[{setDependency:"fixedAttr",desiredValue:t.fixed,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"fixed",value:t.fixed}]}},e.isInactiveCompositeReplacement={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{isInactiveCompositeReplacement:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:{variableName:"isInactiveCompositeReplacement",value:e.isInactiveCompositeReplacement}}]})},e}static returnNormalizedStateVariableDefinitions({attributeNames:e,numerics:t}){let n=this.returnStateVariableDefinitions({attributeNames:e,numerics:t});if(!n)throw Error(`Error in state variable definitions of ${this.componentType}: returnStateVariableDefinitions did not return anything`);let r=function(e){for(let[t,n]of e.entries())"object"==typeof n&&(e[t]=n.variableName)},a=["returnDependencies","definition","inverseDefinition","stateVariablesDeterminingDependencies","stateVariablesDeterminingArraySizeDependencies","isArray","nDimensions","returnArraySizeDependencies","returnArraySize","returnArrayDependenciesByKey","arrayDefinitionByKey","inverseArrayDefinitionByKey","basedOnArrayKeyStateVariables","markStale","getPreviousDependencyValuesForMarkStale","determineDependenciesImmediately","createWorkspace","workspace","provideEssentialValuesInDefinition","providePreviousValuesInDefinition"],i={};for(let e in n){let t=n[e];if(i[e]=t,t.createWorkspace&&(t.workspace={}),t.additionalStateVariablesDefined){for(let[n,o]of t.additionalStateVariablesDefined.entries()){let s={};for(let e of a)e in t&&(s[e]=t[e]);s.additionalStateVariablesDefined=[...t.additionalStateVariablesDefined],s.additionalStateVariablesDefined[n]=e,r(s.additionalStateVariablesDefined);let l=o;"object"==typeof o&&(l=o.variableName,o=Object.assign({},o),delete o.variableName,Object.assign(s,o)),i[l]=s}r(t.additionalStateVariablesDefined)}}return i}static returnStateVariableInfo({onlyPublic:e=!1,onlyForRenderer:t=!1}={}){let n=this.createAttributesObject(),r={},a={},i={};for(let a in n){let i=n[a],o=i.createStateVariable;if(o&&(!e||i.public)&&(!t||i.forRenderer))if(i.public){let e;!i.createComponentOfType?(e=i.createPrimitiveOfType,"string"===e&&(e="text")):e=i.createComponentOfType,r[o]={createComponentOfType:e,public:!0}}else r[o]={}}let o=this.returnNormalizedStateVariableDefinitions({attributeNames:Object.keys(r)});for(let n in o){let s=o[n];if(s.isAlias)i[n]=s.targetVariableName;else if((!e||s.public)&&(!t||s.forRenderer)&&(s.public?r[n]={createComponentOfType:s.shadowingInstructions.createComponentOfType,public:!0}:r[n]={},s.isArray)){let e;r[n].isArray=!0,r[n].nDimensions=void 0===s.nDimensions?1:s.nDimensions,r[n].wrappingComponents=s.shadowingInstructions?.returnWrappingComponents?s.shadowingInstructions.returnWrappingComponents():[],e=s.entryPrefixes?s.entryPrefixes:[n];for(let t of e)a[t]={arrayVariableName:n,nDimensions:s.returnEntryDimensions?s.returnEntryDimensions(t):1,wrappingComponents:s.shadowingInstructions?.returnWrappingComponents?s.shadowingInstructions.returnWrappingComponents(t):[]};s.getArrayKeysFromVarName?r[n].getArrayKeysFromVarName=s.getArrayKeysFromVarName:r[n].getArrayKeysFromVarName=returnDefaultGetArrayKeysFromVarName(r[n].nDimensions)}}return{stateVariableDescriptions:r,arrayEntryPrefixes:a,aliases:i}}get parentName(){if(void 0!==this.ancestors&&0!==this.ancestors.length)return this.ancestors[0].componentName}getAllChildrenDownstreamComponentNames(e=!1){const t=Object.keys(this.allChildren);let n=Object.keys(this.downstreamDependencies);return!0!==e&&(n=n.filter((e=>!0!==this.downstreamDependencies[e].inactive))),[...t,...n]}get allDescendants(){let e=[];for(let t in this.allChildren){let n=this.allChildren[t].component;e=[...e,t,...n.allDescendants]}return e}async serialize(e={}){let t,n={componentType:this.componentType},r=[],a={...e};t=e.sourceAttributesToIgnoreRecursively?[...e.sourceAttributesToIgnoreRecursively]:[],e.sourceAttributesToIgnore&&(t.push(...e.sourceAttributesToIgnore),delete a.sourceAttributesToIgnore);for(let e of this.definingChildren)"object"!=typeof e?r.push(e):r.push(await e.serialize(a));if(void 0!==this.serializedChildren)for(let e of this.serializedChildren)r.push(this.copySerializedComponent(e));r.length>0&&(n.children=r),n.attributes={};for(let r in this.attributes){let i=this.attributes[r];i.component?e.copyAll&&(n.attributes[r]={component:await i.component.serialize(a)}):t.includes(r)&&!e.copyAll||(n.attributes[r]=JSON.parse(JSON.stringify(i)))}return this.essentialState&&Object.keys(this.essentialState).length>0&&(n.state=deepClone(this.essentialState)),e.copyVariants&&this.state.generatedVariantInfo&&(n.variants={desiredVariant:await this.stateValues.generatedVariantInfo}),n.originalName=this.componentName,n.originalDoenetAttributes=deepClone(this.doenetAttributes),n.doenetAttributes=deepClone(this.doenetAttributes),n.originalAttributes=deepClone(n.attributes),delete n.doenetAttributes.prescribedName,delete n.doenetAttributes.assignNames,n}copySerializedComponent(e){if("object"!=typeof e)return e;let t=[];if(void 0!==e.children)for(let n of e.children)t.push(this.copySerializedComponent(n));let n={componentType:e.componentType,originalName:e.componentName,originalNameFromSerializedComponent:!0,children:t,state:{},doenetAttributes:{}};return void 0!==e.doenetAttributes&&(n.originalDoenetAttributes=deepClone(e.doenetAttributes),n.doenetAttributes=deepClone(e.doenetAttributes),n.originalAttributes=deepClone(e.attributes),n.attributes=deepClone(e.attributes),delete n.doenetAttributes.prescribedName,delete n.doenetAttributes.assignNames),void 0!==e.state&&Object.assign(n.state,e.state),n}static adapters=[];static get nAdapters(){return this.adapters.length}getAdapter(e){if(e>=this.constructor.adapters.length)return;let t,n,r,a,i=this.constructor.adapters[e];"string"==typeof i?t=i:(t=i.stateVariable,n=i.componentType,r=i.substituteForPrimaryStateVariable,a=i.stateVariablesToShadow);let o=this.state[t];if(void 0===o||!o.public&&!n)throw Error("Invalid adapter "+t+" in "+this.componentType);return void 0===n&&(n=o.shadowingInstructions.createComponentOfType),{componentType:n,downstreamDependencies:{[this.componentName]:[{dependencyType:"adapter",adapterVariable:t,adapterTargetIdentity:{componentName:this.componentName,componentType:this.componentType},substituteForPrimaryStateVariable:r,stateVariablesToShadow:a}]}}}static getAdapterComponentType(e,t){if(e>=this.adapters.length)return;let n,r,a=this.adapters[e];if("string"==typeof a?n=a:(n=a.stateVariable,r=a.componentType),void 0===r){let e=t[this.componentType].stateVariableDescriptions[n];if(!e)throw Error("Invalid adapter "+n+" in "+this.componentType);if(r=e.createComponentOfType,!r)throw Error(`Couldn't get adapter component type for ${n} of componentType ${this.componentType}`)}return r}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){let n=e.variants?.numberOfVariants;if(void 0!==n)return{success:!0,numberOfVariants:n};let r=[];e.children&&(r=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t})),void 0===e.variants&&(e.variants={}),e.variants.descendantVariantComponents=r,n=1;let a=[];for(let e of r){let r=t.allComponentClasses[e.componentType].determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!r.success)return{success:!1};a.push(r.numberOfVariants),n*=r.numberOfVariants}return e.variants.numberOfVariants=n,e.variants.uniqueVariantData={numberOfVariantsByDescendant:a},{success:!0,numberOfVariants:n}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};let a=!1,i=e.variants.uniqueVariantData.numberOfVariantsByDescendant,o=e.variants.descendantVariantComponents,s=[];if(o.length>0){let e=enumerateCombinations({numberOfOptionsByIndex:i,maxNumber:t})[t-1].map((e=>e+1));for(let t=0;t1){let r=o[t],i=n.allComponentClasses[r.componentType].getUniqueVariant({serializedComponent:r,variantIndex:e[t],componentInfoObjects:n});if(!i.success)return{success:!1};s.push(i.desiredVariant),a=!0}else s.push({})}let l={index:t};return a&&(l.subvariants=s),{success:!0,desiredVariant:l}}}class InlineComponent extends BaseComponent{static componentType="_inline"}class Text extends InlineComponent{static componentType="text";static includeBlankStringChildren=!0;static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"textLike",componentTypes:["string","text","_singleCharacterInline","_inlineRenderInlineChildren"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType,addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},hasEssential:!0,returnDependencies:()=>({textLikeChildren:{dependencyType:"child",childGroups:["textLike"],variableNames:["text"]}}),defaultValue:"",set:e=>null===e?"":String(e),definition:function({dependencyValues:e}){if(0===e.textLikeChildren.length)return{useEssentialOrDefaultValue:{value:!0}};let t="";for(let n of e.textLikeChildren)t+="string"==typeof n?n:n.stateValues.text;return{setValue:{value:t}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n=t.textLikeChildren.length;return n>1?{success:!1}:1===n?{success:!0,instructions:[{setDependency:"textLikeChildren",desiredValue:e.value,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:null===e.value?"":String(e.value)}]}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.text}]})},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveText({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}actions={moveText:this.moveText.bind(this)}}class TextOrInline extends InlineComponent{static componentType="_textOrInline";static renderChildren=!0;static rendererType="containerInline";static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{value:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}}class CompositeComponent extends BaseComponent{constructor(e){super(e),this.replacementsWorkspace={}}static componentType="_composite";static rendererType=void 0;static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.replacements={returnDependencies:()=>({replacements:{dependencyType:"replacement"}}),definition:({dependencyValues:e})=>({setValue:{replacements:e.replacements}})},e.recursiveReplacements={returnDependencies:()=>({recursiveReplacements:{dependencyType:"replacement",recursive:!0}}),definition:({dependencyValues:e})=>({setValue:{recursiveReplacements:e.recursiveReplacements}})},e.fullRecursiveReplacements={returnDependencies:()=>({recursiveReplacements:{dependencyType:"replacement",recursive:!0,recurseNonStandardComposites:!0}}),definition:({dependencyValues:e})=>({setValue:{fullRecursiveReplacements:e.recursiveReplacements}})},e}static createSerializedReplacements(){return{replacements:[]}}static calculateReplacementChanges(){return[]}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes;for(let t in this.allChildren){let n=this.allChildren[t].component;for(let t of n.allPotentialRendererTypes)e.includes(t)||e.push(t)}if(this.replacements)for(let t of this.replacements)if("object"==typeof t)for(let n of t.allPotentialRendererTypes)e.includes(n)||e.push(n);return e}}class Template extends CompositeComponent{static componentType="template";static treatAsComponentForRecursiveReplacements=!0;static includeBlankStringChildren=!0;static renderedDefault=!1;static assignNamesToReplacements=!0;static createsVariants=!0;static keepChildrenSerialized({serializedComponent:e}){return void 0===e.children?[]:Object.keys(e.children)}static createAttributesObject(){let e=super.createAttributesObject();return e.rendered={createComponentOfType:"boolean",createStateVariable:"rendered",defaultValue:this.renderedDefault,public:!0},e.isResponse={leaveRaw:!0},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.serializedChildren={returnDependencies:()=>({serializedChildren:{dependencyType:"serializedChildren",doNotProxy:!0}}),definition:function({dependencyValues:e}){return{setValue:{serializedChildren:e.serializedChildren}}}},e.newNamespace={returnDependencies:()=>({newNamespace:{dependencyType:"attributePrimitive",attributeName:"newNamespace"}}),definition:({dependencyValues:e})=>({setValue:{newNamespace:e.newNamespace}})},e.readyToExpandWhenResolved={returnDependencies:()=>({}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:n}){let r;if(e.typeAttr){if(!(n.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in n.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);r=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error(`You must specify createComponentOfType when specifying nComponents for a ${t.componentType}.`);r=null}return{setValue:{nComponentsSpecified:r}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,alwaysCreateReplacements:n,flags:r}){if(await e.stateValues.nComponentsSpecified,await e.stateValues.rendered||n){let n=deepClone(await e.state.serializedChildren.value),a=e.attributes.newNamespace?.primitive;if("isResponse"in e.attributes)for(let i of n){if("object"!=typeof i)continue;let n=convertAttributesForComponentType({attributes:{isResponse:e.attributes.isResponse},componentType:i.componentType,componentInfoObjects:t,compositeCreatesNewNamespace:a,flags:r});i.attributes||(i.attributes={}),Object.assign(i.attributes,n)}let i=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:n,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:t,originalNamesAreConsistent:!0});return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:i.serializedComponents,assignNames:e.doenetAttributes.assignNames,componentInfoObjects:t,compositeAttributesObj:this.createAttributesObject(),flags:r})).replacements}}return{replacements:[]}}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes,t=this.potentialRendererTypesFromSerializedComponents(this.serializedChildren);for(let n of t)e.includes(n)||e.push(n);return e}}class MathComponent extends InlineComponent{static componentType="math";static primaryStateVariableForDefinition="unnormalizedValue";static primaryEssentialStateVariable="value";static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!0;static descendantCompositesDefaultReplacementType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0,toLowerCase:!0,validValues:["text","latex"]},e.simplify={createComponentOfType:"text",createStateVariable:"simplify",defaultValue:"none",public:!0,toLowerCase:!0,valueTransformations:{true:"full",false:"none"},validValues:["none","full","numbers","numberspreserveorder"]},e.expand={createComponentOfType:"boolean",createStateVariable:"expand",defaultValue:!1,public:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.renderMode={createComponentOfType:"text",createStateVariable:"renderMode",defaultValue:"inline",public:!0,forRenderer:!0},e.unordered={createComponentOfType:"boolean"},e.createVectors={createComponentOfType:"boolean",createStateVariable:"createVectors",defaultValue:!1,public:!0},e.createIntervals={createComponentOfType:"boolean",createStateVariable:"createIntervals",defaultValue:!1,public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.sourcesAreFunctionSymbols={createComponentOfType:"textList",createStateVariable:"sourcesAreFunctionSymbols",defaultValue:[]},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e.groupCompositeReplacements={createPrimitiveOfType:"boolean",createStateVariable:"groupCompositeReplacements",defaultValue:!0},e.displayBlanks={createComponentOfType:"boolean",createStateVariable:"displayBlanks",defaultValue:!0,public:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"strings",componentTypes:["string"]},{group:"displayedMaths",componentTypes:["m","me","men"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displayDigits"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}let a=null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals,i=null===e.displayDigitsAttr||t.displayDigitsAttr,o=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!i&&!o){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displayDecimals"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}if(1===e.mathChildren.length&&0===e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].displayDecimals)return{setValue:{displayDecimals:e.mathChildren[0].stateValues.displayDecimals}};r=!0,n=e.mathChildren[0].stateValues.displayDecimals}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displaySmallAsZero"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}if(1===e.mathChildren.length&&0===e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].displaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathChildren[0].stateValues.displaySmallAsZero}};r=!0,n=e.mathChildren[0].stateValues.displaySmallAsZero}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["padZeros"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}if(1===e.mathChildren.length&&0==e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].padZeros)return{setValue:{padZeros:e.mathChildren[0].stateValues.padZeros}};r=!0,n=e.mathChildren[0].stateValues.padZeros}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.valueShadow={defaultValue:me$3.fromAst("_"),hasEssential:!0,essentialVarName:"value",returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{valueShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"valueShadow",value:e.valueShadow}]}}},e.unordered={defaultValue:!1,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,returnDependencies:()=>({unorderedAttr:{dependencyType:"attributeComponent",attributeName:"unordered",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["unordered"]}}),definition({dependencyValues:e}){if(null===e.unorderedAttr){if(e.mathChildren.length>0){let t=e.mathChildren.every((e=>e.stateValues.unordered));return{setValue:{unordered:t}}}return{useEssentialOrDefaultValue:{unordered:!0}}}return{setValue:{unordered:e.unorderedAttr.stateValues.value}}}},e.codePre={returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e}){let t="math",n=!1;do{n=!1;for(let r of e.stringChildren)if(!0===r.includes(t)){n=!0,t+="m";break}}while(n);return{setValue:{codePre:t}}}},e.mathChildrenFunctionSymbols={returnDependencies:()=>({sourcesAreFunctionSymbols:{dependencyType:"stateVariable",variableName:"sourcesAreFunctionSymbols"},mathChildren:{dependencyType:"child",childGroups:["maths"]}}),definition({dependencyValues:e}){let t=[];if(e.mathChildren.compositeReplacementRange)for(let n of e.mathChildren.compositeReplacementRange)if(e.sourcesAreFunctionSymbols.includes(n.target))for(let e=n.firstInd;e<=n.lastInd;e++)t.push(e);return{setValue:{mathChildrenFunctionSymbols:t}}}},e.expressionWithCodes={hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({stringMathChildren:{dependencyType:"child",childGroups:["strings","maths"]},stringChildren:{dependencyType:"child",childGroups:["strings"]},mathChildren:{dependencyType:"child",childGroups:["maths"]},displayedMathChildren:{dependencyType:"child",childGroups:["displayedMaths"],variableNames:["latex"]},format:{dependencyType:"stateVariable",variableName:"format"},codePre:{dependencyType:"stateVariable",variableName:"codePre"},functionSymbols:{dependencyType:"stateVariable",variableName:"functionSymbols"},mathChildrenFunctionSymbols:{dependencyType:"stateVariable",variableName:"mathChildrenFunctionSymbols"},splitSymbols:{dependencyType:"stateVariable",variableName:"splitSymbols"},parseScientificNotation:{dependencyType:"stateVariable",variableName:"parseScientificNotation"},groupCompositeReplacements:{dependencyType:"stateVariable",variableName:"groupCompositeReplacements"}}),set:e=>null===e?null:convertValueToMathExpression(e),definition:calculateExpressionWithCodes,async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,componentName:r}){let a=e.expressionWithCodes,i=[{setEssentialValue:"expressionWithCodes",value:a}],o=t.stringChildren.length;if(0===o)return{success:!1};if(0===t.mathChildren.length){let e;e="latex"===await n.format?a.toLatex():a.toString(),i.push({setDependency:"stringChildren",desiredValue:e,childIndex:0,variableIndex:0,ignoreChildChangeForComponent:!0});for(let e=1;e({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value","canBeModified"]}}),definition:({dependencyValues:e})=>({setValue:{mathChildrenWithCanBeModified:e.mathChildren}})},e.unnormalizedValue={returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"},codePre:{dependencyType:"stateVariable",variableName:"codePre"},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"}}),set:convertValueToMathExpression,defaultValue:me$3.fromAst("_"),definition:calculateMathValue,inverseDefinition:invertMath},e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType,attributesToShadow:["unordered","displayDigits","displayDecimals","displaySmallAsZero","padZeros","simplify","expand"],addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},returnDependencies:()=>({unnormalizedValue:{dependencyType:"stateVariable",variableName:"unnormalizedValue"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},createVectors:{dependencyType:"stateVariable",variableName:"createVectors"},createIntervals:{dependencyType:"stateVariable",variableName:"createIntervals"}}),definition:function({dependencyValues:e}){let t=e.unnormalizedValue,{simplify:n,expand:r,createVectors:a,createIntervals:i}=e;return t=normalizeMathExpression({value:t,simplify:n,expand:r,createVectors:a,createIntervals:i}),{setValue:{value:t}}},inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"unnormalizedValue",desiredValue:e.value}]}}},e.number={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){let t=e.value.evaluate_to_constant();return null===t&&(t=NaN),{setValue:{number:t}}},inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"value",desiredValue:me$3.fromAst(e.number)}]}}},e.isNumber={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{isNumber:Number.isFinite(e.value.tree)}}}},e.isNumeric={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({number:{dependencyType:"stateVariable",variableName:"number"}}),definition:function({dependencyValues:e}){return{setValue:{isNumeric:Number.isFinite(e.number)}}}},e.valueForDisplay={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:normalizeMathExpression({value:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t}),simplify:e.simplify,expand:e.expand})}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.valueForDisplay}]})},e.latex={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displayBlanks:{dependencyType:"stateVariable",variableName:"displayBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n,r={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.displayBlanks||(r.showBlanks=!1);try{n=e.valueForDisplay.toLatex(r)}catch(t){n=e.displayBlanks?"_":""}return{setValue:{latex:n}}},inverseDefinition({desiredStateVariableValues:e}){let t;try{t=me$3.fromLatex(e.latex)}catch(e){return{success:!1}}return{success:!0,instructions:[{setDependency:"valueForDisplay",desiredValue:t}]}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},value:{dependencyType:"stateVariable",variableName:"value"},displayBlanks:{dependencyType:"stateVariable",variableName:"displayBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n,r={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.displayBlanks||(r.showBlanks=!1);try{n=e.valueForDisplay.toString(r)}catch(t){n=e.displayBlanks?"_":""}return{setValue:{text:superSubscriptsToUnicode(n.toString())}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n,r=getFromText({functionSymbols:await t.functionSymbols,splitSymbols:await t.splitSymbols,parseScientificNotation:await t.parseScientificNotation});try{n=r(unicodeToSuperSubscripts(e.text))}catch(e){return{success:!1}}return{success:!0,instructions:[{setDependency:"value",desiredValue:n}]}}},e.codesAdjacentToStrings={returnDependencies:()=>({stringMathChildren:{dependencyType:"child",childGroups:["strings","maths"]},codePre:{dependencyType:"stateVariable",variableName:"codePre"},format:{dependencyType:"stateVariable",variableName:"format"}}),definition:calculateCodesAdjacentToStrings},e.canBeModified={additionalStateVariablesDefined:["constantChildIndices","codeForExpression","inverseMaps","template","mathChildrenMapped"],returnDependencies:()=>({mathChildrenModifiable:{dependencyType:"child",childGroups:["maths"],variableNames:["canBeModified"]},displayedMathChildren:{dependencyType:"child",childGroups:["displayedMaths"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"},modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition:determineCanBeModified},e.mathChildrenByVectorComponent={returnDependencies:()=>({codePre:{dependencyType:"stateVariable",variableName:"codePre"},mathChildren:{dependencyType:"child",childGroups:["maths"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"}}),definition:function({dependencyValues:e}){if(null===e.expressionWithCodes)return{setValue:{mathChildrenByVectorComponent:null}};let t=e.expressionWithCodes.tree,n=e.mathChildren.length;if(0===n||!Array.isArray(t)||!["tuple","vector"].includes(t[0]))return{setValue:{mathChildrenByVectorComponent:null}};let r={},a=0,i=e.codePre+a;for(let o=1;o=n)break}return{setValue:{mathChildrenByVectorComponent:r}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition({dependencyValues:e}){let t=1,n=e.value.tree;if(Array.isArray(n))if(["vector","tuple","list"].includes(n[0]))t=n.length-1;else if("matrix"===n[0]){let e=n[1].slice(1);1===e[0]?t=e[1]:1===e[1]&&(t=e[0])}else"vector"!==n[1][0]&&"tuple"!==n[1][0]||("^"!==n[0]||"T"!==n[2])&&"prime"!==n[0]||(t=n[1].length-1);return{setValue:{nDimensions:t}}}},e.vector={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"x"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["x"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{value:{dependencyType:"stateVariable",variableName:"value"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t,arraySize:n}){let r=e.value.tree,a=!1,i={};if(Array.isArray(r))if(["vector","tuple","list"].includes(r[0])){for(let e=0;ee.tree))]);else if("matrix"===o[0]){let e=o[1].slice(1);if(1===e[0]){let e=["tuple"];for(let t=0;te.tree))]],o[2]&&i.push(o[2]),i=me$3.fromAst(i));return i||(i=r.desiredVector[0]),{success:!0,instructions:[{setDependency:"value",desiredValue:i}]}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.matrixSize={public:!0,shadowingInstructions:{createComponentOfType:"numberList"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition({dependencyValues:e}){let t=[1,1],n=e.value.tree;return Array.isArray(n)&&(["vector","tuple","list"].includes(n[0])?t=[n.length-1,1]:"matrix"===n[0]?t=n[1].slice(1):"vector"!==n[1][0]&&"tuple"!==n[1][0]||("^"!==n[0]||"T"!==n[2])&&"prime"!==n[0]||(t=[1,n[1].length-1])),{setValue:{matrixSize:t}}}},e.nRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),definition:({dependencyValues:e})=>({setValue:{nRows:e.matrixSize[0]}})},e.nColumns={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),definition:({dependencyValues:e})=>({setValue:{nColumns:e.matrixSize[1]}})},e.matrix={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"matrixEntry"===e?[]:"row"===e?[["matrix","matrixRow"]]:"column"===e?[["matrix","matrixColumn"]]:[["matrixRow"],["matrix"]]},isArray:!0,nDimensions:2,entryPrefixes:["matrixEntry","row","column","rows","columns"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("matrixEntry"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}if("column"===e){let e=Number(t)-1;return Number.isInteger(e)&&e>=0?n?en+","+e)):[]:["0,"+e]:[]}if("rows"===e||"columns"===e){if(!n)return["0,0"];let e=[];for(let t=0;tt+","+n)));return e}},arrayVarNameFromPropIndex(e,t){if("matrix"===t||"rows"===t)return 1===e.length?"row"+e[0]:`matrixEntry${e[0]}_${e[1]}`;if("columns"===t)return 1===e.length?"column"+e[0]:`matrixEntry${e[1]}_${e[0]}`;if("row"===t.slice(0,3)){let n=Number(t.slice(3));if(Number.isInteger(n)&&n>0)return`matrixEntry${n}_${e[0]}`}if("column"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`matrixEntry${e[0]}_${n}`}return null},returnArraySizeDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),returnArraySize:({dependencyValues:e})=>e.matrixSize,returnArrayDependenciesByKey:()=>({globalDependencies:{value:{dependencyType:"stateVariable",variableName:"value"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t,arraySize:n}){let r=e.value.tree,a=!1,i={};if(Array.isArray(r))if(["vector","tuple","list"].includes(r[0])){for(let e=0;e({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}static adapters=[{stateVariable:"number",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text",{componentType:"subsetOfReals",stateVariable:"value",substituteForPrimaryStateVariable:"subsetValue"}];async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}actions={moveMath:this.moveMath.bind(this)}}function calculateExpressionWithCodes({dependencyValues:e,changes:t}){if(!("stringMathChildren"in t&&t.stringMathChildren.componentIdentitiesChanged||"displayedMathChildren"in t||"format"in t||"splitSymbols"in t||"parseScientificNotation"in t||"functionSymbols"in t||"mathChildrenFunctionSymbols"in t))return{useEssentialOrDefaultValue:{expressionWithCodes:!0}};if(0===e.stringMathChildren.length){if(e.displayedMathChildren.length>0){let t;try{t=me$3.fromLatex(e.displayedMathChildren[0].stateValues.latex)}catch(e){t=me$3.fromAst("_")}return{setValue:{expressionWithCodes:t},setEssentialValue:{expressionWithCodes:t}}}return{setValue:{expressionWithCodes:null}}}let n,r,a,i,o="",s=0,l="",u=e.stringMathChildren.compositeReplacementRange;e.groupCompositeReplacements&&u.length>0&&(a=0,i=u[a].firstInd);for(let[t,c]of e.stringMathChildren.entries()){if(void 0===n&&t===i){n=a,r=u[a].lastInd,l="";let o=r===t;if(!o)for(let n=t;n<=r;n++)if("string"==typeof e.stringMathChildren[n]){o=!0;break}o&&(u.length>n+1?(a=n+1,i=u[a].firstInd):(a=void 0,i=void 0),n=void 0,r=void 0)}if("string"==typeof c)o+=" "+c+" ";else{let t,r=e.codePre+s;s++,t="latex"===e.format?"\\var{"+r+"}":" "+r+" ",void 0!==n?(l&&(l+=","),l+=t):o+=t}if(t===r){let s=o.trimEnd(),c=!1;if(0===s.length)c=!0;else{let n=s[s.length-1];if(["{","[","(","|",","].includes(n)){let n=e.stringMathChildren[t+1];if("string"!=typeof n)c=!0;else{let t=n.trimStart();if(0===t.length)c=!0;else{let n=t[0];"latex"===e.format&&"\\"===n&&t.length>1&&(n=t[1]),["}","]",")","|",","].includes(n)||(c=!0)}}}else c=!0}c&&(l="("+l+")"),o+=l,l="",u.length>n+1?(a=n+1,i=u[a].firstInd):(a=void 0,i=void 0),n=void 0,r=void 0}}let c=null,p=[...e.functionSymbols];if(p.push(...e.mathChildrenFunctionSymbols.map((t=>e.codePre+t))),""===o)c=me$3.fromAst("_");else if("text"===e.format){let t=getFromText({functionSymbols:p,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation});try{c=t(o)}catch(e){c=me$3.fromAst("_"),console.log("Invalid value for a math of text format: "+o)}}else if("latex"===e.format){let t=getFromLatex({functionSymbols:p,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation});try{c=t(o)}catch(e){c=me$3.fromAst("_"),console.log("Invalid value for a math of latex format: "+o)}}return{setValue:{expressionWithCodes:c},setEssentialValue:{expressionWithCodes:c}}}function calculateMathValue({dependencyValues:e}={}){if(null===e.expressionWithCodes)return{setValue:{unnormalizedValue:e.valueShadow}};let t={};for(let[n,r]of e.mathChildren.entries())t[e.codePre+n]=r.stateValues.value;let n=e.expressionWithCodes;return e.mathChildren.length>0&&(n=n.substitute(t)),n=me$3.fromAst(mergeListsWithOtherContainers(n.tree)),{setValue:{unnormalizedValue:n}}}function calculateCodesAdjacentToStrings({dependencyValues:e}){let t,n=[];for(let[r,a]of e.stringMathChildren.entries())if("string"==typeof a){let a=e.stringMathChildren[r+1];if(void 0!==a&&"string"==typeof a)continue;let i={};if(void 0!==t&&("latex"===e.format?i.prevCode="\\var{"+e.codePre+t+"}":i.prevCode=e.codePre+t),void 0!==a){let n=0;void 0!==t&&(n=t+1),"latex"===e.format?i.nextCode="\\var{"+e.codePre+n+"}":i.nextCode=e.codePre+n}n.push(i)}else void 0===t?t=0:t++;return{setValue:{codesAdjacentToStrings:n}}}function determineCanBeModified({dependencyValues:e}){if(!e.modifyIndirectly||e.fixed)return{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}};if(0===e.mathChildrenModifiable.length)return e.displayedMathChildren.length>0?{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}}:{setValue:{canBeModified:!0,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}};let t=[],n=[],r=[],a={};for(let[i,o]of e.mathChildrenModifiable.entries()){let s=e.codePre+i;!0===o.stateValues.canBeModified?(t.push(i),n.push(s)):(r.push(s),a[s]=i)}let i=e.codePre+"expr",o=checkForLinearExpression(me$3.utils.unflattenLeft(e.expressionWithCodes.tree),n,i,r);if(o.foundLinear){let e={},r=o.template,s=new Set;for(let r in o.mappings){e[r]=o.mappings[r];let a=e[r].mathChildSub;if(a){let i=t[n.indexOf(a)];e[r].mathChildInd=i,s.add(Number(i))}}return s.has=s.has.bind(s),{setValue:{canBeModified:!0,constantChildIndices:a,codeForExpression:i,inverseMaps:e,template:r,mathChildrenMapped:s}}}return{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}}}function checkForLinearExpression(e,t,n,r=[],a=[]){let i=me$3.variables(e);if(i.every((e=>!t.includes(e)))&&i.every((e=>!r.includes(e)))){let e={},t="x"+a.join("_");return e[t]={result:me$3.fromAst(n).simplify(),components:a},{foundLinear:!0,mappings:e,template:t}}if(!Array.isArray(e))return checkForScalarLinearExpression(e,t,n,a);let o=e[0],s=e.slice(1);if("tuple"===o||"vector"===o||"list"===o){let e={mappings:{},template:[o]},i=0;for(let o=0;o!t.includes(e)))?(n=["+",n,["-",i[0]]],checkForScalarLinearExpression(i[1],t,n,r)):me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["+",n,["-",i[1]]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}:"*"===a?me$3.variables(i[0]).every((e=>!t.includes(e)))?(n=["/",n,i[0]],checkForScalarLinearExpression(i[1],t,n,r)):me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["/",n,i[1]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}:"/"===a&&me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["*",n,i[1]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}}async function invertMath({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r,overrideFixed:a,componentName:i}){if(!await n.canBeModified&&!a)return{success:!1};let o=t.mathChildren,s=t.stringChildren.length;if(1===o.length&&0===s)return{success:!0,instructions:[{setDependency:"mathChildren",desiredValue:e.unnormalizedValue,childIndex:0,variableIndex:0}]};let l=convertValueToMathExpression(e.unnormalizedValue),u=await preprocessMathInverseDefinition({desiredValue:l,stateValues:n,variableName:"value",workspace:r}),c=u.vectorComponentsNotAffected;if(l=u.desiredValue,0===o.length){let h=[];return s>0?h.push({setDependency:"expressionWithCodes",desiredValue:l}):h.push({setDependency:"valueShadow",desiredValue:l}),{success:!0,instructions:h}}let p=await getExpressionPieces({expression:l,stateValues:n});if(!p)return{success:!1};let d=[],m=[];if(c&&await n.mathChildrenByVectorComponent){let y=await n.mathChildrenByVectorComponent;for(let b of c)y[b]&&m.push(...y[b])}let f=await n.mathChildrenWithCanBeModified;for(let[g,v]of o.entries())if(n.mathChildrenMapped.has(g)&&f[g].stateValues.canBeModified){if(!m.includes(g)){let T=p[g],N={},C=!1,A=await n.constantChildIndices;for(let S in A){let x=A[S];N[S]=o[x].stateValues.value,C=!0}C&&(T=T.substitute(N)),T=T.simplify(),d.push({setDependency:"mathChildren",desiredValue:T,childIndex:g,variableIndex:0})}delete p[g]}if(s>0){let w=t.expressionWithCodes,V=t.codePre,E=V.length;function O(e){return"string"==typeof e&&e.substring(0,E)===V}function _(e){return Array.isArray(e)?flattenDeep(e.slice(1)).some(O):O(e)}if(["vector","tuple","list"].includes(w.tree[0])&&!w.tree.slice(1).every(_)){let $=await n.inverseMaps;for(let D in p){let I=$[D];if(void 0!==I.mathChildInd)continue;let R=I.components;w=w.substitute_component(R,p[D])}d.push({setDependency:"expressionWithCodes",desiredValue:w})}}return{success:!0,instructions:d}}async function getExpressionPieces({expression:e,stateValues:t}){let n=await t.template,r=me$3.utils.match(e.tree,n);if(!(r||(r=me$3.utils.match(e.tuples_to_vectors().tree,me$3.fromAst(n).tuples_to_vectors().tree),r||(r=me$3.utils.match(e.to_intervals().tree,me$3.fromAst(n).to_intervals().tree),r||(r=me$3.utils.match(e.tuples_to_vectors().to_intervals().tree,me$3.fromAst(n).tuples_to_vectors().to_intervals().tree),r)))))return!1;let a={};for(let e in r){let n={};n[await t.codeForExpression]=r[e];let i=(await t.inverseMaps)[e];if(void 0!==i){let r=e;void 0!==i.mathChildInd&&(r=i.mathChildInd),a[r]=i.result.substitute(n),a[r]=normalizeMathExpression({value:a[r],simplify:await t.simplify,expand:await t.expand,createVectors:await t.createVectors,createIntervals:await t.createIntervals})}}return a}class Label extends InlineComponent{static componentType="label";static renderChildren=!0;static rendererType="label";static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="valueShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.forObject={createPrimitiveOfType:"string",createStateVariable:"forObject",defaultValue:null,public:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.valueShadow={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{valueShadow:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"valueShadow",value:e.valueShadow}]})},e.hasLatex={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text","latex","value","hasLatex","renderAsMath"],variablesOptional:!0},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length&&null!==e.valueShadow){let t=e.valueShadow;return{setValue:{hasLatex:Boolean(/\\\(.*\\\)/.exec(t))}}}for(let t of e.inlineChildren)if("object"!=typeof t);else if("boolean"==typeof t.stateValues.hasLatex&&"string"==typeof t.stateValues.value&&"string"==typeof t.stateValues.text){if(t.stateValues.hasLatex)return{setValue:{hasLatex:!0}}}else if("boolean"==typeof t.stateValues.renderAsMath&&"string"==typeof t.stateValues.latex&&"string"==typeof t.stateValues.text){if(t.stateValues.renderAsMath)return{setValue:{hasLatex:!0}}}else if("string"==typeof t.stateValues.latex)return{setValue:{hasLatex:!0}};return{setValue:{hasLatex:!1}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"latex",public:!0,shadowingInstructions:{createComponentOfType:"text"}},{variableName:"value",public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"hasLatex"}}}}],returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text","latex","value","hasLatex","renderAsMath"],variablesOptional:!0},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"},hasLatex:{dependencyType:"stateVariable",variableName:"hasLatex"}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length&&null!==e.valueShadow){let t=e.valueShadow,n=t;return e.hasLatex&&(n=n.replace(/\\\(/g,""),n=n.replace(/\\\)/g,"")),{setValue:{text:n,latex:n,value:t}}}let t="",n="";for(let r of e.inlineChildren)if("object"!=typeof r){let e=r.toString();t+=e,n+=e}else"boolean"==typeof r.stateValues.hasLatex&&"string"==typeof r.stateValues.value&&"string"==typeof r.stateValues.text?(t+=r.stateValues.text,n+=r.stateValues.value):"boolean"==typeof r.stateValues.renderAsMath&&"string"==typeof r.stateValues.latex&&"string"==typeof r.stateValues.text?r.stateValues.renderAsMath?(t+=r.stateValues.latex,n+="\\("+r.stateValues.latex+"\\)"):(t+=r.stateValues.text,n+=r.stateValues.text):"string"==typeof r.stateValues.latex?(t+=r.stateValues.latex,n+="\\("+r.stateValues.latex+"\\)"):"string"==typeof r.stateValues.text&&(t+=r.stateValues.text,n+=r.stateValues.text);return{setValue:{text:t,latex:t,value:n}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n;if("string"==typeof e.value)n=e.value;else if("string"==typeof e.text)n=e.text;else{if("string"!=typeof e.latex)return{success:!1};n=e.latex}if(0===t.inlineChildren.length&&null!==t.valueShadow)return{success:!0,instructions:[{setDependency:"valueShadow",desiredValue:n}]};if(1===t.inlineChildren.length){let n=t.inlineChildren[0],r=e.value;if("object"!=typeof n)return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0}]};if("boolean"==typeof n.stateValues.hasLatex&&"string"==typeof n.stateValues.value&&"string"==typeof n.stateValues.text)return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:2}]};if("boolean"==typeof n.stateValues.renderAsMath&&"string"==typeof n.stateValues.latex&&"string"==typeof n.stateValues.text){if(n.stateValues.renderAsMath){let e=r.match(/^\\\((.*)\\\)/);return e&&(r=e[1]),{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:1}]}}return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:0}]}}if("string"==typeof n.stateValues.latex){let e=r.match(/^\\\((.*)\\\)/);return e&&(r=e[1]),{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:1}]}}return"string"==typeof n.stateValues.text?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:0}]}:{success:!1}}return{success:!1}}},e.forObjectComponentName={stateVariablesDeterminingDependencies:["forObject"],returnDependencies:({stateValues:e})=>({forObjectComponentName:{dependencyType:"expandTargetName",target:e.forObject}}),definition:({dependencyValues:e})=>({setValue:{forObjectComponentName:e.forObjectComponentName}})},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}static adapters=["text"];async moveLabel({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}actions={moveLabel:this.moveLabel.bind(this)}}function returnGroupIntoComponentTypeSeparatedBySpaces({componentType:e,forceComponentType:t=!1}){return function({matchedChildren:n,componentInfoObjects:r}){let a=[],i=[];function o(){let n=!1;if(t){if(1===i.length){let t=i[0],o=t.componentType;"copy"===o&&t.attributes?.createComponentOfType&&(t.attributes.nComponents&&1!==t.attributes.nComponents.primitive||(o=t.attributes.createComponentOfType.primitive)),r.isInheritedComponentType({inheritedComponentType:o,baseComponentType:e})&&(a.push(t),n=!0)}}else 1===i.length&&"string"!=typeof i[0]&&(a.push(i[0]),n=!0);!n&&i.length>0&&a.push({componentType:e,children:i}),i=[]}for(let e of n)if("string"!=typeof e)i.push(e);else{let t=e.split(/\s+/),n=t[0];""===n?o():i.push(n);for(let e of t.slice(1))o(),""!==e&&i.push(e)}return o(),{success:!0,newChildren:a}}}function returnBreakStringsIntoComponentTypeBySpaces({componentType:e}){return function({matchedChildren:t}){let n=t.reduce((function(t,n){return"string"==typeof n?[...t,...n.split(/\s+/).filter((e=>e)).map((t=>({componentType:e,children:[t]})))]:[...t,n]}),[]);return{success:!0,newChildren:n}}}class MathList extends InlineComponent{static componentType="mathList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="maths";static primaryStateVariableForDefinition="mathsShadow";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.mergeMathLists={createComponentOfType:"boolean"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"math"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"math"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"mathLists",componentTypes:["mathList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{mathsShadow:!0}})},e.mergeMathLists={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({mergeMathListsAttr:{dependencyType:"attributeComponent",attributeName:"mergeMathLists",variableNames:["value"]},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],skipComponentNames:!0},mathChildren:{dependencyType:"child",childGroups:["maths"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{mergeMathLists:e.mergeMathListsAttr?.stateValues.value||0===e.mathListChildren.length&&1===e.mathChildren.length}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["mergeMathLists"],additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies({stateValues:e}){let t={maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}};return e.mergeMathLists?t.mathAndMathListChildren={dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["value","nComponents"],variablesOptional:!0}:(t.mathListChildren={dependencyType:"child",childGroups:["mathLists"],variableNames:["nComponents"]},t.mathAndMathListChildren={dependencyType:"child",childGroups:["maths","mathLists"],skipComponentNames:!0}),t},definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[];if(e.mathAndMathListChildren.length>0)if(e.mergeMathLists)for(let[a,i]of e.mathAndMathListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})){for(let e=0;ea&&(n=a,r=r.slice(0,a)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.maths={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["math"],stateVariablesDeterminingDependencies:["mergeMathLists","childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["value","math"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].mathAndMathListChildren[0];if(n)if(void 0!==n.stateValues.value){let t=n.stateValues.value;if(e.mergeMathLists&&Array.isArray(t.tree)&&"list"===t.tree[0]){let n=e.childIndexByArrayKey[a][1];r[a]=t.get_component(n)}else r[a]=t}else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["math"+t]}else null!==e.mathsShadow&&(r[a]=e.mathsShadow[a])}return{setValue:{maths:r}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,stateValues:a,workspace:i}){if(t.mergeMathLists){let t=[],o=await a.childIndexByArrayKey,s=[];for(let l in e.maths){if(!n[l])continue;if(s.includes(l))continue;let u;if(void 0!==o[l][2]){let t=Number(l)-o[l][1],n=t+o[l][2]-1;i.desiredMaths||(i.desiredMaths=[]);let r=["list"];for(let o=t;o<=n;o++)void 0!==e.maths[o]?i.desiredMaths[o]=convertValueToMathExpression(e.maths[o]):void 0===i.desiredMaths[o]&&(i.desiredMaths[o]=(await a.maths)[o]),r.push(i.desiredMaths[o].tree),s.push(o.toString());u=me$3.fromAst(r)}else u=e.maths[l];let c=n[l].mathAndMathListChildren[0];c&&(void 0!==c.stateValues.value?t.push({setDependency:r[l].mathAndMathListChildren,desiredValue:u,childIndex:0,variableIndex:0}):t.push({setDependency:r[l].mathAndMathListChildren,desiredValue:u,childIndex:0,variableIndex:1}))}return{success:!0,instructions:t}}let o=[];for(let t in e.maths){if(!n[t])continue;let a=n[t].mathAndMathListChildren[0];a&&(void 0!==a.stateValues.value?o.push({setDependency:r[t].mathAndMathListChildren,desiredValue:e.maths[t],childIndex:0,variableIndex:0}):o.push({setDependency:r[t].mathAndMathListChildren,desiredValue:e.maths[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:o}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({maths:{dependencyType:"stateVariable",variableName:"maths"}}),definition({dependencyValues:e}){let t;return t=0===e.maths.length?me$3.fromAst("_"):1===e.maths.length?e.maths[0]:me$3.fromAst(["list",...e.maths.map((e=>e.tree))]),{setValue:{math:t}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"maths"},e.latex={additionalStateVariablesDefined:["latexs"],public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["valueForDisplay","latex","latexs"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n=[],r={};if(e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.mathAndMathListChildren.length>0)for(let t of e.mathAndMathListChildren)if(t.stateValues.valueForDisplay){let a=t.stateValues.valueForDisplay;if(e.mergeMathLists&&Array.isArray(a.tree)&&"list"===a.tree[0])for(let e=0;eroundForDisplay({value:n,dependencyValues:e,usedDefault:t}).toLatex(r))));let a=e.maximumNumber;return null!==a&&n.length>a&&(a=Math.max(0,Math.floor(a)),n=n.slice(0,a)),{setValue:{latex:n.join(", "),latexs:n}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["valueForDisplay","text","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}}),definition:function({dependencyValues:e}){let t=[];if(e.mathAndMathListChildren.length>0)for(let n of e.mathAndMathListChildren)if(n.stateValues.valueForDisplay){let r=n.stateValues.valueForDisplay;if(e.mergeMathLists&&Array.isArray(r.tree)&&"list"===r.tree[0])for(let e=0;ee.toString())));let n=e.maximumNumber;return null!==n&&t.length>n&&(n=Math.max(0,Math.floor(n)),t=t.slice(0,n)),{setValue:{text:t.join(", "),texts:t}}}},e.componentNamesInList={returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.mathAndMathListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"mathList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],variableNames:["nComponents"]},mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,o=0,s=0;for(let n of e.mathAndMathListChildren){let l=Math.max(0,r-i);if(l>0&&o++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"mathList"})){let t=e.mathListChildren[s];s++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:o}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class Columns extends Text{static componentType="columns";static rendererType="text"}class Title extends TextOrInline{static componentType="title"}class RightHandSide extends MathComponent{static componentType="rightHandSide";static rendererType="math"}class Description extends TextOrInline{static componentType="description";static rendererType=void 0}class Else extends Template{static componentType="else"}class Xlabel extends Label{static componentType="xlabel";static rendererType="label"}class Ylabel extends Label{static componentType="ylabel";static rendererType="label"}class MatrixRow extends MathList{static componentType="matrixRow";static rendererType="mathList"}class MatrixColumn extends MathList{static componentType="matrixColumn";static rendererType="mathList"}var Aliases=Object.freeze({__proto__:null,Columns:Columns,Title:Title,RightHandSide:RightHandSide,Description:Description,Else:Else,Xlabel:Xlabel,Ylabel:Ylabel,MatrixRow:MatrixRow,MatrixColumn:MatrixColumn});class M$3 extends InlineComponent{static componentType="m";static rendererType="math";static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="latex";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"inline",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"",hasEssential:!0,forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["latex","text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length)return{useEssentialOrDefaultValue:{latex:!0}};let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n:"string"==typeof n.stateValues.latex?t+=n.stateValues.latex:"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{latex:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.latex)return{success:!1};if(0===t.inlineChildren.length)return{success:!0,instructions:[{setEssentialValue:"latex",value:e.latex}]};if(1===t.inlineChildren.length){let n=t.inlineChildren[0];return"object"!=typeof n?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0}]}:"string"==typeof n.stateValues.latex?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0,variableIndex:0}]}:"string"==typeof n.stateValues.text?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0,variableIndex:1}]}:{success:!1}}return{success:!1}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["latex","text"],variablesOptional:!0},latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){if(0===e.inlineChildren.length)return{setValue:{latexWithInputChildren:[e.latex]}};let n=[],r="",a=0;for(let i of e.inlineChildren)"object"!=typeof i?r+=i:t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"input"})?(r.length>0&&(n.push(r),r=""),n.push(a),a++):"string"==typeof i.stateValues.latex?r+=i.stateValues.latex:"string"==typeof i.stateValues.text&&(r+=i.stateValues.text);return r.length>0&&n.push(r),{setValue:{latexWithInputChildren:n}}}},e.renderMode={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{renderMode:"inline"}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){let t;try{t=me$3.fromAst(latexToAst.convert(e.latex))}catch(t){return{setValue:{text:e.latex}}}return{setValue:{text:superSubscriptsToUnicode(t.toString())}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}actions={moveMath:this.moveMath.bind(this)}}class Me$2 extends M$3{static componentType="me";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"display"}}),e}}class Men extends M$3{static componentType="men";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"numbered"}}),e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({equationCounter:{dependencyType:"counter",counterName:"equation"}}),definition:({dependencyValues:e})=>({setValue:{equationTag:String(e.equationCounter)}})},e}}var MMeMen=Object.freeze({__proto__:null,M:M$3,Me:Me$2,Men:Men});class Md extends InlineComponent{static componentType="md";static rendererType="math";static primaryStateVariableForDefinition="latex";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"mrows",componentTypes:["mrow"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.mrowChildNames={forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"]}}),definition:({dependencyValues:e})=>({setValue:{mrowChildNames:e.mrowChildren.map((e=>e.componentName))}})},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"",hasEssential:!0,shadowVariable:!0,forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"],variableNames:["latex","hide","equationTag","numbered"]}}),definition:function({dependencyValues:e}){if(e.mrowChildren.length>0){let t="";for(let n of e.mrowChildren)n.stateValues.hide||(t.length>0&&(t+="\\\\"),n.stateValues.numbered?t+=`\\tag{${n.stateValues.equationTag}}`:t+="\\notag ",t+=n.stateValues.latex);return{setValue:{latex:t}}}return{useEssentialOrDefaultValue:{latex:!0}}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"],variableNames:["latexWithInputChildren","hide","equationTag","numbered"]},latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){if(e.mrowChildren.length>0){let t=[],n=0,r="";for(let a of e.mrowChildren)if(!a.stateValues.hide){r.length>0&&(r+="\\\\"),a.stateValues.numbered?r+=`\\tag{${a.stateValues.equationTag}}`:r+="\\notag ";for(let e of a.stateValues.latexWithInputChildren)"number"==typeof e?(r.length>0&&(t.push(r),r=""),t.push(n),n++):r+=e}return r.length>0&&t.push(r),{setValue:{latexWithInputChildren:t}}}return{setValue:{latexWithInputChildren:[e.latex]}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){let t;try{t=e.latex.replaceAll("\\notag","").replaceAll("\\amp","").split("\\\\").map((e=>me$3.fromAst(latexToAst.convert(e)).toString())).join("\\\\\n")}catch(t){return{setValue:{text:e.latex}}}return{setValue:{text:superSubscriptsToUnicode(t.toString())}}}},e.renderMode={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{renderMode:"align"}})},e.numbered={returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!1}})},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}actions={moveMath:this.moveMath.bind(this)}}class Mdn extends Md{static componentType="mdn";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!0}})},e}}class Mrow extends M$3{static componentType="mrow";static createAttributesObject(){let e=super.createAttributesObject();return e.number={createComponentOfType:"boolean"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"display"}}),e.numbered={forRenderer:!0,returnDependencies:()=>({parentNumbered:{dependencyType:"parentStateVariable",variableName:"numbered"},numberAttr:{dependencyType:"attributeComponent",attributeName:"number",variableNames:["value"]}}),definition({dependencyValues:e}){let t;return t=null!==e.numberAttr?e.numberAttr.stateValues.value:e.parentNumbered,{setValue:{numbered:t}}}},e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["numbered"],returnDependencies:({stateValues:e})=>e.numbered?{equationCounter:{dependencyType:"counter",counterName:"equation"}}:{},definition:({dependencyValues:e})=>void 0!==e.equationCounter?{setValue:{equationTag:String(e.equationCounter)}}:{setValue:{equationTag:null}}},e}}var MdMdnMrow=Object.freeze({__proto__:null,Md:Md,Mdn:Mdn,Mrow:Mrow});function periodicSetEquality(e,t,{min_elements_match:n=3,match_partial:r=!1}={}){if(!is_periodic_set(e))return!1;if(is_periodic_set(t)){if(r){let n=contained_in(e.tree,t.tree,r);if(!1===n)return 0;let a=contained_in(t.tree,e.tree,r);return!1===a?0:!0===n?!0===a?1:a:!0===a?n:Math.min(n,a)}return contained_in(e.tree,t.tree,r)&&contained_in(t.tree,e.tree,r)}{let a=e.tree.slice(1);if(a.length>1)return!1;let i=me$3.fromAst(a[0][1]).evaluate_to_constant(),o=me$3.fromAst(["apply","abs",a[0][2]]).evaluate_to_constant();if(!Number.isFinite(i)||!Number.isFinite(o))return!1;let s=a[0][3],l=a[0][4];if(s!==-1/0||l!==1/0)return!1;if("list"!==t.tree[0])return!1;let u=t.tree.slice(1),c=0;if("ldots"===u[0][0])c++,u=u.slice(1);else if(!r)return!1;if("ldots"===u[u.length-1][0])c++,u=u.slice(0,u.length-1);else if(!r)return!1;let p=u.length;if(0===p)return!1;if(!r&&pme$3.fromAst(e).evaluate_to_constant())).map((e=>Number.isFinite(e)?e:NaN));let d=me$3.math.mod(u[0]-i,o);if(!(me$3.math.min(d,o-d)<1e-10*o))return!1;let m=1;for(let e=1;e=n)return!0;let f=m/Math.max(p,n);return f*=(9+c/2)/10,f}}function is_periodic_set(e){var t=e.tree;if(!Array.isArray(t))return!1;if("periodic_set"!==t[0])return!1;var n=t.slice(1);for(var r of n){if(!Array.isArray(r))return!1;if("tuple"!==r[0])return!1;if(5!==r.length)return!1}return!0}function contained_in(e,t,n){if("periodic_set"===e[0]){if(n){let r=0;for(let a of e.slice(1)){let e=contained_in(a,t,n);!0===e?r++:!1!==e&&(r+=e)}let a=e.length-1;return r===a||0!==r&&r/a}return e.slice(1).every((e=>contained_in(e,t)))}var r=e[1],a=e[2],i=e[3],o=e[4];if(i!==-1/0||o!==1/0)return!1;r=me$3.fromAst(["/",r,a]).evaluate_to_constant();var s=t.slice(1),l=[];for(let e=0;e1e3)return!1;let c=o.d;l.push([u,c,r,i])}for(l.sort();;){if(1!==l[0][0])break;let e=l[0][2],t=l[0][3],n=me$3.fromAst(["+",e,["-",r]]).evaluate_to_constant();if(Number.isFinite(n)&&Number.isFinite(t)&&(n=me$3.math.mod(n,t),me$3.math.min(n,t-n)<1e-10*t))return!0;if(l.splice(0,1),0===l.length)return!1}var u=[...new Set(l.map((e=>e[0])))];let c=0;for(let e of u){let t=l.map((function(t,n){let r=e/t[0];return Number.isInteger(r)?[t[0],r,n]:void 0})).filter((e=>e)),a=[];for(let n of t){let t=n[0],i=n[1],o=n[2],s=l[o][2],u=l[o][3];for(let n=0;nc&&(c=t)}}return!!(n&&c>0)&&c}function checkEquality({object1:e,object2:t,isUnordered:n=!1,partialMatches:r=!1,matchByExactPositions:a=!1,symbolicEquality:i=!1,simplify:o="none",expand:s=!1,allowedErrorInNumbers:l=0,includeErrorInNumberExponents:u=!1,allowedErrorIsAbsolute:c=!1,nSignErrorsMatched:p=0,nPeriodicSetMatchesRequired:d=3,caseInsensitiveMatch:m=!1,matchBlanks:f=!1}){let h=!1;if(e instanceof me$3.class){if(h=!0,!(t instanceof me$3.class)){if("number"!=typeof t&&"string"!=typeof t)return{fraction_equal:0};t=me$3.fromAst(t)}}else if(t instanceof me$3.class){if(h=!0,"number"!=typeof e&&"string"!=typeof e)return{fraction_equal:0};e=me$3.fromAst(e)}let y,b=function(e){return e instanceof me$3.class||(e=me$3.fromAst(e)),e=e.normalize_function_names().normalize_applied_functions(),m&&(e=me$3.fromAst(setStringsInTreeToLowerCase(e.tree))),"none"===o?l>0&&(e=e.constants_to_floats()):e="numberspreserveorder"===o?e.evaluate_numbers({max_digits:1/0,skip_ordering:!0}):"number"===o?e.evaluate_numbers({max_digits:1/0}):e.evaluate_numbers({max_digits:1/0,evaluate_functions:!0}),normalizeMathExpression({value:e,simplify:o,expand:s})};y=h?i?function(e,t){let n=b(e),r=b(t);if(p>0){r=JSON.parse(JSON.stringify(r),me$3.reviver);let e=function(e,t){return!e.variables().includes("_")&&!t.variables().includes("_")&&(e=b(e)).equalsViaSyntax(t,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:f})};return n.tree.im||r.tree.im?{fraction_equal:0}:{fraction_equal:me$3.equalSpecifiedSignErrors(r,n,{equalityFunction:e,n_sign_errors:p})?1:0}}if(n.variables().includes("_")||r.variables().includes("_"))return{fraction_equal:0};if(n.tree.im||r.tree.im)return{fraction_equal:0};return{fraction_equal:n.equalsViaSyntax(r,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:f})?1:0}}:function(e,t){let n=e,r=t;if(e instanceof me$3.class||(n=me$3.fromAst(e)),t instanceof me$3.class||(r=me$3.fromAst(t)),m&&(n=me$3.fromAst(setStringsInTreeToLowerCase(n.tree)),r=me$3.fromAst(setStringsInTreeToLowerCase(r.tree))),p>0){r=JSON.parse(JSON.stringify(r),me$3.reviver);let e=function(e,t){return e.equals(t,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:f})};return n.tree.im||r.tree.im?{fraction_equal:0}:{fraction_equal:me$3.equalSpecifiedSignErrors(r,n,{equalityFunction:e,n_sign_errors:p})?1:0}}if(n.tree.im||r.tree.im)return{fraction_equal:0};return{fraction_equal:n.equals(r,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:f})?1:0}}:(e,t)=>(m&&(e=convertStringsToLowerCase(e),t=convertStringsToLowerCase(t)),{fraction_equal:deepCompare(e,t)?1:0});let g=!1,v=!1;if(h){let i=e.tree[0],o=t.tree[0];if("periodic_set"===i||"periodic_set"===o){let n=e,a=t;"periodic_set"!==i&&(n=t,a=e);let o=periodicSetEquality(n,a,{match_partial:r,min_elements_match:d});return!0===o?{fraction_equal:1}:!1===o?{fraction_equal:0}:{fraction_equal:o}}if("list"===i)e=e.tree.slice(1),t="list"===o?t.tree.slice(1):[t.tree];else if("list"===o)t=t.tree.slice(1),e=[e.tree];else if("vector"===i){if(e=e.tree.slice(1),"interval"===o||"matrix"===o||"array"===o||"set"===o)return{fraction_equal:0};t="tuple"===o||"vector"===o?t.tree.slice(1):[t.tree]}else if("vector"===o){if(t=t.tree.slice(1),"interval"===i||"matrix"===i||"array"===i||"set"===i)return{fraction_equal:0};e="tuple"===i?e.tree.slice(1):[e.tree]}else if("interval"===i){a=!0;let n=e.tree[2],r=n[1],i=n[2];if(e=e.tree[1].slice(1),"matrix"===o||"set"===o)return{fraction_equal:0};if("tuple"===o){let e=t.tree.slice(1);if(2!==e.length||!1!==r||!1!==i)return{fraction_equal:0};t=e}else if("array"===o){let e=t.tree.slice(1);if(2!==e.length||!0!==r||!0!==i)return{fraction_equal:0};t=e}else{if("interval"!==o)return{fraction_equal:0};{let e=t.tree[2];if(e[1]!==r||e[2]!==i)return{fraction_equal:0};t=t.tree[1].slice(1)}}}else if("interval"===o){a=!0;let n=t.tree[2],r=n[1],o=n[2];if(t=t.tree[1].slice(1),"matrix"===i||"set"===i)return{fraction_equal:0};if("tuple"===i){let t=e.tree.slice(1);if(2!==t.length||!1!==r||!1!==o)return{fraction_equal:0};e=t}else{if("array"!==i)return{fraction_equal:0};{let t=e.tree.slice(1);if(2!==t.length||!0!==r||!0!==o)return{fraction_equal:0};e=t}}}else if("matrix"===i){if("matrix"!==o)return{fraction_equal:0};e=convertMatrixToArrayOfTuples(e.tree.slice(1)),t=convertMatrixToArrayOfTuples(t.tree.slice(1)),a=!0,v=!0,g=!0}else{if("matrix"===o)return{fraction_equal:0};if("set"===i){let r=[];for(let t of e.tree.slice(1))r.some((e=>1===y(e,t).fraction_equal))||r.push(t);if(e=r,n=!0,"tuple"===o||"array"===o)return{fraction_equal:0};if("set"===o){r=[];for(let e of t.tree.slice(1))r.some((t=>1===y(t,e).fraction_equal))||r.push(e);t=r}else t=[t.tree]}else if("set"===o){let r=[];for(let e of t.tree.slice(1))r.some((t=>1===y(t,e).fraction_equal))||r.push(e);if(t=r,n=!0,"tuple"===i||"array"===i)return{fraction_equal:0};e=[e.tree]}else if("tuple"===i){if(e=e.tree.slice(1),"array"===o)return{fraction_equal:0};t="tuple"===o?t.tree.slice(1):[t.tree]}else if("tuple"===o){if(t=t.tree.slice(1),"array"===i)return{fraction_equal:0};e=[e.tree]}else if("array"===i)e=e.tree.slice(1),t="array"===o?t.tree.slice(1):[t.tree];else{if("array"!==o)return y(e.tree,t.tree);t=t.tree.slice(1),e=[e.tree]}}}else if(Array.isArray(e))Array.isArray(t)||(t="string"==typeof t&&e.every((e=>"string"==typeof e&&!e.includes(",")))?t.split(",").map((e=>e.trim())):[t]);else{if(!Array.isArray(t))return y(e,t);e="string"==typeof e&&t.every((e=>"string"==typeof e&&!e.includes(",")))?e.split(",").map((e=>e.trim())):[e]}let T=e.length,N=t.length,C={fraction_equal:0};if(a&&(n=!1),!n){let n=0,u=Math.min(T,N);for(let r=0;rArray(N+1).fill(0)));for(let n=0;nr&&(r=t.fraction_equal,e=a)}-1!==e&&(S+=r,A.add(e))}return T===N&&T===S?(C.fraction_equal=1,C):r?(C.fraction_equal=S/Math.max(T,N),C):C}function setStringsInTreeToLowerCase(e){return"string"==typeof e?e.toLowerCase():Array.isArray(e)?[e[0],...e.slice(1).map(setStringsInTreeToLowerCase)]:e}function convertStringsToLowerCase(e){return"string"==typeof e?e.toLowerCase():Array.isArray(e)?e.map(convertStringsToLowerCase):e}function convertMatrixToArrayOfTuples(e){let t=e[0][1],n=e[0][2];if(!Number.isInteger(t)||!Number.isInteger(n))return e;let r=[];for(let a=0;aevaluateLogic({logicTree:e,canOverrideUnorderedCompare:t,dependencyValues:n,valueOnInvalid:r});if(!Array.isArray(e)){if("string"==typeof e){let t=n.booleanChildrenByCode[e];if(t)return n.matchPartial&&void 0!==t.stateValues.fractionSatisfied?t.stateValues.fractionSatisfied:t.stateValues.value?1:0;{let t=n.mathChildrenByCode[e];if(t){let e=t.stateValues.value.simplify().evaluate_to_constant();return Number.isFinite(e)&&0!==e?1:0}{let t=n.numberChildrenByCode[e];if(t){let e=t.stateValues.value;return Number.isFinite(e)&&0!==e?1:0}if("true"===e.toLowerCase())return 1;if("false"===e.toLowerCase())return 0}}}else if("number"==typeof e)return 0===e?0:1;return console.warn("Invalid format for boolean condition"),r}let i=e[0],o=e.slice(1);if("not"===i)return 1!==o.length?(console.warn("Invalid format for boolean condition"),r):0===a(o[0])?1:0;if("and"===i)return n.matchPartial?o.reduce(((e,t)=>e+a(t)),0)/o.length:o.every((e=>1===a(e)))?1:0;if("or"===i)return n.matchPartial?o.reduce(((e,t)=>Math.max(a(t),e)),0):o.some((e=>1===a(e)))?1:0;let s=!1,l=!1,u=!1,c=!1;o.forEach((function(e){"string"==typeof e&&(e in n.mathChildrenByCode||e in n.mathListChildrenByCode||e in n.numberChildrenByCode||e in n.numberListChildrenByCode?s=!0:e in n.textChildrenByCode||e in n.textListChildrenByCode?l=!0:e in n.booleanChildrenByCode||e in n.booleanListChildrenByCode?u=!0:e in n.otherChildrenByCode&&(c=!0))}));let p,d=function(e){if("string"==typeof e){let t=n.mathChildrenByCode[e];return void 0!==t?t.stateValues.value.tree:(t=n.mathListChildrenByCode[e],void 0!==t?["list",...t.stateValues.maths.map((e=>e.tree))]:(t=n.numberChildrenByCode[e],void 0!==t?numberToMathExpression(t.stateValues.value).tree:(t=n.numberListChildrenByCode[e],void 0!==t?["list",...t.stateValues.numbers]:e)))}return Array.isArray(e)?[e[0],...e.slice(1).map(d)]:e};if("apply"===i&&["isnumber","isinteger"].includes(o[0])){if(l||u||c)return 0;let e=me$3.fromAst(d(o[1])).simplify().evaluate_to_constant();if(!Number.isFinite(e))return 0;if("isnumber"===o[0])return 1;{let t=Math.round(e);return Math.abs(t-e)<=1e-15*Math.abs(e)?1:0}}if(!["=","ne","<",">","le","ge","lts","gts","in","notin"].includes(i)){if(l||u||c)return console.warn("Invalid format for boolean condition"),r;let t=me$3.fromAst(d(e)).simplify().evaluate_to_constant();return Number.isFinite(t)&&0!==t?1:0}if(u){if(s||l||c)return console.warn("Invalid format for boolean condition"),r;let e=!1,a=!1;if(o=o.map((function(t){if("string"==typeof t){let i=n.booleanChildrenByCode[t];return void 0!==i?i.stateValues.value:(i=n.booleanListChildrenByCode[t],void 0!==i?(i.stateValues.unordered&&(a=!0),i.stateValues.booleans):"true"===(t=t.toLowerCase().trim())||"t"===t||"false"!==t&&"f"!==t&&(console.warn("Invalid format for boolean condition"),e=!0,r))}return console.warn("Invalid format for boolean condition"),e=!0,r})),e)return r;let u=n.unorderedCompare;if(t&&a&&(u=!0),"="===i){let e=o[0];if(n.matchPartial){let t=o.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return o.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}).fraction_equal))?1:0}if("ne"===i){if(2!==o.length)return console.warn("Invalid format for boolean condition"),r;return 0===checkEquality({object1:o[0],object2:o[1],isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}).fraction_equal?1:0}return console.warn("Invalid format for boolean condition"),r}if(l){if(s||c)return console.warn("Invalid format for boolean condition"),r;let e=!1,a=!1,l=function(t,r=!1){if("string"==typeof t){let e=n.textChildrenByCode[t];return void 0!==e?e.stateValues.value.trim().replace(/\s+/," "):(e=n.textListChildrenByCode[t],void 0!==e?(e.stateValues.unordered&&(a=!0),e.stateValues.texts.map((e=>e.trim().replace(/\s+/," ")))):t.trim())}return"number"==typeof t?t.toString():r&&Array.isArray(t)&&"*"===t[0]?t.slice(1).map(l).join(" "):(console.warn("Invalid format for boolean condition"),e=!0,"")};if(o=o.map((e=>l(e,!0))),e)return r;let u=n.unorderedCompare;if(t&&a&&(u=!0),"="===i){let e=o[0];if(n.matchPartial){let t=o.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return o.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}).fraction_equal))?1:0}if("ne"===i){if(2!==o.length)return console.warn("Invalid format for boolean condition"),0;return 0===checkEquality({object1:o[0],object2:o[1],isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}).fraction_equal?1:0}return console.warn("Invalid format for boolean condition"),r}if(c){if(s)return console.warn("Invalid format for boolean condition"),r;let e=!1;return o=o.map((function(t){if("string"==typeof t){let e=n.otherChildrenByCode[t];if(void 0!==e)return e.stateValues.value}return console.warn("Invalid format for boolean condition"),e=!0,null})),e?r:"="===i?o.slice(1).every((e=>deepCompare(e,o[0])))?1:0:"ne"===i?2!==o.length?(console.warn("Invalid format for boolean condition"),0):deepCompare(o[0],o[1])?0:1:(console.warn("Invalid format for boolean condition"),0)}"lts"!==i&&"gts"!==i||(p=o[1].slice(1),o=o[0].slice(1));let m=!1,f=function(e){if("string"==typeof e){let t=n.mathChildrenByCode[e];return void 0!==t?(t.stateValues.unordered&&(m=!0),t.stateValues.value.tree):(t=n.mathListChildrenByCode[e],void 0!==t?(t.stateValues.unordered&&(m=!0),["list",...t.stateValues.maths.map((e=>e.tree))]):(t=n.numberChildrenByCode[e],void 0!==t?numberToMathExpression(t.stateValues.value).tree:(t=n.numberListChildrenByCode[e],void 0!==t?(t.stateValues.unordered&&(m=!0),["list",...t.stateValues.numbers]):e)))}return Array.isArray(e)?[e[0],...e.slice(1).map(f)]:e},h=o.map((function(e){return me$3.fromAst(f(e))})),y=n.unorderedCompare;if(t&&m&&(y=!0),"="===i){let e=h[0];if(Number.isNaN(e.tree))return h.slice(1).every((e=>Number.isNaN(e.tree)))?1:0;if(n.matchPartial){let t=h.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return h.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal))?1:0}if("ne"===i){return 0===checkEquality({object1:h[0],object2:h[1],isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal?1:0}if("in"===i||"notin"===i){let e=h[0],t=h[1].tree;if(!Array.isArray(t)||"set"!==t[0])return console.warn("Invalid format for boolean condition"),r;if(n.matchPartial){let r=t.slice(1).map((t=>checkEquality({object1:e,object2:me$3.fromAst(t),isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}))),a=r.reduce(((e,t)=>Math.max(e,t.fraction_equal)),0);return"in"===i?a:1-a}{let r=t.slice(1).some((t=>1===checkEquality({object1:e,object2:me$3.fromAst(t),isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal));return"in"===i?r?1:0:r?0:1}}let b=h.map((e=>e.simplify().evaluate_to_constant()));if(b.some((e=>null===e||Number.isNaN(e))))return 0;if("<"===i)return b[0]"===i)return b[0]>b[1]?1:0;if("le"===i)return b[0]<=b[1]?1:0;if("ge"===i)return b[0]>=b[1]?1:0;for(let e=0;eb[e+1]))return 0}else if(!(b[e]>=b[e+1]))return 0;return 1}function splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n=!1,init:r=!0}){if(!Array.isArray(e))return"string"!=typeof e||n||r?e:fromTextSplit(e).tree;let a=e[0],i=e.slice(1);return["and","not","or"].includes(a)?"apply"===a?[a,i[0],...i.slice(1).map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:r})))]:[a,...i.map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:r})))]:(i.some((e=>t.includes(e)))&&(n=!0),"apply"===a?[a,i[0],...i.slice(1).map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:!1})))]:[a,...i.map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:!1})))])}class BooleanComponent extends InlineComponent{static componentType="boolean";static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!0;static descendantCompositesDefaultReplacementType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.symbolicEquality={createComponentOfType:"boolean",createStateVariable:"symbolicEquality",defaultValue:!1,public:!0},e.expandOnCompare={createComponentOfType:"boolean",createStateVariable:"expandOnCompare",defaultValue:!1,public:!0},e.simplifyOnCompare={createComponentOfType:"text",createStateVariable:"simplifyOnCompare",defaultValue:"none",toLowerCase:!0,valueTransformations:{"":"full",true:"full"},validValues:["none","full","numbers","numbersepreserveorder"],public:!0},e.unorderedCompare={createComponentOfType:"boolean",createStateVariable:"unorderedCompare",defaultValue:!1,public:!0},e.matchByExactPositions={createComponentOfType:"boolean",createStateVariable:"matchByExactPositions",defaultValue:!1,public:!0},e.allowedErrorInNumbers={createComponentOfType:"number",createStateVariable:"allowedErrorInNumbers",defaultValue:0,public:!0},e.includeErrorInNumberExponents={createComponentOfType:"boolean",createStateVariable:"includeErrorInNumberExponents",defaultValue:!1,public:!0},e.allowedErrorIsAbsolute={createComponentOfType:"boolean",createStateVariable:"allowedErrorIsAbsolute",defaultValue:!1,public:!0},e.nSignErrorsMatched={createComponentOfType:"number",createStateVariable:"nSignErrorsMatched",defaultValue:0,public:!0},e.nPeriodicSetMatchesRequired={createComponentOfType:"integer",createStateVariable:"nPeriodicSetMatchesRequired",defaultValue:3,public:!0},e.caseInsensitiveMatch={createComponentOfType:"boolean",createStateVariable:"caseInsensitiveMatch",defaultValue:!1,public:!0},e.matchBlanks={createComponentOfType:"boolean",createStateVariable:"matchBlanks",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"comparableTypes",componentTypes:["math","mathList","number","numberList","text","textList","boolean","booleanList","orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.parsedExpression={additionalStateVariablesDefined:["codePre"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]}}),definition:buildParsedExpression},e.mathChildrenByCode={additionalStateVariablesDefined:["mathListChildrenByCode","numberChildrenByCode","numberListChildrenByCode","textChildrenByCode","textListChildrenByCode","booleanChildrenByCode","booleanListChildrenByCode","otherChildrenByCode"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"],variableNames:["value","texts","maths","numbers","booleans","fractionSatisfied","unordered"],variablesOptional:!0},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n={},r={},a={},i={},o={},s={},l={},u={},c={},p=0,d=e.codePre;for(let m of e.allChildren)if("string"!=typeof m){let e=d+p;t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"math"})?n[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"mathList"})?r[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"number"})?a[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"numberList"})?i[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"text"})?o[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"textList"})?s[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"boolean"})?l[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"booleanList"})?u[e]=m:c[e]=m,p+=1}return{setValue:{mathChildrenByCode:n,mathListChildrenByCode:r,numberChildrenByCode:a,numberListChildrenByCode:i,textChildrenByCode:o,textListChildrenByCode:s,booleanChildrenByCode:l,booleanListChildrenByCode:u,otherChildrenByCode:c}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean",attributesToShadow:["fixed"]},forRenderer:!0,hasEssential:!0,defaultValue:!1,set:Boolean,returnDependencies:()=>({symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"],variableNames:["value"],variablesOptional:!0},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},booleanListChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanListChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},textListChildrenByCode:{dependencyType:"stateVariable",variableName:"textListChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},mathListChildrenByCode:{dependencyType:"stateVariable",variableName:"mathListChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},numberListChildrenByCode:{dependencyType:"stateVariable",variableName:"numberListChildrenByCode"},otherChildrenByCode:{dependencyType:"stateVariable",variableName:"otherChildrenByCode"}}),definition({dependencyValues:e,usedDefault:t}){if(0===e.allChildren.length)return{useEssentialOrDefaultValue:{value:!0}};if(null===e.parsedExpression)return{setValue:{value:!1}};let n=t.unorderedCompare;return{setValue:{value:1===evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:n,dependencyValues:e})}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentInfoObjects:n}){if(0===t.allChildren.length)return{success:!0,instructions:[{setEssentialValue:"value",value:Boolean(e.value)}]};if(1===t.allChildren.length){let r=t.allChildren[0];if("string"==typeof r)return{success:!0,instructions:[{setDependency:"allChildren",desiredValue:e.value.toString(),childIndex:0,variableIndex:0}]};if(n.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"boolean"}))return{success:!0,instructions:[{setDependency:"allChildren",desiredValue:e.value,childIndex:0,variableIndex:0}]}}return{success:!1}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value?"true":"false"}}},inverseDefinition({desiredStateVariableValues:e}){let t,n=String(e.text).toLowerCase();return"true"===n?t=!0:"false"===n&&(t=!1),void 0!==t?{success:!0,instructions:[{setDependency:"value",desiredValue:t}]}:{success:!1}}},e}static adapters=["text"]}class BooleanOperator extends BooleanComponent{static componentType="_booleanOperator";static rendererType="boolean";static descendantCompositesMustHaveAReplacement=!1;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:"boolean",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"booleans",componentTypes:["boolean"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();delete e.parsedExpression,delete e.mathChildrenByCode;let t=this;return e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({booleanChildren:{dependencyType:"child",childGroups:["booleans"],variableNames:["value"]}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyBooleanOperator(e.booleanChildren.map((e=>e.stateValues.value)))}}}},e}}class BooleanOperatorOneInput extends BooleanComponent{static componentType="_booleanOperatorOneInput";static rendererType="boolean";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePreOperator"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"valuePreOperator"}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyBooleanOperator(e.value)}}}},e}}class Not extends BooleanOperatorOneInput{static componentType="not";static applyBooleanOperator(e){return!e}}class And extends BooleanOperator{static componentType="and";static applyBooleanOperator(e){return e.every((e=>e))}}class Or$1 extends BooleanOperator{static componentType="or";static applyBooleanOperator(e){return e.some((e=>e))}}class Xor extends BooleanOperator{static componentType="xor";static applyBooleanOperator(e){return 1===e.reduce(((e,t)=>e+t),0)}}var BooleanOperators=Object.freeze({__proto__:null,Not:Not,And:And,Or:Or$1,Xor:Xor});class BooleanBaseOperatorOfMath extends BooleanComponent{static componentType="_booleanOperatorOfMath";static rendererType="boolean";static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){return e.every((e=>"string"==typeof e||e.doenetAttributes&&e.doenetAttributes.createdFromMacro))?1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}:{success:!1}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.parsedExpression,delete e.mathChildrenByCode,e.booleanOperator={returnDependencies:()=>({}),definition:()=>({setValue:{booleanOperator:e=>!1}})},e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},booleanOperator:{dependencyType:"stateVariable",variableName:"booleanOperator"}}),definition:function({dependencyValues:e}){return{setValue:{value:e.booleanOperator(e.mathChildren.map((e=>e.stateValues.value)))}}}},e}}class IsInteger extends BooleanBaseOperatorOfMath{static componentType="isInteger";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator.definition=()=>({setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsInteger requires exactly one math child"),null;let t=e[0].evaluate_to_constant();if(!Number.isFinite(t))return!1;let n=Math.round(t);return Math.abs(n-t)<=1e-15*Math.abs(t)}}}),e}}class IsNumber extends BooleanBaseOperatorOfMath{static componentType="isNumber";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator.definition=()=>({setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsNumber requires exactly one math child"),null;let t=e[0].evaluate_to_constant();return Number.isFinite(t)}}}),e}}class IsBetween extends BooleanBaseOperatorOfMath{static componentType="isBetween";static createAttributesObject(){let e=super.createAttributesObject();return e.limits={createComponentOfType:"numberList",createStateVariable:"limits",defaultValue:[],public:!0},e.strict={createComponentOfType:"boolean",createStateVariable:"strict",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator={returnDependencies:()=>({limits:{dependencyType:"stateVariable",variableName:"limits"},strict:{dependencyType:"stateVariable",variableName:"strict"}}),definition({dependencyValues:e}){let t,n,r=e.limits[0],a=e.limits[1];if(r!1}};n=a,t=r}let i=e.strict;return{setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsBetween requires exactly one math child"),null;let r=e[0].evaluate_to_constant();return i?r>n&&r=n&&r<=t}}}}},e}}var BooleanOperatorsOfMath=Object.freeze({__proto__:null,IsInteger:IsInteger,IsNumber:IsNumber,IsBetween:IsBetween});class MathOperator extends MathComponent{static componentType="_mathOperator";static rendererType="math";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.forceSymbolic={createComponentOfType:"boolean",createStateVariable:"forceSymbolic",defaultValue:!1,public:!0},e.forceNumeric={createComponentOfType:"boolean",createStateVariable:"forceNumeric",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:Number.isFinite(Number(e))?"number":"math",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"numbers",componentTypes:["number"]},{group:"mathLists",componentTypes:["mathList"]},{group:"numberLists",componentTypes:["numberList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displayDigits"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDigitsAttr?{setValue:{displayDigits:e.displayDigitsAttr.stateValues.value}}:null!==e.displayDecimalsAttr||1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displayDigits?{useEssentialOrDefaultValue:{displayDigits:!0}}:{setValue:{displayDigits:e.mathLikeChildren[0].stateValues.displayDigits}}},e.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:null,returnDependencies:()=>({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displayDecimals?{useEssentialOrDefaultValue:{displayDecimals:!0}}:{setValue:{displayDecimals:e.mathLikeChildren[0].stateValues.displayDecimals}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displaySmallAsZero?{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}:{setValue:{displaySmallAsZero:e.mathLikeChildren[0].stateValues.displaySmallAsZero}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].padZeros?{useEssentialOrDefaultValue:{padZeros:!0}}:{setValue:{padZeros:e.mathLikeChildren[0].stateValues.padZeros}}},e.isNumericOperator={returnDependencies:()=>({forceNumeric:{dependencyType:"stateVariable",variableName:"forceNumeric"},forceSymbolic:{dependencyType:"stateVariable",variableName:"forceSymbolic"},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["isNumber"],variablesOptional:!0},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],variableNames:["maths"]}}),definition({dependencyValues:e}){let t;return t=!!e.forceNumeric||!e.forceSymbolic&&(0===e.mathChildren.length&&0===e.mathListChildren.length||e.mathChildren.every((e=>e.stateValues.isNumber))&&e.mathListChildren.every((e=>e.stateValues.maths.every((e=>Number.isFinite(e.tree)))))),{setValue:{isNumericOperator:t}}}},delete e.codePre,delete e.expressionWithCodes,delete e.mathChildrenFunctionSymbols,delete e.codesAdjacentToStrings,delete e.mathChildrenByVectorComponent,e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:e=>me$3.fromAst("_")}})},e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:e=>me$3.fromAst("_")}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:null}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:null}})},e.unnormalizedValue={returnDependencies:()=>({mathNumberChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["value","maths","numbers","canBeModified"],variablesOptional:!0},isNumericOperator:{dependencyType:"stateVariable",variableName:"isNumericOperator"},mathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},numericOperator:{dependencyType:"stateVariable",variableName:"numericOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"inverseMathOperator"},inverseNumericOperator:{dependencyType:"stateVariable",variableName:"inverseNumericOperator"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){if(0===e.mathNumberChildren.length)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};if(e.isNumericOperator){let n=[];for(let r of e.mathNumberChildren)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"}))n.push(r.stateValues.value);else if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"math"})){let e=r.stateValues.value.evaluate_to_constant();Number.isFinite(e)||(e=NaN),n.push(e)}else if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"}))n.push(...r.stateValues.numbers);else{let e=r.stateValues.maths.map((e=>{let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}));n.push(...e)}return{setValue:{unnormalizedValue:me$3.fromAst(e.numericOperator(n))}}}{let n=[];for(let r of e.mathNumberChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"})?n.push(me$3.fromAst(r.stateValues.value)):t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"math"})?n.push(r.stateValues.value):t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"})?n.push(...r.stateValues.numbers.map((e=>me$3.fromAst(e)))):n.push(...r.stateValues.maths);return{setValue:{unnormalizedValue:e.mathOperator(n)}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentInfoObjects:n}){if(0===t.mathNumberChildren.length)return{success:!1};if(t.isNumericOperator){if(t.inverseNumericOperator){let r=[],a=[],i=[];for(let[e,o]of t.mathNumberChildren.entries())if(n.isInheritedComponentType({inheritedComponentType:o.componentType,baseComponentType:"number"}))r.push(o.stateValues.value),a.push(o.stateValues.canBeModified),i.push(e);else if(n.isInheritedComponentType({inheritedComponentType:o.componentType,baseComponentType:"math"})){let t=o.stateValues.value.evaluate_to_constant();Number.isFinite(t)||(t=NaN),r.push(t),a.push(o.stateValues.canBeModified),i.push(e)}else if(n.isInheritedComponentType({inheritedComponentType:o.componentType,baseComponentType:"numberList"}))r.push(...o.stateValues.numbers),a.push(...Array(o.stateValues.numbers.length).fill(o.stateValues.canBeModified)),1===o.stateValues.numbers.length?i.push(e):i.push(...Array(o.stateValues.numbers.length).fill(NaN));else{let t=o.stateValues.maths.map((e=>{let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}));r.push(...t),a.push(...Array(o.stateValues.maths.length).fill(o.stateValues.canBeModified)),1===o.stateValues.maths.length?i.push(e):i.push(...Array(o.stateValues.maths.length).fill(NaN))}let o=t.inverseNumericOperator({desiredValue:e.unnormalizedValue.evaluate_to_constant(),inputs:r,canBeModified:a,desiredMathValue:e.unnormalizedValue});if(o.success){let e=i[o.inputNumber];if(Number.isFinite(e)){let r=o.inputValue,a=0,i=t.mathNumberChildren[e];return n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"numberList"})?(a=2,r={0:r}):n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})&&(a=1,r={0:r}),{success:!0,instructions:[{setDependency:"mathNumberChildren",desiredValue:r,childIndex:e,variableIndex:a}]}}return{success:!1}}return{success:!1}}return{success:!1}}if(t.inverseMathOperator){let r=[],a=[],i=[];for(let[e,o]of t.mathNumberChildren.entries())n.isInheritedComponentType({inheritedComponentType:o.componentType,baseComponentType:"number"})?(r.push(me$3.fromAst(o.stateValues.value)),a.push(o.stateValues.canBeModified),i.push(e)):n.isInheritedComponentType({inheritedComponentType:o.componentType,baseComponentType:"math"})?(r.push(o.stateValues.value),a.push(o.stateValues.canBeModified),i.push(e)):n.isInheritedComponentType({inheritedComponentType:o.componentType,baseComponentType:"numberList"})?(r.push(...o.stateValues.numbers.map((e=>me$3.fromAst(e)))),a.push(...Array(o.stateValues.numbers.length).fill(o.stateValues.canBeModified)),1===o.stateValues.numbers.length?i.push(e):i.push(...Array(o.stateValues.numbers.length).fill(NaN))):(r.push(...o.stateValues.maths),a.push(...Array(o.stateValues.maths.length).fill(o.stateValues.canBeModified)),1===o.stateValues.maths.length?i.push(e):i.push(...Array(o.stateValues.maths.length).fill(NaN)));let o=t.inverseMathOperator({desiredValue:e.unnormalizedValue,inputs:r,canBeModified:a});if(o.success){let e=i[o.inputNumber];if(Number.isFinite(e)){let r=o.inputValue,a=0,i=t.mathNumberChildren[e];return n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"numberList"})?(a=2,r={0:r}):n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})&&(a=1,r={0:r}),{success:!0,instructions:[{setDependency:"mathNumberChildren",desiredValue:r,childIndex:e,variableIndex:a}]}}return{success:!1}}return{success:!1}}return{success:!1}}},e.canBeModified={returnDependencies:()=>({modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},mathNumberChildren:{dependencyType:"child",childGroups:["maths","numbers"],variableNames:["canBeModified"]},mathNumberListChildren:{dependencyType:"child",childGroups:["mathLists","numberLists"],variableNames:["nComponents"]},isNumericOperator:{dependencyType:"stateVariable",variableName:"isNumericOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},inverseNumericOperator:{dependencyType:"stateVariable",variableName:"inverseNumericOperator"}}),definition:function({dependencyValues:e}){let t=e.modifyIndirectly&&!e.fixed&&Boolean(e.isNumericOperator?e.inverseNumericOperator:e.inverseMathOperator);if(t&&e.mathNumberChildren.length+e.mathNumberListChildren.length>0){let n=e.mathNumberChildren.filter((e=>e.stateValues.canBeModified)).length+e.mathNumberListChildren.reduce(((e,t)=>e+t.stateValues.nComponents),0);1!==n&&(t=!1)}return{setValue:{canBeModified:t}}}},e}}class MathOperatorOneInput extends MathComponent{static componentType="_mathOperatorOneInput";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:e=>me.fromAst("_")}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:null}})},renameStateVariable({stateVariableDefinitions:e,oldName:"unnormalizedValue",newName:"unnormalizedValuePreOperator"}),e.unnormalizedValue={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"unnormalizedValuePreOperator"},mathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"inverseMathOperator"}}),definition:function({dependencyValues:e}){return{setValue:{unnormalizedValue:e.mathOperator(e.value)}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentName:n}){if(t.inverseMathOperator){return{success:!0,instructions:[{setDependency:"value",desiredValue:t.inverseMathOperator(e.unnormalizedValue)}]}}return{success:!1}}},renameStateVariable({stateVariableDefinitions:e,oldName:"canBeModified",newName:"canBeModifiedPreOperator"}),e.canBeModified={returnDependencies:()=>({canBeModifiedPreOperator:{dependencyType:"stateVariable",variableName:"canBeModifiedPreOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"}}),definition:function({dependencyValues:e}){let t=e.canBeModifiedPreOperator;return e.inverseMathOperator||(t=!1),{setValue:{canBeModified:t}}}},e}}class Sum extends MathOperator{static componentType="sum";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>e+t))}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.add(t)))}}})},e}}class Product extends MathOperator{static componentType="product";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>e*t))}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.multiply(t)))}}})},e}}class ClampNumber extends MathOperatorOneInput{static componentType="clampNumber";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.mathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return clamp({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e.inverseMathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{inverseMathOperator:function(t){return clamp({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e}}function clamp({value:e,lowerValue:t,upperValue:n}){let r=e;return r instanceof me$3.class&&(r=r.evaluate_to_constant()),Number.isFinite(r)?me$3.fromAst(Math.max(t,Math.min(n,r))):me$3.fromAst(NaN)}class WrapNumberPeriodic extends MathOperatorOneInput{static componentType="wrapNumberPeriodic";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.mathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return makePeriodic({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e.inverseMathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{inverseMathOperator:function(t){return makePeriodic({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e}}function makePeriodic({value:e,lowerValue:t,upperValue:n}){let r=e;return r instanceof me$3.class&&(r=r.evaluate_to_constant()),Number.isFinite(r)?t===n?me$3.fromAst(t):(t>n&&([n,t]=[t,n]),me$3.fromAst(t+me$3.math.mod(r-t,n-t))):me$3.fromAst(NaN)}class Round extends MathOperatorOneInput{static componentType="round";static createAttributesObject(){let e=super.createAttributesObject();return e.numberDecimals={createComponentOfType:"number",createStateVariable:"numberDecimals",defaultValue:0,public:!0},e.numberDigits={createComponentOfType:"number",createStateVariable:"numberDigits",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({numberDecimals:{dependencyType:"stateVariable",variableName:"numberDecimals"},numberDigits:{dependencyType:"stateVariable",variableName:"numberDigits"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){let n=t.evaluate_numbers({max_digits:1/0,evaluate_functions:!0});return null!==e.numberDigits?n.round_numbers_to_precision(e.numberDigits):n.round_numbers_to_decimals(e.numberDecimals)}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class setSmallToZero extends MathOperatorOneInput{static componentType="setSmallToZero";static createAttributesObject(){let e=super.createAttributesObject();return e.threshold={createComponentOfType:"number",createStateVariable:"threshold",defaultValue:1e-14,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({threshold:{dependencyType:"stateVariable",variableName:"threshold"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return t.evaluate_numbers({skip_ordering:!0,set_small_zero:e.threshold})}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class ConvertSetToList extends MathOperatorOneInput{static componentType="convertSetToList";static createAttributesObject(){let e=super.createAttributesObject();return delete e.unordered,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.unordered={returnDependencies:()=>({}),definition:()=>({setValue:{unordered:!0}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){if(void 0!==e&&Array.isArray(e.tree)&&"set"===e.tree[0]){let t=[];for(let n of e.tree.slice(1))t.some((t=>e.context.equalsViaSyntax(e.context.fromAst(t),e.context.fromAst(n))))||t.push(n);return e.context.fromAst(["list",...t])}return e}}})},e}}class Ceil extends MathOperatorOneInput{static componentType="ceil";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();if(!Number.isFinite(t))return me$3.fromAst(["apply","ceil",e.tree]);let n=Math.round(t);return Math.abs((n-t)/t)<1e-15?me$3.fromAst(n):me$3.fromAst(Math.ceil(t))}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class Floor extends MathOperatorOneInput{static componentType="floor";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();if(!Number.isFinite(t))return me$3.fromAst(["apply","floor",e.tree]);let n=Math.round(t);return Math.abs((n-t)/t)<1e-15?me$3.fromAst(n):me$3.fromAst(Math.floor(t))}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class Abs extends MathOperatorOneInput{static componentType="abs";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();return Number.isFinite(t)?me$3.fromAst(Math.abs(t)):me$3.fromAst(["apply","abs",e.tree])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function(e){let t=e,n=e.evaluate_to_constant();return Number.isFinite(n)?n<0&&(t=me$3.fromAst(0)):Array.isArray(e.tree)&&"apply"===e.tree[0]&&"abs"===e.tree[1]&&(t=me$3.fromAst(e.tree[2])),t}}})},e}}class Sign extends MathOperatorOneInput{static componentType="sign";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();return Number.isFinite(t)?me$3.fromAst(Math.sign(t)):me$3.fromAst(["apply","sign",e.tree])}}})},e}}class Mean extends MathOperator{static componentType="mean";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){let t=e.reduce(((e,t)=>e+t));return t/=e.length,t}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.add(t))).divide(e.length)}}})},e}}class Variance extends MathOperator{static componentType="variance";static createAttributesObject(){let e=super.createAttributesObject();return e.population={createComponentOfType:"boolean",createStateVariable:"population",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({population:{dependencyType:"stateVariable",variableName:"population"}}),definition:({dependencyValues:e})=>({setValue:{numericOperator:function(t){return calculateNumericVariance(t,e.population)}}})},e.mathOperator={returnDependencies:()=>({population:{dependencyType:"stateVariable",variableName:"population"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return calculateSymbolicVariance(t,e.population)}}})},e}}function calculateNumericVariance(e,t){let n=0,r=0;for(let t of e)n+=t,r+=t*t;let a=e.length;return r-=n**2/a,r/=t?a:a-1,r}function calculateSymbolicVariance(e,t){let n=e.length,r=e.reduce(((e,t)=>e.add(t))),a=e.slice(1).reduce(((e,t)=>e.add(t.pow(2))),e[0].pow(2)).subtract(r.pow(2).divide(n));return a=t?a.divide(n):a.divide(n-1),a}class StandardDeviation extends Variance{static componentType="standardDeviation";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator.definition=({dependencyValues:e})=>({setValue:{numericOperator:function(t){return Math.sqrt(calculateNumericVariance(t,e.population))}}}),e.mathOperator.definition=({dependencyValues:e})=>({setValue:{mathOperator:function(t){return me$3.fromAst(["apply","sqrt",calculateSymbolicVariance(t,e.population).tree])}}}),e}}class Count extends MathOperator{static componentType="count";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.length}}})},e}}class Min extends MathOperator{static componentType="min";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>Math.min(e,t)),1/0)}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","min",["tuple",...e.map((e=>e.tree))]])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function({desiredValue:e,canBeModified:t}){if(1===t.filter((e=>e)).length){let n=t.indexOf(!0);if(n>=0)return{success:!0,inputValue:e,inputNumber:n}}return{success:!1}}}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:function({desiredValue:e,canBeModified:t,desiredMathValue:n}){if(1===t.filter((e=>e)).length){let r=t.indexOf(!0);if(r>=0)return Number.isFinite(e)||(e=n),{success:!0,inputValue:e,inputNumber:r}}return{success:!1}}}})},e}}class Max extends MathOperator{static componentType="max";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>Math.max(e,t)),-1/0)}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","max",["tuple",...e.map((e=>e.tree))]])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function({desiredValue:e,canBeModified:t}){if(1===t.filter((e=>e)).length){let n=t.indexOf(!0);if(n>=0)return{success:!0,inputValue:e,inputNumber:n}}return{success:!1}}}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:function({desiredValue:e,canBeModified:t,desiredMathValue:n}){if(1===t.filter((e=>e)).length){let r=t.indexOf(!0);if(r>=0)return Number.isFinite(e)||(e=n),{success:!0,inputValue:e,inputNumber:r}}return{success:!1}}}})},e}}class Mod extends MathOperator{static componentType="mod";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return 2!==e.length?NaN:me$3.math.mod(e[0],e[1])}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return 2!==e.length?me$3.fromAst("_"):me$3.fromAst(["apply","mod",["tuple",...e.map((e=>e.tree))]])}}})},e}}class Gcd extends MathOperator{static componentType="gcd";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.every(Number.isInteger)?gcd(...e):NaN}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","gcd",["tuple",...e.map((e=>e.tree))]])}}})},e}}class ExtractMath extends MathOperatorOneInput{static componentType="extractMath";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createComponentOfType:"text",createStateVariable:"type",defaultValue:null,toLowerCase:!0,validValues:["operand","function","functionargument","numberofoperands"]},e.operandNumber={createComponentOfType:"number",createStateVariable:"operandNumber",defaultValue:null,public:!0},e.argumentNumber={createComponentOfType:"number",createStateVariable:"argumentNumber",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},operandNumber:{dependencyType:"stateVariable",variableName:"operandNumber"},argumentNumber:{dependencyType:"stateVariable",variableName:"argumentNumber"}}),definition:({dependencyValues:e})=>"operand"===e.type?null===e.operandNumber?(console.warn("Must specify a operandNumber when extracting a math operand"),{setValue:{mathOperator:e=>me$3.fromAst("_")}}):{setValue:{mathOperator:function(t){let n=t.tree;if(!Array.isArray(n))return 1===e.operandNumber?t:me$3.fromAst("_");if("apply"===n[0])return 1===e.operandNumber?t:me$3.fromAst("_");let r=n[e.operandNumber];return void 0===r?me$3.fromAst("_"):me$3.fromAst(r)}}}:"function"===e.type?{setValue:{mathOperator:function(e){let t=e.tree;return Array.isArray(t)?"apply"!==t[0]?me$3.fromAst("_"):me$3.fromAst(t[1]):me$3.fromAst("_")}}}:"functionargument"===e.type?{setValue:{mathOperator:function(t){let n=t.tree;if(!Array.isArray(n))return me$3.fromAst("_");if("apply"!==n[0])return me$3.fromAst("_");let r=n[2];if(null===e.argumentNumber)return me$3.fromAst(r);if(1===e.argumentNumber)return Array.isArray(r)&&"tuple"===r[0]?me$3.fromAst(r[1]):me$3.fromAst(r);if(Array.isArray(r)&&"tuple"===r[0]){let t=r[e.argumentNumber];return void 0===t?me$3.fromAst("_"):me$3.fromAst(t)}return me$3.fromAst("_")}}}:"numberofoperands"===e.type?{setValue:{mathOperator:function(e){let t=e.tree;return Array.isArray(t)?"apply"===t[0]?me$3.fromAst(1):me$3.fromAst(t.length-1):me$3.fromAst(1)}}}:{setValue:{mathOperator:e=>me$3.fromAst("_")}}},e}}function gcd(e,t,...n){return!t&&n.length>0?gcd(e,...n):t?gcd(t,e%t,...n):e}var MathOperators=Object.freeze({__proto__:null,Sum:Sum,Product:Product,ClampNumber:ClampNumber,WrapNumberPeriodic:WrapNumberPeriodic,Round:Round,setSmallToZero:setSmallToZero,ConvertSetToList:ConvertSetToList,Ceil:Ceil,Floor:Floor,Abs:Abs,Sign:Sign,Mean:Mean,Variance:Variance,StandardDeviation:StandardDeviation,Count:Count,Min:Min,Max:Max,Mod:Mod,Gcd:Gcd,ExtractMath:ExtractMath});function returnLabelStateVariableDefinitions(){let e={};return e.componentNameAndShadowSourceNames={returnDependencies:()=>({shadowSource:{dependencyType:"shadowSource",variableNames:["componentNameAndShadowSourceNames"]},unlinkedCopySource:{dependencyType:"unlinkedCopySource",variableNames:["componentNameAndShadowSourceNames"]}}),definition({dependencyValues:e,componentName:t}){let n=[t];return e.shadowSource?.stateValues.componentNameAndShadowSourceNames?n.push(...e.shadowSource.stateValues.componentNameAndShadowSourceNames):e.unlinkedCopySource?.stateValues.componentNameAndShadowSourceNames&&n.push(...e.unlinkedCopySource.stateValues.componentNameAndShadowSourceNames),{setValue:{componentNameAndShadowSourceNames:n}}}},e.label={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"labelHasLatex"}}},hasEssential:!0,doNotShadowEssential:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,additionalStateVariablesDefined:[{variableName:"labelHasLatex",forRenderer:!0}],returnDependencies:()=>({labelChild:{dependencyType:"child",childGroups:["labels"],variableNames:["value","hasLatex"]},labelIsName:{dependencyType:"stateVariable",variableName:"labelIsName"},labelIsNameAttr:{dependencyType:"attributeComponent",attributeName:"labelIsName"},componentNameAndShadowSourceNames:{dependencyType:"stateVariable",variableName:"componentNameAndShadowSourceNames"},shadowSource:{dependencyType:"shadowSource",variableNames:["label","labelHasLatex"]}}),definition({dependencyValues:e,essentialValues:t}){let n=e.labelChild[e.labelChild.length-1];if(n&&!n.shadowDepth)return{setValue:{label:n.stateValues.value,labelHasLatex:n.stateValues.hasLatex}};if(void 0!==t.label)return{useEssentialOrDefaultValue:{label:!0},setValue:{labelHasLatex:!1}};if(e.labelIsName&&!e.labelIsNameAttr.shadowDepth){let t="__",n=e.componentNameAndShadowSourceNames;for(let e of n){let n=e.lastIndexOf("/");if(t=e.substring(n+1),"__"!==t.slice(0,2))break}return"__"===t.slice(0,2)?{setValue:{label:"",labelHasLatex:!1}}:("_"!==t[0]&&(t.includes("_")||t.includes("-")?t=t.replace(/[_\-]/g," "):t.match(/^[a-z]/)?t.match(/[A-Z]/)&&(t=t.replace(/([A-Z])/g," $1").toLowerCase()):t.match(/^[A-Z]/)&&t.match(/[a-z]/)&&(t=t.replace(/([A-Z])/g," $1"),t=t.slice(1))),{setValue:{label:t,labelHasLatex:!1}})}return"string"==typeof e.shadowSource?.stateValues.label?{setValue:{label:e.shadowSource.stateValues.label,labelHasLatex:Boolean(e.shadowSource.stateValues.labelHasLatex)}}:{useEssentialOrDefaultValue:{label:!0},setValue:{labelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.label)return{success:!1};let n=t.labelChild.length-1,r=t.labelChild[n];return r&&!r.shadowDepth?{success:!0,instructions:[{setDependency:"labelChild",desiredValue:e.label,childIndex:n,variableIndex:0}]}:t.labelIsName&&!t.labelIsNameAttr.shadowDepth?{success:!0,instructions:[{setEssentialValue:"label",value:e.label}]}:"string"==typeof t.shadowSource?.stateValues.label?{success:!0,instructions:[{setDependency:"shadowSource",desiredValue:e.label,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"label",value:e.label}]}}},e.labelForGraph={forRenderer:!0,returnDependencies:()=>({label:{dependencyType:"stateVariable",variableName:"label"},labelHasLatex:{dependencyType:"stateVariable",variableName:"labelHasLatex"}}),definition({dependencyValues:e}){let t;if(e.labelHasLatex){let n=0;t="";for(let r of e.label)"("===r?n++:")"===r?n--:0===n&&("_"===r?r="_":"^"===r&&(r="^")),t+=r}else t=e.label.replaceAll("_","_").replaceAll("^","^");return{setValue:{labelForGraph:t}}}},e}class GraphicalComponent extends BaseComponent{static componentType="_graphical";static createAttributesObject(){let e=super.createAttributesObject();return e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showLabel={createComponentOfType:"boolean",createStateVariable:"showLabel",defaultValue:!0,public:!0,forRenderer:!0},e.applyStyleToLabel={createComponentOfType:"boolean",createStateVariable:"applyStyleToLabel",defaultValue:!1,public:!0,forRenderer:!0},e.layer={createComponentOfType:"integer",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();Object.assign(e,t);let n=returnLabelStateVariableDefinitions();return Object.assign(e,n),e}}function returnNumericalFunctionFromFormula({formula:e,nInputs:t,variables:n,domain:r,component:a=0}){let i;if(a=Number(a),Array.isArray(e.tree)&&["tuple","vector"].includes(e.tree[0]))try{e=e.get_component(Number(a))}catch(e){return()=>NaN}else if(0!==a)return()=>NaN;try{i=e.subscripts_to_strings().f()}catch(e){return()=>NaN}if(1===t){let e=n[0].subscripts_to_strings().tree,t=-1/0,a=1/0,o=!1,s=!1;if(null!==r){let e=r[0];if(void 0!==e)try{t=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(t)?o=!e.tree[2][1]:t=-1/0,a=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(a)?s=!e.tree[2][2]:a=1/0}catch(e){}}return function(n,r=!1){if(r){if(isNaN(n))return NaN}else if(!(n>=t)||!(n<=a)||o&&n===t||s&&n===a)return NaN;try{return i({[e]:n})}catch(e){return NaN}}}let o=[];for(let e=0;eme$3.fromAst("_")}else if("0"!==t)return e=>me$3.fromAst("_");let r=e.simplify,a=e.expand,i=n.subscripts_to_strings();if(1===e.nInputs){let t=e.variables[0].subscripts_to_strings().tree;return e=>normalizeMathExpression({value:i.substitute({[t]:e}).strings_to_subscripts(),simplify:r,expand:a})}let o=[];for(let t=0;tNaN;return e}let s=e-1,l={};for(let e=0;e<2;e++){let u,c,p=t[0][e],d=t[s][e],m=n.map((t=>t[e]));i&&(u=o[e]),r&&(c=a[e]),l[e]=function(e){if(isNaN(e))return NaN;if(e<0)return i?(u[2]*e+u[1])*e+u[0]:p;if(e>=s)return r?(e-=s,(c[2]*e+c[1])*e+c[0]):d;let t=Math.floor(e);e-=t;let n=m[t];return((n[3]*e+n[2])*e+n[1])*e+n[0]}}return l}function returnInterpolatedFunction({xs:e,coeffs:t,interpolationPoints:n,domain:r}){let a=[];if(n&&(a=n.map((e=>e.y))),null===e)return e=>NaN;let i=-1/0,o=1/0,s=!1,l=!1;if(null!==r){let e=r[0];if(void 0!==e)try{i=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(i)?s=!e.tree[2][1]:i=-1/0,o=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(o)?l=!e.tree[2][2]:o=1/0}catch(e){}}let u=e[0],c=e[e.length-1];return function(n,r=!1){if(r){if(isNaN(n))return NaN}else if(!(n>=i)||!(n<=o)||s&&n===i||l&&n===o)return NaN;if(n<=u){n-=u;let e=t[0];return((e[3]*n+e[2])*n+e[1])*n+e[0]}if(n>=c){let r=e.length-2;n-=e[r];let a=t[r];return((a[3]*n+a[2])*n+a[1])*n+a[0]}for(var p,d=0,m=e.length-1;d<=m;){p=Math.floor(.5*(d+m));let t=e[p];if(tn))return a[p];m=p-1}}let f=Math.max(0,m);n-=e[f];let h=t[f];return((h[3]*n+h[2])*n+h[1])*n+h[0]}}function returnReturnDerivativesOfInterpolatedFunction({xs:e,coeffs:t,variables:n}){if(!e)return e=>NaN;let r=n[0].subscripts_to_strings().tree,a=e[0],i=e[e.length-1];return function(n){let o=n.map((e=>e.subscripts_to_strings().tree)),s=o.length;return s>3||!o.every((e=>e===r))||o.includes("_")?e=>0:0===s||null===e?e=>NaN:function(n){if(isNaN(n))return NaN;if(n<=a){n-=a;let e=t[0];return 1===s?(3*e[3]*n+2*e[2])*n+e[1]:2===s?6*e[3]*n+2*e[2]:6*e[3]}if(n>=i){let r=e.length-2;n-=e[r];let a=t[r];return 1===s?(3*a[3]*n+2*a[2])*n+a[1]:2===s?6*a[3]*n+2*a[2]:6*a[3]}for(var r,o=0,l=e.length-1;o<=l;){r=Math.floor(.5*(o+l));let a=e[r];if(an))return 1===s?t[r][1]:2===s?2*t[r][2]:6*t[r][3];l=r-1}}let u=Math.max(0,l);n-=e[u];let c=t[u];return 1===s?(3*c[3]*n+2*c[2])*n+c[1]:2===s?6*c[3]*n+2*c[2]:6*c[3]}}}var functionOperatorDefinitions={clampFunction:function(e,t){return function(n){return Number.isFinite(n)?Math.max(e,Math.min(t,n)):NaN}},wrapFunctionPeriodic:function(e,t){return function(n){if(!Number.isFinite(n))return NaN;let r=e,a=t;return r===a?r:(r>a&&([a,r]=[r,a]),r+me$3.math.mod(n-r,a-r))}},derivative:function(e,t){if("interpolatedFunction"===e.derivativeType){let n=returnReturnDerivativesOfInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,variables:e.variables.map(convertValueToMathExpression)}),r=t.map(convertValueToMathExpression);if(e.additionalDerivVariables){r=[...e.additionalDerivVariables.map(convertValueToMathExpression),...r]}if(e.variableMappings)for(let t of e.variableMappings){let e=[];for(let n of r){let r=t[n.subscripts_to_strings().tree];r?e.push(convertValueToMathExpression(r)):e.push(me$3.fromAst("_"))}r=e}return n(r)}return e=>NaN}};class Function$2 extends InlineComponent{static componentType="function";static rendererType="math";static primaryStateVariableForDefinition="numericalfShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.simplify={createComponentOfType:"text",createStateVariable:"simplifySpecified",defaultValue:"none",toLowerCase:!0,valueTransformations:{true:"full"},validValues:["none","full","numbers","numberspreserveorder"]},e.expand={createComponentOfType:"boolean",createStateVariable:"expandSpecified",defaultValue:!1,public:!0},e.xscale={createComponentOfType:"number",createStateVariable:"xscale",defaultValue:1,public:!0},e.yscale={createComponentOfType:"number",createStateVariable:"yscale",defaultValue:1,public:!0},e.nInputs={createComponentOfType:"integer"},e.nOutputs={createComponentOfType:"integer"},e.domain={createComponentOfType:"_intervalListComponent"},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showLabel={createComponentOfType:"boolean",createStateVariable:"showLabel",defaultValue:!0,public:!0,forRenderer:!0},e.applyStyleToLabel={createComponentOfType:"boolean",createStateVariable:"applyStyleToLabel",defaultValue:!1,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.minima={createComponentOfType:"extrema"},e.maxima={createComponentOfType:"extrema"},e.extrema={createComponentOfType:"extrema"},e.through={createComponentOfType:"_pointListComponent"},e.throughSlopes={createComponentOfType:"mathList"},e.variables={createComponentOfType:"variables"},e.symbolic={createComponentOfType:"boolean"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.nearestPointAsCurve={createComponentOfType:"boolean",createStateVariable:"nearestPointAsCurve",defaultValue:!1},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[],i=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a=e.slice(0,t),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),i=e.slice(t))}return 1===r.length&&"string"!=typeof r[0]||0===r.length?{success:!1}:{success:!0,newChildren:[...a,{componentType:"math",children:r},...i]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"functions",componentTypes:["function"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions({numerics:e}){let t=GraphicalComponent.returnStateVariableDefinitions();return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" function"}}}},t.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:10,hasEssential:!0,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displayDigits"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth0){let n=t.functionChild[0],r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;return n||r||(n=!0),n?{useEssentialOrDefaultValue:{displayDigits:{defaultValue:e.functionChild[0].stateValues.displayDigits}}}:{setValue:{displayDigits:e.functionChild[0].stateValues.displayDigits}}}return{useEssentialOrDefaultValue:{displayDigits:!0}}}},t.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:null,hasEssential:!0,returnDependencies:()=>({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{displayDecimals:e.functionChild[0].stateValues.displayDecimals}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}},t.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{displaySmallAsZero:e.functionChild[0].stateValues.displaySmallAsZero}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}},t.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{padZeros:e.functionChild[0].stateValues.padZeros}}:{useEssentialOrDefaultValue:{padZeros:!0}}},t.isInterpolatedFunction={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through"},minima:{dependencyType:"attributeComponent",attributeName:"minima"},maxima:{dependencyType:"attributeComponent",attributeName:"maxima"},extrema:{dependencyType:"attributeComponent",attributeName:"extrema"}}),definition:({dependencyValues:e})=>({setValue:{isInterpolatedFunction:e.through||e.minima||e.maxima||e.extrema}})},t.nInputs={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({nInputsAttr:{dependencyType:"attributeComponent",attributeName:"nInputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nInputs"]},variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["nComponents"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"}}),definition({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{nInputs:1}};if(null!==e.nInputsAttr){let t=e.nInputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nInputs:t}}}return null!==e.variablesAttr?{setValue:{nInputs:Math.max(1,e.variablesAttr.stateValues.nComponents)}}:e.functionChild.length>0?{setValue:{nInputs:e.functionChild[0].stateValues.nInputs}}:{setValue:{nInputs:1}}}},t.nOutputs={defaultValue:1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({nOutputsAttr:{dependencyType:"attributeComponent",attributeName:"nOutputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nOutputs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition({dependencyValues:e}){if(e.functionChild.length>0)return{setValue:{nOutputs:e.functionChild[0].stateValues.nOutputs}};if(null!==e.nOutputsAttr){let t=e.nOutputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nOutputs:t}}}if(e.mathChild.length>0){let t=e.mathChild[0].stateValues.value,n=1;return Array.isArray(t.tree)&&["tuple","vector"].includes(t.tree[0])&&(n=t.tree.length-1),{setValue:{nOutputs:n}}}return{useEssentialOrDefaultValue:{nOutputs:!0}}}},t.domain={returnDependencies:()=>({domainAttr:{dependencyType:"attributeComponent",attributeName:"domain",variableNames:["intervals"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),definition({dependencyValues:e}){if(null!==e.domainAttr){let t=e.nInputs,n=e.domainAttr.stateValues.intervals.slice(0,t);return n.length!==t?{setValue:{domain:null}}:n.every((e=>Array.isArray(e.tree)&&"interval"===e.tree[0]))?{setValue:{domain:n}}:{setValue:{domain:null}}}return e.functionChild.length>0?{setValue:{domain:e.functionChild[0].stateValues.domain}}:{setValue:{domain:null}}}},t.simplify={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({simplifySpecified:{dependencyType:"stateVariable",variableName:"simplifySpecified"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["simplify"]}}),definition:({dependencyValues:e,usedDefault:t})=>t.simplifySpecified&&e.functionChild.length>0?{setValue:{simplify:e.functionChild[0].stateValues.simplify}}:{setValue:{simplify:e.simplifySpecified}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n})=>n.simplifySpecified&&t.functionChild.length>0?{success:!0,instructions:[{setDependency:"functionChild",desiredValue:e.simplify,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setDependency:"simplifySpecified",desiredValue:e.simplify}]}},t.expand={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({expandSpecified:{dependencyType:"stateVariable",variableName:"expandSpecified"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["expand"]}}),definition:({dependencyValues:e,usedDefault:t})=>t.expandSpecified&&e.functionChild.length>0?{setValue:{expand:e.functionChild[0].stateValues.expand}}:{setValue:{expand:e.expandSpecified}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n})=>n.expandSpecified&&t.functionChild.length>0?{success:!0,instructions:[{setDependency:"functionChild",desiredValue:e.expand,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setDependency:"expandSpecified",desiredValue:e.expand}]}},t.numericalfShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{numericalfShadow:!0}})},t.symbolicfShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{symbolicfShadow:!0}})},t.symbolic={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({symbolicAttr:{dependencyType:"attributeComponent",attributeName:"symbolic",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolic"]},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"}}),definition:({dependencyValues:e})=>null!==e.symbolicAttr?{setValue:{symbolic:e.symbolicAttr.stateValues.value}}:e.functionChild.length>0?{setValue:{symbolic:e.functionChild[0].stateValues.symbolic}}:e.numericalfShadow?{setValue:{symbolic:!1}}:e.symbolicfShadow?{setValue:{symbolic:!0}}:{useEssentialOrDefaultValue:{symbolic:!0}}},t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),returnArraySize:({dependencyValues:e})=>[e.nInputs],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["variable"+(Number(n)+1)]}};return{globalDependencies:{variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]},parentVariableForChild:{dependencyType:"parentStateVariable",variableName:"variableForChild"},functionChild:{dependencyType:"child",childGroups:["functions"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arraySize:n,arrayKeys:r,usedDefault:a}){if(null!==e.variablesAttr){let t=e.variablesAttr.stateValues.variables;return{setValue:{variables:returnNVariables(n[0],t)}}}if(e.functionChild.length>0){let e={};for(let n of r)e[n]=t[n].functionChild[0].stateValues["variable"+(Number(n)+1)];return{setValue:{variables:e}}}return e.parentVariableForChild&&!a.parentVariableForChild?{setValue:{variables:Array(n[0]).fill(e.parentVariableForChild)}}:{setValue:{variables:returnNVariables(n[0],[])}}}},t.variable={isAlias:!0,targetVariableName:"variable1"},t.unnormalizedFormula={defaultValue:me$3.fromAst(0),hasEssential:!0,returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["formula"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"}}),definition:function({dependencyValues:e,usedDefault:t}){return e.isInterpolatedFunction?{setValue:{unnormalizedFormula:me$3.fromAst("_")}}:e.mathChild.length>0?{setValue:{unnormalizedFormula:e.mathChild[0].stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0].formula?{setValue:{unnormalizedFormula:e.functionChild[0].stateValues.formula}}:{useEssentialOrDefaultValue:{unnormalizedFormula:!0}}}},t.formula={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},defaultValue:me$3.fromAst(0),hasEssential:!0,returnDependencies:()=>({unnormalizedFormula:{dependencyType:"stateVariable",variableName:"unnormalizedFormula"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"}}),definition:function({dependencyValues:e,usedDefault:t}){if(t.unnormalizedFormula)return{useEssentialOrDefaultValue:{formula:!0}};return{setValue:{formula:normalizeMathExpression({value:e.unnormalizedFormula,simplify:e.simplify,expand:e.expand})}}}},t.nPrescribedPoints={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition({dependencyValues:e}){let t=0;return null!==e.through&&(t=e.through.stateValues.nPoints),{setValue:{nPrescribedPoints:t}}}},t.prescribedPoints={isArray:!0,entryPrefixes:["prescribedPoint"],returnArraySizeDependencies:()=>({nPrescribedPoints:{dependencyType:"stateVariable",variableName:"nPrescribedPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nPrescribedPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["point"+e]},throughSlopes:{dependencyType:"attributeComponent",attributeName:"throughSlopes",variableNames:["math"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].through;if(null!==t){let a=Number(r)+1,i=t.stateValues["point"+a],o=null,s=e[r].throughSlopes;null!==s&&(o=s.stateValues["math"+a],void 0===o&&(o=null)),n[r]={x:i[0],y:i[1],slope:o}}}return{setValue:{prescribedPoints:n}}}},t.prescribedMinima={returnDependencies:()=>({minima:{dependencyType:"attributeComponent",attributeName:"minima",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.minima&&(t=e.minima.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedMinima:t}}}},t.prescribedMaxima={returnDependencies:()=>({maxima:{dependencyType:"attributeComponent",attributeName:"maxima",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.maxima&&(t=e.maxima.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedMaxima:t}}}},t.prescribedExtrema={returnDependencies:()=>({extrema:{dependencyType:"attributeComponent",attributeName:"extrema",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.extrema&&(t=e.extrema.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedExtrema:t}}}},t.interpolationPoints={returnDependencies:()=>({xscale:{dependencyType:"stateVariable",variableName:"xscale"},yscale:{dependencyType:"stateVariable",variableName:"yscale"},prescribedPoints:{dependencyType:"stateVariable",variableName:"prescribedPoints"},prescribedMinima:{dependencyType:"stateVariable",variableName:"prescribedMinima"},prescribedMaxima:{dependencyType:"stateVariable",variableName:"prescribedMaxima"},prescribedExtrema:{dependencyType:"stateVariable",variableName:"prescribedExtrema"}}),definition:({dependencyValues:t})=>calculateInterpolationPoints({dependencyValues:t,numerics:e})},t.xs={additionalStateVariablesDefined:["coeffs"],returnDependencies:()=>({interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"}}),definition:computeSplineParamCoeffs},t.symbolicfs={isArray:!0,entryPrefixes:["symbolicf"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolicfs"]},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)if("0"===r){let n=returnInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain});t[r]=function(e){me$3.fromAst(n(e.evaluate_to_constant()))}}else t[r]=e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.symbolicfs[r];return{setValue:{symbolicfs:t}}}if(e.symbolicfShadow){let t={};for(let r of n)t[r]="0"===r?e.symbolicfShadow:e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}if(e.numericalfShadow){let t={};for(let r of n)t[r]="0"===r?function(t){let n=t.evaluate_to_constant();return null===n?NaN:me$3.fromAst(e.numericalfShadow(n))}:e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}{let t={};for(let r of n)t[r]=returnSymbolicFunctionFromFormula(e,r);return{setValue:{symbolicfs:t}}}}{let t={};for(let r of n)t[r]=returnSymbolicFunctionFromFormula(e,r);return{setValue:{symbolicfs:t}}}}},t.symbolicf={isAlias:!0,targetVariableName:"symbolicf1"},t.numericalfs={isArray:!0,entryPrefixes:["numericalf"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalfs"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)t[r]="0"===r?returnInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain}):e=>me$3.fromAst("_");return{setValue:{numericalfs:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.numericalfs[r];return{setValue:{numericalfs:t}}}if(e.numericalfShadow){let t={};for(let r of n)t[r]="0"===r?e.numericalfShadow:()=>NaN;return{setValue:{numericalfs:t}}}if(e.symbolicfShadow){let e={};for(let t of n)e[t]="0"===t?function(e){let t=dependencyValues.symbolicfShadow(me$3.fromAst(e)).evaluate_to_constant();return null===t&&(t=NaN),t}:()=>NaN;return{setValue:{numericalfs:e}}}{let t={};for(let r of n)t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r});return{setValue:{numericalfs:t}}}}{let t={};for(let r of n)t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r});return{setValue:{numericalfs:t}}}}},t.numericalf={returnDependencies:()=>({numericalf1:{dependencyType:"stateVariable",variableName:"numericalf1"}}),definition:({dependencyValues:e})=>({setValue:{numericalf:e.numericalf1}})},t.fDefinition={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["fDefinition"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:({dependencyValues:e,usedDefault:t})=>e.isInterpolatedFunction?{setValue:{fDefinition:{functionType:"interpolated",xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain}}}:t.formula||"_"===e.formula.tree&&0!==e.functionChild.length?e.functionChild.length>0?{setValue:{fDefinition:e.functionChild[0].stateValues.fDefinition}}:e.numericalfShadow||e.symbolicfShadow?{setValue:{fDefinition:{}}}:{setValue:{fDefinition:{functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain}}}:{setValue:{fDefinition:{functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain}}}},t.fs={isArray:!0,entryPrefixes:["f"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={symbolicf:{dependencyType:"stateVariable",variableName:"symbolicf"+e},numericalf:{dependencyType:"stateVariable",variableName:"numericalf"+e}}}return{globalDependencies:{symbolic:{dependencyType:"stateVariable",variableName:"symbolic"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};if(e.symbolic)for(let e of n)r[e]=t[e].symbolicf;else for(let e of n)r[e]=t[e].numericalf;return{setValue:{fs:r}}}},t.f={isAlias:!0,targetVariableName:"f1"},t.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({formula:{dependencyType:"stateVariable",variableName:"formula"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.formula,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},t.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},t.allMinima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{numericalf:{dependencyType:"stateVariable",variableName:"numericalf"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["allMinima"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:function({dependencyValues:t}){if(t.isInterpolatedFunction){let n=t.xs,r=t.coeffs,a=e.eps,i=[];if(null===n)return{setValue:{allMinima:i}};let o=!1,s=-1/0,l=1/0,u=!1,c=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{s=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(s)?u=!e.tree[2][1]:s=-1/0,l=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][2]:l=1/0}catch(e){}}let p=1e-14*Math.max(Math.abs(s),Math.abs(l)),d=r[0],m=n[1]-n[0];if(0===d[3]){if(d[2]>0){let e=-d[1]/(2*d[2]);e+n[0]>=s-p&&e+n[0]<=l+p&&(e<=m-a?u&&Math.abs(e+n[0]-s)0){let t=Math.sqrt(e),r=(-2*d[2]+t)/(6*d[3]);r+n[0]>=s-p&&r+n[0]<=l+p&&(r<=m-a?u&&Math.abs(r+n[0]-s)0){let t=-d[1]/(2*d[2]);if(t+n[e]>=s-p){if(!(t+n[e]<=l+p)){o=!1;continue}Math.abs(t)=a&&t<=m-a&&(u&&Math.abs(t+n[e]-s)0){let r=Math.sqrt(t),f=(-2*d[2]+r)/(6*d[3]);if(f+n[e]>=s-p){if(!(f+n[e]<=l+p)){o=!1;continue}Math.abs(f)=a&&f<=m-a&&(u&&Math.abs(f+n[e]-s)0){let e=-d[1]/(2*d[2]);e+n[n.length-2]>=s-p&&e+n[n.length-2]<=l+p&&(Math.abs(e)=a&&(u&&Math.abs(e+n[n.length-2]-s)0){let t=Math.sqrt(e),r=(-2*d[2]+t)/(6*d[3]);r+n[n.length-2]>=s-p&&r+n[n.length-2]<=l+p&&(r>=a||Math.abs(r)0)return{setValue:{allMinima:t.functionChild[0].stateValues.allMinima}};if(1!==t.nInputs||1!==t.nOutputs)return{setValue:{allMinima:[]}};let n,r,a=t.variables[0].subscripts_to_strings().tree,i=t.formula.subscripts_to_strings().derivative(a),o=!0;try{n=i.subscripts_to_strings().f()}catch(e){o=!1,r=()=>NaN}o&&(r=function(e){try{return n({[a]:e})}catch(e){return NaN}});let s=e=>t.numericalf(e,!0),l=-100*t.xscale,u=100*t.xscale,c=!1,p=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{l=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][1]:l=-100*t.xscale,u=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(u)?p=!e.tree[2][2]:u=100*t.xscale}catch(e){}}let d=1e3,m=(u-l)/d,f=1e-10*Math.max(Math.abs(l),Math.abs(u)),h=[],y=!1,b=!1,g=s(l-m),v=r(l-m);for(let t=-1;t0&&(T=!0,y=!1,!(t>=l-f&&t<=u+f)||c&&Math.abs(t-l)({allMinima:{dependencyType:"stateVariable",variableName:"allMinima"}}),definition:({dependencyValues:e})=>({setValue:{numberMinima:e.allMinima.length},checkForActualChange:{numberMinima:!0}})},t.minima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"minimum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["minimum","minimumLocations","minimumLocation","minimumValues","minimumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["minimum","minimumLocation","minimumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"minimumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"minimumLocation"+(Number(t)+1):"minimumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("minima"===t){if(1===e.length)return"minimum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"minimumLocation"+t;if(2===e[1])return"minimumValue"+t}return null}}if("minimumLocations"===t)return"minimumLocation"+e[0];if("minimumValues"===t)return"minimumValue"+e[0];if("minimum"===t.slice(0,7)){let n=Number(t.slice(7));if(Number.isInteger(n)&&n>0){if(1===e[0])return"minimumLocation"+n;if(2===e[0])return"minimumValue"+n}}return null},returnArraySizeDependencies:()=>({numberMinima:{dependencyType:"stateVariable",variableName:"numberMinima"}}),returnArraySize:({dependencyValues:e})=>[e.numberMinima,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allMinima:{dependencyType:"stateVariable",variableName:"allMinima"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;ne.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{numericalf:{dependencyType:"stateVariable",variableName:"numericalf"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["allMaxima"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:function({dependencyValues:t}){if(t.isInterpolatedFunction){let n=t.xs,r=t.coeffs,a=e.eps,i=[];if(null===n)return{setValue:{allMaxima:i}};let o=!1,s=-1/0,l=1/0,u=!1,c=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{s=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(s)?u=!e.tree[2][1]:s=-1/0,l=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][2]:l=1/0}catch(e){}}let p=1e-14*Math.max(Math.abs(s),Math.abs(l)),d=r[0],m=n[1]-n[0];if(0===d[3]){if(d[2]<0){let e=-d[1]/(2*d[2]);e+n[0]>=s-p&&e+n[0]<=l+p&&(e<=m-a?u&&Math.abs(e+n[0]-s)0){let t=Math.sqrt(e),r=(-2*d[2]-t)/(6*d[3]);r+n[0]>=s-p&&r+n[0]<=l+p&&(r<=m-a?u&&Math.abs(r+n[0]-s)=s-p){if(!(t+n[e]<=l+p)){o=!1;continue}Math.abs(t)=a&&t<=m-a&&(u&&Math.abs(t+n[e]-s)0){let r=Math.sqrt(t),f=(-2*d[2]-r)/(6*d[3]);if(f+n[e]>=s-p){if(!(f+n[e]<=l+p)){o=!1;continue}Math.abs(f)=a&&f<=m-a&&(u&&Math.abs(f+n[e]-s)=s-p&&e+n[n.length-2]<=l+p&&(Math.abs(e)=a&&(u&&Math.abs(e+n[n.length-2]-s)0){let t=Math.sqrt(e),r=(-2*d[2]-t)/(6*d[3]);r+n[n.length-2]>=s-p&&r+n[n.length-2]<=l+p&&(r>=a||Math.abs(r)0)return{setValue:{allMaxima:t.functionChild[0].stateValues.allMaxima}};if(1!==t.nInputs||1!==t.nOutputs)return{setValue:{allMaxima:[]}};let n,r,a=t.variables[0].subscripts_to_strings().tree,i=t.formula.subscripts_to_strings().derivative(a),o=!0;try{n=i.subscripts_to_strings().f()}catch(e){o=!1,r=()=>NaN}o&&(r=function(e){try{return n({[a]:e})}catch(e){return NaN}});let s=e=>-t.numericalf(e,!0),l=-100*t.xscale,u=100*t.xscale,c=!1,p=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{l=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][1]:l=-100*t.xscale,u=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(u)?p=!e.tree[2][2]:u=100*t.xscale}catch(e){}}let d=1e3,m=(u-l)/d,f=1e-10*Math.max(Math.abs(l),Math.abs(u)),h=[],y=!1,b=!1,g=s(l-m),v=r(l-m);for(let t=-1;t0&&r(t+i)<0&&(T=!0,y=!1,!(t>=l-f&&t<=u+f)||c&&Math.abs(t-l)({allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}),definition:({dependencyValues:e})=>({setValue:{numberMaxima:e.allMaxima.length},checkForActualChange:{numberMaxima:!0}})},t.maxima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"maximum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["maximum","maximumLocations","maximumLocation","maximumValues","maximumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["maximum","maximumLocation","maximumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"maximumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"maximumLocation"+(Number(t)+1):"maximumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("maxima"===t){if(1===e.length)return"maximum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"maximumLocation"+t;if(2===e[1])return"maximumValue"+t}return null}}if("maximumLocations"===t)return"maximumLocation"+e[0];if("maximumValues"===t)return"maximumValue"+e[0];if("maximum"===t.slice(0,7)){let n=Number(t.slice(7));if(Number.isInteger(n)&&n>0){if(1===e[0])return"maximumLocation"+n;if(2===e[0])return"maximumValue"+n}}return null},returnArraySizeDependencies:()=>({numberMaxima:{dependencyType:"stateVariable",variableName:"numberMaxima"}}),returnArraySize:({dependencyValues:e})=>[e.numberMaxima,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({numberMinima:{dependencyType:"stateVariable",variableName:"numberMinima"},numberMaxima:{dependencyType:"stateVariable",variableName:"numberMaxima"}}),definition:function({dependencyValues:e}){return{setValue:{numberExtrema:e.numberMinima+e.numberMaxima},checkForActualChange:{numberExtrema:!0}}}},t.allExtrema={returnDependencies:()=>({allMinima:{dependencyType:"stateVariable",variableName:"allMinima"},allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}),definition({dependencyValues:e}){let t=[...e.allMinima,...e.allMaxima].sort(((e,t)=>e[0]-t[0]));return{setValue:{allExtrema:t}}}},t.extrema={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"extremum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["extremum","extremumLocations","extremumLocation","extremumValues","extremumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["extremum","extremumLocation","extremumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"extremumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"extremumLocation"+(Number(t)+1):"extremumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("extrema"===t){if(1===e.length)return"extremum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"extremumLocation"+t;if(2===e[1])return"extremumValue"+t}return null}}if("extremumLocations"===t)return"extremumLocation"+e[0];if("extremumValues"===t)return"extremumValue"+e[0];if("extremum"===t.slice(0,8)){let n=Number(t.slice(8));if(Number.isInteger(n)&&n>0){if(1===e[0])return"extremumLocation"+n;if(2===e[0])return"extremumValue"+n}}return null},returnArraySizeDependencies:()=>({numberExtrema:{dependencyType:"stateVariable",variableName:"numberExtrema"}}),returnArraySize:({dependencyValues:e})=>[e.numberExtrema,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allExtrema:{dependencyType:"stateVariable",variableName:"allExtrema"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;ne.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}}:{functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["returnNumericalDerivatives","variables"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}},definition:function({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{returnNumericalDerivatives:returnReturnDerivativesOfInterpolatedFunction(e)}};if(e.functionChild.length>0&&e.functionChild[0].stateValues.returnNumericalDerivatives){let t=e.variables.map((e=>e.subscripts_to_strings().tree)),n=e.functionChild[0].stateValues.variables,r=n.map((e=>e.subscripts_to_strings().tree)),a={};for(let[e,i]of t.entries())r[e]&&r[e]!==i&&(a[i]=n[e]);if(0===Object.keys(a).length)return{setValue:{returnNumericalDerivatives:e.functionChild[0].stateValues.returnNumericalDerivatives}};return{setValue:{returnNumericalDerivatives:function(t){let n=[];for(let e of t){let t=a[e.subscripts_to_strings().tree];t?n.push(t):n.push(me$3.fromAst("_"))}return e.functionChild[0].stateValues.returnNumericalDerivatives(n)}}}}return{setValue:{returnNumericalDerivatives:null}}}},t.numericalDerivativesDefinition={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}}:{functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalDerivativesDefinition","variables"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}},definition:function({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{numericalDerivativesDefinition:{derivativeType:"interpolatedFunction",xs:e.xs,coeffs:e.coeffs,variables:e.variables}}};if(e.functionChild.length>0&&e.functionChild[0].stateValues.numericalDerivativesDefinition){let t=e.variables.map((e=>e.subscripts_to_strings().tree)),n=e.functionChild[0].stateValues.variables,r=n.map((e=>e.subscripts_to_strings().tree)),a={};for(let[e,i]of t.entries())r[e]&&r[e]!==i&&(a[i]=n[e]);if(0===Object.keys(a).length)return{setValue:{numericalDerivativesDefinition:e.functionChild[0].stateValues.numericalDerivativesDefinition}};{let t={...e.functionChild[0].stateValues.numericalDerivativesDefinition};return t.variableMappings?t.variableMappings=[a,...t.variableMappings]:t.variableMappings=[a],{setValue:{numericalDerivativesDefinition:t}}}}return{setValue:{numericalDerivativesDefinition:{}}}}},t}static adapters=[{stateVariable:"numericalf",componentType:"curve",stateVariablesToShadow:["label","labelHasLatex"]},{stateVariable:"formula",componentType:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}]}function calculateInterpolationPoints({dependencyValues:e,numerics:t}){let n=[],r=[],a={maximum:e.prescribedMaxima,minimum:e.prescribedMinima,extremum:e.prescribedExtrema,point:e.prescribedPoints};for(let e in a)for(let t of a[e]){let a=null,i=null,o=null;if(null===t.x||(a=t.x.evaluate_to_constant(),Number.isFinite(a)))if(null===t.y||(i=t.y.evaluate_to_constant(),Number.isFinite(i)))if(null!==t.slope&&void 0!==t.slope&&(o=t.slope.evaluate_to_constant(),Number.isFinite(o)||(console.warn("Ignoring non-numerical slope"),o=null)),null===a){if(null===i){console.warn(`Ignoring empty ${e}`);continue}r.push({type:e,y:i,slope:o})}else n.push({type:e,x:a,y:i,slope:o});else console.warn(`Ignoring non-numerical ${e}`);else console.warn(`Ignoring non-numerical ${e}`)}n.sort(((e,t)=>e.x-t.x)),r.sort(((e,t)=>e.y-t.y));let i=-1/0,o=t.eps;for(let e=0;e0;){let e,t;void 0===l?e=v({allowedTypes:["maximum","minimum","extremum"],comparison:"atLeast",value:-1/0}):"maximum"===l?e=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:s-c}):"minimum"===l?e=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:s+c}):"point"===l&&(e=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:s+c}),!0!==e.success&&(e=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:s-c}))),!0===e.success?(t=e.point,r.splice(e.ind,1),m?(t.x=0,m=!1):t.x=i+u):(t=r.pop(),m?(t.x=0,m=!1):t.x=i+2*u);let n=y({p:t,typePrev:l,xPrev:i,yPrev:s});l=n.type,i=n.x,s=n.y}if(0===p.length&&p.push({type:"point",x:0,y:0,slope:0}),m=p[0],"maximum"===m.type){let e={type:"point",x:m.x-u,y:m.y-c,slope:2*c/u};p.splice(0,0,e)}else if("minimum"===m.type){let e={type:"point",x:m.x-u,y:m.y+c,slope:-2*c/u};p.splice(0,0,e)}else if("point"===m.type)if(1===p.length)null===m.slope&&(m.slope=0);else{let e=p[1],t=(e.y-m.y)/(e.x-m.x);if("maximum"===e.type||"minimum"===e.type)null===m.slope&&(m.slope=2*t);else{2===p.length?null===m.slope&&(m.slope=t):(null===e.slope&&(e.slope=h({point:e,prevPoint:m,nextPoint:p[2]})),null===m.slope&&(m.slope=2*(m.y-e.y)/(m.x-e.x)-e.slope));let n={x:m.x-u,y:m.y-u*m.slope,slope:m.slope};p.splice(0,0,n)}}let f=p[p.length-1];if("maximum"===f.type){let e={type:"point",x:f.x+u,y:f.y-c,slope:-2*c/u};p.push(e)}else if("minimum"===f.type){let e={type:"point",x:f.x+u,y:f.y+c,slope:2*c/u};p.push(e)}else if("point"===f.type)if(1===p.length){let e={type:"point",x:f.x+u,y:f.y+m.slope*u,slope:m.slope};p.push(e)}else{let e=p[p.length-2],t=(e.y-f.y)/(e.x-f.x);if("maximum"===e.type||"minimum"===e.type)null===f.slope&&(f.slope=2*t);else{2===p.length?null===f.slope&&(f.slope=t):(null===e.slope&&(e.slope=h({point:e,prevPoint:p[p.length-3],nextPoint:f})),null===f.slope&&(f.slope=2*(e.y-f.y)/(e.x-f.x)-e.slope));let n={x:f.x+u,y:f.y+u*f.slope,slope:f.slope};p.push(n)}}for(let e=1;ei-c||void 0!==r&&null!==e.y&&e.y>t.y-c?b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:o,pNext:t}):g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:o,pNext:t});if("minimum"===n||"minimum"===r)return null!==e.y&&e.yt.y+c?g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:o,pNext:t}):b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:o,pNext:t});if("point"===n||"point"===r){let s="maximum";return(null===e.y&&void 0!==t&&t.type===maximum||null!==e.y&&e.y<=i-c||void 0!==r&&null!==e.y&&e.y>=t.y-c)&&(s="minimum"),"minimum"===s?g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:o,pNext:t}):b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:o,pNext:t})}return null!==e.y&&e.yo-c){let n,a,s=(e+i)/2,l=null,u=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:Math.min(o,t)-c});!0===u.success?(a="minimum",n=u.point.y,r.splice(u.ind,1),l=0):(a="point",n=o-c),p.push({type:a,x:s,y:n,slope:l})}}else if("minimum"===a&&ti-c){let n=[(2*a+e)/3,(a+2*e)/3],o=[i-c,t+c],s=["atMost","atLeast"],l=[["minimum","extremum"],["maximum","extremum"]];for(let e=0;e<2;e++){let t,a,i=n[e],u=null,c=v({allowedTypes:l[e],comparison:s[e],value:o[e]});!0===c.success?(a=l[e][0],t=c.point.y,r.splice(c.ind,1),u=0):(a="point",t=o[e],u=null),p.push({type:a,x:i,y:t,slope:u})}}}else if("minimum"===n){null===t&&(t=void 0===o?i:"minimum"===s.type?Math.min(i,o):Math.min(i,o-c));let n,l,u=Math.max(i,t)+c,d=(e+a)/2,m=null,f=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:u});!0===f.success?(l="maximum",n=f.point.y,r.splice(f.ind,1),m=0):(l="point",n=u),p.push({type:l,x:d,y:n,slope:m})}else if("point"===n)if(null===t)t=void 0===o?i-c:"minimum"===s.type?Math.min(i-c,o):Math.min(i,o)-c;else if(t>i-c){let n,i,o=(e+a)/2,s=null,l=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:t+c});!0===l.success?(i="maximum",n=l.point.y,r.splice(l.ind,1),s=0):(i="point",n=t+c),p.push({type:i,x:o,y:n,slope:s})}let l={type:"minimum",x:e,y:t,slope:0};return p.push(l),l}function v({allowedTypes:e,comparison:t,value:n}){let a=[];if("atMost"===t)a=Object.keys(r).reverse();else{if("atLeast"!==t)return{success:!1};a=Object.keys(r)}for(let i of e)for(let e of a){let a=r[e];if(a.type===i)if("atMost"===t){if(a.y<=n)return{success:!0,ind:e,point:a}}else if(a.y>=n)return{success:!0,ind:e,point:a}}return{success:!1}}}function computeSplineParamCoeffs({dependencyValues:e}){let t=e.interpolationPoints;if(null===t)return{setValue:{xs:null,coeffs:null}};let n,r=[],a=[],i=t[0];a.push(i.x);for(let e=1;et.componentIsSpecifiedType(e,"label");if(0===e.length||!e.every((e=>"string"==typeof e||e.doenetAttributes?.createdFromMacro||n(e))))return{success:!1};let r=e.map(n),a=[],i=[],o=[];if(0===r.filter((e=>e)).length)a=e;else{if(r[0]){let t=r.indexOf(!1);-1!==t&&(i=e.slice(0,t),e=e.slice(t),r=r.slice(t))}let t=r.indexOf(!0);-1===t?a=e:(a=e.slice(0,t),o=e.slice(t))}return 0===a.length||1===a.length&&"string"!=typeof a[0]?{success:!1}:{success:!0,newChildren:[...i,{componentType:"math",children:a},...o]}}}),e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e}),n=this.componentType;t.isInterpolatedFunction={returnDependencies:()=>({}),definition:()=>({setValue:{isInterpolatedFunction:!1}})},delete t.nPrescribedPoints,delete t.prescribedPoints,delete t.prescribedMinima,delete t.prescribedMaxima,delete t.prescribedExtrema,delete t.interpolationPoints,delete t.xs,t.operatorBasedOnFormulaIfAvailable={returnDependencies:()=>({}),definition:()=>({setValue:{operatorBasedOnFormulaIfAvailable:!1}})},t.formula.returnDependencies=()=>({}),t.formula.definition=()=>({setValue:{formula:me$3.fromAst("_")}}),t.operatorComposesWithOriginal={returnDependencies:()=>({}),definition:()=>({setValue:{operatorComposesWithOriginal:!0}})},t.symbolicFunctionOperator={returnDependencies:()=>({}),definition:()=>({setValue:{symbolicFunctionOperator:e=>me$3.fromAst("_")}})},t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({}),definition:()=>({setValue:{numericalFunctionOperator:e=>NaN,numericalFunctionOperatorArguments:[]}})},t.numericalFunctionOperatorArguments={returnDependencies:()=>({}),definition:()=>({setValue:{numericalFunctionOperatorArguments:{}}})},t.formulaOperator={returnDependencies:()=>({}),definition:()=>({setValue:{formulaOperator:e=>me$3.fromAst("_")}})},t.returnNumericalDerivatives={returnDependencies:()=>({}),definition:()=>({setValue:{returnNumericalDerivatives:null}})},t.formula={public:!0,shadowingInstructions:{createComponentOfType:"math"},additionalStateVariablesDefined:["operatorBasedOnFormula"],returnDependencies:()=>({operatorBasedOnFormulaIfAvailable:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormulaIfAvailable"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["formula"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},formulaOperator:{dependencyType:"stateVariable",variableName:"formulaOperator"}}),definition:function({dependencyValues:e}){if(!e.operatorBasedOnFormulaIfAvailable||(0===e.functionChild.length||"_"===e.functionChild[0].stateValues.formula.tree)&&(0===e.mathChild.length||"_"===e.mathChild[0].stateValues.value.tree))return{setValue:{formula:me$3.fromAst("_"),operatorBasedOnFormula:!1}};let t;return t=0===e.functionChild.length?e.mathChild[0].stateValues.value:e.functionChild[0].stateValues.formula,{setValue:{formula:e.formulaOperator(t),operatorBasedOnFormula:!0}}}},t.symbolicfs={isArray:!0,entryPrefixes:["symbolicf"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolicfs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},symbolicFunctionOperator:{dependencyType:"stateVariable",variableName:"symbolicFunctionOperator"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n,arraySize:r}){if(!e.operatorBasedOnFormula){if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let e={};for(let t of n)e[t]=e=>me$3.fromAst("_");return{setValue:{symbolicfs:e}}}{let t=Object.assign({},e);t.formula=e.mathChild[0].stateValues.value;let a=[];for(let e=0;ee.symbolicFunctionOperator(...a.map((e=>e(...t))));return{setValue:{symbolicfs:i}}}}{let t=[];for(let n=0;ne.symbolicFunctionOperator(...t.map((e=>e(...n))));return{setValue:{symbolicfs:a}}}}{let t={};for(let r of n)t[r]=(...t)=>e.symbolicFunctionOperator(...t);return{setValue:{symbolicfs:t}}}}{let t={};for(let r of n)return t[r]=returnSymbolicFunctionFromFormula(e,r),{setValue:{symbolicfs:t}}}}},t.numericalfs={isArray:!0,entryPrefixes:["numericalf"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalfs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n,arraySize:r}){if(!e.operatorBasedOnFormula){if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let e={};for(let t of n)e[t]=e=>NaN;return{setValue:{numericalfs:e}}}{Object.assign({},e).formula=e.mathChild[0].stateValues.value;let t=[];for(let n=0;ne.numericalFunctionOperator(...t.map((e=>e(...n))));return{setValue:{numericalfs:a}}}}{let t=[];for(let n=0;ne.numericalFunctionOperator(...t.map((e=>e(...n))));return{setValue:{numericalfs:a}}}}{let t={};for(let r of n)t[r]=(...t)=>e.numericalFunctionOperator(...t);return{setValue:{numericalfs:t}}}}{let t={};for(let r of n)return t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r}),{setValue:{numericalfs:t}}}}},t.fDefinition={returnDependencies:()=>({operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["fDefinition"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"},numericalFunctionOperatorArguments:{dependencyType:"stateVariable",variableName:"numericalFunctionOperatorArguments"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}),definition({dependencyValues:e}){if(e.operatorBasedOnFormula)return{setValue:{fDefinition:{functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain}}};if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length)return{setValue:{fDefinition:{functionType:"formula",formula:"_",variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain}}};throw Error("function operator with math child not implemented yet")}return{setValue:{fDefinition:{functionType:"functionOperator",componentType:n,nOutputs:e.nOutputs,functionOperatorArguments:e.numericalFunctionOperatorArguments,operatorComposesWithOriginal:!0,originalFDefinition:e.functionChild[0].stateValues.fDefinition}}}}if(0===e.functionChild.length){if(0===e.mathChild.length)return{setValue:{fDefinition:{functionType:"formula",formula:"_",variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain}}};throw Error("function operator with math child not implemented yet")}return{setValue:{fDefinition:{functionType:"functionOperator",componentType:n,nOutputs:e.nOutputs,functionOperatorArguments:e.numericalFunctionOperatorArguments,operatorComposesWithOriginal:!1,originalFDefinition:e.functionChild[0].stateValues.fDefinition}}}}};let r=t.allMinima.returnDependencies;t.allMinima.returnDependencies=function(e){let t=r(e);return delete t.functionChild,t};let a=t.allMaxima.returnDependencies;return t.allMaxima.returnDependencies=function(e){let t=a(e);return delete t.functionChild,t},t}}class ClampFunction extends FunctionOperator{static componentType="clampFunction";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:function({dependencyValues:e}){return{setValue:{numericalFunctionOperator:functionOperatorDefinitions.clampFunction(e.lowerValue,e.upperValue),numericalFunctionOperatorArguments:[e.lowerValue,e.upperValue]}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}class WrapFunctionPeriodic extends FunctionOperator{static componentType="wrapFunctionPeriodic";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:function({dependencyValues:e}){return{setValue:{numericalFunctionOperator:functionOperatorDefinitions.wrapFunctionPeriodic(e.lowerValue,e.upperValue),numericalFunctionOperatorArguments:[e.lowerValue,e.upperValue]}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}class Derivative extends FunctionOperator{static componentType="derivative";static createAttributesObject(){let e=super.createAttributesObject();return e.derivVariables={createComponentOfType:"variables"},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.operatorBasedOnFormulaIfAvailable={returnDependencies:()=>({}),definition:()=>({setValue:{operatorBasedOnFormulaIfAvailable:!0}})},t.operatorComposesWithOriginal={returnDependencies:()=>({}),definition:()=>({setValue:{operatorComposesWithOriginal:!1}})},t.haveFunctionChild={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"]}}),definition:({dependencyValues:e})=>({setValue:{haveFunctionChild:e.functionChild.length>0}})},t.nInputs={defaultValue:1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},stateVariablesDeterminingDependencies:["haveFunctionChild"],returnDependencies({stateValues:e}){let t={nInputsAttr:{dependencyType:"attributeComponent",attributeName:"nInputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nInputs"]},variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["nComponents"]}};return e.haveFunctionChild||(t.derivVariablesAttr={dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]}),t},definition({dependencyValues:e}){if(null!==e.nInputsAttr){let t=e.nInputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nInputs:t}}}if(null!==e.variablesAttr)return{setValue:{nInputs:Math.max(1,e.variablesAttr.stateValues.nComponents)}};if(e.functionChild.length>0)return{setValue:{nInputs:e.functionChild[0].stateValues.nInputs}};if(null!==e.derivVariablesAttr){let t=[...new Set(e.derivVariablesAttr.stateValues.variables.map((e=>e.subscripts_to_strings().tree)))].length;return{setValue:{nInputs:t}}}return{useEssentialOrDefaultValue:{nInputs:!0}}}},t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),returnArraySize:({dependencyValues:e})=>[e.nInputs],stateVariablesDeterminingDependencies:["haveFunctionChild"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]},parentVariableForChild:{dependencyType:"parentStateVariable",variableName:"variableForChild"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},haveFunctionChild:{dependencyType:"stateVariable",variableName:"haveFunctionChild"}},r={};if(t.haveFunctionChild)for(let t of e)r[t]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["variable"+(Number(t)+1)]}};else n.derivVariablesAttr={dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]};return{globalDependencies:n,dependenciesByKey:r}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arraySize:n,arrayKeys:r,usedDefault:a}){if(null!==e.variablesAttr){let t=e.variablesAttr.stateValues.variables;return{setValue:{variables:returnNVariables(n[0],t)}}}if(e.haveFunctionChild){let e={};for(let n of r)e[n]=t[n].functionChild[0].stateValues["variable"+(Number(n)+1)];return{setValue:{variables:e}}}if(null!==e.derivVariablesAttr){let t=[],r=[];for(let n of e.derivVariablesAttr.stateValues.variables){let e=n.subscripts_to_strings().tree;r.includes(e)||(t.push(n),r.push(e))}return{setValue:{variables:returnNVariables(n[0],t)}}}return e.parentVariableForChild&&!a.parentVariableForChild?{setValue:{variables:Array(n[0]).fill(e.parentVariableForChild)}}:{setValue:{variables:returnNVariables(n[0],[])}}}},t.nDerivatives={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({derivVariablesAttr:{dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["nComponents"]}}),definition:({dependencyValues:e})=>null!==e.derivVariablesAttr?{setValue:{nDerivatives:e.derivVariablesAttr.stateValues.nComponents}}:{setValue:{nDerivatives:1}}},t.derivVariables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["derivVariable"],returnArraySizeDependencies:()=>({nDerivatives:{dependencyType:"stateVariable",variableName:"nDerivatives"}}),returnArraySize:({dependencyValues:e})=>[e.nDerivatives],returnArrayDependenciesByKey:()=>({globalDependencies:{derivVariablesAttr:{dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]},variable1:{dependencyType:"stateVariable",variableName:"variable1"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>null!==e.derivVariablesAttr?{setValue:{derivVariables:e.derivVariablesAttr.stateValues.variables}}:{setValue:{derivVariables:{0:e.variable1}}}},t.formulaOperator={returnDependencies:()=>({derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),definition:({dependencyValues:e})=>({setValue:{formulaOperator:function(t){let n=t.subscripts_to_strings();for(let t of e.derivVariables)n=n.derivative(t.subscripts_to_strings().tree);return n.strings_to_subscripts()}}})},t.numericalFunctionOperator={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["returnNumericalDerivatives"],variablesOptional:!0},derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),additionalStateVariablesDefined:["returnNumericalDerivatives"],definition:function({dependencyValues:e}){if(0===e.functionChild.length||!e.functionChild[0].stateValues.returnNumericalDerivatives)return{setValue:{numericalFunctionOperator:e=>NaN,returnNumericalDerivatives:null}};return{setValue:{numericalFunctionOperator:e.functionChild[0].stateValues.returnNumericalDerivatives(e.derivVariables),returnNumericalDerivatives:function(t){let n=[...e.derivVariables,...t];return e.functionChild[0].stateValues.returnNumericalDerivatives(n)}}}}},t.numericalFunctionOperatorArguments={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalDerivativesDefinition"],variablesOptional:!0},derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),additionalStateVariablesDefined:["numericalDerivativesDefinition"],definition:function({dependencyValues:e}){if(0===e.functionChild.length||!e.functionChild[0].stateValues.numericalDerivativesDefinition)return{setValue:{numericalFunctionOperatorArguments:[],numericalDerivativesDefinition:{}}};let t=e.functionChild[0].stateValues.numericalDerivativesDefinition,n={...t};return n.additionalDerivVariables?n.additionalDerivVariables=[...e.derivVariables,...n.additionalDerivVariables]:n.additionalDerivVariables=[...e.derivVariables],{setValue:{numericalFunctionOperatorArguments:[t,e.derivVariables],numericalDerivativesDefinition:n}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}var FunctionOperators=Object.freeze({__proto__:null,ClampFunction:ClampFunction,WrapFunctionPeriodic:WrapFunctionPeriodic,Derivative:Derivative});class TextBaseOperatorOfMath extends Text{static componentType="_textOperatorOfMath";static rendererType="text";static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyTextOperator(e.mathChildren.map((e=>e.stateValues.value)))}}}},e}}class ExtractMathOperator extends TextBaseOperatorOfMath{static componentType="extractMathOperator";static applyTextOperator(e){return 0===e.length?"":1!==e.length?(console.warn("MathOperator requires exactly one math child"),""):Array.isArray(e[0].tree)?e[0].tree[0]:""}}var TextOperatorsOfMath=Object.freeze({__proto__:null,ExtractMathOperator:ExtractMathOperator});class Extremum extends BaseComponent{static componentType="extremum";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.location={createComponentOfType:"math"},e.value={createComponentOfType:"math"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/s+(.*s)?/,replacementFunction:function({matchedChildren:e}){let t=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),n=t({matchedChildren:e});if(!n.success&&1===e.length)return{success:!0,newAttributes:{value:{component:{componentType:"math",children:e}}}};if(n.success){if(1===n.newChildren.length)return{success:!0,newAttributes:{value:{component:n.newChildren[0]}}};if(2===n.newChildren.length){let e=n.newChildren[0],t=n.newChildren[1],r={location:{component:e},value:{component:t}};return(0===e.children.length||1===e.children.length&&"string"==typeof e.children[0]&&""===e.children[0].trim())&&delete r.location,(0===t.children.length||1===t.children.length&&"string"==typeof t.children[0]&&""===t.children[0].trim())&&delete r.value,{success:!0,newAttributes:r}}return{success:!1}}return n}}),e}static returnChildGroups(){return[{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e}),n=this;return t.value={public:!0,shadowingInstructions:{createComponentOfType:"math"},defaultValue:null,hasEssential:!0,additionalStateVariablesDefined:[{variableName:"location",public:!0,shadowingInstructions:{createComponentOfType:"math"},defaultValue:null,hasEssential:!0}],returnDependencies:()=>({extremumChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions","xs"]},location:{dependencyType:"attributeComponent",attributeName:"location",variableNames:["value"]},value:{dependencyType:"attributeComponent",attributeName:"value",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t,r;if(e.extremumChild.length>0){let a=e.extremumChild[0];2!==a.stateValues.nDimensions?(console.log("Cannot determine "+n.componentType+" from a point that isn't 2D"),t=null,r=null):(t=a.stateValues.xs[0],r=a.stateValues.xs[1])}else null!==e.location&&(t=e.location.stateValues.value),null!==e.value&&(r=e.value.stateValues.value);let a={},i={},o=!1,s=!1;void 0===t?(i.location=!0,s=!0):(a.location=t,o=!0),void 0===r?(i.value=!0,s=!0):(a.value=r,o=!0);let l={};return o&&(l.setValue=a),s&&(l.useEssentialOrDefaultValue=i),l}},t}}class Extrema extends BaseComponent{static componentType="extrema";static rendererType=void 0;static componentTypeSingular="extremum";static get componentTypeCapitalized(){return this.componentType.charAt(0).toUpperCase()+this.componentType.slice(1)}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=this;return e.push({replacementFunction:function({matchedChildren:e}){let n=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==n.success?{success:!1}:{success:!0,newChildren:n.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:t.componentTypeSingular,children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"extrema",componentTypes:[this.componentTypeSingular]},{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e["n"+t.componentTypeCapitalized]={additionalStateVariablesDefined:["childIdentities"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["extrema","points"]}}),definition:function({dependencyValues:e}){return{setValue:{["n"+t.componentTypeCapitalized]:e.children.length,childIdentities:e.children}}}},e[t.componentType]={isArray:!0,nDimensions:2,entryPrefixes:[t.componentTypeSingular,t.componentTypeSingular+"Locations",t.componentTypeSingular+"Location",t.componentTypeSingular+"Values",t.componentTypeSingular+"Value"],stateVariablesDeterminingDependencies:["childIdentities"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:n,arraySize:r}){if([t.componentTypeSingular,t.componentTypeSingular+"Location",t.componentTypeSingular+"Value"].includes(e)){let a=Number(n)-1;return Number.isInteger(a)&&a>=0&&(!r||at+",0")):["0,0"]:e===t.componentTypeSingular+"Values"?""!==n?[]:r?Array.from(Array(r[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[n,r]=e.split(",");return"0"===r?t.componentTypeSingular+"Location"+(Number(n)+1):t.componentTypeSingular+"Value"+(Number(n)+1)},arrayVarNameFromPropIndex(e,n){if(n===t.componentType){if(1===e.length)return t.componentTypeSingular+e[0];{let n=Number(e[0]);if(Number.isInteger(n)&&n>0){if(1===e[1])return t.componentTypeSingular+"Location"+n;if(2===e[1])return t.componentTypeSingular+"Value"+n}return null}}if(n===t.componentTypeSingular+"Locations")return t.componentTypeSingular+"Location"+e[0];if(n===t.componentTypeSingular+"Values")return t.componentTypeSingular+"Value"+e[0];let r=t.componentTypeSingular.length;if(n.slice(0,r)===t.componentTypeSingular){let a=Number(n.slice(r));if(Number.isInteger(a)&&a>0){if(1===e[0])return t.componentTypeSingular+"Location"+a;if(2===e[0])return t.componentTypeSingular+"Value"+a}}return null},returnArraySizeDependencies:()=>({nChildren:{dependencyType:"stateVariable",variableName:"n"+t.componentTypeCapitalized}}),returnArraySize:({dependencyValues:e})=>[e.nChildren,2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:n}){let r={};for(let a of e){let e,[i,o]=a.split(",");e=n.childIdentities[i].componentType===t.componentTypeSingular?0===Number(o)?"location":"value":"x"+(Number(o)+1),r[a]={child:{dependencyType:"child",childGroups:["extrema","points"],variableNames:[e],childIndices:[i]}}}return{dependenciesByKey:r}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:n}){let r={};for(let t of n){let n=e[t].child[0];if(n){let e=t.split(",")[1],a=0===Number(e)?"location":"value";a in n.stateValues?r[t]=n.stateValues[a]:r[t]=n.stateValues["x"+(Number(e)+1)]}}return{setValue:{[t.componentType]:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:n}){let r=[];for(let a in e[t.componentType])r.push({setDependency:n[a].extremumChild,desiredValue:e[t.componentType][a],childIndex:0,variableIndex:0});return{success:!0,instructions:r}}},e}}var Extrema$1=Object.freeze({__proto__:null,Extremum:Extremum,Extrema:Extrema});class InlineRenderInlineChildren extends InlineComponent{static componentType="_inlineRenderInlineChildren";static renderChildren=!0;static includeBlankStringChildren=!0;static beginTextDelimiter="";static endTextDelimiter="";static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let n="";for(let t of e.inlineChildren)"object"!=typeof t?n+=t.toString():"string"==typeof t.stateValues.text?n+=t.stateValues.text:n+=" ";return n=t.beginTextDelimiter+n+t.endTextDelimiter,{setValue:{text:n}}}},e}}class Em extends InlineRenderInlineChildren{static componentType="em"}class Alert extends InlineRenderInlineChildren{static componentType="alert"}class Q$2 extends InlineRenderInlineChildren{static componentType="q";static beginTextDelimiter='"';static endTextDelimiter='"'}class SQ extends InlineRenderInlineChildren{static componentType="sq";static beginTextDelimiter="'";static endTextDelimiter="'"}class Term extends InlineRenderInlineChildren{static componentType="term";static rendererType="alert"}class C$2 extends InlineRenderInlineChildren{static componentType="c"}class Tag extends InlineRenderInlineChildren{static componentType="tag";static rendererType="tag";static beginTextDelimiter="<";static endTextDelimiter=">"}class Tage extends InlineRenderInlineChildren{static componentType="tage";static rendererType="tag";static beginTextDelimiter="<";static endTextDelimiter="/>";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.selfClosed={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{selfClosed:!0}})},e}}class Attr extends InlineRenderInlineChildren{static componentType="attr";static rendererType="c"}var ParagraphMarkup=Object.freeze({__proto__:null,Em:Em,Alert:Alert,Q:Q$2,SQ:SQ,Term:Term,C:C$2,Tag:Tag,Tage:Tage,Attr:Attr});class SingleCharacter extends InlineComponent{static componentType="_singleCharacterInline";static unicodeCharacter="";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({}),definition:()=>({setValue:{text:this.unicodeCharacter}})},e}}class Ndash extends SingleCharacter{static componentType="ndash";static unicodeCharacter="–"}class Mdash extends SingleCharacter{static componentType="mdash";static unicodeCharacter="—"}class NBSP extends SingleCharacter{static componentType="nbsp";static unicodeCharacter=" "}class Ellipsis extends SingleCharacter{static componentType="ellipsis";static unicodeCharacter="…"}var SingleCharacterComponents=Object.freeze({__proto__:null,Ndash:Ndash,Mdash:Mdash,NBSP:NBSP,Ellipsis:Ellipsis});class BlockComponent extends BaseComponent{static componentType="_block"}function returnDefaultFeedbackDefinitions(){return{numericalerror:"Credit reduced because numbers in your answer weren't quite right. Did you round too much?",goodjob:"Good job!",onesignerror:"Credit reduced because it appears that you made a sign error.",twosignerrors:"Credit reduced because it appears that you made two sign errors."}}function returnFeedbackDefinitionStateVariables(){let e={setupChildren:{returnDependencies:()=>({setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}}),definition:({dependencyValues:e})=>({setValue:{setupChildren:e.setupChildren}})}};return e.feedbackDefinitions={stateVariablesDeterminingDependencies:["setupChildren"],returnDependencies({stateValues:e}){let t={ancestorWithFeedback:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}};for(let n of e.setupChildren)t[`feedbackDefinitionsOf${n.componentName}`]={dependencyType:"child",parentName:n.componentName,childGroups:["feedbackDefinitions"],variableNames:["value"]};return t},definition({dependencyValues:e}){let t,n={};e.ancestorWithFeedback&&(t=e.ancestorWithFeedback.stateValues.feedbackDefinitions),t||(t=returnDefaultFeedbackDefinitions()),Object.assign(n,t);let r=[];for(let t of e.setupChildren)r.push(...e[`feedbackDefinitionsOf${t.componentName}`]);for(let e of r)Object.assign(n,e.stateValues.value);return{setValue:{feedbackDefinitions:n}}}},e}class SectioningComponent extends BlockComponent{static componentType="_sectioningComponent";static renderChildren=!0;static includeBlankStringChildren=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.aggregateScores={createComponentOfType:"boolean",createStateVariable:"aggregateScores",defaultValue:!1,public:!0},e.weight={createComponentOfType:"number",createStateVariable:"weight",defaultValue:1,public:!0},e.sectionWideCheckWork={createComponentOfType:"boolean",createStateVariable:"sectionWideCheckWork",defaultValue:!1,public:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0},e.boxed={createComponentOfType:"boolean",createStateVariable:"boxed",defaultValue:!1,public:!0,forRenderer:!0},e.suppressAutoName={createComponentOfType:"boolean",createStateVariable:"suppressAutoName",defaultValue:!1,public:!0},e.suppressAutoNumber={createComponentOfType:"boolean",createStateVariable:"suppressAutoNumber",defaultValue:!1,public:!0},e.includeAutoName={createComponentOfType:"boolean",createStateVariable:"includeAutoName",defaultValue:!1,public:!0},e.includeAutoNumber={createComponentOfType:"boolean",createStateVariable:"includeAutoNumber",defaultValue:!1,public:!0},e.includeAutoNameNumberIfNoTitle={createComponentOfType:"boolean",createStateVariable:"includeAutoNameNumberIfNoTitle",defaultValue:!0,public:!0},e.includeParentNumber={createComponentOfType:"boolean",createStateVariable:"includeParentNumber",defaultValue:!1,public:!0},e.level={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"variantControls",componentTypes:["variantControl"]},{group:"titles",componentTypes:["title"]},{group:"setups",componentTypes:["setup"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStyleDefinitionStateVariables();Object.assign(e,t);let n=returnFeedbackDefinitionStateVariables();return Object.assign(e,n),e.enumeration={additionalStateVariablesDefined:[{variableName:"sectionNumber",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies:()=>({countAmongSiblings:{dependencyType:"countAmongSiblingsOfSameType"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["enumeration"]},includeParentNumber:{dependencyType:"stateVariable",variableName:"includeParentNumber"}}),definition({dependencyValues:e}){let t=[];return e.includeParentNumber&&e.sectionAncestor&&t.push(...e.sectionAncestor.stateValues.enumeration),t.push(e.countAmongSiblings),{setValue:{enumeration:t,sectionNumber:t.join(".")}}}},e.sectionName={returnDependencies:()=>({}),definition:()=>({setValue:{sectionName:"Section"}})},e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[e.titleChild.length-1].componentName),{setValue:{titleChildName:t}}}},e.childIndicesToRender={returnDependencies:()=>({titleChildren:{dependencyType:"child",childGroups:["titles"]},allChildren:{dependencyType:"child",childGroups:["anything","variantControls","titles","setups"]},titleChildName:{dependencyType:"stateVariable",variableName:"titleChildName"}}),definition({dependencyValues:e}){let t=[],n=e.titleChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())"object"==typeof a&&n.includes(a.componentName)&&a.componentName!==e.titleChildName||t.push(r);return{setValue:{childIndicesToRender:t}}}},e.title={additionalStateVariablesDefined:[{variableName:"titlePrefix",forRenderer:!0,alwaysUpdateRenderer:!0}],public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,alwaysUpdateRenderer:!0,returnDependencies:({sharedParameters:e})=>({titleChild:{dependencyType:"child",childGroups:["titles"],variableNames:["text"]},sectionName:{dependencyType:"stateVariable",variableName:"sectionName"},sectionNumber:{dependencyType:"stateVariable",variableName:"sectionNumber"},includeAutoName:{dependencyType:"stateVariable",variableName:"includeAutoName"},includeAutoNumber:{dependencyType:"stateVariable",variableName:"includeAutoNumber"},prerender:{dependencyType:"value",value:e.prerender},includeAutoNameNumberIfNoTitle:{dependencyType:"stateVariable",variableName:"includeAutoNameNumberIfNoTitle"}}),definition({dependencyValues:e}){let t="",n="";const r=e.titleChild.length>0;let a=(e.includeAutoNumber||!r&&e.includeAutoNameNumberIfNoTitle)&&!e.prerender,i=e.includeAutoName||!r&&e.includeAutoNameNumberIfNoTitle;return a?(i&&(t=e.sectionName+" "),t+=e.sectionNumber):i&&(t=e.sectionName),r?(t&&(e.includeAutoName?t+=": ":t+=". "),n=e.titleChild[e.titleChild.length-1].stateValues.text):n=t,{setValue:{title:n,titlePrefix:t}}}},e.containerTag={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{containerTag:"section"}})},e.level={forRenderer:!0,returnDependencies:()=>({ancestorLevel:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["level"]},levelAttr:{dependencyType:"attributeComponent",attributeName:"level",variableNames:["value"]}}),definition({dependencyValues:e}){let t=e.levelAttr?.stateValues.value;return t>0||(t=(e.ancestorLevel?.stateValues.level||0)+1),{setValue:{level:t}}}},e.viewedSolution={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{viewedSolution:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"viewedSolution",value:e.viewedSolution}]})},e.scoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"descendant",componentTypes:["_sectioningComponent","answer","setup"],variableNames:["scoredDescendants","aggregateScores","weight"],recurseToMatchedChildren:!1,variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.scoredDescendants)"setup"!==n.componentType&&(n.stateValues.aggregateScores||void 0===n.stateValues.scoredDescendants?t.push(n):t.push(...n.stateValues.scoredDescendants));return{setValue:{scoredDescendants:t}}}},e.answerDescendants={returnDependencies:()=>({answerDescendants:{dependencyType:"descendant",componentTypes:["answer"],variableNames:["justSubmitted"],recurseToMatchedChildren:!1}}),definition:({dependencyValues:e})=>({setValue:{answerDescendants:e.answerDescendants}})},e.justSubmitted={forRenderer:!0,returnDependencies:()=>({answerDescendants:{dependencyType:"stateVariable",variableName:"answerDescendants"}}),definition:({dependencyValues:e})=>({setValue:{justSubmitted:e.answerDescendants.every((e=>e.stateValues.justSubmitted))}})},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition:({dependencyValues:e})=>({setValue:{showCorrectness:!1!==e.showCorrectnessFlag}})},e.displayDigitsForCreditAchieved={returnDependencies:()=>({}),definition:()=>({setValue:{displayDigitsForCreditAchieved:3}})},e.creditAchieved={public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},forRenderer:!0,defaultValue:0,hasEssential:!0,additionalStateVariablesDefined:[{variableName:"percentCreditAchieved",public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},defaultValue:0,hasEssential:!0}],stateVariablesDeterminingDependencies:["aggregateScores","scoredDescendants"],returnDependencies({stateValues:e}){let t={aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"}};if(e.aggregateScores){t.scoredDescendants={dependencyType:"stateVariable",variableName:"scoredDescendants"};for(let[n,r]of e.scoredDescendants.entries())t["creditAchieved"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchieved"}}return t},definition({dependencyValues:e}){if(!e.aggregateScores)return{setValue:{creditAchieved:0,percentCreditAchieved:0}};let t,n=0,r=0;for(let[t,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;n+=e["creditAchieved"+t]*i,r+=i}return t=r>0?n/r:1,{setValue:{creditAchieved:t,percentCreditAchieved:100*t}}}},e.creditAchievedIfSubmit={defaultValue:0,stateVariablesDeterminingDependencies:["aggregateScores","scoredDescendants"],returnDependencies({stateValues:e}){let t={aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"}};if(e.aggregateScores){t.scoredDescendants={dependencyType:"stateVariable",variableName:"scoredDescendants"};for(let[n,r]of e.scoredDescendants.entries())t["creditAchievedIfSubmit"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchievedIfSubmit"}}return t},definition({dependencyValues:e}){if(!e.aggregateScores)return{setValue:{creditAchievedIfSubmit:0}};let t=0,n=0;for(let[r,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;t+=e["creditAchievedIfSubmit"+r]*i,n+=i}return{setValue:{creditAchievedIfSubmit:t/n}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantIndex:{dependencyType:"value",value:e.variantIndex},variantName:{dependencyType:"value",value:e.variantName},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={};e.variantName?(n.index=e.variantIndex,n.name=e.variantName):n.seed=e.variantSeed,n.meta={createdBy:t};let r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e.collapsible={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{collapsible:!1}})},e.open={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{open:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"open",value:e.open}]})},e.createSubmitAllButton={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"suppressAnswerSubmitButtons",forRenderer:!0}],returnDependencies:()=>({sectionWideCheckWork:{dependencyType:"stateVariable",variableName:"sectionWideCheckWork"},aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["suppressAnswerSubmitButtons"]},documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["suppressAnswerSubmitButtons"]}}),definition({dependencyValues:e,componentName:t}){let n=!1,r=!1;return e.documentAncestor.stateValues.suppressAnswerSubmitButtons||e.sectionAncestor&&e.sectionAncestor.stateValues.suppressAnswerSubmitButtons?r=!0:e.sectionWideCheckWork&&(e.aggregateScores?(n=!0,r=!0):console.warn(`Cannot create submit all button for ${t} because it doesn't aggegrate scores`)),{setValue:{createSubmitAllButton:n,suppressAnswerSubmitButtons:r}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e}actions={submitAllAnswers:this.submitAllAnswers.bind(this),revealSection:this.revealSection.bind(this),closeSection:this.closeSection.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)};async submitAllAnswers({actionId:e}){this.coreFunctions.requestRecordEvent({verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType},result:{creditAchieved:await this.stateValues.creditAchievedIfSubmit}});for(let e of await this.stateValues.answerDescendants)await e.stateValues.justSubmitted||await this.coreFunctions.performAction({componentName:e.componentName,actionName:"submitAnswer"});this.coreFunctions.resolveAction({actionId:e})}async revealSection({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!0}],overrideReadOnly:!0,actionId:e,event:{verb:"viewed",object:{componentName:this.componentName,componentType:this.componentType}}})}async closeSection({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!1}],overrideReadOnly:!0,actionId:e,event:{verb:"closed",object:{componentName:this.componentName,componentType:this.componentType}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){if(!e.variants?.allPossibleVariants)return void setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0});let r,a=e.variants.numberOfVariants,i=e.variants.desiredVariant;if(void 0!==i&&void 0!==i.index){let e=Number(i.index);if(Number.isFinite(e)){Number.isInteger(e)||(console.warn("Variant index "+i.index+" must be an integer"),e=Math.round(e));let t=(e-1)%a;t<0&&(t+=a),r=t+1}else console.warn("Variant index "+i.index+" must be a number"),r=1}if(void 0===r){let e=t.variantRng();r=Math.floor(e*a)+1}if(t.allPossibleVariants=e.variants.allPossibleVariants,t.allVariantNames=e.variants.allVariantNames,t.variantSeed=e.variants.allPossibleVariantSeeds[r-1],t.variantIndex=r,t.variantName=e.variants.allPossibleVariants[r-1],t.uniqueIndex=e.variants.allPossibleVariantUniqueIndices[r-1],t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t})}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){if(!e.variants.allPossibleVariants)return super.getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n});let r=e.variants.allPossibleVariantUniqueIndices[t-1];if(void 0===r)return{success:!1};if(!e.variants.uniqueVariants)return{success:!0,desiredVariant:{index:t}};let a=getVariantsForDescendantsForUniqueVariants({variantIndex:r,serializedComponent:e,componentInfoObjects:n});return a.success?(e.variants.selectedUniqueVariant=!0,{success:!0,desiredVariant:{index:t,subvariants:a.desiredVariants}}):(console.log("Failed to get unique variant for section."),{success:!1})}}class Section extends SectioningComponent{static componentType="section";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.includeParentNumber.defaultValue=!0,e}}class Subsection extends Section{static componentType="subsection"}class Subsubsection extends Section{static componentType="subsubsection"}class Paragraphs extends SectioningComponent{static componentType="paragraphs";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.level.definition=()=>({setValue:{level:4}}),e.sectionName.definition=()=>({setValue:{sectionName:"Paragraphs"}}),e}}class Aside extends SectioningComponent{static componentType="aside";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.collapsible={createComponentOfType:"boolean",createStateVariable:"collapsible",defaultValue:!0,public:!0,forRenderer:!0},e.startOpen={createComponentOfType:"boolean",createStateVariable:"startOpen",defaultValue:!1},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.collapsible,e.open.returnDependencies=()=>({startOpen:{dependencyType:"stateVariable",variableName:"startOpen"}}),e.open.definition=({dependencyValues:e})=>({useEssentialOrDefaultValue:{open:{defaultValue:e.startOpen}}}),e.level.definition=()=>({setValue:{level:3}}),e.containerTag.definition=()=>({setValue:{containerTag:"aside"}}),e.sectionName.definition=()=>({setValue:{sectionName:"Aside"}}),e}}class Problem extends SectioningComponent{static componentType="problem";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.aggregateScores.defaultValue=!0,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Problem"}}),e}}class Exercise extends Problem{static componentType="exercise";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Exercise"}}),e}}class Example extends SectioningComponent{static componentType="example";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Example"}}),e}}class StandinForFutureLayoutTag extends SectioningComponent{static componentType="standinForFutureLayoutTag";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.level.definition=()=>({setValue:{level:3}}),e.containerTag.definition=()=>({setValue:{containerTag:"aside"}}),e}}class externalContent extends SectioningComponent{static componentType="externalContent";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.includeAutoNameNumberIfNoTitle.defaultValue=!1,e}}var Sectioning=Object.freeze({__proto__:null,Section:Section,Subsection:Subsection,Subsubsection:Subsubsection,Paragraphs:Paragraphs,Aside:Aside,Problem:Problem,Exercise:Exercise,Example:Example,StandinForFutureLayoutTag:StandinForFutureLayoutTag,externalContent:externalContent});class Ol extends BlockComponent{static componentType="ol";static rendererType="list";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.label={createComponentOfType:"text",createStateVariable:"label",defaultValue:null,public:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"lis",componentTypes:["li"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!0}})},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class Ul extends Ol{static componentType="ul";static rendererType="list";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!1}})},e}}class Li$1 extends BaseComponent{static componentType="li";static rendererType="list";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.item={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{item:!0}})},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={recordVisibilityChange:this.recordVisibilityChange.bind(this)}}var Lists=Object.freeze({__proto__:null,Ol:Ol,Ul:Ul,Li:Li$1});class ODESystem extends InlineComponent{static componentType="odesystem";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.independentVariable={createComponentOfType:"variable",createStateVariable:"independentVariable",defaultValue:me$3.fromAst("t"),public:!0},e.initialIndependentVariableValue={createComponentOfType:"math",createStateVariable:"initialIndependentVariableValue",defaultValue:me$3.fromAst(0),public:!0},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:14,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.renderMode={createComponentOfType:"text",createStateVariable:"renderMode",defaultValue:"align",public:!0,forRenderer:!0},e.chunkSize={createComponentOfType:"number",createStateVariable:"chunkSize",defaultValue:10,public:!0},e.tolerance={createComponentOfType:"number",createStateVariable:"tolerance",defaultValue:1e-6,public:!0},e.maxIterations={createComponentOfType:"number",createStateVariable:"maxIterations",defaultValue:1e3,public:!0},e.hideInitialCondition={createComponentOfType:"boolean",createStateVariable:"hideInitialCondition",defaultValue:!1,public:!0},e.initialConditions={createComponentOfType:"mathList"},e.variables={createComponentOfType:"variables"},e.number={createComponentOfType:"boolean",createStateVariable:"number",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"rightHandSides",componentTypes:["rightHandSide"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.validIndependentVariable={returnDependencies:()=>({independentVarAttr:{dependencyType:"attributeComponent",attributeName:"independentVariable",variableNames:["validVariable"]}}),definition({dependencyValues:e}){let t=!0;return e.independentVarAttr&&(t=e.independentVarAttr.stateValues.validVariable),{setValue:{validIndependentVariable:t}}}},e.nDimensions={returnDependencies:()=>({rhsChildren:{dependencyType:"child",childGroups:["rightHandSides"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nDimensions:e.rhsChildren.length},checkForActualChange:{nDimensions:!0}}}},e.variables={additionalStateVariablesDefined:[{variableName:"validVariables",isArray:!0,entryPrefixes:["validVar"]}],isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["var"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},variables:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables","validVariables"]},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=[],n=[],r=e.nDimensions;null!==e.variables&&(t=e.variables.stateValues.variables,n=[...e.variables.stateValues.validVariables].slice(0,r));let a=returnNVariables(r,t);return a.some((t=>t.equals(e.independentVariable)))&&console.warn("Variables of odesystem must be different than independent variable."),n.length({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={rhsChild:{dependencyType:"child",childGroups:["rightHandSides"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].rhsChild[0].stateValues.value;return{setValue:{rhss:n}}}},e.rhs={isAlias:!0,targetVariableName:"rhs1"},e.righthandside={isAlias:!0,targetVariableName:"rhs1"},e.righthandsides={isAlias:!0,targetVariableName:"rhss"},e.initialConditions={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["initialCondition"],defaultValueByArrayKey:()=>me$3.fromAst(0),returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={initialConditionAttr:{dependencyType:"attributeComponent",attributeName:"initialConditions",variableNames:[`math${Number(n)+1}`]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=!1;if(e[a].initialConditionAttr){let r=e[a].initialConditionAttr.stateValues[`math${Number(a)+1}`];void 0!==r&&(t=!0,n[a]=r)}t||(r[a]=!0)}let a={};return Object.keys(n).length>0&&(a.setValue={initialConditions:n}),Object.keys(r).length>0&&(a.useEssentialOrDefaultValue={initialConditions:r}),a}},e.initialCondition={isAlias:!0,targetVariableName:"initialCondition1"},e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["number"],returnDependencies:({stateValues:e})=>e.number?{equationCounter:{dependencyType:"counter",counterName:"equation"}}:{},definition:({dependencyValues:e})=>void 0!==e.equationCounter?{setValue:{equationTag:String(e.equationCounter)}}:{setValue:{equationTag:null}}},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},variables:{dependencyType:"stateVariable",variableName:"variables"},initialConditions:{dependencyType:"stateVariable",variableName:"initialConditions"},hideInitialCondition:{dependencyType:"stateVariable",variableName:"hideInitialCondition"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},initialIndependentVariableValue:{dependencyType:"stateVariable",variableName:"initialIndependentVariableValue"},rhss:{dependencyType:"stateVariable",variableName:"rhss"},number:{dependencyType:"stateVariable",variableName:"number"},equationTag:{dependencyType:"stateVariable",variableName:"equationTag"}}),definition({dependencyValues:e,usedDefault:t}){let n={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits));let r=[],a=e.independentVariable.toLatex();for(let i=0;i({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},e.numericalRHSf={additionalStateVariablesDefined:["numericalRHSfDefinitions"],returnDependencies:()=>({validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},rhss:{dependencyType:"stateVariable",variableName:"rhss"}}),definition({dependencyValues:e}){let t=!0;e.validIndependentVariable||(console.warn("Can't define ODE RHS functions with invalid independent variable."),t=!1),e.validVariables.every((e=>e))||(console.warn("Can't define ODE RHS functions with an invalid variable."),t=!1);let n,r=e.independentVariable.subscripts_to_strings().tree,a=e.variables.map((e=>e.subscripts_to_strings().tree));a.includes(r)&&(console.warn("Can't define ODE RHS functions when independent variable is a dependent variable"),t=!1),[...new Set(a)].length!==a.length&&(console.warn("Can't define ODE RHS functions with duplicate dependent variable names"),t=!1);try{n=e.rhss.map((e=>e.subscripts_to_strings().f()))}catch(e){console.warn("Cannot define ODE RHS function. Error creating mathjs function"),t=!1}if(!t){let t=e.rhss.length;return{setValue:{numericalRHSf:()=>NaN,numericalRHSfDefinitions:Array(t).fill({})}}}return{setValue:{numericalRHSf:function(e,t){let i={[r]:e};Array.isArray(t)?t.forEach(((e,t)=>i[a[t]]=e)):i[a[0]]=t;try{return n.map((e=>e(i)))}catch(e){return NaN}},numericalRHSfDefinitions:e.rhss.map((e=>({functionType:"formula",formula:e,nInputs:a.length+1,variables:[r,...a]})))}}}},e.haveNumericalInitialConditions={additionalStateVariablesDefined:["t0","x0s"],returnDependencies:()=>({initialIndependentVariableValue:{dependencyType:"stateVariable",variableName:"initialIndependentVariableValue"},initialConditions:{dependencyType:"stateVariable",variableName:"initialConditions"}}),definition({dependencyValues:e}){let t=e.initialIndependentVariableValue.evaluate_to_constant(),n=e.initialConditions.map((e=>e.evaluate_to_constant())),r=Number.isFinite(t)&&n.every((e=>Number.isFinite(e)));return{setValue:{t0:t,x0s:n,haveNumericalInitialConditions:r}}}},e.numericalSolutions={isArray:!0,entryPrefixes:["numericalSolution"],public:!0,shadowingInstructions:{createComponentOfType:"function",addStateVariablesShadowingStateVariables:{fDefinition:{stateVariableToShadow:"numericalSolutionFDefinitions"}}},createWorkspace:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},chunkSize:{dependencyType:"stateVariable",variableName:"chunkSize"},tolerance:{dependencyType:"stateVariable",variableName:"tolerance"},maxIterations:{dependencyType:"stateVariable",variableName:"maxIterations"},haveNumericalInitialConditions:{dependencyType:"stateVariable",variableName:"haveNumericalInitialConditions"},t0:{dependencyType:"stateVariable",variableName:"t0"},x0s:{dependencyType:"stateVariable",variableName:"x0s"},numericalRHSf:{dependencyType:"stateVariable",variableName:"numericalRHSf"}}}),arrayDefinitionByKey({globalDependencyValues:e,workspace:t,componentName:n}){let r={};if(t.calculatedNumericSolutions=[],t.endingNumericalValues=[],t.maxPossibleTime=void 0,!e.haveNumericalInitialConditions){for(let t=0;tNaN;return{setValue:{numericalSolutions:r}}}let a=e.t0,i=e.x0s,o=e.chunkSize,s=e.tolerance,l=e.numericalRHSf,u=e.maxIterations;for(let c=0;c=r)for(let e=r;e<=p;e++){let r=t.endingNumericalValues[e-1];void 0===r&&(r=i);let c=a+e*o,p=me$3.math.dopri(c,c+o,r,l,s,u);t.endingNumericalValues.push(p.y[p.y.length-1]),t.calculatedNumericSolutions.push(p.at.bind(p));let d=p.x[p.x.length-1];if(d<.999999*(c+o)){t.maxPossibleTime=d;let e="For chunksize "+o+" and tolerance "+s+", odesystem";void 0!==n&&(e+=" ("+n+")"),e+=" hit maxiterations ("+u+") at t = "+t.maxPossibleTime+". Will not calculate solution beyond that time. Decrease chunksize, increase maxiterations, or increase tolerance to calculate further.";break}}return e>t.maxPossibleTime?NaN:t.calculatedNumericSolutions[p](e)[c]};return{setValue:{numericalSolutions:r}}}},e.numericalSolution={isAlias:!0,targetVariableName:"numericalSolution1"},e.numericalSolutionFDefinitions={forRenderer:!0,isArray:!0,entryPrefixes:["numericalSolutionFDefinition"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},chunkSize:{dependencyType:"stateVariable",variableName:"chunkSize"},tolerance:{dependencyType:"stateVariable",variableName:"tolerance"},maxIterations:{dependencyType:"stateVariable",variableName:"maxIterations"},haveNumericalInitialConditions:{dependencyType:"stateVariable",variableName:"haveNumericalInitialConditions"},t0:{dependencyType:"stateVariable",variableName:"t0"},x0s:{dependencyType:"stateVariable",variableName:"x0s"},numericalRHSfDefinitions:{dependencyType:"stateVariable",variableName:"numericalRHSfDefinitions"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>e.haveNumericalInitialConditions?{setValue:{numericalSolutionFDefinitions:[...Array(e.nDimensions).keys()].map((t=>({functionType:"ODESolution",nDimensions:e.nDimensions,t0:e.t0,x0s:e.x0s,chunkSize:e.chunkSize,tolerance:e.tolerance,numericalRHSfDefinitions:e.numericalRHSfDefinitions,maxIterations:e.maxIterations,component:t})))}}:{setValue:{numericalSolutionFDefinitions:Array(e.nDimensions).fill({})}}},e}}class Polyline extends GraphicalComponent{static componentType="polyline";actions={movePolyline:this.movePolyline.bind(this),finalizePolylinePosition:this.finalizePolylinePosition.bind(this),polylineClicked:this.polylineClicked.bind(this)};static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.vertices={createComponentOfType:"_pointListComponent"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" polyline"}}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.vertices?{setValue:{nVertices:e.vertices.stateValues.nPoints}}:{setValue:{nVertices:0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.vertices){return{setValue:{nDimensions:e.vertices.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},getAllArrayKeys(e,t=!0,n){function r(e){if(1===e.length)return Array.from(Array(e[0]),((e,t)=>String(t)));{let n=e[0],a=r(e.slice(1)),i=[];for(let e=0;ee+","+t))):i.push(a.map((t=>e+","+t)));return i}}if(n){if(0!==n.length&&e){let t=[...e];return t[0]=n[0],r(t)}return[]}return e&&0!==e.length?r(e):[]},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),o=e[r].vertices;null!==o&&o.stateValues["pointX"+i]?n[r]=o.stateValues["pointX"+i]:n[r]=me$3.fromAst("_")}return{setValue:{vertices:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.vertices){let[a,o]=r.split(","),s=Number(a)+1+"_"+(Number(o)+1);if(null===t[r].vertices||!t[r].vertices.stateValues["pointX"+s])return{success:!1};i.push({setDependency:n[r].vertices,desiredValue:e.vertices[r],variableIndex:0})}return{success:!0,instructions:i}}},e.numericalVertices={isArray:!0,entryPrefixes:["numericalVertex"],forRenderer:!0,returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={vertex:{dependencyType:"stateVariable",variableName:"vertex"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalVertices:n}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,o=[],s=i[0]?.[0],l=i[0]?.[1];for(let e=1;e=1?{x1:f,x2:h}:{x1:l+b*a*n,x2:u+b*y*s};let g=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/s,2);g0&&(p.x3=0),p}}}}},e}async movePolyline({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){let a={};for(let t in e)a[t+",0"]=me$3.fromAst(e[t][0]),a[t+",1"]=me$3.fromAst(e[t][1]);return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],transient:t,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}async finalizePolylinePosition(){return await this.actions.movePolyline({pointCoords:await this.stateValues.numericalVertices,transient:!1})}async polylineClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class CobwebPolyline extends Polyline{static componentType="cobwebPolyline";static rendererType="cobwebPolyline";static createAttributesObject(){let e=super.createAttributesObject();return e.attractThreshold={createComponentOfType:"number",createStateVariable:"attractThreshold",defaultValue:.5,public:!0},e.nPoints={createComponentOfType:"number",createStateVariable:"nPoints",defaultValue:1,public:!0,clamp:[0,1/0],forRenderer:!0},e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x"),public:!0,forRenderer:!0},e.nIterationsRequired={createComponentOfType:"number",createStateVariable:"nIterationsRequired",defaultValue:0,public:!0},e.initialPoint={createComponentOfType:"point"},e.function={createComponentOfType:"function"},e.lockToSolution={createComponentOfType:"boolean",createStateVariable:"lockToSolution",defaultValue:!1},e.defaultPoint={createComponentOfType:"point"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nDimensions.returnDependencies=()=>({}),e.nDimensions.definition=()=>({setValue:{nDimensions:2}}),e.initialPoint={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"initialPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["initialPointX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={initialPointAttr:{dependencyType:"attributeComponent",attributeName:"initialPoint",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=Number(a)+1;e[a].initialPointAttr?n[a]=e[a].initialPointAttr.stateValues["x"+t]:r[a]=!0}let a={};return Object.keys(n).length>0&&(a.setValue={initialPoint:n}),Object.keys(r).length>0&&(a.useEssentialOrDefaultValue={initialPoint:r}),a},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.initialPoint)t[a].initialPointAttr&&t[a].initialPointAttr.stateValues["x"+(Number(a)+1)]?r.push({setDependency:n[a].initialPointAttr,desiredValue:e.initialPoint[a],variableIndex:0}):r.push({setEssentialValue:"initialPoint",value:{[a]:e.initialPoint[a]}});return{success:!0,instructions:r}}},e.f={additionalStateVariablesDefined:[{variableName:"fDefinition",forRenderer:!0}],returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["numericalf","fDefinition"]}}),definition:({dependencyValues:e})=>e.functionAttr?{setValue:{f:e.functionAttr.stateValues.numericalf,fDefinition:e.functionAttr.stateValues.fDefinition}}:{setValue:{f:null,fDefinition:null}}},e.nVertices={isAlias:!0,targetVariableName:"nPoints"},e.nOriginalVertices={providePreviousValuesInDefinition:!0,returnDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e,previousValues:t}){let n=e.nVertices;return t.nOriginalVertices>n&&(n=t.nOriginalVertices),{setValue:{nOriginalVertices:n}}}},e.originalVertices={isArray:!0,nDimensions:2,hasEssential:!0,entryPrefixes:["originalVertexX","originalVertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("originalVertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("originalVertices"===t)return 1===e.length?"originalVertex"+e[0]:`originalVertexX${e[0]}_${e[1]}`;if("originalVertex"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`originalVertexX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nOriginalVertices:{dependencyType:"stateVariable",variableName:"nOriginalVertices"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nOriginalVertices-1,e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},defaultPoint:{dependencyType:"attributeComponent",attributeName:"defaultPoint",variableNames:["xs"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",").map(Number);n[r]={get defaultValue(){if(e.defaultPoint){let n=e.defaultPoint.stateValues.xs;if(2===n.length&&t[1]<2)return n[t[1]]}if(e.graphAncestor){if(0===t[1]){let t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax;return me$3.fromAst((t+n)/2)}if(1===t[1]){let t=e.graphAncestor.stateValues.ymin,n=e.graphAncestor.stateValues.ymax;return me$3.fromAst((t+n)/2)}}return me$3.fromAst(0)}}}return{useEssentialOrDefaultValue:{originalVertices:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.originalVertices)t.push({setEssentialValue:"originalVertices",value:{[n]:e.originalVertices[n]}});return{success:!0,instructions:t}}},e.vertices.additionalStateVariablesDefined=[{variableName:"prelimCorrectVertices",entryPrefixes:["prelimCorrectVertexX","prelimCorrectVertex"],getArrayKeysFromVarName:function({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("prelimCorrectVertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}}}],e.vertices.basedOnArrayKeyStateVariables=!0,e.vertices.returnArrayDependenciesByKey=function({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]="0"===e?{initialPoint:{dependencyType:"stateVariable",variableName:"initialPointX"+(Number(r)+1)}}:{originalVertexX1:{dependencyType:"stateVariable",variableName:"originalVertexX"+e+"_1"},originalVertexX2:{dependencyType:"stateVariable",variableName:"originalVertexX"+e+"_2"},previousVertexX1:{dependencyType:"stateVariable",variableName:"vertexX"+e+"_1"},previousVertexX2:{dependencyType:"stateVariable",variableName:"vertexX"+e+"_2"}}}return{globalDependencies:{f:{dependencyType:"stateVariable",variableName:"f"},attractThreshold:{dependencyType:"stateVariable",variableName:"attractThreshold"},lockToSolution:{dependencyType:"stateVariable",variableName:"lockToSolution"}},dependenciesByKey:t}},e.vertices.arrayDefinitionByKey=function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let[n,o]=i.split(",");if("0"===n)r[i]=t[i].initialPoint,a[i]=null;else{let o,s,l;try{o=[t[i].originalVertexX1.evaluate_to_constant(),t[i].originalVertexX2.evaluate_to_constant()],s=[t[i].previousVertexX1.evaluate_to_constant(),t[i].previousVertexX2.evaluate_to_constant()]}catch(e){r[n+",0"]=me$3.fromAst(0),r[n+",1"]=me$3.fromAst(0),a[n+",0"]=!1;continue}if(Number(n)%2==1){let t=e.f(s[0]);l=[s[0],t]}else l=[s[1],s[1]];Math.pow(o[0]-l[0],2)+Math.pow(o[1]-l[1],2)({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices-1],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={prelimCorrectVertex:{dependencyType:"stateVariable",variableName:"prelimCorrectVertexX"+(Number(n)+2)+"_1"}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].prelimCorrectVertex;return{setValue:{correctVertices:n}}}},e.fractionCorrectVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"nGradedVertices",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"nCorrectVertices",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({correctVertices:{dependencyType:"stateVariable",variableName:"correctVertices"}}),definition({dependencyValues:e}){let t,n,r=e.correctVertices.length;return 0===r?(t=0,n=0):(n=e.correctVertices.reduce(((e,t)=>e+t),0),t=n/r),{setValue:{fractionCorrectVertices:t,nGradedVertices:r,nCorrectVertices:n}}}},e.fractionCorrectVerticesAdjusted={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"nGradedVerticesAdjusted",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({nCorrectVertices:{dependencyType:"stateVariable",variableName:"nCorrectVertices"},nGradedVertices:{dependencyType:"stateVariable",variableName:"nGradedVertices"},nIterationsRequired:{dependencyType:"stateVariable",variableName:"nIterationsRequired"}}),definition({dependencyValues:e}){let t=0;e.nIterationsRequired>0&&(t=2*e.nIterationsRequired-1);let n,r=Math.max(e.nGradedVertices,t);return n=0===r?0:e.nCorrectVertices/r,{setValue:{fractionCorrectVerticesAdjusted:n,nGradedVerticesAdjusted:r}}}},e.nIterateValues={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition:({dependencyValues:e})=>({setValue:{nIterateValues:Math.ceil((e.nVertices+1)/2)}})},e.iterateValues={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["iterateValue"],returnArraySizeDependencies:()=>({nIterateValues:{dependencyType:"stateVariable",variableName:"nIterateValues"}}),returnArraySize:({dependencyValues:e})=>[e.nIterateValues],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]="0"===n?{iterateValue:{dependencyType:"stateVariable",variableName:"vertexX1_1"}}:{iterateValue:{dependencyType:"stateVariable",variableName:"vertexX"+2*Number(n)+"_2"}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].iterateValue;return{setValue:{iterateValues:n}}}},e}}class Point extends GraphicalComponent{static componentType="point";static primaryStateVariableForDefinition="coordsShadow";static stateVariableForAttributeValue="coords";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.x={createComponentOfType:"math"},e.y={createComponentOfType:"math"},e.z={createComponentOfType:"math"},e.xs={createComponentOfType:"mathList"},e.coords={createComponentOfType:"coords"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.showCoordsWhenDragging={createComponentOfType:"boolean",createStateVariable:"showCoordsWhenDragging",defaultValue:!0,public:!0,forRenderer:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),r=e.map((e=>typeof e)),a=r.indexOf("string"),i=r.lastIndexOf("string");if(-1===a){let n=t.componentIsSpecifiedType,r=e.filter((e=>!(n(e,"point")||n(e,"vector")||n(e,"constraints")||n(e,"label"))));if(1===r.length){let t=r[0],n=e.indexOf(t);return{success:!0,newAttributes:{coords:{component:{componentType:"math",children:r}}},newChildren:[...e.slice(0,n),...e.slice(n+1)]}}return{success:!1}}let o=[...e.slice(0,a),...e.slice(i+1)],s=n({matchedChildren:e=e.slice(a,i+1)});return s.success||1!==e.length?s.success?{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:s.newChildren,skipSugar:!0}}},newChildren:o}:{success:!1}:{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:[{componentType:"math",children:e}]}}},newChildren:o}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"points",componentTypes:["point"]},{group:"vectors",componentTypes:["vector"]},{group:"constraints",componentTypes:["constraints"]}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescription:e.selectedStyle.markerColorWord}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.selectedStyle.markerColorWord+" "+e.selectedStyle.markerStyleWord}}}},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{coordsShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e,stateValues:t,workspace:n}){return{success:!0,instructions:[{setEssentialValue:"coordsShadow",value:e.coordsShadow}]}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({coordsShadow:{dependencyType:"stateVariable",variableName:"coordsShadow"},coords:{dependencyType:"attributeComponent",attributeName:"coords",variableNames:["value"]},x:{dependencyType:"attributeComponent",attributeName:"x"},y:{dependencyType:"attributeComponent",attributeName:"y"},z:{dependencyType:"attributeComponent",attributeName:"z"},xs:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["nComponents"]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){let t,n,r=!1;if(n=null!==e.z?3:null!==e.y?2:0,null!==e.coords?(r=!0,t=e.coords.stateValues.value):e.coordsShadow&&(r=!0,t=e.coordsShadow),r){let e=t.tree;return n=Array.isArray(e)&&["tuple","vector"].includes(e[0])?Math.max(e.length-1,n):Math.max(1,n),{setValue:{nDimensions:n},checkForActualChange:{nDimensions:!0}}}return null!==e.xs?{setValue:{nDimensions:Math.max(e.xs.stateValues.nComponents,n)}}:e.pointChild.length>0?{setValue:{nDimensions:Math.max(e.pointChild[0].stateValues.nDimensions,n)}}:e.vectorChild.length>0?{setValue:{nDimensions:Math.max(e.vectorChild[0].stateValues.nDimensions,n)}}:(0===n&&(n=2),{setValue:{nDimensions:n},checkForActualChange:{nDimensions:!0}})}},e.arrayVariableForConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{arrayVariableForConstraints:"unconstrainedXs"}})},e.arrayEntryPrefixForConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{arrayEntryPrefixForConstraints:"unconstrainedX"}})},e.nDimensionsForConstraints={isAlias:!0,targetVariableName:"nDimensions"},e.unconstrainedXs={isArray:!0,entryPrefixes:["unconstrainedX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={xs:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["math"+e]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+e]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+e]}},"0"===n?t[n].component={dependencyType:"attributeComponent",attributeName:"x",variableNames:["value"]}:"1"===n?t[n].component={dependencyType:"attributeComponent",attributeName:"y",variableNames:["value"]}:"2"===n&&(t[n].component={dependencyType:"attributeComponent",attributeName:"z",variableNames:["value"]})}return{globalDependencies:{coordsShadow:{dependencyType:"stateVariable",variableName:"coordsShadow"},coords:{dependencyType:"attributeComponent",attributeName:"coords",variableNames:["value"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r,a={},i={},o=!1;if(null!==e.coords?(o=!0,r=e.coords.stateValues.value):e.coordsShadow&&(o=!0,r=e.coordsShadow),o){let e=r.tree;if(Array.isArray(e)&&["tuple","vector"].includes(e[0]))for(let t of n){let n=Number(t);(n>=0||n0)a[e]=r[0].stateValues["x"+n];else{let r=t[e].vectorChild;r.length>0&&(a[e]=r[0].stateValues["x"+n])}}}for(let e of n){let n=t[e].component;n?a[e]=n.stateValues.value.simplify():void 0===a[e]&&(i[e]=!0)}let s={};return Object.keys(a).length>0&&(s.setValue={unconstrainedXs:a}),Object.keys(i).length>0&&(s.useEssentialOrDefaultValue={unconstrainedXs:i}),s},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i,o,s=[],l=!1,u=!1;null!==t.coords?(l=!0,i="coords",o=Array(a[0]+1)):null!==t.coordsShadow&&(l=!0,i="coordsShadow",o=Array(a[0]+1));for(let t of Object.keys(e.unconstrainedXs).reverse()){let a=convertValueToMathExpression(e.unconstrainedXs[t]);if(null!==n[t].component)s.push({setDependency:r[t].component,desiredValue:a,childIndex:0,variableIndex:0});else if(l)o[Number(t)+1]=a.tree,u=!0;else{if(null!==n[t].xs)s.push({setDependency:r[t].xs,desiredValue:a,childIndex:0,variableIndex:0});else{if(n[t].pointChild.length>0)s.push({setDependency:r[t].pointChild,desiredValue:a,childIndex:0,variableIndex:0});else{n[t].vectorChild.length>0?s.push({setDependency:r[t].vectorChild,desiredValue:a,childIndex:0,variableIndex:0}):s.push({setEssentialValue:"unconstrainedXs",value:{[t]:a}})}}}}if(u){let e;1===a[0]?e=me$3.fromAst(o[1]):(o[0]="vector",e=me$3.fromAst(o));let t={setDependency:i,desiredValue:e};"coords"===i&&(t.childIndex=0,t.variableIndex=0),s.push(t)}return{success:!0,instructions:s}}},e.xs={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["x"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1,r={};r.unconstrainedX={dependencyType:"stateVariable",variableName:`unconstrainedX${e}`},r.constraintsChild={dependencyType:"child",childGroups:["constraints"],variableNames:[`constraintResult${e}`]},t[n]=r}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)if(e[r].constraintsChild.length>0){let t=Number(r)+1;n[r]=convertValueToMathExpression(e[r].constraintsChild[0].stateValues["constraintResult"+t])}else n[r]=convertValueToMathExpression(e[r].unconstrainedX);return t.length>0?{setValue:{xs:n}}:{}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r of Object.keys(e.xs).reverse())t[r]&&(t[r].constraintsChild.length>0?i.push({setDependency:n[r].constraintsChild,desiredValue:e.xs[r],childIndex:0,variableIndex:0}):i.push({setDependency:n[r].unconstrainedX,desiredValue:e.xs[r]}));return{success:!0,instructions:i}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.coords={public:!0,shadowingInstructions:{createComponentOfType:"coords",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({xs:{dependencyType:"stateVariable",variableName:"xs"}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.xs)n?t.push(n.tree):t.push("_");return t=t.length>1?["vector",...t]:1===t.length?t[0]:"_",{setValue:{coords:me$3.fromAst(t)}}},inverseDefinition:async function({desiredStateVariableValues:e,stateValues:t,initialChange:n}){if(n&&!await t.draggable)return{success:!1};let r=[],a={},i=e.coords.tree;if(Array.isArray(i)&&["tuple","vector"].includes(i[0]))for(let t=0;t({coords:{dependencyType:"stateVariable",variableName:"coords"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.coords,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.value={isAlias:!0,targetVariableName:"coords"},e.constraintUsed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({constraintsChild:{dependencyType:"child",childGroups:["constraints"],variableNames:["constraintUsed"]}}),definition:function({dependencyValues:e}){return 0===e.constraintsChild.length?{setValue:{constraintUsed:!1}}:{setValue:{constraintUsed:e.constraintsChild[0].stateValues.constraintUsed}}}},e.numericalXs={isArray:!0,entryPrefixes:["numericalX"],forRenderer:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={x:{dependencyType:"stateVariable",variableName:`x${e}`}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].x;t?(t=e[r].x.evaluate_to_constant(),Number.isFinite(t)?n[r]=t:n[r]=NaN):n[r]=NaN}return{setValue:{numericalXs:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,initialChange:n,stateValues:r}){if(n&&!await r.draggable)return{success:!1};let a=[];for(let n in e.numericalXs)dependencyValuesByKey[n]&&a.push({setDependency:t[n].xs,desiredValue:e.numericalXs[n]});return{success:!0,instructions:a}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalXs:{dependencyType:"stateVariable",variableName:"numericalXs"}}),definition:({dependencyValues:e})=>({setValue:{nearestPoint:function(){let t={};for(let n=1;n<=e.nDimensions;n++){let r=e.numericalXs[n-1];if(!Number.isFinite(r))return{};t["x"+n]=r}return t}}})},e}static adapters=[{stateVariable:"coords",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async movePoint({x:e,y:t,z:n,transient:r,actionId:a}){let i={};return void 0!==e&&(i[0]=me$3.fromAst(e)),void 0!==t&&(i[1]=me$3.fromAst(t)),void 0!==n&&(i[2]=me$3.fromAst(n)),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"xs",value:i}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"xs",value:i}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}switchPoint(){}async pointClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}actions={movePoint:this.movePoint.bind(this),switchPoint:this.switchPoint.bind(this),pointClicked:this.pointClicked.bind(this)}}class EquilibriumPoint extends Point{static componentType="equilibriumPoint";static rendererType="point";static createAttributesObject(){let e=super.createAttributesObject();return e.stable={createComponentOfType:"boolean",createStateVariable:"stable",defaultValue:!0,public:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.open={forRenderer:!0,returnDependencies:()=>({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{open:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.open}]})},e}async switchPoint({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}class Line extends GraphicalComponent{static componentType="line";actions={moveLine:this.moveLine.bind(this),switchLine:this.switchLine.bind(this),lineClicked:this.lineClicked.bind(this)};static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.equation={createComponentOfType:"math"},e.through={createComponentOfType:"_pointListComponent"},e.slope={createComponentOfType:"number"},e.variables={createComponentOfType:"variables"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){if(0===e.length)return{success:!1};let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a.push(...e.slice(0,t)),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),a.push(...e.slice(t)))}return 0===r.length?{success:!1}:{success:!0,newAttributes:{equation:{component:{componentType:"math",children:r}}},newChildren:a}}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" line"}}}},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null===e.throughAttr?{setValue:{nPointsPrescribed:0}}:{setValue:{nPointsPrescribed:e.throughAttr.stateValues.nPoints}}}},e.basedOnSlope={returnDependencies:()=>({slopeAttr:{dependencyType:"attributeComponent",attributeName:"slope"},nPointsPrescribed:{dependencyType:"stateVariable",variableName:"nPointsPrescribed"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition:({dependencyValues:e})=>({setValue:{basedOnSlope:e.nPointsPrescribed<2&&null!==e.slopeAttr&&2===e.nDimensions}})},e.dForSlope={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{dForSlope:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"dForSlope",value:e.dForSlope}]})},e.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["var"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{variables:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n=[];return null!==e.variables&&(n=e.variables.stateValues.variables),{setValue:{variables:returnNVariables(t[0],n)}}}},e.equationIdentity={returnDependencies:()=>({equation:{dependencyType:"attributeComponent",attributeName:"equation"}}),definition:function({dependencyValues:e}){return null!==e.equation?{setValue:{equationIdentity:e.equation}}:{setValue:{equationIdentity:null}}}},e.essentialPoints={isArray:!0,nDimensions:"2",hasEssential:!0,entryPrefixes:["essentialPointX","essentialPoint"],set:convertValueToMathExpression,defaultValueByArrayKey:e=>me$3.fromAst("0,0"===e?1:0),getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("essentialPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialPoints:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.essentialPoints)t.push({setEssentialValue:"essentialPoints",value:{[n]:convertValueToMathExpression(e.essentialPoints[n])}});return{success:!0,instructions:t}}},e.points={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"pointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("points"===t)return 1===e.length?"point"+e[0]:`pointX${e[0]}_${e[1]}`;if("point"===t.slice(0,5)){let n=Number(t.slice(5));if(Number.isInteger(n)&&n>0)return`pointX${n}_${e[0]}`}return null},stateVariablesDeterminingDependencies:["equationIdentity","nPointsPrescribed","basedOnSlope"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey({stateValues:e,arrayKeys:t}){if(null===e.equationIdentity){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1);n[r]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+i]}},e.basedOnSlope?("1"===t&&(1===e.nPointsPrescribed&&n[r].through.variableNames.push("pointX1_"+(Number(a)+1)),n[r].dForSlope={dependencyType:"stateVariable",variableName:"dForSlope"},n[r].slopeAttr={dependencyType:"attributeComponent",attributeName:"slope",variableNames:["value"]}),0===e.nPointsPrescribed&&(n[r].essentialPoint={dependencyType:"stateVariable",variableName:"essentialPointX2_"+(Number(a)+1)})):n[r].essentialPoint={dependencyType:"stateVariable",variableName:"essentialPointX"+i}}return{dependenciesByKey:n,globalDependencies:{nPointsPrescribed:{dependencyType:"stateVariable",variableName:"nPointsPrescribed"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},basedOnSlope:{dependencyType:"stateVariable",variableName:"basedOnSlope"}}}}return{globalDependencies:{coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"},variables:{dependencyType:"stateVariable",variableName:"variables"},lastPointsFromInverting:{dependencyType:"stateVariable",variableName:"lastPointsFromInverting"}}}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r,componentName:a}){if("coeff0"in e){let t=calculatePointsFromCoeffs(e);if(t.success)return{setValue:{points:t.points}};{let e={};for(let t=0;te.toString()))];for(let e=0;e({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>Number.isNaN(e.nDimensions)?[0]:[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={point:{dependencyType:"stateVariable",variableName:"point"+(Number(n)+1)}};return{globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentName:r}){if(Number.isNaN(e.nDimensions))return{};let a={};for(let r of n){let n=t[r].point;Array.isArray(n)||(n=[n]);let i=[];for(let t=0;t({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:function({dependencyValues:e}){let t=e.coeff0.evaluate_to_constant();Number.isFinite(t)||(t=NaN);let n=e.coeffvar1.evaluate_to_constant();Number.isFinite(n)||(n=NaN);let r=e.coeffvar2.evaluate_to_constant();return Number.isFinite(r)||(r=NaN),{setValue:{numericalCoeff0:t,numericalCoeffvar1:n,numericalCoeffvar2:r}}}},e.slope={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:function({dependencyValues:e}){return{setValue:{slope:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeffvar1,b:e.coeffvar2}).simplify()}}}},e.xintercept={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"}}),definition:({dependencyValues:e})=>({setValue:{xintercept:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeff0,b:e.coeffvar1}).simplify()}})},e.yintercept={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:({dependencyValues:e})=>({setValue:{yintercept:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeff0,b:e.coeffvar2}).simplify()}})},e.lastPointsFromInverting={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{lastPointsFromInverting:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"lastPointsFromInverting",value:e.lastPointsFromInverting}]})},e.latex={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({equation:{dependencyType:"stateVariable",variableName:"equation"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.equation,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalCoeff0:{dependencyType:"stateVariable",variableName:"numericalCoeff0"},numericalCoeffvar1:{dependencyType:"stateVariable",variableName:"numericalCoeffvar1"},numericalCoeffvar2:{dependencyType:"stateVariable",variableName:"numericalCoeffvar2"}}),definition({dependencyValues:e}){let t=e.numericalCoeffvar1,n=e.numericalCoeffvar2,r=e.numericalCoeff0,a=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r),i=2!==e.nDimensions||!a||0===t&&0===n;return{setValue:{nearestPoint:function({variables:e,scales:a=[1,1]}){if(i)return{};let o=a[0],s=a[1],l=t*o,u=n*s,c=l*l+u*u,p=e.x1?.evaluate_to_constant(),d=e.x2?.evaluate_to_constant();if(!Number.isFinite(p)||!Number.isFinite(d))return{};let m=p/o,f=d/s,h={};return h.x1=(u*(u*m-l*f)-l*r)*o/c,h.x2=(l*(-u*m+l*f)-u*r)*s/c,void 0!==e.x3&&(h.x3=0),h}}}}},e}static adapters=[{stateVariable:"equation",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async moveLine({point1coords:e,point2coords:t,transient:n,actionId:r}){let a={"0,0":me$3.fromAst(e[0]),"0,1":me$3.fromAst(e[1])};return await this.stateValues.basedOnSlope||(a["1,0"]=me$3.fromAst(t[0]),a["1,1"]=me$3.fromAst(t[1])),n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"points",value:a}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"points",value:a}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{point1:e,point2:t}}})}switchLine(){}async lineClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}function calculateCoeffsFromEquation({equation:e,variables:t}){let n=t[0],r=t[1],a=n.toString(),i=r.toString();if(e=e.expand().simplify(),!Array.isArray(e.tree)||"="!==e.tree[0]||3!==e.tree.length)return{success:!1};let o=me$3.fromAst(["+",e.tree[2],["-",e.tree[1]]]).expand().simplify(),s=[];s=Array.isArray(o.tree)&&"+"===o.tree[0]?o.tree.slice(1):[o.tree];let l=me$3.fromAst(0),u=me$3.fromAst(0),c=me$3.fromAst(0);for(let e of s){let t=p(e);if(!t.success)return{success:!1};l=l.add(t.coeffvar1),u=u.add(t.coeffvar2),c=c.add(t.coeff0)}return l=l.simplify(),u=u.simplify(),c=c.simplify(),{success:!0,coeff0:c,coeffvar1:l,coeffvar2:u};function p(e){let t=0,o=0,s=0;if("string"==typeof e)e===a?t=1:e===i?o=1:s=e;else if("number"==typeof e)s=e;else{if(!Array.isArray(e))return console.warn("Invalid format for equation of line in variables "+n+" and "+r),{success:!1};{let a=e[0],i=e.slice(1);if("-"===a){let e=p(i[0]);if(!e.success)return{success:!1};t=["-",e.coeffvar1.tree],o=["-",e.coeffvar2.tree],s=["-",e.coeff0.tree]}else{if("+"===a)return console.warn("Invalid format for equation of line in variables "+n+" and "+r),{success:!1};if("*"===a){let a=-1,l=-1;for(let e=0;e({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{dashed:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.dashed}]})},e}async switchLine({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}class Curve extends GraphicalComponent{static componentType="curve";static rendererType="curve";actions={moveControlVector:this.moveControlVector.bind(this),moveThroughPoint:this.moveThroughPoint.bind(this),changeVectorControlDirection:this.changeVectorControlDirection.bind(this),switchCurve:this.switchCurve.bind(this),curveClicked:this.curveClicked.bind(this)};static primaryStateVariableForDefinition="fShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.flipFunction={createComponentOfType:"boolean",createStateVariable:"flipFunction",defaultValue:!1,public:!0,forRenderer:!0},e.nDiscretizationPoints={createComponentOfType:"number",createStateVariable:"nDiscretizationPoints",defaultValue:1e3,public:!0},e.periodic={createComponentOfType:"boolean",createStateVariable:"periodic",defaultValue:!1,public:!0},e.splineTension={createComponentOfType:"number",createStateVariable:"splineTension",defaultValue:.8,clamp:[0,1],public:!0},e.extrapolateBackward={createComponentOfType:"boolean",createStateVariable:"extrapolateBackward",defaultValue:!1,public:!0,forRenderer:!0},e.extrapolateForward={createComponentOfType:"boolean",createStateVariable:"extrapolateForward",defaultValue:!1,public:!0,forRenderer:!0},e.splineForm={createComponentOfType:"text",createStateVariable:"splineForm",defaultValue:"centripetal",public:!0,toLowerCase:!0,validValues:["centripetal","uniform"]},e.variable={createComponentOfType:"variable",createStateVariable:"variableForChild",defaultValue:me$3.fromAst("x")},e.through={createComponentOfType:"_pointListComponent"},e.parMin={createComponentOfType:"math"},e.parMax={createComponentOfType:"math"},e.nearestPointAsCurve={createComponentOfType:"boolean",createStateVariable:"nearestPointAsCurvePrelim",defaultValue:!1},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e=>t.componentIsSpecifiedType(e,"label");if(0===e.length||!e.every((e=>"string"==typeof e||e.doenetAttributes?.createdFromMacro||n(e))))return{success:!1};let r=e.map(n),a=[],i=[],o=[];if(0===r.filter((e=>e)).length)a=e;else{if(r[0]){let t=r.indexOf(!1);-1!==t&&(i=e.slice(0,t),e=e.slice(t),r=r.slice(t))}let t=r.indexOf(!0);-1===t?a=e:(a=e.slice(0,t),o=e.slice(t))}if(0===a.length)return{success:!1};let s=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"function",children:e}),mustStripOffOuterParentheses:!0}),l=s({matchedChildren:a}),u=[];return u=l.success?l.newChildren:[{componentType:"function",children:a}],{success:!0,newChildren:[...i,...u,...o]}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"functions",componentTypes:["function"]},{group:"bezierControls",componentTypes:["bezierControls"]}),e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" curve"}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({functionChildren:{dependencyType:"child",childGroups:["functions"]},through:{dependencyType:"attributeComponent",attributeName:"through"}}),definition({dependencyValues:e}){let t="function";return null!==e.through?t="bezier":e.functionChildren.length>1&&(t="parameterization"),{setValue:{curveType:t}}}},t.fShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{fShadow:!0}})},t.graphXmin={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"graphXmax",forRenderer:!0},{variableName:"graphYmin",forRenderer:!0},{variableName:"graphYmax",forRenderer:!0}],returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>e.graphAncestor?{setValue:{graphXmin:e.graphAncestor.stateValues.xmin,graphXmax:e.graphAncestor.stateValues.xmax,graphYmin:e.graphAncestor.stateValues.ymin,graphYmax:e.graphAncestor.stateValues.ymax}}:{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}}},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},parMaxAttr:{dependencyType:"attributeComponent",attributeName:"parMax",variableNames:["value"]},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},adapterSourceDomain:{dependencyType:"adapterSourceStateVariable",variableName:"domain"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"}}),definition:function({dependencyValues:e}){let t;if("bezier"===e.curveType)t=e.nThroughPoints-1,e.extrapolateForward&&(t*=2);else if(null!==e.parMaxAttr)t=e.parMaxAttr.stateValues.value.evaluate_to_constant(),Number.isFinite(t)||(t=NaN);else if("function"===e.curveType){let n,r,a=null;if(a=1===e.functionChild.length?e.functionChild[0].stateValues.domain:e.adapterSourceDomain,null!==a){a=a[0];try{t=me$3.fromAst(a.tree[1][2]).evaluate_to_constant(),Number.isFinite(t)||t===1/0||(t=NaN)}catch(e){}}e.flipFunction?(r=e.graphYmax,n=e.graphYmin):(r=e.graphXmax,n=e.graphXmin),null!==r&&null!==n&&(t=void 0===t?r+.1*(r-n):Math.min(t,r+.1*(r-n))),void 0===t&&(t=1/0)}else t=10;return{setValue:{parMax:t}}}},t.parMin={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},parMinAttr:{dependencyType:"attributeComponent",attributeName:"parMin",variableNames:["value"]},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},adapterSourceDomain:{dependencyType:"adapterSourceStateVariable",variableName:"domain"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"}}),definition:function({dependencyValues:e}){let t;if("bezier"===e.curveType)t=0,e.extrapolateBackward&&(t=-(e.nThroughPoints-1));else if(null!==e.parMinAttr)t=e.parMinAttr.stateValues.value.evaluate_to_constant(),Number.isFinite(t)||(t=NaN);else if("function"===e.curveType){let n,r,a=null;if(a=1===e.functionChild.length?e.functionChild[0].stateValues.domain:e.adapterSourceDomain,null!==a){a=a[0];try{t=me$3.fromAst(a.tree[1][1]).evaluate_to_constant(),Number.isFinite(t)||t===-1/0||(t=NaN)}catch(e){}}e.flipFunction?(r=e.graphYmax,n=e.graphYmin):(r=e.graphXmax,n=e.graphXmin),null!==r&&null!==n&&(t=void 0===t?n+.1*(n-r):Math.max(t,n+.1*(n-r))),void 0===t&&(t=-1/0)}else t=-10;return{setValue:{parMin:t}}}},t.nThroughPoints={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition({dependencyValues:e}){let t=0;return null!==e.through&&(t=e.through.stateValues.nPoints),{setValue:{nThroughPoints:t}}}},t.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.through){return{setValue:{nDimensions:e.through.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),o=e[r].through;null!==o&&o.stateValues["pointX"+i]?n[r]=o.stateValues["pointX"+i]:n[r]=me$3.fromAst(0)}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,o]=r.split(","),s=Number(a)+1+"_"+(Number(o)+1);if(null===t[r].through||!t[r].through.stateValues["pointX"+s])return{success:!1};i.push({setDependency:n[r].through,desiredValue:e.throughPoints[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:i}}},t.numericalThroughPoints={isArray:!0,entryPrefixes:["numericalThroughPoint"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={throughPoint:{dependencyType:"stateVariable",variableName:"throughPoint"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].throughPoint.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalThroughPoints:n}}}},t.haveBezierControls={forRenderer:!0,returnDependencies:()=>({controlChild:{dependencyType:"child",childGroups:["bezierControls"]}}),definition:({dependencyValues:e})=>({setValue:{haveBezierControls:e.controlChild.length>0}})},t.bezierControlsAlwaysVisible={forRenderer:!0,returnDependencies:()=>({controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["alwaysVisible"]}}),definition:({dependencyValues:e})=>({setValue:{bezierControlsAlwaysVisible:e.controlChild.length>0&&e.controlChild[0].stateValues.alwaysVisible}})},t.vectorControlDirections={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["vectorControlDirection"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["direction"+(Number(n)+1)]}};return{dependenciesByKey:t,globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"}}}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlChild;t&&t.length>0?n[r]=t[0].stateValues["direction"+(Number(r)+1)]:n[r]="none"}return{setValue:{vectorControlDirections:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls)return{success:!1};let a=[];for(let r in e.vectorControlDirections){let i=n[r].controlChild;i&&i.length>0&&a.push({setDependency:t[r].controlChild,desiredValue:e.vectorControlDirections[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:a}}},t.hiddenControls={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},isArray:!0,entryPrefixes:["hiddenControl"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["hiddenControl"+(Number(n)+1)]}};return{dependenciesByKey:t,globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"}}}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlChild;t&&t.length>0?n[r]=t[0].stateValues["hiddenControl"+(Number(r)+1)]:n[r]=!1}return{setValue:{hiddenControls:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls)return{success:!1};let a=[];for(let r in e.hiddenControls){let i=n[r].controlChild;i&&i.length>0&&a.push({setDependency:t[r].controlChild,desiredValue:e.hiddenControls[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:a}}},t.controlVectors={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"controlVectorX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["controlVectorX","controlVector"],nDimensions:3,stateVariablesDeterminingDependencies:["vectorControlDirections","nThroughPoints"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("controlVectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 3===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eNumber(e)-1));return 2===e.length&&e.every((e=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eString(e)+","+n)):[]:[String(e)+",0"]:[]}},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=r.split(",").map((e=>Number(e))),a=e.map((e=>e+1)),i=a.join("_");n[r]={direction:{dependencyType:"stateVariable",variableName:"vectorControlDirection"+a[0]},controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["control"+i]}};let o=e[0],s=t.vectorControlDirections[o],l=[];"none"===s?l=[o-1,o,o+1]:"previous"===s?l=[o,o+1]:"next"===s&&(l=[o-1,o]);for(let e of l)e>=0&&eNumber(e))),o=r.map((e=>e+1)),s=o.join("_"),l=r[0],u=r[1],c=n[i].direction;if("none"===c){let r,o,s=n[i]["throughPoint"+(l+1)];l>0&&(r=n[i]["throughPoint"+l]),lNumber(e))),o=i.map((e=>e+1)),s=o.join("_"),l=n[r].controlChild;if(l.length>0){l[0].stateValues["control"+s]&&a.push({setDependency:t[r].controlChild,desiredValue:e.controlVectors[r],childIndex:0,variableIndex:0})}}return{success:!0,instructions:a}}},t.numericalControlVectors={isArray:!0,entryPrefixes:["numericalControlVector"],forRenderer:!0,nDimensions:2,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={controlVector:{dependencyType:"stateVariable",variableName:"controlVector"+a}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlVector.map((e=>e.tree));n[r]=t}return{setValue:{numericalControlVectors:n}}}},t.controlPoints={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"controlPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["controlPointX","controlPoint"],nDimensions:3,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("controlPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 3===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eNumber(e)-1));return 2===e.length&&e.every((e=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eString(e)+","+n)):[]:[String(e)+",0"]:[]}},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={throughPointX:{dependencyType:"stateVariable",variableName:"throughPointX"+r[0]+"_"+r[2]},controlVectorX:{dependencyType:"stateVariable",variableName:"controlVectorX"+a}}}return{globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(2!==e.nDimensions)r[a]=me$3.fromAst(NaN);else{let e=t[a].controlVectorX;if(e){let n=t[a].throughPointX.evaluate_to_constant();Number.isFinite(n)||(n=NaN),r[a]=me$3.fromAst(n+e.tree)}else r[a]=null}return{setValue:{controlPoints:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls||2!==r.nDimensions)return{success:!1};let a=[];for(let r in e.controlPoints){if(n[r].controlVectorX){let i=n[r].throughPointX,o=e.controlPoints[r];o.tree&&(o=o.tree);let s=me$3.fromAst(["+",o,["-",i.tree]]);a.push({setDependency:t[r].controlVectorX,desiredValue:s})}}return{success:!0,instructions:a}}},t.numericalControlPoints={isArray:!0,entryPrefixes:["numericalControlPoint"],forRenderer:!0,nDimensions:2,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={controlPoint:{dependencyType:"stateVariable",variableName:"controlPoint"+a}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlPoint.map((e=>e.tree));n[r]=t}return{setValue:{numericalControlPoints:n}}}},t.splineCoeffs={isArray:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints-1],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1,r=e+1;t[n]={previousPoint:{dependencyType:"stateVariable",variableName:"numericalThroughPoint"+e},nextPoint:{dependencyType:"stateVariable",variableName:"numericalThroughPoint"+r},previousVector:{dependencyType:"stateVariable",variableName:"numericalControlVector"+e+"_2"},nextVector:{dependencyType:"stateVariable",variableName:"numericalControlVector"+r+"_1"}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].previousPoint,a=e[r].nextPoint,i=e[r].previousVector,o=e[r].nextVector,s=[];for(let e=0;e<2;e++)s.push(initCubicPoly(t[e],a[e],3*i[e],-3*o[e]));n[r]=s}return{setValue:{splineCoeffs:n}}}},t.extrapolateBackwardCoeffs={stateVariablesDeterminingDependencies:["extrapolateBackward"],additionalStateVariablesDefined:[{variableName:"extrapolateBackwardMode",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies({stateValues:e}){let t={extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}};return e.extrapolateBackward&&(t.firstSplineCoeffs={dependencyType:"stateVariable",variableName:"splineCoeffs1"},t.graphXmin={dependencyType:"stateVariable",variableName:"graphXmin"},t.graphXmax={dependencyType:"stateVariable",variableName:"graphXmax"},t.graphYmin={dependencyType:"stateVariable",variableName:"graphYmin"},t.graphYmax={dependencyType:"stateVariable",variableName:"graphYmax"}),t},definition({dependencyValues:e}){if(!e.extrapolateBackward||!e.firstSplineCoeffs)return{setValue:{extrapolateBackwardCoeffs:null,extrapolateBackwardMode:""}};let t=e.firstSplineCoeffs[0],n=e.firstSplineCoeffs[1],r=t[0],a=t[1],i=2*t[2],o=n[0],s=n[1],l=a*a+s*s,u=(s*i-a*(2*n[2]))/(l*l);if(Math.abs(u)<1e-12||Math.abs(a)<1e-12||Math.abs(s)<1e-12){let t=a,n=s;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,i=e.nThroughPoints-1,o=r/i/Math.abs(t),s=a/i/Math.abs(n),l=Math.min(o,s);l>1&&(t*=l,n*=l)}return{setValue:{extrapolateBackwardCoeffs:[[r,t,0],[o,n,0]],extrapolateBackwardMode:"line"}}}let c=s*u,p=-a*u;if(c*a>0){let t=c/p,n=(1+t*t)**2,i=a;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,o=e.nThroughPoints-1,s=r/o,l=1/0;if(0!==p){let e=p*n/2*o*o,r=-t*o,i=Math.sqrt(r*r+4*Math.abs(e)*a);l=(Math.abs(r)+i)/(2*Math.abs(e))}let u=Math.min(s,l);u>Math.abs(i)&&(i*=u/Math.abs(i))}return{setValue:{extrapolateBackwardCoeffs:[[r,i,0],[o,-i*t,p*i*i*n/2]],extrapolateBackwardMode:"parabolaVertical"}}}{let t=p/c,n=(1+t*t)**2,a=s;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,i=e.graphYmax-e.graphYmin,o=e.nThroughPoints-1,s=i/o,l=1/0;if(0!==c){let e=c*n/2*o*o,a=-t*o,i=Math.sqrt(a*a+4*Math.abs(e)*r);l=(Math.abs(a)+i)/(2*Math.abs(e))}let u=Math.min(l,s);u>Math.abs(a)&&(a*=u/Math.abs(a))}return{setValue:{extrapolateBackwardCoeffs:[[r,-a*t,c*a*a*n/2],[o,a,0]],extrapolateBackwardMode:"parabolaHorizontal"}}}}},t.extrapolateForwardCoeffs={stateVariablesDeterminingDependencies:["nThroughPoints","extrapolateForward"],additionalStateVariablesDefined:[{variableName:"extrapolateForwardMode",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies({stateValues:e}){let t={extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}};return e.extrapolateForward&&e.nThroughPoints>=2&&(t.lastSplineCoeffs={dependencyType:"stateVariable",variableName:"splineCoeffs"+(e.nThroughPoints-1)},t.graphXmin={dependencyType:"stateVariable",variableName:"graphXmin"},t.graphXmax={dependencyType:"stateVariable",variableName:"graphXmax"},t.graphYmin={dependencyType:"stateVariable",variableName:"graphYmin"},t.graphYmax={dependencyType:"stateVariable",variableName:"graphYmax"}),t},definition({dependencyValues:e}){if(!e.extrapolateForward||!e.lastSplineCoeffs)return{setValue:{extrapolateForwardCoeffs:null,extrapolateForwardMode:""}};let t=e.lastSplineCoeffs[0],n=e.lastSplineCoeffs[1],r=t[0]+t[1]+t[2]+t[3],a=t[1]+2*t[2]+3*t[3],i=2*t[2]+6*t[3],o=n[0]+n[1]+n[2]+n[3],s=n[1]+2*n[2]+3*n[3],l=a*a+s*s,u=(s*i-a*(2*n[2]+6*n[3]))/(l*l);if(Math.abs(u)<1e-12||Math.abs(a)<1e-12||Math.abs(s)<1e-12){let t=a,n=s;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,i=e.nThroughPoints-1,o=r/i/Math.abs(t),s=a/i/Math.abs(n),l=Math.min(o,s);l>1&&(t*=l,n*=l)}return{setValue:{extrapolateForwardCoeffs:[[r,t,0],[o,n,0]],extrapolateForwardMode:"line"}}}let c=s*u,p=-a*u;if(c*a<0){let t=c/p,n=(1+t*t)**2,i=a;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,o=e.nThroughPoints-1,s=r/o,l=1/0;if(0!==p){let e=p*n/2*o*o,r=-t*o,i=Math.sqrt(r*r+4*Math.abs(e)*a);l=(Math.abs(r)+i)/(2*Math.abs(e))}let u=Math.min(s,l);u>Math.abs(i)&&(i*=u/Math.abs(i))}return{setValue:{extrapolateForwardCoeffs:[[r,i,0],[o,-i*t,p*i*i*n/2]],extrapolateForwardMode:"parabolaVertical"}}}{let t=p/c,n=(1+t*t)**2,a=s;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,i=e.graphYmax-e.graphYmin,o=e.nThroughPoints-1,s=i/o,l=1/0;if(0!==c){let e=c*n/2*o*o,a=-t*o,i=Math.sqrt(a*a+4*Math.abs(e)*r);l=(Math.abs(a)+i)/(2*Math.abs(e))}let u=Math.min(l,s);u>Math.abs(a)&&(a*=u/Math.abs(a))}return{setValue:{extrapolateForwardCoeffs:[[r,-a*t,c*a*a*n/2],[o,a,0]],extrapolateForwardMode:"parabolaHorizontal"}}}}},t.fs={isArray:!0,entryPrefixes:["f"],additionalStateVariablesDefined:[{variableName:"fDefinitions",isArray:!0,forRenderer:!0}],returnArraySizeDependencies:()=>({functionChildren:{dependencyType:"child",childGroups:["functions"]},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),returnArraySize:({dependencyValues:e})=>"bezier"===e.curveType?[2]:[Math.max(1,e.functionChildren.length)],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalf","fDefinition"],childIndices:[n]}},0===Number(n)&&(t[n].fShadow={dependencyType:"stateVariable",variableName:"fShadow"},t[n].fDefinitionAdapted={dependencyType:"adapterSourceStateVariable",variableName:"fDefinition"});return{globalDependencies:{curveType:{dependencyType:"stateVariable",variableName:"curveType"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},extrapolateBackwardCoeffs:{dependencyType:"stateVariable",variableName:"extrapolateBackwardCoeffs"},extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},extrapolateForwardCoeffs:{dependencyType:"stateVariable",variableName:"extrapolateForwardCoeffs"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if("bezier"===e.curveType)return{setValue:{fs:returnBezierFunctions(e),fDefinitions:{0:{functionType:"bezier",nThroughPoints:e.nThroughPoints,numericalThroughPoints:e.numericalThroughPoints,splineCoeffs:e.splineCoeffs,extrapolateForward:e.extrapolateForward,extrapolateForwardCoeffs:e.extrapolateForwardCoeffs,extrapolateBackward:e.extrapolateBackward,extrapolateBackwardCoeffs:e.extrapolateBackwardCoeffs},1:null}}};let r={},a={};for(let e of n){let n=t[e].functionChild;1===n.length?(r[e]=n[0].stateValues.numericalf,a[e]=n[0].stateValues.fDefinition):0===Number(e)&&t[e].fShadow?(r[e]=t[e].fShadow,a[e]=t[e].fDefinitionAdapted):(r[e]=()=>0,a[e]={functionType:"zero"})}return{setValue:{fs:r,fDefinitions:a}}}},t.f={isAlias:!0,targetVariableName:"f1"},t.allXCriticalPoints={returnDependencies:()=>({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allXCriticalPoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let e=n[0],r=3*e[3],o=2*e[2],s=e[1];if(Math.abs(r)<1e-14){i=addTimePointBezier({t:-s/o,ind:t,ts:a,ignoreLeft:i})}else{let e=o*o-4*r*s;if(0==e){i=addTimePointBezier({t:-o/(2*r),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),s=[(-o-n)/(2*r),(-o+n)/(2*r)];r<0&&(s=[s[1],s[0]]);let l=!1;for(let e of s){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(l=!0)}i=l}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allXCriticalPoints:t}}}},t.nXCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allXCriticalPoints:{dependencyType:"stateVariable",variableName:"allXCriticalPoints"}}),definition:({dependencyValues:e})=>({setValue:{nXCriticalPoints:e.allXCriticalPoints.length}})},t.xCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"xCriticalPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["xCriticalPointX","xCriticalPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("xCriticalPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("xCriticalPoints"===t)return 1===e.length?"xCriticalPoint"+e[0]:`xCriticalPointX${e[0]}_${e[1]}`;if("xCriticalPoint"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`xCriticalPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nXCriticalPoints:{dependencyType:"stateVariable",variableName:"nXCriticalPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nXCriticalPoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allXCriticalPoints:{dependencyType:"stateVariable",variableName:"allXCriticalPoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allYCriticalPoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let e=n[1],r=3*e[3],o=2*e[2],s=e[1];if(Math.abs(r)<1e-14){i=addTimePointBezier({t:-s/o,ind:t,ts:a,ignoreLeft:i})}else{let e=o*o-4*r*s;if(0==e){i=addTimePointBezier({t:-o/(2*r),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),s=[(-o-n)/(2*r),(-o+n)/(2*r)];r<0&&(s=[s[1],s[0]]);let l=!1;for(let e of s){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(l=!0)}i=l}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allYCriticalPoints:t}}}},t.nYCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allYCriticalPoints:{dependencyType:"stateVariable",variableName:"allYCriticalPoints"}}),definition:({dependencyValues:e})=>({setValue:{nYCriticalPoints:e.allYCriticalPoints.length}})},t.yCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"yCriticalPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["yCriticalPointX","yCriticalPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("yCriticalPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("yCriticalPoints"===t)return 1===e.length?"yCriticalPoint"+e[0]:`yCriticalPointX${e[0]}_${e[1]}`;if("yCriticalPoint"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`yCriticalPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nYCriticalPoints:{dependencyType:"stateVariable",variableName:"nYCriticalPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nYCriticalPoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allYCriticalPoints:{dependencyType:"stateVariable",variableName:"allYCriticalPoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allCurvatureChangePoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let[e,r,o,s]=n[0],[l,u,c,p]=n[1],d=3*(o*p-c*s),m=3*(r*p-u*s),f=r*c-u*o;if(Math.abs(d)<1e-14){i=addTimePointBezier({t:-f/m,ind:t,ts:a,ignoreLeft:i})}else{let e=m*m-4*d*f;if(0==e){i=addTimePointBezier({t:-m/(2*d),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),r=[(-m-n)/(2*d),(-m+n)/(2*d)];d<0&&(r=[r[1],r[0]]);let o=!1;for(let e of r){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(o=!0)}i=o}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allCurvatureChangePoints:t}}}},t.nCurvatureChangePoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"allCurvatureChangePoints"}}),definition:({dependencyValues:e})=>({setValue:{nCurvatureChangePoints:e.allCurvatureChangePoints.length}})},t.curvatureChangePoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"curvatureChangePointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["curvatureChangePointX","curvatureChangePoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("curvatureChangePointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("curvatureChangePoints"===t)return 1===e.length?"curvatureChangePoint"+e[0]:`curvatureChangePointX${e[0]}_${e[1]}`;if("curvatureChangePoint"===t.slice(0,20)){let n=Number(t.slice(20));if(Number.isInteger(n)&&n>0)return`curvatureChangePointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"nCurvatureChangePoints"}}),returnArraySize:({dependencyValues:e})=>[e.nCurvatureChangePoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"allCurvatureChangePoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({nearestPointAsCurvePrelim:{dependencyType:"stateVariable",variableName:"nearestPointAsCurvePrelim"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nearestPointAsCurve"]},adapterSourceValue:{dependencyType:"adapterSourceStateVariable",variableName:"nearestPointAsCurve"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.nearestPointAsCurvePrelim;return t.nearestPointAsCurvePrelim&&(e.functionChild.length>0?n=e.functionChild[0].stateValues.nearestPointAsCurve:null!==e.adapterSourceValue&&(n=e.adapterSourceValue)),{setValue:{nearestPointAsCurve:n}}}},t.nearestPoint={returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},fs:{dependencyType:"stateVariable",variableName:"fs"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"},nDiscretizationPoints:{dependencyType:"stateVariable",variableName:"nDiscretizationPoints"},parMin:{dependencyType:"stateVariable",variableName:"parMin"},parMax:{dependencyType:"stateVariable",variableName:"parMax"},periodic:{dependencyType:"stateVariable",variableName:"periodic"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},nearestPointAsCurve:{dependencyType:"stateVariable",variableName:"nearestPointAsCurve"}}),definition({dependencyValues:t}){let n=null;return"function"===t.curveType?n=getNearestPointFunctionCurve({dependencyValues:t,numerics:e}):["parameterization","bezier"].includes(t.curveType)&&(n=getNearestPointParametrizedCurve({dependencyValues:t,numerics:e})),{setValue:{nearestPoint:n}}}},t}async moveControlVector({controlVector:e,controlVectorInds:t,transient:n,actionId:r}){let a={[t+",0"]:me$3.fromAst(e[0]),[t+",1"]:me$3.fromAst(e[1])};return n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"controlVectors",value:a,sourceInformation:{controlVectorMoved:t}}],transient:n,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"controlVectors",value:a,sourceInformation:{controlVectorMoved:t}}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{["controlVector"+t.join("_")]:e}}})}async moveThroughPoint({throughPoint:e,throughPointInd:t,transient:n,actionId:r}){let a={[t+",0"]:me$3.fromAst(e[0]),[t+",1"]:me$3.fromAst(e[1])};return n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"throughPoints",value:a,sourceInformation:{throughPointMoved:t}}],transient:n,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"throughPoints",value:a,sourceInformation:{throughPointMoved:t}}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{["throughPoint"+t]:e}}})}async changeVectorControlDirection({direction:e,throughPointInd:t,actionId:n}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vectorControlDirection",value:{[t]:e}}],actionId:n})}switchCurve(){}async curveClicked({actionId:e,name:t}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:t}),this.coreFunctions.resolveAction({actionId:e})}}function getNearestPointFunctionCurve({dependencyValues:e,numerics:t}){let n=e.flipFunction,r=e.fs[0],a=e.nDiscretizationPoints,i=e.parMax,o=e.parMin;return function({variables:s,scales:l}){let u,c,p,d,m=s.x1?.evaluate_to_constant(),f=s.x2?.evaluate_to_constant(),h=l[0],y=l[1];if(o!==-1/0){if(u=o,c=r(o),!Number.isFinite(c)){let e=.99999*o+1e-5*i,t=r(e);Number.isFinite(t)&&(u=e,c=t)}if(n){let e=u;u=c,c=e}}if(i!==1/0){if(p=i,d=r(i),!Number.isFinite(d)){let e=1e-5*o+.99999*i,t=r(e);Number.isFinite(t)&&(p=e,d=t)}if(n){let e=p;p=d,d=e}}if(!e.nearestPointAsCurve||!Number.isFinite(m)||!Number.isFinite(f)){let e,t;if(n?(t=f,e=r(t)):(e=m,t=r(e)),!Number.isFinite(e)||!Number.isFinite(t)){let r,a;n?(r=Math.abs(o-f),a=Math.abs(i-f)):(r=Math.abs(o-m),a=Math.abs(i-m)),re.evaluate_to_constant())),a)l=a.map((e=>e.evaluate_to_constant())),o=n?n.map((e=>e.evaluate_to_constant())):[2*s[0]-l[0],2*s[1]-l[1]];else{if(!n)return{coordsNumeric:[me$3.fromAst(NaN),me$3.fromAst(NaN)],numericEntries:!1};o=n.map((e=>e.evaluate_to_constant())),l=[2*s[0]-o[0],2*s[1]-o[1]]}let c=[];if("centripetal"===i){let n=u(o,s),r=u(s,l);n=Math.sqrt(n),r=Math.sqrt(r),rme$3.fromAst(e)));return{coordsNumeric:p,numericEntries:Number.isFinite(c[0])&&Number.isFinite(c[1])}}function initCubicPoly(e,t,n,r){return[e,n,-3*e+3*t-2*n-r,2*e-2*t+n+r]}function addTimePointBezier({t:e,ind:t,ts:n,ignoreLeft:r=!1}){const a=1e-14;let i=!1;return e>=a?e<=.99999999999999?n.push(t+e):e<1.00000000000001&&(n.push(t+1),i=!0):e>-a&&!r&&n.push(t),i}class EquilibriumCurve extends Curve{static componentType="equilibriumCurve";static rendererType="curve";static createAttributesObject(){let e=super.createAttributesObject();return e.stable={createComponentOfType:"boolean",createStateVariable:"stable",defaultValue:!0,public:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.dashed={forRenderer:!0,returnDependencies:()=>({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{dashed:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.dashed}]})},t}async switchCurve({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}var DynamicalSystems=Object.freeze({__proto__:null,ODESystem:ODESystem,CobwebPolyline:CobwebPolyline,EquilibriumPoint:EquilibriumPoint,EquilibriumLine:EquilibriumLine,EquilibriumCurve:EquilibriumCurve});class Atom extends InlineComponent{static componentType="atom";static rendererType="math";static primaryStateVariableForDefinition="atomicNumberShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.symbol={createComponentOfType:"text"},e.atomicNumber={createComponentOfType:"integer"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.atomicNumberShadow={defaultValue:null,hasEssential:!0,essentialVarName:"atomicNumber",returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{atomicNumberShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"atomicNumberShadow",value:e.atomicNumberShadow}]}}},e.dataForAtom={returnDependencies:()=>({fileContents:{dependencyType:"file",cid:"bafkreibilal4glrbpo7p7oodtwtnzkfhiylfoqa2td4ij6h6iqva57kzcy",fileType:"csv"},symbolAttr:{dependencyType:"attributeComponent",attributeName:"symbol",variableNames:["value"]},atomicNumberAttr:{dependencyType:"attributeComponent",attributeName:"atomicNumber",variableNames:["value"]},atomicNumberShadow:{dependencyType:"stateVariable",variableName:"atomicNumberShadow"}}),definition:function({dependencyValues:e}){let t=null,n=null;if(e.symbolAttr)t=e.symbolAttr.stateValues.value.toLowerCase();else if(e.atomicNumberAttr)n=e.atomicNumberAttr.stateValues.value;else{if(!e.atomicNumberShadow)return{setValue:{dataForAtom:null}};n=e.atomicNumberShadow}let r,a=e.fileContents.trim().split("\n");r=null!==n?n-1:["h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","nh","fl","mc","lv","ts","og"].indexOf(t?.toLowerCase());let i=a.slice(1)[r];if(!i)return{setValue:{dataForAtom:null}};i=i.trim().split(",").map((e=>e.trim()));let o=a[0].trim().split(",").map((e=>e.trim())).map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1).trim()),e))),s=o.length,l=["number","string","string","number","number","string","number","string","string","number","number","number","number","number","number","number","string"],u={};for(let e=0;e({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Number"]:null,{setValue:{atomicNumber:t}}}},e.symbol={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Symbol:null,{setValue:{symbol:t}}}},e.name={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Name:null,{setValue:{name:t}}}},e.group={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Group:null,{setValue:{group:t}}}},e.atomicMass={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Mass"]:null,{setValue:{atomicMass:t}}}},e.phaseAtSTP={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Phase at STP"]:null,{setValue:{phaseAtSTP:t}}}},e.chargeOfCommonIon={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Charge of Common Ion"]:null,{setValue:{chargeOfCommonIon:t}}}},e.metalCategory={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Metal/Nonmetal/Metalloid"]:null,{setValue:{metalCategory:t}}}},e.groupName={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Group Name"]:null,{setValue:{groupName:t}}}},e.period={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Period:null,{setValue:{period:t}}}},e.ionizationEnergy={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Ionization Energy"]:null,{setValue:{ionizationEnergy:t}}}},e.meltingPoint={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Melting Point"]:null,{setValue:{meltingPoint:t}}}},e.boilingPoint={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Boiling Point"]:null,{setValue:{boilingPoint:t}}}},e.atomicRadius={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Radius"]:null,{setValue:{atomicRadius:t}}}},e.density={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Density:null,{setValue:{density:t}}}},e.electronegativity={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Electronegativity:null,{setValue:{electronegativity:t}}}},e.electronConfiguration={public:!0,shadowingInstructions:{createComponentOfType:"electronConfiguration"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Electron Configuration"]:null,{setValue:{electronConfiguration:t}}}},e.orbitalDiagram={public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},returnDependencies:()=>({electronConfiguration:{dependencyType:"stateVariable",variableName:"electronConfiguration"}}),definition({dependencyValues:e}){let t;return t=e.electronConfiguration?electronConfigurationToOrbitalDiagram(e.electronConfiguration):null,{setValue:{orbitalDiagram:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"}}),definition({dependencyValues:e}){let t;return t=e.symbol?["^",e.symbol]:"_",{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"}}),definition({dependencyValues:e}){let t;return t=e.symbol?`\\text{${e.symbol}}`:"[\\text{Invalid Chemical Symbol}]",{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math","name",{stateVariable:"atomicNumber",componentType:"ion"}]}function electronConfigurationToOrbitalDiagram(e){let t=e.tree;if(!Array.isArray(t)||"*"!==t[0])return null;t=t.slice(1);let n=t.length/2;if(!Number.isInteger(n))return null;let r=[];for(let e=0;e0))return null;let a=t[2*e+1];if(!Array.isArray(a)||"^"!==a[0])return null;let i=a[1],o=a[2];if(!(["s","p","d","f"].includes(i)&&Number.isInteger(o)&&o>0))return null;let s,l=`${n}${i}`;s="s"===i?1:"p"===i?3:"d"===i?5:7;let u=Array(s).fill("");for(let e=0;e({}),definition:()=>({useEssentialOrDefaultValue:{atomicNumberShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"atomicNumberShadow",value:e.atomicNumberShadow}]}}},e.dataForAtom={returnDependencies:()=>({fileContents:{dependencyType:"file",cid:"bafkreibilal4glrbpo7p7oodtwtnzkfhiylfoqa2td4ij6h6iqva57kzcy",fileType:"csv"},symbolAttr:{dependencyType:"attributeComponent",attributeName:"symbol",variableNames:["value"]},atomicNumberAttr:{dependencyType:"attributeComponent",attributeName:"atomicNumber",variableNames:["value"]},atomChild:{dependencyType:"child",childGroups:["atoms"],variableNames:["atomicNumber"]},atomicNumberShadow:{dependencyType:"stateVariable",variableName:"atomicNumberShadow"}}),definition:function({dependencyValues:e}){let t=null,n=null;if(e.atomChild.length>0)n=e.atomChild[0].stateValues.atomicNumber;else if(e.symbolAttr)t=e.symbolAttr.stateValues.value.toLowerCase();else if(e.atomicNumberAttr)n=e.atomicNumberAttr.stateValues.value;else{if(!e.atomicNumberShadow)return{setValue:{dataForAtom:null}};n=e.atomicNumberShadow}let r,a=e.fileContents.trim().split("\n");r=null!==n?n-1:["h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","nh","fl","mc","lv","ts","og"].indexOf(t?.toLowerCase());let i=a.slice(1)[r];if(!i)return{setValue:{dataForAtom:null}};i=i.trim().split(",").map((e=>e.trim()));let o=a[0].trim().split(",").map((e=>e.trim())).map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1).trim()),e))),s=o.length,l=["number","string","string","number","number","string","number","string","string","number","number","number","number","number","number","number","string"],u={};for(let e=0;e({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Number"]:null,{setValue:{atomicNumber:t}}}},e.symbol={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Symbol:null,{setValue:{symbol:t}}}},e.charge={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"},chargeAttr:{dependencyType:"attributeComponent",attributeName:"charge",variableNames:["value"]}}),definition({dependencyValues:e}){let t;return e.chargeAttr?(t=e.chargeAttr.stateValues.value,Number.isFinite(t)||(t=0)):t=e.dataForAtom&&e.dataForAtom["Charge of Common Ion"]||0,{setValue:{charge:t}}}},e.name={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"},charge:{dependencyType:"stateVariable",variableName:"charge"},group:{dependencyType:"stateVariable",variableName:"group"},atomicNumber:{dependencyType:"stateVariable",variableName:"atomicNumber"}}),definition({dependencyValues:e}){let t;if(e.dataForAtom){if(t=e.dataForAtom.Name,e.charge<0){let e={Hydrogen:"Hydride",Oxygen:"Oxide",Sulfur:"Sulfide",Nitrogen:"Nitride",Phosphorus:"Phosphide",Carbon:"Carbide"},n=t.length;"ine"===t.substring(n-3,n)?t=t.substring(0,n-3)+"ide":t in e&&(t=e[t])}else if(e.charge>0&&(e.group>=3&&e.group<=12||101===e.group||102===e.group||[13,31,49,50,81,82,83,84].includes(e.atomicNumber))){let n="";switch(e.charge){case 1:n=" (I)";break;case 2:n=" (II)";break;case 3:n=" (III)";break;case 4:n=" (IV)";break;case 5:n=" (V)";break;case 6:n=" (VI)";break;case 7:n=" (VII)";break;case 8:n=" (VIII)"}t+=n}}else t=null;return{setValue:{name:t}}}},e.group={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Group:null,{setValue:{group:t}}}},e.metalCategory={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Metal/Nonmetal/Metalloid"]:null,{setValue:{metalCategory:t}}}},e.groupName={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Group Name"]:null,{setValue:{groupName:t}}}},e.period={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Period:null,{setValue:{period:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"},charge:{dependencyType:"stateVariable",variableName:"charge"}}),definition({dependencyValues:e}){let t;return e.symbol?(t=["^",e.symbol],-1===e.charge?t.push("-"):1===e.charge?t.push("+"):e.charge<0?t.push(Math.abs(e.charge)+"-"):e.charge>0&&t.push(Math.abs(e.charge)+"+")):t="_",{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"},charge:{dependencyType:"stateVariable",variableName:"charge"}}),definition({dependencyValues:e}){let t;return e.symbol?(t=`\\text{${e.symbol}}`,-1===e.charge?t+="^-":1===e.charge?t+="^+":e.charge<0?t+=`^{${Math.abs(e.charge)}-}`:e.charge>0&&(t+=`^{${Math.abs(e.charge)}+}`)):t="[\\text{Invalid Chemical Symbol}]",{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math","name"]}class IonicCompound extends InlineComponent{static componentType="ionicCompound";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.symbol={createComponentOfType:"text"},e.atomicNumber={createComponentOfType:"integer"},e.charge={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"ions",componentTypes:["ion"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.ionicCompound={returnDependencies:()=>({ionChildren:{dependencyType:"child",childGroups:["ions"],variableNames:["symbol","charge","atomicNumber","name"]}}),definition({dependencyValues:e}){let t=e.ionChildren.map((e=>e.stateValues.charge));if(2!==t.length)return console.warn("have not implemented ionic compound for anything other than two ions"),{setValue:{ionicCompound:null}};if(!(t[0]*t[1]<0))return console.warn("ionic compound implemented only for one cation and one anion"),{setValue:{ionicCompound:null}};let n=Math.abs(t[1]),r=Math.abs(t[0]),a=me$3.math.gcd(n,r);return n/=a,r/=a,{setValue:{ionicCompound:[{symbol:e.ionChildren[0].stateValues.symbol,atomicNumber:e.ionChildren[0].stateValues.atomicNumber,name:e.ionChildren[0].stateValues.name,charge:t[0],count:n},{symbol:e.ionChildren[1].stateValues.symbol,atomicNumber:e.ionChildren[1].stateValues.atomicNumber,name:e.ionChildren[1].stateValues.name,charge:t[1],count:r}]}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({ionicCompound:{dependencyType:"stateVariable",variableName:"ionicCompound"}}),definition({dependencyValues:e}){let t;if(e.ionicCompound){t=[];for(let n of e.ionicCompound){let e=n.symbol;n.count>1&&(e=["_",e,n.count]),t.push(e)}t=t.length>1?["*",...t]:1===t.length?t[0]:"_"}else t="_";return{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({ionicCompound:{dependencyType:"stateVariable",variableName:"ionicCompound"}}),definition({dependencyValues:e}){let t;if(e.ionicCompound){t="";for(let n of e.ionicCompound)t+=`\\text{${n.symbol}}`,n.count>1&&(t+=`_{${n.count}}`)}else t="[\\text{Invalid Ionic Compound}]";return{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math"]}class ElectronConfiguration extends MathComponent{static componentType="electronConfiguration";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e,usedDefault:t}){let n;try{n=e.valueForDisplay.toLatex()}catch(e){n="_"}return n=n.replaceAll("\\,",""),n=n.replaceAll("\\cdot","~"),{setValue:{latex:n}}}},e}}class OrbitalDiagram extends BlockComponent{static componentType="orbitalDiagram";static variableForPlainMacro="value";static createAttributesObject(){let e=super.createAttributesObject();return e.labels={createComponentOfType:"textList",createStateVariable:"labels",defaultValue:[]},e}static returnSugarInstructions(){return[{replacementFunction:function({matchedChildren:e}){return 1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"tupleList",children:e}]}}}]}static returnChildGroups(){return[{group:"tupleLists",componentTypes:["tupleList"]},{group:"orbitalDiagrams",componentTypes:["orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={defaultValue:[{orbitalText:"",boxes:[]}],public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},forRenderer:!0,returnDependencies:()=>({orbitalDiagramChildren:{dependencyType:"child",childGroups:["orbitalDiagrams"],variableNames:["value"]},tupleListChildren:{dependencyType:"child",childGroups:["tupleLists"],variableNames:["maths"]},labels:{dependencyType:"stateVariable",variableName:"labels"}}),definition:function({dependencyValues:e}){return{setValue:{value:function(){function t(e){if("u"===e||"U"===e)return"U";if("d"===e||"D"===e)return"D";if("e"===e||"E"===e)return"";if(Array.isArray(e)&&"*"===e[0]){let t="";for(let n of e.slice(1))if("u"===n||"U"===n)t+="U";else{if("d"!==n&&"D"!==n)return"";t+="D"}return t}return""}if(1===e.orbitalDiagramChildren.length)return e.orbitalDiagramChildren[0].stateValues.value;let n=[];if(e.tupleListChildren[0]?.stateValues.maths.length>0){let r=e.tupleListChildren[0].stateValues.maths;for(let[a,i]of r.entries()){let r="";e.labels[a]&&(r=e.labels[a]);let o=[];if(Array.isArray(i.tree)&&"tuple"===i.tree[0])for(let e of i.tree.slice(1))o.push(t(e));else o.push(t(i.tree));n.push({orbitalText:r,boxes:o})}return n}return[{orbitalText:"",boxes:[]}]}()}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class OrbitalDiagramInput extends BlockComponent{static componentType="orbitalDiagramInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"orbitalDiagram",createStateVariable:"prefill",defaultValue:[]},e.prefillLabel={createComponentOfType:"textList",createStateVariable:"prefillLabel",defaultValue:[]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={defaultValue:[{orbitalText:"",boxes:[]}],hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},returnDependencies:()=>({prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLabel:{dependencyType:"stateVariable",variableName:"prefillLabel"}}),definition:function({dependencyValues:e}){return{useEssentialOrDefaultValue:{value:{get defaultValue(){return function(){if(e.prefill?.length>0){let t=JSON.parse(JSON.stringify(e.prefill));for(let[n,r]of t.entries())e.prefillLabel[n]&&(r.orbitalText=e.prefillLabel[n]);return t}return[{orbitalText:"",boxes:[]}]}()}}}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"value",value:e.value}]})},e.rows={public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{rows:[...e.value].reverse()}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:[...e.rows].reverse()}]})},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({rows:{dependencyType:"stateVariable",variableName:"rows"}}),definition:function({dependencyValues:e}){return{setValue:{numRows:e.rows.length}}}},e.selectedRowIndex={defaultValue:0,hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({}),definition:function(){return{useEssentialOrDefaultValue:{selectedRowIndex:!0}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n=await t.numRows,r=e.selectedRowIndex;return r=Number.isFinite(r)?Math.min(n,Math.max(0,Math.round(r))):0,{success:!0,instructions:[{setEssentialValue:"selectedRowIndex",value:r}]}}},e.selectedBoxIndex={defaultValue:0,hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({}),definition:function(){return{useEssentialOrDefaultValue:{selectedBoxIndex:!0}}},async inverseDefinition({desiredStateVariableValues:e}){let t=e.selectedBoxIndex;return t=Number.isFinite(t)?Math.max(0,Math.round(t)):0,{success:!0,instructions:[{setEssentialValue:"selectedBoxIndex",value:t}]}}},e}async addRow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t));t.length<20&&(n=[{orbitalText:"",boxes:[]},...t]);let r=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return-1!==await this.stateValues.selectedRowIndex-1&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:0}),-1!==await this.stateValues.selectedBoxIndex-1&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}),await this.coreFunctions.performUpdate({updateInstructions:r,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeRow({actionId:e}){let t=await this.stateValues.rows,n=await this.stateValues.selectedRowIndex-1,r=JSON.parse(JSON.stringify(t));if(t.length>1){let e=t.length-1-n;-1===n&&(e=0),r.splice(e,1)}return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:r},{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:0},{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:r}}})}async addBox({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0),n[a].boxes.length<17&&n[a].boxes.push("");let i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];if(-1!==r){let e=0;i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:e})}return await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeBox({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,o=i;-1===i&&(o=n[a].boxes.length-1),n[a].boxes.splice(o,1);let s=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return-1!==i&&s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}),await this.coreFunctions.performUpdate({updateInstructions:s,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async addUpArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,o=i;-1===i&&(o=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[o].length<3&&(n[a].boxes[o]=n[a].boxes[o]+"U");let s=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:s,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async addDownArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,o=i;-1===i&&(o=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[o].length<3&&(n[a].boxes[o]=n[a].boxes[o]+"D");let s=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:s,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,o=i;-1===i&&(o=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[o].length>0&&(n[a].boxes[o]=n[a].boxes[o].slice(0,-1));let s=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:s,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async updateRowText({newValue:e,actionId:t}){let n=await this.stateValues.rows,r=JSON.parse(JSON.stringify(n)),a=await this.stateValues.selectedRowIndex-1,i=n.length-a-1;-1===a&&(i=0),r[i].orbitalText=e;let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:r}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:r}}})}async selectRow({index:e,actionId:t}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:e}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{selectedRowIndex:e}}})}async selectBox({index:e,actionId:t}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:e}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{selectedBoxIndex:e}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={addRow:this.addRow.bind(this),removeRow:this.removeRow.bind(this),addBox:this.addBox.bind(this),removeBox:this.removeBox.bind(this),addUpArrow:this.addUpArrow.bind(this),addDownArrow:this.addDownArrow.bind(this),removeArrow:this.removeArrow.bind(this),updateRowText:this.updateRowText.bind(this),selectRow:this.selectRow.bind(this),selectBox:this.selectBox.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)}}var Chemistry=Object.freeze({__proto__:null,Atom:Atom,Ion:Ion,IonicCompound:IonicCompound,ElectronConfiguration:ElectronConfiguration,OrbitalDiagram:OrbitalDiagram,OrbitalDiagramInput:OrbitalDiagramInput});class FeedbackDefinition extends BaseComponent{static componentType="feedbackDefinition";static createAttributesObject(){let e=super.createAttributesObject();return e.code={createComponentOfType:"text"},e.text={createComponentOfType:"text"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.feedbackDefinition={returnDependencies:()=>({codeAttr:{dependencyType:"attributeComponent",attributeName:"code",variableNames:["value"]},textAttr:{dependencyType:"attributeComponent",attributeName:"text",variableNames:["value"]}}),definition({dependencyValues:e}){if(null!==e.codeAttr&&null!==e.textAttr){return{setValue:{feedbackDefinition:{[e.codeAttr.stateValues.value.toLowerCase()]:e.textAttr.stateValues.value}}}}return{setValue:{feedbackDefinition:null}}}},e}}class FeedbackDefinitions extends BaseComponent{static componentType="feedbackDefinitions";static rendererType=void 0;static returnChildGroups(){return[{group:"feedbackDefinition",componentTypes:["feedbackDefinition"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({feedbackDefinitionChildren:{dependencyType:"child",childGroups:["feedbackDefinition"],variableNames:["feedbackDefinition"]}}),definition({dependencyValues:e}){let t={};for(let n of e.feedbackDefinitionChildren)n.stateValues.feedbackDefinition&&Object.assign(t,n.stateValues.feedbackDefinition);return{setValue:{value:t}}}},e}}var FeedbackDefinitions$1=Object.freeze({__proto__:null,FeedbackDefinition:FeedbackDefinition,FeedbackDefinitions:FeedbackDefinitions});class StyleDefinition extends BaseComponent{static componentType="styleDefinition";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();e.styleNumber={createPrimitiveOfType:"number",createStateVariable:"styleNumber",defaultValue:1};for(let t in styleAttributes)e[t]={createComponentOfType:styleAttributes[t].componentType};return e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDefinition={returnDependencies:function(){let e={};for(let t in styleAttributes)e[t]={dependencyType:"attributeComponent",attributeName:t,variableNames:["value"]};return e},definition:function({dependencyValues:e}){let t={};for(let n in styleAttributes)null!==e[n]&&(t[n]=e[n].stateValues.value,"string"==typeof t[n]&&(t[n]=t[n].toLowerCase()));return{setValue:{styleDefinition:t}}}},e}}class StyleDefinitions extends BaseComponent{static componentType="styleDefinitions";static rendererType=void 0;static returnChildGroups(){return[{group:"styleDefinition",componentTypes:["styleDefinition"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({styleDefinitionChildren:{dependencyType:"child",childGroups:["styleDefinition"],variableNames:["styleNumber","styleDefinition"]}}),definition({dependencyValues:e}){let t={};for(let n of e.styleDefinitionChildren){let e=n.stateValues.styleNumber,r=t[e];r||(r=t[e]={}),Object.assign(r,n.stateValues.styleDefinition)}return{setValue:{value:t}}}},e}}var StyleDefinitions$1=Object.freeze({__proto__:null,StyleDefinition:StyleDefinition,StyleDefinitions:StyleDefinitions});class ComponentWithSelectableType extends BaseComponent{static componentType="_componentWithSelectableType";static rendererType=void 0;static includeBlankStringChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n}){let r=t.type;r||(r=n.type),r?["number","letters","math","text","boolean"].includes(r)||(console.warn(`Invalid type ${r}, setting type to number`),r="number"):r="number";let a="letters"===r?"text":r;return"text"!==a&&(e=e.filter((e=>"string"!=typeof e||""!==e.trim()))),{success:!0,newChildren:[{componentType:a,children:e}]}}}),e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.type={shadowVariable:!0,returnDependencies:()=>({type:{dependencyType:"doenetAttribute",attributeName:"type"},parentType:{dependencyType:"parentStateVariable",variableName:"type"}}),definition:function({dependencyValues:e,componentName:t}){let n=e.type;return n||(n=e.parentType),n?["number","letters","math","text","boolean"].includes(n)||(console.warn(`Invalid type ${n}, setting type to number`),n="number"):n="number",{setValue:{type:n}}}},e.value={public:!0,shadowingInstructions:{hasVariableComponentType:!0},shadowVariable:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},atMostOneChild:{dependencyType:"child",childGroups:["anything"],variableNames:["value"]}}),definition({dependencyValues:e}){let t;return t=e.atMostOneChild.length>0?e.atMostOneChild[0].stateValues.value:"text"===e.type||"letters"===e.type?"":"boolean"!==e.type&&("number"===e.type?NaN:me$3.fromAst("_")),{setValue:{value:t},setCreateComponentOfType:{value:e.type}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.atMostOneChild.length>0?{success:!0,instructions:[{setDependency:"atMostOneChild",desiredValue:e.value,childIndex:0,variableIndex:0}]}:{success:!1}},e}}class ComponentListWithSelectableType extends ComponentWithSelectableType{static componentType="_componentListWithSelectableType";static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n,isAttributeComponent:r=!1,createdFromMacro:a=!1,componentInfoObjects:i}){let o=t.type;o||(o=n.type),o?["number","letters","math","text","boolean"].includes(o)||(console.warn(`Invalid type ${o}, setting type to number`),o="number"):o="number";let s="letters"===o?"text":o;if(r&&!a){return returnGroupIntoComponentTypeSeparatedBySpaces({componentType:s})({matchedChildren:e})}return returnBreakStringsIntoComponentTypeBySpaces({componentType:s})({matchedChildren:e})}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.value,e.nValues={additionalStateVariablesDefined:["childForValue"],returnDependencies:()=>({anythingForSelectedType:{dependencyType:"child",childGroups:["anything"],variableNames:["nValues"],variablesOptional:!0}}),definition({dependencyValues:e}){let t=0,n=[];for(let[r,a]of e.anythingForSelectedType.entries()){let e=Number.isInteger(a.stateValues.nValues)?a.stateValues.nValues:1;t+=e;for(let t=0;t({nValues:{dependencyType:"stateVariable",variableName:"nValues"}}),returnArraySize:({dependencyValues:e})=>[e.nValues],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.childForValue[r];n[r]={anythingForSelectedType:{dependencyType:"child",childGroups:["anything"],variableNames:["value","values"],childIndices:[e.child],variablesOptional:!0},valueIndex:{dependencyType:"value",value:e.valueIndex}}}return{globalDependencies:{type:{dependencyType:"stateVariable",variableName:"type"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentName:r}){let a={};for(let r of n)if(t[r].anythingForSelectedType&&1===t[r].anythingForSelectedType.length){let n,i=t[r].anythingForSelectedType[0];n=i.stateValues.values?i.stateValues.values[t[r].valueIndex]:i.stateValues.value,a[r]=convertValueToType(n,e.type)}return{setValue:{values:a},setCreateComponentOfType:{values:e.type}}}},e}}class ComponentListOfListsWithSelectableType extends ComponentWithSelectableType{static componentType="_componentListOfListsWithSelectableType";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n}){let r=breakEmbeddedStringsIntoParensPieces({componentList:e,removeParens:!0});if(!0!==r.success)return{success:!1};let a=t.type;return a||(a=n.type),a?["number","letters","math","text","boolean"].includes(a)||(console.warn(`Invalid type ${a}, setting type to number`),a="number"):a="number",{success:!0,newChildren:r.pieces.map((e=>({componentType:"_componentListWithSelectableType",attributes:{type:{primitive:a}},children:e})))}}}),e}static returnChildGroups(){return[{group:"lists",componentTypes:["_componentListWithSelectableType"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.value,e.nLists={returnDependencies:()=>({listChildren:{dependencyType:"child",childGroups:["lists"]}}),definition:({dependencyValues:e})=>({setValue:{nLists:e.listChildren.length}})},e.lists={isArray:!0,entryPrefixes:["list"],returnArraySizeDependencies:()=>({nLists:{dependencyType:"stateVariable",variableName:"nLists"}}),returnArraySize:({dependencyValues:e})=>[e.nLists],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={listChildren:{dependencyType:"child",childGroups:["lists"],variableNames:["values","type"],childIndices:[n]}};return{globalDependencies:{type:{dependencyType:"stateVariable",variableName:"type"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(t[a].listChildren&&1===t[a].listChildren.length){let n=t[a].listChildren[0];n.stateValues.type===e.type?r[a]=n.stateValues.values:r[a]=n.stateValues.values.map((t=>convertValueToType(t,e.type)))}return{setValue:{lists:r}}}},e}}function convertValueToType(e,t){if(Array.isArray(e)&&(e=e[0]),"number"===t){if(e instanceof me$3.class){let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}return Number(e)}if("math"===t){if("string"==typeof e)try{return me$3.fromAst(textToAst$1.convert(e))}catch(e){}return convertValueToMathExpression(e)}return"boolean"===t?Boolean(e):String(e)}var ComponentWithSelectableType$1=Object.freeze({__proto__:null,ComponentWithSelectableType:ComponentWithSelectableType,ComponentListWithSelectableType:ComponentListWithSelectableType,ComponentListOfListsWithSelectableType:ComponentListOfListsWithSelectableType});class SideBySide extends BlockComponent{static componentType="sideBySide";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize"},e.widths={createComponentOfType:"_componentSizeList"},e.margins={createComponentOfType:"_componentSizeList"},e.valign={createComponentOfType:"text"},e.valigns={createComponentOfType:"textList"},e}static returnChildGroups(){return[{group:"blocks",componentTypes:["_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPanels={forRenderer:!0,returnDependencies:()=>({blockChildren:{dependencyType:"child",childGroups:["blocks"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{nPanels:e.blockChildren.length},checkForActualChange:{nPanels:!0}})},e.essentialWidths={isArray:!0,entryPrefixes:["essentialWidth"],defaultValueByArrayKey:()=>null,hasEssential:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialWidths:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialWidths)t[n]=e.essentialWidths[n];return{success:!0,instructions:[{setEssentialValue:"essentialWidths",value:t}]}}},e.allWidthsSpecified={additionalStateVariablesDefined:["widthsAbsolute"],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents","componentSizes"]},parentWidths:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"specifiedWidths"},parentWidthsAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"widthsAbsolute"},essentialWidth:{dependencyType:"stateVariable",variableName:"essentialWidths"}}),definition({dependencyValues:e}){let t,n=[],r=null,a=!1;null!==e.widthsAttr?t=e.widthsAttr.stateValues.nComponents:null!==e.widthAttr?(t=e.nPanels,a=!0):t=0;for(let i=0;iNumber.isFinite(e)?e:null)),{setValue:{allWidthsSpecified:n,widthsAbsolute:r}}}},e.essentialMargins={isArray:!0,entryPrefixes:["essentialMargin"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialMargins:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialMargins)t[n]=e.essentialMargins[n];return{success:!0,instructions:[{setEssentialValue:"essentialMargins",value:t}]}}},e.allMarginsSpecified={additionalStateVariablesDefined:["marginsAbsolute"],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["nComponents","componentSizes"]},parentMargins:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"specifiedMargins"},parentMarginsAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"marginsAbsolute"},essentialMargins:{dependencyType:"stateVariable",variableName:"essentialMargins"}}),definition({dependencyValues:e}){let t=[],n=null;if(null===e.marginsAttr)if(e.parentMargins){n=e.parentMarginsAbsolute;for(let n=0;n<2;n++)null===e.essentialMargins[n]?t[n]=e.parentMargins[n]:t[n]=e.essentialMargins[n]}else for(let n=0;n<2;n++)t[n]=e.essentialMargins[n];else if(0===e.marginsAttr.stateValues.nComponents)for(let n=0;n<2;n++)t[n]=e.essentialMargins[n];else if(1===e.marginsAttr.stateValues.nComponents){let r=null;e.marginsAttr.stateValues.componentSizes[0]&&(r=e.marginsAttr.stateValues.componentSizes[0].size,Number.isFinite(r)||(r=null),n=Boolean(e.marginsAttr.stateValues.componentSizes[0].isAbsolute)),t=[r,r]}else{let r;if(n=!!e.marginsAttr.stateValues.componentSizes[0]&&Boolean(e.marginsAttr.stateValues.componentSizes[0].isAbsolute),r=!!e.marginsAttr.stateValues.componentSizes[1]&&Boolean(e.marginsAttr.stateValues.componentSizes[1].isAbsolute),r!==n)throw Error("SideBySide is not implemented for absolute measurements");t=e.marginsAttr.stateValues.componentSizes.slice(0,2).map((e=>e&&Number.isFinite(e.size)?e.size:null))}return{setValue:{allMarginsSpecified:t,marginsAbsolute:n}}}},e.absoluteMeasurements={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({widthsAbsolute:{dependencyType:"stateVariable",variableName:"widthsAbsolute"},marginsAbsolute:{dependencyType:"stateVariable",variableName:"marginsAbsolute"}}),definition({dependencyValues:e}){let t;if(null===e.widthsAbsolute)t=null!==e.marginsAbsolute&&e.marginsAbsolute;else if(null===e.marginsAbsolute)t=e.widthsAbsolute;else{if(e.widthsAbsolute!==e.marginsAbsolute)throw Error("SideBySide is not implemented for absolute measurements");t=e.widthsAbsolute}if(!0===t)throw Error("SideBySide is not implemented for absolute measurements");return{setValue:{absoluteMeasurements:t}}}},e.allWidths={additionalStateVariablesDefined:["allMargins",{variableName:"gapWidth",public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0}],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},allWidthsSpecified:{dependencyType:"stateVariable",variableName:"allWidthsSpecified"},allMarginsSpecified:{dependencyType:"stateVariable",variableName:"allMarginsSpecified"},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}}),definition({dependencyValues:e}){let t=0,n=[...e.allWidthsSpecified],r=[...e.allMarginsSpecified],a=0,i=0;for(let t=0;t=100){let t=100/(a+o);for(let r=0;r0){let t=(100-(a+o))/i;for(let r=0;r0){let t=(100-(a+o))/(s*e.nPanels);for(let e=0;e<2;e++)null===r[e]&&(r[e]=t)}else e.nPanels>1?t=(100-(a+o))/(e.nPanels-1):1===e.nPanels?r[1]=100-(r[0]+n[0]):console.warn("Invalid sideBySide, as it must have at least one block child");return{setValue:{allWidths:n,allMargins:r,gapWidth:t}}}},e.widths={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["width"],forRenderer:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey({arrayKeys:e}){let t={allWidths:{dependencyType:"stateVariable",variableName:"allWidths"},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}},n={};for(let t of e){let e=Number(t)+1;n[t]={widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:[`componentSize${e}`]},essentialWidth:{dependencyType:"stateVariable",variableName:`essentialWidth${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allWidths[r];return{setValue:{widths:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r,arraySize:a}){let i,o=!1;null!==r.widthsAttr?i=r.widthsAttr.stateValues.nComponents:null!==r.widthAttr?(i=a[0],o=!0):i=0;let s=[];for(let n in e.widths){Number(n)({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={allMargins:{dependencyType:"stateVariable",variableName:"allMargins"},marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["componentSize1","componentSize2","nComponents"]},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}},n={};for(let t of e){let e=Number(t)+1;n[t]={essentialMargin:{dependencyType:"stateVariable",variableName:`essentialMargin${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allMargins[r];return{setValue:{margins:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyNamesByKey:n}){let r=[];if(null===t.marginsAttr)for(let t in e.margins)r.push({setDependency:n[t].essentialMargin,desiredValue:e.margins[t]});else if(t.marginsAttr.stateValues.componentSize1&&Number.isFinite(t.marginsAttr.stateValues.componentSize1.size)){let n=1===t.marginsAttr.stateValues.nComponents;for(let a in e.margins)n?r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[a],isAbsolute:t.absoluteMeasurements},variableIndex:0}):r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[a],isAbsolute:t.absoluteMeasurements},variableIndex:a})}else"0"in e.margins?r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[0],isAbsolute:t.absoluteMeasurements},variableIndex:0}):r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[1],isAbsolute:t.absoluteMeasurements},variableIndex:0}),"1"in e.margins&&t.marginsAttr.stateValues.nComponents>1&&r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[1],isAbsolute:t.absoluteMeasurements},variableIndex:1});return{success:!0,instructions:r}}},e.essentialValigns={isArray:!0,entryPrefixes:["essentialValign"],defaultValueByArrayKey:()=>null,hasEssential:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialValigns:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialValigns)t[n]=e.essentialValigns[n];return{success:!0,instructions:[{setEssentialValue:"essentialValigns",value:t}]}}},e.valigns={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"text"},entryPrefixes:["valign"],forRenderer:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:[`text${e}`]},parentValign:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:`valign${e}`},parentValignAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:`valignAbsolute${e}`},essentialValign:{dependencyType:"stateVariable",variableName:`essentialValign${e}`}}}return{globalDependencies:{valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},o=!1;null!==e.valignsAttr?a=e.valignsAttr.stateValues.nComponents:null!==e.valignAttr?(a=r[0],o=!0):a=0;for(let r of n){let n=Number(r);if(n({sideBySideChildren:{dependencyType:"child",childGroups:["sideBySides"],variableNames:["nPanels"]}}),definition:({dependencyValues:e})=>({setValue:{maxNPanelsPerRow:me$3.math.max(e.sideBySideChildren.map((e=>e.stateValues.nPanels)))},checkForActualChange:{maxNPanelsPerRow:!0}})},e.specifiedWidths={additionalStateVariablesDefined:[{variableName:"widthsAbsoluteArray",isArray:!0}],isArray:!0,entryPrefixes:["specifiedWidth"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:[`componentSize${e}`]}}}return{globalDependencies:{widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},o={},s={},l=!1;null!==e.widthsAttr?a=e.widthsAttr.stateValues.nComponents:null!==e.widthAttr?(a=r[0],l=!0):a=0;for(let r of n){let n=Number(r);if(n0&&(u.useEssentialOrDefaultValue={specifiedWidths:o}),u},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,stateValues:r,arraySize:a}){let i,o=!1;null!==n.widthsAttr?i=n.widthsAttr.stateValues.nComponents:null!==n.widthAttr?(i=a[0],o=!0):i=0;let s=[];for(let n in e.specifiedWidths){Number(n)({widthsAbsoluteArray:{dependencyType:"stateVariable",variableName:"widthsAbsoluteArray"}}),definition({dependencyValues:e}){let t=null;for(let n in e.widthsAbsoluteArray){let r=e.widthsAbsoluteArray[n];if(null!==r)if(r=Boolean(r),null===t)t=r;else if(t!==r)throw Error("SbsGroup is not implemented for absolute measurements")}return{setValue:{widthsAbsolute:t}}}},e.specifiedMargins={additionalStateVariablesDefined:[{variableName:"marginsAbsoluteArray",isArray:!0,entryPrefixes:["marginAbsolute"]}],isArray:!0,entryPrefixes:["specifiedMargin"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:({arrayKeys:e})=>({globalDependencies:{marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["componentSize1","componentSize2","nComponents"]}}}),arrayDefinitionByKey({dependencyValuesByKey:e,globalDependencyValues:t,arrayKeys:n}){let r={},a={},i={};if(null===t.marginsAttr||0===t.marginsAttr.stateValues.nComponents)for(let e of n)a[e]=!0,i[e]=null;else if(1===t.marginsAttr.stateValues.nComponents){let e=null,a=null;t.marginsAttr.stateValues.componentSize1&&(e=t.marginsAttr.stateValues.componentSize1.size,Number.isFinite(e)||(e=null),a=Boolean(t.marginsAttr.stateValues.componentSize1.isAbsolute));for(let t of n)r[t]=e,i[t]=a}else for(let e of n)if(t.marginsAttr.stateValues[`componentSize${Number(e)+1}`]){let n=t.marginsAttr.stateValues[`componentSize${Number(e)+1}`].size;Number.isFinite(n)||(n=null);let a=Boolean(t.marginsAttr.stateValues[`componentSize${Number(e)+1}`].isAbsolute);r[e]=n,i[e]=a}let o={setValue:{marginsAbsoluteArray:i,specifiedMargins:r}};return Object.keys(a).length>0&&(o.useEssentialOrDefaultValue={specifiedMargins:a}),o},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,stateValues:r}){let a=[];if(null===n.marginsAttr)a.push({setEssentialValue:"specifiedMargins",value:e.specifiedMargins});else if(n.marginsAttr.stateValues.componentSize1&&Number.isFinite(n.marginsAttr.stateValues.componentSize1.size)){let t=1===n.marginsAttr.stateValues.nComponents;for(let n in e.specifiedMargins)t?a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[n],isAbsolute:await r.marginsAbsolute},variableIndex:0}):a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[n],isAbsolute:await r.marginsAbsolute},variableIndex:n})}else"0"in e.specifiedMargins?a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[0],isAbsolute:await r.marginsAbsolute},variableIndex:0}):a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[1],isAbsolute:await r.marginsAbsolute},variableIndex:0}),"1"in e.specifiedMargins&&n.marginsAttr.stateValues.nComponents>1&&a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[1],isAbsolute:await r.marginsAbsolute},variableIndex:1});return{success:!0,instructions:a}}},e.marginsAbsolute={returnDependencies:()=>({marginsAbsoluteArray:{dependencyType:"stateVariable",variableName:"marginsAbsoluteArray"}}),definition({dependencyValues:e}){let t=null;for(let n in e.marginsAbsoluteArray){let r=e.marginsAbsoluteArray[n];if(null!==r)if(r=Boolean(r),null===t)t=r;else if(t!==r)throw Error("SbsGroup is not implemented for absolute measurements")}return{setValue:{marginsAbsolute:t}}}},e.absoluteMeasurements={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({widthsAbsolute:{dependencyType:"stateVariable",variableName:"widthsAbsolute"},marginsAbsolute:{dependencyType:"stateVariable",variableName:"marginsAbsolute"}}),definition({dependencyValues:e}){let t;if(null===e.widthsAbsolute)t=null!==e.marginsAbsolute&&e.marginsAbsolute;else if(null===e.marginsAbsolute)t=e.widthsAbsolute;else{if(e.widthsAbsolute!==e.marginsAbsolute)throw Error("SbsGroup is not implemented for absolute measurements");t=e.widthsAbsolute}if(!0===t)throw Error("SbsGroup is not implemented for absolute measurements");return{setValue:{absoluteMeasurements:t}}}},e.allWidths={additionalStateVariablesDefined:["allMargins",{variableName:"gapWidth",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"},specifiedWidths:{dependencyType:"stateVariable",variableName:"specifiedWidths"},specifiedMargins:{dependencyType:"stateVariable",variableName:"specifiedMargins"},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}}),definition({dependencyValues:e}){let t=0,n=[...e.specifiedWidths],r=[...e.specifiedMargins],a=0,i=0;for(let t=0;t=100){let t=100/(a+o);for(let r=0;r0){let t=(100-(a+o))/i;for(let r=0;r0){let t=(100-(a+o))/(s*e.maxNPanelsPerRow);for(let e=0;e<2;e++)null===r[e]&&(r[e]=t)}else e.maxNPanelsPerRow>1?t=(100-(a+o))/(e.maxNPanelsPerRow-1):1===e.maxNPanelsPerRow?r[1]=100-(r[0]+n[0]):console.warn("Invalid sideBySide, as it must have at least one block child");return{setValue:{allWidths:n,allMargins:r,gapWidth:t}}}},e.widths={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["width"],returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={allWidths:{dependencyType:"stateVariable",variableName:"allWidths"}},n={};for(let t of e){let e=Number(t)+1;n[t]={specifiedWidth:{dependencyType:"stateVariable",variableName:`specifiedWidth${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allWidths[r];return{setValue:{widths:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.widths)n.push({setDependency:t[r].specifiedWidth,desiredValue:e.widths[r],variableIndex:0});return{success:!0,instructions:n}}},e.margins={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["margin"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={allMargins:{dependencyType:"stateVariable",variableName:"allMargins"}},n={};for(let t of e){let e=Number(t)+1;n[t]={specifiedMargin:{dependencyType:"stateVariable",variableName:`specifiedMargin${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allMargins[r];return{setValue:{margins:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.margins)n.push({setDependency:t[r].specifiedMargin,desiredValue:e.margins[r],variableIndex:0});return{success:!0,instructions:n}}},e.valigns={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"text"},entryPrefixes:["valign"],hasEssential:!0,defaultValueByArrayKey:()=>"top",returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:[`text${e}`]}}}return{globalDependencies:{valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},o={},s=!1;null!==e.valignsAttr?a=e.valignsAttr.stateValues.nComponents:null!==e.valignAttr?(a=r[0],s=!0):a=0;for(let r of n){let n=Number(r);if(n0&&(l.setValue={valigns:i}),Object.keys(o).length>0&&(l.useEssentialOrDefaultValue={valigns:o}),l},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,arraySize:r}){let a,i=!1;null!==n.valignsAttr?a=n.valignsAttr.stateValues.nComponents:null!==n.valignAttr?(a=r[0],i=!0):a=0;let o=[];for(let n in e.valigns){let r=e.valigns[n].toLowerCase();["top","middle","bottom"].includes(r)&&(Number(n)({stringTextChildren:{dependencyType:"child",childGroups:["stringsTexts"],variableNames:["value"]},hChildren:{dependencyType:"child",childGroups:["hs"],variableNames:["value"]}}),definition({dependencyValues:e}){let t;if(e.hChildren.length>0)t=e.hChildren.map((e=>e.stateValues.value));else{let n="";for(let t of e.stringTextChildren)n+="string"==typeof t?t:t.stateValues.value;t=[n]}return{setValue:{terms:t}}}},e}}var Indexing=Object.freeze({__proto__:null,H:H$2,Idx:Idx});class Div extends BlockComponent{static componentType="div";static rendererType="containerBlock";static renderChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class Span extends InlineComponent{static componentType="span";static rendererType="containerInline";static renderChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}}var Divisions=Object.freeze({__proto__:null,Div:Div,Span:Span});class Pre extends BlockComponent{static componentType="pre";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={recordVisibilityChange:this.recordVisibilityChange.bind(this)}}var Verbatim=Object.freeze({__proto__:null,Pre:Pre});class Paginator extends BlockComponent{static componentType="paginator";static rendererType="containerBlock";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.initialPage={createComponentOfType:"integer",createStateVariable:"initialPage",defaultValue:1},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPages={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"]}}),definition:({dependencyValues:e})=>({setValue:{nPages:e.children.length}})},e.currentPage={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,returnDependencies:()=>({initialPage:{dependencyType:"stateVariable",variableName:"initialPage"},nPages:{dependencyType:"stateVariable",variableName:"nPages"}}),definition:({dependencyValues:e})=>({useEssentialOrDefaultValue:{currentPage:{get defaultValue(){let t=e.initialPage;return Number.isInteger(t)?Math.max(1,Math.min(e.nPages,t)):1}}}}),async inverseDefinition({desiredStateVariableValues:e,stateValues:t,sourceInformation:n={}}){if(!n.fromSetPage)return{success:!1};let r=Number(e.currentPage);return Number.isInteger(r)?(r=Math.max(1,Math.min(await t.nPages,r)),{success:!0,instructions:[{setEssentialValue:"currentPage",value:r}]}):{success:!1}}},e.childIndicesToRender={returnDependencies:()=>({currentPage:{dependencyType:"stateVariable",variableName:"currentPage"}}),definition:({dependencyValues:e})=>({setValue:{childIndicesToRender:[e.currentPage-1]}}),markStale:()=>({updateRenderedChildren:!0})},e}async setPage({number:e,actionId:t}){if(!Number.isInteger(e))return void this.coreFunctions.resolveAction({actionId:t});let n=Math.max(1,Math.min(await this.stateValues.nPages,e)),r=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"currentPage",value:n,sourceInformation:{fromSetPage:!0}}];await this.coreFunctions.performUpdate({updateInstructions:r,actionId:t,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:n,responseText:n.toString()}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={setPage:this.setPage.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class PaginatorControls extends BlockComponent{constructor(e){super(e),this.externalActions={},Object.defineProperty(this.externalActions,"setPage",{enumerable:!0,get:async function(){let e=await this.stateValues.paginatorComponentName;return e?{componentName:e,actionName:"setPage"}:void 0}.bind(this)})}static componentType="paginatorControls";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.previousLabel={createComponentOfType:"text",createStateVariable:"previousLabel",defaultValue:"Previous",forRenderer:!0,public:!0},e.nextLabel={createComponentOfType:"text",createStateVariable:"nextLabel",defaultValue:"Next",forRenderer:!0,public:!0},e.pageLabel={createComponentOfType:"text",createStateVariable:"pageLabel",defaultValue:"Page",forRenderer:!0,public:!0},e.paginator={createPrimitiveOfType:"string",createStateVariable:"paginator",defaultValue:null},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.paginatorComponentName={stateVariablesDeterminingDependencies:["paginator"],returnDependencies:({stateValues:e})=>e.paginator?{paginatorComponentName:{dependencyType:"expandTargetName",target:e.paginator}}:{},definition:({dependencyValues:e})=>({setValue:{paginatorComponentName:e.paginatorComponentName}})},e.currentPage={forRenderer:!0,stateVariablesDeterminingDependencies:["paginatorComponentName"],returnDependencies:({stateValues:e})=>e.paginatorComponentName?{paginatorPage:{dependencyType:"stateVariable",componentName:e.paginatorComponentName,variableName:"currentPage"}}:{},definition:({dependencyValues:e})=>"paginatorPage"in e?{setValue:{currentPage:e.paginatorPage}}:{setValue:{currentPage:1}}},e.nPages={forRenderer:!0,stateVariablesDeterminingDependencies:["paginatorComponentName"],returnDependencies:({stateValues:e})=>e.paginatorComponentName?{paginatorNPages:{dependencyType:"stateVariable",componentName:e.paginatorComponentName,variableName:"nPages"}}:{},definition:({dependencyValues:e})=>"paginatorNPages"in e?{setValue:{nPages:e.paginatorNPages}}:{setValue:{nPages:1}}},e}}var Paginator$1=Object.freeze({__proto__:null,Paginator:Paginator,PaginatorControls:PaginatorControls});class Input extends InlineComponent{static componentType="_input";static createAttributesObject(){let e=super.createAttributesObject();return e.collaborateGroups={createComponentOfType:"collaborateGroups",createStateVariable:"collaborateGroups",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nValues={returnDependencies:()=>({}),definition:()=>({setValue:{nValues:1}})},e.answerAncestor={returnDependencies:()=>({answerAncestor:{dependencyType:"ancestor",componentType:"answer",variableNames:["delegateCheckWorkToInput","justSubmitted","creditAchieved","showCorrectness","numberOfAttemptsLeft"]}}),definition:function({dependencyValues:e}){return{setValue:{answerAncestor:e.answerAncestor}}}},e.includeCheckWork={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=!1;return e.answerAncestor&&(t=e.answerAncestor.stateValues.delegateCheckWorkToInput),{setValue:{includeCheckWork:t}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e.creditAchieved={defaultValue:0,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=0;return e.answerAncestor&&(t=e.answerAncestor.stateValues.creditAchieved),{setValue:{creditAchieved:t}}}},e.valueHasBeenValidated={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=!1;return e.answerAncestor&&e.answerAncestor.stateValues.justSubmitted&&(t=!0),{setValue:{valueHasBeenValidated:t}}}},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"},answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition({dependencyValues:e}){let t;return t=e.answerAncestor?e.answerAncestor.stateValues.showCorrectness:!1!==e.showCorrectnessFlag,{setValue:{showCorrectness:t}}}},e.numberOfAttemptsLeft={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition({dependencyValues:e}){let t;return t=e.answerAncestor?e.answerAncestor.stateValues.numberOfAttemptsLeft:1/0,{setValue:{numberOfAttemptsLeft:t}}}},e}}class MatrixInput extends Input{constructor(e){super(e),this.actions={updateNumRows:this.updateNumRows.bind(this),updateNumColumns:this.updateNumColumns.bind(this)},this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="matrixInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.numRows={createComponentOfType:"integer",createStateVariable:"numRowsPreliminary",defaultValue:1,transformNonFiniteTo:0},e.numColumns={createComponentOfType:"integer",createStateVariable:"numColumnsPreliminary",defaultValue:1,transformNonFiniteTo:0},e.showSizeControls={createComponentOfType:"boolean",createStateVariable:"showSizeControls",defaultValue:!0,public:!0,forRenderer:!0},e.defaultEntry={createComponentOfType:"math",createStateVariable:"defaultEntry",defaultValue:me$3.fromAst("_")},e.prefill={createComponentOfType:"math",createStateVariable:"prefill",defaultValue:me$3.fromAst("_"),public:!0,copyComponentAttributesForCreatedComponent:["format","functionSymbols","splitSymbols","parseScientificNotation"]},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"math"},e.unionFromU={createComponentOfType:"boolean",createStateVariable:"unionFromU",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){if(e.length>0)return{success:!1};return{success:!0,newChildren:[{componentType:"matrixInputGrid"}]}}}),e}static returnChildGroups(){return[{group:"matrixComponentInputs",componentTypes:["matrixComponentInput"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.valueOriginal={hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{valueOriginal:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{valueOriginal:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.valueOriginal,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"valueOriginal",value:e.valueOriginal}]}}},e.immediateValueOriginal={hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.valueOriginal&&!n?{setValue:{immediateValueOriginal:e.valueOriginal},setEssentialValue:{immediateValueOriginal:e.valueOriginal}}:{useEssentialOrDefaultValue:{immediateValueOriginal:{defaultValue:e.valueOriginal}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValueOriginal",value:e.immediateValueOriginal}];return t||n||r.push({setDependency:"valueOriginal",desiredValue:e.immediateValueOriginal}),{success:!0,instructions:r}}},e.haveBoundValue={returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo"}}),definition:({dependencyValues:e})=>({setValue:{haveBoundValue:null!==e.bindValueTo}})},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},forRenderer:!0,returnDependencies:()=>({numRowsPreliminary:{dependencyType:"stateVariable",variableName:"numRowsPreliminary"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},haveBoundValue:{dependencyType:"stateVariable",variableName:"haveBoundValue"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.numRowsPreliminary;if(t.numRowsPreliminary||e.haveBoundValue){let t=e.valueOriginal.tree;if(n=1,Array.isArray(t)){let e=t[0];"matrix"===e?n=t[1][1]:"vector"!==e&&"tuple"!=e||(n=t.length-1)}}return{setValue:{numRows:n}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){let r=e.numRows;if(!Number.isInteger(r))return{success:!1};r=Math.max(0,r);let a=[{setDependency:"numRowsPreliminary",desiredValue:r}];if(t.haveBoundValue){let e=t.valueOriginal.tree,i=(await n.defaultEntry).tree;if(1!==await n.numColumns||!Array.isArray(e)||"vector"!==e[0]&&"tuple"!==e[0]){let e=deepClone((await n.value).tree),t=e[1][1];if(e[1][1]=r,r!==t){if(rt){let o=deepClone(e),s=await n.accumulatedComponents;for(let e=t;e({numColumnsPreliminary:{dependencyType:"stateVariable",variableName:"numColumnsPreliminary"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},haveBoundValue:{dependencyType:"stateVariable",variableName:"haveBoundValue"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.numColumnsPreliminary;if(t.numColumnsPreliminary||e.haveBoundValue){let t=e.valueOriginal.tree;if(n=1,Array.isArray(t)){let e=t[0];"matrix"===e?n=t[1][2]:!Array.isArray(t[1])||"vector"!==t[1][0]&&"tuple"!==t[1][0]||("^"!==e||"T"!==t[2])&&"prime"!==e||(n=t[1].length-1)}}return{setValue:{numColumns:n}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){let r=e.numColumns;if(!Number.isInteger(r))return{success:!1};r=Math.max(0,r);let a=[{setDependency:"numColumnsPreliminary",desiredValue:r}];if(t.haveBoundValue){let e=(await n.defaultEntry).tree,i=t.valueOriginal.tree,o=i[0];if(!Array.isArray(i[1])||"vector"!==i[1][0]&&"tuple"!==i[1][0]||("^"!==o||"T"!==i[2])&&"prime"!==o){let t=deepClone((await n.value).tree),i=t[1][2];if(t[1][2]=r,r!==i){let o=await n.numRows,s=t[2];if(rt){let o=deepClone(i),s=(await n.accumulatedComponents)[0];s||(s=[]);for(let n=t;n({valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),definition({dependencyValues:e,previousValues:t}){let n=[];t.accumulatedComponents&&(n=deepClone(t.accumulatedComponents));let r=e.valueOriginal.tree;if(Array.isArray(r)){let e=r[0];if("matrix"===e){let e=r[2];for(let[t,r]of e.slice(1).entries()){let e=n[t];e||(e=n[t]=[]);for(let[t,n]of r.slice(1).entries())e[t]=n}return{setValue:{accumulatedComponents:n}}}if("vector"===e||"tuple"===e){for(let[e,t]of r.slice(1).entries()){let r=n[e];r||(r=n[e]=[]),r[0]=t}return{setValue:{accumulatedComponents:n}}}if(Array.isArray(r[1])&&("vector"===r[1][0]||"tuple"===r[1][0])&&("^"===e&&"T"===r[2]||"prime"===e)){let e=n[0];e||(e=n[0]=[]);for(let[t,n]of r[1].slice(1).entries())e[t]=n;return{setValue:{accumulatedComponents:n}}}}let a=n[0];return a||(a=n[0]=[]),a[0]=r,{setValue:{accumulatedComponents:n}}}},e.componentValues={isArray:!0,entryPrefixes:["componentValue"],nDimensions:2,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},accumulatedComponents:{dependencyType:"stateVariable",variableName:"accumulatedComponents"},defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n=e.valueOriginal.tree,r=e.accumulatedComponents,a=e.numRows,i=e.numColumns;if(Array.isArray(n)){let t=n[0];if("matrix"===t){if(n[1][1]===a&&n[1][2]===i){let e={},t=n[2];for(let n=0;no)for(let t=0;tt)for(let n=t;n[...e]));else{let e=t.valueOriginal.tree;if(s){if(a=e.slice(1,1+i).map((e=>[e])),a.length1)for(let e=0;e1)for(let e=1;ee.slice(1,o+1))),a[0].length1&&a[0].push(...Array(o-1).fill("_")),i>1)for(let e=1;ee[0]))]);return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:r,treatAsInitialChange:n}]}}if(1===i&&l){let e=t.valueOriginal.tree,r=e[0],i=[e[1][0],...a[0]];return i="^"===r?me$3.fromAst(["^",i,"T"]):me$3.fromAst(["prime",i]),{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:i,treatAsInitialChange:n}]}}{let e=["matrix",["tuple",t.numRows,t.numColumns],["tuple",...a.map((e=>["tuple",...e]))]];return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:me$3.fromAst(e),treatAsInitialChange:n}]}}}},e.componentImmediateValues={isArray:!0,entryPrefixes:["componentImmediateValue"],nDimensions:2,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{immediateValueOriginal:{dependencyType:"stateVariable",variableName:"immediateValueOriginal"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},accumulatedComponents:{dependencyType:"stateVariable",variableName:"accumulatedComponents"},defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n=e.immediateValueOriginal.tree,r=e.accumulatedComponents,a=e.numRows,i=e.numColumns;if(Array.isArray(n)){let t=n[0];if("matrix"===t){if(n[1][1]===a&&n[1][2]===i){let e={},t=n[2];for(let n=0;no)for(let t=0;tt)for(let n=t;n[...e]));else{let e=t.immediateValueOriginal.tree;if(s){if(a=e.slice(1,1+i).map((e=>[e])),a.length1)for(let e=0;e1)for(let e=1;ee.slice(1,o+1))),a[0].length1&&a[0].push(...Array(o-1).fill("_")),i>1)for(let e=1;ee[0]))]);return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:r,treatAsInitialChange:n}]}}if(1===i&&l){let e=t.immediateValueOriginal.tree,r=e[0],i=[e[1][0],...a[0]];return i="^"===r?me$3.fromAst(["^",i,"T"]):me$3.fromAst(["prime",i]),{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:i,treatAsInitialChange:n}]}}{let e=["matrix",["tuple",t.numRows,t.numColumns],["tuple",...a.map((e=>["tuple",...e]))]];return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:me$3.fromAst(e),treatAsInitialChange:n}]}}}},e.componentValuesForDisplay={isArray:!0,entryPrefixes:["componentValueForDisplay"],nDimensions:2,forRenderer:!0,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={componentValue:{dependencyType:"stateVariable",variableName:`componentValue${a}`}}}return{globalDependencies:{displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,usedDefault:r}){let a={};for(let i of n){let n=roundForDisplay({value:t[i].componentValue,dependencyValues:e,usedDefault:r});a[i]=n}return{setValue:{componentValuesForDisplay:a}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({componentValues:{dependencyType:"stateVariable",variableName:"componentValues"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),definition({dependencyValues:e}){let t=e.numRows,n=e.numColumns,r=["matrix",["tuple",t,n]],a=r[2]=["tuple"];for(let r=0;re[1]))]);return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:e}]}}}}else if(1===t.numRows){let e=t.valueOriginal.tree;if(Array.isArray(e)){let t=e[0];if(Array.isArray(e[1])&&("vector"===e[1][0]||"tuple"===e[1][0])&&("^"===t&&"T"===e[2]||"prime"===t)){let r=[e[1][0],...n[2][1].slice(1)];return r="^"===t?me$3.fromAst(["^",r,"T"]):me$3.fromAst(["prime",r]),{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:r}]}}}}return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:e.value}]}}return{success:!1}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({componentImmediateValues:{dependencyType:"stateVariable",variableName:"componentImmediateValues"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},immediateValueOriginal:{dependencyType:"stateVariable",variableName:"immediateValueOriginal"}}),definition({dependencyValues:e}){let t=e.numRows,n=e.numColumns,r=["matrix",["tuple",t,n]],a=r[2]=["tuple"];for(let r=0;re[1]))]);return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:e}]}}}}else if(1===t.numRows){let e=t.immediateValueOriginal.tree;if(Array.isArray(e)){let t=e[0];if(Array.isArray(e[1])&&("vector"===e[1][0]||"tuple"===e[1][0])&&("^"===t&&"T"===e[2]||"prime"===t)){let r=[e[1][0],...n[2][1].slice(1)];return r="^"===t?me$3.fromAst(["^",r,"T"]):me$3.fromAst(["prime",r]),{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:r}]}}}}return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:e.immediateValue}]}}return{success:!1}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"matrix"}})},e}async updateRawValues({rawRendererValues:e,transient:t=!1,actionId:n}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValues",value:e}],transient:t,actionId:n});this.coreFunctions.resolveAction({actionId:n})}async updateNumRows({numRows:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"numRows",value:e}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateNumColumns({numColumns:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"numColumns",value:e}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}static adapters=[{stateVariable:"value",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]}]}class MatrixInputGrid extends CompositeComponent{static componentType="matrixInputGrid";static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numRows={returnDependencies:()=>({parentNumRows:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numRows"}}),definition:({dependencyValues:e})=>({setValue:{numRows:e.parentNumRows}})},e.numColumns={returnDependencies:()=>({parentNumColumns:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numColumns"}}),definition:({dependencyValues:e})=>({setValue:{numColumns:e.parentNumColumns}})},e.readyToExpandWhenResolved={returnDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=await e.stateValues.numRows;r.previousNumRows=i;for(let e=0;es&&(u=l-s,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=u){i=e.replacementsToWithhold-u,s+=u,u=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:i};o.push(t)}else u-=e.replacementsToWithhold,s+=e.replacementsToWithhold,i=0;if(u>0){let e=[];for(let t=s;t({}),definition:()=>({useEssentialOrDefaultValue:{rowInd:!0}})},e.numColumns={returnDependencies:()=>({parentNumColumns:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numColumns"}}),definition:({dependencyValues:e})=>({setValue:{numColumns:e.parentNumColumns}})},e.readyToExpandWhenResolved={returnDependencies:()=>({numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}j;static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=await e.stateValues.numColumns,o=await e.stateValues.rowInd;r.previousNumColumns=i;for(let e=0;es&&(c=l-s,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=c){i=e.replacementsToWithhold-c,s+=c,c=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:i};o.push(t)}else c-=e.replacementsToWithhold,s+=e.replacementsToWithhold,i=0;if(c>0){let e=[];for(let t=s;t({}),definition:()=>({useEssentialOrDefaultValue:{rowInd:!0}})},e.colInd={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{colInd:!0}})},e.format={returnDependencies:()=>({parentFormat:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"format"}}),definition:({dependencyValues:e})=>({setValue:{format:e.parentFormat}})},e.functionSymbols={returnDependencies:()=>({parentFunctionSymbols:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"functionSymbols"}}),definition:({dependencyValues:e})=>({setValue:{functionSymbols:e.parentFunctionSymbols}})},e.splitSymbols={returnDependencies:()=>({parentSplitSymbols:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"splitSymbols"}}),definition:({dependencyValues:e})=>({setValue:{splitSymbols:e.parentSplitSymbols}})},e.parseScientificNotation={returnDependencies:()=>({parentParseScientificNotation:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"parseScientificNotation"}}),definition:({dependencyValues:e})=>({setValue:{parseScientificNotation:e.parentParseScientificNotation}})},e.displayDigits={returnDependencies:()=>({parentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displayDigits"}}),definition({dependencyValues:e,usedDefault:t}){let n={setValue:{displayDigits:e.parentDisplayDigits}};return t.parentDisplayDigits&&(n.markAsUsedDefault={displayDigits:!0}),n}},e.displayDecimals={returnDependencies:()=>({parentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displayDecimals"}}),definition({dependencyValues:e,usedDefault:t}){let n={setValue:{displayDecimals:e.parentDisplayDecimals}};return t.parentDisplayDecimals&&(n.markAsUsedDefault={displayDecimals:!0}),n}},e.displaySmallAsZero={returnDependencies:()=>({parentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displaySmallAsZero"}}),definition:({dependencyValues:e})=>({setValue:{displaySmallAsZero:e.parentDisplaySmallAsZero}})},e.unionFromU={returnDependencies:()=>({parentUnionFromU:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"unionFromU"}}),definition:({dependencyValues:e})=>({setValue:{unionFromU:e.parentUnionFromU}})},e.value={stateVariablesDeterminingDependencies:["rowInd","colInd"],returnDependencies:({stateValues:e})=>{let t="";return null!==e.rowInd&&null!==e.colInd&&(t=`${e.rowInd+1}_${e.colInd+1}`),{parentComponentValue:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:`componentValue${t}`}}},definition:function({dependencyValues:e}){return e.parentComponentValue?{setValue:{value:e.parentComponentValue}}:{setValue:{value:me$3.fromAst("_")}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return{success:!0,instructions:[{setDependency:"parentComponentValue",desiredValue:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},stateVariablesDeterminingDependencies:["rowInd","colInd"],returnDependencies:({stateValues:e})=>{let t="";return null!==e.rowInd&&null!==e.colInd&&(t=`${e.rowInd+1}_${e.colInd+1}`),{parentComponentImmediateValue:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:`componentImmediateValue${t}`}}},definition:function({dependencyValues:e}){return{setValue:{immediateValue:e.parentComponentImmediateValue}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return{success:!0,instructions:[{setDependency:"parentComponentImmediateValue",desiredValue:e.immediateValue,treatAsInitialChange:t}]}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.valueForDisplay.toString()}}}},e.rawRendererValue={forRenderer:!0,hasEssential:!0,shadowVariable:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"lastValueForDisplay",hasEssential:!0,shadowVariable:!0,defaultValue:null,set:convertValueToMathExpression}],returnDependencies:()=>({immediateValue:{dependencyType:"stateVariable",variableName:"immediateValue"},valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition({dependencyValues:e,essentialValues:t}){if(void 0!==t.rawRendererValue&&deepCompare(t.lastValueForDisplay.tree,e.valueForDisplay.tree))return{useEssentialOrDefaultValue:{rawRendererValue:!0,lastValueForDisplay:!0}};{let t=stripLatex(e.valueForDisplay.toLatex());return"_"===t&&(t=""),{setValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay},setEssentialValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay}}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t,essentialValues:n}){const r=async e=>{let n;e=(e=normalizeLatexString(e,{unionFromU:await t.unionFromU})).replace(/\^(\w)/g,"^{$1}");let r=getFromLatex({functionSymbols:await t.functionSymbols,splitSymbols:await t.splitSymbols,parseScientificNotation:await t.parseScientificNotation});try{n=r(e)}catch(e){n=me$3.fromAst("_")}return n};let a=[];if("string"==typeof e.rawRendererValue){let t=n.rawRendererValue,i=e.rawRendererValue;t!==i&&a.push({setEssentialValue:"rawRendererValue",value:i});let o=await r(t),s=await r(i);deepCompare(s.tree,o.tree)||a.push({setDependency:"immediateValue",desiredValue:s,treatAsInitialChange:!0})}else{a.push({setEssentialValue:"lastValueForDisplay",value:e.rawRendererValue});let t=await r(n.rawRendererValue);if(!deepCompare(e.rawRendererValue.tree,t.tree)){let t=stripLatex(e.rawRendererValue.toLatex());"_"===t&&(t=""),a.push({setEssentialValue:"rawRendererValue",value:t})}}return{success:!0,instructions:a}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"math"}})},e}async updateRawValue({rawRendererValue:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.immediateValue;if(!deepCompare((await this.stateValues.value).tree,t.tree)){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}];"_"!==t.tree&&n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"valueForDisplay"});let r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"rawRendererValue"}],actionId:e})}}}var MatrixInput$1=Object.freeze({__proto__:null,MatrixInput:MatrixInput,MatrixInputGrid:MatrixInputGrid,MatrixInputRow:MatrixInputRow,default:MatrixComponentInput});class Document extends BaseComponent{static componentType="document";static rendererType="section";static renderChildren=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return delete e.hide,delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.documentWideCheckWork={createComponentOfType:"boolean",createStateVariable:"documentWideCheckWork",defaultValue:!1,public:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0},e.displayDigitsForCreditAchieved={createComponentOfType:"integer",createStateVariable:"displayDigitsForCreditAchieved",defaultValue:3,public:!0},e.xmlns={createPrimitiveOfType:"string"},e.type={createPrimitiveOfType:"string"},e}static returnChildGroups(){return[{group:"variantControl",componentTypes:["variantControl"]},{group:"title",componentTypes:["title"]},{group:"description",componentTypes:["description"]},{group:"setups",componentTypes:["setup"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStyleDefinitionStateVariables();Object.assign(e,t);let n=returnFeedbackDefinitionStateVariables();return Object.assign(e,n),e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["title"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[0].componentName),{setValue:{titleChildName:t}}}},e.title={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["title"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.titleChild.length?{setValue:{title:""}}:{setValue:{title:e.titleChild[0].stateValues.text}}},e.description={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({descriptionChild:{dependencyType:"child",childGroups:["description"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.descriptionChild.length?{setValue:{description:""}}:{setValue:{description:e.descriptionChild[0].stateValues.text}}},e.level={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{level:0}})},e.viewedSolution={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{viewedSolution:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"viewedSolution",value:e.viewedSolution}]})},e.scoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"descendant",componentTypes:["_sectioningComponent","answer","setup"],variableNames:["scoredDescendants","aggregateScores","weight"],recurseToMatchedChildren:!1,variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.scoredDescendants)"setup"!==n.componentType&&(n.stateValues.aggregateScores||void 0===n.stateValues.scoredDescendants?t.push(n):t.push(...n.stateValues.scoredDescendants));return{setValue:{scoredDescendants:t}}}},e.nScoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}}),definition:({dependencyValues:e})=>({setValue:{nScoredDescendants:e.scoredDescendants.length}})},e.itemCreditAchieved={isArray:!0,returnArraySizeDependencies:()=>({nScoredDescendants:{dependencyType:"stateVariable",variableName:"nScoredDescendants"}}),returnArraySize:({dependencyValues:e})=>[e.nScoredDescendants],stateVariablesDeterminingDependencies:["scoredDescendants"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.scoredDescendants[r];e&&(n[r]={creditAchieved:{dependencyType:"stateVariable",componentName:e.componentName,variableName:"creditAchieved"}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].creditAchieved;return{setValue:{itemCreditAchieved:n}}}},e.itemNumberByAnswerName={stateVariablesDeterminingDependencies:["scoredDescendants"],returnDependencies({stateValues:e}){let t={scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}};for(let n in e.scoredDescendants){let r=e.scoredDescendants[n];t[`descendantsOf${n}`]={dependencyType:"descendant",ancestorName:r.componentName,componentTypes:["answer"],recurseToMatchedChildren:!1}}return t},definition({dependencyValues:e,componentInfoObjects:t}){let n={};for(let[r,a]of e.scoredDescendants.entries()){let i=r+1;for(let t of e[`descendantsOf${r}`])n[t.componentName]=i;t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"answer"})&&(n[a.componentName]=i)}return{setValue:{itemNumberByAnswerName:n}}}},e.itemVariantInfo={isArray:!0,returnArraySizeDependencies:()=>({nScoredDescendants:{dependencyType:"stateVariable",variableName:"nScoredDescendants"}}),returnArraySize:({dependencyValues:e})=>[e.nScoredDescendants],stateVariablesDeterminingDependencies:["scoredDescendants"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.scoredDescendants[r];e&&(n[r]={generatedVariantInfo:{dependencyType:"stateVariable",componentName:e.componentName,variableName:"generatedVariantInfo",variablesOptional:!0}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].generatedVariantInfo;return{setValue:{itemVariantInfo:n}}}},e.answerDescendants={returnDependencies:()=>({answerDescendants:{dependencyType:"descendant",componentTypes:["answer"],variableNames:["justSubmitted"],recurseToMatchedChildren:!1}}),definition:({dependencyValues:e})=>({setValue:{answerDescendants:e.answerDescendants}})},e.justSubmitted={forRenderer:!0,returnDependencies:()=>({answerDescendants:{dependencyType:"stateVariable",variableName:"answerDescendants"}}),definition:({dependencyValues:e})=>({setValue:{justSubmitted:e.answerDescendants.every((e=>e.stateValues.justSubmitted))}})},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition:({dependencyValues:e})=>({setValue:{showCorrectness:!1!==e.showCorrectnessFlag}})},e.creditAchieved={public:!0,forRenderer:!0,defaultValue:0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},additionalStateVariablesDefined:[{variableName:"percentCreditAchieved",public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}}}],returnDependencies:()=>({scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"},itemCreditAchieved:{dependencyType:"stateVariable",variableName:"itemCreditAchieved"}}),definition({dependencyValues:e}){let t,n=0,r=0;for(let[t,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;n+=e.itemCreditAchieved[t]*i,r+=i}return t=r>0?n/r:1,{setValue:{creditAchieved:t,percentCreditAchieved:100*t}}}},e.creditAchievedIfSubmit={defaultValue:0,stateVariablesDeterminingDependencies:["scoredDescendants"],returnDependencies({stateValues:e}){let t={scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}};for(let[n,r]of e.scoredDescendants.entries())t["creditAchievedIfSubmit"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchievedIfSubmit"};return t},definition({dependencyValues:e}){let t=0,n=0;for(let[r,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;t+=e["creditAchievedIfSubmit"+r]*i,n+=i}return{setValue:{creditAchievedIfSubmit:t/n}}}},e.generatedVariantInfo={providePreviousValuesInDefinition:!0,returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantIndex:{dependencyType:"value",value:e.variantIndex},variantName:{dependencyType:"value",value:e.variantName},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t,previousValues:n}){let r={index:e.variantIndex,name:e.variantName,meta:{createdBy:t}},a=r.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?a.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&a.push(...t.stateValues.generatedVariantInfo.subvariants);for(let[e,t]of a.entries())if(!t.subvariants&&n.generatedVariantInfo){let t=n.generatedVariantInfo.subvariants;t[e]?.subvariants&&(a[e]=Object.assign({},a[e]),a[e].subvariants=t[e].subvariants)}return{setValue:{generatedVariantInfo:r}}}},e.createSubmitAllButton={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"suppressAnswerSubmitButtons",forRenderer:!0}],returnDependencies:()=>({documentWideCheckWork:{dependencyType:"stateVariable",variableName:"documentWideCheckWork"}}),definition({dependencyValues:e,componentName:t}){let n=!1,r=!1;return e.documentWideCheckWork&&(n=!0,r=!0),{setValue:{createSubmitAllButton:n,suppressAnswerSubmitButtons:r}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e}actions={submitAllAnswers:this.submitAllAnswers.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)};async submitAllAnswers({actionId:e}){this.coreFunctions.requestRecordEvent({verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType}});for(let e of await this.stateValues.answerDescendants)await e.stateValues.justSubmitted||await this.coreFunctions.performAction({componentName:e.componentName,actionName:"submitAnswer"});this.coreFunctions.resolveAction({actionId:e})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){let r,a=e.variants.numberOfVariants,i=e.variants.desiredVariant;if(void 0!==i&&void 0!==i.index){let e=Number(i.index);if(Number.isFinite(e)){Number.isInteger(e)||(console.warn("Variant index "+i.index+" must be an integer"),e=Math.round(e));let t=(e-1)%a;t<0&&(t+=a),r=t+1}else console.warn("Variant index "+i.index+" must be a number"),r=1}if(void 0===r&&(r=1),t.allPossibleVariants=e.variants.allPossibleVariants,t.allVariantNames=e.variants.allVariantNames,t.variantSeed=e.variants.allPossibleVariantSeeds[r-1],t.variantIndex=r,t.variantName=e.variants.allPossibleVariants[r-1],t.uniqueIndex=e.variants.allPossibleVariantUniqueIndices[r-1],t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:!0})}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants.allPossibleVariantUniqueIndices[t-1];if(void 0===r)return{success:!1};let a=getVariantsForDescendantsForUniqueVariants({variantIndex:r,serializedComponent:e,componentInfoObjects:n});return a.success?{success:!0,desiredVariant:{index:t,subvariants:a.desiredVariants}}:(console.log("Failed to get unique variant for document."),{success:!1})}static includeBlankStringChildren=!0}class TextList$1 extends InlineComponent{static componentType="textList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="texts";static primaryStateVariableForDefinition="textsShadow";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"text"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"text"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"texts",componentTypes:["text"]},{group:"textLists",componentTypes:["textList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.textsShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{textsShadow:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},textListChildren:{dependencyType:"child",childGroups:["textLists"],variableNames:["nComponents"]},textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],skipComponentNames:!0},textsShadow:{dependencyType:"stateVariable",variableName:"textsShadow"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[];if(e.textAndTextListChildren.length>0){let a=0;for(let[i,o]of e.textAndTextListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:o.componentType,baseComponentType:"textList"})){let t=e.textListChildren[a];a++;for(let e=0;ea&&(n=a,r=r.slice(0,a)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],variableNames:["value","text"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},textsShadow:{dependencyType:"stateVariable",variableName:"textsShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].textAndTextListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["text"+t]}else null!==e.textsShadow&&(r[a]=e.textsShadow[a])}return{setValue:{texts:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.texts){if(!n[t])continue;let a=n[t].textAndTextListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].textAndTextListChildren,desiredValue:e.texts[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].textAndTextListChildren,desiredValue:e.texts[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"texts"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e.componentNamesInList={returnDependencies:()=>({textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.textAndTextListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"textList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},textListChildren:{dependencyType:"child",childGroups:["textLists"],variableNames:["nComponents"]},textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"textList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,o=0,s=0;for(let n of e.textAndTextListChildren){let l=Math.max(0,r-i);if(l>0&&o++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"textList"})){let t=e.textListChildren[s];s++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:o}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=["text"]}class TextList extends InlineComponent{static componentType="randomizedTextList";static stateVariableForAttributeValue="texts";static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={default:!1},e.maximumNumber={default:null},e}static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"atLeastZeroTexts",componentType:"text",comparison:"atLeast",number:0}),r=t.newLeaf({name:"atLeastZeroTextLists",componentType:"textList",comparison:"atLeast",number:0}),a=t.newLeaf({name:"exactlyOneString",componentType:"string",number:1,isSugar:!0,returnSugarDependencies:()=>({stringChildren:{dependencyType:"child",childLogicName:"exactlyOneString",variableNames:["value"]}}),logicToWaitOnSugar:["atLeastZeroTexts"],replacementFunction:function({dependencyValues:e}){let t=e.stringChildren[0],n=t.stateValues.value.split(",").map((e=>({componentType:"text",state:{value:e.trim()}})));return{success:!0,newChildren:n,toDelete:[t.componentName]}}}),i=t.newOperator({name:"textAndTextLists",operator:"and",propositions:[n,r]});return t.newOperator({name:"TextsXorSugar",operator:"xor",propositions:[a,i],setAsBase:!0}),t}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],returnDependencies:()=>({textAndTextListChildren:{dependencyType:"child",childLogicName:"textAndTextLists",variableNames:["value","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},childrenToRender:{dependencyType:"stateVariable",variableName:"childrenToRender"}}),definition:function({dependencyValues:e}){let t=[],n=e.textAndTextListChildren.map((e=>e.componentName));for(let r of e.childrenToRender){let a=n.indexOf(r),i=e.textAndTextListChildren[a];i.stateValues.texts?t.push(...i.stateValues.texts):t.push(i.stateValues.value)}return{setValue:{texts:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.texts.length}}}},e.childrenToRender={returnDependencies:({sharedParameters:e})=>({textAndTextListChildren:{dependencyType:"child",childLogicName:"textAndTextLists",variableNames:["childrenToRender"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},selectRng:{dependencyType:"value",value:e.selectRng,doNotProxy:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.textAndTextListChildren)n.stateValues.childrenToRender?t.push(...n.stateValues.childrenToRender):t.push(n.componentName);let n=e.maximumNumber;null!==n&&t.length>n&&(n=Math.max(0,Math.floor(n)),t=t.slice(0,n)),console.log("randomizing children");for(let n=t.length-1;n>0;n--){const r=e.selectRng(),a=Math.floor(r*(n+1));[t[n],t[a]]=[t[a],t[n]]}let r=Math.ceil(e.selectRng()*t.length);return console.log(`numChildren: ${r}`),t=t.slice(0,r),{setValue:{childrenToRender:t}}}},e}initializeRenderer(){void 0===this.renderer&&(this.renderer=new this.availableRenderers.aslist({key:this.componentName}))}}class TupleList extends MathList{static componentType="tupleList";static rendererType="mathList";static includeBlankStringChildren=!1;static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"math",children:e}:e[0]}))}}}),e}}class NumberList extends InlineComponent{static componentType="numberList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="numbers";static primaryStateVariableForDefinition="numbersShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"number"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"number"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"numbers",componentTypes:["number"]},{group:"numberLists",componentTypes:["numberList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{numbersShadow:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},numberListChildren:{dependencyType:"child",childGroups:["numberLists"],variableNames:["nComponents"]},numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],skipComponentNames:!0},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;if(e.numberAndNumberListChildren.length>0)for(let[i,o]of e.numberAndNumberListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:o.componentType,baseComponentType:"numberList"})){let t=e.numberListChildren[a];a++;for(let e=0;ei&&(n=i,r=r.slice(0,i)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.numbers={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["number"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["value","number"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].numberAndNumberListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["number"+t]}else null!==e.numbersShadow&&(r[a]=e.numbersShadow[a])}return{setValue:{numbers:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.numbers){if(!n[t])continue;let a=n[t].numberAndNumberListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].numberAndNumberListChildren,desiredValue:e.numbers[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].numberAndNumberListChildren,desiredValue:e.numbers[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"numbers"},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({numbers:{dependencyType:"stateVariable",variableName:"numbers"}}),definition({dependencyValues:e}){let t;return t=0===e.numbers.length?me$3.fromAst("_"):1===e.numbers.length?me$3.fromAst(e.numbers[0]):me$3.fromAst(["list",...e.numbers]),{setValue:{math:t}}}},e.text={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["valueForDisplay","text","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n=[],r={};if(e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.numberAndNumberListChildren.length>0)for(let t of e.numberAndNumberListChildren)void 0!==t.stateValues.valueForDisplay?n.push(t.stateValues.text):n.push(...t.stateValues.texts);else null!==e.numbersShadow&&(n=e.numbersShadow.map((n=>roundForDisplay({value:me$3.fromAst(n),dependencyValues:e,usedDefault:t}).toString(r))));let a=e.maximumNumber;return null!==a&&n.length>a&&(a=Math.max(0,Math.floor(a)),n=n.slice(0,a)),{setValue:{text:n.join(", "),texts:n}}}},e.componentNamesInList={returnDependencies:()=>({numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.numberAndNumberListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},numberListChildren:{dependencyType:"child",childGroups:["numberLists"],variableNames:["nComponents"]},numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,o=0,s=0;for(let n of e.numberAndNumberListChildren){let l=Math.max(0,r-i);if(l>0&&o++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"numberList"})){let t=e.numberListChildren[s];s++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:o}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class NumberListFromString extends InlineComponent{static componentType="numberListFromString";static rendererType="asList";static renderChildren=!0;static stateVariableForAttributeValue="numbers";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.stringChildren.length}}}},e.numbers={public:!0,shadowingInstructions:{createComponentOfType:"number"},isArray:!0,entryPrefixes:["number"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey:()=>({globalDependencies:{stringChildren:{dependencyType:"child",childGroups:["strings"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let[t,r]of e.stringChildren.entries())n[t]=Number(r);return{setValue:{numbers:n}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"numbers"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({numbers:{dependencyType:"stateVariable",variableName:"numbers"}}),definition:function({dependencyValues:e}){let t=e.numbers.map((e=>e.toString()));return{setValue:{text:t.join(", "),texts:t}}}},e}}class P$2 extends BlockComponent{static componentType="p";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text?t+=n.stateValues.text:t+=" ";return{setValue:{text:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class BooleanList extends InlineComponent{static componentType="booleanList";static rendererType="asList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="booleans";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"boolean"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"boolean"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"booleans",componentTypes:["boolean"]},{group:"booleanLists",componentTypes:["booleanList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},booleanListChildren:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["nComponents"]},booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],skipComponentNames:!0}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;for(let[i,o]of e.booleanAndBooleanListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:o.componentType,baseComponentType:"booleanList"})){let t=e.booleanListChildren[a];a++;for(let e=0;ei&&(n=i,r=r.slice(0,i)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.booleans={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},isArray:!0,entryPrefixes:["boolean"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],variableNames:["value","boolean"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].booleanAndBooleanListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["boolean"+t]}}return{setValue:{booleans:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.booleans){if(!n[t])continue;let a=n[t].booleanAndBooleanListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].booleanAndBooleanListChildren,desiredValue:e.booleans[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].booleanAndBooleanListChildren,desiredValue:e.booleans[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"booleans"},e.componentNamesInList={returnDependencies:()=>({booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.booleanAndBooleanListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"booleanList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},booleanListChildren:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["nComponents"]},booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"booleanList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,o=0,s=0;for(let n of e.booleanAndBooleanListChildren){let l=Math.max(0,r-i);if(l>0&&o++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"booleanList"})){let t=e.booleanListChildren[s];s++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:o}}},markStale:()=>({updateRenderedChildren:!0})},e}}class Copy extends CompositeComponent{static componentType="copy";static assignNamesToReplacements=!0;static acceptTarget=!0;static acceptAnyAttribute=!0;static includeBlankStringChildren=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNewNamespaces={createPrimitiveOfType:"boolean"},e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.obtainPropFromComposite={createPrimitiveOfType:"boolean",createStateVariable:"obtainPropFromComposite",defaultValue:!1,public:!0},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.sourceSubnames={createPrimitiveOfType:"stringArray",createStateVariable:"targetSubnames",defaultValue:null,public:!0},e.sourceSubnamesComponentIndex={createComponentOfType:"numberList",createStateVariable:"targetSubnamesComponentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.uri={createPrimitiveOfType:"string",createStateVariable:"uri",defaultValue:null,public:!0},e.sourceAttributesToIgnore={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnore",defaultValue:["hide"],public:!0},e.sourceAttributesToIgnoreRecursively={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnoreRecursively",defaultValue:["isResponse"],public:!0},e.link={createPrimitiveOfType:"boolean"},e.removeEmptyArrayEntries={createPrimitiveOfType:"boolean",createStateVariable:"removeEmptyArrayEntries",defaultValue:!1},e}static keepChildrenSerialized({serializedComponent:e}){return void 0===e.children?[]:Object.keys(e.children)}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetSourcesName={additionalStateVariablesDefined:[{variableName:"sourcesChildNumber",hasEssential:!0,shadowVariable:!0}],stateVariablesDeterminingDependencies:["target"],determineDependenciesImmediately:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:function({stateValues:e,sharedParameters:t}){let n=t.sourceNameMappings;if(!n)return{};let r=n[e.target];return r?{targetSourcesName:{dependencyType:"value",value:r.name},sourcesChildNumber:{dependencyType:"value",value:r.childNumber}}:{}},definition:function({dependencyValues:e}){let t=e.targetSourcesName,n=e.sourcesChildNumber;return t||(t=null,n=null),{setValue:{targetSourcesName:t,sourcesChildNumber:n},setEssentialValue:{targetSourcesName:t,sourcesChildNumber:n}}}},e.targetSources={stateVariablesDeterminingDependencies:["targetSourcesName"],determineDependenciesImmediately:!0,returnDependencies:({stateValues:e})=>e.targetSourcesName?{targetSourcesComponent:{dependencyType:"componentIdentity",componentName:e.targetSourcesName}}:{},definition:function({dependencyValues:e}){let t=e.targetSourcesComponent;return t||(t=null),{setValue:{targetSources:t}}}},e.sourceIndex={stateVariablesDeterminingDependencies:["target"],determineDependenciesImmediately:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:function({stateValues:e,sharedParameters:t}){let n=t.sourceIndexMappings;if(!n)return{};let r=n[e.target];return void 0===r?{}:{sourceIndex:{dependencyType:"value",value:r}}},definition:function({dependencyValues:e}){let t=e.sourceIndex;return void 0===t&&(t=null),{setValue:{sourceIndex:t},setEssentialValue:{sourceIndex:t}}}},e.targetComponent={shadowVariable:!0,stateVariablesDeterminingDependencies:["targetSources","sourceIndex"],determineDependenciesImmediately:!0,returnDependencies:({stateValues:e})=>null!==e.sourceIndex?{}:null!==e.targetSources?{targetSourcesChildren:{dependencyType:"stateVariable",componentName:e.targetSources.componentName,variableName:"childIdentities"},sourcesChildNumber:{dependencyType:"stateVariable",variableName:"sourcesChildNumber"}}:{targetComponent:{dependencyType:"targetComponent"}},definition:function({dependencyValues:e}){let t=null;return e.targetSourcesChildren?(t=e.targetSourcesChildren[e.sourcesChildNumber],t||(t=null)):e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.cid={additionalStateVariablesDefined:["doenetId"],returnDependencies:()=>({uri:{dependencyType:"stateVariable",variableName:"uri"}}),definition:function({dependencyValues:e}){if(!e.uri||"doenet:"!==e.uri.substring(0,7).toLowerCase())return{setValue:{cid:null,doenetId:null}};let t=null,n=null,r=e.uri.match(/[:&]cid=([^&]+)/i);return r&&(t=r[1]),r=e.uri.match(/[:&]doenetid=([^&]+)/i),r&&(n=r[1]),{setValue:{cid:t,doenetId:n}}}},e.serializedComponentsForCid={returnDependencies:()=>({cid:{dependencyType:"stateVariable",variableName:"cid"},serializedChildren:{dependencyType:"serializedChildren",doNotProxy:!0}}),definition:function({dependencyValues:e}){return e.cid&&e.serializedChildren?.length>0?{setValue:{serializedComponentsForCid:e.serializedChildren}}:{setValue:{serializedComponentsForCid:null}}}},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.isPlainMacro={returnDependencies:()=>({isPlainMacro:{dependencyType:"doenetAttribute",attributeName:"isPlainMacro"},targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"},targetSubnames:{dependencyType:"stateVariable",variableName:"targetSubnames"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=e.isPlainMacro&&(!t.isCompositeComponent({componentType:e.targetComponent?.componentType})||e.targetSubnames);if(n&&e.typeAttr){n=!1;let r=t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()],a=t.allComponentClasses[e.targetComponent?.componentType];if(a){let e=t.publicStateVariableInfo[a.componentType].stateVariableDescriptions[a.variableForPlainMacro];r===a.componentType||!e||void 0!==e.createComponentOfType&&e.createComponentOfType!==r||(n=!0)}}return{setValue:{isPlainMacro:n}}}},e.isPlainCopy={returnDependencies:()=>({isPlainCopy:{dependencyType:"doenetAttribute",attributeName:"isPlainCopy"},targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"},targetSubnames:{dependencyType:"stateVariable",variableName:"targetSubnames"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=e.isPlainCopy&&(!t.isCompositeComponent({componentType:e.targetComponent?.componentType})||e.targetSubnames);if(n&&e.typeAttr){n=!1;let r=t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()],a=t.allComponentClasses[e.targetComponent?.componentType];if(a){let e=t.publicStateVariableInfo[a.componentType].stateVariableDescriptions[a.variableForPlainCopy];r===a.componentType||!e||void 0!==e.createComponentOfType&&e.createComponentOfType!==r||(n=!0)}}return{setValue:{isPlainCopy:n}}}},e.linkAttrForDetermineDeps={returnDependencies:()=>({linkAttr:{dependencyType:"attributePrimitive",attributeName:"link"}}),definition({dependencyValues:e}){let t;return t=null===e.linkAttr||e.linkAttr,{setValue:{linkAttrForDetermineDeps:t}}}},e.replacementSourceIdentities={stateVariablesDeterminingDependencies:["targetComponent","componentIndex","propName","targetSubnames","targetSubnamesComponentIndex","obtainPropFromComposite","linkAttrForDetermineDeps"],additionalStateVariablesDefined:["addLevelToAssignNames"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={},r=!1,a=!1;if(null!==e.targetComponent){if(t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})&&(!e.propName||!e.obtainPropFromComposite))if(e.linkAttrForDetermineDeps){a=!0;let t=e.targetSubnamesComponentIndex;t&&(t=[...t]),n.targets={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,componentIndex:e.componentIndex,targetSubnames:e.targetSubnames,targetSubnamesComponentIndex:t}}else r=!0;a||null!==e.componentIndex&&1!==e.componentIndex||(n.targets={dependencyType:"stateVariable",variableName:"targetComponent"})}return n.addLevelToAssignNames={dependencyType:"value",value:r},n},definition({dependencyValues:e}){let t=null;return e.targets&&(t=e.targets,Array.isArray(t)||(t=[t])),{setValue:{replacementSourceIdentities:t,addLevelToAssignNames:e.addLevelToAssignNames}}}},e.replacementSources={stateVariablesDeterminingDependencies:["replacementSourceIdentities","propName","propIndex","isPlainMacro","isPlainCopy"],additionalStateVariablesDefined:["effectivePropNameBySource"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"},propIndex:{dependencyType:"stateVariable",variableName:"propIndex"}};if(!e.propName&&null!==e.propIndex)throw Error("You cannot specify a propIndex without specifying a prop.");if(null!==e.replacementSourceIdentities)for(let[r,a]of e.replacementSourceIdentities.entries()){let i,o=e.propName;if(e.isPlainMacro?o=t.allComponentClasses[a.componentType].variableForPlainMacro:e.isPlainCopy&&(o=t.allComponentClasses[a.componentType].variableForPlainCopy),o){n["propName"+r]={dependencyType:"value",value:o};let t=e.propIndex;t&&(t=[...t]),i={dependencyType:"stateVariable",componentName:a.componentName,variableName:o,returnAsComponentObject:!0,variablesOptional:!0,propIndex:t,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0}}else i={dependencyType:"componentIdentity",componentName:a.componentName};n["target"+r]=i}return n},definition({dependencyValues:e}){let t=null,n=null;if(null!==e.replacementSourceIdentities){t=[],n=[];for(let r in e.replacementSourceIdentities){let a=e["target"+r];if(a){let i;t.push(a),a.stateValues&&(i=Object.keys(a.stateValues)[0]),!i&&e["propName"+r]&&(i="__prop_name_not_found"),n.push(i)}}}return{setValue:{replacementSources:t,effectivePropNameBySource:n}}}},e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;if(e.typeAttr){if(!(t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in t.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);n=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error("You must specify createComponentOfType when specifying nComponents for a copy.");n=null}return{setValue:{nComponentsSpecified:n}}}},e.link={returnDependencies:()=>({linkAttr:{dependencyType:"attributePrimitive",attributeName:"link"},serializedComponentsForCid:{dependencyType:"stateVariable",variableName:"serializedComponentsForCid"},replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;return n=null===e.linkAttr?!(e.serializedComponentsForCid||e.replacementSourceIdentities&&e.replacementSourceIdentities.some((e=>t.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"module"})))):!1!==e.linkAttr,{setValue:{link:n}}}},e.readyToExpandWhenResolved={stateVariablesDeterminingDependencies:["targetComponent","propName","obtainPropFromComposite","link"],returnDependencies({stateValues:e,componentInfoObjects:t}){let n={targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"},serializedComponentsForCid:{dependencyType:"stateVariable",variableName:"serializedComponentsForCid"},link:{dependencyType:"stateVariable",variableName:"link"}};return!e.targetComponent||!t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})||e.propName&&e.obtainPropFromComposite||(n.targetReadyToExpandWhenResolved={dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"readyToExpandWhenResolved"}),e.link||(n.replacementSources={dependencyType:"stateVariable",variableName:"replacementSources"}),n},definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={stateVariablesDeterminingDependencies:["targetComponent","replacementSourceIdentities","effectivePropNameBySource","propName","obtainPropFromComposite","link","removeEmptyArrayEntries"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){if(!e.link)return{};let n={targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"},replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"},propIndex:{dependencyType:"stateVariable",variableName:"propIndex"}};if(null!==e.effectivePropNameBySource)for(let[t,r]of e.effectivePropNameBySource.entries())if(r){let a=e.replacementSourceIdentities[t];n["sourceArraySize"+t]={dependencyType:"stateVariableArraySize",componentName:a.componentName,variableName:r,variablesOptional:!0,caseInsensitiveVariableMatch:!0},n["sourceComponentType"+t]={dependencyType:"stateVariableComponentType",componentName:a.componentName,variableName:r,variablesOptional:!0,caseInsensitiveVariableMatch:!0}}return null===e.targetComponent||!t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})||e.propName&&e.obtainPropFromComposite||(n.allReplacementIdentities={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,variableNames:["isInactiveCompositeReplacement"]}),e.removeEmptyArrayEntries&&(n.replacementSources={dependencyType:"stateVariable",variableName:"replacementSources"}),n},markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e.effectiveAssignNames={returnDependencies:()=>({assignNames:{dependencyType:"doenetAttribute",attributeName:"assignNames"},addLevelToAssignNames:{dependencyType:"stateVariable",variableName:"addLevelToAssignNames"}}),definition({dependencyValues:e}){let t=e.assignNames;return t&&e.addLevelToAssignNames&&(t=[t]),{setValue:{effectiveAssignNames:t}}}},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,resolveItem:i,publicCaseInsensitiveAliasSubstitutions:o}){await e.stateValues.nComponentsSpecified,n.numReplacementsBySource=[],n.numNonStringReplacementsBySource=[],n.propVariablesCopiedBySource=[],n.sourceNames=[],n.uniqueIdentifiersUsedBySource={};let s=e.attributes.newNamespace?.primitive,l=this.createAttributesObject(),u=await e.stateValues.effectiveAssignNames,c=await e.stateValues.serializedComponentsForCid;if(c){let t=deepClone([c[0]]),i=deepClone(c.slice(1));if(t[0].children){let n;if(n=t[0].componentName?t[0].componentName+"/":t[0].originalName+"/",e.doenetAttributes.keptNewNamespaceOfLastChild){n=n.slice(0,n.length-1);let e=n.lastIndexOf("/");n=n.slice(0,e+1)}restrictTNamesToNamespace({components:t[0].children,namespace:n,invalidateReferencesToBaseNamespace:e.doenetAttributes.keptNewNamespaceOfLastChild})}if("externalContent"===t[0].componentType)for(let n of t[0].children){if("object"!=typeof n)continue;n.attributes||(n.attributes={});let t=convertAttributesForComponentType({attributes:e.attributes,componentType:n.componentType,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:s,flags:a});for(let e in t){let n=t[e];n.component?setTNamesToAbsolute([n.component]):n.childrenForComponent&&setTNamesToAbsolute(n.childrenForComponent)}Object.assign(n.attributes,t)}else{t[0].attributes||(t[0].attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t[0].componentType,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:s,flags:a});for(let e in n){let t=n[e];t.component?setTNamesToAbsolute([t.component]):t.childrenForComponent&&setTNamesToAbsolute(t.childrenForComponent)}Object.assign(t[0].attributes,n)}return t=processAssignNames({assignNames:u,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:s,componentInfoObjects:r}).serializedComponents,e.doenetAttributes.fromCopyFromURI&&i.length>0&&this.addChildrenFromComposite({replacements:t,children:i,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,componentInfoObjects:r}),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}let p=await e.stateValues.sourceIndex;if(null!==p){let t=processAssignNames({assignNames:u,serializedComponents:[{componentType:"number",attributes:convertAttributesForComponentType({attributes:e.attributes,componentType:"number",componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:s,flags:a}),state:{value:p,fixed:!0}}],parentName:e.componentName,parentCreatesNewNamespace:s,componentInfoObjects:r});return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t.serializedComponents,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}let d=await e.stateValues.replacementSourceIdentities;if(!await e.stateValues.targetComponent||!d){let t=[];if(e.doenetAttributes.fromCopyTarget){let i=r.componentTypeLowerCaseMapping[e.attributes.createComponentOfType.primitive.toLowerCase()],o=r.allComponentClasses[i],c=convertAttributesForComponentType({attributes:e.attributes,componentType:i,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:s,flags:a});n.uniqueIdentifiersUsedBySource[0]=[];let p=getUniqueIdentifierFromBase(i+"|empty",n.uniqueIdentifiersUsedBySource[0]),d=deepClone(e.serializedChildren);o.includeBlankStringChildren||(d=d.filter((e=>"string"!=typeof e||""!==e.trim())));let m=c;e.attributes.assignNewNamespaces?.primitive&&(m.newNamespace={primitive:!0}),t=[{componentType:i,attributes:m,children:d,uniqueIdentifier:p}],t=processAssignNames({assignNames:u,serializedComponents:t,parentName:e.componentName,componentInfoObjects:r,originalNamesAreConsistent:!0}).serializedComponents,n.numReplacementsBySource.push(t.length),n.numNonStringReplacementsBySource.push(t.filter((e=>"string"!=typeof e)).length)}return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l})).replacements}}let m=await i({componentName:e.componentName,type:"determineDependencies",stateVariable:"replacementSources",dependency:"__determine_dependencies",expandComposites:!1});if(!m.success)throw Error(`Couldn't resolve determineDependencies of replacementSources of ${e.componentName}`);let f=await e.stateValues.effectivePropNameBySource;for(let t in d){if(f[t]&&(m=await i({componentName:e.componentName,type:"recalculateDownstreamComponents",stateVariable:"replacementSources",dependency:"target"+t,expandComposites:!1}),!m.success))throw Error(`Couldn't resolve recalculateDownstreamComponents for target${t} of replacementSources of ${e.componentName}`)}let h=[],y=[],b=[],g=0,v=0;for(let i in d){let s,u=n.uniqueIdentifiersUsedBySource[i]=[];if(e.attributes.createComponentOfType?.primitive){let t=await e.stateValues.nComponentsSpecified,n=d.length;s=Math.floor(t/n),i"string"!=typeof e)).length,g+=y[i],v+=b[i],h.push(...p)}return n.numReplacementsBySource=y,n.numNonStringReplacementsBySource=b,n.sourceNames=d.map((e=>e.componentName)),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:h,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}static async createReplacementForSource({component:e,sourceNum:t,components:n,numReplacementsSoFar:r,numNonStringReplacementsSoFar:a,uniqueIdentifiersUsed:i,compositeAttributesObj:o,componentInfoObjects:s,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c,fromCopyTarget:p}){let d=(await e.stateValues.replacementSourceIdentities)[t];if("object"!=typeof d)return{serializedReplacements:[d]};let m=n[d.componentName],f=await e.stateValues.link;f&&!await e.stateValues.removeEmptyArrayEntries||(d=(await e.stateValues.replacementSources)[t]);let h=e.attributes.newNamespace?.primitive,y=await e.stateValues.effectiveAssignNames,b=(await e.stateValues.effectivePropNameBySource)[t];if(b){let t=await replacementFromProp({component:e,components:n,replacementSource:d,propName:b,numReplacementsSoFar:r,numNonStringReplacementsSoFar:a,uniqueIdentifiersUsed:i,compositeAttributesObj:o,componentInfoObjects:s,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c});return{serializedReplacements:processAssignNames({assignNames:y,serializedComponents:t.serializedReplacements,parentName:e.componentName,parentCreatesNewNamespace:h,indOffset:a,componentInfoObjects:s}).serializedComponents,propVariablesCopiedByReplacement:t.propVariablesCopiedByReplacement}}let g=await e.stateValues.sourceAttributesToIgnore,v=await e.stateValues.sourceAttributesToIgnoreRecursively,T=[await m.serialize({copyAll:!f,copyVariants:!f,sourceAttributesToIgnore:g,sourceAttributesToIgnoreRecursively:v})];f||void 0===T[0].state?.fixed||delete T[0].state.fixed,T=postProcessCopy({serializedComponents:T,componentName:e.componentName,uniqueIdentifiersUsed:i,addShadowDependencies:f,unlinkExternalCopies:!f}),T.length>0&&delete T[0].doenetAttributes.haveNewNamespaceOnlyFromShadow;for(let t of T){if("object"!=typeof t)continue;t.attributes||(t.attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:s,compositeAttributesObj:o,compositeCreatesNewNamespace:h,flags:c});Object.assign(t.attributes,n)}return T[0].attributes.newNamespace?.primitive&&!e.attributes.assignNewNamespaces?.primitive&&(T[0].doenetAttributes.haveNewNamespaceOnlyFromShadow=!0),T=processAssignNames({assignNames:y,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,serializedComponents:T,parentName:e.componentName,parentCreatesNewNamespace:h,indOffset:a,componentInfoObjects:s,originalNamesAreConsistent:h&&!y}).serializedComponents,p&&1===T.length&&e.serializedChildren.length>0&&this.addChildrenFromComposite({replacements:T,children:e.serializedChildren,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,componentInfoObjects:s}),{serializedReplacements:T}}static addChildrenFromComposite({replacements:e,children:t,assignNewNamespaces:n,componentInfoObjects:r}){let a=e[0];a.children||(a.children=[]);let i=deepClone(t);if(r.allComponentClasses[a.componentType].includeBlankStringChildren||(i=i.filter((e=>"string"!=typeof e||""!==e.trim()))),e[0].attributes.newNamespace?.primitive&&n){renameAutonameBasedOnNewCounts(i,countRegularComponentTypesInNamespace(a.children))}let o=processAssignNames({serializedComponents:i,parentName:e[0].componentName,parentCreatesNewNamespace:n,componentInfoObjects:r,originalNamesAreConsistent:!0});if(e[0].attributes.newNamespace?.primitive&&!n)for(let e of o.serializedComponents)"object"==typeof e&&(e.doenetAttributes.ignoreParentNewNamespace=!0);a.children.push(...o.serializedComponents)}static async calculateReplacementChanges({component:e,componentChanges:t,components:n,workspace:r,componentInfoObjects:a,flags:i,resolveItem:o,publicCaseInsensitiveAliasSubstitutions:s}){if(await e.stateValues.serializedComponentsForCid)return[];if(null!==await e.stateValues.sourceIndex)return[];let l=this.createAttributesObject(),u=await e.stateValues.effectiveAssignNames,c=await e.stateValues.replacementSourceIdentities;if(!await e.stateValues.targetComponent||!c){if(await e.stateValues.targetSources)return[];{let t=[];if(e.replacements.length>0){let n={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToDelete:e.replacements.length};t.push(n)}let n=0===r.sourceNames.length;r.sourceNames=[],r.numReplacementsBySource=[],r.numNonStringReplacementsBySource=[],r.propVariablesCopiedBySource=[];let o=await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:t,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i});return n?[]:o.replacementChanges}}if(await e.stateValues.targetInactive){let t=[],n=e.replacements.length;if(n>0){if(e.replacementsToWithhold!==n){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:n};t.push(e)}t=(await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:t,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i})).replacementChanges}return t}let p=await o({componentName:e.componentName,type:"determineDependencies",stateVariable:"replacementSources",dependency:"__determine_dependencies",expandComposites:!1});if(!p.success)throw Error(`Couldn't resolve determineDependencies of replacementSources of ${e.componentName}`);let d=await e.stateValues.effectivePropNameBySource;for(let t in c){if(d[t]&&(p=await o({componentName:e.componentName,type:"recalculateDownstreamComponents",stateVariable:"replacementSources",dependency:"target"+t,expandComposites:!1}),!p.success))throw Error(`Couldn't resolve recalculateDownstreamComponents for target${t} of replacementSources of ${e.componentName}`)}let m=[];if(e.replacementsToWithhold>0){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};m.push(e)}let f=0,h=0,y=[],b=[],g=[],v=Math.max(c.length,r.numReplacementsBySource.length),T=!1;for(let t=0;t0){if(!T){let e=r.numReplacementsBySource.slice(t).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:f,numberReplacementsToDelete:e};m.push(t)}T=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}r.uniqueIdentifiersUsedBySource[t]=[]}y[t]=0,b[t]=0,g.push([]);continue}let p=r.sourceNames[t],v=void 0===p||u.componentName!==p||T;if(!v)for(let n=0;ne+t),0);v.numberReplacementsToReplace=e,T=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}m.push(v);continue}if(!d[t]&&r.numReplacementsBySource[t]>0){f+=r.numReplacementsBySource[t],h+=r.numNonStringReplacementsBySource[t],y[t]=r.numReplacementsBySource[t],b[t]=r.numNonStringReplacementsBySource[t];continue}let N=r.uniqueIdentifiersUsedBySource[t]=[],C=await this.createReplacementForSource({component:e,sourceNum:t,components:n,numReplacementsSoFar:f,numNonStringReplacementsSoFar:h,uniqueIdentifiersUsed:N,compositeAttributesObj:l,componentInfoObjects:a,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:s,flags:i}),A=C.propVariablesCopiedByReplacement,S=C.serializedReplacements,x=S.length;if(x!==r.numReplacementsBySource[t]){let e=r.numReplacementsBySource.slice(t).reduce(((e,t)=>e+t),0),n={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:f,numberReplacementsToReplace:e,serializedReplacements:S,assignNamesOffset:h};m.push(n),T=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}else{let n=0;for(let a=0;ae!==A[a][t]))?(o=!1,i=!0):e.replacements[f+a].componentType!==S[a].componentType&&(i=!0)),0==a&&i&&o){1===await e.stateValues.nComponentsSpecified&&1===x&&!(e.replacementsToWithhold>0)&&1===r.sourceNames.length&&(i=!1)}if(i){let e={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:f+a,numberReplacementsToReplace:1,serializedReplacements:[S[a]],assignNamesOffset:h+n};m.push(e)}"string"!=typeof S[a]&&n++}}let w=S.filter((e=>"string"!=typeof e)).length;f+=x,h+=w,y[t]=x,b[t]=w,g[t]=A}let N=0===r.sourceNames.length;r.numReplacementsBySource=y,r.numNonStringReplacementsBySource=b,r.sourceNames=c.map((e=>e.componentName)),r.propVariablesCopiedBySource=g;let C=await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:m,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i});return N&&0===r.sourceNames.length?[]:C.replacementChanges}static async recreateReplacements({component:e,sourceNum:t,numReplacementsSoFar:n,numNonStringReplacementsSoFar:r,numReplacementsToDelete:a,uniqueIdentifiersUsed:i,components:o,compositeAttributesObj:s,componentInfoObjects:l,nComponentsForSource:u,publicCaseInsensitiveAliasSubstitutions:c,flags:p}){let d=await this.createReplacementForSource({component:e,sourceNum:t,numReplacementsSoFar:n,numNonStringReplacementsSoFar:r,components:o,uniqueIdentifiersUsed:i,compositeAttributesObj:s,componentInfoObjects:l,nComponentsForSource:u,publicCaseInsensitiveAliasSubstitutions:c,flags:p}),m=d.propVariablesCopiedByReplacement,f=d.serializedReplacements,h={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:a,serializedReplacements:f,assignNamesOffset:r};return{numReplacements:f.length,numNonStringReplacements:f.filter((e=>"string"!=typeof e)).length,propVariablesCopiedByReplacement:m,replacementInstruction:h}}}async function replacementFromProp({component:e,components:t,replacementSource:n,propName:r,uniqueIdentifiersUsed:a,compositeAttributesObj:i,componentInfoObjects:o,nComponentsForSource:s,publicCaseInsensitiveAliasSubstitutions:l,flags:u}){let c=[],p=[],d=e.attributes.newNamespace?.primitive,m=-1,f=t[n.componentName],h=l({stateVariables:[r],componentClass:f.constructor})[0];if(void 0===h||"__not_public"===h.slice(0,12))return"__prop_name_not_found"!==r&&console.warn(`Could not find prop ${r} on a component of type ${n.componentType}`),{serializedReplacements:[],propVariablesCopiedByReplacement:[]};let y=f.state[h],b=await y.value,g=await e.stateValues.link;if(y.isArray||y.isArrayEntry){let t,r,l,b;if(y.isArray?(t=y,l=await y.arraySize,r=y.getAllArrayKeys(l,!1)):(t=f.state[y.arrayStateVariable],r=await y.unflattenedArrayKeys,b=await y.arrayKeys),t.shadowingInstructions?.hasVariableComponentType&&(await e.stateValues.replacementSources,!t.shadowingInstructions.createComponentOfType))return{serializedReplacements:[],propVariablesCopiedByReplacement:[]};let v=y.wrappingComponents,T=v.length,N=s;if(y.isArray)N=l.slice(0,l.length-T).reduce(((e,t)=>e*t),1);else if(0===b.length)N=0;else if(0===T)N=b.length;else if(T>=y.nDimensions)N=1;else if(T===y.nDimensions-1)N=r.length;else{N=flattenLevels(r,y.nDimensions-T-1).length}if(0===T){let s=flattenDeep(r);for(let r=0;r1)for(let e of r){let t=await s(e,i-1);l.push(...t.pieces),c.push(...t.propVariablesCopiedByPiece)}else for(let i of r){let r,s,p=t.arrayVarNameFromArrayKey(i),d=[p],m=getUniqueIdentifierFromBase(n.componentName+"|shadow|"+p,a),h=t.shadowingInstructions.createComponentOfType;if(Array.isArray(h)&&(h=h[t.keyToIndex(i)]),t.shadowingInstructions.addAttributeComponentsShadowingStateVariables){r={};for(let e in t.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let n=t.shadowingInstructions.addAttributeComponentsShadowingStateVariables[e].stateVariableToShadow,a=f.state[n];a.isArray&&(n=a.arrayVarNameFromArrayKey(i)),r[e]={stateVariableToShadow:n}}}if(t.shadowingInstructions.addStateVariablesShadowingStateVariables){s={};for(let e in t.shadowingInstructions.addStateVariablesShadowingStateVariables){let n=t.shadowingInstructions.addStateVariablesShadowingStateVariables[e].stateVariableToShadow,r=f.state[n];r.isArray&&(n=r.arrayVarNameFromArrayKey(i)),s[e]={stateVariableToShadow:n}}}if(g){let t={};if(r){let n=o.allComponentClasses[h].createAttributesObject();for(let a in r){let i=r[a].stateVariableToShadow,o={componentType:n[a].createComponentOfType,downstreamDependencies:{[f.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:i}]}};t[a]={component:o}}}l.push({componentType:h,attributes:t,downstreamDependencies:{[n.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:p,additionalStateVariableShadowing:s}]},uniqueIdentifier:m})}else{let e={};if(r){let t={};for(let e in r){let n=r[e].stateVariableToShadow,a=f.state[n],o=await a.value;a.isArray&&(o=o[a.keyToIndex[i]]),f.state[n].usedDefault||(t[e]=o)}let n=convertAttributesForComponentType({attributes:t,componentType:h,componentInfoObjects:o,flags:u});if(y.shadowingInstructions.attributesToShadow)for(let e of y.shadowingInstructions.attributesToShadow)f.attributes[e]?.component?n[e]={component:await(f.attributes[e]?.component.serialize({copyAll:!0,copyVariants:!0}))}:void 0!==f.attributes[e]?.primitive&&(n[e]={primitive:JSON.parse(JSON.stringify(f.attributes[e].primitive))});Object.assign(e,n)}let n="value",a=o.allComponentClasses[h];a.primaryEssentialStateVariable?n=a.primaryEssentialStateVariable:a.primaryStateVariableForDefinition&&(n=a.primaryStateVariableForDefinition);let s=t.keyToIndex(i);Array.isArray(s)||(s=[s]);let c=await t.value;for(let e of s)c=c[e];let p={componentType:h,attributes:e,state:{[n]:c},uniqueIdentifier:m};l.push(p)}c.push(d)}let p=v[i-1];if(l.length>0&&p&&p.length>0){for(let e=p.length-1;e>=0;e--){let t="object"==typeof p[e]?p[e].componentType:p[e],n=getUniqueIdentifierFromBase(t+"|wrapper",a),r=[],i={};for(let e of l)if(e.isAttribute){let t=e.isAttribute;delete e.isAttribute,i[t]={component:e}}else r.push(e);l=[{componentType:t,children:r,attributes:i,uniqueIdentifier:n,skipSugar:!0}],"object"==typeof p[e]&&(p[e].doenetAttributes&&(l[0].doenetAttributes=Object.assign({},p[e].doenetAttributes)),p[e].isAttribute&&(l[0].isAttribute=p[e].isAttribute))}c=[flattenDeep(c)]}return{pieces:l,propVariablesCopiedByPiece:c}},l=await s(r,y.nDimensions),T=l.pieces;p=l.propVariablesCopiedByPiece;for(let t of T){if("object"!=typeof t)continue;t.attributes||(t.attributes={});let r=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:o,compositeAttributesObj:i,compositeCreatesNewNamespace:d,flags:u});Object.assign(t.attributes,r),g&&(t.downstreamDependencies={[n.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:h,ignorePrimaryStateVariable:!0}]})}if(m+=T.length,c.push(...T),T.length0?"object"==typeof i[0]?(n=i[0].componentType,r=Object.assign({},i[0].doenetAttributes)):n=i[0]:(n=t.shadowingInstructions.createComponentOfType,Array.isArray(n)&&(n=y.isArrayEntry?n[t.keyToIndex(b[e])]:n[e]));let o={componentType:n,uniqueIdentifier:getUniqueIdentifierFromBase(n+"|empty",a)};r&&(o.doenetAttributes=r),c.push(o)}else if(T>N)throw Error(`Something went wrong when creating replacements for ${e.componentName} as we ended up with too many replacements`)}}else{if(y.shadowingInstructions?.hasVariableComponentType&&await y.value,!y.shadowingInstructions?.createComponentOfType)return{serializedReplacements:[],propVariablesCopiedByReplacement:[]};m++,(p[m]=[]).push(h);let t=getUniqueIdentifierFromBase(f.componentName+"|shadow|"+h,a);if("string"===y.shadowingInstructions.createComponentOfType)c.push(await y.value);else{let n=convertAttributesForComponentType({attributes:e.attributes,componentType:y.shadowingInstructions.createComponentOfType,componentInfoObjects:o,compositeAttributesObj:i,compositeCreatesNewNamespace:d,flags:u});if(g){let r={};if(y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let t=o.allComponentClasses[y.shadowingInstructions.createComponentOfType].createAttributesObject();for(let n in y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let a=y.shadowingInstructions.addAttributeComponentsShadowingStateVariables[n].stateVariableToShadow,i={componentType:t[n].createComponentOfType,downstreamDependencies:{[f.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:a}]}};r[n]={component:i}}}Object.assign(r,n),c.push({componentType:y.shadowingInstructions.createComponentOfType,attributes:r,downstreamDependencies:{[f.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:h,additionalStateVariableShadowing:y.shadowingInstructions.addStateVariablesShadowingStateVariables}]},uniqueIdentifier:t})}else{let e={};if(y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let t={};for(let e in y.shadowingInstructions.addAttributeComponentsShadowingStateVariables)if("fixed"!==e){let n=y.shadowingInstructions.addAttributeComponentsShadowingStateVariables[e].stateVariableToShadow,r=await f.state[n].value;f.state[n].usedDefault||(t[e]=r)}let n=convertAttributesForComponentType({attributes:t,componentType:y.shadowingInstructions.createComponentOfType,componentInfoObjects:o,flags:u});if(y.shadowingInstructions.attributesToShadow)for(let e of y.shadowingInstructions.attributesToShadow)f.attributes[e]?.component?n[e]={component:await(f.attributes[e]?.component.serialize({copyAll:!0,copyVariants:!0}))}:void 0!==f.attributes[e]?.primitive&&(n[e]={primitive:JSON.parse(JSON.stringify(f.attributes[e].primitive))});Object.assign(e,n)}Object.assign(e,n);let r="value",a=o.allComponentClasses[y.shadowingInstructions.createComponentOfType];a.primaryEssentialStateVariable?r=a.primaryEssentialStateVariable:a.primaryStateVariableForDefinition&&(r=a.primaryStateVariableForDefinition);let i={componentType:y.shadowingInstructions.createComponentOfType,attributes:e,state:{[r]:b},uniqueIdentifier:t};c.push(i)}}}return{serializedReplacements:c,propVariablesCopiedByReplacement:p}}class Extract extends CompositeComponent{static componentType="extract";static assignNamesToReplacements=!0;static acceptAnyAttribute=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;if(e.typeAttr){if(!(t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in t.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);n=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error("You must specify createComponentOfType when specifying nComponents for a copy.");n=null}return{setValue:{nComponentsSpecified:n}}}},e.link={returnDependencies:()=>({}),definition:()=>({setValue:{link:!0}})},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.sourceComponents={stateVariablesDeterminingDependencies:["propName","componentIndex","propIndex"],additionalStateVariablesDefined:["effectivePropNameBySource"],returnDependencies:function({stateValues:e}){let t,n;null!==e.componentIndex&&(n=Number(e.componentIndex),t=Number.isInteger(n)?[n-1]:[]);let r=e.propIndex;return r&&(r=[...r]),{children:{dependencyType:"child",childGroups:["anything"],variableNames:[e.propName],variablesOptional:!0,childIndices:t,propIndex:r,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0},propName:{dependencyType:"stateVariable",variableName:"propName"}}},definition:function({dependencyValues:e}){let t=e.children,n=[];for(let e of t){let t;e.stateValues&&(t=Object.keys(e.stateValues)[0]),t||(t="__prop_name_not_found"),n.push(t)}return{setValue:{sourceComponents:t,effectivePropNameBySource:n}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({replacementClasses:{dependencyType:"stateVariable",variableName:"sourceComponents"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={returnDependencies:()=>({sourceComponents:{dependencyType:"stateVariable",variableName:"sourceComponents"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,publicCaseInsensitiveAliasSubstitutions:i}){let o=[],s=[],l=0;n.propVariablesCopiedBySource=[],n.uniqueIdentifiersUsedBySource={};let u=this.createAttributesObject(),c=await e.stateValues.sourceComponents;for(let a=0;ae.componentName)),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:o,assignNames:e.doenetAttributes.assignNames,workspace:n,componentInfoObjects:r,compositeAttributesObj:u,flags:a})).replacements}}static async createReplacementForSource({component:e,components:t,sourceNum:n,numReplacementsSoFar:r,uniqueIdentifiersUsed:a,componentInfoObjects:i,compositeAttributesObj:o,publicCaseInsensitiveAliasSubstitutions:s}){let l=(await e.stateValues.effectivePropNameBySource)[n],u=await replacementFromProp({component:e,components:t,replacementSource:(await e.stateValues.sourceComponents)[n],propName:l,uniqueIdentifiersUsed:a,compositeAttributesObj:o,componentInfoObjects:i,publicCaseInsensitiveAliasSubstitutions:s}),c=u.serializedReplacements,p=u.propVariablesCopiedByReplacement,d=e.attributes.newNamespace?.primitive;return c=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:c,parentName:e.componentName,indOffset:r,parentCreatesNewNamespace:d,componentInfoObjects:i}).serializedComponents,{serializedReplacements:c,propVariablesCopiedByReplacement:p}}static async calculateReplacementChanges({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,publicCaseInsensitiveAliasSubstitutions:i}){let o=[],s=0,l=[],u=[],c=this.createAttributesObject(),p=await e.stateValues.sourceComponents,d=Math.max(p.length,n.numReplacementsBySource.length),m=!1;for(let a=0;a0){if(!m){let e=n.numReplacementsBySource.slice(a).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:s,numberReplacementsToDelete:e};o.push(t)}m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}n.uniqueIdentifiersUsedBySource[a]=[]}l[a]=0,u.push([]);continue}let f=n.sourceNames[a],h=void 0===f||d.componentName!==f||m;if(!h)for(let t=0;te+t),0);b.numberReplacementsToReplace=e,m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}o.push(b);continue}let y=n.uniqueIdentifiersUsedBySource[a]=[],b=await this.createReplacementForSource({component:e,sourceNum:a,components:t,numReplacementsSoFar:s,uniqueIdentifiersUsed:y,componentInfoObjects:r,compositeAttributesObj:c,publicCaseInsensitiveAliasSubstitutions:i}),g=b.propVariablesCopiedByReplacement,v=b.serializedReplacements,T=v.length;if(T!==n.numReplacementsBySource[a]){let e=n.numReplacementsBySource.slice(a).reduce(((e,t)=>e+t),0),t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:s,numberReplacementsToReplace:e,serializedReplacements:v,assignNamesOffset:s};o.push(t),m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}else for(let e=0;et!==g[e][n]))){let t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:s+e,numberReplacementsToReplace:1,serializedReplacements:[v[e]],assignNamesOffset:s+e};o.push(t)}s+=T,l[a]=T,u[a]=g}return n.numReplacementsBySource=l,n.numNonStringReplacementsBySource=[...l],n.sourceNames=p.map((e=>e.componentName)),n.propVariablesCopiedBySource=u,(await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:o,assignNames:e.doenetAttributes.assignNames,workspace:n,componentInfoObjects:r,compositeAttributesObj:c,flags:a})).replacementChanges}static async recreateReplacements({component:e,sourceNum:t,numReplacementsSoFar:n,numReplacementsToDelete:r,uniqueIdentifiersUsed:a,components:i,componentInfoObjects:o,compositeAttributesObj:s,publicCaseInsensitiveAliasSubstitutions:l}){let u=await this.createReplacementForSource({component:e,sourceNum:t,numReplacementsSoFar:n,components:i,uniqueIdentifiersUsed:a,componentInfoObjects:o,compositeAttributesObj:s,publicCaseInsensitiveAliasSubstitutions:l}),c=u.propVariablesCopiedByReplacement,p=u.serializedReplacements,d={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:r,serializedReplacements:p,assignNamesOffset:n};return{numReplacements:p.length,propVariablesCopiedByReplacement:c,replacementInstruction:d}}}class Collect extends CompositeComponent{static componentType="collect";static assignNamesToReplacements=!0;static acceptTarget=!0;static acceptAnyAttribute=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.sourceAttributesToIgnore={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnore",defaultValue:[],public:!0},e.sourceAttributesToIgnoreRecursively={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnoreRecursively",defaultValue:["isResponse"],public:!0},e.componentTypes={createComponentOfType:"textList"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.link={returnDependencies:()=>({}),definition:()=>({setValue:{link:!0}})},e.targetComponent={shadowVariable:!0,returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){return{setValue:{targetComponent:e.targetComponent}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.targetName={returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"}}),definition:function({dependencyValues:e}){return null===e.targetComponent?(console.warn("No copy target"),{setValue:{targetName:""}}):{setValue:{targetName:e.targetComponent.componentName}}}},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.componentTypesToCollect={shadowVariable:!0,additionalStateVariablesDefined:[{variableName:"componentClassesToCollect",shadowVariable:!0}],returnDependencies:()=>({componentTypesAttr:{dependencyType:"attributeComponent",attributeName:"componentTypes",variableNames:["texts"]}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[],r=[];if(null!==e.componentTypesAttr)for(let a of e.componentTypesAttr.stateValues.texts){let e=t.componentTypeLowerCaseMapping[a.toLowerCase()],i=t.allComponentClasses[e];if(i)n.push(e),r.push(i);else{let e="Cannot collect component type "+a+". Component type not found.";console.warn(e)}}return{setValue:{componentTypesToCollect:n,componentClassesToCollect:r}}}},e.collectedComponents={stateVariablesDeterminingDependencies:["componentTypesToCollect","targetName","propName","componentIndex","propIndex"],additionalStateVariablesDefined:["effectivePropNameByComponent"],returnDependencies:function({stateValues:e}){if(!e.targetName)return{};let t={dependencyType:"descendant",ancestorName:e.targetName,componentTypes:e.componentTypesToCollect,useReplacementsForComposites:!0,includeNonActiveChildren:!0,recurseToMatchedChildren:!1,componentIndex:e.componentIndex};if(e.propName){let n=e.propIndex;n&&(n=[...n]),t.variableNames=[e.propName],t.variablesOptional=!0,t.propIndex=n,t.caseInsensitiveVariableMatch=!0,t.publicStateVariablesOnly=!0,t.useMappedVariableNames=!0}return{descendants:t,maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},propName:{dependencyType:"stateVariable",variableName:"propName"}}},definition:function({dependencyValues:e}){let t=e.descendants;if(t||(t=[]),null!==e.maximumNumber&&t.length>e.maximumNumber){let n=Math.max(0,Math.floor(e.maximumNumber));t=t.slice(0,n)}let n=[];for(let r of t){let t;r.stateValues&&(t=Object.keys(r.stateValues)[0]),!t&&e.propName&&(t="__prop_name_not_found"),n.push(t)}return{setValue:{collectedComponents:t,effectivePropNameByComponent:n}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({collectedComponents:{dependencyType:"stateVariable",variableName:"collectedComponents"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={returnDependencies:()=>({collectedComponents:{dependencyType:"stateVariable",variableName:"collectedComponents"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,nComponentsForSource:a,publicCaseInsensitiveAliasSubstitutions:i,flags:o}){if(!await e.stateValues.targetComponent)return{replacements:[]};let s=[],l=[],u=0,c=[];n.propVariablesCopiedByCollected=[],n.uniqueIdentifiersUsedByCollected={};let p=this.createAttributesObject(),d=await e.stateValues.collectedComponents;for(let m=0;me.componentName))}else l[m]=0,c[m]=[],n.propVariablesCopiedByCollected[m]=[];return n.numReplacementsByCollected=l,n.collectedNames=d.map((e=>e.componentName)),n.replacementNamesByCollected=c,{replacements:s}}static async createReplacementForCollected({component:e,components:t,collectedNum:n,numReplacementsSoFar:r,uniqueIdentifiersUsed:a,componentInfoObjects:i,compositeAttributesObj:o,nComponentsForSource:s,publicCaseInsensitiveAliasSubstitutions:l,flags:u}){let c=(await e.stateValues.collectedComponents)[n],p=t[c.componentName],d=[],m=[];if(!p)return{serializedReplacements:d,propVariablesCopiedByReplacement:m};let f=e.attributes.newNamespace?.primitive,h=(await e.stateValues.effectivePropNameByComponent)[n];if(h){let n=await replacementFromProp({component:e,components:t,replacementSource:c,propName:h,uniqueIdentifiersUsed:a,compositeAttributesObj:o,componentInfoObjects:i,nComponentsForSource:s,publicCaseInsensitiveAliasSubstitutions:l});d=n.serializedReplacements,m=n.propVariablesCopiedByReplacement}else{let t=await e.stateValues.sourceAttributesToIgnore,r=await e.stateValues.sourceAttributesToIgnoreRecursively;d=postProcessCopy({serializedComponents:[await p.serialize({sourceAttributesToIgnore:t,sourceAttributesToIgnoreRecursively:r})],componentName:e.componentName,uniqueIdentifiersUsed:a,identifierPrefix:n+"|"});for(let t of d){t.attributes||(t.attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:i,compositeAttributesObj:o,compositeCreatesNewNamespace:f,flags:u});Object.assign(t.attributes,n)}}return d=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:d,parentName:e.componentName,indOffset:r,parentCreatesNewNamespace:f,componentInfoObjects:i}).serializedComponents,{serializedReplacements:d,propVariablesCopiedByReplacement:m}}static async calculateReplacementChanges({component:e,componentChanges:t,components:n,workspace:r,componentInfoObjects:a,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:o,flags:s}){let l=0;for(let t=0;t0){if(!y){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:c,numberReplacementsToDelete:e};u.push(t)}y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}r.uniqueIdentifiersUsedByCollected[t]=[]}p[t]=0,d.push([]),m.push([]);continue}let h=r.collectedNames[t];if(void 0===h||l.componentName!==h||y){let l=0;void 0!==h&&(l=r.numReplacementsByCollected[t]);let f=l;y&&(f=0);let g=r.uniqueIdentifiersUsedByCollected[t]=[],v=await this.recreateReplacements({component:e,collectedNum:t,numReplacementsSoFar:c,numReplacementsToDelete:f,components:n,uniqueIdentifiersUsed:g,componentInfoObjects:a,compositeAttributesObj:b,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:o,flags:s});c+=v.numReplacements,p[t]=v.numReplacements,d[t]=v.propVariablesCopiedByReplacement;let T=v.replacementInstruction;if(m[t]=T.serializedReplacements.map((e=>e.componentName)),!y&&v.numReplacements!==l){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0);T.numberReplacementsToReplace=e,y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}u.push(T);continue}if(!await e.stateValues.propName){c+=r.numReplacementsByCollected[t],p[t]=r.numReplacementsByCollected[t],m[t]=r.replacementNamesByCollected[t],d[t]=[];continue}let g=r.uniqueIdentifiersUsedByCollected[t]=[],v=await this.createReplacementForCollected({component:e,collectedNum:t,components:n,numReplacementsSoFar:c,uniqueIdentifiersUsed:g,componentInfoObjects:a,compositeAttributesObj:b,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:o,flags:s}),T=v.propVariablesCopiedByReplacement,N=v.serializedReplacements,C=N.length;if(C!==r.numReplacementsByCollected[t]){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0),n={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:c,numberReplacementsToReplace:e,serializedReplacements:N,assignNamesOffset:c};u.push(n),y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}else for(let e=0;et!==T[e][n]))){let t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:c+e,numberReplacementsToReplace:1,serializedReplacements:[N[e]],assignNamesOffset:c+e};u.push(t)}c+=C,p[t]=C,d[t]=T,m[t]=N.map((e=>e.componentName))}return r.numReplacementsByCollected=p,r.collectedNames=f.map((e=>e.componentName)),r.propVariablesCopiedByCollected=d,r.replacementNamesByCollected=m,u}static async recreateReplacements({component:e,collectedNum:t,numReplacementsSoFar:n,numReplacementsToDelete:r,uniqueIdentifiersUsed:a,components:i,componentInfoObjects:o,compositeAttributesObj:s,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c}){let p=await this.createReplacementForCollected({component:e,collectedNum:t,components:i,numReplacementsSoFar:n,uniqueIdentifiersUsed:a,componentInfoObjects:o,compositeAttributesObj:s,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c}),d=p.propVariablesCopiedByReplacement,m=p.serializedReplacements,f={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:r,serializedReplacements:m,assignNamesOffset:n};return{numReplacements:m.length,propVariablesCopiedByReplacement:d,replacementInstruction:f}}}class Ref extends InlineComponent{static componentType="ref";static renderChildren=!0;static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.textType={createComponentOfType:"text",createStateVariable:"textType",defaultValue:"type-global",public:!0},e.uri={createPrimitiveOfType:"string",createStateVariable:"uri",defaultValue:null,public:!0,forRenderer:!0},e.page={createPrimitiveOfType:"integer",createStateVariable:"page",defaultValue:null,public:!0,forRenderer:!0},e.createButton={createComponentOfType:"boolean",createStateVariable:"createButton",defaultValue:!1,forRenderer:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){return{setValue:{targetComponent:e.targetComponent}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.targetName={forRenderer:!0,returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},uri:{dependencyType:"stateVariable",variableName:"uri"},page:{dependencyType:"stateVariable",variableName:"page"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"},targetAttribute:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:function({dependencyValues:e}){if(e.uri||e.page){if(e.targetAttribute){let t=e.targetAttribute;return"/"!==t[0]&&(t="/"+t),{setValue:{targetName:t}}}return{setValue:{targetName:""}}}return null===e.targetComponent||e.targetInactive?{setValue:{targetName:""}}:{setValue:{targetName:e.targetComponent.componentName}}}},e.cid={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"doenetId",forRenderer:!0},{variableName:"variantIndex",forRenderer:!0},{variableName:"edit",forRenderer:!0},{variableName:"draft",forRenderer:!0},{variableName:"hash",forRenderer:!0}],returnDependencies:()=>({uri:{dependencyType:"stateVariable",variableName:"uri"}}),definition:function({dependencyValues:e}){if(!e.uri||"doenet:"!==e.uri.substring(0,7).toLowerCase())return{setValue:{cid:null,doenetId:null,variantIndex:null,edit:null,draft:null,hash:null}};let t=null,n=null,r=null,a=null,i=null,o=null,s=e.uri.match(/[:&]cid=([^&^#]+)/i);return s&&(t=s[1]),s=e.uri.match(/[:&]doenetid=([^&^#]+)/i),s&&(n=s[1]),s=e.uri.match(/[:&]variant=([^&^#]+)/i),s&&(r=Number(s[1]),!Number.isInteger(r)&&r>=1&&(r=1)),s=e.uri.match(/[:&]edit=([^&^#]+)/i),s&&(i="true"===s[1].toLowerCase()),s=e.uri.match(/[:&]draft=([^&^#]+)/i),s&&(a="true"===s[1].toLowerCase()),s=e.uri.match(/(#.+)/i),s&&(o=s[1]),{setValue:{cid:t,doenetId:n,variantIndex:r,edit:i,draft:a,hash:o}}}},e.linkText={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["targetName"],returnDependencies({stateValues:e}){let t={allChildren:{dependencyType:"child",childGroups:["anything"],variableNames:["text"],variablesOptional:!0},uri:{dependencyType:"stateVariable",variableName:"uri"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"}};return e.targetName&&(t.equationTag={dependencyType:"stateVariable",componentName:e.targetName,variableName:"equationTag",variablesOptional:!0},t.title={dependencyType:"stateVariable",componentName:e.targetName,variableName:"title",variablesOptional:!0}),t},definition:function({dependencyValues:e}){let t="";if(0===e.allChildren.length)null!==e.uri?t=e.uri:e.targetInactive||(null!==e.title?t=e.title:null!==e.equationTag&&(t="("+e.equationTag+")"));else for(let n of e.allChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return t||(t="???"),{setValue:{linkText:t}}}},e}}class Coords extends MathComponent{static componentType="coords";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return delete e.createVectors,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.createVectors={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({}),definition:()=>({setValue:{createVectors:!0}})},e}}class LineSegment extends GraphicalComponent{static componentType="lineSegment";actions={moveLineSegment:this.moveLineSegment.bind(this),lineSegmentClicked:this.lineSegmentClicked.bind(this)};static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.endpoints={createComponentOfType:"_pointListComponent"},e.showCoordsWhenDragging={createComponentOfType:"boolean",createStateVariable:"showCoordsWhenDragging",defaultValue:!0,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" line segment"}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({endpointsAttr:{dependencyType:"attributeComponent",attributeName:"endpoints",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.endpointsAttr){return{setValue:{nDimensions:e.endpointsAttr.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},e.endpoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"endpointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["endpointX","endpoint"],hasEssential:!0,set:convertValueToMathExpression,defaultValueByArrayKey:e=>me$3.fromAst("0,0"===e?1:0),getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("endpointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("endpoints"===t)return 1===e.length?"endpoint"+e[0]:`endpointX${e[0]}_${e[1]}`;if("endpoint"===t.slice(0,8)){let n=Number(t.slice(8));if(Number.isInteger(n)&&n>0)return`endpointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={endpointsAttr:{dependencyType:"attributeComponent",attributeName:"endpoints",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,arraySize:n}){let r={},a={};for(let n of t){let[t,i]=n.split(","),o=Number(t)+1+"_"+(Number(i)+1);null!==e[n].endpointsAttr&&e[n].endpointsAttr.stateValues["pointX"+o]?r[n]=e[n].endpointsAttr.stateValues["pointX"+o]:a[n]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={endpoints:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={endpoints:a}),i},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.endpoints){let[a,o]=r.split(","),s=Number(a)+1+"_"+(Number(o)+1);null!==t[r].endpointsAttr&&t[r].endpointsAttr.stateValues["pointX"+s]?i.push({setDependency:n[r].endpointsAttr,desiredValue:e.endpoints[r],childIndex:0,variableIndex:0}):i.push({setEssentialValue:"endpoints",value:{[r]:e.endpoints[r]}})}return{success:!0,instructions:i}}},e.numericalEndpoints={isArray:!0,entryPrefixes:["numericalEndpoint"],forRenderer:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>Number.isNaN(e.nDimensions)?[0]:[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={endpoint:{dependencyType:"stateVariable",variableName:"endpoint"+(Number(n)+1)}};return{globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(Number.isNaN(e.nDimensions))return{};let r={};for(let a of n){let n=t[a].endpoint,i=[];for(let t=0;t({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"}}),definition({dependencyValues:e}){let t=e.numericalEndpoints[0][0],n=e.numericalEndpoints[0][1],r=e.numericalEndpoints[1][0],a=e.numericalEndpoints[1][1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),o=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(o)return{};let s=i[0],l=i[1],u=(r-t)/s,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/s*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:d>=1?{x1:r,x2:a}:{x1:t+d*u*s,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e.slope={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition({dependencyValues:e}){if(2!==e.nDimensions)return{setValue:{slope:NaN}};let t=e.numericalEndpoints;return{setValue:{slope:(t[1][1]-t[0][1])/(t[1][0]-t[0][0])}}}},e.length={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition({dependencyValues:e}){let t=e.numericalEndpoints,n=0;for(let r=0;r({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" ray"}}}},e.directionShadow={defaultValue:null,hasEssential:!0,essentialVarName:"direction",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{directionShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"directionShadow",value:convertValueToMathExpression(e.directionShadow)}]}}},e.throughShadow={defaultValue:null,hasEssential:!0,essentialVarName:"through",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{throughShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"throughShadow",value:convertValueToMathExpression(e.throughShadow)}]}}},e.endpointShadow={defaultValue:null,hasEssential:!0,essentialVarName:"endpoint",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{endpointShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"endpointShadow",value:convertValueToMathExpression(e.endpointShadow)}]}}},e.basedOnThrough={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"},endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint"},directionAttr:{dependencyType:"attributeComponent",attributeName:"direction"}}),definition:function({dependencyValues:e}){return null!==e.endpointAttr&&null!==e.directionAttr?(null!==e.throughAttr&&console.warn("Ray is prescribed by through, endpoint, and direction. Ignoring specified through."),{setValue:{basedOnThrough:!1},checkForActualChange:{basedOnThrough:!0}}):null!==e.throughAttr?{setValue:{basedOnThrough:!0},checkForActualChange:{basedOnThrough:!0}}:{setValue:{basedOnThrough:null!==e.throughShadow},checkForActualChange:{basedOnThrough:!0}}}},e.basedOnEndpoint={returnDependencies:()=>({endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"}}),definition:function({dependencyValues:e}){return null!==e.endpointAttr?{setValue:{basedOnEndpoint:!0},checkForActualChange:{basedOnEndpoint:!0}}:{setValue:{basedOnEndpoint:null!==e.endpointShadow},checkForActualChange:{basedOnEndpoint:!0}}}},e.basedOnDirection={returnDependencies:()=>({directionAttr:{dependencyType:"attributeComponent",attributeName:"direction"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"}}),definition:function({dependencyValues:e}){return null!==e.directionAttr?{setValue:{basedOnDirection:!0},checkForActualChange:{basedOnDirection:!0}}:{setValue:{basedOnDirection:null!==e.directionShadow},checkForActualChange:{basedOnDirection:!0}}}},e.nDimDirection={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"},directionAttr:{dependencyType:"attributeComponent",attributeName:"direction",variableNames:["nDimensions"]}};return e.basedOnDirection||(e.basedOnThrough&&(t.nDimThrough={dependencyType:"stateVariable",variableName:"nDimThrough"}),e.basedOnEndpoint&&(t.nDimEndpoint={dependencyType:"stateVariable",variableName:"nDimEndpoint"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnDirection){if(null!==e.directionAttr)t=e.directionAttr.stateValues.nDimensions;else if(e.directionShadow){let n=e.directionShadow.tree;t=Array.isArray(n)&&["tuple","vector"].includes(n[0])?n.length-1:2}}else t=e.basedOnThrough?e.basedOnEndpoint?e.nDimThrough===e.nDimEndpoint?e.nDimThrough:NaN:e.nDimThrough:e.basedOnEndpoint?e.nDimEndpoint:2;return{setValue:{nDimDirection:t},checkForActualChange:{nDimDirection:!0}}}},e.nDimThrough={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"},throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nDimensions"]}};return e.basedOnThrough||(e.basedOnEndpoint&&(t.nDimEndpoint={dependencyType:"stateVariable",variableName:"nDimEndpoint"}),e.basedOnDirection&&(t.nDimDirection={dependencyType:"stateVariable",variableName:"nDimDirection"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnThrough){if(null!==e.throughAttr)t=e.throughAttr.stateValues.nDimensions;else if(e.throughShadow){let n=e.throughShadow.tree;t=Array.isArray(n)&&["tuple","vector"].includes(n[0])?n.length-1:2}}else t=e.basedOnDirection?e.basedOnEndpoint?e.nDimDirection===e.nDimEndpoint?e.nDimDirection:NaN:e.nDimDirection:e.basedOnEndpoint?e.nDimEndpoint:2;return{setValue:{nDimThrough:t},checkForActualChange:{nDimThrough:!0}}}},e.nDimEndpoint={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"},endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint",variableNames:["nDimensions"]}};return e.basedOnEndpoint||(e.basedOnThrough&&(t.nDimThrough={dependencyType:"stateVariable",variableName:"nDimThrough"}),e.basedOnDirection&&(t.nDimDirection={dependencyType:"stateVariable",variableName:"nDimDirection"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnEndpoint){if(null!==e.endpointAttr)t=e.endpointAttr.stateValues.nDimensions;else if(e.endpointShadow){let n=e.endpointShadow.tree;t=Array.isArray(n)&&["tuple","vector"].includes(n[0])?n.length-1:2}}else t=e.basedOnDirection?e.basedOnThrough?e.nDimDirection===e.nDimThrough?e.nDimDirection:NaN:e.nDimDirection:e.basedOnThrough?e.nDimThrough:2;return{setValue:{nDimEndpoint:t},checkForActualChange:{nDimEndpoint:!0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},nDimDirection:{dependencyType:"stateVariable",variableName:"nDimDirection"},nDimThrough:{dependencyType:"stateVariable",variableName:"nDimThrough"},nDimEndpoint:{dependencyType:"stateVariable",variableName:"nDimEndpoint"}}),definition:function({dependencyValues:e}){let t;if(e.basedOnDirection){if(e.basedOnEndpoint){if(e.nDimDirection!==e.nDimEndpoint)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}}}else if(e.basedOnThrough&&e.nDimDirection!==e.nDimThrough)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimDirection}else if(e.basedOnEndpoint){if(e.basedOnThrough&&e.nDimEndpoint!==e.nDimThrough)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimEndpoint}else t=e.basedOnThrough?e.nDimThrough:2;return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.direction={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"directionX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["directionX"],hasEssential:!0,essentialVarName:"direction2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough"],returnArraySizeDependencies:()=>({nDimDirection:{dependencyType:"stateVariable",variableName:"nDimDirection"}}),returnArraySize:({dependencyValues:e})=>[e.nDimDirection],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={directionAttr:{dependencyType:"attributeComponent",attributeName:"direction",variableNames:["x"+e]}},!t.basedOnDirection&&t.basedOnThrough&&(n[r].endpointX={dependencyType:"stateVariable",variableName:"endpointX"+e},n[r].throughX={dependencyType:"stateVariable",variableName:"throughX"+e})}return{globalDependencies:{basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;e.basedOnDirection?null!==t[i].directionAttr?r[i]=t[i].directionAttr.stateValues["x"+n]:null!==e.directionShadow&&(r[i]=e.directionShadow.get_component(Number(i))):e.basedOnThrough?r[i]=t[i].throughX.subtract(t[i].endpointX).simplify():a[i]={defaultValue:me$3.fromAst("0"===i?1:0)}}let i={};return Object.keys(r).length>0&&(i.setValue={direction:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={direction:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],o=!1;for(let a in e.direction)t.basedOnDirection?null!==n[a].directionAttr?i.push({setDependency:r[a].directionAttr,desiredValue:e.direction[a],variableIndex:0}):o=!0:t.basedOnThrough?i.push({setDependency:r[a].throughX,desiredValue:n[a].endpointX.add(e.direction[a]).simplify()}):i.push({setEssentialValue:"direction",value:{[a]:convertValueToMathExpression(e.direction[a])}});if(o)if(a[0]>1){let t=["vector"];for(let n in e.direction)t[Number(n)+1]=e.direction[n].tree;t.length=a[0]+1,i.push({setDependency:"directionShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.direction&&i.push({setDependency:"directionShadow",desiredValue:e.direction[0]});return{success:!0,instructions:i}}},e.through={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["throughX"],set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnThrough"],returnArraySizeDependencies:()=>({nDimThrough:{dependencyType:"stateVariable",variableName:"nDimThrough"}}),returnArraySize:({dependencyValues:e})=>[e.nDimThrough],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["x"+e]}},t.basedOnThrough||(n[r].endpointX={dependencyType:"stateVariable",variableName:"endpointX"+e},n[r].directionX={dependencyType:"stateVariable",variableName:"directionX"+e})}return{globalDependencies:{basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=Number(a)+1;e.basedOnThrough?null!==t[a].throughAttr?r[a]=t[a].throughAttr.stateValues["x"+n]:null!==e.throughShadow&&(r[a]=e.throughShadow.get_component(Number(a))):r[a]=t[a].endpointX.add(t[a].directionX).simplify()}return{setValue:{through:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],o=!1;for(let a in e.through)t.basedOnThrough?n[a].throughAttr&&null!==n[a].throughAttr?i.push({setDependency:r[a].throughAttr,desiredValue:e.through[a],variableIndex:0}):null!==t.throughShadow&&(o=!0):i.push({setDependency:r[a].directionX,desiredValue:e.through[a].subtract(n[a].endpointX).simplify()});if(o)if(a[0]>1){let t=["vector"];for(let n in e.through)t[Number(n)+1]=e.through[n].tree;t.length=a[0]+1,i.push({setDependency:"throughShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.through&&i.push({setDependency:"throughShadow",desiredValue:e.through[0]});return{success:!0,instructions:i}}},e.endpoint={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"endpointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["endpointX"],hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(0),essentialVarName:"endpoint2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnEndpoint","basedOnThrough","basedOnDirection"],returnArraySizeDependencies:()=>({nDimEndpoint:{dependencyType:"stateVariable",variableName:"nDimEndpoint"}}),returnArraySize:({dependencyValues:e})=>[e.nDimEndpoint],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint",variableNames:["x"+e]}},t.basedOnEndpoint||t.basedOnThrough&&t.basedOnDirection&&(n[r].throughX={dependencyType:"stateVariable",variableName:"throughX"+e},n[r].directionX={dependencyType:"stateVariable",variableName:"directionX"+e})}return{globalDependencies:{basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;null!==t[i].endpointAttr?r[i]=t[i].endpointAttr.stateValues["x"+n]:null!==e.endpointShadow?r[i]=e.endpointShadow.get_component(Number(i)):e.basedOnThrough&&e.basedOnDirection?r[i]=t[i].throughX.subtract(t[i].directionX).simplify():a[i]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={endpoint:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={endpoint:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],o=!1;for(let a in e.endpoint)n[a].endpointAttr&&null!==n[a].endpointAttr?i.push({setDependency:r[a].endpointAttr,desiredValue:e.endpoint[a],variableIndex:0}):null!==t.endpointShadow?o=!0:t.basedOnThrough&&t.basedOnDirection?i.push({setDependency:r[a].directionX,desiredValue:n[a].throughX.subtract(e.endpoint[a]).simplify()}):i.push({setEssentialValue:"endpoint",value:{[a]:convertValueToMathExpression(e.endpoint[a])}});if(o)if(a[0]>1){let t=["vector"];for(let n in e.endpoint)t[Number(n)+1]=e.endpoint[n].tree;t.length=a[0]+1,i.push({setDependency:"endpointShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.endpoint&&i.push({setDependency:"endpointShadow",desiredValue:e.endpoint[0]});return{success:!0,instructions:i}}},e.numericalEndpoint={forRenderer:!0,returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},endpoint:{dependencyType:"stateVariable",variableName:"endpoint"}}),definition({dependencyValues:e}){if(Number.isNaN(e.nDimensions))return null;let t=e.endpoint,n=[];for(let r=0;r({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},through:{dependencyType:"stateVariable",variableName:"through"}}),definition({dependencyValues:e}){if(Number.isNaN(e.nDimensions))return null;let t=e.through,n=[];for(let r=0;r({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoint:{dependencyType:"stateVariable",variableName:"numericalEndpoint"},numericalThroughpoint:{dependencyType:"stateVariable",variableName:"numericalThroughpoint"}}),definition({dependencyValues:e}){let t=e.numericalEndpoint[0],n=e.numericalEndpoint[1],r=e.numericalThroughpoint[0],a=e.numericalThroughpoint[1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),o=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(o)return{};let s=i[0],l=i[1],u=(r-t)/s,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/s*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:{x1:t+d*u*s,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e}async moveRay({endpointcoords:e,throughcoords:t,transient:n,skippable:r,sourceInformation:a,actionId:i}){let o=[];if(void 0!==e){if(await this.stateValues.basedOnThrough&&await this.stateValues.basedOnDirection){let n;if(void 0===t){let t=await this.stateValues.numericalThroughpoint;n=e.map(((e,n)=>t[n]-e))}else n=e.map(((e,n)=>t[n]-e));o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}else o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"endpoint",value:e.map((e=>me$3.fromAst(e))),sourceInformation:a});if(void 0===t&&!await this.stateValues.basedOnThrough){let t=await this.stateValues.numericalThroughpoint,n=e.map(((e,n)=>t[n]-e));o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}if(void 0!==t){if(await this.stateValues.basedOnThrough)o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"through",value:t.map((e=>me$3.fromAst(e))),sourceInformation:a});else{null==e&&(e=await this.stateValues.numericalEndpoint);let n=e.map(((e,n)=>t[n]-e));o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}if(void 0===e&&await this.stateValues.basedOnThrough&&await this.stateValues.basedOnDirection){let e=await this.stateValues.numericalEndpoint,n=t.map(((t,n)=>t-e[n]));o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}return n?await this.coreFunctions.performUpdate({updateInstructions:o,transient:n,skippable:r,actionId:i}):await this.coreFunctions.performUpdate({updateInstructions:o,actionId:i,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{through:t,endpoint:e}}})}async rayClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Polygon extends Polyline{static componentType="polygon";static representsClosedPath=!0;actions={movePolygon:this.movePolygon.bind(this),polygonClicked:this.polygonClicked.bind(this)};get movePolygon(){return this.movePolyline}get polygonClicked(){return this.polylineClicked}static createAttributesObject(){let e=super.createAttributesObject();return e.filled={createComponentOfType:"boolean",createStateVariable:"filled",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord,n&&(t+=" with "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" with "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord+" polygon",n&&(t+=" with a "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" polygon with a "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord+" polygon",{setValue:{styleDescriptionWithNoun:t}}}},e.borderStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{borderStyleDescription:t}}}},e.fillStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t;return t=e.filled?e.selectedStyle.fillColorWord:"unfilled",{setValue:{fillStyleDescription:t}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,o=[],s=i[a-1]?.[0],l=i[a-1]?.[1];for(let e=0;e=1?{x1:f,x2:h}:{x1:l+b*a*n,x2:u+b*y*s};let g=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/s,2);g0&&(p.x3=0),p}}}}},e}}class Triangle extends Polygon{static componentType="triangle";static rendererType="polygon";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=e.styleDescriptionWithNoun.definition;return e.styleDescriptionWithNoun.definition=function({dependencyValues:e}){let n=t({dependencyValues:e}).setValue.styleDescriptionWithNoun;return n=n.replaceAll("polygon","triangle"),{setValue:{styleDescriptionWithNoun:n}}},e.vertices.hasEssential=!0,e.vertices.defaultValueByArrayKey=function(e){return["0,1","1,0"].includes(e)?me$3.fromAst(1):me$3.fromAst(0)},e.vertices.returnArraySizeDependencies=()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),e.vertices.returnArraySize=function({dependencyValues:e}){return[3,e.nDimensions]},e.vertices.arrayDefinitionByKey=function({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let[t,i]=a.split(","),o=Number(t)+1+"_"+(Number(i)+1),s=e[a].vertices;null!==s&&s.stateValues["pointX"+o]?n[a]=s.stateValues["pointX"+o]:r[a]=!0}return{setValue:{vertices:n},useEssentialOrDefaultValue:{vertices:r}}},e.vertices.inverseArrayDefinitionByKey=async function({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.vertices){let[a,o]=r.split(","),s=Number(a)+1+"_"+(Number(o)+1);null!==t[r].vertices&&t[r].vertices.stateValues["pointX"+s]?i.push({setDependency:n[r].vertices,desiredValue:e.vertices[r],variableIndex:0}):i.push({setEssentialValue:"vertices",value:{[r]:e.vertices[r].simplify()}})}return{success:!0,instructions:i}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{nVertices:3}})},e}}class Rectangle extends Polygon{static componentType="rectangle";static rendererType="polygon";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.vertices={createComponentOfType:"_pointListComponent"},e.center={createComponentOfType:"point"},e.width={createComponentOfType:"number"},e.height={createComponentOfType:"number"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=e.styleDescriptionWithNoun.definition;return e.styleDescriptionWithNoun.definition=function({dependencyValues:e}){let n=t({dependencyValues:e}).setValue.styleDescriptionWithNoun;return n=n.replaceAll("polygon","rectangle"),{setValue:{styleDescriptionWithNoun:n}}},e.nVerticesSpecified={returnDependencies:()=>({verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.verticesAttr?{setValue:{nVerticesSpecified:e.verticesAttr.stateValues.nPoints}}:{setValue:{nVerticesSpecified:0}}}},e.essentialVertex={isArray:!0,entryPrefixes:["essentialVertexX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"}}),returnArraySize:({dependencyValues:e})=>[0===e.nVerticesSpecified?2:0],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:function({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialVertex:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.essentialVertex)t.push({setEssentialValue:"essentialVertex",value:{[n]:e.essentialVertex[n]}});return{success:!0,instructions:t}}},e.haveSpecifiedCenter={returnDependencies:()=>({centerAttr:{dependencyType:"attributeComponent",attributeName:"center"}}),definition:({dependencyValues:e})=>({setValue:{haveSpecifiedCenter:null!==e.centerAttr}})},e.specifiedCenter={isArray:!0,entryPrefixes:["specifiedCenterX"],returnArraySizeDependencies:()=>({haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.haveSpecifiedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={centerAttr:{dependencyType:"attributeComponent",attributeName:"center",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=Number(r)+1;null!==e[r].centerAttr&&(n[r]=e[r].centerAttr.stateValues["x"+t])}return{setValue:{specifiedCenter:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.specifiedCenter)t[a].centerAttr&&null!==t[a].centerAttr&&r.push({setDependency:n[a].centerAttr,desiredValue:e.specifiedCenter[a],variableIndex:0});return{success:!0,instructions:r}}},e.specifiedWidth={defaultValue:1,hasEssential:!0,essentialVarName:"width",returnDependencies:()=>({widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["value"]},nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"},haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),definition:({dependencyValues:e})=>null!==e.widthAttr?{setValue:{specifiedWidth:e.widthAttr.stateValues.value}}:(e.haveSpecifiedCenter?1:0)+e.nVerticesSpecified<=1?{useEssentialOrDefaultValue:{specifiedWidth:!0}}:{setValue:{specifiedWidth:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>null!==t.widthAttr?{success:!0,instructions:[{setDependency:"widthAttr",desiredValue:e.specifiedWidth,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"specifiedWidth",value:e.specifiedWidth}]}},e.specifiedHeight={defaultValue:1,hasEssential:!0,essentialVarName:"height",returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["value"]},nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"},haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),definition:({dependencyValues:e})=>null!==e.heightAttr?{setValue:{specifiedHeight:e.heightAttr.stateValues.value}}:(e.haveSpecifiedCenter?1:0)+e.nVerticesSpecified<=1?{useEssentialOrDefaultValue:{specifiedHeight:!0}}:{setValue:{specifiedHeight:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>null!==t.heightAttr?{success:!0,instructions:[{setDependency:"heightAttr",desiredValue:e.specifiedHeight,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"specifiedHeight",value:e.specifiedHeight}]}},e.center={public:!0,isArray:!0,entryPrefixes:["centerX"],shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"centerX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_"+e},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_"+e}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex0,a=e[r].vertex2;n[r]=t.add(a).divide(2).simplify()}return{setValue:{center:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,stateValues:r}){let a=[],i=await r.center;for(let r in e.center){let o=Number(r),s=t[r].vertex0,l=t[r].vertex2,u=e.center[o].subtract(i[o]),c=s.add(u).simplify(),p=l.add(u).simplify();a.push({setDependency:n[r].vertex0,desiredValue:c},{setDependency:n[r].vertex2,desiredValue:p})}return{success:!0,instructions:a}}},e.width={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:({})=>({vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_1"},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_1"}}),definition({dependencyValues:e}){let t=e.vertex0.evaluate_to_constant(),n=e.vertex2.evaluate_to_constant();return{setValue:{width:Math.abs(t-n)}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=t.vertex0.evaluate_to_constant(),r=t.vertex2.evaluate_to_constant(),a=(r+n)/2,i=(r-n<0?-1:1)*Math.max(0,e.width)/2;return{success:!0,instructions:[{setDependency:"vertex0",desiredValue:me$3.fromAst(a-i)},{setDependency:"vertex2",desiredValue:me$3.fromAst(a+i)}]}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:({})=>({vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_2"},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_2"}}),definition({dependencyValues:e}){let t=e.vertex0.evaluate_to_constant(),n=e.vertex2.evaluate_to_constant();return{setValue:{height:Math.abs(t-n)}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=t.vertex0.evaluate_to_constant(),r=t.vertex2.evaluate_to_constant(),a=(r+n)/2,i=(r-n<0?-1:1)*Math.max(0,e.height)/2;return{success:!0,instructions:[{setDependency:"vertex0",desiredValue:me$3.fromAst(a-i)},{setDependency:"vertex2",desiredValue:me$3.fromAst(a+i)}]}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},stateVariablesDeterminingDependencies:["nVerticesSpecified","haveSpecifiedCenter"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[4,2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"}};if(0===t.nVerticesSpecified)if(r.haveSpecifiedCenter={dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"},t.haveSpecifiedCenter)for(let t of e){let[e,r]=t.split(",");n[t]={specifiedCenter:{dependencyType:"stateVariable",variableName:"specifiedCenterX"+(Number(r)+1)}},"0"===r?n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}:n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"}}else for(let t of e){let[e,r]=t.split(",");n[t]={essentialVertex:{dependencyType:"stateVariable",variableName:"essentialVertexX"+(Number(r)+1)}},"0"===r?"1"!==e&&"2"!==e||(n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}):"2"!==e&&"3"!==e||(n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"})}else if(1===t.nVerticesSpecified)if(r.haveSpecifiedCenter={dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"},t.haveSpecifiedCenter)for(let t of e){let[e,r]=t.split(","),a="1_"+(Number(r)+1);n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}},("0"===r&&"1"===e||"2"===e||"1"===r&&"2"===e||"3"===e)&&(n[t].specifiedCenter={dependencyType:"stateVariable",variableName:"specifiedCenterX"+(Number(r)+1)})}else for(let t of e){let[e,r]=t.split(","),a="1_"+(Number(r)+1);n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}},"0"===r?"1"!==e&&"2"!==e||(n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}):"2"!==e&&"3"!==e||(n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"})}else for(let t of e){let e,[r,a]=t.split(","),i="1_"+(Number(a)+1),o="2_"+(Number(a)+1);e="0"===r?i:"2"===r?o:"1"===r?"0"===a?o:i:"0"===a?i:o,n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+e]}}}return{dependenciesByKey:n,globalDependencies:r}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,globalDependencyValues:n}){let r={};if(0===n.nVerticesSpecified)if(n.haveSpecifiedCenter)for(let n of t){let[t,a]=n.split(","),i=e[n].specifiedCenter;if("0"===a){let a=e[n].specifiedWidth;r[n]="0"===t||"3"===t?i.subtract(a/2):i.add(a/2)}else{let a=e[n].specifiedHeight;r[n]="0"===t||"1"===t?i.subtract(a/2):i.add(a/2)}}else for(let n of t){let[t,a]=n.split(","),i=e[n].essentialVertex;if("0"===a)if("0"===t||"3"===t)r[n]=i;else{let t=e[n].specifiedWidth;r[n]=i.add(t)}else if("0"===t||"1"===t)r[n]=i;else{let t=e[n].specifiedHeight;r[n]=i.add(t)}}else if(1===n.nVerticesSpecified)if(n.haveSpecifiedCenter)for(let n of t){let t,[a,i]=n.split(","),o=e[n].verticesAttr;if(t=null!==o&&1===Object.keys(o.stateValues).length?Object.values(o.stateValues)[0]:me$3.fromAst("_"),"0"===i&&("0"===a||"3"===a)||"1"===i&&("0"===a||"1"===a))r[n]=t;else{let a=e[n].specifiedCenter;r[n]=t.add(a.subtract(t).multiply(2))}}else for(let n of t){let t,[a,i]=n.split(","),o=e[n].verticesAttr;if(t=null!==o&&1===Object.keys(o.stateValues).length?Object.values(o.stateValues)[0]:me$3.fromAst("_"),"0"===i)if("0"===a||"3"===a)r[n]=t;else{let a=e[n].specifiedWidth;r[n]=t.add(a)}else if("0"===a||"1"===a)r[n]=t;else{let a=e[n].specifiedHeight;r[n]=t.add(a)}}else for(let n of t){let t=e[n].verticesAttr;null!==t&&1===Object.keys(t.stateValues).length?r[n]=Object.values(t.stateValues)[0]:r[n]=me$3.fromAst("_")}return{setValue:{vertices:r}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,globalDependencyValues:n,stateValues:r,workspace:a,initialChange:i,dependencyNamesByKey:o}){if(i&&!await r.draggable)return{success:!1};if(!a.v0){let e=await r.vertices;a.v0=[...e[0]],a.v2=[...e[2]]}let s,l,u,c,p,d;for(let t in e.vertices){let[n,r]=t.split(","),i=e.vertices[t];"0"===n?a.v0[Number(r)]=i:"2"===n?a.v2[Number(r)]=i:"1"===n?"0"===r?a.v2[Number(r)]=i:a.v0[Number(r)]=i:"0"===r?a.v0[Number(r)]=i:a.v2[Number(r)]=i,"0"===r?(s=t,"0"===n||"3"===n?u=t:p=t):(l=t,"0"===n||"1"===n?c=t:d=t)}let m=[];if(0===n.nVerticesSpecified)if(n.haveSpecifiedCenter){if(void 0!==s){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant(),t=a.v2[0].add(a.v0[0]).divide(2).simplify();m.push({setDependency:o[s].specifiedWidth,desiredValue:e},{setDependency:o[s].specifiedCenter,desiredValue:t})}if(void 0!==l){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant(),t=a.v2[1].add(a.v0[1]).divide(2).simplify();m.push({setDependency:o[l].specifiedHeight,desiredValue:e},{setDependency:o[l].specifiedCenter,desiredValue:t})}}else{if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:o[u].essentialVertex,desiredValue:e})}if(void 0!==p){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant();m.push({setDependency:o[p].specifiedWidth,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:o[c].essentialVertex,desiredValue:e})}if(void 0!==d){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant();m.push({setDependency:o[d].specifiedHeight,desiredValue:e})}}else if(1===n.nVerticesSpecified)if(n.haveSpecifiedCenter){if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:o[u].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==p){let e=a.v2[0].add(a.v0[0]).divide(2).simplify();m.push({setDependency:o[p].specifiedCenter,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:o[c].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==d){let e=a.v2[1].add(a.v0[1]).divide(2).simplify();m.push({setDependency:o[d].specifiedCenter,desiredValue:e})}}else{if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:o[u].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==p){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant();m.push({setDependency:o[p].specifiedWidth,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:o[c].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==d){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant();m.push({setDependency:o[d].specifiedHeight,desiredValue:e})}}else void 0!==u&&m.push({setDependency:o[u].verticesAttr,desiredValue:a.v0[0],variableIndex:0}),void 0!==p&&m.push({setDependency:o[p].verticesAttr,desiredValue:a.v2[0],variableIndex:0}),void 0!==c&&m.push({setDependency:o[c].verticesAttr,desiredValue:a.v0[1],variableIndex:0}),void 0!==d&&m.push({setDependency:o[d].verticesAttr,desiredValue:a.v2[1],variableIndex:0});return{success:!0,instructions:m}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{nVertices:4}})},e}async movePolygon({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){let a=[],i={};for(let t in e)i[t+",0"]=me$3.fromAst(e[t][0]),i[t+",1"]=me$3.fromAst(e[t][1]);if(a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:i,sourceInformation:n}),1===Object.keys(e).length){let t=Number(Object.keys(e)[0]),n=me$3.fromAst(e[t][0]),r=me$3.fromAst(e[t][1]),i=(t+2)%4,o=await this.stateValues.vertices,s=o[i][0],l=o[i][1];if(await this.stateValues.nVerticesSpecified<2)if(await this.stateValues.haveSpecifiedCenter){let e,i;0===t?(e=n.add(s).divide(2),i=r.add(l).divide(2)):1===t?i=r.add(l).divide(2):3===t&&(e=n.add(s).divide(2)),void 0!==e&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedCenter",value:{0:e.simplify()}}),void 0!==i&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedCenter",value:{1:i.simplify()}})}else{let e,i;0===t?(e=s.subtract(n),i=l.subtract(r)):1===t?i=l.subtract(r):3===t&&(e=s.subtract(n)),void 0!==e&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedWidth",value:e.simplify()}),void 0!==i&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedHeight",value:i.simplify()})}}return t?await this.coreFunctions.performUpdate({updateInstructions:a,transient:t,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:a,actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}}class Circle extends Curve{static componentType="circle";static rendererType="circle";static representsClosedPath=!0;actions={moveCircle:this.moveCircle.bind(this),circleClicked:this.circleClicked.bind(this)};static createAttributesObject(){let e=super.createAttributesObject();return e.through={createComponentOfType:"_pointListComponent"},e.center={createComponentOfType:"point"},e.radius={createComponentOfType:"math"},e.filled={createComponentOfType:"boolean",createStateVariable:"filled",defaultValue:!1,public:!0,forRenderer:!0},delete e.parMin,delete e.parMax,delete e.variable,e}static returnChildGroups(){return GraphicalComponent.returnChildGroups()}static returnStateVariableDefinitions(e){let t=GraphicalComponent.returnStateVariableDefinitions(e);return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord,n&&(t+=" with "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" with "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord+" circle",n&&(t+=" with a "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" circle with a "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord+" circle",{setValue:{styleDescriptionWithNoun:t}}}},t.borderStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{borderStyleDescription:t}}}},t.fillStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t;return t=e.filled?e.selectedStyle.fillColorWord:"unfilled",{setValue:{fillStyleDescription:t}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{curveType:"circle"}})},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMax:NaN}})},t.parMin={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMin:NaN}})},t.fs={forRenderer:!0,isArray:!0,entryPrefixes:["f"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[0],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:()=>({setValue:{fs:{}}})},t.nThroughPoints={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.throughAttr?{setValue:{nThroughPoints:e.throughAttr.stateValues.nPoints}}:{setValue:{nThroughPoints:0}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),o=e[r].throughAttr;null!==o&&o.stateValues["pointX"+i]?n[r]=o.stateValues["pointX"+i]:n[r]=me$3.fromAst("_")}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,o]=r.split(","),s=Number(a)+1+"_"+(Number(o)+1);if(null===t[r].throughAttr||!t[r].throughAttr.stateValues["pointX"+s])return{success:!1};i.push({setDependency:n[r].throughAttr,desiredValue:e.throughPoints[r],variableIndex:0})}return{success:!0,instructions:i}}},t.havePrescribedCenter={returnDependencies:()=>({centerAttr:{dependencyType:"attributeComponent",attributeName:"center"}}),definition:({dependencyValues:e})=>({setValue:{havePrescribedCenter:null!==e.centerAttr},checkForActualChange:{havePrescribedCenter:!0}})},t.prescribedCenter={isArray:!0,entryPrefixes:["prescribedCenterX"],returnArraySizeDependencies:()=>({havePrescribedCenter:{dependencyType:"stateVariable",variableName:"havePrescribedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.havePrescribedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={centerAttr:{dependencyType:"attributeComponent",attributeName:"center",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let e of n){let n=Number(e)+1;null!==t[e].centerAttr&&(r[e]=t[e].centerAttr.stateValues["x"+n],r[e]||(r[e]=me$3.fromAst("_")))}return{setValue:{prescribedCenter:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t of Object.keys(e.prescribedCenter).reverse())null!==n[t].centerAttr&&i.push({setDependency:r[t].centerAttr,desiredValue:e.prescribedCenter[t],variableIndex:0});return{success:!0,instructions:i}}},t.prescribedRadius={defaultValue:null,returnDependencies:()=>({radiusAttr:{dependencyType:"attributeComponent",attributeName:"radius",variableNames:["value"]}}),definition:function({dependencyValues:e}){return null!==e.radiusAttr?{setValue:{prescribedRadius:e.radiusAttr.stateValues.value}}:{setValue:{prescribedRadius:null}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return null!==t.radiusAttr?{success:!0,instructions:[{setDependency:"radiusAttr",desiredValue:e.prescribedRadius,childIndex:0,variableIndex:0}]}:{success:!1}}},t.havePrescribedRadius={returnDependencies:()=>({radiusAttr:{dependencyType:"attributeComponent",attributeName:"radius"}}),definition:({dependencyValues:e})=>({setValue:{havePrescribedRadius:null!==e.radiusAttr},checkForActualChange:{havePrescribedRadius:!0}})},t.numericalPrescribedRadius={returnDependencies:()=>({prescribedRadius:{dependencyType:"stateVariable",variableName:"prescribedRadius"}}),additionalStateVariablesDefined:["haveNonNumericalPrescribedRadius"],definition:function({dependencyValues:e}){let t,n=!1;return null===e.prescribedRadius?t=null:(t=e.prescribedRadius.evaluate_to_constant(),Number.isFinite(t)||(t=NaN,n=!0)),{setValue:{haveNonNumericalPrescribedRadius:n,numericalPrescribedRadius:t},checkForActualChange:{haveNonNumericalEntriesNumericalRadius:!0}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){return await n.haveNonNumericalPrescribedRadius?{success:!1}:void 0!==e.numericalPrescribedRadius?null===t.prescribedRadius?{success:!1}:{success:!0,instructions:[{setDependency:"prescribedRadius",desiredValue:me$3.fromAst(e.numericalPrescribedRadius)}]}:{success:!1}}},t.numericalPrescribedCenter={isArray:!0,entryPrefixes:["numericalPrescribedCenterX"],returnArraySizeDependencies:()=>({havePrescribedCenter:{dependencyType:"stateVariable",variableName:"havePrescribedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.havePrescribedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={prescribedCenterX:{dependencyType:"stateVariable",variableName:"prescribedCenterX"+e}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].prescribedCenterX;t?(n[r]=t.evaluate_to_constant(),Number.isFinite(n[r])||(n[r]=NaN)):n[r]=NaN}return{setValue:{numericalPrescribedCenter:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.numericalPrescribedCenter)n.push({setDependency:t[r].prescribedCenterX,desiredValue:me$3.fromAst(e.numericalPrescribedCenter[r])});return{success:!0,instructions:n}}},t.haveNonNumericalPrescribedCenter={returnDependencies:()=>({numericalPrescribedCenter:{dependencyType:"stateVariable",variableName:"numericalPrescribedCenter"}}),definition({dependencyValues:e}){let t=e.numericalPrescribedCenter.some((e=>!Number.isFinite(e)));return{setValue:{haveNonNumericalPrescribedCenter:t},checkForActualChange:{haveNonNumericalPrescribedCenter:!0}}}},t.numericalThroughPoints={returnDependencies:()=>({throughPoints:{dependencyType:"stateVariable",variableName:"throughPoints"}}),additionalStateVariablesDefined:["haveNonNumericalThroughPoints"],definition:function({dependencyValues:e}){let t=!1,n=[];for(let r of e.throughPoints){let e=[];for(let n=0;n<2;n++){let a;try{a=r[n].evaluate_to_constant()}catch(n){console.warn("Invalid point of circle"),t=!0,e=[];break}if(!Number.isFinite(a)){t=!0,e=[];break}e.push(a)}if(!(e.length>0)){n=[];break}n.push(e)}return{setValue:{haveNonNumericalThroughPoints:t,numericalThroughPoints:n},checkForActualChange:{haveNonNumericalThroughPoints:!0}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(await n.haveNonNumericalThroughPoints)return{success:!1};if(void 0!==e.numericalThroughPoints){let t={};for(let[n,r]of e.numericalThroughPoints.entries())t[n+",0"]=me$3.fromAst(r[0]),t[n+",1"]=me$3.fromAst(r[1]);return{success:!0,instructions:[{setDependency:"throughPoints",desiredValue:t}]}}return{success:!1}}},t.haveNumericalEntries={returnDependencies:()=>({haveNonNumericalPrescribedCenter:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedCenter"},haveNonNumericalPrescribedRadius:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedRadius"},haveNonNumericalThroughPoints:{dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"}}),definition:({dependencyValues:e})=>({setValue:{haveNumericalEntries:!(e.haveNonNumericalPrescribedCenter||e.haveNonNumericalPrescribedRadius||e.haveNonNumericalThroughPoints)}})},t.numericalRadiusCalculatedWithCenter={additionalStateVariablesDefined:["numericalCenterCalculatedWithRadius"],returnDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},haveNumericalEntries:{dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"}}),definition:function({dependencyValues:e}){if(e.haveNonNumericalThroughPoints){let t="Haven't implemented circle through "+e.nThroughPoints+" points";return t+=" in case where don't have numerical values.",console.warn(t),{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}}if(2===e.nThroughPoints){let{numericalCenter:t,numericalRadius:n}=circleFromTwoNumericalPoints({point1:e.numericalThroughPoints[0],point2:e.numericalThroughPoints[1]});return{setValue:{numericalCenterCalculatedWithRadius:t,numericalRadiusCalculatedWithCenter:n}}}if(3===e.nThroughPoints){let t,n,r=e.numericalThroughPoints[0][0],a=e.numericalThroughPoints[1][0],i=e.numericalThroughPoints[2][0],o=e.numericalThroughPoints[0][1],s=e.numericalThroughPoints[1][1],l=e.numericalThroughPoints[2][1];if(r===a&&o===s)if(r===i&&o===l)t=[r,o],n=0;else{let e=circleFromTwoNumericalPoints({point1:[r,o],point2:[i,l]});t=e.numericalCenter,n=e.numericalRadius}else if(r===i&&o===l||a===i&&s===l){let e=circleFromTwoNumericalPoints({point1:[r,o],point2:[a,s]});t=e.numericalCenter,n=e.numericalRadius}else{let e=r*r+o*o,u=a*a+s*s,c=i*i+l*l,p=r*(s-l)-o*(a-i)+a*l-i*s,d=e*(l-s)+u*(o-l)+c*(s-o),m=e*(a-i)+u*(i-r)+c*(r-a),f=e*(i*s-a*l)+u*(r*l-i*o)+c*(a*o-r*s);0!==p?(t=[-d/(2*p),-m/(2*p)],n=Math.sqrt((d*d+m*m-4*p*f)/(4*p*p))):(t=[NaN,NaN],n=NaN)}return{setValue:{numericalCenterCalculatedWithRadius:t,numericalRadiusCalculatedWithCenter:n}}}return e.nThroughPoints>3?(console.warn("Can't calculate circle through more than 3 points"),{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}):{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}}},t.essentialRadius={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{essentialRadius:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"essentialRadius",value:e.essentialRadius}]}}},t.numericalRadius={forRenderer:!0,stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnDependencies:function({stateValues:e}){let t={haveNonNumericalPrescribedRadius:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedRadius"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},essentialRadius:{dependencyType:"stateVariable",variableName:"essentialRadius"}};return e.havePrescribedRadius?(t.numericalPrescribedRadius={dependencyType:"stateVariable",variableName:"numericalPrescribedRadius"},e.havePrescribedCenter&&e.nThroughPoints>0&&(t.haveCenterRadiusPoints={dependencyType:"value",value:!0})):e.havePrescribedCenter?1===e.nThroughPoints&&(t.haveNonNumericalPrescribedCenter={dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedCenter"},t.numericalPrescribedCenter={dependencyType:"stateVariable",variableName:"numericalPrescribedCenter"},t.haveNonNumericalThroughPoints={dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"},t.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"}):e.nThroughPoints>1&&(t.numericalRadiusCalculatedWithCenter={dependencyType:"stateVariable",variableName:"numericalRadiusCalculatedWithCenter"},t.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"}),t},definition:function({dependencyValues:e}){if(e.haveNonNumericalPrescribedRadius||e.haveNonNumericalPrescribedCenter||e.haveNonNumericalThroughPoints)return{setValue:{numericalRadius:NaN}};if(void 0!==e.numericalPrescribedRadius)return e.haveCenterRadiusPoints?(console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{numericalRadius:NaN}}):{setValue:{numericalRadius:Math.max(0,e.numericalPrescribedRadius)}};if(void 0!==e.numericalPrescribedCenter){if(0===e.nThroughPoints){let t=e.essentialRadius;if(t instanceof me$3.class){try{t=t.evaluate_to_constant()}catch(e){}Number.isFinite(t)||(t=NaN)}return{setValue:{numericalRadius:t}}}if(1===e.nThroughPoints){let t=e.numericalThroughPoints[0];return void 0===t?{setValue:{numericalRadius:NaN}}:{setValue:{numericalRadius:Math.sqrt(Math.pow(t[0]-e.numericalPrescribedCenter[0],2)+Math.pow(t[1]-e.numericalPrescribedCenter[1],2))}}}return console.warn("Can't calculate circle with specified center through more than 1 point"),{setValue:{numericalRadius:NaN}}}if(e.nThroughPoints<2){let t=e.essentialRadius;if(t instanceof me$3.class){try{t=t.evaluate_to_constant()}catch(e){}Number.isFinite(t)||(t=NaN)}return{setValue:{numericalRadius:t}}}return{setValue:{numericalRadius:e.numericalRadiusCalculatedWithCenter}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(void 0!==t.numericalPrescribedRadius)return{success:!0,instructions:[{setDependency:"numericalPrescribedRadius",desiredValue:Math.max(0,e.numericalRadius)}]};if(void 0!==t.numericalPrescribedCenter){if(0===t.nThroughPoints)return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:Math.max(0,e.numericalRadius)}]};if(1===t.nThroughPoints){let t=Math.max(0,e.numericalRadius),r=(await n.throughAngles)[0];if(!Number.isFinite(r))return{success:!1};let a=await n.numericalCenter;return{success:!0,instructions:[{setDependency:"numericalThroughPoints",desiredValue:[[a[0]+t*Math.cos(r),a[1]+t*Math.sin(r)]]}]}}return{success:!1}}if(t.nThroughPoints<2)return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:Math.max(0,e.numericalRadius)}]};{let r=[],a=Math.max(0,e.numericalRadius);for(let e=0;e0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:function({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialCenter:t}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,stateValues:t,workspace:n}){let r=[];for(let t in e.essentialCenter)r.push({setEssentialValue:"essentialCenter",value:{[t]:e.essentialCenter[t]}});return{success:!0,instructions:r}}},t.numericalCenter={forRenderer:!0,isArray:!0,entryPrefixes:["numericalCenterX"],stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={};if(t.havePrescribedCenter){for(let t of e){let e=Number(t)+1;r[t]={numericalPrescribedCenterX:{dependencyType:"stateVariable",variableName:"numericalPrescribedCenterX"+e}}}t.havePrescribedRadius&&t.nThroughPoints>0&&(n.haveCenterRadiusPoints={dependencyType:"value",value:!0})}else{for(let t of e){let e=Number(t)+1;r[t]={essentialCenterX:{dependencyType:"stateVariable",variableName:"essentialCenterX"+e}}}n.nThroughPoints={dependencyType:"stateVariable",variableName:"nThroughPoints"},n.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"},n.haveNonNumericalThroughPoints={dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"},t.havePrescribedRadius||1==t.nThroughPoints?n.numericalRadius={dependencyType:"stateVariable",variableName:"numericalRadius"}:t.nThroughPoints>1&&(n.numericalCenterCalculatedWithRadius={dependencyType:"stateVariable",variableName:"numericalCenterCalculatedWithRadius"})}return{globalDependencies:n,dependenciesByKey:r}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(void 0!==t[a].numericalPrescribedCenterX){if(e.haveCenterRadiusPoints)return console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{numericalCenter:[NaN,NaN]}};r[a]=t[a].numericalPrescribedCenterX}if(Object.keys(r).length>0)return{setValue:{numericalCenter:r}};if(e.haveNonNumericalPrescribedRadius||e.haveNonNumericalThroughPoints)return{setValue:{numericalCenter:[NaN,NaN]}};if(void 0!==e.numericalRadius){if(0===e.nThroughPoints){for(let e of n){let n=t[e].essentialCenterX;if(n instanceof me$3.class){try{n=n.evaluate_to_constant()}catch(e){}Number.isFinite(n)||(n=NaN)}r[e]=n}return{setValue:{numericalCenter:r}}}if(1===e.nThroughPoints){if(e.numericalThroughPoints.length<1)return{setValue:{numericalCenter:[NaN,NaN]}};return{setValue:{numericalCenter:[e.numericalThroughPoints[0][0],e.numericalThroughPoints[0][1]-e.numericalRadius]}}}if(2===e.nThroughPoints){if(e.numericalThroughPoints.length<2)return{setValue:{numericalCenter:[NaN,NaN]}};let t=e.numericalRadius,n=e.numericalThroughPoints[0][0],r=e.numericalThroughPoints[1][0],a=e.numericalThroughPoints[0][1],i=e.numericalThroughPoints[1][1],o=Math.pow(n-r,2)+Math.pow(a-i,2),s=t*t;return t<0||4*s0)return{success:!0,instructions:o};if(0===t.nThroughPoints){for(let t in e.numericalCenter)o.push({setDependency:r[t].essentialCenterX,desiredValue:e.numericalCenter[t]});return{success:!0,instructions:o}}{i.desiredCenter||(i.desiredCenter={});for(let t=0;t<2;t++)void 0!==e.numericalCenter[t]?i.desiredCenter[t]=e.numericalCenter[t]:void 0===i.desiredCenter[t]&&(i.desiredCenter[t]=a.numericalCenter[t]);let n=[],r=await a.throughAngles,o=await a.numericalRadius;for(let e=0;e({haveNumericalEntries:{dependencyType:"stateVariable",variableName:"haveNumericalEntries"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"},numericalCenter:{dependencyType:"stateVariable",variableName:"numericalCenter"}}),definition:function({dependencyValues:e}){if(!(e.haveNumericalEntries&&e.nThroughPoints>0&&e.numericalRadius>0&&e.numericalCenter.every((e=>Number.isFinite(e)))))return{useEssentialOrDefaultValue:{throughAngles:!0}};let t=[];for(let n of e.numericalThroughPoints)t.push(Math.atan2(n[1]-e.numericalCenter[1],n[0]-e.numericalCenter[0]));return{setValue:{throughAngles:t},setEssentialValue:{throughAngles:t}}}},t.radius={public:!0,shadowingInstructions:{createComponentOfType:"math"},stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnDependencies:function({stateValues:e}){let t={numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},essentialRadius:{dependencyType:"stateVariable",variableName:"essentialRadius"}};return e.havePrescribedRadius?(t.prescribedRadius={dependencyType:"stateVariable",variableName:"prescribedRadius"},e.havePrescribedCenter&&e.nThroughPoints>0&&(t.haveCenterRadiusPoints={dependencyType:"value",value:!0})):e.havePrescribedCenter&&1===e.nThroughPoints&&(t.prescribedCenter={dependencyType:"stateVariable",variableName:"prescribedCenter"},t.throughPoints={dependencyType:"stateVariable",variableName:"throughPoints"}),t},definition:function({dependencyValues:e}){if(Number.isFinite(e.numericalRadius))return{setValue:{radius:me$3.fromAst(e.numericalRadius)}};if(void 0!==e.prescribedRadius)return e.haveCenterRadiusPoints?(console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{radius:me$3.fromAst("_")}}):{setValue:{radius:e.prescribedRadius}};if(void 0!==e.prescribedCenter){if(0===e.nThroughPoints){let t=e.essentialRadius;return t instanceof me$3.class||(t=Number.isFinite(t)?me$3.fromAst(t):me$3.fromAst("_")),{setValue:{radius:t}}}if(1!==e.nThroughPoints)return console.warn("Can't calculate circle with specified center through more than 1 point"),{setValue:{radius:me$3.fromAst("_")}};try{let t=e.throughPoints[0],n=t[0],r=t[1],a=e.prescribedCenter[0],i=e.prescribedCenter[1];return{setValue:{radius:n.subtract(a).pow(2).add(r.subtract(i).pow(2)).pow(.5).simplify()}}}catch(e){return console.warn("Invalid center or through points of circle"),{setValue:{radius:me$3.fromAst("_")}}}}if(e.nThroughPoints<2){let t=e.essentialRadius;return t instanceof me$3.class||(t=Number.isFinite(t)?me$3.fromAst(t):me$3.fromAst("_")),{setValue:{radius:t}}}return console.warn(`Have not implemented circle through ${e.nThroughPoints} points when non-numerical values`),{setValue:{radius:me$3.fromAst("_")}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n=e.radius.evaluate_to_constant();if(Number.isFinite(n)&&Number.isFinite(t.numericalRadius))return{success:!0,instructions:[{setDependency:"numericalRadius",desiredValue:n}]};if(void 0!==t.prescribedRadius)return{success:!0,instructions:[{setDependency:"prescribedRadius",desiredValue:e.radius}]};if(0===t.nThroughPoints){return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:e.radius}]}}return console.warn("Can't change radius of circle with non-numerical values through points"),{success:!1}}},t.diameter={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({radius:{dependencyType:"stateVariable",variableName:"radius"}}),definition:({dependencyValues:e})=>({setValue:{diameter:e.radius.multiply(2).simplify()}}),inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return{success:!0,instructions:[{setDependency:"radius",desiredValue:e.diameter.divide(2).simplify()}]}}},t.center={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"centerX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["centerX"],stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={};if(t.havePrescribedCenter){n.havePrescribedCenter={dependencyType:"value",value:!0};for(let t of e){let e=Number(t)+1;r[t]={numericalCenterX:{dependencyType:"stateVariable",variableName:"numericalCenterX"+e},prescribedCenterX:{dependencyType:"stateVariable",variableName:"prescribedCenterX"+e}}}t.havePrescribedRadius&&t.nThroughPoints>0&&(n.haveCenterRadiusPoints={dependencyType:"value",value:!0})}else{for(let t of e){let e=Number(t)+1;r[t]={essentialCenterX:{dependencyType:"stateVariable",variableName:"essentialCenterX"+e}}}n.numericalCenter={dependencyType:"stateVariable",variableName:"numericalCenter"},n.nThroughPoints={dependencyType:"stateVariable",variableName:"nThroughPoints"},n.throughPoints={dependencyType:"stateVariable",variableName:"throughPoints"},t.havePrescribedRadius?n.radius={dependencyType:"stateVariable",variableName:"prescribedRadius"}:1==t.nThroughPoints&&(n.radius={dependencyType:"stateVariable",variableName:"radius"})}return{dependenciesByKey:r,globalDependencies:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(e.havePrescribedCenter){if(e.haveCenterRadiusPoints)return console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}};let r={};for(let e of n)Number.isFinite(t[e].numericalCenterX)?r[e]=me$3.fromAst(t[e].numericalCenterX):r[e]=t[e].prescribedCenterX;return{setValue:{center:r}}}if(e.numericalCenter.every((e=>Number.isFinite(e))))return{setValue:{center:e.numericalCenter.map((e=>me$3.fromAst(e)))}};if(void 0!==e.radius){if(0===e.nThroughPoints){let e={};for(let r of n){let n=t[r].essentialCenterX;n instanceof me$3.class||(n=Number.isFinite(n)?me$3.fromAst(n):me$3.fromAst("_")),e[r]=n}return{setValue:{center:e}}}if(1===e.nThroughPoints){let t;try{t=[e.throughPoints[0][0],e.throughPoints[0][1].subtract(e.radius).simplify()]}catch(e){t=[me$3.fromAst("_"),me$3.fromAst("_")]}return{setValue:{center:t}}}return console.warn("Can't create circle through more than one point with given radius when don't have numerical values"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}}}if(0===e.nThroughPoints){let e={};for(let r of n){let n=t[r].essentialCenterX;n instanceof me$3.class||(n=Number.isFinite(n)?me$3.fromAst(n):me$3.fromAst("_")),e[r]=n}return{setValue:{center:e}}}return console.warn("Can't create circle through more than one point when don't have numerical values"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,stateValues:n,dependencyNamesByKey:r,workspace:a}){if(t.havePrescribedCenter){let t=[];for(let n in e.center)t.push({setDependency:r[n].prescribedCenterX,desiredValue:e.center[n],arrayKey:n});return{success:!0,instructions:t}}a.desiredCenter||(a.desiredCenter={});for(let t=0;t<2;t++)void 0!==e.center[t]?a.desiredCenter[t]=e.center[t]:void 0===a.desiredCenter[t]&&(a.desiredCenter[t]=(await n.center)[t]);let i=[],o=!0;for(let e=0;e<2;e++){let t=a.desiredCenter[e].evaluate_to_constant();if(!Number.isFinite(t)){o=!1;break}i.push(t)}if(o&&t.numericalCenter.every((e=>Number.isFinite(e))))return{success:!0,instructions:[{setDependency:"numericalCenter",desiredValue:i}]};if(0===t.nThroughPoints){let t=[];for(let n in e.center)t.push({setDependency:r[n].essentialCenterX,desiredValue:e.center[n],arrayKey:n});return{success:!0,instructions:t}}return console.warn("Haven't implemented changing center of circle through points with non numerical values"),{success:!1}}},t.nearestPoint={returnDependencies:()=>({numericalCenter:{dependencyType:"stateVariable",variableName:"numericalCenter"},numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"}}),definition({dependencyValues:e}){let t=e.numericalRadius,n=e.numericalCenter[0],r=e.numericalCenter[1];return{setValue:{nearestPoint:function({variables:e,scales:a}){let i=e.x1?.evaluate_to_constant(),o=e.x2?.evaluate_to_constant();if(!Number.isFinite(i)||!Number.isFinite(o))return{};if(!(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(t)))return{};let s=Math.atan2(o-r,i-n),l={x1:n+t*Math.cos(s),x2:r+t*Math.sin(s)};return void 0!==e.x3&&(l.x3=0),l}}}}},t}async moveCircle({center:e,radius:t,throughAngles:n,transient:r,actionId:a}){let i=[],o=await this.stateValues.nThroughPoints,s=await this.stateValues.numericalPrescribedCenter;if((o<=1||null!==s)&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"numericalCenter",value:e}),o>=1){let r=[];void 0===n&&(n=await this.stateValues.throughAngles),void 0===t&&(t=await this.stateValues.numericalRadius);for(let a=0;a({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" parabola"}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{curveType:"function"}})},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMax:1/0}})},t.parMin={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMin:-1/0}})},t.aShadow={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{aShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"aShadow",value:e.aShadow}]}}},t.nThroughPoints={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null===e.throughAttr?{setValue:{nThroughPoints:0}}:{setValue:{nThroughPoints:e.throughAttr.stateValues.nPoints}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),o=e[r].throughAttr;if(null!==o&&o.stateValues["pointX"+i]){let e=o.stateValues["pointX"+i].evaluate_to_constant();Number.isFinite(e)?n[r]=me$3.fromAst(e):n[r]=me$3.fromAst("_")}else n[r]=me$3.fromAst("_")}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,o]=r.split(","),s=Number(a)+1+"_"+(Number(o)+1);if(null===t[r].throughAttr||!t[r].throughAttr.stateValues["pointX"+s])return{success:!1};i.push({setDependency:n[r].throughAttr,desiredValue:e.throughPoints[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:i}}},t.numericalThroughPoints={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={throughPoint:{dependencyType:"stateVariable",variableName:"throughPoint"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].throughPoint.map((e=>e.tree));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalThroughPoints:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.numericalThroughPoints){if(!t[a].throughPoint)return{success:!1};r.push({setDependency:n[a].throughPoint,desiredValue:e.numericalThroughPoints[a].map((e=>me$3.fromAst(e)))})}return{success:!0,instructions:r}}},t.numericalPrescribedVertex={returnDependencies:()=>({prescribedVertex:{dependencyType:"stateVariable",variableName:"prescribedVertex"}}),definition({dependencyValues:e}){if(null===e.prescribedVertex)return{setValue:{numericalPrescribedVertex:null}};let t,n;try{t=e.prescribedVertex.get_component(0).evaluate_to_constant(),n=e.prescribedVertex.get_component(1).evaluate_to_constant(),Number.isFinite(t)&&Number.isFinite(n)||(t=NaN,n=NaN)}catch(e){t=NaN,n=NaN}return{setValue:{numericalPrescribedVertex:[t,n]}}}},t.pointsAreNumerical={returnDependencies:()=>({numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalPrescribedVertex:{dependencyType:"stateVariable",variableName:"numericalPrescribedVertex"}}),definition:({dependencyValues:e})=>({setValue:{pointsAreNumerical:e.numericalThroughPoints.every((e=>Number.isFinite(e[0])))&&(!e.numericalPrescribedVertex||Number.isFinite(e.numericalPrescribedVertex[0]))},checkForActualChange:{pointsAreNumerical:!0}})},t.a={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"b",public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0},{variableName:"c",public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0},"realValued"],returnDependencies:()=>({numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalPrescribedVertex:{dependencyType:"stateVariable",variableName:"numericalPrescribedVertex"},pointsAreNumerical:{dependencyType:"stateVariable",variableName:"pointsAreNumerical"},aShadow:{dependencyType:"stateVariable",variableName:"aShadow"}}),definition:function({dependencyValues:e,componentName:t}){if(!e.pointsAreNumerical)return{setValue:{a:NaN,b:NaN,c:NaN,realValued:!1}};let n,r,a,i=!0;if(e.numericalPrescribedVertex){if(0===e.numericalThroughPoints.length){let t=e.numericalPrescribedVertex,i=t[0],o=t[1];return n=e.aShadow,r=-2*n*i,a=n*i*i+o,{setValue:{a:n,b:r,c:a,realValued:!0}}}{let t=e.numericalPrescribedVertex,i=t[0],o=t[1],s=e.numericalThroughPoints[0],l=s[0];return n=(s[1]-o)/(l-i)**2,r=-2*n*i,a=n*i*i+o,{setValue:{a:n,b:r,c:a,realValued:!0}}}}if(0===e.numericalThroughPoints.length)return{setValue:{a:e.aShadow,realValued:!0},useEssentialOrDefaultValue:{b:!0,c:!0}};if(1===e.numericalThroughPoints.length){let t=e.numericalThroughPoints[0],i=t[0],o=t[1];return n=e.aShadow,r=-2*n*i,a=n*i*i+o,{setValue:{a:n,b:r,c:a,realValued:!0}}}if(2===e.numericalThroughPoints.length){n=e.aShadow;let t=e.numericalThroughPoints[0],o=t[0],s=t[1],l=o*o,u=e.numericalThroughPoints[1],c=u[0],p=u[1],d=c*c;return o===c?s==p?(r=-2*n*o,a=n*l+s):(i=!1,n=NaN,r=NaN,a=NaN):(r=(s-p-n*(l-d))/(o-c),a=s-n*l-r*o),{setValue:{a:n,b:r,c:a,realValued:i}}}if(3===e.numericalThroughPoints.length){let t=e.numericalThroughPoints[0],o=t[0],s=t[1],l=o*o,u=e.numericalThroughPoints[1],c=u[0],p=u[1],d=c*c,m=e.numericalThroughPoints[2],f=m[0],h=m[1],y=f*f,b=l-y,g=d-y,v=o-f,T=c-f,N=s-h,C=p-h,A=b*T-g*v;if(0===A){let t,u,d,m=!1;o===c?s===p?o===f?s==h?t=1:m=!0:(t=2,u=f,d=h):m=!0:o===f?s===h?(t=2,u=c,d=p):m=!0:c===f&&p===h?(t=2,u=c,d=p):m=!0,m?(i=!1,n=NaN,r=NaN,a=NaN):1===t?(n=e.aShadow,r=-2*n*o,a=n*o*o+s):(n=e.aShadow,r=(s-d-n*(l-u*u))/(o-u),a=s-n*l-r*o)}else n=(N*T-C*v)/A,r=(C*b-N*g)/A,a=s-r*o-n*l;return{setValue:{a:n,b:r,c:a,realValued:i}}}return console.warn("Haven't implemented parabola through more than 3 points"),{setValue:{a:NaN,b:NaN,c:NaN,realValued:!1}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r}){if(!t.pointsAreNumerical)return{success:!1};let a={},i=function(e){if(Number.isFinite(e))return{success:!0,value:e};if(e instanceof me$3.class){let t=e.evaluate_to_constant();if(Number.isFinite(t))return{success:!0,value:t}}return{success:!1}};if(void 0!==e.a){let t=i(e.a);if(!t.success)return{success:!1};a.a=t.value}if(void 0!==e.b){let t=i(e.b);if(!t.success)return{success:!1};a.b=t.value}if(void 0!==e.c){let t=i(e.c);if(!t.success)return{success:!1};a.c=t.value}Object.assign(r,a);let o=async function(e){return void 0!==r[e]?r[e]:await n[e]};if(0===t.numericalThroughPoints.length){let e=[];return void 0!==a.a&&e.push({setDependency:"aShadow",desiredValue:a.a}),void 0!==a.b&&e.push({setEssentialValue:"b",value:a.b}),void 0!==a.c&&e.push({setEssentialValue:"c",value:a.c}),{success:!0,instructions:e}}if(1===t.numericalThroughPoints.length){let e=await o("a"),t=await o("b"),n=await o("c"),r=[{setDependency:"numericalThroughPoints",desiredValue:[[-t/(2*e),n-t*t/(4*e)]]}];return void 0!==a.a&&r.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:r}}if(2===t.numericalThroughPoints.length){let e=await o("a"),n=await o("b"),r=await o("c"),i=t.numericalThroughPoints[0][0],s=t.numericalThroughPoints[1][0];if(i===s){i=-n/(2*e);let t=r-n*n/(4*e),o=[{setDependency:"numericalThroughPoints",desiredValue:[[i,t],[i,t]]}];return void 0!==a.a&&o.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:o}}{let t=[{setDependency:"numericalThroughPoints",desiredValue:[[i,e*i*i+n*i+r],[s,e*s*s+n*s+r]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}if(3===t.numericalThroughPoints.length){let e,n=await o("a"),r=await o("b"),i=await o("c"),s=t.numericalThroughPoints[0][0],l=t.numericalThroughPoints[1][0],u=t.numericalThroughPoints[2][0],c=3;if(s===l?s===u?c=1:(c=2,e=3):s===u?(c=2,e=2):l===u&&(c=2,e=1),3===c){let e=[{setDependency:"numericalThroughPoints",desiredValue:[[s,n*s*s+r*s+i],[l,n*l*l+r*l+i],[u,n*u*u+r*u+i]]}];return void 0!==a.a&&e.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:e}}if(2===c){if(1===e){let e=n*l*l+r*l+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[s,n*s*s+r*s+i],[l,e],[l,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}if(2===e){let e=n*s*s+r*s+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[s,e],[l,n*l*l+r*l+i],[s,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}{let e=n*s*s+r*s+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[s,e],[s,e],[u,n*u*u+r*u+i]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}{s=-r/(2*n);let e=i-r*r/(4*n),t=[{setDependency:"numericalThroughPoints",desiredValue:[[s,e],[s,e],[s,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}return{success:!1}}},t.vertex={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["vertexX"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({globalDependencies:{a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"},realValued:{dependencyType:"stateVariable",variableName:"realValued"}}}),arrayDefinitionByKey:function({globalDependencyValues:e}){let t={};return e.realValued&&0!==e.a?(t[0]=me$3.fromAst(-e.b/(2*e.a)),t[1]=me$3.fromAst(e.c-e.b**2/(4*e.a))):(t[0]=me$3.fromAst("_"),t[1]=me$3.fromAst("_")),{setValue:{vertex:t}}},inverseArrayDefinitionByKey:async function({desiredStateVariableValues:e,globalDependencyValues:t,workspace:n,stateValues:r}){let a,i;if(a="0"in e.vertex?e.vertex[0].evaluate_to_constant():void 0!==n.x?n.x:(await r.vertex)[0].tree,!Number.isFinite(a))return{success:!1};if(n.x=a,i="1"in e.vertex?e.vertex[1].evaluate_to_constant():void 0!==n.y?n.y:(await r.vertex)[1].tree,!Number.isFinite(i))return{success:!1};n.y=i;let o=t.a;return{success:!0,instructions:[{setDependency:"b",desiredValue:-2*o*a,additionalDependencyValues:{c:i+o*a*a}}]}}},t.equation={public:!0,shadowingInstructions:{createComponentOfType:"math"},additionalProperties:{simplify:"numberspreserveorder",displaysmallaszero:!0},returnDependencies:()=>({a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}),definition:function({dependencyValues:e}){let t=["=","y",["+",["*",e.a,["^","x",2]],["*",e.b,"x"],e.c]];return{setValue:{equation:me$3.fromAst(t).evaluate_numbers({skip_ordering:!0})}}}},t.fs={forRenderer:!0,isArray:!0,entryPrefixes:["f"],additionalStateVariablesDefined:[{variableName:"fDefinitions",isArray:!0,forRenderer:!0}],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[1],returnArrayDependenciesByKey:()=>({globalDependencies:{a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>({setValue:{fs:[function(t){return e.a*t*t+e.b*t+e.c}],fDefinitions:[{functionType:"formula",formula:["+",["*",e.a,"x","x"],["*",e.b,"x"],e.c],variables:["x"],nInputs:1,nOutputs:1,domain:null}]}})},t.f={isAlias:!0,targetVariableName:"f1"},t.nearestPoint={returnDependencies:()=>({f:{dependencyType:"stateVariable",variableName:"f"},a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}),definition({dependencyValues:e,componentName:t}){let n=!(Number.isFinite(e.a)&&Number.isFinite(e.b)&&Number.isFinite(e.c));return{setValue:{nearestPoint:function({variables:t,scales:r}){if(n)return{};let a=r[0],i=r[1],o=t.x1?.evaluate_to_constant(),s=t.x2?.evaluate_to_constant();if(!Number.isFinite(o)||!Number.isFinite(s))return{};o/=a,s/=i;let l=e.a*a*a/i,u=e.b*a/i,c=e.c/i;if(0===l){let e=u*u+1,n={};return n.x1=(o+u*s-u*c)/e*a,n.x2=(u*(o+u*s)+c)/e*i,void 0!==t.x3&&(n.x3=0),n}let p=c-s,d=2*l**2,m=cardano(3*l*u/d,(2*l*p+u**2+1)/d,(u*p-o)/d,1e-14),f=m[0],h=e.f(f*a)/i,y=(o-f)**2+(s-h)**2;for(let t of m.slice(1)){let n=t,r=e.f(n*a)/i,l=(o-n)**2+(s-r)**2;l0){const t=Math.sqrt(o/108),n=2*Math.sqrt(Math.cbrt(i*i/4+o/108)),r=Math.atan2(t,-i/2);return[Math.cos(r/3),Math.cos(r/3+2*Math.PI/3),Math.cos(r/3-2*Math.PI/3)].sort(((e,t)=>e-t)).map((t=>n*t-e/3))}const s=Math.sqrt(-o/108);return[Math.cbrt(-i/2+s)+Math.cbrt(-i/2-s)-e/3]}class BezierControls extends InlineComponent{static componentType="bezierControls";static rendererType="containerInline";static createAttributesObject(){let e=super.createAttributesObject();return e.alwaysVisible={createComponentOfType:"boolean",createStateVariable:"alwaysVisible",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"controlVectors",children:[{componentType:"vector",children:e}]}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"controlVectors",componentTypes:["controlVectors"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nControls={returnDependencies:()=>({nParentPoints:{dependencyType:"parentStateVariable",variableName:"nThroughPoints",skipComponentNames:!0}}),definition({dependencyValues:e}){let t=e.nParentPoints;return Number.isInteger(t)&&t>=0||(t=0),{setValue:{nControls:t}}}},e.pointIndMap={returnDependencies:()=>({controlChildren:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["pointNumber"]}}),definition:function({dependencyValues:e}){let t=[],n=-1;for(let[r,a]of e.controlChildren.entries()){let e=a.stateValues.pointNumber;Number.isFinite(e)?n=Math.round(e)-1:n+=1,t[n]=r}return{setValue:{pointIndMap:t}}}},e.directions={isArray:!0,entryPrefixes:["direction"],hasEssential:!0,defaultValueByArrayKey:()=>"none",stateVariablesDeterminingDependencies:["pointIndMap"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"}}),returnArraySize:({dependencyValues:e})=>[e.nControls],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.pointIndMap[r];void 0!==e&&(n[r]={controlChild:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["direction"],childIndices:[e]}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=e[a].controlChild;t&&1===t.length?n[a]=t[0].stateValues.direction:r[a]=!0}return{setValue:{directions:n},useEssentialOrDefaultValue:{directions:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.directions){let o=n[i].controlChild;o&&1===o.length?r.push({setDependency:t[i].controlChild,desiredValue:e.directions[i],childIndex:0,variableIndex:0}):a[i]=e.directions[i]}return Object.keys(a).length>0&&r.push({setEssentialValue:"directions",value:a}),{success:!0,instructions:r}}},e.hiddenControls={isArray:!0,entryPrefixes:["hiddenControl"],hasEssential:!0,defaultValueByArrayKey:()=>!1,stateVariablesDeterminingDependencies:["pointIndMap"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"}}),returnArraySize:({dependencyValues:e})=>[e.nControls],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.pointIndMap[r];void 0!==e&&(n[r]={controlChild:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["hide"],childIndices:[e]}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=e[a].controlChild;t&&1===t.length?n[a]=t[0].stateValues.hide:r[a]=!0}return{setValue:{hiddenControls:n},useEssentialOrDefaultValue:{hiddenControls:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.hiddenControls){let o=n[i].controlChild;o&&1===o.length?r.push({setDependency:t[i].controlChild,desiredValue:e.hiddenControls[i],childIndex:0,variableIndex:0}):a[i]=e.hiddenControls[i]}return Object.keys(a).length>0&&r.push({setEssentialValue:"hiddenControls",value:a}),{success:!0,instructions:r}}},e.nDimensions={returnDependencies:()=>({nParentDimensions:{dependencyType:"parentStateVariable",variableName:"nDimensions"}}),definition:function({dependencyValues:e}){let t=e.nParentDimensions;return Number.isInteger(t)&&t>=0||(t=0),{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.essentialSymmetricControls={isArray:!0,entryPrefixes:["essentialSymmetricControl"],nDimensions:2,hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(1),returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nControls,e.nDimensions],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)n.split(",").map((e=>Number(e))),t[n]=!0;return{useEssentialOrDefaultValue:{essentialSymmetricControls:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[],n={};for(let t in e.essentialSymmetricControls)n[t]=e.essentialSymmetricControls[t];return Object.keys(n).length>0&&t.push({setEssentialValue:"essentialSymmetricControls",value:n}),{success:!0,instructions:t}}},e.controls={isArray:!0,entryPrefixes:["control"],nDimensions:3,hasEssential:!0,shadowVariable:!0,defaultValueByArrayKey:()=>me$3.fromAst(1),stateVariablesDeterminingDependencies:["pointIndMap","directions"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nControls,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=r.split(",").map((e=>Number(e))),a=e.map((e=>e+1));n[r]={direction:{dependencyType:"stateVariable",variableName:"direction"+a[0]}};let i=t.directions[e[0]];if("none"!==i&&(0===e[1]||1===e[1])){let o=t.pointIndMap[e[0]];void 0!==o&&("symmetric"===i||"previous"===i&&0===e[1]||"next"===i&&1===e[1]?n[r].controlChild={dependencyType:"child",childGroups:["controlVectors"],variableNames:["vectorX1_"+a[2]],childIndices:[o]}:"both"===i&&(n[r].controlChild={dependencyType:"child",childGroups:["controlVectors"],variableNames:["vectorX"+a[1]+"_"+a[2]],childIndices:[o]})),"symmetric"===i&&(n[r].essentialSymmetricControl={dependencyType:"stateVariable",variableName:"essentialSymmetricControl"+a[0]+"_"+a[2]})}}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,componentName:n}){let r={},a={};for(let n of t){let t=n.split(",").map((e=>Number(e))),i=t.map((e=>e+1)),o=e[n].direction;if(0===t[1])if("none"===o||"next"===o)r[n]=null;else{let t=e[n].controlChild,s=!0;if(t&&1===t.length){let e=t[0].stateValues["vectorX1_"+i[2]];e&&(s=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]=me$3.fromAst(e))}s&&("symmetric"===o?r[n]=e[n].essentialSymmetricControl:a[n]=!0)}else if(1===t[1])if("none"===o||"previous"===o)r[n]=null;else{let t=e[n].controlChild,s=!0;if(t&&1===t.length)if("both"===o){let e=t[0].stateValues["vectorX2_"+i[2]];e&&(s=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]=me$3.fromAst(e))}else{let e=t[0].stateValues["vectorX1_"+i[2]];e&&(s=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]="symmetric"===o?me$3.fromAst(-e):me$3.fromAst(e))}s&&("symmetric"===o?e[n].essentialSymmetricControl&&(r[n]=me$3.fromAst(-e[n].essentialSymmetricControl.tree)):a[n]=!0)}}return{setValue:{controls:r},useEssentialOrDefaultValue:{controls:a}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.controls){let o=i.split(",").map((e=>Number(e))),s=o.map((e=>e+1)),l=n[i].direction;if(l)if(0===o[1]){if("none"!==l&&"next"!==l){let o=n[i].controlChild,u=!0;if(o&&1===o.length){o[0].stateValues["vectorX1_"+s[2]]&&(u=!1,r.push({setDependency:t[i].controlChild,desiredValue:e.controls[i],childIndex:0,variableIndex:0}))}if(u){let n=e.controls[i].evaluate_to_constant();Number.isFinite(n)||(n=NaN),n=me$3.fromAst(n),"symmetric"===l?r.push({setDependency:t[i].essentialSymmetricControl,desiredValue:n}):a[i]=n}}}else if(1===o[1]&&"none"!==l&&"previous"!==l){let o,u=n[i].controlChild,c=!0;if(u&&1===u.length)if("both"===l){u[0].stateValues["vectorX2_"+s[2]]&&(c=!1)}else{u[0].stateValues["vectorX1_"+s[2]]&&(c=!1)}o="symmetric"===l?me$3.fromAst(["-",e.controls[i].tree]):e.controls[i],c?(o=o.evaluate_to_constant(),Number.isFinite(o)||(o=NaN),o=me$3.fromAst(o),"symmetric"===l?r.push({setDependency:t[i].essentialSymmetricControl,desiredValue:o}):a[i]=o):r.push({setDependency:t[i].controlChild,desiredValue:o,childIndex:0,variableIndex:0})}}return Object.keys(a).length>0&&r.push({setEssentialValue:"controls",value:a}),{success:!0,instructions:r}}},e}}class VectorListComponent extends BaseComponent{static componentType="_vectorListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"vector",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"vectors",componentTypes:["vector"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nVectors={returnDependencies:()=>({vectorChildren:{dependencyType:"child",childGroups:["vectors"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{nVectors:e.vectorChildren.length},checkForActualChange:{nVectors:!0}})},e.nDimensions={returnDependencies:()=>({vectorChildren:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"],skipPlaceholders:!0}}),definition:function({dependencyValues:e}){let t;if(0===e.vectorChildren.length)t=2;else{t=1;for(let n of e.vectorChildren)Number.isFinite(n.stateValues.nDimensions)&&(t=Math.max(t,n.stateValues.nDimensions))}return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.vectors={isArray:!0,nDimensions:2,entryPrefixes:["vectorX","vector"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vectors"===t)return 1===e.length?"vector"+e[0]:`vectorX${e[0]}_${e[1]}`;if("vector"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vectorX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nVectors:{dependencyType:"stateVariable",variableName:"nVectors"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nVectors,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]={vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+(Number(r)+1)],childIndices:[e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",")[1],a=e[r].vectorChild[0];a&&(n[r]=a.stateValues["x"+(Number(t)+1)])}return{setValue:{vectors:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.vectors)n.push({setDependency:t[r].vectorChild,desiredValue:e.vectors[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}class ControlVectors extends VectorListComponent{static componentType="controlVectors";static createAttributesObject(){let e=super.createAttributesObject();return e.direction={createComponentOfType:"text",createStateVariable:"direction",defaultValue:"symmetric",public:!0,toLowerCase:!0,validValues:["symmetric","previous","next","both","none"]},e.pointNumber={createComponentOfType:"number",createStateVariable:"pointNumber",defaultValue:null,public:!0},e}}class PointListComponent extends BaseComponent{static componentType="_pointListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"point",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPoints={returnDependencies:()=>({pointChildren:{dependencyType:"child",childGroups:["points"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nPoints:e.pointChildren.length},checkForActualChange:{nPoints:!0}}}},e.nDimensions={returnDependencies:()=>({pointChildren:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"],skipPlaceholders:!0}}),definition:function({dependencyValues:e}){let t;if(0===e.pointChildren.length)t=2;else{t=1;for(let n of e.pointChildren)Number.isFinite(n.stateValues.nDimensions)&&(t=Math.max(t,n.stateValues.nDimensions))}return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.points={isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("points"===t)return 1===e.length?"point"+e[0]:`pointX${e[0]}_${e[1]}`;if("point"===t.slice(0,5)){let n=Number(t.slice(5));if(Number.isInteger(n)&&n>0)return`pointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nPoints:{dependencyType:"stateVariable",variableName:"nPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nPoints,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]={pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+(Number(r)+1)],childIndices:[e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",")[1],a=e[r].pointChild[0];a&&(n[r]=a.stateValues["x"+(Number(t)+1)])}return{setValue:{points:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.points)n.push({setDependency:t[r].pointChild,desiredValue:e.points[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}class IntervalListComponent extends BaseComponent{static componentType="_intervalListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoIntervalPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"interval",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"intervals",componentTypes:["interval"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nIntervals={returnDependencies:()=>({intervalChildren:{dependencyType:"child",childGroups:["intervals"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nIntervals:e.intervalChildren.length},checkForActualChange:{nIntervals:!0}}}},e.intervals={isArray:!0,nDimensions:1,entryPrefixes:["interval"],returnArraySizeDependencies:()=>({nIntervals:{dependencyType:"stateVariable",variableName:"nIntervals"}}),returnArraySize:({dependencyValues:e})=>[e.nIntervals],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={intervalChild:{dependencyType:"child",childGroups:["intervals"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].intervalChild[0];t&&(n[r]=t.stateValues.value)}return{setValue:{intervals:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.intervals)n.push({setDependency:t[r].intervalChild,desiredValue:e.intervals[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}function breakEmbeddedStringsIntoIntervalPieces({componentList:e}){let t=0,n=[],r=[];for(let a of e){if("string"!=typeof a){if(0===t)return{success:!1};r.push(a);continue}let e=a.trim(),i=0;for(let a=0;ai){let t=a+1,n=e.substring(i,t).trim();n.length>0&&r.push(n)}n.push(r),r=[],i=a+1}t--}else if(0===t&&!o.match(/\s/))return{success:!1}}if(e.length>i){let t=e.substring(i,e.length).trim();r.push(t)}}return 0!==t||r.length>0?{success:!1}:{success:!0,pieces:n}}class LineListComponent extends BaseComponent{static componentType="_lineListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:"line",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"lines",componentTypes:["line"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nLines={returnDependencies:()=>({lineChildren:{dependencyType:"child",childGroups:["lines"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nLines:e.lineChildren.length},checkForActualChange:{nLines:!0}}}},e.lineNames={isArray:!0,entryPrefixes:["lineName"],returnArraySizeDependencies:()=>({nLines:{dependencyType:"stateVariable",variableName:"nLines"}}),returnArraySize:({dependencyValues:e})=>[e.nLines],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={lineChild:{dependencyType:"child",childGroups:["lines"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].lineChild[0];t&&(n[r]=t.componentName)}return{setValue:{lineNames:n}}}},e}}class AngleListComponent extends BaseComponent{static componentType="_angleListComponent";static createAttributesObject(){let e=super.createAttributesObject();return e.hide={default:!0},e}static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"AtLeastZeroAngles",componentType:"angle",comparison:"atLeast",number:0}),r=breakStringsAndOthersIntoComponentsByStringCommas(),a=t.newLeaf({name:"AtLeastOneString",componentType:"string",comparison:"atLeast",number:1}),i=t.newLeaf({name:"AtLeastOneMath",componentType:"math",comparison:"atLeast",number:1}),o=t.newOperator({name:"StringsAndMaths",operator:"or",propositions:[a,i],requireConsecutive:!0,isSugar:!0,replacementFunction:r});return t.newOperator({name:"AnglesXorSugar",operator:"xor",propositions:[n,o],setAsBase:!0}),t}updateState(e={}){if(e.init&&(this._state.angles={trackChanges:!0}),super.updateState(e),!this.childLogicSatisfied)return this.unresolvedState.angles=!0,void(this.unresolvedState.nAngles=!0);if(this.currentTracker.trackChanges.childrenChanged(this.componentName)){delete this.unresolvedState.angles,delete this.unresolvedState.nAngles;let e=this.childLogic.returnMatches("AtLeastZeroAngles");this.state.nAngles=e.length,this.state.angles=e.map((e=>this.activeChildren[e]))}}initializeRenderer(){void 0===this.renderer&&(this.renderer=new this.availableRenderers.container({key:this.componentName}))}updateChildrenWhoRender(){this.childrenWhoRender=this.state.angles.map((e=>e.componentName))}}class Vector extends GraphicalComponent{static componentType="vector";actions={moveVector:this.moveVector.bind(this),vectorClicked:this.vectorClicked.bind(this)};static primaryStateVariableForDefinition="displacementShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.headDraggable={createComponentOfType:"boolean"},e.tailDraggable={createComponentOfType:"boolean"},e.x={createComponentOfType:"math"},e.y={createComponentOfType:"math"},e.z={createComponentOfType:"math"},e.xs={createComponentOfType:"mathList"},e.displacement={createComponentOfType:"vector"},e.head={createComponentOfType:"point"},e.tail={createComponentOfType:"point"},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),r=e.map((e=>typeof e)),a=r.indexOf("string"),i=r.lastIndexOf("string");if(-1===a){let n=t.componentIsSpecifiedType,r=e.filter((e=>!(n(e,"point")||n(e,"vector")||n(e,"label"))));if(1===r.length){let t=r[0],n=e.indexOf(t);return{success:!0,newAttributes:{displacement:{component:{componentType:"math",children:r}}},newChildren:[...e.slice(0,n),...e.slice(n+1)]}}return{success:!1}}let o=[...e.slice(0,a),...e.slice(i+1)],s=n({matchedChildren:e=e.slice(a,i+1)});return s.success||1!==e.length?s.success?{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:s.newChildren,skipSugar:!0}}},newChildren:o}:{success:!1}:{success:!0,newAttributes:{x:{component:{componentType:"math",children:e}}},newChildren:o}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"points",componentTypes:["point"]},{group:"vectors",componentTypes:["vector"]}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" vector"}}}},e.tailDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({tailDraggableAttr:{dependencyType:"attributeComponent",attributeName:"tailDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.tailDraggableAttr?{setValue:{tailDraggable:e.tailDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{tailDraggable:{defaultValue:e.draggable}}}},e.headDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({headDraggableAttr:{dependencyType:"attributeComponent",attributeName:"headDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.headDraggableAttr?{setValue:{headDraggable:e.headDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{headDraggable:{defaultValue:e.draggable}}}},e.displacementShadow={defaultValue:null,hasEssential:!0,essentialVarName:"displacement",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{displacementShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"displacementShadow",value:convertValueToMathExpression(e.displacementShadow)}]}}},e.headShadow={defaultValue:null,hasEssential:!0,essentialVarName:"head",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{headShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"headShadow",value:convertValueToMathExpression(e.headShadow)}]}}},e.tailShadow={defaultValue:null,hasEssential:!0,essentialVarName:"tail",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{tailShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"tailShadow",value:convertValueToMathExpression(e.tailShadow)}]}}},e.sourceOfDisplacement={returnDependencies:()=>({xAttr:{dependencyType:"attributeComponent",attributeName:"x"},yAttr:{dependencyType:"attributeComponent",attributeName:"y"},zAttr:{dependencyType:"attributeComponent",attributeName:"z"},xsAttr:{dependencyType:"attributeComponent",attributeName:"xs"},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement"},pointChild:{dependencyType:"child",childGroups:["points"]},vectorChild:{dependencyType:"child",childGroups:["vectors"]}}),definition({dependencyValues:e}){let t=null;return e.vectorChild.length>0?t="vectorChild":e.pointChild.length>0?t="pointChild":null!==e.displacementAttr?t="displacementAttr":null!==e.xsAttr?t="xsAttr":null===e.xAttr&&null===e.yAttr&&null===e.zAttr||(t="componentAttrs"),{setValue:{sourceOfDisplacement:t}}}},e.basedOnHead={returnDependencies:()=>({headAttr:{dependencyType:"attributeComponent",attributeName:"head"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"},tailAttr:{dependencyType:"attributeComponent",attributeName:"tail"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"}}),definition:function({dependencyValues:e}){return null!==e.tailAttr&&null!==e.sourceOfDisplacement?(null!==e.headAttr&&console.warn("Vector is prescribed by head, tail, and displacement. Ignoring specified head."),{setValue:{basedOnHead:!1},checkForActualChange:{basedOnHead:!0}}):null!==e.headAttr?{setValue:{basedOnHead:!0},checkForActualChange:{basedOnHead:!0}}:{setValue:{basedOnHead:null!==e.headShadow},checkForActualChange:{basedOnHead:!0}}}},e.basedOnTail={returnDependencies:()=>({tailAttr:{dependencyType:"attributeComponent",attributeName:"tail"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"}}),definition:function({dependencyValues:e}){return null!==e.tailAttr?{setValue:{basedOnTail:!0},checkForActualChange:{basedOnTail:!0}}:{setValue:{basedOnTail:null!==e.tailShadow},checkForActualChange:{basedOnTail:!0}}}},e.basedOnDisplacement={returnDependencies:()=>({sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"}}),definition:function({dependencyValues:e}){return null!==e.sourceOfDisplacement?{setValue:{basedOnDisplacement:!0},checkForActualChange:{basedOnDisplacement:!0}}:{setValue:{basedOnDisplacement:null!==e.displacementShadow},checkForActualChange:{basedOnDisplacement:!0}}}},e.nDimDisplacement={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement",variableNames:["nDimensions"]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"]},xAttr:{dependencyType:"attributeComponent",attributeName:"x"},yAttr:{dependencyType:"attributeComponent",attributeName:"y"},zAttr:{dependencyType:"attributeComponent",attributeName:"z"},xsAttr:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["nComponents"]}};return e.basedOnDisplacement||(e.basedOnHead&&(t.nDimHead={dependencyType:"stateVariable",variableName:"nDimHead"}),e.basedOnTail&&(t.nDimTail={dependencyType:"stateVariable",variableName:"nDimTail"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnDisplacement)switch(e.sourceOfDisplacement){case"vectorChild":t=e.vectorChild[0].stateValues.nDimensions;break;case"pointChild":t=e.pointChild[0].stateValues.nDimensions;break;case"displacementAttr":t=e.displacementAttr.stateValues.nDimensions;break;case"xsAttr":t=e.xsAttr.stateValues.nComponents;break;case"componentAttrs":t=null!==e.zAttr?3:null!==e.yAttr?2:1;break;default:let n=e.displacementShadow.tree;t=Array.isArray(n)&&["tuple","vector"].includes(n[0])?n.length-1:1}else t=e.basedOnHead?e.basedOnTail?e.nDimHead===e.nDimTail?e.nDimHead:NaN:e.nDimHead:e.basedOnTail?e.nDimTail:2;return{setValue:{nDimDisplacement:t},checkForActualChange:{nDimDisplacement:!0}}}},e.nDimHead={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"},headAttr:{dependencyType:"attributeComponent",attributeName:"head",variableNames:["nDimensions"]}};return e.basedOnHead||(e.basedOnTail&&(t.nDimTail={dependencyType:"stateVariable",variableName:"nDimTail"}),e.basedOnDisplacement&&(t.nDimDisplacement={dependencyType:"stateVariable",variableName:"nDimDisplacement"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnHead){if(null!==e.headAttr)t=e.headAttr.stateValues.nDimensions;else if(e.headShadow){let n=e.headShadow.tree;t=Array.isArray(n)&&["tuple","vector"].includes(n[0])?n.length-1:2}}else t=e.basedOnDisplacement?e.basedOnTail?e.nDimDisplacement===e.nDimTail?e.nDimDisplacement:NaN:e.nDimDisplacement:e.basedOnTail?e.nDimTail:2;return{setValue:{nDimHead:t},checkForActualChange:{nDimHead:!0}}}},e.nDimTail={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"},tailAttr:{dependencyType:"attributeComponent",attributeName:"tail",variableNames:["nDimensions"]}};return e.basedOnTail||(e.basedOnHead&&(t.nDimHead={dependencyType:"stateVariable",variableName:"nDimHead"}),e.basedOnDisplacement&&(t.nDimDisplacement={dependencyType:"stateVariable",variableName:"nDimDisplacement"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnTail){if(null!==e.tailAttr)t=e.tailAttr.stateValues.nDimensions;else if(e.tailShadow){let n=e.tailShadow.tree;t=Array.isArray(n)&&["tuple","vector"].includes(n[0])?n.length-1:2}}else t=e.basedOnDisplacement?e.basedOnHead?e.nDimDisplacement===e.nDimHead?e.nDimDisplacement:NaN:e.nDimDisplacement:e.basedOnHead?e.nDimHead:2;return{setValue:{nDimTail:t},checkForActualChange:{nDimTail:!0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},nDimDisplacement:{dependencyType:"stateVariable",variableName:"nDimDisplacement"},nDimHead:{dependencyType:"stateVariable",variableName:"nDimHead"},nDimTail:{dependencyType:"stateVariable",variableName:"nDimTail"}}),definition:function({dependencyValues:e}){let t;if(e.basedOnDisplacement){if(e.basedOnTail){if(e.nDimDisplacement!==e.nDimTail)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}}}else if(e.basedOnHead&&e.nDimDisplacement!==e.nDimHead)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimDisplacement}else if(e.basedOnTail){if(e.basedOnHead&&e.nDimTail!==e.nDimHead)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimTail}else t=e.basedOnHead?e.nDimHead:2;return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.displacement={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"x"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["x"],hasEssential:!0,essentialVarName:"displacement2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","sourceOfDisplacement"],returnArraySizeDependencies:()=>({nDimDisplacement:{dependencyType:"stateVariable",variableName:"nDimDisplacement"}}),returnArraySize:({dependencyValues:e})=>[e.nDimDisplacement],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={xsAttr:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["math"+e]},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement",variableNames:["x"+e]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+e]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+e]}},"0"===r?n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"x",variableNames:["value"]}:"1"===r?n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"y",variableNames:["value"]}:"2"===r&&(n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"z",variableNames:["value"]}),!t.basedOnDisplacement&&t.basedOnHead&&(n[r].tailX={dependencyType:"stateVariable",variableName:"tailX"+e},n[r].headX={dependencyType:"stateVariable",variableName:"headX"+e})}return{globalDependencies:{basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;if(e.basedOnDisplacement)switch(e.sourceOfDisplacement){case"vectorChild":r[i]=t[i].vectorChild[0].stateValues["x"+n];break;case"pointChild":r[i]=t[i].pointChild[0].stateValues["x"+n];break;case"displacementAttr":r[i]=t[i].displacementAttr.stateValues["x"+n];break;case"xsAttr":r[i]=t[i].xsAttr.stateValues["math"+n].simplify();break;case"componentAttrs":let o=t[i].componentAttr;null===o?a[i]={defaultValue:me$3.fromAst(0)}:r[i]=o.stateValues.value.simplify();break;default:let s=e.displacementShadow.tree;Array.isArray(s)&&["tuple","vector"].includes(s[0])?r[i]=e.displacementShadow.get_component(Number(i)):r[i]=e.displacementShadow}else e.basedOnHead?r[i]=t[i].headX.subtract(t[i].tailX).simplify():a[i]={defaultValue:me$3.fromAst("0"===i?1:0)}}let i={};return Object.keys(r).length>0&&(i.setValue={displacement:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={displacement:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],o=!1;for(let a in e.displacement)if(t.basedOnDisplacement)switch(t.sourceOfDisplacement){case"vectorChild":i.push({setDependency:r[a].vectorChild,desiredValue:e.displacement[a],childIndex:0,variableIndex:0});break;case"pointChild":i.push({setDependency:r[a].pointChild,desiredValue:e.displacement[a],childIndex:0,variableIndex:0});break;case"displacementAttr":i.push({setDependency:r[a].displacementAttr,desiredValue:e.displacement[a],variableIndex:0});break;case"xsAttr":i.push({setDependency:r[a].xsAttr,desiredValue:e.displacement[a],variableIndex:0});break;case"componentAttrs":null===n[a].componentAttr?i.push({setEssentialValue:"displacement",value:{[a]:convertValueToMathExpression(e.displacement[a])}}):i.push({setDependency:r[a].componentAttr,desiredValue:e.displacement[a],variableIndex:0});break;default:o=!0}else t.basedOnHead?i.push({setDependency:r[a].headX,desiredValue:n[a].tailX.add(e.displacement[a]).simplify()}):i.push({setEssentialValue:"displacement",value:{[a]:convertValueToMathExpression(e.displacement[a])}});if(o)if(a[0]>1){let t=["vector"];for(let n in e.displacement)t[Number(n)+1]=e.displacement[n].tree;t.length=a[0]+1,i.push({setDependency:"displacementShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.displacement&&i.push({setDependency:"displacementShadow",desiredValue:e.displacement[0]});return{success:!0,instructions:i}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.head={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"headX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["headX"],set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnHead"],returnArraySizeDependencies:()=>({nDimHead:{dependencyType:"stateVariable",variableName:"nDimHead"}}),returnArraySize:({dependencyValues:e})=>[e.nDimHead],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={headAttr:{dependencyType:"attributeComponent",attributeName:"head",variableNames:["x"+e]}},t.basedOnHead||(n[r].tailX={dependencyType:"stateVariable",variableName:"tailX"+e},n[r].x={dependencyType:"stateVariable",variableName:"x"+e})}return{globalDependencies:{basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=Number(a)+1;e.basedOnHead?null!==t[a].headAttr?r[a]=t[a].headAttr.stateValues["x"+n]:null!==e.headShadow&&(r[a]=e.headShadow.get_component(Number(a))):r[a]=t[a].tailX.add(t[a].x).simplify()}return{setValue:{head:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],o=!1;for(let a in e.head)t.basedOnHead?n[a].headAttr&&null!==n[a].headAttr?i.push({setDependency:r[a].headAttr,desiredValue:e.head[a],variableIndex:0}):null!==t.headShadow&&(o=!0):i.push({setDependency:r[a].x,desiredValue:e.head[a].subtract(n[a].tailX).simplify()});if(o)if(a[0]>1){let t=["vector"];for(let n in e.head)t[Number(n)+1]=e.head[n].tree;t.length=a[0]+1,i.push({setDependency:"headShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.head&&i.push({setDependency:"headShadow",desiredValue:e.head[0]});return{success:!0,instructions:i}}},e.tail={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"tailX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["tailX"],hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(0),essentialVarName:"tail2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnTail","basedOnHead","basedOnDisplacement"],returnArraySizeDependencies:()=>({nDimTail:{dependencyType:"stateVariable",variableName:"nDimTail"}}),returnArraySize:({dependencyValues:e})=>[e.nDimTail],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={tailAttr:{dependencyType:"attributeComponent",attributeName:"tail",variableNames:["x"+e]}},t.basedOnTail||t.basedOnHead&&t.basedOnDisplacement&&(n[r].headX={dependencyType:"stateVariable",variableName:"headX"+e},n[r].x={dependencyType:"stateVariable",variableName:"x"+e})}return{globalDependencies:{basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;null!==t[i].tailAttr?r[i]=t[i].tailAttr.stateValues["x"+n]:null!==e.tailShadow?r[i]=e.tailShadow.get_component(Number(i)):e.basedOnHead&&e.basedOnDisplacement?r[i]=t[i].headX.subtract(t[i].x).simplify():a[i]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={tail:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={tail:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],o=!1;for(let a in e.tail)n[a].tailAttr&&null!==n[a].tailAttr?i.push({setDependency:r[a].tailAttr,desiredValue:e.tail[a],variableIndex:0}):null!==t.tailShadow?o=!0:t.basedOnHead&&t.basedOnDisplacement?i.push({setDependency:r[a].x,desiredValue:n[a].headX.subtract(e.tail[a]).simplify()}):i.push({setEssentialValue:"tail",value:{[a]:convertValueToMathExpression(e.tail[a])}});if(o)if(a[0]>1){let t=["vector"];for(let n in e.tail)t[Number(n)+1]=e.tail[n].tree;t.length=a[0]+1,i.push({setDependency:"tailShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.tail&&i.push({setDependency:"tailShadow",desiredValue:e.tail[0]});return{success:!0,instructions:i}}},e.numericalEndpoints={forRenderer:!0,returnDependencies:()=>({head:{dependencyType:"stateVariable",variableName:"head"},tail:{dependencyType:"stateVariable",variableName:"tail"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition:function({dependencyValues:e}){let t,n;if(1===e.nDimensions)e.head[0].evaluate_to_constant(),n=e.tail[0].evaluate_to_constant(),Number.isFinite(n)||(n=NaN);else{t=[],n=[];for(let r=0;r({displacement:{dependencyType:"stateVariable",variableName:"displacement"}}),definition({dependencyValues:e}){let t=[];for(let n of e.displacement)n?t.push(n.tree):t.push("_");return t=t.length>1?["vector",...t]:1===t.length?t[0]:"_",{setValue:{displacementCoords:me$3.fromAst(t)}}},inverseDefinition({desiredStateVariableValues:e}){let t,n=e.displacementCoords.tree;return t=!Array.isArray(n)||"vector"!==n[0]&&"tuple"!==n[0]?[e.displacementCoords]:n.slice(1).map((e=>me$3.fromAst(e))),{success:!0,instructions:[{setDependency:"displacement",desiredValue:t}]}}},e.latex={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({displacementCoords:{dependencyType:"stateVariable",variableName:"displacementCoords"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.displacementCoords,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"}}),definition({dependencyValues:e}){let t=e.numericalEndpoints[0]?.[0],n=e.numericalEndpoints[0]?.[1],r=e.numericalEndpoints[1]?.[0],a=e.numericalEndpoints[1]?.[1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),o=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(o)return{};let s=i[0],l=i[1],u=(r-t)/s,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/s*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:d>=1?{x1:r,x2:a}:{x1:t+d*u*s,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e}static adapters=[{stateVariable:"displacementCoords",componentType:"coords",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async moveVector({tailcoords:e,headcoords:t,transient:n,skippable:r,sourceInformation:a,actionId:i}){if(void 0!==e){if(void 0!==t){if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:i})}else if(!await this.stateValues.tailDraggable)return await this.coreFunctions.resolveAction({actionId:i})}else if(!await this.stateValues.headDraggable)return await this.coreFunctions.resolveAction({actionId:i});let o=[];if(void 0!==e){if(await this.stateValues.basedOnHead&&await this.stateValues.basedOnDisplacement){let n;if(void 0===t){let t=await this.stateValues.numericalEndpoints;n=e.map(((e,n)=>t[1][n]-e))}else n=e.map(((e,n)=>t[n]-e));o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}else o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"tail",value:e.map((e=>me$3.fromAst(e))),sourceInformation:a});if(void 0===t&&!await this.stateValues.basedOnHead){let t=await this.stateValues.numericalEndpoints,n=e.map(((e,n)=>t[1][n]-e));o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}if(void 0!==t){if(await this.stateValues.basedOnHead)o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"head",value:t.map((e=>me$3.fromAst(e))),sourceInformation:a});else{null==e&&(e=(await this.stateValues.numericalEndpoints)[0]);let n=e.map(((e,n)=>t[n]-e));o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}if(void 0===e&&await this.stateValues.basedOnHead&&await this.stateValues.basedOnDisplacement){let e=await this.stateValues.numericalEndpoints,n=t.map(((t,n)=>t-e[0][n]));o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}return n?await this.coreFunctions.performUpdate({updateInstructions:o,transient:n,skippable:r,actionId:i}):await this.coreFunctions.performUpdate({updateInstructions:o,actionId:i,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{head:t,tail:e}}})}async vectorClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Angle extends GraphicalComponent{static componentType="angle";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.radius={createComponentOfType:"math",createStateVariable:"radius",defaultValue:me$3.fromAst(1),public:!0},e.chooseReflexAngle={createComponentOfType:"text",createStateVariable:"chooseReflexAngle",defaultValue:"never",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["never","allowed","always"]},e.inDegrees={createComponentOfType:"boolean",createStateVariable:"inDegrees",defaultValue:!1,public:!0,forRenderer:!0},e.radians={createComponentOfType:"math"},e.degrees={createComponentOfType:"math"},e.through={createComponentOfType:"_pointListComponent"},e.betweenLines={createComponentOfType:"_lineListComponent"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a.push(...e.slice(0,t)),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),a.push(...e.slice(t)))}return 0===r.length?{success:!1}:{success:!0,newAttributes:{radians:{component:{componentType:"math",children:r}}},newChildren:a}}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({betweenLines:{dependencyType:"attributeComponent",attributeName:"betweenLines"}}),definition({dependencyValues:e}){let t=null;return null!==e.betweenLines&&(t=e.betweenLines.componentName),{setValue:{betweenLinesName:t}}}},e.nPointsSpecified={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:({dependencyValues:e})=>null!==e.through?{setValue:{nPointsSpecified:e.through.stateValues.nPoints}}:{setValue:{nPointsSpecified:0}}},e.points={isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],stateVariablesDeterminingDependencies:["betweenLinesName"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[3,2],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},returnArrayDependenciesByKey({stateValues:e}){let t={nPointsSpecified:{dependencyType:"stateVariable",variableName:"nPointsSpecified"},throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["points"]},radiansAttr:{dependencyType:"attributeComponent",attributeName:"radians",variableNames:["value"]},degreesAttr:{dependencyType:"attributeComponent",attributeName:"degrees",variableNames:["value"]}};return null!==e.betweenLinesName&&(t.lineChildren={dependencyType:"child",parentName:e.betweenLinesName,childGroups:["lines"],variableNames:["points","nDimensions","coeff0","coeffvar1","coeffvar2","nearestPoint"]}),{globalDependencies:t}},arrayDefinitionByKey({globalDependencyValues:e}){if(e.lineChildren){if(e.lineChildren.length>2){console.warn(`Cannot define an angle between ${e.lineChildren.length} line(s)`);let t={};for(let e=0;e<3;e++)for(let n=0;n<2;n++)t[e+","+n]=me$3.fromAst("_");return{setValue:{points:t}}}if(1===e.lineChildren.length){let t=e.lineChildren[0];if(2!==t.stateValues.nDimensions){let e={};for(let t=0;t<3;t++)for(let n=0;n<2;n++)e[t+","+n]=me$3.fromAst("_");return{setValue:{points:e}}}let n=t.stateValues.nearestPoint({variables:{x1:me$3.fromAst(0),x2:me$3.fromAst(0)}}),r=t.stateValues.points[0][0].evaluate_to_constant(),a=t.stateValues.points[0][1].evaluate_to_constant(),i=t.stateValues.points[1][0].evaluate_to_constant(),o=t.stateValues.points[1][1].evaluate_to_constant(),s=Math.atan2(o-a,i-r),l={"0,0":me$3.fromAst(n.x1+Math.cos(s)),"0,1":me$3.fromAst(n.x2+Math.sin(s)),"1,0":me$3.fromAst(n.x1),"1,1":me$3.fromAst(n.x2)},u=null;if(e.radiansAttr){if(u=e.radiansAttr.stateValues.value.evaluate_to_constant(),!Number.isFinite(u)){let e={};return e["2,0"]=me$3.fromAst("_"),e["2,1"]=me$3.fromAst("_"),{setValue:{points:e}}}}else if(e.degreesAttr){let t=e.degreesAttr.stateValues.value.evaluate_to_constant();if(!Number.isFinite(t))return l["2,0"]=me$3.fromAst("_"),l["2,1"]=me$3.fromAst("_"),{setValue:{points:l}};u=t/180*Math.PI}else u=Math.PI/2;let c=s+u;return l["2,0"]=me$3.fromAst(n.x1+Math.cos(c)),l["2,1"]=me$3.fromAst(n.x2+Math.sin(c)),{setValue:{points:l}}}{let t=e.lineChildren[0],n=e.lineChildren[1],r=calculateLineIntersection(t,n);if(void 0===r){let e={};for(let t=0;t<3;t++)for(let n=0;n<2;n++)e[t+","+n]=me$3.fromAst("_");return{setValue:{points:e}}}let a=r,i=t.stateValues.points[0][0].evaluate_to_constant(),o=t.stateValues.points[0][1].evaluate_to_constant(),s=t.stateValues.points[1][0].evaluate_to_constant(),l=t.stateValues.points[1][1].evaluate_to_constant(),u=[me$3.fromAst(a[0].tree+s-i),me$3.fromAst(a[1].tree+l-o)];i=n.stateValues.points[0][0].evaluate_to_constant(),o=n.stateValues.points[0][1].evaluate_to_constant(),s=n.stateValues.points[1][0].evaluate_to_constant(),l=n.stateValues.points[1][1].evaluate_to_constant();let c=[me$3.fromAst(a[0].tree+s-i),me$3.fromAst(a[1].tree+l-o)];return{setValue:{points:{"0,0":u[0],"0,1":u[1],"1,0":a[0],"1,1":a[1],"2,0":c[0],"2,1":c[1]}}}}}let t,n=e.nPointsSpecified;t=e.throughAttr?e.throughAttr.stateValues.points:[];let r={};for(let[e,n]of t.entries())r[e+",0"]=n[0],r[e+",1"]=n[1];if(0===n&&(r["0,0"]=me$3.fromAst(1),r["0,1"]=me$3.fromAst(0)),n<2&&(r["1,0"]=me$3.fromAst(0),r["1,1"]=me$3.fromAst(0)),n<3){let t=null;if(e.radiansAttr){if(t=e.radiansAttr.stateValues.value.evaluate_to_constant(),!Number.isFinite(t))return r["2,0"]=me$3.fromAst("_"),r["2,1"]=me$3.fromAst("_"),{setValue:{points:r}}}else if(e.degreesAttr){let n=e.degreesAttr.stateValues.value.evaluate_to_constant();if(!Number.isFinite(n))return r["2,0"]=me$3.fromAst("_"),r["2,1"]=me$3.fromAst("_"),{setValue:{points:r}};t=n/180*Math.PI}else t=Math.PI/2;let n=r["0,0"].evaluate_to_constant(),a=r["0,1"].evaluate_to_constant(),i=r["1,0"].evaluate_to_constant(),o=r["1,1"].evaluate_to_constant(),s=Math.atan2(a-o,n-i)+t;r["2,0"]=me$3.fromAst(i+Math.cos(s)),r["2,1"]=me$3.fromAst(o+Math.sin(s))}return{setValue:{points:r}}}},e.radians={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},additionalStateVariablesDefined:[{variableName:"swapPointOrder",forRenderer:!0}],returnDependencies:()=>({radians:{dependencyType:"attributeComponent",attributeName:"radians",variableNames:["value"]},degrees:{dependencyType:"attributeComponent",attributeName:"degrees",variableNames:["value"]},points:{dependencyType:"stateVariable",variableName:"points"},chooseReflexAngle:{dependencyType:"stateVariable",variableName:"chooseReflexAngle"}}),definition({dependencyValues:e}){let t=!1;if(null!==e.radians)return{setValue:{radians:e.radians.stateValues.value.simplify(),swapPointOrder:t}};if(null!==e.degrees)return{setValue:{radians:e.degrees.stateValues.value.divide(me$3.fromAst(180)).simplify().multiply(me$3.fromAst("pi")).simplify(),swapPointOrder:t}};let n,r=[],a=!1;for(let t=0;t<3;t++)r.push([e.points[t][0].evaluate_to_constant(),e.points[t][1].evaluate_to_constant()]),null!==r[t][0]&&null!==r[t][1]||(a=!0);return a?{setValue:{radians:me$3.fromAst("_"),swapPointOrder:t}}:(n=Math.atan2(r[2][1]-r[1][1],r[2][0]-r[1][0])-Math.atan2(r[0][1]-r[1][1],r[0][0]-r[1][0]),n<0&&(n+=2*Math.PI),n>Math.PI?"never"===e.chooseReflexAngle&&(n=2*Math.PI-n,t=!0):"always"===e.chooseReflexAngle&&(n=2*Math.PI-n,t=!0),{setValue:{radians:me$3.fromAst(n),swapPointOrder:t}})}},e.value={isAlias:!0,targetVariableName:"radians"},e.angle={isAlias:!0,targetVariableName:"radians"},e.degrees={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({radians:{dependencyType:"stateVariable",variableName:"radians"}}),definition({dependencyValues:e}){let t;if("_"===e.radians.tree||Number.isNaN(e.radians.tree))t=e.radians;else{let n=e.radians.evaluate_to_constant();t=Number.isFinite(n)?me$3.fromAst(180*n/Math.PI):e.radians.multiply(me$3.fromAst(["/",180,"pi"])).simplify()}return{setValue:{degrees:t}}}},e.latexForRenderer={forRenderer:!0,returnDependencies:()=>({inDegrees:{dependencyType:"stateVariable",variableName:"inDegrees"},radians:{dependencyType:"stateVariable",variableName:"radians"},degrees:{dependencyType:"stateVariable",variableName:"degrees"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits));let r=roundForDisplay({value:e.inDegrees?e.degrees:e.radians,dependencyValues:e,usedDefault:t}).toLatex(n);return e.inDegrees&&(r+="^\\circ"),{setValue:{latexForRenderer:r}}}},e.numericalPoints={isArray:!0,entryPrefixes:["numericalPoint"],forRenderer:!0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[3],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={point:{dependencyType:"stateVariable",variableName:"point"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].point,a=[];for(let e=0;e<2;e++){let n=t[e].evaluate_to_constant();Number.isFinite(n)||(n=NaN),a.push(n)}n[r]=a}return{setValue:{numericalPoints:n}}}},e.numericalRadius={forRenderer:!0,returnDependencies:()=>({radius:{dependencyType:"stateVariable",variableName:"radius"}}),definition({dependencyValues:e}){let t=e.radius.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),{setValue:{numericalRadius:t}}}},e}static adapters=["radians"]}function calculateLineIntersection(e,t){if(2!==e.stateValues.nDimensions||2!==t.stateValues.nDimensions)return void console.log("Calculating angle between two lines implemented only in 2D");let n=e.stateValues.coeffvar1.evaluate_to_constant(),r=e.stateValues.coeffvar2.evaluate_to_constant(),a=e.stateValues.coeff0.evaluate_to_constant(),i=t.stateValues.coeffvar1.evaluate_to_constant(),o=t.stateValues.coeffvar2.evaluate_to_constant(),s=t.stateValues.coeff0.evaluate_to_constant();if(!(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a)&&Number.isFinite(i)&&Number.isFinite(o)&&Number.isFinite(s)))return void console.log("Calculating angle between two lines implemented only for constant coefficients");let l=n*o-i*r;if(Math.abs(l)<1e-14)return Math.abs(s*n-a*i)>1e-14?void console.log("Cannot calculate angle between two parallel lines"):0===n&&0===r&&0===a||0===i&&0===o&&0===s?void 0:0!==r?[me$3.fromAst(0),me$3.fromAst(-a/r)]:[me$3.fromAst(-a/n),me$3.fromAst(0)];let u=(s*r-a*o)/l,c=(a*i-s*n)/l;return[me$3.fromAst(u),me$3.fromAst(c)]}var defaults$5={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify},util$1={isArray:Array.isArray,assign:Object.assign,isObject:e=>"object"==typeof e,isFunction:e=>"function"==typeof e,isBoolean:e=>"boolean"==typeof e,isRegex:e=>e instanceof RegExp,keys:Object.keys};const DEFAULTS=defaults$5,isFunction$2=util$1.isFunction,isBoolean$1=util$1.isBoolean,isObject$p=util$1.isObject,isArray$9=util$1.isArray,isRegex=util$1.isRegex,assign$2=util$1.assign,keys$4=util$1.keys;function serialize(e){return null==e?e:isRegex(e)?e.toString():e.toJSON?e.toJSON():e}function stringifyDeterministic(e,t){t=t||assign$2({},DEFAULTS),isFunction$2(t)&&(t={compare:t});const n=t.space||DEFAULTS.space,r=isBoolean$1(t.cycles)?t.cycles:DEFAULTS.cycles,a=t.replacer||DEFAULTS.replacer,i=t.stringify||DEFAULTS.stringify,o=t.compare&&function(e){return function(t){return function(n,r){const a={key:n,value:t[n]},i={key:r,value:t[r]};return e(a,i)}}}(t.compare);r||i(e);const s=[];return function e(t,l,u,c){const p=n?"\n"+new Array(c+1).join(n):"",d=n?": ":":";if(u=serialize(u),void 0!==(u=a.call(t,l,u))){if(!isObject$p(u)||null===u)return i(u);if(isArray$9(u)){const t=[];for(let r=0;r0)for(let e of t.children)"object"!=typeof e?e.trim()&&(p=!0):i(e,"when")||(i(e,"math")||i(e,"number")||i(e,"mathList")||i(e,"numberList")?(o=!0,p=!0):i(e,"text")||i(e,"textList")?(s=!0,p=!0):i(e,"boolean")?(l=!0,p=!0):i(e,"booleanList")?l=!0:n.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"})&&!e.attributes?.createComponentOfType?.primitive?p=!0:i(e,"orbitalDiagram")||(p=!0));else p=!0;else i(t,"mathInput")?(m.push(!1),o=!0,c=!0):i(t,"textInput")?(m.push(!1),s=!0,c=!0):i(t,"_input")||i(t,"considerAsResponses")?(m.push(!1),c=!0):(n.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:"_composite"})&&t.attributes?.createComponentOfType?.primitive,m.push(!0),p=!0);if(c&&(d=!0),u>0){if(e=e.filter((e=>"string"!=typeof e||""!==e.trim())),e.length!==u)return{success:!1};{let n={componentType:"choiceInput",children:e};return t.shuffleOrder&&(n.attributes={shuffleOrder:{primitive:!0}}),{success:!0,newChildren:[n]}}}if(!p&&!d){for(let t of e)if(i(t,"award")&&t.children?.length>0&&r(t.children)){d=!0;break}if(!d)for(let t of e)i(t,"award")&&t.children?.length>0&&a(t.children)}let f=[],h=[],y=[];if(0===m.filter((e=>!e)).length)f=e;else{if(!m[0]){let t=m.indexOf(!0);-1!==t&&(h=e.slice(0,t),e=e.slice(t),m=m.slice(t))}let t=m.indexOf(!1);-1===t?f=e:(f=e.slice(0,t),y=e.slice(t))}for(;"string"==typeof f[0]&&""===f[0].trim();)f=f.slice(1);let b,g,v=f.length;for(;"string"==typeof f[v-1]&&""===f[v-1].trim();)f=f.slice(0,v-1),v=f.length;if(t.type?(g=t.type,["math","text","boolean"].includes(g)||(console.warn(`Invalid type ${g}`),g="math")):g=o?"math":s?"text":l?"boolean":"math",0===f.length)b=[...h,...y];else{let e;e=f.length>1||n.isInheritedComponentType({inheritedComponentType:f[0].componentType,baseComponentType:"_composite"})&&!f[0].props?.componentType?[{componentType:g,children:f}]:f,b=[...h,{componentType:"award",children:e},...y]}if(p&&!c){b=[{componentType:g+"Input"},...b]}return{success:!0,newChildren:b}}}),e}static returnChildGroups(){return[{group:"awards",componentTypes:["award"]},{group:"inputs",componentTypes:["_input"]},{group:"responses",componentTypes:["considerAsResponses"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"disabled",newName:"disabledOriginal"}),e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessPreliminary:{dependencyType:"stateVariable",variableName:"showCorrectnessPreliminary"},showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition({dependencyValues:e,usedDefault:t}){let n;return n=t.showCorrectnessPreliminary?!1!==e.showCorrectnessFlag:e.showCorrectnessPreliminary,{setValue:{showCorrectness:n}}}},e.haveAwardThatRequiresInput={returnDependencies:()=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["requireInputInAnswer"]}}),definition:({dependencyValues:e})=>({setValue:{haveAwardThatRequiresInput:e.awardChildren.some((e=>e.stateValues.requireInputInAnswer))}})},e.allInputChildrenIncludingSugared={returnDependencies:()=>({allInputChildrenIncludingSugared:{dependencyType:"child",childGroups:["inputs"]}}),definition:({dependencyValues:e})=>({setValue:{allInputChildrenIncludingSugared:e.allInputChildrenIncludingSugared}})},e.inputChildren={stateVariablesDeterminingDependencies:["allInputChildrenIncludingSugared"],additionalStateVariablesDefined:["inputChildIndices","skippedFirstInput"],forRenderer:!0,returnDependencies({stateValues:e}){let t={allInputChildrenIncludingSugared:{dependencyType:"stateVariable",variableName:"allInputChildrenIncludingSugared"},haveAwardThatRequiresInput:{dependencyType:"stateVariable",variableName:"haveAwardThatRequiresInput"}};return e.allInputChildrenIncludingSugared.length>0&&(t.firstInputFromSugar={dependencyType:"doenetAttribute",componentName:e.allInputChildrenIncludingSugared[0].componentName,attributeName:"createdFromSugar"}),t},definition({dependencyValues:e}){let t=[...e.allInputChildrenIncludingSugared],n=[...e.allInputChildrenIncludingSugared.keys()],r=!1;return"choiceInput"!==t[0]?.componentType&&(!e.haveAwardThatRequiresInput||e.allInputChildrenIncludingSugared.length>1)&&e.firstInputFromSugar&&(r=!0,t=t.slice(1),n=n.slice(1)),{setValue:{inputChildren:t,inputChildIndices:n,skippedFirstInput:r}}}},e.inputChildrenWithValues={stateVariablesDeterminingDependencies:["inputChildIndices"],forRenderer:!0,returnDependencies:({stateValues:e})=>({inputChildren:{dependencyType:"child",childGroups:["inputs"],variableNames:["valueToRecordOnSubmit","valueRecordedAtSubmit","value"],childIndices:e.inputChildIndices,variablesOptional:!0}}),definition:function({dependencyValues:e}){return{setValue:{inputChildrenWithValues:e.inputChildren}}}},e.inputChildWithValues={returnDependencies:()=>({inputChildrenWithValues:{dependencyType:"stateVariable",variableName:"inputChildrenWithValues"}}),definition({dependencyValues:e}){let t=null;return 1===e.inputChildrenWithValues.length&&(t=e.inputChildrenWithValues[0]),{setValue:{inputChildWithValues:t}}}},e.awardInputResponseChildren={returnDependencies:()=>({awardInputResponseChildren:{dependencyType:"child",childGroups:["awards","inputs","responses"]},skippedFirstInput:{dependencyType:"stateVariable",variableName:"skippedFirstInput"}}),definition({dependencyValues:e}){let t=[...e.awardInputResponseChildren];return e.skippedFirstInput&&(t=t.slice(1)),{setValue:{awardInputResponseChildren:t}}}},e.nResponses={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["awardInputResponseChildren"],returnDependencies({stateValues:e,componentInfoObjects:t}){let n={childTypes:{dependencyType:"value",value:e.awardInputResponseChildren.map((e=>e.componentType))}};for(let[r,a]of e.awardInputResponseChildren.entries())t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"award"})?n["child"+r]={dependencyType:"descendant",ancestorName:a.componentName,componentTypes:["_base"],variableNames:["isResponse","nValues"],variablesOptional:!0,recurseToMatchedChildren:!0,includeNonActiveChildren:!0,skipOverAdapters:!0}:t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_input"})?n["childNValues"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"nValues",variablesOptional:!0}:n["child"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"childrenWithNValues"};return n},definition({dependencyValues:e,componentInfoObjects:t}){let n=0;for(let[r,a]of e.childTypes.entries())if(t.isInheritedComponentType({inheritedComponentType:a,baseComponentType:"award"}))for(let a of e["child"+r])a.stateValues.isResponse&&!t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_composite"})&&(void 0===a.stateValues.nValues?n+=1:n+=a.stateValues.nValues);else if(t.isInheritedComponentType({inheritedComponentType:a,baseComponentType:"_input"})){let t=e["childNValues"+r];n+=void 0===t?1:t}else for(let t of e["child"+r])void 0===t.stateValues.nValues?n+=1:n+=t.stateValues.nValues;return{setValue:{nResponses:n}}}},e.currentResponses={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["currentResponse"],stateVariablesDeterminingDependencies:["awardInputResponseChildren"],returnArraySizeDependencies:()=>({nResponses:{dependencyType:"stateVariable",variableName:"nResponses"}}),returnArraySize:({dependencyValues:e})=>[e.nResponses],returnArrayDependenciesByKey({stateValues:e,componentInfoObjects:t}){let n={childTypes:{dependencyType:"value",value:e.awardInputResponseChildren.map((e=>e.componentType))}};for(let[r,a]of e.awardInputResponseChildren.entries())t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"award"})?n["child"+r]={dependencyType:"descendant",ancestorName:a.componentName,componentTypes:["_base"],variableNames:["isResponse","value","values","componentType"],variablesOptional:!0,recurseToMatchedChildren:!0,includeAttributeChildren:!0,includeNonActiveChildren:!0,skipOverAdapters:!0}:t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_input"})?(n["childValue"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"value",variablesOptional:!0},n["childValues"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"values",variablesOptional:!0},n["childComponentType"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"componentType",variablesOptional:!0}):n["child"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"childrenAsResponses"};return{globalDependencies:n}},arrayDefinitionByKey({globalDependencyValues:e,componentInfoObjects:t}){let n=[],r=[],a=[];for(let[n,r]of e.childTypes.entries())if(t.isInheritedComponentType({inheritedComponentType:r,baseComponentType:"award"}))for(let r of e["child"+n])r.stateValues.isResponse&&!t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})&&a.push(r);else if(t.isInheritedComponentType({inheritedComponentType:r,baseComponentType:"_input"})){let t={componentType:r,stateValues:{value:e["childValue"+n],values:e["childValues"+n],componentType:e["childComponentType"+n]}};a.push(t)}else a.push(...e["child"+n]);for(let e of a){let t=e.stateValues.componentType;t||(t=e.componentType),"mathList"===t?t="math":"numberList"===t?t="number":"textList"===t?t="text":"booleanList"===t&&(t="boolean"),Array.isArray(e.stateValues.values)?(n.push(...e.stateValues.values),r.push(...Array(e.stateValues.values.length).fill(t))):(n.push(e.stateValues.value),r.push(t))}return{setValue:{currentResponses:n},setCreateComponentOfType:{currentResponses:r}}}},e.currentResponse={isAlias:!0,targetVariableName:"currentResponse1"},e.nSubmittedResponses={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{nSubmittedResponses:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nSubmittedResponses",value:e.nSubmittedResponses}]})},e.submittedResponsesComponentType={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{submittedResponsesComponentType:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return e.submittedResponsesComponentType?{success:!0,instructions:[{setEssentialValue:"submittedResponsesComponentType",value:[...e.submittedResponsesComponentType]}]}:{success:!0,instructions:[{setEssentialValue:"submittedResponsesComponentType",value:[]}]}}},e.submittedResponses={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["submittedResponse"],defaultValueByArrayKey:()=>"_",hasEssential:!0,inverseShadowToSetEntireArray:!0,doNotCombineInverseArrayInstructions:!0,returnArraySizeDependencies:()=>({nSubmittedResponses:{dependencyType:"stateVariable",variableName:"nSubmittedResponses"}}),returnArraySize:({dependencyValues:e})=>[e.nSubmittedResponses],returnArrayDependenciesByKey:()=>({globalDependencies:{submittedResponsesComponentType:{dependencyType:"stateVariable",variableName:"submittedResponsesComponentType"},nSubmittedResponses:{dependencyType:"stateVariable",variableName:"nSubmittedResponses"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=[];e.submittedResponsesComponentType&&t.push(...e.submittedResponsesComponentType.slice(0,e.nSubmittedResponses));let n={};for(let r=0;r({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e.delegateCheckWork={additionalStateVariablesDefined:["delegateCheckWorkToInput","delegateCheckWorkToAncestor"],forRenderer:!0,returnDependencies:()=>({inputChildren:{dependencyType:"stateVariable",variableName:"inputChildren"},forceFullCheckworkButton:{dependencyType:"stateVariable",variableName:"forceFullCheckworkButton"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["suppressAnswerSubmitButtons"]},documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["suppressAnswerSubmitButtons"]}}),definition:function({dependencyValues:e}){let t=!1,n=!1,r=!1;return e.documentAncestor.stateValues.suppressAnswerSubmitButtons||e.sectionAncestor?.stateValues.suppressAnswerSubmitButtons?t=r=!0:1!==e.inputChildren.length||e.forceFullCheckworkButton||(n=r=!0),{setValue:{delegateCheckWork:r,delegateCheckWorkToAncestor:t,delegateCheckWorkToInput:n}}}},e.creditAchievedIfSubmit={additionalStateVariablesDefined:["awardsUsedIfSubmit","awardChildren","inputUsedIfSubmit"],stateVariablesDeterminingDependencies:["inputChildIndices"],returnDependencies:({stateValues:e})=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["credit","creditAchievedIfSubmit","fractionSatisfiedIfSubmit"]},inputChildren:{dependencyType:"child",childGroups:["inputs"],variableNames:["creditAchievedIfSubmit"],childIndices:e.inputChildIndices,variablesOptional:!0},nAwardsCredited:{dependencyType:"stateVariable",variableName:"nAwardsCredited"}}),definition:function({dependencyValues:e}){let t=0,n=e.nAwardsCredited,r=Array(n).fill(null),a=null;if(0===e.awardChildren.length){if(1===e.inputChildren.length){let n=e.inputChildren[0].stateValues.creditAchievedIfSubmit;n>=0&&(t=n,a=e.inputChildren[0].componentName)}}else{let a=Array(n).fill(null),i=0;for(let t of e.awardChildren){let e=t.stateValues.creditAchievedIfSubmit;if((e>i||null===r[n-1])&&t.stateValues.fractionSatisfiedIfSubmit>0)if(null===r[0])r[0]=t.componentName,a[0]=e,i=Math.min(...a);else for(let[o,s]of a.entries())if(e>s||null===s){r.splice(o,0,t.componentName),r=r.slice(0,n),a.splice(o,0,e),a=a.slice(0,n),i=Math.min(...a);break}}t=Math.min(1,a.reduce(((e,t)=>e+t),0))}return{setValue:{creditAchievedIfSubmit:t,awardsUsedIfSubmit:r,awardChildren:e.awardChildren,inputUsedIfSubmit:a}}}},e.creditAchieved={defaultValue:0,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchieved:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"creditAchieved",value:e.creditAchieved}]}}},e.responseHasBeenSubmitted={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{responseHasBeenSubmitted:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"responseHasBeenSubmitted",value:e.responseHasBeenSubmitted}]}}},e.autoSubmit={returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{autoSubmit:Boolean(e.autoSubmit)}})},e.creditAchievedDependencies={shadowVariable:!0,stateVariablesDeterminingDependencies:["autoSubmit"],returnDependencies:({stateValues:e})=>({currentCreditAchievedDependencies:{dependencyType:"recursiveDependencyValues",variableNames:["creditAchievedIfSubmit"],includeImmediateValueWithValue:!e.autoSubmit,includeRawValueWithImmediateValue:!e.autoSubmit,includeOnlyEssentialValues:!0}}),definition({dependencyValues:e}){let t=lib(e.currentCreditAchievedDependencies,{replacer:serializedComponentsReplacer});return{setValue:{creditAchievedDependencies:Base64.stringify(sha1(t))}}},markStale:()=>({answerCreditPotentiallyChanged:!0})},e.creditAchievedDependenciesAtSubmit={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchievedDependenciesAtSubmit:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"creditAchievedDependenciesAtSubmit",value:e.creditAchievedDependenciesAtSubmit}]}}},e.justSubmitted={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({currentCreditAchievedDependencies:{dependencyType:"stateVariable",variableName:"creditAchievedDependencies"},creditAchievedDependenciesAtSubmit:{dependencyType:"stateVariable",variableName:"creditAchievedDependenciesAtSubmit"},disableAfterCorrect:{dependencyType:"stateVariable",variableName:"disableAfterCorrect"},hasBeenCorrect:{dependencyType:"stateVariable",variableName:"hasBeenCorrect"}}),definition:function({dependencyValues:e,justUpdatedForNewComponent:t,componentName:n}){if(e.disableAfterCorrect&&e.hasBeenCorrect)return{setValue:{justSubmitted:!0}};return e.creditAchievedDependenciesAtSubmit!==e.currentCreditAchievedDependencies&&!t?{setValue:{justSubmitted:!1},setEssentialValue:{justSubmitted:!1}}:{useEssentialOrDefaultValue:{justSubmitted:!0}}},inverseDefinition:({desiredStateVariableValues:e,componentName:t})=>({success:!0,instructions:[{setEssentialValue:"justSubmitted",value:e.justSubmitted}]})},e.allFeedbacks={returnDependencies:()=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["feedbacks"]},feedbackComponents:{dependencyType:"descendant",componentTypes:["_input"],variableNames:["feedbacks"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.awardChildren)t.push(...n.stateValues.feedbacks);for(let n of e.feedbackComponents)Array.isArray(n.stateValues.feedbacks)&&t.push(...n.stateValues.feedbacks);return{setValue:{allFeedbacks:t}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({}),definition:()=>({useEssentialOrDefaultValue:{nSubmissions:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nSubmissions",value:e.nSubmissions}]})},e.numberOfAttemptsLeft={public:!0,shadowingInstructions:{createComponentOfType:"integer"},forRenderer:!0,returnDependencies:()=>({nSubmissions:{dependencyType:"stateVariable",variableName:"nSubmissions"},maximumNumberOfAttempts:{dependencyType:"stateVariable",variableName:"maximumNumberOfAttempts"}}),definition:({dependencyValues:e})=>({setValue:{numberOfAttemptsLeft:e.maximumNumberOfAttempts-e.nSubmissions}})},e.hasBeenCorrect={defaultValue:!1,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({creditAchieved:{dependencyType:"stateVariable",variableName:"creditAchieved"}}),definition:({dependencyValues:e})=>1===e.creditAchieved?{setValue:{hasBeenCorrect:!0},setEssentialValue:{hasBeenCorrect:!0}}:{useEssentialOrDefaultValue:{hasBeenCorrect:!0}}},e.disabled={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,stateVariablesDeterminingDependencies:["disableAfterCorrect"],returnDependencies({stateValues:e}){let t={disabledOriginal:{dependencyType:"stateVariable",variableName:"disabledOriginal"},numberOfAttemptsLeft:{dependencyType:"stateVariable",variableName:"numberOfAttemptsLeft"},disableAfterCorrect:{dependencyType:"stateVariable",variableName:"disableAfterCorrect"}};return e.disableAfterCorrect&&(t.hasBeenCorrect={dependencyType:"stateVariable",variableName:"hasBeenCorrect"}),t},definition:({dependencyValues:e})=>({setValue:{disabled:e.disabledOriginal||e.numberOfAttemptsLeft<1||e.disableAfterCorrect&&e.hasBeenCorrect}})},e.inItemNumber={returnDependencies:()=>({documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["itemNumberByAnswerName"]}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{inItemNumber:e.documentAncestor.stateValues.itemNumberByAnswerName[t]}})},e}actions={submitAnswer:this.submitAnswer.bind(this)};async submitAnswer({actionId:e}){let t=await this.stateValues.numberOfAttemptsLeft;if(t<1)return void console.warn(`Cannot submit answer for ${this.componentName} as number of attempts left is ${t}`);let n=await this.stateValues.creditAchievedIfSubmit,r=await this.stateValues.awardsUsedIfSubmit,a=await this.stateValues.inputUsedIfSubmit,i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"creditAchieved",value:n},{updateType:"updateValue",componentName:this.componentName,stateVariable:"responseHasBeenSubmitted",value:!0}],o=await this.stateValues.inputChildrenWithValues;if(1===o.length){let e=o[0];a===e.componentName&&"valueToRecordOnSubmit"in e.stateValues&&"valueRecordedAtSubmit"in e.stateValues&&i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"valueRecordedAtSubmit",value:e.stateValues.valueToRecordOnSubmit})}let s=await this.stateValues.currentResponses;i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"submittedResponses",value:s}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"submittedResponsesComponentType",value:this.state.currentResponses.shadowingInstructions.createComponentOfType}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"justSubmitted",value:!0}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"creditAchievedDependenciesAtSubmit",value:await this.stateValues.creditAchievedDependencies}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"nSubmissions",value:await this.stateValues.nSubmissions+1});for(let e of await this.stateValues.awardChildren){let t=r.includes(e.componentName);i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"awarded",value:t}),i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"creditAchieved",value:e.stateValues.creditAchievedIfSubmit}),i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"fractionSatisfied",value:e.stateValues.fractionSatisfiedIfSubmit})}let l=[];for(let e of s)if(e.toString)try{l.push(e.toString())}catch(e){l.push("_")}else l.push(e);return i.push({updateType:"recordItemSubmission",itemNumber:await this.stateValues.inItemNumber,submittedComponent:this.componentName,response:s,responseText:l,creditAchieved:n}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:{verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType},result:{response:s,responseText:l,creditAchieved:n}},suppressToast:await this.stateValues.suppressToast}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}}class Award extends BaseComponent{static componentType="award";static rendererType=void 0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static variableForPlainMacro="awarded";static variableForPlainCopy="awarded";static createAttributesObject(){let e=super.createAttributesObject();return e.credit={createComponentOfType:"number",createStateVariable:"credit",defaultValue:1,public:!0,attributesForCreatedComponent:{convertBoolean:!0}},e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"},e.symbolicEquality={createComponentOfType:"boolean",createStateVariable:"symbolicEquality",defaultValue:!1,public:!0,fallBackToParentStateVariable:"symbolicEquality"},e.expandOnCompare={createComponentOfType:"boolean",createStateVariable:"expandOnCompare",defaultValue:!1,public:!0,fallBackToParentStateVariable:"expandOnCompare"},e.simplifyOnCompare={createComponentOfType:"text",createStateVariable:"simplifyOnCompare",defaultValue:"none",toLowerCase:!0,valueTransformations:{"":"full",true:"full"},validValues:["none","full","numbers","numberspreserveorder"],public:!0,fallBackToParentStateVariable:"simplifyOnCompare"},e.unorderedCompare={createComponentOfType:"boolean",createStateVariable:"unorderedCompare",defaultValue:!1,public:!0,fallBackToParentStateVariable:"unorderedCompare"},e.matchByExactPositions={createComponentOfType:"boolean",createStateVariable:"matchByExactPositions",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchByExactPositions"},e.allowedErrorInNumbers={createComponentOfType:"number",createStateVariable:"allowedErrorInNumbers",defaultValue:0,public:!0,fallBackToParentStateVariable:"allowedErrorInNumbers"},e.includeErrorInNumberExponents={createComponentOfType:"boolean",createStateVariable:"includeErrorInNumberExponents",defaultValue:!1,public:!0,fallBackToParentStateVariable:"includeErrorInNumberExponents"},e.allowedErrorIsAbsolute={createComponentOfType:"boolean",createStateVariable:"allowedErrorIsAbsolute",defaultValue:!1,public:!0,fallBackToParentStateVariable:"allowedErrorIsAbsolute"},e.nSignErrorsMatched={createComponentOfType:"number",createStateVariable:"nSignErrorsMatched",defaultValue:0,public:!0,fallBackToParentStateVariable:"nSignErrorsMatched"},e.nPeriodicSetMatchesRequired={createComponentOfType:"integer",createStateVariable:"nPeriodicSetMatchesRequired",defaultValue:3,public:!0,fallBackToParentStateVariable:"nPeriodicSetMatchesRequired"},e.caseInsensitiveMatch={createComponentOfType:"boolean",createStateVariable:"caseInsensitiveMatch",defaultValue:!1,public:!0,fallBackToParentStateVariable:"caseInsensitiveMatch"},e.matchBlanks={createComponentOfType:"boolean",createStateVariable:"matchBlanks",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchBlanks"},e.feedbackCodes={createComponentOfType:"textList",createStateVariable:"feedbackCodes",defaultValue:[],public:!0},e.feedbackText={createComponentOfType:"text",createStateVariable:"feedbackText",defaultValue:null,public:!0},e.sourcesAreResponses={createPrimitiveOfType:"string"},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e}static preprocessSerializedChildren({serializedChildren:e,attributes:t,componentName:n}){if(t.sourcesAreResponses){let r,a=t.sourcesAreResponses.primitive.split(/\s+/).filter((e=>e));r=t.newNamespace?.primitive?n+"/":getNamespaceFromName(n);for(let t of a){let n;if("/"===t[0])n=t;else if("../"===t.slice(0,3)){let e=getNamespaceFromName(r.slice(0,r.length-1)),a=t.slice(3);for(;"../"===a.slice(0,3);){if("/"===e){n=null;break}e=getNamespaceFromName(e.slice(0,e.length-1)),a=a.slice(3)}null!==n&&(n=e+a)}else n=r+t;addResponsesToDescendantsWithTarget(e,t,n)}}}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,parentAttributes:t,componentInfoObjects:n}){for(;"string"==typeof e[0]&&""===e[0].trim();)e=e.slice(1);let r=e.length;for(;"string"==typeof e[r-1]&&""===e[r-1].trim();)r=(e=e.slice(0,r-1)).length;if(1===e.length&&"object"==typeof e[0])return{success:!1};let a,i=n.componentIsSpecifiedType,o=!1,s=!1,l=!1;for(let t of e)"object"==typeof t&&(i(t,"math")||i(t,"number")||i(t,"mathList")||i(t,"numberList")?o=!0:i(t,"text")||i(t,"textList")?s=!0:(i(t,"boolean")||i(t,"booleanList"))&&(l=!0));return t.type?(a=t.type,["math","text","boolean"].includes(a)||(console.warn(`Invalid type ${a}`),a="math")):a=o?"math":s?"text":l?"boolean":"math",{success:!0,newChildren:[{componentType:a,children:e}]}}}),e}static returnChildGroups(){return[{group:"whens",componentTypes:["when"]},{group:"maths",componentTypes:["math"]},{group:"numbers",componentTypes:["number"]},{group:"texts",componentTypes:["text"]},{group:"booleans",componentTypes:["boolean"]},{group:"mathLists",componentTypes:["mathList"]},{group:"numberLists",componentTypes:["numberList"]},{group:"textLists",componentTypes:["textList"]},{group:"booleanLists",componentTypes:["booleanList"]},{group:"otherComparableTypes",componentTypes:["orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.parsedExpression={additionalStateVariablesDefined:["requireInputInAnswer"],returnDependencies:()=>({whenChild:{dependencyType:"child",childGroups:["whens"]},typeChildren:{dependencyType:"child",childGroups:["maths","numbers","texts","booleans","mathLists","numberLists","textLists","booleanLists","otherComparableTypes"]}}),definition:function({dependencyValues:e}){let t=null,n=!1;return 0==e.whenChild.length&&e.typeChildren.length>0&&(n=!0,t=me$3.fromAst(["=","comp1","comp2"])),{setValue:{parsedExpression:t,requireInputInAnswer:n}}}},e.creditAchievedIfSubmit={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"fractionSatisfiedIfSubmit",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({credit:{dependencyType:"stateVariable",variableName:"credit"},whenChild:{dependencyType:"child",childGroups:["whens"],variableNames:["fractionSatisfied"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value","unordered"]},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},textChild:{dependencyType:"child",childGroups:["texts"],variableNames:["value"]},booleanChild:{dependencyType:"child",childGroups:["booleans"],variableNames:["value"]},mathListChild:{dependencyType:"child",childGroups:["mathLists"],variableNames:["maths","unordered"]},numberListChild:{dependencyType:"child",childGroups:["numberLists"],variableNames:["numbers","unordered"]},textListChild:{dependencyType:"child",childGroups:["textLists"],variableNames:["texts","unordered"]},booleanListChild:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["booleans","unordered"]},otherComparableChild:{dependencyType:"child",childGroups:["otherComparableTypes"],variableNames:["value"]},answerInput:{dependencyType:"parentStateVariable",variableName:"inputChildWithValues"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"},symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n;if(e.whenChild.length>0)n=e.whenChild[0].stateValues.fractionSatisfied;else{if(!e.answerInput||!e.parsedExpression)return{setValue:{creditAchievedIfSubmit:0,fractionSatisfiedIfSubmit:0}};n=evaluateLogicDirectlyFromChildren({dependencyValues:e,usedDefault:t})}n=Math.max(0,Math.min(1,n));let r=0;return Number.isFinite(e.credit)&&(r=Math.max(0,Math.min(1,e.credit))*n),{setValue:{fractionSatisfiedIfSubmit:n,creditAchievedIfSubmit:r}}}},e.fractionSatisfied={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{fractionSatisfied:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"fractionSatisfied",value:e.fractionSatisfied}]}:{success:!1}}},e.creditAchieved={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchieved:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"creditAchieved",value:e.creditAchieved}]}:{success:!1}}},e.awarded={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{awarded:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"awarded",value:e.awarded}]}:{success:!1}}},e.allFeedbacks={returnDependencies:()=>({feedbackText:{dependencyType:"stateVariable",variableName:"feedbackText"},feedbackCodes:{dependencyType:"stateVariable",variableName:"feedbackCodes"},feedbackDefinitionAncestor:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},awarded:{dependencyType:"stateVariable",variableName:"awarded"}}),definition:function({dependencyValues:e}){if(!e.awarded)return{setValue:{allFeedbacks:[]}};let t=[],n=e.feedbackDefinitionAncestor.stateValues.feedbackDefinitions;for(let r of e.feedbackCodes){let e=n[r.toLowerCase()];e&&t.push(e)}return null!==e.feedbackText&&t.push(e.feedbackText),{setValue:{allFeedbacks:t}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n0?n.textChildrenByCode.comp2=e.textChild[0]:e.mathChild.length>0?n.mathChildrenByCode.comp2=e.mathChild[0]:e.numberChild.length>0?n.numberChildrenByCode.comp2=e.numberChild[0]:e.booleanChild.length>0?n.booleanChildrenByCode.comp2=e.booleanChild[0]:e.textListChild.length>0?n.textListChildrenByCode.comp2=e.textListChild[0]:e.mathListChild.length>0?n.mathListChildrenByCode.comp2=e.mathListChild[0]:e.numberListChild.length>0?n.numberListChildrenByCode.comp2=e.numberListChild[0]:e.booleanListChild.length>0?n.booleanListChildrenByCode.comp2=e.booleanListChild[0]:e.otherComparableChild.length>0&&(n.otherChildrenByCode.comp2=e.otherComparableChild[0]);let a=e.answerInput.stateValues.immediateValue;void 0===a&&(a=e.answerInput.stateValues.value);let i={stateValues:{value:a}};return"textInput"===e.answerInput.componentType?n.textChildrenByCode.comp1=i:"booleanInput"===e.answerInput.componentType?n.booleanChildrenByCode.comp1=i:n.mathChildrenByCode.comp1=i,evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:r,dependencyValues:n})}function addResponsesToDescendantsWithTarget(e,t,n){for(let r of e){let e=r.props;if(e&&0!==Object.keys(e).length||(e=r.doenetAttributes),e)for(let a in e)if("target"===a.toLowerCase()&&e[a]===t||"targetcomponentname"===a.toLowerCase()&&e[a]===n){r.attributes||(r.attributes={});let e=Object.keys(r.attributes).map((e=>e.toLowerCase())).includes("isresponse");e||(r.attributes.isResponse=!0)}r.children&&addResponsesToDescendantsWithTarget(r.children,t,n)}}class When extends BooleanComponent{static componentType="when";static rendererType=void 0;static stateVariableForAttributeValue="conditionSatisfied";static createAttributesObject(){let e=super.createAttributesObject();e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"};for(let t of["symbolicEquality","expandOnCompare","simplifyOnCompare","unorderedCompare","matchByExactPositions","allowedErrorInNumbers","includeErrorInNumberExponents","allowedErrorIsAbsolute","nSignErrorsMatched","nPeriodicSetMatchesRequired","caseInsensitiveMatch","matchBlanks"])e[t].fallBackToParentStateVariable=t;return e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},additionalStateVariablesDefined:[{variableName:"fractionSatisfied",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"conditionSatisfied",public:!0,shadowingInstructions:{createComponentOfType:"boolean"}}],returnDependencies:()=>({matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"},symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},booleanListChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanListChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},textListChildrenByCode:{dependencyType:"stateVariable",variableName:"textListChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},mathListChildrenByCode:{dependencyType:"stateVariable",variableName:"mathListChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},numberListChildrenByCode:{dependencyType:"stateVariable",variableName:"numberListChildrenByCode"},otherChildrenByCode:{dependencyType:"stateVariable",variableName:"otherChildrenByCode"}}),definition({dependencyValues:e,usedDefault:t}){if(null===e.parsedExpression)return{setValue:{conditionSatisfied:!1,value:!1,fractionSatisfied:0}};let n=t.unorderedCompare,r=evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:n,dependencyValues:e}),a=1===r;return{setValue:{fractionSatisfied:r,conditionSatisfied:a,value:a}}}},e}}class MathInput extends Input{constructor(e){super(e),this.actions={updateRawValue:this.updateRawValue.bind(this),updateValue:this.updateValue.bind(this)},this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="mathInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"math",createStateVariable:"prefill",defaultValue:me$3.fromAst("_"),public:!0,copyComponentAttributesForCreatedComponent:["format","functionSymbols","splitSymbols","parseScientificNotation"]},e.prefillLatex={createComponentOfType:"latex",createStateVariable:"prefillLatex",defaultValue:"",public:!0},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"math"},e.unionFromU={createComponentOfType:"boolean",createStateVariable:"unionFromU",defaultValue:!1,public:!0},e.hideNaN={createComponentOfType:"boolean",createStateVariable:"hideNaN",defaultValue:!0,public:!0},e.removeStrings={createComponentOfType:"textList",createStateVariable:"removeStrings",defaultValue:null},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){return 0===e.length?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLatex:{dependencyType:"stateVariable",variableName:"prefillLatex"},unionFromU:{dependencyType:"stateVariable",variableName:"unionFromU"},functionSymbols:{dependencyType:"stateVariable",variableName:"functionSymbols"},splitSymbols:{dependencyType:"stateVariable",variableName:"splitSymbols"},parseScientificNotation:{dependencyType:"stateVariable",variableName:"parseScientificNotation"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,usedDefault:t}){return e.mathChild.length>0?{setValue:{value:e.mathChild[0].stateValues.value}}:e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{get defaultValue(){return!t.prefill||t.prefillLatex?e.prefill:calculateMathExpressionFromLatex({latex:e.prefillLatex,unionFromU:e.unionFromU,functionSymbols:e.functionSymbols,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation})}}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.mathChild.length>0?{success:!0,instructions:[{setDependency:"mathChild",desiredValue:e.value,variableIndex:0,childIndex:0}]}:t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n,usedDefault:r}){return!t.value||n||r.value?{useEssentialOrDefaultValue:{immediateValue:{defaultValue:e.value}}}:{setValue:{immediateValue:e.value},setEssentialValue:{immediateValue:e.value}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.valueForDisplay.toString()}}}},e.dontUpdateRawValueInDefinition={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{dontUpdateRawValueInDefinition:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"dontUpdateRawValueInDefinition",value:e.dontUpdateRawValueInDefinition}]})},e.rawRendererValue={forRenderer:!0,hasEssential:!0,shadowVariable:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"lastValueForDisplay",hasEssential:!0,shadowVariable:!0,defaultValue:null,set:convertValueToMathExpression}],returnDependencies:()=>({immediateValue:{dependencyType:"stateVariable",variableName:"immediateValue"},valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},hideNaN:{dependencyType:"stateVariable",variableName:"hideNaN"},dontUpdateRawValueInDefinition:{dependencyType:"stateVariable",variableName:"dontUpdateRawValueInDefinition"},prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLatex:{dependencyType:"stateVariable",variableName:"prefillLatex"}}),definition({dependencyValues:e,essentialValues:t,justUpdatedForNewComponent:n,usedDefault:r}){if(void 0!==t.rawRendererValue&&(n||deepCompare(t.lastValueForDisplay.tree,e.valueForDisplay.tree)||e.dontUpdateRawValueInDefinition))return{useEssentialOrDefaultValue:{rawRendererValue:!0,lastValueForDisplay:!0}};{let t;return t=r.immediateValue&&r.prefill&&!r.prefillLatex?stripLatex(e.prefillLatex):stripLatex(e.valueForDisplay.toLatex({showBlanks:!1})),e.hideNaN&&"NaN"===t&&(t=""),{setValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay},setEssentialValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay}}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t,essentialValues:n,dependencyValues:r,componentName:a}){let i=[];if("string"==typeof e.rawRendererValue){let r=n.rawRendererValue,a=e.rawRendererValue;r!==a&&i.push({setEssentialValue:"rawRendererValue",value:a});let o=await t.unionFromU,s=await t.functionSymbols,l=await t.splitSymbols,u=await t.parseScientificNotation,c=await t.removeStrings,p=calculateMathExpressionFromLatex({latex:r,unionFromU:o,functionSymbols:s,splitSymbols:l,parseScientificNotation:u,removeStrings:c}),d=calculateMathExpressionFromLatex({latex:a,unionFromU:o,functionSymbols:s,splitSymbols:l,parseScientificNotation:u,removeStrings:c});deepCompare(d.tree,p.tree)||i.push({setDependency:"immediateValue",desiredValue:d,treatAsInitialChange:!0})}else if(e.rawRendererValue instanceof me$3.class){i.push({setEssentialValue:"lastValueForDisplay",value:e.rawRendererValue});let a=await t.unionFromU,o=await t.functionSymbols,s=await t.splitSymbols,l=await t.parseScientificNotation,u=await t.removeStrings,c=calculateMathExpressionFromLatex({latex:n.rawRendererValue,unionFromU:a,functionSymbols:o,splitSymbols:s,parseScientificNotation:l,removeStrings:u});if(!deepCompare(e.rawRendererValue.tree,c.tree)){let t=stripLatex(e.rawRendererValue.toLatex({showBlanks:!1}));r.hideNaN&&"NaN"===t&&(t=""),i.push({setEssentialValue:"rawRendererValue",value:t})}}else e.lastValueForDisplay instanceof me$3.class&&i.push({setEssentialValue:"lastValueForDisplay",value:e.lastValueForDisplay});return{success:!0,instructions:i}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"math"}})},e}async updateRawValue({rawRendererValue:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],transient:!0,actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.immediateValue;if(!deepCompare((await this.stateValues.value).tree,t.tree)){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"dontUpdateRawValueInDefinition",value:!0},{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"dontUpdateRawValueInDefinition",value:!1},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}];"_"!==t.tree?n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"valueForDisplay"}):n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"lastValueForDisplay",valueOfStateVariable:"valueForDisplay"});let r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:e})}}static adapters=[{stateVariable:"value",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]}]}function calculateMathExpressionFromLatex({latex:e,unionFromU:t,functionSymbols:n,splitSymbols:r,parseScientificNotation:a,removeStrings:i}){let o;if(i)for(let t of i)["$","%"].includes(t)&&(t="\\"+t),e=e.replaceAll(t,"");e=normalizeLatexString(e,{unionFromU:t});let s=getFromLatex({functionSymbols:n,splitSymbols:r,parseScientificNotation:a});try{o=s(e)}catch(e){o=me$3.fromAst("_")}return o}class Textinput extends Input{constructor(e){super(e),this.actions={updateImmediateValue:this.updateImmediateValue.bind(this),updateValue:this.updateValue.bind(this)},this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="textInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e.size={createComponentOfType:"number",createStateVariable:"size",defaultValue:10,forRenderer:!0,public:!0},e.bindValueTo={createComponentOfType:"text"},e.expanded={createComponentOfType:"boolean",createStateVariable:"expanded",defaultValue:!1,forRenderer:!0,public:!0},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:600,isAbsolute:!0},forRenderer:!0,public:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:120,isAbsolute:!0},forRenderer:!0,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.value&&!n?{setValue:{immediateValue:e.value},setEssentialValue:{immediateValue:e.value}}:{useEssentialOrDefaultValue:{immediateValue:{defaultValue:e.value}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"text"}})},e}async updateImmediateValue({text:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],transient:!0,actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(!await this.stateValues.disabled){let t=await this.stateValues.immediateValue;if(await this.stateValues.value!==t){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}],r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}}this.coreFunctions.resolveAction({actionId:e})}}class BooleanInput extends Input{constructor(e){super(e),this.actions={updateBoolean:this.updateBoolean.bind(this)},this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="booleanInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"boolean",createStateVariable:"prefill",defaultValue:!1,public:!0},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.asToggleButton={createComponentOfType:"boolean",createStateVariable:"asToggleButton",defaultValue:!1,forRenderer:!0,public:!0},e.bindValueTo={createComponentOfType:"boolean"},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value?"true":"false"}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"boolean"}})},e}static adapters=["value"];async updateBoolean({boolean:e,actionId:t}){if(!await this.stateValues.disabled){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],r={verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:e,responseText:e.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,event:r,actionId:t}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:t})}}class Choiceinput extends Input{constructor(e){super(e),this.actions={updateSelectedIndices:this.updateSelectedIndices.bind(this)},this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="choiceInput";static renderChildren=!0;static variableForPlainMacro="values";static variableForPlainCopy="values";static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.selectMultiple={createComponentOfType:"boolean",createStateVariable:"selectMultiple",defaultValue:!1,public:!0,forRenderer:!0,fallBackToParentStateVariable:"selectMultiple"},e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"},e.inline={createComponentOfType:"boolean"},e.shuffleOrder={createPrimitiveOfType:"boolean",createStateVariable:"shuffleOrder",defaultValue:!1,public:!0},e.preselectChoice={createComponentOfType:"number",createStateVariable:"preselectChoice",defaultValue:null},e.bindValueTo={createComponentOfType:"text"},e.placeHolder={createComponentOfType:"text",createStateVariable:"placeHolder",defaultValue:"",forRenderer:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0,fallBackToParentStateVariable:"submitLabel"},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0,fallBackToParentStateVariable:"submitLabelNoCorrectness"},e}static returnChildGroups(){return[{group:"choices",componentTypes:["choice"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.inline={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,returnDependencies:()=>({inlineAttr:{dependencyType:"attributeComponent",attributeName:"inline",variableNames:["value"]},parentInline:{dependencyType:"parentStateVariable",variableName:"inline"}}),definition:({dependencyValues:e})=>e.inlineAttr?{setValue:{inline:e.inlineAttr.stateValues.value}}:null!==e.parentInline?{setValue:{inline:e.parentInline}}:{useEssentialOrDefaultValue:{inline:{}}}},e.numberChoices={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"]}}),definition:({dependencyValues:e})=>({setValue:{numberChoices:e.choiceChildren.length}})},e.choiceOrder={forRenderer:!0,shadowVariable:!0,returnDependencies:({sharedParameters:e})=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},shuffleOrder:{dependencyType:"stateVariable",variableName:"shuffleOrder"},variantSeed:{dependencyType:"value",value:e.variantSeed},rngClass:{dependencyType:"value",value:e.rngClass,doNotProxy:!0},variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){let t,n=e.choiceChildren.length;if(e.shuffleOrder){let r=e.variants?.desiredVariant?.indices;if(void 0!==r)if(r.length!==n)console.warn("Ignoring indices specified for choiceInput as number of indices doesn't match number of choice children.");else{if(r=r.map(Number),!r.every(Number.isInteger))throw Error("All indices specified for choiceInput must be integers");if(r.every((e=>e>=1&&e<=n)))return{setValue:{choiceOrder:r}};console.warn("Ignoring indices specified for choiceInput as some indices out of range.")}let a=e.rngClass(e.variantSeed+"co");t=[...Array(n).keys()].map((e=>e+1));for(let e=n-1;e>0;e--){const n=a(),r=Math.floor(n*(e+1));[t[e],t[r]]=[t[r],t[e]]}}else t=[...Array(n).keys()].map((e=>e+1));return{setValue:{choiceOrder:t}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({componentInfoObjects:e,sharedParameters:t})=>({variantSeed:{dependencyType:"value",value:t.variantSeed},choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},shuffleOrder:{dependencyType:"stateVariable",variableName:"shuffleOrder"},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(e.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}};e.shuffleOrder&&(n.indices=e.choiceOrder);let r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e.choiceChildrenOrdered={additionalStateVariablesDefined:[{variableName:"numberChoices",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"]}}),definition:function({dependencyValues:e}){let t=e.choiceChildren.length,n=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceChildrenOrdered:n,numberChoices:t}}}},e.choiceTexts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["choiceText"],forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceTexts:t.map((e=>e.stateValues.text))}}}},e.choiceMaths={public:!0,shadowingInstructions:{createComponentOfType:"math"},isArray:!0,entryPrefixes:["choiceMath"],forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["math"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceMaths:t.map((e=>e.stateValues.math))}}}},e.choicePreselects={isArray:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["preSelect"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicePreselects:t.map((e=>e.stateValues.preSelect))}}}},e.choicesDisabled={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["disabled"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicesDisabled:t.map((e=>e.stateValues.disabled))}}}},e.choicesHidden={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["hidden"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicesHidden:t.map((e=>e.stateValues.hidden))}}}},e.componentType={returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["math"]}}),definition({dependencyValues:e}){let t="text";return e.choiceChildren.length>0&&e.choiceChildren.every((e=>e.stateValues.math))&&(t="math"),{setValue:{componentType:t}}}},e.indicesMatchedByBoundValue={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},selectMultiple:{dependencyType:"stateVariable",variableName:"selectMultiple"}}),definition({dependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));if(null!==e.bindValueTo){let n=t.map((e=>e.stateValues.text.toLowerCase().trim()));if(e.bindValueTo.stateValues.value){if(e.selectMultiple){let t=e.bindValueTo.stateValues.value.toLowerCase().split(",").map((e=>e.trim())),r=[];for(let e of t){let t=n.indexOf(e);-1===t||r.includes(t+1)||r.push(t+1)}return r.sort(((e,t)=>e-t)),{setValue:{indicesMatchedByBoundValue:r}}}{let t=n.indexOf(e.bindValueTo.stateValues.value.toLowerCase().trim());if(-1!==t)return{setValue:{indicesMatchedByBoundValue:[t+1]}}}}}return{setValue:{indicesMatchedByBoundValue:[]}}}},e.allSelectedIndices={hasEssential:!0,returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},indicesMatchedByBoundValue:{dependencyType:"stateVariable",variableName:"indicesMatchedByBoundValue"},preselectChoice:{dependencyType:"stateVariable",variableName:"preselectChoice"},choicePreselects:{dependencyType:"stateVariable",variableName:"choicePreselects"},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]}}),definition:({dependencyValues:e})=>null!==e.bindValueTo?{setValue:{allSelectedIndices:e.indicesMatchedByBoundValue}}:{useEssentialOrDefaultValue:{allSelectedIndices:{get defaultValue(){let t=e.choicePreselects.indexOf(!0);return-1!==t?[t+1]:null!==e.preselectChoice?[e.preselectChoice]:[]}}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(null===t.bindValueTo)return{success:!0,instructions:[{setEssentialValue:"allSelectedIndices",value:e.allSelectedIndices}]};{let n="";if(e.allSelectedIndices.length>0){let r=t.choiceOrder.map((e=>t.choiceChildren[e-1])),a=[];for(let t of e.allSelectedIndices){let e=r[t-1];e&&a.push(e.stateValues.text)}n=a.join(", ")}return{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:n,variableIndex:0}]}}}},e.nSelectedIndices={returnDependencies:()=>({allSelectedIndices:{dependencyType:"stateVariable",variableName:"allSelectedIndices"}}),definition:({dependencyValues:e})=>({setValue:{nSelectedIndices:e.allSelectedIndices.length}})},e.selectedIndices={public:!0,shadowingInstructions:{createComponentOfType:"number"},isArray:!0,entryPrefixes:["selectedIndex"],forRenderer:!0,returnArraySizeDependencies:()=>({nSelectedIndices:{dependencyType:"stateVariable",variableName:"nSelectedIndices"}}),returnArraySize:({dependencyValues:e})=>[e.nSelectedIndices],returnArrayDependenciesByKey:()=>({globalDependencies:{allSelectedIndices:{dependencyType:"stateVariable",variableName:"allSelectedIndices"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n in e.allSelectedIndices)t[n]=e.allSelectedIndices[n];return{setValue:{selectedIndices:t}}}},e.selectedIndex={isAlias:!0,targetVariableName:"selectedIndex1"},e.selectedValues={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["selectedValue"],returnArraySizeDependencies:()=>({nSelectedIndices:{dependencyType:"stateVariable",variableName:"nSelectedIndices"}}),returnArraySize:({dependencyValues:e})=>[e.nSelectedIndices],returnArrayDependenciesByKey:()=>({globalDependencies:{selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},choiceTexts:{dependencyType:"stateVariable",variableName:"choiceTexts"},choiceMaths:{dependencyType:"stateVariable",variableName:"choiceMaths"},componentType:{dependencyType:"stateVariable",variableName:"componentType"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={},r=e.componentType;for(let a of t)n[a]="math"===r?e.choiceMaths[e.selectedIndices[a]-1]:e.choiceTexts[e.selectedIndices[a]-1];return{setValue:{selectedValues:n},setCreateComponentOfType:{selectedValues:r}}}},e.selectedValue={isAlias:!0,targetVariableName:"selectedValue1"},e.values={isAlias:!0,targetVariableName:"selectedValues"},e.nValues={isAlias:!0,targetVariableName:"nSelectedIndices"},e.childIndicesSelected={returnDependencies:()=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"}}),definition({dependencyValues:e}){let t=e.selectedIndices.map((t=>e.choiceOrder[t-1]));return{setValue:{childIndicesSelected:t}}}},e.creditAchievedIfSubmit={returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["selected","credit"]},selectMultiple:{dependencyType:"stateVariable",variableName:"selectMultiple"},matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"}}),definition:function({dependencyValues:e}){let t=0;if(e.selectMultiple){let n=0,r=0,a=0;for(let t of e.choiceChildren)t.stateValues.selected?1===t.stateValues.credit?n++:r++:1===t.stateValues.credit&&a++;if(e.matchPartial){let e=n+r+a;t=0===e?1:n/e}else r+a===0&&(t=1)}else for(let n of e.choiceChildren)if(n.stateValues.selected){t=n.stateValues.credit;break}return{setValue:{creditAchievedIfSubmit:t}}}},e.valueToRecordOnSubmit={isAlias:!0,targetVariableName:"selectedIndices"},e.submittedIndices={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["submitted"]}}),definition({dependencyValues:e}){let t=[],n=e.choiceOrder.map((t=>e.choiceChildren[t-1]));for(let[e,r]of n.entries())r.stateValues.submitted&&t.push(e+1);return{setValue:{submittedIndices:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=[];for(let[r,a]of t.choiceOrder.entries())n.push({setDependency:"choiceChildren",desiredValue:e.submittedIndices.includes(r+1),variableIndex:0,childIndex:a-1});return{success:!0,instructions:n}}},e.valueRecordedAtSubmit={isAlias:!0,targetVariableName:"submittedIndices"},e.allFeedbacks={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["feedbacks"]}}),definition({dependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1])),n=[];for(let e of t)n.push(...e.stateValues.feedbacks);return{setValue:{allFeedbacks:n}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;nr[e-1]))}},i=await this.stateValues.answerAncestor;return i&&(a.context={answerAncestor:i.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:t,event:a}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n})}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){if(!e.attributes?.shuffleOrder?.primitive)return super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});let n=0;for(let r of e.children)if("choice"===r.componentType)n++;else{if(!t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})||"choice"!==r.attributes.createComponentOfType?.primitive)return{success:!1};if(void 0!==r.attributes.nComponents?.primitive){let e=Number(r.attributes.nComponents?.primitive);if(!(Number.isInteger(e)&&e>=0))return{success:!1};n+=e}else n++}let r=1;for(let e=2;e<=n;e++)r*=e;let a=super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!a.success)return{success:!1};let i=a.numberOfVariants*r;return e.variants.numberOfVariants=i,e.variants.uniqueVariantData={numberOfVariantsByDescendant:e.variants.uniqueVariantData.numberOfVariantsByDescendant,numberOfPermutations:r,numberOfChoices:n},{success:!0,numberOfVariants:i}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};if(!e.attributes.shuffleOrder?.primitive)return super.getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n});let a=e.variants.uniqueVariantData.numberOfVariantsByDescendant,i=e.variants.descendantVariantComponents,o=e.variants.uniqueVariantData.numberOfPermutations,s=e.variants.uniqueVariantData.numberOfChoices,l=[...a];l.push(o);let u=enumerateCombinations({numberOfOptionsByIndex:l,maxNumber:t})[t-1].map((e=>e+1)),c=u.pop(),p=u,d=[...Array(s).keys()].map((e=>e+1)),m=enumeratePermutations({values:d,maxNumber:c})[c-1],f=!1,h=[];for(let e=0;e1){let t=i[e],r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:p[e],componentInfoObjects:n});if(!r.success)return{success:!1};h.push(r.desiredVariant),f=!0}else h.push({});let y={indices:m};return f&&(y.subvariants=h),{success:!0,desiredVariant:y}}}class Choice extends InlineComponent{static componentType="choice";static rendererType="containerInline";static renderChildren=!0;static variableForPlainMacro="submitted";static variableForPlainCopy="submitted";static createAttributesObject(){let e=super.createAttributesObject();return e.credit={createComponentOfType:"number",createStateVariable:"credit",defaultValue:0,public:!0,attributesForCreatedComponent:{convertBoolean:!0}},e.feedbackCodes={createComponentOfType:"textList",createStateVariable:"feedbackCodes",defaultValue:[],public:!0},e.feedbackText={createComponentOfType:"text",createStateVariable:"feedbackText",defaultValue:null,public:!0},e.preSelect={createComponentOfType:"boolean",createStateVariable:"preSelect",defaultValue:!1},e}static returnChildGroups(){return[{group:"children",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["children"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{text:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["children"],variableNames:["value","latex"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=null;if(1===e.inlineChildren.length){let n=e.inlineChildren[0];if("object"==typeof n){let e=n.stateValues.value;if(e instanceof me$3.class)t=e;else if("number"==typeof e)t=me$3.fromAst(e);else if("string"==typeof n.stateValues.latex)try{t=me$3.fromLatex(n.stateValues.latex)}catch(e){}}}return{setValue:{math:t}}}},e.selected={defaultValue:!1,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({countAmongSiblings:{dependencyType:"countAmongSiblingsOfSameType"},childIndicesSelected:{dependencyType:"parentStateVariable",parentComponentType:"choiceInput",variableName:"childIndicesSelected"},primaryShadow:{dependencyType:"primaryShadow",variableNames:["selected"]}}),definition({dependencyValues:e,componentName:t}){let n;return n=e.childIndicesSelected?e.childIndicesSelected.includes(e.countAmongSiblings):!!e.primaryShadow&&e.primaryShadow.stateValues.selected,{setValue:{selected:n}}}},e.submitted={defaultValue:!1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},doNotShadowEssential:!0,returnDependencies:()=>({primaryShadow:{dependencyType:"primaryShadow",variableNames:["submitted"]}}),definition:({dependencyValues:e})=>e.primaryShadow?{setValue:{submitted:e.primaryShadow.stateValues.submitted}}:{useEssentialOrDefaultValue:{submitted:!0}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.primaryShadow?{success:!1}:{success:!0,instructions:[{setEssentialValue:"submitted",value:e.submitted}]}}},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedbacktext"},returnDependencies:()=>({feedbackText:{dependencyType:"stateVariable",variableName:"feedbackText"},feedbackCodes:{dependencyType:"stateVariable",variableName:"feedbackCodes"},feedbackDefinitionAncestor:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},submitted:{dependencyType:"stateVariable",variableName:"submitted"}}),definition({dependencyValues:e}){if(!e.submitted)return{setValue:{feedbacks:[]}};let t=[],n=e.feedbackDefinitionAncestor.stateValues.feedbackDefinitions;for(let r of e.feedbackCodes){let e=n[r.toLowerCase()];e&&t.push(e)}return null!==e.feedbackText&&t.push(e.feedbackText),{setValue:{feedbacks:t}}}},e}static includeBlankStringChildren=!0;static adapters=["text","math"]}class NumberComponent extends InlineComponent{static componentType="number";static variableForPlainMacro="value";static createAttributesObject(){let e=super.createAttributesObject();return e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.renderAsMath={createComponentOfType:"boolean",createStateVariable:"renderAsMath",defaultValue:!1,public:!0,forRenderer:!0},e.convertBoolean={createPrimitiveOfType:"boolean",createStateVariable:"convertBoolean",defaultValue:!1},e.valueOnNaN={createPrimitiveOfType:"number",createStateVariable:"valueOnNaN",defaultValue:NaN},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/..+/,replacementFunction:({matchedChildren:e,componentAttributes:t})=>({success:!t.convertBoolean,newChildren:[{componentType:"math",children:e}]})}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"numbers",componentTypes:["number"]},{group:"maths",componentTypes:["math"]},{group:"texts",componentTypes:["text"]},{group:"booleans",componentTypes:["boolean"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displayDigits"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}let a=null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals,i=null===e.displayDigitsAttr||t.displayDigitsAttr,o=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!i&&!o){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displayDecimals"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}if(1===e.numberMathChildren.length&&0===e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].displayDecimals)return{setValue:{displayDecimals:e.numberMathChildren[0].stateValues.displayDecimals}};r=!0,n=e.numberMathChildren[0].stateValues.displayDecimals}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displaySmallAsZero"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}if(1===e.numberMathChildren.length&&0===e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].displaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberMathChildren[0].stateValues.displaySmallAsZero}};r=!0,n=e.numberMathChildren[0].stateValues.displaySmallAsZero}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["padZeros"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}if(1===e.numberMathChildren.length&&0==e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].padZeros)return{setValue:{padZeros:e.numberMathChildren[0].stateValues.padZeros}};r=!0,n=e.numberMathChildren[0].stateValues.padZeros}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.singleNumberOrStringChild={additionalStateVariablesDefined:["singleMathChild"],returnDependencies:()=>({numberChildren:{dependencyType:"child",childGroups:["numbers"]},stringChildren:{dependencyType:"child",childGroups:["strings"]},mathChildren:{dependencyType:"child",childGroups:["maths"]},booleanChildren:{dependencyType:"child",childGroups:["booleans"]},textChildren:{dependencyType:"child",childGroups:["texts"]}}),definition({dependencyValues:e}){let t=e.numberChildren.length+e.stringChildren.length,n=e.mathChildren.length,r=e.booleanChildren.length+e.textChildren.length;return{setValue:{singleNumberOrStringChild:t<=1&&n+r===0,singleMathChild:1===n&&t+r===0}}}},e.parsedExpression={additionalStateVariablesDefined:["codePre"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]}}),definition:buildParsedExpression},e.mathChildrenByCode={additionalStateVariablesDefined:["textChildrenByCode","numberChildrenByCode","booleanChildrenByCode"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"],variableNames:["value","texts","maths","booleans"],variablesOptional:!0},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n={},r={},a={},i={},o=0,s=e.codePre;for(let l of e.allChildren)if("string"!=typeof l){let e=s+o;t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"math"})?n[e]=l:t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"number"})?r[e]=l:t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"text"})?a[e]=l:i[e]=l,o+=1}return{setValue:{mathChildrenByCode:n,numberChildrenByCode:r,textChildrenByCode:a,booleanChildrenByCode:i}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},hasEssential:!0,stateVariablesDeterminingDependencies:["singleNumberOrStringChild"],returnDependencies:({stateValues:e})=>e.singleNumberOrStringChild?{singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},convertBoolean:{dependencyType:"stateVariable",variableName:"convertBoolean"},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},stringChild:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},valueOnNaN:{dependencyType:"stateVariable",variableName:"valueOnNaN"}}:{singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},singleMathChild:{dependencyType:"stateVariable",variableName:"singleMathChild"},convertBoolean:{dependencyType:"stateVariable",variableName:"convertBoolean"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"],variableNames:["value","texts","maths","unordered"],variablesOptional:!0},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},valueOnNaN:{dependencyType:"stateVariable",variableName:"valueOnNaN"}},definition({dependencyValues:e,componentInfoObjects:t}){if(e.singleNumberOrStringChild){if(0===e.numberChild.length){if(0===e.stringChild.length)return{useEssentialOrDefaultValue:{value:{defaultValue:e.valueOnNaN}}};let n=Number(e.stringChild[0]);if(Number.isNaN(n))try{if(n=me$3.fromAst(textToAst$1.convert(e.stringChild[0])).evaluate_to_constant(),"boolean"==typeof n)n=e.convertBoolean?n?1:0:e.valueOnNaN;else if(null===n||Number.isNaN(n))if(e.convertBoolean){n=evaluateLogic({logicTree:buildParsedExpression({dependencyValues:{stringChildren:e.stringChild,allChildren:e.stringChild},componentInfoObjects:t}).setValue.parsedExpression.tree,dependencyValues:{booleanChildrenByCode:{},booleanListChildrenByCode:{},textChildrenByCode:{},textListChildrenByCode:{},mathChildrenByCode:{},mathListChildrenByCode:{},numberChildrenByCode:{},numberListChildrenByCode:{},otherChildrenByCode:{}},valueOnInvalid:e.valueOnNaN})}else n=e.valueOnNaN;else n?.re===1/0||n?.re===-1/0||n?.im===1/0||n?.im===-1/0?n=numberToMathExpression(n).evaluate_to_constant():0===n?.im&&(n=n.re)}catch(t){n=e.valueOnNaN}return{setValue:{value:n}}}{let t=e.numberChild[0].stateValues.value;return Number.isNaN(t)&&(t=e.valueOnNaN),{setValue:{value:t}}}}if(null===e.parsedExpression)return{setValue:{value:e.valueOnNaN}};if(0===Object.keys(e.textChildrenByCode).length&&0===Object.keys(e.booleanChildrenByCode).length){let t,n=function(t){if("string"==typeof t){let n=e.mathChildrenByCode[t];return void 0!==n?n.stateValues.value.tree:(n=e.numberChildrenByCode[t],void 0!==n?numberToMathExpression(n.stateValues.value).tree:t)}return Array.isArray(t)?[t[0],...t.slice(1).map(n)]:t};try{t=me$3.fromAst(n(e.parsedExpression.tree)).evaluate_to_constant()}catch(n){t=e.valueOnNaN}if(!Number.isNaN(t)&&("number"==typeof t||"number"==typeof t?.re&&"number"==typeof t?.im))return t.re===1/0||t.re===-1/0||t.im===1/0||t.im===-1/0?t=numberToMathExpression(t).evaluate_to_constant():0===t.im&&(t=t.re),{setValue:{value:t}}}if(!e.convertBoolean)return{setValue:{value:e.valueOnNaN}};return(e=Object.assign({},e)).mathListChildrenByCode={},e.numberListChildrenByCode={},e.textListChildrenByCode={},e.booleanListChildrenByCode={},e.otherChildrenByCode={},{setValue:{value:evaluateLogic({logicTree:e.parsedExpression.tree,dependencyValues:e,valueOnInvalid:e.valueOnNaN})}}},set:function(e){if(null===e)return NaN;if("number"==typeof e||"number"==typeof e?.re&&"number"==typeof e?.im)return e;let t=Number(e);if(Number.isNaN(t))try{t=me$3.fromAst(textToAst$1.convert(e)).evaluate_to_constant(),null===t&&(t=NaN)}catch(e){t=NaN}return t},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,overrideFixed:r}){if(!await n.canBeModified&&!r)return{success:!1};let a,i=e.value;return i instanceof me$3.class?(i=i.evaluate_to_constant(),(Number.isNaN(i)||"number"!=typeof i&&("number"!=typeof i?.re||"number"!=typeof i?.im))&&(i=t.valueOnNaN)):(Number.isNaN(i)||"number"!=typeof i&&("number"!=typeof i?.re||"number"!=typeof i?.im))&&(i=Number(i),Number.isNaN(i)&&(i=t.valueOnNaN)),t.singleNumberOrStringChild?(a=0===t.numberChild.length?0===t.stringChild.length?[{setEssentialValue:"value",value:numberToMathExpression(i).evaluate_to_constant()}]:[{setDependency:"stringChild",desiredValue:numberToMathExpression(i).toString(),childIndex:0,variableIndex:0}]:[{setDependency:"numberChild",desiredValue:i,childIndex:0,variableIndex:0}],{success:!0,instructions:a}):t.singleMathChild?{success:!0,instructions:[{setDependency:"allChildren",desiredValue:numberToMathExpression(i),childIndex:0,variableIndex:0}]}:{success:!1}}},e.valueForDisplay={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:numberToMathExpression(e.value),dependencyValues:e,usedDefault:t}).evaluate_to_constant()}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{text:numberToMathExpression(e.valueForDisplay).toString(n)}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n=Number(e.text);if(Number.isFinite(n))return{success:!0,instructions:[{setDependency:"value",desiredValue:n}]};{let t,r=getFromText({parseScientificNotation:!1});try{t=r(e.text)}catch(e){return{success:!1}}return n=t.evaluate_to_constant(),Number.isFinite(n)?{success:!0,instructions:[{setDependency:"value",desiredValue:n}]}:{success:!1}}}},e.math=mathStateVariableFromNumberStateVariable({numberVariableName:"value",mathVariableName:"math",isPublic:!0}),e.math.shadowingInstructions.attributesToShadow=["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"}}),definition({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:numberToMathExpression(e.valueForDisplay).toLatex(n)}}}},e.canBeModified={returnDependencies:()=>({numberChildModifiable:{dependencyType:"child",childGroups:["numbers"],variableNames:["canBeModified"]},modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},singleMathChild:{dependencyType:"stateVariable",variableName:"singleMathChild"}}),definition:function({dependencyValues:e}){return!e.modifyIndirectly||e.fixed||!e.singleNumberOrStringChild&&!e.singleMathChild?{setValue:{canBeModified:!1}}:1!==e.numberChildModifiable.length||e.numberChildModifiable[0].stateValues.canBeModified?{setValue:{canBeModified:!0}}:{setValue:{canBeModified:!1}}}},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class Integer extends NumberComponent{static componentType="integer";static rendererType="number";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePreRound"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({valuePreRound:{dependencyType:"stateVariable",variableName:"valuePreRound"}}),set:function(e){if(null===e)return NaN;let t=Number(e);if(Number.isNaN(t))try{t=me$3.fromAst(textToAst.convert(e)).evaluate_to_constant(),null===t&&(t=NaN)}catch(e){t=NaN}return Math.round(t)},definition:({dependencyValues:e})=>({setValue:{value:Math.round(e.valuePreRound)}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.value;return t instanceof me$3.class?(t=t.evaluate_to_constant(),Number.isFinite(t)||(t=NaN)):t=Number(t),t=Math.round(t),{success:!0,instructions:[{setDependency:"valuePreRound",desiredValue:t}]}}},e}}const maxWidth=850,sizePossibilities=["tiny","small","medium","large","full"],widthFractions=[1/12,.3,.5,.7,1],fractionMidpoints=widthFractions.map(((e,t)=>(e+(widthFractions[t+1]||1/0))/2)),orderedWidthMidpoints=fractionMidpoints.map((e=>maxWidth*e)),orderedPercentWidthMidpoints=fractionMidpoints.map((e=>100*e)),widthsBySize={};sizePossibilities.forEach(((e,t)=>widthsBySize[e]=Math.floor(widthFractions[t]*maxWidth)));const percentWidthsBySize={};sizePossibilities.forEach(((e,t)=>percentWidthsBySize[e]=Math.round(100*widthFractions[t])));class Graph$1 extends BlockComponent{static componentType="graph";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.xmin={createComponentOfType:"number",createStateVariable:"xminPrelim",defaultValue:-10},e.xmax={createComponentOfType:"number",createStateVariable:"xmaxPrelim",defaultValue:10},e.ymin={createComponentOfType:"number",createStateVariable:"yminPrelim",defaultValue:-10},e.ymax={createComponentOfType:"number",createStateVariable:"ymaxPrelim",defaultValue:10},e.width={createComponentOfType:"_componentSize"},e.size={createComponentOfType:"text"},e.aspectRatio={createComponentOfType:"number"},e.height={createComponentOfType:"_componentSize"},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",validValues:["block","inline"],defaultValue:"block",forRenderer:!0,public:!0},e.horizontalAlign={createComponentOfType:"text",createStateVariable:"horizontalAlign",validValues:["center","left","right"],defaultValue:"center",forRenderer:!0,public:!0},e.identicalAxisScales={createPrimitiveOfType:"boolean",createStateVariable:"identicalAxisScales",defaultValue:!1,public:!0},e.displayXAxis={createComponentOfType:"boolean",createStateVariable:"displayXAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxis={createComponentOfType:"boolean",createStateVariable:"displayYAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayXAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayXAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayYAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.xlabel={createComponentOfType:"label"},e.xlabelPosition={createComponentOfType:"text",createStateVariable:"xlabelPosition",defaultValue:"right",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["right","left"]},e.xTickScaleFactor={createComponentOfType:"math",createStateVariable:"xTickScaleFactor",defaultValue:null,public:!0,forRenderer:!0},e.ylabel={createComponentOfType:"label"},e.ylabelPosition={createComponentOfType:"text",createStateVariable:"ylabelPosition",defaultValue:"top",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["top","bottom"]},e.ylabelAlignment={createComponentOfType:"text",createStateVariable:"ylabelAlignment",defaultValue:"left",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["left","right"]},e.yTickScaleFactor={createComponentOfType:"math",createStateVariable:"yTickScaleFactor",defaultValue:null,public:!0,forRenderer:!0},e.showNavigation={createComponentOfType:"boolean",createStateVariable:"showNavigation",defaultValue:!0,public:!0,forRenderer:!0},e.fixAxes={createComponentOfType:"boolean",createStateVariable:"fixAxes",defaultValue:!1,public:!0,forRenderer:!0},e.grid={createComponentOfType:"text"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"xlabels",componentTypes:["xlabel"]},{group:"ylabels",componentTypes:["ylabel"]},{group:"graphical",componentTypes:["_graphical","text","image","math","m","md","label"]},{group:"childrenThatShouldNotBeHere",componentTypes:["_base"],matchAfterAdapters:!0}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({xlabelAttr:{dependencyType:"attributeComponent",attributeName:"xlabel",variableNames:["value","hasLatex"]},xlabelChild:{dependencyType:"child",childGroups:["xlabels"],variableNames:["value","hasLatex"]}}),definition({dependencyValues:e}){if(e.xlabelChild.length>0){let t=e.xlabelChild[e.xlabelChild.length-1];return{setValue:{xlabel:t.stateValues.value,xlabelHasLatex:t.stateValues.hasLatex}}}return e.xlabelAttr?{setValue:{xlabel:e.xlabelAttr.stateValues.value,xlabelHasLatex:e.xlabelAttr.stateValues.hasLatex}}:{useEssentialOrDefaultValue:{xlabel:!0},setValue:{xlabelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.xlabel)return{success:!1};if(t.xlabelChild.length>0){let n=t.xlabelChild.length-1;return{success:!0,instructions:[{setDependency:"xlabelChild",desiredValue:e.xlabel,childIndex:n,variableIndex:0}]}}return{success:!0,instructions:[{setEssentialValue:"xlabel",value:e.xlabel}]}}},e.ylabel={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"ylabelHasLatex"}}},hasEssential:!0,defaultValue:"",additionalStateVariablesDefined:[{variableName:"ylabelHasLatex",forRenderer:!0}],returnDependencies:()=>({ylabelAttr:{dependencyType:"attributeComponent",attributeName:"ylabel",variableNames:["value","hasLatex"]},ylabelChild:{dependencyType:"child",childGroups:["ylabels"],variableNames:["value","hasLatex"]}}),definition({dependencyValues:e}){if(e.ylabelChild.length>0){let t=e.ylabelChild[e.ylabelChild.length-1];return{setValue:{ylabel:t.stateValues.value,ylabelHasLatex:t.stateValues.hasLatex}}}return e.ylabelAttr?{setValue:{ylabel:e.ylabelAttr.stateValues.value,ylabelHasLatex:e.ylabelAttr.stateValues.hasLatex}}:{useEssentialOrDefaultValue:{ylabel:!0},setValue:{ylabelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.ylabel)return{success:!1};if(t.ylabelChild.length>0){let n=t.ylabelChild.length-1;return{success:!0,instructions:[{setDependency:"ylabelChild",desiredValue:e.ylabel,childIndex:n,variableIndex:0}]}}return{success:!0,instructions:[{setEssentialValue:"ylabel",value:e.ylabel}]}}},e.graphicalDescendants={forRenderer:!0,returnDependencies:()=>({graphicalDescendants:{dependencyType:"descendant",componentTypes:["_graphical"]}}),definition:function({dependencyValues:e}){return{setValue:{graphicalDescendants:e.graphicalDescendants}}}},e.childIndicesToRender={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"]},allChildren:{dependencyType:"child",childGroups:["graphical","xlabels","ylabels","childrenThatShouldNotBeHere"]}}),definition({dependencyValues:e}){let t=[],n=e.graphicalChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())n.includes(a.componentName)&&t.push(r);return{setValue:{childIndicesToRender:t}}}},e.nChildrenAdded={defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{nChildrenAdded:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nChildrenAdded",value:e.nChildrenAdded}]})},e.size={public:!0,defaultValue:"medium",hasEssential:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({sizeAttr:{dependencyType:"attributeComponent",attributeName:"size",variableNames:["value"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]}}),definition({dependencyValues:e}){const t="medium";if(e.sizeAttr){let n=e.sizeAttr.stateValues.value.toLowerCase();return sizePossibilities.includes(n)||(n=t),{setValue:{size:n}}}if(e.widthAttr){let n=e.widthAttr.stateValues.componentSize;if(null===n)return{setValue:{size:t}};let r,{isAbsolute:a,size:i}=n;if(a){for(let[e,t]of orderedWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}else{for(let[e,t]of orderedPercentWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}return{setValue:{size:r}}}return{useEssentialOrDefaultValue:{size:!0}}}},e.width={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},returnDependencies:()=>({size:{dependencyType:"stateVariable",variableName:"size"}}),definition:({dependencyValues:e})=>({setValue:{width:{isAbsolute:!0,size:widthsBySize[e.size]}}})},e.aspectRatioFromAxisScales={returnDependencies:()=>({aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]}}),definition:({dependencyValues:e})=>(null!==e.heightAttr&&console.warn("Height attribute of graph is deprecated and is being ignored. Use aspectRatio attribute instead."),{setValue:{aspectRatioFromAxisScales:e.identicalAxisScales&&null===e.aspectRatioAttr},checkForActualChange:{aspectRatioFromAxisScales:!0}})},e.aspectRatio={public:!0,forRenderer:!0,defaultValue:1,hasEssential:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["aspectRatioFromAxisScales"],returnDependencies:({stateValues:e})=>e.aspectRatioFromAxisScales?{aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},yscale:{dependencyType:"stateVariable",variableName:"yscale"}}:{aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},width:{dependencyType:"stateVariable",variableName:"width"}},definition({dependencyValues:e}){if(e.aspectRatioFromAxisScales){return{setValue:{aspectRatio:e.xscale/e.yscale}}}if(null!==e.aspectRatioAttr){let t=e.aspectRatioAttr.stateValues.value;return Number.isFinite(t)||(t=1),{setValue:{aspectRatio:t}}}return{useEssentialOrDefaultValue:{aspectRatio:!0}}}},e.xmin={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xminPrelim:{dependencyType:"stateVariable",variableName:"xminPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{xmin:e.xminPrelim}};if(!t.xminPrelim)return{setValue:{xmin:e.xminPrelim}};let n=!t.xmaxPrelim,r=!t.yminPrelim,a=!t.ymaxPrelim;if(r&&a){let t=e.aspectRatio,r=(e.ymaxPrelim-e.yminPrelim)*t;return n?{setValue:{xmin:e.xmaxPrelim-r}}:{setValue:{xmin:-r/2}}}return n?{setValue:{xmin:e.xmaxPrelim-20}}:{setValue:{xmin:-10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xminPrelim",desiredValue:e.xmin}]}},e.xmax={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xmaxPrelim:{dependencyType:"stateVariable",variableName:"xmaxPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{xmax:e.xmaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,o=a&&i,s=n&&r,l=e.xminPrelim;if(o){let t=e.aspectRatio,a=(e.ymaxPrelim-e.yminPrelim)*t;if(s){let t=e.xmaxPrelim-l;return{setValue:{xmax:l+Math.max(t,a)}}}return n?{setValue:{xmax:l+a}}:r?{setValue:{xmax:e.xmaxPrelim}}:{setValue:{xmax:a/2}}}return r?{setValue:{xmax:e.xmaxPrelim}}:n?{setValue:{xmax:l+20}}:{setValue:{xmax:10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xmaxPrelim",desiredValue:e.xmax}]}},e.ymin={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},yminPrelim:{dependencyType:"stateVariable",variableName:"yminPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{ymin:e.yminPrelim}};if(!t.yminPrelim)return{setValue:{ymin:e.yminPrelim}};let n=!t.ymaxPrelim,r=!t.xminPrelim,a=!t.xmaxPrelim,i=r&&a,o=e.aspectRatio;if(i){let t=(e.xmaxPrelim-e.xminPrelim)/o;return n?{setValue:{ymin:e.ymaxPrelim-t}}:{setValue:{ymin:-t/2}}}return n?{setValue:{ymin:e.ymaxPrelim-20/o}}:{setValue:{ymin:-10/o}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"yminPrelim",desiredValue:e.ymin}]}},e.ymax={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},ymaxPrelim:{dependencyType:"stateVariable",variableName:"ymaxPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{ymax:e.ymaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,o=a&&i,s=n&&r,l=e.yminPrelim,u=e.aspectRatio;if(s){let t=(e.xmaxPrelim-e.xminPrelim)/u;if(o){let n=e.ymaxPrelim-l;return{setValue:{ymax:l+Math.max(n,t)}}}return a?{setValue:{ymax:l+t}}:i?{setValue:{ymax:e.ymaxPrelim}}:{setValue:{ymax:t/2}}}return i?{setValue:{ymax:e.ymaxPrelim}}:a?{setValue:{ymax:l+20/u}}:{setValue:{ymax:10/u}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"ymaxPrelim",desiredValue:e.ymax}]}},e.xscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({xmin:{dependencyType:"stateVariable",variableName:"xmin"},xmax:{dependencyType:"stateVariable",variableName:"xmax"}}),definition:({dependencyValues:e})=>({setValue:{xscale:e.xmax-e.xmin}})},e.yscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({ymin:{dependencyType:"stateVariable",variableName:"ymin"},ymax:{dependencyType:"stateVariable",variableName:"ymax"}}),definition:({dependencyValues:e})=>({setValue:{yscale:e.ymax-e.ymin}})},e.gridAttrCompName={returnDependencies:()=>({gridAttr:{dependencyType:"attributeComponent",attributeName:"grid"}}),definition:({dependencyValues:e})=>e.gridAttr?{setValue:{gridAttrCompName:e.gridAttr.componentName}}:{setValue:{gridAttrCompName:null}}},e.gridAttrCompChildren={stateVariablesDeterminingDependencies:["gridAttrCompName"],returnDependencies:({stateValues:e})=>e.gridAttrCompName?{gridAttrCompChildren:{dependencyType:"child",parentName:e.gridAttrCompName,childGroups:["textLike"],variableNames:["value"]}}:{},definition:({dependencyValues:e})=>e.gridAttrCompChildren?{setValue:{gridAttrCompChildren:e.gridAttrCompChildren}}:{setValue:{gridAttrCompChildren:null}}},e.grid={public:!0,shadowingInstructions:{hasVariableComponentType:!0,attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,stateVariablesDeterminingDependencies:["gridAttrCompChildren"],returnDependencies({stateValues:e}){if(e.gridAttrCompChildren){let t={gridAttrCompChildren:{dependencyType:"stateVariable",variableName:"gridAttrCompChildren"},gridAttr:{dependencyType:"attributeComponent",attributeName:"grid",variableNames:["value"]}};for(let[n,r]of e.gridAttrCompChildren.entries())t["childAdapter"+n]={dependencyType:"adapterSourceStateVariable",componentName:r.componentName,variableName:"value"};return t}return{}},definition({dependencyValues:e}){if(!e.gridAttrCompChildren)return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};let t=e.gridAttr.stateValues.value.toLowerCase().trim();if("true"===t?t="medium":"false"===t&&(t="none"),["medium","dense","none"].includes(t))return{setValue:{grid:t},setCreateComponentOfType:{grid:"text"}};let n=[],r=[];for(let t of e.gridAttrCompChildren)if("string"!=typeof t)r.push(t);else{let e=t.split(/\s+/),a=e[0];""===a?r.length>0&&(n.push(r),r=[]):r.push(a);for(let t of e.slice(1))r.length>0&&(n.push(r),r=[]),""!==t&&r.push(t)}if(r.length>0&&n.push(r),n.length<2)return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t=[];for(let r of n)if(1===r.length){let n=r[0];if("string"==typeof n){let e=me$3.fromText(n).evaluate_to_constant();if(!(e>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(e)}else{let r=e.gridAttrCompChildren.indexOf(n),a=e["childAdapter"+r];if(a instanceof me$3.class&&(a=a.evaluate_to_constant()),!(a>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(a)}}else{let n=1;for(let t of r)if("string"==typeof t)n*=me$3.fromText(t).evaluate_to_constant();else{let r=e.gridAttrCompChildren.indexOf(t),a=e["childAdapter"+r];a instanceof me$3.class&&(a=a.evaluate_to_constant()),n*=a}if(!(n>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(n)}return{setValue:{grid:t},setCreateComponentOfType:{grid:"numberList"}}}},e}async changeAxisLimits({xmin:e,xmax:t,ymin:n,ymax:r,actionId:a}){let i=[];return void 0!==e&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmin",value:e}),void 0!==t&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmax",value:t}),void 0!==n&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymin",value:n}),void 0!==r&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymax",value:r}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{xmin:e,xmax:t,ymin:n,ymax:r}}})}async addChildren({serializedComponents:e,actionId:t}){if(e&&e.length>0){let n=processAssignNames({serializedComponents:e,parentName:this.componentName,parentCreatesNewNamespace:this.attributes.newNamespace?.primitive,componentInfoObjects:this.componentInfoObjects,indOffset:await this.stateValues.nChildrenAdded});return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"addComponents",serializedComponents:n.serializedComponents,parentName:this.componentName,assignNamesOffset:await this.stateValues.nChildrenAdded},{updateType:"updateValue",componentName:this.componentName,stateVariable:"nChildrenAdded",value:await this.stateValues.nChildrenAdded+n.serializedComponents.length}],actionId:t})}this.coreFunctions.resolveAction({actionId:t})}async deleteChildren({number:e,actionId:t}){let n=Math.min(e,await this.stateValues.nChildrenAdded);if(n>0){let e=this.definingChildren.length,r=this.definingChildren.slice(e-n,e).map((e=>e.componentName));return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"deleteComponents",componentNames:r},{updateType:"updateValue",componentName:this.componentName,stateVariable:"nChildrenAdded",value:await this.stateValues.nChildrenAdded-n}],actionId:t})}this.coreFunctions.resolveAction({actionId:t})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={changeAxisLimits:this.changeAxisLimits.bind(this),addChildren:this.addChildren.bind(this),deleteChildren:this.deleteChildren.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class Variables extends MathList{static componentType="variables";static stateVariableForAttributeValue="variables";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();e.variables={public:!0,shadowingInstructions:{createComponentOfType:"variable"},isArray:!0,entryPrefixes:["var"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={math:{dependencyType:"stateVariable",variableName:"math"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].math;return{setValue:{variables:n}}}};let t=this.componentType;return e.validVariables={returnDependencies:()=>({variables:{dependencyType:"stateVariable",variableName:"variables"}}),definition:function({dependencyValues:e}){let n=[];for(let r of e.variables){let e=isValidVariable(r);e||(console.warn("Invalid value for "+t),e=!1),n.push(e)}return{setValue:{validVariables:n}}}},e}}class Variable extends MathComponent{static componentType="variable";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.validVariable={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){let t=isValidVariable(e.value);return t||console.warn("Invalid value of a "+this.componentType),{setValue:{validVariable:t}}}},e}}class Interval extends MathComponent{static componentType="interval";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return delete e.createIntervals,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.createIntervals={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({}),definition:()=>({setValue:{createIntervals:!0}})},e}}class Group extends Template{static componentType="group";static renderedDefault=!0}class Option$1 extends Group{static componentType="option";static renderedDefault=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.selectForVariants={createComponentOfType:"textListFromString",createStateVariable:"selectForVariants",defaultValue:[],public:!0},e.selectWeight={createComponentOfType:"number",createStateVariable:"selectWeight",defaultValue:1,public:!0},e}}class Sequence extends CompositeComponent{static componentType="sequence";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();e.fixed={leaveRaw:!0},e.displayDigits={leaveRaw:!0},e.displayDecimals={leaveRaw:!0},e.displaySmallAsZero={leaveRaw:!0},e.padZeros={leaveRaw:!0};let t=returnStandardSequenceAttributes();return Object.assign(e,t),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStandardSequenceStateVariableDefinitions();return Object.assign(e,t),e.readyToExpandWhenResolved={returnDependencies:()=>({from:{dependencyType:"stateVariable",variableName:"from"},length:{dependencyType:"stateVariable",variableName:"length"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"},exclude:{dependencyType:"stateVariable",variableName:"exclude"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r}){if(!await e.stateValues.validSequence)return t.lastReplacementParameters={from:null,length:null,step:null,type:null,exclude:null},{replacements:[]};let a=await e.stateValues.from,i=await e.stateValues.length,o=await e.stateValues.step,s=await e.stateValues.type,l=await e.stateValues.exclude;t.lastReplacementParameters={from:a,length:i,step:o,type:s,exclude:l};let u=e.attributes.newNamespace?.primitive,c=returnSequenceValues({from:a,step:o,length:i,exclude:l,type:s,lowercase:await e.stateValues.lowercase}),p=s;"letters"===s&&(p="text");let d=[],m={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(m[t]=e.attributes[t]);for(let e of c){let t={};Object.keys(m).length>0&&(t=convertAttributesForComponentType({attributes:m,componentType:p,componentInfoObjects:n,compositeCreatesNewNamespace:u,flags:r}));let a={componentType:p,attributes:t,state:{value:e,fixed:!0}};d.push(a)}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:d,parentName:e.componentName,parentCreatesNewNamespace:u,componentInfoObjects:n}).serializedComponents}}static async calculateReplacementChanges({component:e,workspace:t,componentInfoObjects:n,flags:r}){let a=t.lastReplacementParameters,i=[];if(!await e.stateValues.validSequence){let t=e.replacementsToWithhold;if(t||(t=0),e.replacements.length-t>0){let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:e.replacements.length};i.push(t)}return a.length=0,i}let o=await e.stateValues.from,s=await e.stateValues.length,l=await e.stateValues.step,u=await e.stateValues.type,c=await e.stateValues.exclude,p=await e.stateValues.lowercase;if(a.type!==u||a.exclude.length>0||c.length>0){let a=(await this.createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r})).replacements,o={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:a,replacementsToWithhold:0};i.push(o)}else{let t=!1;"math"===u?o.equals(a.from)&&l.equals(a.step)||(t=!0):o===a.from&&l===a.step||(t=!0);let c,d=a.length,m=0,f=0,h=d;if(sd&&(m=s-d,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=m){c=e.replacementsToWithhold-m,f+=m,d+=m,m=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:c};i.push(t)}else m-=e.replacementsToWithhold,f+=e.replacementsToWithhold,d+=e.replacementsToWithhold,c=0;if(!0===t&&(f=d,h=0),f>0)for(let t=h;t0){let t=[],a=e.attributes.newNamespace?.primitive,s={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(s[t]=e.attributes[t]);for(let i=d;i0&&(m=convertAttributesForComponentType({attributes:s,componentType:d,componentInfoObjects:n,compositeCreatesNewNamespace:a,flags:r}));let f={componentType:d,attributes:m,state:{value:c,fixed:!0}};t.push(f)}let c={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:d,serializedReplacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:n,indOffset:d}).serializedComponents,replacementsToWithhold:0,assignNamesOffset:d};i.push(c)}}return a.type=u,a.from=o,a.length=s,a.step=l,a.exclude=c,i}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes,t="number";this.attributes.type&&this.attributes.type.primitive&&(t=this.attributes.type.primitive);let n=this.componentInfoObjects.allComponentClasses["letters"===t?"text":t].rendererType;return e.includes(n)||e.push(n),e}}class Map$1 extends CompositeComponent{static componentType="map";static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.behavior={createComponentOfType:"text",createStateVariable:"behavior",defaultValue:"combination",public:!0,trim:!0},e.isResponse={leaveRaw:!0},e}static returnChildGroups(){return[{group:"templates",componentTypes:["template"]},{group:"sources",componentTypes:["sources"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nSources={additionalStateVariablesDefined:["sourcesNames","sourceAliases","sourceIndexAliases"],returnDependencies:()=>({sourcesChildren:{dependencyType:"child",childGroups:["sources"],variableNames:["alias","indexAlias"]}}),definition:function({dependencyValues:e}){return{setValue:{nSources:e.sourcesChildren.length,sourcesNames:e.sourcesChildren.map((e=>e.componentName)),sourceAliases:e.sourcesChildren.map((e=>e.stateValues.alias)),sourceIndexAliases:e.sourcesChildren.map((e=>e.stateValues.indexAlias))}}}},e.nIterates={additionalStateVariablesDefined:["minNIterates","sourcesChildNames"],returnDependencies:()=>({sourcesChildren:{dependencyType:"child",childGroups:["sources"],variableNames:["numberOfChildren","childComponentNames"]}}),definition:function({dependencyValues:e}){let t=e.sourcesChildren.map((e=>e.stateValues.numberOfChildren)),n=Math.min(...t),r=e.sourcesChildren.map((e=>[...e.stateValues.childComponentNames]));return{setValue:{nIterates:t,minNIterates:n,sourcesChildNames:r}}}},e.template={returnDependencies:()=>({templateChild:{dependencyType:"child",childGroups:["templates"],variableNames:["serializedChildren","newNamespace"]}}),definition:function({dependencyValues:e}){let t=e.templateChild[0];if(!t)return{setValue:{template:null}};let n={componentType:"template",state:{rendered:!0},children:t.stateValues.serializedChildren,originalName:t.componentName};return t.stateValues.newNamespace&&(n.attributes={newNamespace:{primitive:!0}}),{setValue:{template:n}}}},e.validBehavior={returnDependencies:()=>({behavior:{dependencyType:"stateVariable",variableName:"behavior"},nIterates:{dependencyType:"stateVariable",variableName:"nIterates"}}),definition:function({dependencyValues:e}){let t=!0;return"parallel"===e.behavior?e.nIterates.slice(1).some((t=>t!=e.nIterates[0]))&&console.warn("Warning: map with parallel behavior and different numbers of iterates in sources activeChildren. Extra iterates will be ignored."):"combination"!==e.behavior&&(console.warn("Invalid map behavior: "+e.behavior),t=!1),{setValue:{validBehavior:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({validBehavior:{dependencyType:"stateVariable",variableName:"validBehavior"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r}){if(!await e.stateValues.validBehavior)return t.lastReplacementParameters={sourcesNames:[],sourcesChildNames:[],behavior:void 0,nIterates:void 0,minNIterates:void 0},{replacements:[]};t.lastReplacementParameters={sourcesNames:await e.stateValues.sourcesNames,sourcesChildNames:await e.stateValues.sourcesChildNames,behavior:await e.stateValues.behavior,nIterates:await e.stateValues.nIterates,minNIterates:await e.stateValues.minNIterates,replacementsToWithhold:0,withheldSubstitutionChildNames:[]};let a=[];if("parallel"===await e.stateValues.behavior)for(let t=0;t=c-1){r++;let t=[deepClone(p)],n={};n=convertAttributesForComponentType({attributes:e.attributes,componentType:t[0].componentType,componentInfoObjects:a,compositeAttributesObj:d,compositeCreatesNewNamespace:l,flags:i}),t[0].attributes||(t[0].attributes={}),Object.assign(t[0].attributes,n),!t[0].attributes.newNamespace?.primitive&&t[0].children&&markToCreateAllUniqueNames(t[0].children);let u=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:l,componentInfoObjects:a,indOffset:r}).serializedComponents[0];await addSharedParameters(u,e,s),o.push(u)}else{let n=await this.recurseThroughCombinations({component:e,sourcesNumber:t+1,childnumberArray:s,iterateNumber:r,componentInfoObjects:a,flags:i});o.push(...n.replacements),r=n.iterateNumber}return{replacements:o,iterateNumber:r}}static async calculateReplacementChanges({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a}){let i=[];if(!await e.stateValues.validBehavior){if(n.lastReplacementParameters={sourcesNames:[],sourcesChildNames:[],behavior:void 0,nIterates:void 0,minNIterates:void 0,replacementsToWithhold:0,withheldSubstitutionChildNames:[]},e.replacements.length>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToDelete:e.replacements.length,replacementsToWithhold:0};i.push(t)}return i}let o=n.lastReplacementParameters,s=!1,l=!0,u=await e.stateValues.nSources,c=await e.stateValues.sourcesNames;if(u!==o.sourcesNames.length)l=!1;else for(let e=0;e1&&(s=!0)}else s=!0;if(s){let t=await this.createSerializedReplacements({component:e,workspace:n,componentInfoObjects:r,flags:a}).replacements,o={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:t,replacementsToWithhold:0};return i.push(o),n.lastReplacementParameters={sourcesNames:c,sourcesChildNames:d,behavior:m,nIterates:p,minNIterates:await e.stateValues.minNIterates,replacementsToWithhold:0,withheldSubstitutionChildNames:[]},i}let f=await e.stateValues.minNIterates,h=o.minNIterates,y=0,b=e.replacementsToWithhold;b||(b=0);let g=o.withheldSubstitutionChildNames,v=!1;if(fh){let t=f-h;if(b>0)if(b>=t){y=b-t,t=0;let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:y};i.push(e)}else t-=b,h+=b,y=0;if(t>0){let t=[];for(let n=h;nr?{success:!1}:{success:!0,desiredVariant:{index:t}}}}async function addSharedParameters(e,t,n){let r=e.doenetAttributes.addToSharedParameters=[],a=await t.stateValues.sourcesNames;for(let[e,i]of(await t.stateValues.sourceAliases).entries())if(i){let t=a[e];r.push({parameterName:"sourceNameMappings",key:i,value:{name:t,childNumber:n[e]}})}for(let[e,a]of(await t.stateValues.sourceIndexAliases).entries())a&&r.push({parameterName:"sourceIndexMappings",key:a,value:n[e]+1})}class Sources extends BaseComponent{static componentType="sources";static rendererType="containerInline";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.alias={createPrimitiveOfType:"string",validationFunction:function(e){if(!/[a-zA-Z_]/.test(e.substring(0,1)))throw Error("All aliases must begin with a letter or an underscore");if(!/^[a-zA-Z0-9_\-]+$/.test(e))throw Error("Aliases can contain only letters, numbers, hyphens, and underscores");return e}},e.indexAlias={createPrimitiveOfType:"string",validationFunction:function(e){if(!/[a-zA-Z_]/.test(e.substring(0,1)))throw Error("All index aliases must begin with a letter or an underscore");if(!/^[a-zA-Z0-9_\-]+$/.test(e))throw Error("Index aliases can contain only letters, numbers, hyphens, and underscores");return e}},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.alias={returnDependencies:()=>({alias:{dependencyType:"attributePrimitive",attributeName:"alias"}}),definition:({dependencyValues:e})=>({setValue:{alias:e.alias}})},e.indexAlias={returnDependencies:()=>({indexAlias:{dependencyType:"attributePrimitive",attributeName:"indexAlias"}}),definition:({dependencyValues:e})=>({setValue:{indexAlias:e.indexAlias}})},e.numberOfChildren={additionalStateVariablesDefined:["childComponentNames","childIdentities"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"]}}),definition:function({dependencyValues:e}){let t=e.children.length,n=e.children.map((e=>e.componentName));return{setValue:{numberOfChildren:t,childComponentNames:n,childIdentities:e.children}}}},e}}class Slider extends BaseComponent{constructor(e){super(e),this.changeValue=this.changeValue.bind(this),this.actions={changeValue:this.changeValue}}static componentType="slider";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultValue:"number",toLowerCase:!0,validValues:["number","text"],forRenderer:!0},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:300,isAbsolute:!0},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:100,isAbsolute:!0},public:!0,forRenderer:!0},e.initialValue={createComponentOfType:"_componentWithSelectableType",createStateVariable:"initialValue",defaultValue:null},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showControls={createComponentOfType:"boolean",createStateVariable:"showControls",defaultValue:!1,public:!0,forRenderer:!0},e.showTicks={createComponentOfType:"boolean",createStateVariable:"showTicks",defaultValue:!0,public:!0,forRenderer:!0},e.showValue={createComponentOfType:"boolean",createStateVariable:"showValue",defaultValue:!0,public:!0,forRenderer:!0},e.from={createComponentOfType:"number",createStateVariable:"from",defaultValue:0,public:!0,forRenderer:!0},e.to={createComponentOfType:"number",createStateVariable:"to",defaultValue:10,public:!0,forRenderer:!0},e.step={createComponentOfType:"number",createStateVariable:"step",defaultValue:1,public:!0,forRenderer:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"_componentWithSelectableType"},e}static returnChildGroups(){return[{group:"numbersTexts",componentTypes:["number","text"]},{group:"markers",componentTypes:["markers"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({numberAndTextChildren:{dependencyType:"child",childGroups:["numbersTexts"],variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];if("text"===e.type)for(let r of e.numberAndTextChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"text"})?n.push(r.stateValues.value):n.push(r.stateValues.value.toString());else if(e.numberAndTextChildren.length>0){for(let r of e.numberAndTextChildren)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"}))n.push(r.stateValues.value);else{let e=Number(r.stateValues.value);Number.isFinite(e)&&n.push(e)}n.sort(((e,t)=>e-t))}return{setValue:{items:n},setCreateComponentOfType:{items:e.type}}}},e.nItems={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},to:{dependencyType:"stateVariable",variableName:"to"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t=e.items.length;return 0===t&&"number"===e.type&&(t=Math.floor((e.to-e.from)/e.step+1e-10)+1,t>=0&&Number.isFinite(t)||(t=0)),{setValue:{nItems:t}}}},e.firstItem={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t;return t=e.items.length>0?e.items[0]:"number"===e.type?e.from:null,{setValue:{firstItem:t}}}},e.lastItem={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},nItems:{dependencyType:"stateVariable",variableName:"nItems"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t;return t=e.items.length>0?e.items[e.items.length-1]:"number"===e.type?e.from+(e.nItems-1)*e.step:null,{setValue:{lastItem:t}}}},e.valueToIndex={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"}}),definition:function({dependencyValues:e}){let t={};for(let[n,r]of e.items.entries())t[r]=n;return{setValue:{valueToIndex:t}}}},e.preliminaryValue={hasEssential:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},initialValue:{dependencyType:"stateVariable",variableName:"initialValue"},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]}}),definition:({dependencyValues:e})=>e.bindValueTo?{setValue:{preliminaryValue:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{preliminaryValue:{get defaultValue(){return e.initialValue}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.preliminaryValue,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"preliminaryValue",value:e.preliminaryValue}]}},e.index={forRenderer:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},valueToIndex:{dependencyType:"stateVariable",variableName:"valueToIndex"},items:{dependencyType:"stateVariable",variableName:"items"},preliminaryValue:{dependencyType:"stateVariable",variableName:"preliminaryValue"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"},nItems:{dependencyType:"stateVariable",variableName:"nItems"}}),definition:function({dependencyValues:e}){let t=findIndexOfClosestValidValue(e);return void 0===t&&(t=0),{setValue:{index:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(0===t.items.length){let n=t.from,r=t.step,a=e.index;return Number.isInteger(a)&&(a>=0&&a({type:{dependencyType:"stateVariable",variableName:"type"},items:{dependencyType:"stateVariable",variableName:"items"},index:{dependencyType:"stateVariable",variableName:"index"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"}}),definition:function({dependencyValues:e}){let t;return t=e.items.length>0?e.items[e.index]:e.from+e.step*e.index,{setValue:{value:t},setCreateComponentOfType:{value:e.type}}},inverseDefinition:invertSliderValue},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t}).tree}}}},e.markers={forRenderer:!0,returnDependencies:()=>({markersChild:{dependencyType:"child",childGroups:["markers"],variableNames:["markerType","markers"]},type:{dependencyType:"stateVariable",variableName:"type"},items:{dependencyType:"stateVariable",variableName:"items"}}),definition:function({dependencyValues:e}){let t=[];if(e.markersChild.length>0){let n=e.markersChild[0].stateValues.markerType;"empty"===n?t=[...e.items]:n!==e.type?(console.warn("Markers type doesn't match slider type."),t=[]):t=e.markersChild[0].stateValues.markers}return{setValue:{markers:t}}}},e}async changeValue({value:e,transient:t,actionId:n}){if(!await this.stateValues.disabled)return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],transient:t,actionId:n}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],actionId:n,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:e,responseText:e.toString()}}});this.coreFunctions.resolveAction({actionId:n})}}function findIndexOfClosestValidValue({preliminaryValue:e,valueToIndex:t,type:n,items:r,from:a,step:i,nItems:o}){let s=e;if(0===r.length){if(!Number.isFinite(s))return;let e=Math.round((s-a)/i);return e>=0?er[e]?t:e;let n=Math.round((t+e)/2);return s>r[n]?u(n,t):u(e,n)},c=u();if(0!==c){let e=r[c-1],t=r[c];Math.abs(s-e)({textChildren:{dependencyType:"child",childGroups:["texts"]},numberChildren:{dependencyType:"child",childGroups:["numbers"]}}),definition:function({dependencyValues:e}){let t;return t=e.textChildren.length>0?"text":e.numberChildren.length>0?"number":"empty",{setValue:{markerType:t}}}},e.markers={public:!0,isArray:!0,shadowingInstructions:{hasVariableComponentType:!0},entryPrefixes:["item"],returnDependencies:()=>({markerType:{dependencyType:"stateVariable",variableName:"markerType"},textChildren:{dependencyType:"child",childGroups:["texts"],variableNames:["value"]},numberChildren:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]}}),definition:function({dependencyValues:e}){let t=[],n=e.markerType;return"text"===e.markerType?t=e.textChildren.map((e=>e.stateValues.value)):"number"===e.markerType?(t=e.numberChildren.map((e=>e.stateValues.value)),t.sort(((e,t)=>e-t))):n="text",{setValue:{markers:t},setCreateComponentOfType:{markers:n}}}},e}}function applyConstraintFromComponentConstraints({variables:e,applyComponentConstraint:t,scales:n}){let r={},a=!1;for(let i in e){let o=t({variables:{[i]:e[i]},scales:n});o.constrained&&(a=!0,r[i]=o.variables[i])}return a?{constrained:a,variables:r}:{}}class Constraints extends BaseComponent{static componentType="constraints";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.baseOnGraph={createPrimitiveOfType:"string",createStateVariable:"baseOnGraph",defaultValue:null},e}static returnChildGroups(){return[{group:"constraints",componentTypes:["_constraint"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["independentComponentConstraints"]}}),definition:({dependencyValues:e})=>({setValue:{independentComponentConstraints:e.constraintChildren.every((e=>e.stateValues.independentComponentConstraints))}})},e.arrayEntryPrefixForConstraints={returnDependencies:()=>({arrayEntryPrefixForConstraints:{dependencyType:"parentStateVariable",variableName:"arrayEntryPrefixForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{arrayEntryPrefixForConstraints:e.arrayEntryPrefixForConstraints}})},e.arrayVariableForConstraints={returnDependencies:()=>({arrayVariableForConstraints:{dependencyType:"parentStateVariable",variableName:"arrayVariableForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{arrayVariableForConstraints:e.arrayVariableForConstraints}})},e.nDimensions={returnDependencies:()=>({nDimensions:{dependencyType:"parentStateVariable",variableName:"nDimensionsForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{nDimensions:e.nDimensions}})},e.graphComponentName={stateVariablesDeterminingDependencies:["baseOnGraph"],returnDependencies:({stateValues:e})=>e.baseOnGraph?{graphComponentName:{dependencyType:"expandTargetName",target:e.baseOnGraph}}:{},definition:({dependencyValues:e})=>e.graphComponentName?{setValue:{graphComponentName:e.graphComponentName}}:{setValue:{graphComponentName:null}}},e.scales={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["graphComponentName"],returnDependencies:({stateValues:e})=>e.graphComponentName?{graph:{dependencyType:"multipleStateVariables",componentName:e.graphComponentName,variableNames:["xscale","yscale"],variablesOptional:!0}}:{},definition({dependencyValues:e}){if(e.graph){let t=e.graph.stateValues,n=[t.xscale,t.yscale,1];if(n.every((e=>Number.isFinite(e)&&e>0)))return{setValue:{scales:n}}}return{setValue:{scales:[1,1,1]}}}},e.graphXmin={additionalStateVariablesDefined:["graphXmax","graphYmin","graphYmax"],stateVariablesDeterminingDependencies:["graphComponentName"],returnDependencies:({stateValues:e})=>e.graphComponentName?{graph:{dependencyType:"multipleStateVariables",componentName:e.graphComponentName,variableNames:["xmin","xmax","ymin","ymax"],variablesOptional:!0}}:{},definition({dependencyValues:e}){if(!e.graph)return{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}};let t=e.graph.stateValues.xmin,n=e.graph.stateValues.xmax,r=e.graph.stateValues.ymin,a=e.graph.stateValues.ymax;return[t,n,r,a].every(Number.isFinite)?{setValue:{graphXmin:t,graphXmax:n,graphYmin:r,graphYmax:a}}:{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}}}},e.constraintResults={additionalStateVariablesDefined:[{variableName:"constraintUsedByComponent",isArray:!0,entryPrefixes:["constraintUsedByComponent"]}],isArray:!0,entryPrefixes:["constraintResult"],stateVariablesDeterminingDependencies:["independentComponentConstraints","arrayEntryPrefixForConstraints","arrayVariableForConstraints"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0},independentComponentConstraints:{dependencyType:"stateVariable",variableName:"independentComponentConstraints"},scales:{dependencyType:"stateVariable",variableName:"scales"}},r=t.arrayEntryPrefixForConstraints,a={};if(t.independentComponentConstraints)for(let t of e)a[t]={x:{dependencyType:"parentStateVariable",variableName:r+(Number(t)+1)}};else{let e=t.arrayVariableForConstraints?t.arrayVariableForConstraints:"__null";n.xs={dependencyType:"parentStateVariable",variableName:e}}return{globalDependencies:n,dependenciesByKey:a}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(e.independentComponentConstraints){let r={},a={};for(let i of n){let n=Number(i)+1,o={["x"+n]:t[i].x},s=!1;for(let t of e.constraintChildren){let r=t.stateValues.applyComponentConstraint({variables:o,scales:e.scales});r.constrained&&(o["x"+n]=convertValueToMathExpression(r.variables["x"+n]),s=!0)}r[i]=o["x"+n],a[i]=s}return{setValue:{constraintResults:r,constraintUsedByComponent:a}}}{let t={},n=!1;for(let n in e.xs)t[`x${Number(n)+1}`]=e.xs[n];for(let r of e.constraintChildren){let a;if(a=r.stateValues.applyConstraint?r.stateValues.applyConstraint({variables:t,scales:e.scales}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:r.stateValues.applyComponentConstraint,scales:e.scales}),a.constrained){for(let e in a.variables)t[e]=convertValueToMathExpression(a.variables[e]);n=!0}}let r={},a={};for(let i in e.xs)r[i]=t[`x${Number(i)+1}`],a[i]=n;return{setValue:{constraintResults:r,constraintUsedByComponent:a}}}},inverseArrayDefinitionByKey:async function({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,stateValues:a,workspace:i}){if(t.independentComponentConstraints){let n=[];for(let a in e.constraintResults){let i=Number(a)+1,o={["x"+i]:convertValueToMathExpression(e.constraintResults[a])};for(let e of t.constraintChildren){let n=e.stateValues.applyComponentConstraint({variables:o,scales:t.scales});n.constrained&&(o["x"+i]=convertValueToMathExpression(n.variables["x"+i]))}n.push({setDependency:r[a].x,desiredValue:o["x"+i]})}return{success:!0,instructions:n}}{let n={};i.desiredConstraintResults||(i.desiredConstraintResults={}),Object.assign(i.desiredConstraintResults,e.constraintResults);let r=await a.constraintResults;for(let e in r){let t=Number(e)+1;e in i.desiredConstraintResults?n["x"+t]=convertValueToMathExpression(i.desiredConstraintResults[e]):n["x"+t]=convertValueToMathExpression(r[e])}for(let e of t.constraintChildren){let r;if(r=e.stateValues.applyConstraint?e.stateValues.applyConstraint({variables:n,scales:t.scales}):applyConstraintFromComponentConstraints({variables:n,applyComponentConstraint:e.stateValues.applyComponentConstraint,scales:t.scales}),r.constrained)for(let e in r.variables)n[e]=convertValueToMathExpression(r.variables[e])}let o={};for(let e in i.desiredConstraintResults)o[e]=n[`x${Number(e)+1}`];return{success:!0,instructions:[{setDependency:"xs",desiredValue:o}]}}}},e.constraintUsed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({constraintUsedByComponent:{dependencyType:"stateVariable",variableName:"constraintUsedByComponent"}}),definition:function({dependencyValues:e}){let t=Object.values(e.constraintUsedByComponent).some((e=>e));return{setValue:{constraintUsed:t}}}},e}}class ConstraintComponent extends BaseComponent{static componentType="_constraint";static rendererType=void 0;static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!1}})},e}}class ConstrainToGrid extends ConstraintComponent{static componentType="constrainToGrid";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0},e.dz={createComponentOfType:"number",createStateVariable:"dz",defaultValue:1,public:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0},e.zoffset={createComponentOfType:"number",createStateVariable:"zoffset",defaultValue:0,public:!0},e.ignoreGraphBounds={createComponentOfType:"boolean",createStateVariable:"ignoreGraphBounds",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!0}})},e.applyComponentConstraint={returnDependencies:()=>({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},ignoreGraphBounds:{dependencyType:"stateVariable",variableName:"ignoreGraphBounds"}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),"x1"in t){let n=findFiniteNumericalValue(t.x1);if(!Number.isFinite(n))return{};let a=e.dx,i=e.xoffset,o=Math.round((n-i)/a)*a+i;if(Number.isFinite(o)){if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphXmin,n=e.constraintAncestor.stateValues.graphXmax):"graph"===r&&(t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax),void 0!==t&&(on&&(o=Math.floor((n-i)/a)*a+i))}return{constrained:!0,variables:{x1:o}}}return{}}if("x2"in t){let n=findFiniteNumericalValue(t.x2);if(!Number.isFinite(n))return{};let a=e.dy,i=e.yoffset,o=Math.round((n-i)/a)*a+i;if(Number.isFinite(o)){if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphYmin,n=e.constraintAncestor.stateValues.graphYmax):"graph"===r&&(t=e.graphAncestor.stateValues.ymin,n=e.graphAncestor.stateValues.ymax),void 0!==t&&(on&&(o=Math.floor((n-i)/a)*a+i))}return{constrained:!0,variables:{x2:o}}}return{}}if("x3"in t){let n=findFiniteNumericalValue(t.x3);if(!Number.isFinite(n))return{};let r=e.dz,a=e.zoffset,i=Math.round((n-a)/r)*r+a;return Number.isFinite(i)?{constrained:!0,variables:{x3:i}}:{}}return{}}}})},e}}class ConstrainToGraph extends ConstraintComponent{static componentType="constrainToGraph";static createAttributesObject(){let e=super.createAttributesObject();return e.buffer={createComponentOfType:"number",createStateVariable:"buffer",defaultValue:.01,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!0}})},e.applyComponentConstraint={returnDependencies:()=>({constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},buffer:{dependencyType:"stateVariable",variableName:"buffer"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),!r)return{};if("x1"in t){let n,a,i=findFiniteNumericalValue(t.x1);if(!Number.isFinite(i))return{};if("constraints"===r?(n=e.constraintAncestor.stateValues.graphXmin,a=e.constraintAncestor.stateValues.graphXmax):(n=e.graphAncestor.stateValues.xmin,a=e.graphAncestor.stateValues.xmax),!Number.isFinite(n)||!Number.isFinite(a))return{};let o=n,s=a,l=e.buffer;if(l>0){let e=l*(a-n);o+=e,s-=e}return{constrained:!0,variables:{x1:Math.max(o,Math.min(s,i))}}}if("x2"in t){let n,a,i=findFiniteNumericalValue(t.x2);if(!Number.isFinite(i))return{};if("constraints"===r?(n=e.constraintAncestor.stateValues.graphYmin,a=e.constraintAncestor.stateValues.graphYmax):(n=e.graphAncestor.stateValues.ymin,a=e.graphAncestor.stateValues.ymax),!Number.isFinite(n)||!Number.isFinite(a))return{};let o=n,s=a,l=e.buffer;if(l>0){let e=l*(a-n);o+=e,s-=e}return{constrained:!0,variables:{x2:Math.max(o,Math.min(s,i))}}}return{}}}})},e}}class AttractToGrid extends ConstraintComponent{static componentType="attractToGrid";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0},e.dz={createComponentOfType:"number",createStateVariable:"dz",defaultValue:1,public:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0},e.zoffset={createComponentOfType:"number",createStateVariable:"zoffset",defaultValue:0,public:!0},e.xthreshold={createComponentOfType:"number",createStateVariable:"xthreshold",defaultValue:.2,public:!0},e.ythreshold={createComponentOfType:"number",createStateVariable:"ythreshold",defaultValue:.2,public:!0},e.zthreshold={createComponentOfType:"number",createStateVariable:"zthreshold",defaultValue:.2,public:!0},e.includeGridlines={createComponentOfType:"boolean",createStateVariable:"includeGridlines",defaultValue:!1,public:!0},e.ignoreGraphBounds={createComponentOfType:"boolean",createStateVariable:"ignoreGraphBounds",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({includeGridlines:{dependencyType:"stateVariable",variableName:"includeGridlines"}}),definition:({dependencyValues:e})=>({setValue:{independentComponentConstraints:e.includeGridlines}})},e.applyComponentConstraint={returnDependencies:()=>({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},xthreshold:{dependencyType:"stateVariable",variableName:"xthreshold"},ythreshold:{dependencyType:"stateVariable",variableName:"ythreshold"},zthreshold:{dependencyType:"stateVariable",variableName:"zthreshold"},constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},ignoreGraphBounds:{dependencyType:"stateVariable",variableName:"ignoreGraphBounds"}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),"x1"in t){let n=findFiniteNumericalValue(t.x1);if(!Number.isFinite(n))return{};let a=e.dx,i=e.xoffset,o=Math.round((n-i)/a)*a+i;if(!Number.isFinite(o))return{};if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphXmin,n=e.constraintAncestor.stateValues.graphXmax):"graph"===r&&(t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax),void 0!==t&&(on&&(o=Math.floor((n-i)/a)*a+i))}return Math.abs(n-o)n&&(o=Math.floor((n-i)/a)*a+i))}return Math.abs(n-o)({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},xthreshold:{dependencyType:"stateVariable",variableName:"xthreshold"},ythreshold:{dependencyType:"stateVariable",variableName:"ythreshold"},zthreshold:{dependencyType:"stateVariable",variableName:"zthreshold"},includeGridlines:{dependencyType:"stateVariable",variableName:"includeGridlines"},applyComponentConstraint:{dependencyType:"stateVariable",variableName:"applyComponentConstraint"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r={},a=!1;for(let i in t){let o=e.applyComponentConstraint({variables:{[i]:t[i]},scales:n});o.constrained&&(a=!0,r[i]=o.variables[i])}if(!a)return{};if(!e.includeGridlines){if(void 0!==t.x1&&void 0===r.x1)return{};if(void 0!==t.x2&&void 0===r.x2)return{};if(void 0!==t.x3&&void 0===r.x3)return{}}return{constrained:a,variables:r}}}})},e}}class ConstrainTo extends ConstraintComponent{static componentType="constrainTo";static returnChildGroups(){return[{group:"graphical",componentTypes:["_graphical"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nearestPointFunctions={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"],variableNames:["nearestPoint"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.graphicalChildren)n.stateValues.nearestPoint?t.push(n.stateValues.nearestPoint):console.warn(`cannot attract to ${n.componentName} as it doesn't have a nearestPoint state variable`);return{setValue:{nearestPointFunctions:t}}}},e.applyConstraint={returnDependencies:()=>({nearestPointFunctions:{dependencyType:"stateVariable",variableName:"nearestPointFunctions"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r=1/0,a={},i=!1,o={};for(let e in t)o[e]=findFiniteNumericalValue(t[e]);for(let s of e.nearestPointFunctions){let e=s({variables:t,scales:n});if(void 0===e)continue;let l={},u=0;if(void 0!==o.x1){if(void 0===e.x1)continue;l.x1=e.x1,u+=Math.pow(o.x1-e.x1,2)}if(void 0!==o.x2){if(void 0===e.x2)continue;l.x2=e.x2,u+=Math.pow(o.x2-e.x2,2)}if(void 0!==o.x3){if(void 0===e.x3)continue;l.x3=e.x3,u+=Math.pow(o.x3-e.x3,2)}u({thresholdAttr:{dependencyType:"attributeComponent",attributeName:"threshold",variableNames:["value"]},constraintsAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin"]}}),definition({dependencyValues:e}){if(e.thresholdAttr)return{setValue:{threshold:e.thresholdAttr.stateValues.value}};{let t=.02;return null!==e.constraintsAncestor&&null!==e.constraintsAncestor.stateValues.graphXmin||(t=.5),{useEssentialOrDefaultValue:{threshold:{defaultValue:t}}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.thresholdAttr?{success:!0,instructions:[{setDependency:"thresholdAttr",desiredValue:e.threshold}]}:{success:!0,instructions:[{setEssentialValue:"threshold",value:e.threshold}]}},e.nearestPointFunctions={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"],variableNames:["nearestPoint"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.graphicalChildren)n.stateValues.nearestPoint?t.push(n.stateValues.nearestPoint):console.warn(`cannot attract to ${n.componentName} as it doesn't have a nearestPoint state variable`);return{setValue:{nearestPointFunctions:t}}}},e.graphXscale={additionalStateVariablesDefined:["graphYscale"],returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["scales"]}}),definition({dependencyValues:e}){if(!e.graphAncestor)return{setValue:{graphXscale:null,graphYscale:null}};return{setValue:{graphXscale:e.graphAncestor.stateValues.xscale,graphYscale:e.graphAncestor.stateValues.yscale}}}},e.applyConstraint={returnDependencies:()=>({nearestPointFunctions:{dependencyType:"stateVariable",variableName:"nearestPointFunctions"},threshold:{dependencyType:"stateVariable",variableName:"threshold"},constraintsAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["scales"]}}),definition({dependencyValues:e}){let t=1,n=1;return e.constraintsAncestor&&([t,n]=e.constraintsAncestor.stateValues.scales),{setValue:{applyConstraint:function({variables:r,scales:a}){let i=1/0,o={},s={};for(let e in r)s[e]=findFiniteNumericalValue(r[e]);for(let l of e.nearestPointFunctions){let e=l({variables:r,scales:a});if(void 0===e)continue;let u={},c=0;if(void 0!==s.x1){if(void 0===e.x1)continue;u.x1=e.x1,c+=Math.pow((s.x1-e.x1)/t,2)}if(void 0!==s.x2){if(void 0===e.x2)continue;u.x2=e.x2,c+=Math.pow((s.x2-e.x2)/n,2)}if(void 0!==s.x3){if(void 0===e.x3)continue;u.x3=e.x3,c+=Math.pow(s.x3-e.x3,2)}ce.threshold*e.threshold?{}:{constrained:!0,variables:o}}}}}},e}}class ConstraintUnion extends ConstraintComponent{static componentType="constraintUnion";static returnChildGroups(){return[{group:"constraints",componentTypes:["_constraint"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.applyConstraint={returnDependencies:()=>({constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r;if(1===e.constraintChildren.length){let a=e.constraintChildren[0];return r=a.stateValues.applyConstraint?a.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:a.stateValues.applyComponentConstraint,scales:n}),r}let a,i=1/0,o={};for(let[s,l]of e.constraintChildren.entries()){if(r=l.stateValues.applyConstraint?l.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:l.stateValues.applyComponentConstraint,scales:n}),!r.constrained)continue;let e=0;for(let n in r.variables){let a=findFiniteNumericalValue(t[n]),i=findFiniteNumericalValue(r.variables[n]);if(!Number.isFinite(a)||!Number.isFinite(i)){e=1/0;break}e+=Math.pow(a-i,2)}e({constraintChild:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0},independentComponentConstraints:{dependencyType:"stateVariable",variableName:"independentComponentConstraints"},threshold:{dependencyType:"stateVariable",variableName:"threshold"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r,a=e.constraintChild[0];if(!a)return{};r=a.stateValues.applyConstraint?a.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:a.stateValues.applyComponentConstraint,scales:n});let i=0;for(let e in r.variables){let n=findFiniteNumericalValue(t[e]),a=findFiniteNumericalValue(r.variables[e]);if(!Number.isFinite(n)||!Number.isFinite(a))return{};i+=Math.pow(n-a,2)}return i>e.threshold*e.threshold?{}:r}}})},e}}class Intersection extends CompositeComponent{static componentType="intersection";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e}static returnChildGroups(){return[{group:"lines",componentTypes:["line"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.lineChildren={returnDependencies:()=>({lineChildren:{dependencyType:"child",childGroups:["lines"],variableNames:["numericalCoeff0","numericalCoeffvar1","numericalCoeffvar2","nDimensions"]}}),definition:({dependencyValues:e})=>({setValue:{lineChildren:e.lineChildren}})},e.readyToExpandWhenResolved={returnDependencies:()=>({lineChildren:{dependencyType:"stateVariable",variableName:"lineChildren"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n}){let r=await e.stateValues.lineChildren,a=r.length;if(0===a)return{replacements:[]};if(1===a){let a=r[0].componentName,i=await t[a].serialize({sourceAttributesToIgnoreRecursively:["isResponse"]});i.state||(i.state={}),i.state.draggable=!1,i.state.fixed=!0;let o=postProcessCopy({serializedComponents:[i],componentName:e.componentName}),s=e.attributes.newNamespace?.primitive;return o=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:o,parentName:e.componentName,parentCreatesNewNamespace:s,componentInfoObjects:n}).serializedComponents,{replacements:o}}if(a>2)return console.warn("Haven't implemented intersection for more than two objects"),{replacements:[]};let i=r[0],o=r[1];if(2!==i.stateValues.nDimensions||2!==o.stateValues.nDimensions)return console.log("Intersection of lines implemented only in 2D"),{replacements:[]};let s=i.stateValues.numericalCoeffvar1,l=i.stateValues.numericalCoeffvar2,u=i.stateValues.numericalCoeff0,c=o.stateValues.numericalCoeffvar1,p=o.stateValues.numericalCoeffvar2,d=o.stateValues.numericalCoeff0;if(!(Number.isFinite(s)&&Number.isFinite(l)&&Number.isFinite(u)&&Number.isFinite(c)&&Number.isFinite(p)&&Number.isFinite(d)))return console.log("Intersection of lines implemented only for constant coefficients"),{replacements:[]};let m=s*p-c*l;if(Math.abs(m)<1e-14){if(Math.abs(d*s-u*c)>1e-14)return{replacements:[]};if(0===s&&0===l&&0===u||0===c&&0===p&&0===d)return{replacements:[]};{let a=r[0].componentName,i=await t[a].serialize({sourceAttributesToIgnoreRecursively:["isResponse"]});i.state||(i.state={}),i.state.draggable=!1,i.state.fixed=!0;let o=postProcessCopy({serializedComponents:[i],componentName:e.componentName}),s=e.attributes.newNamespace?.primitive;return o=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:o,parentName:e.componentName,parentCreatesNewNamespace:s,componentInfoObjects:n}).serializedComponents,{replacements:o}}}let f=(d*l-u*p)/m,h=(u*c-d*s)/m,y=[{componentType:"point",state:{coords:me$3.fromAst(["vector",f,h]),draggable:!1,fixed:!0}}],b=e.attributes.newNamespace?.primitive;return y=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:y,parentName:e.componentName,parentCreatesNewNamespace:b,componentInfoObjects:n}).serializedComponents,{replacements:y}}static async calculateReplacementChanges({component:e,components:t,componentInfoObjects:n}){let r=[],a=(await this.createSerializedReplacements({component:e,components:t,componentInfoObjects:n})).replacements,i=a.length,o=!0;if(i===e.replacements.length){o=!1;for(let t=0;t({children:{dependencyType:"child",childGroups:["anything"],variableNames:["width"]},columns:{dependencyType:"stateVariable",variableName:"columns"}}),definition:function({dependencyValues:e}){let t=[],n=e.children.map((e=>e.stateValues.width));if(null!==e.columns){let r;if(-1!==e.columns.indexOf(","))r=e.columns.split(",").map(Number);else if(-1!==e.columns.indexOf("-")){let[t,n]=e.columns.split("-");r=[];for(let e=Number(t);e<=n;e++)r.push(e)}else r=[Number(e.columns)];let a={},i={};for(let e of r){let t=[],r=0;for(let a=0;ai&&(i=n[t]);t.push(i),r+=Number(i)}a[e]=t,i[e]=r}let o=-1;for(let e of r){let e=Number.POSITIVE_INFINITY,n=-1;for(let t of r)i[t]<=e&&t>o&&(e=i[t],n=t);e=this.state.threshold?{}:{variables:{x1:p,x2:d},constraintIndices:[i+1],constrained:!0}}}class ConditionalContent extends CompositeComponent{static componentType="conditionalContent";static includeBlankStringChildren=!0;static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static keepChildrenSerialized({serializedComponent:e,componentInfoObjects:t}){if(void 0===e.children)return[];let n=t.componentIsSpecifiedType,r=[];for(let[t,a]of e.children.entries())n(a,"case")||n(a,"else")||r.push(t);return r}static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.maximumNumberToShow={createComponentOfType:"number",createStateVariable:"maximumNumberToShow",defaultValue:null,public:!0},e.condition={createComponentOfType:"boolean"},e}static returnChildGroups(){return[{group:"cases",componentTypes:["case"]},{group:"elses",componentTypes:["else"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.baseConditionSatisfied={returnDependencies:()=>({conditionAttr:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t=!0;return e.conditionAttr&&(t=e.conditionAttr.stateValues.value),{setValue:{baseConditionSatisfied:t}}}},e.nCases={additionalStateVariablesDefined:["caseChildren"],returnDependencies:()=>({caseChildren:{dependencyType:"child",childGroups:["cases"]}}),definition:({dependencyValues:e})=>({setValue:{caseChildren:e.caseChildren,nCases:e.caseChildren.length}})},e.elseChild={returnDependencies:()=>({elseChild:{dependencyType:"child",childGroups:["elses"]}}),definition({dependencyValues:e}){let t=null;return e.elseChild.length>0&&(t=e.elseChild[0]),{setValue:{elseChild:t}}}},e.haveCasesOrElse={returnDependencies:()=>({nCases:{dependencyType:"stateVariable",variableName:"nCases"},elseChild:{dependencyType:"stateVariable",variableName:"elseChild"}}),definition:({dependencyValues:e})=>({setValue:{haveCasesOrElse:e.nCases>0||null!==e.elseChild}})},e.selectedIndices={returnDependencies:()=>({caseChildren:{dependencyType:"child",childGroups:["cases"],variableNames:["conditionSatisfied"]},elseChild:{dependencyType:"stateVariable",variableName:"elseChild"},maximumNumberToShow:{dependencyType:"stateVariable",variableName:"maximumNumberToShow"}}),definition({dependencyValues:e}){let t=[];for(let[n,r]of e.caseChildren.entries())r.stateValues.conditionSatisfied&&t.push(n);if(0===t.length&&e.elseChild&&t.push(e.caseChildren.length),null!==e.maximumNumberToShow&&t.length>e.maximumNumberToShow){let n=Math.max(0,Math.floor(e.maximumNumberToShow));t=t.slice(0,n)}return{setValue:{selectedIndices:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({baseConditionSatisfied:{dependencyType:"stateVariable",variableName:"baseConditionSatisfied"},haveCasesOrElse:{dependencyType:"stateVariable",variableName:"haveCasesOrElse"},selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r}){let a=await this.getReplacements(e,t,r);return n.previousSelectedIndices=[...await e.stateValues.selectedIndices],n.previousBaseConditionSatisfied=await e.stateValues.baseConditionSatisfied,{replacements:a}}static async getReplacements(e,t,n){if(!await e.stateValues.baseConditionSatisfied)return[];let r=[];if(await e.stateValues.haveCasesOrElse){let n=await e.stateValues.caseChildren;for(let[a,i]of(await e.stateValues.selectedIndices).entries()){let o,s,l;ie===i[t]))){if(r.previousBaseConditionSatisfied===o)return[];if(!o){let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:e.replacements.length};return r.previousBaseConditionSatisfied=o,[t]}if(e.replacements.length===e.serializedChildren.length){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};return r.previousBaseConditionSatisfied=o,[e]}}let s=[],l=await this.getReplacements(e,n,a),u={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:l,replacementsToWithhold:0};return s.push(u),r.previousSelectedIndices=[...i],r.previousBaseConditionSatisfied=o,s}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes;if(this.serializedChildren){let t=this.potentialRendererTypesFromSerializedComponents(this.serializedChildren);for(let n of t)e.includes(n)||e.push(n)}return e}}class AsList extends InlineComponent{static componentType="asList";static renderChildren=!0;static returnChildGroups(){return[{group:"inline",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.inlineChildren)"object"!=typeof n?t.push(n.toString()):"string"==typeof n.stateValues.text?t.push(n.stateValues.text):t.push("");return{setValue:{text:t.join(", ")}}}},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["text","latex"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.inlineChildren)"object"!=typeof n?t.push(n.toString()):"string"==typeof n.stateValues.latex?t.push(n.stateValues.latex):"string"==typeof n.stateValues.text?t.push(n.stateValues.text):t.push("");return{setValue:{latex:t.join(", ")}}}},e}}function normalizeIndex(e){if(null!==e&&""!==e){if(Number.isFinite(Number(e)))return Number(e)-1;if("string"==typeof e)return lettersToNumber(e)}}function lettersToNumber(e){let t=0,n=(e=e.toUpperCase()).length,r=n;for(;(r-=1)>-1;){let a=e.charCodeAt(r)-64;if(a<1||a>26)return void console.warn("Cannot convert "+e+" to a number");t+=a*Math.pow(26,n-1-r)}return t--,t}var check=function(e){return e&&e.Math==Math&&e},global$w=check("object"==typeof globalThis&&globalThis)||check("object"==typeof window&&window)||check("object"==typeof self&&self)||check("object"==typeof commonjsGlobal&&commonjsGlobal)||function(){return this}()||Function("return this")(),objectGetOwnPropertyDescriptor={},fails$G=function(e){try{return!!e()}catch(e){return!0}},fails$F=fails$G,descriptors=!fails$F((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),fails$E=fails$G,functionBindNative=!fails$E((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),NATIVE_BIND$4=functionBindNative,call$o=Function.prototype.call,functionCall=NATIVE_BIND$4?call$o.bind(call$o):function(){return call$o.apply(call$o,arguments)},objectPropertyIsEnumerable={},$propertyIsEnumerable$2={}.propertyIsEnumerable,getOwnPropertyDescriptor$5=Object.getOwnPropertyDescriptor,NASHORN_BUG=getOwnPropertyDescriptor$5&&!$propertyIsEnumerable$2.call({1:2},1);objectPropertyIsEnumerable.f=NASHORN_BUG?function(e){var t=getOwnPropertyDescriptor$5(this,e);return!!t&&t.enumerable}:$propertyIsEnumerable$2;var createPropertyDescriptor$5=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},NATIVE_BIND$3=functionBindNative,FunctionPrototype$3=Function.prototype,bind$c=FunctionPrototype$3.bind,call$n=FunctionPrototype$3.call,uncurryThis$I=NATIVE_BIND$3&&bind$c.bind(call$n,call$n),functionUncurryThis=NATIVE_BIND$3?function(e){return e&&uncurryThis$I(e)}:function(e){return e&&function(){return call$n.apply(e,arguments)}},uncurryThis$H=functionUncurryThis,toString$k=uncurryThis$H({}.toString),stringSlice$a=uncurryThis$H("".slice),classofRaw$1=function(e){return stringSlice$a(toString$k(e),8,-1)},uncurryThis$G=functionUncurryThis,fails$D=fails$G,classof$b=classofRaw$1,$Object$4=Object,split$1=uncurryThis$G("".split),indexedObject=fails$D((function(){return!$Object$4("z").propertyIsEnumerable(0)}))?function(e){return"String"==classof$b(e)?split$1(e,""):$Object$4(e)}:$Object$4,$TypeError$g=TypeError,requireObjectCoercible$b=function(e){if(null==e)throw $TypeError$g("Can't call method on "+e);return e},IndexedObject$4=indexedObject,requireObjectCoercible$a=requireObjectCoercible$b,toIndexedObject$b=function(e){return IndexedObject$4(requireObjectCoercible$a(e))},isCallable$q=function(e){return"function"==typeof e},isCallable$p=isCallable$q,isObject$o=function(e){return"object"==typeof e?null!==e:isCallable$p(e)},global$v=global$w,isCallable$o=isCallable$q,aFunction=function(e){return isCallable$o(e)?e:void 0},getBuiltIn$d=function(e,t){return arguments.length<2?aFunction(global$v[e]):global$v[e]&&global$v[e][t]},uncurryThis$F=functionUncurryThis,objectIsPrototypeOf=uncurryThis$F({}.isPrototypeOf),getBuiltIn$c=getBuiltIn$d,engineUserAgent=getBuiltIn$c("navigator","userAgent")||"",global$u=global$w,userAgent$6=engineUserAgent,process$3=global$u.process,Deno$1=global$u.Deno,versions=process$3&&process$3.versions||Deno$1&&Deno$1.version,v8=versions&&versions.v8,match,version;v8&&(match=v8.split("."),version=match[0]>0&&match[0]<4?1:+(match[0]+match[1])),!version&&userAgent$6&&(match=userAgent$6.match(/Edge\/(\d+)/),(!match||match[1]>=74)&&(match=userAgent$6.match(/Chrome\/(\d+)/),match&&(version=+match[1])));var engineV8Version=version,V8_VERSION$3=engineV8Version,fails$C=fails$G,nativeSymbol=!!Object.getOwnPropertySymbols&&!fails$C((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&V8_VERSION$3&&V8_VERSION$3<41})),NATIVE_SYMBOL$6=nativeSymbol,useSymbolAsUid=NATIVE_SYMBOL$6&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,getBuiltIn$b=getBuiltIn$d,isCallable$n=isCallable$q,isPrototypeOf$7=objectIsPrototypeOf,USE_SYMBOL_AS_UID$1=useSymbolAsUid,$Object$3=Object,isSymbol$5=USE_SYMBOL_AS_UID$1?function(e){return"symbol"==typeof e}:function(e){var t=getBuiltIn$b("Symbol");return isCallable$n(t)&&isPrototypeOf$7(t.prototype,$Object$3(e))},$String$4=String,tryToString$6=function(e){try{return $String$4(e)}catch(e){return"Object"}},isCallable$m=isCallable$q,tryToString$5=tryToString$6,$TypeError$f=TypeError,aCallable$a=function(e){if(isCallable$m(e))return e;throw $TypeError$f(tryToString$5(e)+" is not a function")},aCallable$9=aCallable$a,getMethod$5=function(e,t){var n=e[t];return null==n?void 0:aCallable$9(n)},call$m=functionCall,isCallable$l=isCallable$q,isObject$n=isObject$o,$TypeError$e=TypeError,ordinaryToPrimitive$1=function(e,t){var n,r;if("string"===t&&isCallable$l(n=e.toString)&&!isObject$n(r=call$m(n,e)))return r;if(isCallable$l(n=e.valueOf)&&!isObject$n(r=call$m(n,e)))return r;if("string"!==t&&isCallable$l(n=e.toString)&&!isObject$n(r=call$m(n,e)))return r;throw $TypeError$e("Can't convert object to primitive value")},shared$7={exports:{}},global$t=global$w,defineProperty$c=Object.defineProperty,defineGlobalProperty$3=function(e,t){try{defineProperty$c(global$t,e,{value:t,configurable:!0,writable:!0})}catch(n){global$t[e]=t}return t},global$s=global$w,defineGlobalProperty$2=defineGlobalProperty$3,SHARED="__core-js_shared__",store$3=global$s[SHARED]||defineGlobalProperty$2(SHARED,{}),sharedStore=store$3,store$2=sharedStore;(shared$7.exports=function(e,t){return store$2[e]||(store$2[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.24.1",mode:"global",copyright:"© 2014-2022 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.24.1/LICENSE",source:"https://github.com/zloirock/core-js"});var requireObjectCoercible$9=requireObjectCoercible$b,$Object$2=Object,toObject$e=function(e){return $Object$2(requireObjectCoercible$9(e))},uncurryThis$E=functionUncurryThis,toObject$d=toObject$e,hasOwnProperty$1=uncurryThis$E({}.hasOwnProperty),hasOwnProperty_1=Object.hasOwn||function(e,t){return hasOwnProperty$1(toObject$d(e),t)},uncurryThis$D=functionUncurryThis,id$2=0,postfix=Math.random(),toString$j=uncurryThis$D(1..toString),uid$4=function(e){return"Symbol("+(void 0===e?"":e)+")_"+toString$j(++id$2+postfix,36)},global$r=global$w,shared$6=shared$7.exports,hasOwn$l=hasOwnProperty_1,uid$3=uid$4,NATIVE_SYMBOL$5=nativeSymbol,USE_SYMBOL_AS_UID=useSymbolAsUid,WellKnownSymbolsStore$1=shared$6("wks"),Symbol$1=global$r.Symbol,symbolFor=Symbol$1&&Symbol$1.for,createWellKnownSymbol=USE_SYMBOL_AS_UID?Symbol$1:Symbol$1&&Symbol$1.withoutSetter||uid$3,wellKnownSymbol$q=function(e){if(!hasOwn$l(WellKnownSymbolsStore$1,e)||!NATIVE_SYMBOL$5&&"string"!=typeof WellKnownSymbolsStore$1[e]){var t="Symbol."+e;NATIVE_SYMBOL$5&&hasOwn$l(Symbol$1,e)?WellKnownSymbolsStore$1[e]=Symbol$1[e]:WellKnownSymbolsStore$1[e]=USE_SYMBOL_AS_UID&&symbolFor?symbolFor(t):createWellKnownSymbol(t)}return WellKnownSymbolsStore$1[e]},call$l=functionCall,isObject$m=isObject$o,isSymbol$4=isSymbol$5,getMethod$4=getMethod$5,ordinaryToPrimitive=ordinaryToPrimitive$1,wellKnownSymbol$p=wellKnownSymbol$q,$TypeError$d=TypeError,TO_PRIMITIVE=wellKnownSymbol$p("toPrimitive"),toPrimitive$2=function(e,t){if(!isObject$m(e)||isSymbol$4(e))return e;var n,r=getMethod$4(e,TO_PRIMITIVE);if(r){if(void 0===t&&(t="default"),n=call$l(r,e,t),!isObject$m(n)||isSymbol$4(n))return n;throw $TypeError$d("Can't convert object to primitive value")}return void 0===t&&(t="number"),ordinaryToPrimitive(e,t)},toPrimitive$1=toPrimitive$2,isSymbol$3=isSymbol$5,toPropertyKey$4=function(e){var t=toPrimitive$1(e,"string");return isSymbol$3(t)?t:t+""},global$q=global$w,isObject$l=isObject$o,document$3=global$q.document,EXISTS$1=isObject$l(document$3)&&isObject$l(document$3.createElement),documentCreateElement$2=function(e){return EXISTS$1?document$3.createElement(e):{}},DESCRIPTORS$i=descriptors,fails$B=fails$G,createElement$1=documentCreateElement$2,ie8DomDefine=!DESCRIPTORS$i&&!fails$B((function(){return 7!=Object.defineProperty(createElement$1("div"),"a",{get:function(){return 7}}).a})),DESCRIPTORS$h=descriptors,call$k=functionCall,propertyIsEnumerableModule$2=objectPropertyIsEnumerable,createPropertyDescriptor$4=createPropertyDescriptor$5,toIndexedObject$a=toIndexedObject$b,toPropertyKey$3=toPropertyKey$4,hasOwn$k=hasOwnProperty_1,IE8_DOM_DEFINE$1=ie8DomDefine,$getOwnPropertyDescriptor$2=Object.getOwnPropertyDescriptor;objectGetOwnPropertyDescriptor.f=DESCRIPTORS$h?$getOwnPropertyDescriptor$2:function(e,t){if(e=toIndexedObject$a(e),t=toPropertyKey$3(t),IE8_DOM_DEFINE$1)try{return $getOwnPropertyDescriptor$2(e,t)}catch(e){}if(hasOwn$k(e,t))return createPropertyDescriptor$4(!call$k(propertyIsEnumerableModule$2.f,e,t),e[t])};var objectDefineProperty={},DESCRIPTORS$g=descriptors,fails$A=fails$G,v8PrototypeDefineBug=DESCRIPTORS$g&&fails$A((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),isObject$k=isObject$o,$String$3=String,$TypeError$c=TypeError,anObject$k=function(e){if(isObject$k(e))return e;throw $TypeError$c($String$3(e)+" is not an object")},DESCRIPTORS$f=descriptors,IE8_DOM_DEFINE=ie8DomDefine,V8_PROTOTYPE_DEFINE_BUG$1=v8PrototypeDefineBug,anObject$j=anObject$k,toPropertyKey$2=toPropertyKey$4,$TypeError$b=TypeError,$defineProperty$1=Object.defineProperty,$getOwnPropertyDescriptor$1=Object.getOwnPropertyDescriptor,ENUMERABLE="enumerable",CONFIGURABLE$1="configurable",WRITABLE="writable";objectDefineProperty.f=DESCRIPTORS$f?V8_PROTOTYPE_DEFINE_BUG$1?function(e,t,n){if(anObject$j(e),t=toPropertyKey$2(t),anObject$j(n),"function"==typeof e&&"prototype"===t&&"value"in n&&WRITABLE in n&&!n[WRITABLE]){var r=$getOwnPropertyDescriptor$1(e,t);r&&r[WRITABLE]&&(e[t]=n.value,n={configurable:CONFIGURABLE$1 in n?n[CONFIGURABLE$1]:r[CONFIGURABLE$1],enumerable:ENUMERABLE in n?n[ENUMERABLE]:r[ENUMERABLE],writable:!1})}return $defineProperty$1(e,t,n)}:$defineProperty$1:function(e,t,n){if(anObject$j(e),t=toPropertyKey$2(t),anObject$j(n),IE8_DOM_DEFINE)try{return $defineProperty$1(e,t,n)}catch(e){}if("get"in n||"set"in n)throw $TypeError$b("Accessors not supported");return"value"in n&&(e[t]=n.value),e};var DESCRIPTORS$e=descriptors,definePropertyModule$6=objectDefineProperty,createPropertyDescriptor$3=createPropertyDescriptor$5,createNonEnumerableProperty$7=DESCRIPTORS$e?function(e,t,n){return definePropertyModule$6.f(e,t,createPropertyDescriptor$3(1,n))}:function(e,t,n){return e[t]=n,e},makeBuiltIn$2={exports:{}},DESCRIPTORS$d=descriptors,hasOwn$j=hasOwnProperty_1,FunctionPrototype$2=Function.prototype,getDescriptor=DESCRIPTORS$d&&Object.getOwnPropertyDescriptor,EXISTS=hasOwn$j(FunctionPrototype$2,"name"),PROPER=EXISTS&&"something"===function(){}.name,CONFIGURABLE=EXISTS&&(!DESCRIPTORS$d||DESCRIPTORS$d&&getDescriptor(FunctionPrototype$2,"name").configurable),functionName$1={EXISTS:EXISTS,PROPER:PROPER,CONFIGURABLE:CONFIGURABLE},uncurryThis$C=functionUncurryThis,isCallable$k=isCallable$q,store$1=sharedStore,functionToString$1=uncurryThis$C(Function.toString);isCallable$k(store$1.inspectSource)||(store$1.inspectSource=function(e){return functionToString$1(e)});var inspectSource$4=store$1.inspectSource,global$p=global$w,isCallable$j=isCallable$q,inspectSource$3=inspectSource$4,WeakMap$2=global$p.WeakMap,nativeWeakMap=isCallable$j(WeakMap$2)&&/native code/.test(inspectSource$3(WeakMap$2)),shared$5=shared$7.exports,uid$2=uid$4,keys$3=shared$5("keys"),sharedKey$4=function(e){return keys$3[e]||(keys$3[e]=uid$2(e))},hiddenKeys$6={},NATIVE_WEAK_MAP$1=nativeWeakMap,global$o=global$w,uncurryThis$B=functionUncurryThis,isObject$j=isObject$o,createNonEnumerableProperty$6=createNonEnumerableProperty$7,hasOwn$i=hasOwnProperty_1,shared$4=sharedStore,sharedKey$3=sharedKey$4,hiddenKeys$5=hiddenKeys$6,OBJECT_ALREADY_INITIALIZED="Object already initialized",TypeError$4=global$o.TypeError,WeakMap$1=global$o.WeakMap,set$2,get$1,has$1,enforce=function(e){return has$1(e)?get$1(e):set$2(e,{})},getterFor=function(e){return function(t){var n;if(!isObject$j(t)||(n=get$1(t)).type!==e)throw TypeError$4("Incompatible receiver, "+e+" required");return n}};if(NATIVE_WEAK_MAP$1||shared$4.state){var store=shared$4.state||(shared$4.state=new WeakMap$1),wmget=uncurryThis$B(store.get),wmhas=uncurryThis$B(store.has),wmset=uncurryThis$B(store.set);set$2=function(e,t){if(wmhas(store,e))throw new TypeError$4(OBJECT_ALREADY_INITIALIZED);return t.facade=e,wmset(store,e,t),t},get$1=function(e){return wmget(store,e)||{}},has$1=function(e){return wmhas(store,e)}}else{var STATE=sharedKey$3("state");hiddenKeys$5[STATE]=!0,set$2=function(e,t){if(hasOwn$i(e,STATE))throw new TypeError$4(OBJECT_ALREADY_INITIALIZED);return t.facade=e,createNonEnumerableProperty$6(e,STATE,t),t},get$1=function(e){return hasOwn$i(e,STATE)?e[STATE]:{}},has$1=function(e){return hasOwn$i(e,STATE)}}var internalState={set:set$2,get:get$1,has:has$1,enforce:enforce,getterFor:getterFor},fails$z=fails$G,isCallable$i=isCallable$q,hasOwn$h=hasOwnProperty_1,DESCRIPTORS$c=descriptors,CONFIGURABLE_FUNCTION_NAME$1=functionName$1.CONFIGURABLE,inspectSource$2=inspectSource$4,InternalStateModule$6=internalState,enforceInternalState$2=InternalStateModule$6.enforce,getInternalState$4=InternalStateModule$6.get,defineProperty$b=Object.defineProperty,CONFIGURABLE_LENGTH=DESCRIPTORS$c&&!fails$z((function(){return 8!==defineProperty$b((function(){}),"length",{value:8}).length})),TEMPLATE=String(String).split("String"),makeBuiltIn$1=makeBuiltIn$2.exports=function(e,t,n){"Symbol("===String(t).slice(0,7)&&(t="["+String(t).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),n&&n.getter&&(t="get "+t),n&&n.setter&&(t="set "+t),(!hasOwn$h(e,"name")||CONFIGURABLE_FUNCTION_NAME$1&&e.name!==t)&&(DESCRIPTORS$c?defineProperty$b(e,"name",{value:t,configurable:!0}):e.name=t),CONFIGURABLE_LENGTH&&n&&hasOwn$h(n,"arity")&&e.length!==n.arity&&defineProperty$b(e,"length",{value:n.arity});try{n&&hasOwn$h(n,"constructor")&&n.constructor?DESCRIPTORS$c&&defineProperty$b(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(e){}var r=enforceInternalState$2(e);return hasOwn$h(r,"source")||(r.source=TEMPLATE.join("string"==typeof t?t:"")),e};Function.prototype.toString=makeBuiltIn$1((function(){return isCallable$i(this)&&getInternalState$4(this).source||inspectSource$2(this)}),"toString");var isCallable$h=isCallable$q,definePropertyModule$5=objectDefineProperty,makeBuiltIn=makeBuiltIn$2.exports,defineGlobalProperty$1=defineGlobalProperty$3,defineBuiltIn$e=function(e,t,n,r){r||(r={});var a=r.enumerable,i=void 0!==r.name?r.name:t;if(isCallable$h(n)&&makeBuiltIn(n,i,r),r.global)a?e[t]=n:defineGlobalProperty$1(t,n);else{try{r.unsafe?e[t]&&(a=!0):delete e[t]}catch(e){}a?e[t]=n:definePropertyModule$5.f(e,t,{value:n,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},objectGetOwnPropertyNames={},ceil$1=Math.ceil,floor$4=Math.floor,mathTrunc=Math.trunc||function(e){var t=+e;return(t>0?floor$4:ceil$1)(t)},trunc$1=mathTrunc,toIntegerOrInfinity$7=function(e){var t=+e;return t!=t||0===t?0:trunc$1(t)},toIntegerOrInfinity$6=toIntegerOrInfinity$7,max$4=Math.max,min$6=Math.min,toAbsoluteIndex$6=function(e,t){var n=toIntegerOrInfinity$6(e);return n<0?max$4(n+t,0):min$6(n,t)},toIntegerOrInfinity$5=toIntegerOrInfinity$7,min$5=Math.min,toLength$6=function(e){return e>0?min$5(toIntegerOrInfinity$5(e),9007199254740991):0},toLength$5=toLength$6,lengthOfArrayLike$b=function(e){return toLength$5(e.length)},toIndexedObject$9=toIndexedObject$b,toAbsoluteIndex$5=toAbsoluteIndex$6,lengthOfArrayLike$a=lengthOfArrayLike$b,createMethod$6=function(e){return function(t,n,r){var a,i=toIndexedObject$9(t),o=lengthOfArrayLike$a(i),s=toAbsoluteIndex$5(r,o);if(e&&n!=n){for(;o>s;)if((a=i[s++])!=a)return!0}else for(;o>s;s++)if((e||s in i)&&i[s]===n)return e||s||0;return!e&&-1}},arrayIncludes={includes:createMethod$6(!0),indexOf:createMethod$6(!1)},uncurryThis$A=functionUncurryThis,hasOwn$g=hasOwnProperty_1,toIndexedObject$8=toIndexedObject$b,indexOf$2=arrayIncludes.indexOf,hiddenKeys$4=hiddenKeys$6,push$7=uncurryThis$A([].push),objectKeysInternal=function(e,t){var n,r=toIndexedObject$8(e),a=0,i=[];for(n in r)!hasOwn$g(hiddenKeys$4,n)&&hasOwn$g(r,n)&&push$7(i,n);for(;t.length>a;)hasOwn$g(r,n=t[a++])&&(~indexOf$2(i,n)||push$7(i,n));return i},enumBugKeys$3=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],internalObjectKeys$1=objectKeysInternal,enumBugKeys$2=enumBugKeys$3,hiddenKeys$3=enumBugKeys$2.concat("length","prototype");objectGetOwnPropertyNames.f=Object.getOwnPropertyNames||function(e){return internalObjectKeys$1(e,hiddenKeys$3)};var objectGetOwnPropertySymbols={};objectGetOwnPropertySymbols.f=Object.getOwnPropertySymbols;var getBuiltIn$a=getBuiltIn$d,uncurryThis$z=functionUncurryThis,getOwnPropertyNamesModule$2=objectGetOwnPropertyNames,getOwnPropertySymbolsModule$3=objectGetOwnPropertySymbols,anObject$i=anObject$k,concat$3=uncurryThis$z([].concat),ownKeys$1=getBuiltIn$a("Reflect","ownKeys")||function(e){var t=getOwnPropertyNamesModule$2.f(anObject$i(e)),n=getOwnPropertySymbolsModule$3.f;return n?concat$3(t,n(e)):t},hasOwn$f=hasOwnProperty_1,ownKeys=ownKeys$1,getOwnPropertyDescriptorModule$2=objectGetOwnPropertyDescriptor,definePropertyModule$4=objectDefineProperty,copyConstructorProperties$2=function(e,t,n){for(var r=ownKeys(t),a=definePropertyModule$4.f,i=getOwnPropertyDescriptorModule$2.f,o=0;o1?arguments[1]:void 0,t.length)),r=toString$h(e);return un$StartsWith?un$StartsWith(t,r,n):stringSlice$9(t,n,n+r.length)===r}});var TO_STRING_TAG_SUPPORT$1=toStringTagSupport,classof$6=classof$9,objectToString=TO_STRING_TAG_SUPPORT$1?{}.toString:function(){return"[object "+classof$6(this)+"]"},TO_STRING_TAG_SUPPORT=toStringTagSupport,defineBuiltIn$c=defineBuiltIn$e,toString$g=objectToString;TO_STRING_TAG_SUPPORT||defineBuiltIn$c(Object.prototype,"toString",toString$g,{unsafe:!0});var NATIVE_BIND$2=functionBindNative,FunctionPrototype$1=Function.prototype,apply$5=FunctionPrototype$1.apply,call$j=FunctionPrototype$1.call,functionApply="object"==typeof Reflect&&Reflect.apply||(NATIVE_BIND$2?call$j.bind(apply$5):function(){return call$j.apply(apply$5,arguments)}),uncurryThis$x=functionUncurryThis,arraySlice$6=uncurryThis$x([].slice),uncurryThis$w=functionUncurryThis,aCallable$8=aCallable$a,isObject$h=isObject$o,hasOwn$d=hasOwnProperty_1,arraySlice$5=arraySlice$6,NATIVE_BIND$1=functionBindNative,$Function=Function,concat$2=uncurryThis$w([].concat),join$1=uncurryThis$w([].join),factories={},construct$1=function(e,t,n){if(!hasOwn$d(factories,t)){for(var r=[],a=0;ao;)definePropertyModule$2.f(e,n=a[o++],r[n]);return e};var getBuiltIn$8=getBuiltIn$d,html$2=getBuiltIn$8("document","documentElement"),anObject$g=anObject$k,definePropertiesModule$1=objectDefineProperties,enumBugKeys=enumBugKeys$3,hiddenKeys$2=hiddenKeys$6,html$1=html$2,documentCreateElement$1=documentCreateElement$2,sharedKey$1=sharedKey$4,GT=">",LT="<",PROTOTYPE$1="prototype",SCRIPT="script",IE_PROTO=sharedKey$1("IE_PROTO"),EmptyConstructor=function(){},scriptTag=function(e){return LT+SCRIPT+GT+e+LT+"/"+SCRIPT+GT},NullProtoObjectViaActiveX=function(e){e.write(scriptTag("")),e.close();var t=e.parentWindow.Object;return e=null,t},NullProtoObjectViaIFrame=function(){var e,t=documentCreateElement$1("iframe"),n="java"+SCRIPT+":";return t.style.display="none",html$1.appendChild(t),t.src=String(n),(e=t.contentWindow.document).open(),e.write(scriptTag("document.F=Object")),e.close(),e.F},activeXDocument,NullProtoObject=function(){try{activeXDocument=new ActiveXObject("htmlfile")}catch(e){}NullProtoObject="undefined"!=typeof document?document.domain&&activeXDocument?NullProtoObjectViaActiveX(activeXDocument):NullProtoObjectViaIFrame():NullProtoObjectViaActiveX(activeXDocument);for(var e=enumBugKeys.length;e--;)delete NullProtoObject[PROTOTYPE$1][enumBugKeys[e]];return NullProtoObject()};hiddenKeys$2[IE_PROTO]=!0;var objectCreate=Object.create||function(e,t){var n;return null!==e?(EmptyConstructor[PROTOTYPE$1]=anObject$g(e),n=new EmptyConstructor,EmptyConstructor[PROTOTYPE$1]=null,n[IE_PROTO]=e):n=NullProtoObject(),void 0===t?n:definePropertiesModule$1.f(n,t)},$$V=_export,getBuiltIn$7=getBuiltIn$d,apply$4=functionApply,bind$b=functionBind,aConstructor$1=aConstructor$2,anObject$f=anObject$k,isObject$g=isObject$o,create$4=objectCreate,fails$t=fails$G,nativeConstruct=getBuiltIn$7("Reflect","construct"),ObjectPrototype$1=Object.prototype,push$6=[].push,NEW_TARGET_BUG=fails$t((function(){function e(){}return!(nativeConstruct((function(){}),[],e)instanceof e)})),ARGS_BUG=!fails$t((function(){nativeConstruct((function(){}))})),FORCED$7=NEW_TARGET_BUG||ARGS_BUG;$$V({target:"Reflect",stat:!0,forced:FORCED$7,sham:FORCED$7},{construct:function(e,t){aConstructor$1(e),anObject$f(t);var n=arguments.length<3?e:aConstructor$1(arguments[2]);if(ARGS_BUG&&!NEW_TARGET_BUG)return nativeConstruct(e,t,n);if(e==n){switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3])}var r=[null];return apply$4(push$6,r,t),new(apply$4(bind$b,e,r))}var a=n.prototype,i=create$4(isObject$g(a)?a:ObjectPrototype$1),o=apply$4(e,i,t);return isObject$g(o)?o:i}});var classof$4=classofRaw$1,isArray$8=Array.isArray||function(e){return"Array"==classof$4(e)},fails$s=fails$G,wellKnownSymbol$k=wellKnownSymbol$q,V8_VERSION$2=engineV8Version,SPECIES$6=wellKnownSymbol$k("species"),arrayMethodHasSpeciesSupport$5=function(e){return V8_VERSION$2>=51||!fails$s((function(){var t=[];return(t.constructor={})[SPECIES$6]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},$$U=_export,isArray$7=isArray$8,isConstructor$2=isConstructor$4,isObject$f=isObject$o,toAbsoluteIndex$3=toAbsoluteIndex$6,lengthOfArrayLike$8=lengthOfArrayLike$b,toIndexedObject$5=toIndexedObject$b,createProperty$3=createProperty$5,wellKnownSymbol$j=wellKnownSymbol$q,arrayMethodHasSpeciesSupport$4=arrayMethodHasSpeciesSupport$5,un$Slice=arraySlice$6,HAS_SPECIES_SUPPORT$3=arrayMethodHasSpeciesSupport$4("slice"),SPECIES$5=wellKnownSymbol$j("species"),$Array$2=Array,max$2=Math.max;$$U({target:"Array",proto:!0,forced:!HAS_SPECIES_SUPPORT$3},{slice:function(e,t){var n,r,a,i=toIndexedObject$5(this),o=lengthOfArrayLike$8(i),s=toAbsoluteIndex$3(e,o),l=toAbsoluteIndex$3(void 0===t?o:t,o);if(isArray$7(i)&&(n=i.constructor,(isConstructor$2(n)&&(n===$Array$2||isArray$7(n.prototype))||isObject$f(n)&&null===(n=n[SPECIES$5]))&&(n=void 0),n===$Array$2||void 0===n))return un$Slice(i,s,l);for(r=new(void 0===n?$Array$2:n)(max$2(l-s,0)),a=0;s1?arguments[1]:void 0,i=void 0!==a;i&&(a=bind$9(a,r>2?arguments[2]:void 0));var o,s,l,u,c,p,d=getIteratorMethod$1(t),m=0;if(!d||this===$Array$1&&isArrayIteratorMethod$1(d))for(o=lengthOfArrayLike$7(t),s=n?new this(o):$Array$1(o);o>m;m++)p=i?a(t[m],m):t[m],createProperty$2(s,m,p);else for(c=(u=getIterator$1(t,d)).next,s=n?new this:[];!(l=call$g(c,u)).done;m++)p=i?callWithSafeIterationClosing(u,a,[l.value,m],!0):l.value,createProperty$2(s,m,p);return s.length=m,s},wellKnownSymbol$g=wellKnownSymbol$q,ITERATOR$3=wellKnownSymbol$g("iterator"),SAFE_CLOSING=!1;try{var called=0,iteratorWithReturn={next:function(){return{done:!!called++}},return:function(){SAFE_CLOSING=!0}};iteratorWithReturn[ITERATOR$3]=function(){return this},Array.from(iteratorWithReturn,(function(){throw 2}))}catch(e){}var checkCorrectnessOfIteration$3=function(e,t){if(!t&&!SAFE_CLOSING)return!1;var n=!1;try{var r={};r[ITERATOR$3]=function(){return{next:function(){return{done:n=!0}}}},e(r)}catch(e){}return n},$$T=_export,from$1=arrayFrom,checkCorrectnessOfIteration$2=checkCorrectnessOfIteration$3,INCORRECT_ITERATION=!checkCorrectnessOfIteration$2((function(e){Array.from(e)}));$$T({target:"Array",stat:!0,forced:INCORRECT_ITERATION},{from:from$1});var uncurryThis$s=functionUncurryThis,toIntegerOrInfinity$4=toIntegerOrInfinity$7,toString$f=toString$i,requireObjectCoercible$7=requireObjectCoercible$b,charAt$6=uncurryThis$s("".charAt),charCodeAt$2=uncurryThis$s("".charCodeAt),stringSlice$8=uncurryThis$s("".slice),createMethod$5=function(e){return function(t,n){var r,a,i=toString$f(requireObjectCoercible$7(t)),o=toIntegerOrInfinity$4(n),s=i.length;return o<0||o>=s?e?"":void 0:(r=charCodeAt$2(i,o))<55296||r>56319||o+1===s||(a=charCodeAt$2(i,o+1))<56320||a>57343?e?charAt$6(i,o):r:e?stringSlice$8(i,o,o+2):a-56320+(r-55296<<10)+65536}},stringMultibyte={codeAt:createMethod$5(!1),charAt:createMethod$5(!0)},fails$r=fails$G,isCallable$c=isCallable$q,getPrototypeOf$2=objectGetPrototypeOf,defineBuiltIn$b=defineBuiltIn$e,wellKnownSymbol$f=wellKnownSymbol$q,ITERATOR$2=wellKnownSymbol$f("iterator"),BUGGY_SAFARI_ITERATORS$1=!1,IteratorPrototype$2,PrototypeOfArrayIteratorPrototype,arrayIterator;[].keys&&(arrayIterator=[].keys(),"next"in arrayIterator?(PrototypeOfArrayIteratorPrototype=getPrototypeOf$2(getPrototypeOf$2(arrayIterator)),PrototypeOfArrayIteratorPrototype!==Object.prototype&&(IteratorPrototype$2=PrototypeOfArrayIteratorPrototype)):BUGGY_SAFARI_ITERATORS$1=!0);var NEW_ITERATOR_PROTOTYPE=null==IteratorPrototype$2||fails$r((function(){var e={};return IteratorPrototype$2[ITERATOR$2].call(e)!==e}));NEW_ITERATOR_PROTOTYPE&&(IteratorPrototype$2={}),isCallable$c(IteratorPrototype$2[ITERATOR$2])||defineBuiltIn$b(IteratorPrototype$2,ITERATOR$2,(function(){return this}));var iteratorsCore={IteratorPrototype:IteratorPrototype$2,BUGGY_SAFARI_ITERATORS:BUGGY_SAFARI_ITERATORS$1},defineProperty$9=objectDefineProperty.f,hasOwn$c=hasOwnProperty_1,wellKnownSymbol$e=wellKnownSymbol$q,TO_STRING_TAG$1=wellKnownSymbol$e("toStringTag"),setToStringTag$8=function(e,t,n){e&&!n&&(e=e.prototype),e&&!hasOwn$c(e,TO_STRING_TAG$1)&&defineProperty$9(e,TO_STRING_TAG$1,{configurable:!0,value:t})},IteratorPrototype$1=iteratorsCore.IteratorPrototype,create$3=objectCreate,createPropertyDescriptor$1=createPropertyDescriptor$5,setToStringTag$7=setToStringTag$8,Iterators$2=iterators,returnThis$1=function(){return this},createIteratorConstructor$1=function(e,t,n,r){var a=t+" Iterator";return e.prototype=create$3(IteratorPrototype$1,{next:createPropertyDescriptor$1(+!r,n)}),setToStringTag$7(e,a,!1),Iterators$2[a]=returnThis$1,e},isCallable$b=isCallable$q,$String$1=String,$TypeError$7=TypeError,aPossiblePrototype$1=function(e){if("object"==typeof e||isCallable$b(e))return e;throw $TypeError$7("Can't set "+$String$1(e)+" as a prototype")},uncurryThis$r=functionUncurryThis,anObject$b=anObject$k,aPossiblePrototype=aPossiblePrototype$1,objectSetPrototypeOf=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,n={};try{(e=uncurryThis$r(Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set))(n,[]),t=n instanceof Array}catch(e){}return function(n,r){return anObject$b(n),aPossiblePrototype(r),t?e(n,r):n.__proto__=r,n}}():void 0),$$S=_export,call$f=functionCall,FunctionName=functionName$1,isCallable$a=isCallable$q,createIteratorConstructor=createIteratorConstructor$1,getPrototypeOf$1=objectGetPrototypeOf,setPrototypeOf$2=objectSetPrototypeOf,setToStringTag$6=setToStringTag$8,createNonEnumerableProperty$4=createNonEnumerableProperty$7,defineBuiltIn$a=defineBuiltIn$e,wellKnownSymbol$d=wellKnownSymbol$q,Iterators$1=iterators,IteratorsCore=iteratorsCore,PROPER_FUNCTION_NAME$2=FunctionName.PROPER,CONFIGURABLE_FUNCTION_NAME=FunctionName.CONFIGURABLE,IteratorPrototype=IteratorsCore.IteratorPrototype,BUGGY_SAFARI_ITERATORS=IteratorsCore.BUGGY_SAFARI_ITERATORS,ITERATOR$1=wellKnownSymbol$d("iterator"),KEYS="keys",VALUES="values",ENTRIES="entries",returnThis=function(){return this},defineIterator$3=function(e,t,n,r,a,i,o){createIteratorConstructor(n,t,r);var s,l,u,c=function(e){if(e===a&&h)return h;if(!BUGGY_SAFARI_ITERATORS&&e in m)return m[e];switch(e){case KEYS:case VALUES:case ENTRIES:return function(){return new n(this,e)}}return function(){return new n(this)}},p=t+" Iterator",d=!1,m=e.prototype,f=m[ITERATOR$1]||m["@@iterator"]||a&&m[a],h=!BUGGY_SAFARI_ITERATORS&&f||c(a),y="Array"==t&&m.entries||f;if(y&&(s=getPrototypeOf$1(y.call(new e)))!==Object.prototype&&s.next&&(getPrototypeOf$1(s)!==IteratorPrototype&&(setPrototypeOf$2?setPrototypeOf$2(s,IteratorPrototype):isCallable$a(s[ITERATOR$1])||defineBuiltIn$a(s,ITERATOR$1,returnThis)),setToStringTag$6(s,p,!0)),PROPER_FUNCTION_NAME$2&&a==VALUES&&f&&f.name!==VALUES&&(CONFIGURABLE_FUNCTION_NAME?createNonEnumerableProperty$4(m,"name",VALUES):(d=!0,h=function(){return call$f(f,this)})),a)if(l={values:c(VALUES),keys:i?h:c(KEYS),entries:c(ENTRIES)},o)for(u in l)(BUGGY_SAFARI_ITERATORS||d||!(u in m))&&defineBuiltIn$a(m,u,l[u]);else $$S({target:t,proto:!0,forced:BUGGY_SAFARI_ITERATORS||d},l);return m[ITERATOR$1]!==h&&defineBuiltIn$a(m,ITERATOR$1,h,{name:a}),Iterators$1[t]=h,l},charAt$5=stringMultibyte.charAt,toString$e=toString$i,InternalStateModule$5=internalState,defineIterator$2=defineIterator$3,STRING_ITERATOR="String Iterator",setInternalState$5=InternalStateModule$5.set,getInternalState$3=InternalStateModule$5.getterFor(STRING_ITERATOR);defineIterator$2(String,"String",(function(e){setInternalState$5(this,{type:STRING_ITERATOR,string:toString$e(e),index:0})}),(function(){var e,t=getInternalState$3(this),n=t.string,r=t.index;return r>=n.length?{value:void 0,done:!0}:(e=charAt$5(n,r),t.index+=e.length,{value:e,done:!1})}));var anObject$a=anObject$k,regexpFlags$1=function(){var e=anObject$a(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},fails$q=fails$G,global$m=global$w,$RegExp$2=global$m.RegExp,UNSUPPORTED_Y$3=fails$q((function(){var e=$RegExp$2("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),MISSED_STICKY$1=UNSUPPORTED_Y$3||fails$q((function(){return!$RegExp$2("a","y").sticky})),BROKEN_CARET=UNSUPPORTED_Y$3||fails$q((function(){var e=$RegExp$2("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),regexpStickyHelpers={BROKEN_CARET:BROKEN_CARET,MISSED_STICKY:MISSED_STICKY$1,UNSUPPORTED_Y:UNSUPPORTED_Y$3},fails$p=fails$G,global$l=global$w,$RegExp$1=global$l.RegExp,regexpUnsupportedDotAll=fails$p((function(){var e=$RegExp$1(".","s");return!(e.dotAll&&e.exec("\n")&&"s"===e.flags)})),fails$o=fails$G,global$k=global$w,$RegExp=global$k.RegExp,regexpUnsupportedNcg=fails$o((function(){var e=$RegExp("(?b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$c")})),call$e=functionCall,uncurryThis$q=functionUncurryThis,toString$d=toString$i,regexpFlags=regexpFlags$1,stickyHelpers$2=regexpStickyHelpers,shared$3=shared$7.exports,create$2=objectCreate,getInternalState$2=internalState.get,UNSUPPORTED_DOT_ALL$1=regexpUnsupportedDotAll,UNSUPPORTED_NCG$1=regexpUnsupportedNcg,nativeReplace=shared$3("native-string-replace",String.prototype.replace),nativeExec=RegExp.prototype.exec,patchedExec=nativeExec,charAt$4=uncurryThis$q("".charAt),indexOf$1=uncurryThis$q("".indexOf),replace$5=uncurryThis$q("".replace),stringSlice$7=uncurryThis$q("".slice),UPDATES_LAST_INDEX_WRONG=function(){var e=/a/,t=/b*/g;return call$e(nativeExec,e,"a"),call$e(nativeExec,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),UNSUPPORTED_Y$2=stickyHelpers$2.BROKEN_CARET,NPCG_INCLUDED=void 0!==/()??/.exec("")[1],PATCH=UPDATES_LAST_INDEX_WRONG||NPCG_INCLUDED||UNSUPPORTED_Y$2||UNSUPPORTED_DOT_ALL$1||UNSUPPORTED_NCG$1;PATCH&&(patchedExec=function(e){var t,n,r,a,i,o,s,l=this,u=getInternalState$2(l),c=toString$d(e),p=u.raw;if(p)return p.lastIndex=l.lastIndex,t=call$e(patchedExec,p,c),l.lastIndex=p.lastIndex,t;var d=u.groups,m=UNSUPPORTED_Y$2&&l.sticky,f=call$e(regexpFlags,l),h=l.source,y=0,b=c;if(m&&(f=replace$5(f,"y",""),-1===indexOf$1(f,"g")&&(f+="g"),b=stringSlice$7(c,l.lastIndex),l.lastIndex>0&&(!l.multiline||l.multiline&&"\n"!==charAt$4(c,l.lastIndex-1))&&(h="(?: "+h+")",b=" "+b,y++),n=new RegExp("^(?:"+h+")",f)),NPCG_INCLUDED&&(n=new RegExp("^"+h+"$(?!\\s)",f)),UPDATES_LAST_INDEX_WRONG&&(r=l.lastIndex),a=call$e(nativeExec,m?n:l,b),m?a?(a.input=stringSlice$7(a.input,y),a[0]=stringSlice$7(a[0],y),a.index=l.lastIndex,l.lastIndex+=a[0].length):l.lastIndex=0:UPDATES_LAST_INDEX_WRONG&&a&&(l.lastIndex=l.global?a.index+a[0].length:r),NPCG_INCLUDED&&a&&a.length>1&&call$e(nativeReplace,a[0],n,(function(){for(i=1;ig;g++)if((s||g in h)&&(m=y(d=h[g],g,f),e))if(t)T[g]=m;else if(m)switch(e){case 3:return!0;case 5:return d;case 6:return g;case 2:push$5(T,d)}else switch(e){case 4:return!1;case 7:push$5(T,d)}return i?-1:r||a?a:T}},arrayIteration={forEach:createMethod$4(0),map:createMethod$4(1),filter:createMethod$4(2),some:createMethod$4(3),every:createMethod$4(4),find:createMethod$4(5),findIndex:createMethod$4(6),filterReject:createMethod$4(7)},$$Q=_export,global$i=global$w,call$c=functionCall,uncurryThis$o=functionUncurryThis,DESCRIPTORS$9=descriptors,NATIVE_SYMBOL$4=nativeSymbol,fails$n=fails$G,hasOwn$a=hasOwnProperty_1,isPrototypeOf$6=objectIsPrototypeOf,anObject$9=anObject$k,toIndexedObject$4=toIndexedObject$b,toPropertyKey=toPropertyKey$4,$toString$1=toString$i,createPropertyDescriptor=createPropertyDescriptor$5,nativeObjectCreate=objectCreate,objectKeys$2=objectKeys$4,getOwnPropertyNamesModule$1=objectGetOwnPropertyNames,getOwnPropertyNamesExternal=objectGetOwnPropertyNamesExternal,getOwnPropertySymbolsModule$2=objectGetOwnPropertySymbols,getOwnPropertyDescriptorModule$1=objectGetOwnPropertyDescriptor,definePropertyModule$1=objectDefineProperty,definePropertiesModule=objectDefineProperties,propertyIsEnumerableModule$1=objectPropertyIsEnumerable,defineBuiltIn$8=defineBuiltIn$e,shared$2=shared$7.exports,sharedKey=sharedKey$4,hiddenKeys$1=hiddenKeys$6,uid$1=uid$4,wellKnownSymbol$9=wellKnownSymbol$q,wrappedWellKnownSymbolModule=wellKnownSymbolWrapped,defineWellKnownSymbol$3=defineWellKnownSymbol$4,defineSymbolToPrimitive=symbolDefineToPrimitive,setToStringTag$5=setToStringTag$8,InternalStateModule$4=internalState,$forEach$1=arrayIteration.forEach,HIDDEN=sharedKey("hidden"),SYMBOL="Symbol",PROTOTYPE="prototype",setInternalState$4=InternalStateModule$4.set,getInternalState$1=InternalStateModule$4.getterFor(SYMBOL),ObjectPrototype=Object[PROTOTYPE],$Symbol=global$i.Symbol,SymbolPrototype$1=$Symbol&&$Symbol[PROTOTYPE],TypeError$3=global$i.TypeError,QObject=global$i.QObject,nativeGetOwnPropertyDescriptor$1=getOwnPropertyDescriptorModule$1.f,nativeDefineProperty=definePropertyModule$1.f,nativeGetOwnPropertyNames=getOwnPropertyNamesExternal.f,nativePropertyIsEnumerable=propertyIsEnumerableModule$1.f,push$4=uncurryThis$o([].push),AllSymbols=shared$2("symbols"),ObjectPrototypeSymbols=shared$2("op-symbols"),WellKnownSymbolsStore=shared$2("wks"),USE_SETTER=!QObject||!QObject[PROTOTYPE]||!QObject[PROTOTYPE].findChild,setSymbolDescriptor=DESCRIPTORS$9&&fails$n((function(){return 7!=nativeObjectCreate(nativeDefineProperty({},"a",{get:function(){return nativeDefineProperty(this,"a",{value:7}).a}})).a}))?function(e,t,n){var r=nativeGetOwnPropertyDescriptor$1(ObjectPrototype,t);r&&delete ObjectPrototype[t],nativeDefineProperty(e,t,n),r&&e!==ObjectPrototype&&nativeDefineProperty(ObjectPrototype,t,r)}:nativeDefineProperty,wrap=function(e,t){var n=AllSymbols[e]=nativeObjectCreate(SymbolPrototype$1);return setInternalState$4(n,{type:SYMBOL,tag:e,description:t}),DESCRIPTORS$9||(n.description=t),n},$defineProperty=function(e,t,n){e===ObjectPrototype&&$defineProperty(ObjectPrototypeSymbols,t,n),anObject$9(e);var r=toPropertyKey(t);return anObject$9(n),hasOwn$a(AllSymbols,r)?(n.enumerable?(hasOwn$a(e,HIDDEN)&&e[HIDDEN][r]&&(e[HIDDEN][r]=!1),n=nativeObjectCreate(n,{enumerable:createPropertyDescriptor(0,!1)})):(hasOwn$a(e,HIDDEN)||nativeDefineProperty(e,HIDDEN,createPropertyDescriptor(1,{})),e[HIDDEN][r]=!0),setSymbolDescriptor(e,r,n)):nativeDefineProperty(e,r,n)},$defineProperties=function(e,t){anObject$9(e);var n=toIndexedObject$4(t),r=objectKeys$2(n).concat($getOwnPropertySymbols(n));return $forEach$1(r,(function(t){DESCRIPTORS$9&&!call$c($propertyIsEnumerable$1,n,t)||$defineProperty(e,t,n[t])})),e},$create=function(e,t){return void 0===t?nativeObjectCreate(e):$defineProperties(nativeObjectCreate(e),t)},$propertyIsEnumerable$1=function(e){var t=toPropertyKey(e),n=call$c(nativePropertyIsEnumerable,this,t);return!(this===ObjectPrototype&&hasOwn$a(AllSymbols,t)&&!hasOwn$a(ObjectPrototypeSymbols,t))&&(!(n||!hasOwn$a(this,t)||!hasOwn$a(AllSymbols,t)||hasOwn$a(this,HIDDEN)&&this[HIDDEN][t])||n)},$getOwnPropertyDescriptor=function(e,t){var n=toIndexedObject$4(e),r=toPropertyKey(t);if(n!==ObjectPrototype||!hasOwn$a(AllSymbols,r)||hasOwn$a(ObjectPrototypeSymbols,r)){var a=nativeGetOwnPropertyDescriptor$1(n,r);return!a||!hasOwn$a(AllSymbols,r)||hasOwn$a(n,HIDDEN)&&n[HIDDEN][r]||(a.enumerable=!0),a}},$getOwnPropertyNames=function(e){var t=nativeGetOwnPropertyNames(toIndexedObject$4(e)),n=[];return $forEach$1(t,(function(e){hasOwn$a(AllSymbols,e)||hasOwn$a(hiddenKeys$1,e)||push$4(n,e)})),n},$getOwnPropertySymbols=function(e){var t=e===ObjectPrototype,n=nativeGetOwnPropertyNames(t?ObjectPrototypeSymbols:toIndexedObject$4(e)),r=[];return $forEach$1(n,(function(e){!hasOwn$a(AllSymbols,e)||t&&!hasOwn$a(ObjectPrototype,e)||push$4(r,AllSymbols[e])})),r};NATIVE_SYMBOL$4||($Symbol=function(){if(isPrototypeOf$6(SymbolPrototype$1,this))throw TypeError$3("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?$toString$1(arguments[0]):void 0,t=uid$1(e),n=function(e){this===ObjectPrototype&&call$c(n,ObjectPrototypeSymbols,e),hasOwn$a(this,HIDDEN)&&hasOwn$a(this[HIDDEN],t)&&(this[HIDDEN][t]=!1),setSymbolDescriptor(this,t,createPropertyDescriptor(1,e))};return DESCRIPTORS$9&&USE_SETTER&&setSymbolDescriptor(ObjectPrototype,t,{configurable:!0,set:n}),wrap(t,e)},SymbolPrototype$1=$Symbol[PROTOTYPE],defineBuiltIn$8(SymbolPrototype$1,"toString",(function(){return getInternalState$1(this).tag})),defineBuiltIn$8($Symbol,"withoutSetter",(function(e){return wrap(uid$1(e),e)})),propertyIsEnumerableModule$1.f=$propertyIsEnumerable$1,definePropertyModule$1.f=$defineProperty,definePropertiesModule.f=$defineProperties,getOwnPropertyDescriptorModule$1.f=$getOwnPropertyDescriptor,getOwnPropertyNamesModule$1.f=getOwnPropertyNamesExternal.f=$getOwnPropertyNames,getOwnPropertySymbolsModule$2.f=$getOwnPropertySymbols,wrappedWellKnownSymbolModule.f=function(e){return wrap(wellKnownSymbol$9(e),e)},DESCRIPTORS$9&&(nativeDefineProperty(SymbolPrototype$1,"description",{configurable:!0,get:function(){return getInternalState$1(this).description}}),defineBuiltIn$8(ObjectPrototype,"propertyIsEnumerable",$propertyIsEnumerable$1,{unsafe:!0}))),$$Q({global:!0,constructor:!0,wrap:!0,forced:!NATIVE_SYMBOL$4,sham:!NATIVE_SYMBOL$4},{Symbol:$Symbol}),$forEach$1(objectKeys$2(WellKnownSymbolsStore),(function(e){defineWellKnownSymbol$3(e)})),$$Q({target:SYMBOL,stat:!0,forced:!NATIVE_SYMBOL$4},{useSetter:function(){USE_SETTER=!0},useSimple:function(){USE_SETTER=!1}}),$$Q({target:"Object",stat:!0,forced:!NATIVE_SYMBOL$4,sham:!DESCRIPTORS$9},{create:$create,defineProperty:$defineProperty,defineProperties:$defineProperties,getOwnPropertyDescriptor:$getOwnPropertyDescriptor}),$$Q({target:"Object",stat:!0,forced:!NATIVE_SYMBOL$4},{getOwnPropertyNames:$getOwnPropertyNames}),defineSymbolToPrimitive(),setToStringTag$5($Symbol,SYMBOL),hiddenKeys$1[HIDDEN]=!0;var NATIVE_SYMBOL$3=nativeSymbol,nativeSymbolRegistry=NATIVE_SYMBOL$3&&!!Symbol.for&&!!Symbol.keyFor,$$P=_export,getBuiltIn$5=getBuiltIn$d,hasOwn$9=hasOwnProperty_1,toString$c=toString$i,shared$1=shared$7.exports,NATIVE_SYMBOL_REGISTRY$1=nativeSymbolRegistry,StringToSymbolRegistry=shared$1("string-to-symbol-registry"),SymbolToStringRegistry$1=shared$1("symbol-to-string-registry");$$P({target:"Symbol",stat:!0,forced:!NATIVE_SYMBOL_REGISTRY$1},{for:function(e){var t=toString$c(e);if(hasOwn$9(StringToSymbolRegistry,t))return StringToSymbolRegistry[t];var n=getBuiltIn$5("Symbol")(t);return StringToSymbolRegistry[t]=n,SymbolToStringRegistry$1[n]=t,n}});var $$O=_export,hasOwn$8=hasOwnProperty_1,isSymbol$2=isSymbol$5,tryToString$2=tryToString$6,shared=shared$7.exports,NATIVE_SYMBOL_REGISTRY=nativeSymbolRegistry,SymbolToStringRegistry=shared("symbol-to-string-registry");$$O({target:"Symbol",stat:!0,forced:!NATIVE_SYMBOL_REGISTRY},{keyFor:function(e){if(!isSymbol$2(e))throw TypeError(tryToString$2(e)+" is not a symbol");if(hasOwn$8(SymbolToStringRegistry,e))return SymbolToStringRegistry[e]}});var $$N=_export,getBuiltIn$4=getBuiltIn$d,apply$3=functionApply,call$b=functionCall,uncurryThis$n=functionUncurryThis,fails$m=fails$G,isArray$5=isArray$8,isCallable$9=isCallable$q,isObject$d=isObject$o,isSymbol$1=isSymbol$5,arraySlice$4=arraySlice$6,NATIVE_SYMBOL$2=nativeSymbol,$stringify=getBuiltIn$4("JSON","stringify"),exec$2=uncurryThis$n(/./.exec),charAt$3=uncurryThis$n("".charAt),charCodeAt$1=uncurryThis$n("".charCodeAt),replace$4=uncurryThis$n("".replace),numberToString=uncurryThis$n(1..toString),tester=/[\uD800-\uDFFF]/g,low=/^[\uD800-\uDBFF]$/,hi$1=/^[\uDC00-\uDFFF]$/,WRONG_SYMBOLS_CONVERSION=!NATIVE_SYMBOL$2||fails$m((function(){var e=getBuiltIn$4("Symbol")();return"[null]"!=$stringify([e])||"{}"!=$stringify({a:e})||"{}"!=$stringify(Object(e))})),ILL_FORMED_UNICODE=fails$m((function(){return'"\\udf06\\ud834"'!==$stringify("\udf06\ud834")||'"\\udead"'!==$stringify("\udead")})),stringifyWithSymbolsFix=function(e,t){var n=arraySlice$4(arguments),r=t;if((isObject$d(t)||void 0!==e)&&!isSymbol$1(e))return isArray$5(t)||(t=function(e,t){if(isCallable$9(r)&&(t=call$b(r,this,e,t)),!isSymbol$1(t))return t}),n[1]=t,apply$3($stringify,null,n)},fixIllFormed=function(e,t,n){var r=charAt$3(n,t-1),a=charAt$3(n,t+1);return exec$2(low,e)&&!exec$2(hi$1,a)||exec$2(hi$1,e)&&!exec$2(low,r)?"\\u"+numberToString(charCodeAt$1(e,0),16):e};$stringify&&$$N({target:"JSON",stat:!0,arity:3,forced:WRONG_SYMBOLS_CONVERSION||ILL_FORMED_UNICODE},{stringify:function(e,t,n){var r=arraySlice$4(arguments),a=apply$3(WRONG_SYMBOLS_CONVERSION?stringifyWithSymbolsFix:$stringify,null,r);return ILL_FORMED_UNICODE&&"string"==typeof a?replace$4(a,tester,fixIllFormed):a}});var $$M=_export,NATIVE_SYMBOL$1=nativeSymbol,fails$l=fails$G,getOwnPropertySymbolsModule$1=objectGetOwnPropertySymbols,toObject$8=toObject$e,FORCED$6=!NATIVE_SYMBOL$1||fails$l((function(){getOwnPropertySymbolsModule$1.f(1)}));$$M({target:"Object",stat:!0,forced:FORCED$6},{getOwnPropertySymbols:function(e){var t=getOwnPropertySymbolsModule$1.f;return t?t(toObject$8(e)):[]}});var $$L=_export,DESCRIPTORS$8=descriptors,global$h=global$w,uncurryThis$m=functionUncurryThis,hasOwn$7=hasOwnProperty_1,isCallable$8=isCallable$q,isPrototypeOf$5=objectIsPrototypeOf,toString$b=toString$i,defineProperty$7=objectDefineProperty.f,copyConstructorProperties=copyConstructorProperties$2,NativeSymbol=global$h.Symbol,SymbolPrototype=NativeSymbol&&NativeSymbol.prototype;if(DESCRIPTORS$8&&isCallable$8(NativeSymbol)&&(!("description"in SymbolPrototype)||void 0!==NativeSymbol().description)){var EmptyStringDescriptionStore={},SymbolWrapper=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:toString$b(arguments[0]),t=isPrototypeOf$5(SymbolPrototype,this)?new NativeSymbol(e):void 0===e?NativeSymbol():NativeSymbol(e);return""===e&&(EmptyStringDescriptionStore[t]=!0),t};copyConstructorProperties(SymbolWrapper,NativeSymbol),SymbolWrapper.prototype=SymbolPrototype,SymbolPrototype.constructor=SymbolWrapper;var NATIVE_SYMBOL="Symbol(test)"==String(NativeSymbol("test")),symbolToString=uncurryThis$m(SymbolPrototype.toString),symbolValueOf=uncurryThis$m(SymbolPrototype.valueOf),regexp=/^Symbol\((.*)\)[^)]+$/,replace$3=uncurryThis$m("".replace),stringSlice$6=uncurryThis$m("".slice);defineProperty$7(SymbolPrototype,"description",{configurable:!0,get:function(){var e=symbolValueOf(this),t=symbolToString(e);if(hasOwn$7(EmptyStringDescriptionStore,e))return"";var n=NATIVE_SYMBOL?stringSlice$6(t,7,-1):replace$3(t,regexp,"$1");return""===n?void 0:n}}),$$L({global:!0,constructor:!0,forced:!0},{Symbol:SymbolWrapper})}var defineWellKnownSymbol$2=defineWellKnownSymbol$4;defineWellKnownSymbol$2("iterator");var wellKnownSymbol$8=wellKnownSymbol$q,create$1=objectCreate,defineProperty$6=objectDefineProperty.f,UNSCOPABLES=wellKnownSymbol$8("unscopables"),ArrayPrototype=Array.prototype;null==ArrayPrototype[UNSCOPABLES]&&defineProperty$6(ArrayPrototype,UNSCOPABLES,{configurable:!0,value:create$1(null)});var addToUnscopables$5=function(e){ArrayPrototype[UNSCOPABLES][e]=!0},toIndexedObject$3=toIndexedObject$b,addToUnscopables$4=addToUnscopables$5,Iterators=iterators,InternalStateModule$3=internalState,defineProperty$5=objectDefineProperty.f,defineIterator$1=defineIterator$3,DESCRIPTORS$7=descriptors,ARRAY_ITERATOR="Array Iterator",setInternalState$3=InternalStateModule$3.set,getInternalState=InternalStateModule$3.getterFor(ARRAY_ITERATOR),es_array_iterator=defineIterator$1(Array,"Array",(function(e,t){setInternalState$3(this,{type:ARRAY_ITERATOR,target:toIndexedObject$3(e),index:0,kind:t})}),(function(){var e=getInternalState(this),t=e.target,n=e.kind,r=e.index++;return!t||r>=t.length?(e.target=void 0,{value:void 0,done:!0}):"keys"==n?{value:r,done:!1}:"values"==n?{value:t[r],done:!1}:{value:[r,t[r]],done:!1}}),"values"),values$1=Iterators.Arguments=Iterators.Array;if(addToUnscopables$4("keys"),addToUnscopables$4("values"),addToUnscopables$4("entries"),DESCRIPTORS$7&&"values"!==values$1.name)try{defineProperty$5(values$1,"name",{value:"values"})}catch(e){}var domIterables={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},documentCreateElement=documentCreateElement$2,classList=documentCreateElement("span").classList,DOMTokenListPrototype$2=classList&&classList.constructor&&classList.constructor.prototype,domTokenListPrototype=DOMTokenListPrototype$2===Object.prototype?void 0:DOMTokenListPrototype$2,global$g=global$w,DOMIterables$1=domIterables,DOMTokenListPrototype$1=domTokenListPrototype,ArrayIteratorMethods=es_array_iterator,createNonEnumerableProperty$3=createNonEnumerableProperty$7,wellKnownSymbol$7=wellKnownSymbol$q,ITERATOR=wellKnownSymbol$7("iterator"),TO_STRING_TAG=wellKnownSymbol$7("toStringTag"),ArrayValues=ArrayIteratorMethods.values,handlePrototype$1=function(e,t){if(e){if(e[ITERATOR]!==ArrayValues)try{createNonEnumerableProperty$3(e,ITERATOR,ArrayValues)}catch(t){e[ITERATOR]=ArrayValues}if(e[TO_STRING_TAG]||createNonEnumerableProperty$3(e,TO_STRING_TAG,t),DOMIterables$1[t])for(var n in ArrayIteratorMethods)if(e[n]!==ArrayIteratorMethods[n])try{createNonEnumerableProperty$3(e,n,ArrayIteratorMethods[n])}catch(t){e[n]=ArrayIteratorMethods[n]}}};for(var COLLECTION_NAME$1 in DOMIterables$1)handlePrototype$1(global$g[COLLECTION_NAME$1]&&global$g[COLLECTION_NAME$1].prototype,COLLECTION_NAME$1);handlePrototype$1(DOMTokenListPrototype$1,"DOMTokenList");var DESCRIPTORS$6=descriptors,uncurryThis$l=functionUncurryThis,call$a=functionCall,fails$k=fails$G,objectKeys$1=objectKeys$4,getOwnPropertySymbolsModule=objectGetOwnPropertySymbols,propertyIsEnumerableModule=objectPropertyIsEnumerable,toObject$7=toObject$e,IndexedObject$2=indexedObject,$assign=Object.assign,defineProperty$4=Object.defineProperty,concat$1=uncurryThis$l([].concat),objectAssign=!$assign||fails$k((function(){if(DESCRIPTORS$6&&1!==$assign({b:1},$assign(defineProperty$4({},"a",{enumerable:!0,get:function(){defineProperty$4(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach((function(e){t[e]=e})),7!=$assign({},e)[n]||objectKeys$1($assign({},t)).join("")!=r}))?function(e,t){for(var n=toObject$7(e),r=arguments.length,a=1,i=getOwnPropertySymbolsModule.f,o=propertyIsEnumerableModule.f;r>a;)for(var s,l=IndexedObject$2(arguments[a++]),u=i?concat$1(objectKeys$1(l),i(l)):objectKeys$1(l),c=u.length,p=0;c>p;)s=u[p++],DESCRIPTORS$6&&!call$a(o,l,s)||(n[s]=l[s]);return n}:$assign,$$K=_export,assign$1=objectAssign;$$K({target:"Object",stat:!0,arity:2,forced:Object.assign!==assign$1},{assign:assign$1});var $TypeError$6=TypeError,MAX_SAFE_INTEGER=9007199254740991,doesNotExceedSafeInteger$2=function(e){if(e>MAX_SAFE_INTEGER)throw $TypeError$6("Maximum allowed index exceeded");return e},$$J=_export,fails$j=fails$G,isArray$4=isArray$8,isObject$c=isObject$o,toObject$6=toObject$e,lengthOfArrayLike$5=lengthOfArrayLike$b,doesNotExceedSafeInteger$1=doesNotExceedSafeInteger$2,createProperty$1=createProperty$5,arraySpeciesCreate$1=arraySpeciesCreate$3,arrayMethodHasSpeciesSupport$3=arrayMethodHasSpeciesSupport$5,wellKnownSymbol$6=wellKnownSymbol$q,V8_VERSION$1=engineV8Version,IS_CONCAT_SPREADABLE=wellKnownSymbol$6("isConcatSpreadable"),IS_CONCAT_SPREADABLE_SUPPORT=V8_VERSION$1>=51||!fails$j((function(){var e=[];return e[IS_CONCAT_SPREADABLE]=!1,e.concat()[0]!==e})),SPECIES_SUPPORT=arrayMethodHasSpeciesSupport$3("concat"),isConcatSpreadable=function(e){if(!isObject$c(e))return!1;var t=e[IS_CONCAT_SPREADABLE];return void 0!==t?!!t:isArray$4(e)},FORCED$5=!IS_CONCAT_SPREADABLE_SUPPORT||!SPECIES_SUPPORT;$$J({target:"Array",proto:!0,arity:1,forced:FORCED$5},{concat:function(e){var t,n,r,a,i,o=toObject$6(this),s=arraySpeciesCreate$1(o,0),l=0;for(t=-1,r=arguments.length;t1?arguments[1]:void 0)}});var internalMetadata={exports:{}},fails$i=fails$G,arrayBufferNonExtensible=fails$i((function(){if("function"==typeof ArrayBuffer){var e=new ArrayBuffer(8);Object.isExtensible(e)&&Object.defineProperty(e,"a",{value:8})}})),fails$h=fails$G,isObject$b=isObject$o,classof$2=classofRaw$1,ARRAY_BUFFER_NON_EXTENSIBLE=arrayBufferNonExtensible,$isExtensible=Object.isExtensible,FAILS_ON_PRIMITIVES$2=fails$h((function(){$isExtensible(1)})),objectIsExtensible=FAILS_ON_PRIMITIVES$2||ARRAY_BUFFER_NON_EXTENSIBLE?function(e){return!!isObject$b(e)&&((!ARRAY_BUFFER_NON_EXTENSIBLE||"ArrayBuffer"!=classof$2(e))&&(!$isExtensible||$isExtensible(e)))}:$isExtensible,fails$g=fails$G,freezing=!fails$g((function(){return Object.isExtensible(Object.preventExtensions({}))})),$$H=_export,uncurryThis$k=functionUncurryThis,hiddenKeys=hiddenKeys$6,isObject$a=isObject$o,hasOwn$6=hasOwnProperty_1,defineProperty$3=objectDefineProperty.f,getOwnPropertyNamesModule=objectGetOwnPropertyNames,getOwnPropertyNamesExternalModule=objectGetOwnPropertyNamesExternal,isExtensible$1=objectIsExtensible,uid=uid$4,FREEZING=freezing,REQUIRED=!1,METADATA=uid("meta"),id$1=0,setMetadata=function(e){defineProperty$3(e,METADATA,{value:{objectID:"O"+id$1++,weakData:{}}})},fastKey$1=function(e,t){if(!isObject$a(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!hasOwn$6(e,METADATA)){if(!isExtensible$1(e))return"F";if(!t)return"E";setMetadata(e)}return e[METADATA].objectID},getWeakData$1=function(e,t){if(!hasOwn$6(e,METADATA)){if(!isExtensible$1(e))return!0;if(!t)return!1;setMetadata(e)}return e[METADATA].weakData},onFreeze=function(e){return FREEZING&&REQUIRED&&isExtensible$1(e)&&!hasOwn$6(e,METADATA)&&setMetadata(e),e},enable=function(){meta.enable=function(){},REQUIRED=!0;var e=getOwnPropertyNamesModule.f,t=uncurryThis$k([].splice),n={};n[METADATA]=1,e(n).length&&(getOwnPropertyNamesModule.f=function(n){for(var r=e(n),a=0,i=r.length;ai;i++)if((s=b(e[i]))&&isPrototypeOf$4(ResultPrototype,s))return s;return new Result(!1)}r=getIterator(e,a)}for(l=d?e.next:r.next;!(u=call$9(l,r)).done;){try{s=b(u.value)}catch(e){iteratorClose(r,"throw",e)}if("object"==typeof s&&s&&isPrototypeOf$4(ResultPrototype,s))return s}return new Result(!1)},isPrototypeOf$3=objectIsPrototypeOf,$TypeError$4=TypeError,anInstance$4=function(e,t){if(isPrototypeOf$3(t,e))return e;throw $TypeError$4("Incorrect invocation")},isCallable$7=isCallable$q,isObject$9=isObject$o,setPrototypeOf$1=objectSetPrototypeOf,inheritIfRequired$3=function(e,t,n){var r,a;return setPrototypeOf$1&&isCallable$7(r=t.constructor)&&r!==n&&isObject$9(a=r.prototype)&&a!==n.prototype&&setPrototypeOf$1(e,a),e},$$G=_export,global$f=global$w,uncurryThis$j=functionUncurryThis,isForced$3=isForced_1,defineBuiltIn$7=defineBuiltIn$e,InternalMetadataModule$1=internalMetadata.exports,iterate$4=iterate$5,anInstance$3=anInstance$4,isCallable$6=isCallable$q,isObject$8=isObject$o,fails$f=fails$G,checkCorrectnessOfIteration$1=checkCorrectnessOfIteration$3,setToStringTag$4=setToStringTag$8,inheritIfRequired$2=inheritIfRequired$3,collection$3=function(e,t,n){var r=-1!==e.indexOf("Map"),a=-1!==e.indexOf("Weak"),i=r?"set":"add",o=global$f[e],s=o&&o.prototype,l=o,u={},c=function(e){var t=uncurryThis$j(s[e]);defineBuiltIn$7(s,e,"add"==e?function(e){return t(this,0===e?0:e),this}:"delete"==e?function(e){return!(a&&!isObject$8(e))&&t(this,0===e?0:e)}:"get"==e?function(e){return a&&!isObject$8(e)?void 0:t(this,0===e?0:e)}:"has"==e?function(e){return!(a&&!isObject$8(e))&&t(this,0===e?0:e)}:function(e,n){return t(this,0===e?0:e,n),this})};if(isForced$3(e,!isCallable$6(o)||!(a||s.forEach&&!fails$f((function(){(new o).entries().next()})))))l=n.getConstructor(t,e,r,i),InternalMetadataModule$1.enable();else if(isForced$3(e,!0)){var p=new l,d=p[i](a?{}:-0,1)!=p,m=fails$f((function(){p.has(1)})),f=checkCorrectnessOfIteration$1((function(e){new o(e)})),h=!a&&fails$f((function(){for(var e=new o,t=5;t--;)e[i](t,t);return!e.has(-0)}));f||((l=t((function(e,t){anInstance$3(e,s);var n=inheritIfRequired$2(new o,e,l);return null!=t&&iterate$4(t,n[i],{that:n,AS_ENTRIES:r}),n}))).prototype=s,s.constructor=l),(m||h)&&(c("delete"),c("has"),r&&c("get")),(h||d)&&c(i),a&&s.clear&&delete s.clear}return u[e]=l,$$G({global:!0,constructor:!0,forced:l!=o},u),setToStringTag$4(l,e),a||n.setStrong(l,e,r),l},defineBuiltIn$6=defineBuiltIn$e,defineBuiltIns$3=function(e,t,n){for(var r in t)defineBuiltIn$6(e,r,t[r],n);return e},getBuiltIn$3=getBuiltIn$d,definePropertyModule=objectDefineProperty,wellKnownSymbol$5=wellKnownSymbol$q,DESCRIPTORS$5=descriptors,SPECIES$3=wellKnownSymbol$5("species"),setSpecies$3=function(e){var t=getBuiltIn$3(e),n=definePropertyModule.f;DESCRIPTORS$5&&t&&!t[SPECIES$3]&&n(t,SPECIES$3,{configurable:!0,get:function(){return this}})},defineProperty$2=objectDefineProperty.f,create=objectCreate,defineBuiltIns$2=defineBuiltIns$3,bind$6=functionBindContext,anInstance$2=anInstance$4,iterate$3=iterate$5,defineIterator=defineIterator$3,setSpecies$2=setSpecies$3,DESCRIPTORS$4=descriptors,fastKey=internalMetadata.exports.fastKey,InternalStateModule$2=internalState,setInternalState$2=InternalStateModule$2.set,internalStateGetterFor$1=InternalStateModule$2.getterFor,collectionStrong$2={getConstructor:function(e,t,n,r){var a=e((function(e,a){anInstance$2(e,i),setInternalState$2(e,{type:t,index:create(null),first:void 0,last:void 0,size:0}),DESCRIPTORS$4||(e.size=0),null!=a&&iterate$3(a,e[r],{that:e,AS_ENTRIES:n})})),i=a.prototype,o=internalStateGetterFor$1(t),s=function(e,t,n){var r,a,i=o(e),s=l(e,t);return s?s.value=n:(i.last=s={index:a=fastKey(t,!0),key:t,value:n,previous:r=i.last,next:void 0,removed:!1},i.first||(i.first=s),r&&(r.next=s),DESCRIPTORS$4?i.size++:e.size++,"F"!==a&&(i.index[a]=s)),e},l=function(e,t){var n,r=o(e),a=fastKey(t);if("F"!==a)return r.index[a];for(n=r.first;n;n=n.next)if(n.key==t)return n};return defineBuiltIns$2(i,{clear:function(){for(var e=o(this),t=e.index,n=e.first;n;)n.removed=!0,n.previous&&(n.previous=n.previous.next=void 0),delete t[n.index],n=n.next;e.first=e.last=void 0,DESCRIPTORS$4?e.size=0:this.size=0},delete:function(e){var t=this,n=o(t),r=l(t,e);if(r){var a=r.next,i=r.previous;delete n.index[r.index],r.removed=!0,i&&(i.next=a),a&&(a.previous=i),n.first==r&&(n.first=a),n.last==r&&(n.last=i),DESCRIPTORS$4?n.size--:t.size--}return!!r},forEach:function(e){for(var t,n=o(this),r=bind$6(e,arguments.length>1?arguments[1]:void 0);t=t?t.next:n.first;)for(r(t.value,t.key,this);t&&t.removed;)t=t.previous},has:function(e){return!!l(this,e)}}),defineBuiltIns$2(i,n?{get:function(e){var t=l(this,e);return t&&t.value},set:function(e,t){return s(this,0===e?0:e,t)}}:{add:function(e){return s(this,e=0===e?0:e,e)}}),DESCRIPTORS$4&&defineProperty$2(i,"size",{get:function(){return o(this).size}}),a},setStrong:function(e,t,n){var r=t+" Iterator",a=internalStateGetterFor$1(t),i=internalStateGetterFor$1(r);defineIterator(e,t,(function(e,t){setInternalState$2(this,{type:r,target:e,state:a(e),kind:t,last:void 0})}),(function(){for(var e=i(this),t=e.kind,n=e.last;n&&n.removed;)n=n.previous;return e.target&&(e.last=n=n?n.next:e.state.first)?"keys"==t?{value:n.key,done:!1}:"values"==t?{value:n.value,done:!1}:{value:[n.key,n.value],done:!1}:(e.target=void 0,{value:void 0,done:!0})}),n?"entries":"values",!n,!0),setSpecies$2(t)}},collection$2=collection$3,collectionStrong$1=collectionStrong$2;collection$2("Set",(function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}}),collectionStrong$1);var fails$e=fails$G,arrayMethodIsStrict$4=function(e,t){var n=[][e];return!!n&&fails$e((function(){n.call(null,t||function(){return 1},1)}))},$forEach=arrayIteration.forEach,arrayMethodIsStrict$3=arrayMethodIsStrict$4,STRICT_METHOD$3=arrayMethodIsStrict$3("forEach"),arrayForEach=STRICT_METHOD$3?[].forEach:function(e){return $forEach(this,e,arguments.length>1?arguments[1]:void 0)},global$e=global$w,DOMIterables=domIterables,DOMTokenListPrototype=domTokenListPrototype,forEach$2=arrayForEach,createNonEnumerableProperty$2=createNonEnumerableProperty$7,handlePrototype=function(e){if(e&&e.forEach!==forEach$2)try{createNonEnumerableProperty$2(e,"forEach",forEach$2)}catch(t){e.forEach=forEach$2}};for(var COLLECTION_NAME in DOMIterables)DOMIterables[COLLECTION_NAME]&&handlePrototype(global$e[COLLECTION_NAME]&&global$e[COLLECTION_NAME].prototype);handlePrototype(DOMTokenListPrototype);var $$F=_export,$filter=arrayIteration.filter,arrayMethodHasSpeciesSupport$1=arrayMethodHasSpeciesSupport$5,HAS_SPECIES_SUPPORT$1=arrayMethodHasSpeciesSupport$1("filter");$$F({target:"Array",proto:!0,forced:!HAS_SPECIES_SUPPORT$1},{filter:function(e){return $filter(this,e,arguments.length>1?arguments[1]:void 0)}});var defineWellKnownSymbol$1=defineWellKnownSymbol$4;defineWellKnownSymbol$1("asyncIterator");var getBuiltIn$2=getBuiltIn$d,defineWellKnownSymbol=defineWellKnownSymbol$4,setToStringTag$3=setToStringTag$8;defineWellKnownSymbol("toStringTag"),setToStringTag$3(getBuiltIn$2("Symbol"),"Symbol");var global$d=global$w,setToStringTag$2=setToStringTag$8;setToStringTag$2(global$d.JSON,"JSON",!0);var setToStringTag$1=setToStringTag$8;setToStringTag$1(Math,"Math",!0);var classof$1=classofRaw$1,global$c=global$w,engineIsNode="process"==classof$1(global$c.process),anObject$7=anObject$k,aConstructor=aConstructor$2,wellKnownSymbol$4=wellKnownSymbol$q,SPECIES$2=wellKnownSymbol$4("species"),speciesConstructor$2=function(e,t){var n,r=anObject$7(e).constructor;return void 0===r||null==(n=anObject$7(r)[SPECIES$2])?t:aConstructor(n)},$TypeError$3=TypeError,validateArgumentsLength$1=function(e,t){if(e2)if(u=trim$1(u),43===(t=charCodeAt(u,0))||45===t){if(88===(n=charCodeAt(u,2))||120===n)return NaN}else if(48===t){switch(charCodeAt(u,1)){case 66:case 98:r=2,a=49;break;case 79:case 111:r=8,a=55;break;default:return+u}for(o=(i=arraySlice$2(u,2)).length,s=0;sa)return NaN;return parseInt(i,r)}return+u};if(isForced$1(NUMBER,!NativeNumber(" 0o1")||!NativeNumber("0b1")||NativeNumber("+0x1"))){for(var NumberWrapper=function(e){var t=arguments.length<1?0:NativeNumber(toNumeric(e)),n=this;return isPrototypeOf$2(NumberPrototype,n)&&fails$c((function(){thisNumberValue$1(n)}))?inheritIfRequired$1(Object(t),n,NumberWrapper):t},keys$2=DESCRIPTORS$3?getOwnPropertyNames$1(NativeNumber):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,isFinite,isInteger,isNaN,isSafeInteger,parseFloat,parseInt,fromString,range".split(","),j$2=0,key;keys$2.length>j$2;j$2++)hasOwn$4(NativeNumber,key=keys$2[j$2])&&!hasOwn$4(NumberWrapper,key)&&defineProperty$1(NumberWrapper,key,getOwnPropertyDescriptor$1(NativeNumber,key));NumberWrapper.prototype=NumberPrototype,NumberPrototype.constructor=NumberWrapper,defineBuiltIn$3(global$3,NUMBER,NumberWrapper,{constructor:!0})}var call$4=functionCall,hasOwn$3=hasOwnProperty_1,isPrototypeOf$1=objectIsPrototypeOf,regExpFlags=regexpFlags$1,RegExpPrototype$3=RegExp.prototype,regexpGetFlags=function(e){var t=e.flags;return void 0!==t||"flags"in RegExpPrototype$3||hasOwn$3(e,"flags")||!isPrototypeOf$1(RegExpPrototype$3,e)?t:call$4(regExpFlags,e)},PROPER_FUNCTION_NAME$1=functionName$1.PROPER,defineBuiltIn$2=defineBuiltIn$e,anObject$5=anObject$k,$toString=toString$i,fails$b=fails$G,getRegExpFlags$1=regexpGetFlags,TO_STRING="toString",RegExpPrototype$2=RegExp.prototype,n$ToString=RegExpPrototype$2[TO_STRING],NOT_GENERIC=fails$b((function(){return"/a/b"!=n$ToString.call({source:"a",flags:"b"})})),INCORRECT_NAME=PROPER_FUNCTION_NAME$1&&n$ToString.name!=TO_STRING;(NOT_GENERIC||INCORRECT_NAME)&&defineBuiltIn$2(RegExp.prototype,TO_STRING,(function(){var e=anObject$5(this);return"/"+$toString(e.source)+"/"+$toString(getRegExpFlags$1(e))}),{unsafe:!0});var defineProperty=objectDefineProperty.f,proxyAccessor$1=function(e,t,n){n in e||defineProperty(e,n,{configurable:!0,get:function(){return t[n]},set:function(e){t[n]=e}})},DESCRIPTORS$2=descriptors,global$2=global$w,uncurryThis$e=functionUncurryThis,isForced=isForced_1,inheritIfRequired=inheritIfRequired$3,createNonEnumerableProperty$1=createNonEnumerableProperty$7,getOwnPropertyNames=objectGetOwnPropertyNames.f,isPrototypeOf=objectIsPrototypeOf,isRegExp$2=isRegexp,toString$9=toString$i,getRegExpFlags=regexpGetFlags,stickyHelpers$1=regexpStickyHelpers,proxyAccessor=proxyAccessor$1,defineBuiltIn$1=defineBuiltIn$e,fails$a=fails$G,hasOwn$2=hasOwnProperty_1,enforceInternalState$1=internalState.enforce,setSpecies=setSpecies$3,wellKnownSymbol$2=wellKnownSymbol$q,UNSUPPORTED_DOT_ALL=regexpUnsupportedDotAll,UNSUPPORTED_NCG=regexpUnsupportedNcg,MATCH=wellKnownSymbol$2("match"),NativeRegExp=global$2.RegExp,RegExpPrototype$1=NativeRegExp.prototype,SyntaxError$1=global$2.SyntaxError,exec$1=uncurryThis$e(RegExpPrototype$1.exec),charAt$2=uncurryThis$e("".charAt),replace$1=uncurryThis$e("".replace),stringIndexOf$2=uncurryThis$e("".indexOf),stringSlice$5=uncurryThis$e("".slice),IS_NCG=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,re1=/a/g,re2=/a/g,CORRECT_NEW=new NativeRegExp(re1)!==re1,MISSED_STICKY=stickyHelpers$1.MISSED_STICKY,UNSUPPORTED_Y$1=stickyHelpers$1.UNSUPPORTED_Y,BASE_FORCED=DESCRIPTORS$2&&(!CORRECT_NEW||MISSED_STICKY||UNSUPPORTED_DOT_ALL||UNSUPPORTED_NCG||fails$a((function(){return re2[MATCH]=!1,NativeRegExp(re1)!=re1||NativeRegExp(re2)==re2||"/a/i"!=NativeRegExp(re1,"i")}))),handleDotAll=function(e){for(var t,n=e.length,r=0,a="",i=!1;r<=n;r++)"\\"!==(t=charAt$2(e,r))?i||"."!==t?("["===t?i=!0:"]"===t&&(i=!1),a+=t):a+="[\\s\\S]":a+=t+charAt$2(e,++r);return a},handleNCG=function(e){for(var t,n=e.length,r=0,a="",i=[],o={},s=!1,l=!1,u=0,c="";r<=n;r++){if("\\"===(t=charAt$2(e,r)))t+=charAt$2(e,++r);else if("]"===t)s=!1;else if(!s)switch(!0){case"["===t:s=!0;break;case"("===t:exec$1(IS_NCG,stringSlice$5(e,r+1))&&(r+=2,l=!0),a+=t,u++;continue;case">"===t&&l:if(""===c||hasOwn$2(o,c))throw new SyntaxError$1("Invalid capture group name");o[c]=!0,i[i.length]=[c,u],l=!1,c="";continue}l?c+=t:a+=t}return[a,i]};if(isForced("RegExp",BASE_FORCED)){for(var RegExpWrapper=function(e,t){var n,r,a,i,o,s,l=isPrototypeOf(RegExpPrototype$1,this),u=isRegExp$2(e),c=void 0===t,p=[],d=e;if(!l&&u&&c&&e.constructor===RegExpWrapper)return e;if((u||isPrototypeOf(RegExpPrototype$1,e))&&(e=e.source,c&&(t=getRegExpFlags(d))),e=void 0===e?"":toString$9(e),t=void 0===t?"":toString$9(t),d=e,UNSUPPORTED_DOT_ALL&&"dotAll"in re1&&(r=!!t&&stringIndexOf$2(t,"s")>-1)&&(t=replace$1(t,/s/g,"")),n=t,MISSED_STICKY&&"sticky"in re1&&(a=!!t&&stringIndexOf$2(t,"y")>-1)&&UNSUPPORTED_Y$1&&(t=replace$1(t,/y/g,"")),UNSUPPORTED_NCG&&(e=(i=handleNCG(e))[0],p=i[1]),o=inheritIfRequired(NativeRegExp(e,t),l?this:RegExpPrototype$1,RegExpWrapper),(r||a||p.length)&&(s=enforceInternalState$1(o),r&&(s.dotAll=!0,s.raw=RegExpWrapper(handleDotAll(e),n)),a&&(s.sticky=!0),p.length&&(s.groups=p)),e!==d)try{createNonEnumerableProperty$1(o,"source",""===d?"(?:)":d)}catch(e){}return o},keys$1=getOwnPropertyNames(NativeRegExp),index=0;keys$1.length>index;)proxyAccessor(RegExpWrapper,NativeRegExp,keys$1[index++]);RegExpPrototype$1.constructor=RegExpWrapper,RegExpWrapper.prototype=RegExpPrototype$1,defineBuiltIn$1(global$2,"RegExp",RegExpWrapper,{constructor:!0})}setSpecies("RegExp");var collection$1=collection$3,collectionStrong=collectionStrong$2;function _typeof$1d(e){return _typeof$1d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$1d(e)}function _defineProperties$1P(e,t){for(var n=0;n15?n:(t=Math.round(t),round_numbers_to_precision_sub(n,t))}const round_numbers_to_precision_sub=function(e,t=14){if("number"==typeof e&&Number.isFinite(e)&&0!==e){const n=math$1.floor(math$1.log10(math$1.abs(e))),r=t-n-1;return r<0?parseFloat(toFixed(e,r)+"0".repeat(math$1.abs(r))):parseFloat(toFixed(e,r))}return Array.isArray(e)?[e[0],...e.slice(1).map((e=>round_numbers_to_precision_sub(e,t)))]:e};function round_numbers_to_decimals(e,t=14){var n=get_tree(e);if(!Number.isFinite(t))throw Error("For round_numbers_to_decimals, ndecimals must be a number");return t=Math.round(t),t=Math.max(-330,Math.min(330,t)),round_numbers_to_decimals_sub(n,t)}const round_numbers_to_decimals_sub=function(e,t=0){return"number"==typeof e?t<0?parseFloat(toFixed(e,t)+"0".repeat(math$1.abs(t))):parseFloat(toFixed(e,t)):Array.isArray(e)?[e[0],...e.slice(1).map((e=>round_numbers_to_decimals_sub(e,t)))]:e};var round=Object.freeze({__proto__:null,round_numbers_to_precision:round_numbers_to_precision,round_numbers_to_decimals:round_numbers_to_decimals});const match=function(e,t,n){let r=get_tree(e),a=get_tree(t);return match$2(r,a,n)};var match$1=Object.freeze({__proto__:null,match:match});const expression_to_tree$1=[simplify$1,differentiation,normalization,arithmetic,transformation,solve,sets,matrix$1,rational,round],expression_to_other=[variables$1,printing,equality,integration,evaluation,analytic,sign_error,match$1];function abs(e){return["apply","abs",get_tree(e)]}function exp(e){return["apply","exp",get_tree(e)]}function log(e){return["apply","log",get_tree(e)]}function log10(e){return["apply","log10",get_tree(e)]}function sign(e){return["apply","sign",get_tree(e)]}function sqrt(e){return["apply","sqrt",get_tree(e)]}function conj(e){return["apply","conj",get_tree(e)]}function im(e){return["apply","im",get_tree(e)]}function re(e){return["apply","re",get_tree(e)]}function factorial(e){return["apply","factorial",get_tree(e)]}function gamma(e){return["apply","gamma",get_tree(e)]}function erf(e){return["apply","erf",get_tree(e)]}function acos(e){return["apply","acos",get_tree(e)]}function acosh(e){return["apply","acosh",get_tree(e)]}function acot(e){return["apply","acot",get_tree(e)]}function acoth(e){return["apply","acoth",get_tree(e)]}function acsc(e){return["apply","acsc",get_tree(e)]}function acsch(e){return["apply","acsch",get_tree(e)]}function asec(e){return["apply","asec",get_tree(e)]}function asech(e){return["apply","asech",get_tree(e)]}function asin(e){return["apply","asin",get_tree(e)]}function asinh(e){return["apply","asinh",get_tree(e)]}function atan(e){return["apply","atan",get_tree(e)]}function atanh(e){return["apply","atanh",get_tree(e)]}function cos(e){return["apply","cos",get_tree(e)]}function cosh(e){return["apply","cosh",get_tree(e)]}function cot(e){return["apply","cot",get_tree(e)]}function coth(e){return["apply","coth",get_tree(e)]}function csc(e){return["apply","csc",get_tree(e)]}function csch(e){return["apply","csch",get_tree(e)]}function sec(e){return["apply","sec",get_tree(e)]}function sech(e){return["apply","sech",get_tree(e)]}function sin(e){return["apply","sin",get_tree(e)]}function sinh(e){return["apply","sinh",get_tree(e)]}function tan(e){return["apply","tan",get_tree(e)]}function tanh(e){return["apply","tanh",get_tree(e)]}function atan2(e,t){return["apply","atan2",["tuple",get_tree(e),get_tree(t)]]}var standard=Object.freeze({__proto__:null,abs:abs,exp:exp,log:log,log10:log10,sign:sign,sqrt:sqrt,conj:conj,im:im,re:re,factorial:factorial,gamma:gamma,erf:erf,acos:acos,acosh:acosh,acot:acot,acoth:acoth,acsc:acsc,acsch:acsch,asec:asec,asech:asech,asin:asin,asinh:asinh,atan:atan,atanh:atanh,cos:cos,cosh:cosh,cot:cot,coth:coth,csc:csc,csch:csch,sec:sec,sech:sech,sin:sin,sinh:sinh,tan:tan,tanh:tanh,atan2:atan2});const expression_to_tree=[standard],whitespace_rule="\\s|\\\\,|\\\\!|\\\\ |\\\\>|\\\\;|\\\\:|\\\\quad\\b|\\\\qquad\\b",sci_notat_exp_regex="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))?",number_rules_sci=[["[0-9]+(\\.[0-9]*)?"+sci_notat_exp_regex,"NUMBER"],["\\.[0-9]+"+sci_notat_exp_regex,"NUMBER"]],number_rules_non_sci=[["[0-9]+(\\.[0-9]*)?","NUMBER"],["\\.[0-9]+","NUMBER"]],base_latex_rules=[["\\*","*"],["\\/","/"],["-","-"],["\\+","+"],["\\^","^"],["\\(","("],["\\\\left\\s*\\(","("],["\\\\bigl\\s*\\(","("],["\\\\Bigl\\s*\\(","("],["\\\\biggl\\s*\\(","("],["\\\\Biggl\\s*\\(","("],["\\)",")"],["\\\\right\\s*\\)",")"],["\\\\bigr\\s*\\)",")"],["\\\\Bigr\\s*\\)",")"],["\\\\biggr\\s*\\)",")"],["\\\\Biggr\\s*\\)",")"],["\\[","["],["\\\\left\\s*\\[","["],["\\\\bigl\\s*\\[","["],["\\\\Bigl\\s*\\[","["],["\\\\biggl\\s*\\[","["],["\\\\Biggl\\s*\\[","["],["\\]","]"],["\\\\right\\s*\\]","]"],["\\\\bigr\\s*\\]","]"],["\\\\Bigr\\s*\\]","]"],["\\\\biggr\\s*\\]","]"],["\\\\Biggr\\s*\\]","]"],["\\|","|"],["\\\\left\\s*\\|","|L"],["\\\\bigl\\s*\\|","|L"],["\\\\Bigl\\s*\\|","|L"],["\\\\biggl\\s*\\|","|L"],["\\\\Biggl\\s*\\|","|L"],["\\\\right\\s*\\|","|"],["\\\\bigr\\s*\\|","|"],["\\\\Bigr\\s*\\|","|"],["\\\\biggr\\s*\\|","|"],["\\\\Biggr\\s*\\|","|"],["\\\\big\\s*\\|","|"],["\\\\Big\\s*\\|","|"],["\\\\bigg\\s*\\|","|"],["\\\\Bigg\\s*\\|","|"],["{","{"],["}","}"],["\\\\{","LBRACE"],["\\\\left\\s*\\\\{","LBRACE"],["\\\\bigl\\s*\\\\{","LBRACE"],["\\\\Bigl\\s*\\\\{","LBRACE"],["\\\\biggl\\s*\\\\{","LBRACE"],["\\\\Biggl\\s*\\\\{","LBRACE"],["\\\\}","RBRACE"],["\\\\right\\s*\\\\}","RBRACE"],["\\\\bigr\\s*\\\\}","RBRACE"],["\\\\Bigr\\s*\\\\}","RBRACE"],["\\\\biggr\\s*\\\\}","RBRACE"],["\\\\Biggr\\s*\\\\}","RBRACE"],["\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\left\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\bigl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\Bigl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\biggl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\Biggl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\right\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\bigr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\Bigr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\biggr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\Biggr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\left\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\bigl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\Bigl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\biggl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\Biggl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\right\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\bigr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\Bigr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\biggr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\Biggr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\left\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\bigl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\Bigl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\biggl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\Biggl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\right\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\bigr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\Bigr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\biggr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\Biggr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\cdot(?![a-zA-Z])","*"],["\\\\div(?![a-zA-Z])","/"],["\\\\times(?![a-zA-Z])","*"],[",",","],[":",":"],["\\\\mid(?![a-zA-Z])","MID"],["\\\\vartheta(?![a-zA-Z])","LATEXCOMMAND","\\theta"],["\\\\varepsilon(?![a-zA-Z])","LATEXCOMMAND","\\epsilon"],["\\\\varrho(?![a-zA-Z])","LATEXCOMMAND","\\rho"],["\\\\varphi(?![a-zA-Z])","LATEXCOMMAND","\\phi"],["\\\\infty(?![a-zA-Z])","INFINITY"],["\\\\asin(?![a-zA-Z])","LATEXCOMMAND","\\arcsin"],["\\\\acos(?![a-zA-Z])","LATEXCOMMAND","\\arccos"],["\\\\atan(?![a-zA-Z])","LATEXCOMMAND","\\arctan"],["\\\\sqrt(?![a-zA-Z])","SQRT"],["\\\\land(?![a-zA-Z])","AND"],["\\\\wedge(?![a-zA-Z])","AND"],["\\\\lor(?![a-zA-Z])","OR"],["\\\\vee(?![a-zA-Z])","OR"],["\\\\lnot(?![a-zA-Z])","NOT"],["=","="],["\\\\neq(?![a-zA-Z])","NE"],["\\\\ne(?![a-zA-Z])","NE"],["\\\\not\\s*=","NE"],["\\\\leq(?![a-zA-Z])","LE"],["\\\\le(?![a-zA-Z])","LE"],["\\\\geq(?![a-zA-Z])","GE"],["\\\\ge(?![a-zA-Z])","GE"],["<","<"],["\\\\lt(?![a-zA-Z])","<"],[">",">"],["\\\\gt(?![a-zA-Z])",">"],["\\\\in(?![a-zA-Z])","IN"],["\\\\notin(?![a-zA-Z])","NOTIN"],["\\\\not\\s*\\\\in(?![a-zA-Z])","NOTIN"],["\\\\ni(?![a-zA-Z])","NI"],["\\\\not\\s*\\\\ni(?![a-zA-Z])","NOTNI"],["\\\\subset(?![a-zA-Z])","SUBSET"],["\\\\subseteq(?![a-zA-Z])","SUBSETEQ"],["\\\\not\\s*\\\\subset(?![a-zA-Z])","NOTSUBSET"],["\\\\not\\s*\\\\subseteq(?![a-zA-Z])","NOTSUBSETEQ"],["\\\\supset(?![a-zA-Z])","SUPERSET"],["\\\\supseteq(?![a-zA-Z])","SUPERSETEQ"],["\\\\not\\s*\\\\supset(?![a-zA-Z])","NOTSUPERSET"],["\\\\not\\s*\\\\supseteq(?![a-zA-Z])","NOTSUPERSETEQ"],["\\\\cup(?![a-zA-Z])","UNION"],["\\\\cap(?![a-zA-Z])","INTERSECT"],["\\\\perp(?![a-zA-Z])","PERP"],["\\\\bot(?![a-zA-Z])","PERP"],["\\\\parallel(?![a-zA-Z])","PARALLEL"],["\\\\\\|","PARALLEL"],["\\\\angle(?![a-zA-Z])","ANGLE"],["\\\\int(?![a-zA-Z])","INT"],["!","!"],["'","'"],["_","_"],["&","&"],["\\\\ldots(?![a-zA-Z])","LDOTS"],["\\\\\\\\","LINEBREAK"],["\\\\begin\\s*{\\s*[a-zA-Z0-9]+\\s*}","BEGINENVIRONMENT"],["\\\\end\\s*{\\s*[a-zA-Z0-9]+\\s*}","ENDENVIRONMENT"],["\\\\operatorname\\s*{\\s*[a-zA-Z0-9\\+\\-]+\\s*}","VARMULTICHAR"],["\\\\[a-zA-Z]+(?![a-zA-Z])","LATEXCOMMAND"],["\\\\[$%]","LATEXCOMMAND"],["[a-zA-Z_$%]","VAR"]],allowSimplifiedFunctionApplicationDefault=!0,allowedLatexSymbolsDefault=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","angle","circ","%","$"],appliedFunctionSymbolsDefault=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","conj","Re","Im","det","trace","nPr","nCr","floor","ceil","round"],functionSymbolsDefault=["f","g"],operatorSymbolsDefault={frac:{nargs:2,substitute:"/"},binom:{nargs:2},vec:{nargs:1},overline:{nargs:1,substitute:"linesegment",remove_products:!0}},unitsDefault=get_all_units();unitsDefault.circ=unitsDefault.deg,unitsDefault.circ.substitute="deg",unitsDefault.circ.isExponent=!0,delete unitsDefault.deg;const parseLeibnizNotationDefault=!0;class latexToAst$1{constructor({allowSimplifiedFunctionApplication:e=allowSimplifiedFunctionApplicationDefault,allowedLatexSymbols:t=allowedLatexSymbolsDefault,appliedFunctionSymbols:n=appliedFunctionSymbolsDefault,functionSymbols:r=functionSymbolsDefault,operatorSymbols:a=operatorSymbolsDefault,units:i=unitsDefault,parseLeibnizNotation:s=parseLeibnizNotationDefault,parseScientificNotation:o=!0}={}){this.allowSimplifiedFunctionApplication=e,this.allowedLatexSymbols=t,this.appliedFunctionSymbols=n,this.functionSymbols=r,this.operatorSymbols=a,this.units=i,this.parseLeibnizNotation=s;let l=base_latex_rules;l=o?[...number_rules_sci,...l]:[...number_rules_non_sci,...l],this.lexer=new lexer(l,whitespace_rule)}advance(e){if(this.token=this.lexer.advance(e),"INVALID"===this.token.token_type)throw new ParseError("Invalid symbol '"+this.token.original_text+"'",this.lexer.location)}return_state(){return{lexer_state:this.lexer.return_state(),token:Object.assign({},this.token)}}set_state(e){this.lexer.set_state(e.lexer_state),this.token=Object.assign({},e.token)}convert(e){this.lexer.set_input(e),this.advance();var t=this.statement_list();if("EOF"!==this.token.token_type)throw new ParseError("Invalid location of '"+this.token.original_text+"'",this.lexer.location);return flatten(t)}statement_list(){for(var e=[this.statement()];","===this.token.token_type;)this.advance(),e.push(this.statement());return e.length>1?["list"].concat(e):e[0]}statement({inside_absolute_value:e=0}={}){if("LDOTS"===this.token.token_type)return this.advance(),["ldots"];var t;try{t=this.return_state();let n=this.statement_a({inside_absolute_value:e});if(":"!==this.token.token_type&&"MID"!==this.token.token_type)return n;let r=":"===this.token.token_type?":":"|";return this.advance(),[r,n,this.statement_a()]}catch(e){try{this.set_state(t);let n=this.statement_a({parse_absolute_value:!1});if("|"!==this.token.token_type[0])throw e;return this.advance(),["|",n,this.statement_a({parse_absolute_value:!1})]}catch(t){throw e}}}statement_a({inside_absolute_value:e=0,parse_absolute_value:t=!0}={}){for(var n=this.statement_b({inside_absolute_value:e,parse_absolute_value:t});"OR"===this.token.token_type;){let r=this.token.token_type.toLowerCase();this.advance(),n=[r,n,this.statement_b({inside_absolute_value:e,parse_absolute_value:t})]}return n}statement_b(e){for(var t=this.relation(e);"AND"===this.token.token_type;){let n=this.token.token_type.toLowerCase();this.advance(),t=[n,t,this.relation(e)]}return t}relation(e){if("NOT"===this.token.token_type||"!"===this.token.token_type)return this.advance(),["not",this.relation(e)];for(var t=this.expression(e);"="===this.token.token_type||"NE"===this.token.token_type||"<"===this.token.token_type||">"===this.token.token_type||"LE"===this.token.token_type||"GE"===this.token.token_type||"IN"===this.token.token_type||"NOTIN"===this.token.token_type||"NI"===this.token.token_type||"NOTNI"===this.token.token_type||"SUBSET"===this.token.token_type||"NOTSUBSET"===this.token.token_type||"SUBSETEQ"===this.token.token_type||"NOTSUBSETEQ"===this.token.token_type||"SUPERSET"===this.token.token_type||"NOTSUPERSET"===this.token.token_type||"SUPERSETEQ"===this.token.token_type||"NOTSUPERSETEQ"===this.token.token_type;){let n=this.token.token_type.toLowerCase(),r=0;"<"===this.token.token_type||"LE"===this.token.token_type?r=-1:">"!==this.token.token_type&&"GE"!==this.token.token_type||(r=1),this.advance();let a=this.expression(e);if(-1===r)if("<"===this.token.token_type||"LE"===this.token.token_type){let r=["tuple"];"<"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;"<"===this.token.token_type||"LE"===this.token.token_type;)"<"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["lts",i,r]}else t=[n,t,a];else if(1===r)if(">"===this.token.token_type||"GE"===this.token.token_type){let r=["tuple"];">"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;">"===this.token.token_type||"GE"===this.token.token_type;)">"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["gts",i,r]}else t=[n,t,a];else if("="===n)for(t=["=",t,a];"="===this.token.token_type;)this.advance(),t.push(this.expression(e));else t=[n,t,a]}return t}expression(e){let t=!1;"+"===this.token.token_type&&(t=!0,this.advance());let n=!1;"-"===this.token.token_type&&(n=!0,this.advance());var r=this.term(e);if(n||t){if(!1===r)return(t?"+":"")+(n?"-":"");if("string"==typeof r&&[...r].every((e=>["+","-"].includes(e))))return(t?"+":"")+(n?"-":"")+r}for(!1===r&&(r="_"),n&&(r=r>0?-r:["-",r]),t&&(r=["+",r]);["+","-","UNION","INTERSECT","PERP","PARALLEL"].includes(this.token.token_type);){let t=this.token.token_type.toLowerCase(),n=!1,a=!1;"-"===this.token.token_type?(t="+",n=!0,this.advance()):(this.advance(),"+"===t&&"-"===this.token.token_type&&(n=!0,a=!0,this.advance()));let i=this.term(e);if("+"===t){if(!1===i&&("number"==typeof r||"string"==typeof r))return a?r+"+-":n?r+"-":r+"+";if("string"==typeof i&&[...i].every((e=>["+","-"].includes(e)))&&("number"==typeof r||"string"==typeof r))return a?r+"+-"+i:n?r+"-"+i:r+"+"+i}!1===i&&(i="_"),n&&(i=i>0?-i:["-",i]),r=[t,r,i]}return r}term(e){var t=this.factor(e),n=!1;do{if(n=!1,"*"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["*",t,r],n=!0}else if("/"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["/",t,r],n=!0}else{let r=Object.assign({},e);r.allow_absolute_value_closing=!0;let a=this.nonMinusFactor(r);!1!==a&&(!1===t&&(t="_"),t=["*",t,a],n=!0)}}while(n);return this.convert_units_in_term(flatten(t))}convert_units_in_term(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);if("*"===t){let e=n.length;for(let[t,r]of n.entries()){let a=this.units[r];if(a){if(a.prefix&&t0){let i,s=r;return a.substitute&&(s=a.substitute),i=1===t?["unit",n[0],s]:["unit",["*",...n.slice(0,t).map(this.convert_units_in_term.bind(this))],s],t===e-1?i:this.convert_units_in_term(["*",i,...n.slice(t+1)])}}}return[t,...n.map(this.convert_units_in_term.bind(this))]}if("/"===t)return["/",this.convert_units_in_term(n[0]),this.convert_units_in_term(n[1])];if("^"===t){let e=this.units[n[1]];if(e&&e.isExponent){let t=n[1];return e.substitute&&(t=e.substitute),["unit",n[0],t]}return[t,...n.map(this.convert_units_in_term.bind(this))]}return[t,...n.map(this.convert_units_in_term.bind(this))]}factor(e){if("+"===this.token.token_text){this.advance();let t=this.factor(e);return!1===t?"+":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"+"+t:["+",t]}if("-"===this.token.token_type){this.advance();let t=this.factor(e);return t>0?-t:!1===t?"-":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"-"+t:["-",t]}let t=this.nonMinusFactor(e);return!1===t&&"PERP"===this.token.token_type&&(t="perp",this.advance()),t}nonMinusFactor(e){for(var t=this.baseFactor(e);"^"===this.token.token_type||"!"===this.token.token_type||"'"===this.token.token_type;)!1===t&&(t="_"),"^"===this.token.token_type?(this.advance(),t=["^",t,this.get_subsuperscript(e)]):"!"===this.token.token_type?(t=["apply","factorial",t],this.advance()):(t=["prime",t],this.advance());return t}get_single_digit_as_number(){if("NUMBER"===this.token.token_type&&"."!==this.token.token_text[0]){let e=Number(this.token.token_text[0]);return this.token.token_text.length>1&&this.lexer.unput(this.token.token_text.slice(1)),this.advance(),e}return null}get_subsuperscript({parse_absolute_value:e}){let t=this.get_single_digit_as_number();if(null!==t)return t;if(["+","-","PERP"].includes(this.token.token_type)){let e=this.token.token_type.toLowerCase();return this.advance(),e}{let t=this.baseFactor({parse_absolute_value:e,in_subsuperscript_with_no_delimiters:!0});return!1===t&&(t="_"),t}}baseFactor({inside_absolute_value:e=0,parse_absolute_value:t=!0,allow_absolute_value_closing:n=!1,in_subsuperscript_with_no_delimiters:r=!1}={}){var a=!1;if("BEGINENVIRONMENT"===this.token.token_type){let e=/\\begin\s*{\s*([a-zA-Z0-9]+)\s*}/.exec(this.token.token_text)[1];if(["matrix","pmatrix","bmatrix"].includes(e)){let n=0,r=0,i=[],s=[],o=0,l=this.token.token_type;for(this.advance();"ENDENVIRONMENT"!==this.token.token_type;)"&"===this.token.token_type?("&"!==l&&"LINEBREAK"!==l||(s.push(0),o+=1),l=this.token.token_type,this.advance()):"LINEBREAK"===this.token.token_type?("&"!==l&&"LINEBREAK"!==l||(s.push(0),o+=1),i.push(s),o>r&&(r=o),n+=1,o=0,s=[],l=this.token.token_type,this.advance()):(s.push(this.statement({parse_absolute_value:t})),o+=1,l=" ");if(/\\end\s*{\s*([a-zA-Z0-9]+)\s*}/.exec(this.token.token_text)[1]!==e)throw new ParseError("Expecting \\end{"+e+"}",this.lexer.location);"&"===l&&(s.push(0),o+=1),i.push(s),o>r&&(r=o),n+=1,this.advance(),a=["matrix",["tuple",n,r]];let u=["tuple"];for(let e of i){let t=["tuple"].concat(e);for(let n=e.length;n=2?a[0]="("===n||"{"===n?"tuple":"["===n?"array":"LBRACE"===n?"set":"altvector":"LBRACE"===n&&("|"===a[0]||a[0],a=["set",a]);this.advance()}else if("|"!==this.token.token_type[0]||!t||0!==e&&n&&"L"!==this.token.token_type[1]){if("LFLOOR"===this.token.token_type||"LCEIL"===this.token.token_type){let e,t;if("LFLOOR"===this.token.token_type?(e="RFLOOR",t="floor"):"LCEIL"===this.token.token_type&&(e="RCEIL",t="ceil"),this.advance(),a=["apply",t,a=this.statement()],this.token.token_type!==e)throw new ParseError("Expecting "+e,this.lexer.location);this.advance()}else if("ANGLE"===this.token.token_type)if(this.advance(),"{"===this.token.token_type||"("===this.token.token_type){let e;e="{"===this.token.token_type?"}":")",this.advance();let t=this.statement_list();if(this.token.token_type!==e)throw new ParseError("Expecting "+e,this.lexer.location);this.advance(),"list"===t[0]?a=["angle",...t.slice(1)]:"*"===t[0]&&(a=["angle",t])}else{let e=[],n=this.nonMinusFactor({parse_absolute_value:t});for(;!1!==n;)e.push(n),n=this.nonMinusFactor({parse_absolute_value:t});a=0===e.length?"angle":["angle",...e]}else if("INT"===this.token.token_type){this.advance();let e="int";"_"===this.token.token_type&&(this.advance(),e=["_",e,this.get_subsuperscript({parse_absolute_value:t})]),"^"===this.token.token_type&&(this.advance(),e=["^",e,this.get_subsuperscript({parse_absolute_value:t})]);let n=flatten(this.term({parse_absolute_value:t}));if(Array.isArray(n)&&"*"===n[0]){let e=[];for(let t=0;tn)return!1;if(s===n){if("}"!==this.token.token_type)return!1;this.advance();let s="derivative_leibniz";"∂"===t&&(s="partial_"+s),e=[s],1===n?e.push(r):e.push(["tuple",r,n]);let o=[];for(let e=0;e,larger":function(e){return[">",e[0],e[1]]},"<=,smallerEq":function(e){return["le",e[0],e[1]]},">=,largerEq":function(e){return["ge",e[0],e[1]]},"!=,unequal":function(e){return["ne",e[0],e[1]]},"!,factorial":function(e){return["apply","factorial",e[0]]}};class mathjsToAst{convert(e){if(e.isConstantNode)return e.value;if(e.isSymbolNode)return e.name;if(e.isOperatorNode){var t=[e.op,e.fn].join(",");if(t in operators)return operators[t](e.args.map(function(e,t){return this.convert(e)}.bind(this)));throw Error("Unsupported operator: "+e.op+", "+e.fn)}if(e.isFunctionNode){var n=e.args.map(function(e,t){return this.convert(e)}.bind(this));n=n.length>1?["tuple"].concat(n):n[0];var r=["apply",e.name];return r.push(n),r}if(e.isArrayNode)return["vector"].concat(e.args.map(function(e,t){return this.convert(e)}.bind(this)));if(e.isParenthesisNode)return this.convert(e.content);throw Error("Unsupported node type: "+e.type)}}class mathjsToGuppy{constructor(){this.mathjsToAst=new mathjsToAst,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.mathjsToAst.convert(e))}}class mathjsToLatex{constructor(){this.mathjsToAst=new mathjsToAst,this.astToLatex=new astToLatex$1}convert(e){return this.astToLatex.convert(this.mathjsToAst.convert(e))}}class mathjsToText{constructor(){this.mathjsToAst=new mathjsToAst,this.astToText=new astToText$2}convert(e){return this.astToText.convert(this.mathjsToAst.convert(e))}}function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex1)for(var n=1;n0)return parse$1(e);if("number"===n&&!1===isNaN(e))return t.long?fmtLong(e):fmtShort(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse$1(e){if(!((e=String(e)).length>100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function fmtShort(e){return e>=d?Math.round(e/d)+"d":e>=h?Math.round(e/h)+"h":e>=m?Math.round(e/m)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function fmtLong(e){return plural(e,d,"day")||plural(e,h,"hour")||plural(e,m,"minute")||plural(e,s,"second")||e+" ms"}function plural(e,t,n){if(!(e=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(n())}(browser,browser.exports);var debug=browser.exports("xml-parser"),xmlParser=parse;function parse(e){return e=(e=e.trim()).replace(//g,""),{declaration:function(){if(n(/^<\?xml\s*/)){for(var e={attributes:{}};!r()&&!a("?>");){var i=t();if(!i)return e;e.attributes[i.name]=i.value}return n(/\?>\s*/),e}}(),root:function i(){debug("tag %j",e);var s=n(/^<([\w-:.]+)\s*/);if(s){for(var o,l={name:s[1],attributes:{},children:[]};!(r()||a(">")||a("?>")||a("/>"));){var u=t();if(!u)return l;l.attributes[u.name]=u.value}if(n(/^\s*\/>\s*/))return l;for(n(/\??>\s*/),l.content=function(){debug("content %j",e);var t=n(/^([^<]*)/);return t?t[1]:""}();o=i();)l.children.push(o);return n(/^<\/[\w-:.]+>\s*/),l}}()};function t(){debug("attribute %j",e);var t,r=n(/([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/);if(r)return{name:r[1],value:(t=r[2],t.replace(/^['"]|['"]$/g,""))}}function n(t){var n=e.match(t);if(n)return e=e.slice(n[0].length),n}function r(){return 0==e.length}function a(t){return 0==e.indexOf(t)}}const entities={"Α":"\\Alpha","Α":"\\Alpha","Α":"\\Alpha","\\u0391;":"\\Alpha","Β":"\\Beta","Β":"\\Beta","Β":"\\Beta","\\u0392;":"\\Beta","Γ":"\\Gamma","Γ":"\\Gamma","Γ":"\\Gamma","\\u0393;":"\\Gamma","Δ":"\\Delta","Δ":"\\Delta","Δ":"\\Delta","\\u0394;":"\\Delta","Ε":"\\Epsilon","Ε":"\\Epsilon","Ε":"\\Epsilon","\\u0395;":"\\Epsilon","Ζ":"\\Zeta","Ζ":"\\Zeta","Ζ":"\\Zeta","\\u0396;":"\\Zeta","Η":"\\Eta","Η":"\\Eta","Η":"\\Eta","\\u0397;":"\\Eta","Θ":"\\Theta","Θ":"\\Theta","Θ":"\\Theta","\\u0398;":"\\Theta","Ι":"\\Iota","Ι":"\\Iota","Ι":"\\Iota","\\u0399;":"\\Iota","Κ":"\\Kappa","Κ":"\\Kappa","Κ":"\\Kappa","\\u039A;":"\\Kappa","Λ":"\\Lambda","Λ":"\\Lambda","Λ":"\\Lambda","\\u039B;":"\\Lambda","Μ":"\\Mu","Μ":"\\Mu","Μ":"\\Mu","\\u039C;":"\\Mu","Ν":"\\Nu","Ν":"\\Nu","Ν":"\\Nu","\\u039D;":"\\Nu","Ξ":"\\Xi","Ξ":"\\Xi","Ξ":"\\Xi","\\u039E;":"\\Xi","Ο":"\\Omicron","Ο":"\\Omicron","Ο":"\\Omicron","\\u039F;":"\\Omicron","Π":"\\Pi","Π":"\\Pi","Π":"\\Pi","\\u03A0;":"\\Pi","Ρ":"\\Rho","Ρ":"\\Rho","Ρ":"\\Rho","\\u03A1;":"\\Rho","Σ":"\\Sigma","Σ":"\\Sigma","Σ":"\\Sigma","\\u03A3;":"\\Sigma","Τ":"\\Tau","Τ":"\\Tau","Τ":"\\Tau","\\u03A4;":"\\Tau","Υ":"\\Upsilon","Υ":"\\Upsilon","Υ":"\\Upsilon","\\u03A5;":"\\Upsilon","Φ":"\\Phi","Φ":"\\Phi","Φ":"\\Phi","\\u03A6;":"\\Phi","Χ":"\\Chi","Χ":"\\Chi","Χ":"\\Chi","\\u03A7;":"\\Chi","Ψ":"\\Psi","Ψ":"\\Psi","Ψ":"\\Psi","\\u03A8;":"\\Psi","Ω":"\\Omega","Ω":"\\Omega","Ω":"\\Omega","\\u03A9;":"\\Omega","α":"\\alpha","α":"\\alpha","α":"\\alpha","\\u03B1;":"\\alpha","β":"\\beta","β":"\\beta","β":"\\beta","\\u03B2;":"\\beta","γ":"\\gamma","γ":"\\gamma","γ":"\\gamma","\\u03B3;":"\\gamma","δ":"\\delta","δ":"\\delta","δ":"\\delta","\\u03B4;":"\\delta","ε":"\\epsilon","ε":"\\epsilon","ε":"\\epsilon","\\u03B5;":"\\epsilon","ζ":"\\zeta","ζ":"\\zeta","ζ":"\\zeta","\\u03B6;":"\\zeta","η":"\\eta","η":"\\eta","η":"\\eta","\\u03B7;":"\\eta","θ":"\\theta","θ":"\\theta","θ":"\\theta","\\u03B8;":"\\theta","ι":"\\iota","ι":"\\iota","ι":"\\iota","\\u03B9;":"\\iota","κ":"\\kappa","κ":"\\kappa","κ":"\\kappa","\\u03BA;":"\\kappa","λ":"\\lambda","λ":"\\lambda","λ":"\\lambda","\\u03BB;":"\\lambda","μ":"\\mu","μ":"\\mu","μ":"\\mu","\\u03BC;":"\\mu","ν":"\\nu","ν":"\\nu","ν":"\\nu","\\u03BD;":"\\nu","ξ":"\\xi","ξ":"\\xi","ξ":"\\xi","\\u03BE;":"\\xi","ο":"\\omicron","ο":"\\omicron","ο":"\\omicron","\\u03BF;":"\\omicron","π":"\\pi","π":"\\pi","π":"\\pi","\\u03C0;":"\\pi","ρ":"\\rho","ρ":"\\rho","ρ":"\\rho","\\u03C1;":"\\rho","ς":"\\sigma",";":"\\sigma","ς":"\\sigma","\\u03C2;":"\\sigma","σ":"\\sigma","σ":"\\sigma","σ":"\\sigma","\\u03C3;":"\\sigma","τ":"\\tau","τ":"\\tau","τ":"\\tau","\\u03C4;":"\\tau","υ":"\\upsilon","υ":"\\upsilon","υ":"\\upsilon","\\u03C5;":"\\upsilon","φ":"\\phi","φ":"\\phi","φ":"\\phi","\\u03C6;":"\\phi","χ":"\\chi","χ":"\\chi","χ":"\\chi","\\u03C7;":"\\chi","ψ":"\\psi","ψ":"\\psi","ψ":"\\psi","\\u03C8;":"\\psi","ω":"\\omega","ω":"\\omega","ω":"\\omega","\\u03C9;":"\\omega","−":"-","−":"-","∞":"\\infty","∞":"\\infty","∞":"\\infty","⋅":"\\cdot","⋅":"\\cdot","⋅":"\\cdot","×":"\\times","×":"\\times","×":"\\times"};class mmlToLatex{parse(e){return"mi"===e.name?entities[e.content]?entities[e.content]:e.content.length>1?"\\"+e.content:e.content:"mn"===e.name?e.content:"msup"===e.name?this.parse(e.children[0])+"^{"+this.parse(e.children[1])+"}":"mroot"===e.name?"\\sqrt["+this.parse(e.children[1])+"]{"+this.parse(e.children[1])+"}":"mfrac"===e.name?"\\frac{"+this.parse(e.children[0])+"}{"+this.parse(e.children[1])+"}":"msqrt"===e.name?"\\sqrt{"+e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" ")+"}":"mo"===e.name?entities[e.content]?entities[e.content]:"⁡"===e.content?" ":e.content:"mrow"===e.name&&"MJX-TeXAtom-ORD"===e.attributes.class?e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" "):"math"===e.name||"mrow"===e.name?"("+e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" ")+")":void 0}convert(e){return this.parse(xmlParser(e).root)}}class mmlToAst$1{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1}convert(e){return this.latexToAst.convert(this.mmlToLatex.convert(e))}}class mmlToGuppy{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class mmlToMathjs{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToMathjs=new astToMathjs$1}convert(e){return this.astToMathjs.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class mmlToText{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToText=new astToText$2}convert(e){return this.astToText.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class textToGuppy{constructor(){this.textToAst=new textToAst$4,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.textToAst.convert(e))}}class textToLatex{constructor(){this.textToAst=new textToAst$4,this.astToLatex=new astToLatex$1}convert(e){return this.astToLatex.convert(this.textToAst.convert(e))}}class textToMathjs{constructor(){this.textToAst=new textToAst$4,this.astToMathjs=new astToMathjs$1}convert(e){return this.astToMathjs.convert(this.textToAst.convert(e))}}var converters=Object.freeze({__proto__:null,astToLatexObj:astToLatex$1,astToTextObj:astToText$2,astToGuppyObj:astToGuppy$1,astToMathjsObj:astToMathjs$1,latexToAstObj:latexToAst$1,latexToGuppyObj:latexToGuppy,latexToMathjsObj:latexToMathjs,latexToTextObj:latexToText,mathjsToAstObj:mathjsToAst,mathjsToGuppyObj:mathjsToGuppy,mathjsToLatexObj:mathjsToLatex,mathjsToTextObj:mathjsToText,mmlToAstObj:mmlToAst$1,mmlToGuppyObj:mmlToGuppy,mmlToLatexObj:mmlToLatex,mmlToMathjsObj:mmlToMathjs,mmlToTextObj:mmlToText,textToAstObj:textToAst$4,textToGuppyObj:textToGuppy,textToLatexObj:textToLatex,textToMathjsObj:textToMathjs,astToGLSL:astToGLSL$1}),textToAst=new textToAst$4,latexToAst=new latexToAst$1,mmlToAst=new mmlToAst$1,utils={match:match$2,flatten:flatten$5,unflattenLeft:unflattenLeft,unflattenRight:unflattenRight};function Expression(e,t){this.tree=flatten$5(e),this.context=t,this.toJSON=function(){let e={objectType:"math-expression",tree:this.tree},t={};for(let e in this.context.assumptions)Object.keys(this.context.assumptions[e]).length>0&&(t[e]=this.context.assumptions[e]);return Object.keys(t).length>0&&(e.assumptions=t),e}}function extend(e,t){return flatten_array(Array.prototype.slice.call(arguments,2)).forEach((function(n){if(n)for(var r in n)t?function(){var t=r;e[t]=function(){return this.fromAst(n[t].apply(null,arguments))}}():e[r]=n[r]})),e}function extend_prototype(e,t){return flatten_array(Array.prototype.slice.call(arguments,2)).forEach((function(n){if(n)for(var r in n)!function(){var a=r;e[a]=function(){var e=[this].concat(Array.prototype.slice.call(arguments));return t?this.context.fromAst(n[a].apply(null,e)):n[a].apply(null,e)}}()})),e}function create_from_multiple(e,t){if(Array.isArray(e)||"number"==typeof e)return new Expression(e,Context);if("string"==typeof e)try{return new Expression(textToAst.convert(e),Context)}catch(t){try{return new Expression(latexToAst.convert(e),Context)}catch(n){try{return new Expression(mmlToAst.convert(e),Context)}catch(r){if(-1!==e.indexOf("\\"))throw n;if(-1!==e.indexOf(">>2]>>>24-i%4*8&255;t[r+i>>>2]|=s<<24-(r+i)%4*8}else for(i=0;i>>2]=n[i>>>2];return this.sigBytes+=a,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n,r=[],a=function(t){var n=987654321,r=4294967295;return function(){var a=((n=36969*(65535&n)+(n>>16)&r)<<16)+(t=18e3*(65535&t)+(t>>16)&r)&r;return a/=4294967296,(a+=.5)*(e.random()>.5?1:-1)}},i=0;i>>2]>>>24-a%4*8&255;r.push((i>>>4).toString(16)),r.push((15&i).toString(16))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new s.init(n,t/2)}},u=o.Latin1={stringify:function(e){for(var t=e.words,n=e.sigBytes,r=[],a=0;a>>2]>>>24-a%4*8&255;r.push(String.fromCharCode(i))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new s.init(n,t)}},c=o.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},p=a.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=c.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,a=n.sigBytes,i=this.blockSize,o=a/(4*i),l=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*i,u=e.min(4*l,a);if(l){for(var c=0;c>>31}var p=(r<<5|r>>>27)+l+i[u];p+=u<20?1518500249+(a&s|~a&o):u<40?1859775393+(a^s^o):u<60?(a&s|a&o|s&o)-1894007588:(a^s^o)-899497514,l=o,o=s,s=a<<30|a>>>2,a=r,r=p}n[0]=n[0]+r|0,n[1]=n[1]+a|0,n[2]=n[2]+s|0,n[3]=n[3]+o|0,n[4]=n[4]+l|0},_doFinalize:function(){var e=this._data,t=e.words,n=8*this._nDataBytes,r=8*e.sigBytes;return t[r>>>5]|=128<<24-r%32,t[14+(r+64>>>9<<4)]=Math.floor(n/4294967296),t[15+(r+64>>>9<<4)]=n,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});e.SHA1=r._createHelper(s),e.HmacSHA1=r._createHmacHelper(s)}(),CryptoJS.SHA1);var sha1=sha1$1.exports,encBase64={exports:{}};!function(e,t){e.exports=function(e){return function(){var t=e,n=t.lib.WordArray;function r(e,t,r){for(var a=[],i=0,s=0;s>>6-s%4*2;a[i>>>2]|=(o|l)<<24-i%4*8,i++}return n.create(a,i)}t.enc.Base64={stringify:function(e){var t=e.words,n=e.sigBytes,r=this._map;e.clamp();for(var a=[],i=0;i>>2]>>>24-i%4*8&255)<<16|(t[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|t[i+2>>>2]>>>24-(i+2)%4*8&255,o=0;o<4&&i+.75*o>>6*(3-o)&63));var l=r.charAt(64);if(l)for(;a.length%4;)a.push(l);return a.join("")},parse:function(e){var t=e.length,n=this._map,a=this._reverseMap;if(!a){a=this._reverseMap=[];for(var i=0;iArray.isArray(t)?e.concat(flattenDeep(t)):e.concat(t)),[])}function flattenLevels(e,t){return console.log(`levels: ${t}`),e.reduce(((e,n)=>Array.isArray(n)&&t>1?e.concat(flattenLevels(n,t-1)):e.concat(n)),[])}class Subset{union(e){return this.complement().intersect(e.complement()).complement()}intersectWithOpenInterval(e){return this.intersect(e)}setMinus(e){return this.intersect(e.complement())}symmetricDifference(e){return this.setMinus(e).union(e.setMinus(this))}equals(e){return this.symmetricDifference(e).isEmpty()}toJSON(){return{objectType:"subset",data:Object.assign({},this),subsetType:this.constructor.subsetType}}static reviver(e,t){if(t&&"subset"===t.objectType&&void 0!==t.subsetType){if("emptySet"===t.subsetType)return new EmptySet;if("realLine"===t.subsetType)return new RealLine;if("singleton"===t.subsetType)return new Singleton(t.data.element);if("union"===t.subsetType)return new Union(t.data.subsets);if("openInterval"===t.subsetType)return new OpenInterval(t.data.left,t.data.right)}return t}copy(){return this.constructor.reviver(null,this.toJSON())}}class EmptySet extends Subset{static subsetType="emptySet";union(e){return e}intersect(){return new EmptySet}contains(){return!1}isEmpty(){return!0}complement(){return new RealLine}toString(){return"∅"}toMathExpression(){return me$3.fromAst("∅")}}class RealLine extends Subset{static subsetType="realLine";union(){return new RealLine}intersect(e){return e}contains(){return!0}complement(){return new EmptySet}isEmpty(){return!1}toString(){return"ℝ"}toMathExpression(){return me$3.fromAst("R")}}class Singleton extends Subset{static subsetType="singleton";constructor(e){if(super(),!Number.isFinite(e))return new EmptySet;this.element=e}union(e){return e.contains(this.element)?e:new Union([e,this])}intersect(e){return e.contains(this.element)?new Singleton(this.element):new EmptySet}isEmpty(){return!1}contains(e){return e===this.element}complement(){return new Union([new OpenInterval(-1/0,this.element),new OpenInterval(this.element,1/0)])}toString(){return`{${this.element}}`}toMathExpression(){return me$3.fromAst(["set",this.element])}}class Union extends Subset{static subsetType="union";intersect(e){return new Union(this.subsets.map((t=>e.intersect(t))))}toString(){return this.subsets.map((e=>e.toString())).join(" U ")}toMathExpression(){return me$3.fromAst(["union",...this.subsets.map((e=>e.toMathExpression().tree))])}constructor(e){super();let t=e.filter((e=>!e.isEmpty()));if(0===t.length)return new EmptySet;t=t.reduce(((e,t)=>t instanceof Union?e.concat(t.subsets):e.concat(t)),[]),this.subsets=[];for(let e=0;ea&&s.elementi.left&&at.contains(e)))}isEmpty(){return this.subsets.every((e=>e.isEmpty()))}complement(){return this.subsets.map((e=>e.complement())).reduce(((e,t)=>e.intersect(t)))}}class Interval$1 extends Subset{constructor(e,t){return super(),this.left=e,this.right=t,this.left<=this.right?this.left===-1/0&&this.right===1/0?new RealLine:this:new EmptySet}}class OpenInterval extends Interval$1{static subsetType="openInterval";constructor(e,t){return super(e,t),e===t?new EmptySet:this}intersect(e){return e.intersectWithOpenInterval(this)}intersectWithOpenInterval(e){return new OpenInterval(Math.max(this.left,e.left),Math.min(this.right,e.right))}complement(){return new Union([new OpenClosedInterval(-1/0,this.left),new ClosedOpenInterval(this.right,1/0)])}isEmpty(){return this.left>=this.right}contains(e){return e>this.left&&ebuildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new EmptySet:1===n.length?n[0]:new Union(n)}if("intersect"===n||"and"===n){let n=e.slice(1).map((e=>buildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new RealLine:n.reduce(((e,t)=>e.intersect(t)))}if("set"===n){let n=e.slice(1).map((e=>buildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new EmptySet:1===n.length?n[0]:new Union(n)}if(["<","le",">","ge","=","ne"].includes(n)){let r=e[1],a=!1;if(!Number.isFinite(r))if(deepCompare(r,t))a=!0;else if(r=me$3.fromAst(r).evaluate_to_constant(),!Number.isFinite(r)&&r!==1/0&&r!==-1/0)return new EmptySet;let i=e[2],s=!1;if(!Number.isFinite(i))if(deepCompare(i,t))s=!0;else if(i=me$3.fromAst(i).evaluate_to_constant(),!Number.isFinite(i)&&i!==1/0&&i!==-1/0)return new EmptySet;return a?s?new EmptySet:"<"===n?new OpenInterval(-1/0,i):"le"===n?new OpenClosedInterval(-1/0,i):">"===n?new OpenInterval(i,1/0):"ge"===n?new ClosedOpenInterval(i,1/0):"="===n?Number.isFinite(i)?new Singleton(i):new EmptySet:Number.isFinite(i)?new Union([new OpenInterval(-1/0,i),new OpenInterval(i,1/0)]):new RealLine:s?"<"===n?new OpenInterval(r,1/0):"le"===n?new ClosedOpenInterval(r,1/0):">"===n?new OpenInterval(-1/0,r):"ge"===n?new OpenClosedInterval(-1/0,r):"="===n?Number.isFinite(r)?new Singleton(r):new EmptySet:Number.isFinite(r)?new Union([new OpenInterval(-1/0,r),new OpenInterval(r,1/0)]):new RealLine:new EmptySet}if(["lts","gts"].includes(n)){let r=e[1].slice(1),a=e[2].slice(1);if(3!==r.length||!deepCompare(r[1],t))return new EmptySet;"gts"===n&&(r.reverse(),a.reverse());let i=r[0];if(!Number.isFinite(i)&&(i=me$3.fromAst(i).evaluate_to_constant(),!Number.isFinite(i)&&i!==1/0&&i!==-1/0))return new EmptySet;let s=r[2];return Number.isFinite(s)||(s=me$3.fromAst(s).evaluate_to_constant(),Number.isFinite(s)||s===1/0||s===-1/0)?a[0]?a[1]?new OpenInterval(i,s):new OpenClosedInterval(i,s):a[1]?new ClosedOpenInterval(i,s):new ClosedInterval(i,s):new EmptySet}if("|"===n){let t=e[1];return buildSubsetFromIntervals(e[2],t)}if("^"!==n||"C"!==e[2]&&"c"!==e[2]){if("in"===n)return deepCompare(e[1],t)?buildSubsetFromIntervals(e[2],t):new EmptySet;if("ni"===n)return deepCompare(e[2],t)?buildSubsetFromIntervals(e[1],t):new EmptySet;if("notin"===n){if(deepCompare(e[1],t)){let n=buildSubsetFromIntervals(e[2],t);if(n)return n.complement()}return new EmptySet}if("notni"===n){if(deepCompare(e[2],t)){let n=buildSubsetFromIntervals(e[1],t);if(n)return n.complement()}return new EmptySet}{let t=me$3.fromAst(e).evaluate_to_constant();return Number.isFinite(t)?new Singleton(t):new EmptySet}}{let n=buildSubsetFromIntervals(e[1],t);return n?n.complement():new EmptySet}}function buildSubsetFromMathExpression(e,t){return buildSubsetFromIntervals(e.to_intervals().tree,t.tree)}function deepClone(e,t,n){if(Object(e)!==e||e instanceof Function)return e;if(void 0!==t&&e instanceof t)return e;if(e instanceof me$3.class||e instanceof theModule.Subset)return e.copy();if(void 0===n&&(n=new WeakMap),Array.isArray(e))return[...e.map((e=>deepClone(e,t,n)))];if(e.constructor===Object&&0===Object.entries(e).length)return{};if(n.has(e))return n.get(e);try{var r=new e.constructor}catch(t){r=Object.create(Object.getPrototypeOf(e))}return e instanceof Map?Array.from(e,(([e,a])=>r.set(deepClone(e,t,n),deepClone(a,t,n)))):e instanceof Set&&Array.from(e,(e=>r.add(deepClone(e,t,n)))),n.set(e,r),Object.assign(r,...Object.keys(e).map((r=>({[r]:deepClone(e[r],t,n)}))))}function deepCompare(e,t,n){var r,a;return r=[],a=[],function e(t,i){var s;if(Number.isNaN(t)&&Number.isNaN(i))return!0;if(t===i)return!0;if(void 0!==n&&t instanceof n&&i instanceof n)return t.componentName===i.componentName;if(t instanceof me$3.class&&i instanceof me$3.class)return e(t.tree,i.tree);if("function"==typeof t&&"function"==typeof i||t instanceof Date&&i instanceof Date||t instanceof RegExp&&i instanceof RegExp||t instanceof String&&i instanceof String||t instanceof Number&&i instanceof Number)return t.toString()===i.toString();if(!(t instanceof Object&&i instanceof Object))return!1;if(t.isPrototypeOf(i)||i.isPrototypeOf(t))return!1;if(t.constructor!==i.constructor)return!1;if(t.prototype!==i.prototype)return!1;if(r.indexOf(t)>-1||a.indexOf(i)>-1)return!1;for(s in i){if(i.hasOwnProperty(s)!==t.hasOwnProperty(s))return!1;if(typeof i[s]!=typeof t[s])return!1}for(s in t){if(i.hasOwnProperty(s)!==t.hasOwnProperty(s))return!1;if(typeof i[s]!=typeof t[s])return!1;switch(typeof t[s]){case"object":case"function":if(r.push(t),a.push(i),!e(t[s],i[s]))return!1;r.pop(),a.pop();break;default:if(!(t[s]===i[s]||Number.isNaN(t[s])&&Number.isNaN(i[s])))return!1}}return!0}(e,t)}function breakStringsAndOthersIntoComponentsByStringCommas(e){return null}function returnBreakStringsSugarFunction({childrenToComponentFunction:e,mustStripOffOuterParentheses:t=!1}){return function({matchedChildren:n}){let r=0,a=[],i=[],s=!1,o=n.length;if(t){let e=n[0];if("string"!=typeof e||"("!==e.trimLeft()[0])return{success:!1}}for(let[e,l]of n.entries()){if("string"!=typeof l){i.push(l);continue}let u=l.trim();if(0===e&&t&&"("===u[0]){let e=n[o-1];if("string"==typeof e){let t=e.trimRight();")"===t[t.length-1]&&(s=!0,u=u.substring(1))}}let c=0;for(let t=0;tc&&i.push(u.substring(c,t)),a.push(i),i=[],c=t+1)}u.length>c&&i.push(u.substring(c,u.length))}return 0!==r?{success:!1}:(a.push(i),{success:!0,newChildren:a.map(e)})}}function breakEmbeddedStringByCommas({childrenList:e}){let t=0,n=[],r=[];for(let a of e){if("string"!=typeof a){r.push(a);continue}let e=a.trim(),i=0;for(let a=0;ai){let t=e.substring(i,a).trim();r.push(t)}n.push(r),r=[],i=a+1}}if(e.length>i){let t=e.substring(i,e.length).trim();r.push(t)}}return 0!==t?{success:!1}:(n.push(r),{success:!0,pieces:n})}function breakEmbeddedStringsIntoParensPieces({componentList:e,removeParens:t=!1}){let n=0,r=[],a=[];for(let i of e){if("string"!=typeof i){0===n?r.push([i]):a.push(i);continue}let e=i.trim(),s=0;for(let i=0;is){let n=t?i:i+1,r=e.substring(s,n).trim();r.length>0&&a.push(r)}r.push(a),a=[],s=i+1}n--}else if(0===n&&!o.match(/\s/))return{success:!1}}if(e.length>s){let t=e.substring(s,e.length).trim();a.push(t)}}return 0!==n?{success:!1}:(a.length>0&&r.push(a),{success:!0,pieces:r})}var global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex1)for(var n=1;n{throw new Error("This node type doesn't define a deserialize function")})}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return"function"!=typeof e&&(e=NodeType.match(e)),t=>{let n=e(t);return void 0===n?null:[this,n]}}}NodeProp.closedBy=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.openedBy=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.group=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.contextHash=new NodeProp({perNode:!0}),NodeProp.lookAhead=new NodeProp({perNode:!0}),NodeProp.mounted=new NodeProp({perNode:!0});const noProps=Object.create(null);class NodeType{constructor(e,t,n,r=0){this.name=e,this.props=t,this.id=n,this.flags=r}static define(e){let t=e.props&&e.props.length?Object.create(null):noProps,n=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(null==e.name?8:0),r=new NodeType(e.name||"",t,e.id,n);if(e.props)for(let n of e.props)if(Array.isArray(n)||(n=n(r)),n){if(n[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[n[0].id]=n[1]}return r}prop(e){return this.props[e.id]}get isTop(){return(1&this.flags)>0}get isSkipped(){return(2&this.flags)>0}get isError(){return(4&this.flags)>0}get isAnonymous(){return(8&this.flags)>0}is(e){if("string"==typeof e){if(this.name==e)return!0;let t=this.prop(NodeProp.group);return!!t&&t.indexOf(e)>-1}return this.id==e}static match(e){let t=Object.create(null);for(let n in e)for(let r of n.split(" "))t[r]=e[n];return e=>{for(let n=e.prop(NodeProp.group),r=-1;r<(n?n.length:0);r++){let a=t[r<0?e.name:n[r]];if(a)return a}}}}NodeType.none=new NodeType("",Object.create(null),0,8);class NodeSet{constructor(e){this.types=e;for(let t=0;te.node;;){let s=!1;if(e.from<=a&&e.to>=r&&(e.type.isAnonymous||!1!==t(e.type,e.from,e.to,i))){if(e.firstChild())continue;e.type.isAnonymous||(s=!0)}for(;s&&n&&n(e.type,e.from,e.to,i),s=e.type.isAnonymous,!e.nextSibling();){if(!e.parent())return;s=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:balanceRange(NodeType.none,this.children,this.positions,0,this.children.length,0,this.length,((e,t,n)=>new Tree(this.type,e,t,n,this.propValues)),e.makeTree||((e,t,n)=>new Tree(NodeType.none,e,t,n)))}static build(e){return buildTree(e)}}Tree.empty=new Tree(NodeType.none,[],[],0);class FlatBufferCursor{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new FlatBufferCursor(this.buffer,this.index)}}class TreeBuffer{constructor(e,t,n){this.buffer=e,this.length=t,this.set=n}get type(){return NodeType.none}toString(){let e=[];for(let t=0;t0));o=i[o+3]);return s}slice(e,t,n,r){let a=this.buffer,i=new Uint16Array(t-e);for(let r=e,s=0;r=t&&nt;case 1:return n<=t&&r>t;case 2:return r>t;case 4:return!0}}function enterUnfinishedNodesBefore(e,t){let n=e.childBefore(t);for(;n;){let t=n.lastChild;if(!t||t.to!=n.to)break;t.type.isError&&t.from==t.to?(e=n,n=t.prevSibling):n=t}return e}function resolveNode(e,t,n,r){for(var a;e.from==e.to||(n<1?e.from>=t:e.from>t)||(n>-1?e.to<=t:e.to0?s.length:-1;e!=l;e+=t){let l=s[e],u=o[e]+i._from;if(checkSide(r,n,u,u+l.length))if(l instanceof TreeBuffer){if(2&a)continue;let s=l.findChild(0,l.buffer.length,t,n-u,r);if(s>-1)return new BufferNode(new BufferContext(i,l,e,u),null,s)}else if(1&a||!l.type.isAnonymous||hasChild(l)){let s;if(!(1&a)&&l.props&&(s=l.prop(NodeProp.mounted))&&!s.overlay)return new TreeNode(s.tree,u,e,i);let o=new TreeNode(l,u,e,i);return 1&a||!o.type.isAnonymous?o:o.nextChild(t<0?l.children.length-1:0,t,n,r)}}if(1&a||!i.type.isAnonymous)return null;if(e=i.index>=0?i.index+t:t<0?-1:i._parent.node.children.length,i=i._parent,!i)return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this.node.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this.node.children.length-1,-1,e,-2)}enter(e,t,n=!0,r=!0){let a;if(n&&(a=this.node.prop(NodeProp.mounted))&&a.overlay){let n=e-this.from;for(let{from:e,to:r}of a.overlay)if((t>0?e<=n:e=n:r>n))return new TreeNode(a.tree,a.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,r?0:2)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get cursor(){return new TreeCursor(this)}get tree(){return this.node}toTree(){return this.node}resolve(e,t=0){return resolveNode(this,e,t,!1)}resolveInner(e,t=0){return resolveNode(this,e,t,!0)}enterUnfinishedNodesBefore(e){return enterUnfinishedNodesBefore(this,e)}getChild(e,t=null,n=null){let r=getChildren(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return getChildren(this,e,t,n)}toString(){return this.node.toString()}}function getChildren(e,t,n,r){let a=e.cursor,i=[];if(!a.firstChild())return i;if(null!=n)for(;!a.type.is(n);)if(!a.nextSibling())return i;for(;;){if(null!=r&&a.type.is(r))return i;if(a.type.is(t)&&i.push(a.node),!a.nextSibling())return null==r?i:[]}}class BufferContext{constructor(e,t,n,r){this.parent=e,this.buffer=t,this.index=n,this.start=r}}class BufferNode{constructor(e,t,n){this.context=e,this._parent=t,this.index=n,this.type=e.buffer.set.types[e.buffer.buffer[n]]}get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}child(e,t,n){let{buffer:r}=this.context,a=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.context.start,n);return a<0?null:new BufferNode(this.context,this,a)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}enter(e,t,n,r=!0){if(!r)return null;let{buffer:a}=this.context,i=a.findChild(this.index+4,a.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return i<0?null:new BufferNode(this.context,this,i)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new BufferNode(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new BufferNode(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get cursor(){return new TreeCursor(this)}get tree(){return null}toTree(){let e=[],t=[],{buffer:n}=this.context,r=this.index+4,a=n.buffer[this.index+3];if(a>r){let i=n.buffer[this.index+1],s=n.buffer[this.index+2];e.push(n.slice(r,a,i,s)),t.push(0)}return new Tree(this.type,e,t,this.to-this.from)}resolve(e,t=0){return resolveNode(this,e,t,!1)}resolveInner(e,t=0){return resolveNode(this,e,t,!0)}enterUnfinishedNodesBefore(e){return enterUnfinishedNodesBefore(this,e)}toString(){return this.context.buffer.childString(this.index)}getChild(e,t=null,n=null){let r=getChildren(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return getChildren(this,e,t,n)}}class TreeCursor{constructor(e,t=0){if(this.mode=t,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,e instanceof TreeNode)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let t=e._parent;t;t=t._parent)this.stack.unshift(t.index);this.bufferNode=e,this.yieldBuf(e.index)}}get name(){return this.type.name}yieldNode(e){return!!e&&(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0)}yieldBuf(e,t){this.index=e;let{start:n,buffer:r}=this.buffer;return this.type=t||r.set.types[r.buffer[e]],this.from=n+r.buffer[e+1],this.to=n+r.buffer[e+2],!0}yield(e){return!!e&&(e instanceof TreeNode?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)))}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,n){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree.node.children.length-1:0,e,t,n,this.mode));let{buffer:r}=this.buffer,a=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.buffer.start,n);return!(a<0)&&(this.stack.push(this.index),this.yieldBuf(a))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,n=!0,r=!0){return this.buffer?!!r&&this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,n&&!(1&this.mode),r))}parent(){if(!this.buffer)return this.yieldNode(1&this.mode?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=1&this.mode?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return!!this._tree._parent&&this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode));let{buffer:t}=this.buffer,n=this.stack.length-1;if(e<0){let e=n<0?0:this.stack[n]+4;if(this.index!=e)return this.yieldBuf(t.findChild(e,this.index,-1,0,4))}else{let e=t.buffer[this.index+3];if(e<(n<0?t.buffer.length:t.buffer[this.stack[n]+3]))return this.yieldBuf(e)}return n<0&&this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode))}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,n,{buffer:r}=this;if(r){if(e>0){if(this.index-1)for(let r=t+e,a=e<0?-1:n.node.children.length;r!=a;r+=e){let e=n.node.children[r];if(1&this.mode||e instanceof TreeBuffer||!e.type.isAnonymous||hasChild(e))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let i=e;i;i=i._parent)if(i.index==r){if(r==this.index)return i;t=i,n=a+1;break e}r=this.stack[--a]}for(let e=n;ee instanceof TreeBuffer||!e.type.isAnonymous||hasChild(e)))}function buildTree(e){var t;let{buffer:n,nodeSet:r,maxBufferLength:a=DefaultBufferLength,reused:i=[],minRepeatType:s=r.types.length}=e,o=Array.isArray(n)?new FlatBufferCursor(n,n.length):n,l=r.types,u=0,c=0;function p(e,t,n,f,y){let{id:g,start:b,end:v,size:N}=o,T=c;for(;N<0;){if(o.next(),-1==N){let t=i[g];return n.push(t),void f.push(b-e)}if(-3==N)return void(u=g);if(-4==N)return void(c=g);throw new RangeError(`Unrecognized record size: ${N}`)}let C,A,V=l[g],x=b-e;if(v-b<=a&&(A=function(e,t){let n=o.fork(),r=0,i=0,l=0,u=n.end-a,c={size:0,start:0,skip:0};e:for(let a=n.pos-e;n.pos>a;){let e=n.size;if(n.id==t&&e>=0){c.size=r,c.start=i,c.skip=l,l+=4,r+=4,n.next();continue}let o=n.pos-e;if(e<0||o=s?4:0,d=n.start;for(n.next();n.pos>o;){if(n.size<0){if(-3!=n.size)break e;p+=4}else n.id>=s&&(p+=4);n.next()}i=d,r+=e,l+=p}(t<0||r==e)&&(c.size=r,c.start=i,c.skip=l);return c.size>4?c:void 0}(o.pos-t,y))){let t=new Uint16Array(A.size-A.skip),n=o.pos-A.size,a=t.length;for(;o.pos>n;)a=h(A.start,t,a);C=new TreeBuffer(t,v-A.start,r),x=A.start-e}else{let e=o.pos-N;o.next();let t=[],n=[],r=g>=s?g:-1,i=0,l=v;for(;o.pos>e;)r>=0&&o.id==r&&o.size>=0?(o.end<=l-a&&(d(t,n,b,i,o.end,l,r,T),i=t.length,l=o.end),o.next()):p(b,e,t,n,r);if(r>=0&&i>0&&i-1&&i>0){let e=function(e){return(t,n,r)=>{let a,i,s=0,o=t.length-1;if(o>=0&&(a=t[o])instanceof Tree){if(!o&&a.type==e&&a.length==r)return a;(i=a.prop(NodeProp.lookAhead))&&(s=n[o]+a.length+i)}return m(e,t,n,r,s)}}(V);C=balanceRange(V,t,n,0,t.length,0,v-b,e,e)}else C=m(V,t,n,v-b,T-v)}n.push(C),f.push(x)}function d(e,t,n,a,i,s,o,l){let u=[],c=[];for(;e.length>a;)u.push(e.pop()),c.push(t.pop()+n-i);e.push(m(r.types[o],u,c,s-i,l-s)),t.push(i-n)}function m(e,t,n,r,a=0,i){if(u){let e=[NodeProp.contextHash,u];i=i?[e].concat(i):[e]}if(a>25){let e=[NodeProp.lookAhead,a];i=i?[e].concat(i):[e]}return new Tree(e,t,n,r,i)}function h(e,t,n){let{id:r,start:a,end:i,size:l}=o;if(o.next(),l>=0&&r4){let r=o.pos-(l-4);for(;o.pos>r;)n=h(e,t,n)}t[--n]=s,t[--n]=i-e,t[--n]=a-e,t[--n]=r}else-3==l?u=r:-4==l&&(c=r);return n}let f=[],y=[];for(;o.pos>0;)p(e.start||0,e.bufferStart||0,f,y,-1);let g=null!==(t=e.length)&&void 0!==t?t:f.length?y[0]+f[0].length:0;return new Tree(l[e.topID],f.reverse(),y.reverse(),g)}const nodeSizeCache=new WeakMap;function nodeSize(e,t){if(!e.isAnonymous||t instanceof TreeBuffer||t.type!=e)return 1;let n=nodeSizeCache.get(t);if(null==n){n=1;for(let r of t.children){if(r.type!=e||!(r instanceof Tree)){n=1;break}n+=nodeSize(e,r)}nodeSizeCache.set(t,n)}return n}function balanceRange(e,t,n,r,a,i,s,o,l){let u=0;for(let n=r;n=c)break;h+=t}if(u==a+1){if(h>c){let e=n[a];t(e.children,e.positions,0,e.children.length,r[a]+o);continue}p.push(n[a])}else{let t=r[u-1]+n[u-1].length-m;p.push(balanceRange(e,n,r,a,u,m,t,null,l))}d.push(m+o-i)}}(t,n,r,a,0),(o||l)(p,d,s)}class Parser$1{startParse(e,t,n){return"string"==typeof e&&(e=new StringInput(e)),n=n?n.length?n.map((e=>new Range(e.from,e.to))):[new Range(0,0)]:[new Range(0,e.length)],this.createParse(e,t||[],n)}parse(e,t,n){let r=this.startParse(e,t,n);for(;;){let e=r.advance();if(e)return e}}}class StringInput{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}new NodeProp({perNode:!0});class Stack$1{constructor(e,t,n,r,a,i,s,o,l,u=0,c){this.p=e,this.stack=t,this.state=n,this.reducePos=r,this.pos=a,this.score=i,this.buffer=s,this.bufferBase=o,this.curContext=l,this.lookAhead=u,this.parent=c}toString(){return`[${this.stack.filter(((e,t)=>t%3==0)).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,n=0){let r=e.parser.context;return new Stack$1(e,[],t,n,n,0,[],0,r?new StackContext(r,r.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){let t=e>>19,n=65535&e,{parser:r}=this.p,a=r.dynamicPrecedence(n);if(a&&(this.score+=a),0==t)return this.pushState(r.getGoto(this.state,n,!0),this.reducePos),ni;)this.stack.pop();this.reduceContext(n,s)}storeNode(e,t,n,r=4,a=!1){if(0==e){let e=this,r=this.buffer.length;if(0==r&&e.parent&&(r=e.bufferBase-e.parent.bufferBase,e=e.parent),r>0&&0==e.buffer[r-4]&&e.buffer[r-1]>-1){if(t==n)return;if(e.buffer[r-2]>=t)return void(e.buffer[r-2]=n)}}if(a&&this.pos!=n){let a=this.buffer.length;if(a>0&&0!=this.buffer[a-4])for(;a>0&&this.buffer[a-2]>n;)this.buffer[a]=this.buffer[a-4],this.buffer[a+1]=this.buffer[a-3],this.buffer[a+2]=this.buffer[a-2],this.buffer[a+3]=this.buffer[a-1],a-=4,r>4&&(r-=4);this.buffer[a]=e,this.buffer[a+1]=t,this.buffer[a+2]=n,this.buffer[a+3]=r}else this.buffer.push(e,t,n,r)}shift(e,t,n){let r=this.pos;if(131072&e)this.pushState(65535&e,this.pos);else if(0==(262144&e)){let a=e,{parser:i}=this.p;(n>this.pos||t<=i.maxNode)&&(this.pos=n,i.stateFlag(a,1)||(this.reducePos=n)),this.pushState(a,r),this.shiftContext(t,r),t<=i.maxNode&&this.buffer.push(t,r,n,4)}else this.pos=n,this.shiftContext(t,r),t<=this.p.parser.maxNode&&this.buffer.push(t,r,n,4)}apply(e,t,n){65536&e?this.reduce(e):this.shift(e,t,n)}useNode(e,t){let n=this.p.reused.length-1;(n<0||this.p.reused[n]!=e)&&(this.p.reused.push(e),n++);let r=this.pos;this.reducePos=this.pos=r+e.length,this.pushState(t,r),this.buffer.push(n,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(;t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let n=e.buffer.slice(t),r=e.bufferBase+t;for(;e&&r==e.bufferBase;)e=e.parent;return new Stack$1(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,n,r,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let n=e<=this.p.parser.maxNode;n&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,n?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new SimulatedStack(this);;){let n=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(0==(65536&n))return!0;if(0==n)return!1;t.reduce(n)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let n=[];for(let r,a=0;a1&t&&e==r))||n.push(t[e],r)}t=n}let n=[];for(let e=0;e>19,r=65535&e,a=this.stack.length-3*n;if(a<0||t.getGoto(this.stack[a],r,!1)<0)return!1;this.storeNode(0,this.reducePos,this.reducePos,4,!0),this.score-=100}return this.reduce(e),!0}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(3!=this.stack.length)return!1;let{parser:e}=this.p;return 65535==e.data[e.stateSlot(this.state,1)]&&!e.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;tthis.lookAhead&&(this.emitLookAhead(),this.lookAhead=e)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}}class StackContext{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}var Recover;!function(e){e[e.Insert=200]="Insert",e[e.Delete=190]="Delete",e[e.Reduce=100]="Reduce",e[e.MaxNext=4]="MaxNext",e[e.MaxInsertStackDepth=300]="MaxInsertStackDepth",e[e.DampenInsertStackDepth=120]="DampenInsertStackDepth"}(Recover||(Recover={}));class SimulatedStack{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=65535&e,n=e>>19;0==n?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=3*(n-1);let r=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=r}}class StackBufferCursor{constructor(e,t,n){this.stack=e,this.pos=t,this.index=n,this.buffer=e.buffer,0==this.index&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new StackBufferCursor(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;null!=e&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,0==this.index&&this.maybeNext()}fork(){return new StackBufferCursor(this.stack,this.pos,this.index)}}class CachedToken{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const nullToken=new CachedToken;class InputStream{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=nullToken,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let n=this.range,r=this.rangeIndex,a=this.pos+e;for(;an.to:a>=n.to;){if(r==this.ranges.length-1)return null;let e=this.ranges[++r];a+=e.from-n.to,n=e}return a}peek(e){let t,n,r=this.chunkOff+e;if(r>=0&&r=this.chunk2Pos&&tr.to&&(this.chunk2=this.chunk2.slice(0,r.to-t)),n=this.chunk2.charCodeAt(0)}}return t>=this.token.lookAhead&&(this.token.lookAhead=t+1),n}acceptToken(e,t=0){let n=t?this.resolveOffset(t,-1):this.pos;if(null==n||n=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=nullToken,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let n="";for(let r of this.ranges){if(r.from>=t)break;r.to>e&&(n+=this.input.read(Math.max(r.from,e),Math.min(r.to,t)))}return n}}class TokenGroup{constructor(e,t){this.data=e,this.id=t}token(e,t){readToken(this.data,e,t,this.id)}}TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1;class ExternalTokenizer{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function readToken(e,t,n,r){let a=0,i=1<0){let n=e[r];if(o.allows(n)&&(-1==t.token.value||t.token.value==n||s.overrides(n,t.token.value))){t.acceptToken(n);break}}for(let r=t.next,i=0,s=e[a+2];i>1,l=n+o+(o<<1),u=e[l],c=e[l+1];if(r=c)){a=e[l+2],t.advance();continue e}i=o+1}}break}}function decodeArray(e,t=Uint16Array){if("string"!=typeof e)return e;let n=null;for(let r=0,a=0;r=92&&t--,t>=34&&t--;let a=t-32;if(a>=46&&(a-=46,n=!0),i+=a,n)break;i*=46}n?n[a++]=i:n=new t(i)}return n}const verbose=void 0!==browser$1&&/\bparse\b/.test(browser$1.env.LOG);let stackIDs=null;var Safety,Rec;function cutAt(e,t,n){let r=e.fullCursor();for(r.moveTo(t);;)if(!(n<0?r.childBefore(t):r.childAfter(t)))for(;;){if((n<0?r.tot)&&!r.type.isError)return n<0?Math.max(0,Math.min(r.to-1,t-25)):Math.min(e.length,Math.max(r.from+1,t+25));if(n<0?r.prevSibling():r.nextSibling())break;if(!r.parent())return n<0?0:e.length}}!function(e){e[e.Margin=25]="Margin"}(Safety||(Safety={}));class FragmentCursor{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?cutAt(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?cutAt(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=i,null;if(a instanceof Tree){if(i==e){if(i=Math.max(this.safeFrom,e)&&(this.trees.push(a),this.start.push(i),this.index.push(0))}else this.index[t]++,this.nextStart=i+a.length}}}class TokenCache{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map((e=>new CachedToken))}getActions(e){let t=0,n=null,{parser:r}=e.p,{tokenizers:a}=r,i=r.stateSlot(e.state,3),s=e.curContext?e.curContext.hash:0,o=0;for(let r=0;ru.end+25&&(o=Math.max(u.lookAhead,o)),0!=u.value)){let r=t;if(u.extended>-1&&(t=this.addActions(e,u.extended,u.end,t)),t=this.addActions(e,u.value,u.end,t),!l.extend&&(n=u,t>r))break}}for(;this.actions.length>t;)this.actions.pop();return o&&e.setLookAhead(o),n||e.pos!=this.stream.end||(n=new CachedToken,n.value=e.p.parser.eofTerm,n.start=n.end=e.pos,t=this.addActions(e,n.value,n.end,t)),this.mainToken=n,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new CachedToken,{pos:n,p:r}=e;return t.start=n,t.end=Math.min(n+1,r.stream.end),t.value=n==r.stream.end?r.parser.eofTerm:0,t}updateCachedToken(e,t,n){if(t.token(this.stream.reset(n.pos,e),n),e.value>-1){let{parser:t}=n.p;for(let r=0;r=0&&n.p.parser.dialect.allows(a>>1)){0==(1&a)?e.value=a>>1:e.extended=a>>1;break}}}else e.value=0,e.end=Math.min(n.p.stream.end,n.pos+1)}putAction(e,t,n,r){for(let t=0;t4*e.bufferLength?new FragmentCursor(n,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e,t,n=this.stacks,r=this.minStackPos,a=this.stacks=[];for(let i=0;ir)a.push(s);else{if(this.advanceStack(s,a,n))continue;{e||(e=[],t=[]),e.push(s);let n=this.tokens.getMainToken(s);t.push(n.value,n.end)}}break}}if(!a.length){let t=e&&findFinished(e);if(t)return this.stackToTree(t);if(this.parser.strict)throw verbose&&e&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+r);this.recovering||(this.recovering=5)}if(this.recovering&&e){let n=null!=this.stoppedAt&&e[0].pos>this.stoppedAt?e[0]:this.runRecovery(e,t,a);if(n)return this.stackToTree(n.forceAll())}if(this.recovering){let e=1==this.recovering?1:3*this.recovering;if(a.length>e)for(a.sort(((e,t)=>t.score-e.score));a.length>e;)a.pop();a.some((e=>e.reducePos>r))&&this.recovering--}else if(a.length>1)e:for(let e=0;e500&&r.buffer.length>500){if(!((t.score-r.score||t.buffer.length-r.buffer.length)>0)){a.splice(e--,1);continue e}a.splice(n--,1)}}}this.minStackPos=a[0].pos;for(let e=1;e ":"";if(null!=this.stoppedAt&&r>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let t=e.curContext&&e.curContext.tracker.strict,n=t?e.curContext.hash:0;for(let s=this.fragments.nodeAt(r);s;){let r=this.parser.nodeSet.types[s.type.id]==s.type?a.getGoto(e.state,s.type.id):-1;if(r>-1&&s.length&&(!t||(s.prop(NodeProp.contextHash)||0)==n))return e.useNode(s,r),verbose&&console.log(i+this.stackID(e)+` (via reuse of ${a.getName(s.type.id)})`),!0;if(!(s instanceof Tree)||0==s.children.length||s.positions[0]>0)break;let o=s.children[0];if(!(o instanceof Tree&&0==s.positions[0]))break;s=o}}let s=a.stateSlot(e.state,4);if(s>0)return e.reduce(s),verbose&&console.log(i+this.stackID(e)+` (via always-reduce ${a.getName(65535&s)})`),!0;if(e.stack.length>=15e3)for(;e.stack.length>9e3&&e.forceReduce(););let o=this.tokens.getActions(e);for(let s=0;sr?t.push(d):n.push(d)}return!1}advanceFully(e,t){let n=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>n)return pushStackDedup(e,t),!0}}runRecovery(e,t,n){let r=null,a=!1;for(let i=0;i ":"";if(s.deadEnd){if(a)continue;if(a=!0,s.restart(),verbose&&console.log(u+this.stackID(s)+" (restarted)"),this.advanceFully(s,n))continue}let c=s.split(),p=u;for(let e=0;c.forceReduce()&&e<10;e++){if(verbose&&console.log(p+this.stackID(c)+" (via force-reduce)"),this.advanceFully(c,n))break;verbose&&(p=this.stackID(c)+" -> ")}for(let e of s.recoverByInsert(o))verbose&&console.log(u+this.stackID(e)+" (via recover-insert)"),this.advanceFully(e,n);this.stream.end>s.pos?(l==s.pos&&(l++,o=0),s.recoverByDelete(o,l),verbose&&console.log(u+this.stackID(s)+` (via recover-delete ${this.parser.getName(o)})`),pushStackDedup(s,n)):(!r||r.scoree;class ContextTracker{constructor(e){this.start=e.start,this.shift=e.shift||id,this.reduce=e.reduce||id,this.reuse=e.reuse||id,this.hash=e.hash||(()=>0),this.strict=!1!==e.strict}}class LRParser extends Parser$1{constructor(e){if(super(),this.wrappers=[],13!=e.version)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (13)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let n=0;ne.topRules[t][1])),r=[];for(let e=0;e=0)a(r,e,t[n++]);else{let i=t[n+-r];for(let s=-r;s>0;s--)a(t[n++],e,i);n++}}}this.nodeSet=new NodeSet(t.map(((t,a)=>NodeType.define({name:a>=this.minRepeatTerm?void 0:t,id:a,props:r[a],top:n.indexOf(a)>-1,error:0==a,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1})))),this.strict=!1,this.bufferLength=DefaultBufferLength;let i=decodeArray(e.tokenData);if(this.context=e.context,this.specialized=new Uint16Array(e.specialized?e.specialized.length:0),this.specializers=[],e.specialized)for(let t=0;t"number"==typeof e?new TokenGroup(i,e):e)),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,n){let r=new Parse(this,e,t,n);for(let a of this.wrappers)r=a(r,e,t,n);return r}getGoto(e,t,n=!1){let r=this.goto;if(t>=r[0])return-1;for(let a=r[t+1];;){let t=r[a++],i=1&t,s=r[a++];if(i&&n)return s;for(let n=a+(t>>1);a0}validAction(e,t){if(t==this.stateSlot(e,4))return!0;for(let n=this.stateSlot(e,1);;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])return!1;n=pair(this.data,n+2)}if(t==pair(this.data,n+1))return!0}}nextStates(e){let t=[];for(let n=this.stateSlot(e,1);;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])break;n=pair(this.data,n+2)}if(0==(1&this.data[n+2])){let e=this.data[n+1];t.some(((t,n)=>1&n&&t==e))||t.push(this.data[n],e)}}return t}overrides(e,t){let n=findOffset(this.data,this.tokenPrecTable,t);return n<0||findOffset(this.data,this.tokenPrecTable,e){let n=e.tokenizers.find((e=>e.from==t));return n?n.to:t}))),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),null!=e.strict&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),null!=e.bufferLength&&(t.bufferLength=e.bufferLength),t}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return null==t?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),n=t.map((()=>!1));if(e)for(let r of e.split(" ")){let e=t.indexOf(r);e>=0&&(n[e]=!0)}let r=null;for(let e=0;ee)&&n.p.parser.stateFlag(n.state,2)&&(!t||t.score=65&&e<=90||95==e||e>=97&&e<=122||e>=161}function isSpace(e){return 9==e||10==e||13==e||32==e}let cachedName=null,cachedInput=null,cachedPos=0;function tagNameAfter(e,t){let n=e.pos+t;if(cachedInput==e&&cachedPos==n)return cachedName;for(;isSpace(e.peek(t));)t++;let r="";for(;;){let n=e.peek(t);if(!nameChar(n))break;r+=String.fromCharCode(n),t++}return cachedInput=e,cachedPos=n,cachedName=r||null}function ElementContext(e,t){this.name=e,this.parent=t,this.hash=t?t.hash:0;for(let t=0;tt==StartTag?new ElementContext(tagNameAfter(r,1)||"",e):e,reduce:(e,t)=>t==Element&&e?e.parent:e,reuse(e,t,n,r){let a=t.type.id;return a==StartTag||a==OpenTag?new ElementContext(tagNameAfter(r,1)||"",e):e},hash:e=>e?e.hash:0,strict:!1}),startTag=new ExternalTokenizer(((e,t)=>{if(60==e.next)if(e.advance(),47==e.next){e.advance();let n=tagNameAfter(e,0);if(!n)return e.acceptToken(incompleteStartCloseTag);if(t.context&&n.toLowerCase()==t.context.name.toLowerCase())return e.acceptToken(StartCloseTag);for(let r=t.context;r;r=r.parent)if(r.name==n)return e.acceptToken(MissingCloseTag,-2);e.acceptToken(mismatchedStartCloseTag)}else if(33!=e.next&&63!=e.next&&!isSpace(e.next))return e.acceptToken(StartTag)}),{contextual:!0});function scanTo(e,t){return new ExternalTokenizer((n=>{for(let r=0,a=0;;a++){if(n.next<0){a&&n.acceptToken(e);break}if(n.next==t.charCodeAt(r)){if(r++,r==t.length){a>t.length&&n.acceptToken(e,1-t.length);break}}else r=0;n.advance()}}))}const commentContent=scanTo(commentContent$1,"--\x3e"),parser=LRParser.deserialize({version:13,states:"*[OQOTOOO]OYO'#CdOeO`O'#CfO!OOTO'#CeOOOP'#Ce'#CeOOOP'#Cx'#CxOOOP'#Co'#CoQQOTOOOOOQ'#Cp'#CpO!VOYO,59OOOOP,59O,59OO!_OpO,59QO!mO`O'#ClOOOP'#DT'#DTOOOP'#Cu'#CuO!rOTO,59PO!yO`O'#CmOOOP,59P,59POOOP-E6m-E6mOOOQ-E6n-E6nOOOP1G.j1G.jOOOO'#Cq'#CqO#ROpO1G.lO#aOpO'#ChOOOO'#Cr'#CrO#rOpO1G.lOOOP1G.l1G.lOOOP1G.t1G.tO#}OWO,59WOOOP-E6s-E6sOOOP1G.k1G.kO$SO`O,59XO$[OWO,59XOOOO-E6o-E6oO$dOpO7+$WOOOP7+$W7+$WOOOP7+$`7+$`O$oOpO,59SO%QOWO,59SOOOO-E6p-E6pOOOP1G.r1G.rO%]OWO1G.sO%]OWO1G.sOOOP1G.s1G.sOOOP< tag. Found ${e.slice(a-1,i)}`)}n.firstChild();let t=e.substring(n.from,n.to);if(!1===n.nextSibling()){if(t in s)throw Error(`Duplicate attribute ${t}. Found in component of type ${r} at indices ${n.from}-${n.to}`);s[t]=!0}else{n.nextSibling();let a=e.substring(n.from+1,n.to-1);if(t in s)throw Error(`Duplicate attribute ${t}. Found in component of type ${r} at indices ${n.from}-${n.to}`);s[t]=a}n.parent()}n.parent();let o={componentType:r,props:{...s},children:[]};for(;n.nextSibling();)if("Text"===n.name){let t=e.substring(n.from,n.to);""!==t&&o.children.push(t)}else{if("Element"!==n.name){if("CloseTag"===n.name)break;if("Comment"===n.name)continue;throw"MismatchedCloseTag"===n.name?Error(`Invalid DoenetML at position ${n.from}. Mismatched closing tag. Expected . Found ${e.slice(n.from,n.to)}.`):Error(`Invalid DoenetML at position ${n.from}. Expected a closing tag. Instead found ${e.slice(n.from,n.to)}.`)}o.children.push(t(n.node.cursor))}return o.range={openBegin:a,openEnd:i,closeBegin:n.from,closeEnd:n.to},o}if("SelfClosingTag"===n.name){n.firstChild(),n.nextSibling();let t=e.substring(n.from,n.to),r=n.from,a={};for(;n.nextSibling();){if("Attribute"!==n.name)throw Error(`Invalid DoenetML at positions ${n.from} to ${n.to}. Error in self-closing <${t}/> tag.`);n.firstChild();let r=e.substring(n.from,n.to);if(!1===n.nextSibling()){if(r in a)throw Error(`Duplicate attribute ${r}. Found in component of type ${t} at indices ${n.from}-${n.to}`);a[r]=!0}else{if(n.nextSibling(),r in a)throw Error(`Duplicate attribute ${r}. Found in component of type ${t} at indices ${n.from}-${n.to}`);let i=e.substring(n.from+1,n.to-1);a[r]=i}n.parent()}let i={selfCloseBegin:r,selfCloseEnd:n.to+2};return{componentType:t,props:{...a},children:[],range:i}}throw Error("Non SelfClosingTag/OpenTag in Element. How did you do that?")}function n(n){if("Element"===n.node.name)return t(n.node.cursor);if("Comment"===n.node.name)return null;if("Text"!==n.node.name)throw Error(`Invalid DoenetML at positions ${n.node.from} to ${n.node.to}. Found ${e.substring(n.node.from,n.node.to)}`);{let t=e.substring(n.node.from,n.node.to);if(""!==t)return t}}if(!e)return[];let r=parse(e),a=[];if(!r.firstChild())return a;let i=n(r);for(null!=i&&a.push(i);r.nextSibling();){let e=n(r);null!=e&&a.push(e)}return a}var base32$1={exports:{}};!function(e){!function(){var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof browser$1&&browser$1.versions&&browser$1.versions.node&&(t=commonjsGlobal);var n=!t.HI_BASE32_NO_COMMON_JS&&e.exports,r="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),a={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},i=[0,0,0,0,0,0,0,0],s=function(e,t){t.length>10&&(t="..."+t.substr(-10));var n=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw n.position=e,n},o=function(e){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");for(var t,n,r,i,s,o,l,u,c=[],p=0,d=(e=e.replace(/=/g,"")).length,m=0,h=d>>3<<3;m>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1),c[p++]=255&(s<<7|o<<2|l>>>3),c[p++]=255&(l<<5|u);var f=d-h;return 2===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2)):4===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4)):5===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],s=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1)):7===f&&(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],s=a[e.charAt(m++)],o=a[e.charAt(m++)],l=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1),c[p++]=255&(s<<7|o<<2|l>>>3)),c},l=function(e,t){if(!t)return function(e){for(var t,n,r="",a=e.length,i=0,o=0;i191&&t<=223?(n=31&t,o=1):t<=239?(n=15&t,o=2):t<=247?(n=7&t,o=3):s(i,r);for(var l=0;l191)&&s(i,r),n<<=6,n+=63&t;n>=55296&&n<=57343&&s(i,r),n>1114111&&s(i,r),n<=65535?r+=String.fromCharCode(n):(n-=65536,r+=String.fromCharCode(55296+(n>>10)),r+=String.fromCharCode(56320+(1023&n)))}return r}(o(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");var n,r,i,l,u,c,p,d,m="",h=e.indexOf("=");-1===h&&(h=e.length);for(var f=0,y=h>>3<<3;f>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|p>>>3))+String.fromCharCode(255&(p<<5|d));var g=h-y;return 2===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))):4===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))):5===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],u=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))):7===g&&(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],u=a[e.charAt(f++)],c=a[e.charAt(f++)],p=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|p>>>3))),m},u={encode:function(e,t){var n="string"!=typeof e;return n&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),n?function(e){for(var t,n,a,i,s,o="",l=e.length,u=0,c=5*parseInt(l/5);u>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[31&(i<<3|s>>>5)]+r[31&s];var p=l-c;return 1===p?(t=e[u],o+=r[t>>>3]+r[t<<2&31]+"======"):2===p?(t=e[u++],n=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===p?(t=e[u++],n=e[u++],a=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):4===p&&(t=e[u++],n=e[u++],a=e[u++],i=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[i<<3&31]+"="),o}(e):t?function(e){for(var t,n,a,i,s,o="",l=e.length,u=0,c=5*parseInt(l/5);u>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[31&(i<<3|s>>>5)]+r[31&s];var p=l-c;return 1===p?(t=e.charCodeAt(u),o+=r[t>>>3]+r[t<<2&31]+"======"):2===p?(t=e.charCodeAt(u++),n=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===p?(t=e.charCodeAt(u++),n=e.charCodeAt(u++),a=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):4===p&&(t=e.charCodeAt(u++),n=e.charCodeAt(u++),a=e.charCodeAt(u++),i=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[i<<3&31]+"="),o}(e):function(e){var t,n,a,s,o,l,u,c=!1,p="",d=0,m=0,h=e.length;if(""===e)return p;do{for(i[0]=i[5],i[1]=i[6],i[2]=i[7],u=m;d>6,i[u++]=128|63&l):l<55296||l>=57344?(i[u++]=224|l>>12,i[u++]=128|l>>6&63,i[u++]=128|63&l):(l=65536+((1023&l)<<10|1023&e.charCodeAt(++d)),i[u++]=240|l>>18,i[u++]=128|l>>12&63,i[u++]=128|l>>6&63,i[u++]=128|63&l);m=u-5,d===h&&++d,d>h&&u<6&&(c=!0),t=i[0],u>4?(n=i[1],a=i[2],s=i[3],o=i[4],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|s>>>7)]+r[s>>>2&31]+r[31&(s<<3|o>>>5)]+r[31&o]):1===u?p+=r[t>>>3]+r[t<<2&31]+"======":2===u?(n=i[1],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===u?(n=i[1],a=i[2],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):(n=i[1],a=i[2],s=i[3],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|s>>>7)]+r[s>>>2&31]+r[s<<3&31]+"=")}while(!c);return p}(e)},decode:l};l.asBytes=o,n?e.exports=u:t.base32=u}()}(base32$1);var base32=base32$1.exports;async function cidFromText(e){let t=(new TextEncoder).encode(e);return await cidFromArrayBuffer(t)}async function cidFromArrayBuffer(e){let t=await crypto.subtle.digest("SHA-256",e),n=new Uint8Array(36);return n.set([1,85,18,32]),n.set(new Uint8Array(t),4),"b"+base32.encode(n).toLowerCase().replace(/=+/,"")}const textByCid={};function retrieveTextFileForCid(e,t="doenet"){return void 0!==textByCid[e]?Promise.resolve(textByCid[e]):new Promise(((n,r)=>{let a,i,s=retrieveTextFileFromIPFS(e),o=s.promise,l=s.controller,u=!1,c=!1;o.then((t=>{clearTimeout(i),a&&!c&&a.abort(),textByCid[e]=t,n(t)})).catch((e=>{u=!0,c&&(clearTimeout(i),r(e))})),i=setTimeout((()=>{let s=retrieveTextFileFromServer(e,t),o=s.promise;a=s.controller,o.then((t=>{u||l.abort(),textByCid[e]=t,n(t)})).catch((e=>{c=!0,u?r(e):i=setTimeout((()=>{l.abort(),r(e)}),5e3)}))}),100)}))}function retrieveTextFileFromIPFS(e){let t=new AbortController,n=t.signal;return{promise:async function(){try{let t=await fetch(`https://${e}.ipfs.dweb.link/`,{signal:n});if(t.ok){let n=await t.text();return await cidFromText(n)===e?n:Promise.reject(new Error("cid mismatch"))}return Promise.reject(new Error(`cid not found: ${e}`))}catch(t){return Promise.reject(new Error(`cid not found: ${e}`))}}(),controller:t}}function retrieveTextFileFromServer(e,t){let n=new AbortController,r=n.signal;return{promise:async function(){try{let n=await fetch(`/media/${e}.${t}`,{signal:r});if(n.ok){let t=await n.text(),r=await cidFromText(t);return r===e?t:(console.warn(`cid mismatch, ${e}, ${r}`),Promise.reject(new Error("cid mismatch")))}return Promise.reject(new Error(`cid not found: ${e}`))}catch(t){return Promise.reject(new Error(`cid not found: ${e}`))}}(),controller:n}}async function expandDoenetMLsToFullSerializedComponents({cids:e,doenetMLs:t,componentInfoObjects:n}){let r=[],a={};for(let e of t){let t=parseAndCompile(e);t=cleanIfHaveJustDocument(t),substituteDeprecations(t),temporarilyRenameSourceBackToTarget(t),correctComponentTypeCapitalization(t,n.componentTypeLowerCaseMapping),copyTargetOrFromURIAttributeCreatesCopyComponent(t,n.isCompositeComponent),createAttributesFromProps(t,n),breakUpTargetIntoPropsAndIndices(t,n),applyMacros(t,n),removeBlankStringChildren(t,n),decodeXMLEntities(t),applySugar({serializedComponents:t,componentInfoObjects:n}),r.push(t);let i=findContentCopies({serializedComponents:t});for(let e in i.cidComponents)void 0===a[e]&&(a[e]=[]),a[e].push(...i.cidComponents[e])}let i=Object.keys(a);if(i.length>0){let{newDoenetMLs:e,newCids:t}=await cidsToDoenetMLs(i);for(let[e,n]of i.entries())if(t[e]&&t[e].substring(0,n.length)!==n)return Promise.reject(new Error(`Requested cid ${n} but got back ${t[e]}!`));let r=i.length;for(let n=0;n"string"!=typeof e||e.trim())),r=1===t.length&&"object"==typeof t[0],a=e.doenetAttributes?.fromCopyFromURI;if(a||r)if(a&&!r)console.warn("ignoring copyFromURI as it was not a single component");else{let n=t[0];n.attributes||(n.attributes={}),e.doenetAttributes||(e.doenetAttributes={}),e.doenetAttributes.keptNewNamespaceOfLastChild=Boolean(n.attributes.newNamespace?.primitive),n.attributes.newNamespace={primitive:!0},e.children=[n,...e.children],e.doenetAttributes.nameFirstChildIndependently=!0}else{let t={componentType:"externalContent",children:JSON.parse(JSON.stringify(n)),attributes:{newNamespace:{primitive:!0}},doenetAttributes:{createUniqueName:!0}};e.children=[t,...e.children]}}}}return{cids:e,fullSerializedComponents:r}}function cidsToDoenetMLs(e){let t=[],n=e;for(let n of e)t.push(retrieveTextFileForCid(n,"doenet"));return Promise.all(t).then((e=>Promise.resolve({newDoenetMLs:e,newCids:n}))).catch((e=>{let t;return t=1===n.length?`Could not retrieve cid ${n[0]}`:`Could not retrieve cids ${n.join(",")}`,t+=": "+e.message,console.error(t),Promise.reject(new Error(t))}))}function removeBlankStringChildren(e,t){for(let n of e){if(n.children){let e=t.allComponentClasses[n.componentType];e&&!e.includeBlankStringChildren&&(n.children=n.children.filter((e=>"string"!=typeof e||""!==e.trim()))),removeBlankStringChildren(n.children,t)}for(let e in n.attributes){let r=n.attributes[e].component;r&&r.children&&removeBlankStringChildren([r],t)}}}function findContentCopies({serializedComponents:e}){let t={};for(let n of e)if("copy"===n.componentType){if(n.attributes&&n.attributes.uri){let e=n.attributes.uri.primitive;if(e&&"doenet:"===e.substring(0,7).toLowerCase()){let r=e.match(/[:&]cid=([^&]+)/i);if(r){let e=r[1];void 0===t[e]&&(t[e]=[]),t[e].push(n)}}}}else if(void 0!==n.children){let e=findContentCopies({serializedComponents:n.children});for(let n in e.cidComponents)void 0===t[n]&&(t[n]=[]),t[n].push(...e.cidComponents[n])}return{cidComponents:t}}function addDocumentIfItsMissing(e){if(1!==e.length||"document"!==e[0].componentType){let t=e.splice(0);e.push({componentType:"document",children:t})}}function substituteDeprecations(e){let t={tname:"target",triggerwithtnames:"triggerWith",updatewithtname:"updateWith",paginatortname:"paginator",randomizeorder:"shuffleOrder",copytarget:"copySource",triggerwithtargets:"triggerWith",triggerwhentargetsclicked:"triggerWhenObjectsClicked",fortarget:"forObject",targetattributestoignore:"sourceAttributesToIgnore",targetattributestoignorerecursively:"sourceAttributesToIgnoreRecursively",targetsareresponses:"sourcesAreResponses",updatewithtarget:"updateWith",targetsarefunctionsymbols:"sourcesAreFunctionSymbols",selectforvariantnames:"selectForVariants"},n={copy:{target:"source",tname:"source"},collect:{target:"source",tname:"source"},summarystatistics:{target:"source"}};for(let r of e)if("object"==typeof r){if(r.props){let e=r.componentType,a=n[e.toLowerCase()];a||(a={});let i=!0;for(;i;){i=!1;for(let n in r.props){let s=n.toLowerCase();if(s in a){let t=a[s];console.warn(`Attribute ${n} of component type ${e} is deprecated. Use ${t} instead.`),r.props[t]=r.props[n],delete r.props[n],i=!0;break}if(s in t){let e=t[s];console.warn(`Attribute ${n} is deprecated. Use ${e} instead.`),r.props[e]=r.props[n],delete r.props[n],i=!0;break}}}}r.children&&substituteDeprecations(r.children)}}function temporarilyRenameSourceBackToTarget(e){let t={copysource:"copyTarget"},n={copy:{source:"target"},collect:{source:"target"}};for(let r of e)if("object"==typeof r){if(r.props){let e=n[r.componentType.toLowerCase()];e||(e={});let a=!0;for(;a;){a=!1;for(let n in r.props){let i=n.toLowerCase();if(i in e){let t=e[i];r.props[t]=r.props[n],delete r.props[n],a=!0;break}if(i in t){let e=t[i];r.props[e]=r.props[n],delete r.props[n],a=!0;break}}}}r.children&&temporarilyRenameSourceBackToTarget(r.children)}}function cleanIfHaveJustDocument(e){let t=e.filter((e=>"string"!=typeof e||""!==e.trim()));return 1===t.length&&"document"===t[0].componentType?t:e}function correctComponentTypeCapitalization(e,t){for(let n of e){if("object"!=typeof n)continue;let e=t[n.componentType.toLowerCase()];if(!e)throw Error(`Invalid component type${indexRangeString(n)}: ${n.componentType}`);n.componentType=e,n.children&&correctComponentTypeCapitalization(n.children,t)}}function copyTargetOrFromURIAttributeCreatesCopyComponent(e,t){for(let n of e){if(n.props){let e=!1,r=!1,a=!1,i=n.componentType,s=t({componentType:i,includeNonStandard:!1}),o=t({componentType:i,includeNonStandard:!0});for(let t of Object.keys(n.props)){let l=t.toLowerCase();if("copytarget"===l){if(e)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);if(r)throw Error(`Cannot combine copyTarget and copyFromURI attribiutes. For in component of type ${i}${indexRangeString(n)}`);if(a)throw o?Error(`A component of type ${i} cannot have both assignNames and copyTarget. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);if(e=!0,n.doenetAttributes||(n.doenetAttributes={}),s||(n.props.createComponentOfType=i,n.doenetAttributes.nameBecomesAssignNames=!0),n.componentType="copy",n.props.target=n.props[t],"string"!=typeof n.props.target)throw Error(`Must specify value for copyTarget. Found in component of type ${i}${indexRangeString(n)}`);delete n.props[t],n.doenetAttributes.fromCopyTarget=!0,n.doenetAttributes.createNameFromComponentType=i,n.props.assignNamesSkip="1"}else if("copyfromuri"===l){if(r)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);if(e)throw Error(`Cannot combine copyTarget and copyFromURI attribiutes. For in component of type ${i}${indexRangeString(n)}`);if(a)throw o?Error(`A component of type ${i} cannot have both assignNames and copyFromURI. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);if(r=!0,n.doenetAttributes||(n.doenetAttributes={}),s||(n.props.createComponentOfType=i,n.doenetAttributes.nameBecomesAssignNames=!0),n.componentType="copy",n.props.uri=n.props[t],"string"!=typeof n.props.uri)throw Error(`Must specify value for copyFromURI. Found in component of type ${i}${indexRangeString(n)}`);delete n.props[t],n.doenetAttributes.fromCopyFromURI=!0,n.doenetAttributes.createNameFromComponentType=i,n.props.assignNamesSkip="1"}else if("assignnames"===l&&!s){if(e||r)throw o?Error(`A component of type ${i} cannot have both assignNames and copyTarget. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);a=!0}}if(e){for(let e of Object.keys(n.props)){if("prop"===e.toLowerCase())throw Error(`Invalid attribute prop for component of type ${i}${indexRangeString(n)}`)}let e=!1;for(let t of Object.keys(n.props)){if("copyprop"===t.toLowerCase()){if(e)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);n.props.prop=n.props[t],delete n.props[t],e=!0}}}}n.children&©TargetOrFromURIAttributeCreatesCopyComponent(n.children,t)}}function breakUpTargetIntoPropsAndIndices(e,t,n=""){for(let[r,a]of e.entries()){if(a.props&&["copy","updateValue","animateFromSequence"].includes(a.componentType)){let i,s,o,l,u,c,p;for(let e of Object.keys(a.props)){if("target"===e.toLowerCase()){if(i)throw Error(`Cannot repeat attribute ${e}. Found in component type ${a.componentType}${indexRangeString(a)}`);i=e,p=a.props[e];let t=buildSourcePieces(p,!0);t.success&&t.matchLength===p.length&&(s=t.sourceName,o=t.componentIndex,l=t.componentAttributes,u=t.propArray,c=t.subNames)}}if(i&&s)if(o||l||u.length>0){if(a.attributes.prop)throw Error(`Cannot combine the prop attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);if(a.attributes.propIndex)throw Error(`Cannot combine the propIndex attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);if(a.attributes.componentIndex)throw Error(`Cannot combine the componentIndex attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);let d=createComponentFromExtendedSource({sourceName:s,componentIndex:o,subNames:c,componentAttributes:l,propArray:u,componentInfoObjects:t});if(d.success){let t=d.newComponent;if("copy"===a.componentType)delete a.props[i],Object.assign(a.attributes,t.attributes),a.doenetAttributes||(a.doenetAttributes={}),Object.assign(a.doenetAttributes,t.doenetAttributes),a.doenetAttributes.createNameFromComponentType||(a.doenetAttributes.createNameFromComponentType=a.componentType),a.componentType=t.componentType,0!==u.length||a.attributes.prop||a.attributes.propIndex||(a.doenetAttributes.isPlainCopy=!0),t.children&&(a.children=t.children);else if("copy"===t.componentType)delete a.props[i],Object.assign(a.attributes,t.attributes),a.doenetAttributes||(a.doenetAttributes={}),Object.assign(a.doenetAttributes,t.doenetAttributes);else{let s=createUniqueName("extract","fromExtendedSource"+n+"|"+r);t.doenetAttributes.prescribedName=s,t.doenetAttributes.createdFromMacro=!0;let o={componentType:"setup",children:[t],doenetAttributes:{createdFromMacro:!0}};e.push(o),delete a.props[i],a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.target=s,a.doenetAttributes.allowDoubleUnderscoreTarget=!0}}else"copy"===a.componentType?console.warn(`invalid copy source: ${p}`):console.warn(`invalid target: ${p}`)}else"copy"!==a.componentType||a.attributes.prop||a.attributes.propIndex||(a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.isPlainCopy=!0)}a.children&&breakUpTargetIntoPropsAndIndices(a.children,t,n+"|"+r)}}function createAttributesFromProps(e,t){for(let n of e){if("object"!=typeof n)continue;let e=t.allComponentClasses[n.componentType],r=e.createAttributesObject(),a={};for(let e in r)a[e.toLowerCase()]=e;let i={},s=Object.assign({},n.props);if(n.props)for(let o in n.props){let l=a[o.toLowerCase()],u=r[l];if(u){if(l in i)throw Error(`Cannot repeat attribute ${l}. Found in component type ${n.componentType}${indexRangeString(n)}`);i[l]=componentFromAttribute({attrObj:u,value:n.props[o],originalComponentProps:s,componentInfoObjects:t}),delete n.props[o]}else if(!["name","assignnames","target"].includes(o.toLowerCase())){if(!e.acceptAnyAttribute)throw Error(`Invalid attribute ${o} for component of type ${n.componentType}${indexRangeString(n)}`);i[o]=componentFromAttribute({value:n.props[o],originalComponentProps:s,componentInfoObjects:t}),delete n.props[o]}}for(let e in r){let n=r[e];n.createPrimitiveOfType&&"defaultPrimitiveValue"in n&&!(e in i)&&(i[e]=componentFromAttribute({attrObj:n,originalComponentProps:s,value:n.defaultPrimitiveValue.toString(),componentInfoObjects:t}))}n.attributes=i,void 0!==n.children&&createAttributesFromProps(n.children,t)}}function componentFromAttribute({attrObj:e,value:t,originalComponentProps:n,componentInfoObjects:r}){if("object"!=typeof t?t={rawString:t.toString()}:null===t&&(t={rawString:""}),e&&e.createComponentOfType){let a,i=t.rawString.trim().toLowerCase();if("true"===i&&void 0!==e.valueForTrue)a={componentType:e.createComponentOfType,state:{value:e.valueForTrue}};else if("false"===i&&void 0!==e.valueForFalse)a={componentType:e.createComponentOfType,state:{value:e.valueForFalse}};else if(r.isInheritedComponentType({inheritedComponentType:e.createComponentOfType,baseComponentType:"boolean"})&&["true","false"].includes(i))a={componentType:e.createComponentOfType,state:{value:"true"===i}};else{let n=t.childrenForComponent;n=n?JSON.parse(JSON.stringify(n)):[t.rawString],a={componentType:e.createComponentOfType,children:n},removeBlankStringChildren([a],r)}if(e.attributesForCreatedComponent||e.copyComponentAttributesForCreatedComponent){if(e.attributesForCreatedComponent?a.props=e.attributesForCreatedComponent:a.props={},e.copyComponentAttributesForCreatedComponent)for(let t of e.copyComponentAttributesForCreatedComponent)n[t]&&(a.props[t]=JSON.parse(JSON.stringify(n[t])));createAttributesFromProps([a],r)}let s={component:a};return e.ignoreFixed&&(s.ignoreFixed=!0),s}if(e&&e.createPrimitiveOfType){let n;if("boolean"===e.createPrimitiveOfType){n="true"===t.rawString.trim().toLowerCase()}else n="number"===e.createPrimitiveOfType?Number(t.rawString):"integer"===e.createPrimitiveOfType?Math.round(Number(t.rawString)):"stringArray"===e.createPrimitiveOfType?t.rawString.trim().split(/\s+/):"numberArray"===e.createPrimitiveOfType?t.rawString.trim().split(/\s+/).map(Number):t.rawString;return e.validationFunction&&(n=e.validationFunction(n)),{primitive:n}}if(e&&e.createTargetComponentNames){return{targetComponentNames:t.rawString.trim().split(/\s+/).map((e=>("$"===e[0]&&"$"!==e[1]&&"("===(e=e.slice(1))[0]&&")"===e[e.length-1]&&(e=e.slice(1,e.length-1)),{relativeName:e})))}}return t.childrenForComponent||(t.childrenForComponent=[t.rawString]),t}function findPreSugarIndsAndMarkFromSugar(e){let t=[];for(let n of e)if("object"==typeof n)if(void 0!==n.preSugarInd)t.push(n.preSugarInd);else if(n.doenetAttributes||(n.doenetAttributes={}),n.doenetAttributes.createdFromSugar=!0,n.children){let e=findPreSugarIndsAndMarkFromSugar(n.children);t.push(...e)}return t}function applyMacros(e,t){for(let n of e)if(n.children&&applyMacros(n.children,t),n.attributes)for(let e in n.attributes){let r=n.attributes[e];r.component?applyMacros([r.component],t):r.childrenForComponent&&applyMacros(r.childrenForComponent,t)}substituteMacros(e,t)}function substituteMacros(e,t){for(let n=0;n0&&e[n-1].range){let t=e[n-1].range;t.closeEnd?r+=t.closeEnd:t.selfCloseEnd&&(r+=t.selfCloseBegin)}throw Error(`${d.message}. At indices ${r}-${r+c}. Found: ${t}`)}l=d.newComponent,markCreatedFromMacro([l]),0===s.propArray.length&&(l.doenetAttributes.isPlainMacro=!0),o=[l];let m=1,h=i.substring(u+c);if(2===p){let r=i.slice(u+c).match(/^\s*\(/);if(!r){a=u+2;continue}let s=c+r[0].length,l=[],p=!1;i.length>u+s&&(p=!0,l.push(i.substring(u+s))),l.push(...e.slice(n+1));let d=createEvaluateIfFindMatchedClosingParens({componentsFromMacro:o,remainingComponents:l,includeFirstInRemaining:p,componentInfoObjects:t});if(!d.success){a=u+2;continue}o=d.componentsFromMacro,m=d.lastComponentIndMatched+1,p||m++,h=""}let f=[];u>0&&f.push(i.substring(0,u)),f.push(...o),h.length>0&&f.push(h),e.splice(n,m,...f),u>0&&n++;break}}}}function createComponentFromExtendedSource({sourceName:e,componentIndex:t,componentAttributes:n,propArray:r,subNames:a,componentInfoObjects:i}){let s={componentType:"copy",doenetAttributes:{target:e},attributes:{}};if(t){let e=[t];applyMacros(e,i),s.attributes.componentIndex={component:{componentType:"integer",children:e}}}if(a?.length>0){let e=[],t=[];for(let n of a)e.push(n.subName),void 0!==n.subNameComponentIndex&&(t.length0){let e=[t.join(" ")];applyMacros(e,i),s.attributes.sourceSubnamesComponentIndex={component:{componentType:"numberList",children:e}}}}let o=!1;if(n){o=!0;let e=createAttributesFromString(n,i);if(!e.success)return e;Object.assign(s.attributes,e.newAttributes),e.assignNames&&(s.props={assignNames:e.assignNames})}for(let e of r){if(o&&(s.doenetAttributes.createdFromMacro=!0,s={componentType:"extract",attributes:{},doenetAttributes:{},children:[s]}),s.attributes.prop={primitive:e.prop},e.propIndex){let t=[e.propIndex.join(" ")];applyMacros(t,i),s.attributes.propIndex={component:{componentType:"numberList",children:t}}}if(e.attributes){let t=createAttributesFromString(e.attributes,i);if(!t.success)return t;Object.assign(s.attributes,t.newAttributes),t.assignNames&&(s.props={assignNames:t.assignNames})}o=!0}return{success:!0,newComponent:s}}function createAttributesFromString(e,t){let n,r=``;try{n=parseAndCompile(r)}catch(e){return{success:!1,message:"Error in macro"}}createAttributesFromProps(n,t),markCreatedFromMacro(n),applyMacros(n,t);let a,i=n[0].attributes;if(i.prop||i.propIndex||i.componentIndex)return{success:!1,message:"Error in macro: macro cannot directly add attributes prop, propIndex, or componentIndex"};if(n[0].props)for(let e in n[0].props)if("assignnames"===e.toLowerCase()){if(a)return{success:!1,message:"Error in macro: cannot repeat assignNames"};a=n[0].props[e]}return{success:!0,newAttributes:i,assignNames:a}}function findFirstFullMacroInString(e){let t,n=0;for(;;){let r=e.substring(n).match(/(\$+)(.?)/);if(!r)return{success:!1};if(t=r[1].length,n+=r.index+t,t<=2){let r=!1,a=e.substring(n),i=0,s=findWordOrDelimitedGroup(a,r);"("===s.startDelim&&(r=!0,a=s.group,i=s.group.length);let o=buildSourcePieces(a,r);if(o.success){if(r){if(o.matchLength!==i)return{success:!1};o.matchLength+=2}return o.nDollarSigns=t,o.firstIndMatched=n-t,o.matchLength+=t,o}}}}function buildSourcePieces(e,t){let n=findWordOrDelimitedGroup(e,t),r=0;if(n.withPeriod||!n.word)return{success:!1};let a={sourceName:(n.withSlash?"/":"")+n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t),"["===n.startDelim&&(a.componentIndex=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t));let i=[];for(;n.withSlash;){let a={subName:n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t),"["===n.startDelim&&(a.subNameComponentIndex=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t)),i.push(a)}a.subNames=i,"{"===n.startDelim&&(a.componentAttributes=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t));let s=[];for(;n.withPeriod;){let a={prop:n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t);let i=[];for(;"["===n.startDelim;)i.push(n.group),r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t);i.length>0&&(a.propIndex=i),"{"===n.startDelim&&(a.attributes=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t)),s.push(a)}return a.propArray=s,a.matchLength=r,a.success=!0,a}function findWordOrDelimitedGroup(e,t=!1){let n,r=!1,a=!1;"."===e[0]&&"."!==e[1]&&(r=!0,e=e.substring(1)),t?r?n=/^[\w-]+/:("/"===e[0]&&e[1].match(/\w/)&&(a=!0,e=e.substring(1)),n=/^([\w\/-]|\.\.\/)+/):n=/^[a-zA-Z_]\w*/;let i=e.match(n);if(i)return{success:!0,withPeriod:r,withSlash:a,word:i[0],matchLength:i[0].length+(r?1:0)+(a?1:0)};if(r||a)return{success:!1};let s=[],o={"(":")","{":"}","[":"]"},l=Object.values(o),u=e[0],c=o[u];if(!c)return{success:!1};s.push(c);for(let t=1;t0?t[i]=s.substring(0,a.charInd):t=t.slice(0,i);let l=breakEmbeddedStringByCommas({childrenList:t});l.pieces.forEach((e=>applyMacros(e,r)));let u=l.pieces.map((e=>1===e.length&&"string"!=typeof e[0]?e[0]:{componentType:"math",doenetAttributes:{createdFromMacro:!0},children:e})),c=[{componentType:"evaluate",doenetAttributes:{createdFromMacro:!0},attributes:{function:{component:{componentType:"function",doenetAttributes:{createdFromMacro:!0},children:e}},input:{component:{componentType:"mathList",doenetAttributes:{createdFromMacro:!0},children:u}}}}];return o.length>0&&c.push(o),{success:!0,componentsFromMacro:c,lastComponentIndMatched:i}}function findFirstUnmatchedClosingParens(e){let t=0;for(let[n,r]of e.entries())if("string"==typeof r){let e=r;for(let r=0;r").replace(/</g,"<").replace(/$/g,"$").replace(/&/g,"&")}for(let[n,r]of e.entries())if("string"==typeof r)e[n]=t(r);else if(r.children&&decodeXMLEntities(r.children),r.attributes)for(let e in r.attributes){let n=r.attributes[e];n.component?decodeXMLEntities([n.component]):n.primitive?"string"==typeof n.primitive&&(n.primitive=t(n.primitive)):(n.childrenForComponent&&decodeXMLEntities(n.childrenForComponent),n.rawString&&(n.rawString=t(n.rawString)))}}function applySugar({serializedComponents:e,parentParametersFromSugar:t={},parentAttributes:n={},componentInfoObjects:r,parentUniqueId:a="",isAttributeComponent:i=!1}){for(let[s,o]of e.entries()){if("object"!=typeof o)continue;let e=o.componentType,l=r.allComponentClasses[e];if(!l)throw Error(`Unrecognized component type ${e}`);let u=a+"|"+e+s,c={};for(let e in o.attributes){let t=o.attributes[e];void 0!==t.primitive&&(c[e]=t.primitive)}if(o.children){let a={};if(!o.skipSugar)for(let[s,p]of l.returnSugarInstructions().entries()){let l=o.children.map((e=>"string"==typeof e?"s":"n")).join("");if(p.childrenRegex){let e=l.match(p.childrenRegex);if(!e||e[0].length!==o.children.length)continue}let d=deepClone(o.children),m=0;for(let e of d)"string"!=typeof e&&(e.preSugarInd=m,m++);let h=!1;o.doenetAttributes&&o.doenetAttributes.createdFromMacro&&(h=!0);let f=p.replacementFunction({matchedChildren:d,parentParametersFromSugar:t,parentAttributes:n,componentAttributes:c,uniqueId:u+"|sugar"+s,componentInfoObjects:r,isAttributeComponent:i,createdFromMacro:h});if(f.success){let t=f.newChildren,n=f.newAttributes,r=[],i=[];if(t&&(r=findPreSugarIndsAndMarkFromSugar(t)),n)for(let e in n){let t=n[e].component;t&&i.push(...findPreSugarIndsAndMarkFromSugar(t.children))}let s=[...r,...i];if(s.length!==m||!s.sort(((e,t)=>e-t)).every(((e,t)=>e===t)))throw Error(`Invalid sugar for ${e} as didn't return set of original components`);if(r.length>0){let t=[...r].sort(((e,t)=>e-t));if(!t.every(((e,t)=>e===r[t])))throw Error(`Invalid sugar for ${e} as didn't return original components in order`)}f.parametersForChildrenSugar&&Object.assign(a,f.parametersForChildrenSugar),o.children=t||[],n&&(o.attributes||(o.attributes={}),Object.assign(o.attributes,n))}}l.removeBlankStringChildrenPostSugar&&(o.children=o.children.filter((e=>"string"!=typeof e||/\S/.test(e)))),applySugar({serializedComponents:o.children,parentParametersFromSugar:a,parentAttributes:c,componentInfoObjects:r,parentUniqueId:u})}if(o.attributes)for(let e in o.attributes){let t=o.attributes[e];t.component&&applySugar({serializedComponents:[t.component],parentAttributes:c,componentInfoObjects:r,parentUniqueId:u,isAttributeComponent:!0})}}}function breakStringInPiecesBySpacesOrParens(e){if("string"!=typeof e)return{success:!1};let t=0,n=[];e=e.trim();let r=0;for(let a=0;a0&&n.push(t),r=a}t++}else if(")"===i){if(0===t)return{success:!1};if(1===t){let t=e.substring(r+1,a).trim();if(t.length>0){let e=breakStringInPiecesBySpacesOrParens(t);!0===e.success?n.push(e.pieces):n.push(t)}r=a+1}t--}else if(0===t&&i.match(/\s/)){let t=e.substring(r,a).trim();t.length>0&&n.push(t),r=a}}if(0!==t)return{success:!1};let a=e.substring(r,e.length).trim();return a.length>0&&n.push(a),{success:!0,pieces:n}}function countRegularComponentTypesInNamespace(e,t={}){for(let n of e)if("object"==typeof n){let e=n.componentType,r=t[e];void 0===r&&(r=0);let a=n.doenetAttributes;a?.isAttributeChild||a?.createdFromSugar||a?.createdFromMacro||(t[e]=++r),n.children&&!n.attributes?.newNamespace?.primitive&&(t=countRegularComponentTypesInNamespace(n.children,t))}return t}function renameAutonameBasedOnNewCounts(e,t={}){let n={...t};for(let t of e)if("object"==typeof t){let e=t.componentType,r=n[e];void 0===r&&(r=0);let a=t.doenetAttributes;if(!(a?.isAttributeChild||a?.createdFromSugar||a?.createdFromMacro)&&(n[e]=++r,t.componentName)){let n=t.componentName.lastIndexOf("/"),a=t.componentName.substring(n+1),i="_"+e.toLowerCase();a.substring(0,i.length)===i&&(t.componentName=t.componentName.substring(0,n+1)+i+r)}t.children&&!t.attributes?.newNamespace?.primitive&&(n=renameAutonameBasedOnNewCounts(t.children,n))}return n}function createComponentNames({serializedComponents:e,namespaceStack:t=[],componentInfoObjects:n,parentDoenetAttributes:r={},parentName:a,useOriginalNames:i=!1,attributesByTargetComponentName:s,indOffset:o=0,createNameContext:l="",initWithoutShadowingComposite:u=!1}){0===t.length&&t.push({namespace:"",componentCounts:{},namesUsed:{}});let c=t.length-1,p=t[c];for(let[r,d]of e.entries()){if("object"!=typeof d)continue;let e=d.componentType,m=n.allComponentClasses[e],h=d.doenetAttributes;void 0===h&&(h=d.doenetAttributes={});let f=d.attributes;f||(f=d.attributes={}),h.createNameFromComponentType&&(e=h.createNameFromComponentType);let y,g=h.prescribedName,b=h.assignNames,v=h.target,N=h.isAttributeChild||h.createdFromSugar||h.createdFromMacro||h.createUniqueName;(f.newNamespace?.primitive||i&&d.originalAttributes&&d.originalAttributes.newNamespace)&&(y=!0);let T=void 0!==g,C=d.props;if(void 0===C)C=d.props={};else for(let t in C){let n=t.toLowerCase();if("name"===n){if(void 0!==g)throw Error(`Cannot define name twice. Found in component of type ${e}${indexRangeString(d)}`);g=C[t],delete C[t]}else if("assignnames"===n){if(void 0!==b)throw Error(`Cannot define assignNames twice for a component. Found in component of type ${e}${indexRangeString(d)}`);{let n=breakStringInPiecesBySpacesOrParens(C[t]);if(!n.success)throw Error(`Invalid format for assignnames. Found in component of type ${e}${indexRangeString(d)}`);b=n.pieces,delete C[t]}}else if("target"===n){if(void 0!==v)throw Error(`Cannot define target twice for a component. Found in component of type ${e}${indexRangeString(d)}`);if("string"!=typeof C[t])throw Error(`Must specify value for target. Found in component of type ${e}${indexRangeString(d)}`);v=C[t].trim(),delete C[t]}}if(g){if(!T&&!h.createdFromSugar){if(!/[a-zA-Z]/.test(g.substring(0,1)))throw Error(`Invalid component name: ${g}. Component name must begin with a letter. Found in component of type ${e}${indexRangeString(d)}`);if(!/^[a-zA-Z0-9_\-]+$/.test(g))throw Error(`Invalid component name: ${g}. Component name can contain only letters, numbers, hyphens, and underscores. Found in component of type ${e}${indexRangeString(d)}`)}h.prescribedName=g}else if(N){let t=a+"|createUniqueName|";d.downstreamDependencies?t+=JSON.stringify(d.downstreamDependencies):t+=r+"|"+o+"|"+l,g=createUniqueName(e.toLowerCase(),t)}if(!b&&i&&d.originalDoenetAttributes&&d.originalDoenetAttributes.assignNames&&(b=d.originalDoenetAttributes.assignNames),b){if(!m.assignNamesToReplacements)throw Error(`Cannot assign names for component type ${e}${indexRangeString(d)}`);if(h.assignNames=b,!h.createUniqueAssignNames){let t=flattenDeep(b);if(!h.fromCopyTarget&&!h.fromCopyFromURI)for(let n of t){if(!/[a-zA-Z]/.test(n.substring(0,1)))throw Error(`All assigned names must begin with a letter. Found in component of type ${e}${indexRangeString(d)}`);if(!/^[a-zA-Z0-9_\-]+$/.test(n))throw Error(`Assigned names can contain only letters, numbers, hyphens, and underscores. Found in component of type ${e}${indexRangeString(d)}`)}if(t.length!==new Set(t).size)throw Error(`Duplicate assigned names. Found in component of type ${e}${indexRangeString(d)}`)}}y&&(f.newNamespace={primitive:y});let A=p.componentCounts[e];void 0===A&&(A=0),h.isAttributeChild||h.createdFromSugar||h.createdFromMacro||(p.componentCounts[e]=++A);let V="";for(let e=0;e<=c;e++)V+=t[e].namespace+"/";if(!g){if(i&&d.originalName){let e=d.originalName.lastIndexOf("/");g=d.originalName.substring(e+1)}g||(g="_"+e.toLowerCase()+A)}if(h.nameBecomesAssignNames){y&&(f.assignNewNamespaces={primitive:!0},delete f.newNamespace,y=!1),b=h.assignNames=[g],delete h.nameBecomesAssignNames;let e=a+"|createUniqueName|";h.createUniqueName=!0,delete h.prescribedName,d.downstreamDependencies?e+=JSON.stringify(d.downstreamDependencies):e+=r+"|"+o+"|"+l,g=createUniqueName("copy",e)}if(V+=g,d.componentName=V,g){if(g in p.namesUsed)throw Error(`Duplicate component name ${V}. Found in component of type ${e}${indexRangeString(d)}`);p.namesUsed[g]=!0}if(!y&&b)for(let t of flattenDeep(b)){if(t in p.namesUsed)throw Error(`Duplicate component name ${t} (from assignNames of ${V}). Found in component of type ${e}${indexRangeString(d)}`);p.namesUsed[t]=!0}if(d.doenetAttributes.createUniqueAssignNames&&d.originalName){let e=d.doenetAttributes.assignNames;e||(e=d.doenetAttributes.originalAssignNames);let n,r=V+"|createUniqueName|assignNames|",a="";if(y)a=V+"/",n=d.originalName+"/";else{for(let e=0;e<=c;e++)a+=t[e].namespace+"/";let e=d.originalName.lastIndexOf("/");n=d.originalName.slice(0,e+1)}let i=createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:e,longNameIdBase:r,namespace:a,oldNamespace:n,attributesByTargetComponentName:s});b=d.doenetAttributes.assignNames=i}if(renameMatchingTargetNames(d,s),v){if(!m.acceptTarget)throw Error(`Component type ${e} does not accept a target attribute. Found in component ${V}${indexRangeString(d)}`);if(v.includes("|"))throw Error(`target cannot include |. Found in component of type ${e}${indexRangeString(d)}`);h.target=v,h.targetComponentName=convertComponentTarget({relativeName:v,oldAbsoluteName:h.targetComponentName,namespaceStack:t,acceptDoubleUnderscore:h.createdFromSugar||h.allowDoubleUnderscoreTarget})}for(let e in f){let n=f[e];if(n.targetComponentNames)for(let e of n.targetComponentNames)e.absoluteName=convertComponentTarget({relativeName:e.relativeName,oldAbsoluteName:e.absoluteName,namespaceStack:t,acceptDoubleUnderscore:h.createdFromSugar||h.allowDoubleUnderscoreTarget})}if(d.children)if(y||f.assignNewNamespaces?.primitive){let e={};b&&flattenDeep(b).forEach((t=>e[t]=!0));let r=d.children;if(h.nameFirstChildIndependently&&d.children.length>0){r=r.slice(1);let e={namespace:g,componentCounts:{},namesUsed:{}};t.push(e),createComponentNames({serializedComponents:[d.children[0]],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),t.pop()}let a={namespace:g,componentCounts:{},namesUsed:e};if(h.haveNewNamespaceOnlyFromShadow){let e=!0,o=[...r];for(;o.length>0;){let r=[];for(let t of o){if(Boolean(t.doenetAttributes?.ignoreParentNewNamespace)===e)break;r.push(t)}o.splice(0,r.length),e?t.push(a):u&&r.forEach((e=>e.doenetAttributes.createUniqueName=!0)),createComponentNames({serializedComponents:r,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),e&&t.pop(),e=!e}}else t.push(a),createComponentNames({serializedComponents:r,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),t.pop()}else{let e=d.children;if(h.nameFirstChildIndependently&&e.length>0){e=e.slice(1);let r=p.namesUsed,a=p.componentCounts;p.namesUsed={},p.componentCounts={},createComponentNames({serializedComponents:[d.children[0]],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),p.namesUsed=r,p.componentCounts=a}createComponentNames({serializedComponents:e,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s})}if(d.attributes)for(let e in d.attributes){let r=d.attributes[e];if(r.component){let a=r.component;a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.isAttributeChild=!0,r.ignoreFixed&&(a.doenetAttributes.ignoreParentFixed=!0),createComponentNames({serializedComponents:[a],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s,createNameContext:e})}else r.childrenForComponent&&createComponentNames({serializedComponents:r.childrenForComponent,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s,createNameContext:e})}}return e}function createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:e,longNameIdBase:t,namespace:n,oldNamespace:r,attributesByTargetComponentName:a}){let i=[];for(let[s,o]of e.entries())if(Array.isArray(o)){let e=createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:o,longNameIdBase:t+s+"_",namespace:n,oldNamespace:r,attributesByTargetComponentName:a});i.push(e)}else{let e=createUniqueName("fromAssignNames",t+s);i.push(e),renameMatchingTargetNames({componentName:n+e,originalName:r+o},a,!0)}return i}function convertComponentTarget({relativeName:e,oldAbsoluteName:t,namespaceStack:n,acceptDoubleUnderscore:r}){if(!t&&/__/.test(e)&&!r)throw Error("Invalid reference target: "+e);let a;if("/"===e.substring(0,1))a=e;else{let t=n.length-1;for(;"../"===e.substring(0,3);)e=e.substring(3),t--;t<0&&(t=0),a="";for(let e=0;e<=t;e++)a+=n[e].namespace+"/";a+=e}return a}function serializedComponentsReplacer(e,t){return t!=t?{objectType:"special-numeric",stringValue:"NaN"}:t===1/0?{objectType:"special-numeric",stringValue:"Infinity"}:t===-1/0?{objectType:"special-numeric",stringValue:"-Infinity"}:t}let nanInfinityReviver=function(e,t){if(t&&"special-numeric"===t.objectType){if("NaN"===t.stringValue)return NaN;if("Infinity"===t.stringValue)return 1/0;if("-Infinity"===t.stringValue)return-1/0}return t};function serializedComponentsReviver(e,t){return me$3.reviver(e,theModule.Subset.reviver(e,nanInfinityReviver(e,t)))}function processAssignNames({assignNames:e=[],assignNewNamespaces:t=!1,serializedComponents:n,parentName:r,parentCreatesNewNamespace:a,componentInfoObjects:i,indOffset:s=0,originalNamesAreConsistent:o=!1,shadowingComposite:l=!1}){let u=n.length;moveComponentNamesToOriginalNames(n);let c={},p=null;if(o){if(u>0){let e=n.filter((e=>"object"==typeof e))[0];if(e&&e.originalName){let t=e.originalName.lastIndexOf("/");p=e.originalName.substring(0,t)}}if(null!==p)for(let e of n)setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:p,components:[e],attributesByTargetComponentName:c})}else for(let e=0;e0&&t.originalName){let e=t.originalName.lastIndexOf("/");p=t.originalName.substring(0,e)}null!==p&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:p,components:[t],attributesByTargetComponentName:c})}}let d=[],m=0;for(let h=0;h0&&y.originalName)){let e=y.originalName.lastIndexOf("/");p=y.originalName.substring(0,e)}if(g)if(i.allComponentClasses[y.componentType].assignNamesSkipOver)g=[g];else if(y.attributes?.assignNamesSkip){let e=y.attributes.assignNamesSkip.primitive;if(e>0)for(let t=0;t({namespace:e,componentCounts:{},namesUsed:{}})));"/"!==e[0]&&c.splice(0,0,{componentCounts:{},namesUsed:{},namespace:""}),t.doenetAttributes||(t.doenetAttributes={}),t.attributes||(t.attributes={}),t.attributes.newNamespace?.primitive||s?u=!0:(u=!1,t.children&&markToCreateAllUniqueNames(t.children));for(let e in t.attributes){let n=t.attributes[e];n.component?markToCreateAllUniqueNames([n.component]):n.childrenForComponent&&markToCreateAllUniqueNames(n.childrenForComponent)}createComponentNames({serializedComponents:[t],namespaceStack:c,componentInfoObjects:a,parentName:e,useOriginalNames:u,attributesByTargetComponentName:i,indOffset:n,initWithoutShadowingComposite:!o})}function setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:t,attributesByTargetComponentName:n}){let r=e.length;for(let a of t)if("object"==typeof a){if(a.doenetAttributes&&a.doenetAttributes.target){let t=a.doenetAttributes.targetComponentName;void 0!==t&&(t.substring(0,r)!==e&&(a.doenetAttributes.target=t),n[t]||(n[t]=[]),n[t].push(a.doenetAttributes))}for(let t in a.attributes){let i=a.attributes[t];if(i.targetComponentNames)for(let t of i.targetComponentNames){let a=t.absoluteName;void 0!==a&&(a.substring(0,r)!==e&&(t.relativeName=a),n[a]||(n[a]=[]),n[a].push(t))}}if(a.children&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:a.children,attributesByTargetComponentName:n}),a.attributes)for(let t in a.attributes){let r=a.attributes[t];r.component?setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:[r.component],attributesByTargetComponentName:n}):r.childrenForComponent&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:r.childrenForComponent,attributesByTargetComponentName:n})}}}function renameMatchingTargetNames(e,t,n=!1){if(e.originalName&&t&&e.componentName!==e.originalName){if(t[e.originalName])for(let n of t[e.originalName])n.relativeName?(n.relativeName=e.componentName,n.absoluteName=e.componentName):(n.target=e.componentName,n.targetComponentName=e.componentName);if(n){let n=e.originalName+"/",r=n.length;for(let a in t)if(a.substring(0,r)===n){let n=a.substring(r);for(let r of t[a])r.relativeName?(r.relativeName=e.componentName+"/"+n,r.absoluteName=e.componentName+"/"+n):(r.target=e.componentName+"/"+n,r.targetComponentName=e.componentName+"/"+n)}}}}function moveComponentNamesToOriginalNames(e){for(let t of e)if(t.componentName&&(t.originalName=t.componentName,delete t.componentName),t.children&&moveComponentNamesToOriginalNames(t.children),t.attributes)for(let e in t.attributes){let n=t.attributes[e];n.component?moveComponentNamesToOriginalNames([n.component]):n.childrenForComponent&&moveComponentNamesToOriginalNames(n.childrenForComponent)}}function markToCreateAllUniqueNames(e){for(let t of e)if("object"==typeof t&&(t.doenetAttributes||(t.doenetAttributes={}),t.doenetAttributes.createUniqueName=!0,delete t.doenetAttributes.prescribedName,t.attributes?.newNamespace?.primitive||(t.doenetAttributes.assignNames?(t.doenetAttributes.createUniqueAssignNames=!0,t.doenetAttributes.originalAssignNames=t.doenetAttributes.assignNames,delete t.doenetAttributes.assignNames):t.originalDoenetAttributes&&t.originalDoenetAttributes.assignNames&&(t.doenetAttributes.createUniqueAssignNames=!0,t.doenetAttributes.originalAssignNames=t.originalDoenetAttributes.assignNames),t.children&&markToCreateAllUniqueNames(t.children)),t.attributes))for(let e in t.attributes){let n=t.attributes[e];n.component?markToCreateAllUniqueNames([n.component]):n.childrenForComponent&&markToCreateAllUniqueNames(n.childrenForComponent)}}function setTNamesToAbsolute(e){for(let t of e){if(t.doenetAttributes&&t.doenetAttributes.target){let e=t.doenetAttributes.targetComponentName;void 0!==e&&(t.doenetAttributes.target=e)}if(t.children&&setTNamesToAbsolute(t.children),t.attributes)for(let e in t.attributes){let n=t.attributes[e];n.component?setTNamesToAbsolute([n.component]):n.childrenForComponent&&setTNamesToAbsolute(n.childrenForComponent)}}}function restrictTNamesToNamespace({components:e,namespace:t,parentNamespace:n,parentIsCopy:r=!1,invalidateReferencesToBaseNamespace:a=!1}){void 0===n&&(n=t);let i=t.length;for(let s of e){if(s.doenetAttributes&&s.doenetAttributes.target){let e=s.doenetAttributes.target;if("/"===e[0]){if(e.substring(0,i)!==t){let n=t.split("/").slice(1),r=e.split("/").slice(1),a=!1,i=t+e.slice(1);for(;n.length>0&&n[0]===r[0];)n=n.slice(1),r=r.slice(1),a=!0;if(a)i=t+r.join("/");else{let n=t.split("/").slice(1);for(let t=1;tn){r&&t<=n&&a.push({begin:t,end:n,componentName:r}),s=!0;break}r&&o.indBegin>t&&a.push({begin:t,end:o.indBegin-1,componentName:r});let l=extractRangeIndexPieces({componentArray:e.slice(i+1),lastInd:o.indBegin,stopInd:o.indEnd,enclosingComponentName:o.componentName});i+=l.componentsConsumed+1,a.push(...l.rangePieces),t=o.indEnd+1}return!s&&Number.isFinite(n)&&n>=t&&a.push({begin:t,end:n,componentName:r}),{componentsConsumed:i,rangePieces:a}}function createStateProxyHandler(){return{get:function(e,t){let n=e[t];return void 0!==n&&(n=n.isArray&&(n.public||n.trackChanges)?new Proxy(n.value,createArrayProxyHandler({variable:t,nDimensions:n.nDimensions})):n.value),n},set:function(e,t,n){throw Error("Property "+t+" is read-only")},deleteProperty:function(e,t){throw Error("Property "+t+" is read-only")}}}function createArrayProxyHandler({variable:e,nDimensions:t,indicesSoFar:n=[]}){return{variable:e,nDimensions:t,indicesSoFar:n,get:function(e,n){if("then"===n&&e instanceof Promise)return t=>e.then.bind(e)((e=>t(null!==e&&"object"==typeof e?new Proxy(e,createArrayProxyHandler({variable:this.variable,nDimensions:this.nDimensions,indicesSoFar:this.indicesSoFar})):e)));let r=e[n];return null!==r&&"object"==typeof r&&t>1&&(r=new Proxy(r,createArrayProxyHandler({variable:this.variable,nDimensions:this.nDimensions-1,indicesSoFar:[...this.indicesSoFar,n]}))),r},set:function(e,t,n){throw Error("Property "+t+" is read-only")},deleteProperty:function(e,t){throw Error("Property "+t+" is read-only")}}}function postProcessCopy({serializedComponents:e,componentName:t,addShadowDependencies:n=!0,markAsPrimaryShadow:r=!1,uniqueIdentifiersUsed:a=[],identifierPrefix:i="",unlinkExternalCopies:s=!1,copiesByTargetComponentName:o={},componentNamesFound:l=[],assignNamesFound:u=[],activeAliases:c=[],init:p=!0}){for(let d in e){let m,h=e[d];if("object"==typeof h){if(h.originalName){if(s){if(l.push(h.originalName),h.originalDoenetAttributes&&h.originalDoenetAttributes.assignNames){let e;if(h.attributes.newNamespace?.primitive)e=h.originalName;else{let t=h.originalName.lastIndexOf("/");e=h.originalName.substring(0,t)}for(let t of h.originalDoenetAttributes.assignNames)l.push(e+"/"+t),u.push(e+"/"+t)}h.attributes&&(h.attributes.alias&&c.push(h.attributes.alias.primitive),h.attributes.indexAlias&&c.push(h.attributes.indexAlias.primitive))}if(m=i+h.originalName+"|shadow",!h.originalNameFromSerializedComponent)if(n){let e={[h.originalName]:[{dependencyType:"referenceShadow",compositeName:t}]};if(p&&(e[h.originalName][0].firstLevelReplacement=!0),r&&(e[h.originalName][0].isPrimaryShadow=!0),h.state){let t=Object.keys(h.state);e[h.originalName].downstreamStateVariables=t,e[h.originalName].upstreamStateVariables=t}h.downstreamDependencies=e}else h.unlinkedCopySource=h.originalName}else m=i+h.componentType+"|shadowUnnamed";if("copy"===h.componentType&&s){let e=h.doenetAttributes.targetComponentName;if(e)c.includes(h.doenetAttributes.target)?h.doenetAttributes.targetComponentName=h.doenetAttributes.target:(void 0===o[e]&&(o[e]=[]),o[e].push(h));else if(!h.attributes.uri)throw Error("we need to create a targetComponentName here, then.")}h.uniqueIdentifier=getUniqueIdentifierFromBase(m,a)}}for(let p in e){let d=e[p];if("object"==typeof d){postProcessCopy({serializedComponents:d.children,componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1});for(let e in d.attributes){let p=d.attributes[e];p.component&&(p.component=postProcessCopy({serializedComponents:[p.component],componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1})[0])}d.replacements&&postProcessCopy({serializedComponents:d.replacements,componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1})}}if(p&&s)for(let e in o)if(!l.includes(e)){let t=!1;for(let n of u){let r=n+"/",a=r.length;if(e.substring(0,a)===r){t=!0;break}}if(!t)for(let t of o[e])t.attributes||(t.attributes={}),t.attributes.link={primitive:!1},t.doenetAttributes.target=t.doenetAttributes.targetComponentName}return e}function convertAttributesForComponentType({attributes:e,componentType:t,componentInfoObjects:n,compositeAttributesObj:r={},compositeCreatesNewNamespace:a,flags:i}){let s=n.allComponentClasses[t],o=s.createAttributesObject(),l={};for(let e in o)l[e.toLowerCase()]=e;let u={};for(let t in e){if(t in r&&!r[t].leaveRaw)continue;let i=l[t.toLowerCase()],c=o[i];if(c){if(i in u)throw Error(`Cannot repeat prop ${i}`);if(u[i]=componentFromAttribute({attrObj:c,value:JSON.parse(JSON.stringify(e[t])),componentInfoObjects:n}),u[i].component?.children){let e=[u[i].component];if(applyMacros(e,n),removeBlankStringChildren(e,n),applySugar({serializedComponents:e,componentInfoObjects:n,isAttributeComponent:!0}),a)for(let e of u[i].component.children)if("copy"===e.componentType){let t=e.doenetAttributes.target;/[a-zA-Z_]/.test(t[0])&&(e.doenetAttributes.target="../"+t)}}}else s.acceptAnyAttribute&&(u[t]=JSON.parse(JSON.stringify(e[t])))}return u}async function verifyReplacementsMatchSpecifiedType({component:e,replacements:t,replacementChanges:n,assignNames:r,workspace:a={},componentInfoObjects:i,compositeAttributesObj:s,flags:o}){if(!e.attributes.createComponentOfType?.primitive&&!e.sharedParameters.compositesMustHaveAReplacement)return{replacements:t,replacementChanges:n};let l,u=e.replacementsToWithhold;if(n){l=e.replacements.map((e=>e.componentType));for(let e of n)if("add"===e.changeType){if(void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold),!e.changeTopLevelReplacements)continue;if(e.serializedReplacements){let t=e.numberReplacementsToReplace;t>0||(t=0);let n=e.firstReplacementInd,r=e.serializedReplacements.map((e=>e.componentType));l.splice(n,t,...r)}}else if("delete"===e.changeType){if(void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold),e.changeTopLevelReplacements){let t=e.firstReplacementInd,n=e.numberReplacementsToDelete;l.splice(t,n)}}else"changeReplacementsToWithhold"===e.changeType&&void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold)}else i.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"template"})&&(t=t.filter((e=>e.componentType||e.trim().length>0))),l=t.map((e=>e.componentType)),1===l.length&&"externalContent"===l[0]&&(l=t[0].children.filter((e=>e.componentType||e.trim().length>0)).map((e=>e.componentType)));if(u>0&&(l=l.slice(0,l.length-u)),!e.attributes.createComponentOfType?.primitive&&e.sharedParameters.compositesMustHaveAReplacement&&l.length>0)return{replacements:t,replacementChanges:n};let c=e.attributes.createComponentOfType?.primitive,p=await e.stateValues.nComponentsSpecified;if(!c){if(c=e.sharedParameters.compositesDefaultReplacementType,!c)throw Error("A component class specified descendantCompositesMustHaveAReplacement but didn't specify descendantCompositesDefaultReplacementType");p=1}if(c=i.componentTypeLowerCaseMapping[c.toLowerCase()],l.length!==p||!l.every((e=>e===c))){if(1===t?.length&&i.isInheritedComponentType({inheritedComponentType:t[0].componentType,baseComponentType:"template"}))return t[0].attributes||(t[0].attributes={}),t[0].attributes.createComponentOfType={primitive:c},t[0].attributes.nComponents={primitive:p},{replacements:t,replacementChanges:n};let d,m=l.length===p&&!(u>0)&&a.sourceNames?.length===p;m&&n&&(1===n.length&&n[0].numberReplacementsToReplace===p?d=n[0].serializedReplacements:m=!1),m?d||(d=t):(a.numReplacementsBySource=[],a.numNonStringReplacementsBySource=[],a.propVariablesCopiedBySource=[],a.sourceNames=[],a.uniqueIdentifiersUsedBySource={},a.uniqueIdentifiersUsedBySource[0]=[]);let h=e.attributes.newNamespace?.primitive;t=[];for(let n=0;n"string"!=typeof e)).length),n){n=[],e.replacementsToWithhold>0&&n.push({changeType:"changeReplacementsToWithhold",replacementsToWithhold:0});let r=0;e.replacements&&(r=e.replacements.length),n.push({changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:r,serializedReplacements:t})}}return{replacements:t,replacementChanges:n}}function gatherDescendants({ancestor:e,descendantTypes:t,recurseToMatchedChildren:n=!0,useReplacementsForComposites:r=!1,includeNonActiveChildren:a=!1,skipOverAdapters:i=!1,ignoreReplacementsOfMatchedComposites:s=!1,ignoreReplacementsOfEncounteredComposites:o=!1,init:l=!0,componentInfoObjects:u}){let c=e=>t.some((t=>u.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:t}))),p=[];if(r&&u.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"}))l&&p.push(...replacementsForComposites({composite:e,componentInfoObjects:u,includeComposites:a}).filter((e=>"object"==typeof e)));else for(let t of e.allChildrenOrdered){let n,r=e.allChildren[t],s=!1,o=!1;if(r)n=r.component,n.adaptedFrom&&(o=!0),e.activeChildren.includes(n)&&(s=!0);else for(let r of e.activeChildren){if(r.placeholderInd===t){n=r,s=!0,"string"==typeof t&&"adapt"===t.substring(t.length-5,t.length)&&(o=!0);break}if(r.adaptedFrom&&achild.adaptedFrom.placeholderInd===t){n=r.adaptedFrom;break}}n&&(o&&i?p.includes(n.adaptedFrom)||p.push(n.adaptedFrom):(s||a)&&p.push(n))}if(s||o){let e=[];for(let t of p){let n=c(t);o&&!n&&(n=!("copy"===t.componentType&&t.doenetAttributes.copiedURI)),n&&u.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:"_composite"})&&(e=[...e,...replacementsForComposites({composite:t,componentInfoObjects:u,includeComposites:!0}).filter((e=>"object"==typeof e)).map((e=>e.componentName?e.componentName:e.placeholderInd))])}e.length>0&&(p=p.filter((t=>!(e.includes(t.componentName)||e.includes(t.placeholderInd)))))}let d=[];for(let e of p){let l=c(e);if(l&&d.push({componentName:e.componentName?e.componentName:e.placeholderInd,componentType:e.componentType}),(!l||n)&&void 0===e.placeholderInd){let l=gatherDescendants({ancestor:e,descendantTypes:t,recurseToMatchedChildren:n,useReplacementsForComposites:r,includeNonActiveChildren:a,skipOverAdapters:i,ignoreReplacementsOfMatchedComposites:s,ignoreReplacementsOfEncounteredComposites:o,init:!1,componentInfoObjects:u});d.push(...l)}}return d}function replacementsForComposites({composite:e,includeComposites:t=!1,componentInfoObjects:n}){let r=[];if(e.replacements){let a;if(e.replacementsToWithhold){let t=e.replacements.length-e.replacementsToWithhold;a=e.replacements.slice(0,t)}else a=e.replacements;for(let e of a)n.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"})?(t&&r.push(e),r.push(...replacementsForComposites({composite:e,componentInfoObjects:n,includeComposites:t}))):r.push(e)}return r}function ancestorsIncludingComposites(e,t){if(void 0===e.ancestors||0===e.ancestors.length)return[];let n=[e.ancestors[0].componentName],r=t[e.ancestors[0].componentName];if(r&&n.push(...ancestorsIncludingComposites(r,t)),e.replacementOf){n.push(e.replacementOf.componentName);let r=ancestorsIncludingComposites(e.replacementOf,t);for(let e of r)n.includes(e)||n.push(e)}return n}const dependencyTypeArray=[];class DependencyHandler{constructor({_components:e,componentInfoObjects:t,core:n}){this.upstreamDependencies={},this.downstreamDependencies={},this.switchDependencies={},this.circularCheckPassed={},this.circularResolveBlockedCheckPassed={},this.dependencyTypes={},dependencyTypeArray.forEach((e=>this.dependencyTypes[e.dependencyType]=e)),this.core=n,this._components=e,this.componentInfoObjects=t,this.updateTriggers={descendantDependenciesByAncestor:{},ancestorDependenciesByPotentialAncestor:{},replacementDependenciesByComposite:{},childDependenciesByParent:{},parentDependenciesByParent:{},dependenciesMissingComponentBySpecifiedName:{},dependenciesBasedOnDependenciesOfStateVariables:{},primaryShadowDependencies:{}},this.resolveBlockers={neededToResolve:{},resolveBlockedBy:{}}}async setUpComponentDependencies(e){this.downstreamDependencies[e.componentName]&&this.deleteAllDownstreamDependencies({component:e}),this.downstreamDependencies[e.componentName]={},this.upstreamDependencies[e.componentName]||(this.upstreamDependencies[e.componentName]={});let t=[],n=[];for(let r in e.state)e.state[r].isArrayEntry||e.state[r].isAlias||n.includes(r)||(t.push(r),e.state[r].additionalStateVariablesDefined&&n.push(...e.state[r].additionalStateVariablesDefined));for(let n of t){let t=[n];e.state[n].additionalStateVariablesDefined&&t.push(...e.state[n].additionalStateVariablesDefined),await this.setUpStateVariableDependencies({component:e,stateVariable:n,allStateVariablesAffected:t})}}async setUpStateVariableDependencies({component:e,stateVariable:t,allStateVariablesAffected:n}){let r,a=e.state[t];a.stateVariablesDeterminingDependencies?(r={},a.stateVariablesDeterminingDependencies&&(r.__determine_dependencies={dependencyType:"determineDependencies",variableNames:a.stateVariablesDeterminingDependencies})):r=await a.returnDependencies({componentInfoObjects:this.componentInfoObjects,sharedParameters:e.sharedParameters});for(let a in r){let i=r[a];if(!(i.dependencyType in this.dependencyTypes))throw Error(`Unrecognized dependency type ${i.dependencyType} for ${a} of ${t} of ${e.componentName}`);let s=new this.dependencyTypes[i.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:n,dependencyName:a,dependencyDefinition:i,dependencyHandler:this,expandComposites:!1,forceExpandComposites:!1});await s.initialize(),s.checkForCircular()}}deleteAllDownstreamDependencies({component:e,stateVariables:t="__all__"}){let n,r=e.componentName;n="__all__"===t?Object.keys(this.downstreamDependencies[r]):t;for(let e of n){let t=this.downstreamDependencies[r][e];for(let e in t)t[e].deleteDependency();delete this.downstreamDependencies[r][e]}0!==Object.keys(this.downstreamDependencies[r]).length||this.components[r]||delete this.downstreamDependencies[r]}async deleteAllUpstreamDependencies({component:e,stateVariables:t="__all__",completelyDelete:n=!1}){let r,a=e.componentName;r="__all__"===t?Object.keys(this.upstreamDependencies[a]):t;for(let e of r){if(this.upstreamDependencies[a][e])for(let t of[...this.upstreamDependencies[a][e]])if(n){for(let e of t.upstreamVariableNames)this._components[t.upstreamComponentName].state[e].initiallyResolved&&await this.core.markStateVariableAndUpstreamDependentsStale({component:this.components[t.upstreamComponentName],varName:e});t.deleteDependency()}else await t.removeDownstreamComponent({indexToRemove:t.downstreamComponentNames.indexOf(a)});delete this.upstreamDependencies[a][e]}0!==Object.keys(this.upstreamDependencies[a]).length||this._components[a]||delete this.upstreamDependencies[a]}async addBlockersFromChangedStateVariableDependencies({componentName:e,stateVariables:t}){let n=this.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e];if(n)for(let r of t){let t=n[r];if(t)for(let n of t)if(n.gettingValue){let t=n.varsWithUpdatedDeps[e];t||(t=n.varsWithUpdatedDeps[e]=[]),t.includes(r)||t.push(r)}else for(let e of n.upstreamVariableNames)await this.addBlocker({blockerComponentName:n.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:n.dependencyName,componentNameBlocked:n.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e})}}async addBlockersFromChangedActiveChildren({parent:e}){if(await this.collateCountersAndPropagateToAncestors(e),this.updateTriggers.childDependenciesByParent[e.componentName])for(let t of this.updateTriggers.childDependenciesByParent[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}if(e.ancestors){if(this.updateTriggers.parentDependenciesByParent[e.componentName])for(let t of this.updateTriggers.parentDependenciesByParent[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}for(let t of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.addDescendantBlockersToAncestor(t);if(this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])for(let t of this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}}}async resolveBlockersFromChangedActiveChildren(e,t=!1){if(await this.collateCountersAndPropagateToAncestors(e),this.updateTriggers.childDependenciesByParent[e.componentName])for(let n of this.updateTriggers.childDependenciesByParent[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t});if(e.ancestors){if(this.updateTriggers.parentDependenciesByParent[e.componentName])for(let n of this.updateTriggers.parentDependenciesByParent[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t});for(let n of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.resolveDescendantBlockersToAncestor(n,t);if(this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])for(let n of this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t})}}async addDescendantBlockersToAncestor(e){if(this.updateTriggers.descendantDependenciesByAncestor[e])for(let t of this.updateTriggers.descendantDependenciesByAncestor[e]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}}async resolveDescendantBlockersToAncestor(e,t=!1){if(this.updateTriggers.descendantDependenciesByAncestor[e])for(let n of this.updateTriggers.descendantDependenciesByAncestor[e])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t})}async addBlockersFromChangedReplacements(e){if(this.updateTriggers.replacementDependenciesByComposite[e.componentName])for(let t of this.updateTriggers.replacementDependenciesByComposite[e.componentName])for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let t of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.addDescendantBlockersToAncestor(t)}checkForCircularDependency({componentName:e,varName:t,previouslyVisited:n=[]}){let r=e+":"+t;if(n.includes(r)){console.log("found circular",r,n);let e,t=/^(.*):/,a=n.map((e=>e.match(t)[1])),i=a.filter((e=>"__"!==e.slice(0,2))).reduce(((e,t)=>e.includes(t)?e:[...e,t]),[]);throw 0===i.length&&(i=[a[0]]),1===i.length?e=i[0]:2===i.length?e=i.join(" and "):(i[i.length-2]=i.slice(i.length-2).join(", and "),i.pop(),e=i.join(", ")),Error(`Circular dependency involving ${e}`)}if(n=[...n,r],!this.circularCheckPassed[r]&&(this.circularCheckPassed[r]=!0,e in this.downstreamDependencies)){let r=this.downstreamDependencies[e][t];for(let e in r){let t=r[e],a=t.downstreamComponentNames;if(!a)continue;let i=t.mappedDownstreamVariableNamesByComponent;if(i)for(let[e,t]of a.entries()){let r=i[e];for(let e of r)this.checkForCircularDependency({componentName:t,varName:e,previouslyVisited:n})}}}}resetCircularCheckPassed(e,t){let n=e+":"+t;if(this.circularCheckPassed[n]){delete this.circularCheckPassed[n];let r=this.upstreamDependencies[e][t];if(r)for(let e of r)for(let t of e.upstreamVariableNames)"__identity"!==t&&this.resetCircularCheckPassed(e.upstreamComponentName,t)}}async updateDependencies({componentName:e,stateVariable:t,dependency:n}){let r=this._components[e],a=r.state[t],i=[t];a.additionalStateVariablesDefined&&i.push(...a.additionalStateVariablesDefined);let s,o=this.downstreamDependencies[e][t].__determine_dependencies;if(o){let t=!0;if(o.originalDownstreamVariableNames.length>0)for(let[r,a]of o.downstreamComponentNames.entries()){let s=this._components[a];for(let l of o.mappedDownstreamVariableNamesByComponent[r]){let r=s.state[l].isResolved;if(!r){r=(await this.resolveItem({componentName:a,type:"stateVariable",stateVariable:l})).success}if(!r){t=!1;for(let t of i)await this.addBlocker({blockerComponentName:a,blockerType:"stateVariable",blockerStateVariable:l,componentNameBlocked:e,typeBlocked:"determineDependencies",stateVariableBlocked:t,dependencyBlocked:n})}}}if(!t)return{success:!1};s=await o.getValue()}else s={changes:{},value:{stateValues:{}}};if(0===Object.keys(s.changes).length&&void 0!==a._previousValue)return{success:!0};let l={stateValues:Object.assign({},s.value.stateValues),componentInfoObjects:this.componentInfoObjects,sharedParameters:r.sharedParameters},u=await a.returnDependencies(l);a.stateVariablesDeterminingDependencies&&(u.__determine_dependencies={dependencyType:"determineDependencies",variableNames:a.stateVariablesDeterminingDependencies});let c=await this.replaceDependenciesIfChanged({component:r,stateVariable:t,newDependencies:u,allStateVariablesAffected:i});if(!c.changedDependency&&!l.changedDependency)return{success:!0};for(let e of c.newlyCreatedDependencies)e.checkForCircular();for(let e of i)this.checkForCircularDependency({componentName:r.componentName,varName:e}),r.state[e].forceRecalculation=!0;a.initiallyResolved&&await this.core.markStateVariableAndUpstreamDependentsStale({component:r,varName:t});for(let e of i)r.state[e].initiallyResolved&&this.recordActualChangeInUpstreamDependencies({component:r,varName:e});return await this.addBlockersFromChangedStateVariableDependencies({componentName:e,stateVariables:i}),{success:!0}}async replaceDependenciesIfChanged({component:e,stateVariable:t,newDependencies:n,allStateVariablesAffected:r}){let a=this.downstreamDependencies[e.componentName][t],i=!1,s=[];for(let e in a)e in n||(i=!0,a[e].deleteDependency());for(let o in n)if(o in a){if(!deepCompare(n[o],a[o].definition)){i=!0,a[o].deleteDependency();let l=n[o],u=new this.dependencyTypes[l.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:r,dependencyName:o,dependencyDefinition:l,dependencyHandler:this});await u.initialize(),s.push(u)}}else{i=!0;let a=n[o],l=new this.dependencyTypes[a.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:r,dependencyName:o,dependencyDefinition:a,dependencyHandler:this});await l.initialize(),s.push(l)}return{changedDependency:i,newlyCreatedDependencies:s}}async checkForDependenciesOnNewComponent(e){let t=[],n={};if(this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]){for(let r of this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]){let a=this._components[r.upstreamComponentName];if(!a)continue;let i=!0;for(let e of r.upstreamVariableNames)if(!(e in a.state)){i=!1;break}if(i){for(let e of r.upstreamVariableNames){a.state[e].initiallyResolved&&(n[r.upstreamComponentName]&&n[r.upstreamComponentName][e]||t.push({componentName:r.upstreamComponentName,varName:e}))}for(let t of r.upstreamVariableNames)this.deleteFromNeededToResolve({componentNameBlocked:r.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:r.dependencyName,blockerComponentName:e,blockerType:"componentIdentity"});if((await this.resolveIfReady({componentName:r.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:r.representativeStateVariable,dependency:r.dependencyName,expandComposites:!1,recurseUpstream:!0})).success)for(let e of r.upstreamVariableNames)a.state[e].initiallyResolved||(n[r.upstreamComponentName]||(n[r.upstreamComponentName]={}),n[r.upstreamComponentName][e]=!0);else for(let e of r.upstreamVariableNames)await this.addBlocker({blockerComponentName:r.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:r.dependencyName,componentNameBlocked:r.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e})}}delete this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]}return t}async getStateVariableDependencyValues({component:e,stateVariable:t}){let n={},r={},a={},i=this.downstreamDependencies[e.componentName][t];for(let e in i){let{value:t,changes:s,usedDefault:o}=await i[e].getValue();n[e]=t,Object.keys(s).length>0&&(r[e]=s),o&&(a[e]=o)}return{dependencyValues:n,changes:r,usedDefault:a}}recordActualChangeInUpstreamDependencies({component:e,varName:t,changes:n}){let r=e.componentName,a=this.upstreamDependencies[r][t];if(a)for(let i of a)if(i.valuesChanged){let a=i.downstreamComponentNames.indexOf(r),s=i.valuesChanged[a][t];if(!s&&e.stateVarAliases)for(let n in e.stateVarAliases)e.stateVarAliases[n]===t&&n in upValuesChangedSub&&(s=upValuesChangedSub[n]);if(!s){if(!e.state[t].isArrayEntry)throw Error(`Something is wrong, as a variable ${t} of ${e.componentName} actually changed, but wasn't marked with a potential change`);s=upValuesChangedSub[t]={changed:{}}}e.state[t]&&e.state[t].isArray?(void 0===s.changed?s.changed={arrayKeysChanged:{}}:!0===s.changed&&(s.changed={allArrayKeysChanged:!0,arraySizeChanged:!0,arrayKeysChanged:{}}),n&&(n.allArrayKeysChanged&&(s.changed.allArrayKeysChanged=!0),n.arraySizeChanged&&(s.changed.arraySizeChanged=!0),Object.assign(s.changed.arrayKeysChanged,n.arrayKeysChanged))):s.changed=!0}}async collateCountersAndPropagateToAncestors(e){let t=Object.keys(e.counters);for(let n of e.allChildrenOrdered){let e=this._components[n];if(e)for(let n in e.counters)t.includes(n)||t.push(n)}let n=!1;for(let r of t){let t=e.counters[r];t||(t=e.counters[r]={dependencies:[],componentList:[]});let a=[];t.dependencies.length>0&&a.push(e.componentName);for(let t of e.allChildrenOrdered){let e=this._components[t];if(e){let t=e.counters[r];t&&a.push(...t.componentList)}}(a.length!==t.componentList.length||t.componentList.some(((e,t)=>e!=a[t])))&&(n=!0,t.componentList=a)}if(!n)return{foundChange:!1};if(!e.ancestors[0]){for(let n of t){let t=e.counters[n];for(let[e,r]of t.componentList.entries()){let t=this._components[r],a=t.counters[n];a.value=e+1;for(let e of a.dependencies)if(t.state[e.representativeStateVariable].initiallyResolved){await this.core.markStateVariableAndUpstreamDependentsStale({component:t,varName:e.representativeStateVariable});for(let n of e.upstreamVariableNames)t.state[n].forceRecalculation=!0,this.recordActualChangeInUpstreamDependencies({component:t,varName:n})}}}return{foundChange:!0,finishedPropagation:!0}}let r=this._components[e.ancestors[0].componentName];if(!r||!r.allChildrenOrdered.includes(e.componentName))return{foundChange:!0,finishedPropagation:!1};let a=await this.collateCountersAndPropagateToAncestors(r);return a.foundChange||console.error(`we found a change in propagating counters for ${e.componentName}, but no change for ancestors!`),{foundChange:!0,finishedPropagation:a.finishedPropagation}}getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.neededToResolve[e];a||(a=this.resolveBlockers.neededToResolve[e]={});let i=a[t];if(i||(i=a[t]={}),n){let e=i;if(i=e[n],i||(i=e[n]={}),r){let e=i;i=e[r],i||(i=e[r]={})}}return i}deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:t,stateVariableBlocked:n,dependencyBlocked:r,blockerType:a,blockerCode:i,deleteFromReciprocal:s=!0}){let o=e;n&&(o+="|"+n,r&&(o+="|"+r));let l=function(e){if(a){if(e[a])if(i){let n=e[a].indexOf(i);if(-1!==n&&e[a].splice(n,1),0===e[a].length&&delete e[a],s){let[e,n,r]=i.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:a,blockerStateVariable:n,blockerDependency:r,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}}else{if(s)for(let n of e[a]){let[e,r,i]=n.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:a,blockerStateVariable:r,blockerDependency:i,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}delete e[a]}}else if(s)for(let n in e)for(let r of e[n]){let[e,a,i]=r.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:n,blockerStateVariable:a,blockerDependency:i,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}}.bind(this),u=this.resolveBlockers.neededToResolve[e];if(u){let i=u[t];if(i)if(n){let e=i[n];if(e)if(r){let t=e[r];t&&(l(t),a&&0!==Object.keys(t).length||delete e[r]),0===Object.keys(e).length&&delete i[n]}else l(e),a&&0!==Object.keys(e).length||delete i[n];0===Object.keys(i).length&&delete u[t]}else l(i),a&&0!==Object.keys(i).length||delete u[t];0===Object.keys(u).length&&delete this.resolveBlockers.neededToResolve[e]}}checkIfHaveNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.neededToResolve[e];if(!a)return!1;let i=a[t];if(!i)return!1;if(n){if(i=i[n],!i)return!1;if(r){if(i=i[r],!i)return!1}}return Object.keys(i).length>0}getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.resolveBlockedBy[e];a||(a=this.resolveBlockers.resolveBlockedBy[e]={});let i=a[t];if(i||(i=a[t]={}),n){let e=i;if(i=e[n],i||(i=e[n]={}),r){let e=i;i=e[r],i||(i=e[r]={})}}return i}deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,typeBlocked:a,codeBlocked:i,deleteFromReciprocal:s=!0}){let o=e;n&&(o+="|"+n,r&&(o+="|"+r));let l=function(e){if(a){if(e[a])if(i){let n=e[a].indexOf(i);if(-1!==n&&e[a].splice(n,1),0===e[a].length&&delete e[a],s){let[e,n,r]=i.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:a,stateVariableBlocked:n,dependencyBlocked:r,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}}else{if(s)for(let n of e[a]){let[e,r,i]=n.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:a,stateVariableBlocked:r,dependencyBlocked:i,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}delete e[a]}}else if(s)for(let n in e)for(let r of e[n]){let[e,a,i]=r.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:n,stateVariableBlocked:a,dependencyBlocked:i,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}}.bind(this),u=this.resolveBlockers.resolveBlockedBy[e];if(u){let i=u[t];if(i)if(n){let e=i[n];if(e)if(r){let t=e[r];t&&(l(t),a&&0!==Object.keys(t).length||delete e[r]),0===Object.keys(e).length&&delete i[n]}else l(e),a&&0!==Object.keys(e).length||delete i[n];0===Object.keys(i).length&&delete u[t]}else l(i),a&&0!==Object.keys(i).length||delete u[t];0===Object.keys(u).length&&delete this.resolveBlockers.resolveBlockedBy[e]}}async addBlocker({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,componentNameBlocked:a,typeBlocked:i,stateVariableBlocked:s,dependencyBlocked:o}){let l=e;n&&(l+="|"+n,r&&(l+="|"+r));let u=a;s&&(u+="|"+s,o&&(u+="|"+o));let c=this.getNeededToResolve({componentName:a,type:i,stateVariable:s,dependency:o}),p=c[t];if(p||(p=c[t]=[]),p.includes(l))return;if(p.push(l),"stateVariable"===i){let e=this._components[a];if(e){let t=e.state[s];if(t.isResolved=!1,t.initiallyResolved){await this.core.markStateVariableAndUpstreamDependentsStale({component:e,varName:s});let t=this.upstreamDependencies[a][s];if(t)for(let e of t)if(this._components[e.upstreamComponentName])for(let t of e.upstreamVariableNames)await this.addBlocker({blockerComponentName:a,blockerType:"stateVariable",blockerStateVariable:s,componentNameBlocked:e.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t})}}}let d=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r}),m=d[i];m||(m=d[i]=[]),m.includes(u)||m.push(u),this.resetCircularResolveBlockerCheckPassed({componentName:a,type:i,stateVariable:s,dependency:o}),this.checkForCircularResolveBlocker({componentName:a,type:i,stateVariable:s,dependency:o})}async processNewlyResolved({componentNameNewlyResolved:e,typeNewlyResolved:t,stateVariableNewlyResolved:n,dependencyNewlyResolved:r,expandComposites:a=!0,force:i=!1,recurseUpstream:s=!1}){if("stateVariable"===t){let t=this._components[e];if(t){t.state[n]&&(t.state[n].isResolved=!0,t.state[n].initiallyResolved=!0)}}else if("componentIdentity"===t){if(!(e in this._components)&&!i)return{success:!1}}else if("recalculateDownstreamComponents"===t){let t;try{t=this.downstreamDependencies[e][n][r]}catch(e){}if(t){let e=await t.recalculateDownstreamComponents({force:i});if(!e.success&&!i)return e;for(let e of t.upstreamVariableNames)this.deleteFromNeededToResolve({componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e,blockerType:"recalculateDownstreamComponents",blockerCode:t.upstreamComponentName+"|"+e+"|"+r});for(let e of t.upstreamVariableNames)await this.resolveIfReady({componentName:t.upstreamComponentName,type:"stateVariable",stateVariable:e,expandComposites:a,force:i,recurseUpstream:s});return{success:!0}}}else if("determineDependencies"===t){let t;try{t=this.downstreamDependencies[e][n][r]}catch(e){}if(t){let o=this.getNeededToResolve({componentName:e,type:"stateVariable",stateVariable:n}),l=!1,u=[];if(o.determineDependencies)for(let t of o.determineDependencies){let[r,a,i]=t.split("|");if(this.checkIfHaveNeededToResolve({componentName:e,type:"determineDependency",stateVariable:n,dependency:i})){l=!0;break}u.push(i)}if(l)return{success:!0};if(!(await this.updateDependencies({componentName:e,stateVariable:n,dependency:r})).success)return{success:!1};for(let n of t.upstreamVariableNames){for(let e of u)this.deleteFromResolveBlockedBy({blockerComponentName:t.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:n,blockerDependency:e});await this.resolveIfReady({componentName:e,type:"stateVariable",stateVariable:n,expandComposites:a,force:i,recurseUpstream:s})}return{success:!0}}}else if("childMatches"===t){let t=this._components[e];if(t&&!t.childrenMatched){if(!(await this.core.deriveChildResultsFromDefiningChildren({parent:t,expandComposites:a,forceExpandComposites:i})).skipping&&!t.childrenMatchedWithPlaceholders&&!i)return{success:!1}}}else{if("expandComposite"!==t)throw Error(`Unrecognized type newly resolved: ${t}`);if(!this._components[e].isExpanded){if(this.core.updateInfo.compositesBeingExpanded.includes(e))return{success:!1};await this.core.expandCompositeComponent(this._components[e])}}let o=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r});o=Object.assign({},o);for(let l in o)for(let u of[...o[l]])if(this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,typeBlocked:l,codeBlocked:u}),s){let[e,t,n]=u.split("|");await this.resolveIfReady({componentName:e,type:l,stateVariable:t,dependency:n,expandComposites:a,force:i,recurseUpstream:s})}return{success:!0}}async resolveStateVariablesIfReady({component:e,stateVariables:t}){let n=e.componentName;t||(await this.resolveIfReady({componentName:n,type:"componentIdentity",expandComposites:!1}),t=Object.keys(e.state));for(let r of t){let t=e.state[r];if(t&&t.determineDependenciesImmediately){let e=this.getNeededToResolve({componentName:n,type:"stateVariable",stateVariable:r}).determineDependencies;if(e)for(let t of e){let[e,n,r]=t.split("|");await this.resolveIfReady({componentName:e,type:"determineDependencies",stateVariable:n,dependency:r,expandComposites:!0})}}await this.resolveIfReady({componentName:n,type:"stateVariable",stateVariable:r,expandComposites:!1})}}async resolveIfReady({componentName:e,type:t,stateVariable:n,dependency:r,expandComposites:a=!0,force:i=!1,recurseUpstream:s=!1}){return this.checkIfHaveNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r})?{success:!1}:(this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:t,stateVariableBlocked:n,dependencyBlocked:r}),await this.processNewlyResolved({componentNameNewlyResolved:e,typeNewlyResolved:t,stateVariableNewlyResolved:n,dependencyNewlyResolved:r,expandComposites:a,force:i,recurseUpstream:s}))}async resolveItem({componentName:e,type:t,stateVariable:n,dependency:r,force:a=!1,recurseUpstream:i=!1,expandComposites:s=!0,numPreviouslyNeeded:o}){let l,u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}),c=u.determineDependencies;if(c&&c.length>0)for(let e of[...c]){let[t,n,r]=e.split("|"),i=await this.resolveItem({componentName:t,type:"determineDependencies",stateVariable:n,dependency:r,force:a,expandComposites:s});if(!i.success)return i}"stateVariable"===t&&this._components[e]&&(l=this._components[e].state[n],l&&(l.currentlyResolving=!0));let p=1/0,d=1/0;for(;(Object.keys(u).length>0||d>0)&&!(Number.isFinite(d)&&d>=p);){d>0&&(u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r})),p=d,d=0;for(let i in u){if("determineDependencies"===i)throw Error(`Shouldn't have determine dependencies blocker after determining dependencies: ${e}, ${t}, ${n}, ${r}`);for(let e of[...u[i]]){let[t,n,r]=e.split("|"),o=await this.resolveItem({componentName:t,type:i,stateVariable:n,dependency:r,expandComposites:s});if(!o.success){if(!a)return o;d++}}}}if(d>0)for(u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r});Object.keys(u).length>0;)for(let i in u){if("determineDependencies"===i)throw Error(`Shouldn't have determine dependencies blocker after determining dependencies: ${e}, ${t}, ${n}, ${r}`);for(let e of[...u[i]]){let[t,n,r]=e.split("|"),o=await this.resolveItem({componentName:t,type:i,stateVariable:n,dependency:r,force:a,expandComposites:s});if(!o.success)return o}}l&&(l.currentlyResolving=!1);let m=await this.resolveIfReady({componentName:e,type:t,stateVariable:n,dependency:r,force:a,recurseUpstream:i,expandComposites:s});if(!m.success){let l=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}),u=Object.keys(l).length;u>0&&(void 0===o||ue.match(t)[1])),r=n.filter((e=>"__"!==e.slice(0,2))).reduce(((e,t)=>e.includes(t)?e:[...e,t]),[]);0===r.length&&(r=[n[0]]),1===r.length?e=r[0]:2===r.length?e=r.join(" and "):(r[r.length-2]=r.slice(r.length-2).join(", and "),r.pop(),e=r.join(", "));let i=[],o=[];for(let e of a){let[t,n]=e.split("|"),r=this._components[t];if(r){this.componentInfoObjects.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})&&!r.attributes.createComponentOfType?.primitive&&("readyToExpandWhenResolved"===n?i.push(t):n===r.constructor.stateVariableToEvaluateAfterReplacements&&o.push(t))}}let l=!1;for(let e of i)if(o.includes(e)){l=!0;break}let u=`Circular dependency involving ${e}.`;throw l&&(u+=" Specifying the type of a composite component may address this circular dependency."),Error(u)}if(a=[...a,s],!this.circularResolveBlockedCheckPassed[s]){this.circularResolveBlockedCheckPassed[s]=!0;let i=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r});for(let e in i)for(let t of i[e]){let[n,r,i]=t.split("|");this.checkForCircularResolveBlocker({componentName:n,type:e,stateVariable:r,dependency:i,previouslyVisited:a})}}}resetCircularResolveBlockerCheckPassed({componentName:e,type:t,stateVariable:n,dependency:r}){let a=e;n&&(a+="|"+n,r&&(a+="|"+r));let i=a+"|"+t;if(this.circularResolveBlockedCheckPassed[i]){delete this.circularResolveBlockedCheckPassed[i];let a=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r});for(let e in a)for(let t of a[e]){let[n,r,a]=t.split("|");this.resetCircularResolveBlockerCheckPassed({componentName:n,type:e,stateVariable:r,dependency:a})}}}get components(){return this._components}set components(e){return null}}class Dependency{constructor({component:e,stateVariable:t,allStateVariablesAffected:n,dependencyName:r,dependencyDefinition:a,dependencyHandler:i}){this.dependencyName=r,this.dependencyHandler=i,this.upstreamComponentName=e.componentName,this.upstreamVariableNames=n,this.definition=Object.assign({},a),this.representativeStateVariable=t,a.doNotProxy&&(this.doNotProxy=!0),a.variablesOptional&&(this.variablesOptional=!0),a.publicStateVariablesOnly&&(this.publicStateVariablesOnly=!0),a.caseInsensitiveVariableMatch&&(this.caseInsensitiveVariableMatch=!0),a.useMappedVariableNames&&(this.useMappedVariableNames=!0),a.propIndex&&(a.propIndex.every(Number.isFinite)?this.propIndex=a.propIndex.map(Math.round):this.propIndex=[]),this.returnSingleVariableValue=!1,this.returnSingleComponent=!1,this.originalDownstreamVariableNames=[]}static dependencyType="_base";downstreamVariableNameIfNoVariables="__identity";static get rendererType(){return this.componentType}get dependencyType(){return this.constructor.dependencyType}setUpParameters(){}async determineDownstreamComponents(){return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async initialize(){this.setUpParameters();let e=await this.determineDownstreamComponents(),t=e.downstreamComponentNames,n=e.downstreamComponentTypes;this.componentIdentitiesChanged=!0;let r=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName];r||(r=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName]={});for(let e of this.upstreamVariableNames)r[e]||(r[e]={}),r[e][this.dependencyName]=this;0!==this.originalDownstreamVariableNames.length||this.originalVariablesByComponent?(this.mappedDownstreamVariableNamesByComponent=[],this.valuesChanged=[]):(delete this.mappedDownstreamVariableNamesByComponent,delete this.upValuesChanged),this.downstreamComponentNames=[],this.downstreamComponentTypes=[];for(let[e,r]of t.entries())await this.addDownstreamComponent({downstreamComponentName:r,downstreamComponentType:n[e],index:e})}async addDownstreamComponent({downstreamComponentName:e,downstreamComponentType:t,index:n}){this.componentIdentitiesChanged=!0,this.downstreamComponentNames.splice(n,0,e),this.downstreamComponentTypes.splice(n,0,t);let r=this.dependencyHandler._components[e];if(r){let t;t=this.originalVariablesByComponent?this.originalDownstreamVariableNamesByComponent[n]:this.originalDownstreamVariableNames,this.caseInsensitiveVariableMatch&&(t=this.dependencyHandler.core.findCaseInsensitiveMatches({stateVariables:t,componentClass:r.constructor})),this.publicStateVariablesOnly&&(t=this.dependencyHandler.core.matchPublicStateVariables({stateVariables:t,componentClass:r.constructor}));let a=this.dependencyHandler.core.substituteAliases({stateVariables:t,componentClass:r.constructor});this.constructor.convertToArraySize&&(a=a.map((function(e){let t=r.state[e];if(t)return t.arraySizeStateVariable?t.arraySizeStateVariable:`__${e}_is_not_an_array`;if(r.arrayEntryPrefixes){let t=Object.keys(r.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let n of t)if(e.substring(0,n.length)===n){let t=r.arrayEntryPrefixes[n],a=r.state[t];if(a.getArrayKeysFromVarName({arrayEntryPrefix:n,varEnding:e.substring(n.length),nDimensions:a.nDimensions}).length>0)return r.state[t].arraySizeStateVariable}}return`__${e}_is_not_an_array`}))),void 0!==this.propIndex&&(a=await this.dependencyHandler.core.arrayEntryNamesFromPropIndex({stateVariables:a,component:r,propIndex:this.propIndex}));let i=a;if(t.length>0||this.originalVariablesByComponent){this.mappedDownstreamVariableNamesByComponent.splice(n,0,a);let t={};for(let e of a)t[e]={changed:!0};this.valuesChanged.splice(n,0,t),this.variablesOptional&&(i=i.filter((e=>e in r.state||this.dependencyHandler.core.checkIfArrayEntry({stateVariable:e,component:r}))));for(let t of i)if(r.state[t]||await this.dependencyHandler.core.createFromArrayEntry({component:r,stateVariable:t}),!r.state[t].isResolved)for(let n of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:t,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:n}),"determineDependencies"===this.dependencyType&&await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:t,componentNameBlocked:this.upstreamComponentName,typeBlocked:"determineDependencies",stateVariableBlocked:n,dependencyBlocked:this.dependencyName})}0===i.length&&(i=[this.downstreamVariableNameIfNoVariables]);let s=this.dependencyHandler.upstreamDependencies[e];s||(s=this.dependencyHandler.upstreamDependencies[e]={});for(let e of i)if(void 0===s[e]&&(s[e]=[]),s[e].push(this),e!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}async removeDownstreamComponent({indexToRemove:e,recordChange:t=!0}){t&&(this.componentIdentitiesChanged=!0);let n=this.downstreamComponentNames[e];if(this.downstreamComponentNames.splice(e,1),this.downstreamComponentTypes.splice(e,1),n in this.dependencyHandler._components){let t;this.mappedDownstreamVariableNamesByComponent?(t=this.mappedDownstreamVariableNamesByComponent[e],this.mappedDownstreamVariableNamesByComponent.splice(e,1),this.valuesChanged.splice(e,1),this.variablesOptional&&t.push(this.downstreamVariableNameIfNoVariables)):t=[this.downstreamVariableNameIfNoVariables];for(let e of t){let t=this.dependencyHandler.upstreamDependencies[n][e];if(t){let r=t.indexOf(this);-1!==r&&(1===t.length?delete this.dependencyHandler.upstreamDependencies[n][e]:t.splice(r,1))}if(e!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}}if(t)for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}async swapDownstreamComponents(e,t){this.componentIdentitiesChanged=!0,[this.downstreamComponentNames[e],this.downstreamComponentNames[t]]=[this.downstreamComponentNames[t],this.downstreamComponentNames[e]],[this.downstreamComponentTypes[e],this.downstreamComponentTypes[t]]=[this.downstreamComponentTypes[t],this.downstreamComponentTypes[e]],(this.originalDownstreamVariableNames.length>0||this.originalVariablesByComponent)&&([this.mappedDownstreamVariableNamesByComponent[e],this.mappedDownstreamVariableNamesByComponent[t]]=[this.mappedDownstreamVariableNamesByComponent[t],this.mappedDownstreamVariableNamesByComponent[e]],[this.valuesChanged[e],this.valuesChanged[t]]=[this.valuesChanged[t],this.valuesChanged[e]]);for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}deleteDependency(){let e=[];if(this.mappedDownstreamVariableNamesByComponent){if(e=this.mappedDownstreamVariableNamesByComponent,this.variablesOptional){let t=[];for(let[n,r]of this.downstreamComponentNames.entries()){let a=[];for(let t of e[n])this.dependencyHandler.components[r].state[t]&&a.push(t);a.length>0?t.push(a):t.push([this.downstreamVariableNameIfNoVariables])}e=t}}else e=Array(this.downstreamComponentNames.length).fill([this.downstreamVariableNameIfNoVariables]);for(let[t,n]of this.downstreamComponentNames.entries())for(let r of e[t]){let e=this.dependencyHandler.upstreamDependencies[n][r];if(e){let t=e.indexOf(this);-1!==t&&(1===e.length?delete this.dependencyHandler.upstreamDependencies[n][r]:e.splice(t,1))}for(let e of this.upstreamVariableNames)this.dependencyHandler.deleteFromNeededToResolve({componentNameBlocked:this.componentName,typeBlocked:"stateVariable",stateVariableBlocked:e,blockerType:"stateVariable",blockerCode:n+"|"+r});if(r!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}this.deleteFromUpdateTriggers();let t=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName];for(let e of this.upstreamVariableNames)delete t[e][this.dependencyName]}deleteFromUpdateTriggers(){}async getValue({verbose:e=!1,skipProxy:t=!1}={}){let n=[],r={},a=[];this.componentIdentitiesChanged&&(r.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1);for(let[e,t]of this.downstreamComponentNames.entries()){let i=this.dependencyHandler._components[t];if(a[e]=!1,i){let s,o={componentType:i.componentType};if(this.skipComponentNames||(o.componentName=t),s=this.originalVariablesByComponent?this.originalDownstreamVariableNamesByComponent[e]:this.originalDownstreamVariableNames,s.length>0){o.stateValues={};let t={},n=!1;for(let[a,l]of s.entries()){let s=this.mappedDownstreamVariableNamesByComponent[e][a],u=this.useMappedVariableNames?s:l;if(!this.variablesOptional||s in i.state){let a=i.state[s];if(!a.deferred)if(o.stateValues[u]=await a.value,this.valuesChanged[e][s].changed&&(r.valuesChanged||(r.valuesChanged={}),r.valuesChanged[e]||(r.valuesChanged[e]={}),r.valuesChanged[e][u]=this.valuesChanged[e][s]),this.valuesChanged[e][s]={},a.usedDefault)t[u]=!0,n=!0;else if(a.isArrayEntry&&1===a.arrayKeys.length){i.state[a.arrayStateVariable].usedDefaultByArrayKey[a.arrayKeys[0]]&&(t[u]=!0,n=!0)}}}n&&(a[e]=t)}n.push(o)}else n.push({componentType:this.downstreamComponentTypes[e]})}if(!e)if(this.returnSingleVariableValue)if(1===n.length){n=n[0],r.valuesChanged&&r.valuesChanged[0]?r.valuesChanged=r.valuesChanged[0]:delete r.valuesChanged,a=a[0];let e=Object.keys(n.stateValues);if(1===e.length){let t=e[0];n=n.stateValues[t],r.valuesChanged&&r.valuesChanged[t]&&(r.valuesChanged=r.valuesChanged[t]),a&&(a=a[t])}else n=null,r={},a=!1}else n=null,r={},a=!1;else this.returnSingleComponent&&(1===n.length?(n=n[0],r.valuesChanged&&r.valuesChanged[0]?r.valuesChanged=r.valuesChanged[0]:delete r.valuesChanged,a=a[0]):(n=null,a=!1));return{value:n,changes:r,usedDefault:a}}checkForCircular(){for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e);for(let e of this.upstreamVariableNames)this.dependencyHandler.checkForCircularDependency({componentName:this.upstreamComponentName,varName:e})}async recalculateDownstreamComponents({force:e=!1}={}){let t=await this.determineDownstreamComponents({force:e}),n=t.downstreamComponentNames,r=n.length!==this.downstreamComponentNames.length||this.downstreamComponentNames.some(((e,t)=>e!=n[t]));if(r){this.componentIdentitiesChanged=!0;let e=0;for(let[t,r]of[...this.downstreamComponentNames].entries())n.includes(r)||(await this.removeDownstreamComponent({indexToRemove:t-e}),e++);for(let[e,r]of n.entries()){let n=this.downstreamComponentNames.indexOf(r);-1!==n?n!==e&&await this.swapDownstreamComponents(n,e):await this.addDownstreamComponent({downstreamComponentName:r,downstreamComponentType:t.downstreamComponentTypes[e],index:e})}}if(this.originalVariablesByComponent)for(let[e,n]of[...this.downstreamComponentNames].entries())(this.mappedDownstreamVariableNamesByComponent[e].length!==this.originalDownstreamVariableNamesByComponent[e].length||this.mappedDownstreamVariableNamesByComponent[e].some(((t,n)=>this.originalDownstreamVariableNamesByComponent[e][n]!==t)))&&(await this.removeDownstreamComponent({indexToRemove:e}),await this.addDownstreamComponent({downstreamComponentName:n,downstreamComponentType:t.downstreamComponentTypes[e],index:e}));return{success:t.success}}}class StateVariableDependency extends Dependency{static dependencyType="stateVariable";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,void 0===this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableName is not defined`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.returnAsComponentObject?this.returnSingleComponent=!0:this.returnSingleVariableValue=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(StateVariableDependency);class MultipleStateVariablesDependency extends Dependency{static dependencyType="multipleStateVariables";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(MultipleStateVariablesDependency);class StateVariableComponentTypeDependency extends StateVariableDependency{static dependencyType="stateVariableComponentType";async getValue({verbose:e=!1}={}){let t=[],n={};if(this.staticValue)t=[this.staticValue];else if(this.componentIdentitiesChanged&&(n.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let e=this.downstreamComponentNames[0],r=this.dependencyHandler.components[e],a={componentName:r.componentName,componentType:r.componentType,stateValues:{}},i=this.originalDownstreamVariableNames[0],s=this.mappedDownstreamVariableNamesByComponent[0][0],o=this.useMappedVariableNames?s:i;if((!this.variablesOptional||s in r.state)&&!r.state[s].deferred){let e=r.state[s];if(await e.value,a.stateValues[o]=e.componentType,e.isArray&&e.wrappingComponents?.length>0){let t=e.wrappingComponents[e.wrappingComponents.length-1][0];"object"==typeof t&&(t=t.componentType),a.stateValues[o]=t}this.valuesChanged[0][s].changed&&(n.valuesChanged||(n.valuesChanged={}),n.valuesChanged[0]||(n.valuesChanged[0]={}),n.valuesChanged[0][o]=this.valuesChanged[0][s]),this.valuesChanged[0][s]={};let t=e.shadowingInstructions?.hasVariableComponentType;if(!t&&e.isArrayEntry){t=r.state[e.arrayStateVariable].shadowingInstructions?.hasVariableComponentType}t||(this.staticValue=a,await this.removeDownstreamComponent({indexToRemove:0,recordChange:!1}))}t=[a]}if(!e)if(this.returnSingleVariableValue)if(1===t.length){t=t[0];let e=Object.keys(t.stateValues);n.valuesChanged&&n.valuesChanged[0]&&n.valuesChanged[0][0]&&(n.valuesChanged=n.valuesChanged[0][0]),t=1===e.length?t.stateValues[e[0]]:null}else t=null;else this.returnSingleComponent&&(1===t.length?(t=t[0],n.valuesChanged&&n.valuesChanged[0]&&(n.valuesChanged=n.valuesChanged[0])):t=null);return{value:t,changes:n,usedDefault:!1}}}dependencyTypeArray.push(StateVariableComponentTypeDependency);class StateVariableArraySizeDependency extends StateVariableDependency{static dependencyType="stateVariableArraySize";static convertToArraySize=!0}dependencyTypeArray.push(StateVariableArraySizeDependency);class RecursiveDependencyValuesDependency extends Dependency{static dependencyType="recursiveDependencyValues";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,void 0===this.definition.variableNames)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames is not defined`);this.startingVariableNames=this.definition.variableNames,this.originalVariablesByComponent=!0,this.includeImmediateValueWithValue=this.definition.includeImmediateValueWithValue,this.includeRawValueWithImmediateValue=this.definition.includeRawValueWithImmediateValue,this.includeOnlyEssentialValues=this.definition.includeOnlyEssentialValues,this.variablesOptional=!0}async determineDownstreamComponents({force:e=!1}={}){this.missingComponents=[],this.originalDownstreamVariableNamesByComponent=[];let t=await this.getRecursiveDependencyVariables({componentName:this.componentName,variableNames:this.startingVariableNames,force:e});if(!t.success)return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=[],r=[];for(let e in t.components)if(this.includeOnlyEssentialValues){let a=[],i=this.dependencyHandler._components[e];for(let n of t.components[e].variableNames)(i.state[n]?.hasEssential||i.state[n]?.isArrayEntry&&i.state[i.state[n].arrayStateVariable].hasEssential)&&a.push(n);a.length>0&&(n.push(e),r.push(t.components[e].componentType),this.originalDownstreamVariableNamesByComponent.push(a))}else n.push(e),r.push(t.components[e].componentType),this.originalDownstreamVariableNamesByComponent.push(t.components[e].variableNames);return{success:!0,downstreamComponentNames:n,downstreamComponentTypes:r}}async getRecursiveDependencyVariables({componentName:e,variableNames:t,force:n,components:r={}}){let a=this.dependencyHandler._components[e];if(!a){if(!this.missingComponents.includes(e)){let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];t||(t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]=[]),t.includes(this)||t.push(this)}for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});return{success:!1}}this.includeImmediateValueWithValue&&t.includes("value")&&!t.includes("immediateValue")&&"immediateValue"in a.state&&(t=[...t,"immediateValue"]),this.includeRawValueWithImmediateValue&&t.includes("immediateValue")&&!t.includes("rawRendererValue")&&"rawRendererValue"in a.state&&(t=[...t,"rawRendererValue"]);let i=r[e];i||(i=r[e]={componentName:e,componentType:a.componentType,variableNames:[]});let s=this.dependencyHandler.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e];s||(s=this.dependencyHandler.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e]={});for(let o of t)if(!i.variableNames.includes(o)){i.variableNames.push(o);let t=s[o];t||(t=s[o]=[]),t.includes(this)||t.push(this);let l=a.state[o];if(l){if(!l.isResolved){if(!n){for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:o,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});return{success:!1}}await l.value}let t=this.dependencyHandler.downstreamDependencies[a.componentName][o];for(let e in t){let a=t[e];for(let[e,t]of a.downstreamComponentNames.entries()){let i=[];if((a.originalDownstreamVariableNames.length>0||a.originalVariablesByComponent)&&(i=a.mappedDownstreamVariableNamesByComponent[e]),!(await this.getRecursiveDependencyVariables({componentName:t,variableNames:i,force:n,components:r})).success)return{success:!1}}}}}return{success:!0,components:r}}async getValue(){let e;this.gettingValue=!0,this.varsWithUpdatedDeps={};let t={},n=!0,r={};for(;n;){if(n=!1,e=await super.getValue(),e.changes.valuesChanged)if(r.valuesChanged)for(let t in e.changes.valuesChanged){let n=e.changes.valuesChanged[t];if(r.valuesChanged[t])for(let e in n)r.valuesChanged[t][e]=n[e];else r.valuesChanged[t]=n}else r.valuesChanged=e.changes.valuesChanged;for(let e in this.varsWithUpdatedDeps){let r=t[e];r||(r=t[e]=[]);for(let t of this.varsWithUpdatedDeps[e])r.includes(t)||(r.push(t),n=!0)}n&&await this.recalculateDownstreamComponents()}return this.gettingValue=!1,e.changes=r,e}deleteFromUpdateTriggers(){for(let e of this.missingComponents){let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}}dependencyTypeArray.push(RecursiveDependencyValuesDependency);class ComponentIdentityDependency extends Dependency{static dependencyType="componentIdentity";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ComponentIdentityDependency);class AttributeComponentDependency extends Dependency{static dependencyType="attributeComponent";setUpParameters(){if(this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.attributeName=this.definition.attributeName,this.returnSingleComponent=!0,this.shadowDepth=0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=e.attributes[this.attributeName];if(this.shadowDepth=0,t?.component)return{success:!0,downstreamComponentNames:[t.component.componentName],downstreamComponentTypes:[t.component.componentType]};let n=e;for(;n.shadows;){let e=n.shadows,r=n.shadows.propVariable;if(n=this.dependencyHandler._components[e.componentName],!n)break;if(r){if(!n.state[r]?.shadowingInstructions?.attributesToShadow?.includes(this.attributeName)&&!n.constructor.createAttributesObject()[this.attributeName]?.propagateToProps)break}else{let t=this.dependencyHandler._components[e.compositeName];if("sourceAttributesToIgnoreRecursively"in t.state){if((await t.stateValues.sourceAttributesToIgnoreRecursively).includes(this.attributeName))break}if(e.firstLevelReplacement&&"sourceAttributesToIgnore"in t.state){if((await t.stateValues.sourceAttributesToIgnore).includes(this.attributeName))break}}if(this.shadowDepth++,t=n.attributes[this.attributeName],t?.component)return{success:!0,downstreamComponentNames:[t.component.componentName],downstreamComponentTypes:[t.component.componentType]}}return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0});return t.value&&(t.value.shadowDepth=this.shadowDepth),t}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AttributeComponentDependency);class ChildDependency extends Dependency{static dependencyType="child";setUpParameters(){if(this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];if(this.childGroups=this.definition.childGroups,!Array.isArray(this.childGroups))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: childGroups must be an array`);void 0!==this.definition.childIndices&&(this.childIndices=this.definition.childIndices.map((e=>Number(e)))),this.skipComponentNames=this.definition.skipComponentNames,this.skipPlaceholders=this.definition.skipPlaceholders,this.proceedIfAllChildrenNotMatched=this.definition.proceedIfAllChildrenNotMatched}async determineDownstreamComponents(){this.downstreamPrimitives?this.previousDownstreamPrimitives=[...this.downstreamPrimitives]:this.previousDownstreamPrimitives=[],this.downstreamPrimitives=[];let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];t||(t=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName]=[]),t.includes(this)||t.push(this);let n=e.returnMatchedChildIndices(this.childGroups);if(void 0===n)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: childGroups ${this.childGroups} does not exist.`);if(this.childIndices&&(n=n.filter(((e,t)=>this.childIndices.includes(t)))),!e.childrenMatched&&!this.proceedIfAllChildrenNotMatched){let t=!1;if(e.childrenMatchedWithPlaceholders&&(this.skipPlaceholders&&(n=n.filter((t=>!e.placeholderActiveChildrenIndices.includes(t)))),t=!(!this.skipComponentNames||0!==this.originalDownstreamVariableNames.length)||n.every((t=>!e.placeholderActiveChildrenIndices.includes(t)))),!t){let t=e.unexpandedCompositesNotReady.length>0;if(!t&&e.unexpandedCompositesReady.length>0){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(t){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});let t=[],r=[];for(let a of e.unexpandedCompositesNotReady){if(e.childrenMatchedWithPlaceholders){if(e.placeholderActiveChildrenIndicesByComposite[a].every((e=>!n.includes(e))))continue}this.dependencyHandler._components[a].attributes.createComponentOfType?.primitive?t.push(a):r.push(a)}let a=r;0===a.length&&(a=t);for(let e of a)for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.upstreamComponentName,typeBlocked:"childMatches",stateVariableBlocked:t});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}}}let r=n.map((t=>e.activeChildren[t]));if(this.compositeReplacementRange=[],e.compositeReplacementActiveRange&&r.length>0){let t=0;for(;t=r){let e=t,i=t;for(;a.lastInd>r&&t=r);)i=t;if(this.compositeReplacementRange.push({compositeName:a.compositeName,target:a.target,firstInd:e,lastInd:i}),t++,t===n.length)break;r=n[t]}t++}}this.shadowDepthByChild=[];for(let t of r){let n=0,r=t,a=e;for(;r?.shadows&&r.shadows.compositeName===a?.shadows?.compositeName;)n++,a=this.dependencyHandler._components[a.shadows.componentName],r=this.dependencyHandler._components[r.shadows.componentName];this.shadowDepthByChild.push(n)}this.activeChildrenIndices=n;let a=[],i=[];for(let[e,t]of r.entries())"object"==typeof t?(this.downstreamPrimitives.push(null),a.push(t.componentName?t.componentName:`__placeholder_${e}`),i.push(t.componentType)):this.downstreamPrimitives.push(t);return{success:!0,downstreamComponentNames:a,downstreamComponentTypes:i}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0}),n=[],r=0;for(let[e,a]of this.downstreamPrimitives.entries())if(null===a){t.value[r].shadowDepth=this.shadowDepthByChild[e],n.push(t.value[r]),r++}else n.push(a);return n.compositeReplacementRange=this.compositeReplacementRange,t.value=n,(this.downstreamPrimitives.length!==this.previousDownstreamPrimitives.length||this.downstreamPrimitives.some(((e,t)=>e!==this.previousDownstreamPrimitives[t])))&&(t.changes.componentIdentitiesChanged=!0,this.previousDownstreamPrimitives=[...this.downstreamPrimitives]),t}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ChildDependency);class DescendantDependency extends Dependency{static dependencyType="descendant";setUpParameters(){if(this.definition.ancestorName?(this.ancestorName=this.definition.ancestorName,this.specifiedComponentName=this.ancestorName):this.ancestorName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.componentTypes=this.definition.componentTypes,this.recurseToMatchedChildren=this.definition.recurseToMatchedChildren,this.useReplacementsForComposites=this.definition.useReplacementsForComposites,this.includeNonActiveChildren=this.definition.includeNonActiveChildren,this.includeAttributeChildren=this.definition.includeAttributeChildren,this.skipOverAdapters=this.definition.skipOverAdapters,this.ignoreReplacementsOfMatchedComposites=this.definition.ignoreReplacementsOfMatchedComposites,this.ignoreReplacementsOfEncounteredComposites=this.definition.ignoreReplacementsOfEncounteredComposites,null!==this.definition.componentIndex&&void 0!==this.definition.componentIndex&&(Number.isInteger(this.definition.componentIndex)?this.componentIndex=this.definition.componentIndex:this.componentIndex=NaN)}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.ancestorName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.ancestorName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName];t||(t=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName]=[]),t.includes(this)||t.push(this);let n=this.gatherUnexpandedComposites(e);if(n.haveCompositesNotReady||n.haveUnexpandedCompositeReady){for(let e of this.upstreamVariableNames){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let t in n.unexpandedCompositesReadyByParentName)await this.dependencyHandler.addBlocker({blockerComponentName:t,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName});for(let t in n.unexpandedCompositesNotReadyByParentName)await this.dependencyHandler.addBlocker({blockerComponentName:t,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName})}return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let r=gatherDescendants({ancestor:e,descendantTypes:this.componentTypes,recurseToMatchedChildren:this.recurseToMatchedChildren,useReplacementsForComposites:this.useReplacementsForComposites,includeNonActiveChildren:this.includeNonActiveChildren,skipOverAdapters:this.skipOverAdapters,ignoreReplacementsOfMatchedComposites:this.ignoreReplacementsOfMatchedComposites,ignoreReplacementsOfEncounteredComposites:this.ignoreReplacementsOfEncounteredComposites,componentInfoObjects:this.dependencyHandler.componentInfoObjects});if(void 0!==this.componentIndex){let e=r[this.componentIndex-1];r=e?[e]:[]}return{success:!0,downstreamComponentNames:r.map((e=>e.componentName)),downstreamComponentTypes:r.map((e=>e.componentType))}}gatherUnexpandedComposites(e){let t={},n={},r=!1,a=!1,i=this.skipComponentNames&&0===this.originalDownstreamVariableNames.length;if(!e.childrenMatched)if(e.childrenMatchedWithPlaceholders){if(e.unexpandedCompositesReady.length>0){let n=this.unexpandedCompositesAdjustedForPlacedholders(e.unexpandedCompositesReady,i);n.length>0&&(t[e.componentName]=n,r=!0)}if(e.unexpandedCompositesNotReady.length>0){let t=this.unexpandedCompositesAdjustedForPlacedholders(e.unexpandedCompositesNotReady,i);t.length>0&&(n[e.componentName]=t,a=!0)}}else e.unexpandedCompositesReady.length>0&&(t[e.componentName]=e.unexpandedCompositesReady,r=!0),e.unexpandedCompositesNotReady.length>0&&(n[e.componentName]=e.unexpandedCompositesNotReady,a=!0);for(let i in e.allChildren){let s=e.allChildren[i].component;if("object"==typeof s){let e=this.gatherUnexpandedComposites(s);e.haveUnexpandedCompositeReady&&(Object.assign(t,e.unexpandedCompositesReadyByParentName),r=!0),e.haveCompositesNotReady&&(Object.assign(n,e.unexpandedCompositesNotReadyByParentName),a=!0)}}return{unexpandedCompositesReadyByParentName:t,haveUnexpandedCompositeReady:r,unexpandedCompositesNotReadyByParentName:n,haveCompositesNotReady:a}}unexpandedCompositesAdjustedForPlacedholders(e,t){let n=[];for(let r of e){let e=this.dependencyHandler._components[r];if(e.attributes.createComponentOfType){let a=this.dependencyHandler.componentInfoObjects.componentTypeLowerCaseMapping[e.attributes.createComponentOfType.primitive.toLowerCase()],i=this.componentTypes.some((e=>this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:a,baseComponentType:e})));i&&t||n.push(r)}else n.push(r)}return n}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(DescendantDependency);class ParentDependency extends Dependency{static dependencyType="parentStateVariable";setUpParameters(){if(this.definition.childName?(this.childName=this.definition.childName,this.specifiedComponentName=this.childName):this.childName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.parentComponentType&&(this.parentComponentType=this.definition.parentComponentType),this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.childName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.childName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(this.parentComponentType&&!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.parentComponentType}))return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];return n||(n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}dependencyTypeArray.push(ParentDependency);class ParentIdentityDependency extends Dependency{static dependencyType="parentIdentity";setUpParameters(){this.definition.childName?(this.childName=this.definition.childName,this.specifiedComponentName=this.childName):this.childName=this.upstreamComponentName,this.definition.parentComponentType&&(this.parentComponentType=this.definition.parentComponentType),this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.childName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.childName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(this.parentComponentType&&!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.parentComponentType}))return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];return n||(n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}dependencyTypeArray.push(ParentIdentityDependency);class AncestorDependency extends Dependency{static dependencyType="ancestor";setUpParameters(){if(this.definition.descendantName?(this.descendantName=this.definition.descendantName,this.specifiedComponentName=this.descendantName):this.descendantName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.definition.componentType&&(this.componentType=this.definition.componentType)}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.descendantName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.descendantName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.descendantName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.descendantName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!(this.dependencyHandler.core.documentName in this.dependencyHandler._components)){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e}),await this.dependencyHandler.addBlocker({blockerComponentName:this.dependencyHandler.core.documentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.findMatchingAncestor(e);if(t.missingComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[t.missingComponentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[t.missingComponentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:t.missingComponentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}for(let e of t.ancestorsExamined){let t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e];t||(t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e]=[]),t.includes(this)||t.push(this)}return this.ancestorResults=t,t.ancestorFound?{success:!0,downstreamComponentNames:[t.ancestorFound.componentName],downstreamComponentTypes:[t.ancestorFound.componentClass.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}findMatchingAncestor(e){let t=[];if(this.componentType){for(let n of e.ancestors){let e=this.dependencyHandler._components[n.componentName];if(!e)return{missingComponentName:n.componentName};if(t.push(n.componentName),this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:this.componentType}))return{ancestorsExamined:t,ancestorFound:n}}return{ancestorsExamined:t}}if(0===this.originalDownstreamVariableNames.length)return console.warn(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must specify componentType or variableNames to find ancestor`),{ancestorsExamined:t};let n=this.originalDownstreamVariableNames;for(let r of e.ancestors){let e=this.dependencyHandler._components[r.componentName];if(!e)return{missingComponentName:r.componentName};t.push(r.componentName);let a=!0;for(let t of n)if(!(t in e.state)&&!this.dependencyHandler.core.checkIfArrayEntry({stateVariable:t,component:e})){a=!1;break}if(a)return{ancestorsExamined:t,ancestorFound:r}}return{ancestorsExamined:t}}deleteFromUpdateTriggers(){for(let e of this.ancestorResults.ancestorsExamined){let t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}if(this.ancestorResults&&this.ancestorResults.missingComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorResults.missingComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AncestorDependency);class ReplacementDependency extends Dependency{static dependencyType="replacement";setUpParameters(){if(this.definition.compositeName?(this.compositeName=this.definition.compositeName,this.specifiedComponentName=this.compositeName):this.compositeName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.recursive=this.definition.recursive,this.recurseNonStandardComposites=this.definition.recurseNonStandardComposites,null!==this.definition.componentIndex&&void 0!==this.definition.componentIndex&&(Number.isInteger(this.definition.componentIndex)?this.componentIndex=this.definition.componentIndex:this.componentIndex=NaN),this.definition.targetSubnames&&(this.targetSubnames=this.definition.targetSubnames),this.definition.targetSubnamesComponentIndex&&(this.definition.targetSubnamesComponentIndex.every(Number.isInteger)?this.targetSubnamesComponentIndex=this.definition.targetSubnamesComponentIndex:this.targetSubnamesComponentIndex=[NaN]),this.includeWithheldReplacements=this.definition.includeWithheldReplacements,this.expandReplacements=!0}async determineDownstreamComponents(){this.replacementPrimitives?this.previousReplacementPrimitives=[...this.replacementPrimitives]:this.previousReplacementPrimitives=[],this.replacementPrimitives=[];let e=this.dependencyHandler._components[this.compositeName];if(!e){let a=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.compositeName];a||(a=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.compositeName]=[]),a.includes(this)||a.push(this);for(let i of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:i,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:i,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:i});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.isExpanded){for(let s of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:s,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:s}),await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"expandComposite",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:s,dependencyBlocked:this.dependencyName});return e.state.readyToExpandWhenResolved.isResolved||await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.compositeName,typeBlocked:"expandComposite"}),{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}this.compositesFound=[this.compositeName];let t=e.replacements;if(!this.includeWithheldReplacements&&e.replacementsToWithhold>0&&(t=t.slice(0,-e.replacementsToWithhold)),this.recursive){let o=this.dependencyHandler.core.recursivelyReplaceCompositesWithReplacements({replacements:t,recurseNonStandardComposites:this.recurseNonStandardComposites,includeWithheldReplacements:this.includeWithheldReplacements});if(o.unexpandedCompositesNotReady.length>0||o.unexpandedCompositesReady.length>0){for(let l of this.upstreamVariableNames){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:l,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:l});for(let u of[...o.unexpandedCompositesReady,...o.unexpandedCompositesNotReady])await this.dependencyHandler.addBlocker({blockerComponentName:u,blockerType:"expandComposite",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:l,dependencyBlocked:this.dependencyName})}for(let c of o.unexpandedCompositesNotReady)await this.dependencyHandler.addBlocker({blockerComponentName:c,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:c,typeBlocked:"expandComposite"});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}t=o.newReplacements,this.compositesFound.push(...o.compositesFound)}for(let p of this.compositesFound){let d=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[p];d||(d=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[p]=[]),d.includes(this)||d.push(this)}if(void 0!==this.componentIndex){let m=t[this.componentIndex-1];t=m?[m]:[]}if(this.targetSubnames){function h({components:e,subNames:t,subNamesComponentIndex:n,dep:r}){if(0===t.length)return e;let a=t.slice(1),i=[];for(let s of e){let e=s.componentName+"/"+t[0],o=r.dependencyHandler._components[e];if(o)r.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:o.componentType,baseComponentType:"_composite"})?console.warn("Have not yet implemented recursing subnames to multiple levels of composites"):0===a.length&&(n?.length,1)&&i.push(o);else{let t=r.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];t||(t=r.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]=[]),t.includes(r)||t.push(r)}}return i}t=h({components:t,subNames:this.targetSubnames,subNamesComponentIndex:this.targetSubnamesComponentIndex,dep:this})}let n=[],r=[];for(let f of t)"object"==typeof f?(this.replacementPrimitives.push(null),n.push(f.componentName),r.push(f.componentType)):this.replacementPrimitives.push(f);return{success:!0,downstreamComponentNames:n,downstreamComponentTypes:r}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0}),n=[],r=0;for(let e of this.replacementPrimitives)null===e?(n.push(t.value[r]),r++):n.push(e);return t.value=n,(this.replacementPrimitives.length!==this.previousReplacementPrimitives.length||this.replacementPrimitives.some(((e,t)=>e!==this.previousReplacementPrimitives[t])))&&(t.changes.componentIdentitiesChanged=!0,this.previousReplacementPrimitives=[...this.replacementPrimitives]),t}deleteFromUpdateTriggers(){if(this.compositesFound)for(let e of this.compositesFound){let t=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ReplacementDependency);class SourceCompositeStateVariableDependency extends Dependency{static dependencyType="sourceCompositeStateVariable";setUpParameters(){if(this.definition.replacementName?(this.replacementName=this.definition.replacementName,this.specifiedComponentName=this.replacementName):this.replacementName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.compositeComponentType&&(this.compositeComponentType=this.definition.compositeComponentType),this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.replacementName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.replacementName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.replacementOf;if(this.compositeComponentType)for(;!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.compositeComponentType});){if(!t.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};t=t.replacementOf}return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SourceCompositeStateVariableDependency);class SourceCompositeIdentityDependency extends Dependency{static dependencyType="sourceCompositeIdentity";setUpParameters(){this.definition.replacementName?(this.replacementName=this.definition.replacementName,this.specifiedComponentName=this.replacementName):this.replacementName=this.upstreamComponentName,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.replacementName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.replacementName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.replacementOf;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SourceCompositeIdentityDependency);class ShadowSourceDependency extends Dependency{static dependencyType="shadowSource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.shadows)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.shadows.componentName,n=this.dependencyHandler._components[t];return n?{success:!0,downstreamComponentNames:[n.componentName],downstreamComponentTypes:[n.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ShadowSourceDependency);class UnlinkedCopySourceDependency extends Dependency{static dependencyType="unlinkedCopySource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.unlinkedCopySource)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.unlinkedCopySource,n=this.dependencyHandler._components[t];return n?{success:!0,downstreamComponentNames:[n.componentName],downstreamComponentTypes:[n.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(UnlinkedCopySourceDependency);class PrimaryShadowDependency extends Dependency{static dependencyType="primaryShadow";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.primaryShadowDependencies[this.componentName];if(t||(t=this.dependencyHandler.updateTriggers.primaryShadowDependencies[this.componentName]=[]),t.includes(this)||t.push(this),!e.primaryShadow)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=e.primaryShadow,r=this.dependencyHandler._components[n];return r?{success:!0,downstreamComponentNames:[r.componentName],downstreamComponentTypes:[r.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(PrimaryShadowDependency);class AdapterSourceStateVariableDependency extends Dependency{static dependencyType="adapterSourceStateVariable";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.adaptedFrom)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.adaptedFrom;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AdapterSourceStateVariableDependency);class AdapterSourceDependency extends Dependency{static dependencyType="adapterSource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.adaptedFrom)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.adaptedFrom;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AdapterSourceDependency);class CountAmongSiblingsDependency extends Dependency{static dependencyType="countAmongSiblingsOfSameType";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return console.warn(`component ${this.componentName} does not have a parent for state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}.`),{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let n=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(n||(n=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),!t.childrenMatched){if(!t.childrenMatchedWithPlaceholders){let e=t.unexpandedCompositesNotReady.length>0;if(!e&&t.unexpandedCompositesReady.length>0){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(e){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let e of t.unexpandedCompositesNotReady)for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.upstreamComponentName,typeBlocked:"childMatches",stateVariableBlocked:t});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}}}return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}async getValue(){let e=this.dependencyHandler.components[this.upstreamComponentName].componentType,t=this.dependencyHandler.components[this.parentName].activeChildren.filter((t=>t.componentType===e)),n=t.map((e=>e.componentName)).indexOf(this.upstreamComponentName)+1;if(this.parentName===this.dependencyHandler.core.documentName){let t=this.dependencyHandler.core.previousComponentTypeCounts[e];t&&(n+=t)}return{value:n,changes:{}}}}dependencyTypeArray.push(CountAmongSiblingsDependency);class AttributeTargetComponentNamesDependency extends StateVariableDependency{static dependencyType="attributeTargetComponentNames";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.parentName?(this.componentName=this.definition.parentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let t=this.dependencyHandler.components[this.componentName];t&&(e=t.attributes[this.attributeName],e=e?e.targetComponentNames:null)}return{value:e,changes:t}}}dependencyTypeArray.push(AttributeTargetComponentNamesDependency);class TargetComponentDependency extends Dependency{static dependencyType="targetComponent";setUpParameters(){let e=this.dependencyHandler._components[this.upstreamComponentName];if(this.target=e.doenetAttributes.target,this.target&&(this.targetComponentName=this.specifiedComponentName=e.doenetAttributes.targetComponentName),this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0}async determineDownstreamComponents(){if(!this.target)return{downstreamComponentNames:[],downstreamComponentTypes:[]};let e=this.dependencyHandler._components[this.targetComponentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.targetComponentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.targetComponentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.targetComponentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.targetComponentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}dependencyTypeArray.push(TargetComponentDependency);class ValueDependency extends Dependency{static dependencyType="value";setUpParameters(){this.value=this.definition.value}async getValue(){return{value:this.value,changes:{}}}}dependencyTypeArray.push(ValueDependency);class FlagDependency extends ValueDependency{static dependencyType="flag";setUpParameters(){this.flagName=this.definition.flagName,this.value=this.dependencyHandler.core.flags[this.flagName]}}dependencyTypeArray.push(FlagDependency);class DoenetAttributeDependency extends StateVariableDependency{static dependencyType="doenetAttribute";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){e=this.dependencyHandler.components[this.downstreamComponentNames[0]].doenetAttributes[this.attributeName]}return{value:e,changes:t}}}dependencyTypeArray.push(DoenetAttributeDependency);class AttributePrimitiveDependency extends StateVariableDependency{static dependencyType="attributePrimitive";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.parentName?(this.componentName=this.definition.parentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let t=this.dependencyHandler.components[this.componentName];t&&(e=t.attributes[this.attributeName],e=e?e.primitive:null)}return{value:e,changes:t}}}dependencyTypeArray.push(AttributePrimitiveDependency);class SerializedChildrenDependency extends Dependency{static dependencyType="serializedChildren";setUpParameters(){this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler._components[this.parentName].serializedChildren,changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SerializedChildrenDependency);class VariantsDependency extends Dependency{static dependencyType="variants";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler._components[this.componentName].variants,changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(VariantsDependency);class CounterDependency extends Dependency{static dependencyType="counter";setUpParameters(){this.counterName=this.definition.counterName,this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName],t=e.counters[this.counterName];return t||(t=e.counters[this.counterName]={dependencies:[],componentList:[],value:null}),t.dependencies.includes(this)||t.dependencies.push(this),await this.dependencyHandler.collateCountersAndPropagateToAncestors(e),{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async getValue(){return{value:this.dependencyHandler._components[this.componentName].counters[this.counterName].value,changes:{}}}}dependencyTypeArray.push(CounterDependency);class DetermineDependenciesDependency extends Dependency{static dependencyType="determineDependencies";setUpParameters(){if(this.recalculateDependencies=!0,this.definition.componentName?this.componentName=this.definition.componentName:this.componentName=this.upstreamComponentName,void 0===this.definition.variableNames)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames is not defined`);this.originalDownstreamVariableNames=this.definition.variableNames,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}async markStale(){let e=this.dependencyHandler._components[this.upstreamComponentName];for(let t of this.upstreamVariableNames)if(!(e&&e.state[t]&&e.state[t].currentlyResolving)){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});for(let e in this.dependencyHandler.downstreamDependencies[this.upstreamComponentName][t]){"determineDependencies"!==this.dependencyHandler.downstreamDependencies[this.upstreamComponentName][t][e].dependencyType&&await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:e})}}}}dependencyTypeArray.push(DetermineDependenciesDependency);class FileDependency extends Dependency{static dependencyType="file";setUpParameters(){this.cid=this.definition.cid,this.uri=this.definition.uri,this.fileType=this.definition.fileType}async getValue(){let e;if(this.cid){if("csv"!==this.fileType.toLowerCase())return{value:null,changes:{}};return e="csv",{value:await retrieveTextFileForCid(this.cid,e),changes:{}}}{let e=await fetch(this.uri);if(e.ok){return{value:await e.text(),changes:{}}}return{value:null,changes:{}}}}}dependencyTypeArray.push(FileDependency);var appliedFunctionSymbolsDefault=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","min","max","mean","median","floor","ceil","round","sum","prod","variance","std","count","mod","re","im","det","trace","nPr","nCr"],appliedFunctionSymbolsDefaultLatex=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","min","max","mean","median","floor","ceil","round","sum","prod","variance","std","count","mod","Re","Im","det","trace","nPr","nCr"];let allowedLatexSymbols=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","varnothing","emptyset","angle","circ","$","%"];var textToAst$1=new me$3.converters.textToAstObj({appliedFunctionSymbols:appliedFunctionSymbolsDefault});function getFromText({functionSymbols:e,appliedFunctionSymbols:t=appliedFunctionSymbolsDefault,splitSymbols:n=!0,parseScientificNotation:r=!1}){return a=>me$3.fromAst(new me$3.converters.textToAstObj({appliedFunctionSymbols:t,functionSymbols:e,splitSymbols:n,parseScientificNotation:r}).convert(a))}var latexToAst=new me$3.converters.latexToAstObj({appliedFunctionSymbols:appliedFunctionSymbolsDefaultLatex,allowedLatexSymbols:allowedLatexSymbols});function getFromLatex({functionSymbols:e,appliedFunctionSymbols:t=appliedFunctionSymbolsDefaultLatex,splitSymbols:n=!0,parseScientificNotation:r=!1}){return n?n=>me$3.fromAst(new me$3.converters.latexToAstObj({appliedFunctionSymbols:t,functionSymbols:e,allowedLatexSymbols:allowedLatexSymbols,parseScientificNotation:r}).convert(wrapWordIncludingNumberWithVar(n,r))):n=>me$3.fromAst(new me$3.converters.latexToAstObj({appliedFunctionSymbols:t,functionSymbols:e,allowedLatexSymbols:allowedLatexSymbols,parseScientificNotation:r}).convert(wrapWordWithVar(n,r)))}function normalizeMathExpression({value:e,simplify:t,expand:n=!1,createVectors:r=!1,createIntervals:a=!1}){return r&&(e=e.tuples_to_vectors()),a&&(e=e.to_intervals()),n&&(e=e.expand()),"full"===t?e.simplify():"numbers"===t?e.evaluate_numbers():"numberspreserveorder"===t?e.evaluate_numbers({skip_ordering:!0}):e}function findFiniteNumericalValue(e){if(void 0!==e)return Number.isFinite(e)||void 0!==e.evaluate_to_constant&&(e=e.evaluate_to_constant(),Number.isFinite(e))?e:null}function convertValueToMathExpression(e){return e instanceof me$3.class?e:"number"==typeof e||"string"==typeof e||Array.isArray(e)?me$3.fromAst(e):me$3.fromAst("_")}function returnNVariables(e,t){if(!Number.isInteger(e)||e<1)return[];let n=t.length;if(0===n){if(1===e)return[me$3.fromAst("x")];if(2===e)return[me$3.fromAst("x"),me$3.fromAst("y")];if(3===e)return[me$3.fromAst("x"),me$3.fromAst("y"),me$3.fromAst("z")];{let t=[];for(let n=1;n<=e;n++)t.push(me$3.fromAst(textToAst$1.convert(`x_${n}`)));return t}}if(new Set(t.map((e=>e.toString()))).sizee.toString()))],a=[...t];for(let t=n+1;t<=e;t++){let n;n=1==t?e>3?["x_1"]:["x"]:2==t?e>3?["x_2","y_2"]:["y","x_2"]:3==t?e>3?["x_3","y_3","z_3"]:["z","x_3","z_3"]:["x","y","z","u","v","w","X","Y","Z"].map((e=>`${e}_${t}`));let i=!1;for(let e of n)if(!r.includes(e)){a.push(me$3.fromAst(textToAst$1.convert(e))),r.push(e),i=!0;break}if(!i){let e=n[0];a.push(me$3.fromAst(textToAst$1.convert(e))),r.push(e),console.warn("Variables added were not unique")}}return a}async function preprocessMathInverseDefinition({desiredValue:e,stateValues:t,variableName:n="value",arrayKey:r,workspace:a}){if(!vectorOperators.includes(e.tree[0])||!e.tree.includes())return{desiredValue:e};let i,s=n+"Ast";if(void 0!==r&&(s+=`_${r}`),a[s])i=a[s].slice(0,e.tree.length);else{let a=await t[n];a&&void 0!==r&&(a=a[r]),a&&vectorOperators.includes(a.tree[0])&&(i=a.tree.slice(0,e.tree.length))}if(i){let t=[],n=!1;for(let[r,a]of e.tree.entries())void 0===a?(n=!0,t.push(r)):i[r]=a;return e=me$3.fromAst(i),a[s]=i,n?{desiredValue:e,vectorComponentsNotAffected:t}:{desiredValue:e}}{let t=[];for(let n of e.tree.slice(1))void 0===n?t.push("_"):t.push(n);return{desiredValue:e=me$3.fromAst([e.tree[0],...t])}}}function normalizeLatexString(e,{unionFromU:t=!1}={}){let n=[["α","\\alpha "],["β","\\beta "],["ϐ","\\beta "],["Γ","\\Gamma "],["γ","\\gamma "],["Δ","\\Delta "],["δ","\\delta "],["ε","\\epsilon "],["ϵ","\\epsilon "],["ζ","\\zeta "],["η","\\eta "],["Θ","\\Theta "],["ϴ","\\Theta "],["θ","\\theta "],["ᶿ","\\theta "],["ϑ","\\theta "],["ι","\\iota "],["κ","\\kappa "],["Λ","\\Lambda "],["λ","\\lambda "],["μ","\\mu "],["µ","\\mu "],["ν","\\nu "],["Ξ","\\Xi "],["ξ","\\xi "],["Π","\\Pi "],["π","\\pi "],["ϖ","\\pi "],["ρ","\\rho "],["ϱ","\\rho "],["Σ","\\Sigma "],["σ","\\sigma "],["ς","\\sigma "],["τ","\\tau "],["Υ","\\Upsilon "],["υ","\\upsilon "],["Φ","\\Phi "],["φ","\\phi "],["ϕ","\\phi "],["Ψ","\\Psi "],["ψ","\\psi "],["Ω","\\Omega "],["ω","\\omega "],["−","-"],["⋅"," \\cdot "],["·"," \\cdot "],["∪"," \\cup "],["∩"," \\cap "],["∞"," \\infty "],["∅"," \\emptyset "]];for(let t of n)e=e.replaceAll(t[0],t[1]);let r=e.match(/^(\\ )*(\\ldots|\.(\\ )*\.(\\ )*\.)(\\ )*(.*)$/);if(r){let t=r[6];e=","!==t[0]?"\\ldots,"+t:"\\ldots"+t}let a=e.match(/^(.*?)(\\ )*(\\ldots|\.(\\ )*\.(\\ )*\.)(\\ )*$/);if(a){let t=a[1];e=","!==t[t.length-1]?t+",\\ldots":t+"\\ldots"}return e=(e=e.replaceAll(/(\b|\\ )or(\b|\\ )/g,"$1\\lor$2")).replaceAll(/(\b|\\ )and(\b|\\ )/g,"$1\\land$2"),t&&(e=e.replaceAll(/(\b|\\ )U(\b|\\ )/g,"$1\\cup$2")),e}function isValidVariable(e){let t=e.tree,n=!0;return"string"==typeof t?"_"===t&&(n=!1):(!Array.isArray(t)||"_"!==t[0]||"string"!=typeof t[1]||"string"!=typeof t[2]&&"number"!=typeof t[2])&&(n=!1),n}function mathStateVariableFromNumberStateVariable({numberVariableName:e="number",mathVariableName:t="math",isPublic:n=!1}={}){let r={returnDependencies:()=>({number:{dependencyType:"stateVariable",variableName:e}}),definition:function({dependencyValues:e}){return{setValue:{[t]:numberToMathExpression(e.number)}}},inverseDefinition:function({desiredStateVariableValues:e}){let n=e[t].evaluate_to_constant();return null===n&&(n=NaN),{success:!0,instructions:[{setDependency:"number",desiredValue:n}]}}};return n&&(r.public=!0,r.shadowingInstructions={createComponentOfType:"math"}),r}function numberToMathExpression(e){let t;if("number"==typeof e?.re&&"number"==typeof e?.im)if(0===e.im)t=e.re;else{let n;n=1===e.im?"i":-1===e.im?["-","i"]:["*",e.im,"i"],t=0===e.re?n:["+",e.re,n]}else t=e;return me$3.fromAst(t)}function roundForDisplay({value:e,dependencyValues:t,usedDefault:n}){let r;return!n.displayDigits&&t.displayDigits>=1||n.displayDecimals||!Number.isFinite(t.displayDecimals)?(r=t.displayDigits>=1?me$3.round_numbers_to_precision(e,t.displayDigits):me$3.round_numbers_to_precision(e,10),t.displaySmallAsZero>0&&(r=me$3.evaluate_numbers(r,{skip_ordering:!0,set_small_zero:t.displaySmallAsZero}))):r=me$3.round_numbers_to_decimals(e,t.displayDecimals),r}function mergeListsWithOtherContainers(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);return[...vectorOperators,"list","set"].includes(t)&&(n=n.reduce(((e,t)=>Array.isArray(t)&&"list"===t[0]?[...e,...t.slice(1)]:[...e,t]),[])),n=n.map((e=>mergeListsWithOtherContainers(e))),[t,...n]}function wrapWordWithVar(e,t){let n="",r=/\\operatorname\s*{[^{}]*}/,a=e.match(r);for(;a;){let i=a.index,s=i+a[0].length;n+=wrapWordWithVarSub(e.substring(0,i),t),n+=e.substring(i,s),a=(e=e.substring(s)).match(r)}return n+=wrapWordWithVarSub(e,t),n}function wrapWordWithVarSub(e,t){let n="";const r=/([^a-zA-Z0-9]?)([a-zA-Z][a-zA-Z0-9]+)([^a-zA-Z0-9]?)/;let a;if(t){const e="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))";a=new RegExp("([0-9]+(\\.[0-9]*)?"+e+")|(\\.[0-9]+"+e+")")}let i=e.match(r);for(;i;){let s=i.index,o=s+i[0].length-i[3].length;if(t){let t=e.match(a);if(t&&t.indexs){n+=e.substring(0,o),i=(e=e.substring(o)).match(r);continue}}if("\\"===i[1])n+=e.substring(0,o),e=e.substring(o);else{let t=s+i[1].length;n+=e.substring(0,t),n+=`\\operatorname{${i[2]}}`,e=e.substring(o)}i=e.match(r)}return n+=e,n}function wrapWordIncludingNumberWithVar(e,t){let n="",r=/\\operatorname\s*{[^{}]*}/,a=e.match(r);for(;a;){let i=a.index,s=i+a[0].length;n+=wrapWordIncludingNumberWithVarSub(e.substring(0,i),t),n+=e.substring(i,s),a=(e=e.substring(s)).match(r)}return n+=wrapWordIncludingNumberWithVarSub(e,t),n}function wrapWordIncludingNumberWithVarSub(e,t){let n="";const r=/([^a-zA-Z0-9\s]?\s*)([a-zA-Z][a-zA-Z0-9]*[0-9][a-zA-Z0-9]*)([^a-zA-Z0-9]?)/;let a;if(t){const e="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))";a=new RegExp("([0-9]+(\\.[0-9]*)?"+e+")|(\\.[0-9]+"+e+")")}let i=e.match(r);for(;i;){let s=i.index,o=s+i[0].length-i[3].length;if(t){let t=e.match(a);if(t&&t.indexs){n+=e.substring(0,o),i=(e=e.substring(o)).match(r);continue}}if("\\"===i[1]||"^"===i[1][0]||"_"===i[1][0])n+=e.substring(0,o),e=e.substring(o);else{let t=s+i[1].length;n+=e.substring(0,t),n+=`\\operatorname{${i[2]}}`,e=e.substring(o)}i=e.match(r)}return n+=e,n}function stripLatex(e){return e.replaceAll("\\,","").replaceAll(/\\operatorname{([^{}]*)}/g,"$1")}function superSubscriptsToUnicode(e){let t={0:"₀",1:"₁",2:"₂",3:"₃",4:"₄",5:"₅",6:"₆",7:"₇",8:"₈",9:"₉","+":"₊","-":"₋"," ":""},n={0:"⁰",1:"¹",2:"²",3:"³",4:"⁴",5:"⁵",6:"⁶",7:"⁷",8:"⁸",9:"⁹","+":"⁺","-":"⁻"," ":""};function r(e,n){let r="";for(let e of n)r+=t[e];return r}function a(e,t){let r="";for(let e of t)r+=n[e];return r}return e=(e=(e=(e=e.replaceAll(/_(\d+)/g,r)).replaceAll(/_\(([\d +-]+)\)/g,r)).replaceAll(/\^(\d+)/g,a)).replaceAll(/\^\(([\d +-]+)\)/g,a)}function unicodeToSuperSubscripts(e){let t={"₀":"0","₁":"1","₂":"2","₃":"3","₄":"4","₅":"5","₆":"6","₇":"7","₈":"8","₉":"9","₊":"+","₋":"-"},n={"⁰":"0","¹":"1","²":"2","³":"3","⁴":"4","⁵":"5","⁶":"6","⁷":"7","⁸":"8","⁹":"9","⁺":"+","⁻":"-"};return e=(e=e.replaceAll(/([\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u208A\u208B]+)/g,(function(e,n){let r="";for(let e of n)r+=t[e];return"_("+r+")"}))).replaceAll(/([\u2070\u00B9\u00B2\u00B3\u2074\u2075\u2076\u2077\u2078\u2079\u207A\u207B]+)/g,(function(e,t){let r="";for(let e of t)r+=n[e];return"^("+r+")"}))}const vectorOperators=["vector","altvector","tuple"];function renameStateVariable({stateVariableDefinitions:e,oldName:t,newName:n}){let r=e[n]=e[t];if(delete e[t],r.additionalStateVariablesDefined){let e=r.additionalStateVariablesDefined.indexOf(t);-1!==e&&(r.additionalStateVariablesDefined[e]=n)}let a=r.definition,i=["setValue","useEssentialOrDefaultValue","setEssentialValue"],s=["noChanges"];r.definition=function(e){let r=a(e);for(let e of i)r[e]&&t in r[e]&&(r[e][n]=r[e][t],delete r[e][t]);for(let e of s)if(r[e]){let a=r[e].indexOf(t);-1!==a&&(r[e][a]=n)}return r};let o=r.inverseDefinition;o&&(r.inverseDefinition=async function(e){let r=e.desiredStateVariableValues;r[t]=r[n],delete r[n];let a=await o(e);if(a.success)for(let e of a.instructions)e.setEssentialValue===t&&(e.setEssentialValue=n);return a})}function returnDefaultGetArrayKeysFromVarName(e){return e>1?function({arrayEntryPrefix:e,varEnding:t,arraySize:n,nDimensions:r}){let a=t.split("_").map((e=>Number(e)-1));return a.length===r&&a.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?a.every(((e,t)=>e=0?n?rcrypto.getRandomValues(new Uint8Array(e)).reduce(((e,t)=>e+=(t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_"),""),core,queuedRequestActions=[];async function createCore(e){core=new Core(e),core.getInitializedPromise().then((()=>{for(let e of queuedRequestActions)core.requestAction(e);queuedRequestActions=[]}))}async function returnAllStateVariables(e){if(!e.components)return{};let t={};for(let n in e.components){let r=e.components[n],a=t[n]={componentName:n,componentType:r.componentType,stateValues:{}};for(let e in r.state)a.stateValues[e]=removeFunctionsMathExpressionClass(await r.state[e].value);a.activeChildren=r.activeChildren.map((e=>e.componentName?{componentName:e.componentName,componentType:e.componentType}:e)),r.replacements&&(a.replacements=r.replacements.map((e=>e.componentName?{componentName:e.componentName,componentType:e.componentType}:e)),void 0!==r.replacementsToWithhold&&(a.replacementsToWithhold=r.replacementsToWithhold)),a.sharedParameters=removeFunctionsMathExpressionClass(r.sharedParameters)}return t}function removeFunctionsMathExpressionClass(e){if(e instanceof me$3.class)e=e.tree;else if("function"==typeof e)e=void 0;else if(Array.isArray(e))e=e.map((e=>removeFunctionsMathExpressionClass(e)));else if("object"==typeof e&&null!==e){let t={};for(let n in e)t[n]=removeFunctionsMathExpressionClass(e[n]);e=t}return e}onmessage=function(e){"createCore"===e.data.messageType?createCore(e.data.args):"requestAction"===e.data.messageType?core?.initialized?core.requestAction(e.data.args):queuedRequestActions.push(e.data.args):"returnAllStateVariables"===e.data.messageType?(console.log("all components"),console.log(core._components),returnAllStateVariables(core).then((e=>{postMessage({messageType:"returnAllStateVariables",args:e})}))):"visibilityChange"===e.data.messageType?core.handleVisibilityChange(e.data.args):"terminate"===e.data.messageType?core.terminate().then((()=>{postMessage({messageType:"terminated"})})):"navigatingToComponent"===e.data.messageType?core.handleNavigatingToComponent(e.data.args.componentName):"submitAllAnswers"===e.data.messageType&&core.requestAction({componentName:core.documentName,actionName:"submitAllAnswers",args:e.data.args})};let styleAttributes={lineColor:{componentType:"text"},lineColorWord:{componentType:"text"},lineOpacity:{componentType:"number"},lineWidth:{componentType:"number"},lineWidthWord:{componentType:"text"},lineStyle:{componentType:"text"},lineStyleWord:{componentType:"text"},markerColor:{componentType:"text"},markerColorWord:{componentType:"text"},markerStyle:{componentType:"text"},markerStyleWord:{componentType:"text"},markerSize:{componentType:"number"},fillColor:{componentType:"text"},fillColorWord:{componentType:"text"},fillOpacity:{componentType:"number"}},defaultStyle={lineColor:"#648FFF",lineColorWord:"blue",lineOpacity:.7,lineWidth:4,lineWidthWord:"thick",lineStyle:"solid",lineStyleWord:"",markerColor:"#648FFF",markerColorWord:"blue",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"#648FFF",fillColorWord:"blue",fillOpacity:.3};function returnDefaultStyleDefinitions(){return{1:{lineColor:"#648FFF",lineColorWord:"blue",lineOpacity:.7,lineWidth:4,lineWidthWord:"thick",lineStyle:"solid",lineStyleWord:"",markerColor:"#648FFF",markerColorWord:"blue",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"#648FFF",fillColorWord:"blue",fillOpacity:.3},2:{lineColor:"#D4042D",lineColorWord:"red",lineOpacity:.7,lineWidth:2,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#D4042D",markerColorWord:"red",markerStyle:"square",markerStyleWord:"square",markerSize:5,fillColor:"#D4042D",fillColorWord:"red",fillOpacity:.3},3:{lineColor:"#F19143",lineColorWord:"orange",lineOpacity:.7,lineWidth:3,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#F19143",markerColorWord:"orange",markerStyle:"triangle",markerStyleWord:"triangle",markerSize:5,fillColor:"#F19143",fillColorWord:"orange",fillOpacity:.3},4:{lineColor:"#644CD6",lineColorWord:"purple",lineOpacity:.7,lineWidth:2,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#644CD6",markerColorWord:"purple",markerStyle:"diamond",markerStyleWord:"diamond",markerSize:5,fillColor:"#644CD6",fillColorWord:"purple",fillOpacity:.3},5:{lineColor:"black",lineColorWord:"black",lineOpacity:.7,lineWidth:1,lineWidthWord:"thin",lineStyle:"solid",lineStyleWord:"",markerColor:"black",markerColorWord:"black",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"black",fillColorWord:"black",fillOpacity:.3},6:{lineColor:"gray",lineColorWord:"gray",lineOpacity:.7,lineWidth:1,lineWidthWord:"thin",lineStyle:"dotted",lineStyleWord:"dotted",markerColor:"gray",markerColorWord:"gray",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"gray",fillColorWord:"gray",fillOpacity:.3}}}function returnStyleDefinitionStateVariables(){let e={setupChildren:{returnDependencies:()=>({setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}}),definition:({dependencyValues:e})=>({setValue:{setupChildren:e.setupChildren}})}};return e.styleDefinitions={stateVariablesDeterminingDependencies:["setupChildren"],returnDependencies({stateValues:e}){let t={ancestorWithStyle:{dependencyType:"ancestor",variableNames:["styleDefinitions"]},setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}};for(let n of e.setupChildren)t[`styleDefinitionsOf${n.componentName}`]={dependencyType:"child",parentName:n.componentName,childGroups:["styleDefinitions"],variableNames:["value"]};return t},definition({dependencyValues:e}){let t,n={};e.ancestorWithStyle&&(t=e.ancestorWithStyle.stateValues.styleDefinitions),t||(t=returnDefaultStyleDefinitions());for(let e in t)n[e]=Object.assign({},t[e]);let r=[];for(let t of e.setupChildren)r.push(...e[`styleDefinitionsOf${t.componentName}`]);for(let e of r){let t=e.stateValues.value;for(let e in t){let r=n[e];r||(r=n[e]=Object.assign({},defaultStyle));let a=Object.assign({},t[e]);"markerColor"in a&&!("markerColorWord"in a)&&(a.markerColorWord=a.markerColor),"markerStyle"in a&&!("markerStyleWord"in a)&&(a.markerStyleWord=a.markerStyle,"circle"===a.markerStyleWord?a.markerStyleWord="point":"triangle"===a.markerStyleWord.slice(0,8)&&(a.markerStyleWord="triangle")),"lineColor"in a&&!("lineColorWord"in a)&&(a.lineColorWord=a.lineColor),"fillColor"in a&&!("fillColorWord"in a)&&(a.fillColorWord=a.fillColor),"lineWidth"in a&&!("lineWidthWord"in a)&&(a.lineWidth>=4?a.lineWidthWord="thick":a.lineWidth<=1?a.lineWidthWord="thin":a.lineWidthWord=""),"lineStyle"in a&&!("lineStyleWord"in a)&&("dashed"===a.lineStyle?a.lineStyleWord="dashed":"dotted"===a.lineStyle?a.lineStyleWord="dotted":a.lineStyleWord=""),Object.assign(r,a)}}return{setValue:{styleDefinitions:n}}}},e}function returnSelectedStyleStateVariableDefinition(){return{selectedStyle:{forRenderer:!0,willNeverBeEssential:!0,returnDependencies:()=>({styleNumber:{dependencyType:"stateVariable",variableName:"styleNumber"},ancestorWithStyle:{dependencyType:"ancestor",variableNames:["styleDefinitions"]}}),definition:function({dependencyValues:e}){let t=e.ancestorWithStyle.stateValues.styleDefinitions;t||(t=returnDefaultStyleDefinitions());let n=t[e.styleNumber];return void 0===n&&(n=defaultStyle),{setValue:{selectedStyle:n}}}}}}function enumerateSelectionCombinations({numberOfIndices:e,numberOfOptions:t,maxNumber:n=1/0,withReplacement:r=!1,skipZero:a=!1}){if(1===e){let e=[...Array(t).keys()];return e=e.slice(1),a||(e=[...e,0]),e=e.slice(0,n),e=e.map((e=>[e])),e}let i=enumerateSelectionCombinations({numberOfIndices:e-1,numberOfOptions:t,maxNumber:n,withReplacement:r,skipZero:!r}),s=[],o=0;for(let e of i)for(let r=1;r<=t;r++){let i=[r%t,...e.map((e=>(r+e)%t))];if((!a||!i.includes(0))&&(s.push(i),o++,o>=n))return s}return s}function enumerateCombinations({numberOfOptionsByIndex:e,maxNumber:t=1/0}){let n=e.length;if(0===n)return[];let r=[];for(let t=0;t[...t,...e]),[]).reduce(((e,t)=>Math.max(e,t)),1);if(1===a){let n=e.reduce(((e,t)=>e*t));n=Math.min(n,t);let r=[];for(let t=0;tt%e));r.push(n)}return r}if(2===n){let n=a,r=me$3.math.lcm(...e),i=[],s=0;for(let a=0;a=t)return i}return i}let i=[];for(let t=0;t1?n.push(me$3.math.lcm(e[t],e[a])):n.push(null);i.push(n)}let s,o=i.reduce(((e,t)=>[...t,...e]),[]).filter((e=>null!==e)).reduce(((e,t)=>Math.min(e,t)),1/0);for(let e=0;e{if(0===e.length)n.push(a);else for(let i=0;i=t)return}};return r(e),n}function returnStandardSequenceAttributes(){return{type:{createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"number",toLowerCase:!0,validValues:["number","math","letters"]},from:{createComponentOfType:"_componentWithSelectableType"},to:{createComponentOfType:"_componentWithSelectableType"},step:{createComponentOfType:"math"},length:{createComponentOfType:"number"},exclude:{createComponentOfType:"_componentListWithSelectableType"}}}function returnStandardSequenceStateVariableDefinitions(){let e={specifiedFrom:{returnDependencies:()=>({fromAttr:{dependencyType:"attributeComponent",attributeName:"from",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"from",definition:function({dependencyValues:e}){return null===e.fromAttr?{useEssentialOrDefaultValue:{specifiedFrom:!0}}:null===e.fromAttr.stateValues.value?{setValue:{specifiedFrom:NaN}}:{setValue:{specifiedFrom:e.fromAttr.stateValues.value}}}},specifiedTo:{returnDependencies:()=>({toAttr:{dependencyType:"attributeComponent",attributeName:"to",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"to",definition:function({dependencyValues:e}){return null===e.toAttr?{useEssentialOrDefaultValue:{specifiedTo:!0}}:null===e.toAttr.stateValues.value?{setValue:{specifiedTo:NaN}}:{setValue:{specifiedTo:e.toAttr.stateValues.value}}}},specifiedLength:{returnDependencies:()=>({lengthAttr:{dependencyType:"attributeComponent",attributeName:"length",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"length",definition:function({dependencyValues:e}){return null===e.lengthAttr?{useEssentialOrDefaultValue:{specifiedLength:!0}}:null===e.lengthAttr.stateValues.value?{setValue:{specifiedLength:NaN}}:{setValue:{specifiedLength:e.lengthAttr.stateValues.value}}}},specifiedStep:{returnDependencies:()=>({stepAttr:{dependencyType:"attributeComponent",attributeName:"step",variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"}}),defaultValue:null,hasEssential:!0,essentialVarName:"step",definition:function({dependencyValues:e}){if(null===e.stepAttr)return{useEssentialOrDefaultValue:{specifiedStep:!0}};let t=e.stepAttr.stateValues.value;return null===t?{setValue:{specifiedStep:NaN}}:{setValue:{specifiedStep:t}}}},specifiedExclude:{returnDependencies:()=>({excludeAttr:{dependencyType:"attributeComponent",attributeName:"exclude",variableNames:["values"]}}),defaultValue:[],hasEssential:!0,essentialVarName:"exclude",definition:function({dependencyValues:e}){return null===e.excludeAttr?{useEssentialOrDefaultValue:{specifiedExclude:!0}}:{setValue:{specifiedExclude:e.excludeAttr.stateValues.values}}}},lowercase:{returnDependencies:()=>({specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"}}),definition:function({dependencyValues:e}){let t=/^[A-Z]*$/,n=!0;return null!==e.specifiedFrom?t.test(e.specifiedFrom)&&(n=!1):null!==e.specifiedTo&&t.test(e.specifiedTo)&&(n=!1),{setValue:{lowercase:n}}}}};return e.validSequence={returnDependencies:()=>({specifiedLength:{dependencyType:"stateVariable",variableName:"specifiedLength"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},type:{dependencyType:"stateVariable",variableName:"type"},lowercase:{dependencyType:"stateVariable",variableName:"lowercase"}}),definition:function({dependencyValues:e}){let t=!0;if(null!==e.specifiedLength&&(!Number.isInteger(e.specifiedLength)||e.specifiedLength<0)&&(console.warn("Invalid length of sequence. Must be a non-negative integer."),t=!1),null!==e.specifiedStep&&"math"!==e.type){let n=findFiniteNumericalValue(e.specifiedStep);Number.isFinite(n)||(console.warn("Invalid step of sequence. Must be a number for sequence of type "+e.type+"."),t=!1)}if(null!==e.specifiedFrom)if("number"===e.type){let n=findFiniteNumericalValue(e.specifiedFrom);Number.isFinite(n)||(console.warn("Invalid from of number sequence. Must be a number"),t=!1)}else Number.isNaN(e.specifiedFrom)&&(console.warn("Invalid from of sequence"),t=!1);if(null!==e.specifiedTo)if("number"===e.type){let n=findFiniteNumericalValue(e.specifiedTo);Number.isFinite(n)||(console.warn("Invalid to of number sequence. Must be a number"),t=!1)}else Number.isNaN(e.specifiedTo)&&(console.warn("Invalid to of sequence"),t=!1);return{setValue:{validSequence:t}}}},e.from={additionalStateVariablesDefined:["step","length","exclude"],returnDependencies:()=>({specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},specifiedLength:{dependencyType:"stateVariable",variableName:"specifiedLength"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"},type:{dependencyType:"stateVariable",variableName:"type"},specifiedExclude:{dependencyType:"stateVariable",variableName:"specifiedExclude"},validSequence:{dependencyType:"stateVariable",variableName:"validSequence"}}),definition:function({dependencyValues:e}){let t=e.specifiedFrom,n=e.specifiedTo,r=e.specifiedStep,a=e.specifiedLength,i=[...e.specifiedExclude],s=e.type;if("math"===e.type)null!==n&&(n instanceof me$3.class||(n=me$3.fromAst(n))),null!==t&&(t instanceof me$3.class||(t=me$3.fromAst(t))),null!==r&&(r instanceof me$3.class||(r=me$3.fromAst(r)));else if(null!==r&&r instanceof me$3.class&&(r=r.evaluate_to_constant()),"letters"===e.type)null!==t&&(t=lettersToNumber$1(t)),null!==n&&(n=lettersToNumber$1(n)),i=i.map(lettersToNumber$1);else if("number"===e.type){null!==n&&(n=n instanceof me$3.class?n.evaluate_to_constant():Number(n)),null!==t&&(t=t instanceof me$3.class?t.evaluate_to_constant():Number(t));for(let[e,t]of i.entries())t instanceof me$3.class?i[e]=t.evaluate_to_constant():i[e]=Number(t)}if(e.validSequence){let e=calculateSequenceParameters({from:t,to:n,step:r,length:a,type:s});return e.exclude=i,{setValue:e}}return(!Number.isInteger(a)||a<0)&&(a=0),{setValue:{from:t,step:r,length:a,exclude:i}}}},e}function calculateSequenceParameters({from:e,to:t,step:n,length:r,type:a}){if(null===e)null===t?(e="math"===a?me$3.fromAst(1):1,null===n?(n="math"===a?me$3.fromAst(1):1,null===r&&(r=10)):null===r&&(r=10)):(null===n&&(n="math"===a?me$3.fromAst(1):1),null===r&&(r="math"===a?Math.floor((t.subtract(1).divide(n).evaluate_to_constant()+1)*(1+1e-14)):Math.floor(((t-1)/n+1)*(1+1e-14))),"math"===a?e=t.subtract(n.multiply(r-1)).simplify():(e=t-n*(r-1),"letters"===a&&e<1&&(e=t-n*((r=Math.floor(((t-1)/n+1)*(1+1e-14)))-1))));else if(null===t)null===n&&(n="math"===a?me$3.fromAst(1):1),null===r&&(r=10);else if(null===n)null===r?"math"===a?(n=me$3.fromAst(1),r=Math.floor(t.subtract(e).add(1).evaluate_to_constant()*(1+1e-14))):(n=1,r=Math.floor((t-e+1)*(1+1e-14))):"math"===a?n=t.subtract(e).divide(r-1):(n=(t-e)/(r-1),"letters"===a&&(n=Math.floor(n)));else{if(null!==r)throw Error("Can't define from, to, step, and length for sequence");r="math"===a?Math.floor(t.subtract(e).divide(n).add(1).evaluate_to_constant()*(1+1e-14)):Math.floor(((t-e)/n+1)*(1+1e-14))}return(!Number.isInteger(r)||r<0)&&(console.warn("Invalid length of sequence. Must be a non-negative integer."),r=0),{from:e,step:n,length:r}}function returnSequenceValues({from:e,step:t,length:n,exclude:r,type:a,lowercase:i,maxNum:s},o=!1){let l=[],u=0;for(let c=0;c0&&("math"===a?n=n.add(t.multiply(me$3.fromAst(c))).expand().simplify():n+=t*c),"math"===a){if(r.some((e=>e&&e.equals(n))))continue}else if("number"===a){if(r.some((e=>Math.abs(e-n)<=1e-14*Math.max(Math.abs(e),Math.abs(n)))))continue}else if(r.includes(n))continue;if("letters"===a&&(n=numberToLetters(n,i)),o?l.push({value:n,originalIndex:c}):l.push(n),u++,u===s)break}return l}function returnSequenceValueForIndex({index:e,from:t,step:n,length:r,exclude:a,type:i,lowercase:s}){if(!(e>=0&&(void 0===r||e0&&("math"===i?o=o.add(n.multiply(me$3.fromAst(e))).expand().simplify():o+=n*e),"math"===i){if(a.some((e=>e&&e.equals(o))))return null}else if("number"===i){if(a.some((e=>Math.abs(e-o)<=1e-14*Math.max(Math.abs(e),Math.abs(o)))))return null}else if(a.includes(o))return null;return"letters"===i&&(o=numberToLetters(o,s)),o}function lettersToNumber$1(e){try{e=e.toUpperCase()}catch(t){return void console.warn("Cannot convert "+e+" to a number")}let t=0,n=e.length,r=n;for(;(r-=1)>-1;){let a=e.charCodeAt(r)-64;if(a<1||a>26)return void console.warn("Cannot convert "+e+" to a number");t+=a*Math.pow(26,n-1-r)}return t}function numberToLetters(e,t){e--;let n=65;t&&(n=97);let r="";for(;;){let t=e%26;if(r=String.fromCharCode(n+t)+r,e<26)break;e=Math.floor(e/26)-1}return r}function getVariantsForDescendantsForUniqueVariants({variantIndex:e,serializedComponent:t,componentInfoObjects:n}){let r=t.variants?.descendantVariantComponents;if(void 0===r)return{success:!1};let a=r.map((e=>e.variants.numberOfVariants)),i=enumerateCombinations({numberOfOptionsByIndex:a,maxNumber:e})[e-1],s=[];for(let[e,t]of r.entries()){let r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:i[e]+1,componentInfoObjects:n});if(!r.success)return{succss:!1};s.push(r.desiredVariant)}return{success:!0,desiredVariants:s}}function setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:r=!1}){let a,i;if(e.variants&&(i=e.variants.desiredVariant),a=void 0!==i?.seed?i.seed.toString():r?t.subpartVariantRng().toString().slice(2):t.variantRng().toString().slice(2),t.variantSeed=a,t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}function gatherVariantComponents({serializedComponents:e,componentInfoObjects:t}){let n=[];for(let r of e){if("object"!=typeof r)continue;if(r.variants||(r.variants={}),r.variants.isVariantComponent){n.push(r);continue}if(r.componentType in t.componentTypesCreatingVariants){r.variants.isVariantComponent=!0,n.push(r);continue}if(!r.children)continue;if(r.children.some((e=>"variantControl"===e.componentType))){r.variants.isVariantComponent=!0,n.push(r);continue}let e=gatherVariantComponents({serializedComponents:r.children,componentInfoObjects:t});e.length>0&&(r.variants.descendantVariantComponents=e,n.push(...e))}return n}function getNumberOfVariants({serializedComponent:e,componentInfoObjects:t}){let n;e.variants||(e.variants={});for(let t of e.children)if("variantControl"===t.componentType){n=t;break}let r="document"===e.componentType;if(!n){if(!r)return{success:!1};let n=e.children.filter((e=>e.componentType||""!==e.trim()));if(1===n.length&&t.isInheritedComponentType({inheritedComponentType:n[0].componentType,baseComponentType:"_sectioningComponent"})){let r=n[0],a=getNumberOfVariants({serializedComponent:r,componentInfoObjects:t});if(a.success)return e.variants.descendantVariantComponents=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t}),e.variants.uniqueVariants=!0,e.variants.numberOfVariants=r.variants.numberOfVariants,e.variants.allPossibleVariants=r.variants.allPossibleVariants,e.variants.allVariantNames=r.variants.allVariantNames,e.variants.allPossibleVariantUniqueIndices=[...r.variants.allPossibleVariants.keys()].map((e=>e+1)),e.variants.allPossibleVariantSeeds=[...r.variants.allPossibleVariants.keys()].map((e=>(e+1).toString())),a}}return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:r})}function determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:n=!1}){let r;void 0===e.variants&&(e.variants={});for(let t of e.children)if("variantControl"===t.componentType){r=t;break}if(!r&&!n){return t.allComponentClasses._base.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t})}let a=[];if(r?.attributes.variantNames&&(a=r.attributes.variantNames.component.children.map((e=>e.toLowerCase()))),a.length!==[...new Set(a)].length)throw Error("Duplicate variant names specified");let i=r?.attributes.nVariants?.primitive;Number.isFinite(i)||(i=100),i=Math.min(Math.max(i,1),1e3);let s=[...a];if(s.lengthe.toLowerCase())),o=[...new Set(o)];for(let e of o)if(!s.includes(e))throw Error(`Cannot include variant ${e} as ${e} is a not variant name`)}let l=r?.attributes.variantsToExclude?.component.children;if(l){l=l.map((e=>e.toLowerCase()));for(let e of l)if(!s.includes(e))throw Error(`Cannot exclude variant ${e} as ${e} is not a variant name`)}else l=[];o=o?o.filter((e=>!l.includes(e))):[...s].filter((e=>!l.includes(e)));let u=o.map((e=>s.indexOf(e)+1)),c=[];r?.attributes.seeds&&(c=r.attributes.seeds.component.children);let p=[...c];if(p.lengthp[e-1])),h=void 0!==r?.attributes.uniqueVariants,f=r?.attributes.uniqueVariants?.primitive;if(f||!h){d=t.allComponentClasses._base.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}),f=!!d.success&&(f||d.numberOfVariants<=i)}let y=[],g=[],b=[];if(f)for(let[e,t]of u.entries())t<=d.numberOfVariants&&(g.push(t),y.push(o[e]),b.push(m[e]));else y=o,g=u,b=m;let v=y.length;if(0===v)throw Error("No variants selected based on variantsToInclude, variantsToExclude, and the number of variants available");return e.variants.uniqueVariants=f,e.variants.numberOfVariants=v,e.variants.allPossibleVariants=y,e.variants.allVariantNames=s,e.variants.allPossibleVariantUniqueIndices=g,e.variants.allPossibleVariantSeeds=b,{success:!0,numberOfVariants:v}}function indexToLowercaseLetters(e){return numberToLetters(e,!0)}class BaseComponent{constructor({componentName:e,ancestors:t,serializedComponent:n,definingChildren:r,serializedChildren:a,attributes:i,stateVariableDefinitions:s,componentInfoObjects:o,coreFunctions:l,flags:u,shadow:c,numerics:p,parentSharedParameters:d,sharedParameters:m}){this.numerics=p,this.parentSharedParameters=d,this.sharedParameters=m,this.componentName=e,this.ancestors=t,this.counters={},this.componentInfoObjects=o,this.coreFunctions=l,this.flags=u,!0===c&&(this.isShadow=!0),this.definingChildren=r,void 0===this.definingChildren&&(this.definingChildren=[]),this.serializedChildren=a,this.attributes=i,this.state={};for(let e in s)this.state[e]=Object.assign({},s[e]);this.stateValues=new Proxy(this.state,createStateProxyHandler()),this.essentialState={},n.state&&(this.essentialState=deepClone(n.state)),this.doenetAttributes={},void 0!==n.doenetAttributes&&Object.assign(this.doenetAttributes,n.doenetAttributes),void 0!==n.variants&&(this.variants=n.variants),n.range&&(this.doenetMLrange=n.range),this.actions={copyDoenetMLToClipboard:this.copyDoenetMLToClipboard.bind(this)}}static componentType="_base";static get rendererType(){return this.componentType}get componentType(){return this.constructor.componentType}get componentOrAdaptedName(){return this.adaptedFrom?this.adaptedFrom.componentOrAdaptedName:this.componentName}get rendererType(){return this.constructor.rendererType}get allPotentialRendererTypes(){let e=[];this.rendererType&&e.push(this.rendererType);for(let t in this.state){let n=this.state[t];if(n.public){let t=n.componentType;Array.isArray(t)||(t=[t]),n.wrappingComponents&&t.push(...flattenDeep(n.wrappingComponents).map((e=>"object"==typeof e?e.componentType:e)));for(let n of t){let t=this.componentInfoObjects.allComponentClasses[n];if(t){let n=t.rendererType;n&&!e.includes(n)&&e.push(n)}}}}if(this.constructor.adapters)for(let t of this.constructor.adapters){let n;n="string"==typeof t?t:t.componentType;let r=this.componentInfoObjects.allComponentClasses[n];if(r){let t=r.rendererType;t&&!e.includes(t)&&e.push(t)}}if(!this.rendererType)return e;for(let t in this.allChildren){let n=this.allChildren[t].component;if("object"==typeof n)for(let t of n.allPotentialRendererTypes)e.includes(t)||e.push(t)}return e}potentialRendererTypesFromSerializedComponents(e){let t=[];for(let n of e){let e=this.componentInfoObjects.allComponentClasses[n.componentType];if(e){let n=e.rendererType;n&&!t.includes(n)&&t.push(n);let r=e.returnStateVariableInfo({onlyPublic:!0}).stateVariableDescriptions;for(let e in r){let n=r[e],a=n.shadowingInstructions?.createComponentOfType;Array.isArray(a)||(a=[a]),n.wrappingComponents&&a.push(...flattenDeep(n.wrappingComponents).map((e=>"object"==typeof e?e.componentType:e)));for(let e of a){let n=this.componentInfoObjects.allComponentClasses[e];if(n){let e=n.rendererType;e&&!t.includes(e)&&t.push(e)}}}if(e.adapters)for(let n of e.adapters){let e;e="string"==typeof n?n:n.componentType;let r=this.componentInfoObjects.allComponentClasses[e];if(r){let e=r.rendererType;e&&!t.includes(e)&&t.push(e)}}}if(n.children){let e=this.potentialRendererTypesFromSerializedComponents(n.children);for(let n of e)t.includes(n)||t.push(n)}}return t}get childrenMatched(){return this.childrenMatchedWithPlaceholders&&!this.placeholderActiveChildrenIndices}static createAttributesObject(){return{hide:{createComponentOfType:"boolean",createStateVariable:"hide",defaultValue:!1,public:!0},disabled:{createComponentOfType:"boolean"},fixed:{createComponentOfType:"boolean",ignoreFixed:!0},modifyIndirectly:{createComponentOfType:"boolean",createStateVariable:"modifyIndirectly",defaultValue:!0,public:!0,propagateToProps:!0},styleNumber:{createComponentOfType:"number",createStateVariable:"styleNumber",defaultValue:1,public:!0,fallBackToParentStateVariable:"styleNumber"},isResponse:{createPrimitiveOfType:"boolean",createStateVariable:"isResponse",defaultValue:!1,public:!0},newNamespace:{createPrimitiveOfType:"boolean",createStateVariable:"newNamespace",defaultValue:!1,public:!0}}}static returnSugarInstructions(){return[]}static returnChildGroups(){return[]}static get childGroups(){return this.hasOwnProperty("childGroupsData")||(this.childGroupsData=this.returnChildGroups()),this.childGroupsData}static childGroupOfComponentTypeData;static get childGroupOfComponentType(){return this.hasOwnProperty("childGroupOfComponentTypeData")||(this.childGroupOfComponentTypeData={}),this.childGroupOfComponentTypeData}static childGroupIndsByNameData;static get childGroupIndsByName(){if(this.hasOwnProperty("childGroupIndsByNameData"))return Object.assign({},this.childGroupIndsByNameData);this.childGroupIndsByNameData={};for(let[e,t]of this.childGroups.entries()){if(t.group in this.childGroupIndsByNameData)throw Error(`Invalid childGroups for componentClass ${this.componentType}: ${t} is repeated`);this.childGroupIndsByNameData[t.group]=e}return Object.assign({},this.childGroupIndsByNameData)}returnMatchedChildIndices(e){let t=[];for(let n of e){let e=this.childMatchesByGroup[n];if(!e)return;t.push(...e)}return t.sort(((e,t)=>e-t))}static returnStateVariableDefinitions(){let e={};return e.hidden={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({hide:{dependencyType:"stateVariable",variableName:"hide",variablesOptional:!0},parentHidden:{dependencyType:"parentStateVariable",variableName:"hidden"},sourceCompositeHidden:{dependencyType:"sourceCompositeStateVariable",variableName:"hidden"},adapterSourceHidden:{dependencyType:"adapterSourceStateVariable",variableName:"hidden"}}),definition:({dependencyValues:e})=>({setValue:{hidden:Boolean(e.parentHidden||e.sourceCompositeHidden||e.adapterSourceHidden||e.hide)}}),markStale:()=>({updateParentRenderedChildren:!0}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"hide",desiredValue:e.hidden}]})},e.disabled={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,hasEssential:!0,doNotShadowEssential:!0,defaultValue:!1,provideEssentialValuesInDefinition:!0,returnDependencies:()=>({disabledAttr:{dependencyType:"attributeComponent",attributeName:"disabled",variableNames:["value"]},readOnly:{dependencyType:"flag",flagName:"readOnly"},parentDisabled:{dependencyType:"parentStateVariable",variableName:"disabled"},sourceCompositeDisabled:{dependencyType:"sourceCompositeStateVariable",variableName:"disabled"},adapterSourceDisabled:{dependencyType:"adapterSourceStateVariable",variableName:"disabled"}}),definition({dependencyValues:e,usedDefault:t,essentialValues:n}){if(e.readOnly)return{setValue:{disabled:!0}};if(null!==e.disabledAttr)return{setValue:{disabled:e.disabledAttr.stateValues.value}};if(void 0!==n.disabled)return{useEssentialOrDefaultValue:{disabled:!0}};let r=!1,a=!0;return null===e.parentDisabled||t.parentDisabled||(r=r||e.parentDisabled,a=!1),null===e.sourceCompositeDisabled||t.sourceCompositeDisabled||(r=r||e.sourceCompositeDisabled,a=!1),null===e.adapterSourceDisabled||t.adapterSourceDisabled||(r=r||e.adapterSourceDisabled,a=!1),a?{useEssentialOrDefaultValue:{disabled:!0}}:{setValue:{disabled:r}}},inverseDefinition:({dependencyValues:e,desiredStateVariableValues:t})=>null!==e.disabledAttr?{success:!0,instructions:[{setDependency:"disabledAttr",desiredValue:t.disabled,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"disabled",value:t.disabled}]}},e.fixed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,ignoreFixed:!0,provideEssentialValuesInDefinition:!0,returnDependencies:()=>({fixedAttr:{dependencyType:"attributeComponent",attributeName:"fixed",variableNames:["value"]},parentFixed:{dependencyType:"parentStateVariable",variableName:"fixed"},sourceCompositeFixed:{dependencyType:"sourceCompositeStateVariable",variableName:"fixed"},adapterSourceFixed:{dependencyType:"adapterSourceStateVariable",variableName:"fixed"},ignoreParentFixed:{dependencyType:"doenetAttribute",attributeName:"ignoreParentFixed"}}),definition({dependencyValues:e,usedDefault:t,essentialValues:n}){if(null!==e.fixedAttr)return{setValue:{fixed:e.fixedAttr.stateValues.value}};if(void 0!==n.fixed)return{useEssentialOrDefaultValue:{fixed:!0}};let r=!1,a=!0;return null===e.parentFixed||t.parentFixed||e.ignoreParentFixed||(r=r||e.parentFixed,a=!1),null===e.sourceCompositeFixed||t.sourceCompositeFixed||(r=r||e.sourceCompositeFixed,a=!1),null===e.adapterSourceFixed||t.adapterSourceFixed||(r=r||e.adapterSourceFixed,a=!1),a?{useEssentialOrDefaultValue:{fixed:!0}}:{setValue:{fixed:r}}},inverseDefinition:({dependencyValues:e,desiredStateVariableValues:t})=>null!==e.fixedAttr?{success:!0,instructions:[{setDependency:"fixedAttr",desiredValue:t.fixed,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"fixed",value:t.fixed}]}},e.isInactiveCompositeReplacement={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{isInactiveCompositeReplacement:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:{variableName:"isInactiveCompositeReplacement",value:e.isInactiveCompositeReplacement}}]})},e}static returnNormalizedStateVariableDefinitions({attributeNames:e,numerics:t}){let n=this.returnStateVariableDefinitions({attributeNames:e,numerics:t});if(!n)throw Error(`Error in state variable definitions of ${this.componentType}: returnStateVariableDefinitions did not return anything`);let r=function(e){for(let[t,n]of e.entries())"object"==typeof n&&(e[t]=n.variableName)},a=["returnDependencies","definition","inverseDefinition","stateVariablesDeterminingDependencies","stateVariablesDeterminingArraySizeDependencies","isArray","nDimensions","returnArraySizeDependencies","returnArraySize","returnArrayDependenciesByKey","arrayDefinitionByKey","inverseArrayDefinitionByKey","basedOnArrayKeyStateVariables","markStale","getPreviousDependencyValuesForMarkStale","determineDependenciesImmediately","createWorkspace","workspace","provideEssentialValuesInDefinition","providePreviousValuesInDefinition"],i={};for(let e in n){let t=n[e];if(i[e]=t,t.createWorkspace&&(t.workspace={}),t.additionalStateVariablesDefined){for(let[n,s]of t.additionalStateVariablesDefined.entries()){let o={};for(let e of a)e in t&&(o[e]=t[e]);o.additionalStateVariablesDefined=[...t.additionalStateVariablesDefined],o.additionalStateVariablesDefined[n]=e,r(o.additionalStateVariablesDefined);let l=s;"object"==typeof s&&(l=s.variableName,s=Object.assign({},s),delete s.variableName,Object.assign(o,s)),i[l]=o}r(t.additionalStateVariablesDefined)}}return i}static returnStateVariableInfo({onlyPublic:e=!1,onlyForRenderer:t=!1}={}){let n=this.createAttributesObject(),r={},a={},i={};for(let a in n){let i=n[a],s=i.createStateVariable;if(s&&(!e||i.public)&&(!t||i.forRenderer))if(i.public){let e;!i.createComponentOfType?(e=i.createPrimitiveOfType,"string"===e&&(e="text")):e=i.createComponentOfType,r[s]={createComponentOfType:e,public:!0}}else r[s]={}}let s=this.returnNormalizedStateVariableDefinitions({attributeNames:Object.keys(r)});for(let n in s){let o=s[n];if(o.isAlias)i[n]=o.targetVariableName;else if((!e||o.public)&&(!t||o.forRenderer)&&(o.public?r[n]={createComponentOfType:o.shadowingInstructions.createComponentOfType,public:!0}:r[n]={},o.isArray)){let e;r[n].isArray=!0,r[n].nDimensions=void 0===o.nDimensions?1:o.nDimensions,r[n].wrappingComponents=o.shadowingInstructions?.returnWrappingComponents?o.shadowingInstructions.returnWrappingComponents():[],e=o.entryPrefixes?o.entryPrefixes:[n];for(let t of e)a[t]={arrayVariableName:n,nDimensions:o.returnEntryDimensions?o.returnEntryDimensions(t):1,wrappingComponents:o.shadowingInstructions?.returnWrappingComponents?o.shadowingInstructions.returnWrappingComponents(t):[]};o.getArrayKeysFromVarName?r[n].getArrayKeysFromVarName=o.getArrayKeysFromVarName:r[n].getArrayKeysFromVarName=returnDefaultGetArrayKeysFromVarName(r[n].nDimensions)}}return{stateVariableDescriptions:r,arrayEntryPrefixes:a,aliases:i}}get parentName(){if(void 0!==this.ancestors&&0!==this.ancestors.length)return this.ancestors[0].componentName}getAllChildrenDownstreamComponentNames(e=!1){const t=Object.keys(this.allChildren);let n=Object.keys(this.downstreamDependencies);return!0!==e&&(n=n.filter((e=>!0!==this.downstreamDependencies[e].inactive))),[...t,...n]}get allDescendants(){let e=[];for(let t in this.allChildren){let n=this.allChildren[t].component;e=[...e,t,...n.allDescendants]}return e}async serialize(e={}){let t,n={componentType:this.componentType},r=[],a={...e};t=e.sourceAttributesToIgnoreRecursively?[...e.sourceAttributesToIgnoreRecursively]:[],e.sourceAttributesToIgnore&&(t.push(...e.sourceAttributesToIgnore),delete a.sourceAttributesToIgnore);for(let e of this.definingChildren)"object"!=typeof e?r.push(e):r.push(await e.serialize(a));if(void 0!==this.serializedChildren)for(let e of this.serializedChildren)r.push(this.copySerializedComponent(e));r.length>0&&(n.children=r),n.attributes={};for(let r in this.attributes){let i=this.attributes[r];i.component?e.copyAll&&(n.attributes[r]={component:await i.component.serialize(a)}):t.includes(r)&&!e.copyAll||(n.attributes[r]=JSON.parse(JSON.stringify(i)))}return this.essentialState&&Object.keys(this.essentialState).length>0&&(n.state=deepClone(this.essentialState)),e.copyVariants&&this.state.generatedVariantInfo&&(n.variants={desiredVariant:await this.stateValues.generatedVariantInfo}),n.originalName=this.componentName,n.originalDoenetAttributes=deepClone(this.doenetAttributes),n.doenetAttributes=deepClone(this.doenetAttributes),n.originalAttributes=deepClone(n.attributes),delete n.doenetAttributes.prescribedName,delete n.doenetAttributes.assignNames,n}copySerializedComponent(e){if("object"!=typeof e)return e;let t=[];if(void 0!==e.children)for(let n of e.children)t.push(this.copySerializedComponent(n));let n={componentType:e.componentType,originalName:e.componentName,originalNameFromSerializedComponent:!0,children:t,state:{},doenetAttributes:{}};return void 0!==e.doenetAttributes&&(n.originalDoenetAttributes=deepClone(e.doenetAttributes),n.doenetAttributes=deepClone(e.doenetAttributes),n.originalAttributes=deepClone(e.attributes),n.attributes=deepClone(e.attributes),delete n.doenetAttributes.prescribedName,delete n.doenetAttributes.assignNames),void 0!==e.state&&Object.assign(n.state,e.state),n}static adapters=[];static get nAdapters(){return this.adapters.length}getAdapter(e){if(e>=this.constructor.adapters.length)return;let t,n,r,a,i=this.constructor.adapters[e];"string"==typeof i?t=i:(t=i.stateVariable,n=i.componentType,r=i.substituteForPrimaryStateVariable,a=i.stateVariablesToShadow);let s=this.state[t];if(void 0===s||!s.public&&!n)throw Error("Invalid adapter "+t+" in "+this.componentType);return void 0===n&&(n=s.shadowingInstructions.createComponentOfType),{componentType:n,downstreamDependencies:{[this.componentName]:[{dependencyType:"adapter",adapterVariable:t,adapterTargetIdentity:{componentName:this.componentName,componentType:this.componentType},substituteForPrimaryStateVariable:r,stateVariablesToShadow:a}]}}}static getAdapterComponentType(e,t){if(e>=this.adapters.length)return;let n,r,a=this.adapters[e];if("string"==typeof a?n=a:(n=a.stateVariable,r=a.componentType),void 0===r){let e=t[this.componentType].stateVariableDescriptions[n];if(!e)throw Error("Invalid adapter "+n+" in "+this.componentType);if(r=e.createComponentOfType,!r)throw Error(`Couldn't get adapter component type for ${n} of componentType ${this.componentType}`)}return r}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){let n=e.variants?.numberOfVariants;if(void 0!==n)return{success:!0,numberOfVariants:n};let r=[];e.children&&(r=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t})),void 0===e.variants&&(e.variants={}),e.variants.descendantVariantComponents=r,n=1;let a=[];for(let e of r){let r=t.allComponentClasses[e.componentType].determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!r.success)return{success:!1};a.push(r.numberOfVariants),n*=r.numberOfVariants}return e.variants.numberOfVariants=n,e.variants.uniqueVariantData={numberOfVariantsByDescendant:a},{success:!0,numberOfVariants:n}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};let a=!1,i=e.variants.uniqueVariantData.numberOfVariantsByDescendant,s=e.variants.descendantVariantComponents,o=[];if(s.length>0){let e=enumerateCombinations({numberOfOptionsByIndex:i,maxNumber:t})[t-1].map((e=>e+1));for(let t=0;t1){let r=s[t],i=n.allComponentClasses[r.componentType].getUniqueVariant({serializedComponent:r,variantIndex:e[t],componentInfoObjects:n});if(!i.success)return{success:!1};o.push(i.desiredVariant),a=!0}else o.push({})}let l={index:t};return a&&(l.subvariants=o),{success:!0,desiredVariant:l}}async copyDoenetMLToClipboard({actionId:e}){let t=this.coreFunctions.requestComponentDoenetML(this.componentName);t?this.coreFunctions.copyToClipboard(t,e):this.coreFunctions.resolveAction({actionId:e})}}class InlineComponent extends BaseComponent{static componentType="_inline"}class Text extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveText:this.moveText.bind(this)})}static componentType="text";static includeBlankStringChildren=!0;static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"textLike",componentTypes:["string","text","_singleCharacterInline","_inlineRenderInlineChildren"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType,addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},hasEssential:!0,returnDependencies:()=>({textLikeChildren:{dependencyType:"child",childGroups:["textLike"],variableNames:["text"]}}),defaultValue:"",set:e=>null===e?"":String(e),definition:function({dependencyValues:e}){if(0===e.textLikeChildren.length)return{useEssentialOrDefaultValue:{value:!0}};let t="";for(let n of e.textLikeChildren)t+="string"==typeof n?n:n.stateValues.text;return{setValue:{value:t}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n=t.textLikeChildren.length;return n>1?{success:!1}:1===n?{success:!0,instructions:[{setDependency:"textLikeChildren",desiredValue:e.value,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:null===e.value?"":String(e.value)}]}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.text}]})},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveText({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class TextOrInline extends InlineComponent{static componentType="_textOrInline";static renderChildren=!0;static rendererType="containerInline";static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{value:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}}class CompositeComponent extends BaseComponent{constructor(e){super(e),this.replacementsWorkspace={}}static componentType="_composite";static rendererType=void 0;static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.replacements={returnDependencies:()=>({replacements:{dependencyType:"replacement"}}),definition:({dependencyValues:e})=>({setValue:{replacements:e.replacements}})},e.recursiveReplacements={returnDependencies:()=>({recursiveReplacements:{dependencyType:"replacement",recursive:!0}}),definition:({dependencyValues:e})=>({setValue:{recursiveReplacements:e.recursiveReplacements}})},e.fullRecursiveReplacements={returnDependencies:()=>({recursiveReplacements:{dependencyType:"replacement",recursive:!0,recurseNonStandardComposites:!0}}),definition:({dependencyValues:e})=>({setValue:{fullRecursiveReplacements:e.recursiveReplacements}})},e}static createSerializedReplacements(){return{replacements:[]}}static calculateReplacementChanges(){return[]}replacements=[];replacementsToWithhold=0;get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes;for(let t in this.allChildren){let n=this.allChildren[t].component;for(let t of n.allPotentialRendererTypes)e.includes(t)||e.push(t)}if(this.replacements)for(let t of this.replacements)if("object"==typeof t)for(let n of t.allPotentialRendererTypes)e.includes(n)||e.push(n);return e}}class Template extends CompositeComponent{static componentType="template";static treatAsComponentForRecursiveReplacements=!0;static includeBlankStringChildren=!0;static renderedDefault=!1;static assignNamesToReplacements=!0;static createsVariants=!0;static keepChildrenSerialized({serializedComponent:e}){return void 0===e.children?[]:Object.keys(e.children)}static createAttributesObject(){let e=super.createAttributesObject();return e.rendered={createComponentOfType:"boolean",createStateVariable:"rendered",defaultValue:this.renderedDefault,public:!0},e.isResponse={leaveRaw:!0},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.serializedChildren={returnDependencies:()=>({serializedChildren:{dependencyType:"serializedChildren",doNotProxy:!0}}),definition:function({dependencyValues:e}){return{setValue:{serializedChildren:e.serializedChildren}}}},e.newNamespace={returnDependencies:()=>({newNamespace:{dependencyType:"attributePrimitive",attributeName:"newNamespace"}}),definition:({dependencyValues:e})=>({setValue:{newNamespace:e.newNamespace}})},e.readyToExpandWhenResolved={returnDependencies:()=>({}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:n}){let r;if(e.typeAttr){if(!(n.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in n.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);r=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error(`You must specify createComponentOfType when specifying nComponents for a ${t.componentType}.`);r=null}return{setValue:{nComponentsSpecified:r}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,alwaysCreateReplacements:n,flags:r}){if(await e.stateValues.nComponentsSpecified,await e.stateValues.rendered||n){let n=deepClone(await e.state.serializedChildren.value),a=e.attributes.newNamespace?.primitive;if("isResponse"in e.attributes)for(let i of n){if("object"!=typeof i)continue;let n=convertAttributesForComponentType({attributes:{isResponse:e.attributes.isResponse},componentType:i.componentType,componentInfoObjects:t,compositeCreatesNewNamespace:a,flags:r});i.attributes||(i.attributes={}),Object.assign(i.attributes,n)}let i=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:n,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:t,originalNamesAreConsistent:!0});return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:i.serializedComponents,assignNames:e.doenetAttributes.assignNames,componentInfoObjects:t,compositeAttributesObj:this.createAttributesObject(),flags:r})).replacements}}return{replacements:[]}}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes,t=this.potentialRendererTypesFromSerializedComponents(this.serializedChildren);for(let n of t)e.includes(n)||e.push(n);return e}}const vectorAndListOperators=["list",...vectorOperators];class MathComponent extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="math";static primaryStateVariableForDefinition="unnormalizedValue";static primaryEssentialStateVariable="value";static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!0;static descendantCompositesDefaultReplacementType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0,toLowerCase:!0,validValues:["text","latex"]},e.simplify={createComponentOfType:"text",createStateVariable:"simplify",defaultValue:"none",public:!0,toLowerCase:!0,valueTransformations:{true:"full",false:"none"},validValues:["none","full","numbers","numberspreserveorder"]},e.expand={createComponentOfType:"boolean",createStateVariable:"expand",defaultValue:!1,public:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.renderMode={createComponentOfType:"text",createStateVariable:"renderMode",defaultValue:"inline",public:!0,forRenderer:!0},e.unordered={createComponentOfType:"boolean"},e.createVectors={createComponentOfType:"boolean",createStateVariable:"createVectors",defaultValue:!1,public:!0},e.createIntervals={createComponentOfType:"boolean",createStateVariable:"createIntervals",defaultValue:!1,public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.sourcesAreFunctionSymbols={createComponentOfType:"textList",createStateVariable:"sourcesAreFunctionSymbols",defaultValue:[]},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e.groupCompositeReplacements={createPrimitiveOfType:"boolean",createStateVariable:"groupCompositeReplacements",defaultValue:!0},e.displayBlanks={createComponentOfType:"boolean",createStateVariable:"displayBlanks",defaultValue:!0,public:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"strings",componentTypes:["string"]},{group:"displayedMaths",componentTypes:["m","me","men"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displayDigits"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}let a=null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals,i=null===e.displayDigitsAttr||t.displayDigitsAttr,s=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!i&&!s){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displayDecimals"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}if(1===e.mathChildren.length&&0===e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].displayDecimals)return{setValue:{displayDecimals:e.mathChildren[0].stateValues.displayDecimals}};r=!0,n=e.mathChildren[0].stateValues.displayDecimals}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displaySmallAsZero"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}if(1===e.mathChildren.length&&0===e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].displaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathChildren[0].stateValues.displaySmallAsZero}};r=!0,n=e.mathChildren[0].stateValues.displaySmallAsZero}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["padZeros"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}if(1===e.mathChildren.length&&0==e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].padZeros)return{setValue:{padZeros:e.mathChildren[0].stateValues.padZeros}};r=!0,n=e.mathChildren[0].stateValues.padZeros}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.valueShadow={defaultValue:me$3.fromAst("_"),hasEssential:!0,essentialVarName:"value",returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{valueShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"valueShadow",value:e.valueShadow}]}}},e.unordered={defaultValue:!1,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,returnDependencies:()=>({unorderedAttr:{dependencyType:"attributeComponent",attributeName:"unordered",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["unordered"]}}),definition({dependencyValues:e}){if(null===e.unorderedAttr){if(e.mathChildren.length>0){let t=e.mathChildren.every((e=>e.stateValues.unordered));return{setValue:{unordered:t}}}return{useEssentialOrDefaultValue:{unordered:!0}}}return{setValue:{unordered:e.unorderedAttr.stateValues.value}}}},e.codePre={returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e}){let t="math",n=!1;do{n=!1;for(let r of e.stringChildren)if(!0===r.includes(t)){n=!0,t+="m";break}}while(n);return{setValue:{codePre:t}}}},e.mathChildrenFunctionSymbols={returnDependencies:()=>({sourcesAreFunctionSymbols:{dependencyType:"stateVariable",variableName:"sourcesAreFunctionSymbols"},mathChildren:{dependencyType:"child",childGroups:["maths"]}}),definition({dependencyValues:e}){let t=[];if(e.mathChildren.compositeReplacementRange)for(let n of e.mathChildren.compositeReplacementRange)if(e.sourcesAreFunctionSymbols.includes(n.target))for(let e=n.firstInd;e<=n.lastInd;e++)t.push(e);return{setValue:{mathChildrenFunctionSymbols:t}}}},e.expressionWithCodes={hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({stringMathChildren:{dependencyType:"child",childGroups:["strings","maths"]},stringChildren:{dependencyType:"child",childGroups:["strings"]},mathChildren:{dependencyType:"child",childGroups:["maths"]},displayedMathChildren:{dependencyType:"child",childGroups:["displayedMaths"],variableNames:["latex"]},format:{dependencyType:"stateVariable",variableName:"format"},codePre:{dependencyType:"stateVariable",variableName:"codePre"},functionSymbols:{dependencyType:"stateVariable",variableName:"functionSymbols"},mathChildrenFunctionSymbols:{dependencyType:"stateVariable",variableName:"mathChildrenFunctionSymbols"},splitSymbols:{dependencyType:"stateVariable",variableName:"splitSymbols"},parseScientificNotation:{dependencyType:"stateVariable",variableName:"parseScientificNotation"},groupCompositeReplacements:{dependencyType:"stateVariable",variableName:"groupCompositeReplacements"}}),set:e=>null===e?null:convertValueToMathExpression(e),definition:calculateExpressionWithCodes,async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,componentName:r}){let a=e.expressionWithCodes,i=[{setEssentialValue:"expressionWithCodes",value:a}],s=t.stringChildren.length;if(0===s)return{success:!1};if(0===t.mathChildren.length){let e;e="latex"===await n.format?a.toLatex():a.toString(),i.push({setDependency:"stringChildren",desiredValue:e,childIndex:0,variableIndex:0,ignoreChildChangeForComponent:!0});for(let e=1;e({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value","canBeModified"]}}),definition:({dependencyValues:e})=>({setValue:{mathChildrenWithCanBeModified:e.mathChildren}})},e.unnormalizedValue={returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"},codePre:{dependencyType:"stateVariable",variableName:"codePre"},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"}}),set:convertValueToMathExpression,defaultValue:me$3.fromAst("_"),definition:calculateMathValue,inverseDefinition:invertMath},e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType,attributesToShadow:["unordered","displayDigits","displayDecimals","displaySmallAsZero","padZeros","simplify","expand"],addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},returnDependencies:()=>({unnormalizedValue:{dependencyType:"stateVariable",variableName:"unnormalizedValue"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},createVectors:{dependencyType:"stateVariable",variableName:"createVectors"},createIntervals:{dependencyType:"stateVariable",variableName:"createIntervals"}}),definition:function({dependencyValues:e}){let t=e.unnormalizedValue,{simplify:n,expand:r,createVectors:a,createIntervals:i}=e;return t=normalizeMathExpression({value:t,simplify:n,expand:r,createVectors:a,createIntervals:i}),{setValue:{value:t}}},inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"unnormalizedValue",desiredValue:e.value}]}}},e.number={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){let t=e.value.evaluate_to_constant();return null===t&&(t=NaN),{setValue:{number:t}}},inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"value",desiredValue:me$3.fromAst(e.number)}]}}},e.isNumber={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{isNumber:Number.isFinite(e.value.tree)}}}},e.isNumeric={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({number:{dependencyType:"stateVariable",variableName:"number"}}),definition:function({dependencyValues:e}){return{setValue:{isNumeric:Number.isFinite(e.number)}}}},e.valueForDisplay={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:normalizeMathExpression({value:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t}),simplify:e.simplify,expand:e.expand})}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.valueForDisplay}]})},e.latex={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displayBlanks:{dependencyType:"stateVariable",variableName:"displayBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n,r={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.displayBlanks||(r.showBlanks=!1);try{n=e.valueForDisplay.toLatex(r)}catch(t){n=e.displayBlanks?"_":""}return{setValue:{latex:n}}},inverseDefinition({desiredStateVariableValues:e}){let t;try{t=me$3.fromLatex(e.latex)}catch(e){return{success:!1}}return{success:!0,instructions:[{setDependency:"valueForDisplay",desiredValue:t}]}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},value:{dependencyType:"stateVariable",variableName:"value"},displayBlanks:{dependencyType:"stateVariable",variableName:"displayBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n,r={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.displayBlanks||(r.showBlanks=!1);try{n=e.valueForDisplay.toString(r)}catch(t){n=e.displayBlanks?"_":""}return{setValue:{text:superSubscriptsToUnicode(n.toString())}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n,r=getFromText({functionSymbols:await t.functionSymbols,splitSymbols:await t.splitSymbols,parseScientificNotation:await t.parseScientificNotation});try{n=r(unicodeToSuperSubscripts(e.text))}catch(e){return{success:!1}}return{success:!0,instructions:[{setDependency:"value",desiredValue:n}]}}},e.codesAdjacentToStrings={returnDependencies:()=>({stringMathChildren:{dependencyType:"child",childGroups:["strings","maths"]},codePre:{dependencyType:"stateVariable",variableName:"codePre"},format:{dependencyType:"stateVariable",variableName:"format"}}),definition:calculateCodesAdjacentToStrings},e.canBeModified={additionalStateVariablesDefined:["constantChildIndices","codeForExpression","inverseMaps","template","mathChildrenMapped"],returnDependencies:()=>({mathChildrenModifiable:{dependencyType:"child",childGroups:["maths"],variableNames:["canBeModified"]},displayedMathChildren:{dependencyType:"child",childGroups:["displayedMaths"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"},modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition:determineCanBeModified},e.mathChildrenByVectorComponent={returnDependencies:()=>({codePre:{dependencyType:"stateVariable",variableName:"codePre"},mathChildren:{dependencyType:"child",childGroups:["maths"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"}}),definition:function({dependencyValues:e}){if(null===e.expressionWithCodes)return{setValue:{mathChildrenByVectorComponent:null}};let t=e.expressionWithCodes.tree,n=e.mathChildren.length;if(0===n||!Array.isArray(t)||!vectorOperators.includes(t[0]))return{setValue:{mathChildrenByVectorComponent:null}};let r={},a=0,i=e.codePre+a;for(let s=1;s=n)break}return{setValue:{mathChildrenByVectorComponent:r}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition({dependencyValues:e}){let t=1,n=e.value.tree;if(Array.isArray(n))if(vectorAndListOperators.includes(n[0]))t=n.length-1;else if("matrix"===n[0]){let e=n[1].slice(1);1===e[0]?t=e[1]:1===e[1]&&(t=e[0])}else vectorOperators.includes(n[1][0])&&("^"===n[0]&&"T"===n[2]||"prime"===n[0])&&(t=n[1].length-1);return{setValue:{nDimensions:t}}}},e.vector={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"x"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["x"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{value:{dependencyType:"stateVariable",variableName:"value"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t,arraySize:n}){let r=e.value.tree,a=!1,i={};if(Array.isArray(r))if(vectorAndListOperators.includes(r[0])){for(let e=0;ee.tree))]);else if("matrix"===s[0]){let e=s[1].slice(1);if(1===e[0]){let e=["tuple"];for(let t=0;te.tree))]],s[2]&&i.push(s[2]),i=me$3.fromAst(i));return i||(i=r.desiredVector[0]),{success:!0,instructions:[{setDependency:"value",desiredValue:i}]}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.matrixSize={public:!0,shadowingInstructions:{createComponentOfType:"numberList"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition({dependencyValues:e}){let t=[1,1],n=e.value.tree;return Array.isArray(n)&&(vectorAndListOperators.includes(n[0])?t=[n.length-1,1]:"matrix"===n[0]?t=n[1].slice(1):vectorOperators.includes(n[1][0])&&("^"===n[0]&&"T"===n[2]||"prime"===n[0])&&(t=[1,n[1].length-1])),{setValue:{matrixSize:t}}}},e.nRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),definition:({dependencyValues:e})=>({setValue:{nRows:e.matrixSize[0]}})},e.nColumns={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),definition:({dependencyValues:e})=>({setValue:{nColumns:e.matrixSize[1]}})},e.matrix={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"matrixEntry"===e?[]:"row"===e?[["matrix","matrixRow"]]:"column"===e?[["matrix","matrixColumn"]]:[["matrixRow"],["matrix"]]},isArray:!0,nDimensions:2,entryPrefixes:["matrixEntry","row","column","rows","columns"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("matrixEntry"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}if("column"===e){let e=Number(t)-1;return Number.isInteger(e)&&e>=0?n?en+","+e)):[]:["0,"+e]:[]}if("rows"===e||"columns"===e){if(!n)return["0,0"];let e=[];for(let t=0;tt+","+n)));return e}},arrayVarNameFromPropIndex(e,t){if("matrix"===t||"rows"===t)return 1===e.length?"row"+e[0]:`matrixEntry${e[0]}_${e[1]}`;if("columns"===t)return 1===e.length?"column"+e[0]:`matrixEntry${e[1]}_${e[0]}`;if("row"===t.slice(0,3)){let n=Number(t.slice(3));if(Number.isInteger(n)&&n>0)return`matrixEntry${n}_${e[0]}`}if("column"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`matrixEntry${e[0]}_${n}`}return null},returnArraySizeDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),returnArraySize:({dependencyValues:e})=>e.matrixSize,returnArrayDependenciesByKey:()=>({globalDependencies:{value:{dependencyType:"stateVariable",variableName:"value"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t,arraySize:n}){let r=e.value.tree,a=!1,i={};if(Array.isArray(r))if(vectorAndListOperators.includes(r[0])){for(let e=0;e({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}static adapters=[{stateVariable:"number",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text",{componentType:"subsetOfReals",stateVariable:"value",substituteForPrimaryStateVariable:"subsetValue"}];async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}function calculateExpressionWithCodes({dependencyValues:e,changes:t}){if(!("stringMathChildren"in t&&t.stringMathChildren.componentIdentitiesChanged||"displayedMathChildren"in t||"format"in t||"splitSymbols"in t||"parseScientificNotation"in t||"functionSymbols"in t||"mathChildrenFunctionSymbols"in t))return{useEssentialOrDefaultValue:{expressionWithCodes:!0}};if(0===e.stringMathChildren.length){if(e.displayedMathChildren.length>0){let t;try{t=me$3.fromLatex(e.displayedMathChildren[0].stateValues.latex)}catch(e){t=me$3.fromAst("_")}return{setValue:{expressionWithCodes:t},setEssentialValue:{expressionWithCodes:t}}}return{setValue:{expressionWithCodes:null},setEssentialValue:{expressionWithCodes:null}}}let n,r,a,i,s="",o=0,l="",u=e.stringMathChildren.compositeReplacementRange;e.groupCompositeReplacements&&u.length>0&&(a=0,i=u[a].firstInd);for(let[t,c]of e.stringMathChildren.entries()){if(void 0===n&&t===i){n=a,r=u[a].lastInd,l="";let s=r===t;if(!s)for(let n=t;n<=r;n++)if("string"==typeof e.stringMathChildren[n]){s=!0;break}s&&(u.length>n+1?(a=n+1,i=u[a].firstInd):(a=void 0,i=void 0),n=void 0,r=void 0)}if("string"==typeof c)s+=" "+c+" ";else{let t,r=e.codePre+o;o++,t="latex"===e.format?"\\operatorname{"+r+"}":" "+r+" ",void 0!==n?(l&&(l+=","),l+=t):s+=t}if(t===r){let o=s.trimEnd(),c=!1;if(0===o.length)c=!0;else{let n=o[o.length-1];if(["{","[","(","|",","].includes(n)){let n=e.stringMathChildren[t+1];if("string"!=typeof n)c=!0;else{let t=n.trimStart();if(0===t.length)c=!0;else{let n=t[0];"latex"===e.format&&"\\"===n&&t.length>1&&(n=t[1]),["}","]",")","|",","].includes(n)||(c=!0)}}}else c=!0}c&&(l="("+l+")"),s+=l,l="",u.length>n+1?(a=n+1,i=u[a].firstInd):(a=void 0,i=void 0),n=void 0,r=void 0}}let c=null,p=[...e.functionSymbols];if(p.push(...e.mathChildrenFunctionSymbols.map((t=>e.codePre+t))),""===s)c=me$3.fromAst("_");else if("text"===e.format){let t=getFromText({functionSymbols:p,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation});try{c=t(s)}catch(e){c=me$3.fromAst("_"),console.log("Invalid value for a math of text format: "+s)}}else if("latex"===e.format){let t=getFromLatex({functionSymbols:p,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation});try{c=t(s)}catch(e){c=me$3.fromAst("_"),console.log("Invalid value for a math of latex format: "+s)}}return{setValue:{expressionWithCodes:c},setEssentialValue:{expressionWithCodes:c}}}function calculateMathValue({dependencyValues:e}={}){if(null===e.expressionWithCodes)return{setValue:{unnormalizedValue:e.valueShadow}};let t={};for(let[n,r]of e.mathChildren.entries())t[e.codePre+n]=r.stateValues.value;let n=e.expressionWithCodes;return e.mathChildren.length>0&&(n=n.substitute(t)),n=me$3.fromAst(mergeListsWithOtherContainers(n.tree)),{setValue:{unnormalizedValue:n}}}function calculateCodesAdjacentToStrings({dependencyValues:e}){let t,n=[];for(let[r,a]of e.stringMathChildren.entries())if("string"==typeof a){let a=e.stringMathChildren[r+1];if(void 0!==a&&"string"==typeof a)continue;let i={};if(void 0!==t&&("latex"===e.format?i.prevCode="\\operatorname{"+e.codePre+t+"}":i.prevCode=e.codePre+t),void 0!==a){let n=0;void 0!==t&&(n=t+1),"latex"===e.format?i.nextCode="\\operatorname{"+e.codePre+n+"}":i.nextCode=e.codePre+n}n.push(i)}else void 0===t?t=0:t++;return{setValue:{codesAdjacentToStrings:n}}}function determineCanBeModified({dependencyValues:e}){if(!e.modifyIndirectly||e.fixed)return{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}};if(0===e.mathChildrenModifiable.length)return e.displayedMathChildren.length>0?{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}}:{setValue:{canBeModified:!0,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}};let t=[],n=[],r=[],a={};for(let[i,s]of e.mathChildrenModifiable.entries()){let o=e.codePre+i;!0===s.stateValues.canBeModified?(t.push(i),n.push(o)):(r.push(o),a[o]=i)}let i=e.codePre+"expr",s=checkForLinearExpression(me$3.utils.unflattenLeft(e.expressionWithCodes.tree),n,i,r);if(s.foundLinear){let e={},r=s.template,o=new Set;for(let r in s.mappings){e[r]=s.mappings[r];let a=e[r].mathChildSub;if(a){let i=t[n.indexOf(a)];e[r].mathChildInd=i,o.add(Number(i))}}return o.has=o.has.bind(o),{setValue:{canBeModified:!0,constantChildIndices:a,codeForExpression:i,inverseMaps:e,template:r,mathChildrenMapped:o}}}return{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}}}function checkForLinearExpression(e,t,n,r=[],a=[]){let i=me$3.variables(e);if(i.every((e=>!t.includes(e)))&&i.every((e=>!r.includes(e)))){let e={},t="x"+a.join("_");return e[t]={result:me$3.fromAst(n).simplify(),components:a},{foundLinear:!0,mappings:e,template:t}}if(!Array.isArray(e))return checkForScalarLinearExpression(e,t,n,a);let s=e[0],o=e.slice(1);if(vectorAndListOperators.includes(s)){let e={mappings:{},template:[s]},i=0;for(let s=0;s!t.includes(e)))?(n=["+",n,["-",i[0]]],checkForScalarLinearExpression(i[1],t,n,r)):me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["+",n,["-",i[1]]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}:"*"===a?me$3.variables(i[0]).every((e=>!t.includes(e)))?(n=["/",n,i[0]],checkForScalarLinearExpression(i[1],t,n,r)):me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["/",n,i[1]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}:"/"===a&&me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["*",n,i[1]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}}async function invertMath({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r,overrideFixed:a,componentName:i}){if(!await n.canBeModified&&!a)return{success:!1};let s=t.mathChildren,o=t.stringChildren.length;if(1===s.length&&0===o)return{success:!0,instructions:[{setDependency:"mathChildren",desiredValue:e.unnormalizedValue,childIndex:0,variableIndex:0}]};let l=convertValueToMathExpression(e.unnormalizedValue),u=await preprocessMathInverseDefinition({desiredValue:l,stateValues:n,variableName:"value",workspace:r}),c=u.vectorComponentsNotAffected;if(l=u.desiredValue,0===s.length){let f=[];return o>0?f.push({setDependency:"expressionWithCodes",desiredValue:l}):f.push({setDependency:"valueShadow",desiredValue:l}),{success:!0,instructions:f}}let p=await getExpressionPieces({expression:l,stateValues:n});if(!p)return{success:!1};let d=[],m=[];if(c&&await n.mathChildrenByVectorComponent){let y=await n.mathChildrenByVectorComponent;for(let g of c)y[g]&&m.push(...y[g])}let h=await n.mathChildrenWithCanBeModified;for(let[b,v]of s.entries())if(n.mathChildrenMapped.has(b)&&h[b].stateValues.canBeModified){if(!m.includes(b)){let N=p[b],T={},C=!1,A=await n.constantChildIndices;for(let V in A){let x=A[V];T[V]=s[x].stateValues.value,C=!0}C&&(N=N.substitute(T)),N=N.simplify(),d.push({setDependency:"mathChildren",desiredValue:N,childIndex:b,variableIndex:0})}delete p[b]}if(o>0){let S=t.expressionWithCodes,w=t.codePre,E=w.length;function D(e){return"string"==typeof e&&e.substring(0,E)===w}function O(e){return Array.isArray(e)?flattenDeep(e.slice(1)).some(D):D(e)}if(vectorAndListOperators.includes(S.tree[0])&&!S.tree.slice(1).every(O)){let I=await n.inverseMaps;for(let R in p){let _=I[R];if(void 0!==_.mathChildInd)continue;let M=_.components;S=S.substitute_component(M,p[R])}d.push({setDependency:"expressionWithCodes",desiredValue:S})}}return{success:!0,instructions:d}}async function getExpressionPieces({expression:e,stateValues:t}){let n=await t.template,r=me$3.utils.match(e.tree,n);if(!(r||(r=me$3.utils.match(e.tuples_to_vectors().tree,me$3.fromAst(n).tuples_to_vectors().tree),r||(r=me$3.utils.match(e.to_intervals().tree,me$3.fromAst(n).to_intervals().tree),r||(r=me$3.utils.match(e.tuples_to_vectors().to_intervals().tree,me$3.fromAst(n).tuples_to_vectors().to_intervals().tree),r)))))return!1;let a={};for(let e in r){let n={};n[await t.codeForExpression]=r[e];let i=(await t.inverseMaps)[e];if(void 0!==i){let r=e;void 0!==i.mathChildInd&&(r=i.mathChildInd),a[r]=i.result.substitute(n),a[r]=normalizeMathExpression({value:a[r],simplify:await t.simplify,expand:await t.expand,createVectors:await t.createVectors,createIntervals:await t.createIntervals})}}return a}class Label extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveLabel:this.moveLabel.bind(this)})}static componentType="label";static renderChildren=!0;static rendererType="label";static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="valueShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.forObject={createTargetComponentNames:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.valueShadow={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{valueShadow:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"valueShadow",value:e.valueShadow}]})},e.hasLatex={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text","latex","value","hasLatex","renderAsMath"],variablesOptional:!0},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length&&null!==e.valueShadow){let t=e.valueShadow;return{setValue:{hasLatex:Boolean(/\\\(.*\\\)/.exec(t))}}}for(let t of e.inlineChildren)if("object"!=typeof t);else if("boolean"==typeof t.stateValues.hasLatex&&"string"==typeof t.stateValues.value&&"string"==typeof t.stateValues.text){if(t.stateValues.hasLatex)return{setValue:{hasLatex:!0}}}else if("boolean"==typeof t.stateValues.renderAsMath&&"string"==typeof t.stateValues.latex&&"string"==typeof t.stateValues.text){if(t.stateValues.renderAsMath)return{setValue:{hasLatex:!0}}}else if("string"==typeof t.stateValues.latex)return{setValue:{hasLatex:!0}};return{setValue:{hasLatex:!1}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"latex",public:!0,shadowingInstructions:{createComponentOfType:"text"}},{variableName:"value",public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"hasLatex"}}}}],returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text","latex","value","hasLatex","renderAsMath"],variablesOptional:!0},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"},hasLatex:{dependencyType:"stateVariable",variableName:"hasLatex"}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length&&null!==e.valueShadow){let t=e.valueShadow,n=t;return e.hasLatex&&(n=n.replace(/\\\(/g,""),n=n.replace(/\\\)/g,"")),{setValue:{text:n,latex:n,value:t}}}let t="",n="";for(let r of e.inlineChildren)if("object"!=typeof r){let e=r.toString();t+=e,n+=e}else"boolean"==typeof r.stateValues.hasLatex&&"string"==typeof r.stateValues.value&&"string"==typeof r.stateValues.text?(t+=r.stateValues.text,n+=r.stateValues.value):"boolean"==typeof r.stateValues.renderAsMath&&"string"==typeof r.stateValues.latex&&"string"==typeof r.stateValues.text?r.stateValues.renderAsMath?(t+=r.stateValues.latex,n+="\\("+r.stateValues.latex+"\\)"):(t+=r.stateValues.text,n+=r.stateValues.text):"string"==typeof r.stateValues.latex?(t+=r.stateValues.latex,n+="\\("+r.stateValues.latex+"\\)"):"string"==typeof r.stateValues.text&&(t+=r.stateValues.text,n+=r.stateValues.text);return{setValue:{text:t,latex:t,value:n}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n;if("string"==typeof e.value)n=e.value;else if("string"==typeof e.text)n=e.text;else{if("string"!=typeof e.latex)return{success:!1};n=e.latex}if(0===t.inlineChildren.length&&null!==t.valueShadow)return{success:!0,instructions:[{setDependency:"valueShadow",desiredValue:n}]};if(1===t.inlineChildren.length){let n=t.inlineChildren[0],r=e.value;if("object"!=typeof n)return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0}]};if("boolean"==typeof n.stateValues.hasLatex&&"string"==typeof n.stateValues.value&&"string"==typeof n.stateValues.text)return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:2}]};if("boolean"==typeof n.stateValues.renderAsMath&&"string"==typeof n.stateValues.latex&&"string"==typeof n.stateValues.text){if(n.stateValues.renderAsMath){let e=r.match(/^\\\((.*)\\\)/);return e&&(r=e[1]),{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:1}]}}return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:0}]}}if("string"==typeof n.stateValues.latex){let e=r.match(/^\\\((.*)\\\)/);return e&&(r=e[1]),{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:1}]}}return"string"==typeof n.stateValues.text?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:0}]}:{success:!1}}return{success:!1}}},e.forObjectComponentName={returnDependencies:()=>({forObject:{dependencyType:"attributeTargetComponentNames",attributeName:"forObject"}}),definition({dependencyValues:e}){let t;return t=1===e.forObject?.length?e.forObject[0].absoluteName:null,{setValue:{forObjectComponentName:t}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}static adapters=["text"];async moveLabel({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}function returnGroupIntoComponentTypeSeparatedBySpaces({componentType:e,forceComponentType:t=!1}){return function({matchedChildren:n,componentInfoObjects:r}){let a=[],i=[];function s(){let n=!1;if(t){if(1===i.length){let t=i[0],s=t.componentType;"copy"===s&&t.attributes?.createComponentOfType&&(t.attributes.nComponents&&1!==t.attributes.nComponents.primitive||(s=t.attributes.createComponentOfType.primitive)),r.isInheritedComponentType({inheritedComponentType:s,baseComponentType:e})&&(a.push(t),n=!0)}}else 1===i.length&&"string"!=typeof i[0]&&(a.push(i[0]),n=!0);!n&&i.length>0&&a.push({componentType:e,children:i}),i=[]}for(let e of n)if("string"!=typeof e)i.push(e);else{let t=e.split(/\s+/),n=t[0];""===n?s():i.push(n);for(let e of t.slice(1))s(),""!==e&&i.push(e)}return s(),{success:!0,newChildren:a}}}function returnBreakStringsIntoComponentTypeBySpaces({componentType:e}){return function({matchedChildren:t}){let n=t.reduce((function(t,n){return"string"==typeof n?[...t,...n.split(/\s+/).filter((e=>e)).map((t=>({componentType:e,children:[t]})))]:[...t,n]}),[]);return{success:!0,newChildren:n}}}class MathList extends InlineComponent{static componentType="mathList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="maths";static primaryStateVariableForDefinition="mathsShadow";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.mergeMathLists={createComponentOfType:"boolean"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"math"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"math"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"mathLists",componentTypes:["mathList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{mathsShadow:!0}})},e.mergeMathLists={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({mergeMathListsAttr:{dependencyType:"attributeComponent",attributeName:"mergeMathLists",variableNames:["value"]},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],skipComponentNames:!0},mathChildren:{dependencyType:"child",childGroups:["maths"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{mergeMathLists:e.mergeMathListsAttr?.stateValues.value||0===e.mathListChildren.length&&1===e.mathChildren.length}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["mergeMathLists"],additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies({stateValues:e}){let t={maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}};return e.mergeMathLists?t.mathAndMathListChildren={dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["value","nComponents"],variablesOptional:!0}:(t.mathListChildren={dependencyType:"child",childGroups:["mathLists"],variableNames:["nComponents"]},t.mathAndMathListChildren={dependencyType:"child",childGroups:["maths","mathLists"],skipComponentNames:!0}),t},definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[];if(e.mathAndMathListChildren.length>0)if(e.mergeMathLists)for(let[a,i]of e.mathAndMathListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})){for(let e=0;ea&&(n=a,r=r.slice(0,a)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.maths={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["math"],stateVariablesDeterminingDependencies:["mergeMathLists","childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["value","math"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].mathAndMathListChildren[0];if(n)if(void 0!==n.stateValues.value){let t=n.stateValues.value;if(e.mergeMathLists&&Array.isArray(t.tree)&&"list"===t.tree[0]){let n=e.childIndexByArrayKey[a][1];r[a]=t.get_component(n)}else r[a]=t}else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["math"+t]}else null!==e.mathsShadow&&(r[a]=e.mathsShadow[a])}return{setValue:{maths:r}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,stateValues:a,workspace:i}){if(t.mergeMathLists){let t=[],s=await a.childIndexByArrayKey,o=[];for(let l in e.maths){if(!n[l])continue;if(o.includes(l))continue;let u;if(void 0!==s[l][2]){let t=Number(l)-s[l][1],n=t+s[l][2]-1;i.desiredMaths||(i.desiredMaths=[]);let r=["list"];for(let s=t;s<=n;s++)void 0!==e.maths[s]?i.desiredMaths[s]=convertValueToMathExpression(e.maths[s]):void 0===i.desiredMaths[s]&&(i.desiredMaths[s]=(await a.maths)[s]),r.push(i.desiredMaths[s].tree),o.push(s.toString());u=me$3.fromAst(r)}else u=e.maths[l];let c=n[l].mathAndMathListChildren[0];c&&(void 0!==c.stateValues.value?t.push({setDependency:r[l].mathAndMathListChildren,desiredValue:u,childIndex:0,variableIndex:0}):t.push({setDependency:r[l].mathAndMathListChildren,desiredValue:u,childIndex:0,variableIndex:1}))}return{success:!0,instructions:t}}let s=[];for(let t in e.maths){if(!n[t])continue;let a=n[t].mathAndMathListChildren[0];a&&(void 0!==a.stateValues.value?s.push({setDependency:r[t].mathAndMathListChildren,desiredValue:e.maths[t],childIndex:0,variableIndex:0}):s.push({setDependency:r[t].mathAndMathListChildren,desiredValue:e.maths[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:s}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({maths:{dependencyType:"stateVariable",variableName:"maths"}}),definition({dependencyValues:e}){let t;return t=0===e.maths.length?me$3.fromAst("_"):1===e.maths.length?e.maths[0]:me$3.fromAst(["list",...e.maths.map((e=>e.tree))]),{setValue:{math:t}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"maths"},e.latex={additionalStateVariablesDefined:["latexs"],public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["valueForDisplay","latex","latexs"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n=[],r={};if(e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.mathAndMathListChildren.length>0)for(let t of e.mathAndMathListChildren)if(t.stateValues.valueForDisplay){let a=t.stateValues.valueForDisplay;if(e.mergeMathLists&&Array.isArray(a.tree)&&"list"===a.tree[0])for(let e=0;eroundForDisplay({value:n,dependencyValues:e,usedDefault:t}).toLatex(r))));let a=e.maximumNumber;return null!==a&&n.length>a&&(a=Math.max(0,Math.floor(a)),n=n.slice(0,a)),{setValue:{latex:n.join(", "),latexs:n}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["valueForDisplay","text","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}}),definition:function({dependencyValues:e}){let t=[];if(e.mathAndMathListChildren.length>0)for(let n of e.mathAndMathListChildren)if(n.stateValues.valueForDisplay){let r=n.stateValues.valueForDisplay;if(e.mergeMathLists&&Array.isArray(r.tree)&&"list"===r.tree[0])for(let e=0;ee.toString())));let n=e.maximumNumber;return null!==n&&t.length>n&&(n=Math.max(0,Math.floor(n)),t=t.slice(0,n)),{setValue:{text:t.join(", "),texts:t}}}},e.componentNamesInList={returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.mathAndMathListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"mathList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],variableNames:["nComponents"]},mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.mathAndMathListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"mathList"})){let t=e.mathListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class Columns extends Text{static componentType="columns";static rendererType="text"}class Title extends TextOrInline{static componentType="title"}class RightHandSide extends MathComponent{static componentType="rightHandSide";static rendererType="math"}class Description extends TextOrInline{static componentType="description";static rendererType=void 0}class Else extends Template{static componentType="else"}class Xlabel extends Label{static componentType="xlabel";static rendererType="label"}class Ylabel extends Label{static componentType="ylabel";static rendererType="label"}class MatrixRow extends MathList{static componentType="matrixRow";static rendererType="mathList"}class MatrixColumn extends MathList{static componentType="matrixColumn";static rendererType="mathList"}var Aliases=Object.freeze({__proto__:null,Columns:Columns,Title:Title,RightHandSide:RightHandSide,Description:Description,Else:Else,Xlabel:Xlabel,Ylabel:Ylabel,MatrixRow:MatrixRow,MatrixColumn:MatrixColumn});class M$3 extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="m";static rendererType="math";static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="latex";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"inline",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"",hasEssential:!0,forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["latex","text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length)return{useEssentialOrDefaultValue:{latex:!0}};let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n:"string"==typeof n.stateValues.latex?t+=n.stateValues.latex:"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{latex:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.latex)return{success:!1};if(0===t.inlineChildren.length)return{success:!0,instructions:[{setEssentialValue:"latex",value:e.latex}]};if(1===t.inlineChildren.length){let n=t.inlineChildren[0];return"object"!=typeof n?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0}]}:"string"==typeof n.stateValues.latex?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0,variableIndex:0}]}:"string"==typeof n.stateValues.text?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0,variableIndex:1}]}:{success:!1}}return{success:!1}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["latex","text"],variablesOptional:!0},latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){if(0===e.inlineChildren.length)return{setValue:{latexWithInputChildren:[e.latex]}};let n=[],r="",a=0;for(let i of e.inlineChildren)"object"!=typeof i?r+=i:t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"input"})?(r.length>0&&(n.push(r),r=""),n.push(a),a++):"string"==typeof i.stateValues.latex?r+=i.stateValues.latex:"string"==typeof i.stateValues.text&&(r+=i.stateValues.text);return r.length>0&&n.push(r),{setValue:{latexWithInputChildren:n}}}},e.renderMode={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{renderMode:"inline"}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){let t;try{t=me$3.fromAst(latexToAst.convert(e.latex))}catch(t){return{setValue:{text:e.latex}}}return{setValue:{text:superSubscriptsToUnicode(t.toString())}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class Me$2 extends M$3{static componentType="me";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"display"}}),e}}class Men extends M$3{static componentType="men";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"numbered"}}),e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({equationCounter:{dependencyType:"counter",counterName:"equation"}}),definition:({dependencyValues:e})=>({setValue:{equationTag:String(e.equationCounter)}})},e}}var MMeMen=Object.freeze({__proto__:null,M:M$3,Me:Me$2,Men:Men});class Md extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="md";static rendererType="math";static primaryStateVariableForDefinition="latex";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"mrows",componentTypes:["mrow"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.mrowChildNames={forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"]}}),definition:({dependencyValues:e})=>({setValue:{mrowChildNames:e.mrowChildren.map((e=>e.componentName))}})},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"",hasEssential:!0,shadowVariable:!0,forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"],variableNames:["latex","hide","equationTag","numbered"]}}),definition:function({dependencyValues:e}){if(e.mrowChildren.length>0){let t="";for(let n of e.mrowChildren)n.stateValues.hide||(t.length>0&&(t+="\\\\"),n.stateValues.numbered?t+=`\\tag{${n.stateValues.equationTag}}`:t+="\\notag ",t+=n.stateValues.latex);return{setValue:{latex:t}}}return{useEssentialOrDefaultValue:{latex:!0}}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"],variableNames:["latexWithInputChildren","hide","equationTag","numbered"]},latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){if(e.mrowChildren.length>0){let t=[],n=0,r="";for(let a of e.mrowChildren)if(!a.stateValues.hide){r.length>0&&(r+="\\\\"),a.stateValues.numbered?r+=`\\tag{${a.stateValues.equationTag}}`:r+="\\notag ";for(let e of a.stateValues.latexWithInputChildren)"number"==typeof e?(r.length>0&&(t.push(r),r=""),t.push(n),n++):r+=e}return r.length>0&&t.push(r),{setValue:{latexWithInputChildren:t}}}return{setValue:{latexWithInputChildren:[e.latex]}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){let t;try{t=e.latex.replaceAll("\\notag","").replaceAll("\\amp","").split("\\\\").map((e=>me$3.fromAst(latexToAst.convert(e)).toString())).join("\\\\\n")}catch(t){return{setValue:{text:e.latex}}}return{setValue:{text:superSubscriptsToUnicode(t.toString())}}}},e.renderMode={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{renderMode:"align"}})},e.numbered={returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!1}})},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class Mdn extends Md{static componentType="mdn";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!0}})},e}}class Mrow extends M$3{static componentType="mrow";static createAttributesObject(){let e=super.createAttributesObject();return e.number={createComponentOfType:"boolean"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"display"}}),e.numbered={forRenderer:!0,returnDependencies:()=>({parentNumbered:{dependencyType:"parentStateVariable",variableName:"numbered"},numberAttr:{dependencyType:"attributeComponent",attributeName:"number",variableNames:["value"]}}),definition({dependencyValues:e}){let t;return t=null!==e.numberAttr?e.numberAttr.stateValues.value:e.parentNumbered,{setValue:{numbered:t}}}},e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["numbered"],returnDependencies:({stateValues:e})=>e.numbered?{equationCounter:{dependencyType:"counter",counterName:"equation"}}:{},definition:({dependencyValues:e})=>void 0!==e.equationCounter?{setValue:{equationTag:String(e.equationCounter)}}:{setValue:{equationTag:null}}},e}}var MdMdnMrow=Object.freeze({__proto__:null,Md:Md,Mdn:Mdn,Mrow:Mrow});function periodicSetEquality(e,t,{min_elements_match:n=3,match_partial:r=!1}={}){if(!is_periodic_set(e))return!1;if(is_periodic_set(t)){if(r){let n=contained_in(e.tree,t.tree,r);if(!1===n)return 0;let a=contained_in(t.tree,e.tree,r);return!1===a?0:!0===n?!0===a?1:a:!0===a?n:Math.min(n,a)}return contained_in(e.tree,t.tree,r)&&contained_in(t.tree,e.tree,r)}{let a=e.tree.slice(1);if(a.length>1)return!1;let i=me$3.fromAst(a[0][1]).evaluate_to_constant(),s=me$3.fromAst(["apply","abs",a[0][2]]).evaluate_to_constant();if(!Number.isFinite(i)||!Number.isFinite(s))return!1;let o=a[0][3],l=a[0][4];if(o!==-1/0||l!==1/0)return!1;if("list"!==t.tree[0])return!1;let u=t.tree.slice(1),c=0;if("ldots"===u[0][0])c++,u=u.slice(1);else if(!r)return!1;if("ldots"===u[u.length-1][0])c++,u=u.slice(0,u.length-1);else if(!r)return!1;let p=u.length;if(0===p)return!1;if(!r&&pme$3.fromAst(e).evaluate_to_constant())).map((e=>Number.isFinite(e)?e:NaN));let d=me$3.math.mod(u[0]-i,s);if(!(me$3.math.min(d,s-d)<1e-10*s))return!1;let m=1;for(let e=1;e=n)return!0;let h=m/Math.max(p,n);return h*=(9+c/2)/10,h}}function is_periodic_set(e){var t=e.tree;if(!Array.isArray(t))return!1;if("periodic_set"!==t[0])return!1;var n=t.slice(1);for(var r of n){if(!Array.isArray(r))return!1;if("tuple"!==r[0])return!1;if(5!==r.length)return!1}return!0}function contained_in(e,t,n){if("periodic_set"===e[0]){if(n){let r=0;for(let a of e.slice(1)){let e=contained_in(a,t,n);!0===e?r++:!1!==e&&(r+=e)}let a=e.length-1;return r===a||0!==r&&r/a}return e.slice(1).every((e=>contained_in(e,t)))}var r=e[1],a=e[2],i=e[3],s=e[4];if(i!==-1/0||s!==1/0)return!1;r=me$3.fromAst(["/",r,a]).evaluate_to_constant();var o=t.slice(1),l=[];for(let e=0;e1e3)return!1;let c=s.d;l.push([u,c,r,i])}for(l.sort();;){if(1!==l[0][0])break;let e=l[0][2],t=l[0][3],n=me$3.fromAst(["+",e,["-",r]]).evaluate_to_constant();if(Number.isFinite(n)&&Number.isFinite(t)&&(n=me$3.math.mod(n,t),me$3.math.min(n,t-n)<1e-10*t))return!0;if(l.splice(0,1),0===l.length)return!1}var u=[...new Set(l.map((e=>e[0])))];let c=0;for(let e of u){let t=l.map((function(t,n){let r=e/t[0];return Number.isInteger(r)?[t[0],r,n]:void 0})).filter((e=>e)),a=[];for(let n of t){let t=n[0],i=n[1],s=n[2],o=l[s][2],u=l[s][3];for(let n=0;nc&&(c=t)}}return!!(n&&c>0)&&c}const nonTupleVectorOperators=["vector","altvector"];function checkEquality({object1:e,object2:t,isUnordered:n=!1,partialMatches:r=!1,matchByExactPositions:a=!1,symbolicEquality:i=!1,simplify:s="none",expand:o=!1,allowedErrorInNumbers:l=0,includeErrorInNumberExponents:u=!1,allowedErrorIsAbsolute:c=!1,nSignErrorsMatched:p=0,nPeriodicSetMatchesRequired:d=3,caseInsensitiveMatch:m=!1,matchBlanks:h=!1}){let f=!1;if(e instanceof me$3.class){if(f=!0,!(t instanceof me$3.class)){if("number"!=typeof t&&"string"!=typeof t)return{fraction_equal:0};t=me$3.fromAst(t)}}else if(t instanceof me$3.class){if(f=!0,"number"!=typeof e&&"string"!=typeof e)return{fraction_equal:0};e=me$3.fromAst(e)}let y,g=function(e){return e instanceof me$3.class||(e=me$3.fromAst(e)),e=e.normalize_function_names().normalize_applied_functions(),m&&(e=me$3.fromAst(setStringsInTreeToLowerCase(e.tree))),"none"===s?l>0&&(e=e.constants_to_floats()):e="numberspreserveorder"===s?e.evaluate_numbers({max_digits:1/0,skip_ordering:!0}):"number"===s?e.evaluate_numbers({max_digits:1/0}):e.evaluate_numbers({max_digits:1/0,evaluate_functions:!0}),normalizeMathExpression({value:e,simplify:s,expand:o})};y=f?i?function(e,t){let n=g(e),r=g(t);if(p>0){r=JSON.parse(JSON.stringify(r),me$3.reviver);let e=function(e,t){return!e.variables().includes("_")&&!t.variables().includes("_")&&(e=g(e)).equalsViaSyntax(t,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})};return n.tree.im||r.tree.im?{fraction_equal:0}:{fraction_equal:me$3.equalSpecifiedSignErrors(r,n,{equalityFunction:e,n_sign_errors:p})?1:0}}if(n.variables().includes("_")||r.variables().includes("_"))return{fraction_equal:0};if(n.tree.im||r.tree.im)return{fraction_equal:0};return{fraction_equal:n.equalsViaSyntax(r,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})?1:0}}:function(e,t){let n=e,r=t;if(e instanceof me$3.class||(n=me$3.fromAst(e)),t instanceof me$3.class||(r=me$3.fromAst(t)),m&&(n=me$3.fromAst(setStringsInTreeToLowerCase(n.tree)),r=me$3.fromAst(setStringsInTreeToLowerCase(r.tree))),p>0){r=JSON.parse(JSON.stringify(r),me$3.reviver);let e=function(e,t){return e.equals(t,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})};return n.tree.im||r.tree.im?{fraction_equal:0}:{fraction_equal:me$3.equalSpecifiedSignErrors(r,n,{equalityFunction:e,n_sign_errors:p})?1:0}}if(n.tree.im||r.tree.im)return{fraction_equal:0};return{fraction_equal:n.equals(r,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})?1:0}}:(e,t)=>(m&&(e=convertStringsToLowerCase(e),t=convertStringsToLowerCase(t)),{fraction_equal:deepCompare(e,t)?1:0});let b=!1,v=!1;if(f){let i=e.tree[0],s=t.tree[0];if("periodic_set"===i||"periodic_set"===s){let n=e,a=t;"periodic_set"!==i&&(n=t,a=e);let s=periodicSetEquality(n,a,{match_partial:r,min_elements_match:d});return!0===s?{fraction_equal:1}:!1===s?{fraction_equal:0}:{fraction_equal:s}}if("list"===i)e=e.tree.slice(1),t="list"===s?t.tree.slice(1):[t.tree];else if("list"===s)t=t.tree.slice(1),e=[e.tree];else if(nonTupleVectorOperators.includes(i)){if(e=e.tree.slice(1),"interval"===s||"matrix"===s||"array"===s||"set"===s)return{fraction_equal:0};t=vectorOperators.includes(s)?t.tree.slice(1):[t.tree]}else if(nonTupleVectorOperators.includes(s)){if(t=t.tree.slice(1),"interval"===i||"matrix"===i||"array"===i||"set"===i)return{fraction_equal:0};e="tuple"===i?e.tree.slice(1):[e.tree]}else if("interval"===i){a=!0;let n=e.tree[2],r=n[1],i=n[2];if(e=e.tree[1].slice(1),"matrix"===s||"set"===s)return{fraction_equal:0};if("tuple"===s){let e=t.tree.slice(1);if(2!==e.length||!1!==r||!1!==i)return{fraction_equal:0};t=e}else if("array"===s){let e=t.tree.slice(1);if(2!==e.length||!0!==r||!0!==i)return{fraction_equal:0};t=e}else{if("interval"!==s)return{fraction_equal:0};{let e=t.tree[2];if(e[1]!==r||e[2]!==i)return{fraction_equal:0};t=t.tree[1].slice(1)}}}else if("interval"===s){a=!0;let n=t.tree[2],r=n[1],s=n[2];if(t=t.tree[1].slice(1),"matrix"===i||"set"===i)return{fraction_equal:0};if("tuple"===i){let t=e.tree.slice(1);if(2!==t.length||!1!==r||!1!==s)return{fraction_equal:0};e=t}else{if("array"!==i)return{fraction_equal:0};{let t=e.tree.slice(1);if(2!==t.length||!0!==r||!0!==s)return{fraction_equal:0};e=t}}}else if("matrix"===i){if("matrix"!==s)return{fraction_equal:0};e=convertMatrixToArrayOfTuples(e.tree.slice(1)),t=convertMatrixToArrayOfTuples(t.tree.slice(1)),a=!0,v=!0,b=!0}else{if("matrix"===s)return{fraction_equal:0};if("set"===i){let r=[];for(let t of e.tree.slice(1))r.some((e=>1===y(e,t).fraction_equal))||r.push(t);if(e=r,n=!0,"tuple"===s||"array"===s)return{fraction_equal:0};if("set"===s){r=[];for(let e of t.tree.slice(1))r.some((t=>1===y(t,e).fraction_equal))||r.push(e);t=r}else t=[t.tree]}else if("set"===s){let r=[];for(let e of t.tree.slice(1))r.some((t=>1===y(t,e).fraction_equal))||r.push(e);if(t=r,n=!0,"tuple"===i||"array"===i)return{fraction_equal:0};e=[e.tree]}else if("tuple"===i){if(e=e.tree.slice(1),"array"===s)return{fraction_equal:0};t="tuple"===s?t.tree.slice(1):[t.tree]}else if("tuple"===s){if(t=t.tree.slice(1),"array"===i)return{fraction_equal:0};e=[e.tree]}else if("array"===i)e=e.tree.slice(1),t="array"===s?t.tree.slice(1):[t.tree];else{if("array"!==s)return y(e.tree,t.tree);t=t.tree.slice(1),e=[e.tree]}}}else if(Array.isArray(e))Array.isArray(t)||(t="string"==typeof t&&e.every((e=>"string"==typeof e&&!e.includes(",")))?t.split(",").map((e=>e.trim())):[t]);else{if(!Array.isArray(t))return y(e,t);e="string"==typeof e&&t.every((e=>"string"==typeof e&&!e.includes(",")))?e.split(",").map((e=>e.trim())):[e]}let N=e.length,T=t.length,C={fraction_equal:0};if(a&&(n=!1),!n){let n=0,u=Math.min(N,T);for(let r=0;rArray(T+1).fill(0)));for(let n=0;nr&&(r=t.fraction_equal,e=a)}-1!==e&&(V+=r,A.add(e))}return N===T&&N===V?(C.fraction_equal=1,C):r?(C.fraction_equal=V/Math.max(N,T),C):C}function setStringsInTreeToLowerCase(e){return"string"==typeof e?e.toLowerCase():Array.isArray(e)?[e[0],...e.slice(1).map(setStringsInTreeToLowerCase)]:e}function convertStringsToLowerCase(e){return"string"==typeof e?e.toLowerCase():Array.isArray(e)?e.map(convertStringsToLowerCase):e}function convertMatrixToArrayOfTuples(e){let t=e[0][1],n=e[0][2];if(!Number.isInteger(t)||!Number.isInteger(n))return e;let r=[];for(let a=0;aevaluateLogic({logicTree:e,canOverrideUnorderedCompare:t,dependencyValues:n,valueOnInvalid:r});if(!Array.isArray(e)){if("string"==typeof e){let t=n.booleanChildrenByCode[e];if(t)return n.matchPartial&&void 0!==t.stateValues.fractionSatisfied?t.stateValues.fractionSatisfied:t.stateValues.value?1:0;{let t=n.mathChildrenByCode[e];if(t){let e=t.stateValues.value.simplify().evaluate_to_constant();return Number.isFinite(e)&&0!==e?1:0}{let t=n.numberChildrenByCode[e];if(t){let e=t.stateValues.value;return Number.isFinite(e)&&0!==e?1:0}if("true"===e.toLowerCase())return 1;if("false"===e.toLowerCase())return 0}}}else if("number"==typeof e)return 0===e?0:1;return console.warn("Invalid format for boolean condition"),r}let i=e[0],s=e.slice(1);if("not"===i)return 1!==s.length?(console.warn("Invalid format for boolean condition"),r):0===a(s[0])?1:0;if("and"===i)return n.matchPartial?s.reduce(((e,t)=>e+a(t)),0)/s.length:s.every((e=>1===a(e)))?1:0;if("or"===i)return n.matchPartial?s.reduce(((e,t)=>Math.max(a(t),e)),0):s.some((e=>1===a(e)))?1:0;let o=!1,l=!1,u=!1,c=!1;s.forEach((function(e){"string"==typeof e&&(e in n.mathChildrenByCode||e in n.mathListChildrenByCode||e in n.numberChildrenByCode||e in n.numberListChildrenByCode?o=!0:e in n.textChildrenByCode||e in n.textListChildrenByCode?l=!0:e in n.booleanChildrenByCode||e in n.booleanListChildrenByCode?u=!0:e in n.otherChildrenByCode&&(c=!0))}));let p,d=function(e){if("string"==typeof e){let t=n.mathChildrenByCode[e];return void 0!==t?t.stateValues.value.tree:(t=n.mathListChildrenByCode[e],void 0!==t?["list",...t.stateValues.maths.map((e=>e.tree))]:(t=n.numberChildrenByCode[e],void 0!==t?numberToMathExpression(t.stateValues.value).tree:(t=n.numberListChildrenByCode[e],void 0!==t?["list",...t.stateValues.numbers]:e)))}return Array.isArray(e)?[e[0],...e.slice(1).map(d)]:e};if("apply"===i&&["isnumber","isinteger"].includes(s[0])){if(l||u||c)return 0;let e=me$3.fromAst(d(s[1])).simplify().evaluate_to_constant();if(!Number.isFinite(e))return 0;if("isnumber"===s[0])return 1;{let t=Math.round(e);return Math.abs(t-e)<=1e-15*Math.abs(e)?1:0}}if(!["=","ne","<",">","le","ge","lts","gts","in","notin"].includes(i)){if(l||u||c)return console.warn("Invalid format for boolean condition"),r;let t=me$3.fromAst(d(e)).simplify().evaluate_to_constant();return Number.isFinite(t)&&0!==t?1:0}if(u){if(o||l||c)return console.warn("Invalid format for boolean condition"),r;let e=!1,a=!1;if(s=s.map((function(t){if("string"==typeof t){let i=n.booleanChildrenByCode[t];return void 0!==i?i.stateValues.value:(i=n.booleanListChildrenByCode[t],void 0!==i?(i.stateValues.unordered&&(a=!0),i.stateValues.booleans):"true"===(t=t.toLowerCase().trim())||"t"===t||"false"!==t&&"f"!==t&&(console.warn("Invalid format for boolean condition"),e=!0,r))}return console.warn("Invalid format for boolean condition"),e=!0,r})),e)return r;let u=n.unorderedCompare;if(t&&a&&(u=!0),"="===i){let e=s[0];if(n.matchPartial){let t=s.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return s.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}).fraction_equal))?1:0}if("ne"===i){if(2!==s.length)return console.warn("Invalid format for boolean condition"),r;return 0===checkEquality({object1:s[0],object2:s[1],isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}).fraction_equal?1:0}return console.warn("Invalid format for boolean condition"),r}if(l){if(o||c)return console.warn("Invalid format for boolean condition"),r;let e=!1,a=!1,l=function(t,r=!1){if("string"==typeof t){let e=n.textChildrenByCode[t];return void 0!==e?e.stateValues.value.trim().replace(/\s+/," "):(e=n.textListChildrenByCode[t],void 0!==e?(e.stateValues.unordered&&(a=!0),e.stateValues.texts.map((e=>e.trim().replace(/\s+/," ")))):t.trim())}return"number"==typeof t?t.toString():r&&Array.isArray(t)&&"*"===t[0]?t.slice(1).map(l).join(" "):(console.warn("Invalid format for boolean condition"),e=!0,"")};if(s=s.map((e=>l(e,!0))),e)return r;let u=n.unorderedCompare;if(t&&a&&(u=!0),"="===i){let e=s[0];if(n.matchPartial){let t=s.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return s.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}).fraction_equal))?1:0}if("ne"===i){if(2!==s.length)return console.warn("Invalid format for boolean condition"),0;return 0===checkEquality({object1:s[0],object2:s[1],isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}).fraction_equal?1:0}return console.warn("Invalid format for boolean condition"),r}if(c){if(o)return console.warn("Invalid format for boolean condition"),r;let e=!1;return s=s.map((function(t){if("string"==typeof t){let e=n.otherChildrenByCode[t];if(void 0!==e)return e.stateValues.value}return console.warn("Invalid format for boolean condition"),e=!0,null})),e?r:"="===i?s.slice(1).every((e=>deepCompare(e,s[0])))?1:0:"ne"===i?2!==s.length?(console.warn("Invalid format for boolean condition"),0):deepCompare(s[0],s[1])?0:1:(console.warn("Invalid format for boolean condition"),0)}"lts"!==i&&"gts"!==i||(p=s[1].slice(1),s=s[0].slice(1));let m=!1,h=function(e){if("string"==typeof e){let t=n.mathChildrenByCode[e];return void 0!==t?(t.stateValues.unordered&&(m=!0),t.stateValues.value.tree):(t=n.mathListChildrenByCode[e],void 0!==t?(t.stateValues.unordered&&(m=!0),["list",...t.stateValues.maths.map((e=>e.tree))]):(t=n.numberChildrenByCode[e],void 0!==t?numberToMathExpression(t.stateValues.value).tree:(t=n.numberListChildrenByCode[e],void 0!==t?(t.stateValues.unordered&&(m=!0),["list",...t.stateValues.numbers]):e)))}return Array.isArray(e)?[e[0],...e.slice(1).map(h)]:e},f=s.map((function(e){return me$3.fromAst(h(e))})),y=n.unorderedCompare;if(t&&m&&(y=!0),"="===i){let e=f[0];if(Number.isNaN(e.tree))return f.slice(1).every((e=>Number.isNaN(e.tree)))?1:0;if(n.matchPartial){let t=f.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return f.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal))?1:0}if("ne"===i){return 0===checkEquality({object1:f[0],object2:f[1],isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal?1:0}if("in"===i||"notin"===i){let e=f[0],t=f[1].tree;if(!Array.isArray(t)||"set"!==t[0])return console.warn("Invalid format for boolean condition"),r;if(n.matchPartial){let r=t.slice(1).map((t=>checkEquality({object1:e,object2:me$3.fromAst(t),isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}))),a=r.reduce(((e,t)=>Math.max(e,t.fraction_equal)),0);return"in"===i?a:1-a}{let r=t.slice(1).some((t=>1===checkEquality({object1:e,object2:me$3.fromAst(t),isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal));return"in"===i?r?1:0:r?0:1}}let g=f.map((e=>e.simplify().evaluate_to_constant()));if(g.some((e=>null===e||Number.isNaN(e))))return 0;if("<"===i)return g[0]"===i)return g[0]>g[1]?1:0;if("le"===i)return g[0]<=g[1]?1:0;if("ge"===i)return g[0]>=g[1]?1:0;for(let e=0;eg[e+1]))return 0}else if(!(g[e]>=g[e+1]))return 0;return 1}function splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n=!1,init:r=!0}){if(!Array.isArray(e))return"string"!=typeof e||n||r?e:fromTextSplit(e).tree;let a=e[0],i=e.slice(1);if(["and","not","or"].includes(a))return"apply"===a?[a,i[0],...i.slice(1).map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:r})))]:[a,...i.map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:r})))];if(i.some((e=>t.includes(e)))&&(n=!0),"apply"===a)return[a,i[0],...i.slice(1).map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:!1})))];if("angle"===a){let e=[];for(let r of i)if("string"!=typeof r||n)e.push(splitSymbolsIfMath({logicTree:r,nonMathCodes:t,foundNonMath:n,init:!1}));else{let t=fromTextSplit(r).tree;"*"===t[0]?e.push(...t.slice(1)):e.push(t)}return[a,...e]}return[a,...i.map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:!1})))]}class BooleanComponent extends InlineComponent{static componentType="boolean";static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!0;static descendantCompositesDefaultReplacementType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.symbolicEquality={createComponentOfType:"boolean",createStateVariable:"symbolicEquality",defaultValue:!1,public:!0},e.expandOnCompare={createComponentOfType:"boolean",createStateVariable:"expandOnCompare",defaultValue:!1,public:!0},e.simplifyOnCompare={createComponentOfType:"text",createStateVariable:"simplifyOnCompare",defaultValue:"none",toLowerCase:!0,valueTransformations:{"":"full",true:"full"},validValues:["none","full","numbers","numbersepreserveorder"],public:!0},e.unorderedCompare={createComponentOfType:"boolean",createStateVariable:"unorderedCompare",defaultValue:!1,public:!0},e.matchByExactPositions={createComponentOfType:"boolean",createStateVariable:"matchByExactPositions",defaultValue:!1,public:!0},e.allowedErrorInNumbers={createComponentOfType:"number",createStateVariable:"allowedErrorInNumbers",defaultValue:0,public:!0},e.includeErrorInNumberExponents={createComponentOfType:"boolean",createStateVariable:"includeErrorInNumberExponents",defaultValue:!1,public:!0},e.allowedErrorIsAbsolute={createComponentOfType:"boolean",createStateVariable:"allowedErrorIsAbsolute",defaultValue:!1,public:!0},e.nSignErrorsMatched={createComponentOfType:"number",createStateVariable:"nSignErrorsMatched",defaultValue:0,public:!0},e.nPeriodicSetMatchesRequired={createComponentOfType:"integer",createStateVariable:"nPeriodicSetMatchesRequired",defaultValue:3,public:!0},e.caseInsensitiveMatch={createComponentOfType:"boolean",createStateVariable:"caseInsensitiveMatch",defaultValue:!1,public:!0},e.matchBlanks={createComponentOfType:"boolean",createStateVariable:"matchBlanks",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"comparableTypes",componentTypes:["math","mathList","number","numberList","text","textList","boolean","booleanList","orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.parsedExpression={additionalStateVariablesDefined:["codePre"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]}}),definition:buildParsedExpression},e.mathChildrenByCode={additionalStateVariablesDefined:["mathListChildrenByCode","numberChildrenByCode","numberListChildrenByCode","textChildrenByCode","textListChildrenByCode","booleanChildrenByCode","booleanListChildrenByCode","otherChildrenByCode"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"],variableNames:["value","texts","maths","numbers","booleans","fractionSatisfied","unordered"],variablesOptional:!0},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n={},r={},a={},i={},s={},o={},l={},u={},c={},p=0,d=e.codePre;for(let m of e.allChildren)if("string"!=typeof m){let e=d+p;t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"math"})?n[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"mathList"})?r[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"number"})?a[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"numberList"})?i[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"text"})?s[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"textList"})?o[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"boolean"})?l[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"booleanList"})?u[e]=m:c[e]=m,p+=1}return{setValue:{mathChildrenByCode:n,mathListChildrenByCode:r,numberChildrenByCode:a,numberListChildrenByCode:i,textChildrenByCode:s,textListChildrenByCode:o,booleanChildrenByCode:l,booleanListChildrenByCode:u,otherChildrenByCode:c}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean",attributesToShadow:["fixed"]},forRenderer:!0,hasEssential:!0,defaultValue:!1,set:Boolean,returnDependencies:()=>({symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"],variableNames:["value"],variablesOptional:!0},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},booleanListChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanListChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},textListChildrenByCode:{dependencyType:"stateVariable",variableName:"textListChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},mathListChildrenByCode:{dependencyType:"stateVariable",variableName:"mathListChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},numberListChildrenByCode:{dependencyType:"stateVariable",variableName:"numberListChildrenByCode"},otherChildrenByCode:{dependencyType:"stateVariable",variableName:"otherChildrenByCode"}}),definition({dependencyValues:e,usedDefault:t}){if(0===e.allChildren.length)return{useEssentialOrDefaultValue:{value:!0}};if(null===e.parsedExpression)return{setValue:{value:!1}};let n=t.unorderedCompare;return{setValue:{value:1===evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:n,dependencyValues:e})}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentInfoObjects:n}){if(0===t.allChildren.length)return{success:!0,instructions:[{setEssentialValue:"value",value:Boolean(e.value)}]};if(1===t.allChildren.length){let r=t.allChildren[0];if("string"==typeof r)return{success:!0,instructions:[{setDependency:"allChildren",desiredValue:e.value.toString(),childIndex:0,variableIndex:0}]};if(n.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"boolean"}))return{success:!0,instructions:[{setDependency:"allChildren",desiredValue:e.value,childIndex:0,variableIndex:0}]}}return{success:!1}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value?"true":"false"}}},inverseDefinition({desiredStateVariableValues:e}){let t,n=String(e.text).toLowerCase();return"true"===n?t=!0:"false"===n&&(t=!1),void 0!==t?{success:!0,instructions:[{setDependency:"value",desiredValue:t}]}:{success:!1}}},e}static adapters=["text"]}class BooleanOperator extends BooleanComponent{static componentType="_booleanOperator";static rendererType="boolean";static descendantCompositesMustHaveAReplacement=!1;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:"boolean",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"booleans",componentTypes:["boolean"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();delete e.parsedExpression,delete e.mathChildrenByCode;let t=this;return e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({booleanChildren:{dependencyType:"child",childGroups:["booleans"],variableNames:["value"]}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyBooleanOperator(e.booleanChildren.map((e=>e.stateValues.value)))}}}},e}}class BooleanOperatorOneInput extends BooleanComponent{static componentType="_booleanOperatorOneInput";static rendererType="boolean";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePreOperator"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"valuePreOperator"}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyBooleanOperator(e.value)}}}},e}}class Not extends BooleanOperatorOneInput{static componentType="not";static applyBooleanOperator(e){return!e}}class And extends BooleanOperator{static componentType="and";static applyBooleanOperator(e){return e.every((e=>e))}}class Or$1 extends BooleanOperator{static componentType="or";static applyBooleanOperator(e){return e.some((e=>e))}}class Xor extends BooleanOperator{static componentType="xor";static applyBooleanOperator(e){return 1===e.reduce(((e,t)=>e+t),0)}}var BooleanOperators=Object.freeze({__proto__:null,Not:Not,And:And,Or:Or$1,Xor:Xor});class BooleanBaseOperatorOfMath extends BooleanComponent{static componentType="_booleanOperatorOfMath";static rendererType="boolean";static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){return e.every((e=>"string"==typeof e||e.doenetAttributes&&e.doenetAttributes.createdFromMacro))?1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}:{success:!1}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.parsedExpression,delete e.mathChildrenByCode,e.booleanOperator={returnDependencies:()=>({}),definition:()=>({setValue:{booleanOperator:e=>!1}})},e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},booleanOperator:{dependencyType:"stateVariable",variableName:"booleanOperator"}}),definition:function({dependencyValues:e}){return{setValue:{value:e.booleanOperator(e.mathChildren.map((e=>e.stateValues.value)))}}}},e}}class IsInteger extends BooleanBaseOperatorOfMath{static componentType="isInteger";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator.definition=()=>({setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsInteger requires exactly one math child"),null;let t=e[0].evaluate_to_constant();if(!Number.isFinite(t))return!1;let n=Math.round(t);return Math.abs(n-t)<=1e-15*Math.abs(t)}}}),e}}class IsNumber extends BooleanBaseOperatorOfMath{static componentType="isNumber";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator.definition=()=>({setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsNumber requires exactly one math child"),null;let t=e[0].evaluate_to_constant();return Number.isFinite(t)}}}),e}}class IsBetween extends BooleanBaseOperatorOfMath{static componentType="isBetween";static createAttributesObject(){let e=super.createAttributesObject();return e.limits={createComponentOfType:"numberList",createStateVariable:"limits",defaultValue:[],public:!0},e.strict={createComponentOfType:"boolean",createStateVariable:"strict",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator={returnDependencies:()=>({limits:{dependencyType:"stateVariable",variableName:"limits"},strict:{dependencyType:"stateVariable",variableName:"strict"}}),definition({dependencyValues:e}){let t,n,r=e.limits[0],a=e.limits[1];if(r!1}};n=a,t=r}let i=e.strict;return{setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsBetween requires exactly one math child"),null;let r=e[0].evaluate_to_constant();return i?r>n&&r=n&&r<=t}}}}},e}}var BooleanOperatorsOfMath=Object.freeze({__proto__:null,IsInteger:IsInteger,IsNumber:IsNumber,IsBetween:IsBetween});class MathOperator extends MathComponent{static componentType="_mathOperator";static rendererType="math";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.forceSymbolic={createComponentOfType:"boolean",createStateVariable:"forceSymbolic",defaultValue:!1,public:!0},e.forceNumeric={createComponentOfType:"boolean",createStateVariable:"forceNumeric",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:Number.isFinite(Number(e))?"number":"math",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"numbers",componentTypes:["number"]},{group:"mathLists",componentTypes:["mathList"]},{group:"numberLists",componentTypes:["numberList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displayDigits"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDigitsAttr?{setValue:{displayDigits:e.displayDigitsAttr.stateValues.value}}:null!==e.displayDecimalsAttr||1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displayDigits?{useEssentialOrDefaultValue:{displayDigits:!0}}:{setValue:{displayDigits:e.mathLikeChildren[0].stateValues.displayDigits}}},e.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:null,returnDependencies:()=>({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displayDecimals?{useEssentialOrDefaultValue:{displayDecimals:!0}}:{setValue:{displayDecimals:e.mathLikeChildren[0].stateValues.displayDecimals}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displaySmallAsZero?{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}:{setValue:{displaySmallAsZero:e.mathLikeChildren[0].stateValues.displaySmallAsZero}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].padZeros?{useEssentialOrDefaultValue:{padZeros:!0}}:{setValue:{padZeros:e.mathLikeChildren[0].stateValues.padZeros}}},e.isNumericOperator={returnDependencies:()=>({forceNumeric:{dependencyType:"stateVariable",variableName:"forceNumeric"},forceSymbolic:{dependencyType:"stateVariable",variableName:"forceSymbolic"},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["isNumber"],variablesOptional:!0},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],variableNames:["maths"]}}),definition({dependencyValues:e}){let t;return t=!!e.forceNumeric||!e.forceSymbolic&&(0===e.mathChildren.length&&0===e.mathListChildren.length||e.mathChildren.every((e=>e.stateValues.isNumber))&&e.mathListChildren.every((e=>e.stateValues.maths.every((e=>Number.isFinite(e.tree)))))),{setValue:{isNumericOperator:t}}}},delete e.codePre,delete e.expressionWithCodes,delete e.mathChildrenFunctionSymbols,delete e.codesAdjacentToStrings,delete e.mathChildrenByVectorComponent,e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:e=>me$3.fromAst("_")}})},e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:e=>me$3.fromAst("_")}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:null}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:null}})},e.unnormalizedValue={returnDependencies:()=>({mathNumberChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["value","maths","numbers","canBeModified"],variablesOptional:!0},isNumericOperator:{dependencyType:"stateVariable",variableName:"isNumericOperator"},mathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},numericOperator:{dependencyType:"stateVariable",variableName:"numericOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"inverseMathOperator"},inverseNumericOperator:{dependencyType:"stateVariable",variableName:"inverseNumericOperator"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){if(0===e.mathNumberChildren.length)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};if(e.isNumericOperator){let n=[];for(let r of e.mathNumberChildren)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"}))n.push(r.stateValues.value);else if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"math"})){let e=r.stateValues.value.evaluate_to_constant();Number.isFinite(e)||(e=NaN),n.push(e)}else if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"}))n.push(...r.stateValues.numbers);else{let e=r.stateValues.maths.map((e=>{let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}));n.push(...e)}return{setValue:{unnormalizedValue:me$3.fromAst(e.numericOperator(n))}}}{let n=[];for(let r of e.mathNumberChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"})?n.push(me$3.fromAst(r.stateValues.value)):t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"math"})?n.push(r.stateValues.value):t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"})?n.push(...r.stateValues.numbers.map((e=>me$3.fromAst(e)))):n.push(...r.stateValues.maths);return{setValue:{unnormalizedValue:e.mathOperator(n)}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentInfoObjects:n}){if(0===t.mathNumberChildren.length)return{success:!1};if(t.isNumericOperator){if(t.inverseNumericOperator){let r=[],a=[],i=[];for(let[e,s]of t.mathNumberChildren.entries())if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"number"}))r.push(s.stateValues.value),a.push(s.stateValues.canBeModified),i.push(e);else if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"math"})){let t=s.stateValues.value.evaluate_to_constant();Number.isFinite(t)||(t=NaN),r.push(t),a.push(s.stateValues.canBeModified),i.push(e)}else if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"}))r.push(...s.stateValues.numbers),a.push(...Array(s.stateValues.numbers.length).fill(s.stateValues.canBeModified)),1===s.stateValues.numbers.length?i.push(e):i.push(...Array(s.stateValues.numbers.length).fill(NaN));else{let t=s.stateValues.maths.map((e=>{let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}));r.push(...t),a.push(...Array(s.stateValues.maths.length).fill(s.stateValues.canBeModified)),1===s.stateValues.maths.length?i.push(e):i.push(...Array(s.stateValues.maths.length).fill(NaN))}let s=t.inverseNumericOperator({desiredValue:e.unnormalizedValue.evaluate_to_constant(),inputs:r,canBeModified:a,desiredMathValue:e.unnormalizedValue});if(s.success){let e=i[s.inputNumber];if(Number.isFinite(e)){let r=s.inputValue,a=0,i=t.mathNumberChildren[e];return n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"numberList"})?(a=2,r={0:r}):n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})&&(a=1,r={0:r}),{success:!0,instructions:[{setDependency:"mathNumberChildren",desiredValue:r,childIndex:e,variableIndex:a}]}}return{success:!1}}return{success:!1}}return{success:!1}}if(t.inverseMathOperator){let r=[],a=[],i=[];for(let[e,s]of t.mathNumberChildren.entries())n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"number"})?(r.push(me$3.fromAst(s.stateValues.value)),a.push(s.stateValues.canBeModified),i.push(e)):n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"math"})?(r.push(s.stateValues.value),a.push(s.stateValues.canBeModified),i.push(e)):n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"})?(r.push(...s.stateValues.numbers.map((e=>me$3.fromAst(e)))),a.push(...Array(s.stateValues.numbers.length).fill(s.stateValues.canBeModified)),1===s.stateValues.numbers.length?i.push(e):i.push(...Array(s.stateValues.numbers.length).fill(NaN))):(r.push(...s.stateValues.maths),a.push(...Array(s.stateValues.maths.length).fill(s.stateValues.canBeModified)),1===s.stateValues.maths.length?i.push(e):i.push(...Array(s.stateValues.maths.length).fill(NaN)));let s=t.inverseMathOperator({desiredValue:e.unnormalizedValue,inputs:r,canBeModified:a});if(s.success){let e=i[s.inputNumber];if(Number.isFinite(e)){let r=s.inputValue,a=0,i=t.mathNumberChildren[e];return n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"numberList"})?(a=2,r={0:r}):n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})&&(a=1,r={0:r}),{success:!0,instructions:[{setDependency:"mathNumberChildren",desiredValue:r,childIndex:e,variableIndex:a}]}}return{success:!1}}return{success:!1}}return{success:!1}}},e.canBeModified={returnDependencies:()=>({modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},mathNumberChildren:{dependencyType:"child",childGroups:["maths","numbers"],variableNames:["canBeModified"]},mathNumberListChildren:{dependencyType:"child",childGroups:["mathLists","numberLists"],variableNames:["nComponents"]},isNumericOperator:{dependencyType:"stateVariable",variableName:"isNumericOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},inverseNumericOperator:{dependencyType:"stateVariable",variableName:"inverseNumericOperator"}}),definition:function({dependencyValues:e}){let t=e.modifyIndirectly&&!e.fixed&&Boolean(e.isNumericOperator?e.inverseNumericOperator:e.inverseMathOperator);if(t&&e.mathNumberChildren.length+e.mathNumberListChildren.length>0){let n=e.mathNumberChildren.filter((e=>e.stateValues.canBeModified)).length+e.mathNumberListChildren.reduce(((e,t)=>e+t.stateValues.nComponents),0);1!==n&&(t=!1)}return{setValue:{canBeModified:t}}}},e}}class MathOperatorOneInput extends MathComponent{static componentType="_mathOperatorOneInput";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:e=>me.fromAst("_")}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:null}})},renameStateVariable({stateVariableDefinitions:e,oldName:"unnormalizedValue",newName:"unnormalizedValuePreOperator"}),e.unnormalizedValue={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"unnormalizedValuePreOperator"},mathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"inverseMathOperator"}}),definition:function({dependencyValues:e}){return{setValue:{unnormalizedValue:e.mathOperator(e.value)}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentName:n}){if(t.inverseMathOperator){return{success:!0,instructions:[{setDependency:"value",desiredValue:t.inverseMathOperator(e.unnormalizedValue)}]}}return{success:!1}}},renameStateVariable({stateVariableDefinitions:e,oldName:"canBeModified",newName:"canBeModifiedPreOperator"}),e.canBeModified={returnDependencies:()=>({canBeModifiedPreOperator:{dependencyType:"stateVariable",variableName:"canBeModifiedPreOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"}}),definition:function({dependencyValues:e}){let t=e.canBeModifiedPreOperator;return e.inverseMathOperator||(t=!1),{setValue:{canBeModified:t}}}},e}}class Sum extends MathOperator{static componentType="sum";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>e+t))}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.add(t)))}}})},e}}class Product extends MathOperator{static componentType="product";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>e*t))}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.multiply(t)))}}})},e}}class ClampNumber extends MathOperatorOneInput{static componentType="clampNumber";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.mathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return clamp({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e.inverseMathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{inverseMathOperator:function(t){return clamp({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e}}function clamp({value:e,lowerValue:t,upperValue:n}){let r=e;return r instanceof me$3.class&&(r=r.evaluate_to_constant()),Number.isFinite(r)?me$3.fromAst(Math.max(t,Math.min(n,r))):me$3.fromAst(NaN)}class WrapNumberPeriodic extends MathOperatorOneInput{static componentType="wrapNumberPeriodic";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.mathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return makePeriodic({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e.inverseMathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{inverseMathOperator:function(t){return makePeriodic({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e}}function makePeriodic({value:e,lowerValue:t,upperValue:n}){let r=e;return r instanceof me$3.class&&(r=r.evaluate_to_constant()),Number.isFinite(r)?t===n?me$3.fromAst(t):(t>n&&([n,t]=[t,n]),me$3.fromAst(t+me$3.math.mod(r-t,n-t))):me$3.fromAst(NaN)}class Round extends MathOperatorOneInput{static componentType="round";static createAttributesObject(){let e=super.createAttributesObject();return e.numberDecimals={createComponentOfType:"number",createStateVariable:"numberDecimals",defaultValue:0,public:!0},e.numberDigits={createComponentOfType:"number",createStateVariable:"numberDigits",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({numberDecimals:{dependencyType:"stateVariable",variableName:"numberDecimals"},numberDigits:{dependencyType:"stateVariable",variableName:"numberDigits"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){let n=t.evaluate_numbers({max_digits:1/0,evaluate_functions:!0});return null!==e.numberDigits?n.round_numbers_to_precision(e.numberDigits):n.round_numbers_to_decimals(e.numberDecimals)}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class setSmallToZero extends MathOperatorOneInput{static componentType="setSmallToZero";static createAttributesObject(){let e=super.createAttributesObject();return e.threshold={createComponentOfType:"number",createStateVariable:"threshold",defaultValue:1e-14,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({threshold:{dependencyType:"stateVariable",variableName:"threshold"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return t.evaluate_numbers({skip_ordering:!0,set_small_zero:e.threshold})}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class ConvertSetToList extends MathOperatorOneInput{static componentType="convertSetToList";static createAttributesObject(){let e=super.createAttributesObject();return delete e.unordered,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.unordered={returnDependencies:()=>({}),definition:()=>({setValue:{unordered:!0}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){if(void 0!==e&&Array.isArray(e.tree)&&"set"===e.tree[0]){let t=[];for(let n of e.tree.slice(1))t.some((t=>e.context.equalsViaSyntax(e.context.fromAst(t),e.context.fromAst(n))))||t.push(n);return e.context.fromAst(["list",...t])}return e}}})},e}}class Ceil extends MathOperatorOneInput{static componentType="ceil";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();if(!Number.isFinite(t))return me$3.fromAst(["apply","ceil",e.tree]);let n=Math.round(t);return Math.abs((n-t)/t)<1e-15?me$3.fromAst(n):me$3.fromAst(Math.ceil(t))}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class Floor extends MathOperatorOneInput{static componentType="floor";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();if(!Number.isFinite(t))return me$3.fromAst(["apply","floor",e.tree]);let n=Math.round(t);return Math.abs((n-t)/t)<1e-15?me$3.fromAst(n):me$3.fromAst(Math.floor(t))}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class Abs extends MathOperatorOneInput{static componentType="abs";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();return Number.isFinite(t)?me$3.fromAst(Math.abs(t)):me$3.fromAst(["apply","abs",e.tree])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function(e){let t=e,n=e.evaluate_to_constant();return Number.isFinite(n)?n<0&&(t=me$3.fromAst(0)):Array.isArray(e.tree)&&"apply"===e.tree[0]&&"abs"===e.tree[1]&&(t=me$3.fromAst(e.tree[2])),t}}})},e}}class Sign extends MathOperatorOneInput{static componentType="sign";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();return Number.isFinite(t)?me$3.fromAst(Math.sign(t)):me$3.fromAst(["apply","sign",e.tree])}}})},e}}class Mean extends MathOperator{static componentType="mean";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){let t=e.reduce(((e,t)=>e+t));return t/=e.length,t}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.add(t))).divide(e.length)}}})},e}}class Variance extends MathOperator{static componentType="variance";static createAttributesObject(){let e=super.createAttributesObject();return e.population={createComponentOfType:"boolean",createStateVariable:"population",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({population:{dependencyType:"stateVariable",variableName:"population"}}),definition:({dependencyValues:e})=>({setValue:{numericOperator:function(t){return calculateNumericVariance(t,e.population)}}})},e.mathOperator={returnDependencies:()=>({population:{dependencyType:"stateVariable",variableName:"population"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return calculateSymbolicVariance(t,e.population)}}})},e}}function calculateNumericVariance(e,t){let n=0,r=0;for(let t of e)n+=t,r+=t*t;let a=e.length;return r-=n**2/a,r/=t?a:a-1,r}function calculateSymbolicVariance(e,t){let n=e.length,r=e.reduce(((e,t)=>e.add(t))),a=e.slice(1).reduce(((e,t)=>e.add(t.pow(2))),e[0].pow(2)).subtract(r.pow(2).divide(n));return a=t?a.divide(n):a.divide(n-1),a}class StandardDeviation extends Variance{static componentType="standardDeviation";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator.definition=({dependencyValues:e})=>({setValue:{numericOperator:function(t){return Math.sqrt(calculateNumericVariance(t,e.population))}}}),e.mathOperator.definition=({dependencyValues:e})=>({setValue:{mathOperator:function(t){return me$3.fromAst(["apply","sqrt",calculateSymbolicVariance(t,e.population).tree])}}}),e}}class Count extends MathOperator{static componentType="count";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.length}}})},e}}class Min extends MathOperator{static componentType="min";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>Math.min(e,t)),1/0)}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","min",["tuple",...e.map((e=>e.tree))]])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function({desiredValue:e,canBeModified:t}){if(1===t.filter((e=>e)).length){let n=t.indexOf(!0);if(n>=0)return{success:!0,inputValue:e,inputNumber:n}}return{success:!1}}}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:function({desiredValue:e,canBeModified:t,desiredMathValue:n}){if(1===t.filter((e=>e)).length){let r=t.indexOf(!0);if(r>=0)return Number.isFinite(e)||(e=n),{success:!0,inputValue:e,inputNumber:r}}return{success:!1}}}})},e}}class Max extends MathOperator{static componentType="max";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>Math.max(e,t)),-1/0)}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","max",["tuple",...e.map((e=>e.tree))]])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function({desiredValue:e,canBeModified:t}){if(1===t.filter((e=>e)).length){let n=t.indexOf(!0);if(n>=0)return{success:!0,inputValue:e,inputNumber:n}}return{success:!1}}}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:function({desiredValue:e,canBeModified:t,desiredMathValue:n}){if(1===t.filter((e=>e)).length){let r=t.indexOf(!0);if(r>=0)return Number.isFinite(e)||(e=n),{success:!0,inputValue:e,inputNumber:r}}return{success:!1}}}})},e}}class Mod extends MathOperator{static componentType="mod";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return 2!==e.length?NaN:me$3.math.mod(e[0],e[1])}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return 2!==e.length?me$3.fromAst("_"):me$3.fromAst(["apply","mod",["tuple",...e.map((e=>e.tree))]])}}})},e}}class Gcd extends MathOperator{static componentType="gcd";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.every(Number.isInteger)?gcd(...e):NaN}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","gcd",["tuple",...e.map((e=>e.tree))]])}}})},e}}class ExtractMath extends MathOperatorOneInput{static componentType="extractMath";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createComponentOfType:"text",createStateVariable:"type",defaultValue:null,toLowerCase:!0,validValues:["operand","function","functionargument","numberofoperands"]},e.operandNumber={createComponentOfType:"number",createStateVariable:"operandNumber",defaultValue:null,public:!0},e.argumentNumber={createComponentOfType:"number",createStateVariable:"argumentNumber",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},operandNumber:{dependencyType:"stateVariable",variableName:"operandNumber"},argumentNumber:{dependencyType:"stateVariable",variableName:"argumentNumber"}}),definition:({dependencyValues:e})=>"operand"===e.type?null===e.operandNumber?(console.warn("Must specify a operandNumber when extracting a math operand"),{setValue:{mathOperator:e=>me$3.fromAst("_")}}):{setValue:{mathOperator:function(t){let n=t.tree;if(!Array.isArray(n))return 1===e.operandNumber?t:me$3.fromAst("_");if("apply"===n[0])return 1===e.operandNumber?t:me$3.fromAst("_");let r=n[e.operandNumber];return void 0===r?me$3.fromAst("_"):me$3.fromAst(r)}}}:"function"===e.type?{setValue:{mathOperator:function(e){let t=e.tree;return Array.isArray(t)?"apply"!==t[0]?me$3.fromAst("_"):me$3.fromAst(t[1]):me$3.fromAst("_")}}}:"functionargument"===e.type?{setValue:{mathOperator:function(t){let n=t.tree;if(!Array.isArray(n))return me$3.fromAst("_");if("apply"!==n[0])return me$3.fromAst("_");let r=n[2];if(null===e.argumentNumber)return me$3.fromAst(r);if(1===e.argumentNumber)return Array.isArray(r)&&"tuple"===r[0]?me$3.fromAst(r[1]):me$3.fromAst(r);if(Array.isArray(r)&&"tuple"===r[0]){let t=r[e.argumentNumber];return void 0===t?me$3.fromAst("_"):me$3.fromAst(t)}return me$3.fromAst("_")}}}:"numberofoperands"===e.type?{setValue:{mathOperator:function(e){let t=e.tree;return Array.isArray(t)?"apply"===t[0]?me$3.fromAst(1):me$3.fromAst(t.length-1):me$3.fromAst(1)}}}:{setValue:{mathOperator:e=>me$3.fromAst("_")}}},e}}function gcd(e,t,...n){return!t&&n.length>0?gcd(e,...n):t?gcd(t,e%t,...n):e}var MathOperators=Object.freeze({__proto__:null,Sum:Sum,Product:Product,ClampNumber:ClampNumber,WrapNumberPeriodic:WrapNumberPeriodic,Round:Round,setSmallToZero:setSmallToZero,ConvertSetToList:ConvertSetToList,Ceil:Ceil,Floor:Floor,Abs:Abs,Sign:Sign,Mean:Mean,Variance:Variance,StandardDeviation:StandardDeviation,Count:Count,Min:Min,Max:Max,Mod:Mod,Gcd:Gcd,ExtractMath:ExtractMath});function returnLabelStateVariableDefinitions(){let e={};return e.componentNameAndShadowSourceNames={returnDependencies:()=>({shadowSource:{dependencyType:"shadowSource",variableNames:["componentNameAndShadowSourceNames"]},unlinkedCopySource:{dependencyType:"unlinkedCopySource",variableNames:["componentNameAndShadowSourceNames"]}}),definition({dependencyValues:e,componentName:t}){let n=[t];return e.shadowSource?.stateValues.componentNameAndShadowSourceNames?n.push(...e.shadowSource.stateValues.componentNameAndShadowSourceNames):e.unlinkedCopySource?.stateValues.componentNameAndShadowSourceNames&&n.push(...e.unlinkedCopySource.stateValues.componentNameAndShadowSourceNames),{setValue:{componentNameAndShadowSourceNames:n}}}},e.label={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"labelHasLatex"}}},hasEssential:!0,doNotShadowEssential:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,additionalStateVariablesDefined:[{variableName:"labelHasLatex",forRenderer:!0}],returnDependencies:()=>({labelChild:{dependencyType:"child",childGroups:["labels"],variableNames:["value","hasLatex"]},labelIsName:{dependencyType:"stateVariable",variableName:"labelIsName"},labelIsNameAttr:{dependencyType:"attributeComponent",attributeName:"labelIsName"},componentNameAndShadowSourceNames:{dependencyType:"stateVariable",variableName:"componentNameAndShadowSourceNames"},shadowSource:{dependencyType:"shadowSource",variableNames:["label","labelHasLatex"]}}),definition({dependencyValues:e,essentialValues:t}){let n=e.labelChild[e.labelChild.length-1];if(n&&!n.shadowDepth)return{setValue:{label:n.stateValues.value,labelHasLatex:n.stateValues.hasLatex}};if(void 0!==t.label)return{useEssentialOrDefaultValue:{label:!0},setValue:{labelHasLatex:!1}};if(e.labelIsName&&!e.labelIsNameAttr.shadowDepth){let t="__",n=e.componentNameAndShadowSourceNames;for(let e of n){let n=e.lastIndexOf("/");if(t=e.substring(n+1),"__"!==t.slice(0,2))break}return"__"===t.slice(0,2)?{setValue:{label:"",labelHasLatex:!1}}:("_"!==t[0]&&(t.includes("_")||t.includes("-")?t=t.replace(/[_\-]/g," "):t.match(/^[a-z]/)?t.match(/[A-Z]/)&&(t=t.replace(/([A-Z])/g," $1").toLowerCase()):t.match(/^[A-Z]/)&&t.match(/[a-z]/)&&(t=t.replace(/([A-Z])/g," $1"),t=t.slice(1))),{setValue:{label:t,labelHasLatex:!1}})}return"string"==typeof e.shadowSource?.stateValues.label?{setValue:{label:e.shadowSource.stateValues.label,labelHasLatex:Boolean(e.shadowSource.stateValues.labelHasLatex)}}:{useEssentialOrDefaultValue:{label:!0},setValue:{labelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.label)return{success:!1};let n=t.labelChild.length-1,r=t.labelChild[n];return r&&!r.shadowDepth?{success:!0,instructions:[{setDependency:"labelChild",desiredValue:e.label,childIndex:n,variableIndex:0}]}:t.labelIsName&&!t.labelIsNameAttr.shadowDepth?{success:!0,instructions:[{setEssentialValue:"label",value:e.label}]}:"string"==typeof t.shadowSource?.stateValues.label?{success:!0,instructions:[{setDependency:"shadowSource",desiredValue:e.label,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"label",value:e.label}]}}},e.labelForGraph={forRenderer:!0,returnDependencies:()=>({label:{dependencyType:"stateVariable",variableName:"label"},labelHasLatex:{dependencyType:"stateVariable",variableName:"labelHasLatex"}}),definition({dependencyValues:e}){let t;if(e.labelHasLatex){let n=0;t="";for(let r of e.label)"("===r?n++:")"===r?n--:0===n&&("_"===r?r="_":"^"===r&&(r="^")),t+=r}else t=e.label.replaceAll("_","_").replaceAll("^","^");return{setValue:{labelForGraph:t}}}},e}class GraphicalComponent extends BaseComponent{static componentType="_graphical";static createAttributesObject(){let e=super.createAttributesObject();return e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showLabel={createComponentOfType:"boolean",createStateVariable:"showLabel",defaultValue:!0,public:!0,forRenderer:!0},e.applyStyleToLabel={createComponentOfType:"boolean",createStateVariable:"applyStyleToLabel",defaultValue:!1,public:!0,forRenderer:!0},e.layer={createComponentOfType:"integer",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();Object.assign(e,t);let n=returnLabelStateVariableDefinitions();return Object.assign(e,n),e}}function returnNumericalFunctionFromFormula({formula:e,nInputs:t,variables:n,domain:r,component:a=0}){let i;if(a=Number(a),Array.isArray(e.tree)&&vectorOperators.includes(e.tree[0]))try{e=e.get_component(Number(a))}catch(e){return()=>NaN}else if(0!==a)return()=>NaN;try{i=e.subscripts_to_strings().f()}catch(e){return()=>NaN}if(1===t){let e=n[0].subscripts_to_strings().tree,t=-1/0,a=1/0,s=!1,o=!1;if(null!==r){let e=r[0];if(void 0!==e)try{t=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(t)?s=!e.tree[2][1]:t=-1/0,a=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(a)?o=!e.tree[2][2]:a=1/0}catch(e){}}return function(n,r=!1){if(r){if(isNaN(n))return NaN}else if(!(n>=t)||!(n<=a)||s&&n===t||o&&n===a)return NaN;try{return i({[e]:n})}catch(e){return NaN}}}let s=[];for(let e=0;eme$3.fromAst("_")}else if("0"!==t)return e=>me$3.fromAst("_");let r=e.simplify,a=e.expand,i=n.subscripts_to_strings();if(1===e.nInputs){let t=e.variables[0].subscripts_to_strings().tree;return e=>normalizeMathExpression({value:i.substitute({[t]:e}).strings_to_subscripts(),simplify:r,expand:a})}let s=[];for(let t=0;tNaN;return e}let o=e-1,l={};for(let e=0;e<2;e++){let u,c,p=t[0][e],d=t[o][e],m=n.map((t=>t[e]));i&&(u=s[e]),r&&(c=a[e]),l[e]=function(e){if(isNaN(e))return NaN;if(e<0)return i?(u[2]*e+u[1])*e+u[0]:p;if(e>=o)return r?(e-=o,(c[2]*e+c[1])*e+c[0]):d;let t=Math.floor(e);e-=t;let n=m[t];return((n[3]*e+n[2])*e+n[1])*e+n[0]}}return l}function returnInterpolatedFunction({xs:e,coeffs:t,interpolationPoints:n,domain:r}){let a=[];if(n&&(a=n.map((e=>e.y))),null===e)return e=>NaN;let i=-1/0,s=1/0,o=!1,l=!1;if(null!==r){let e=r[0];if(void 0!==e)try{i=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(i)?o=!e.tree[2][1]:i=-1/0,s=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(s)?l=!e.tree[2][2]:s=1/0}catch(e){}}let u=e[0],c=e[e.length-1];return function(n,r=!1){if(r){if(isNaN(n))return NaN}else if(!(n>=i)||!(n<=s)||o&&n===i||l&&n===s)return NaN;if(n<=u){n-=u;let e=t[0];return((e[3]*n+e[2])*n+e[1])*n+e[0]}if(n>=c){let r=e.length-2;n-=e[r];let a=t[r];return((a[3]*n+a[2])*n+a[1])*n+a[0]}for(var p,d=0,m=e.length-1;d<=m;){p=Math.floor(.5*(d+m));let t=e[p];if(tn))return a[p];m=p-1}}let h=Math.max(0,m);n-=e[h];let f=t[h];return((f[3]*n+f[2])*n+f[1])*n+f[0]}}function returnReturnDerivativesOfInterpolatedFunction({xs:e,coeffs:t,variables:n}){if(!e)return e=>NaN;let r=n[0].subscripts_to_strings().tree,a=e[0],i=e[e.length-1];return function(n){let s=n.map((e=>e.subscripts_to_strings().tree)),o=s.length;return o>3||!s.every((e=>e===r))||s.includes("_")?e=>0:0===o||null===e?e=>NaN:function(n){if(isNaN(n))return NaN;if(n<=a){n-=a;let e=t[0];return 1===o?(3*e[3]*n+2*e[2])*n+e[1]:2===o?6*e[3]*n+2*e[2]:6*e[3]}if(n>=i){let r=e.length-2;n-=e[r];let a=t[r];return 1===o?(3*a[3]*n+2*a[2])*n+a[1]:2===o?6*a[3]*n+2*a[2]:6*a[3]}for(var r,s=0,l=e.length-1;s<=l;){r=Math.floor(.5*(s+l));let a=e[r];if(an))return 1===o?t[r][1]:2===o?2*t[r][2]:6*t[r][3];l=r-1}}let u=Math.max(0,l);n-=e[u];let c=t[u];return 1===o?(3*c[3]*n+2*c[2])*n+c[1]:2===o?6*c[3]*n+2*c[2]:6*c[3]}}}var functionOperatorDefinitions={clampFunction:function(e,t){return function(n){return Number.isFinite(n)?Math.max(e,Math.min(t,n)):NaN}},wrapFunctionPeriodic:function(e,t){return function(n){if(!Number.isFinite(n))return NaN;let r=e,a=t;return r===a?r:(r>a&&([a,r]=[r,a]),r+me$3.math.mod(n-r,a-r))}},derivative:function(e,t){if("interpolatedFunction"===e.derivativeType){let n=returnReturnDerivativesOfInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,variables:e.variables.map(convertValueToMathExpression)}),r=t.map(convertValueToMathExpression);if(e.additionalDerivVariables){r=[...e.additionalDerivVariables.map(convertValueToMathExpression),...r]}if(e.variableMappings)for(let t of e.variableMappings){let e=[];for(let n of r){let r=t[n.subscripts_to_strings().tree];r?e.push(convertValueToMathExpression(r)):e.push(me$3.fromAst("_"))}r=e}return n(r)}return e=>NaN}};class Function$1 extends InlineComponent{static componentType="function";static rendererType="math";static primaryStateVariableForDefinition="numericalfShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.simplify={createComponentOfType:"text",createStateVariable:"simplifySpecified",defaultValue:"none",toLowerCase:!0,valueTransformations:{true:"full"},validValues:["none","full","numbers","numberspreserveorder"]},e.expand={createComponentOfType:"boolean",createStateVariable:"expandSpecified",defaultValue:!1,public:!0},e.xscale={createComponentOfType:"number",createStateVariable:"xscale",defaultValue:1,public:!0},e.yscale={createComponentOfType:"number",createStateVariable:"yscale",defaultValue:1,public:!0},e.nInputs={createComponentOfType:"integer"},e.nOutputs={createComponentOfType:"integer"},e.domain={createComponentOfType:"_intervalListComponent"},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showLabel={createComponentOfType:"boolean",createStateVariable:"showLabel",defaultValue:!0,public:!0,forRenderer:!0},e.applyStyleToLabel={createComponentOfType:"boolean",createStateVariable:"applyStyleToLabel",defaultValue:!1,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.minima={createComponentOfType:"extrema"},e.maxima={createComponentOfType:"extrema"},e.extrema={createComponentOfType:"extrema"},e.through={createComponentOfType:"_pointListComponent"},e.throughSlopes={createComponentOfType:"mathList"},e.variables={createComponentOfType:"variables"},e.symbolic={createComponentOfType:"boolean"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.nearestPointAsCurve={createComponentOfType:"boolean",createStateVariable:"nearestPointAsCurve",defaultValue:!1},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[],i=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a=e.slice(0,t),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),i=e.slice(t))}return 1===r.length&&"string"!=typeof r[0]||0===r.length?{success:!1}:{success:!0,newChildren:[...a,{componentType:"math",children:r},...i]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"functions",componentTypes:["function"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions({numerics:e}){let t=GraphicalComponent.returnStateVariableDefinitions();return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" function"}}}},t.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:10,hasEssential:!0,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displayDigits"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth0){let n=t.functionChild[0],r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;return n||r||(n=!0),n?{useEssentialOrDefaultValue:{displayDigits:{defaultValue:e.functionChild[0].stateValues.displayDigits}}}:{setValue:{displayDigits:e.functionChild[0].stateValues.displayDigits}}}return{useEssentialOrDefaultValue:{displayDigits:!0}}}},t.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:null,hasEssential:!0,returnDependencies:()=>({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{displayDecimals:e.functionChild[0].stateValues.displayDecimals}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}},t.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{displaySmallAsZero:e.functionChild[0].stateValues.displaySmallAsZero}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}},t.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{padZeros:e.functionChild[0].stateValues.padZeros}}:{useEssentialOrDefaultValue:{padZeros:!0}}},t.isInterpolatedFunction={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through"},minima:{dependencyType:"attributeComponent",attributeName:"minima"},maxima:{dependencyType:"attributeComponent",attributeName:"maxima"},extrema:{dependencyType:"attributeComponent",attributeName:"extrema"}}),definition:({dependencyValues:e})=>({setValue:{isInterpolatedFunction:e.through||e.minima||e.maxima||e.extrema}})},t.nInputs={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({nInputsAttr:{dependencyType:"attributeComponent",attributeName:"nInputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nInputs"]},variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["nComponents"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"}}),definition({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{nInputs:1}};if(null!==e.nInputsAttr){let t=e.nInputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nInputs:t}}}return null!==e.variablesAttr?{setValue:{nInputs:Math.max(1,e.variablesAttr.stateValues.nComponents)}}:e.functionChild.length>0?{setValue:{nInputs:e.functionChild[0].stateValues.nInputs}}:{setValue:{nInputs:1}}}},t.nOutputs={defaultValue:1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({nOutputsAttr:{dependencyType:"attributeComponent",attributeName:"nOutputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nOutputs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition({dependencyValues:e}){if(e.functionChild.length>0)return{setValue:{nOutputs:e.functionChild[0].stateValues.nOutputs}};if(null!==e.nOutputsAttr){let t=e.nOutputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nOutputs:t}}}if(e.mathChild.length>0){let t=e.mathChild[0].stateValues.value,n=1;return Array.isArray(t.tree)&&vectorOperators.includes(t.tree[0])&&(n=t.tree.length-1),{setValue:{nOutputs:n}}}return{useEssentialOrDefaultValue:{nOutputs:!0}}}},t.domain={returnDependencies:()=>({domainAttr:{dependencyType:"attributeComponent",attributeName:"domain",variableNames:["intervals"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),definition({dependencyValues:e}){if(null!==e.domainAttr){let t=e.nInputs,n=e.domainAttr.stateValues.intervals.slice(0,t);return n.length!==t?{setValue:{domain:null}}:n.every((e=>Array.isArray(e.tree)&&"interval"===e.tree[0]))?{setValue:{domain:n}}:{setValue:{domain:null}}}return e.functionChild.length>0?{setValue:{domain:e.functionChild[0].stateValues.domain}}:{setValue:{domain:null}}}},t.simplify={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({simplifySpecified:{dependencyType:"stateVariable",variableName:"simplifySpecified"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["simplify"]}}),definition:({dependencyValues:e,usedDefault:t})=>t.simplifySpecified&&e.functionChild.length>0?{setValue:{simplify:e.functionChild[0].stateValues.simplify}}:{setValue:{simplify:e.simplifySpecified}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n})=>n.simplifySpecified&&t.functionChild.length>0?{success:!0,instructions:[{setDependency:"functionChild",desiredValue:e.simplify,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setDependency:"simplifySpecified",desiredValue:e.simplify}]}},t.expand={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({expandSpecified:{dependencyType:"stateVariable",variableName:"expandSpecified"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["expand"]}}),definition:({dependencyValues:e,usedDefault:t})=>t.expandSpecified&&e.functionChild.length>0?{setValue:{expand:e.functionChild[0].stateValues.expand}}:{setValue:{expand:e.expandSpecified}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n})=>n.expandSpecified&&t.functionChild.length>0?{success:!0,instructions:[{setDependency:"functionChild",desiredValue:e.expand,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setDependency:"expandSpecified",desiredValue:e.expand}]}},t.numericalfShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{numericalfShadow:!0}})},t.symbolicfShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{symbolicfShadow:!0}})},t.symbolic={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({symbolicAttr:{dependencyType:"attributeComponent",attributeName:"symbolic",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolic"]},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"}}),definition:({dependencyValues:e})=>null!==e.symbolicAttr?{setValue:{symbolic:e.symbolicAttr.stateValues.value}}:e.functionChild.length>0?{setValue:{symbolic:e.functionChild[0].stateValues.symbolic}}:e.numericalfShadow?{setValue:{symbolic:!1}}:e.symbolicfShadow?{setValue:{symbolic:!0}}:{useEssentialOrDefaultValue:{symbolic:!0}}},t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),returnArraySize:({dependencyValues:e})=>[e.nInputs],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["variable"+(Number(n)+1)]}};return{globalDependencies:{variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]},parentVariableForChild:{dependencyType:"parentStateVariable",variableName:"variableForChild"},functionChild:{dependencyType:"child",childGroups:["functions"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arraySize:n,arrayKeys:r,usedDefault:a}){if(null!==e.variablesAttr){let t=e.variablesAttr.stateValues.variables;return{setValue:{variables:returnNVariables(n[0],t)}}}if(e.functionChild.length>0){let e={};for(let n of r)e[n]=t[n].functionChild[0].stateValues["variable"+(Number(n)+1)];return{setValue:{variables:e}}}return e.parentVariableForChild&&!a.parentVariableForChild?{setValue:{variables:Array(n[0]).fill(e.parentVariableForChild)}}:{setValue:{variables:returnNVariables(n[0],[])}}}},t.variable={isAlias:!0,targetVariableName:"variable1"},t.unnormalizedFormula={defaultValue:me$3.fromAst(0),hasEssential:!0,returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["formula"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"}}),definition:function({dependencyValues:e,usedDefault:t}){return e.isInterpolatedFunction?{setValue:{unnormalizedFormula:me$3.fromAst("_")}}:e.mathChild.length>0?{setValue:{unnormalizedFormula:e.mathChild[0].stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0].formula?{setValue:{unnormalizedFormula:e.functionChild[0].stateValues.formula}}:{useEssentialOrDefaultValue:{unnormalizedFormula:!0}}}},t.formula={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},defaultValue:me$3.fromAst(0),hasEssential:!0,returnDependencies:()=>({unnormalizedFormula:{dependencyType:"stateVariable",variableName:"unnormalizedFormula"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"}}),definition:function({dependencyValues:e,usedDefault:t}){if(t.unnormalizedFormula)return{useEssentialOrDefaultValue:{formula:!0}};return{setValue:{formula:normalizeMathExpression({value:e.unnormalizedFormula,simplify:e.simplify,expand:e.expand})}}}},t.nPrescribedPoints={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition({dependencyValues:e}){let t=0;return null!==e.through&&(t=e.through.stateValues.nPoints),{setValue:{nPrescribedPoints:t}}}},t.prescribedPoints={isArray:!0,entryPrefixes:["prescribedPoint"],returnArraySizeDependencies:()=>({nPrescribedPoints:{dependencyType:"stateVariable",variableName:"nPrescribedPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nPrescribedPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["point"+e]},throughSlopes:{dependencyType:"attributeComponent",attributeName:"throughSlopes",variableNames:["math"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].through;if(null!==t){let a=Number(r)+1,i=t.stateValues["point"+a],s=null,o=e[r].throughSlopes;null!==o&&(s=o.stateValues["math"+a],void 0===s&&(s=null)),n[r]={x:i[0],y:i[1],slope:s}}}return{setValue:{prescribedPoints:n}}}},t.prescribedMinima={returnDependencies:()=>({minima:{dependencyType:"attributeComponent",attributeName:"minima",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.minima&&(t=e.minima.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedMinima:t}}}},t.prescribedMaxima={returnDependencies:()=>({maxima:{dependencyType:"attributeComponent",attributeName:"maxima",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.maxima&&(t=e.maxima.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedMaxima:t}}}},t.prescribedExtrema={returnDependencies:()=>({extrema:{dependencyType:"attributeComponent",attributeName:"extrema",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.extrema&&(t=e.extrema.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedExtrema:t}}}},t.interpolationPoints={returnDependencies:()=>({xscale:{dependencyType:"stateVariable",variableName:"xscale"},yscale:{dependencyType:"stateVariable",variableName:"yscale"},prescribedPoints:{dependencyType:"stateVariable",variableName:"prescribedPoints"},prescribedMinima:{dependencyType:"stateVariable",variableName:"prescribedMinima"},prescribedMaxima:{dependencyType:"stateVariable",variableName:"prescribedMaxima"},prescribedExtrema:{dependencyType:"stateVariable",variableName:"prescribedExtrema"}}),definition:({dependencyValues:t})=>calculateInterpolationPoints({dependencyValues:t,numerics:e})},t.xs={additionalStateVariablesDefined:["coeffs"],returnDependencies:()=>({interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"}}),definition:computeSplineParamCoeffs},t.symbolicfs={isArray:!0,entryPrefixes:["symbolicf"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolicfs"]},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)if("0"===r){let n=returnInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain});t[r]=function(e){me$3.fromAst(n(e.evaluate_to_constant()))}}else t[r]=e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.symbolicfs[r];return{setValue:{symbolicfs:t}}}if(e.symbolicfShadow){let t={};for(let r of n)t[r]="0"===r?e.symbolicfShadow:e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}if(e.numericalfShadow){let t={};for(let r of n)t[r]="0"===r?function(t){let n=t.evaluate_to_constant();return null===n?NaN:me$3.fromAst(e.numericalfShadow(n))}:e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}{let t={};for(let r of n)t[r]=returnSymbolicFunctionFromFormula(e,r);return{setValue:{symbolicfs:t}}}}{let t={};for(let r of n)t[r]=returnSymbolicFunctionFromFormula(e,r);return{setValue:{symbolicfs:t}}}}},t.symbolicf={isAlias:!0,targetVariableName:"symbolicf1"},t.numericalfs={isArray:!0,entryPrefixes:["numericalf"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalfs"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)t[r]="0"===r?returnInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain}):e=>me$3.fromAst("_");return{setValue:{numericalfs:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.numericalfs[r];return{setValue:{numericalfs:t}}}if(e.numericalfShadow){let t={};for(let r of n)t[r]="0"===r?e.numericalfShadow:()=>NaN;return{setValue:{numericalfs:t}}}if(e.symbolicfShadow){let e={};for(let t of n)e[t]="0"===t?function(e){let t=dependencyValues.symbolicfShadow(me$3.fromAst(e)).evaluate_to_constant();return null===t&&(t=NaN),t}:()=>NaN;return{setValue:{numericalfs:e}}}{let t={};for(let r of n)t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r});return{setValue:{numericalfs:t}}}}{let t={};for(let r of n)t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r});return{setValue:{numericalfs:t}}}}},t.numericalf={returnDependencies:()=>({numericalf1:{dependencyType:"stateVariable",variableName:"numericalf1"}}),definition:({dependencyValues:e})=>({setValue:{numericalf:e.numericalf1}})},t.fDefinition={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["fDefinition"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:({dependencyValues:e,usedDefault:t})=>e.isInterpolatedFunction?{setValue:{fDefinition:{functionType:"interpolated",xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain}}}:t.formula||"_"===e.formula.tree&&0!==e.functionChild.length?e.functionChild.length>0?{setValue:{fDefinition:e.functionChild[0].stateValues.fDefinition}}:e.numericalfShadow||e.symbolicfShadow?{setValue:{fDefinition:{}}}:{setValue:{fDefinition:{functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain}}}:{setValue:{fDefinition:{functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain}}}},t.fs={isArray:!0,entryPrefixes:["f"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={symbolicf:{dependencyType:"stateVariable",variableName:"symbolicf"+e},numericalf:{dependencyType:"stateVariable",variableName:"numericalf"+e}}}return{globalDependencies:{symbolic:{dependencyType:"stateVariable",variableName:"symbolic"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};if(e.symbolic)for(let e of n)r[e]=t[e].symbolicf;else for(let e of n)r[e]=t[e].numericalf;return{setValue:{fs:r}}}},t.f={isAlias:!0,targetVariableName:"f1"},t.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({formula:{dependencyType:"stateVariable",variableName:"formula"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.formula,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},t.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},t.allMinima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{numericalf:{dependencyType:"stateVariable",variableName:"numericalf"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["allMinima"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:function({dependencyValues:t}){if(t.isInterpolatedFunction){let n=t.xs,r=t.coeffs,a=e.eps,i=[];if(null===n)return{setValue:{allMinima:i}};let s=!1,o=-1/0,l=1/0,u=!1,c=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{o=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(o)?u=!e.tree[2][1]:o=-1/0,l=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][2]:l=1/0}catch(e){}}let p=1e-14*Math.max(Math.abs(o),Math.abs(l)),d=r[0],m=n[1]-n[0];if(0===d[3]){if(d[2]>0){let e=-d[1]/(2*d[2]);e+n[0]>=o-p&&e+n[0]<=l+p&&(e<=m-a?u&&Math.abs(e+n[0]-o)0){let t=Math.sqrt(e),r=(-2*d[2]+t)/(6*d[3]);r+n[0]>=o-p&&r+n[0]<=l+p&&(r<=m-a?u&&Math.abs(r+n[0]-o)0){let t=-d[1]/(2*d[2]);if(t+n[e]>=o-p){if(!(t+n[e]<=l+p)){s=!1;continue}Math.abs(t)=a&&t<=m-a&&(u&&Math.abs(t+n[e]-o)0){let r=Math.sqrt(t),h=(-2*d[2]+r)/(6*d[3]);if(h+n[e]>=o-p){if(!(h+n[e]<=l+p)){s=!1;continue}Math.abs(h)=a&&h<=m-a&&(u&&Math.abs(h+n[e]-o)0){let e=-d[1]/(2*d[2]);e+n[n.length-2]>=o-p&&e+n[n.length-2]<=l+p&&(Math.abs(e)=a&&(u&&Math.abs(e+n[n.length-2]-o)0){let t=Math.sqrt(e),r=(-2*d[2]+t)/(6*d[3]);r+n[n.length-2]>=o-p&&r+n[n.length-2]<=l+p&&(r>=a||Math.abs(r)0)return{setValue:{allMinima:t.functionChild[0].stateValues.allMinima}};if(1!==t.nInputs||1!==t.nOutputs)return{setValue:{allMinima:[]}};let n,r,a=t.variables[0].subscripts_to_strings().tree,i=t.formula.subscripts_to_strings().derivative(a),s=!0;try{n=i.subscripts_to_strings().f()}catch(e){s=!1,r=()=>NaN}s&&(r=function(e){try{return n({[a]:e})}catch(e){return NaN}});let o=e=>t.numericalf(e,!0),l=-100*t.xscale,u=100*t.xscale,c=!1,p=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{l=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][1]:l=-100*t.xscale,u=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(u)?p=!e.tree[2][2]:u=100*t.xscale}catch(e){}}let d=1e3,m=(u-l)/d,h=1e-10*Math.max(Math.abs(l),Math.abs(u)),f=[],y=!1,g=!1,b=o(l-m),v=r(l-m);for(let t=-1;t0&&(N=!0,y=!1,!(t>=l-h&&t<=u+h)||c&&Math.abs(t-l)({allMinima:{dependencyType:"stateVariable",variableName:"allMinima"}}),definition:({dependencyValues:e})=>({setValue:{numberMinima:e.allMinima.length},checkForActualChange:{numberMinima:!0}})},t.minima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"minimum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["minimum","minimumLocations","minimumLocation","minimumValues","minimumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["minimum","minimumLocation","minimumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"minimumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"minimumLocation"+(Number(t)+1):"minimumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("minima"===t){if(1===e.length)return"minimum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"minimumLocation"+t;if(2===e[1])return"minimumValue"+t}return null}}if("minimumLocations"===t)return"minimumLocation"+e[0];if("minimumValues"===t)return"minimumValue"+e[0];if("minimum"===t.slice(0,7)){let n=Number(t.slice(7));if(Number.isInteger(n)&&n>0){if(1===e[0])return"minimumLocation"+n;if(2===e[0])return"minimumValue"+n}}return null},returnArraySizeDependencies:()=>({numberMinima:{dependencyType:"stateVariable",variableName:"numberMinima"}}),returnArraySize:({dependencyValues:e})=>[e.numberMinima,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allMinima:{dependencyType:"stateVariable",variableName:"allMinima"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;ne.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{numericalf:{dependencyType:"stateVariable",variableName:"numericalf"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["allMaxima"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:function({dependencyValues:t}){if(t.isInterpolatedFunction){let n=t.xs,r=t.coeffs,a=e.eps,i=[];if(null===n)return{setValue:{allMaxima:i}};let s=!1,o=-1/0,l=1/0,u=!1,c=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{o=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(o)?u=!e.tree[2][1]:o=-1/0,l=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][2]:l=1/0}catch(e){}}let p=1e-14*Math.max(Math.abs(o),Math.abs(l)),d=r[0],m=n[1]-n[0];if(0===d[3]){if(d[2]<0){let e=-d[1]/(2*d[2]);e+n[0]>=o-p&&e+n[0]<=l+p&&(e<=m-a?u&&Math.abs(e+n[0]-o)0){let t=Math.sqrt(e),r=(-2*d[2]-t)/(6*d[3]);r+n[0]>=o-p&&r+n[0]<=l+p&&(r<=m-a?u&&Math.abs(r+n[0]-o)=o-p){if(!(t+n[e]<=l+p)){s=!1;continue}Math.abs(t)=a&&t<=m-a&&(u&&Math.abs(t+n[e]-o)0){let r=Math.sqrt(t),h=(-2*d[2]-r)/(6*d[3]);if(h+n[e]>=o-p){if(!(h+n[e]<=l+p)){s=!1;continue}Math.abs(h)=a&&h<=m-a&&(u&&Math.abs(h+n[e]-o)=o-p&&e+n[n.length-2]<=l+p&&(Math.abs(e)=a&&(u&&Math.abs(e+n[n.length-2]-o)0){let t=Math.sqrt(e),r=(-2*d[2]-t)/(6*d[3]);r+n[n.length-2]>=o-p&&r+n[n.length-2]<=l+p&&(r>=a||Math.abs(r)0)return{setValue:{allMaxima:t.functionChild[0].stateValues.allMaxima}};if(1!==t.nInputs||1!==t.nOutputs)return{setValue:{allMaxima:[]}};let n,r,a=t.variables[0].subscripts_to_strings().tree,i=t.formula.subscripts_to_strings().derivative(a),s=!0;try{n=i.subscripts_to_strings().f()}catch(e){s=!1,r=()=>NaN}s&&(r=function(e){try{return n({[a]:e})}catch(e){return NaN}});let o=e=>-t.numericalf(e,!0),l=-100*t.xscale,u=100*t.xscale,c=!1,p=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{l=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][1]:l=-100*t.xscale,u=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(u)?p=!e.tree[2][2]:u=100*t.xscale}catch(e){}}let d=1e3,m=(u-l)/d,h=1e-10*Math.max(Math.abs(l),Math.abs(u)),f=[],y=!1,g=!1,b=o(l-m),v=r(l-m);for(let t=-1;t0&&r(t+i)<0&&(N=!0,y=!1,!(t>=l-h&&t<=u+h)||c&&Math.abs(t-l)({allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}),definition:({dependencyValues:e})=>({setValue:{numberMaxima:e.allMaxima.length},checkForActualChange:{numberMaxima:!0}})},t.maxima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"maximum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["maximum","maximumLocations","maximumLocation","maximumValues","maximumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["maximum","maximumLocation","maximumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"maximumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"maximumLocation"+(Number(t)+1):"maximumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("maxima"===t){if(1===e.length)return"maximum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"maximumLocation"+t;if(2===e[1])return"maximumValue"+t}return null}}if("maximumLocations"===t)return"maximumLocation"+e[0];if("maximumValues"===t)return"maximumValue"+e[0];if("maximum"===t.slice(0,7)){let n=Number(t.slice(7));if(Number.isInteger(n)&&n>0){if(1===e[0])return"maximumLocation"+n;if(2===e[0])return"maximumValue"+n}}return null},returnArraySizeDependencies:()=>({numberMaxima:{dependencyType:"stateVariable",variableName:"numberMaxima"}}),returnArraySize:({dependencyValues:e})=>[e.numberMaxima,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({numberMinima:{dependencyType:"stateVariable",variableName:"numberMinima"},numberMaxima:{dependencyType:"stateVariable",variableName:"numberMaxima"}}),definition:function({dependencyValues:e}){return{setValue:{numberExtrema:e.numberMinima+e.numberMaxima},checkForActualChange:{numberExtrema:!0}}}},t.allExtrema={returnDependencies:()=>({allMinima:{dependencyType:"stateVariable",variableName:"allMinima"},allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}),definition({dependencyValues:e}){let t=[...e.allMinima,...e.allMaxima].sort(((e,t)=>e[0]-t[0]));return{setValue:{allExtrema:t}}}},t.extrema={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"extremum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["extremum","extremumLocations","extremumLocation","extremumValues","extremumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["extremum","extremumLocation","extremumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"extremumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"extremumLocation"+(Number(t)+1):"extremumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("extrema"===t){if(1===e.length)return"extremum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"extremumLocation"+t;if(2===e[1])return"extremumValue"+t}return null}}if("extremumLocations"===t)return"extremumLocation"+e[0];if("extremumValues"===t)return"extremumValue"+e[0];if("extremum"===t.slice(0,8)){let n=Number(t.slice(8));if(Number.isInteger(n)&&n>0){if(1===e[0])return"extremumLocation"+n;if(2===e[0])return"extremumValue"+n}}return null},returnArraySizeDependencies:()=>({numberExtrema:{dependencyType:"stateVariable",variableName:"numberExtrema"}}),returnArraySize:({dependencyValues:e})=>[e.numberExtrema,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allExtrema:{dependencyType:"stateVariable",variableName:"allExtrema"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;ne.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}}:{functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["returnNumericalDerivatives","variables"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}},definition:function({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{returnNumericalDerivatives:returnReturnDerivativesOfInterpolatedFunction(e)}};if(e.functionChild.length>0&&e.functionChild[0].stateValues.returnNumericalDerivatives){let t=e.variables.map((e=>e.subscripts_to_strings().tree)),n=e.functionChild[0].stateValues.variables,r=n.map((e=>e.subscripts_to_strings().tree)),a={};for(let[e,i]of t.entries())r[e]&&r[e]!==i&&(a[i]=n[e]);if(0===Object.keys(a).length)return{setValue:{returnNumericalDerivatives:e.functionChild[0].stateValues.returnNumericalDerivatives}};return{setValue:{returnNumericalDerivatives:function(t){let n=[];for(let e of t){let t=a[e.subscripts_to_strings().tree];t?n.push(t):n.push(me$3.fromAst("_"))}return e.functionChild[0].stateValues.returnNumericalDerivatives(n)}}}}return{setValue:{returnNumericalDerivatives:null}}}},t.numericalDerivativesDefinition={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}}:{functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalDerivativesDefinition","variables"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}},definition:function({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{numericalDerivativesDefinition:{derivativeType:"interpolatedFunction",xs:e.xs,coeffs:e.coeffs,variables:e.variables}}};if(e.functionChild.length>0&&e.functionChild[0].stateValues.numericalDerivativesDefinition){let t=e.variables.map((e=>e.subscripts_to_strings().tree)),n=e.functionChild[0].stateValues.variables,r=n.map((e=>e.subscripts_to_strings().tree)),a={};for(let[e,i]of t.entries())r[e]&&r[e]!==i&&(a[i]=n[e]);if(0===Object.keys(a).length)return{setValue:{numericalDerivativesDefinition:e.functionChild[0].stateValues.numericalDerivativesDefinition}};{let t={...e.functionChild[0].stateValues.numericalDerivativesDefinition};return t.variableMappings?t.variableMappings=[a,...t.variableMappings]:t.variableMappings=[a],{setValue:{numericalDerivativesDefinition:t}}}}return{setValue:{numericalDerivativesDefinition:{}}}}},t}static adapters=[{stateVariable:"numericalf",componentType:"curve",stateVariablesToShadow:["label","labelHasLatex"]},{stateVariable:"formula",componentType:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}]}function calculateInterpolationPoints({dependencyValues:e,numerics:t}){let n=[],r=[],a={maximum:e.prescribedMaxima,minimum:e.prescribedMinima,extremum:e.prescribedExtrema,point:e.prescribedPoints};for(let e in a)for(let t of a[e]){let a=null,i=null,s=null;if(null===t.x||(a=t.x.evaluate_to_constant(),Number.isFinite(a)))if(null===t.y||(i=t.y.evaluate_to_constant(),Number.isFinite(i)))if(null!==t.slope&&void 0!==t.slope&&(s=t.slope.evaluate_to_constant(),Number.isFinite(s)||(console.warn("Ignoring non-numerical slope"),s=null)),null===a){if(null===i){console.warn(`Ignoring empty ${e}`);continue}r.push({type:e,y:i,slope:s})}else n.push({type:e,x:a,y:i,slope:s});else console.warn(`Ignoring non-numerical ${e}`);else console.warn(`Ignoring non-numerical ${e}`)}n.sort(((e,t)=>e.x-t.x)),r.sort(((e,t)=>e.y-t.y));let i=-1/0,s=t.eps;for(let e=0;e0;){let e,t;void 0===l?e=v({allowedTypes:["maximum","minimum","extremum"],comparison:"atLeast",value:-1/0}):"maximum"===l?e=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:o-c}):"minimum"===l?e=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:o+c}):"point"===l&&(e=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:o+c}),!0!==e.success&&(e=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:o-c}))),!0===e.success?(t=e.point,r.splice(e.ind,1),m?(t.x=0,m=!1):t.x=i+u):(t=r.pop(),m?(t.x=0,m=!1):t.x=i+2*u);let n=y({p:t,typePrev:l,xPrev:i,yPrev:o});l=n.type,i=n.x,o=n.y}if(0===p.length&&p.push({type:"point",x:0,y:0,slope:0}),m=p[0],"maximum"===m.type){let e={type:"point",x:m.x-u,y:m.y-c,slope:2*c/u};p.splice(0,0,e)}else if("minimum"===m.type){let e={type:"point",x:m.x-u,y:m.y+c,slope:-2*c/u};p.splice(0,0,e)}else if("point"===m.type)if(1===p.length)null===m.slope&&(m.slope=0);else{let e=p[1],t=(e.y-m.y)/(e.x-m.x);if("maximum"===e.type||"minimum"===e.type)null===m.slope&&(m.slope=2*t);else{2===p.length?null===m.slope&&(m.slope=t):(null===e.slope&&(e.slope=f({point:e,prevPoint:m,nextPoint:p[2]})),null===m.slope&&(m.slope=2*(m.y-e.y)/(m.x-e.x)-e.slope));let n={x:m.x-u,y:m.y-u*m.slope,slope:m.slope};p.splice(0,0,n)}}let h=p[p.length-1];if("maximum"===h.type){let e={type:"point",x:h.x+u,y:h.y-c,slope:-2*c/u};p.push(e)}else if("minimum"===h.type){let e={type:"point",x:h.x+u,y:h.y+c,slope:2*c/u};p.push(e)}else if("point"===h.type)if(1===p.length){let e={type:"point",x:h.x+u,y:h.y+m.slope*u,slope:m.slope};p.push(e)}else{let e=p[p.length-2],t=(e.y-h.y)/(e.x-h.x);if("maximum"===e.type||"minimum"===e.type)null===h.slope&&(h.slope=2*t);else{2===p.length?null===h.slope&&(h.slope=t):(null===e.slope&&(e.slope=f({point:e,prevPoint:p[p.length-3],nextPoint:h})),null===h.slope&&(h.slope=2*(e.y-h.y)/(e.x-h.x)-e.slope));let n={x:h.x+u,y:h.y+u*h.slope,slope:h.slope};p.push(n)}}for(let e=1;ei-c||void 0!==r&&null!==e.y&&e.y>t.y-c?g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t});if("minimum"===n||"minimum"===r)return null!==e.y&&e.yt.y+c?b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t});if("point"===n||"point"===r){let o="maximum";return(null===e.y&&void 0!==t&&t.type===maximum||null!==e.y&&e.y<=i-c||void 0!==r&&null!==e.y&&e.y>=t.y-c)&&(o="minimum"),"minimum"===o?b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t})}return null!==e.y&&e.ys-c){let n,a,o=(e+i)/2,l=null,u=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:Math.min(s,t)-c});!0===u.success?(a="minimum",n=u.point.y,r.splice(u.ind,1),l=0):(a="point",n=s-c),p.push({type:a,x:o,y:n,slope:l})}}else if("minimum"===a&&ti-c){let n=[(2*a+e)/3,(a+2*e)/3],s=[i-c,t+c],o=["atMost","atLeast"],l=[["minimum","extremum"],["maximum","extremum"]];for(let e=0;e<2;e++){let t,a,i=n[e],u=null,c=v({allowedTypes:l[e],comparison:o[e],value:s[e]});!0===c.success?(a=l[e][0],t=c.point.y,r.splice(c.ind,1),u=0):(a="point",t=s[e],u=null),p.push({type:a,x:i,y:t,slope:u})}}}else if("minimum"===n){null===t&&(t=void 0===s?i:"minimum"===o.type?Math.min(i,s):Math.min(i,s-c));let n,l,u=Math.max(i,t)+c,d=(e+a)/2,m=null,h=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:u});!0===h.success?(l="maximum",n=h.point.y,r.splice(h.ind,1),m=0):(l="point",n=u),p.push({type:l,x:d,y:n,slope:m})}else if("point"===n)if(null===t)t=void 0===s?i-c:"minimum"===o.type?Math.min(i-c,s):Math.min(i,s)-c;else if(t>i-c){let n,i,s=(e+a)/2,o=null,l=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:t+c});!0===l.success?(i="maximum",n=l.point.y,r.splice(l.ind,1),o=0):(i="point",n=t+c),p.push({type:i,x:s,y:n,slope:o})}let l={type:"minimum",x:e,y:t,slope:0};return p.push(l),l}function v({allowedTypes:e,comparison:t,value:n}){let a=[];if("atMost"===t)a=Object.keys(r).reverse();else{if("atLeast"!==t)return{success:!1};a=Object.keys(r)}for(let i of e)for(let e of a){let a=r[e];if(a.type===i)if("atMost"===t){if(a.y<=n)return{success:!0,ind:e,point:a}}else if(a.y>=n)return{success:!0,ind:e,point:a}}return{success:!1}}}function computeSplineParamCoeffs({dependencyValues:e}){let t=e.interpolationPoints;if(null===t)return{setValue:{xs:null,coeffs:null}};let n,r=[],a=[],i=t[0];a.push(i.x);for(let e=1;et.componentIsSpecifiedType(e,"label");if(0===e.length||!e.every((e=>"string"==typeof e||e.doenetAttributes?.createdFromMacro||n(e))))return{success:!1};let r=e.map(n),a=[],i=[],s=[];if(0===r.filter((e=>e)).length)a=e;else{if(r[0]){let t=r.indexOf(!1);-1!==t&&(i=e.slice(0,t),e=e.slice(t),r=r.slice(t))}let t=r.indexOf(!0);-1===t?a=e:(a=e.slice(0,t),s=e.slice(t))}return 0===a.length||1===a.length&&"string"!=typeof a[0]?{success:!1}:{success:!0,newChildren:[...i,{componentType:"math",children:a},...s]}}}),e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e}),n=this.componentType;t.isInterpolatedFunction={returnDependencies:()=>({}),definition:()=>({setValue:{isInterpolatedFunction:!1}})},delete t.nPrescribedPoints,delete t.prescribedPoints,delete t.prescribedMinima,delete t.prescribedMaxima,delete t.prescribedExtrema,delete t.interpolationPoints,delete t.xs,t.operatorBasedOnFormulaIfAvailable={returnDependencies:()=>({}),definition:()=>({setValue:{operatorBasedOnFormulaIfAvailable:!1}})},t.formula.returnDependencies=()=>({}),t.formula.definition=()=>({setValue:{formula:me$3.fromAst("_")}}),t.operatorComposesWithOriginal={returnDependencies:()=>({}),definition:()=>({setValue:{operatorComposesWithOriginal:!0}})},t.symbolicFunctionOperator={returnDependencies:()=>({}),definition:()=>({setValue:{symbolicFunctionOperator:e=>me$3.fromAst("_")}})},t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({}),definition:()=>({setValue:{numericalFunctionOperator:e=>NaN,numericalFunctionOperatorArguments:[]}})},t.numericalFunctionOperatorArguments={returnDependencies:()=>({}),definition:()=>({setValue:{numericalFunctionOperatorArguments:{}}})},t.formulaOperator={returnDependencies:()=>({}),definition:()=>({setValue:{formulaOperator:e=>me$3.fromAst("_")}})},t.returnNumericalDerivatives={returnDependencies:()=>({}),definition:()=>({setValue:{returnNumericalDerivatives:null}})},t.formula={public:!0,shadowingInstructions:{createComponentOfType:"math"},additionalStateVariablesDefined:["operatorBasedOnFormula"],returnDependencies:()=>({operatorBasedOnFormulaIfAvailable:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormulaIfAvailable"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["formula"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},formulaOperator:{dependencyType:"stateVariable",variableName:"formulaOperator"}}),definition:function({dependencyValues:e}){if(!e.operatorBasedOnFormulaIfAvailable||(0===e.functionChild.length||"_"===e.functionChild[0].stateValues.formula.tree)&&(0===e.mathChild.length||"_"===e.mathChild[0].stateValues.value.tree))return{setValue:{formula:me$3.fromAst("_"),operatorBasedOnFormula:!1}};let t;return t=0===e.functionChild.length?e.mathChild[0].stateValues.value:e.functionChild[0].stateValues.formula,{setValue:{formula:e.formulaOperator(t),operatorBasedOnFormula:!0}}}},t.symbolicfs={isArray:!0,entryPrefixes:["symbolicf"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolicfs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},symbolicFunctionOperator:{dependencyType:"stateVariable",variableName:"symbolicFunctionOperator"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n,arraySize:r}){if(!e.operatorBasedOnFormula){if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let e={};for(let t of n)e[t]=e=>me$3.fromAst("_");return{setValue:{symbolicfs:e}}}{let t=Object.assign({},e);t.formula=e.mathChild[0].stateValues.value;let a=[];for(let e=0;ee.symbolicFunctionOperator(...a.map((e=>e(...t))));return{setValue:{symbolicfs:i}}}}{let t=[];for(let n=0;ne.symbolicFunctionOperator(...t.map((e=>e(...n))));return{setValue:{symbolicfs:a}}}}{let t={};for(let r of n)t[r]=(...t)=>e.symbolicFunctionOperator(...t);return{setValue:{symbolicfs:t}}}}{let t={};for(let r of n)return t[r]=returnSymbolicFunctionFromFormula(e,r),{setValue:{symbolicfs:t}}}}},t.numericalfs={isArray:!0,entryPrefixes:["numericalf"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalfs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n,arraySize:r}){if(!e.operatorBasedOnFormula){if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let e={};for(let t of n)e[t]=e=>NaN;return{setValue:{numericalfs:e}}}{Object.assign({},e).formula=e.mathChild[0].stateValues.value;let t=[];for(let n=0;ne.numericalFunctionOperator(...t.map((e=>e(...n))));return{setValue:{numericalfs:a}}}}{let t=[];for(let n=0;ne.numericalFunctionOperator(...t.map((e=>e(...n))));return{setValue:{numericalfs:a}}}}{let t={};for(let r of n)t[r]=(...t)=>e.numericalFunctionOperator(...t);return{setValue:{numericalfs:t}}}}{let t={};for(let r of n)return t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r}),{setValue:{numericalfs:t}}}}},t.fDefinition={returnDependencies:()=>({operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["fDefinition"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"},numericalFunctionOperatorArguments:{dependencyType:"stateVariable",variableName:"numericalFunctionOperatorArguments"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}),definition({dependencyValues:e}){if(e.operatorBasedOnFormula)return{setValue:{fDefinition:{functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain}}};if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length)return{setValue:{fDefinition:{functionType:"formula",formula:"_",variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain}}};throw Error("function operator with math child not implemented yet")}return{setValue:{fDefinition:{functionType:"functionOperator",componentType:n,nOutputs:e.nOutputs,functionOperatorArguments:e.numericalFunctionOperatorArguments,operatorComposesWithOriginal:!0,originalFDefinition:e.functionChild[0].stateValues.fDefinition}}}}if(0===e.functionChild.length){if(0===e.mathChild.length)return{setValue:{fDefinition:{functionType:"formula",formula:"_",variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain}}};throw Error("function operator with math child not implemented yet")}return{setValue:{fDefinition:{functionType:"functionOperator",componentType:n,nOutputs:e.nOutputs,functionOperatorArguments:e.numericalFunctionOperatorArguments,operatorComposesWithOriginal:!1,originalFDefinition:e.functionChild[0].stateValues.fDefinition}}}}};let r=t.allMinima.returnDependencies;t.allMinima.returnDependencies=function(e){let t=r(e);return delete t.functionChild,t};let a=t.allMaxima.returnDependencies;return t.allMaxima.returnDependencies=function(e){let t=a(e);return delete t.functionChild,t},t}}class ClampFunction extends FunctionOperator{static componentType="clampFunction";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:function({dependencyValues:e}){return{setValue:{numericalFunctionOperator:functionOperatorDefinitions.clampFunction(e.lowerValue,e.upperValue),numericalFunctionOperatorArguments:[e.lowerValue,e.upperValue]}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}class WrapFunctionPeriodic extends FunctionOperator{static componentType="wrapFunctionPeriodic";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:function({dependencyValues:e}){return{setValue:{numericalFunctionOperator:functionOperatorDefinitions.wrapFunctionPeriodic(e.lowerValue,e.upperValue),numericalFunctionOperatorArguments:[e.lowerValue,e.upperValue]}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}class Derivative extends FunctionOperator{static componentType="derivative";static createAttributesObject(){let e=super.createAttributesObject();return e.derivVariables={createComponentOfType:"variables"},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.operatorBasedOnFormulaIfAvailable={returnDependencies:()=>({}),definition:()=>({setValue:{operatorBasedOnFormulaIfAvailable:!0}})},t.operatorComposesWithOriginal={returnDependencies:()=>({}),definition:()=>({setValue:{operatorComposesWithOriginal:!1}})},t.haveFunctionChild={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"]}}),definition:({dependencyValues:e})=>({setValue:{haveFunctionChild:e.functionChild.length>0}})},t.nInputs={defaultValue:1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},stateVariablesDeterminingDependencies:["haveFunctionChild"],returnDependencies({stateValues:e}){let t={nInputsAttr:{dependencyType:"attributeComponent",attributeName:"nInputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nInputs"]},variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["nComponents"]}};return e.haveFunctionChild||(t.derivVariablesAttr={dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]}),t},definition({dependencyValues:e}){if(null!==e.nInputsAttr){let t=e.nInputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nInputs:t}}}if(null!==e.variablesAttr)return{setValue:{nInputs:Math.max(1,e.variablesAttr.stateValues.nComponents)}};if(e.functionChild.length>0)return{setValue:{nInputs:e.functionChild[0].stateValues.nInputs}};if(null!==e.derivVariablesAttr){let t=[...new Set(e.derivVariablesAttr.stateValues.variables.map((e=>e.subscripts_to_strings().tree)))].length;return{setValue:{nInputs:t}}}return{useEssentialOrDefaultValue:{nInputs:!0}}}},t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),returnArraySize:({dependencyValues:e})=>[e.nInputs],stateVariablesDeterminingDependencies:["haveFunctionChild"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]},parentVariableForChild:{dependencyType:"parentStateVariable",variableName:"variableForChild"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},haveFunctionChild:{dependencyType:"stateVariable",variableName:"haveFunctionChild"}},r={};if(t.haveFunctionChild)for(let t of e)r[t]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["variable"+(Number(t)+1)]}};else n.derivVariablesAttr={dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]};return{globalDependencies:n,dependenciesByKey:r}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arraySize:n,arrayKeys:r,usedDefault:a}){if(null!==e.variablesAttr){let t=e.variablesAttr.stateValues.variables;return{setValue:{variables:returnNVariables(n[0],t)}}}if(e.haveFunctionChild){let e={};for(let n of r)e[n]=t[n].functionChild[0].stateValues["variable"+(Number(n)+1)];return{setValue:{variables:e}}}if(null!==e.derivVariablesAttr){let t=[],r=[];for(let n of e.derivVariablesAttr.stateValues.variables){let e=n.subscripts_to_strings().tree;r.includes(e)||(t.push(n),r.push(e))}return{setValue:{variables:returnNVariables(n[0],t)}}}return e.parentVariableForChild&&!a.parentVariableForChild?{setValue:{variables:Array(n[0]).fill(e.parentVariableForChild)}}:{setValue:{variables:returnNVariables(n[0],[])}}}},t.nDerivatives={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({derivVariablesAttr:{dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["nComponents"]}}),definition:({dependencyValues:e})=>null!==e.derivVariablesAttr?{setValue:{nDerivatives:e.derivVariablesAttr.stateValues.nComponents}}:{setValue:{nDerivatives:1}}},t.derivVariables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["derivVariable"],returnArraySizeDependencies:()=>({nDerivatives:{dependencyType:"stateVariable",variableName:"nDerivatives"}}),returnArraySize:({dependencyValues:e})=>[e.nDerivatives],returnArrayDependenciesByKey:()=>({globalDependencies:{derivVariablesAttr:{dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]},variable1:{dependencyType:"stateVariable",variableName:"variable1"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>null!==e.derivVariablesAttr?{setValue:{derivVariables:e.derivVariablesAttr.stateValues.variables}}:{setValue:{derivVariables:{0:e.variable1}}}},t.formulaOperator={returnDependencies:()=>({derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),definition:({dependencyValues:e})=>({setValue:{formulaOperator:function(t){let n=t.subscripts_to_strings();for(let t of e.derivVariables)n=n.derivative(t.subscripts_to_strings().tree);return n.strings_to_subscripts()}}})},t.numericalFunctionOperator={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["returnNumericalDerivatives"],variablesOptional:!0},derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),additionalStateVariablesDefined:["returnNumericalDerivatives"],definition:function({dependencyValues:e}){if(0===e.functionChild.length||!e.functionChild[0].stateValues.returnNumericalDerivatives)return{setValue:{numericalFunctionOperator:e=>NaN,returnNumericalDerivatives:null}};return{setValue:{numericalFunctionOperator:e.functionChild[0].stateValues.returnNumericalDerivatives(e.derivVariables),returnNumericalDerivatives:function(t){let n=[...e.derivVariables,...t];return e.functionChild[0].stateValues.returnNumericalDerivatives(n)}}}}},t.numericalFunctionOperatorArguments={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalDerivativesDefinition"],variablesOptional:!0},derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),additionalStateVariablesDefined:["numericalDerivativesDefinition"],definition:function({dependencyValues:e}){if(0===e.functionChild.length||!e.functionChild[0].stateValues.numericalDerivativesDefinition)return{setValue:{numericalFunctionOperatorArguments:[],numericalDerivativesDefinition:{}}};let t=e.functionChild[0].stateValues.numericalDerivativesDefinition,n={...t};return n.additionalDerivVariables?n.additionalDerivVariables=[...e.derivVariables,...n.additionalDerivVariables]:n.additionalDerivVariables=[...e.derivVariables],{setValue:{numericalFunctionOperatorArguments:[t,e.derivVariables],numericalDerivativesDefinition:n}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}var FunctionOperators=Object.freeze({__proto__:null,ClampFunction:ClampFunction,WrapFunctionPeriodic:WrapFunctionPeriodic,Derivative:Derivative});class TextBaseOperatorOfMath extends Text{static componentType="_textOperatorOfMath";static rendererType="text";static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyTextOperator(e.mathChildren.map((e=>e.stateValues.value)))}}}},e}}class ExtractMathOperator extends TextBaseOperatorOfMath{static componentType="extractMathOperator";static applyTextOperator(e){return 0===e.length?"":1!==e.length?(console.warn("MathOperator requires exactly one math child"),""):Array.isArray(e[0].tree)?e[0].tree[0]:""}}var TextOperatorsOfMath=Object.freeze({__proto__:null,ExtractMathOperator:ExtractMathOperator});class Extremum extends BaseComponent{static componentType="extremum";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.location={createComponentOfType:"math"},e.value={createComponentOfType:"math"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/s+(.*s)?/,replacementFunction:function({matchedChildren:e}){let t=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),n=t({matchedChildren:e});if(!n.success&&1===e.length)return{success:!0,newAttributes:{value:{component:{componentType:"math",children:e}}}};if(n.success){if(1===n.newChildren.length)return{success:!0,newAttributes:{value:{component:n.newChildren[0]}}};if(2===n.newChildren.length){let e=n.newChildren[0],t=n.newChildren[1],r={location:{component:e},value:{component:t}};return(0===e.children.length||1===e.children.length&&"string"==typeof e.children[0]&&""===e.children[0].trim())&&delete r.location,(0===t.children.length||1===t.children.length&&"string"==typeof t.children[0]&&""===t.children[0].trim())&&delete r.value,{success:!0,newAttributes:r}}return{success:!1}}return n}}),e}static returnChildGroups(){return[{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e}),n=this;return t.value={public:!0,shadowingInstructions:{createComponentOfType:"math"},defaultValue:null,hasEssential:!0,additionalStateVariablesDefined:[{variableName:"location",public:!0,shadowingInstructions:{createComponentOfType:"math"},defaultValue:null,hasEssential:!0}],returnDependencies:()=>({extremumChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions","xs"]},location:{dependencyType:"attributeComponent",attributeName:"location",variableNames:["value"]},value:{dependencyType:"attributeComponent",attributeName:"value",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t,r;if(e.extremumChild.length>0){let a=e.extremumChild[0];2!==a.stateValues.nDimensions?(console.log("Cannot determine "+n.componentType+" from a point that isn't 2D"),t=null,r=null):(t=a.stateValues.xs[0],r=a.stateValues.xs[1])}else null!==e.location&&(t=e.location.stateValues.value),null!==e.value&&(r=e.value.stateValues.value);let a={},i={},s=!1,o=!1;void 0===t?(i.location=!0,o=!0):(a.location=t,s=!0),void 0===r?(i.value=!0,o=!0):(a.value=r,s=!0);let l={};return s&&(l.setValue=a),o&&(l.useEssentialOrDefaultValue=i),l}},t}}class Extrema extends BaseComponent{static componentType="extrema";static rendererType=void 0;static componentTypeSingular="extremum";static get componentTypeCapitalized(){return this.componentType.charAt(0).toUpperCase()+this.componentType.slice(1)}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=this;return e.push({replacementFunction:function({matchedChildren:e}){let n=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==n.success?{success:!1}:{success:!0,newChildren:n.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:t.componentTypeSingular,children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"extrema",componentTypes:[this.componentTypeSingular]},{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e["n"+t.componentTypeCapitalized]={additionalStateVariablesDefined:["childIdentities"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["extrema","points"]}}),definition:function({dependencyValues:e}){return{setValue:{["n"+t.componentTypeCapitalized]:e.children.length,childIdentities:e.children}}}},e[t.componentType]={isArray:!0,nDimensions:2,entryPrefixes:[t.componentTypeSingular,t.componentTypeSingular+"Locations",t.componentTypeSingular+"Location",t.componentTypeSingular+"Values",t.componentTypeSingular+"Value"],stateVariablesDeterminingDependencies:["childIdentities"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:n,arraySize:r}){if([t.componentTypeSingular,t.componentTypeSingular+"Location",t.componentTypeSingular+"Value"].includes(e)){let a=Number(n)-1;return Number.isInteger(a)&&a>=0&&(!r||at+",0")):["0,0"]:e===t.componentTypeSingular+"Values"?""!==n?[]:r?Array.from(Array(r[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[n,r]=e.split(",");return"0"===r?t.componentTypeSingular+"Location"+(Number(n)+1):t.componentTypeSingular+"Value"+(Number(n)+1)},arrayVarNameFromPropIndex(e,n){if(n===t.componentType){if(1===e.length)return t.componentTypeSingular+e[0];{let n=Number(e[0]);if(Number.isInteger(n)&&n>0){if(1===e[1])return t.componentTypeSingular+"Location"+n;if(2===e[1])return t.componentTypeSingular+"Value"+n}return null}}if(n===t.componentTypeSingular+"Locations")return t.componentTypeSingular+"Location"+e[0];if(n===t.componentTypeSingular+"Values")return t.componentTypeSingular+"Value"+e[0];let r=t.componentTypeSingular.length;if(n.slice(0,r)===t.componentTypeSingular){let a=Number(n.slice(r));if(Number.isInteger(a)&&a>0){if(1===e[0])return t.componentTypeSingular+"Location"+a;if(2===e[0])return t.componentTypeSingular+"Value"+a}}return null},returnArraySizeDependencies:()=>({nChildren:{dependencyType:"stateVariable",variableName:"n"+t.componentTypeCapitalized}}),returnArraySize:({dependencyValues:e})=>[e.nChildren,2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:n}){let r={};for(let a of e){let e,[i,s]=a.split(",");e=n.childIdentities[i].componentType===t.componentTypeSingular?0===Number(s)?"location":"value":"x"+(Number(s)+1),r[a]={child:{dependencyType:"child",childGroups:["extrema","points"],variableNames:[e],childIndices:[i]}}}return{dependenciesByKey:r}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:n}){let r={};for(let t of n){let n=e[t].child[0];if(n){let e=t.split(",")[1],a=0===Number(e)?"location":"value";a in n.stateValues?r[t]=n.stateValues[a]:r[t]=n.stateValues["x"+(Number(e)+1)]}}return{setValue:{[t.componentType]:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:n}){let r=[];for(let a in e[t.componentType])r.push({setDependency:n[a].extremumChild,desiredValue:e[t.componentType][a],childIndex:0,variableIndex:0});return{success:!0,instructions:r}}},e}}var Extrema$1=Object.freeze({__proto__:null,Extremum:Extremum,Extrema:Extrema});class InlineRenderInlineChildren extends InlineComponent{static componentType="_inlineRenderInlineChildren";static renderChildren=!0;static includeBlankStringChildren=!0;static beginTextDelimiter="";static endTextDelimiter="";static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let n="";for(let t of e.inlineChildren)"object"!=typeof t?n+=t.toString():"string"==typeof t.stateValues.text?n+=t.stateValues.text:n+=" ";return n=t.beginTextDelimiter+n+t.endTextDelimiter,{setValue:{text:n}}}},e}}class Em extends InlineRenderInlineChildren{static componentType="em"}class Alert extends InlineRenderInlineChildren{static componentType="alert"}class Q$2 extends InlineRenderInlineChildren{static componentType="q";static beginTextDelimiter='"';static endTextDelimiter='"'}class SQ extends InlineRenderInlineChildren{static componentType="sq";static beginTextDelimiter="'";static endTextDelimiter="'"}class Term extends InlineRenderInlineChildren{static componentType="term";static rendererType="alert"}class C$2 extends InlineRenderInlineChildren{static componentType="c"}class Tag extends InlineRenderInlineChildren{static componentType="tag";static rendererType="tag";static beginTextDelimiter="<";static endTextDelimiter=">"}class Tage extends InlineRenderInlineChildren{static componentType="tage";static rendererType="tag";static beginTextDelimiter="<";static endTextDelimiter="/>";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.selfClosed={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{selfClosed:!0}})},e}}class Attr extends InlineRenderInlineChildren{static componentType="attr";static rendererType="c"}var ParagraphMarkup=Object.freeze({__proto__:null,Em:Em,Alert:Alert,Q:Q$2,SQ:SQ,Term:Term,C:C$2,Tag:Tag,Tage:Tage,Attr:Attr});class SingleCharacter extends InlineComponent{static componentType="_singleCharacterInline";static unicodeCharacter="";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({}),definition:()=>({setValue:{text:this.unicodeCharacter}})},e}}class Ndash extends SingleCharacter{static componentType="ndash";static unicodeCharacter="–"}class Mdash extends SingleCharacter{static componentType="mdash";static unicodeCharacter="—"}class NBSP extends SingleCharacter{static componentType="nbsp";static unicodeCharacter=" "}class Ellipsis extends SingleCharacter{static componentType="ellipsis";static unicodeCharacter="…"}var SingleCharacterComponents=Object.freeze({__proto__:null,Ndash:Ndash,Mdash:Mdash,NBSP:NBSP,Ellipsis:Ellipsis});class BlockComponent extends BaseComponent{static componentType="_block"}function returnDefaultFeedbackDefinitions(){return{numericalerror:"Credit reduced because numbers in your answer weren't quite right. Did you round too much?",goodjob:"Good job!",onesignerror:"Credit reduced because it appears that you made a sign error.",twosignerrors:"Credit reduced because it appears that you made two sign errors."}}function returnFeedbackDefinitionStateVariables(){let e={setupChildren:{returnDependencies:()=>({setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}}),definition:({dependencyValues:e})=>({setValue:{setupChildren:e.setupChildren}})}};return e.feedbackDefinitions={stateVariablesDeterminingDependencies:["setupChildren"],returnDependencies({stateValues:e}){let t={ancestorWithFeedback:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}};for(let n of e.setupChildren)t[`feedbackDefinitionsOf${n.componentName}`]={dependencyType:"child",parentName:n.componentName,childGroups:["feedbackDefinitions"],variableNames:["value"]};return t},definition({dependencyValues:e}){let t,n={};e.ancestorWithFeedback&&(t=e.ancestorWithFeedback.stateValues.feedbackDefinitions),t||(t=returnDefaultFeedbackDefinitions()),Object.assign(n,t);let r=[];for(let t of e.setupChildren)r.push(...e[`feedbackDefinitionsOf${t.componentName}`]);for(let e of r)Object.assign(n,e.stateValues.value);return{setValue:{feedbackDefinitions:n}}}},e}class SectioningComponent extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{submitAllAnswers:this.submitAllAnswers.bind(this),revealSection:this.revealSection.bind(this),closeSection:this.closeSection.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="_sectioningComponent";static renderChildren=!0;static includeBlankStringChildren=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.aggregateScores={createComponentOfType:"boolean",createStateVariable:"aggregateScores",defaultValue:!1,public:!0},e.weight={createComponentOfType:"number",createStateVariable:"weight",defaultValue:1,public:!0},e.sectionWideCheckWork={createComponentOfType:"boolean",createStateVariable:"sectionWideCheckWork",defaultValue:!1,public:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0},e.boxed={createComponentOfType:"boolean",createStateVariable:"boxed",defaultValue:!1,public:!0,forRenderer:!0},e.suppressAutoName={createComponentOfType:"boolean",createStateVariable:"suppressAutoName",defaultValue:!1,public:!0},e.suppressAutoNumber={createComponentOfType:"boolean",createStateVariable:"suppressAutoNumber",defaultValue:!1,public:!0},e.includeAutoName={createComponentOfType:"boolean",createStateVariable:"includeAutoName",defaultValue:!1,public:!0},e.includeAutoNumber={createComponentOfType:"boolean",createStateVariable:"includeAutoNumber",defaultValue:!1,public:!0},e.includeAutoNameNumberIfNoTitle={createComponentOfType:"boolean",createStateVariable:"includeAutoNameNumberIfNoTitle",defaultValue:!0,public:!0},e.includeParentNumber={createComponentOfType:"boolean",createStateVariable:"includeParentNumber",defaultValue:!1,public:!0},e.level={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"variantControls",componentTypes:["variantControl"]},{group:"titles",componentTypes:["title"]},{group:"setups",componentTypes:["setup"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStyleDefinitionStateVariables();Object.assign(e,t);let n=returnFeedbackDefinitionStateVariables();return Object.assign(e,n),e.enumeration={additionalStateVariablesDefined:[{variableName:"sectionNumber",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies:()=>({countAmongSiblings:{dependencyType:"countAmongSiblingsOfSameType"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["enumeration"]},includeParentNumber:{dependencyType:"stateVariable",variableName:"includeParentNumber"}}),definition({dependencyValues:e}){let t=[];return e.includeParentNumber&&e.sectionAncestor&&t.push(...e.sectionAncestor.stateValues.enumeration),t.push(e.countAmongSiblings),{setValue:{enumeration:t,sectionNumber:t.join(".")}}}},e.sectionName={returnDependencies:()=>({}),definition:()=>({setValue:{sectionName:"Section"}})},e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[e.titleChild.length-1].componentName),{setValue:{titleChildName:t}}}},e.childIndicesToRender={returnDependencies:()=>({titleChildren:{dependencyType:"child",childGroups:["titles"]},allChildren:{dependencyType:"child",childGroups:["anything","variantControls","titles","setups"]},titleChildName:{dependencyType:"stateVariable",variableName:"titleChildName"}}),definition({dependencyValues:e}){let t=[],n=e.titleChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())"object"==typeof a&&n.includes(a.componentName)&&a.componentName!==e.titleChildName||t.push(r);return{setValue:{childIndicesToRender:t}}}},e.title={additionalStateVariablesDefined:[{variableName:"titlePrefix",forRenderer:!0,alwaysUpdateRenderer:!0}],public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,alwaysUpdateRenderer:!0,returnDependencies:({sharedParameters:e})=>({titleChild:{dependencyType:"child",childGroups:["titles"],variableNames:["text"]},sectionName:{dependencyType:"stateVariable",variableName:"sectionName"},sectionNumber:{dependencyType:"stateVariable",variableName:"sectionNumber"},includeAutoName:{dependencyType:"stateVariable",variableName:"includeAutoName"},includeAutoNumber:{dependencyType:"stateVariable",variableName:"includeAutoNumber"},prerender:{dependencyType:"value",value:e.prerender},includeAutoNameNumberIfNoTitle:{dependencyType:"stateVariable",variableName:"includeAutoNameNumberIfNoTitle"}}),definition({dependencyValues:e}){let t="",n="";const r=e.titleChild.length>0;let a=(e.includeAutoNumber||!r&&e.includeAutoNameNumberIfNoTitle)&&!e.prerender,i=e.includeAutoName||!r&&e.includeAutoNameNumberIfNoTitle;return a?(i&&(t=e.sectionName+" "),t+=e.sectionNumber):i&&(t=e.sectionName),r?(t&&(e.includeAutoName?t+=": ":t+=". "),n=e.titleChild[e.titleChild.length-1].stateValues.text):n=t,{setValue:{title:n,titlePrefix:t}}}},e.containerTag={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{containerTag:"section"}})},e.level={forRenderer:!0,returnDependencies:()=>({ancestorLevel:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["level"]},levelAttr:{dependencyType:"attributeComponent",attributeName:"level",variableNames:["value"]}}),definition({dependencyValues:e}){let t=e.levelAttr?.stateValues.value;return t>0||(t=(e.ancestorLevel?.stateValues.level||0)+1),{setValue:{level:t}}}},e.viewedSolution={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{viewedSolution:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"viewedSolution",value:e.viewedSolution}]})},e.scoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"descendant",componentTypes:["_sectioningComponent","answer","setup"],variableNames:["scoredDescendants","aggregateScores","weight"],recurseToMatchedChildren:!1,variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.scoredDescendants)"setup"!==n.componentType&&(n.stateValues.aggregateScores||void 0===n.stateValues.scoredDescendants?t.push(n):t.push(...n.stateValues.scoredDescendants));return{setValue:{scoredDescendants:t}}}},e.answerDescendants={returnDependencies:()=>({answerDescendants:{dependencyType:"descendant",componentTypes:["answer"],variableNames:["justSubmitted"],recurseToMatchedChildren:!1}}),definition:({dependencyValues:e})=>({setValue:{answerDescendants:e.answerDescendants}})},e.justSubmitted={forRenderer:!0,returnDependencies:()=>({answerDescendants:{dependencyType:"stateVariable",variableName:"answerDescendants"}}),definition:({dependencyValues:e})=>({setValue:{justSubmitted:e.answerDescendants.every((e=>e.stateValues.justSubmitted))}})},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition:({dependencyValues:e})=>({setValue:{showCorrectness:!1!==e.showCorrectnessFlag}})},e.displayDigitsForCreditAchieved={returnDependencies:()=>({}),definition:()=>({setValue:{displayDigitsForCreditAchieved:3}})},e.creditAchieved={public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},forRenderer:!0,defaultValue:0,hasEssential:!0,additionalStateVariablesDefined:[{variableName:"percentCreditAchieved",public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},defaultValue:0,hasEssential:!0}],stateVariablesDeterminingDependencies:["aggregateScores","scoredDescendants"],returnDependencies({stateValues:e}){let t={aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"}};if(e.aggregateScores){t.scoredDescendants={dependencyType:"stateVariable",variableName:"scoredDescendants"};for(let[n,r]of e.scoredDescendants.entries())t["creditAchieved"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchieved"}}return t},definition({dependencyValues:e}){if(!e.aggregateScores)return{setValue:{creditAchieved:0,percentCreditAchieved:0}};let t,n=0,r=0;for(let[t,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;n+=e["creditAchieved"+t]*i,r+=i}return t=r>0?n/r:1,{setValue:{creditAchieved:t,percentCreditAchieved:100*t}}}},e.creditAchievedIfSubmit={defaultValue:0,stateVariablesDeterminingDependencies:["aggregateScores","scoredDescendants"],returnDependencies({stateValues:e}){let t={aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"}};if(e.aggregateScores){t.scoredDescendants={dependencyType:"stateVariable",variableName:"scoredDescendants"};for(let[n,r]of e.scoredDescendants.entries())t["creditAchievedIfSubmit"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchievedIfSubmit"}}return t},definition({dependencyValues:e}){if(!e.aggregateScores)return{setValue:{creditAchievedIfSubmit:0}};let t=0,n=0;for(let[r,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;t+=e["creditAchievedIfSubmit"+r]*i,n+=i}return{setValue:{creditAchievedIfSubmit:t/n}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantIndex:{dependencyType:"value",value:e.variantIndex},variantName:{dependencyType:"value",value:e.variantName},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={};e.variantName?(n.index=e.variantIndex,n.name=e.variantName):n.seed=e.variantSeed,n.meta={createdBy:t};let r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e.collapsible={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{collapsible:!1}})},e.open={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{open:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"open",value:e.open}]})},e.createSubmitAllButton={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"suppressAnswerSubmitButtons",forRenderer:!0}],returnDependencies:()=>({sectionWideCheckWork:{dependencyType:"stateVariable",variableName:"sectionWideCheckWork"},aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["suppressAnswerSubmitButtons"]},documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["suppressAnswerSubmitButtons"]}}),definition({dependencyValues:e,componentName:t}){let n=!1,r=!1;return e.documentAncestor.stateValues.suppressAnswerSubmitButtons||e.sectionAncestor&&e.sectionAncestor.stateValues.suppressAnswerSubmitButtons?r=!0:e.sectionWideCheckWork&&(e.aggregateScores?(n=!0,r=!0):console.warn(`Cannot create submit all button for ${t} because it doesn't aggegrate scores`)),{setValue:{createSubmitAllButton:n,suppressAnswerSubmitButtons:r}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e}async submitAllAnswers({actionId:e}){this.coreFunctions.requestRecordEvent({verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType},result:{creditAchieved:await this.stateValues.creditAchievedIfSubmit}});for(let e of await this.stateValues.answerDescendants)await e.stateValues.justSubmitted||await this.coreFunctions.performAction({componentName:e.componentName,actionName:"submitAnswer"});this.coreFunctions.resolveAction({actionId:e})}async revealSection({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!0}],overrideReadOnly:!0,actionId:e,event:{verb:"viewed",object:{componentName:this.componentName,componentType:this.componentType}}})}async closeSection({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!1}],overrideReadOnly:!0,actionId:e,event:{verb:"closed",object:{componentName:this.componentName,componentType:this.componentType}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){if(!e.variants?.allPossibleVariants)return void setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0});let r,a=e.variants.numberOfVariants,i=e.variants.desiredVariant;if(void 0!==i&&void 0!==i.index){let e=Number(i.index);if(Number.isFinite(e)){Number.isInteger(e)||(console.warn("Variant index "+i.index+" must be an integer"),e=Math.round(e));let t=(e-1)%a;t<0&&(t+=a),r=t+1}else console.warn("Variant index "+i.index+" must be a number"),r=1}if(void 0===r){let e=t.variantRng();r=Math.floor(e*a)+1}if(t.allPossibleVariants=e.variants.allPossibleVariants,t.allVariantNames=e.variants.allVariantNames,t.variantSeed=e.variants.allPossibleVariantSeeds[r-1],t.variantIndex=r,t.variantName=e.variants.allPossibleVariants[r-1],t.uniqueIndex=e.variants.allPossibleVariantUniqueIndices[r-1],t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t})}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){if(!e.variants.allPossibleVariants)return super.getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n});let r=e.variants.allPossibleVariantUniqueIndices[t-1];if(void 0===r)return{success:!1};if(!e.variants.uniqueVariants)return{success:!0,desiredVariant:{index:t}};let a=getVariantsForDescendantsForUniqueVariants({variantIndex:r,serializedComponent:e,componentInfoObjects:n});return a.success?(e.variants.selectedUniqueVariant=!0,{success:!0,desiredVariant:{index:t,subvariants:a.desiredVariants}}):(console.log("Failed to get unique variant for section."),{success:!1})}}class Section extends SectioningComponent{static componentType="section";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.includeParentNumber.defaultValue=!0,e}}class Subsection extends Section{static componentType="subsection"}class Subsubsection extends Section{static componentType="subsubsection"}class Paragraphs extends SectioningComponent{static componentType="paragraphs";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.level.definition=()=>({setValue:{level:4}}),e.sectionName.definition=()=>({setValue:{sectionName:"Paragraphs"}}),e}}class Aside extends SectioningComponent{static componentType="aside";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.collapsible={createComponentOfType:"boolean",createStateVariable:"collapsible",defaultValue:!0,public:!0,forRenderer:!0},e.startOpen={createComponentOfType:"boolean",createStateVariable:"startOpen",defaultValue:!1},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.collapsible,e.open.returnDependencies=()=>({startOpen:{dependencyType:"stateVariable",variableName:"startOpen"}}),e.open.definition=({dependencyValues:e})=>({useEssentialOrDefaultValue:{open:{defaultValue:e.startOpen}}}),e.level.definition=()=>({setValue:{level:3}}),e.containerTag.definition=()=>({setValue:{containerTag:"aside"}}),e.sectionName.definition=()=>({setValue:{sectionName:"Aside"}}),e}}class Problem extends SectioningComponent{static componentType="problem";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.aggregateScores.defaultValue=!0,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Problem"}}),e}}class Exercise extends Problem{static componentType="exercise";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Exercise"}}),e}}class Example extends SectioningComponent{static componentType="example";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Example"}}),e}}class StandinForFutureLayoutTag extends SectioningComponent{static componentType="standinForFutureLayoutTag";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.level.definition=()=>({setValue:{level:3}}),e.containerTag.definition=()=>({setValue:{containerTag:"aside"}}),e}}class externalContent extends SectioningComponent{static componentType="externalContent";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.includeAutoNameNumberIfNoTitle.defaultValue=!1,e}}var Sectioning=Object.freeze({__proto__:null,Section:Section,Subsection:Subsection,Subsubsection:Subsubsection,Paragraphs:Paragraphs,Aside:Aside,Problem:Problem,Exercise:Exercise,Example:Example,StandinForFutureLayoutTag:StandinForFutureLayoutTag,externalContent:externalContent});class Ol extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="ol";static rendererType="list";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.label={createComponentOfType:"text",createStateVariable:"label",defaultValue:null,public:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"lis",componentTypes:["li"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!0}})},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Ul extends Ol{static componentType="ul";static rendererType="list";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!1}})},e}}class Li$1 extends BaseComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="li";static rendererType="list";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.item={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{item:!0}})},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Lists=Object.freeze({__proto__:null,Ol:Ol,Ul:Ul,Li:Li$1});class ODESystem extends InlineComponent{static componentType="odesystem";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.independentVariable={createComponentOfType:"variable",createStateVariable:"independentVariable",defaultValue:me$3.fromAst("t"),public:!0},e.initialIndependentVariableValue={createComponentOfType:"math",createStateVariable:"initialIndependentVariableValue",defaultValue:me$3.fromAst(0),public:!0},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:14,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.renderMode={createComponentOfType:"text",createStateVariable:"renderMode",defaultValue:"align",public:!0,forRenderer:!0},e.chunkSize={createComponentOfType:"number",createStateVariable:"chunkSize",defaultValue:10,public:!0},e.tolerance={createComponentOfType:"number",createStateVariable:"tolerance",defaultValue:1e-6,public:!0},e.maxIterations={createComponentOfType:"number",createStateVariable:"maxIterations",defaultValue:1e3,public:!0},e.hideInitialCondition={createComponentOfType:"boolean",createStateVariable:"hideInitialCondition",defaultValue:!1,public:!0},e.initialConditions={createComponentOfType:"mathList"},e.variables={createComponentOfType:"variables"},e.number={createComponentOfType:"boolean",createStateVariable:"number",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"rightHandSides",componentTypes:["rightHandSide"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.validIndependentVariable={returnDependencies:()=>({independentVarAttr:{dependencyType:"attributeComponent",attributeName:"independentVariable",variableNames:["validVariable"]}}),definition({dependencyValues:e}){let t=!0;return e.independentVarAttr&&(t=e.independentVarAttr.stateValues.validVariable),{setValue:{validIndependentVariable:t}}}},e.nDimensions={returnDependencies:()=>({rhsChildren:{dependencyType:"child",childGroups:["rightHandSides"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nDimensions:e.rhsChildren.length},checkForActualChange:{nDimensions:!0}}}},e.variables={additionalStateVariablesDefined:[{variableName:"validVariables",isArray:!0,entryPrefixes:["validVar"]}],isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["var"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},variables:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables","validVariables"]},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=[],n=[],r=e.nDimensions;null!==e.variables&&(t=e.variables.stateValues.variables,n=[...e.variables.stateValues.validVariables].slice(0,r));let a=returnNVariables(r,t);return a.some((t=>t.equals(e.independentVariable)))&&console.warn("Variables of odesystem must be different than independent variable."),n.length({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={rhsChild:{dependencyType:"child",childGroups:["rightHandSides"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].rhsChild[0].stateValues.value;return{setValue:{rhss:n}}}},e.rhs={isAlias:!0,targetVariableName:"rhs1"},e.righthandside={isAlias:!0,targetVariableName:"rhs1"},e.righthandsides={isAlias:!0,targetVariableName:"rhss"},e.initialConditions={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["initialCondition"],defaultValueByArrayKey:()=>me$3.fromAst(0),returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={initialConditionAttr:{dependencyType:"attributeComponent",attributeName:"initialConditions",variableNames:[`math${Number(n)+1}`]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=!1;if(e[a].initialConditionAttr){let r=e[a].initialConditionAttr.stateValues[`math${Number(a)+1}`];void 0!==r&&(t=!0,n[a]=r)}t||(r[a]=!0)}let a={};return Object.keys(n).length>0&&(a.setValue={initialConditions:n}),Object.keys(r).length>0&&(a.useEssentialOrDefaultValue={initialConditions:r}),a}},e.initialCondition={isAlias:!0,targetVariableName:"initialCondition1"},e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["number"],returnDependencies:({stateValues:e})=>e.number?{equationCounter:{dependencyType:"counter",counterName:"equation"}}:{},definition:({dependencyValues:e})=>void 0!==e.equationCounter?{setValue:{equationTag:String(e.equationCounter)}}:{setValue:{equationTag:null}}},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},variables:{dependencyType:"stateVariable",variableName:"variables"},initialConditions:{dependencyType:"stateVariable",variableName:"initialConditions"},hideInitialCondition:{dependencyType:"stateVariable",variableName:"hideInitialCondition"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},initialIndependentVariableValue:{dependencyType:"stateVariable",variableName:"initialIndependentVariableValue"},rhss:{dependencyType:"stateVariable",variableName:"rhss"},number:{dependencyType:"stateVariable",variableName:"number"},equationTag:{dependencyType:"stateVariable",variableName:"equationTag"}}),definition({dependencyValues:e,usedDefault:t}){let n={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits));let r=[],a=e.independentVariable.toLatex();for(let i=0;i({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},e.numericalRHSf={additionalStateVariablesDefined:["numericalRHSfDefinitions"],returnDependencies:()=>({validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},rhss:{dependencyType:"stateVariable",variableName:"rhss"}}),definition({dependencyValues:e}){let t=!0;e.validIndependentVariable||(console.warn("Can't define ODE RHS functions with invalid independent variable."),t=!1),e.validVariables.every((e=>e))||(console.warn("Can't define ODE RHS functions with an invalid variable."),t=!1);let n,r=e.independentVariable.subscripts_to_strings().tree,a=e.variables.map((e=>e.subscripts_to_strings().tree));a.includes(r)&&(console.warn("Can't define ODE RHS functions when independent variable is a dependent variable"),t=!1),[...new Set(a)].length!==a.length&&(console.warn("Can't define ODE RHS functions with duplicate dependent variable names"),t=!1);try{n=e.rhss.map((e=>e.subscripts_to_strings().f()))}catch(e){console.warn("Cannot define ODE RHS function. Error creating mathjs function"),t=!1}if(!t){let t=e.rhss.length;return{setValue:{numericalRHSf:()=>NaN,numericalRHSfDefinitions:Array(t).fill({})}}}return{setValue:{numericalRHSf:function(e,t){let i={[r]:e};Array.isArray(t)?t.forEach(((e,t)=>i[a[t]]=e)):i[a[0]]=t;try{return n.map((e=>e(i)))}catch(e){return NaN}},numericalRHSfDefinitions:e.rhss.map((e=>({functionType:"formula",formula:e,nInputs:a.length+1,variables:[r,...a]})))}}}},e.haveNumericalInitialConditions={additionalStateVariablesDefined:["t0","x0s"],returnDependencies:()=>({initialIndependentVariableValue:{dependencyType:"stateVariable",variableName:"initialIndependentVariableValue"},initialConditions:{dependencyType:"stateVariable",variableName:"initialConditions"}}),definition({dependencyValues:e}){let t=e.initialIndependentVariableValue.evaluate_to_constant(),n=e.initialConditions.map((e=>e.evaluate_to_constant())),r=Number.isFinite(t)&&n.every((e=>Number.isFinite(e)));return{setValue:{t0:t,x0s:n,haveNumericalInitialConditions:r}}}},e.numericalSolutions={isArray:!0,entryPrefixes:["numericalSolution"],public:!0,shadowingInstructions:{createComponentOfType:"function",addStateVariablesShadowingStateVariables:{fDefinition:{stateVariableToShadow:"numericalSolutionFDefinitions"}}},createWorkspace:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},chunkSize:{dependencyType:"stateVariable",variableName:"chunkSize"},tolerance:{dependencyType:"stateVariable",variableName:"tolerance"},maxIterations:{dependencyType:"stateVariable",variableName:"maxIterations"},haveNumericalInitialConditions:{dependencyType:"stateVariable",variableName:"haveNumericalInitialConditions"},t0:{dependencyType:"stateVariable",variableName:"t0"},x0s:{dependencyType:"stateVariable",variableName:"x0s"},numericalRHSf:{dependencyType:"stateVariable",variableName:"numericalRHSf"}}}),arrayDefinitionByKey({globalDependencyValues:e,workspace:t,componentName:n}){let r={};if(t.calculatedNumericSolutions=[],t.endingNumericalValues=[],t.maxPossibleTime=void 0,!e.haveNumericalInitialConditions){for(let t=0;tNaN;return{setValue:{numericalSolutions:r}}}let a=e.t0,i=e.x0s,s=e.chunkSize,o=e.tolerance,l=e.numericalRHSf,u=e.maxIterations;for(let c=0;c=r)for(let e=r;e<=p;e++){let r=t.endingNumericalValues[e-1];void 0===r&&(r=i);let c=a+e*s,p=me$3.math.dopri(c,c+s,r,l,o,u);t.endingNumericalValues.push(p.y[p.y.length-1]),t.calculatedNumericSolutions.push(p.at.bind(p));let d=p.x[p.x.length-1];if(d<.999999*(c+s)){t.maxPossibleTime=d;let e="For chunksize "+s+" and tolerance "+o+", odesystem";void 0!==n&&(e+=" ("+n+")"),e+=" hit maxiterations ("+u+") at t = "+t.maxPossibleTime+". Will not calculate solution beyond that time. Decrease chunksize, increase maxiterations, or increase tolerance to calculate further.";break}}return e>t.maxPossibleTime?NaN:t.calculatedNumericSolutions[p](e)[c]};return{setValue:{numericalSolutions:r}}}},e.numericalSolution={isAlias:!0,targetVariableName:"numericalSolution1"},e.numericalSolutionFDefinitions={forRenderer:!0,isArray:!0,entryPrefixes:["numericalSolutionFDefinition"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},chunkSize:{dependencyType:"stateVariable",variableName:"chunkSize"},tolerance:{dependencyType:"stateVariable",variableName:"tolerance"},maxIterations:{dependencyType:"stateVariable",variableName:"maxIterations"},haveNumericalInitialConditions:{dependencyType:"stateVariable",variableName:"haveNumericalInitialConditions"},t0:{dependencyType:"stateVariable",variableName:"t0"},x0s:{dependencyType:"stateVariable",variableName:"x0s"},numericalRHSfDefinitions:{dependencyType:"stateVariable",variableName:"numericalRHSfDefinitions"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>e.haveNumericalInitialConditions?{setValue:{numericalSolutionFDefinitions:[...Array(e.nDimensions).keys()].map((t=>({functionType:"ODESolution",nDimensions:e.nDimensions,t0:e.t0,x0s:e.x0s,chunkSize:e.chunkSize,tolerance:e.tolerance,numericalRHSfDefinitions:e.numericalRHSfDefinitions,maxIterations:e.maxIterations,component:t})))}}:{setValue:{numericalSolutionFDefinitions:Array(e.nDimensions).fill({})}}},e}}class Polyline extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{movePolyline:this.movePolyline.bind(this),finalizePolylinePosition:this.finalizePolylinePosition.bind(this),polylineClicked:this.polylineClicked.bind(this),mouseDownOnPolyline:this.mouseDownOnPolyline.bind(this)})}static componentType="polyline";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.verticesDraggable={createComponentOfType:"boolean"},e.vertices={createComponentOfType:"_pointListComponent"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" polyline"}}}},e.verticesDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({verticesDraggableAttr:{dependencyType:"attributeComponent",attributeName:"verticesDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.verticesDraggableAttr?{setValue:{verticesDraggable:e.verticesDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{verticesDraggable:{defaultValue:e.draggable}}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.vertices?{setValue:{nVertices:e.vertices.stateValues.nPoints}}:{setValue:{nVertices:0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.vertices){return{setValue:{nDimensions:e.vertices.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},getAllArrayKeys(e,t=!0,n){function r(e){if(1===e.length)return Array.from(Array(e[0]),((e,t)=>String(t)));{let n=e[0],a=r(e.slice(1)),i=[];for(let e=0;ee+","+t))):i.push(a.map((t=>e+","+t)));return i}}if(n){if(0!==n.length&&e){let t=[...e];return t[0]=n[0],r(t)}return[]}return e&&0!==e.length?r(e):[]},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].vertices;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst("_")}return{setValue:{vertices:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){let i=[];for(let r in e.vertices){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].vertices||!t[r].vertices.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].vertices,desiredValue:e.vertices[r],variableIndex:0})}return{success:!0,instructions:i}}},e.numericalVertices={isArray:!0,entryPrefixes:["numericalVertex"],forRenderer:!0,returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={vertex:{dependencyType:"stateVariable",variableName:"vertex"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalVertices:n}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,s=[],o=i[0]?.[0],l=i[0]?.[1];for(let e=1;e=1?{x1:h,x2:f}:{x1:l+g*a*n,x2:u+g*y*o};let b=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/o,2);b0&&(p.x3=0),p}}}}},e}async movePolyline({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){if(1===Object.keys(e).length){if(!await this.stateValues.verticesDraggable)return await this.coreFunctions.resolveAction({actionId:r})}else if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:r});let a={};for(let t in e)a[t+",0"]=me$3.fromAst(e[t][0]),a[t+",1"]=me$3.fromAst(e[t][1]);return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],transient:t,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}async finalizePolylinePosition(){return await this.actions.movePolyline({pointCoords:await this.stateValues.numericalVertices,transient:!1})}async polylineClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnPolyline({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class CobwebPolyline extends Polyline{static componentType="cobwebPolyline";static rendererType="cobwebPolyline";static createAttributesObject(){let e=super.createAttributesObject();return e.attractThreshold={createComponentOfType:"number",createStateVariable:"attractThreshold",defaultValue:.5,public:!0},e.nPoints={createComponentOfType:"number",createStateVariable:"nPoints",defaultValue:1,public:!0,clamp:[0,1/0],forRenderer:!0},e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x"),public:!0,forRenderer:!0},e.nIterationsRequired={createComponentOfType:"number",createStateVariable:"nIterationsRequired",defaultValue:0,public:!0},e.initialPoint={createComponentOfType:"point"},e.function={createComponentOfType:"function"},e.lockToSolution={createComponentOfType:"boolean",createStateVariable:"lockToSolution",defaultValue:!1},e.defaultPoint={createComponentOfType:"point"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nDimensions.returnDependencies=()=>({}),e.nDimensions.definition=()=>({setValue:{nDimensions:2}}),e.initialPoint={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"initialPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["initialPointX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={initialPointAttr:{dependencyType:"attributeComponent",attributeName:"initialPoint",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=Number(a)+1;e[a].initialPointAttr?n[a]=e[a].initialPointAttr.stateValues["x"+t]:r[a]=!0}let a={};return Object.keys(n).length>0&&(a.setValue={initialPoint:n}),Object.keys(r).length>0&&(a.useEssentialOrDefaultValue={initialPoint:r}),a},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.initialPoint)t[a].initialPointAttr&&t[a].initialPointAttr.stateValues["x"+(Number(a)+1)]?r.push({setDependency:n[a].initialPointAttr,desiredValue:e.initialPoint[a],variableIndex:0}):r.push({setEssentialValue:"initialPoint",value:{[a]:e.initialPoint[a]}});return{success:!0,instructions:r}}},e.f={additionalStateVariablesDefined:[{variableName:"fDefinition",forRenderer:!0}],returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["numericalf","fDefinition"]}}),definition:({dependencyValues:e})=>e.functionAttr?{setValue:{f:e.functionAttr.stateValues.numericalf,fDefinition:e.functionAttr.stateValues.fDefinition}}:{setValue:{f:null,fDefinition:null}}},e.nVertices={isAlias:!0,targetVariableName:"nPoints"},e.nOriginalVertices={providePreviousValuesInDefinition:!0,returnDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e,previousValues:t}){let n=e.nVertices;return t.nOriginalVertices>n&&(n=t.nOriginalVertices),{setValue:{nOriginalVertices:n}}}},e.originalVertices={isArray:!0,nDimensions:2,hasEssential:!0,entryPrefixes:["originalVertexX","originalVertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("originalVertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("originalVertices"===t)return 1===e.length?"originalVertex"+e[0]:`originalVertexX${e[0]}_${e[1]}`;if("originalVertex"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`originalVertexX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nOriginalVertices:{dependencyType:"stateVariable",variableName:"nOriginalVertices"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nOriginalVertices-1,e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},defaultPoint:{dependencyType:"attributeComponent",attributeName:"defaultPoint",variableNames:["xs"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",").map(Number);n[r]={get defaultValue(){if(e.defaultPoint){let n=e.defaultPoint.stateValues.xs;if(2===n.length&&t[1]<2)return n[t[1]]}if(e.graphAncestor){if(0===t[1]){let t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax;return me$3.fromAst((t+n)/2)}if(1===t[1]){let t=e.graphAncestor.stateValues.ymin,n=e.graphAncestor.stateValues.ymax;return me$3.fromAst((t+n)/2)}}return me$3.fromAst(0)}}}return{useEssentialOrDefaultValue:{originalVertices:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.originalVertices)t.push({setEssentialValue:"originalVertices",value:{[n]:e.originalVertices[n]}});return{success:!0,instructions:t}}},e.vertices.additionalStateVariablesDefined=[{variableName:"prelimCorrectVertices",entryPrefixes:["prelimCorrectVertexX","prelimCorrectVertex"],getArrayKeysFromVarName:function({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("prelimCorrectVertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}}}],e.vertices.basedOnArrayKeyStateVariables=!0,e.vertices.returnArrayDependenciesByKey=function({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]="0"===e?{initialPoint:{dependencyType:"stateVariable",variableName:"initialPointX"+(Number(r)+1)}}:{originalVertexX1:{dependencyType:"stateVariable",variableName:"originalVertexX"+e+"_1"},originalVertexX2:{dependencyType:"stateVariable",variableName:"originalVertexX"+e+"_2"},previousVertexX1:{dependencyType:"stateVariable",variableName:"vertexX"+e+"_1"},previousVertexX2:{dependencyType:"stateVariable",variableName:"vertexX"+e+"_2"}}}return{globalDependencies:{f:{dependencyType:"stateVariable",variableName:"f"},attractThreshold:{dependencyType:"stateVariable",variableName:"attractThreshold"},lockToSolution:{dependencyType:"stateVariable",variableName:"lockToSolution"}},dependenciesByKey:t}},e.vertices.arrayDefinitionByKey=function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let[n,s]=i.split(",");if("0"===n)r[i]=t[i].initialPoint,a[i]=null;else{let s,o,l;try{s=[t[i].originalVertexX1.evaluate_to_constant(),t[i].originalVertexX2.evaluate_to_constant()],o=[t[i].previousVertexX1.evaluate_to_constant(),t[i].previousVertexX2.evaluate_to_constant()]}catch(e){r[n+",0"]=me$3.fromAst(0),r[n+",1"]=me$3.fromAst(0),a[n+",0"]=!1;continue}if(Number(n)%2==1){let t=e.f(o[0]);l=[o[0],t]}else l=[o[1],o[1]];Math.pow(s[0]-l[0],2)+Math.pow(s[1]-l[1],2)({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices-1],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={prelimCorrectVertex:{dependencyType:"stateVariable",variableName:"prelimCorrectVertexX"+(Number(n)+2)+"_1"}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].prelimCorrectVertex;return{setValue:{correctVertices:n}}}},e.fractionCorrectVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"nGradedVertices",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"nCorrectVertices",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({correctVertices:{dependencyType:"stateVariable",variableName:"correctVertices"}}),definition({dependencyValues:e}){let t,n,r=e.correctVertices.length;return 0===r?(t=0,n=0):(n=e.correctVertices.reduce(((e,t)=>e+t),0),t=n/r),{setValue:{fractionCorrectVertices:t,nGradedVertices:r,nCorrectVertices:n}}}},e.fractionCorrectVerticesAdjusted={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"nGradedVerticesAdjusted",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({nCorrectVertices:{dependencyType:"stateVariable",variableName:"nCorrectVertices"},nGradedVertices:{dependencyType:"stateVariable",variableName:"nGradedVertices"},nIterationsRequired:{dependencyType:"stateVariable",variableName:"nIterationsRequired"}}),definition({dependencyValues:e}){let t=0;e.nIterationsRequired>0&&(t=2*e.nIterationsRequired-1);let n,r=Math.max(e.nGradedVertices,t);return n=0===r?0:e.nCorrectVertices/r,{setValue:{fractionCorrectVerticesAdjusted:n,nGradedVerticesAdjusted:r}}}},e.nIterateValues={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition:({dependencyValues:e})=>({setValue:{nIterateValues:Math.ceil((e.nVertices+1)/2)}})},e.iterateValues={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["iterateValue"],returnArraySizeDependencies:()=>({nIterateValues:{dependencyType:"stateVariable",variableName:"nIterateValues"}}),returnArraySize:({dependencyValues:e})=>[e.nIterateValues],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]="0"===n?{iterateValue:{dependencyType:"stateVariable",variableName:"vertexX1_1"}}:{iterateValue:{dependencyType:"stateVariable",variableName:"vertexX"+2*Number(n)+"_2"}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].iterateValue;return{setValue:{iterateValues:n}}}},e}}class Point extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{movePoint:this.movePoint.bind(this),switchPoint:this.switchPoint.bind(this),pointClicked:this.pointClicked.bind(this),mouseDownOnPoint:this.mouseDownOnPoint.bind(this)})}static componentType="point";static primaryStateVariableForDefinition="coordsShadow";static stateVariableForAttributeValue="coords";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.x={createComponentOfType:"math"},e.y={createComponentOfType:"math"},e.z={createComponentOfType:"math"},e.xs={createComponentOfType:"mathList"},e.coords={createComponentOfType:"coords"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.showCoordsWhenDragging={createComponentOfType:"boolean",createStateVariable:"showCoordsWhenDragging",defaultValue:!0,public:!0,forRenderer:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),r=e.map((e=>typeof e)),a=r.indexOf("string"),i=r.lastIndexOf("string");if(-1===a){let n=t.componentIsSpecifiedType,r=e.filter((e=>!(n(e,"point")||n(e,"vector")||n(e,"constraints")||n(e,"label"))));if(1===r.length){let t=r[0],n=e.indexOf(t);return{success:!0,newAttributes:{coords:{component:{componentType:"math",children:r}}},newChildren:[...e.slice(0,n),...e.slice(n+1)]}}return{success:!1}}let s=[...e.slice(0,a),...e.slice(i+1)],o=n({matchedChildren:e=e.slice(a,i+1)});return o.success||1!==e.length?o.success?{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:o.newChildren,skipSugar:!0}}},newChildren:s}:{success:!1}:{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:[{componentType:"math",children:e}]}}},newChildren:s}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"points",componentTypes:["point"]},{group:"vectors",componentTypes:["vector"]},{group:"constraints",componentTypes:["constraints"]}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescription:e.selectedStyle.markerColorWord}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.selectedStyle.markerColorWord+" "+e.selectedStyle.markerStyleWord}}}},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{coordsShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e,stateValues:t,workspace:n}){return{success:!0,instructions:[{setEssentialValue:"coordsShadow",value:e.coordsShadow}]}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({coordsShadow:{dependencyType:"stateVariable",variableName:"coordsShadow"},coords:{dependencyType:"attributeComponent",attributeName:"coords",variableNames:["value"]},x:{dependencyType:"attributeComponent",attributeName:"x"},y:{dependencyType:"attributeComponent",attributeName:"y"},z:{dependencyType:"attributeComponent",attributeName:"z"},xs:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["nComponents"]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){let t,n,r=!1;if(n=null!==e.z?3:null!==e.y?2:0,null!==e.coords?(r=!0,t=e.coords.stateValues.value):e.coordsShadow&&(r=!0,t=e.coordsShadow),r){let e=t.tree;return n=Array.isArray(e)&&vectorOperators.includes(e[0])?Math.max(e.length-1,n):Math.max(1,n),{setValue:{nDimensions:n},checkForActualChange:{nDimensions:!0}}}return null!==e.xs?{setValue:{nDimensions:Math.max(e.xs.stateValues.nComponents,n)}}:e.pointChild.length>0?{setValue:{nDimensions:Math.max(e.pointChild[0].stateValues.nDimensions,n)}}:e.vectorChild.length>0?{setValue:{nDimensions:Math.max(e.vectorChild[0].stateValues.nDimensions,n)}}:(0===n&&(n=2),{setValue:{nDimensions:n},checkForActualChange:{nDimensions:!0}})}},e.arrayVariableForConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{arrayVariableForConstraints:"unconstrainedXs"}})},e.arrayEntryPrefixForConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{arrayEntryPrefixForConstraints:"unconstrainedX"}})},e.nDimensionsForConstraints={isAlias:!0,targetVariableName:"nDimensions"},e.unconstrainedXs={isArray:!0,entryPrefixes:["unconstrainedX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={xs:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["math"+e]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+e]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+e]}},"0"===n?t[n].component={dependencyType:"attributeComponent",attributeName:"x",variableNames:["value"]}:"1"===n?t[n].component={dependencyType:"attributeComponent",attributeName:"y",variableNames:["value"]}:"2"===n&&(t[n].component={dependencyType:"attributeComponent",attributeName:"z",variableNames:["value"]})}return{globalDependencies:{coordsShadow:{dependencyType:"stateVariable",variableName:"coordsShadow"},coords:{dependencyType:"attributeComponent",attributeName:"coords",variableNames:["value"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r,a={},i={},s=!1;if(null!==e.coords?(s=!0,r=e.coords.stateValues.value):e.coordsShadow&&(s=!0,r=e.coordsShadow),s){let e=r.tree;if(Array.isArray(e)&&vectorOperators.includes(e[0]))for(let t of n){let n=Number(t);(n>=0||n0)a[e]=r[0].stateValues["x"+n];else{let r=t[e].vectorChild;r.length>0&&(a[e]=r[0].stateValues["x"+n])}}}for(let e of n){let n=t[e].component;n?a[e]=n.stateValues.value.simplify():void 0===a[e]&&(i[e]=!0)}let o={};return Object.keys(a).length>0&&(o.setValue={unconstrainedXs:a}),Object.keys(i).length>0&&(o.useEssentialOrDefaultValue={unconstrainedXs:i}),o},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i,s,o=[],l=!1,u=!1;null!==t.coords?(l=!0,i="coords",s=Array(a[0]+1)):null!==t.coordsShadow&&(l=!0,i="coordsShadow",s=Array(a[0]+1));for(let t of Object.keys(e.unconstrainedXs).reverse()){let a=convertValueToMathExpression(e.unconstrainedXs[t]);if(null!==n[t].component)o.push({setDependency:r[t].component,desiredValue:a,childIndex:0,variableIndex:0});else if(l)s[Number(t)+1]=a.tree,u=!0;else{if(null!==n[t].xs)o.push({setDependency:r[t].xs,desiredValue:a,childIndex:0,variableIndex:0});else{if(n[t].pointChild.length>0)o.push({setDependency:r[t].pointChild,desiredValue:a,childIndex:0,variableIndex:0});else{n[t].vectorChild.length>0?o.push({setDependency:r[t].vectorChild,desiredValue:a,childIndex:0,variableIndex:0}):o.push({setEssentialValue:"unconstrainedXs",value:{[t]:a}})}}}}if(u){let e;1===a[0]?e=me$3.fromAst(s[1]):(s[0]="vector",e=me$3.fromAst(s));let t={setDependency:i,desiredValue:e};"coords"===i&&(t.childIndex=0,t.variableIndex=0),o.push(t)}return{success:!0,instructions:o}}},e.xs={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["x"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1,r={};r.unconstrainedX={dependencyType:"stateVariable",variableName:`unconstrainedX${e}`},r.constraintsChild={dependencyType:"child",childGroups:["constraints"],variableNames:[`constraintResult${e}`]},t[n]=r}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)if(e[r].constraintsChild.length>0){let t=Number(r)+1;n[r]=convertValueToMathExpression(e[r].constraintsChild[0].stateValues["constraintResult"+t])}else n[r]=convertValueToMathExpression(e[r].unconstrainedX);return t.length>0?{setValue:{xs:n}}:{}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r of Object.keys(e.xs).reverse())t[r]&&(t[r].constraintsChild.length>0?i.push({setDependency:n[r].constraintsChild,desiredValue:e.xs[r],childIndex:0,variableIndex:0}):i.push({setDependency:n[r].unconstrainedX,desiredValue:e.xs[r]}));return{success:!0,instructions:i}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.coords={public:!0,shadowingInstructions:{createComponentOfType:"coords",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({xs:{dependencyType:"stateVariable",variableName:"xs"}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.xs)n?t.push(n.tree):t.push("_");return t=t.length>1?["vector",...t]:1===t.length?t[0]:"_",{setValue:{coords:me$3.fromAst(t)}}},inverseDefinition:async function({desiredStateVariableValues:e,stateValues:t,initialChange:n}){if(n&&!await t.draggable)return{success:!1};let r=[],a={},i=e.coords.tree;if(Array.isArray(i)&&vectorOperators.includes(i[0]))for(let t=0;t({coords:{dependencyType:"stateVariable",variableName:"coords"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.coords,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.value={isAlias:!0,targetVariableName:"coords"},e.constraintUsed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({constraintsChild:{dependencyType:"child",childGroups:["constraints"],variableNames:["constraintUsed"]}}),definition:function({dependencyValues:e}){return 0===e.constraintsChild.length?{setValue:{constraintUsed:!1}}:{setValue:{constraintUsed:e.constraintsChild[0].stateValues.constraintUsed}}}},e.numericalXs={isArray:!0,entryPrefixes:["numericalX"],forRenderer:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={x:{dependencyType:"stateVariable",variableName:`x${e}`}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].x;t?(t=e[r].x.evaluate_to_constant(),Number.isFinite(t)?n[r]=t:n[r]=NaN):n[r]=NaN}return{setValue:{numericalXs:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,initialChange:n,stateValues:r}){if(n&&!await r.draggable)return{success:!1};let a=[];for(let n in e.numericalXs)dependencyValuesByKey[n]&&a.push({setDependency:t[n].xs,desiredValue:e.numericalXs[n]});return{success:!0,instructions:a}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalXs:{dependencyType:"stateVariable",variableName:"numericalXs"}}),definition:({dependencyValues:e})=>({setValue:{nearestPoint:function(){let t={};for(let n=1;n<=e.nDimensions;n++){let r=e.numericalXs[n-1];if(!Number.isFinite(r))return{};t["x"+n]=r}return t}}})},e}static adapters=[{stateVariable:"coords",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async movePoint({x:e,y:t,z:n,transient:r,actionId:a}){let i={};return void 0!==e&&(i[0]=me$3.fromAst(e)),void 0!==t&&(i[1]=me$3.fromAst(t)),void 0!==n&&(i[2]=me$3.fromAst(n)),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"xs",value:i}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"xs",value:i}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}switchPoint(){}async pointClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnPoint({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class EquilibriumPoint extends Point{static componentType="equilibriumPoint";static rendererType="point";static createAttributesObject(){let e=super.createAttributesObject();return e.stable={createComponentOfType:"boolean",createStateVariable:"stable",defaultValue:!0,public:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.open={forRenderer:!0,returnDependencies:()=>({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{open:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.open}]})},e}async switchPoint({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}class Line extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveLine:this.moveLine.bind(this),switchLine:this.switchLine.bind(this),lineClicked:this.lineClicked.bind(this),mouseDownOnLine:this.mouseDownOnLine.bind(this)})}static componentType="line";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.equation={createComponentOfType:"math"},e.through={createComponentOfType:"_pointListComponent"},e.slope={createComponentOfType:"number"},e.variables={createComponentOfType:"variables"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){if(0===e.length)return{success:!1};let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a.push(...e.slice(0,t)),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),a.push(...e.slice(t)))}return 0===r.length?{success:!1}:{success:!0,newAttributes:{equation:{component:{componentType:"math",children:r}}},newChildren:a}}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" line"}}}},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null===e.throughAttr?{setValue:{nPointsPrescribed:0}}:{setValue:{nPointsPrescribed:e.throughAttr.stateValues.nPoints}}}},e.basedOnSlope={returnDependencies:()=>({slopeAttr:{dependencyType:"attributeComponent",attributeName:"slope"},nPointsPrescribed:{dependencyType:"stateVariable",variableName:"nPointsPrescribed"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition:({dependencyValues:e})=>({setValue:{basedOnSlope:e.nPointsPrescribed<2&&null!==e.slopeAttr&&2===e.nDimensions}})},e.dForSlope={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{dForSlope:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"dForSlope",value:e.dForSlope}]})},e.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["var"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{variables:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n=[];return null!==e.variables&&(n=e.variables.stateValues.variables),{setValue:{variables:returnNVariables(t[0],n)}}}},e.equationIdentity={returnDependencies:()=>({equation:{dependencyType:"attributeComponent",attributeName:"equation"}}),definition:function({dependencyValues:e}){return null!==e.equation?{setValue:{equationIdentity:e.equation}}:{setValue:{equationIdentity:null}}}},e.essentialPoints={isArray:!0,nDimensions:"2",hasEssential:!0,entryPrefixes:["essentialPointX","essentialPoint"],set:convertValueToMathExpression,defaultValueByArrayKey:e=>me$3.fromAst("0,0"===e?1:0),getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("essentialPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialPoints:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.essentialPoints)t.push({setEssentialValue:"essentialPoints",value:{[n]:convertValueToMathExpression(e.essentialPoints[n])}});return{success:!0,instructions:t}}},e.points={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"pointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("points"===t)return 1===e.length?"point"+e[0]:`pointX${e[0]}_${e[1]}`;if("point"===t.slice(0,5)){let n=Number(t.slice(5));if(Number.isInteger(n)&&n>0)return`pointX${n}_${e[0]}`}return null},stateVariablesDeterminingDependencies:["equationIdentity","nPointsPrescribed","basedOnSlope"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey({stateValues:e,arrayKeys:t}){if(null===e.equationIdentity){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1);n[r]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+i]}},e.basedOnSlope?("1"===t&&(1===e.nPointsPrescribed&&n[r].through.variableNames.push("pointX1_"+(Number(a)+1)),n[r].dForSlope={dependencyType:"stateVariable",variableName:"dForSlope"},n[r].slopeAttr={dependencyType:"attributeComponent",attributeName:"slope",variableNames:["value"]}),0===e.nPointsPrescribed&&(n[r].essentialPoint={dependencyType:"stateVariable",variableName:"essentialPointX2_"+(Number(a)+1)})):n[r].essentialPoint={dependencyType:"stateVariable",variableName:"essentialPointX"+i}}return{dependenciesByKey:n,globalDependencies:{nPointsPrescribed:{dependencyType:"stateVariable",variableName:"nPointsPrescribed"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},basedOnSlope:{dependencyType:"stateVariable",variableName:"basedOnSlope"}}}}return{globalDependencies:{coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"},variables:{dependencyType:"stateVariable",variableName:"variables"},lastPointsFromInverting:{dependencyType:"stateVariable",variableName:"lastPointsFromInverting"}}}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r,componentName:a}){if("coeff0"in e){let t=calculatePointsFromCoeffs(e);if(t.success)return{setValue:{points:t.points}};{let e={};for(let t=0;te.toString()))];for(let e=0;e({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>Number.isNaN(e.nDimensions)?[0]:[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={point:{dependencyType:"stateVariable",variableName:"point"+(Number(n)+1)}};return{globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentName:r}){if(Number.isNaN(e.nDimensions))return{};let a={};for(let r of n){let n=t[r].point;Array.isArray(n)||(n=[n]);let i=[];for(let t=0;t({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:function({dependencyValues:e}){let t=e.coeff0.evaluate_to_constant();Number.isFinite(t)||(t=NaN);let n=e.coeffvar1.evaluate_to_constant();Number.isFinite(n)||(n=NaN);let r=e.coeffvar2.evaluate_to_constant();return Number.isFinite(r)||(r=NaN),{setValue:{numericalCoeff0:t,numericalCoeffvar1:n,numericalCoeffvar2:r}}}},e.slope={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:function({dependencyValues:e}){return{setValue:{slope:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeffvar1,b:e.coeffvar2}).simplify()}}}},e.xintercept={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"}}),definition:({dependencyValues:e})=>({setValue:{xintercept:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeff0,b:e.coeffvar1}).simplify()}})},e.yintercept={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:({dependencyValues:e})=>({setValue:{yintercept:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeff0,b:e.coeffvar2}).simplify()}})},e.lastPointsFromInverting={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{lastPointsFromInverting:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"lastPointsFromInverting",value:e.lastPointsFromInverting}]})},e.latex={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({equation:{dependencyType:"stateVariable",variableName:"equation"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.equation,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalCoeff0:{dependencyType:"stateVariable",variableName:"numericalCoeff0"},numericalCoeffvar1:{dependencyType:"stateVariable",variableName:"numericalCoeffvar1"},numericalCoeffvar2:{dependencyType:"stateVariable",variableName:"numericalCoeffvar2"}}),definition({dependencyValues:e}){let t=e.numericalCoeffvar1,n=e.numericalCoeffvar2,r=e.numericalCoeff0,a=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r),i=2!==e.nDimensions||!a||0===t&&0===n;return{setValue:{nearestPoint:function({variables:e,scales:a=[1,1]}){if(i)return{};let s=a[0],o=a[1],l=t*s,u=n*o,c=l*l+u*u,p=e.x1?.evaluate_to_constant(),d=e.x2?.evaluate_to_constant();if(!Number.isFinite(p)||!Number.isFinite(d))return{};let m=p/s,h=d/o,f={};return f.x1=(u*(u*m-l*h)-l*r)*s/c,f.x2=(l*(-u*m+l*h)-u*r)*o/c,void 0!==e.x3&&(f.x3=0),f}}}}},e}static adapters=[{stateVariable:"equation",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async moveLine({point1coords:e,point2coords:t,transient:n,actionId:r}){let a={"0,0":me$3.fromAst(e[0]),"0,1":me$3.fromAst(e[1])};return await this.stateValues.basedOnSlope||(a["1,0"]=me$3.fromAst(t[0]),a["1,1"]=me$3.fromAst(t[1])),n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"points",value:a}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"points",value:a}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{point1:e,point2:t}}})}switchLine(){}async lineClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnLine({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}function calculateCoeffsFromEquation({equation:e,variables:t}){let n=t[0],r=t[1],a=n.toString(),i=r.toString();if(e=e.expand().simplify(),!Array.isArray(e.tree)||"="!==e.tree[0]||3!==e.tree.length)return{success:!1};let s=me$3.fromAst(["+",e.tree[2],["-",e.tree[1]]]).expand().simplify(),o=[];o=Array.isArray(s.tree)&&"+"===s.tree[0]?s.tree.slice(1):[s.tree];let l=me$3.fromAst(0),u=me$3.fromAst(0),c=me$3.fromAst(0);for(let e of o){let t=p(e);if(!t.success)return{success:!1};l=l.add(t.coeffvar1),u=u.add(t.coeffvar2),c=c.add(t.coeff0)}return l=l.simplify(),u=u.simplify(),c=c.simplify(),{success:!0,coeff0:c,coeffvar1:l,coeffvar2:u};function p(e){let t=0,s=0,o=0;if("string"==typeof e)e===a?t=1:e===i?s=1:o=e;else if("number"==typeof e)o=e;else{if(!Array.isArray(e))return console.warn("Invalid format for equation of line in variables "+n+" and "+r),{success:!1};{let a=e[0],i=e.slice(1);if("-"===a){let e=p(i[0]);if(!e.success)return{success:!1};t=["-",e.coeffvar1.tree],s=["-",e.coeffvar2.tree],o=["-",e.coeff0.tree]}else{if("+"===a)return console.warn("Invalid format for equation of line in variables "+n+" and "+r),{success:!1};if("*"===a){let a=-1,l=-1;for(let e=0;e({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{dashed:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.dashed}]})},e}async switchLine({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}class Curve extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveControlVector:this.moveControlVector.bind(this),moveThroughPoint:this.moveThroughPoint.bind(this),changeVectorControlDirection:this.changeVectorControlDirection.bind(this),switchCurve:this.switchCurve.bind(this),curveClicked:this.curveClicked.bind(this),mouseDownOnCurve:this.mouseDownOnCurve.bind(this)})}static componentType="curve";static rendererType="curve";static primaryStateVariableForDefinition="fShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.flipFunction={createComponentOfType:"boolean",createStateVariable:"flipFunction",defaultValue:!1,public:!0,forRenderer:!0},e.nDiscretizationPoints={createComponentOfType:"number",createStateVariable:"nDiscretizationPoints",defaultValue:1e3,public:!0},e.periodic={createComponentOfType:"boolean",createStateVariable:"periodic",defaultValue:!1,public:!0},e.splineTension={createComponentOfType:"number",createStateVariable:"splineTension",defaultValue:.8,clamp:[0,1],public:!0},e.extrapolateBackward={createComponentOfType:"boolean",createStateVariable:"extrapolateBackward",defaultValue:!1,public:!0,forRenderer:!0},e.extrapolateForward={createComponentOfType:"boolean",createStateVariable:"extrapolateForward",defaultValue:!1,public:!0,forRenderer:!0},e.splineForm={createComponentOfType:"text",createStateVariable:"splineForm",defaultValue:"centripetal",public:!0,toLowerCase:!0,validValues:["centripetal","uniform"]},e.variable={createComponentOfType:"variable",createStateVariable:"variableForChild",defaultValue:me$3.fromAst("x")},e.through={createComponentOfType:"_pointListComponent"},e.parMin={createComponentOfType:"math"},e.parMax={createComponentOfType:"math"},e.nearestPointAsCurve={createComponentOfType:"boolean",createStateVariable:"nearestPointAsCurvePrelim",defaultValue:!1},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e=>t.componentIsSpecifiedType(e,"label");if(0===e.length||!e.every((e=>"string"==typeof e||e.doenetAttributes?.createdFromMacro||n(e))))return{success:!1};let r=e.map(n),a=[],i=[],s=[];if(0===r.filter((e=>e)).length)a=e;else{if(r[0]){let t=r.indexOf(!1);-1!==t&&(i=e.slice(0,t),e=e.slice(t),r=r.slice(t))}let t=r.indexOf(!0);-1===t?a=e:(a=e.slice(0,t),s=e.slice(t))}if(0===a.length)return{success:!1};let o=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"function",children:e}),mustStripOffOuterParentheses:!0}),l=o({matchedChildren:a}),u=[];return u=l.success?l.newChildren:[{componentType:"function",children:a}],{success:!0,newChildren:[...i,...u,...s]}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"functions",componentTypes:["function"]},{group:"bezierControls",componentTypes:["bezierControls"]}),e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" curve"}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({functionChildren:{dependencyType:"child",childGroups:["functions"]},through:{dependencyType:"attributeComponent",attributeName:"through"}}),definition({dependencyValues:e}){let t="function";return null!==e.through?t="bezier":e.functionChildren.length>1&&(t="parameterization"),{setValue:{curveType:t}}}},t.fShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{fShadow:!0}})},t.graphXmin={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"graphXmax",forRenderer:!0},{variableName:"graphYmin",forRenderer:!0},{variableName:"graphYmax",forRenderer:!0}],returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>e.graphAncestor?{setValue:{graphXmin:e.graphAncestor.stateValues.xmin,graphXmax:e.graphAncestor.stateValues.xmax,graphYmin:e.graphAncestor.stateValues.ymin,graphYmax:e.graphAncestor.stateValues.ymax}}:{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}}},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},parMaxAttr:{dependencyType:"attributeComponent",attributeName:"parMax",variableNames:["value"]},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},adapterSourceDomain:{dependencyType:"adapterSourceStateVariable",variableName:"domain"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"}}),definition:function({dependencyValues:e}){let t;if("bezier"===e.curveType)t=e.nThroughPoints-1,e.extrapolateForward&&(t*=2);else if(null!==e.parMaxAttr)t=e.parMaxAttr.stateValues.value.evaluate_to_constant(),Number.isFinite(t)||(t=NaN);else if("function"===e.curveType){let n,r,a=null;if(a=1===e.functionChild.length?e.functionChild[0].stateValues.domain:e.adapterSourceDomain,null!==a){a=a[0];try{t=me$3.fromAst(a.tree[1][2]).evaluate_to_constant(),Number.isFinite(t)||t===1/0||(t=NaN)}catch(e){}}e.flipFunction?(r=e.graphYmax,n=e.graphYmin):(r=e.graphXmax,n=e.graphXmin),null!==r&&null!==n&&(t=void 0===t?r+.1*(r-n):Math.min(t,r+.1*(r-n))),void 0===t&&(t=1/0)}else t=10;return{setValue:{parMax:t}}}},t.parMin={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},parMinAttr:{dependencyType:"attributeComponent",attributeName:"parMin",variableNames:["value"]},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},adapterSourceDomain:{dependencyType:"adapterSourceStateVariable",variableName:"domain"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"}}),definition:function({dependencyValues:e}){let t;if("bezier"===e.curveType)t=0,e.extrapolateBackward&&(t=-(e.nThroughPoints-1));else if(null!==e.parMinAttr)t=e.parMinAttr.stateValues.value.evaluate_to_constant(),Number.isFinite(t)||(t=NaN);else if("function"===e.curveType){let n,r,a=null;if(a=1===e.functionChild.length?e.functionChild[0].stateValues.domain:e.adapterSourceDomain,null!==a){a=a[0];try{t=me$3.fromAst(a.tree[1][1]).evaluate_to_constant(),Number.isFinite(t)||t===-1/0||(t=NaN)}catch(e){}}e.flipFunction?(r=e.graphYmax,n=e.graphYmin):(r=e.graphXmax,n=e.graphXmin),null!==r&&null!==n&&(t=void 0===t?n+.1*(n-r):Math.max(t,n+.1*(n-r))),void 0===t&&(t=-1/0)}else t=-10;return{setValue:{parMin:t}}}},t.nThroughPoints={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition({dependencyValues:e}){let t=0;return null!==e.through&&(t=e.through.stateValues.nPoints),{setValue:{nThroughPoints:t}}}},t.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.through){return{setValue:{nDimensions:e.through.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].through;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst(0)}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].through||!t[r].through.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].through,desiredValue:e.throughPoints[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:i}}},t.numericalThroughPoints={isArray:!0,entryPrefixes:["numericalThroughPoint"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={throughPoint:{dependencyType:"stateVariable",variableName:"throughPoint"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].throughPoint.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalThroughPoints:n}}}},t.haveBezierControls={forRenderer:!0,returnDependencies:()=>({controlChild:{dependencyType:"child",childGroups:["bezierControls"]}}),definition:({dependencyValues:e})=>({setValue:{haveBezierControls:e.controlChild.length>0}})},t.bezierControlsAlwaysVisible={forRenderer:!0,returnDependencies:()=>({controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["alwaysVisible"]}}),definition:({dependencyValues:e})=>({setValue:{bezierControlsAlwaysVisible:e.controlChild.length>0&&e.controlChild[0].stateValues.alwaysVisible}})},t.vectorControlDirections={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["vectorControlDirection"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["direction"+(Number(n)+1)]}};return{dependenciesByKey:t,globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"}}}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlChild;t&&t.length>0?n[r]=t[0].stateValues["direction"+(Number(r)+1)]:n[r]="none"}return{setValue:{vectorControlDirections:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls)return{success:!1};let a=[];for(let r in e.vectorControlDirections){let i=n[r].controlChild;i&&i.length>0&&a.push({setDependency:t[r].controlChild,desiredValue:e.vectorControlDirections[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:a}}},t.hiddenControls={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},isArray:!0,entryPrefixes:["hiddenControl"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["hiddenControl"+(Number(n)+1)]}};return{dependenciesByKey:t,globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"}}}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlChild;t&&t.length>0?n[r]=t[0].stateValues["hiddenControl"+(Number(r)+1)]:n[r]=!1}return{setValue:{hiddenControls:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls)return{success:!1};let a=[];for(let r in e.hiddenControls){let i=n[r].controlChild;i&&i.length>0&&a.push({setDependency:t[r].controlChild,desiredValue:e.hiddenControls[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:a}}},t.controlVectors={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"controlVectorX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["controlVectorX","controlVector"],nDimensions:3,stateVariablesDeterminingDependencies:["vectorControlDirections","nThroughPoints"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("controlVectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 3===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eNumber(e)-1));return 2===e.length&&e.every((e=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eString(e)+","+n)):[]:[String(e)+",0"]:[]}},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=r.split(",").map((e=>Number(e))),a=e.map((e=>e+1)),i=a.join("_");n[r]={direction:{dependencyType:"stateVariable",variableName:"vectorControlDirection"+a[0]},controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["control"+i]}};let s=e[0],o=t.vectorControlDirections[s],l=[];"none"===o?l=[s-1,s,s+1]:"previous"===o?l=[s,s+1]:"next"===o&&(l=[s-1,s]);for(let e of l)e>=0&&eNumber(e))),s=r.map((e=>e+1)),o=s.join("_"),l=r[0],u=r[1],c=n[i].direction;if("none"===c){let r,s,o=n[i]["throughPoint"+(l+1)];l>0&&(r=n[i]["throughPoint"+l]),lNumber(e))),s=i.map((e=>e+1)),o=s.join("_"),l=n[r].controlChild;if(l.length>0){l[0].stateValues["control"+o]&&a.push({setDependency:t[r].controlChild,desiredValue:e.controlVectors[r],childIndex:0,variableIndex:0})}}return{success:!0,instructions:a}}},t.numericalControlVectors={isArray:!0,entryPrefixes:["numericalControlVector"],forRenderer:!0,nDimensions:2,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={controlVector:{dependencyType:"stateVariable",variableName:"controlVector"+a}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlVector.map((e=>e.tree));n[r]=t}return{setValue:{numericalControlVectors:n}}}},t.controlPoints={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"controlPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["controlPointX","controlPoint"],nDimensions:3,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("controlPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 3===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eNumber(e)-1));return 2===e.length&&e.every((e=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eString(e)+","+n)):[]:[String(e)+",0"]:[]}},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={throughPointX:{dependencyType:"stateVariable",variableName:"throughPointX"+r[0]+"_"+r[2]},controlVectorX:{dependencyType:"stateVariable",variableName:"controlVectorX"+a}}}return{globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(2!==e.nDimensions)r[a]=me$3.fromAst(NaN);else{let e=t[a].controlVectorX;if(e){let n=t[a].throughPointX.evaluate_to_constant();Number.isFinite(n)||(n=NaN),r[a]=me$3.fromAst(n+e.tree)}else r[a]=null}return{setValue:{controlPoints:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls||2!==r.nDimensions)return{success:!1};let a=[];for(let r in e.controlPoints){if(n[r].controlVectorX){let i=n[r].throughPointX,s=e.controlPoints[r];s.tree&&(s=s.tree);let o=me$3.fromAst(["+",s,["-",i.tree]]);a.push({setDependency:t[r].controlVectorX,desiredValue:o})}}return{success:!0,instructions:a}}},t.numericalControlPoints={isArray:!0,entryPrefixes:["numericalControlPoint"],forRenderer:!0,nDimensions:2,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={controlPoint:{dependencyType:"stateVariable",variableName:"controlPoint"+a}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlPoint.map((e=>e.tree));n[r]=t}return{setValue:{numericalControlPoints:n}}}},t.splineCoeffs={isArray:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints-1],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1,r=e+1;t[n]={previousPoint:{dependencyType:"stateVariable",variableName:"numericalThroughPoint"+e},nextPoint:{dependencyType:"stateVariable",variableName:"numericalThroughPoint"+r},previousVector:{dependencyType:"stateVariable",variableName:"numericalControlVector"+e+"_2"},nextVector:{dependencyType:"stateVariable",variableName:"numericalControlVector"+r+"_1"}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].previousPoint,a=e[r].nextPoint,i=e[r].previousVector,s=e[r].nextVector,o=[];for(let e=0;e<2;e++)o.push(initCubicPoly(t[e],a[e],3*i[e],-3*s[e]));n[r]=o}return{setValue:{splineCoeffs:n}}}},t.extrapolateBackwardCoeffs={stateVariablesDeterminingDependencies:["extrapolateBackward"],additionalStateVariablesDefined:[{variableName:"extrapolateBackwardMode",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies({stateValues:e}){let t={extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}};return e.extrapolateBackward&&(t.firstSplineCoeffs={dependencyType:"stateVariable",variableName:"splineCoeffs1"},t.graphXmin={dependencyType:"stateVariable",variableName:"graphXmin"},t.graphXmax={dependencyType:"stateVariable",variableName:"graphXmax"},t.graphYmin={dependencyType:"stateVariable",variableName:"graphYmin"},t.graphYmax={dependencyType:"stateVariable",variableName:"graphYmax"}),t},definition({dependencyValues:e}){if(!e.extrapolateBackward||!e.firstSplineCoeffs)return{setValue:{extrapolateBackwardCoeffs:null,extrapolateBackwardMode:""}};let t=e.firstSplineCoeffs[0],n=e.firstSplineCoeffs[1],r=t[0],a=t[1],i=2*t[2],s=n[0],o=n[1],l=a*a+o*o,u=(o*i-a*(2*n[2]))/(l*l);if(Math.abs(u)<1e-12||Math.abs(a)<1e-12||Math.abs(o)<1e-12){let t=a,n=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,i=e.nThroughPoints-1,s=r/i/Math.abs(t),o=a/i/Math.abs(n),l=Math.min(s,o);l>1&&(t*=l,n*=l)}return{setValue:{extrapolateBackwardCoeffs:[[r,t,0],[s,n,0]],extrapolateBackwardMode:"line"}}}let c=o*u,p=-a*u;if(c*a>0){let t=c/p,n=(1+t*t)**2,i=a;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=r/s,l=1/0;if(0!==p){let e=p*n/2*s*s,r=-t*s,i=Math.sqrt(r*r+4*Math.abs(e)*a);l=(Math.abs(r)+i)/(2*Math.abs(e))}let u=Math.min(o,l);u>Math.abs(i)&&(i*=u/Math.abs(i))}return{setValue:{extrapolateBackwardCoeffs:[[r,i,0],[s,-i*t,p*i*i*n/2]],extrapolateBackwardMode:"parabolaVertical"}}}{let t=p/c,n=(1+t*t)**2,a=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,i=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=i/s,l=1/0;if(0!==c){let e=c*n/2*s*s,a=-t*s,i=Math.sqrt(a*a+4*Math.abs(e)*r);l=(Math.abs(a)+i)/(2*Math.abs(e))}let u=Math.min(l,o);u>Math.abs(a)&&(a*=u/Math.abs(a))}return{setValue:{extrapolateBackwardCoeffs:[[r,-a*t,c*a*a*n/2],[s,a,0]],extrapolateBackwardMode:"parabolaHorizontal"}}}}},t.extrapolateForwardCoeffs={stateVariablesDeterminingDependencies:["nThroughPoints","extrapolateForward"],additionalStateVariablesDefined:[{variableName:"extrapolateForwardMode",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies({stateValues:e}){let t={extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}};return e.extrapolateForward&&e.nThroughPoints>=2&&(t.lastSplineCoeffs={dependencyType:"stateVariable",variableName:"splineCoeffs"+(e.nThroughPoints-1)},t.graphXmin={dependencyType:"stateVariable",variableName:"graphXmin"},t.graphXmax={dependencyType:"stateVariable",variableName:"graphXmax"},t.graphYmin={dependencyType:"stateVariable",variableName:"graphYmin"},t.graphYmax={dependencyType:"stateVariable",variableName:"graphYmax"}),t},definition({dependencyValues:e}){if(!e.extrapolateForward||!e.lastSplineCoeffs)return{setValue:{extrapolateForwardCoeffs:null,extrapolateForwardMode:""}};let t=e.lastSplineCoeffs[0],n=e.lastSplineCoeffs[1],r=t[0]+t[1]+t[2]+t[3],a=t[1]+2*t[2]+3*t[3],i=2*t[2]+6*t[3],s=n[0]+n[1]+n[2]+n[3],o=n[1]+2*n[2]+3*n[3],l=a*a+o*o,u=(o*i-a*(2*n[2]+6*n[3]))/(l*l);if(Math.abs(u)<1e-12||Math.abs(a)<1e-12||Math.abs(o)<1e-12){let t=a,n=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,i=e.nThroughPoints-1,s=r/i/Math.abs(t),o=a/i/Math.abs(n),l=Math.min(s,o);l>1&&(t*=l,n*=l)}return{setValue:{extrapolateForwardCoeffs:[[r,t,0],[s,n,0]],extrapolateForwardMode:"line"}}}let c=o*u,p=-a*u;if(c*a<0){let t=c/p,n=(1+t*t)**2,i=a;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=r/s,l=1/0;if(0!==p){let e=p*n/2*s*s,r=-t*s,i=Math.sqrt(r*r+4*Math.abs(e)*a);l=(Math.abs(r)+i)/(2*Math.abs(e))}let u=Math.min(o,l);u>Math.abs(i)&&(i*=u/Math.abs(i))}return{setValue:{extrapolateForwardCoeffs:[[r,i,0],[s,-i*t,p*i*i*n/2]],extrapolateForwardMode:"parabolaVertical"}}}{let t=p/c,n=(1+t*t)**2,a=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,i=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=i/s,l=1/0;if(0!==c){let e=c*n/2*s*s,a=-t*s,i=Math.sqrt(a*a+4*Math.abs(e)*r);l=(Math.abs(a)+i)/(2*Math.abs(e))}let u=Math.min(l,o);u>Math.abs(a)&&(a*=u/Math.abs(a))}return{setValue:{extrapolateForwardCoeffs:[[r,-a*t,c*a*a*n/2],[s,a,0]],extrapolateForwardMode:"parabolaHorizontal"}}}}},t.fs={isArray:!0,entryPrefixes:["f"],additionalStateVariablesDefined:[{variableName:"fDefinitions",isArray:!0,forRenderer:!0}],returnArraySizeDependencies:()=>({functionChildren:{dependencyType:"child",childGroups:["functions"]},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),returnArraySize:({dependencyValues:e})=>"bezier"===e.curveType?[2]:[Math.max(1,e.functionChildren.length)],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalf","fDefinition"],childIndices:[n]}},0===Number(n)&&(t[n].fShadow={dependencyType:"stateVariable",variableName:"fShadow"},t[n].fDefinitionAdapted={dependencyType:"adapterSourceStateVariable",variableName:"fDefinition"});return{globalDependencies:{curveType:{dependencyType:"stateVariable",variableName:"curveType"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},extrapolateBackwardCoeffs:{dependencyType:"stateVariable",variableName:"extrapolateBackwardCoeffs"},extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},extrapolateForwardCoeffs:{dependencyType:"stateVariable",variableName:"extrapolateForwardCoeffs"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if("bezier"===e.curveType)return{setValue:{fs:returnBezierFunctions(e),fDefinitions:{0:{functionType:"bezier",nThroughPoints:e.nThroughPoints,numericalThroughPoints:e.numericalThroughPoints,splineCoeffs:e.splineCoeffs,extrapolateForward:e.extrapolateForward,extrapolateForwardCoeffs:e.extrapolateForwardCoeffs,extrapolateBackward:e.extrapolateBackward,extrapolateBackwardCoeffs:e.extrapolateBackwardCoeffs},1:null}}};let r={},a={};for(let e of n){let n=t[e].functionChild;1===n.length?(r[e]=n[0].stateValues.numericalf,a[e]=n[0].stateValues.fDefinition):0===Number(e)&&t[e].fShadow?(r[e]=t[e].fShadow,a[e]=t[e].fDefinitionAdapted):(r[e]=()=>0,a[e]={functionType:"zero"})}return{setValue:{fs:r,fDefinitions:a}}}},t.f={isAlias:!0,targetVariableName:"f1"},t.allXCriticalPoints={returnDependencies:()=>({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allXCriticalPoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let e=n[0],r=3*e[3],s=2*e[2],o=e[1];if(Math.abs(r)<1e-14){i=addTimePointBezier({t:-o/s,ind:t,ts:a,ignoreLeft:i})}else{let e=s*s-4*r*o;if(0==e){i=addTimePointBezier({t:-s/(2*r),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),o=[(-s-n)/(2*r),(-s+n)/(2*r)];r<0&&(o=[o[1],o[0]]);let l=!1;for(let e of o){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(l=!0)}i=l}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allXCriticalPoints:t}}}},t.nXCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allXCriticalPoints:{dependencyType:"stateVariable",variableName:"allXCriticalPoints"}}),definition:({dependencyValues:e})=>({setValue:{nXCriticalPoints:e.allXCriticalPoints.length}})},t.xCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"xCriticalPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["xCriticalPointX","xCriticalPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("xCriticalPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("xCriticalPoints"===t)return 1===e.length?"xCriticalPoint"+e[0]:`xCriticalPointX${e[0]}_${e[1]}`;if("xCriticalPoint"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`xCriticalPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nXCriticalPoints:{dependencyType:"stateVariable",variableName:"nXCriticalPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nXCriticalPoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allXCriticalPoints:{dependencyType:"stateVariable",variableName:"allXCriticalPoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allYCriticalPoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let e=n[1],r=3*e[3],s=2*e[2],o=e[1];if(Math.abs(r)<1e-14){i=addTimePointBezier({t:-o/s,ind:t,ts:a,ignoreLeft:i})}else{let e=s*s-4*r*o;if(0==e){i=addTimePointBezier({t:-s/(2*r),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),o=[(-s-n)/(2*r),(-s+n)/(2*r)];r<0&&(o=[o[1],o[0]]);let l=!1;for(let e of o){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(l=!0)}i=l}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allYCriticalPoints:t}}}},t.nYCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allYCriticalPoints:{dependencyType:"stateVariable",variableName:"allYCriticalPoints"}}),definition:({dependencyValues:e})=>({setValue:{nYCriticalPoints:e.allYCriticalPoints.length}})},t.yCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"yCriticalPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["yCriticalPointX","yCriticalPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("yCriticalPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("yCriticalPoints"===t)return 1===e.length?"yCriticalPoint"+e[0]:`yCriticalPointX${e[0]}_${e[1]}`;if("yCriticalPoint"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`yCriticalPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nYCriticalPoints:{dependencyType:"stateVariable",variableName:"nYCriticalPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nYCriticalPoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allYCriticalPoints:{dependencyType:"stateVariable",variableName:"allYCriticalPoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allCurvatureChangePoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let[e,r,s,o]=n[0],[l,u,c,p]=n[1],d=3*(s*p-c*o),m=3*(r*p-u*o),h=r*c-u*s;if(Math.abs(d)<1e-14){i=addTimePointBezier({t:-h/m,ind:t,ts:a,ignoreLeft:i})}else{let e=m*m-4*d*h;if(0==e){i=addTimePointBezier({t:-m/(2*d),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),r=[(-m-n)/(2*d),(-m+n)/(2*d)];d<0&&(r=[r[1],r[0]]);let s=!1;for(let e of r){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(s=!0)}i=s}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allCurvatureChangePoints:t}}}},t.nCurvatureChangePoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"allCurvatureChangePoints"}}),definition:({dependencyValues:e})=>({setValue:{nCurvatureChangePoints:e.allCurvatureChangePoints.length}})},t.curvatureChangePoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"curvatureChangePointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["curvatureChangePointX","curvatureChangePoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("curvatureChangePointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("curvatureChangePoints"===t)return 1===e.length?"curvatureChangePoint"+e[0]:`curvatureChangePointX${e[0]}_${e[1]}`;if("curvatureChangePoint"===t.slice(0,20)){let n=Number(t.slice(20));if(Number.isInteger(n)&&n>0)return`curvatureChangePointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"nCurvatureChangePoints"}}),returnArraySize:({dependencyValues:e})=>[e.nCurvatureChangePoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"allCurvatureChangePoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({nearestPointAsCurvePrelim:{dependencyType:"stateVariable",variableName:"nearestPointAsCurvePrelim"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nearestPointAsCurve"]},adapterSourceValue:{dependencyType:"adapterSourceStateVariable",variableName:"nearestPointAsCurve"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.nearestPointAsCurvePrelim;return t.nearestPointAsCurvePrelim&&(e.functionChild.length>0?n=e.functionChild[0].stateValues.nearestPointAsCurve:null!==e.adapterSourceValue&&(n=e.adapterSourceValue)),{setValue:{nearestPointAsCurve:n}}}},t.nearestPoint={returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},fs:{dependencyType:"stateVariable",variableName:"fs"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"},nDiscretizationPoints:{dependencyType:"stateVariable",variableName:"nDiscretizationPoints"},parMin:{dependencyType:"stateVariable",variableName:"parMin"},parMax:{dependencyType:"stateVariable",variableName:"parMax"},periodic:{dependencyType:"stateVariable",variableName:"periodic"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},nearestPointAsCurve:{dependencyType:"stateVariable",variableName:"nearestPointAsCurve"}}),definition({dependencyValues:t}){let n=null;return"function"===t.curveType?n=getNearestPointFunctionCurve({dependencyValues:t,numerics:e}):["parameterization","bezier"].includes(t.curveType)&&(n=getNearestPointParametrizedCurve({dependencyValues:t,numerics:e})),{setValue:{nearestPoint:n}}}},t}async moveControlVector({controlVector:e,controlVectorInds:t,transient:n,actionId:r}){let a={[t+",0"]:me$3.fromAst(e[0]),[t+",1"]:me$3.fromAst(e[1])};return n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"controlVectors",value:a,sourceInformation:{controlVectorMoved:t}}],transient:n,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"controlVectors",value:a,sourceInformation:{controlVectorMoved:t}}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{["controlVector"+t.join("_")]:e}}})}async moveThroughPoint({throughPoint:e,throughPointInd:t,transient:n,actionId:r}){let a={[t+",0"]:me$3.fromAst(e[0]),[t+",1"]:me$3.fromAst(e[1])};return n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"throughPoints",value:a,sourceInformation:{throughPointMoved:t}}],transient:n,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"throughPoints",value:a,sourceInformation:{throughPointMoved:t}}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{["throughPoint"+t]:e}}})}async changeVectorControlDirection({direction:e,throughPointInd:t,actionId:n}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vectorControlDirection",value:{[t]:e}}],actionId:n})}switchCurve(){}async curveClicked({actionId:e,name:t}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:t}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnCurve({actionId:e,name:t}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:t}),this.coreFunctions.resolveAction({actionId:e})}}function getNearestPointFunctionCurve({dependencyValues:e,numerics:t}){let n=e.flipFunction,r=e.fs[0],a=e.nDiscretizationPoints,i=e.parMax,s=e.parMin;return function({variables:o,scales:l}){let u,c,p,d,m=o.x1?.evaluate_to_constant(),h=o.x2?.evaluate_to_constant(),f=l[0],y=l[1];if(s!==-1/0){if(u=s,c=r(s),!Number.isFinite(c)){let e=.99999*s+1e-5*i,t=r(e);Number.isFinite(t)&&(u=e,c=t)}if(n){let e=u;u=c,c=e}}if(i!==1/0){if(p=i,d=r(i),!Number.isFinite(d)){let e=1e-5*s+.99999*i,t=r(e);Number.isFinite(t)&&(p=e,d=t)}if(n){let e=p;p=d,d=e}}if(!e.nearestPointAsCurve||!Number.isFinite(m)||!Number.isFinite(h)){let e,t;if(n?(t=h,e=r(t)):(e=m,t=r(e)),!Number.isFinite(e)||!Number.isFinite(t)){let r,a;n?(r=Math.abs(s-h),a=Math.abs(i-h)):(r=Math.abs(s-m),a=Math.abs(i-m)),re.evaluate_to_constant())),a)l=a.map((e=>e.evaluate_to_constant())),s=n?n.map((e=>e.evaluate_to_constant())):[2*o[0]-l[0],2*o[1]-l[1]];else{if(!n)return{coordsNumeric:[me$3.fromAst(NaN),me$3.fromAst(NaN)],numericEntries:!1};s=n.map((e=>e.evaluate_to_constant())),l=[2*o[0]-s[0],2*o[1]-s[1]]}let c=[];if("centripetal"===i){let n=u(s,o),r=u(o,l);n=Math.sqrt(n),r=Math.sqrt(r),rme$3.fromAst(e)));return{coordsNumeric:p,numericEntries:Number.isFinite(c[0])&&Number.isFinite(c[1])}}function initCubicPoly(e,t,n,r){return[e,n,-3*e+3*t-2*n-r,2*e-2*t+n+r]}function addTimePointBezier({t:e,ind:t,ts:n,ignoreLeft:r=!1}){const a=1e-14;let i=!1;return e>=a?e<=.99999999999999?n.push(t+e):e<1.00000000000001&&(n.push(t+1),i=!0):e>-a&&!r&&n.push(t),i}class EquilibriumCurve extends Curve{static componentType="equilibriumCurve";static rendererType="curve";static createAttributesObject(){let e=super.createAttributesObject();return e.stable={createComponentOfType:"boolean",createStateVariable:"stable",defaultValue:!0,public:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.dashed={forRenderer:!0,returnDependencies:()=>({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{dashed:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.dashed}]})},t}async switchCurve({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}var DynamicalSystems=Object.freeze({__proto__:null,ODESystem:ODESystem,CobwebPolyline:CobwebPolyline,EquilibriumPoint:EquilibriumPoint,EquilibriumLine:EquilibriumLine,EquilibriumCurve:EquilibriumCurve});class Atom extends InlineComponent{static componentType="atom";static rendererType="math";static primaryStateVariableForDefinition="atomicNumberShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.symbol={createComponentOfType:"text"},e.atomicNumber={createComponentOfType:"integer"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.atomicNumberShadow={defaultValue:null,hasEssential:!0,essentialVarName:"atomicNumber",returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{atomicNumberShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"atomicNumberShadow",value:e.atomicNumberShadow}]}}},e.dataForAtom={returnDependencies:()=>({fileContents:{dependencyType:"file",cid:"bafkreibilal4glrbpo7p7oodtwtnzkfhiylfoqa2td4ij6h6iqva57kzcy",fileType:"csv"},symbolAttr:{dependencyType:"attributeComponent",attributeName:"symbol",variableNames:["value"]},atomicNumberAttr:{dependencyType:"attributeComponent",attributeName:"atomicNumber",variableNames:["value"]},atomicNumberShadow:{dependencyType:"stateVariable",variableName:"atomicNumberShadow"}}),definition:function({dependencyValues:e}){let t=null,n=null;if(e.symbolAttr)t=e.symbolAttr.stateValues.value.toLowerCase();else if(e.atomicNumberAttr)n=e.atomicNumberAttr.stateValues.value;else{if(!e.atomicNumberShadow)return{setValue:{dataForAtom:null}};n=e.atomicNumberShadow}let r,a=e.fileContents.trim().split("\n");r=null!==n?n-1:["h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","nh","fl","mc","lv","ts","og"].indexOf(t?.toLowerCase());let i=a.slice(1)[r];if(!i)return{setValue:{dataForAtom:null}};i=i.trim().split(",").map((e=>e.trim()));let s=a[0].trim().split(",").map((e=>e.trim())).map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1).trim()),e))),o=s.length,l=["number","string","string","number","number","string","number","string","string","number","number","number","number","number","number","number","string"],u={};for(let e=0;e({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Number"]:null,{setValue:{atomicNumber:t}}}},e.symbol={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Symbol:null,{setValue:{symbol:t}}}},e.name={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Name:null,{setValue:{name:t}}}},e.group={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Group:null,{setValue:{group:t}}}},e.atomicMass={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Mass"]:null,{setValue:{atomicMass:t}}}},e.phaseAtSTP={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Phase at STP"]:null,{setValue:{phaseAtSTP:t}}}},e.chargeOfCommonIon={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Charge of Common Ion"]:null,{setValue:{chargeOfCommonIon:t}}}},e.metalCategory={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Metal/Nonmetal/Metalloid"]:null,{setValue:{metalCategory:t}}}},e.groupName={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Group Name"]:null,{setValue:{groupName:t}}}},e.period={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Period:null,{setValue:{period:t}}}},e.ionizationEnergy={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Ionization Energy"]:null,{setValue:{ionizationEnergy:t}}}},e.meltingPoint={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Melting Point"]:null,{setValue:{meltingPoint:t}}}},e.boilingPoint={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Boiling Point"]:null,{setValue:{boilingPoint:t}}}},e.atomicRadius={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Radius"]:null,{setValue:{atomicRadius:t}}}},e.density={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Density:null,{setValue:{density:t}}}},e.electronegativity={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Electronegativity:null,{setValue:{electronegativity:t}}}},e.electronConfiguration={public:!0,shadowingInstructions:{createComponentOfType:"electronConfiguration"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Electron Configuration"]:null,{setValue:{electronConfiguration:t}}}},e.orbitalDiagram={public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},returnDependencies:()=>({electronConfiguration:{dependencyType:"stateVariable",variableName:"electronConfiguration"}}),definition({dependencyValues:e}){let t;return t=e.electronConfiguration?electronConfigurationToOrbitalDiagram(e.electronConfiguration):null,{setValue:{orbitalDiagram:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"}}),definition({dependencyValues:e}){let t;return t=e.symbol?["^",e.symbol]:"_",{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"}}),definition({dependencyValues:e}){let t;return t=e.symbol?`\\text{${e.symbol}}`:"[\\text{Invalid Chemical Symbol}]",{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math","name",{stateVariable:"atomicNumber",componentType:"ion"}]}function electronConfigurationToOrbitalDiagram(e){let t=e.tree;if(!Array.isArray(t)||"*"!==t[0])return null;t=t.slice(1);let n=t.length/2;if(!Number.isInteger(n))return null;let r=[];for(let e=0;e0))return null;let a=t[2*e+1];if(!Array.isArray(a)||"^"!==a[0])return null;let i=a[1],s=a[2];if(!(["s","p","d","f"].includes(i)&&Number.isInteger(s)&&s>0))return null;let o,l=`${n}${i}`;o="s"===i?1:"p"===i?3:"d"===i?5:7;let u=Array(o).fill("");for(let e=0;e({}),definition:()=>({useEssentialOrDefaultValue:{atomicNumberShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"atomicNumberShadow",value:e.atomicNumberShadow}]}}},e.dataForAtom={returnDependencies:()=>({fileContents:{dependencyType:"file",cid:"bafkreibilal4glrbpo7p7oodtwtnzkfhiylfoqa2td4ij6h6iqva57kzcy",fileType:"csv"},symbolAttr:{dependencyType:"attributeComponent",attributeName:"symbol",variableNames:["value"]},atomicNumberAttr:{dependencyType:"attributeComponent",attributeName:"atomicNumber",variableNames:["value"]},atomChild:{dependencyType:"child",childGroups:["atoms"],variableNames:["atomicNumber"]},atomicNumberShadow:{dependencyType:"stateVariable",variableName:"atomicNumberShadow"}}),definition:function({dependencyValues:e}){let t=null,n=null;if(e.atomChild.length>0)n=e.atomChild[0].stateValues.atomicNumber;else if(e.symbolAttr)t=e.symbolAttr.stateValues.value.toLowerCase();else if(e.atomicNumberAttr)n=e.atomicNumberAttr.stateValues.value;else{if(!e.atomicNumberShadow)return{setValue:{dataForAtom:null}};n=e.atomicNumberShadow}let r,a=e.fileContents.trim().split("\n");r=null!==n?n-1:["h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","nh","fl","mc","lv","ts","og"].indexOf(t?.toLowerCase());let i=a.slice(1)[r];if(!i)return{setValue:{dataForAtom:null}};i=i.trim().split(",").map((e=>e.trim()));let s=a[0].trim().split(",").map((e=>e.trim())).map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1).trim()),e))),o=s.length,l=["number","string","string","number","number","string","number","string","string","number","number","number","number","number","number","number","string"],u={};for(let e=0;e({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Number"]:null,{setValue:{atomicNumber:t}}}},e.symbol={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Symbol:null,{setValue:{symbol:t}}}},e.charge={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"},chargeAttr:{dependencyType:"attributeComponent",attributeName:"charge",variableNames:["value"]}}),definition({dependencyValues:e}){let t;return e.chargeAttr?(t=e.chargeAttr.stateValues.value,Number.isFinite(t)||(t=0)):t=e.dataForAtom&&e.dataForAtom["Charge of Common Ion"]||0,{setValue:{charge:t}}}},e.name={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"},charge:{dependencyType:"stateVariable",variableName:"charge"},group:{dependencyType:"stateVariable",variableName:"group"},atomicNumber:{dependencyType:"stateVariable",variableName:"atomicNumber"}}),definition({dependencyValues:e}){let t;if(e.dataForAtom){if(t=e.dataForAtom.Name,e.charge<0){let e={Hydrogen:"Hydride",Oxygen:"Oxide",Sulfur:"Sulfide",Nitrogen:"Nitride",Phosphorus:"Phosphide",Carbon:"Carbide"},n=t.length;"ine"===t.substring(n-3,n)?t=t.substring(0,n-3)+"ide":t in e&&(t=e[t])}else if(e.charge>0&&(e.group>=3&&e.group<=12||101===e.group||102===e.group||[13,31,49,50,81,82,83,84].includes(e.atomicNumber))){let n="";switch(e.charge){case 1:n=" (I)";break;case 2:n=" (II)";break;case 3:n=" (III)";break;case 4:n=" (IV)";break;case 5:n=" (V)";break;case 6:n=" (VI)";break;case 7:n=" (VII)";break;case 8:n=" (VIII)"}t+=n}}else t=null;return{setValue:{name:t}}}},e.group={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Group:null,{setValue:{group:t}}}},e.metalCategory={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Metal/Nonmetal/Metalloid"]:null,{setValue:{metalCategory:t}}}},e.groupName={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Group Name"]:null,{setValue:{groupName:t}}}},e.period={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Period:null,{setValue:{period:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"},charge:{dependencyType:"stateVariable",variableName:"charge"}}),definition({dependencyValues:e}){let t;return e.symbol?(t=["^",e.symbol],-1===e.charge?t.push("-"):1===e.charge?t.push("+"):e.charge<0?t.push(Math.abs(e.charge)+"-"):e.charge>0&&t.push(Math.abs(e.charge)+"+")):t="_",{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"},charge:{dependencyType:"stateVariable",variableName:"charge"}}),definition({dependencyValues:e}){let t;return e.symbol?(t=`\\text{${e.symbol}}`,-1===e.charge?t+="^-":1===e.charge?t+="^+":e.charge<0?t+=`^{${Math.abs(e.charge)}-}`:e.charge>0&&(t+=`^{${Math.abs(e.charge)}+}`)):t="[\\text{Invalid Chemical Symbol}]",{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math","name"]}class IonicCompound extends InlineComponent{static componentType="ionicCompound";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.symbol={createComponentOfType:"text"},e.atomicNumber={createComponentOfType:"integer"},e.charge={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"ions",componentTypes:["ion"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.ionicCompound={returnDependencies:()=>({ionChildren:{dependencyType:"child",childGroups:["ions"],variableNames:["symbol","charge","atomicNumber","name"]}}),definition({dependencyValues:e}){let t=e.ionChildren.map((e=>e.stateValues.charge));if(2!==t.length)return console.warn("have not implemented ionic compound for anything other than two ions"),{setValue:{ionicCompound:null}};if(!(t[0]*t[1]<0))return console.warn("ionic compound implemented only for one cation and one anion"),{setValue:{ionicCompound:null}};let n=Math.abs(t[1]),r=Math.abs(t[0]),a=me$3.math.gcd(n,r);return n/=a,r/=a,{setValue:{ionicCompound:[{symbol:e.ionChildren[0].stateValues.symbol,atomicNumber:e.ionChildren[0].stateValues.atomicNumber,name:e.ionChildren[0].stateValues.name,charge:t[0],count:n},{symbol:e.ionChildren[1].stateValues.symbol,atomicNumber:e.ionChildren[1].stateValues.atomicNumber,name:e.ionChildren[1].stateValues.name,charge:t[1],count:r}]}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({ionicCompound:{dependencyType:"stateVariable",variableName:"ionicCompound"}}),definition({dependencyValues:e}){let t;if(e.ionicCompound){t=[];for(let n of e.ionicCompound){let e=n.symbol;n.count>1&&(e=["_",e,n.count]),t.push(e)}t=t.length>1?["*",...t]:1===t.length?t[0]:"_"}else t="_";return{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({ionicCompound:{dependencyType:"stateVariable",variableName:"ionicCompound"}}),definition({dependencyValues:e}){let t;if(e.ionicCompound){t="";for(let n of e.ionicCompound)t+=`\\text{${n.symbol}}`,n.count>1&&(t+=`_{${n.count}}`)}else t="[\\text{Invalid Ionic Compound}]";return{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math"]}class ElectronConfiguration extends MathComponent{static componentType="electronConfiguration";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e,usedDefault:t}){let n;try{n=e.valueForDisplay.toLatex()}catch(e){n="_"}return n=n.replaceAll("\\,",""),n=n.replaceAll("\\cdot","~"),{setValue:{latex:n}}}},e}}class OrbitalDiagram extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="orbitalDiagram";static variableForPlainMacro="value";static createAttributesObject(){let e=super.createAttributesObject();return e.labels={createComponentOfType:"textList",createStateVariable:"labels",defaultValue:[]},e}static returnSugarInstructions(){return[{replacementFunction:function({matchedChildren:e}){return 1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"tupleList",children:e}]}}}]}static returnChildGroups(){return[{group:"tupleLists",componentTypes:["tupleList"]},{group:"orbitalDiagrams",componentTypes:["orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={defaultValue:[{orbitalText:"",boxes:[]}],public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},forRenderer:!0,returnDependencies:()=>({orbitalDiagramChildren:{dependencyType:"child",childGroups:["orbitalDiagrams"],variableNames:["value"]},tupleListChildren:{dependencyType:"child",childGroups:["tupleLists"],variableNames:["maths"]},labels:{dependencyType:"stateVariable",variableName:"labels"}}),definition:function({dependencyValues:e}){return{setValue:{value:function(){function t(e){if("u"===e||"U"===e)return"U";if("d"===e||"D"===e)return"D";if("e"===e||"E"===e)return"";if(Array.isArray(e)&&"*"===e[0]){let t="";for(let n of e.slice(1))if("u"===n||"U"===n)t+="U";else{if("d"!==n&&"D"!==n)return"";t+="D"}return t}return""}if(1===e.orbitalDiagramChildren.length)return e.orbitalDiagramChildren[0].stateValues.value;let n=[];if(e.tupleListChildren[0]?.stateValues.maths.length>0){let r=e.tupleListChildren[0].stateValues.maths;for(let[a,i]of r.entries()){let r="";e.labels[a]&&(r=e.labels[a]);let s=[];if(Array.isArray(i.tree)&&"tuple"===i.tree[0])for(let e of i.tree.slice(1))s.push(t(e));else s.push(t(i.tree));n.push({orbitalText:r,boxes:s})}return n}return[{orbitalText:"",boxes:[]}]}()}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class OrbitalDiagramInput extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{addRow:this.addRow.bind(this),removeRow:this.removeRow.bind(this),addBox:this.addBox.bind(this),removeBox:this.removeBox.bind(this),addUpArrow:this.addUpArrow.bind(this),addDownArrow:this.addDownArrow.bind(this),removeArrow:this.removeArrow.bind(this),updateRowText:this.updateRowText.bind(this),selectRow:this.selectRow.bind(this),selectBox:this.selectBox.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="orbitalDiagramInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"orbitalDiagram",createStateVariable:"prefill",defaultValue:[]},e.prefillLabel={createComponentOfType:"textList",createStateVariable:"prefillLabel",defaultValue:[]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={defaultValue:[{orbitalText:"",boxes:[]}],hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},returnDependencies:()=>({prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLabel:{dependencyType:"stateVariable",variableName:"prefillLabel"}}),definition:function({dependencyValues:e}){return{useEssentialOrDefaultValue:{value:{get defaultValue(){return function(){if(e.prefill?.length>0){let t=JSON.parse(JSON.stringify(e.prefill));for(let[n,r]of t.entries())e.prefillLabel[n]&&(r.orbitalText=e.prefillLabel[n]);return t}return[{orbitalText:"",boxes:[]}]}()}}}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"value",value:e.value}]})},e.rows={public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{rows:[...e.value].reverse()}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:[...e.rows].reverse()}]})},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({rows:{dependencyType:"stateVariable",variableName:"rows"}}),definition:function({dependencyValues:e}){return{setValue:{numRows:e.rows.length}}}},e.selectedRowIndex={defaultValue:0,hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({}),definition:function(){return{useEssentialOrDefaultValue:{selectedRowIndex:!0}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n=await t.numRows,r=e.selectedRowIndex;return r=Number.isFinite(r)?Math.min(n,Math.max(0,Math.round(r))):0,{success:!0,instructions:[{setEssentialValue:"selectedRowIndex",value:r}]}}},e.selectedBoxIndex={defaultValue:0,hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({}),definition:function(){return{useEssentialOrDefaultValue:{selectedBoxIndex:!0}}},async inverseDefinition({desiredStateVariableValues:e}){let t=e.selectedBoxIndex;return t=Number.isFinite(t)?Math.max(0,Math.round(t)):0,{success:!0,instructions:[{setEssentialValue:"selectedBoxIndex",value:t}]}}},e}async addRow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t));t.length<20&&(n=[{orbitalText:"",boxes:[]},...t]);let r=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return-1!==await this.stateValues.selectedRowIndex-1&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:0}),-1!==await this.stateValues.selectedBoxIndex-1&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}),await this.coreFunctions.performUpdate({updateInstructions:r,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeRow({actionId:e}){let t=await this.stateValues.rows,n=await this.stateValues.selectedRowIndex-1,r=JSON.parse(JSON.stringify(t));if(t.length>1){let e=t.length-1-n;-1===n&&(e=0),r.splice(e,1)}return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:r},{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:0},{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:r}}})}async addBox({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0),n[a].boxes.length<17&&n[a].boxes.push("");let i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];if(-1!==r){let e=0;i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:e})}return await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeBox({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.splice(s,1);let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return-1!==i&&o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}),await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async addUpArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length<3&&(n[a].boxes[s]=n[a].boxes[s]+"U");let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async addDownArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length<3&&(n[a].boxes[s]=n[a].boxes[s]+"D");let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length>0&&(n[a].boxes[s]=n[a].boxes[s].slice(0,-1));let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async updateRowText({newValue:e,actionId:t}){let n=await this.stateValues.rows,r=JSON.parse(JSON.stringify(n)),a=await this.stateValues.selectedRowIndex-1,i=n.length-a-1;-1===a&&(i=0),r[i].orbitalText=e;let s=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:r}];return await this.coreFunctions.performUpdate({updateInstructions:s,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:r}}})}async selectRow({index:e,actionId:t}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:e}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{selectedRowIndex:e}}})}async selectBox({index:e,actionId:t}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:e}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{selectedBoxIndex:e}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Chemistry=Object.freeze({__proto__:null,Atom:Atom,Ion:Ion,IonicCompound:IonicCompound,ElectronConfiguration:ElectronConfiguration,OrbitalDiagram:OrbitalDiagram,OrbitalDiagramInput:OrbitalDiagramInput});class FeedbackDefinition extends BaseComponent{static componentType="feedbackDefinition";static createAttributesObject(){let e=super.createAttributesObject();return e.code={createComponentOfType:"text"},e.text={createComponentOfType:"text"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.feedbackDefinition={returnDependencies:()=>({codeAttr:{dependencyType:"attributeComponent",attributeName:"code",variableNames:["value"]},textAttr:{dependencyType:"attributeComponent",attributeName:"text",variableNames:["value"]}}),definition({dependencyValues:e}){if(null!==e.codeAttr&&null!==e.textAttr){return{setValue:{feedbackDefinition:{[e.codeAttr.stateValues.value.toLowerCase()]:e.textAttr.stateValues.value}}}}return{setValue:{feedbackDefinition:null}}}},e}}class FeedbackDefinitions extends BaseComponent{static componentType="feedbackDefinitions";static rendererType=void 0;static returnChildGroups(){return[{group:"feedbackDefinition",componentTypes:["feedbackDefinition"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({feedbackDefinitionChildren:{dependencyType:"child",childGroups:["feedbackDefinition"],variableNames:["feedbackDefinition"]}}),definition({dependencyValues:e}){let t={};for(let n of e.feedbackDefinitionChildren)n.stateValues.feedbackDefinition&&Object.assign(t,n.stateValues.feedbackDefinition);return{setValue:{value:t}}}},e}}var FeedbackDefinitions$1=Object.freeze({__proto__:null,FeedbackDefinition:FeedbackDefinition,FeedbackDefinitions:FeedbackDefinitions});class StyleDefinition extends BaseComponent{static componentType="styleDefinition";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();e.styleNumber={createPrimitiveOfType:"number",createStateVariable:"styleNumber",defaultValue:1};for(let t in styleAttributes)e[t]={createComponentOfType:styleAttributes[t].componentType};return e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDefinition={returnDependencies:function(){let e={};for(let t in styleAttributes)e[t]={dependencyType:"attributeComponent",attributeName:t,variableNames:["value"]};return e},definition:function({dependencyValues:e}){let t={};for(let n in styleAttributes)null!==e[n]&&(t[n]=e[n].stateValues.value,"string"==typeof t[n]&&(t[n]=t[n].toLowerCase()));return{setValue:{styleDefinition:t}}}},e}}class StyleDefinitions extends BaseComponent{static componentType="styleDefinitions";static rendererType=void 0;static returnChildGroups(){return[{group:"styleDefinition",componentTypes:["styleDefinition"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({styleDefinitionChildren:{dependencyType:"child",childGroups:["styleDefinition"],variableNames:["styleNumber","styleDefinition"]}}),definition({dependencyValues:e}){let t={};for(let n of e.styleDefinitionChildren){let e=n.stateValues.styleNumber,r=t[e];r||(r=t[e]={}),Object.assign(r,n.stateValues.styleDefinition)}return{setValue:{value:t}}}},e}}var StyleDefinitions$1=Object.freeze({__proto__:null,StyleDefinition:StyleDefinition,StyleDefinitions:StyleDefinitions});class ComponentWithSelectableType extends BaseComponent{static componentType="_componentWithSelectableType";static rendererType=void 0;static includeBlankStringChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n}){let r=t.type;r||(r=n.type),r?["number","letters","math","text","boolean"].includes(r)||(console.warn(`Invalid type ${r}, setting type to number`),r="number"):r="number";let a="letters"===r?"text":r;return"text"!==a&&(e=e.filter((e=>"string"!=typeof e||""!==e.trim()))),{success:!0,newChildren:[{componentType:a,children:e}]}}}),e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.type={shadowVariable:!0,returnDependencies:()=>({type:{dependencyType:"doenetAttribute",attributeName:"type"},parentType:{dependencyType:"parentStateVariable",variableName:"type"}}),definition:function({dependencyValues:e,componentName:t}){let n=e.type;return n||(n=e.parentType),n?["number","letters","math","text","boolean"].includes(n)||(console.warn(`Invalid type ${n}, setting type to number`),n="number"):n="number",{setValue:{type:n}}}},e.value={public:!0,shadowingInstructions:{hasVariableComponentType:!0},shadowVariable:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},atMostOneChild:{dependencyType:"child",childGroups:["anything"],variableNames:["value"]}}),definition({dependencyValues:e}){let t;return t=e.atMostOneChild.length>0?e.atMostOneChild[0].stateValues.value:"text"===e.type||"letters"===e.type?"":"boolean"!==e.type&&("number"===e.type?NaN:me$3.fromAst("_")),{setValue:{value:t},setCreateComponentOfType:{value:e.type}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.atMostOneChild.length>0?{success:!0,instructions:[{setDependency:"atMostOneChild",desiredValue:e.value,childIndex:0,variableIndex:0}]}:{success:!1}},e}}class ComponentListWithSelectableType extends ComponentWithSelectableType{static componentType="_componentListWithSelectableType";static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n,isAttributeComponent:r=!1,createdFromMacro:a=!1,componentInfoObjects:i}){let s=t.type;s||(s=n.type),s?["number","letters","math","text","boolean"].includes(s)||(console.warn(`Invalid type ${s}, setting type to number`),s="number"):s="number";let o="letters"===s?"text":s;if(r&&!a){return returnGroupIntoComponentTypeSeparatedBySpaces({componentType:o})({matchedChildren:e})}return returnBreakStringsIntoComponentTypeBySpaces({componentType:o})({matchedChildren:e})}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.value,e.nValues={additionalStateVariablesDefined:["childForValue"],returnDependencies:()=>({anythingForSelectedType:{dependencyType:"child",childGroups:["anything"],variableNames:["nValues"],variablesOptional:!0}}),definition({dependencyValues:e}){let t=0,n=[];for(let[r,a]of e.anythingForSelectedType.entries()){let e=Number.isInteger(a.stateValues.nValues)?a.stateValues.nValues:1;t+=e;for(let t=0;t({nValues:{dependencyType:"stateVariable",variableName:"nValues"}}),returnArraySize:({dependencyValues:e})=>[e.nValues],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.childForValue[r];n[r]={anythingForSelectedType:{dependencyType:"child",childGroups:["anything"],variableNames:["value","values"],childIndices:[e.child],variablesOptional:!0},valueIndex:{dependencyType:"value",value:e.valueIndex}}}return{globalDependencies:{type:{dependencyType:"stateVariable",variableName:"type"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentName:r}){let a={};for(let r of n)if(t[r].anythingForSelectedType&&1===t[r].anythingForSelectedType.length){let n,i=t[r].anythingForSelectedType[0];n=i.stateValues.values?i.stateValues.values[t[r].valueIndex]:i.stateValues.value,a[r]=convertValueToType(n,e.type)}return{setValue:{values:a},setCreateComponentOfType:{values:e.type}}}},e}}class ComponentListOfListsWithSelectableType extends ComponentWithSelectableType{static componentType="_componentListOfListsWithSelectableType";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n}){let r=breakEmbeddedStringsIntoParensPieces({componentList:e,removeParens:!0});if(!0!==r.success)return{success:!1};let a=t.type;return a||(a=n.type),a?["number","letters","math","text","boolean"].includes(a)||(console.warn(`Invalid type ${a}, setting type to number`),a="number"):a="number",{success:!0,newChildren:r.pieces.map((e=>({componentType:"_componentListWithSelectableType",attributes:{type:{primitive:a}},children:e})))}}}),e}static returnChildGroups(){return[{group:"lists",componentTypes:["_componentListWithSelectableType"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.value,e.nLists={returnDependencies:()=>({listChildren:{dependencyType:"child",childGroups:["lists"]}}),definition:({dependencyValues:e})=>({setValue:{nLists:e.listChildren.length}})},e.lists={isArray:!0,entryPrefixes:["list"],returnArraySizeDependencies:()=>({nLists:{dependencyType:"stateVariable",variableName:"nLists"}}),returnArraySize:({dependencyValues:e})=>[e.nLists],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={listChildren:{dependencyType:"child",childGroups:["lists"],variableNames:["values","type"],childIndices:[n]}};return{globalDependencies:{type:{dependencyType:"stateVariable",variableName:"type"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(t[a].listChildren&&1===t[a].listChildren.length){let n=t[a].listChildren[0];n.stateValues.type===e.type?r[a]=n.stateValues.values:r[a]=n.stateValues.values.map((t=>convertValueToType(t,e.type)))}return{setValue:{lists:r}}}},e}}function convertValueToType(e,t){if(Array.isArray(e)&&(e=e[0]),"number"===t){if(e instanceof me$3.class){let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}return Number(e)}if("math"===t){if("string"==typeof e)try{return me$3.fromAst(textToAst$1.convert(e))}catch(e){}return convertValueToMathExpression(e)}return"boolean"===t?Boolean(e):String(e)}var ComponentWithSelectableType$1=Object.freeze({__proto__:null,ComponentWithSelectableType:ComponentWithSelectableType,ComponentListWithSelectableType:ComponentListWithSelectableType,ComponentListOfListsWithSelectableType:ComponentListOfListsWithSelectableType});class SideBySide extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="sideBySide";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize"},e.widths={createComponentOfType:"_componentSizeList"},e.margins={createComponentOfType:"_componentSizeList"},e.valign={createComponentOfType:"text"},e.valigns={createComponentOfType:"textList"},e}static returnChildGroups(){return[{group:"blocks",componentTypes:["_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPanels={forRenderer:!0,returnDependencies:()=>({blockChildren:{dependencyType:"child",childGroups:["blocks"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{nPanels:e.blockChildren.length},checkForActualChange:{nPanels:!0}})},e.essentialWidths={isArray:!0,entryPrefixes:["essentialWidth"],defaultValueByArrayKey:()=>null,hasEssential:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialWidths:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialWidths)t[n]=e.essentialWidths[n];return{success:!0,instructions:[{setEssentialValue:"essentialWidths",value:t}]}}},e.allWidthsSpecified={additionalStateVariablesDefined:["widthsAbsolute"],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents","componentSizes"]},parentWidths:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"specifiedWidths"},parentWidthsAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"widthsAbsolute"},essentialWidth:{dependencyType:"stateVariable",variableName:"essentialWidths"}}),definition({dependencyValues:e}){let t,n=[],r=null,a=!1;null!==e.widthsAttr?t=e.widthsAttr.stateValues.nComponents:null!==e.widthAttr?(t=e.nPanels,a=!0):t=0;for(let i=0;iNumber.isFinite(e)?e:null)),{setValue:{allWidthsSpecified:n,widthsAbsolute:r}}}},e.essentialMargins={isArray:!0,entryPrefixes:["essentialMargin"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialMargins:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialMargins)t[n]=e.essentialMargins[n];return{success:!0,instructions:[{setEssentialValue:"essentialMargins",value:t}]}}},e.allMarginsSpecified={additionalStateVariablesDefined:["marginsAbsolute"],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["nComponents","componentSizes"]},parentMargins:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"specifiedMargins"},parentMarginsAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"marginsAbsolute"},essentialMargins:{dependencyType:"stateVariable",variableName:"essentialMargins"}}),definition({dependencyValues:e}){let t=[],n=null;if(null===e.marginsAttr)if(e.parentMargins){n=e.parentMarginsAbsolute;for(let n=0;n<2;n++)null===e.essentialMargins[n]?t[n]=e.parentMargins[n]:t[n]=e.essentialMargins[n]}else for(let n=0;n<2;n++)t[n]=e.essentialMargins[n];else if(0===e.marginsAttr.stateValues.nComponents)for(let n=0;n<2;n++)t[n]=e.essentialMargins[n];else if(1===e.marginsAttr.stateValues.nComponents){let r=null;e.marginsAttr.stateValues.componentSizes[0]&&(r=e.marginsAttr.stateValues.componentSizes[0].size,Number.isFinite(r)||(r=null),n=Boolean(e.marginsAttr.stateValues.componentSizes[0].isAbsolute)),t=[r,r]}else{let r;if(n=!!e.marginsAttr.stateValues.componentSizes[0]&&Boolean(e.marginsAttr.stateValues.componentSizes[0].isAbsolute),r=!!e.marginsAttr.stateValues.componentSizes[1]&&Boolean(e.marginsAttr.stateValues.componentSizes[1].isAbsolute),r!==n)throw Error("SideBySide is not implemented for absolute measurements");t=e.marginsAttr.stateValues.componentSizes.slice(0,2).map((e=>e&&Number.isFinite(e.size)?e.size:null))}return{setValue:{allMarginsSpecified:t,marginsAbsolute:n}}}},e.absoluteMeasurements={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({widthsAbsolute:{dependencyType:"stateVariable",variableName:"widthsAbsolute"},marginsAbsolute:{dependencyType:"stateVariable",variableName:"marginsAbsolute"}}),definition({dependencyValues:e}){let t;if(null===e.widthsAbsolute)t=null!==e.marginsAbsolute&&e.marginsAbsolute;else if(null===e.marginsAbsolute)t=e.widthsAbsolute;else{if(e.widthsAbsolute!==e.marginsAbsolute)throw Error("SideBySide is not implemented for absolute measurements");t=e.widthsAbsolute}if(!0===t)throw Error("SideBySide is not implemented for absolute measurements");return{setValue:{absoluteMeasurements:t}}}},e.allWidths={additionalStateVariablesDefined:["allMargins",{variableName:"gapWidth",public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0}],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},allWidthsSpecified:{dependencyType:"stateVariable",variableName:"allWidthsSpecified"},allMarginsSpecified:{dependencyType:"stateVariable",variableName:"allMarginsSpecified"},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}}),definition({dependencyValues:e}){let t=0,n=[...e.allWidthsSpecified],r=[...e.allMarginsSpecified],a=0,i=0;for(let t=0;t=100){let t=100/(a+s);for(let r=0;r0){let t=(100-(a+s))/i;for(let r=0;r0){let t=(100-(a+s))/(o*e.nPanels);for(let e=0;e<2;e++)null===r[e]&&(r[e]=t)}else e.nPanels>1?t=(100-(a+s))/(e.nPanels-1):1===e.nPanels?r[1]=100-(r[0]+n[0]):console.warn("Invalid sideBySide, as it must have at least one block child");return{setValue:{allWidths:n,allMargins:r,gapWidth:t}}}},e.widths={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["width"],forRenderer:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey({arrayKeys:e}){let t={allWidths:{dependencyType:"stateVariable",variableName:"allWidths"},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}},n={};for(let t of e){let e=Number(t)+1;n[t]={widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:[`componentSize${e}`]},essentialWidth:{dependencyType:"stateVariable",variableName:`essentialWidth${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allWidths[r];return{setValue:{widths:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r,arraySize:a}){let i,s=!1;null!==r.widthsAttr?i=r.widthsAttr.stateValues.nComponents:null!==r.widthAttr?(i=a[0],s=!0):i=0;let o=[];for(let n in e.widths){Number(n)({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={allMargins:{dependencyType:"stateVariable",variableName:"allMargins"},marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["componentSize1","componentSize2","nComponents"]},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}},n={};for(let t of e){let e=Number(t)+1;n[t]={essentialMargin:{dependencyType:"stateVariable",variableName:`essentialMargin${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allMargins[r];return{setValue:{margins:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyNamesByKey:n}){let r=[];if(null===t.marginsAttr)for(let t in e.margins)r.push({setDependency:n[t].essentialMargin,desiredValue:e.margins[t]});else if(t.marginsAttr.stateValues.componentSize1&&Number.isFinite(t.marginsAttr.stateValues.componentSize1.size)){let n=1===t.marginsAttr.stateValues.nComponents;for(let a in e.margins)n?r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[a],isAbsolute:t.absoluteMeasurements},variableIndex:0}):r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[a],isAbsolute:t.absoluteMeasurements},variableIndex:a})}else"0"in e.margins?r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[0],isAbsolute:t.absoluteMeasurements},variableIndex:0}):r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[1],isAbsolute:t.absoluteMeasurements},variableIndex:0}),"1"in e.margins&&t.marginsAttr.stateValues.nComponents>1&&r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[1],isAbsolute:t.absoluteMeasurements},variableIndex:1});return{success:!0,instructions:r}}},e.essentialValigns={isArray:!0,entryPrefixes:["essentialValign"],defaultValueByArrayKey:()=>null,hasEssential:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialValigns:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialValigns)t[n]=e.essentialValigns[n];return{success:!0,instructions:[{setEssentialValue:"essentialValigns",value:t}]}}},e.valigns={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"text"},entryPrefixes:["valign"],forRenderer:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:[`text${e}`]},parentValign:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:`valign${e}`},parentValignAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:`valignAbsolute${e}`},essentialValign:{dependencyType:"stateVariable",variableName:`essentialValign${e}`}}}return{globalDependencies:{valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s=!1;null!==e.valignsAttr?a=e.valignsAttr.stateValues.nComponents:null!==e.valignAttr?(a=r[0],s=!0):a=0;for(let r of n){let n=Number(r);if(n({sideBySideChildren:{dependencyType:"child",childGroups:["sideBySides"],variableNames:["nPanels"]}}),definition:({dependencyValues:e})=>({setValue:{maxNPanelsPerRow:me$3.math.max(e.sideBySideChildren.map((e=>e.stateValues.nPanels)))},checkForActualChange:{maxNPanelsPerRow:!0}})},e.specifiedWidths={additionalStateVariablesDefined:[{variableName:"widthsAbsoluteArray",isArray:!0}],isArray:!0,entryPrefixes:["specifiedWidth"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:[`componentSize${e}`]}}}return{globalDependencies:{widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s={},o={},l=!1;null!==e.widthsAttr?a=e.widthsAttr.stateValues.nComponents:null!==e.widthAttr?(a=r[0],l=!0):a=0;for(let r of n){let n=Number(r);if(n0&&(u.useEssentialOrDefaultValue={specifiedWidths:s}),u},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,stateValues:r,arraySize:a}){let i,s=!1;null!==n.widthsAttr?i=n.widthsAttr.stateValues.nComponents:null!==n.widthAttr?(i=a[0],s=!0):i=0;let o=[];for(let n in e.specifiedWidths){Number(n)({widthsAbsoluteArray:{dependencyType:"stateVariable",variableName:"widthsAbsoluteArray"}}),definition({dependencyValues:e}){let t=null;for(let n in e.widthsAbsoluteArray){let r=e.widthsAbsoluteArray[n];if(null!==r)if(r=Boolean(r),null===t)t=r;else if(t!==r)throw Error("SbsGroup is not implemented for absolute measurements")}return{setValue:{widthsAbsolute:t}}}},e.specifiedMargins={additionalStateVariablesDefined:[{variableName:"marginsAbsoluteArray",isArray:!0,entryPrefixes:["marginAbsolute"]}],isArray:!0,entryPrefixes:["specifiedMargin"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:({arrayKeys:e})=>({globalDependencies:{marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["componentSize1","componentSize2","nComponents"]}}}),arrayDefinitionByKey({dependencyValuesByKey:e,globalDependencyValues:t,arrayKeys:n}){let r={},a={},i={};if(null===t.marginsAttr||0===t.marginsAttr.stateValues.nComponents)for(let e of n)a[e]=!0,i[e]=null;else if(1===t.marginsAttr.stateValues.nComponents){let e=null,a=null;t.marginsAttr.stateValues.componentSize1&&(e=t.marginsAttr.stateValues.componentSize1.size,Number.isFinite(e)||(e=null),a=Boolean(t.marginsAttr.stateValues.componentSize1.isAbsolute));for(let t of n)r[t]=e,i[t]=a}else for(let e of n)if(t.marginsAttr.stateValues[`componentSize${Number(e)+1}`]){let n=t.marginsAttr.stateValues[`componentSize${Number(e)+1}`].size;Number.isFinite(n)||(n=null);let a=Boolean(t.marginsAttr.stateValues[`componentSize${Number(e)+1}`].isAbsolute);r[e]=n,i[e]=a}let s={setValue:{marginsAbsoluteArray:i,specifiedMargins:r}};return Object.keys(a).length>0&&(s.useEssentialOrDefaultValue={specifiedMargins:a}),s},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,stateValues:r}){let a=[];if(null===n.marginsAttr)a.push({setEssentialValue:"specifiedMargins",value:e.specifiedMargins});else if(n.marginsAttr.stateValues.componentSize1&&Number.isFinite(n.marginsAttr.stateValues.componentSize1.size)){let t=1===n.marginsAttr.stateValues.nComponents;for(let n in e.specifiedMargins)t?a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[n],isAbsolute:await r.marginsAbsolute},variableIndex:0}):a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[n],isAbsolute:await r.marginsAbsolute},variableIndex:n})}else"0"in e.specifiedMargins?a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[0],isAbsolute:await r.marginsAbsolute},variableIndex:0}):a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[1],isAbsolute:await r.marginsAbsolute},variableIndex:0}),"1"in e.specifiedMargins&&n.marginsAttr.stateValues.nComponents>1&&a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[1],isAbsolute:await r.marginsAbsolute},variableIndex:1});return{success:!0,instructions:a}}},e.marginsAbsolute={returnDependencies:()=>({marginsAbsoluteArray:{dependencyType:"stateVariable",variableName:"marginsAbsoluteArray"}}),definition({dependencyValues:e}){let t=null;for(let n in e.marginsAbsoluteArray){let r=e.marginsAbsoluteArray[n];if(null!==r)if(r=Boolean(r),null===t)t=r;else if(t!==r)throw Error("SbsGroup is not implemented for absolute measurements")}return{setValue:{marginsAbsolute:t}}}},e.absoluteMeasurements={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({widthsAbsolute:{dependencyType:"stateVariable",variableName:"widthsAbsolute"},marginsAbsolute:{dependencyType:"stateVariable",variableName:"marginsAbsolute"}}),definition({dependencyValues:e}){let t;if(null===e.widthsAbsolute)t=null!==e.marginsAbsolute&&e.marginsAbsolute;else if(null===e.marginsAbsolute)t=e.widthsAbsolute;else{if(e.widthsAbsolute!==e.marginsAbsolute)throw Error("SbsGroup is not implemented for absolute measurements");t=e.widthsAbsolute}if(!0===t)throw Error("SbsGroup is not implemented for absolute measurements");return{setValue:{absoluteMeasurements:t}}}},e.allWidths={additionalStateVariablesDefined:["allMargins",{variableName:"gapWidth",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"},specifiedWidths:{dependencyType:"stateVariable",variableName:"specifiedWidths"},specifiedMargins:{dependencyType:"stateVariable",variableName:"specifiedMargins"},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}}),definition({dependencyValues:e}){let t=0,n=[...e.specifiedWidths],r=[...e.specifiedMargins],a=0,i=0;for(let t=0;t=100){let t=100/(a+s);for(let r=0;r0){let t=(100-(a+s))/i;for(let r=0;r0){let t=(100-(a+s))/(o*e.maxNPanelsPerRow);for(let e=0;e<2;e++)null===r[e]&&(r[e]=t)}else e.maxNPanelsPerRow>1?t=(100-(a+s))/(e.maxNPanelsPerRow-1):1===e.maxNPanelsPerRow?r[1]=100-(r[0]+n[0]):console.warn("Invalid sideBySide, as it must have at least one block child");return{setValue:{allWidths:n,allMargins:r,gapWidth:t}}}},e.widths={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["width"],returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={allWidths:{dependencyType:"stateVariable",variableName:"allWidths"}},n={};for(let t of e){let e=Number(t)+1;n[t]={specifiedWidth:{dependencyType:"stateVariable",variableName:`specifiedWidth${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allWidths[r];return{setValue:{widths:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.widths)n.push({setDependency:t[r].specifiedWidth,desiredValue:e.widths[r],variableIndex:0});return{success:!0,instructions:n}}},e.margins={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["margin"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={allMargins:{dependencyType:"stateVariable",variableName:"allMargins"}},n={};for(let t of e){let e=Number(t)+1;n[t]={specifiedMargin:{dependencyType:"stateVariable",variableName:`specifiedMargin${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allMargins[r];return{setValue:{margins:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.margins)n.push({setDependency:t[r].specifiedMargin,desiredValue:e.margins[r],variableIndex:0});return{success:!0,instructions:n}}},e.valigns={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"text"},entryPrefixes:["valign"],hasEssential:!0,defaultValueByArrayKey:()=>"top",returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:[`text${e}`]}}}return{globalDependencies:{valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s={},o=!1;null!==e.valignsAttr?a=e.valignsAttr.stateValues.nComponents:null!==e.valignAttr?(a=r[0],o=!0):a=0;for(let r of n){let n=Number(r);if(n0&&(l.setValue={valigns:i}),Object.keys(s).length>0&&(l.useEssentialOrDefaultValue={valigns:s}),l},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,arraySize:r}){let a,i=!1;null!==n.valignsAttr?a=n.valignsAttr.stateValues.nComponents:null!==n.valignAttr?(a=r[0],i=!0):a=0;let s=[];for(let n in e.valigns){let r=e.valigns[n].toLowerCase();["top","middle","bottom"].includes(r)&&(Number(n)({stringTextChildren:{dependencyType:"child",childGroups:["stringsTexts"],variableNames:["value"]},hChildren:{dependencyType:"child",childGroups:["hs"],variableNames:["value"]}}),definition({dependencyValues:e}){let t;if(e.hChildren.length>0)t=e.hChildren.map((e=>e.stateValues.value));else{let n="";for(let t of e.stringTextChildren)n+="string"==typeof t?t:t.stateValues.value;t=[n]}return{setValue:{terms:t}}}},e}}var Indexing=Object.freeze({__proto__:null,H:H$2,Idx:Idx});class Div extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="div";static rendererType="containerBlock";static renderChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Span extends InlineComponent{static componentType="span";static rendererType="containerInline";static renderChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}}var Divisions=Object.freeze({__proto__:null,Div:Div,Span:Span});class Pre extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="pre";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Verbatim=Object.freeze({__proto__:null,Pre:Pre});class Paginator extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{setPage:this.setPage.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="paginator";static rendererType="containerBlock";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.initialPage={createComponentOfType:"integer",createStateVariable:"initialPage",defaultValue:1},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPages={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"]}}),definition:({dependencyValues:e})=>({setValue:{nPages:e.children.length}})},e.currentPage={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,returnDependencies:()=>({initialPage:{dependencyType:"stateVariable",variableName:"initialPage"},nPages:{dependencyType:"stateVariable",variableName:"nPages"}}),definition:({dependencyValues:e})=>({useEssentialOrDefaultValue:{currentPage:{get defaultValue(){let t=e.initialPage;return Number.isInteger(t)?Math.max(1,Math.min(e.nPages,t)):1}}}}),async inverseDefinition({desiredStateVariableValues:e,stateValues:t,sourceInformation:n={}}){if(!n.fromSetPage)return{success:!1};let r=Number(e.currentPage);return Number.isInteger(r)?(r=Math.max(1,Math.min(await t.nPages,r)),{success:!0,instructions:[{setEssentialValue:"currentPage",value:r}]}):{success:!1}}},e.childIndicesToRender={returnDependencies:()=>({currentPage:{dependencyType:"stateVariable",variableName:"currentPage"}}),definition:({dependencyValues:e})=>({setValue:{childIndicesToRender:[e.currentPage-1]}}),markStale:()=>({updateRenderedChildren:!0})},e}async setPage({number:e,actionId:t}){if(!Number.isInteger(e))return void this.coreFunctions.resolveAction({actionId:t});let n=Math.max(1,Math.min(await this.stateValues.nPages,e)),r=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"currentPage",value:n,sourceInformation:{fromSetPage:!0}}];await this.coreFunctions.performUpdate({updateInstructions:r,actionId:t,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:n,responseText:n.toString()}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class PaginatorControls extends BlockComponent{constructor(e){super(e),this.externalActions={},Object.defineProperty(this.externalActions,"setPage",{enumerable:!0,get:async function(){let e=await this.stateValues.paginatorComponentName;return e?{componentName:e,actionName:"setPage"}:void 0}.bind(this)})}static componentType="paginatorControls";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.previousLabel={createComponentOfType:"text",createStateVariable:"previousLabel",defaultValue:"Previous",forRenderer:!0,public:!0},e.nextLabel={createComponentOfType:"text",createStateVariable:"nextLabel",defaultValue:"Next",forRenderer:!0,public:!0},e.pageLabel={createComponentOfType:"text",createStateVariable:"pageLabel",defaultValue:"Page",forRenderer:!0,public:!0},e.paginator={createTargetComponentNames:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.paginatorComponentName={returnDependencies:()=>({paginator:{dependencyType:"attributeTargetComponentNames",attributeName:"paginator"}}),definition({dependencyValues:e}){let t;return t=1===e.paginator?.length?e.paginator[0].absoluteName:null,{setValue:{paginatorComponentName:t}}}},e.currentPage={forRenderer:!0,stateVariablesDeterminingDependencies:["paginatorComponentName"],returnDependencies:({stateValues:e})=>e.paginatorComponentName?{paginatorPage:{dependencyType:"stateVariable",componentName:e.paginatorComponentName,variableName:"currentPage"}}:{},definition:({dependencyValues:e})=>"paginatorPage"in e?{setValue:{currentPage:e.paginatorPage}}:{setValue:{currentPage:1}}},e.nPages={forRenderer:!0,stateVariablesDeterminingDependencies:["paginatorComponentName"],returnDependencies:({stateValues:e})=>e.paginatorComponentName?{paginatorNPages:{dependencyType:"stateVariable",componentName:e.paginatorComponentName,variableName:"nPages"}}:{},definition:({dependencyValues:e})=>"paginatorNPages"in e?{setValue:{nPages:e.paginatorNPages}}:{setValue:{nPages:1}}},e}}var Paginator$1=Object.freeze({__proto__:null,Paginator:Paginator,PaginatorControls:PaginatorControls});class Input extends InlineComponent{static componentType="_input";static createAttributesObject(){let e=super.createAttributesObject();return e.collaborateGroups={createComponentOfType:"collaborateGroups",createStateVariable:"collaborateGroups",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nValues={returnDependencies:()=>({}),definition:()=>({setValue:{nValues:1}})},e.answerAncestor={returnDependencies:()=>({answerAncestor:{dependencyType:"ancestor",componentType:"answer",variableNames:["delegateCheckWorkToInput","justSubmitted","creditAchieved","showCorrectness","numberOfAttemptsLeft"]}}),definition:function({dependencyValues:e}){return{setValue:{answerAncestor:e.answerAncestor}}}},e.includeCheckWork={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=!1;return e.answerAncestor&&(t=e.answerAncestor.stateValues.delegateCheckWorkToInput),{setValue:{includeCheckWork:t}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e.creditAchieved={defaultValue:0,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=0;return e.answerAncestor&&(t=e.answerAncestor.stateValues.creditAchieved),{setValue:{creditAchieved:t}}}},e.valueHasBeenValidated={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=!1;return e.answerAncestor&&e.answerAncestor.stateValues.justSubmitted&&(t=!0),{setValue:{valueHasBeenValidated:t}}}},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"},answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition({dependencyValues:e}){let t;return t=e.answerAncestor?e.answerAncestor.stateValues.showCorrectness:!1!==e.showCorrectnessFlag,{setValue:{showCorrectness:t}}}},e.numberOfAttemptsLeft={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition({dependencyValues:e}){let t;return t=e.answerAncestor?e.answerAncestor.stateValues.numberOfAttemptsLeft:1/0,{setValue:{numberOfAttemptsLeft:t}}}},e}}class MatrixInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateNumRows:this.updateNumRows.bind(this),updateNumColumns:this.updateNumColumns.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="matrixInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.numRows={createComponentOfType:"integer",createStateVariable:"numRowsPreliminary",defaultValue:1,transformNonFiniteTo:0},e.numColumns={createComponentOfType:"integer",createStateVariable:"numColumnsPreliminary",defaultValue:1,transformNonFiniteTo:0},e.showSizeControls={createComponentOfType:"boolean",createStateVariable:"showSizeControls",defaultValue:!0,public:!0,forRenderer:!0},e.defaultEntry={createComponentOfType:"math",createStateVariable:"defaultEntry",defaultValue:me$3.fromAst("_")},e.prefill={createComponentOfType:"math",createStateVariable:"prefill",defaultValue:me$3.fromAst("_"),public:!0,copyComponentAttributesForCreatedComponent:["format","functionSymbols","splitSymbols","parseScientificNotation"]},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"math"},e.unionFromU={createComponentOfType:"boolean",createStateVariable:"unionFromU",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){if(e.length>0)return{success:!1};return{success:!0,newChildren:[{componentType:"matrixInputGrid"}]}}}),e}static returnChildGroups(){return[{group:"matrixComponentInputs",componentTypes:["matrixComponentInput"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.valueOriginal={hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{valueOriginal:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{valueOriginal:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.valueOriginal,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"valueOriginal",value:e.valueOriginal}]}}},e.immediateValueOriginal={hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.valueOriginal&&!n?{setValue:{immediateValueOriginal:e.valueOriginal},setEssentialValue:{immediateValueOriginal:e.valueOriginal}}:{useEssentialOrDefaultValue:{immediateValueOriginal:{defaultValue:e.valueOriginal}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValueOriginal",value:e.immediateValueOriginal}];return t||n||r.push({setDependency:"valueOriginal",desiredValue:e.immediateValueOriginal}),{success:!0,instructions:r}}},e.haveBoundValue={returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo"}}),definition:({dependencyValues:e})=>({setValue:{haveBoundValue:null!==e.bindValueTo}})},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},forRenderer:!0,returnDependencies:()=>({numRowsPreliminary:{dependencyType:"stateVariable",variableName:"numRowsPreliminary"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},haveBoundValue:{dependencyType:"stateVariable",variableName:"haveBoundValue"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.numRowsPreliminary;if(t.numRowsPreliminary||e.haveBoundValue){let t=e.valueOriginal.tree;if(n=1,Array.isArray(t)){let e=t[0];"matrix"===e?n=t[1][1]:vectorOperators.includes(e)&&(n=t.length-1)}}return{setValue:{numRows:n}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){let r=e.numRows;if(!Number.isInteger(r))return{success:!1};r=Math.max(0,r);let a=[{setDependency:"numRowsPreliminary",desiredValue:r}];if(t.haveBoundValue){let e=t.valueOriginal.tree,i=(await n.defaultEntry).tree;if(1===await n.numColumns&&Array.isArray(e)&&vectorOperators.includes(e[0])){let t=e.length-1;if(rt){let s=deepClone(e),o=await n.accumulatedComponents;for(let e=t;e({numColumnsPreliminary:{dependencyType:"stateVariable",variableName:"numColumnsPreliminary"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},haveBoundValue:{dependencyType:"stateVariable",variableName:"haveBoundValue"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.numColumnsPreliminary;if(t.numColumnsPreliminary||e.haveBoundValue){let t=e.valueOriginal.tree;if(n=1,Array.isArray(t)){let e=t[0];"matrix"===e?n=t[1][2]:Array.isArray(t[1])&&vectorOperators.includes(t[1][0])&&("^"===e&&"T"===t[2]||"prime"===e)&&(n=t[1].length-1)}}return{setValue:{numColumns:n}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){let r=e.numColumns;if(!Number.isInteger(r))return{success:!1};r=Math.max(0,r);let a=[{setDependency:"numColumnsPreliminary",desiredValue:r}];if(t.haveBoundValue){let e=(await n.defaultEntry).tree,i=t.valueOriginal.tree,s=i[0];if(Array.isArray(i[1])&&vectorOperators.includes(i[1][0])&&("^"===s&&"T"===i[2]||"prime"===s)){let t=i[1].length-1;if(rt){let s=deepClone(i),o=(await n.accumulatedComponents)[0];o||(o=[]);for(let n=t;n({valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),definition({dependencyValues:e,previousValues:t}){let n=[];t.accumulatedComponents&&(n=deepClone(t.accumulatedComponents));let r=e.valueOriginal.tree;if(Array.isArray(r)){let e=r[0];if("matrix"===e){let e=r[2];for(let[t,r]of e.slice(1).entries()){let e=n[t];e||(e=n[t]=[]);for(let[t,n]of r.slice(1).entries())e[t]=n}return{setValue:{accumulatedComponents:n}}}if(vectorOperators.includes(e)){for(let[e,t]of r.slice(1).entries()){let r=n[e];r||(r=n[e]=[]),r[0]=t}return{setValue:{accumulatedComponents:n}}}if(Array.isArray(r[1])&&vectorOperators.includes(r[1][0])&&("^"===e&&"T"===r[2]||"prime"===e)){let e=n[0];e||(e=n[0]=[]);for(let[t,n]of r[1].slice(1).entries())e[t]=n;return{setValue:{accumulatedComponents:n}}}}let a=n[0];return a||(a=n[0]=[]),a[0]=r,{setValue:{accumulatedComponents:n}}}},e.componentValues={isArray:!0,entryPrefixes:["componentValue"],nDimensions:2,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},accumulatedComponents:{dependencyType:"stateVariable",variableName:"accumulatedComponents"},defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n=e.valueOriginal.tree,r=e.accumulatedComponents,a=e.numRows,i=e.numColumns;if(Array.isArray(n)){let t=n[0];if("matrix"===t){if(n[1][1]===a&&n[1][2]===i){let e={},t=n[2];for(let n=0;ns)for(let t=0;tt)for(let n=t;n[...e]));else{let e=t.valueOriginal.tree;if(o){if(a=e.slice(1,1+i).map((e=>[e])),a.length1)for(let e=0;e1)for(let e=1;ee.slice(1,s+1))),a[0].length1&&a[0].push(...Array(s-1).fill("_")),i>1)for(let e=1;ee[0]))]);return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:r,treatAsInitialChange:n}]}}if(1===i&&l){let e=t.valueOriginal.tree,r=e[0],i=[e[1][0],...a[0]];return i="^"===r?me$3.fromAst(["^",i,"T"]):me$3.fromAst(["prime",i]),{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:i,treatAsInitialChange:n}]}}{let e=["matrix",["tuple",t.numRows,t.numColumns],["tuple",...a.map((e=>["tuple",...e]))]];return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:me$3.fromAst(e),treatAsInitialChange:n}]}}}},e.componentImmediateValues={isArray:!0,entryPrefixes:["componentImmediateValue"],nDimensions:2,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{immediateValueOriginal:{dependencyType:"stateVariable",variableName:"immediateValueOriginal"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},accumulatedComponents:{dependencyType:"stateVariable",variableName:"accumulatedComponents"},defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n=e.immediateValueOriginal.tree,r=e.accumulatedComponents,a=e.numRows,i=e.numColumns;if(Array.isArray(n)){let t=n[0];if("matrix"===t){if(n[1][1]===a&&n[1][2]===i){let e={},t=n[2];for(let n=0;ns)for(let t=0;tt)for(let n=t;n[...e]));else{let e=t.immediateValueOriginal.tree;if(o){if(a=e.slice(1,1+i).map((e=>[e])),a.length1)for(let e=0;e1)for(let e=1;ee.slice(1,s+1))),a[0].length1&&a[0].push(...Array(s-1).fill("_")),i>1)for(let e=1;ee[0]))]);return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:r,treatAsInitialChange:n}]}}if(1===i&&l){let e=t.immediateValueOriginal.tree,r=e[0],i=[e[1][0],...a[0]];return i="^"===r?me$3.fromAst(["^",i,"T"]):me$3.fromAst(["prime",i]),{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:i,treatAsInitialChange:n}]}}{let e=["matrix",["tuple",t.numRows,t.numColumns],["tuple",...a.map((e=>["tuple",...e]))]];return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:me$3.fromAst(e),treatAsInitialChange:n}]}}}},e.componentValuesForDisplay={isArray:!0,entryPrefixes:["componentValueForDisplay"],nDimensions:2,forRenderer:!0,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={componentValue:{dependencyType:"stateVariable",variableName:`componentValue${a}`}}}return{globalDependencies:{displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,usedDefault:r}){let a={};for(let i of n){let n=roundForDisplay({value:t[i].componentValue,dependencyValues:e,usedDefault:r});a[i]=n}return{setValue:{componentValuesForDisplay:a}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({componentValues:{dependencyType:"stateVariable",variableName:"componentValues"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),definition({dependencyValues:e}){let t=e.numRows,n=e.numColumns,r=["matrix",["tuple",t,n]],a=r[2]=["tuple"];for(let r=0;re[1]))]);return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:e}]}}}}else if(1===t.numRows){let e=t.valueOriginal.tree;if(Array.isArray(e)){let t=e[0];if(Array.isArray(e[1])&&vectorOperators.includes(e[1][0])&&("^"===t&&"T"===e[2]||"prime"===t)){let r=[e[1][0],...n[2][1].slice(1)];return r="^"===t?me$3.fromAst(["^",r,"T"]):me$3.fromAst(["prime",r]),{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:r}]}}}}return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:e.value}]}}return{success:!1}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({componentImmediateValues:{dependencyType:"stateVariable",variableName:"componentImmediateValues"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},immediateValueOriginal:{dependencyType:"stateVariable",variableName:"immediateValueOriginal"}}),definition({dependencyValues:e}){let t=e.numRows,n=e.numColumns,r=["matrix",["tuple",t,n]],a=r[2]=["tuple"];for(let r=0;re[1]))]);return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:e}]}}}}else if(1===t.numRows){let e=t.immediateValueOriginal.tree;if(Array.isArray(e)){let t=e[0];if(Array.isArray(e[1])&&vectorOperators.includes(e[1][0])&&("^"===t&&"T"===e[2]||"prime"===t)){let r=[e[1][0],...n[2][1].slice(1)];return r="^"===t?me$3.fromAst(["^",r,"T"]):me$3.fromAst(["prime",r]),{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:r}]}}}}return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:e.immediateValue}]}}return{success:!1}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"matrix"}})},e}async updateRawValues({rawRendererValues:e,transient:t=!1,actionId:n}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValues",value:e}],transient:t,actionId:n});this.coreFunctions.resolveAction({actionId:n})}async updateNumRows({numRows:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"numRows",value:e}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateNumColumns({numColumns:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"numColumns",value:e}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}static adapters=[{stateVariable:"value",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]}]}class MatrixInputGrid extends CompositeComponent{static componentType="matrixInputGrid";static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numRows={returnDependencies:()=>({parentNumRows:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numRows"}}),definition:({dependencyValues:e})=>({setValue:{numRows:e.parentNumRows}})},e.numColumns={returnDependencies:()=>({parentNumColumns:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numColumns"}}),definition:({dependencyValues:e})=>({setValue:{numColumns:e.parentNumColumns}})},e.readyToExpandWhenResolved={returnDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=await e.stateValues.numRows;r.previousNumRows=i;for(let e=0;eo&&(u=l-o,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=u){i=e.replacementsToWithhold-u,o+=u,u=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:i};s.push(t)}else u-=e.replacementsToWithhold,o+=e.replacementsToWithhold,i=0;if(u>0){let e=[];for(let t=o;t({}),definition:()=>({useEssentialOrDefaultValue:{rowInd:!0}})},e.numColumns={returnDependencies:()=>({parentNumColumns:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numColumns"}}),definition:({dependencyValues:e})=>({setValue:{numColumns:e.parentNumColumns}})},e.readyToExpandWhenResolved={returnDependencies:()=>({numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}j;static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=await e.stateValues.numColumns,s=await e.stateValues.rowInd;r.previousNumColumns=i;for(let e=0;eo&&(c=l-o,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=c){i=e.replacementsToWithhold-c,o+=c,c=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:i};s.push(t)}else c-=e.replacementsToWithhold,o+=e.replacementsToWithhold,i=0;if(c>0){let e=[];for(let t=o;t({}),definition:()=>({useEssentialOrDefaultValue:{rowInd:!0}})},e.colInd={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{colInd:!0}})},e.format={returnDependencies:()=>({parentFormat:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"format"}}),definition:({dependencyValues:e})=>({setValue:{format:e.parentFormat}})},e.functionSymbols={returnDependencies:()=>({parentFunctionSymbols:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"functionSymbols"}}),definition:({dependencyValues:e})=>({setValue:{functionSymbols:e.parentFunctionSymbols}})},e.splitSymbols={returnDependencies:()=>({parentSplitSymbols:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"splitSymbols"}}),definition:({dependencyValues:e})=>({setValue:{splitSymbols:e.parentSplitSymbols}})},e.parseScientificNotation={returnDependencies:()=>({parentParseScientificNotation:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"parseScientificNotation"}}),definition:({dependencyValues:e})=>({setValue:{parseScientificNotation:e.parentParseScientificNotation}})},e.displayDigits={returnDependencies:()=>({parentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displayDigits"}}),definition({dependencyValues:e,usedDefault:t}){let n={setValue:{displayDigits:e.parentDisplayDigits}};return t.parentDisplayDigits&&(n.markAsUsedDefault={displayDigits:!0}),n}},e.displayDecimals={returnDependencies:()=>({parentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displayDecimals"}}),definition({dependencyValues:e,usedDefault:t}){let n={setValue:{displayDecimals:e.parentDisplayDecimals}};return t.parentDisplayDecimals&&(n.markAsUsedDefault={displayDecimals:!0}),n}},e.displaySmallAsZero={returnDependencies:()=>({parentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displaySmallAsZero"}}),definition:({dependencyValues:e})=>({setValue:{displaySmallAsZero:e.parentDisplaySmallAsZero}})},e.unionFromU={returnDependencies:()=>({parentUnionFromU:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"unionFromU"}}),definition:({dependencyValues:e})=>({setValue:{unionFromU:e.parentUnionFromU}})},e.value={stateVariablesDeterminingDependencies:["rowInd","colInd"],returnDependencies:({stateValues:e})=>{let t="";return null!==e.rowInd&&null!==e.colInd&&(t=`${e.rowInd+1}_${e.colInd+1}`),{parentComponentValue:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:`componentValue${t}`}}},definition:function({dependencyValues:e}){return e.parentComponentValue?{setValue:{value:e.parentComponentValue}}:{setValue:{value:me$3.fromAst("_")}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return{success:!0,instructions:[{setDependency:"parentComponentValue",desiredValue:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},stateVariablesDeterminingDependencies:["rowInd","colInd"],returnDependencies:({stateValues:e})=>{let t="";return null!==e.rowInd&&null!==e.colInd&&(t=`${e.rowInd+1}_${e.colInd+1}`),{parentComponentImmediateValue:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:`componentImmediateValue${t}`}}},definition:function({dependencyValues:e}){return{setValue:{immediateValue:e.parentComponentImmediateValue}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return{success:!0,instructions:[{setDependency:"parentComponentImmediateValue",desiredValue:e.immediateValue,treatAsInitialChange:t}]}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.valueForDisplay.toString()}}}},e.rawRendererValue={forRenderer:!0,hasEssential:!0,shadowVariable:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"lastValueForDisplay",hasEssential:!0,shadowVariable:!0,defaultValue:null,set:convertValueToMathExpression}],returnDependencies:()=>({immediateValue:{dependencyType:"stateVariable",variableName:"immediateValue"},valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition({dependencyValues:e,essentialValues:t}){if(void 0!==t.rawRendererValue&&deepCompare(t.lastValueForDisplay.tree,e.valueForDisplay.tree))return{useEssentialOrDefaultValue:{rawRendererValue:!0,lastValueForDisplay:!0}};{let t=stripLatex(e.valueForDisplay.toLatex());return"_"===t&&(t=""),{setValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay},setEssentialValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay}}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t,essentialValues:n}){const r=async e=>{let n;e=(e=normalizeLatexString(e,{unionFromU:await t.unionFromU})).replace(/\^(\w)/g,"^{$1}");let r=getFromLatex({functionSymbols:await t.functionSymbols,splitSymbols:await t.splitSymbols,parseScientificNotation:await t.parseScientificNotation});try{n=r(e)}catch(e){n=me$3.fromAst("_")}return n};let a=[];if("string"==typeof e.rawRendererValue){let t=n.rawRendererValue,i=e.rawRendererValue;t!==i&&a.push({setEssentialValue:"rawRendererValue",value:i});let s=await r(t),o=await r(i);deepCompare(o.tree,s.tree)||a.push({setDependency:"immediateValue",desiredValue:o,treatAsInitialChange:!0})}else{a.push({setEssentialValue:"lastValueForDisplay",value:e.rawRendererValue});let t=await r(n.rawRendererValue);if(!deepCompare(e.rawRendererValue.tree,t.tree)){let t=stripLatex(e.rawRendererValue.toLatex());"_"===t&&(t=""),a.push({setEssentialValue:"rawRendererValue",value:t})}}return{success:!0,instructions:a}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"math"}})},e}async updateRawValue({rawRendererValue:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.immediateValue;if(!deepCompare((await this.stateValues.value).tree,t.tree)){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}];"_"!==t.tree&&n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"valueForDisplay"});let r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"rawRendererValue"}],actionId:e})}}}var MatrixInput$1=Object.freeze({__proto__:null,MatrixInput:MatrixInput,MatrixInputGrid:MatrixInputGrid,MatrixInputRow:MatrixInputRow,default:MatrixComponentInput});class Document extends BaseComponent{constructor(e){super(e),Object.assign(this.actions,{submitAllAnswers:this.submitAllAnswers.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="document";static rendererType="section";static renderChildren=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return delete e.hide,delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.documentWideCheckWork={createComponentOfType:"boolean",createStateVariable:"documentWideCheckWork",defaultValue:!1,public:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0},e.displayDigitsForCreditAchieved={createComponentOfType:"integer",createStateVariable:"displayDigitsForCreditAchieved",defaultValue:3,public:!0},e.xmlns={createPrimitiveOfType:"string"},e.type={createPrimitiveOfType:"string"},e}static returnChildGroups(){return[{group:"variantControl",componentTypes:["variantControl"]},{group:"title",componentTypes:["title"]},{group:"description",componentTypes:["description"]},{group:"setups",componentTypes:["setup"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStyleDefinitionStateVariables();Object.assign(e,t);let n=returnFeedbackDefinitionStateVariables();return Object.assign(e,n),e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["title"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[0].componentName),{setValue:{titleChildName:t}}}},e.title={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["title"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.titleChild.length?{setValue:{title:""}}:{setValue:{title:e.titleChild[0].stateValues.text}}},e.description={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({descriptionChild:{dependencyType:"child",childGroups:["description"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.descriptionChild.length?{setValue:{description:""}}:{setValue:{description:e.descriptionChild[0].stateValues.text}}},e.level={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{level:0}})},e.viewedSolution={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{viewedSolution:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"viewedSolution",value:e.viewedSolution}]})},e.scoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"descendant",componentTypes:["_sectioningComponent","answer","setup"],variableNames:["scoredDescendants","aggregateScores","weight"],recurseToMatchedChildren:!1,variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.scoredDescendants)"setup"!==n.componentType&&(n.stateValues.aggregateScores||void 0===n.stateValues.scoredDescendants?t.push(n):t.push(...n.stateValues.scoredDescendants));return{setValue:{scoredDescendants:t}}}},e.nScoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}}),definition:({dependencyValues:e})=>({setValue:{nScoredDescendants:e.scoredDescendants.length}})},e.itemCreditAchieved={isArray:!0,returnArraySizeDependencies:()=>({nScoredDescendants:{dependencyType:"stateVariable",variableName:"nScoredDescendants"}}),returnArraySize:({dependencyValues:e})=>[e.nScoredDescendants],stateVariablesDeterminingDependencies:["scoredDescendants"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.scoredDescendants[r];e&&(n[r]={creditAchieved:{dependencyType:"stateVariable",componentName:e.componentName,variableName:"creditAchieved"}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].creditAchieved;return{setValue:{itemCreditAchieved:n}}}},e.itemNumberByAnswerName={stateVariablesDeterminingDependencies:["scoredDescendants"],returnDependencies({stateValues:e}){let t={scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}};for(let n in e.scoredDescendants){let r=e.scoredDescendants[n];t[`descendantsOf${n}`]={dependencyType:"descendant",ancestorName:r.componentName,componentTypes:["answer"],recurseToMatchedChildren:!1}}return t},definition({dependencyValues:e,componentInfoObjects:t}){let n={};for(let[r,a]of e.scoredDescendants.entries()){let i=r+1;for(let t of e[`descendantsOf${r}`])n[t.componentName]=i;t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"answer"})&&(n[a.componentName]=i)}return{setValue:{itemNumberByAnswerName:n}}}},e.itemVariantInfo={isArray:!0,returnArraySizeDependencies:()=>({nScoredDescendants:{dependencyType:"stateVariable",variableName:"nScoredDescendants"}}),returnArraySize:({dependencyValues:e})=>[e.nScoredDescendants],stateVariablesDeterminingDependencies:["scoredDescendants"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.scoredDescendants[r];e&&(n[r]={generatedVariantInfo:{dependencyType:"stateVariable",componentName:e.componentName,variableName:"generatedVariantInfo",variablesOptional:!0}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].generatedVariantInfo;return{setValue:{itemVariantInfo:n}}}},e.answerDescendants={returnDependencies:()=>({answerDescendants:{dependencyType:"descendant",componentTypes:["answer"],variableNames:["justSubmitted"],recurseToMatchedChildren:!1}}),definition:({dependencyValues:e})=>({setValue:{answerDescendants:e.answerDescendants}})},e.justSubmitted={forRenderer:!0,returnDependencies:()=>({answerDescendants:{dependencyType:"stateVariable",variableName:"answerDescendants"}}),definition:({dependencyValues:e})=>({setValue:{justSubmitted:e.answerDescendants.every((e=>e.stateValues.justSubmitted))}})},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition:({dependencyValues:e})=>({setValue:{showCorrectness:!1!==e.showCorrectnessFlag}})},e.creditAchieved={public:!0,forRenderer:!0,defaultValue:0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},additionalStateVariablesDefined:[{variableName:"percentCreditAchieved",public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}}}],returnDependencies:()=>({scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"},itemCreditAchieved:{dependencyType:"stateVariable",variableName:"itemCreditAchieved"}}),definition({dependencyValues:e}){let t,n=0,r=0;for(let[t,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;n+=e.itemCreditAchieved[t]*i,r+=i}return t=r>0?n/r:1,{setValue:{creditAchieved:t,percentCreditAchieved:100*t}}}},e.creditAchievedIfSubmit={defaultValue:0,stateVariablesDeterminingDependencies:["scoredDescendants"],returnDependencies({stateValues:e}){let t={scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}};for(let[n,r]of e.scoredDescendants.entries())t["creditAchievedIfSubmit"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchievedIfSubmit"};return t},definition({dependencyValues:e}){let t=0,n=0;for(let[r,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;t+=e["creditAchievedIfSubmit"+r]*i,n+=i}return{setValue:{creditAchievedIfSubmit:t/n}}}},e.generatedVariantInfo={providePreviousValuesInDefinition:!0,returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantIndex:{dependencyType:"value",value:e.variantIndex},variantName:{dependencyType:"value",value:e.variantName},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t,previousValues:n}){let r={index:e.variantIndex,name:e.variantName,meta:{createdBy:t}},a=r.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?a.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&a.push(...t.stateValues.generatedVariantInfo.subvariants);for(let[e,t]of a.entries())if(!t.subvariants&&n.generatedVariantInfo){let t=n.generatedVariantInfo.subvariants;t[e]?.subvariants&&(a[e]=Object.assign({},a[e]),a[e].subvariants=t[e].subvariants)}return{setValue:{generatedVariantInfo:r}}}},e.createSubmitAllButton={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"suppressAnswerSubmitButtons",forRenderer:!0}],returnDependencies:()=>({documentWideCheckWork:{dependencyType:"stateVariable",variableName:"documentWideCheckWork"}}),definition({dependencyValues:e,componentName:t}){let n=!1,r=!1;return e.documentWideCheckWork&&(n=!0,r=!0),{setValue:{createSubmitAllButton:n,suppressAnswerSubmitButtons:r}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e}async submitAllAnswers({actionId:e}){this.coreFunctions.requestRecordEvent({verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType}});for(let e of await this.stateValues.answerDescendants)await e.stateValues.justSubmitted||await this.coreFunctions.performAction({componentName:e.componentName,actionName:"submitAnswer"});this.coreFunctions.resolveAction({actionId:e})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){let r,a=e.variants.numberOfVariants,i=e.variants.desiredVariant;if(void 0!==i&&void 0!==i.index){let e=Number(i.index);if(Number.isFinite(e)){Number.isInteger(e)||(console.warn("Variant index "+i.index+" must be an integer"),e=Math.round(e));let t=(e-1)%a;t<0&&(t+=a),r=t+1}else console.warn("Variant index "+i.index+" must be a number"),r=1}if(void 0===r&&(r=1),t.allPossibleVariants=e.variants.allPossibleVariants,t.allVariantNames=e.variants.allVariantNames,t.variantSeed=e.variants.allPossibleVariantSeeds[r-1],t.variantIndex=r,t.variantName=e.variants.allPossibleVariants[r-1],t.uniqueIndex=e.variants.allPossibleVariantUniqueIndices[r-1],t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:!0})}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants.allPossibleVariantUniqueIndices[t-1];if(void 0===r)return{success:!1};let a=getVariantsForDescendantsForUniqueVariants({variantIndex:r,serializedComponent:e,componentInfoObjects:n});return a.success?{success:!0,desiredVariant:{index:t,subvariants:a.desiredVariants}}:(console.log("Failed to get unique variant for document."),{success:!1})}static includeBlankStringChildren=!0}class TextList$1 extends InlineComponent{static componentType="textList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="texts";static primaryStateVariableForDefinition="textsShadow";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"text"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"text"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"texts",componentTypes:["text"]},{group:"textLists",componentTypes:["textList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.textsShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{textsShadow:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},textListChildren:{dependencyType:"child",childGroups:["textLists"],variableNames:["nComponents"]},textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],skipComponentNames:!0},textsShadow:{dependencyType:"stateVariable",variableName:"textsShadow"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[];if(e.textAndTextListChildren.length>0){let a=0;for(let[i,s]of e.textAndTextListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"textList"})){let t=e.textListChildren[a];a++;for(let e=0;ea&&(n=a,r=r.slice(0,a)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],variableNames:["value","text"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},textsShadow:{dependencyType:"stateVariable",variableName:"textsShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].textAndTextListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["text"+t]}else null!==e.textsShadow&&(r[a]=e.textsShadow[a])}return{setValue:{texts:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.texts){if(!n[t])continue;let a=n[t].textAndTextListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].textAndTextListChildren,desiredValue:e.texts[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].textAndTextListChildren,desiredValue:e.texts[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"texts"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e.componentNamesInList={returnDependencies:()=>({textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.textAndTextListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"textList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},textListChildren:{dependencyType:"child",childGroups:["textLists"],variableNames:["nComponents"]},textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"textList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.textAndTextListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"textList"})){let t=e.textListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=["text"]}class TextList extends InlineComponent{static componentType="randomizedTextList";static stateVariableForAttributeValue="texts";static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={default:!1},e.maximumNumber={default:null},e}static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"atLeastZeroTexts",componentType:"text",comparison:"atLeast",number:0}),r=t.newLeaf({name:"atLeastZeroTextLists",componentType:"textList",comparison:"atLeast",number:0}),a=t.newLeaf({name:"exactlyOneString",componentType:"string",number:1,isSugar:!0,returnSugarDependencies:()=>({stringChildren:{dependencyType:"child",childLogicName:"exactlyOneString",variableNames:["value"]}}),logicToWaitOnSugar:["atLeastZeroTexts"],replacementFunction:function({dependencyValues:e}){let t=e.stringChildren[0],n=t.stateValues.value.split(",").map((e=>({componentType:"text",state:{value:e.trim()}})));return{success:!0,newChildren:n,toDelete:[t.componentName]}}}),i=t.newOperator({name:"textAndTextLists",operator:"and",propositions:[n,r]});return t.newOperator({name:"TextsXorSugar",operator:"xor",propositions:[a,i],setAsBase:!0}),t}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],returnDependencies:()=>({textAndTextListChildren:{dependencyType:"child",childLogicName:"textAndTextLists",variableNames:["value","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},childrenToRender:{dependencyType:"stateVariable",variableName:"childrenToRender"}}),definition:function({dependencyValues:e}){let t=[],n=e.textAndTextListChildren.map((e=>e.componentName));for(let r of e.childrenToRender){let a=n.indexOf(r),i=e.textAndTextListChildren[a];i.stateValues.texts?t.push(...i.stateValues.texts):t.push(i.stateValues.value)}return{setValue:{texts:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.texts.length}}}},e.childrenToRender={returnDependencies:({sharedParameters:e})=>({textAndTextListChildren:{dependencyType:"child",childLogicName:"textAndTextLists",variableNames:["childrenToRender"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},selectRng:{dependencyType:"value",value:e.selectRng,doNotProxy:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.textAndTextListChildren)n.stateValues.childrenToRender?t.push(...n.stateValues.childrenToRender):t.push(n.componentName);let n=e.maximumNumber;null!==n&&t.length>n&&(n=Math.max(0,Math.floor(n)),t=t.slice(0,n)),console.log("randomizing children");for(let n=t.length-1;n>0;n--){const r=e.selectRng(),a=Math.floor(r*(n+1));[t[n],t[a]]=[t[a],t[n]]}let r=Math.ceil(e.selectRng()*t.length);return console.log(`numChildren: ${r}`),t=t.slice(0,r),{setValue:{childrenToRender:t}}}},e}initializeRenderer(){void 0===this.renderer&&(this.renderer=new this.availableRenderers.aslist({key:this.componentName}))}}class TupleList extends MathList{static componentType="tupleList";static rendererType="mathList";static includeBlankStringChildren=!1;static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"math",children:e}:e[0]}))}}}),e}}class NumberList extends InlineComponent{static componentType="numberList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="numbers";static primaryStateVariableForDefinition="numbersShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"number"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"number"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"numbers",componentTypes:["number"]},{group:"numberLists",componentTypes:["numberList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{numbersShadow:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},numberListChildren:{dependencyType:"child",childGroups:["numberLists"],variableNames:["nComponents"]},numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],skipComponentNames:!0},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;if(e.numberAndNumberListChildren.length>0)for(let[i,s]of e.numberAndNumberListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"})){let t=e.numberListChildren[a];a++;for(let e=0;ei&&(n=i,r=r.slice(0,i)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.numbers={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["number"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["value","number"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].numberAndNumberListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["number"+t]}else null!==e.numbersShadow&&(r[a]=e.numbersShadow[a])}return{setValue:{numbers:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.numbers){if(!n[t])continue;let a=n[t].numberAndNumberListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].numberAndNumberListChildren,desiredValue:e.numbers[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].numberAndNumberListChildren,desiredValue:e.numbers[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"numbers"},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({numbers:{dependencyType:"stateVariable",variableName:"numbers"}}),definition({dependencyValues:e}){let t;return t=0===e.numbers.length?me$3.fromAst("_"):1===e.numbers.length?me$3.fromAst(e.numbers[0]):me$3.fromAst(["list",...e.numbers]),{setValue:{math:t}}}},e.text={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["valueForDisplay","text","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n=[],r={};if(e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.numberAndNumberListChildren.length>0)for(let t of e.numberAndNumberListChildren)void 0!==t.stateValues.valueForDisplay?n.push(t.stateValues.text):n.push(...t.stateValues.texts);else null!==e.numbersShadow&&(n=e.numbersShadow.map((n=>roundForDisplay({value:me$3.fromAst(n),dependencyValues:e,usedDefault:t}).toString(r))));let a=e.maximumNumber;return null!==a&&n.length>a&&(a=Math.max(0,Math.floor(a)),n=n.slice(0,a)),{setValue:{text:n.join(", "),texts:n}}}},e.componentNamesInList={returnDependencies:()=>({numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.numberAndNumberListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},numberListChildren:{dependencyType:"child",childGroups:["numberLists"],variableNames:["nComponents"]},numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.numberAndNumberListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"numberList"})){let t=e.numberListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class NumberListFromString extends InlineComponent{static componentType="numberListFromString";static rendererType="asList";static renderChildren=!0;static stateVariableForAttributeValue="numbers";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.stringChildren.length}}}},e.numbers={public:!0,shadowingInstructions:{createComponentOfType:"number"},isArray:!0,entryPrefixes:["number"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey:()=>({globalDependencies:{stringChildren:{dependencyType:"child",childGroups:["strings"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let[t,r]of e.stringChildren.entries())n[t]=Number(r);return{setValue:{numbers:n}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"numbers"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({numbers:{dependencyType:"stateVariable",variableName:"numbers"}}),definition:function({dependencyValues:e}){let t=e.numbers.map((e=>e.toString()));return{setValue:{text:t.join(", "),texts:t}}}},e}}class P$2 extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="p";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text?t+=n.stateValues.text:t+=" ";return{setValue:{text:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class BooleanList extends InlineComponent{static componentType="booleanList";static rendererType="asList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="booleans";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"boolean"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"boolean"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"booleans",componentTypes:["boolean"]},{group:"booleanLists",componentTypes:["booleanList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},booleanListChildren:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["nComponents"]},booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],skipComponentNames:!0}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;for(let[i,s]of e.booleanAndBooleanListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"booleanList"})){let t=e.booleanListChildren[a];a++;for(let e=0;ei&&(n=i,r=r.slice(0,i)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.booleans={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},isArray:!0,entryPrefixes:["boolean"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],variableNames:["value","boolean"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].booleanAndBooleanListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["boolean"+t]}}return{setValue:{booleans:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.booleans){if(!n[t])continue;let a=n[t].booleanAndBooleanListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].booleanAndBooleanListChildren,desiredValue:e.booleans[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].booleanAndBooleanListChildren,desiredValue:e.booleans[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"booleans"},e.componentNamesInList={returnDependencies:()=>({booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.booleanAndBooleanListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"booleanList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},booleanListChildren:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["nComponents"]},booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"booleanList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.booleanAndBooleanListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"booleanList"})){let t=e.booleanListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}}class Copy extends CompositeComponent{static componentType="copy";static assignNamesToReplacements=!0;static acceptTarget=!0;static acceptAnyAttribute=!0;static includeBlankStringChildren=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNewNamespaces={createPrimitiveOfType:"boolean"},e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.obtainPropFromComposite={createPrimitiveOfType:"boolean",createStateVariable:"obtainPropFromComposite",defaultValue:!1,public:!0},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.sourceSubnames={createPrimitiveOfType:"stringArray",createStateVariable:"targetSubnames",defaultValue:null,public:!0},e.sourceSubnamesComponentIndex={createComponentOfType:"numberList",createStateVariable:"targetSubnamesComponentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.uri={createPrimitiveOfType:"string",createStateVariable:"uri",defaultValue:null,public:!0},e.sourceAttributesToIgnore={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnore",defaultValue:["hide"],public:!0},e.sourceAttributesToIgnoreRecursively={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnoreRecursively",defaultValue:["isResponse"],public:!0},e.link={createPrimitiveOfType:"boolean"},e.removeEmptyArrayEntries={createPrimitiveOfType:"boolean",createStateVariable:"removeEmptyArrayEntries",defaultValue:!1},e}static keepChildrenSerialized({serializedComponent:e}){return void 0===e.children?[]:Object.keys(e.children)}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetSourcesName={additionalStateVariablesDefined:[{variableName:"sourcesChildNumber",hasEssential:!0,shadowVariable:!0}],stateVariablesDeterminingDependencies:["target"],determineDependenciesImmediately:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:function({stateValues:e,sharedParameters:t}){let n=t.sourceNameMappings;if(!n)return{};let r=n[e.target];return r?{targetSourcesName:{dependencyType:"value",value:r.name},sourcesChildNumber:{dependencyType:"value",value:r.childNumber}}:{}},definition:function({dependencyValues:e}){let t=e.targetSourcesName,n=e.sourcesChildNumber;return t||(t=null,n=null),{setValue:{targetSourcesName:t,sourcesChildNumber:n},setEssentialValue:{targetSourcesName:t,sourcesChildNumber:n}}}},e.targetSources={stateVariablesDeterminingDependencies:["targetSourcesName"],determineDependenciesImmediately:!0,returnDependencies:({stateValues:e})=>e.targetSourcesName?{targetSourcesComponent:{dependencyType:"componentIdentity",componentName:e.targetSourcesName}}:{},definition:function({dependencyValues:e}){let t=e.targetSourcesComponent;return t||(t=null),{setValue:{targetSources:t}}}},e.sourceIndex={stateVariablesDeterminingDependencies:["target"],determineDependenciesImmediately:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:function({stateValues:e,sharedParameters:t}){let n=t.sourceIndexMappings;if(!n)return{};let r=n[e.target];return void 0===r?{}:{sourceIndex:{dependencyType:"value",value:r}}},definition:function({dependencyValues:e}){let t=e.sourceIndex;return void 0===t&&(t=null),{setValue:{sourceIndex:t},setEssentialValue:{sourceIndex:t}}}},e.targetComponent={shadowVariable:!0,stateVariablesDeterminingDependencies:["targetSources","sourceIndex"],determineDependenciesImmediately:!0,returnDependencies:({stateValues:e})=>null!==e.sourceIndex?{}:null!==e.targetSources?{targetSourcesChildren:{dependencyType:"stateVariable",componentName:e.targetSources.componentName,variableName:"childIdentities"},sourcesChildNumber:{dependencyType:"stateVariable",variableName:"sourcesChildNumber"}}:{targetComponent:{dependencyType:"targetComponent"}},definition:function({dependencyValues:e}){let t=null;return e.targetSourcesChildren?(t=e.targetSourcesChildren[e.sourcesChildNumber],t||(t=null)):e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.cid={additionalStateVariablesDefined:["doenetId"],returnDependencies:()=>({uri:{dependencyType:"stateVariable",variableName:"uri"}}),definition:function({dependencyValues:e}){if(!e.uri||"doenet:"!==e.uri.substring(0,7).toLowerCase())return{setValue:{cid:null,doenetId:null}};let t=null,n=null,r=e.uri.match(/[:&]cid=([^&]+)/i);return r&&(t=r[1]),r=e.uri.match(/[:&]doenetid=([^&]+)/i),r&&(n=r[1]),{setValue:{cid:t,doenetId:n}}}},e.serializedComponentsForCid={returnDependencies:()=>({cid:{dependencyType:"stateVariable",variableName:"cid"},serializedChildren:{dependencyType:"serializedChildren",doNotProxy:!0}}),definition:function({dependencyValues:e}){return e.cid&&e.serializedChildren?.length>0?{setValue:{serializedComponentsForCid:e.serializedChildren}}:{setValue:{serializedComponentsForCid:null}}}},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.isPlainMacro={returnDependencies:()=>({isPlainMacro:{dependencyType:"doenetAttribute",attributeName:"isPlainMacro"},targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"},targetSubnames:{dependencyType:"stateVariable",variableName:"targetSubnames"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=e.isPlainMacro&&(!t.isCompositeComponent({componentType:e.targetComponent?.componentType})||e.targetSubnames);if(n&&e.typeAttr){n=!1;let r=t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()],a=t.allComponentClasses[e.targetComponent?.componentType];if(a){let e=t.publicStateVariableInfo[a.componentType].stateVariableDescriptions[a.variableForPlainMacro];r===a.componentType||!e||void 0!==e.createComponentOfType&&e.createComponentOfType!==r||(n=!0)}}return{setValue:{isPlainMacro:n}}}},e.isPlainCopy={returnDependencies:()=>({isPlainCopy:{dependencyType:"doenetAttribute",attributeName:"isPlainCopy"},targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"},targetSubnames:{dependencyType:"stateVariable",variableName:"targetSubnames"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=e.isPlainCopy&&(!t.isCompositeComponent({componentType:e.targetComponent?.componentType})||e.targetSubnames);if(n&&e.typeAttr){n=!1;let r=t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()],a=t.allComponentClasses[e.targetComponent?.componentType];if(a){let e=t.publicStateVariableInfo[a.componentType].stateVariableDescriptions[a.variableForPlainCopy];r===a.componentType||!e||void 0!==e.createComponentOfType&&e.createComponentOfType!==r||(n=!0)}}return{setValue:{isPlainCopy:n}}}},e.linkAttrForDetermineDeps={returnDependencies:()=>({linkAttr:{dependencyType:"attributePrimitive",attributeName:"link"}}),definition({dependencyValues:e}){let t;return t=null===e.linkAttr||e.linkAttr,{setValue:{linkAttrForDetermineDeps:t}}}},e.replacementSourceIdentities={stateVariablesDeterminingDependencies:["targetComponent","componentIndex","propName","targetSubnames","targetSubnamesComponentIndex","obtainPropFromComposite","linkAttrForDetermineDeps"],additionalStateVariablesDefined:["addLevelToAssignNames"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={},r=!1,a=!1;if(null!==e.targetComponent){if(t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})&&(!e.propName||!e.obtainPropFromComposite))if(e.linkAttrForDetermineDeps){a=!0;let t=e.targetSubnamesComponentIndex;t&&(t=[...t]),n.targets={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,componentIndex:e.componentIndex,targetSubnames:e.targetSubnames,targetSubnamesComponentIndex:t}}else r=!0;a||null!==e.componentIndex&&1!==e.componentIndex||(n.targets={dependencyType:"stateVariable",variableName:"targetComponent"})}return n.addLevelToAssignNames={dependencyType:"value",value:r},n},definition({dependencyValues:e}){let t=null;return e.targets&&(t=e.targets,Array.isArray(t)||(t=[t])),{setValue:{replacementSourceIdentities:t,addLevelToAssignNames:e.addLevelToAssignNames}}}},e.replacementSources={stateVariablesDeterminingDependencies:["replacementSourceIdentities","propName","propIndex","isPlainMacro","isPlainCopy"],additionalStateVariablesDefined:["effectivePropNameBySource"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"},propIndex:{dependencyType:"stateVariable",variableName:"propIndex"}};if(!e.propName&&null!==e.propIndex)throw Error("You cannot specify a propIndex without specifying a prop.");if(null!==e.replacementSourceIdentities)for(let[r,a]of e.replacementSourceIdentities.entries()){let i,s=e.propName;if(e.isPlainMacro?s=t.allComponentClasses[a.componentType].variableForPlainMacro:e.isPlainCopy&&(s=t.allComponentClasses[a.componentType].variableForPlainCopy),s){n["propName"+r]={dependencyType:"value",value:s};let t=e.propIndex;t&&(t=[...t]),i={dependencyType:"stateVariable",componentName:a.componentName,variableName:s,returnAsComponentObject:!0,variablesOptional:!0,propIndex:t,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0}}else i={dependencyType:"componentIdentity",componentName:a.componentName};n["target"+r]=i}return n},definition({dependencyValues:e}){let t=null,n=null;if(null!==e.replacementSourceIdentities){t=[],n=[];for(let r in e.replacementSourceIdentities){let a=e["target"+r];if(a){let i;t.push(a),a.stateValues&&(i=Object.keys(a.stateValues)[0]),!i&&e["propName"+r]&&(i="__prop_name_not_found"),n.push(i)}}}return{setValue:{replacementSources:t,effectivePropNameBySource:n}}}},e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;if(e.typeAttr){if(!(t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in t.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);n=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error("You must specify createComponentOfType when specifying nComponents for a copy.");n=null}return{setValue:{nComponentsSpecified:n}}}},e.link={returnDependencies:()=>({linkAttr:{dependencyType:"attributePrimitive",attributeName:"link"},serializedComponentsForCid:{dependencyType:"stateVariable",variableName:"serializedComponentsForCid"},replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;return n=null===e.linkAttr?!(e.serializedComponentsForCid||e.replacementSourceIdentities&&e.replacementSourceIdentities.some((e=>t.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"module"})))):!1!==e.linkAttr,{setValue:{link:n}}}},e.readyToExpandWhenResolved={stateVariablesDeterminingDependencies:["targetComponent","propName","obtainPropFromComposite","link"],returnDependencies({stateValues:e,componentInfoObjects:t}){let n={targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"},serializedComponentsForCid:{dependencyType:"stateVariable",variableName:"serializedComponentsForCid"},link:{dependencyType:"stateVariable",variableName:"link"}};return!e.targetComponent||!t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})||e.propName&&e.obtainPropFromComposite||(n.targetReadyToExpandWhenResolved={dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"readyToExpandWhenResolved"}),e.link||(n.replacementSources={dependencyType:"stateVariable",variableName:"replacementSources"}),n},definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={stateVariablesDeterminingDependencies:["targetComponent","replacementSourceIdentities","effectivePropNameBySource","propName","obtainPropFromComposite","link","removeEmptyArrayEntries"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){if(!e.link)return{};let n={targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"},replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"},propIndex:{dependencyType:"stateVariable",variableName:"propIndex"}};if(null!==e.effectivePropNameBySource)for(let[t,r]of e.effectivePropNameBySource.entries())if(r){let a=e.replacementSourceIdentities[t];n["sourceArraySize"+t]={dependencyType:"stateVariableArraySize",componentName:a.componentName,variableName:r,variablesOptional:!0,caseInsensitiveVariableMatch:!0},n["sourceComponentType"+t]={dependencyType:"stateVariableComponentType",componentName:a.componentName,variableName:r,variablesOptional:!0,caseInsensitiveVariableMatch:!0}}return null===e.targetComponent||!t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})||e.propName&&e.obtainPropFromComposite||(n.allReplacementIdentities={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,variableNames:["isInactiveCompositeReplacement"]}),e.removeEmptyArrayEntries&&(n.replacementSources={dependencyType:"stateVariable",variableName:"replacementSources"}),n},markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e.effectiveAssignNames={returnDependencies:()=>({assignNames:{dependencyType:"doenetAttribute",attributeName:"assignNames"},addLevelToAssignNames:{dependencyType:"stateVariable",variableName:"addLevelToAssignNames"}}),definition({dependencyValues:e}){let t=e.assignNames;return t&&e.addLevelToAssignNames&&(t=[t]),{setValue:{effectiveAssignNames:t}}}},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,resolveItem:i,publicCaseInsensitiveAliasSubstitutions:s}){await e.stateValues.nComponentsSpecified,n.numReplacementsBySource=[],n.numNonStringReplacementsBySource=[],n.propVariablesCopiedBySource=[],n.sourceNames=[],n.uniqueIdentifiersUsedBySource={};let o=e.attributes.newNamespace?.primitive,l=this.createAttributesObject(),u=await e.stateValues.effectiveAssignNames,c=await e.stateValues.serializedComponentsForCid;if(c){let t=deepClone([c[0]]),i=deepClone(c.slice(1));if(t[0].children){let n;if(n=t[0].componentName?t[0].componentName+"/":t[0].originalName+"/",e.doenetAttributes.keptNewNamespaceOfLastChild){n=n.slice(0,n.length-1);let e=n.lastIndexOf("/");n=n.slice(0,e+1)}restrictTNamesToNamespace({components:t[0].children,namespace:n,invalidateReferencesToBaseNamespace:e.doenetAttributes.keptNewNamespaceOfLastChild})}if("externalContent"===t[0].componentType)for(let n of t[0].children){if("object"!=typeof n)continue;n.attributes||(n.attributes={});let t=convertAttributesForComponentType({attributes:e.attributes,componentType:n.componentType,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});for(let e in t){let n=t[e];n.component?setTNamesToAbsolute([n.component]):n.childrenForComponent&&setTNamesToAbsolute(n.childrenForComponent)}Object.assign(n.attributes,t)}else{t[0].attributes||(t[0].attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t[0].componentType,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});for(let e in n){let t=n[e];t.component?setTNamesToAbsolute([t.component]):t.childrenForComponent&&setTNamesToAbsolute(t.childrenForComponent)}Object.assign(t[0].attributes,n)}return t=processAssignNames({assignNames:u,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:r}).serializedComponents,e.doenetAttributes.fromCopyFromURI&&i.length>0&&this.addChildrenFromComposite({replacements:t,children:i,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,componentInfoObjects:r}),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}let p=await e.stateValues.sourceIndex;if(null!==p){let t=processAssignNames({assignNames:u,serializedComponents:[{componentType:"number",attributes:convertAttributesForComponentType({attributes:e.attributes,componentType:"number",componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a}),state:{value:p,fixed:!0}}],parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:r});return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t.serializedComponents,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}let d=await e.stateValues.replacementSourceIdentities;if(!await e.stateValues.targetComponent||!d){let t=[];if(e.doenetAttributes.fromCopyTarget){let i=r.componentTypeLowerCaseMapping[e.attributes.createComponentOfType.primitive.toLowerCase()],s=r.allComponentClasses[i],c=convertAttributesForComponentType({attributes:e.attributes,componentType:i,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});n.uniqueIdentifiersUsedBySource[0]=[];let p=getUniqueIdentifierFromBase(i+"|empty",n.uniqueIdentifiersUsedBySource[0]),d=deepClone(e.serializedChildren);s.includeBlankStringChildren||(d=d.filter((e=>"string"!=typeof e||""!==e.trim())));let m=c;e.attributes.assignNewNamespaces?.primitive&&(m.newNamespace={primitive:!0}),t=[{componentType:i,attributes:m,children:d,uniqueIdentifier:p}],t=processAssignNames({assignNames:u,serializedComponents:t,parentName:e.componentName,componentInfoObjects:r,originalNamesAreConsistent:!0}).serializedComponents,n.numReplacementsBySource.push(t.length),n.numNonStringReplacementsBySource.push(t.filter((e=>"string"!=typeof e)).length)}return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l})).replacements}}let m=await i({componentName:e.componentName,type:"determineDependencies",stateVariable:"replacementSources",dependency:"__determine_dependencies",expandComposites:!1});if(!m.success)throw Error(`Couldn't resolve determineDependencies of replacementSources of ${e.componentName}`);let h=await e.stateValues.effectivePropNameBySource;for(let t in d){if(h[t]&&(m=await i({componentName:e.componentName,type:"recalculateDownstreamComponents",stateVariable:"replacementSources",dependency:"target"+t,expandComposites:!1}),!m.success))throw Error(`Couldn't resolve recalculateDownstreamComponents for target${t} of replacementSources of ${e.componentName}`)}let f=[],y=[],g=[],b=0,v=0;for(let i in d){let o,u=n.uniqueIdentifiersUsedBySource[i]=[];if(e.attributes.createComponentOfType?.primitive){let t=await e.stateValues.nComponentsSpecified,n=d.length;o=Math.floor(t/n),i"string"!=typeof e)).length,b+=y[i],v+=g[i],f.push(...p)}return n.numReplacementsBySource=y,n.numNonStringReplacementsBySource=g,n.sourceNames=d.map((e=>e.componentName)),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:f,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}static async createReplacementForSource({component:e,sourceNum:t,components:n,numReplacementsSoFar:r,numNonStringReplacementsSoFar:a,uniqueIdentifiersUsed:i,compositeAttributesObj:s,componentInfoObjects:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c,fromCopyTarget:p}){let d=(await e.stateValues.replacementSourceIdentities)[t];if("object"!=typeof d)return{serializedReplacements:[d]};let m=n[d.componentName],h=await e.stateValues.link;h&&!await e.stateValues.removeEmptyArrayEntries||(d=(await e.stateValues.replacementSources)[t]);let f=e.attributes.newNamespace?.primitive,y=await e.stateValues.effectiveAssignNames,g=(await e.stateValues.effectivePropNameBySource)[t];if(g){let t=await replacementFromProp({component:e,components:n,replacementSource:d,propName:g,numReplacementsSoFar:r,numNonStringReplacementsSoFar:a,uniqueIdentifiersUsed:i,compositeAttributesObj:s,componentInfoObjects:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c});return{serializedReplacements:processAssignNames({assignNames:y,serializedComponents:t.serializedReplacements,parentName:e.componentName,parentCreatesNewNamespace:f,indOffset:a,componentInfoObjects:o}).serializedComponents,propVariablesCopiedByReplacement:t.propVariablesCopiedByReplacement}}let b=await e.stateValues.sourceAttributesToIgnore,v=await e.stateValues.sourceAttributesToIgnoreRecursively,N=[await m.serialize({copyAll:!h,copyVariants:!h,sourceAttributesToIgnore:b,sourceAttributesToIgnoreRecursively:v})];h||void 0===N[0].state?.fixed||delete N[0].state.fixed,N=postProcessCopy({serializedComponents:N,componentName:e.componentName,uniqueIdentifiersUsed:i,addShadowDependencies:h,unlinkExternalCopies:!h}),N.length>0&&delete N[0].doenetAttributes.haveNewNamespaceOnlyFromShadow;for(let t of N){if("object"!=typeof t)continue;t.attributes||(t.attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:o,compositeAttributesObj:s,compositeCreatesNewNamespace:f,flags:c});Object.assign(t.attributes,n)}return N[0].attributes.newNamespace?.primitive&&!e.attributes.assignNewNamespaces?.primitive&&(N[0].doenetAttributes.haveNewNamespaceOnlyFromShadow=!0),N=processAssignNames({assignNames:y,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,serializedComponents:N,parentName:e.componentName,parentCreatesNewNamespace:f,indOffset:a,componentInfoObjects:o,originalNamesAreConsistent:f&&!y}).serializedComponents,p&&1===N.length&&e.serializedChildren.length>0&&this.addChildrenFromComposite({replacements:N,children:e.serializedChildren,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,componentInfoObjects:o}),{serializedReplacements:N}}static addChildrenFromComposite({replacements:e,children:t,assignNewNamespaces:n,componentInfoObjects:r}){let a=e[0];a.children||(a.children=[]);let i=deepClone(t);if(r.allComponentClasses[a.componentType].includeBlankStringChildren||(i=i.filter((e=>"string"!=typeof e||""!==e.trim()))),e[0].attributes.newNamespace?.primitive&&n){renameAutonameBasedOnNewCounts(i,countRegularComponentTypesInNamespace(a.children))}let s=processAssignNames({serializedComponents:i,parentName:e[0].componentName,parentCreatesNewNamespace:n,componentInfoObjects:r,originalNamesAreConsistent:!0});if(e[0].attributes.newNamespace?.primitive&&!n)for(let e of s.serializedComponents)"object"==typeof e&&(e.doenetAttributes.ignoreParentNewNamespace=!0);a.children.push(...s.serializedComponents)}static async calculateReplacementChanges({component:e,componentChanges:t,components:n,workspace:r,componentInfoObjects:a,flags:i,resolveItem:s,publicCaseInsensitiveAliasSubstitutions:o}){if(await e.stateValues.serializedComponentsForCid)return[];if(null!==await e.stateValues.sourceIndex)return[];let l=this.createAttributesObject(),u=await e.stateValues.effectiveAssignNames,c=await e.stateValues.replacementSourceIdentities;if(!await e.stateValues.targetComponent||!c){if(await e.stateValues.targetSources)return[];{let t=[];if(e.replacements.length>0){let n={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToDelete:e.replacements.length};t.push(n)}let n=0===r.sourceNames.length;r.sourceNames=[],r.numReplacementsBySource=[],r.numNonStringReplacementsBySource=[],r.propVariablesCopiedBySource=[];let s=await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:t,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i});return n?[]:s.replacementChanges}}if(await e.stateValues.targetInactive){let t=[],n=e.replacements.length;if(n>0){if(e.replacementsToWithhold!==n){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:n};t.push(e)}t=(await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:t,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i})).replacementChanges}return t}let p=await s({componentName:e.componentName,type:"determineDependencies",stateVariable:"replacementSources",dependency:"__determine_dependencies",expandComposites:!1});if(!p.success)throw Error(`Couldn't resolve determineDependencies of replacementSources of ${e.componentName}`);let d=await e.stateValues.effectivePropNameBySource;for(let t in c){if(d[t]&&(p=await s({componentName:e.componentName,type:"recalculateDownstreamComponents",stateVariable:"replacementSources",dependency:"target"+t,expandComposites:!1}),!p.success))throw Error(`Couldn't resolve recalculateDownstreamComponents for target${t} of replacementSources of ${e.componentName}`)}let m=[];if(e.replacementsToWithhold>0){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};m.push(e)}let h=0,f=0,y=[],g=[],b=[],v=Math.max(c.length,r.numReplacementsBySource.length),N=!1;for(let t=0;t0){if(!N){let e=r.numReplacementsBySource.slice(t).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:h,numberReplacementsToDelete:e};m.push(t)}N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}r.uniqueIdentifiersUsedBySource[t]=[]}y[t]=0,g[t]=0,b.push([]);continue}let p=r.sourceNames[t],v=void 0===p||u.componentName!==p||N;if(!v)for(let n=0;ne+t),0);v.numberReplacementsToReplace=e,N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}m.push(v);continue}if(!d[t]&&r.numReplacementsBySource[t]>0){h+=r.numReplacementsBySource[t],f+=r.numNonStringReplacementsBySource[t],y[t]=r.numReplacementsBySource[t],g[t]=r.numNonStringReplacementsBySource[t];continue}let T=r.uniqueIdentifiersUsedBySource[t]=[],C=await this.createReplacementForSource({component:e,sourceNum:t,components:n,numReplacementsSoFar:h,numNonStringReplacementsSoFar:f,uniqueIdentifiersUsed:T,compositeAttributesObj:l,componentInfoObjects:a,nComponentsForSource:s,publicCaseInsensitiveAliasSubstitutions:o,flags:i}),A=C.propVariablesCopiedByReplacement,V=C.serializedReplacements,x=V.length;if(x!==r.numReplacementsBySource[t]){let e=r.numReplacementsBySource.slice(t).reduce(((e,t)=>e+t),0),n={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:h,numberReplacementsToReplace:e,serializedReplacements:V,assignNamesOffset:f};m.push(n),N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}else{let n=0;for(let a=0;ae!==A[a][t]))?(s=!1,i=!0):e.replacements[h+a].componentType!==V[a].componentType&&(i=!0)),0==a&&i&&s){1===await e.stateValues.nComponentsSpecified&&1===x&&!(e.replacementsToWithhold>0)&&1===r.sourceNames.length&&(i=!1)}if(i){let e={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:h+a,numberReplacementsToReplace:1,serializedReplacements:[V[a]],assignNamesOffset:f+n};m.push(e)}"string"!=typeof V[a]&&n++}}let S=V.filter((e=>"string"!=typeof e)).length;h+=x,f+=S,y[t]=x,g[t]=S,b[t]=A}let T=0===r.sourceNames.length;r.numReplacementsBySource=y,r.numNonStringReplacementsBySource=g,r.sourceNames=c.map((e=>e.componentName)),r.propVariablesCopiedBySource=b;let C=await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:m,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i});return T&&0===r.sourceNames.length?[]:C.replacementChanges}static async recreateReplacements({component:e,sourceNum:t,numReplacementsSoFar:n,numNonStringReplacementsSoFar:r,numReplacementsToDelete:a,uniqueIdentifiersUsed:i,components:s,compositeAttributesObj:o,componentInfoObjects:l,nComponentsForSource:u,publicCaseInsensitiveAliasSubstitutions:c,flags:p}){let d=await this.createReplacementForSource({component:e,sourceNum:t,numReplacementsSoFar:n,numNonStringReplacementsSoFar:r,components:s,uniqueIdentifiersUsed:i,compositeAttributesObj:o,componentInfoObjects:l,nComponentsForSource:u,publicCaseInsensitiveAliasSubstitutions:c,flags:p}),m=d.propVariablesCopiedByReplacement,h=d.serializedReplacements,f={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:a,serializedReplacements:h,assignNamesOffset:r};return{numReplacements:h.length,numNonStringReplacements:h.filter((e=>"string"!=typeof e)).length,propVariablesCopiedByReplacement:m,replacementInstruction:f}}}async function replacementFromProp({component:e,components:t,replacementSource:n,propName:r,uniqueIdentifiersUsed:a,compositeAttributesObj:i,componentInfoObjects:s,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l,flags:u}){let c=[],p=[],d=e.attributes.newNamespace?.primitive,m=-1,h=t[n.componentName],f=l({stateVariables:[r],componentClass:h.constructor})[0];if(void 0===f||"__not_public"===f.slice(0,12))return"__prop_name_not_found"!==r&&console.warn(`Could not find prop ${r} on a component of type ${n.componentType}`),{serializedReplacements:[],propVariablesCopiedByReplacement:[]};let y=h.state[f],g=await y.value,b=await e.stateValues.link;if(y.isArray||y.isArrayEntry){let t,r,l,g;if(y.isArray?(t=y,l=await y.arraySize,r=y.getAllArrayKeys(l,!1)):(t=h.state[y.arrayStateVariable],r=await y.unflattenedArrayKeys,g=await y.arrayKeys),t.shadowingInstructions?.hasVariableComponentType&&(await e.stateValues.replacementSources,!t.shadowingInstructions.createComponentOfType))return{serializedReplacements:[],propVariablesCopiedByReplacement:[]};let v=y.wrappingComponents,N=v.length,T=o;if(y.isArray)T=l.slice(0,l.length-N).reduce(((e,t)=>e*t),1);else if(0===g.length)T=0;else if(0===N)T=g.length;else if(N>=y.nDimensions)T=1;else if(N===y.nDimensions-1)T=r.length;else{T=flattenLevels(r,y.nDimensions-N-1).length}if(0===N){let o=flattenDeep(r);for(let r=0;r1)for(let e of r){let t=await o(e,i-1);l.push(...t.pieces),c.push(...t.propVariablesCopiedByPiece)}else for(let i of r){let r,o,p=t.arrayVarNameFromArrayKey(i),d=[p],m=getUniqueIdentifierFromBase(n.componentName+"|shadow|"+p,a),f=t.shadowingInstructions.createComponentOfType;if(Array.isArray(f)&&(f=f[t.keyToIndex(i)]),t.shadowingInstructions.addAttributeComponentsShadowingStateVariables){r={};for(let e in t.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let n=t.shadowingInstructions.addAttributeComponentsShadowingStateVariables[e].stateVariableToShadow,a=h.state[n];a.isArray&&(n=a.arrayVarNameFromArrayKey(i)),r[e]={stateVariableToShadow:n}}}if(t.shadowingInstructions.addStateVariablesShadowingStateVariables){o={};for(let e in t.shadowingInstructions.addStateVariablesShadowingStateVariables){let n=t.shadowingInstructions.addStateVariablesShadowingStateVariables[e].stateVariableToShadow,r=h.state[n];r.isArray&&(n=r.arrayVarNameFromArrayKey(i)),o[e]={stateVariableToShadow:n}}}if(b){let t={};if(r){let n=s.allComponentClasses[f].createAttributesObject();for(let a in r){let i=r[a].stateVariableToShadow,s={componentType:n[a].createComponentOfType,downstreamDependencies:{[h.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:i}]}};t[a]={component:s}}}l.push({componentType:f,attributes:t,downstreamDependencies:{[n.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:p,additionalStateVariableShadowing:o}]},uniqueIdentifier:m})}else{let e={};if(r){let t={};for(let e in r){let n=r[e].stateVariableToShadow,a=h.state[n],s=await a.value;a.isArray&&(s=s[a.keyToIndex[i]]),h.state[n].usedDefault||(t[e]=s)}let n=convertAttributesForComponentType({attributes:t,componentType:f,componentInfoObjects:s,flags:u});if(y.shadowingInstructions.attributesToShadow)for(let e of y.shadowingInstructions.attributesToShadow)h.attributes[e]?.component?n[e]={component:await(h.attributes[e]?.component.serialize({copyAll:!0,copyVariants:!0}))}:void 0!==h.attributes[e]?.primitive&&(n[e]={primitive:JSON.parse(JSON.stringify(h.attributes[e].primitive))});Object.assign(e,n)}let n="value",a=s.allComponentClasses[f];a.primaryEssentialStateVariable?n=a.primaryEssentialStateVariable:a.primaryStateVariableForDefinition&&(n=a.primaryStateVariableForDefinition);let o=t.keyToIndex(i);Array.isArray(o)||(o=[o]);let c=await t.value;for(let e of o)c=c[e];let p={componentType:f,attributes:e,state:{[n]:c},uniqueIdentifier:m};l.push(p)}c.push(d)}let p=v[i-1];if(l.length>0&&p&&p.length>0){for(let e=p.length-1;e>=0;e--){let t="object"==typeof p[e]?p[e].componentType:p[e],n=getUniqueIdentifierFromBase(t+"|wrapper",a),r=[],i={};for(let e of l)if(e.isAttribute){let t=e.isAttribute;delete e.isAttribute,i[t]={component:e}}else r.push(e);l=[{componentType:t,children:r,attributes:i,uniqueIdentifier:n,skipSugar:!0}],"object"==typeof p[e]&&(p[e].doenetAttributes&&(l[0].doenetAttributes=Object.assign({},p[e].doenetAttributes)),p[e].isAttribute&&(l[0].isAttribute=p[e].isAttribute))}c=[flattenDeep(c)]}return{pieces:l,propVariablesCopiedByPiece:c}},l=await o(r,y.nDimensions),N=l.pieces;p=l.propVariablesCopiedByPiece;for(let t of N){if("object"!=typeof t)continue;t.attributes||(t.attributes={});let r=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:s,compositeAttributesObj:i,compositeCreatesNewNamespace:d,flags:u});Object.assign(t.attributes,r),b&&(t.downstreamDependencies={[n.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:f,ignorePrimaryStateVariable:!0}]})}if(m+=N.length,c.push(...N),N.length0?"object"==typeof i[0]?(n=i[0].componentType,r=Object.assign({},i[0].doenetAttributes)):n=i[0]:(n=t.shadowingInstructions.createComponentOfType,Array.isArray(n)&&(n=y.isArrayEntry?n[t.keyToIndex(g[e])]:n[e]));let s={componentType:n,uniqueIdentifier:getUniqueIdentifierFromBase(n+"|empty",a)};r&&(s.doenetAttributes=r),c.push(s)}else if(N>T)throw Error(`Something went wrong when creating replacements for ${e.componentName} as we ended up with too many replacements`)}}else{if(y.shadowingInstructions?.hasVariableComponentType&&await y.value,!y.shadowingInstructions?.createComponentOfType)return{serializedReplacements:[],propVariablesCopiedByReplacement:[]};m++,(p[m]=[]).push(f);let t=getUniqueIdentifierFromBase(h.componentName+"|shadow|"+f,a);if("string"===y.shadowingInstructions.createComponentOfType)c.push(await y.value);else{let n=convertAttributesForComponentType({attributes:e.attributes,componentType:y.shadowingInstructions.createComponentOfType,componentInfoObjects:s,compositeAttributesObj:i,compositeCreatesNewNamespace:d,flags:u});if(b){let r={};if(y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let t=s.allComponentClasses[y.shadowingInstructions.createComponentOfType].createAttributesObject();for(let n in y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let a=y.shadowingInstructions.addAttributeComponentsShadowingStateVariables[n].stateVariableToShadow,i={componentType:t[n].createComponentOfType,downstreamDependencies:{[h.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:a}]}};r[n]={component:i}}}Object.assign(r,n),c.push({componentType:y.shadowingInstructions.createComponentOfType,attributes:r,downstreamDependencies:{[h.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:f,additionalStateVariableShadowing:y.shadowingInstructions.addStateVariablesShadowingStateVariables}]},uniqueIdentifier:t})}else{let e={};if(y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let t={};for(let e in y.shadowingInstructions.addAttributeComponentsShadowingStateVariables)if("fixed"!==e){let n=y.shadowingInstructions.addAttributeComponentsShadowingStateVariables[e].stateVariableToShadow,r=await h.state[n].value;h.state[n].usedDefault||(t[e]=r)}let n=convertAttributesForComponentType({attributes:t,componentType:y.shadowingInstructions.createComponentOfType,componentInfoObjects:s,flags:u});if(y.shadowingInstructions.attributesToShadow)for(let e of y.shadowingInstructions.attributesToShadow)h.attributes[e]?.component?n[e]={component:await(h.attributes[e]?.component.serialize({copyAll:!0,copyVariants:!0}))}:void 0!==h.attributes[e]?.primitive&&(n[e]={primitive:JSON.parse(JSON.stringify(h.attributes[e].primitive))});Object.assign(e,n)}Object.assign(e,n);let r="value",a=s.allComponentClasses[y.shadowingInstructions.createComponentOfType];a.primaryEssentialStateVariable?r=a.primaryEssentialStateVariable:a.primaryStateVariableForDefinition&&(r=a.primaryStateVariableForDefinition);let i={componentType:y.shadowingInstructions.createComponentOfType,attributes:e,state:{[r]:g},uniqueIdentifier:t};c.push(i)}}}return{serializedReplacements:c,propVariablesCopiedByReplacement:p}}class Extract extends CompositeComponent{static componentType="extract";static assignNamesToReplacements=!0;static acceptAnyAttribute=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;if(e.typeAttr){if(!(t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in t.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);n=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error("You must specify createComponentOfType when specifying nComponents for a copy.");n=null}return{setValue:{nComponentsSpecified:n}}}},e.link={returnDependencies:()=>({}),definition:()=>({setValue:{link:!0}})},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.sourceComponents={stateVariablesDeterminingDependencies:["propName","componentIndex","propIndex"],additionalStateVariablesDefined:["effectivePropNameBySource"],returnDependencies:function({stateValues:e}){let t,n;null!==e.componentIndex&&(n=Number(e.componentIndex),t=Number.isInteger(n)?[n-1]:[]);let r=e.propIndex;return r&&(r=[...r]),{children:{dependencyType:"child",childGroups:["anything"],variableNames:[e.propName],variablesOptional:!0,childIndices:t,propIndex:r,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0},propName:{dependencyType:"stateVariable",variableName:"propName"}}},definition:function({dependencyValues:e}){let t=e.children,n=[];for(let e of t){let t;e.stateValues&&(t=Object.keys(e.stateValues)[0]),t||(t="__prop_name_not_found"),n.push(t)}return{setValue:{sourceComponents:t,effectivePropNameBySource:n}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({replacementClasses:{dependencyType:"stateVariable",variableName:"sourceComponents"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={returnDependencies:()=>({sourceComponents:{dependencyType:"stateVariable",variableName:"sourceComponents"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,publicCaseInsensitiveAliasSubstitutions:i}){let s=[],o=[],l=0;n.propVariablesCopiedBySource=[],n.uniqueIdentifiersUsedBySource={};let u=this.createAttributesObject(),c=await e.stateValues.sourceComponents;for(let a=0;ae.componentName)),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:s,assignNames:e.doenetAttributes.assignNames,workspace:n,componentInfoObjects:r,compositeAttributesObj:u,flags:a})).replacements}}static async createReplacementForSource({component:e,components:t,sourceNum:n,numReplacementsSoFar:r,uniqueIdentifiersUsed:a,componentInfoObjects:i,compositeAttributesObj:s,publicCaseInsensitiveAliasSubstitutions:o}){let l=(await e.stateValues.effectivePropNameBySource)[n],u=await replacementFromProp({component:e,components:t,replacementSource:(await e.stateValues.sourceComponents)[n],propName:l,uniqueIdentifiersUsed:a,compositeAttributesObj:s,componentInfoObjects:i,publicCaseInsensitiveAliasSubstitutions:o}),c=u.serializedReplacements,p=u.propVariablesCopiedByReplacement,d=e.attributes.newNamespace?.primitive;return c=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:c,parentName:e.componentName,indOffset:r,parentCreatesNewNamespace:d,componentInfoObjects:i}).serializedComponents,{serializedReplacements:c,propVariablesCopiedByReplacement:p}}static async calculateReplacementChanges({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,publicCaseInsensitiveAliasSubstitutions:i}){let s=[],o=0,l=[],u=[],c=this.createAttributesObject(),p=await e.stateValues.sourceComponents,d=Math.max(p.length,n.numReplacementsBySource.length),m=!1;for(let a=0;a0){if(!m){let e=n.numReplacementsBySource.slice(a).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:o,numberReplacementsToDelete:e};s.push(t)}m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}n.uniqueIdentifiersUsedBySource[a]=[]}l[a]=0,u.push([]);continue}let h=n.sourceNames[a],f=void 0===h||d.componentName!==h||m;if(!f)for(let t=0;te+t),0);g.numberReplacementsToReplace=e,m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}s.push(g);continue}let y=n.uniqueIdentifiersUsedBySource[a]=[],g=await this.createReplacementForSource({component:e,sourceNum:a,components:t,numReplacementsSoFar:o,uniqueIdentifiersUsed:y,componentInfoObjects:r,compositeAttributesObj:c,publicCaseInsensitiveAliasSubstitutions:i}),b=g.propVariablesCopiedByReplacement,v=g.serializedReplacements,N=v.length;if(N!==n.numReplacementsBySource[a]){let e=n.numReplacementsBySource.slice(a).reduce(((e,t)=>e+t),0),t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:o,numberReplacementsToReplace:e,serializedReplacements:v,assignNamesOffset:o};s.push(t),m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}else for(let e=0;et!==b[e][n]))){let t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:o+e,numberReplacementsToReplace:1,serializedReplacements:[v[e]],assignNamesOffset:o+e};s.push(t)}o+=N,l[a]=N,u[a]=b}return n.numReplacementsBySource=l,n.numNonStringReplacementsBySource=[...l],n.sourceNames=p.map((e=>e.componentName)),n.propVariablesCopiedBySource=u,(await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:s,assignNames:e.doenetAttributes.assignNames,workspace:n,componentInfoObjects:r,compositeAttributesObj:c,flags:a})).replacementChanges}static async recreateReplacements({component:e,sourceNum:t,numReplacementsSoFar:n,numReplacementsToDelete:r,uniqueIdentifiersUsed:a,components:i,componentInfoObjects:s,compositeAttributesObj:o,publicCaseInsensitiveAliasSubstitutions:l}){let u=await this.createReplacementForSource({component:e,sourceNum:t,numReplacementsSoFar:n,components:i,uniqueIdentifiersUsed:a,componentInfoObjects:s,compositeAttributesObj:o,publicCaseInsensitiveAliasSubstitutions:l}),c=u.propVariablesCopiedByReplacement,p=u.serializedReplacements,d={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:r,serializedReplacements:p,assignNamesOffset:n};return{numReplacements:p.length,propVariablesCopiedByReplacement:c,replacementInstruction:d}}}class Collect extends CompositeComponent{static componentType="collect";static assignNamesToReplacements=!0;static acceptTarget=!0;static acceptAnyAttribute=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.sourceAttributesToIgnore={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnore",defaultValue:[],public:!0},e.sourceAttributesToIgnoreRecursively={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnoreRecursively",defaultValue:["isResponse"],public:!0},e.componentTypes={createComponentOfType:"textList"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.link={returnDependencies:()=>({}),definition:()=>({setValue:{link:!0}})},e.targetComponent={shadowVariable:!0,returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){return{setValue:{targetComponent:e.targetComponent}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.targetName={returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"}}),definition:function({dependencyValues:e}){return null===e.targetComponent?(console.warn("No copy target"),{setValue:{targetName:""}}):{setValue:{targetName:e.targetComponent.componentName}}}},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.componentTypesToCollect={shadowVariable:!0,additionalStateVariablesDefined:[{variableName:"componentClassesToCollect",shadowVariable:!0}],returnDependencies:()=>({componentTypesAttr:{dependencyType:"attributeComponent",attributeName:"componentTypes",variableNames:["texts"]}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[],r=[];if(null!==e.componentTypesAttr)for(let a of e.componentTypesAttr.stateValues.texts){let e=t.componentTypeLowerCaseMapping[a.toLowerCase()],i=t.allComponentClasses[e];if(i)n.push(e),r.push(i);else{let e="Cannot collect component type "+a+". Component type not found.";console.warn(e)}}return{setValue:{componentTypesToCollect:n,componentClassesToCollect:r}}}},e.collectedComponents={stateVariablesDeterminingDependencies:["componentTypesToCollect","targetName","propName","componentIndex","propIndex"],additionalStateVariablesDefined:["effectivePropNameByComponent"],returnDependencies:function({stateValues:e}){if(!e.targetName)return{};let t={dependencyType:"descendant",ancestorName:e.targetName,componentTypes:e.componentTypesToCollect,useReplacementsForComposites:!0,includeNonActiveChildren:!0,recurseToMatchedChildren:!1,componentIndex:e.componentIndex};if(e.propName){let n=e.propIndex;n&&(n=[...n]),t.variableNames=[e.propName],t.variablesOptional=!0,t.propIndex=n,t.caseInsensitiveVariableMatch=!0,t.publicStateVariablesOnly=!0,t.useMappedVariableNames=!0}return{descendants:t,maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},propName:{dependencyType:"stateVariable",variableName:"propName"}}},definition:function({dependencyValues:e}){let t=e.descendants;if(t||(t=[]),null!==e.maximumNumber&&t.length>e.maximumNumber){let n=Math.max(0,Math.floor(e.maximumNumber));t=t.slice(0,n)}let n=[];for(let r of t){let t;r.stateValues&&(t=Object.keys(r.stateValues)[0]),!t&&e.propName&&(t="__prop_name_not_found"),n.push(t)}return{setValue:{collectedComponents:t,effectivePropNameByComponent:n}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({collectedComponents:{dependencyType:"stateVariable",variableName:"collectedComponents"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={returnDependencies:()=>({collectedComponents:{dependencyType:"stateVariable",variableName:"collectedComponents"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,nComponentsForSource:a,publicCaseInsensitiveAliasSubstitutions:i,flags:s}){if(!await e.stateValues.targetComponent)return{replacements:[]};let o=[],l=[],u=0,c=[];n.propVariablesCopiedByCollected=[],n.uniqueIdentifiersUsedByCollected={};let p=this.createAttributesObject(),d=await e.stateValues.collectedComponents;for(let m=0;me.componentName))}else l[m]=0,c[m]=[],n.propVariablesCopiedByCollected[m]=[];return n.numReplacementsByCollected=l,n.collectedNames=d.map((e=>e.componentName)),n.replacementNamesByCollected=c,{replacements:o}}static async createReplacementForCollected({component:e,components:t,collectedNum:n,numReplacementsSoFar:r,uniqueIdentifiersUsed:a,componentInfoObjects:i,compositeAttributesObj:s,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l,flags:u}){let c=(await e.stateValues.collectedComponents)[n],p=t[c.componentName],d=[],m=[];if(!p)return{serializedReplacements:d,propVariablesCopiedByReplacement:m};let h=e.attributes.newNamespace?.primitive,f=(await e.stateValues.effectivePropNameByComponent)[n];if(f){let n=await replacementFromProp({component:e,components:t,replacementSource:c,propName:f,uniqueIdentifiersUsed:a,compositeAttributesObj:s,componentInfoObjects:i,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l});d=n.serializedReplacements,m=n.propVariablesCopiedByReplacement}else{let t=await e.stateValues.sourceAttributesToIgnore,r=await e.stateValues.sourceAttributesToIgnoreRecursively;d=postProcessCopy({serializedComponents:[await p.serialize({sourceAttributesToIgnore:t,sourceAttributesToIgnoreRecursively:r})],componentName:e.componentName,uniqueIdentifiersUsed:a,identifierPrefix:n+"|"});for(let t of d){t.attributes||(t.attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:i,compositeAttributesObj:s,compositeCreatesNewNamespace:h,flags:u});Object.assign(t.attributes,n)}}return d=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:d,parentName:e.componentName,indOffset:r,parentCreatesNewNamespace:h,componentInfoObjects:i}).serializedComponents,{serializedReplacements:d,propVariablesCopiedByReplacement:m}}static async calculateReplacementChanges({component:e,componentChanges:t,components:n,workspace:r,componentInfoObjects:a,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o}){let l=0;for(let t=0;t0){if(!y){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:c,numberReplacementsToDelete:e};u.push(t)}y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}r.uniqueIdentifiersUsedByCollected[t]=[]}p[t]=0,d.push([]),m.push([]);continue}let f=r.collectedNames[t];if(void 0===f||l.componentName!==f||y){let l=0;void 0!==f&&(l=r.numReplacementsByCollected[t]);let h=l;y&&(h=0);let b=r.uniqueIdentifiersUsedByCollected[t]=[],v=await this.recreateReplacements({component:e,collectedNum:t,numReplacementsSoFar:c,numReplacementsToDelete:h,components:n,uniqueIdentifiersUsed:b,componentInfoObjects:a,compositeAttributesObj:g,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o});c+=v.numReplacements,p[t]=v.numReplacements,d[t]=v.propVariablesCopiedByReplacement;let N=v.replacementInstruction;if(m[t]=N.serializedReplacements.map((e=>e.componentName)),!y&&v.numReplacements!==l){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0);N.numberReplacementsToReplace=e,y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}u.push(N);continue}if(!await e.stateValues.propName){c+=r.numReplacementsByCollected[t],p[t]=r.numReplacementsByCollected[t],m[t]=r.replacementNamesByCollected[t],d[t]=[];continue}let b=r.uniqueIdentifiersUsedByCollected[t]=[],v=await this.createReplacementForCollected({component:e,collectedNum:t,components:n,numReplacementsSoFar:c,uniqueIdentifiersUsed:b,componentInfoObjects:a,compositeAttributesObj:g,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o}),N=v.propVariablesCopiedByReplacement,T=v.serializedReplacements,C=T.length;if(C!==r.numReplacementsByCollected[t]){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0),n={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:c,numberReplacementsToReplace:e,serializedReplacements:T,assignNamesOffset:c};u.push(n),y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}else for(let e=0;et!==N[e][n]))){let t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:c+e,numberReplacementsToReplace:1,serializedReplacements:[T[e]],assignNamesOffset:c+e};u.push(t)}c+=C,p[t]=C,d[t]=N,m[t]=T.map((e=>e.componentName))}return r.numReplacementsByCollected=p,r.collectedNames=h.map((e=>e.componentName)),r.propVariablesCopiedByCollected=d,r.replacementNamesByCollected=m,u}static async recreateReplacements({component:e,collectedNum:t,numReplacementsSoFar:n,numReplacementsToDelete:r,uniqueIdentifiersUsed:a,components:i,componentInfoObjects:s,compositeAttributesObj:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c}){let p=await this.createReplacementForCollected({component:e,collectedNum:t,components:i,numReplacementsSoFar:n,uniqueIdentifiersUsed:a,componentInfoObjects:s,compositeAttributesObj:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c}),d=p.propVariablesCopiedByReplacement,m=p.serializedReplacements,h={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:r,serializedReplacements:m,assignNamesOffset:n};return{numReplacements:m.length,propVariablesCopiedByReplacement:d,replacementInstruction:h}}}class Ref extends InlineComponent{static componentType="ref";static renderChildren=!0;static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.textType={createComponentOfType:"text",createStateVariable:"textType",defaultValue:"type-global",public:!0},e.uri={createPrimitiveOfType:"string",createStateVariable:"uri",defaultValue:null,public:!0,forRenderer:!0},e.page={createPrimitiveOfType:"integer",createStateVariable:"page",defaultValue:null,public:!0,forRenderer:!0},e.createButton={createComponentOfType:"boolean",createStateVariable:"createButton",defaultValue:!1,forRenderer:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){return{setValue:{targetComponent:e.targetComponent}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.targetName={forRenderer:!0,returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},uri:{dependencyType:"stateVariable",variableName:"uri"},page:{dependencyType:"stateVariable",variableName:"page"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"},targetAttribute:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:function({dependencyValues:e}){if(e.uri||e.page){if(e.targetAttribute){let t=e.targetAttribute;return"/"!==t[0]&&(t="/"+t),{setValue:{targetName:t}}}return{setValue:{targetName:""}}}return null===e.targetComponent||e.targetInactive?{setValue:{targetName:""}}:{setValue:{targetName:e.targetComponent.componentName}}}},e.cid={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"doenetId",forRenderer:!0},{variableName:"variantIndex",forRenderer:!0},{variableName:"edit",forRenderer:!0},{variableName:"draft",forRenderer:!0},{variableName:"hash",forRenderer:!0}],returnDependencies:()=>({uri:{dependencyType:"stateVariable",variableName:"uri"}}),definition:function({dependencyValues:e}){if(!e.uri||"doenet:"!==e.uri.substring(0,7).toLowerCase())return{setValue:{cid:null,doenetId:null,variantIndex:null,edit:null,draft:null,hash:null}};let t=null,n=null,r=null,a=null,i=null,s=null,o=e.uri.match(/[:&]cid=([^&^#]+)/i);return o&&(t=o[1]),o=e.uri.match(/[:&]doenetid=([^&^#]+)/i),o&&(n=o[1]),o=e.uri.match(/[:&]variant=([^&^#]+)/i),o&&(r=Number(o[1]),!Number.isInteger(r)&&r>=1&&(r=1)),o=e.uri.match(/[:&]edit=([^&^#]+)/i),o&&(i="true"===o[1].toLowerCase()),o=e.uri.match(/[:&]draft=([^&^#]+)/i),o&&(a="true"===o[1].toLowerCase()),o=e.uri.match(/(#.+)/i),o&&(s=o[1]),{setValue:{cid:t,doenetId:n,variantIndex:r,edit:i,draft:a,hash:s}}}},e.linkText={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["targetName"],returnDependencies({stateValues:e}){let t={allChildren:{dependencyType:"child",childGroups:["anything"],variableNames:["text"],variablesOptional:!0},uri:{dependencyType:"stateVariable",variableName:"uri"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"}};return e.targetName&&(t.equationTag={dependencyType:"stateVariable",componentName:e.targetName,variableName:"equationTag",variablesOptional:!0},t.title={dependencyType:"stateVariable",componentName:e.targetName,variableName:"title",variablesOptional:!0}),t},definition:function({dependencyValues:e}){let t="";if(0===e.allChildren.length)null!==e.uri?t=e.uri:e.targetInactive||(null!==e.title?t=e.title:null!==e.equationTag&&(t="("+e.equationTag+")"));else for(let n of e.allChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return t||(t="???"),{setValue:{linkText:t}}}},e}}class Coords extends MathComponent{static componentType="coords";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return delete e.createVectors,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.createVectors={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({}),definition:()=>({setValue:{createVectors:!0}})},e}}class LineSegment extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveLineSegment:this.moveLineSegment.bind(this),lineSegmentClicked:this.lineSegmentClicked.bind(this),mouseDownOnLineSegment:this.mouseDownOnLineSegment.bind(this)})}static componentType="lineSegment";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.endpointsDraggable={createComponentOfType:"boolean"},e.endpoints={createComponentOfType:"_pointListComponent"},e.showCoordsWhenDragging={createComponentOfType:"boolean",createStateVariable:"showCoordsWhenDragging",defaultValue:!0,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" line segment"}}}},e.endpointsDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({endpointsDraggableAttr:{dependencyType:"attributeComponent",attributeName:"endpointsDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.endpointsDraggableAttr?{setValue:{endpointsDraggable:e.endpointsDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{endpointsDraggable:{defaultValue:e.draggable}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({endpointsAttr:{dependencyType:"attributeComponent",attributeName:"endpoints",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.endpointsAttr){return{setValue:{nDimensions:e.endpointsAttr.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},e.endpoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"endpointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["endpointX","endpoint"],hasEssential:!0,set:convertValueToMathExpression,defaultValueByArrayKey:e=>me$3.fromAst("0,0"===e?1:0),getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("endpointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("endpoints"===t)return 1===e.length?"endpoint"+e[0]:`endpointX${e[0]}_${e[1]}`;if("endpoint"===t.slice(0,8)){let n=Number(t.slice(8));if(Number.isInteger(n)&&n>0)return`endpointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={endpointsAttr:{dependencyType:"attributeComponent",attributeName:"endpoints",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,arraySize:n}){let r={},a={};for(let n of t){let[t,i]=n.split(","),s=Number(t)+1+"_"+(Number(i)+1);null!==e[n].endpointsAttr&&e[n].endpointsAttr.stateValues["pointX"+s]?r[n]=e[n].endpointsAttr.stateValues["pointX"+s]:a[n]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={endpoints:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={endpoints:a}),i},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){let i=[];for(let r in e.endpoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);null!==t[r].endpointsAttr&&t[r].endpointsAttr.stateValues["pointX"+o]?i.push({setDependency:n[r].endpointsAttr,desiredValue:e.endpoints[r],childIndex:0,variableIndex:0}):i.push({setEssentialValue:"endpoints",value:{[r]:e.endpoints[r]}})}return{success:!0,instructions:i}}},e.length={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},endpoints:{dependencyType:"stateVariable",variableName:"endpoints"}}),definition({dependencyValues:e}){let t=0,n=e.endpoints[0],r=e.endpoints[1],a=!0;for(let i=0;ie+t*t),0));r=r.map((e=>e/o));let l=e.length.evaluate_to_constant();if(!Number.isFinite(l)||l<0)return{success:!1};let u=[],c=[],p=l/2;for(let e=0;e({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>Number.isNaN(e.nDimensions)?[0]:[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={endpoint:{dependencyType:"stateVariable",variableName:"endpoint"+(Number(n)+1)}};return{globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(Number.isNaN(e.nDimensions))return{};let r={};for(let a of n){let n=t[a].endpoint,i=[];for(let t=0;t({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"}}),definition({dependencyValues:e}){let t=e.numericalEndpoints[0][0],n=e.numericalEndpoints[0][1],r=e.numericalEndpoints[1][0],a=e.numericalEndpoints[1][1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:d>=1?{x1:r,x2:a}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e.slope={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition({dependencyValues:e}){if(2!==e.nDimensions)return{setValue:{slope:NaN}};let t=e.numericalEndpoints;return{setValue:{slope:(t[1][1]-t[0][1])/(t[1][0]-t[0][0])}}}},e}async moveLineSegment({point1coords:e,point2coords:t,transient:n,actionId:r}){if(void 0===e||void 0===t){if(!await this.stateValues.endpointsDraggable)return await this.coreFunctions.resolveAction({actionId:r})}else if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:r});let a={};return void 0!==e&&(a["0,0"]=me$3.fromAst(e[0]),a["0,1"]=me$3.fromAst(e[1])),void 0!==t&&(a["1,0"]=me$3.fromAst(t[0]),a["1,1"]=me$3.fromAst(t[1])),n?await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"endpoints",value:a}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"endpoints",value:a}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{point1:e,point2:t}}})}async lineSegmentClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnLineSegment({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Ray extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveRay:this.moveRay.bind(this),rayClicked:this.rayClicked.bind(this),mouseDownOnRay:this.mouseDownOnRay.bind(this)})}static componentType="ray";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.endpoint={createComponentOfType:"point"},e.through={createComponentOfType:"point"},e.direction={createComponentOfType:"vector"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" ray"}}}},e.directionShadow={defaultValue:null,hasEssential:!0,essentialVarName:"direction",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{directionShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"directionShadow",value:convertValueToMathExpression(e.directionShadow)}]}}},e.throughShadow={defaultValue:null,hasEssential:!0,essentialVarName:"through",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{throughShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"throughShadow",value:convertValueToMathExpression(e.throughShadow)}]}}},e.endpointShadow={defaultValue:null,hasEssential:!0,essentialVarName:"endpoint",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{endpointShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"endpointShadow",value:convertValueToMathExpression(e.endpointShadow)}]}}},e.basedOnThrough={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"},endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint"},directionAttr:{dependencyType:"attributeComponent",attributeName:"direction"}}),definition:function({dependencyValues:e}){return null!==e.endpointAttr&&null!==e.directionAttr?(null!==e.throughAttr&&console.warn("Ray is prescribed by through, endpoint, and direction. Ignoring specified through."),{setValue:{basedOnThrough:!1},checkForActualChange:{basedOnThrough:!0}}):null!==e.throughAttr?{setValue:{basedOnThrough:!0},checkForActualChange:{basedOnThrough:!0}}:{setValue:{basedOnThrough:null!==e.throughShadow},checkForActualChange:{basedOnThrough:!0}}}},e.basedOnEndpoint={returnDependencies:()=>({endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"}}),definition:function({dependencyValues:e}){return null!==e.endpointAttr?{setValue:{basedOnEndpoint:!0},checkForActualChange:{basedOnEndpoint:!0}}:{setValue:{basedOnEndpoint:null!==e.endpointShadow},checkForActualChange:{basedOnEndpoint:!0}}}},e.basedOnDirection={returnDependencies:()=>({directionAttr:{dependencyType:"attributeComponent",attributeName:"direction"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"}}),definition:function({dependencyValues:e}){return null!==e.directionAttr?{setValue:{basedOnDirection:!0},checkForActualChange:{basedOnDirection:!0}}:{setValue:{basedOnDirection:null!==e.directionShadow},checkForActualChange:{basedOnDirection:!0}}}},e.nDimDirection={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"},directionAttr:{dependencyType:"attributeComponent",attributeName:"direction",variableNames:["nDimensions"]}};return e.basedOnDirection||(e.basedOnThrough&&(t.nDimThrough={dependencyType:"stateVariable",variableName:"nDimThrough"}),e.basedOnEndpoint&&(t.nDimEndpoint={dependencyType:"stateVariable",variableName:"nDimEndpoint"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnDirection){if(null!==e.directionAttr)t=e.directionAttr.stateValues.nDimensions;else if(e.directionShadow){let n=e.directionShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnThrough?e.basedOnEndpoint?e.nDimThrough===e.nDimEndpoint?e.nDimThrough:NaN:e.nDimThrough:e.basedOnEndpoint?e.nDimEndpoint:2;return{setValue:{nDimDirection:t},checkForActualChange:{nDimDirection:!0}}}},e.nDimThrough={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"},throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nDimensions"]}};return e.basedOnThrough||(e.basedOnEndpoint&&(t.nDimEndpoint={dependencyType:"stateVariable",variableName:"nDimEndpoint"}),e.basedOnDirection&&(t.nDimDirection={dependencyType:"stateVariable",variableName:"nDimDirection"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnThrough){if(null!==e.throughAttr)t=e.throughAttr.stateValues.nDimensions;else if(e.throughShadow){let n=e.throughShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDirection?e.basedOnEndpoint?e.nDimDirection===e.nDimEndpoint?e.nDimDirection:NaN:e.nDimDirection:e.basedOnEndpoint?e.nDimEndpoint:2;return{setValue:{nDimThrough:t},checkForActualChange:{nDimThrough:!0}}}},e.nDimEndpoint={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"},endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint",variableNames:["nDimensions"]}};return e.basedOnEndpoint||(e.basedOnThrough&&(t.nDimThrough={dependencyType:"stateVariable",variableName:"nDimThrough"}),e.basedOnDirection&&(t.nDimDirection={dependencyType:"stateVariable",variableName:"nDimDirection"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnEndpoint){if(null!==e.endpointAttr)t=e.endpointAttr.stateValues.nDimensions;else if(e.endpointShadow){let n=e.endpointShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDirection?e.basedOnThrough?e.nDimDirection===e.nDimThrough?e.nDimDirection:NaN:e.nDimDirection:e.basedOnThrough?e.nDimThrough:2;return{setValue:{nDimEndpoint:t},checkForActualChange:{nDimEndpoint:!0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},nDimDirection:{dependencyType:"stateVariable",variableName:"nDimDirection"},nDimThrough:{dependencyType:"stateVariable",variableName:"nDimThrough"},nDimEndpoint:{dependencyType:"stateVariable",variableName:"nDimEndpoint"}}),definition:function({dependencyValues:e}){let t;if(e.basedOnDirection){if(e.basedOnEndpoint){if(e.nDimDirection!==e.nDimEndpoint)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}}}else if(e.basedOnThrough&&e.nDimDirection!==e.nDimThrough)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimDirection}else if(e.basedOnEndpoint){if(e.basedOnThrough&&e.nDimEndpoint!==e.nDimThrough)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimEndpoint}else t=e.basedOnThrough?e.nDimThrough:2;return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.direction={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"directionX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["directionX"],hasEssential:!0,essentialVarName:"direction2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough"],returnArraySizeDependencies:()=>({nDimDirection:{dependencyType:"stateVariable",variableName:"nDimDirection"}}),returnArraySize:({dependencyValues:e})=>[e.nDimDirection],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={directionAttr:{dependencyType:"attributeComponent",attributeName:"direction",variableNames:["x"+e]}},!t.basedOnDirection&&t.basedOnThrough&&(n[r].endpointX={dependencyType:"stateVariable",variableName:"endpointX"+e},n[r].throughX={dependencyType:"stateVariable",variableName:"throughX"+e})}return{globalDependencies:{basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;e.basedOnDirection?null!==t[i].directionAttr?r[i]=t[i].directionAttr.stateValues["x"+n]:null!==e.directionShadow&&(r[i]=e.directionShadow.get_component(Number(i))):e.basedOnThrough?r[i]=t[i].throughX.subtract(t[i].endpointX).simplify():a[i]={defaultValue:me$3.fromAst("0"===i?1:0)}}let i={};return Object.keys(r).length>0&&(i.setValue={direction:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={direction:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.direction)t.basedOnDirection?null!==n[a].directionAttr?i.push({setDependency:r[a].directionAttr,desiredValue:e.direction[a],variableIndex:0}):s=!0:t.basedOnThrough?i.push({setDependency:r[a].throughX,desiredValue:n[a].endpointX.add(e.direction[a]).simplify()}):i.push({setEssentialValue:"direction",value:{[a]:convertValueToMathExpression(e.direction[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.direction)t[Number(n)+1]=e.direction[n].tree;t.length=a[0]+1,i.push({setDependency:"directionShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.direction&&i.push({setDependency:"directionShadow",desiredValue:e.direction[0]});return{success:!0,instructions:i}}},e.through={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["throughX"],set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnThrough"],returnArraySizeDependencies:()=>({nDimThrough:{dependencyType:"stateVariable",variableName:"nDimThrough"}}),returnArraySize:({dependencyValues:e})=>[e.nDimThrough],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["x"+e]}},t.basedOnThrough||(n[r].endpointX={dependencyType:"stateVariable",variableName:"endpointX"+e},n[r].directionX={dependencyType:"stateVariable",variableName:"directionX"+e})}return{globalDependencies:{basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=Number(a)+1;e.basedOnThrough?null!==t[a].throughAttr?r[a]=t[a].throughAttr.stateValues["x"+n]:null!==e.throughShadow&&(r[a]=e.throughShadow.get_component(Number(a))):r[a]=t[a].endpointX.add(t[a].directionX).simplify()}return{setValue:{through:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.through)t.basedOnThrough?n[a].throughAttr&&null!==n[a].throughAttr?i.push({setDependency:r[a].throughAttr,desiredValue:e.through[a],variableIndex:0}):null!==t.throughShadow&&(s=!0):i.push({setDependency:r[a].directionX,desiredValue:e.through[a].subtract(n[a].endpointX).simplify()});if(s)if(a[0]>1){let t=["vector"];for(let n in e.through)t[Number(n)+1]=e.through[n].tree;t.length=a[0]+1,i.push({setDependency:"throughShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.through&&i.push({setDependency:"throughShadow",desiredValue:e.through[0]});return{success:!0,instructions:i}}},e.endpoint={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"endpointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["endpointX"],hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(0),essentialVarName:"endpoint2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnEndpoint","basedOnThrough","basedOnDirection"],returnArraySizeDependencies:()=>({nDimEndpoint:{dependencyType:"stateVariable",variableName:"nDimEndpoint"}}),returnArraySize:({dependencyValues:e})=>[e.nDimEndpoint],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint",variableNames:["x"+e]}},t.basedOnEndpoint||t.basedOnThrough&&t.basedOnDirection&&(n[r].throughX={dependencyType:"stateVariable",variableName:"throughX"+e},n[r].directionX={dependencyType:"stateVariable",variableName:"directionX"+e})}return{globalDependencies:{basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;null!==t[i].endpointAttr?r[i]=t[i].endpointAttr.stateValues["x"+n]:null!==e.endpointShadow?r[i]=e.endpointShadow.get_component(Number(i)):e.basedOnThrough&&e.basedOnDirection?r[i]=t[i].throughX.subtract(t[i].directionX).simplify():a[i]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={endpoint:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={endpoint:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.endpoint)n[a].endpointAttr&&null!==n[a].endpointAttr?i.push({setDependency:r[a].endpointAttr,desiredValue:e.endpoint[a],variableIndex:0}):null!==t.endpointShadow?s=!0:t.basedOnThrough&&t.basedOnDirection?i.push({setDependency:r[a].directionX,desiredValue:n[a].throughX.subtract(e.endpoint[a]).simplify()}):i.push({setEssentialValue:"endpoint",value:{[a]:convertValueToMathExpression(e.endpoint[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.endpoint)t[Number(n)+1]=e.endpoint[n].tree;t.length=a[0]+1,i.push({setDependency:"endpointShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.endpoint&&i.push({setDependency:"endpointShadow",desiredValue:e.endpoint[0]});return{success:!0,instructions:i}}},e.numericalEndpoint={forRenderer:!0,returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},endpoint:{dependencyType:"stateVariable",variableName:"endpoint"}}),definition({dependencyValues:e}){if(Number.isNaN(e.nDimensions))return null;let t=e.endpoint,n=[];for(let r=0;r({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},through:{dependencyType:"stateVariable",variableName:"through"}}),definition({dependencyValues:e}){if(Number.isNaN(e.nDimensions))return null;let t=e.through,n=[];for(let r=0;r({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoint:{dependencyType:"stateVariable",variableName:"numericalEndpoint"},numericalThroughpoint:{dependencyType:"stateVariable",variableName:"numericalThroughpoint"}}),definition({dependencyValues:e}){let t=e.numericalEndpoint[0],n=e.numericalEndpoint[1],r=e.numericalThroughpoint[0],a=e.numericalThroughpoint[1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e}async moveRay({endpointcoords:e,throughcoords:t,transient:n,skippable:r,sourceInformation:a,actionId:i}){let s=[];if(void 0!==e){if(await this.stateValues.basedOnThrough&&await this.stateValues.basedOnDirection){let n;if(void 0===t){let t=await this.stateValues.numericalThroughpoint;n=e.map(((e,n)=>t[n]-e))}else n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}else s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"endpoint",value:e.map((e=>me$3.fromAst(e))),sourceInformation:a});if(void 0===t&&!await this.stateValues.basedOnThrough){let t=await this.stateValues.numericalThroughpoint,n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}if(void 0!==t){if(await this.stateValues.basedOnThrough)s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"through",value:t.map((e=>me$3.fromAst(e))),sourceInformation:a});else{null==e&&(e=await this.stateValues.numericalEndpoint);let n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}if(void 0===e&&await this.stateValues.basedOnThrough&&await this.stateValues.basedOnDirection){let e=await this.stateValues.numericalEndpoint,n=t.map(((t,n)=>t-e[n]));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}return n?await this.coreFunctions.performUpdate({updateInstructions:s,transient:n,skippable:r,actionId:i}):await this.coreFunctions.performUpdate({updateInstructions:s,actionId:i,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{through:t,endpoint:e}}})}async rayClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnRay({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Polygon extends Polyline{constructor(e){super(e),Object.assign(this.actions,{movePolygon:this.movePolygon.bind(this),polygonClicked:this.polygonClicked.bind(this),mouseDownOnPolygon:this.mouseDownOnPolygon.bind(this)})}static componentType="polygon";static representsClosedPath=!0;get movePolygon(){return this.movePolyline}get polygonClicked(){return this.polylineClicked}get mouseDownOnPolygon(){return this.mouseDownOnPolyline}static createAttributesObject(){let e=super.createAttributesObject();return e.filled={createComponentOfType:"boolean",createStateVariable:"filled",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord,n&&(t+=" with "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" with "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord+" polygon",n&&(t+=" with a "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" polygon with a "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord+" polygon",{setValue:{styleDescriptionWithNoun:t}}}},e.borderStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{borderStyleDescription:t}}}},e.fillStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t;return t=e.filled?e.selectedStyle.fillColorWord:"unfilled",{setValue:{fillStyleDescription:t}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,s=[],o=i[a-1]?.[0],l=i[a-1]?.[1];for(let e=0;e=1?{x1:h,x2:f}:{x1:l+g*a*n,x2:u+g*y*o};let b=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/o,2);b0&&(p.x3=0),p}}}}},e}}class Triangle extends Polygon{static componentType="triangle";static rendererType="polygon";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=e.styleDescriptionWithNoun.definition;return e.styleDescriptionWithNoun.definition=function({dependencyValues:e}){let n=t({dependencyValues:e}).setValue.styleDescriptionWithNoun;return n=n.replaceAll("polygon","triangle"),{setValue:{styleDescriptionWithNoun:n}}},e.vertices.hasEssential=!0,e.vertices.defaultValueByArrayKey=function(e){return["0,1","1,0"].includes(e)?me$3.fromAst(1):me$3.fromAst(0)},e.vertices.returnArraySizeDependencies=()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),e.vertices.returnArraySize=function({dependencyValues:e}){return[3,e.nDimensions]},e.vertices.arrayDefinitionByKey=function({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let[t,i]=a.split(","),s=Number(t)+1+"_"+(Number(i)+1),o=e[a].vertices;null!==o&&o.stateValues["pointX"+s]?n[a]=o.stateValues["pointX"+s]:r[a]=!0}return{setValue:{vertices:n},useEssentialOrDefaultValue:{vertices:r}}},e.vertices.inverseArrayDefinitionByKey=async function({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.vertices){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);null!==t[r].vertices&&t[r].vertices.stateValues["pointX"+o]?i.push({setDependency:n[r].vertices,desiredValue:e.vertices[r],variableIndex:0}):i.push({setEssentialValue:"vertices",value:{[r]:e.vertices[r].simplify()}})}return{success:!0,instructions:i}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{nVertices:3}})},e}}class Rectangle extends Polygon{static componentType="rectangle";static rendererType="polygon";static createAttributesObject(){let e=super.createAttributesObject();return e.center={createComponentOfType:"point"},e.width={createComponentOfType:"number"},e.height={createComponentOfType:"number"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=e.styleDescriptionWithNoun.definition;return e.styleDescriptionWithNoun.definition=function({dependencyValues:e}){let n=t({dependencyValues:e}).setValue.styleDescriptionWithNoun;return n=n.replaceAll("polygon","rectangle"),{setValue:{styleDescriptionWithNoun:n}}},e.nVerticesSpecified={returnDependencies:()=>({verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.verticesAttr?{setValue:{nVerticesSpecified:e.verticesAttr.stateValues.nPoints}}:{setValue:{nVerticesSpecified:0}}}},e.essentialVertex={isArray:!0,entryPrefixes:["essentialVertexX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"}}),returnArraySize:({dependencyValues:e})=>[0===e.nVerticesSpecified?2:0],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:function({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialVertex:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.essentialVertex)t.push({setEssentialValue:"essentialVertex",value:{[n]:e.essentialVertex[n]}});return{success:!0,instructions:t}}},e.haveSpecifiedCenter={returnDependencies:()=>({centerAttr:{dependencyType:"attributeComponent",attributeName:"center"}}),definition:({dependencyValues:e})=>({setValue:{haveSpecifiedCenter:null!==e.centerAttr}})},e.specifiedCenter={isArray:!0,entryPrefixes:["specifiedCenterX"],returnArraySizeDependencies:()=>({haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.haveSpecifiedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={centerAttr:{dependencyType:"attributeComponent",attributeName:"center",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=Number(r)+1;null!==e[r].centerAttr&&(n[r]=e[r].centerAttr.stateValues["x"+t])}return{setValue:{specifiedCenter:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.specifiedCenter)t[a].centerAttr&&null!==t[a].centerAttr&&r.push({setDependency:n[a].centerAttr,desiredValue:e.specifiedCenter[a],variableIndex:0});return{success:!0,instructions:r}}},e.specifiedWidth={defaultValue:1,hasEssential:!0,essentialVarName:"width",returnDependencies:()=>({widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["value"]},nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"},haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),definition:({dependencyValues:e})=>null!==e.widthAttr?{setValue:{specifiedWidth:e.widthAttr.stateValues.value}}:(e.haveSpecifiedCenter?1:0)+e.nVerticesSpecified<=1?{useEssentialOrDefaultValue:{specifiedWidth:!0}}:{setValue:{specifiedWidth:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>null!==t.widthAttr?{success:!0,instructions:[{setDependency:"widthAttr",desiredValue:e.specifiedWidth,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"specifiedWidth",value:e.specifiedWidth}]}},e.specifiedHeight={defaultValue:1,hasEssential:!0,essentialVarName:"height",returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["value"]},nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"},haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),definition:({dependencyValues:e})=>null!==e.heightAttr?{setValue:{specifiedHeight:e.heightAttr.stateValues.value}}:(e.haveSpecifiedCenter?1:0)+e.nVerticesSpecified<=1?{useEssentialOrDefaultValue:{specifiedHeight:!0}}:{setValue:{specifiedHeight:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>null!==t.heightAttr?{success:!0,instructions:[{setDependency:"heightAttr",desiredValue:e.specifiedHeight,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"specifiedHeight",value:e.specifiedHeight}]}},e.center={public:!0,isArray:!0,entryPrefixes:["centerX"],shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"centerX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_"+e},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_"+e}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex0,a=e[r].vertex2;n[r]=t.add(a).divide(2).simplify()}return{setValue:{center:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,stateValues:r}){let a=[],i=await r.center;for(let r in e.center){let s=Number(r),o=t[r].vertex0,l=t[r].vertex2,u=e.center[s].subtract(i[s]),c=o.add(u).simplify(),p=l.add(u).simplify();a.push({setDependency:n[r].vertex0,desiredValue:c},{setDependency:n[r].vertex2,desiredValue:p})}return{success:!0,instructions:a}}},e.width={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:({})=>({vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_1"},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_1"}}),definition({dependencyValues:e}){let t=e.vertex0.evaluate_to_constant(),n=e.vertex2.evaluate_to_constant();return{setValue:{width:Math.abs(t-n)}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=t.vertex0.evaluate_to_constant(),r=t.vertex2.evaluate_to_constant(),a=(r+n)/2,i=(r-n<0?-1:1)*Math.max(0,e.width)/2;return{success:!0,instructions:[{setDependency:"vertex0",desiredValue:me$3.fromAst(a-i)},{setDependency:"vertex2",desiredValue:me$3.fromAst(a+i)}]}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:({})=>({vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_2"},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_2"}}),definition({dependencyValues:e}){let t=e.vertex0.evaluate_to_constant(),n=e.vertex2.evaluate_to_constant();return{setValue:{height:Math.abs(t-n)}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=t.vertex0.evaluate_to_constant(),r=t.vertex2.evaluate_to_constant(),a=(r+n)/2,i=(r-n<0?-1:1)*Math.max(0,e.height)/2;return{success:!0,instructions:[{setDependency:"vertex0",desiredValue:me$3.fromAst(a-i)},{setDependency:"vertex2",desiredValue:me$3.fromAst(a+i)}]}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},stateVariablesDeterminingDependencies:["nVerticesSpecified","haveSpecifiedCenter"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[4,2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"}};if(0===t.nVerticesSpecified)if(r.haveSpecifiedCenter={dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"},t.haveSpecifiedCenter)for(let t of e){let[e,r]=t.split(",");n[t]={specifiedCenter:{dependencyType:"stateVariable",variableName:"specifiedCenterX"+(Number(r)+1)}},"0"===r?n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}:n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"}}else for(let t of e){let[e,r]=t.split(",");n[t]={essentialVertex:{dependencyType:"stateVariable",variableName:"essentialVertexX"+(Number(r)+1)}},"0"===r?"1"!==e&&"2"!==e||(n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}):"2"!==e&&"3"!==e||(n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"})}else if(1===t.nVerticesSpecified)if(r.haveSpecifiedCenter={dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"},t.haveSpecifiedCenter)for(let t of e){let[e,r]=t.split(","),a="1_"+(Number(r)+1);n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}},("0"===r&&"1"===e||"2"===e||"1"===r&&"2"===e||"3"===e)&&(n[t].specifiedCenter={dependencyType:"stateVariable",variableName:"specifiedCenterX"+(Number(r)+1)})}else for(let t of e){let[e,r]=t.split(","),a="1_"+(Number(r)+1);n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}},"0"===r?"1"!==e&&"2"!==e||(n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}):"2"!==e&&"3"!==e||(n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"})}else for(let t of e){let e,[r,a]=t.split(","),i="1_"+(Number(a)+1),s="2_"+(Number(a)+1);e="0"===r?i:"2"===r?s:"1"===r?"0"===a?s:i:"0"===a?i:s,n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+e]}}}return{dependenciesByKey:n,globalDependencies:r}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,globalDependencyValues:n}){let r={};if(0===n.nVerticesSpecified)if(n.haveSpecifiedCenter)for(let n of t){let[t,a]=n.split(","),i=e[n].specifiedCenter;if("0"===a){let a=e[n].specifiedWidth;r[n]="0"===t||"3"===t?i.subtract(a/2):i.add(a/2)}else{let a=e[n].specifiedHeight;r[n]="0"===t||"1"===t?i.subtract(a/2):i.add(a/2)}}else for(let n of t){let[t,a]=n.split(","),i=e[n].essentialVertex;if("0"===a)if("0"===t||"3"===t)r[n]=i;else{let t=e[n].specifiedWidth;r[n]=i.add(t)}else if("0"===t||"1"===t)r[n]=i;else{let t=e[n].specifiedHeight;r[n]=i.add(t)}}else if(1===n.nVerticesSpecified)if(n.haveSpecifiedCenter)for(let n of t){let t,[a,i]=n.split(","),s=e[n].verticesAttr;if(t=null!==s&&1===Object.keys(s.stateValues).length?Object.values(s.stateValues)[0]:me$3.fromAst("_"),"0"===i&&("0"===a||"3"===a)||"1"===i&&("0"===a||"1"===a))r[n]=t;else{let a=e[n].specifiedCenter;r[n]=t.add(a.subtract(t).multiply(2))}}else for(let n of t){let t,[a,i]=n.split(","),s=e[n].verticesAttr;if(t=null!==s&&1===Object.keys(s.stateValues).length?Object.values(s.stateValues)[0]:me$3.fromAst("_"),"0"===i)if("0"===a||"3"===a)r[n]=t;else{let a=e[n].specifiedWidth;r[n]=t.add(a)}else if("0"===a||"1"===a)r[n]=t;else{let a=e[n].specifiedHeight;r[n]=t.add(a)}}else for(let n of t){let t=e[n].verticesAttr;null!==t&&1===Object.keys(t.stateValues).length?r[n]=Object.values(t.stateValues)[0]:r[n]=me$3.fromAst("_")}return{setValue:{vertices:r}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,globalDependencyValues:n,stateValues:r,workspace:a,initialChange:i,dependencyNamesByKey:s}){if(i&&!await r.draggable)return{success:!1};if(!a.v0){let e=await r.vertices;a.v0=[...e[0]],a.v2=[...e[2]]}let o,l,u,c,p,d;for(let t in e.vertices){let[n,r]=t.split(","),i=e.vertices[t];"0"===n?a.v0[Number(r)]=i:"2"===n?a.v2[Number(r)]=i:"1"===n?"0"===r?a.v2[Number(r)]=i:a.v0[Number(r)]=i:"0"===r?a.v0[Number(r)]=i:a.v2[Number(r)]=i,"0"===r?(o=t,"0"===n||"3"===n?u=t:p=t):(l=t,"0"===n||"1"===n?c=t:d=t)}let m=[];if(0===n.nVerticesSpecified)if(n.haveSpecifiedCenter){if(void 0!==o){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant(),t=a.v2[0].add(a.v0[0]).divide(2).simplify();m.push({setDependency:s[o].specifiedWidth,desiredValue:e},{setDependency:s[o].specifiedCenter,desiredValue:t})}if(void 0!==l){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant(),t=a.v2[1].add(a.v0[1]).divide(2).simplify();m.push({setDependency:s[l].specifiedHeight,desiredValue:e},{setDependency:s[l].specifiedCenter,desiredValue:t})}}else{if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].essentialVertex,desiredValue:e})}if(void 0!==p){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant();m.push({setDependency:s[p].specifiedWidth,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].essentialVertex,desiredValue:e})}if(void 0!==d){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant();m.push({setDependency:s[d].specifiedHeight,desiredValue:e})}}else if(1===n.nVerticesSpecified)if(n.haveSpecifiedCenter){if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==p){let e=a.v2[0].add(a.v0[0]).divide(2).simplify();m.push({setDependency:s[p].specifiedCenter,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==d){let e=a.v2[1].add(a.v0[1]).divide(2).simplify();m.push({setDependency:s[d].specifiedCenter,desiredValue:e})}}else{if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==p){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant();m.push({setDependency:s[p].specifiedWidth,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==d){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant();m.push({setDependency:s[d].specifiedHeight,desiredValue:e})}}else void 0!==u&&m.push({setDependency:s[u].verticesAttr,desiredValue:a.v0[0],variableIndex:0}),void 0!==p&&m.push({setDependency:s[p].verticesAttr,desiredValue:a.v2[0],variableIndex:0}),void 0!==c&&m.push({setDependency:s[c].verticesAttr,desiredValue:a.v0[1],variableIndex:0}),void 0!==d&&m.push({setDependency:s[d].verticesAttr,desiredValue:a.v2[1],variableIndex:0});return{success:!0,instructions:m}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{nVertices:4}})},e}async movePolygon({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){let a=[],i={};for(let t in e)i[t+",0"]=me$3.fromAst(e[t][0]),i[t+",1"]=me$3.fromAst(e[t][1]);if(a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:i,sourceInformation:n}),1===Object.keys(e).length){let t=Number(Object.keys(e)[0]),n=me$3.fromAst(e[t][0]),r=me$3.fromAst(e[t][1]),i=(t+2)%4,s=await this.stateValues.vertices,o=s[i][0],l=s[i][1];if(await this.stateValues.nVerticesSpecified<2)if(await this.stateValues.haveSpecifiedCenter){let e,i;0===t?(e=n.add(o).divide(2),i=r.add(l).divide(2)):1===t?i=r.add(l).divide(2):3===t&&(e=n.add(o).divide(2)),void 0!==e&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedCenter",value:{0:e.simplify()}}),void 0!==i&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedCenter",value:{1:i.simplify()}})}else{let e,i;0===t?(e=o.subtract(n),i=l.subtract(r)):1===t?i=l.subtract(r):3===t&&(e=o.subtract(n)),void 0!==e&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedWidth",value:e.simplify()}),void 0!==i&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedHeight",value:i.simplify()})}}return t?await this.coreFunctions.performUpdate({updateInstructions:a,transient:t,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:a,actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}}class Circle extends Curve{constructor(e){super(e),Object.assign(this.actions,{moveCircle:this.moveCircle.bind(this),circleClicked:this.circleClicked.bind(this),mouseDownOnCircle:this.mouseDownOnCircle.bind(this)})}static componentType="circle";static rendererType="circle";static representsClosedPath=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.through={createComponentOfType:"_pointListComponent"},e.center={createComponentOfType:"point"},e.radius={createComponentOfType:"math"},e.filled={createComponentOfType:"boolean",createStateVariable:"filled",defaultValue:!1,public:!0,forRenderer:!0},delete e.parMin,delete e.parMax,delete e.variable,e}static returnChildGroups(){return GraphicalComponent.returnChildGroups()}static returnStateVariableDefinitions(e){let t=GraphicalComponent.returnStateVariableDefinitions(e);return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord,n&&(t+=" with "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" with "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord+" circle",n&&(t+=" with a "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" circle with a "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord+" circle",{setValue:{styleDescriptionWithNoun:t}}}},t.borderStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{borderStyleDescription:t}}}},t.fillStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t;return t=e.filled?e.selectedStyle.fillColorWord:"unfilled",{setValue:{fillStyleDescription:t}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{curveType:"circle"}})},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMax:NaN}})},t.parMin={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMin:NaN}})},t.fs={forRenderer:!0,isArray:!0,entryPrefixes:["f"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[0],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:()=>({setValue:{fs:{}}})},t.nThroughPoints={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.throughAttr?{setValue:{nThroughPoints:e.throughAttr.stateValues.nPoints}}:{setValue:{nThroughPoints:0}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].throughAttr;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst("_")}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].throughAttr||!t[r].throughAttr.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].throughAttr,desiredValue:e.throughPoints[r],variableIndex:0})}return{success:!0,instructions:i}}},t.havePrescribedCenter={returnDependencies:()=>({centerAttr:{dependencyType:"attributeComponent",attributeName:"center"}}),definition:({dependencyValues:e})=>({setValue:{havePrescribedCenter:null!==e.centerAttr},checkForActualChange:{havePrescribedCenter:!0}})},t.prescribedCenter={isArray:!0,entryPrefixes:["prescribedCenterX"],returnArraySizeDependencies:()=>({havePrescribedCenter:{dependencyType:"stateVariable",variableName:"havePrescribedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.havePrescribedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={centerAttr:{dependencyType:"attributeComponent",attributeName:"center",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let e of n){let n=Number(e)+1;null!==t[e].centerAttr&&(r[e]=t[e].centerAttr.stateValues["x"+n],r[e]||(r[e]=me$3.fromAst("_")))}return{setValue:{prescribedCenter:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t of Object.keys(e.prescribedCenter).reverse())null!==n[t].centerAttr&&i.push({setDependency:r[t].centerAttr,desiredValue:e.prescribedCenter[t],variableIndex:0});return{success:!0,instructions:i}}},t.prescribedRadius={defaultValue:null,returnDependencies:()=>({radiusAttr:{dependencyType:"attributeComponent",attributeName:"radius",variableNames:["value"]}}),definition:function({dependencyValues:e}){return null!==e.radiusAttr?{setValue:{prescribedRadius:e.radiusAttr.stateValues.value}}:{setValue:{prescribedRadius:null}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return null!==t.radiusAttr?{success:!0,instructions:[{setDependency:"radiusAttr",desiredValue:e.prescribedRadius,childIndex:0,variableIndex:0}]}:{success:!1}}},t.havePrescribedRadius={returnDependencies:()=>({radiusAttr:{dependencyType:"attributeComponent",attributeName:"radius"}}),definition:({dependencyValues:e})=>({setValue:{havePrescribedRadius:null!==e.radiusAttr},checkForActualChange:{havePrescribedRadius:!0}})},t.numericalPrescribedRadius={returnDependencies:()=>({prescribedRadius:{dependencyType:"stateVariable",variableName:"prescribedRadius"}}),additionalStateVariablesDefined:["haveNonNumericalPrescribedRadius"],definition:function({dependencyValues:e}){let t,n=!1;return null===e.prescribedRadius?t=null:(t=e.prescribedRadius.evaluate_to_constant(),Number.isFinite(t)||(t=NaN,n=!0)),{setValue:{haveNonNumericalPrescribedRadius:n,numericalPrescribedRadius:t},checkForActualChange:{haveNonNumericalEntriesNumericalRadius:!0}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){return await n.haveNonNumericalPrescribedRadius?{success:!1}:void 0!==e.numericalPrescribedRadius?null===t.prescribedRadius?{success:!1}:{success:!0,instructions:[{setDependency:"prescribedRadius",desiredValue:me$3.fromAst(e.numericalPrescribedRadius)}]}:{success:!1}}},t.numericalPrescribedCenter={isArray:!0,entryPrefixes:["numericalPrescribedCenterX"],returnArraySizeDependencies:()=>({havePrescribedCenter:{dependencyType:"stateVariable",variableName:"havePrescribedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.havePrescribedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={prescribedCenterX:{dependencyType:"stateVariable",variableName:"prescribedCenterX"+e}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].prescribedCenterX;t?(n[r]=t.evaluate_to_constant(),Number.isFinite(n[r])||(n[r]=NaN)):n[r]=NaN}return{setValue:{numericalPrescribedCenter:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.numericalPrescribedCenter)n.push({setDependency:t[r].prescribedCenterX,desiredValue:me$3.fromAst(e.numericalPrescribedCenter[r])});return{success:!0,instructions:n}}},t.haveNonNumericalPrescribedCenter={returnDependencies:()=>({numericalPrescribedCenter:{dependencyType:"stateVariable",variableName:"numericalPrescribedCenter"}}),definition({dependencyValues:e}){let t=e.numericalPrescribedCenter.some((e=>!Number.isFinite(e)));return{setValue:{haveNonNumericalPrescribedCenter:t},checkForActualChange:{haveNonNumericalPrescribedCenter:!0}}}},t.numericalThroughPoints={returnDependencies:()=>({throughPoints:{dependencyType:"stateVariable",variableName:"throughPoints"}}),additionalStateVariablesDefined:["haveNonNumericalThroughPoints"],definition:function({dependencyValues:e}){let t=!1,n=[];for(let r of e.throughPoints){let e=[];for(let n=0;n<2;n++){let a;try{a=r[n].evaluate_to_constant()}catch(n){console.warn("Invalid point of circle"),t=!0,e=[];break}if(!Number.isFinite(a)){t=!0,e=[];break}e.push(a)}if(!(e.length>0)){n=[];break}n.push(e)}return{setValue:{haveNonNumericalThroughPoints:t,numericalThroughPoints:n},checkForActualChange:{haveNonNumericalThroughPoints:!0}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(await n.haveNonNumericalThroughPoints)return{success:!1};if(void 0!==e.numericalThroughPoints){let t={};for(let[n,r]of e.numericalThroughPoints.entries())t[n+",0"]=me$3.fromAst(r[0]),t[n+",1"]=me$3.fromAst(r[1]);return{success:!0,instructions:[{setDependency:"throughPoints",desiredValue:t}]}}return{success:!1}}},t.haveNumericalEntries={returnDependencies:()=>({haveNonNumericalPrescribedCenter:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedCenter"},haveNonNumericalPrescribedRadius:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedRadius"},haveNonNumericalThroughPoints:{dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"}}),definition:({dependencyValues:e})=>({setValue:{haveNumericalEntries:!(e.haveNonNumericalPrescribedCenter||e.haveNonNumericalPrescribedRadius||e.haveNonNumericalThroughPoints)}})},t.numericalRadiusCalculatedWithCenter={additionalStateVariablesDefined:["numericalCenterCalculatedWithRadius"],returnDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},haveNumericalEntries:{dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"}}),definition:function({dependencyValues:e}){if(e.haveNonNumericalThroughPoints){let t="Haven't implemented circle through "+e.nThroughPoints+" points";return t+=" in case where don't have numerical values.",console.warn(t),{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}}if(2===e.nThroughPoints){let{numericalCenter:t,numericalRadius:n}=circleFromTwoNumericalPoints({point1:e.numericalThroughPoints[0],point2:e.numericalThroughPoints[1]});return{setValue:{numericalCenterCalculatedWithRadius:t,numericalRadiusCalculatedWithCenter:n}}}if(3===e.nThroughPoints){let t,n,r=e.numericalThroughPoints[0][0],a=e.numericalThroughPoints[1][0],i=e.numericalThroughPoints[2][0],s=e.numericalThroughPoints[0][1],o=e.numericalThroughPoints[1][1],l=e.numericalThroughPoints[2][1];if(r===a&&s===o)if(r===i&&s===l)t=[r,s],n=0;else{let e=circleFromTwoNumericalPoints({point1:[r,s],point2:[i,l]});t=e.numericalCenter,n=e.numericalRadius}else if(r===i&&s===l||a===i&&o===l){let e=circleFromTwoNumericalPoints({point1:[r,s],point2:[a,o]});t=e.numericalCenter,n=e.numericalRadius}else{let e=r*r+s*s,u=a*a+o*o,c=i*i+l*l,p=r*(o-l)-s*(a-i)+a*l-i*o,d=e*(l-o)+u*(s-l)+c*(o-s),m=e*(a-i)+u*(i-r)+c*(r-a),h=e*(i*o-a*l)+u*(r*l-i*s)+c*(a*s-r*o);0!==p?(t=[-d/(2*p),-m/(2*p)],n=Math.sqrt((d*d+m*m-4*p*h)/(4*p*p))):(t=[NaN,NaN],n=NaN)}return{setValue:{numericalCenterCalculatedWithRadius:t,numericalRadiusCalculatedWithCenter:n}}}return e.nThroughPoints>3?(console.warn("Can't calculate circle through more than 3 points"),{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}):{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}}},t.essentialRadius={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{essentialRadius:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"essentialRadius",value:e.essentialRadius}]}}},t.numericalRadius={forRenderer:!0,stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnDependencies:function({stateValues:e}){let t={haveNonNumericalPrescribedRadius:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedRadius"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},essentialRadius:{dependencyType:"stateVariable",variableName:"essentialRadius"}};return e.havePrescribedRadius?(t.numericalPrescribedRadius={dependencyType:"stateVariable",variableName:"numericalPrescribedRadius"},e.havePrescribedCenter&&e.nThroughPoints>0&&(t.haveCenterRadiusPoints={dependencyType:"value",value:!0})):e.havePrescribedCenter?1===e.nThroughPoints&&(t.haveNonNumericalPrescribedCenter={dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedCenter"},t.numericalPrescribedCenter={dependencyType:"stateVariable",variableName:"numericalPrescribedCenter"},t.haveNonNumericalThroughPoints={dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"},t.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"}):e.nThroughPoints>1&&(t.numericalRadiusCalculatedWithCenter={dependencyType:"stateVariable",variableName:"numericalRadiusCalculatedWithCenter"},t.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"}),t},definition:function({dependencyValues:e}){if(e.haveNonNumericalPrescribedRadius||e.haveNonNumericalPrescribedCenter||e.haveNonNumericalThroughPoints)return{setValue:{numericalRadius:NaN}};if(void 0!==e.numericalPrescribedRadius)return e.haveCenterRadiusPoints?(console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{numericalRadius:NaN}}):{setValue:{numericalRadius:Math.max(0,e.numericalPrescribedRadius)}};if(void 0!==e.numericalPrescribedCenter){if(0===e.nThroughPoints){let t=e.essentialRadius;if(t instanceof me$3.class){try{t=t.evaluate_to_constant()}catch(e){}Number.isFinite(t)||(t=NaN)}return{setValue:{numericalRadius:t}}}if(1===e.nThroughPoints){let t=e.numericalThroughPoints[0];return void 0===t?{setValue:{numericalRadius:NaN}}:{setValue:{numericalRadius:Math.sqrt(Math.pow(t[0]-e.numericalPrescribedCenter[0],2)+Math.pow(t[1]-e.numericalPrescribedCenter[1],2))}}}return console.warn("Can't calculate circle with specified center through more than 1 point"),{setValue:{numericalRadius:NaN}}}if(e.nThroughPoints<2){let t=e.essentialRadius;if(t instanceof me$3.class){try{t=t.evaluate_to_constant()}catch(e){}Number.isFinite(t)||(t=NaN)}return{setValue:{numericalRadius:t}}}return{setValue:{numericalRadius:e.numericalRadiusCalculatedWithCenter}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(void 0!==t.numericalPrescribedRadius)return{success:!0,instructions:[{setDependency:"numericalPrescribedRadius",desiredValue:Math.max(0,e.numericalRadius)}]};if(void 0!==t.numericalPrescribedCenter){if(0===t.nThroughPoints)return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:Math.max(0,e.numericalRadius)}]};if(1===t.nThroughPoints){let t=Math.max(0,e.numericalRadius),r=(await n.throughAngles)[0];if(!Number.isFinite(r))return{success:!1};let a=await n.numericalCenter;return{success:!0,instructions:[{setDependency:"numericalThroughPoints",desiredValue:[[a[0]+t*Math.cos(r),a[1]+t*Math.sin(r)]]}]}}return{success:!1}}if(t.nThroughPoints<2)return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:Math.max(0,e.numericalRadius)}]};{let r=[],a=Math.max(0,e.numericalRadius);for(let e=0;e0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:function({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialCenter:t}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,stateValues:t,workspace:n}){let r=[];for(let t in e.essentialCenter)r.push({setEssentialValue:"essentialCenter",value:{[t]:e.essentialCenter[t]}});return{success:!0,instructions:r}}},t.numericalCenter={forRenderer:!0,isArray:!0,entryPrefixes:["numericalCenterX"],stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={};if(t.havePrescribedCenter){for(let t of e){let e=Number(t)+1;r[t]={numericalPrescribedCenterX:{dependencyType:"stateVariable",variableName:"numericalPrescribedCenterX"+e}}}t.havePrescribedRadius&&t.nThroughPoints>0&&(n.haveCenterRadiusPoints={dependencyType:"value",value:!0})}else{for(let t of e){let e=Number(t)+1;r[t]={essentialCenterX:{dependencyType:"stateVariable",variableName:"essentialCenterX"+e}}}n.nThroughPoints={dependencyType:"stateVariable",variableName:"nThroughPoints"},n.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"},n.haveNonNumericalThroughPoints={dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"},t.havePrescribedRadius||1==t.nThroughPoints?n.numericalRadius={dependencyType:"stateVariable",variableName:"numericalRadius"}:t.nThroughPoints>1&&(n.numericalCenterCalculatedWithRadius={dependencyType:"stateVariable",variableName:"numericalCenterCalculatedWithRadius"})}return{globalDependencies:n,dependenciesByKey:r}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(void 0!==t[a].numericalPrescribedCenterX){if(e.haveCenterRadiusPoints)return console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{numericalCenter:[NaN,NaN]}};r[a]=t[a].numericalPrescribedCenterX}if(Object.keys(r).length>0)return{setValue:{numericalCenter:r}};if(e.haveNonNumericalPrescribedRadius||e.haveNonNumericalThroughPoints)return{setValue:{numericalCenter:[NaN,NaN]}};if(void 0!==e.numericalRadius){if(0===e.nThroughPoints){for(let e of n){let n=t[e].essentialCenterX;if(n instanceof me$3.class){try{n=n.evaluate_to_constant()}catch(e){}Number.isFinite(n)||(n=NaN)}r[e]=n}return{setValue:{numericalCenter:r}}}if(1===e.nThroughPoints){if(e.numericalThroughPoints.length<1)return{setValue:{numericalCenter:[NaN,NaN]}};return{setValue:{numericalCenter:[e.numericalThroughPoints[0][0],e.numericalThroughPoints[0][1]-e.numericalRadius]}}}if(2===e.nThroughPoints){if(e.numericalThroughPoints.length<2)return{setValue:{numericalCenter:[NaN,NaN]}};let t=e.numericalRadius,n=e.numericalThroughPoints[0][0],r=e.numericalThroughPoints[1][0],a=e.numericalThroughPoints[0][1],i=e.numericalThroughPoints[1][1],s=Math.pow(n-r,2)+Math.pow(a-i,2),o=t*t;return t<0||4*o0)return{success:!0,instructions:s};if(0===t.nThroughPoints){for(let t in e.numericalCenter)s.push({setDependency:r[t].essentialCenterX,desiredValue:e.numericalCenter[t]});return{success:!0,instructions:s}}{i.desiredCenter||(i.desiredCenter={});for(let t=0;t<2;t++)void 0!==e.numericalCenter[t]?i.desiredCenter[t]=e.numericalCenter[t]:void 0===i.desiredCenter[t]&&(i.desiredCenter[t]=a.numericalCenter[t]);let n=[],r=await a.throughAngles,s=await a.numericalRadius;for(let e=0;e({haveNumericalEntries:{dependencyType:"stateVariable",variableName:"haveNumericalEntries"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"},numericalCenter:{dependencyType:"stateVariable",variableName:"numericalCenter"}}),definition:function({dependencyValues:e}){if(!(e.haveNumericalEntries&&e.nThroughPoints>0&&e.numericalRadius>0&&e.numericalCenter.every((e=>Number.isFinite(e)))))return{useEssentialOrDefaultValue:{throughAngles:!0}};let t=[];for(let n of e.numericalThroughPoints)t.push(Math.atan2(n[1]-e.numericalCenter[1],n[0]-e.numericalCenter[0]));return{setValue:{throughAngles:t},setEssentialValue:{throughAngles:t}}}},t.radius={public:!0,shadowingInstructions:{createComponentOfType:"math"},stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnDependencies:function({stateValues:e}){let t={numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},essentialRadius:{dependencyType:"stateVariable",variableName:"essentialRadius"}};return e.havePrescribedRadius?(t.prescribedRadius={dependencyType:"stateVariable",variableName:"prescribedRadius"},e.havePrescribedCenter&&e.nThroughPoints>0&&(t.haveCenterRadiusPoints={dependencyType:"value",value:!0})):e.havePrescribedCenter&&1===e.nThroughPoints&&(t.prescribedCenter={dependencyType:"stateVariable",variableName:"prescribedCenter"},t.throughPoints={dependencyType:"stateVariable",variableName:"throughPoints"}),t},definition:function({dependencyValues:e}){if(Number.isFinite(e.numericalRadius))return{setValue:{radius:me$3.fromAst(e.numericalRadius)}};if(void 0!==e.prescribedRadius)return e.haveCenterRadiusPoints?(console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{radius:me$3.fromAst("_")}}):{setValue:{radius:e.prescribedRadius}};if(void 0!==e.prescribedCenter){if(0===e.nThroughPoints){let t=e.essentialRadius;return t instanceof me$3.class||(t=Number.isFinite(t)?me$3.fromAst(t):me$3.fromAst("_")),{setValue:{radius:t}}}if(1!==e.nThroughPoints)return console.warn("Can't calculate circle with specified center through more than 1 point"),{setValue:{radius:me$3.fromAst("_")}};try{let t=e.throughPoints[0],n=t[0],r=t[1],a=e.prescribedCenter[0],i=e.prescribedCenter[1];return{setValue:{radius:n.subtract(a).pow(2).add(r.subtract(i).pow(2)).pow(.5).simplify()}}}catch(e){return console.warn("Invalid center or through points of circle"),{setValue:{radius:me$3.fromAst("_")}}}}if(e.nThroughPoints<2){let t=e.essentialRadius;return t instanceof me$3.class||(t=Number.isFinite(t)?me$3.fromAst(t):me$3.fromAst("_")),{setValue:{radius:t}}}return console.warn(`Have not implemented circle through ${e.nThroughPoints} points when non-numerical values`),{setValue:{radius:me$3.fromAst("_")}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n=e.radius.evaluate_to_constant();if(Number.isFinite(n)&&Number.isFinite(t.numericalRadius))return{success:!0,instructions:[{setDependency:"numericalRadius",desiredValue:n}]};if(void 0!==t.prescribedRadius)return{success:!0,instructions:[{setDependency:"prescribedRadius",desiredValue:e.radius}]};if(0===t.nThroughPoints){return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:e.radius}]}}return console.warn("Can't change radius of circle with non-numerical values through points"),{success:!1}}},t.diameter={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({radius:{dependencyType:"stateVariable",variableName:"radius"}}),definition:({dependencyValues:e})=>({setValue:{diameter:e.radius.multiply(2).simplify()}}),inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return{success:!0,instructions:[{setDependency:"radius",desiredValue:e.diameter.divide(2).simplify()}]}}},t.center={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"centerX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["centerX"],stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={};if(t.havePrescribedCenter){n.havePrescribedCenter={dependencyType:"value",value:!0};for(let t of e){let e=Number(t)+1;r[t]={numericalCenterX:{dependencyType:"stateVariable",variableName:"numericalCenterX"+e},prescribedCenterX:{dependencyType:"stateVariable",variableName:"prescribedCenterX"+e}}}t.havePrescribedRadius&&t.nThroughPoints>0&&(n.haveCenterRadiusPoints={dependencyType:"value",value:!0})}else{for(let t of e){let e=Number(t)+1;r[t]={essentialCenterX:{dependencyType:"stateVariable",variableName:"essentialCenterX"+e}}}n.numericalCenter={dependencyType:"stateVariable",variableName:"numericalCenter"},n.nThroughPoints={dependencyType:"stateVariable",variableName:"nThroughPoints"},n.throughPoints={dependencyType:"stateVariable",variableName:"throughPoints"},t.havePrescribedRadius?n.radius={dependencyType:"stateVariable",variableName:"prescribedRadius"}:1==t.nThroughPoints&&(n.radius={dependencyType:"stateVariable",variableName:"radius"})}return{dependenciesByKey:r,globalDependencies:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(e.havePrescribedCenter){if(e.haveCenterRadiusPoints)return console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}};let r={};for(let e of n)Number.isFinite(t[e].numericalCenterX)?r[e]=me$3.fromAst(t[e].numericalCenterX):r[e]=t[e].prescribedCenterX;return{setValue:{center:r}}}if(e.numericalCenter.every((e=>Number.isFinite(e))))return{setValue:{center:e.numericalCenter.map((e=>me$3.fromAst(e)))}};if(void 0!==e.radius){if(0===e.nThroughPoints){let e={};for(let r of n){let n=t[r].essentialCenterX;n instanceof me$3.class||(n=Number.isFinite(n)?me$3.fromAst(n):me$3.fromAst("_")),e[r]=n}return{setValue:{center:e}}}if(1===e.nThroughPoints){let t;try{t=[e.throughPoints[0][0],e.throughPoints[0][1].subtract(e.radius).simplify()]}catch(e){t=[me$3.fromAst("_"),me$3.fromAst("_")]}return{setValue:{center:t}}}return console.warn("Can't create circle through more than one point with given radius when don't have numerical values"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}}}if(0===e.nThroughPoints){let e={};for(let r of n){let n=t[r].essentialCenterX;n instanceof me$3.class||(n=Number.isFinite(n)?me$3.fromAst(n):me$3.fromAst("_")),e[r]=n}return{setValue:{center:e}}}return console.warn("Can't create circle through more than one point when don't have numerical values"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,stateValues:n,dependencyNamesByKey:r,workspace:a}){if(t.havePrescribedCenter){let t=[];for(let n in e.center)t.push({setDependency:r[n].prescribedCenterX,desiredValue:e.center[n],arrayKey:n});return{success:!0,instructions:t}}a.desiredCenter||(a.desiredCenter={});for(let t=0;t<2;t++)void 0!==e.center[t]?a.desiredCenter[t]=e.center[t]:void 0===a.desiredCenter[t]&&(a.desiredCenter[t]=(await n.center)[t]);let i=[],s=!0;for(let e=0;e<2;e++){let t=a.desiredCenter[e].evaluate_to_constant();if(!Number.isFinite(t)){s=!1;break}i.push(t)}if(s&&t.numericalCenter.every((e=>Number.isFinite(e))))return{success:!0,instructions:[{setDependency:"numericalCenter",desiredValue:i}]};if(0===t.nThroughPoints){let t=[];for(let n in e.center)t.push({setDependency:r[n].essentialCenterX,desiredValue:e.center[n],arrayKey:n});return{success:!0,instructions:t}}return console.warn("Haven't implemented changing center of circle through points with non numerical values"),{success:!1}}},t.nearestPoint={returnDependencies:()=>({numericalCenter:{dependencyType:"stateVariable",variableName:"numericalCenter"},numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"}}),definition({dependencyValues:e}){let t=e.numericalRadius,n=e.numericalCenter[0],r=e.numericalCenter[1];return{setValue:{nearestPoint:function({variables:e,scales:a}){let i=e.x1?.evaluate_to_constant(),s=e.x2?.evaluate_to_constant();if(!Number.isFinite(i)||!Number.isFinite(s))return{};if(!(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(t)))return{};let o=Math.atan2(s-r,i-n),l={x1:n+t*Math.cos(o),x2:r+t*Math.sin(o)};return void 0!==e.x3&&(l.x3=0),l}}}}},t}async moveCircle({center:e,radius:t,throughAngles:n,transient:r,actionId:a}){let i=[],s=await this.stateValues.nThroughPoints,o=await this.stateValues.numericalPrescribedCenter;if((s<=1||null!==o)&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"numericalCenter",value:e}),s>=1){let r=[];void 0===n&&(n=await this.stateValues.throughAngles),void 0===t&&(t=await this.stateValues.numericalRadius);for(let a=0;a({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" parabola"}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{curveType:"function"}})},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMax:1/0}})},t.parMin={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMin:-1/0}})},t.aShadow={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{aShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"aShadow",value:e.aShadow}]}}},t.nThroughPoints={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null===e.throughAttr?{setValue:{nThroughPoints:0}}:{setValue:{nThroughPoints:e.throughAttr.stateValues.nPoints}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].throughAttr;if(null!==s&&s.stateValues["pointX"+i]){let e=s.stateValues["pointX"+i].evaluate_to_constant();Number.isFinite(e)?n[r]=me$3.fromAst(e):n[r]=me$3.fromAst("_")}else n[r]=me$3.fromAst("_")}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].throughAttr||!t[r].throughAttr.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].throughAttr,desiredValue:e.throughPoints[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:i}}},t.numericalThroughPoints={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={throughPoint:{dependencyType:"stateVariable",variableName:"throughPoint"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].throughPoint.map((e=>e.tree));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalThroughPoints:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.numericalThroughPoints){if(!t[a].throughPoint)return{success:!1};r.push({setDependency:n[a].throughPoint,desiredValue:e.numericalThroughPoints[a].map((e=>me$3.fromAst(e)))})}return{success:!0,instructions:r}}},t.numericalPrescribedVertex={returnDependencies:()=>({prescribedVertex:{dependencyType:"stateVariable",variableName:"prescribedVertex"}}),definition({dependencyValues:e}){if(null===e.prescribedVertex)return{setValue:{numericalPrescribedVertex:null}};let t,n;try{t=e.prescribedVertex.get_component(0).evaluate_to_constant(),n=e.prescribedVertex.get_component(1).evaluate_to_constant(),Number.isFinite(t)&&Number.isFinite(n)||(t=NaN,n=NaN)}catch(e){t=NaN,n=NaN}return{setValue:{numericalPrescribedVertex:[t,n]}}}},t.pointsAreNumerical={returnDependencies:()=>({numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalPrescribedVertex:{dependencyType:"stateVariable",variableName:"numericalPrescribedVertex"}}),definition:({dependencyValues:e})=>({setValue:{pointsAreNumerical:e.numericalThroughPoints.every((e=>Number.isFinite(e[0])))&&(!e.numericalPrescribedVertex||Number.isFinite(e.numericalPrescribedVertex[0]))},checkForActualChange:{pointsAreNumerical:!0}})},t.a={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"b",public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0},{variableName:"c",public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0},"realValued"],returnDependencies:()=>({numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalPrescribedVertex:{dependencyType:"stateVariable",variableName:"numericalPrescribedVertex"},pointsAreNumerical:{dependencyType:"stateVariable",variableName:"pointsAreNumerical"},aShadow:{dependencyType:"stateVariable",variableName:"aShadow"}}),definition:function({dependencyValues:e,componentName:t}){if(!e.pointsAreNumerical)return{setValue:{a:NaN,b:NaN,c:NaN,realValued:!1}};let n,r,a,i=!0;if(e.numericalPrescribedVertex){if(0===e.numericalThroughPoints.length){let t=e.numericalPrescribedVertex,i=t[0],s=t[1];return n=e.aShadow,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}{let t=e.numericalPrescribedVertex,i=t[0],s=t[1],o=e.numericalThroughPoints[0],l=o[0];return n=(o[1]-s)/(l-i)**2,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}}if(0===e.numericalThroughPoints.length)return{setValue:{a:e.aShadow,realValued:!0},useEssentialOrDefaultValue:{b:!0,c:!0}};if(1===e.numericalThroughPoints.length){let t=e.numericalThroughPoints[0],i=t[0],s=t[1];return n=e.aShadow,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}if(2===e.numericalThroughPoints.length){n=e.aShadow;let t=e.numericalThroughPoints[0],s=t[0],o=t[1],l=s*s,u=e.numericalThroughPoints[1],c=u[0],p=u[1],d=c*c;return s===c?o==p?(r=-2*n*s,a=n*l+o):(i=!1,n=NaN,r=NaN,a=NaN):(r=(o-p-n*(l-d))/(s-c),a=o-n*l-r*s),{setValue:{a:n,b:r,c:a,realValued:i}}}if(3===e.numericalThroughPoints.length){let t=e.numericalThroughPoints[0],s=t[0],o=t[1],l=s*s,u=e.numericalThroughPoints[1],c=u[0],p=u[1],d=c*c,m=e.numericalThroughPoints[2],h=m[0],f=m[1],y=h*h,g=l-y,b=d-y,v=s-h,N=c-h,T=o-f,C=p-f,A=g*N-b*v;if(0===A){let t,u,d,m=!1;s===c?o===p?s===h?o==f?t=1:m=!0:(t=2,u=h,d=f):m=!0:s===h?o===f?(t=2,u=c,d=p):m=!0:c===h&&p===f?(t=2,u=c,d=p):m=!0,m?(i=!1,n=NaN,r=NaN,a=NaN):1===t?(n=e.aShadow,r=-2*n*s,a=n*s*s+o):(n=e.aShadow,r=(o-d-n*(l-u*u))/(s-u),a=o-n*l-r*s)}else n=(T*N-C*v)/A,r=(C*g-T*b)/A,a=o-r*s-n*l;return{setValue:{a:n,b:r,c:a,realValued:i}}}return console.warn("Haven't implemented parabola through more than 3 points"),{setValue:{a:NaN,b:NaN,c:NaN,realValued:!1}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r}){if(!t.pointsAreNumerical)return{success:!1};let a={},i=function(e){if(Number.isFinite(e))return{success:!0,value:e};if(e instanceof me$3.class){let t=e.evaluate_to_constant();if(Number.isFinite(t))return{success:!0,value:t}}return{success:!1}};if(void 0!==e.a){let t=i(e.a);if(!t.success)return{success:!1};a.a=t.value}if(void 0!==e.b){let t=i(e.b);if(!t.success)return{success:!1};a.b=t.value}if(void 0!==e.c){let t=i(e.c);if(!t.success)return{success:!1};a.c=t.value}Object.assign(r,a);let s=async function(e){return void 0!==r[e]?r[e]:await n[e]};if(0===t.numericalThroughPoints.length){let e=[];return void 0!==a.a&&e.push({setDependency:"aShadow",desiredValue:a.a}),void 0!==a.b&&e.push({setEssentialValue:"b",value:a.b}),void 0!==a.c&&e.push({setEssentialValue:"c",value:a.c}),{success:!0,instructions:e}}if(1===t.numericalThroughPoints.length){let e=await s("a"),t=await s("b"),n=await s("c"),r=[{setDependency:"numericalThroughPoints",desiredValue:[[-t/(2*e),n-t*t/(4*e)]]}];return void 0!==a.a&&r.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:r}}if(2===t.numericalThroughPoints.length){let e=await s("a"),n=await s("b"),r=await s("c"),i=t.numericalThroughPoints[0][0],o=t.numericalThroughPoints[1][0];if(i===o){i=-n/(2*e);let t=r-n*n/(4*e),s=[{setDependency:"numericalThroughPoints",desiredValue:[[i,t],[i,t]]}];return void 0!==a.a&&s.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:s}}{let t=[{setDependency:"numericalThroughPoints",desiredValue:[[i,e*i*i+n*i+r],[o,e*o*o+n*o+r]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}if(3===t.numericalThroughPoints.length){let e,n=await s("a"),r=await s("b"),i=await s("c"),o=t.numericalThroughPoints[0][0],l=t.numericalThroughPoints[1][0],u=t.numericalThroughPoints[2][0],c=3;if(o===l?o===u?c=1:(c=2,e=3):o===u?(c=2,e=2):l===u&&(c=2,e=1),3===c){let e=[{setDependency:"numericalThroughPoints",desiredValue:[[o,n*o*o+r*o+i],[l,n*l*l+r*l+i],[u,n*u*u+r*u+i]]}];return void 0!==a.a&&e.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:e}}if(2===c){if(1===e){let e=n*l*l+r*l+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,n*o*o+r*o+i],[l,e],[l,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}if(2===e){let e=n*o*o+r*o+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[l,n*l*l+r*l+i],[o,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}{let e=n*o*o+r*o+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[o,e],[u,n*u*u+r*u+i]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}{o=-r/(2*n);let e=i-r*r/(4*n),t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[o,e],[o,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}return{success:!1}}},t.vertex={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["vertexX"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({globalDependencies:{a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"},realValued:{dependencyType:"stateVariable",variableName:"realValued"}}}),arrayDefinitionByKey:function({globalDependencyValues:e}){let t={};return e.realValued&&0!==e.a?(t[0]=me$3.fromAst(-e.b/(2*e.a)),t[1]=me$3.fromAst(e.c-e.b**2/(4*e.a))):(t[0]=me$3.fromAst("_"),t[1]=me$3.fromAst("_")),{setValue:{vertex:t}}},inverseArrayDefinitionByKey:async function({desiredStateVariableValues:e,globalDependencyValues:t,workspace:n,stateValues:r}){let a,i;if(a="0"in e.vertex?e.vertex[0].evaluate_to_constant():void 0!==n.x?n.x:(await r.vertex)[0].tree,!Number.isFinite(a))return{success:!1};if(n.x=a,i="1"in e.vertex?e.vertex[1].evaluate_to_constant():void 0!==n.y?n.y:(await r.vertex)[1].tree,!Number.isFinite(i))return{success:!1};n.y=i;let s=t.a;return{success:!0,instructions:[{setDependency:"b",desiredValue:-2*s*a,additionalDependencyValues:{c:i+s*a*a}}]}}},t.equation={public:!0,shadowingInstructions:{createComponentOfType:"math"},additionalProperties:{simplify:"numberspreserveorder",displaysmallaszero:!0},returnDependencies:()=>({a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}),definition:function({dependencyValues:e}){let t=["=","y",["+",["*",e.a,["^","x",2]],["*",e.b,"x"],e.c]];return{setValue:{equation:me$3.fromAst(t).evaluate_numbers({skip_ordering:!0})}}}},t.fs={forRenderer:!0,isArray:!0,entryPrefixes:["f"],additionalStateVariablesDefined:[{variableName:"fDefinitions",isArray:!0,forRenderer:!0}],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[1],returnArrayDependenciesByKey:()=>({globalDependencies:{a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>({setValue:{fs:[function(t){return e.a*t*t+e.b*t+e.c}],fDefinitions:[{functionType:"formula",formula:["+",["*",e.a,"x","x"],["*",e.b,"x"],e.c],variables:["x"],nInputs:1,nOutputs:1,domain:null}]}})},t.f={isAlias:!0,targetVariableName:"f1"},t.nearestPoint={returnDependencies:()=>({f:{dependencyType:"stateVariable",variableName:"f"},a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}),definition({dependencyValues:e,componentName:t}){let n=!(Number.isFinite(e.a)&&Number.isFinite(e.b)&&Number.isFinite(e.c));return{setValue:{nearestPoint:function({variables:t,scales:r}){if(n)return{};let a=r[0],i=r[1],s=t.x1?.evaluate_to_constant(),o=t.x2?.evaluate_to_constant();if(!Number.isFinite(s)||!Number.isFinite(o))return{};s/=a,o/=i;let l=e.a*a*a/i,u=e.b*a/i,c=e.c/i;if(0===l){let e=u*u+1,n={};return n.x1=(s+u*o-u*c)/e*a,n.x2=(u*(s+u*o)+c)/e*i,void 0!==t.x3&&(n.x3=0),n}let p=c-o,d=2*l**2,m=cardano(3*l*u/d,(2*l*p+u**2+1)/d,(u*p-s)/d,1e-14),h=m[0],f=e.f(h*a)/i,y=(s-h)**2+(o-f)**2;for(let t of m.slice(1)){let n=t,r=e.f(n*a)/i,l=(s-n)**2+(o-r)**2;l0){const t=Math.sqrt(s/108),n=2*Math.sqrt(Math.cbrt(i*i/4+s/108)),r=Math.atan2(t,-i/2);return[Math.cos(r/3),Math.cos(r/3+2*Math.PI/3),Math.cos(r/3-2*Math.PI/3)].sort(((e,t)=>e-t)).map((t=>n*t-e/3))}const o=Math.sqrt(-s/108);return[Math.cbrt(-i/2+o)+Math.cbrt(-i/2-o)-e/3]}class BezierControls extends InlineComponent{static componentType="bezierControls";static rendererType="containerInline";static createAttributesObject(){let e=super.createAttributesObject();return e.alwaysVisible={createComponentOfType:"boolean",createStateVariable:"alwaysVisible",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"controlVectors",children:[{componentType:"vector",children:e}]}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"controlVectors",componentTypes:["controlVectors"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nControls={returnDependencies:()=>({nParentPoints:{dependencyType:"parentStateVariable",variableName:"nThroughPoints",skipComponentNames:!0}}),definition({dependencyValues:e}){let t=e.nParentPoints;return Number.isInteger(t)&&t>=0||(t=0),{setValue:{nControls:t}}}},e.pointIndMap={returnDependencies:()=>({controlChildren:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["pointNumber"]}}),definition:function({dependencyValues:e}){let t=[],n=-1;for(let[r,a]of e.controlChildren.entries()){let e=a.stateValues.pointNumber;Number.isFinite(e)?n=Math.round(e)-1:n+=1,t[n]=r}return{setValue:{pointIndMap:t}}}},e.directions={isArray:!0,entryPrefixes:["direction"],hasEssential:!0,defaultValueByArrayKey:()=>"none",stateVariablesDeterminingDependencies:["pointIndMap"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"}}),returnArraySize:({dependencyValues:e})=>[e.nControls],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.pointIndMap[r];void 0!==e&&(n[r]={controlChild:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["direction"],childIndices:[e]}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=e[a].controlChild;t&&1===t.length?n[a]=t[0].stateValues.direction:r[a]=!0}return{setValue:{directions:n},useEssentialOrDefaultValue:{directions:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.directions){let s=n[i].controlChild;s&&1===s.length?r.push({setDependency:t[i].controlChild,desiredValue:e.directions[i],childIndex:0,variableIndex:0}):a[i]=e.directions[i]}return Object.keys(a).length>0&&r.push({setEssentialValue:"directions",value:a}),{success:!0,instructions:r}}},e.hiddenControls={isArray:!0,entryPrefixes:["hiddenControl"],hasEssential:!0,defaultValueByArrayKey:()=>!1,stateVariablesDeterminingDependencies:["pointIndMap"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"}}),returnArraySize:({dependencyValues:e})=>[e.nControls],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.pointIndMap[r];void 0!==e&&(n[r]={controlChild:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["hide"],childIndices:[e]}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=e[a].controlChild;t&&1===t.length?n[a]=t[0].stateValues.hide:r[a]=!0}return{setValue:{hiddenControls:n},useEssentialOrDefaultValue:{hiddenControls:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.hiddenControls){let s=n[i].controlChild;s&&1===s.length?r.push({setDependency:t[i].controlChild,desiredValue:e.hiddenControls[i],childIndex:0,variableIndex:0}):a[i]=e.hiddenControls[i]}return Object.keys(a).length>0&&r.push({setEssentialValue:"hiddenControls",value:a}),{success:!0,instructions:r}}},e.nDimensions={returnDependencies:()=>({nParentDimensions:{dependencyType:"parentStateVariable",variableName:"nDimensions"}}),definition:function({dependencyValues:e}){let t=e.nParentDimensions;return Number.isInteger(t)&&t>=0||(t=0),{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.essentialSymmetricControls={isArray:!0,entryPrefixes:["essentialSymmetricControl"],nDimensions:2,hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(1),returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nControls,e.nDimensions],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)n.split(",").map((e=>Number(e))),t[n]=!0;return{useEssentialOrDefaultValue:{essentialSymmetricControls:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[],n={};for(let t in e.essentialSymmetricControls)n[t]=e.essentialSymmetricControls[t];return Object.keys(n).length>0&&t.push({setEssentialValue:"essentialSymmetricControls",value:n}),{success:!0,instructions:t}}},e.controls={isArray:!0,entryPrefixes:["control"],nDimensions:3,hasEssential:!0,shadowVariable:!0,defaultValueByArrayKey:()=>me$3.fromAst(1),stateVariablesDeterminingDependencies:["pointIndMap","directions"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nControls,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=r.split(",").map((e=>Number(e))),a=e.map((e=>e+1));n[r]={direction:{dependencyType:"stateVariable",variableName:"direction"+a[0]}};let i=t.directions[e[0]];if("none"!==i&&(0===e[1]||1===e[1])){let s=t.pointIndMap[e[0]];void 0!==s&&("symmetric"===i||"previous"===i&&0===e[1]||"next"===i&&1===e[1]?n[r].controlChild={dependencyType:"child",childGroups:["controlVectors"],variableNames:["vectorX1_"+a[2]],childIndices:[s]}:"both"===i&&(n[r].controlChild={dependencyType:"child",childGroups:["controlVectors"],variableNames:["vectorX"+a[1]+"_"+a[2]],childIndices:[s]})),"symmetric"===i&&(n[r].essentialSymmetricControl={dependencyType:"stateVariable",variableName:"essentialSymmetricControl"+a[0]+"_"+a[2]})}}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,componentName:n}){let r={},a={};for(let n of t){let t=n.split(",").map((e=>Number(e))),i=t.map((e=>e+1)),s=e[n].direction;if(0===t[1])if("none"===s||"next"===s)r[n]=null;else{let t=e[n].controlChild,o=!0;if(t&&1===t.length){let e=t[0].stateValues["vectorX1_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]=me$3.fromAst(e))}o&&("symmetric"===s?r[n]=e[n].essentialSymmetricControl:a[n]=!0)}else if(1===t[1])if("none"===s||"previous"===s)r[n]=null;else{let t=e[n].controlChild,o=!0;if(t&&1===t.length)if("both"===s){let e=t[0].stateValues["vectorX2_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]=me$3.fromAst(e))}else{let e=t[0].stateValues["vectorX1_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]="symmetric"===s?me$3.fromAst(-e):me$3.fromAst(e))}o&&("symmetric"===s?e[n].essentialSymmetricControl&&(r[n]=me$3.fromAst(-e[n].essentialSymmetricControl.tree)):a[n]=!0)}}return{setValue:{controls:r},useEssentialOrDefaultValue:{controls:a}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.controls){let s=i.split(",").map((e=>Number(e))),o=s.map((e=>e+1)),l=n[i].direction;if(l)if(0===s[1]){if("none"!==l&&"next"!==l){let s=n[i].controlChild,u=!0;if(s&&1===s.length){s[0].stateValues["vectorX1_"+o[2]]&&(u=!1,r.push({setDependency:t[i].controlChild,desiredValue:e.controls[i],childIndex:0,variableIndex:0}))}if(u){let n=e.controls[i].evaluate_to_constant();Number.isFinite(n)||(n=NaN),n=me$3.fromAst(n),"symmetric"===l?r.push({setDependency:t[i].essentialSymmetricControl,desiredValue:n}):a[i]=n}}}else if(1===s[1]&&"none"!==l&&"previous"!==l){let s,u=n[i].controlChild,c=!0;if(u&&1===u.length)if("both"===l){u[0].stateValues["vectorX2_"+o[2]]&&(c=!1)}else{u[0].stateValues["vectorX1_"+o[2]]&&(c=!1)}s="symmetric"===l?me$3.fromAst(["-",e.controls[i].tree]):e.controls[i],c?(s=s.evaluate_to_constant(),Number.isFinite(s)||(s=NaN),s=me$3.fromAst(s),"symmetric"===l?r.push({setDependency:t[i].essentialSymmetricControl,desiredValue:s}):a[i]=s):r.push({setDependency:t[i].controlChild,desiredValue:s,childIndex:0,variableIndex:0})}}return Object.keys(a).length>0&&r.push({setEssentialValue:"controls",value:a}),{success:!0,instructions:r}}},e}}class VectorListComponent extends BaseComponent{static componentType="_vectorListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"vector",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"vectors",componentTypes:["vector"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nVectors={returnDependencies:()=>({vectorChildren:{dependencyType:"child",childGroups:["vectors"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{nVectors:e.vectorChildren.length},checkForActualChange:{nVectors:!0}})},e.nDimensions={returnDependencies:()=>({vectorChildren:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"],skipPlaceholders:!0}}),definition:function({dependencyValues:e}){let t;if(0===e.vectorChildren.length)t=2;else{t=1;for(let n of e.vectorChildren)Number.isFinite(n.stateValues.nDimensions)&&(t=Math.max(t,n.stateValues.nDimensions))}return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.vectors={isArray:!0,nDimensions:2,entryPrefixes:["vectorX","vector"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vectors"===t)return 1===e.length?"vector"+e[0]:`vectorX${e[0]}_${e[1]}`;if("vector"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vectorX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nVectors:{dependencyType:"stateVariable",variableName:"nVectors"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nVectors,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]={vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+(Number(r)+1)],childIndices:[e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",")[1],a=e[r].vectorChild[0];a&&(n[r]=a.stateValues["x"+(Number(t)+1)])}return{setValue:{vectors:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.vectors)n.push({setDependency:t[r].vectorChild,desiredValue:e.vectors[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}class ControlVectors extends VectorListComponent{static componentType="controlVectors";static createAttributesObject(){let e=super.createAttributesObject();return e.direction={createComponentOfType:"text",createStateVariable:"direction",defaultValue:"symmetric",public:!0,toLowerCase:!0,validValues:["symmetric","previous","next","both","none"]},e.pointNumber={createComponentOfType:"number",createStateVariable:"pointNumber",defaultValue:null,public:!0},e}}class PointListComponent extends BaseComponent{static componentType="_pointListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"point",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPoints={returnDependencies:()=>({pointChildren:{dependencyType:"child",childGroups:["points"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nPoints:e.pointChildren.length},checkForActualChange:{nPoints:!0}}}},e.nDimensions={returnDependencies:()=>({pointChildren:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"],skipPlaceholders:!0}}),definition:function({dependencyValues:e}){let t;if(0===e.pointChildren.length)t=2;else{t=1;for(let n of e.pointChildren)Number.isFinite(n.stateValues.nDimensions)&&(t=Math.max(t,n.stateValues.nDimensions))}return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.points={isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("points"===t)return 1===e.length?"point"+e[0]:`pointX${e[0]}_${e[1]}`;if("point"===t.slice(0,5)){let n=Number(t.slice(5));if(Number.isInteger(n)&&n>0)return`pointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nPoints:{dependencyType:"stateVariable",variableName:"nPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nPoints,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]={pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+(Number(r)+1)],childIndices:[e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",")[1],a=e[r].pointChild[0];a&&(n[r]=a.stateValues["x"+(Number(t)+1)])}return{setValue:{points:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.points)n.push({setDependency:t[r].pointChild,desiredValue:e.points[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}class IntervalListComponent extends BaseComponent{static componentType="_intervalListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoIntervalPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"interval",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"intervals",componentTypes:["interval"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nIntervals={returnDependencies:()=>({intervalChildren:{dependencyType:"child",childGroups:["intervals"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nIntervals:e.intervalChildren.length},checkForActualChange:{nIntervals:!0}}}},e.intervals={isArray:!0,nDimensions:1,entryPrefixes:["interval"],returnArraySizeDependencies:()=>({nIntervals:{dependencyType:"stateVariable",variableName:"nIntervals"}}),returnArraySize:({dependencyValues:e})=>[e.nIntervals],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={intervalChild:{dependencyType:"child",childGroups:["intervals"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].intervalChild[0];t&&(n[r]=t.stateValues.value)}return{setValue:{intervals:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.intervals)n.push({setDependency:t[r].intervalChild,desiredValue:e.intervals[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}function breakEmbeddedStringsIntoIntervalPieces({componentList:e}){let t=0,n=[],r=[];for(let a of e){if("string"!=typeof a){if(0===t)return{success:!1};r.push(a);continue}let e=a.trim(),i=0;for(let a=0;ai){let t=a+1,n=e.substring(i,t).trim();n.length>0&&r.push(n)}n.push(r),r=[],i=a+1}t--}else if(0===t&&!s.match(/\s/))return{success:!1}}if(e.length>i){let t=e.substring(i,e.length).trim();r.push(t)}}return 0!==t||r.length>0?{success:!1}:{success:!0,pieces:n}}class LineListComponent extends BaseComponent{static componentType="_lineListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:"line",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"lines",componentTypes:["line"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nLines={returnDependencies:()=>({lineChildren:{dependencyType:"child",childGroups:["lines"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nLines:e.lineChildren.length},checkForActualChange:{nLines:!0}}}},e.lineNames={isArray:!0,entryPrefixes:["lineName"],returnArraySizeDependencies:()=>({nLines:{dependencyType:"stateVariable",variableName:"nLines"}}),returnArraySize:({dependencyValues:e})=>[e.nLines],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={lineChild:{dependencyType:"child",childGroups:["lines"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].lineChild[0];t&&(n[r]=t.componentName)}return{setValue:{lineNames:n}}}},e}}class AngleListComponent extends BaseComponent{static componentType="_angleListComponent";static createAttributesObject(){let e=super.createAttributesObject();return e.hide={default:!0},e}static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"AtLeastZeroAngles",componentType:"angle",comparison:"atLeast",number:0}),r=breakStringsAndOthersIntoComponentsByStringCommas(),a=t.newLeaf({name:"AtLeastOneString",componentType:"string",comparison:"atLeast",number:1}),i=t.newLeaf({name:"AtLeastOneMath",componentType:"math",comparison:"atLeast",number:1}),s=t.newOperator({name:"StringsAndMaths",operator:"or",propositions:[a,i],requireConsecutive:!0,isSugar:!0,replacementFunction:r});return t.newOperator({name:"AnglesXorSugar",operator:"xor",propositions:[n,s],setAsBase:!0}),t}updateState(e={}){if(e.init&&(this._state.angles={trackChanges:!0}),super.updateState(e),!this.childLogicSatisfied)return this.unresolvedState.angles=!0,void(this.unresolvedState.nAngles=!0);if(this.currentTracker.trackChanges.childrenChanged(this.componentName)){delete this.unresolvedState.angles,delete this.unresolvedState.nAngles;let e=this.childLogic.returnMatches("AtLeastZeroAngles");this.state.nAngles=e.length,this.state.angles=e.map((e=>this.activeChildren[e]))}}initializeRenderer(){void 0===this.renderer&&(this.renderer=new this.availableRenderers.container({key:this.componentName}))}updateChildrenWhoRender(){this.childrenWhoRender=this.state.angles.map((e=>e.componentName))}}class Vector extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveVector:this.moveVector.bind(this),vectorClicked:this.vectorClicked.bind(this),mouseDownOnVector:this.mouseDownOnVector.bind(this)})}static componentType="vector";static primaryStateVariableForDefinition="displacementShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.headDraggable={createComponentOfType:"boolean"},e.tailDraggable={createComponentOfType:"boolean"},e.x={createComponentOfType:"math"},e.y={createComponentOfType:"math"},e.z={createComponentOfType:"math"},e.xs={createComponentOfType:"mathList"},e.displacement={createComponentOfType:"vector"},e.head={createComponentOfType:"point"},e.tail={createComponentOfType:"point"},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.displayWithAngleBrackets={createComponentOfType:"boolean",createStateVariable:"displayWithAngleBrackets",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),r=e.map((e=>typeof e)),a=r.indexOf("string"),i=r.lastIndexOf("string");if(-1===a){let n=t.componentIsSpecifiedType,r=e.filter((e=>!(n(e,"point")||n(e,"vector")||n(e,"label"))));if(1===r.length){let t=r[0],n=e.indexOf(t);return{success:!0,newAttributes:{displacement:{component:{componentType:"math",children:r}}},newChildren:[...e.slice(0,n),...e.slice(n+1)]}}return{success:!1}}let s=[...e.slice(0,a),...e.slice(i+1)],o=n({matchedChildren:e=e.slice(a,i+1)});return o.success||1!==e.length?o.success?{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:o.newChildren,skipSugar:!0}}},newChildren:s}:{success:!1}:{success:!0,newAttributes:{x:{component:{componentType:"math",children:e}}},newChildren:s}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"points",componentTypes:["point"]},{group:"vectors",componentTypes:["vector"]}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" vector"}}}},e.tailDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({tailDraggableAttr:{dependencyType:"attributeComponent",attributeName:"tailDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.tailDraggableAttr?{setValue:{tailDraggable:e.tailDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{tailDraggable:{defaultValue:e.draggable}}}},e.headDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({headDraggableAttr:{dependencyType:"attributeComponent",attributeName:"headDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.headDraggableAttr?{setValue:{headDraggable:e.headDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{headDraggable:{defaultValue:e.draggable}}}},e.displacementShadow={defaultValue:null,hasEssential:!0,essentialVarName:"displacement",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{displacementShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"displacementShadow",value:convertValueToMathExpression(e.displacementShadow)}]}}},e.headShadow={defaultValue:null,hasEssential:!0,essentialVarName:"head",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{headShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"headShadow",value:convertValueToMathExpression(e.headShadow)}]}}},e.tailShadow={defaultValue:null,hasEssential:!0,essentialVarName:"tail",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{tailShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"tailShadow",value:convertValueToMathExpression(e.tailShadow)}]}}},e.sourceOfDisplacement={returnDependencies:()=>({xAttr:{dependencyType:"attributeComponent",attributeName:"x"},yAttr:{dependencyType:"attributeComponent",attributeName:"y"},zAttr:{dependencyType:"attributeComponent",attributeName:"z"},xsAttr:{dependencyType:"attributeComponent",attributeName:"xs"},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement"},pointChild:{dependencyType:"child",childGroups:["points"]},vectorChild:{dependencyType:"child",childGroups:["vectors"]}}),definition({dependencyValues:e}){let t=null;return e.vectorChild.length>0?t="vectorChild":e.pointChild.length>0?t="pointChild":null!==e.displacementAttr?t="displacementAttr":null!==e.xsAttr?t="xsAttr":null===e.xAttr&&null===e.yAttr&&null===e.zAttr||(t="componentAttrs"),{setValue:{sourceOfDisplacement:t}}}},e.basedOnHead={returnDependencies:()=>({headAttr:{dependencyType:"attributeComponent",attributeName:"head"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"},tailAttr:{dependencyType:"attributeComponent",attributeName:"tail"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"}}),definition:function({dependencyValues:e}){return null!==e.tailAttr&&null!==e.sourceOfDisplacement?(null!==e.headAttr&&console.warn("Vector is prescribed by head, tail, and displacement. Ignoring specified head."),{setValue:{basedOnHead:!1},checkForActualChange:{basedOnHead:!0}}):null!==e.headAttr?{setValue:{basedOnHead:!0},checkForActualChange:{basedOnHead:!0}}:{setValue:{basedOnHead:null!==e.headShadow},checkForActualChange:{basedOnHead:!0}}}},e.basedOnTail={returnDependencies:()=>({tailAttr:{dependencyType:"attributeComponent",attributeName:"tail"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"}}),definition:function({dependencyValues:e}){return null!==e.tailAttr?{setValue:{basedOnTail:!0},checkForActualChange:{basedOnTail:!0}}:{setValue:{basedOnTail:null!==e.tailShadow},checkForActualChange:{basedOnTail:!0}}}},e.basedOnDisplacement={returnDependencies:()=>({sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"}}),definition:function({dependencyValues:e}){return null!==e.sourceOfDisplacement?{setValue:{basedOnDisplacement:!0},checkForActualChange:{basedOnDisplacement:!0}}:{setValue:{basedOnDisplacement:null!==e.displacementShadow},checkForActualChange:{basedOnDisplacement:!0}}}},e.nDimDisplacement={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement",variableNames:["nDimensions"]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"]},xAttr:{dependencyType:"attributeComponent",attributeName:"x"},yAttr:{dependencyType:"attributeComponent",attributeName:"y"},zAttr:{dependencyType:"attributeComponent",attributeName:"z"},xsAttr:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["nComponents"]}};return e.basedOnDisplacement||(e.basedOnHead&&(t.nDimHead={dependencyType:"stateVariable",variableName:"nDimHead"}),e.basedOnTail&&(t.nDimTail={dependencyType:"stateVariable",variableName:"nDimTail"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnDisplacement)switch(e.sourceOfDisplacement){case"vectorChild":t=e.vectorChild[0].stateValues.nDimensions;break;case"pointChild":t=e.pointChild[0].stateValues.nDimensions;break;case"displacementAttr":t=e.displacementAttr.stateValues.nDimensions;break;case"xsAttr":t=e.xsAttr.stateValues.nComponents;break;case"componentAttrs":t=null!==e.zAttr?3:null!==e.yAttr?2:1;break;default:let n=e.displacementShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:1}else t=e.basedOnHead?e.basedOnTail?e.nDimHead===e.nDimTail?e.nDimHead:NaN:e.nDimHead:e.basedOnTail?e.nDimTail:2;return{setValue:{nDimDisplacement:t},checkForActualChange:{nDimDisplacement:!0}}}},e.nDimHead={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"},headAttr:{dependencyType:"attributeComponent",attributeName:"head",variableNames:["nDimensions"]}};return e.basedOnHead||(e.basedOnTail&&(t.nDimTail={dependencyType:"stateVariable",variableName:"nDimTail"}),e.basedOnDisplacement&&(t.nDimDisplacement={dependencyType:"stateVariable",variableName:"nDimDisplacement"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnHead){if(null!==e.headAttr)t=e.headAttr.stateValues.nDimensions;else if(e.headShadow){let n=e.headShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDisplacement?e.basedOnTail?e.nDimDisplacement===e.nDimTail?e.nDimDisplacement:NaN:e.nDimDisplacement:e.basedOnTail?e.nDimTail:2;return{setValue:{nDimHead:t},checkForActualChange:{nDimHead:!0}}}},e.nDimTail={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"},tailAttr:{dependencyType:"attributeComponent",attributeName:"tail",variableNames:["nDimensions"]}};return e.basedOnTail||(e.basedOnHead&&(t.nDimHead={dependencyType:"stateVariable",variableName:"nDimHead"}),e.basedOnDisplacement&&(t.nDimDisplacement={dependencyType:"stateVariable",variableName:"nDimDisplacement"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnTail){if(null!==e.tailAttr)t=e.tailAttr.stateValues.nDimensions;else if(e.tailShadow){let n=e.tailShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDisplacement?e.basedOnHead?e.nDimDisplacement===e.nDimHead?e.nDimDisplacement:NaN:e.nDimDisplacement:e.basedOnHead?e.nDimHead:2;return{setValue:{nDimTail:t},checkForActualChange:{nDimTail:!0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},nDimDisplacement:{dependencyType:"stateVariable",variableName:"nDimDisplacement"},nDimHead:{dependencyType:"stateVariable",variableName:"nDimHead"},nDimTail:{dependencyType:"stateVariable",variableName:"nDimTail"}}),definition:function({dependencyValues:e}){let t;if(e.basedOnDisplacement){if(e.basedOnTail){if(e.nDimDisplacement!==e.nDimTail)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}}}else if(e.basedOnHead&&e.nDimDisplacement!==e.nDimHead)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimDisplacement}else if(e.basedOnTail){if(e.basedOnHead&&e.nDimTail!==e.nDimHead)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimTail}else t=e.basedOnHead?e.nDimHead:2;return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.displacement={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros","displayWithAngleBrackets"],returnWrappingComponents:e=>"x"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["x"],hasEssential:!0,essentialVarName:"displacement2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","sourceOfDisplacement"],returnArraySizeDependencies:()=>({nDimDisplacement:{dependencyType:"stateVariable",variableName:"nDimDisplacement"}}),returnArraySize:({dependencyValues:e})=>[e.nDimDisplacement],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={xsAttr:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["math"+e]},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement",variableNames:["x"+e]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+e]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+e]}},"0"===r?n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"x",variableNames:["value"]}:"1"===r?n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"y",variableNames:["value"]}:"2"===r&&(n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"z",variableNames:["value"]}),!t.basedOnDisplacement&&t.basedOnHead&&(n[r].tailX={dependencyType:"stateVariable",variableName:"tailX"+e},n[r].headX={dependencyType:"stateVariable",variableName:"headX"+e})}return{globalDependencies:{basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;if(e.basedOnDisplacement)switch(e.sourceOfDisplacement){case"vectorChild":r[i]=t[i].vectorChild[0].stateValues["x"+n];break;case"pointChild":r[i]=t[i].pointChild[0].stateValues["x"+n];break;case"displacementAttr":r[i]=t[i].displacementAttr.stateValues["x"+n];break;case"xsAttr":r[i]=t[i].xsAttr.stateValues["math"+n].simplify();break;case"componentAttrs":let s=t[i].componentAttr;null===s?a[i]={defaultValue:me$3.fromAst(0)}:r[i]=s.stateValues.value.simplify();break;default:let o=e.displacementShadow.tree;Array.isArray(o)&&vectorOperators.includes(o[0])?r[i]=e.displacementShadow.get_component(Number(i)):r[i]=e.displacementShadow}else e.basedOnHead?r[i]=t[i].headX.subtract(t[i].tailX).simplify():a[i]={defaultValue:me$3.fromAst("0"===i?1:0)}}let i={};return Object.keys(r).length>0&&(i.setValue={displacement:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={displacement:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.displacement)if(t.basedOnDisplacement)switch(t.sourceOfDisplacement){case"vectorChild":i.push({setDependency:r[a].vectorChild,desiredValue:e.displacement[a],childIndex:0,variableIndex:0});break;case"pointChild":i.push({setDependency:r[a].pointChild,desiredValue:e.displacement[a],childIndex:0,variableIndex:0});break;case"displacementAttr":i.push({setDependency:r[a].displacementAttr,desiredValue:e.displacement[a],variableIndex:0});break;case"xsAttr":i.push({setDependency:r[a].xsAttr,desiredValue:e.displacement[a],variableIndex:0});break;case"componentAttrs":null===n[a].componentAttr?i.push({setEssentialValue:"displacement",value:{[a]:convertValueToMathExpression(e.displacement[a])}}):i.push({setDependency:r[a].componentAttr,desiredValue:e.displacement[a],variableIndex:0});break;default:s=!0}else t.basedOnHead?i.push({setDependency:r[a].headX,desiredValue:n[a].tailX.add(e.displacement[a]).simplify()}):i.push({setEssentialValue:"displacement",value:{[a]:convertValueToMathExpression(e.displacement[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.displacement)t[Number(n)+1]=e.displacement[n].tree;t.length=a[0]+1,i.push({setDependency:"displacementShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.displacement&&i.push({setDependency:"displacementShadow",desiredValue:e.displacement[0]});return{success:!0,instructions:i}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.head={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"headX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["headX"],set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnHead"],returnArraySizeDependencies:()=>({nDimHead:{dependencyType:"stateVariable",variableName:"nDimHead"}}),returnArraySize:({dependencyValues:e})=>[e.nDimHead],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={headAttr:{dependencyType:"attributeComponent",attributeName:"head",variableNames:["x"+e]}},t.basedOnHead||(n[r].tailX={dependencyType:"stateVariable",variableName:"tailX"+e},n[r].x={dependencyType:"stateVariable",variableName:"x"+e})}return{globalDependencies:{basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=Number(a)+1;e.basedOnHead?null!==t[a].headAttr?r[a]=t[a].headAttr.stateValues["x"+n]:null!==e.headShadow&&(r[a]=e.headShadow.get_component(Number(a))):r[a]=t[a].tailX.add(t[a].x).simplify()}return{setValue:{head:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.head)t.basedOnHead?n[a].headAttr&&null!==n[a].headAttr?i.push({setDependency:r[a].headAttr,desiredValue:e.head[a],variableIndex:0}):null!==t.headShadow&&(s=!0):i.push({setDependency:r[a].x,desiredValue:e.head[a].subtract(n[a].tailX).simplify()});if(s)if(a[0]>1){let t=["vector"];for(let n in e.head)t[Number(n)+1]=e.head[n].tree;t.length=a[0]+1,i.push({setDependency:"headShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.head&&i.push({setDependency:"headShadow",desiredValue:e.head[0]});return{success:!0,instructions:i}}},e.tail={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"tailX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["tailX"],hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(0),essentialVarName:"tail2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnTail","basedOnHead","basedOnDisplacement"],returnArraySizeDependencies:()=>({nDimTail:{dependencyType:"stateVariable",variableName:"nDimTail"}}),returnArraySize:({dependencyValues:e})=>[e.nDimTail],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={tailAttr:{dependencyType:"attributeComponent",attributeName:"tail",variableNames:["x"+e]}},t.basedOnTail||t.basedOnHead&&t.basedOnDisplacement&&(n[r].headX={dependencyType:"stateVariable",variableName:"headX"+e},n[r].x={dependencyType:"stateVariable",variableName:"x"+e})}return{globalDependencies:{basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;null!==t[i].tailAttr?r[i]=t[i].tailAttr.stateValues["x"+n]:null!==e.tailShadow?r[i]=e.tailShadow.get_component(Number(i)):e.basedOnHead&&e.basedOnDisplacement?r[i]=t[i].headX.subtract(t[i].x).simplify():a[i]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={tail:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={tail:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.tail)n[a].tailAttr&&null!==n[a].tailAttr?i.push({setDependency:r[a].tailAttr,desiredValue:e.tail[a],variableIndex:0}):null!==t.tailShadow?s=!0:t.basedOnHead&&t.basedOnDisplacement?i.push({setDependency:r[a].x,desiredValue:n[a].headX.subtract(e.tail[a]).simplify()}):i.push({setEssentialValue:"tail",value:{[a]:convertValueToMathExpression(e.tail[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.tail)t[Number(n)+1]=e.tail[n].tree;t.length=a[0]+1,i.push({setDependency:"tailShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.tail&&i.push({setDependency:"tailShadow",desiredValue:e.tail[0]});return{success:!0,instructions:i}}},e.magnitude={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},displacement:{dependencyType:"stateVariable",variableName:"displacement"}}),definition({dependencyValues:e}){let t=0,n=!0;for(let r=0;re/i));let s=e.magnitude.evaluate_to_constant();if(!Number.isFinite(s)||s<0)return{success:!1};let o=[];for(let e=0;e({head:{dependencyType:"stateVariable",variableName:"head"},tail:{dependencyType:"stateVariable",variableName:"tail"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition:function({dependencyValues:e}){let t,n;if(1===e.nDimensions)e.head[0].evaluate_to_constant(),n=e.tail[0].evaluate_to_constant(),Number.isFinite(n)||(n=NaN);else{t=[],n=[];for(let r=0;r({displacement:{dependencyType:"stateVariable",variableName:"displacement"},displayWithAngleBrackets:{dependencyType:"stateVariable",variableName:"displayWithAngleBrackets"}}),definition({dependencyValues:e}){let t=[];for(let n of e.displacement)n?t.push(n.tree):t.push("_");if(t.length>1){t=[e.displayWithAngleBrackets?"altvector":"vector",...t]}else t=1===t.length?t[0]:"_";return{setValue:{displacementCoords:me$3.fromAst(t)}}},inverseDefinition({desiredStateVariableValues:e}){let t,n=e.displacementCoords.tree;return t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.slice(1).map((e=>me$3.fromAst(e))):[e.displacementCoords],{success:!0,instructions:[{setDependency:"displacement",desiredValue:t}]}}},e.latex={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({displacementCoords:{dependencyType:"stateVariable",variableName:"displacementCoords"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.displacementCoords,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"}}),definition({dependencyValues:e}){let t=e.numericalEndpoints[0]?.[0],n=e.numericalEndpoints[0]?.[1],r=e.numericalEndpoints[1]?.[0],a=e.numericalEndpoints[1]?.[1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:d>=1?{x1:r,x2:a}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e}static adapters=[{stateVariable:"displacementCoords",componentType:"coords",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async moveVector({tailcoords:e,headcoords:t,transient:n,skippable:r,sourceInformation:a,actionId:i}){if(void 0!==e){if(void 0!==t){if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:i})}else if(!await this.stateValues.tailDraggable)return await this.coreFunctions.resolveAction({actionId:i})}else if(!await this.stateValues.headDraggable)return await this.coreFunctions.resolveAction({actionId:i});let s=[];if(void 0!==e){if(await this.stateValues.basedOnHead&&await this.stateValues.basedOnDisplacement){let n;if(void 0===t){let t=await this.stateValues.numericalEndpoints;n=e.map(((e,n)=>t[1][n]-e))}else n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}else s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"tail",value:e.map((e=>me$3.fromAst(e))),sourceInformation:a});if(void 0===t&&!await this.stateValues.basedOnHead){let t=await this.stateValues.numericalEndpoints,n=e.map(((e,n)=>t[1][n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}if(void 0!==t){if(await this.stateValues.basedOnHead)s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"head",value:t.map((e=>me$3.fromAst(e))),sourceInformation:a});else{null==e&&(e=(await this.stateValues.numericalEndpoints)[0]);let n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}if(void 0===e&&await this.stateValues.basedOnHead&&await this.stateValues.basedOnDisplacement){let e=await this.stateValues.numericalEndpoints,n=t.map(((t,n)=>t-e[0][n]));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}return n?await this.coreFunctions.performUpdate({updateInstructions:s,transient:n,skippable:r,actionId:i}):await this.coreFunctions.performUpdate({updateInstructions:s,actionId:i,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{head:t,tail:e}}})}async vectorClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnVector({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Angle extends GraphicalComponent{static componentType="angle";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.radius={createComponentOfType:"math",createStateVariable:"radius",defaultValue:me$3.fromAst(1),public:!0},e.chooseReflexAngle={createComponentOfType:"text",createStateVariable:"chooseReflexAngle",defaultValue:"never",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["never","allowed","always"]},e.inDegrees={createComponentOfType:"boolean",createStateVariable:"inDegrees",defaultValue:!1,public:!0,forRenderer:!0},e.radians={createComponentOfType:"math"},e.degrees={createComponentOfType:"math"},e.through={createComponentOfType:"_pointListComponent"},e.betweenLines={createComponentOfType:"_lineListComponent"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.emphasizeRightAngle={createComponentOfType:"boolean",createStateVariable:"emphasizeRightAngle",defaultValue:!0,public:!0,forRenderer:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a.push(...e.slice(0,t)),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),a.push(...e.slice(t)))}return 0===r.length?{success:!1}:{success:!0,newAttributes:{radians:{component:{componentType:"math",children:r}}},newChildren:a}}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({betweenLines:{dependencyType:"attributeComponent",attributeName:"betweenLines"}}),definition({dependencyValues:e}){let t=null;return null!==e.betweenLines&&(t=e.betweenLines.componentName),{setValue:{betweenLinesName:t}}}},e.nPointsSpecified={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:({dependencyValues:e})=>null!==e.through?{setValue:{nPointsSpecified:e.through.stateValues.nPoints}}:{setValue:{nPointsSpecified:0}}},e.points={isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],stateVariablesDeterminingDependencies:["betweenLinesName"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[3,2],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},returnArrayDependenciesByKey({stateValues:e}){let t={nPointsSpecified:{dependencyType:"stateVariable",variableName:"nPointsSpecified"},throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["points"]},radiansAttr:{dependencyType:"attributeComponent",attributeName:"radians",variableNames:["value"]},degreesAttr:{dependencyType:"attributeComponent",attributeName:"degrees",variableNames:["value"]}};return null!==e.betweenLinesName&&(t.lineChildren={dependencyType:"child",parentName:e.betweenLinesName,childGroups:["lines"],variableNames:["points","nDimensions","coeff0","coeffvar1","coeffvar2","nearestPoint"]}),{globalDependencies:t}},arrayDefinitionByKey({globalDependencyValues:e}){if(e.lineChildren){if(e.lineChildren.length>2){console.warn(`Cannot define an angle between ${e.lineChildren.length} line(s)`);let t={};for(let e=0;e<3;e++)for(let n=0;n<2;n++)t[e+","+n]=me$3.fromAst("_");return{setValue:{points:t}}}if(1===e.lineChildren.length){let t=e.lineChildren[0];if(2!==t.stateValues.nDimensions){let e={};for(let t=0;t<3;t++)for(let n=0;n<2;n++)e[t+","+n]=me$3.fromAst("_");return{setValue:{points:e}}}let n=t.stateValues.nearestPoint({variables:{x1:me$3.fromAst(0),x2:me$3.fromAst(0)}}),r=t.stateValues.points[0][0].evaluate_to_constant(),a=t.stateValues.points[0][1].evaluate_to_constant(),i=t.stateValues.points[1][0].evaluate_to_constant(),s=t.stateValues.points[1][1].evaluate_to_constant(),o=Math.atan2(s-a,i-r),l={"0,0":me$3.fromAst(n.x1+Math.cos(o)),"0,1":me$3.fromAst(n.x2+Math.sin(o)),"1,0":me$3.fromAst(n.x1),"1,1":me$3.fromAst(n.x2)},u=null;if(e.radiansAttr){if(u=e.radiansAttr.stateValues.value.evaluate_to_constant(),!Number.isFinite(u)){let e={};return e["2,0"]=me$3.fromAst("_"),e["2,1"]=me$3.fromAst("_"),{setValue:{points:e}}}}else if(e.degreesAttr){let t=e.degreesAttr.stateValues.value.evaluate_to_constant();if(!Number.isFinite(t))return l["2,0"]=me$3.fromAst("_"),l["2,1"]=me$3.fromAst("_"),{setValue:{points:l}};u=t/180*Math.PI}else u=Math.PI/2;let c=o+u;return l["2,0"]=me$3.fromAst(n.x1+Math.cos(c)),l["2,1"]=me$3.fromAst(n.x2+Math.sin(c)),{setValue:{points:l}}}{let t=e.lineChildren[0],n=e.lineChildren[1],r=calculateLineIntersection(t,n);if(void 0===r){let e={};for(let t=0;t<3;t++)for(let n=0;n<2;n++)e[t+","+n]=me$3.fromAst("_");return{setValue:{points:e}}}let a=r,i=t.stateValues.points[0][0].evaluate_to_constant(),s=t.stateValues.points[0][1].evaluate_to_constant(),o=t.stateValues.points[1][0].evaluate_to_constant(),l=t.stateValues.points[1][1].evaluate_to_constant(),u=[me$3.fromAst(a[0].tree+o-i),me$3.fromAst(a[1].tree+l-s)];i=n.stateValues.points[0][0].evaluate_to_constant(),s=n.stateValues.points[0][1].evaluate_to_constant(),o=n.stateValues.points[1][0].evaluate_to_constant(),l=n.stateValues.points[1][1].evaluate_to_constant();let c=[me$3.fromAst(a[0].tree+o-i),me$3.fromAst(a[1].tree+l-s)];return{setValue:{points:{"0,0":u[0],"0,1":u[1],"1,0":a[0],"1,1":a[1],"2,0":c[0],"2,1":c[1]}}}}}let t,n=e.nPointsSpecified;t=e.throughAttr?e.throughAttr.stateValues.points:[];let r={};for(let[e,n]of t.entries())r[e+",0"]=n[0],r[e+",1"]=n[1];if(0===n&&(r["0,0"]=me$3.fromAst(1),r["0,1"]=me$3.fromAst(0)),n<2&&(r["1,0"]=me$3.fromAst(0),r["1,1"]=me$3.fromAst(0)),n<3){let t=null;if(e.radiansAttr){if(t=e.radiansAttr.stateValues.value.evaluate_to_constant(),!Number.isFinite(t))return r["2,0"]=me$3.fromAst("_"),r["2,1"]=me$3.fromAst("_"),{setValue:{points:r}}}else if(e.degreesAttr){let n=e.degreesAttr.stateValues.value.evaluate_to_constant();if(!Number.isFinite(n))return r["2,0"]=me$3.fromAst("_"),r["2,1"]=me$3.fromAst("_"),{setValue:{points:r}};t=n/180*Math.PI}else t=Math.PI/2;let n=r["0,0"].evaluate_to_constant(),a=r["0,1"].evaluate_to_constant(),i=r["1,0"].evaluate_to_constant(),s=r["1,1"].evaluate_to_constant(),o=Math.atan2(a-s,n-i)+t;r["2,0"]=me$3.fromAst(i+Math.cos(o)),r["2,1"]=me$3.fromAst(s+Math.sin(o))}return{setValue:{points:r}}}},e.radians={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},additionalStateVariablesDefined:[{variableName:"swapPointOrder",forRenderer:!0}],returnDependencies:()=>({radians:{dependencyType:"attributeComponent",attributeName:"radians",variableNames:["value"]},degrees:{dependencyType:"attributeComponent",attributeName:"degrees",variableNames:["value"]},points:{dependencyType:"stateVariable",variableName:"points"},chooseReflexAngle:{dependencyType:"stateVariable",variableName:"chooseReflexAngle"}}),definition({dependencyValues:e}){let t=!1;if(null!==e.radians)return{setValue:{radians:e.radians.stateValues.value.simplify(),swapPointOrder:t}};if(null!==e.degrees)return{setValue:{radians:e.degrees.stateValues.value.divide(me$3.fromAst(180)).simplify().multiply(me$3.fromAst("pi")).simplify(),swapPointOrder:t}};let n,r=[],a=!1;for(let t=0;t<3;t++)r.push([e.points[t][0].evaluate_to_constant(),e.points[t][1].evaluate_to_constant()]),null!==r[t][0]&&null!==r[t][1]||(a=!0);return a?{setValue:{radians:me$3.fromAst("_"),swapPointOrder:t}}:(n=Math.atan2(r[2][1]-r[1][1],r[2][0]-r[1][0])-Math.atan2(r[0][1]-r[1][1],r[0][0]-r[1][0]),n<0&&(n+=2*Math.PI),n>Math.PI?"never"===e.chooseReflexAngle&&(n=2*Math.PI-n,t=!0):"always"===e.chooseReflexAngle&&(n=2*Math.PI-n,t=!0),{setValue:{radians:me$3.fromAst(n),swapPointOrder:t}})}},e.value={isAlias:!0,targetVariableName:"radians"},e.angle={isAlias:!0,targetVariableName:"radians"},e.degrees={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({radians:{dependencyType:"stateVariable",variableName:"radians"}}),definition({dependencyValues:e}){let t;if("_"===e.radians.tree||Number.isNaN(e.radians.tree))t=e.radians;else{let n=e.radians.evaluate_to_constant();t=Number.isFinite(n)?me$3.fromAst(180*n/Math.PI):e.radians.multiply(me$3.fromAst(["/",180,"pi"])).simplify()}return{setValue:{degrees:t}}}},e.latexForRenderer={forRenderer:!0,returnDependencies:()=>({inDegrees:{dependencyType:"stateVariable",variableName:"inDegrees"},radians:{dependencyType:"stateVariable",variableName:"radians"},degrees:{dependencyType:"stateVariable",variableName:"degrees"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits));let r=roundForDisplay({value:e.inDegrees?e.degrees:e.radians,dependencyValues:e,usedDefault:t}).toLatex(n);return e.inDegrees&&(r+="^\\circ"),{setValue:{latexForRenderer:r}}}},e.numericalPoints={isArray:!0,entryPrefixes:["numericalPoint"],forRenderer:!0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[3],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={point:{dependencyType:"stateVariable",variableName:"point"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].point,a=[];for(let e=0;e<2;e++){let n=t[e].evaluate_to_constant();Number.isFinite(n)||(n=NaN),a.push(n)}n[r]=a}return{setValue:{numericalPoints:n}}}},e.numericalRadius={forRenderer:!0,returnDependencies:()=>({radius:{dependencyType:"stateVariable",variableName:"radius"}}),definition({dependencyValues:e}){let t=e.radius.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),{setValue:{numericalRadius:t}}}},e}static adapters=["radians"]}function calculateLineIntersection(e,t){if(2!==e.stateValues.nDimensions||2!==t.stateValues.nDimensions)return void console.log("Calculating angle between two lines implemented only in 2D");let n=e.stateValues.coeffvar1.evaluate_to_constant(),r=e.stateValues.coeffvar2.evaluate_to_constant(),a=e.stateValues.coeff0.evaluate_to_constant(),i=t.stateValues.coeffvar1.evaluate_to_constant(),s=t.stateValues.coeffvar2.evaluate_to_constant(),o=t.stateValues.coeff0.evaluate_to_constant();if(!(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a)&&Number.isFinite(i)&&Number.isFinite(s)&&Number.isFinite(o)))return void console.log("Calculating angle between two lines implemented only for constant coefficients");let l=n*s-i*r;if(Math.abs(l)<1e-14)return Math.abs(o*n-a*i)>1e-14?void console.log("Cannot calculate angle between two parallel lines"):0===n&&0===r&&0===a||0===i&&0===s&&0===o?void 0:0!==r?[me$3.fromAst(0),me$3.fromAst(-a/r)]:[me$3.fromAst(-a/n),me$3.fromAst(0)];let u=(o*r-a*s)/l,c=(a*i-o*n)/l;return[me$3.fromAst(u),me$3.fromAst(c)]}var defaults$5={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify},util$1={isArray:Array.isArray,assign:Object.assign,isObject:e=>"object"==typeof e,isFunction:e=>"function"==typeof e,isBoolean:e=>"boolean"==typeof e,isRegex:e=>e instanceof RegExp,keys:Object.keys};const DEFAULTS=defaults$5,isFunction$2=util$1.isFunction,isBoolean$1=util$1.isBoolean,isObject$2=util$1.isObject,isArray$3=util$1.isArray,isRegex=util$1.isRegex,assign$1=util$1.assign,keys$1=util$1.keys;function serialize(e){return null==e?e:isRegex(e)?e.toString():e.toJSON?e.toJSON():e}function stringifyDeterministic(e,t){t=t||assign$1({},DEFAULTS),isFunction$2(t)&&(t={compare:t});const n=t.space||DEFAULTS.space,r=isBoolean$1(t.cycles)?t.cycles:DEFAULTS.cycles,a=t.replacer||DEFAULTS.replacer,i=t.stringify||DEFAULTS.stringify,s=t.compare&&function(e){return function(t){return function(n,r){const a={key:n,value:t[n]},i={key:r,value:t[r]};return e(a,i)}}}(t.compare);r||i(e);const o=[];return function e(t,l,u,c){const p=n?"\n"+new Array(c+1).join(n):"",d=n?": ":":";if(u=serialize(u),void 0!==(u=a.call(t,l,u))){if(!isObject$2(u)||null===u)return i(u);if(isArray$3(u)){const t=[];for(let r=0;r0)for(let e of t.children)"object"!=typeof e?e.trim()&&(p=!0):i(e,"when")||(i(e,"math")||i(e,"number")||i(e,"mathList")||i(e,"numberList")?(s=!0,p=!0):i(e,"text")||i(e,"textList")?(o=!0,p=!0):i(e,"boolean")?(l=!0,p=!0):i(e,"booleanList")?l=!0:n.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"})&&!e.attributes?.createComponentOfType?.primitive?p=!0:i(e,"orbitalDiagram")||(p=!0));else p=!0;else i(t,"mathInput")?(m.push(!1),s=!0,c=!0):i(t,"textInput")?(m.push(!1),o=!0,c=!0):i(t,"_input")||i(t,"considerAsResponses")?(m.push(!1),c=!0):(n.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:"_composite"})&&t.attributes?.createComponentOfType?.primitive,m.push(!0),p=!0);if(c&&(d=!0),u>0){if(e=e.filter((e=>"string"!=typeof e||""!==e.trim())),e.length!==u)return{success:!1};{let n={componentType:"choiceInput",children:e};return t.shuffleOrder&&(n.attributes={shuffleOrder:{primitive:!0}}),{success:!0,newChildren:[n]}}}if(!p&&!d){for(let t of e)if(i(t,"award")&&t.children?.length>0&&r(t.children)){d=!0;break}if(!d)for(let t of e)i(t,"award")&&t.children?.length>0&&a(t.children)}let h=[],f=[],y=[];if(0===m.filter((e=>!e)).length)h=e;else{if(!m[0]){let t=m.indexOf(!0);-1!==t&&(f=e.slice(0,t),e=e.slice(t),m=m.slice(t))}let t=m.indexOf(!1);-1===t?h=e:(h=e.slice(0,t),y=e.slice(t))}for(;"string"==typeof h[0]&&""===h[0].trim();)h=h.slice(1);let g,b,v=h.length;for(;"string"==typeof h[v-1]&&""===h[v-1].trim();)h=h.slice(0,v-1),v=h.length;if(t.type?(b=t.type,["math","text","boolean"].includes(b)||(console.warn(`Invalid type ${b}`),b="math")):b=s?"math":o?"text":l?"boolean":"math",0===h.length)g=[...f,...y];else{let e;e=h.length>1||n.isInheritedComponentType({inheritedComponentType:h[0].componentType,baseComponentType:"_composite"})&&!h[0].props?.componentType?[{componentType:b,children:h}]:h,g=[...f,{componentType:"award",children:e},...y]}if(p&&!c){g=[{componentType:b+"Input"},...g]}return{success:!0,newChildren:g}}}),e}static returnChildGroups(){return[{group:"awards",componentTypes:["award"]},{group:"inputs",componentTypes:["_input"]},{group:"responses",componentTypes:["considerAsResponses"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"disabled",newName:"disabledOriginal"}),e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessPreliminary:{dependencyType:"stateVariable",variableName:"showCorrectnessPreliminary"},showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition({dependencyValues:e,usedDefault:t}){let n;return n=t.showCorrectnessPreliminary?!1!==e.showCorrectnessFlag:e.showCorrectnessPreliminary,{setValue:{showCorrectness:n}}}},e.haveAwardThatRequiresInput={returnDependencies:()=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["requireInputInAnswer"]}}),definition:({dependencyValues:e})=>({setValue:{haveAwardThatRequiresInput:e.awardChildren.some((e=>e.stateValues.requireInputInAnswer))}})},e.allInputChildrenIncludingSugared={returnDependencies:()=>({allInputChildrenIncludingSugared:{dependencyType:"child",childGroups:["inputs"]}}),definition:({dependencyValues:e})=>({setValue:{allInputChildrenIncludingSugared:e.allInputChildrenIncludingSugared}})},e.inputChildren={stateVariablesDeterminingDependencies:["allInputChildrenIncludingSugared"],additionalStateVariablesDefined:["inputChildIndices","skippedFirstInput"],forRenderer:!0,returnDependencies({stateValues:e}){let t={allInputChildrenIncludingSugared:{dependencyType:"stateVariable",variableName:"allInputChildrenIncludingSugared"},haveAwardThatRequiresInput:{dependencyType:"stateVariable",variableName:"haveAwardThatRequiresInput"}};return e.allInputChildrenIncludingSugared.length>0&&(t.firstInputFromSugar={dependencyType:"doenetAttribute",componentName:e.allInputChildrenIncludingSugared[0].componentName,attributeName:"createdFromSugar"}),t},definition({dependencyValues:e}){let t=[...e.allInputChildrenIncludingSugared],n=[...e.allInputChildrenIncludingSugared.keys()],r=!1;return"choiceInput"!==t[0]?.componentType&&(!e.haveAwardThatRequiresInput||e.allInputChildrenIncludingSugared.length>1)&&e.firstInputFromSugar&&(r=!0,t=t.slice(1),n=n.slice(1)),{setValue:{inputChildren:t,inputChildIndices:n,skippedFirstInput:r}}}},e.inputChildrenWithValues={stateVariablesDeterminingDependencies:["inputChildIndices"],forRenderer:!0,returnDependencies:({stateValues:e})=>({inputChildren:{dependencyType:"child",childGroups:["inputs"],variableNames:["valueToRecordOnSubmit","valueRecordedAtSubmit","value"],childIndices:e.inputChildIndices,variablesOptional:!0}}),definition:function({dependencyValues:e}){return{setValue:{inputChildrenWithValues:e.inputChildren}}}},e.inputChildWithValues={returnDependencies:()=>({inputChildrenWithValues:{dependencyType:"stateVariable",variableName:"inputChildrenWithValues"}}),definition({dependencyValues:e}){let t=null;return 1===e.inputChildrenWithValues.length&&(t=e.inputChildrenWithValues[0]),{setValue:{inputChildWithValues:t}}}},e.awardInputResponseChildren={returnDependencies:()=>({awardInputResponseChildren:{dependencyType:"child",childGroups:["awards","inputs","responses"]},skippedFirstInput:{dependencyType:"stateVariable",variableName:"skippedFirstInput"}}),definition({dependencyValues:e}){let t=[...e.awardInputResponseChildren];return e.skippedFirstInput&&(t=t.slice(1)),{setValue:{awardInputResponseChildren:t}}}},e.nResponses={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["awardInputResponseChildren"],returnDependencies({stateValues:e,componentInfoObjects:t}){let n={childTypes:{dependencyType:"value",value:e.awardInputResponseChildren.map((e=>e.componentType))}};for(let[r,a]of e.awardInputResponseChildren.entries())t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"award"})?n["child"+r]={dependencyType:"descendant",ancestorName:a.componentName,componentTypes:["_base"],variableNames:["isResponse","nValues"],variablesOptional:!0,recurseToMatchedChildren:!0,includeNonActiveChildren:!0,skipOverAdapters:!0}:t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_input"})?n["childNValues"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"nValues",variablesOptional:!0}:n["child"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"childrenWithNValues"};return n},definition({dependencyValues:e,componentInfoObjects:t}){let n=0;for(let[r,a]of e.childTypes.entries())if(t.isInheritedComponentType({inheritedComponentType:a,baseComponentType:"award"}))for(let a of e["child"+r])a.stateValues.isResponse&&!t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_composite"})&&(void 0===a.stateValues.nValues?n+=1:n+=a.stateValues.nValues);else if(t.isInheritedComponentType({inheritedComponentType:a,baseComponentType:"_input"})){let t=e["childNValues"+r];n+=void 0===t?1:t}else for(let t of e["child"+r])void 0===t.stateValues.nValues?n+=1:n+=t.stateValues.nValues;return{setValue:{nResponses:n}}}},e.currentResponses={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["currentResponse"],stateVariablesDeterminingDependencies:["awardInputResponseChildren"],returnArraySizeDependencies:()=>({nResponses:{dependencyType:"stateVariable",variableName:"nResponses"}}),returnArraySize:({dependencyValues:e})=>[e.nResponses],returnArrayDependenciesByKey({stateValues:e,componentInfoObjects:t}){let n={childTypes:{dependencyType:"value",value:e.awardInputResponseChildren.map((e=>e.componentType))}};for(let[r,a]of e.awardInputResponseChildren.entries())t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"award"})?n["child"+r]={dependencyType:"descendant",ancestorName:a.componentName,componentTypes:["_base"],variableNames:["isResponse","value","values","formula","componentType"],variablesOptional:!0,recurseToMatchedChildren:!0,includeAttributeChildren:!0,includeNonActiveChildren:!0,skipOverAdapters:!0}:t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_input"})?(n["childValue"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"value",variablesOptional:!0},n["childValues"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"values",variablesOptional:!0},n["childComponentType"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"componentType",variablesOptional:!0}):n["child"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"childrenAsResponses"};return{globalDependencies:n}},arrayDefinitionByKey({globalDependencyValues:e,componentInfoObjects:t}){let n=[],r=[],a=[];for(let[n,r]of e.childTypes.entries())if(t.isInheritedComponentType({inheritedComponentType:r,baseComponentType:"award"}))for(let r of e["child"+n])r.stateValues.isResponse&&!t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})&&a.push(r);else if(t.isInheritedComponentType({inheritedComponentType:r,baseComponentType:"_input"})){let t={componentType:r,stateValues:{value:e["childValue"+n],values:e["childValues"+n],componentType:e["childComponentType"+n]}};a.push(t)}else a.push(...e["child"+n]);for(let e of a){let t=e.stateValues.componentType;t||(t=e.componentType),"mathList"===t?t="math":"numberList"===t?t="number":"textList"===t?t="text":"booleanList"===t&&(t="boolean"),Array.isArray(e.stateValues.values)?(n.push(...e.stateValues.values),r.push(...Array(e.stateValues.values.length).fill(t))):void 0!==e.stateValues.value?(n.push(e.stateValues.value),r.push(t)):e.stateValues.formula instanceof me$3.class?(n.push(e.stateValues.formula),r.push("math")):(n.push(""),r.push("text"))}return{setValue:{currentResponses:n},setCreateComponentOfType:{currentResponses:r}}}},e.currentResponse={isAlias:!0,targetVariableName:"currentResponse1"},e.nSubmittedResponses={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{nSubmittedResponses:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nSubmittedResponses",value:e.nSubmittedResponses}]})},e.submittedResponsesComponentType={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{submittedResponsesComponentType:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return e.submittedResponsesComponentType?{success:!0,instructions:[{setEssentialValue:"submittedResponsesComponentType",value:[...e.submittedResponsesComponentType]}]}:{success:!0,instructions:[{setEssentialValue:"submittedResponsesComponentType",value:[]}]}}},e.submittedResponses={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["submittedResponse"],defaultValueByArrayKey:()=>"_",hasEssential:!0,inverseShadowToSetEntireArray:!0,doNotCombineInverseArrayInstructions:!0,returnArraySizeDependencies:()=>({nSubmittedResponses:{dependencyType:"stateVariable",variableName:"nSubmittedResponses"}}),returnArraySize:({dependencyValues:e})=>[e.nSubmittedResponses],returnArrayDependenciesByKey:()=>({globalDependencies:{submittedResponsesComponentType:{dependencyType:"stateVariable",variableName:"submittedResponsesComponentType"},nSubmittedResponses:{dependencyType:"stateVariable",variableName:"nSubmittedResponses"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=[];e.submittedResponsesComponentType&&t.push(...e.submittedResponsesComponentType.slice(0,e.nSubmittedResponses));let n={};for(let r=0;r({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e.delegateCheckWork={additionalStateVariablesDefined:["delegateCheckWorkToInput","delegateCheckWorkToAncestor"],forRenderer:!0,returnDependencies:()=>({inputChildren:{dependencyType:"stateVariable",variableName:"inputChildren"},forceFullCheckworkButton:{dependencyType:"stateVariable",variableName:"forceFullCheckworkButton"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["suppressAnswerSubmitButtons"]},documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["suppressAnswerSubmitButtons"]}}),definition:function({dependencyValues:e}){let t=!1,n=!1,r=!1;return e.documentAncestor.stateValues.suppressAnswerSubmitButtons||e.sectionAncestor?.stateValues.suppressAnswerSubmitButtons?t=r=!0:1!==e.inputChildren.length||e.forceFullCheckworkButton||(n=r=!0),{setValue:{delegateCheckWork:r,delegateCheckWorkToAncestor:t,delegateCheckWorkToInput:n}}}},e.creditAchievedIfSubmit={additionalStateVariablesDefined:["awardsUsedIfSubmit","awardChildren","inputUsedIfSubmit"],stateVariablesDeterminingDependencies:["inputChildIndices"],returnDependencies:({stateValues:e})=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["credit","creditAchievedIfSubmit","fractionSatisfiedIfSubmit"]},inputChildren:{dependencyType:"child",childGroups:["inputs"],variableNames:["creditAchievedIfSubmit"],childIndices:e.inputChildIndices,variablesOptional:!0},nAwardsCredited:{dependencyType:"stateVariable",variableName:"nAwardsCredited"}}),definition:function({dependencyValues:e}){let t=0,n=e.nAwardsCredited,r=Array(n).fill(null),a=null;if(0===e.awardChildren.length){if(1===e.inputChildren.length){let n=e.inputChildren[0].stateValues.creditAchievedIfSubmit;n>=0&&(t=n,a=e.inputChildren[0].componentName)}}else{let a=Array(n).fill(null),i=0;for(let t of e.awardChildren){let e=t.stateValues.creditAchievedIfSubmit;if((e>i||null===r[n-1])&&t.stateValues.fractionSatisfiedIfSubmit>0)if(null===r[0])r[0]=t.componentName,a[0]=e,i=Math.min(...a);else for(let[s,o]of a.entries())if(e>o||null===o){r.splice(s,0,t.componentName),r=r.slice(0,n),a.splice(s,0,e),a=a.slice(0,n),i=Math.min(...a);break}}t=Math.min(1,a.reduce(((e,t)=>e+t),0))}return{setValue:{creditAchievedIfSubmit:t,awardsUsedIfSubmit:r,awardChildren:e.awardChildren,inputUsedIfSubmit:a}}}},e.creditAchieved={defaultValue:0,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchieved:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"creditAchieved",value:e.creditAchieved}]}}},e.responseHasBeenSubmitted={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{responseHasBeenSubmitted:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"responseHasBeenSubmitted",value:e.responseHasBeenSubmitted}]}}},e.autoSubmit={returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{autoSubmit:Boolean(e.autoSubmit)}})},e.creditAchievedDependencies={shadowVariable:!0,stateVariablesDeterminingDependencies:["autoSubmit"],returnDependencies:({stateValues:e})=>({currentCreditAchievedDependencies:{dependencyType:"recursiveDependencyValues",variableNames:["creditAchievedIfSubmit"],includeImmediateValueWithValue:!e.autoSubmit,includeRawValueWithImmediateValue:!e.autoSubmit,includeOnlyEssentialValues:!0}}),definition({dependencyValues:e}){let t=lib(e.currentCreditAchievedDependencies,{replacer:serializedComponentsReplacer});return{setValue:{creditAchievedDependencies:Base64.stringify(sha1(t))}}},markStale:()=>({answerCreditPotentiallyChanged:!0})},e.creditAchievedDependenciesAtSubmit={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchievedDependenciesAtSubmit:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"creditAchievedDependenciesAtSubmit",value:e.creditAchievedDependenciesAtSubmit}]}}},e.justSubmitted={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({currentCreditAchievedDependencies:{dependencyType:"stateVariable",variableName:"creditAchievedDependencies"},creditAchievedDependenciesAtSubmit:{dependencyType:"stateVariable",variableName:"creditAchievedDependenciesAtSubmit"},disableAfterCorrect:{dependencyType:"stateVariable",variableName:"disableAfterCorrect"},hasBeenCorrect:{dependencyType:"stateVariable",variableName:"hasBeenCorrect"}}),definition:function({dependencyValues:e,justUpdatedForNewComponent:t,componentName:n}){if(e.disableAfterCorrect&&e.hasBeenCorrect)return{setValue:{justSubmitted:!0}};return e.creditAchievedDependenciesAtSubmit!==e.currentCreditAchievedDependencies&&!t?{setValue:{justSubmitted:!1},setEssentialValue:{justSubmitted:!1}}:{useEssentialOrDefaultValue:{justSubmitted:!0}}},inverseDefinition:({desiredStateVariableValues:e,componentName:t})=>({success:!0,instructions:[{setEssentialValue:"justSubmitted",value:e.justSubmitted}]})},e.allFeedbacks={returnDependencies:()=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["feedbacks"]},feedbackComponents:{dependencyType:"descendant",componentTypes:["_input"],variableNames:["feedbacks"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.awardChildren)t.push(...n.stateValues.feedbacks);for(let n of e.feedbackComponents)Array.isArray(n.stateValues.feedbacks)&&t.push(...n.stateValues.feedbacks);return{setValue:{allFeedbacks:t}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({}),definition:()=>({useEssentialOrDefaultValue:{nSubmissions:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nSubmissions",value:e.nSubmissions}]})},e.numberOfAttemptsLeft={public:!0,shadowingInstructions:{createComponentOfType:"integer"},forRenderer:!0,returnDependencies:()=>({nSubmissions:{dependencyType:"stateVariable",variableName:"nSubmissions"},maximumNumberOfAttempts:{dependencyType:"stateVariable",variableName:"maximumNumberOfAttempts"}}),definition:({dependencyValues:e})=>({setValue:{numberOfAttemptsLeft:e.maximumNumberOfAttempts-e.nSubmissions}})},e.hasBeenCorrect={defaultValue:!1,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({creditAchieved:{dependencyType:"stateVariable",variableName:"creditAchieved"}}),definition:({dependencyValues:e})=>1===e.creditAchieved?{setValue:{hasBeenCorrect:!0},setEssentialValue:{hasBeenCorrect:!0}}:{useEssentialOrDefaultValue:{hasBeenCorrect:!0}}},e.disabled={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,stateVariablesDeterminingDependencies:["disableAfterCorrect"],returnDependencies({stateValues:e}){let t={disabledOriginal:{dependencyType:"stateVariable",variableName:"disabledOriginal"},numberOfAttemptsLeft:{dependencyType:"stateVariable",variableName:"numberOfAttemptsLeft"},disableAfterCorrect:{dependencyType:"stateVariable",variableName:"disableAfterCorrect"}};return e.disableAfterCorrect&&(t.hasBeenCorrect={dependencyType:"stateVariable",variableName:"hasBeenCorrect"}),t},definition:({dependencyValues:e})=>({setValue:{disabled:e.disabledOriginal||e.numberOfAttemptsLeft<1||e.disableAfterCorrect&&e.hasBeenCorrect}})},e.inItemNumber={returnDependencies:()=>({documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["itemNumberByAnswerName"]}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{inItemNumber:e.documentAncestor.stateValues.itemNumberByAnswerName[t]}})},e}async submitAnswer({actionId:e}){let t=await this.stateValues.numberOfAttemptsLeft;if(t<1)return void console.warn(`Cannot submit answer for ${this.componentName} as number of attempts left is ${t}`);let n=await this.stateValues.creditAchievedIfSubmit,r=await this.stateValues.awardsUsedIfSubmit,a=await this.stateValues.inputUsedIfSubmit,i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"creditAchieved",value:n},{updateType:"updateValue",componentName:this.componentName,stateVariable:"responseHasBeenSubmitted",value:!0}],s=await this.stateValues.inputChildrenWithValues;if(1===s.length){let e=s[0];a===e.componentName&&"valueToRecordOnSubmit"in e.stateValues&&"valueRecordedAtSubmit"in e.stateValues&&i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"valueRecordedAtSubmit",value:e.stateValues.valueToRecordOnSubmit})}let o=await this.stateValues.currentResponses;i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"submittedResponses",value:o}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"submittedResponsesComponentType",value:this.state.currentResponses.shadowingInstructions.createComponentOfType}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"justSubmitted",value:!0}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"creditAchievedDependenciesAtSubmit",value:await this.stateValues.creditAchievedDependencies}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"nSubmissions",value:await this.stateValues.nSubmissions+1});for(let e of await this.stateValues.awardChildren){let t=r.includes(e.componentName);i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"awarded",value:t}),i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"creditAchieved",value:e.stateValues.creditAchievedIfSubmit}),i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"fractionSatisfied",value:e.stateValues.fractionSatisfiedIfSubmit})}let l=[];for(let e of o)if(e.toString)try{l.push(e.toString())}catch(e){l.push("_")}else l.push(e);return i.push({updateType:"recordItemSubmission",itemNumber:await this.stateValues.inItemNumber,submittedComponent:this.componentName,response:o,responseText:l,creditAchieved:n}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:{verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType},result:{response:o,responseText:l,creditAchieved:n}},suppressToast:await this.stateValues.suppressToast}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}}class Award extends BaseComponent{static componentType="award";static rendererType=void 0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static variableForPlainMacro="awarded";static variableForPlainCopy="awarded";static createAttributesObject(){let e=super.createAttributesObject();return e.credit={createComponentOfType:"number",createStateVariable:"credit",defaultValue:1,public:!0,attributesForCreatedComponent:{convertBoolean:!0}},e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"},e.symbolicEquality={createComponentOfType:"boolean",createStateVariable:"symbolicEquality",defaultValue:!1,public:!0,fallBackToParentStateVariable:"symbolicEquality"},e.expandOnCompare={createComponentOfType:"boolean",createStateVariable:"expandOnCompare",defaultValue:!1,public:!0,fallBackToParentStateVariable:"expandOnCompare"},e.simplifyOnCompare={createComponentOfType:"text",createStateVariable:"simplifyOnCompare",defaultValue:"none",toLowerCase:!0,valueTransformations:{"":"full",true:"full"},validValues:["none","full","numbers","numberspreserveorder"],public:!0,fallBackToParentStateVariable:"simplifyOnCompare"},e.unorderedCompare={createComponentOfType:"boolean",createStateVariable:"unorderedCompare",defaultValue:!1,public:!0,fallBackToParentStateVariable:"unorderedCompare"},e.matchByExactPositions={createComponentOfType:"boolean",createStateVariable:"matchByExactPositions",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchByExactPositions"},e.allowedErrorInNumbers={createComponentOfType:"number",createStateVariable:"allowedErrorInNumbers",defaultValue:0,public:!0,fallBackToParentStateVariable:"allowedErrorInNumbers"},e.includeErrorInNumberExponents={createComponentOfType:"boolean",createStateVariable:"includeErrorInNumberExponents",defaultValue:!1,public:!0,fallBackToParentStateVariable:"includeErrorInNumberExponents"},e.allowedErrorIsAbsolute={createComponentOfType:"boolean",createStateVariable:"allowedErrorIsAbsolute",defaultValue:!1,public:!0,fallBackToParentStateVariable:"allowedErrorIsAbsolute"},e.nSignErrorsMatched={createComponentOfType:"number",createStateVariable:"nSignErrorsMatched",defaultValue:0,public:!0,fallBackToParentStateVariable:"nSignErrorsMatched"},e.nPeriodicSetMatchesRequired={createComponentOfType:"integer",createStateVariable:"nPeriodicSetMatchesRequired",defaultValue:3,public:!0,fallBackToParentStateVariable:"nPeriodicSetMatchesRequired"},e.caseInsensitiveMatch={createComponentOfType:"boolean",createStateVariable:"caseInsensitiveMatch",defaultValue:!1,public:!0,fallBackToParentStateVariable:"caseInsensitiveMatch"},e.matchBlanks={createComponentOfType:"boolean",createStateVariable:"matchBlanks",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchBlanks"},e.feedbackCodes={createComponentOfType:"textList",createStateVariable:"feedbackCodes",defaultValue:[],public:!0},e.feedbackText={createComponentOfType:"text",createStateVariable:"feedbackText",defaultValue:null,public:!0},e.sourcesAreResponses={createPrimitiveOfType:"string"},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e}static preprocessSerializedChildren({serializedChildren:e,attributes:t,componentName:n}){if(t.sourcesAreResponses){let r,a=t.sourcesAreResponses.primitive.split(/\s+/).filter((e=>e));r=t.newNamespace?.primitive?n+"/":getNamespaceFromName(n);for(let t of a){let n;if("/"===t[0])n=t;else if("../"===t.slice(0,3)){let e=getNamespaceFromName(r.slice(0,r.length-1)),a=t.slice(3);for(;"../"===a.slice(0,3);){if("/"===e){n=null;break}e=getNamespaceFromName(e.slice(0,e.length-1)),a=a.slice(3)}null!==n&&(n=e+a)}else n=r+t;addResponsesToDescendantsWithTarget(e,t,n)}}}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,parentAttributes:t,componentInfoObjects:n}){for(;"string"==typeof e[0]&&""===e[0].trim();)e=e.slice(1);let r=e.length;for(;"string"==typeof e[r-1]&&""===e[r-1].trim();)r=(e=e.slice(0,r-1)).length;if(1===e.length&&"object"==typeof e[0])return{success:!1};let a,i=n.componentIsSpecifiedType,s=!1,o=!1,l=!1;for(let t of e)"object"==typeof t&&(i(t,"math")||i(t,"number")||i(t,"mathList")||i(t,"numberList")?s=!0:i(t,"text")||i(t,"textList")?o=!0:(i(t,"boolean")||i(t,"booleanList"))&&(l=!0));return t.type?(a=t.type,["math","text","boolean"].includes(a)||(console.warn(`Invalid type ${a}`),a="math")):a=s?"math":o?"text":l?"boolean":"math",{success:!0,newChildren:[{componentType:a,children:e}]}}}),e}static returnChildGroups(){return[{group:"whens",componentTypes:["when"]},{group:"maths",componentTypes:["math"]},{group:"numbers",componentTypes:["number"]},{group:"texts",componentTypes:["text"]},{group:"booleans",componentTypes:["boolean"]},{group:"mathLists",componentTypes:["mathList"]},{group:"numberLists",componentTypes:["numberList"]},{group:"textLists",componentTypes:["textList"]},{group:"booleanLists",componentTypes:["booleanList"]},{group:"otherComparableTypes",componentTypes:["orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.parsedExpression={additionalStateVariablesDefined:["requireInputInAnswer"],returnDependencies:()=>({whenChild:{dependencyType:"child",childGroups:["whens"]},typeChildren:{dependencyType:"child",childGroups:["maths","numbers","texts","booleans","mathLists","numberLists","textLists","booleanLists","otherComparableTypes"]}}),definition:function({dependencyValues:e}){let t=null,n=!1;return 0==e.whenChild.length&&e.typeChildren.length>0&&(n=!0,t=me$3.fromAst(["=","comp1","comp2"])),{setValue:{parsedExpression:t,requireInputInAnswer:n}}}},e.creditAchievedIfSubmit={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"fractionSatisfiedIfSubmit",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({credit:{dependencyType:"stateVariable",variableName:"credit"},whenChild:{dependencyType:"child",childGroups:["whens"],variableNames:["fractionSatisfied"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value","unordered"]},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},textChild:{dependencyType:"child",childGroups:["texts"],variableNames:["value"]},booleanChild:{dependencyType:"child",childGroups:["booleans"],variableNames:["value"]},mathListChild:{dependencyType:"child",childGroups:["mathLists"],variableNames:["maths","unordered"]},numberListChild:{dependencyType:"child",childGroups:["numberLists"],variableNames:["numbers","unordered"]},textListChild:{dependencyType:"child",childGroups:["textLists"],variableNames:["texts","unordered"]},booleanListChild:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["booleans","unordered"]},otherComparableChild:{dependencyType:"child",childGroups:["otherComparableTypes"],variableNames:["value"]},answerInput:{dependencyType:"parentStateVariable",variableName:"inputChildWithValues"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"},symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n;if(e.whenChild.length>0)n=e.whenChild[0].stateValues.fractionSatisfied;else{if(!e.answerInput||!e.parsedExpression)return{setValue:{creditAchievedIfSubmit:0,fractionSatisfiedIfSubmit:0}};n=evaluateLogicDirectlyFromChildren({dependencyValues:e,usedDefault:t})}n=Math.max(0,Math.min(1,n));let r=0;return Number.isFinite(e.credit)&&(r=Math.max(0,Math.min(1,e.credit))*n),{setValue:{fractionSatisfiedIfSubmit:n,creditAchievedIfSubmit:r}}}},e.fractionSatisfied={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{fractionSatisfied:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"fractionSatisfied",value:e.fractionSatisfied}]}:{success:!1}}},e.creditAchieved={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchieved:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"creditAchieved",value:e.creditAchieved}]}:{success:!1}}},e.awarded={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{awarded:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"awarded",value:e.awarded}]}:{success:!1}}},e.allFeedbacks={returnDependencies:()=>({feedbackText:{dependencyType:"stateVariable",variableName:"feedbackText"},feedbackCodes:{dependencyType:"stateVariable",variableName:"feedbackCodes"},feedbackDefinitionAncestor:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},awarded:{dependencyType:"stateVariable",variableName:"awarded"}}),definition:function({dependencyValues:e}){if(!e.awarded)return{setValue:{allFeedbacks:[]}};let t=[],n=e.feedbackDefinitionAncestor.stateValues.feedbackDefinitions;for(let r of e.feedbackCodes){let e=n[r.toLowerCase()];e&&t.push(e)}return null!==e.feedbackText&&t.push(e.feedbackText),{setValue:{allFeedbacks:t}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n0?n.textChildrenByCode.comp2=e.textChild[0]:e.mathChild.length>0?n.mathChildrenByCode.comp2=e.mathChild[0]:e.numberChild.length>0?n.numberChildrenByCode.comp2=e.numberChild[0]:e.booleanChild.length>0?n.booleanChildrenByCode.comp2=e.booleanChild[0]:e.textListChild.length>0?n.textListChildrenByCode.comp2=e.textListChild[0]:e.mathListChild.length>0?n.mathListChildrenByCode.comp2=e.mathListChild[0]:e.numberListChild.length>0?n.numberListChildrenByCode.comp2=e.numberListChild[0]:e.booleanListChild.length>0?n.booleanListChildrenByCode.comp2=e.booleanListChild[0]:e.otherComparableChild.length>0&&(n.otherChildrenByCode.comp2=e.otherComparableChild[0]);let a=e.answerInput.stateValues.immediateValue;void 0===a&&(a=e.answerInput.stateValues.value);let i={stateValues:{value:a}};return"textInput"===e.answerInput.componentType?n.textChildrenByCode.comp1=i:"booleanInput"===e.answerInput.componentType?n.booleanChildrenByCode.comp1=i:n.mathChildrenByCode.comp1=i,evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:r,dependencyValues:n})}function addResponsesToDescendantsWithTarget(e,t,n){for(let r of e){let e=r.props;if(e&&0!==Object.keys(e).length||(e=r.doenetAttributes),e)for(let a in e)if("target"===a.toLowerCase()&&e[a]===t||"targetcomponentname"===a.toLowerCase()&&e[a]===n){r.attributes||(r.attributes={});let e=Object.keys(r.attributes).map((e=>e.toLowerCase())).includes("isresponse");e||(r.attributes.isResponse=!0)}r.children&&addResponsesToDescendantsWithTarget(r.children,t,n)}}class When extends BooleanComponent{static componentType="when";static rendererType=void 0;static stateVariableForAttributeValue="conditionSatisfied";static createAttributesObject(){let e=super.createAttributesObject();e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"};for(let t of["symbolicEquality","expandOnCompare","simplifyOnCompare","unorderedCompare","matchByExactPositions","allowedErrorInNumbers","includeErrorInNumberExponents","allowedErrorIsAbsolute","nSignErrorsMatched","nPeriodicSetMatchesRequired","caseInsensitiveMatch","matchBlanks"])e[t].fallBackToParentStateVariable=t;return e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},additionalStateVariablesDefined:[{variableName:"fractionSatisfied",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"conditionSatisfied",public:!0,shadowingInstructions:{createComponentOfType:"boolean"}}],returnDependencies:()=>({matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"},symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},booleanListChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanListChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},textListChildrenByCode:{dependencyType:"stateVariable",variableName:"textListChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},mathListChildrenByCode:{dependencyType:"stateVariable",variableName:"mathListChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},numberListChildrenByCode:{dependencyType:"stateVariable",variableName:"numberListChildrenByCode"},otherChildrenByCode:{dependencyType:"stateVariable",variableName:"otherChildrenByCode"}}),definition({dependencyValues:e,usedDefault:t}){if(null===e.parsedExpression)return{setValue:{conditionSatisfied:!1,value:!1,fractionSatisfied:0}};let n=t.unorderedCompare,r=evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:n,dependencyValues:e}),a=1===r;return{setValue:{fractionSatisfied:r,conditionSatisfied:a,value:a}}}},e}}class MathInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateRawValue:this.updateRawValue.bind(this),updateValue:this.updateValue.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="mathInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"math",createStateVariable:"prefill",defaultValue:me$3.fromAst("_"),public:!0,copyComponentAttributesForCreatedComponent:["format","functionSymbols","splitSymbols","parseScientificNotation"]},e.prefillLatex={createComponentOfType:"latex",createStateVariable:"prefillLatex",defaultValue:"",public:!0},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"math"},e.unionFromU={createComponentOfType:"boolean",createStateVariable:"unionFromU",defaultValue:!1,public:!0},e.hideNaN={createComponentOfType:"boolean",createStateVariable:"hideNaN",defaultValue:!0,public:!0},e.removeStrings={createComponentOfType:"textList",createStateVariable:"removeStrings",defaultValue:null},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){return 0===e.length?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLatex:{dependencyType:"stateVariable",variableName:"prefillLatex"},unionFromU:{dependencyType:"stateVariable",variableName:"unionFromU"},functionSymbols:{dependencyType:"stateVariable",variableName:"functionSymbols"},splitSymbols:{dependencyType:"stateVariable",variableName:"splitSymbols"},parseScientificNotation:{dependencyType:"stateVariable",variableName:"parseScientificNotation"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,usedDefault:t}){return e.mathChild.length>0?{setValue:{value:e.mathChild[0].stateValues.value}}:e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{get defaultValue(){return!t.prefill||t.prefillLatex?e.prefill:calculateMathExpressionFromLatex({latex:e.prefillLatex,unionFromU:e.unionFromU,functionSymbols:e.functionSymbols,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation})}}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.mathChild.length>0?{success:!0,instructions:[{setDependency:"mathChild",desiredValue:e.value,variableIndex:0,childIndex:0}]}:t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n,usedDefault:r}){return!t.value||n||r.value?{useEssentialOrDefaultValue:{immediateValue:{defaultValue:e.value}}}:{setValue:{immediateValue:e.value},setEssentialValue:{immediateValue:e.value}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.valueForDisplay.toString()}}}},e.dontUpdateRawValueInDefinition={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{dontUpdateRawValueInDefinition:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"dontUpdateRawValueInDefinition",value:e.dontUpdateRawValueInDefinition}]})},e.rawRendererValue={forRenderer:!0,hasEssential:!0,shadowVariable:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"lastValueForDisplay",hasEssential:!0,shadowVariable:!0,defaultValue:null,set:convertValueToMathExpression}],returnDependencies:()=>({immediateValue:{dependencyType:"stateVariable",variableName:"immediateValue"},valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},hideNaN:{dependencyType:"stateVariable",variableName:"hideNaN"},dontUpdateRawValueInDefinition:{dependencyType:"stateVariable",variableName:"dontUpdateRawValueInDefinition"},prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLatex:{dependencyType:"stateVariable",variableName:"prefillLatex"}}),definition({dependencyValues:e,essentialValues:t,justUpdatedForNewComponent:n,usedDefault:r}){if(void 0!==t.rawRendererValue&&(n||deepCompare(t.lastValueForDisplay.tree,e.valueForDisplay.tree)||e.dontUpdateRawValueInDefinition))return{useEssentialOrDefaultValue:{rawRendererValue:!0,lastValueForDisplay:!0}};{let t;return t=r.immediateValue&&r.prefill&&!r.prefillLatex?stripLatex(e.prefillLatex):stripLatex(e.valueForDisplay.toLatex({showBlanks:!1})),e.hideNaN&&"NaN"===t&&(t=""),{setValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay},setEssentialValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay}}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t,essentialValues:n,dependencyValues:r,componentName:a}){let i=[];if("string"==typeof e.rawRendererValue){let r=n.rawRendererValue,a=e.rawRendererValue;r!==a&&i.push({setEssentialValue:"rawRendererValue",value:a});let s=await t.unionFromU,o=await t.functionSymbols,l=await t.splitSymbols,u=await t.parseScientificNotation,c=await t.removeStrings,p=calculateMathExpressionFromLatex({latex:r,unionFromU:s,functionSymbols:o,splitSymbols:l,parseScientificNotation:u,removeStrings:c}),d=calculateMathExpressionFromLatex({latex:a,unionFromU:s,functionSymbols:o,splitSymbols:l,parseScientificNotation:u,removeStrings:c});deepCompare(d.tree,p.tree)||i.push({setDependency:"immediateValue",desiredValue:d,treatAsInitialChange:!0})}else if(e.rawRendererValue instanceof me$3.class){i.push({setEssentialValue:"lastValueForDisplay",value:e.rawRendererValue});let a=await t.unionFromU,s=await t.functionSymbols,o=await t.splitSymbols,l=await t.parseScientificNotation,u=await t.removeStrings,c=calculateMathExpressionFromLatex({latex:n.rawRendererValue,unionFromU:a,functionSymbols:s,splitSymbols:o,parseScientificNotation:l,removeStrings:u});if(!deepCompare(e.rawRendererValue.tree,c.tree)){let t=stripLatex(e.rawRendererValue.toLatex({showBlanks:!1}));r.hideNaN&&"NaN"===t&&(t=""),i.push({setEssentialValue:"rawRendererValue",value:t})}}else e.lastValueForDisplay instanceof me$3.class&&i.push({setEssentialValue:"lastValueForDisplay",value:e.lastValueForDisplay});return{success:!0,instructions:i}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"math"}})},e}async updateRawValue({rawRendererValue:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],transient:!0,actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.immediateValue;if(!deepCompare((await this.stateValues.value).tree,t.tree)){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"dontUpdateRawValueInDefinition",value:!0},{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"dontUpdateRawValueInDefinition",value:!1},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}];"_"!==t.tree?n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"valueForDisplay"}):n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"lastValueForDisplay",valueOfStateVariable:"valueForDisplay"});let r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:e})}}static adapters=[{stateVariable:"value",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]}]}function calculateMathExpressionFromLatex({latex:e,unionFromU:t,functionSymbols:n,splitSymbols:r,parseScientificNotation:a,removeStrings:i}){let s;if(i)for(let t of i)["$","%"].includes(t)&&(t="\\"+t),e=e.replaceAll(t,"");e=normalizeLatexString(e,{unionFromU:t});let o=getFromLatex({functionSymbols:n,splitSymbols:r,parseScientificNotation:a});try{s=o(e)}catch(e){s=me$3.fromAst("_")}return s}class Textinput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateImmediateValue:this.updateImmediateValue.bind(this),updateValue:this.updateValue.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="textInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e.size={createComponentOfType:"number",createStateVariable:"size",defaultValue:10,forRenderer:!0,public:!0},e.bindValueTo={createComponentOfType:"text"},e.expanded={createComponentOfType:"boolean",createStateVariable:"expanded",defaultValue:!1,forRenderer:!0,public:!0},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:600,isAbsolute:!0},forRenderer:!0,public:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:120,isAbsolute:!0},forRenderer:!0,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.value&&!n?{setValue:{immediateValue:e.value},setEssentialValue:{immediateValue:e.value}}:{useEssentialOrDefaultValue:{immediateValue:{defaultValue:e.value}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"text"}})},e}async updateImmediateValue({text:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],transient:!0,actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(!await this.stateValues.disabled){let t=await this.stateValues.immediateValue;if(await this.stateValues.value!==t){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}],r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}}this.coreFunctions.resolveAction({actionId:e})}}class BooleanInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateBoolean:this.updateBoolean.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="booleanInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"boolean",createStateVariable:"prefill",defaultValue:!1,public:!0},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.asToggleButton={createComponentOfType:"boolean",createStateVariable:"asToggleButton",defaultValue:!1,forRenderer:!0,public:!0},e.bindValueTo={createComponentOfType:"boolean"},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value?"true":"false"}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"boolean"}})},e}static adapters=["value"];async updateBoolean({boolean:e,actionId:t}){if(!await this.stateValues.disabled){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],r={verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:e,responseText:e.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,event:r,actionId:t}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:t})}}class Choiceinput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateSelectedIndices:this.updateSelectedIndices.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="choiceInput";static renderChildren=!0;static variableForPlainMacro="values";static variableForPlainCopy="values";static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.selectMultiple={createComponentOfType:"boolean",createStateVariable:"selectMultiple",defaultValue:!1,public:!0,forRenderer:!0,fallBackToParentStateVariable:"selectMultiple"},e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"},e.inline={createComponentOfType:"boolean"},e.shuffleOrder={createPrimitiveOfType:"boolean",createStateVariable:"shuffleOrder",defaultValue:!1,public:!0},e.preselectChoice={createComponentOfType:"number",createStateVariable:"preselectChoice",defaultValue:null},e.bindValueTo={createComponentOfType:"text"},e.placeHolder={createComponentOfType:"text",createStateVariable:"placeHolder",defaultValue:"",forRenderer:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0,fallBackToParentStateVariable:"submitLabel"},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0,fallBackToParentStateVariable:"submitLabelNoCorrectness"},e}static returnChildGroups(){return[{group:"choices",componentTypes:["choice"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.inline={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,returnDependencies:()=>({inlineAttr:{dependencyType:"attributeComponent",attributeName:"inline",variableNames:["value"]},parentInline:{dependencyType:"parentStateVariable",variableName:"inline"}}),definition:({dependencyValues:e})=>e.inlineAttr?{setValue:{inline:e.inlineAttr.stateValues.value}}:null!==e.parentInline?{setValue:{inline:e.parentInline}}:{useEssentialOrDefaultValue:{inline:{}}}},e.numberChoices={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"]}}),definition:({dependencyValues:e})=>({setValue:{numberChoices:e.choiceChildren.length}})},e.choiceOrder={forRenderer:!0,shadowVariable:!0,returnDependencies:({sharedParameters:e})=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},shuffleOrder:{dependencyType:"stateVariable",variableName:"shuffleOrder"},variantSeed:{dependencyType:"value",value:e.variantSeed},rngClass:{dependencyType:"value",value:e.rngClass,doNotProxy:!0},variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){let t,n=e.choiceChildren.length;if(e.shuffleOrder){let r=e.variants?.desiredVariant?.indices;if(void 0!==r)if(r.length!==n)console.warn("Ignoring indices specified for choiceInput as number of indices doesn't match number of choice children.");else{if(r=r.map(Number),!r.every(Number.isInteger))throw Error("All indices specified for choiceInput must be integers");if(r.every((e=>e>=1&&e<=n)))return{setValue:{choiceOrder:r}};console.warn("Ignoring indices specified for choiceInput as some indices out of range.")}let a=e.rngClass(e.variantSeed+"co");t=[...Array(n).keys()].map((e=>e+1));for(let e=n-1;e>0;e--){const n=a(),r=Math.floor(n*(e+1));[t[e],t[r]]=[t[r],t[e]]}}else t=[...Array(n).keys()].map((e=>e+1));return{setValue:{choiceOrder:t}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({componentInfoObjects:e,sharedParameters:t})=>({variantSeed:{dependencyType:"value",value:t.variantSeed},choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},shuffleOrder:{dependencyType:"stateVariable",variableName:"shuffleOrder"},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(e.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}};e.shuffleOrder&&(n.indices=e.choiceOrder);let r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e.choiceChildrenOrdered={additionalStateVariablesDefined:[{variableName:"numberChoices",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"]}}),definition:function({dependencyValues:e}){let t=e.choiceChildren.length,n=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceChildrenOrdered:n,numberChoices:t}}}},e.choiceTexts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["choiceText"],forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceTexts:t.map((e=>e.stateValues.text))}}}},e.choiceMaths={public:!0,shadowingInstructions:{createComponentOfType:"math"},isArray:!0,entryPrefixes:["choiceMath"],forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["math"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceMaths:t.map((e=>e.stateValues.math))}}}},e.choicePreselects={isArray:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["preSelect"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicePreselects:t.map((e=>e.stateValues.preSelect))}}}},e.choicesDisabled={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["disabled"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicesDisabled:t.map((e=>e.stateValues.disabled))}}}},e.choicesHidden={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["hidden"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicesHidden:t.map((e=>e.stateValues.hidden))}}}},e.componentType={returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["math"]}}),definition({dependencyValues:e}){let t="text";return e.choiceChildren.length>0&&e.choiceChildren.every((e=>e.stateValues.math))&&(t="math"),{setValue:{componentType:t}}}},e.indicesMatchedByBoundValue={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},selectMultiple:{dependencyType:"stateVariable",variableName:"selectMultiple"}}),definition({dependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));if(null!==e.bindValueTo){let n=t.map((e=>e.stateValues.text.toLowerCase().trim()));if(e.bindValueTo.stateValues.value){if(e.selectMultiple){let t=e.bindValueTo.stateValues.value.toLowerCase().split(",").map((e=>e.trim())),r=[];for(let e of t){let t=n.indexOf(e);-1===t||r.includes(t+1)||r.push(t+1)}return r.sort(((e,t)=>e-t)),{setValue:{indicesMatchedByBoundValue:r}}}{let t=n.indexOf(e.bindValueTo.stateValues.value.toLowerCase().trim());if(-1!==t)return{setValue:{indicesMatchedByBoundValue:[t+1]}}}}}return{setValue:{indicesMatchedByBoundValue:[]}}}},e.allSelectedIndices={hasEssential:!0,returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},indicesMatchedByBoundValue:{dependencyType:"stateVariable",variableName:"indicesMatchedByBoundValue"},preselectChoice:{dependencyType:"stateVariable",variableName:"preselectChoice"},choicePreselects:{dependencyType:"stateVariable",variableName:"choicePreselects"},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]}}),definition:({dependencyValues:e})=>null!==e.bindValueTo?{setValue:{allSelectedIndices:e.indicesMatchedByBoundValue}}:{useEssentialOrDefaultValue:{allSelectedIndices:{get defaultValue(){let t=e.choicePreselects.indexOf(!0);return-1!==t?[t+1]:null!==e.preselectChoice?[e.preselectChoice]:[]}}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(null===t.bindValueTo)return{success:!0,instructions:[{setEssentialValue:"allSelectedIndices",value:e.allSelectedIndices}]};{let n="";if(e.allSelectedIndices.length>0){let r=t.choiceOrder.map((e=>t.choiceChildren[e-1])),a=[];for(let t of e.allSelectedIndices){let e=r[t-1];e&&a.push(e.stateValues.text)}n=a.join(", ")}return{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:n,variableIndex:0}]}}}},e.nSelectedIndices={returnDependencies:()=>({allSelectedIndices:{dependencyType:"stateVariable",variableName:"allSelectedIndices"}}),definition:({dependencyValues:e})=>({setValue:{nSelectedIndices:e.allSelectedIndices.length}})},e.selectedIndices={public:!0,shadowingInstructions:{createComponentOfType:"number"},isArray:!0,entryPrefixes:["selectedIndex"],forRenderer:!0,returnArraySizeDependencies:()=>({nSelectedIndices:{dependencyType:"stateVariable",variableName:"nSelectedIndices"}}),returnArraySize:({dependencyValues:e})=>[e.nSelectedIndices],returnArrayDependenciesByKey:()=>({globalDependencies:{allSelectedIndices:{dependencyType:"stateVariable",variableName:"allSelectedIndices"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n in e.allSelectedIndices)t[n]=e.allSelectedIndices[n];return{setValue:{selectedIndices:t}}}},e.selectedIndex={isAlias:!0,targetVariableName:"selectedIndex1"},e.selectedValues={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["selectedValue"],returnArraySizeDependencies:()=>({nSelectedIndices:{dependencyType:"stateVariable",variableName:"nSelectedIndices"}}),returnArraySize:({dependencyValues:e})=>[e.nSelectedIndices],returnArrayDependenciesByKey:()=>({globalDependencies:{selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},choiceTexts:{dependencyType:"stateVariable",variableName:"choiceTexts"},choiceMaths:{dependencyType:"stateVariable",variableName:"choiceMaths"},componentType:{dependencyType:"stateVariable",variableName:"componentType"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={},r=e.componentType;for(let a of t)n[a]="math"===r?e.choiceMaths[e.selectedIndices[a]-1]:e.choiceTexts[e.selectedIndices[a]-1];return{setValue:{selectedValues:n},setCreateComponentOfType:{selectedValues:r}}}},e.selectedValue={isAlias:!0,targetVariableName:"selectedValue1"},e.values={isAlias:!0,targetVariableName:"selectedValues"},e.nValues={isAlias:!0,targetVariableName:"nSelectedIndices"},e.childIndicesSelected={returnDependencies:()=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"}}),definition({dependencyValues:e}){let t=e.selectedIndices.map((t=>e.choiceOrder[t-1]));return{setValue:{childIndicesSelected:t}}}},e.creditAchievedIfSubmit={returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["selected","credit"]},selectMultiple:{dependencyType:"stateVariable",variableName:"selectMultiple"},matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"}}),definition:function({dependencyValues:e}){let t=0;if(e.selectMultiple){let n=0,r=0,a=0;for(let t of e.choiceChildren)t.stateValues.selected?1===t.stateValues.credit?n++:r++:1===t.stateValues.credit&&a++;if(e.matchPartial){let e=n+r+a;t=0===e?1:n/e}else r+a===0&&(t=1)}else for(let n of e.choiceChildren)if(n.stateValues.selected){t=n.stateValues.credit;break}return{setValue:{creditAchievedIfSubmit:t}}}},e.valueToRecordOnSubmit={isAlias:!0,targetVariableName:"selectedIndices"},e.submittedIndices={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["submitted"]}}),definition({dependencyValues:e}){let t=[],n=e.choiceOrder.map((t=>e.choiceChildren[t-1]));for(let[e,r]of n.entries())r.stateValues.submitted&&t.push(e+1);return{setValue:{submittedIndices:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=[];for(let[r,a]of t.choiceOrder.entries())n.push({setDependency:"choiceChildren",desiredValue:e.submittedIndices.includes(r+1),variableIndex:0,childIndex:a-1});return{success:!0,instructions:n}}},e.valueRecordedAtSubmit={isAlias:!0,targetVariableName:"submittedIndices"},e.allFeedbacks={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["feedbacks"]}}),definition({dependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1])),n=[];for(let e of t)n.push(...e.stateValues.feedbacks);return{setValue:{allFeedbacks:n}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;nr[e-1]))}},i=await this.stateValues.answerAncestor;return i&&(a.context={answerAncestor:i.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:t,event:a}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n})}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){if(!e.attributes?.shuffleOrder?.primitive)return super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});let n=0;for(let r of e.children)if("choice"===r.componentType)n++;else{if(!t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})||"choice"!==r.attributes.createComponentOfType?.primitive)return{success:!1};if(void 0!==r.attributes.nComponents?.primitive){let e=Number(r.attributes.nComponents?.primitive);if(!(Number.isInteger(e)&&e>=0))return{success:!1};n+=e}else n++}let r=1;for(let e=2;e<=n;e++)r*=e;let a=super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!a.success)return{success:!1};let i=a.numberOfVariants*r;return e.variants.numberOfVariants=i,e.variants.uniqueVariantData={numberOfVariantsByDescendant:e.variants.uniqueVariantData.numberOfVariantsByDescendant,numberOfPermutations:r,numberOfChoices:n},{success:!0,numberOfVariants:i}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};if(!e.attributes.shuffleOrder?.primitive)return super.getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n});let a=e.variants.uniqueVariantData.numberOfVariantsByDescendant,i=e.variants.descendantVariantComponents,s=e.variants.uniqueVariantData.numberOfPermutations,o=e.variants.uniqueVariantData.numberOfChoices,l=[...a];l.push(s);let u=enumerateCombinations({numberOfOptionsByIndex:l,maxNumber:t})[t-1].map((e=>e+1)),c=u.pop(),p=u,d=[...Array(o).keys()].map((e=>e+1)),m=enumeratePermutations({values:d,maxNumber:c})[c-1],h=!1,f=[];for(let e=0;e1){let t=i[e],r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:p[e],componentInfoObjects:n});if(!r.success)return{success:!1};f.push(r.desiredVariant),h=!0}else f.push({});let y={indices:m};return h&&(y.subvariants=f),{success:!0,desiredVariant:y}}}class Choice extends InlineComponent{static componentType="choice";static rendererType="containerInline";static renderChildren=!0;static variableForPlainMacro="submitted";static variableForPlainCopy="submitted";static createAttributesObject(){let e=super.createAttributesObject();return e.credit={createComponentOfType:"number",createStateVariable:"credit",defaultValue:0,public:!0,attributesForCreatedComponent:{convertBoolean:!0}},e.feedbackCodes={createComponentOfType:"textList",createStateVariable:"feedbackCodes",defaultValue:[],public:!0},e.feedbackText={createComponentOfType:"text",createStateVariable:"feedbackText",defaultValue:null,public:!0},e.preSelect={createComponentOfType:"boolean",createStateVariable:"preSelect",defaultValue:!1},e}static returnChildGroups(){return[{group:"children",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["children"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{text:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["children"],variableNames:["value","latex"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=null;if(1===e.inlineChildren.length){let n=e.inlineChildren[0];if("object"==typeof n){let e=n.stateValues.value;if(e instanceof me$3.class)t=e;else if("number"==typeof e)t=me$3.fromAst(e);else if("string"==typeof n.stateValues.latex)try{t=me$3.fromLatex(n.stateValues.latex)}catch(e){}}}return{setValue:{math:t}}}},e.selected={defaultValue:!1,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({countAmongSiblings:{dependencyType:"countAmongSiblingsOfSameType"},childIndicesSelected:{dependencyType:"parentStateVariable",parentComponentType:"choiceInput",variableName:"childIndicesSelected"},primaryShadow:{dependencyType:"primaryShadow",variableNames:["selected"]}}),definition({dependencyValues:e,componentName:t}){let n;return n=e.childIndicesSelected?e.childIndicesSelected.includes(e.countAmongSiblings):!!e.primaryShadow&&e.primaryShadow.stateValues.selected,{setValue:{selected:n}}}},e.submitted={defaultValue:!1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},doNotShadowEssential:!0,returnDependencies:()=>({primaryShadow:{dependencyType:"primaryShadow",variableNames:["submitted"]}}),definition:({dependencyValues:e})=>e.primaryShadow?{setValue:{submitted:e.primaryShadow.stateValues.submitted}}:{useEssentialOrDefaultValue:{submitted:!0}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.primaryShadow?{success:!1}:{success:!0,instructions:[{setEssentialValue:"submitted",value:e.submitted}]}}},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedbacktext"},returnDependencies:()=>({feedbackText:{dependencyType:"stateVariable",variableName:"feedbackText"},feedbackCodes:{dependencyType:"stateVariable",variableName:"feedbackCodes"},feedbackDefinitionAncestor:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},submitted:{dependencyType:"stateVariable",variableName:"submitted"}}),definition({dependencyValues:e}){if(!e.submitted)return{setValue:{feedbacks:[]}};let t=[],n=e.feedbackDefinitionAncestor.stateValues.feedbackDefinitions;for(let r of e.feedbackCodes){let e=n[r.toLowerCase()];e&&t.push(e)}return null!==e.feedbackText&&t.push(e.feedbackText),{setValue:{feedbacks:t}}}},e}static includeBlankStringChildren=!0;static adapters=["text","math"]}class NumberComponent extends InlineComponent{static componentType="number";static variableForPlainMacro="value";static createAttributesObject(){let e=super.createAttributesObject();return e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.renderAsMath={createComponentOfType:"boolean",createStateVariable:"renderAsMath",defaultValue:!1,public:!0,forRenderer:!0},e.convertBoolean={createPrimitiveOfType:"boolean",createStateVariable:"convertBoolean",defaultValue:!1},e.valueOnNaN={createPrimitiveOfType:"number",createStateVariable:"valueOnNaN",defaultValue:NaN},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/..+/,replacementFunction:({matchedChildren:e,componentAttributes:t})=>({success:!t.convertBoolean,newChildren:[{componentType:"math",children:e}]})}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"numbers",componentTypes:["number"]},{group:"maths",componentTypes:["math"]},{group:"texts",componentTypes:["text"]},{group:"booleans",componentTypes:["boolean"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displayDigits"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}let a=null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals,i=null===e.displayDigitsAttr||t.displayDigitsAttr,s=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!i&&!s){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displayDecimals"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}if(1===e.numberMathChildren.length&&0===e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].displayDecimals)return{setValue:{displayDecimals:e.numberMathChildren[0].stateValues.displayDecimals}};r=!0,n=e.numberMathChildren[0].stateValues.displayDecimals}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displaySmallAsZero"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}if(1===e.numberMathChildren.length&&0===e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].displaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberMathChildren[0].stateValues.displaySmallAsZero}};r=!0,n=e.numberMathChildren[0].stateValues.displaySmallAsZero}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["padZeros"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}if(1===e.numberMathChildren.length&&0==e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].padZeros)return{setValue:{padZeros:e.numberMathChildren[0].stateValues.padZeros}};r=!0,n=e.numberMathChildren[0].stateValues.padZeros}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.singleNumberOrStringChild={additionalStateVariablesDefined:["singleMathChild"],returnDependencies:()=>({numberChildren:{dependencyType:"child",childGroups:["numbers"]},stringChildren:{dependencyType:"child",childGroups:["strings"]},mathChildren:{dependencyType:"child",childGroups:["maths"]},booleanChildren:{dependencyType:"child",childGroups:["booleans"]},textChildren:{dependencyType:"child",childGroups:["texts"]}}),definition({dependencyValues:e}){let t=e.numberChildren.length+e.stringChildren.length,n=e.mathChildren.length,r=e.booleanChildren.length+e.textChildren.length;return{setValue:{singleNumberOrStringChild:t<=1&&n+r===0,singleMathChild:1===n&&t+r===0}}}},e.parsedExpression={additionalStateVariablesDefined:["codePre"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]}}),definition:buildParsedExpression},e.mathChildrenByCode={additionalStateVariablesDefined:["textChildrenByCode","numberChildrenByCode","booleanChildrenByCode"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"],variableNames:["value","texts","maths","booleans"],variablesOptional:!0},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n={},r={},a={},i={},s=0,o=e.codePre;for(let l of e.allChildren)if("string"!=typeof l){let e=o+s;t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"math"})?n[e]=l:t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"number"})?r[e]=l:t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"text"})?a[e]=l:i[e]=l,s+=1}return{setValue:{mathChildrenByCode:n,numberChildrenByCode:r,textChildrenByCode:a,booleanChildrenByCode:i}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},hasEssential:!0,stateVariablesDeterminingDependencies:["singleNumberOrStringChild"],returnDependencies:({stateValues:e})=>e.singleNumberOrStringChild?{singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},convertBoolean:{dependencyType:"stateVariable",variableName:"convertBoolean"},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},stringChild:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},valueOnNaN:{dependencyType:"stateVariable",variableName:"valueOnNaN"}}:{singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},singleMathChild:{dependencyType:"stateVariable",variableName:"singleMathChild"},convertBoolean:{dependencyType:"stateVariable",variableName:"convertBoolean"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"],variableNames:["value","texts","maths","unordered"],variablesOptional:!0},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},valueOnNaN:{dependencyType:"stateVariable",variableName:"valueOnNaN"}},definition({dependencyValues:e,componentInfoObjects:t}){if(e.singleNumberOrStringChild){if(0===e.numberChild.length){if(0===e.stringChild.length)return{useEssentialOrDefaultValue:{value:{defaultValue:e.valueOnNaN}}};let n=Number(e.stringChild[0]);if(Number.isNaN(n))try{if(n=me$3.fromAst(textToAst$1.convert(e.stringChild[0])).evaluate_to_constant(),"boolean"==typeof n)n=e.convertBoolean?n?1:0:e.valueOnNaN;else if(null===n||Number.isNaN(n))if(e.convertBoolean){n=evaluateLogic({logicTree:buildParsedExpression({dependencyValues:{stringChildren:e.stringChild,allChildren:e.stringChild},componentInfoObjects:t}).setValue.parsedExpression.tree,dependencyValues:{booleanChildrenByCode:{},booleanListChildrenByCode:{},textChildrenByCode:{},textListChildrenByCode:{},mathChildrenByCode:{},mathListChildrenByCode:{},numberChildrenByCode:{},numberListChildrenByCode:{},otherChildrenByCode:{}},valueOnInvalid:e.valueOnNaN})}else n=e.valueOnNaN;else n?.re===1/0||n?.re===-1/0||n?.im===1/0||n?.im===-1/0?n=numberToMathExpression(n).evaluate_to_constant():0===n?.im&&(n=n.re)}catch(t){n=e.valueOnNaN}return{setValue:{value:n}}}{let t=e.numberChild[0].stateValues.value;return Number.isNaN(t)&&(t=e.valueOnNaN),{setValue:{value:t}}}}if(null===e.parsedExpression)return{setValue:{value:e.valueOnNaN}};if(0===Object.keys(e.textChildrenByCode).length&&0===Object.keys(e.booleanChildrenByCode).length){let t,n=function(t){if("string"==typeof t){let n=e.mathChildrenByCode[t];return void 0!==n?n.stateValues.value.tree:(n=e.numberChildrenByCode[t],void 0!==n?numberToMathExpression(n.stateValues.value).tree:t)}return Array.isArray(t)?[t[0],...t.slice(1).map(n)]:t};try{t=me$3.fromAst(n(e.parsedExpression.tree)).evaluate_to_constant()}catch(n){t=e.valueOnNaN}if(!Number.isNaN(t)&&("number"==typeof t||"number"==typeof t?.re&&"number"==typeof t?.im))return t.re===1/0||t.re===-1/0||t.im===1/0||t.im===-1/0?t=numberToMathExpression(t).evaluate_to_constant():0===t.im&&(t=t.re),{setValue:{value:t}}}if(!e.convertBoolean)return{setValue:{value:e.valueOnNaN}};return(e=Object.assign({},e)).mathListChildrenByCode={},e.numberListChildrenByCode={},e.textListChildrenByCode={},e.booleanListChildrenByCode={},e.otherChildrenByCode={},{setValue:{value:evaluateLogic({logicTree:e.parsedExpression.tree,dependencyValues:e,valueOnInvalid:e.valueOnNaN})}}},set:function(e){if(null===e)return NaN;if("number"==typeof e||"number"==typeof e?.re&&"number"==typeof e?.im)return e;let t=Number(e);if(Number.isNaN(t))try{t=me$3.fromAst(textToAst$1.convert(e)).evaluate_to_constant(),null===t&&(t=NaN)}catch(e){t=NaN}return t},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,overrideFixed:r}){if(!await n.canBeModified&&!r)return{success:!1};let a,i=e.value;return i instanceof me$3.class?(i=i.evaluate_to_constant(),(Number.isNaN(i)||"number"!=typeof i&&("number"!=typeof i?.re||"number"!=typeof i?.im))&&(i=t.valueOnNaN)):(Number.isNaN(i)||"number"!=typeof i&&("number"!=typeof i?.re||"number"!=typeof i?.im))&&(i=Number(i),Number.isNaN(i)&&(i=t.valueOnNaN)),t.singleNumberOrStringChild?(a=0===t.numberChild.length?0===t.stringChild.length?[{setEssentialValue:"value",value:numberToMathExpression(i).evaluate_to_constant()}]:[{setDependency:"stringChild",desiredValue:numberToMathExpression(i).toString(),childIndex:0,variableIndex:0}]:[{setDependency:"numberChild",desiredValue:i,childIndex:0,variableIndex:0}],{success:!0,instructions:a}):t.singleMathChild?{success:!0,instructions:[{setDependency:"allChildren",desiredValue:numberToMathExpression(i),childIndex:0,variableIndex:0}]}:{success:!1}}},e.valueForDisplay={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:numberToMathExpression(e.value),dependencyValues:e,usedDefault:t}).evaluate_to_constant()}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{text:numberToMathExpression(e.valueForDisplay).toString(n)}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n=Number(e.text);if(Number.isFinite(n))return{success:!0,instructions:[{setDependency:"value",desiredValue:n}]};{let t,r=getFromText({parseScientificNotation:!1});try{t=r(e.text)}catch(e){return{success:!1}}return n=t.evaluate_to_constant(),Number.isFinite(n)?{success:!0,instructions:[{setDependency:"value",desiredValue:n}]}:{success:!1}}}},e.math=mathStateVariableFromNumberStateVariable({numberVariableName:"value",mathVariableName:"math",isPublic:!0}),e.math.shadowingInstructions.attributesToShadow=["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"}}),definition({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:numberToMathExpression(e.valueForDisplay).toLatex(n)}}}},e.canBeModified={returnDependencies:()=>({numberChildModifiable:{dependencyType:"child",childGroups:["numbers"],variableNames:["canBeModified"]},modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},singleMathChild:{dependencyType:"stateVariable",variableName:"singleMathChild"}}),definition:function({dependencyValues:e}){return!e.modifyIndirectly||e.fixed||!e.singleNumberOrStringChild&&!e.singleMathChild?{setValue:{canBeModified:!1}}:1!==e.numberChildModifiable.length||e.numberChildModifiable[0].stateValues.canBeModified?{setValue:{canBeModified:!0}}:{setValue:{canBeModified:!1}}}},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class Integer extends NumberComponent{static componentType="integer";static rendererType="number";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePreRound"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({valuePreRound:{dependencyType:"stateVariable",variableName:"valuePreRound"}}),set:function(e){if(null===e)return NaN;let t=Number(e);if(Number.isNaN(t))try{t=me$3.fromAst(textToAst.convert(e)).evaluate_to_constant(),null===t&&(t=NaN)}catch(e){t=NaN}return Math.round(t)},definition:({dependencyValues:e})=>({setValue:{value:Math.round(e.valuePreRound)}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.value;return t instanceof me$3.class?(t=t.evaluate_to_constant(),Number.isFinite(t)||(t=NaN)):t=Number(t),t=Math.round(t),{success:!0,instructions:[{setDependency:"valuePreRound",desiredValue:t}]}}},e}}const maxWidth=850,sizePossibilities=["tiny","small","medium","large","full"],widthFractions=[1/12,.3,.5,.7,1],fractionMidpoints=widthFractions.map(((e,t)=>(e+(widthFractions[t+1]||1/0))/2)),orderedWidthMidpoints=fractionMidpoints.map((e=>maxWidth*e)),orderedPercentWidthMidpoints=fractionMidpoints.map((e=>100*e)),widthsBySize={};sizePossibilities.forEach(((e,t)=>widthsBySize[e]=Math.floor(widthFractions[t]*maxWidth)));const percentWidthsBySize={};sizePossibilities.forEach(((e,t)=>percentWidthsBySize[e]=Math.round(100*widthFractions[t])));class Graph$1 extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{changeAxisLimits:this.changeAxisLimits.bind(this),addChildren:this.addChildren.bind(this),deleteChildren:this.deleteChildren.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="graph";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.xmin={createComponentOfType:"number",createStateVariable:"xminPrelim",defaultValue:-10},e.xmax={createComponentOfType:"number",createStateVariable:"xmaxPrelim",defaultValue:10},e.ymin={createComponentOfType:"number",createStateVariable:"yminPrelim",defaultValue:-10},e.ymax={createComponentOfType:"number",createStateVariable:"ymaxPrelim",defaultValue:10},e.width={createComponentOfType:"_componentSize"},e.size={createComponentOfType:"text"},e.aspectRatio={createComponentOfType:"number"},e.height={createComponentOfType:"_componentSize"},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",validValues:["block","inline"],defaultValue:"block",forRenderer:!0,public:!0},e.horizontalAlign={createComponentOfType:"text",createStateVariable:"horizontalAlign",validValues:["center","left","right"],defaultValue:"center",forRenderer:!0,public:!0},e.identicalAxisScales={createPrimitiveOfType:"boolean",createStateVariable:"identicalAxisScales",defaultValue:!1,public:!0},e.displayXAxis={createComponentOfType:"boolean",createStateVariable:"displayXAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxis={createComponentOfType:"boolean",createStateVariable:"displayYAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayXAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayXAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayYAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.xlabel={createComponentOfType:"label"},e.xlabelPosition={createComponentOfType:"text",createStateVariable:"xlabelPosition",defaultValue:"right",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["right","left"]},e.xTickScaleFactor={createComponentOfType:"math",createStateVariable:"xTickScaleFactor",defaultValue:null,public:!0,forRenderer:!0},e.ylabel={createComponentOfType:"label"},e.ylabelPosition={createComponentOfType:"text",createStateVariable:"ylabelPosition",defaultValue:"top",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["top","bottom"]},e.ylabelAlignment={createComponentOfType:"text",createStateVariable:"ylabelAlignment",defaultValue:"left",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["left","right"]},e.yTickScaleFactor={createComponentOfType:"math",createStateVariable:"yTickScaleFactor",defaultValue:null,public:!0,forRenderer:!0},e.showNavigation={createComponentOfType:"boolean",createStateVariable:"showNavigation",defaultValue:!0,public:!0,forRenderer:!0},e.fixAxes={createComponentOfType:"boolean",createStateVariable:"fixAxes",defaultValue:!1,public:!0,forRenderer:!0},e.grid={createComponentOfType:"text"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"xlabels",componentTypes:["xlabel"]},{group:"ylabels",componentTypes:["ylabel"]},{group:"graphical",componentTypes:["_graphical","text","image","math","m","md","label"]},{group:"childrenThatShouldNotBeHere",componentTypes:["_base"],matchAfterAdapters:!0}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({xlabelAttr:{dependencyType:"attributeComponent",attributeName:"xlabel",variableNames:["value","hasLatex"]},xlabelChild:{dependencyType:"child",childGroups:["xlabels"],variableNames:["value","hasLatex"]}}),definition({dependencyValues:e}){if(e.xlabelChild.length>0){let t=e.xlabelChild[e.xlabelChild.length-1];return{setValue:{xlabel:t.stateValues.value,xlabelHasLatex:t.stateValues.hasLatex}}}return e.xlabelAttr?{setValue:{xlabel:e.xlabelAttr.stateValues.value,xlabelHasLatex:e.xlabelAttr.stateValues.hasLatex}}:{useEssentialOrDefaultValue:{xlabel:!0},setValue:{xlabelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.xlabel)return{success:!1};if(t.xlabelChild.length>0){let n=t.xlabelChild.length-1;return{success:!0,instructions:[{setDependency:"xlabelChild",desiredValue:e.xlabel,childIndex:n,variableIndex:0}]}}return{success:!0,instructions:[{setEssentialValue:"xlabel",value:e.xlabel}]}}},e.ylabel={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"ylabelHasLatex"}}},hasEssential:!0,defaultValue:"",additionalStateVariablesDefined:[{variableName:"ylabelHasLatex",forRenderer:!0}],returnDependencies:()=>({ylabelAttr:{dependencyType:"attributeComponent",attributeName:"ylabel",variableNames:["value","hasLatex"]},ylabelChild:{dependencyType:"child",childGroups:["ylabels"],variableNames:["value","hasLatex"]}}),definition({dependencyValues:e}){if(e.ylabelChild.length>0){let t=e.ylabelChild[e.ylabelChild.length-1];return{setValue:{ylabel:t.stateValues.value,ylabelHasLatex:t.stateValues.hasLatex}}}return e.ylabelAttr?{setValue:{ylabel:e.ylabelAttr.stateValues.value,ylabelHasLatex:e.ylabelAttr.stateValues.hasLatex}}:{useEssentialOrDefaultValue:{ylabel:!0},setValue:{ylabelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.ylabel)return{success:!1};if(t.ylabelChild.length>0){let n=t.ylabelChild.length-1;return{success:!0,instructions:[{setDependency:"ylabelChild",desiredValue:e.ylabel,childIndex:n,variableIndex:0}]}}return{success:!0,instructions:[{setEssentialValue:"ylabel",value:e.ylabel}]}}},e.graphicalDescendants={forRenderer:!0,returnDependencies:()=>({graphicalDescendants:{dependencyType:"descendant",componentTypes:["_graphical"]}}),definition:function({dependencyValues:e}){return{setValue:{graphicalDescendants:e.graphicalDescendants}}}},e.childIndicesToRender={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"]},allChildren:{dependencyType:"child",childGroups:["graphical","xlabels","ylabels","childrenThatShouldNotBeHere"]}}),definition({dependencyValues:e}){let t=[],n=e.graphicalChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())n.includes(a.componentName)&&t.push(r);return{setValue:{childIndicesToRender:t}}}},e.nChildrenAdded={defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{nChildrenAdded:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nChildrenAdded",value:e.nChildrenAdded}]})},e.size={public:!0,defaultValue:"medium",hasEssential:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({sizeAttr:{dependencyType:"attributeComponent",attributeName:"size",variableNames:["value"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]}}),definition({dependencyValues:e}){const t="medium";if(e.sizeAttr){let n=e.sizeAttr.stateValues.value.toLowerCase();return sizePossibilities.includes(n)||(n=t),{setValue:{size:n}}}if(e.widthAttr){let n=e.widthAttr.stateValues.componentSize;if(null===n)return{setValue:{size:t}};let r,{isAbsolute:a,size:i}=n;if(a){for(let[e,t]of orderedWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}else{for(let[e,t]of orderedPercentWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}return{setValue:{size:r}}}return{useEssentialOrDefaultValue:{size:!0}}}},e.width={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},returnDependencies:()=>({size:{dependencyType:"stateVariable",variableName:"size"}}),definition:({dependencyValues:e})=>({setValue:{width:{isAbsolute:!0,size:widthsBySize[e.size]}}})},e.aspectRatioFromAxisScales={returnDependencies:()=>({aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]}}),definition:({dependencyValues:e})=>(null!==e.heightAttr&&console.warn("Height attribute of graph is deprecated and is being ignored. Use aspectRatio attribute instead."),{setValue:{aspectRatioFromAxisScales:e.identicalAxisScales&&null===e.aspectRatioAttr},checkForActualChange:{aspectRatioFromAxisScales:!0}})},e.aspectRatio={public:!0,forRenderer:!0,defaultValue:1,hasEssential:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["aspectRatioFromAxisScales"],returnDependencies:({stateValues:e})=>e.aspectRatioFromAxisScales?{aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},yscale:{dependencyType:"stateVariable",variableName:"yscale"}}:{aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},width:{dependencyType:"stateVariable",variableName:"width"}},definition({dependencyValues:e}){if(e.aspectRatioFromAxisScales){return{setValue:{aspectRatio:e.xscale/e.yscale}}}if(null!==e.aspectRatioAttr){let t=e.aspectRatioAttr.stateValues.value;return Number.isFinite(t)||(t=1),{setValue:{aspectRatio:t}}}return{useEssentialOrDefaultValue:{aspectRatio:!0}}}},e.xmin={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xminPrelim:{dependencyType:"stateVariable",variableName:"xminPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{xmin:e.xminPrelim}};if(!t.xminPrelim)return{setValue:{xmin:e.xminPrelim}};let n=!t.xmaxPrelim,r=!t.yminPrelim,a=!t.ymaxPrelim;if(r&&a){let t=e.aspectRatio,r=(e.ymaxPrelim-e.yminPrelim)*t;return n?{setValue:{xmin:e.xmaxPrelim-r}}:{setValue:{xmin:-r/2}}}return n?{setValue:{xmin:e.xmaxPrelim-20}}:{setValue:{xmin:-10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xminPrelim",desiredValue:e.xmin}]}},e.xmax={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xmaxPrelim:{dependencyType:"stateVariable",variableName:"xmaxPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{xmax:e.xmaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.xminPrelim;if(s){let t=e.aspectRatio,a=(e.ymaxPrelim-e.yminPrelim)*t;if(o){let t=e.xmaxPrelim-l;return{setValue:{xmax:l+Math.max(t,a)}}}return n?{setValue:{xmax:l+a}}:r?{setValue:{xmax:e.xmaxPrelim}}:{setValue:{xmax:a/2}}}return r?{setValue:{xmax:e.xmaxPrelim}}:n?{setValue:{xmax:l+20}}:{setValue:{xmax:10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xmaxPrelim",desiredValue:e.xmax}]}},e.ymin={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},yminPrelim:{dependencyType:"stateVariable",variableName:"yminPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{ymin:e.yminPrelim}};if(!t.yminPrelim)return{setValue:{ymin:e.yminPrelim}};let n=!t.ymaxPrelim,r=!t.xminPrelim,a=!t.xmaxPrelim,i=r&&a,s=e.aspectRatio;if(i){let t=(e.xmaxPrelim-e.xminPrelim)/s;return n?{setValue:{ymin:e.ymaxPrelim-t}}:{setValue:{ymin:-t/2}}}return n?{setValue:{ymin:e.ymaxPrelim-20/s}}:{setValue:{ymin:-10/s}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"yminPrelim",desiredValue:e.ymin}]}},e.ymax={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},ymaxPrelim:{dependencyType:"stateVariable",variableName:"ymaxPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{ymax:e.ymaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.yminPrelim,u=e.aspectRatio;if(o){let t=(e.xmaxPrelim-e.xminPrelim)/u;if(s){let n=e.ymaxPrelim-l;return{setValue:{ymax:l+Math.max(n,t)}}}return a?{setValue:{ymax:l+t}}:i?{setValue:{ymax:e.ymaxPrelim}}:{setValue:{ymax:t/2}}}return i?{setValue:{ymax:e.ymaxPrelim}}:a?{setValue:{ymax:l+20/u}}:{setValue:{ymax:10/u}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"ymaxPrelim",desiredValue:e.ymax}]}},e.xscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({xmin:{dependencyType:"stateVariable",variableName:"xmin"},xmax:{dependencyType:"stateVariable",variableName:"xmax"}}),definition:({dependencyValues:e})=>({setValue:{xscale:e.xmax-e.xmin}})},e.yscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({ymin:{dependencyType:"stateVariable",variableName:"ymin"},ymax:{dependencyType:"stateVariable",variableName:"ymax"}}),definition:({dependencyValues:e})=>({setValue:{yscale:e.ymax-e.ymin}})},e.gridAttrCompName={returnDependencies:()=>({gridAttr:{dependencyType:"attributeComponent",attributeName:"grid"}}),definition:({dependencyValues:e})=>e.gridAttr?{setValue:{gridAttrCompName:e.gridAttr.componentName}}:{setValue:{gridAttrCompName:null}}},e.gridAttrCompChildren={stateVariablesDeterminingDependencies:["gridAttrCompName"],returnDependencies:({stateValues:e})=>e.gridAttrCompName?{gridAttrCompChildren:{dependencyType:"child",parentName:e.gridAttrCompName,childGroups:["textLike"],variableNames:["value"]}}:{},definition:({dependencyValues:e})=>e.gridAttrCompChildren?{setValue:{gridAttrCompChildren:e.gridAttrCompChildren}}:{setValue:{gridAttrCompChildren:null}}},e.grid={public:!0,shadowingInstructions:{hasVariableComponentType:!0,attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,stateVariablesDeterminingDependencies:["gridAttrCompChildren"],returnDependencies({stateValues:e}){if(e.gridAttrCompChildren){let t={gridAttrCompChildren:{dependencyType:"stateVariable",variableName:"gridAttrCompChildren"},gridAttr:{dependencyType:"attributeComponent",attributeName:"grid",variableNames:["value"]}};for(let[n,r]of e.gridAttrCompChildren.entries())t["childAdapter"+n]={dependencyType:"adapterSourceStateVariable",componentName:r.componentName,variableName:"value"};return t}return{}},definition({dependencyValues:e}){if(!e.gridAttrCompChildren)return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};let t=e.gridAttr.stateValues.value.toLowerCase().trim();if("true"===t?t="medium":"false"===t&&(t="none"),["medium","dense","none"].includes(t))return{setValue:{grid:t},setCreateComponentOfType:{grid:"text"}};let n=[],r=[];for(let t of e.gridAttrCompChildren)if("string"!=typeof t)r.push(t);else{let e=t.split(/\s+/),a=e[0];""===a?r.length>0&&(n.push(r),r=[]):r.push(a);for(let t of e.slice(1))r.length>0&&(n.push(r),r=[]),""!==t&&r.push(t)}if(r.length>0&&n.push(r),n.length<2)return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t=[];for(let r of n)if(1===r.length){let n=r[0];if("string"==typeof n){let e=me$3.fromText(n).evaluate_to_constant();if(!(e>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(e)}else{let r=e.gridAttrCompChildren.indexOf(n),a=e["childAdapter"+r];if(a instanceof me$3.class&&(a=a.evaluate_to_constant()),!(a>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(a)}}else{let n=1;for(let t of r)if("string"==typeof t)n*=me$3.fromText(t).evaluate_to_constant();else{let r=e.gridAttrCompChildren.indexOf(t),a=e["childAdapter"+r];a instanceof me$3.class&&(a=a.evaluate_to_constant()),n*=a}if(!(n>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(n)}return{setValue:{grid:t},setCreateComponentOfType:{grid:"numberList"}}}},e}async changeAxisLimits({xmin:e,xmax:t,ymin:n,ymax:r,actionId:a}){let i=[];return void 0!==e&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmin",value:e}),void 0!==t&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmax",value:t}),void 0!==n&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymin",value:n}),void 0!==r&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymax",value:r}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{xmin:e,xmax:t,ymin:n,ymax:r}}})}async addChildren({serializedComponents:e,actionId:t}){if(e&&e.length>0){let n=processAssignNames({serializedComponents:e,parentName:this.componentName,parentCreatesNewNamespace:this.attributes.newNamespace?.primitive,componentInfoObjects:this.componentInfoObjects,indOffset:await this.stateValues.nChildrenAdded});return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"addComponents",serializedComponents:n.serializedComponents,parentName:this.componentName,assignNamesOffset:await this.stateValues.nChildrenAdded},{updateType:"updateValue",componentName:this.componentName,stateVariable:"nChildrenAdded",value:await this.stateValues.nChildrenAdded+n.serializedComponents.length}],actionId:t})}this.coreFunctions.resolveAction({actionId:t})}async deleteChildren({number:e,actionId:t}){let n=Math.min(e,await this.stateValues.nChildrenAdded);if(n>0){let e=this.definingChildren.length,r=this.definingChildren.slice(e-n,e).map((e=>e.componentName));return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"deleteComponents",componentNames:r},{updateType:"updateValue",componentName:this.componentName,stateVariable:"nChildrenAdded",value:await this.stateValues.nChildrenAdded-n}],actionId:t})}this.coreFunctions.resolveAction({actionId:t})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Variables extends MathList{static componentType="variables";static stateVariableForAttributeValue="variables";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();e.variables={public:!0,shadowingInstructions:{createComponentOfType:"variable"},isArray:!0,entryPrefixes:["var"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={math:{dependencyType:"stateVariable",variableName:"math"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].math;return{setValue:{variables:n}}}};let t=this.componentType;return e.validVariables={returnDependencies:()=>({variables:{dependencyType:"stateVariable",variableName:"variables"}}),definition:function({dependencyValues:e}){let n=[];for(let r of e.variables){let e=isValidVariable(r);e||(console.warn("Invalid value for "+t),e=!1),n.push(e)}return{setValue:{validVariables:n}}}},e}}class Variable extends MathComponent{static componentType="variable";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.validVariable={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){let t=isValidVariable(e.value);return t||console.warn("Invalid value of a "+this.componentType),{setValue:{validVariable:t}}}},e}}class Interval extends MathComponent{static componentType="interval";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return delete e.createIntervals,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.createIntervals={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({}),definition:()=>({setValue:{createIntervals:!0}})},e}}class Group extends Template{static componentType="group";static renderedDefault=!0}class Option$1 extends Group{static componentType="option";static renderedDefault=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.selectForVariants={createComponentOfType:"textListFromString",createStateVariable:"selectForVariants",defaultValue:[],public:!0},e.selectWeight={createComponentOfType:"number",createStateVariable:"selectWeight",defaultValue:1,public:!0},e}}class Sequence extends CompositeComponent{static componentType="sequence";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();e.fixed={leaveRaw:!0},e.displayDigits={leaveRaw:!0},e.displayDecimals={leaveRaw:!0},e.displaySmallAsZero={leaveRaw:!0},e.padZeros={leaveRaw:!0};let t=returnStandardSequenceAttributes();return Object.assign(e,t),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStandardSequenceStateVariableDefinitions();return Object.assign(e,t),e.readyToExpandWhenResolved={returnDependencies:()=>({from:{dependencyType:"stateVariable",variableName:"from"},length:{dependencyType:"stateVariable",variableName:"length"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"},exclude:{dependencyType:"stateVariable",variableName:"exclude"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r}){if(!await e.stateValues.validSequence)return t.lastReplacementParameters={from:null,length:null,step:null,type:null,exclude:null},{replacements:[]};let a=await e.stateValues.from,i=await e.stateValues.length,s=await e.stateValues.step,o=await e.stateValues.type,l=await e.stateValues.exclude;t.lastReplacementParameters={from:a,length:i,step:s,type:o,exclude:l};let u=e.attributes.newNamespace?.primitive,c=returnSequenceValues({from:a,step:s,length:i,exclude:l,type:o,lowercase:await e.stateValues.lowercase}),p=o;"letters"===o&&(p="text");let d=[],m={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(m[t]=e.attributes[t]);for(let e of c){let t={};Object.keys(m).length>0&&(t=convertAttributesForComponentType({attributes:m,componentType:p,componentInfoObjects:n,compositeCreatesNewNamespace:u,flags:r}));let a={componentType:p,attributes:t,state:{value:e,fixed:!0}};d.push(a)}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:d,parentName:e.componentName,parentCreatesNewNamespace:u,componentInfoObjects:n}).serializedComponents}}static async calculateReplacementChanges({component:e,workspace:t,componentInfoObjects:n,flags:r}){let a=t.lastReplacementParameters,i=[];if(!await e.stateValues.validSequence){let t=e.replacementsToWithhold;if(t||(t=0),e.replacements.length-t>0){let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:e.replacements.length};i.push(t)}return a.length=0,i}let s=await e.stateValues.from,o=await e.stateValues.length,l=await e.stateValues.step,u=await e.stateValues.type,c=await e.stateValues.exclude,p=await e.stateValues.lowercase;if(a.type!==u||a.exclude.length>0||c.length>0){let a=(await this.createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r})).replacements,s={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:a,replacementsToWithhold:0};i.push(s)}else{let t=!1;"math"===u?s.equals(a.from)&&l.equals(a.step)||(t=!0):s===a.from&&l===a.step||(t=!0);let c,d=a.length,m=0,h=0,f=d;if(od&&(m=o-d,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=m){c=e.replacementsToWithhold-m,h+=m,d+=m,m=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:c};i.push(t)}else m-=e.replacementsToWithhold,h+=e.replacementsToWithhold,d+=e.replacementsToWithhold,c=0;if(!0===t&&(h=d,f=0),h>0)for(let t=f;t0){let t=[],a=e.attributes.newNamespace?.primitive,o={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(o[t]=e.attributes[t]);for(let i=d;i0&&(m=convertAttributesForComponentType({attributes:o,componentType:d,componentInfoObjects:n,compositeCreatesNewNamespace:a,flags:r}));let h={componentType:d,attributes:m,state:{value:c,fixed:!0}};t.push(h)}let c={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:d,serializedReplacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:n,indOffset:d}).serializedComponents,replacementsToWithhold:0,assignNamesOffset:d};i.push(c)}}return a.type=u,a.from=s,a.length=o,a.step=l,a.exclude=c,i}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes,t="number";this.attributes.type&&this.attributes.type.primitive&&(t=this.attributes.type.primitive);let n=this.componentInfoObjects.allComponentClasses["letters"===t?"text":t].rendererType;return e.includes(n)||e.push(n),e}}class Map$1 extends CompositeComponent{static componentType="map";static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.behavior={createComponentOfType:"text",createStateVariable:"behavior",defaultValue:"combination",public:!0,trim:!0},e.isResponse={leaveRaw:!0},e}static returnChildGroups(){return[{group:"templates",componentTypes:["template"]},{group:"sources",componentTypes:["sources"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nSources={additionalStateVariablesDefined:["sourcesNames","sourceAliases","sourceIndexAliases"],returnDependencies:()=>({sourcesChildren:{dependencyType:"child",childGroups:["sources"],variableNames:["alias","indexAlias"]}}),definition:function({dependencyValues:e}){return{setValue:{nSources:e.sourcesChildren.length,sourcesNames:e.sourcesChildren.map((e=>e.componentName)),sourceAliases:e.sourcesChildren.map((e=>e.stateValues.alias)),sourceIndexAliases:e.sourcesChildren.map((e=>e.stateValues.indexAlias))}}}},e.nIterates={additionalStateVariablesDefined:["minNIterates","sourcesChildNames"],returnDependencies:()=>({sourcesChildren:{dependencyType:"child",childGroups:["sources"],variableNames:["numberOfChildren","childComponentNames"]}}),definition:function({dependencyValues:e}){let t=e.sourcesChildren.map((e=>e.stateValues.numberOfChildren)),n=Math.min(...t),r=e.sourcesChildren.map((e=>[...e.stateValues.childComponentNames]));return{setValue:{nIterates:t,minNIterates:n,sourcesChildNames:r}}}},e.template={returnDependencies:()=>({templateChild:{dependencyType:"child",childGroups:["templates"],variableNames:["serializedChildren","newNamespace"]}}),definition:function({dependencyValues:e}){let t=e.templateChild[0];if(!t)return{setValue:{template:null}};let n={componentType:"template",state:{rendered:!0},children:t.stateValues.serializedChildren,originalName:t.componentName};return t.stateValues.newNamespace&&(n.attributes={newNamespace:{primitive:!0}}),{setValue:{template:n}}}},e.validBehavior={returnDependencies:()=>({behavior:{dependencyType:"stateVariable",variableName:"behavior"},nIterates:{dependencyType:"stateVariable",variableName:"nIterates"}}),definition:function({dependencyValues:e}){let t=!0;return"parallel"===e.behavior?e.nIterates.slice(1).some((t=>t!=e.nIterates[0]))&&console.warn("Warning: map with parallel behavior and different numbers of iterates in sources activeChildren. Extra iterates will be ignored."):"combination"!==e.behavior&&(console.warn("Invalid map behavior: "+e.behavior),t=!1),{setValue:{validBehavior:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({validBehavior:{dependencyType:"stateVariable",variableName:"validBehavior"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r}){if(!await e.stateValues.validBehavior)return t.lastReplacementParameters={sourcesNames:[],sourcesChildNames:[],behavior:void 0,nIterates:void 0,minNIterates:void 0},{replacements:[]};t.lastReplacementParameters={sourcesNames:await e.stateValues.sourcesNames,sourcesChildNames:await e.stateValues.sourcesChildNames,behavior:await e.stateValues.behavior,nIterates:await e.stateValues.nIterates,minNIterates:await e.stateValues.minNIterates,replacementsToWithhold:0,withheldSubstitutionChildNames:[]};let a=[];if("parallel"===await e.stateValues.behavior)for(let t=0;t=c-1){r++;let t=[deepClone(p)],n={};n=convertAttributesForComponentType({attributes:e.attributes,componentType:t[0].componentType,componentInfoObjects:a,compositeAttributesObj:d,compositeCreatesNewNamespace:l,flags:i}),t[0].attributes||(t[0].attributes={}),Object.assign(t[0].attributes,n),!t[0].attributes.newNamespace?.primitive&&t[0].children&&markToCreateAllUniqueNames(t[0].children);let u=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:l,componentInfoObjects:a,indOffset:r}).serializedComponents[0];await addSharedParameters(u,e,o),s.push(u)}else{let n=await this.recurseThroughCombinations({component:e,sourcesNumber:t+1,childnumberArray:o,iterateNumber:r,componentInfoObjects:a,flags:i});s.push(...n.replacements),r=n.iterateNumber}return{replacements:s,iterateNumber:r}}static async calculateReplacementChanges({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a}){let i=[];if(!await e.stateValues.validBehavior){if(n.lastReplacementParameters={sourcesNames:[],sourcesChildNames:[],behavior:void 0,nIterates:void 0,minNIterates:void 0,replacementsToWithhold:0,withheldSubstitutionChildNames:[]},e.replacements.length>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToDelete:e.replacements.length,replacementsToWithhold:0};i.push(t)}return i}let s=n.lastReplacementParameters,o=!1,l=!0,u=await e.stateValues.nSources,c=await e.stateValues.sourcesNames;if(u!==s.sourcesNames.length)l=!1;else for(let e=0;e1&&(o=!0)}else o=!0;if(o){let t=await this.createSerializedReplacements({component:e,workspace:n,componentInfoObjects:r,flags:a}).replacements,s={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:t,replacementsToWithhold:0};return i.push(s),n.lastReplacementParameters={sourcesNames:c,sourcesChildNames:d,behavior:m,nIterates:p,minNIterates:await e.stateValues.minNIterates,replacementsToWithhold:0,withheldSubstitutionChildNames:[]},i}let h=await e.stateValues.minNIterates,f=s.minNIterates,y=0,g=e.replacementsToWithhold;g||(g=0);let b=s.withheldSubstitutionChildNames,v=!1;if(hf){let t=h-f;if(g>0)if(g>=t){y=g-t,t=0;let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:y};i.push(e)}else t-=g,f+=g,y=0;if(t>0){let t=[];for(let n=f;nr?{success:!1}:{success:!0,desiredVariant:{index:t}}}}async function addSharedParameters(e,t,n){let r=e.doenetAttributes.addToSharedParameters=[],a=await t.stateValues.sourcesNames;for(let[e,i]of(await t.stateValues.sourceAliases).entries())if(i){let t=a[e];r.push({parameterName:"sourceNameMappings",key:i,value:{name:t,childNumber:n[e]}})}for(let[e,a]of(await t.stateValues.sourceIndexAliases).entries())a&&r.push({parameterName:"sourceIndexMappings",key:a,value:n[e]+1})}class Sources extends BaseComponent{static componentType="sources";static rendererType="containerInline";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.alias={createPrimitiveOfType:"string",validationFunction:function(e){if(!/[a-zA-Z_]/.test(e.substring(0,1)))throw Error("All aliases must begin with a letter or an underscore");if(!/^[a-zA-Z0-9_\-]+$/.test(e))throw Error("Aliases can contain only letters, numbers, hyphens, and underscores");return e}},e.indexAlias={createPrimitiveOfType:"string",validationFunction:function(e){if(!/[a-zA-Z_]/.test(e.substring(0,1)))throw Error("All index aliases must begin with a letter or an underscore");if(!/^[a-zA-Z0-9_\-]+$/.test(e))throw Error("Index aliases can contain only letters, numbers, hyphens, and underscores");return e}},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.alias={returnDependencies:()=>({alias:{dependencyType:"attributePrimitive",attributeName:"alias"}}),definition:({dependencyValues:e})=>({setValue:{alias:e.alias}})},e.indexAlias={returnDependencies:()=>({indexAlias:{dependencyType:"attributePrimitive",attributeName:"indexAlias"}}),definition:({dependencyValues:e})=>({setValue:{indexAlias:e.indexAlias}})},e.numberOfChildren={additionalStateVariablesDefined:["childComponentNames","childIdentities"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"]}}),definition:function({dependencyValues:e}){let t=e.children.length,n=e.children.map((e=>e.componentName));return{setValue:{numberOfChildren:t,childComponentNames:n,childIdentities:e.children}}}},e}}class Slider extends BaseComponent{constructor(e){super(e),this.changeValue=this.changeValue.bind(this),Object.assign(this.actions,{changeValue:this.changeValue})}static componentType="slider";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultValue:"number",toLowerCase:!0,validValues:["number","text"],forRenderer:!0},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:300,isAbsolute:!0},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:100,isAbsolute:!0},public:!0,forRenderer:!0},e.initialValue={createComponentOfType:"_componentWithSelectableType",createStateVariable:"initialValue",defaultValue:null},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showControls={createComponentOfType:"boolean",createStateVariable:"showControls",defaultValue:!1,public:!0,forRenderer:!0},e.showTicks={createComponentOfType:"boolean",createStateVariable:"showTicks",defaultValue:!0,public:!0,forRenderer:!0},e.showValue={createComponentOfType:"boolean",createStateVariable:"showValue",defaultValue:!0,public:!0,forRenderer:!0},e.from={createComponentOfType:"number",createStateVariable:"from",defaultValue:0,public:!0,forRenderer:!0},e.to={createComponentOfType:"number",createStateVariable:"to",defaultValue:10,public:!0,forRenderer:!0},e.step={createComponentOfType:"number",createStateVariable:"step",defaultValue:1,public:!0,forRenderer:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"_componentWithSelectableType"},e}static returnChildGroups(){return[{group:"numbersTexts",componentTypes:["number","text"]},{group:"markers",componentTypes:["markers"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({numberAndTextChildren:{dependencyType:"child",childGroups:["numbersTexts"],variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];if("text"===e.type)for(let r of e.numberAndTextChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"text"})?n.push(r.stateValues.value):n.push(r.stateValues.value.toString());else if(e.numberAndTextChildren.length>0){for(let r of e.numberAndTextChildren)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"}))n.push(r.stateValues.value);else{let e=Number(r.stateValues.value);Number.isFinite(e)&&n.push(e)}n.sort(((e,t)=>e-t))}return{setValue:{items:n},setCreateComponentOfType:{items:e.type}}}},e.nItems={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},to:{dependencyType:"stateVariable",variableName:"to"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t=e.items.length;return 0===t&&"number"===e.type&&(t=Math.floor((e.to-e.from)/e.step+1e-10)+1,t>=0&&Number.isFinite(t)||(t=0)),{setValue:{nItems:t}}}},e.firstItem={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t;return t=e.items.length>0?e.items[0]:"number"===e.type?e.from:null,{setValue:{firstItem:t}}}},e.lastItem={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},nItems:{dependencyType:"stateVariable",variableName:"nItems"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t;return t=e.items.length>0?e.items[e.items.length-1]:"number"===e.type?e.from+(e.nItems-1)*e.step:null,{setValue:{lastItem:t}}}},e.valueToIndex={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"}}),definition:function({dependencyValues:e}){let t={};for(let[n,r]of e.items.entries())t[r]=n;return{setValue:{valueToIndex:t}}}},e.preliminaryValue={hasEssential:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},initialValue:{dependencyType:"stateVariable",variableName:"initialValue"},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]}}),definition:({dependencyValues:e})=>e.bindValueTo?{setValue:{preliminaryValue:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{preliminaryValue:{get defaultValue(){return e.initialValue}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.preliminaryValue,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"preliminaryValue",value:e.preliminaryValue}]}},e.index={forRenderer:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},valueToIndex:{dependencyType:"stateVariable",variableName:"valueToIndex"},items:{dependencyType:"stateVariable",variableName:"items"},preliminaryValue:{dependencyType:"stateVariable",variableName:"preliminaryValue"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"},nItems:{dependencyType:"stateVariable",variableName:"nItems"}}),definition:function({dependencyValues:e}){let t=findIndexOfClosestValidValue(e);return void 0===t&&(t=0),{setValue:{index:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(0===t.items.length){let n=t.from,r=t.step,a=e.index;return Number.isInteger(a)&&(a>=0&&a({type:{dependencyType:"stateVariable",variableName:"type"},items:{dependencyType:"stateVariable",variableName:"items"},index:{dependencyType:"stateVariable",variableName:"index"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"}}),definition:function({dependencyValues:e}){let t;return t=e.items.length>0?e.items[e.index]:e.from+e.step*e.index,{setValue:{value:t},setCreateComponentOfType:{value:e.type}}},inverseDefinition:invertSliderValue},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t}).tree}}}},e.markers={forRenderer:!0,returnDependencies:()=>({markersChild:{dependencyType:"child",childGroups:["markers"],variableNames:["markerType","markers"]},type:{dependencyType:"stateVariable",variableName:"type"},items:{dependencyType:"stateVariable",variableName:"items"}}),definition:function({dependencyValues:e}){let t=[];if(e.markersChild.length>0){let n=e.markersChild[0].stateValues.markerType;"empty"===n?t=[...e.items]:n!==e.type?(console.warn("Markers type doesn't match slider type."),t=[]):t=e.markersChild[0].stateValues.markers}return{setValue:{markers:t}}}},e}async changeValue({value:e,transient:t,actionId:n}){if(!await this.stateValues.disabled)return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],transient:t,actionId:n}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],actionId:n,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:e,responseText:e.toString()}}});this.coreFunctions.resolveAction({actionId:n})}}function findIndexOfClosestValidValue({preliminaryValue:e,valueToIndex:t,type:n,items:r,from:a,step:i,nItems:s}){let o=e;if(0===r.length){if(!Number.isFinite(o))return;let e=Math.round((o-a)/i);return e>=0?er[e]?t:e;let n=Math.round((t+e)/2);return o>r[n]?u(n,t):u(e,n)},c=u();if(0!==c){let e=r[c-1],t=r[c];Math.abs(o-e)({textChildren:{dependencyType:"child",childGroups:["texts"]},numberChildren:{dependencyType:"child",childGroups:["numbers"]}}),definition:function({dependencyValues:e}){let t;return t=e.textChildren.length>0?"text":e.numberChildren.length>0?"number":"empty",{setValue:{markerType:t}}}},e.markers={public:!0,isArray:!0,shadowingInstructions:{hasVariableComponentType:!0},entryPrefixes:["item"],returnDependencies:()=>({markerType:{dependencyType:"stateVariable",variableName:"markerType"},textChildren:{dependencyType:"child",childGroups:["texts"],variableNames:["value"]},numberChildren:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]}}),definition:function({dependencyValues:e}){let t=[],n=e.markerType;return"text"===e.markerType?t=e.textChildren.map((e=>e.stateValues.value)):"number"===e.markerType?(t=e.numberChildren.map((e=>e.stateValues.value)),t.sort(((e,t)=>e-t))):n="text",{setValue:{markers:t},setCreateComponentOfType:{markers:n}}}},e}}function applyConstraintFromComponentConstraints({variables:e,applyComponentConstraint:t,scales:n}){let r={},a=!1;for(let i in e){let s=t({variables:{[i]:e[i]},scales:n});s.constrained&&(a=!0,r[i]=s.variables[i])}return a?{constrained:a,variables:r}:{}}class Constraints extends BaseComponent{static componentType="constraints";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.baseOnGraph={createTargetComponentNames:!0},e}static returnChildGroups(){return[{group:"constraints",componentTypes:["_constraint"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["independentComponentConstraints"]}}),definition:({dependencyValues:e})=>({setValue:{independentComponentConstraints:e.constraintChildren.every((e=>e.stateValues.independentComponentConstraints))}})},e.arrayEntryPrefixForConstraints={returnDependencies:()=>({arrayEntryPrefixForConstraints:{dependencyType:"parentStateVariable",variableName:"arrayEntryPrefixForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{arrayEntryPrefixForConstraints:e.arrayEntryPrefixForConstraints}})},e.arrayVariableForConstraints={returnDependencies:()=>({arrayVariableForConstraints:{dependencyType:"parentStateVariable",variableName:"arrayVariableForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{arrayVariableForConstraints:e.arrayVariableForConstraints}})},e.nDimensions={returnDependencies:()=>({nDimensions:{dependencyType:"parentStateVariable",variableName:"nDimensionsForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{nDimensions:e.nDimensions}})},e.graphComponentName={returnDependencies:()=>({graphComponentName:{dependencyType:"attributeTargetComponentNames",attributeName:"baseOnGraph"}}),definition:({dependencyValues:e})=>1===e.graphComponentName?.length?{setValue:{graphComponentName:e.graphComponentName[0].absoluteName}}:{setValue:{graphComponentName:null}}},e.scales={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["graphComponentName"],returnDependencies:({stateValues:e})=>e.graphComponentName?{graph:{dependencyType:"multipleStateVariables",componentName:e.graphComponentName,variableNames:["xscale","yscale"],variablesOptional:!0}}:{},definition({dependencyValues:e}){if(e.graph){let t=e.graph.stateValues,n=[t.xscale,t.yscale,1];if(n.every((e=>Number.isFinite(e)&&e>0)))return{setValue:{scales:n}}}return{setValue:{scales:[1,1,1]}}}},e.graphXmin={additionalStateVariablesDefined:["graphXmax","graphYmin","graphYmax"],stateVariablesDeterminingDependencies:["graphComponentName"],returnDependencies:({stateValues:e})=>e.graphComponentName?{graph:{dependencyType:"multipleStateVariables",componentName:e.graphComponentName,variableNames:["xmin","xmax","ymin","ymax"],variablesOptional:!0}}:{},definition({dependencyValues:e}){if(!e.graph)return{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}};let t=e.graph.stateValues.xmin,n=e.graph.stateValues.xmax,r=e.graph.stateValues.ymin,a=e.graph.stateValues.ymax;return[t,n,r,a].every(Number.isFinite)?{setValue:{graphXmin:t,graphXmax:n,graphYmin:r,graphYmax:a}}:{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}}}},e.constraintResults={additionalStateVariablesDefined:[{variableName:"constraintUsedByComponent",isArray:!0,entryPrefixes:["constraintUsedByComponent"]}],isArray:!0,entryPrefixes:["constraintResult"],stateVariablesDeterminingDependencies:["independentComponentConstraints","arrayEntryPrefixForConstraints","arrayVariableForConstraints"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0},independentComponentConstraints:{dependencyType:"stateVariable",variableName:"independentComponentConstraints"},scales:{dependencyType:"stateVariable",variableName:"scales"}},r=t.arrayEntryPrefixForConstraints,a={};if(t.independentComponentConstraints)for(let t of e)a[t]={x:{dependencyType:"parentStateVariable",variableName:r+(Number(t)+1)}};else{let e=t.arrayVariableForConstraints?t.arrayVariableForConstraints:"__null";n.xs={dependencyType:"parentStateVariable",variableName:e}}return{globalDependencies:n,dependenciesByKey:a}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(e.independentComponentConstraints){let r={},a={};for(let i of n){let n=Number(i)+1,s={["x"+n]:t[i].x},o=!1;for(let t of e.constraintChildren){let r=t.stateValues.applyComponentConstraint({variables:s,scales:e.scales});r.constrained&&(s["x"+n]=convertValueToMathExpression(r.variables["x"+n]),o=!0)}r[i]=s["x"+n],a[i]=o}return{setValue:{constraintResults:r,constraintUsedByComponent:a}}}{let t={},n=!1;for(let n in e.xs)t[`x${Number(n)+1}`]=e.xs[n];for(let r of e.constraintChildren){let a;if(a=r.stateValues.applyConstraint?r.stateValues.applyConstraint({variables:t,scales:e.scales}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:r.stateValues.applyComponentConstraint,scales:e.scales}),a.constrained){for(let e in a.variables)t[e]=convertValueToMathExpression(a.variables[e]);n=!0}}let r={},a={};for(let i in e.xs)r[i]=t[`x${Number(i)+1}`],a[i]=n;return{setValue:{constraintResults:r,constraintUsedByComponent:a}}}},inverseArrayDefinitionByKey:async function({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,stateValues:a,workspace:i}){if(t.independentComponentConstraints){let n=[];for(let a in e.constraintResults){let i=Number(a)+1,s={["x"+i]:convertValueToMathExpression(e.constraintResults[a])};for(let e of t.constraintChildren){let n=e.stateValues.applyComponentConstraint({variables:s,scales:t.scales});n.constrained&&(s["x"+i]=convertValueToMathExpression(n.variables["x"+i]))}n.push({setDependency:r[a].x,desiredValue:s["x"+i]})}return{success:!0,instructions:n}}{let n={};i.desiredConstraintResults||(i.desiredConstraintResults={}),Object.assign(i.desiredConstraintResults,e.constraintResults);let r=await a.constraintResults;for(let e in r){let t=Number(e)+1;e in i.desiredConstraintResults?n["x"+t]=convertValueToMathExpression(i.desiredConstraintResults[e]):n["x"+t]=convertValueToMathExpression(r[e])}for(let e of t.constraintChildren){let r;if(r=e.stateValues.applyConstraint?e.stateValues.applyConstraint({variables:n,scales:t.scales}):applyConstraintFromComponentConstraints({variables:n,applyComponentConstraint:e.stateValues.applyComponentConstraint,scales:t.scales}),r.constrained)for(let e in r.variables)n[e]=convertValueToMathExpression(r.variables[e])}let s={};for(let e in i.desiredConstraintResults)s[e]=n[`x${Number(e)+1}`];return{success:!0,instructions:[{setDependency:"xs",desiredValue:s}]}}}},e.constraintUsed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({constraintUsedByComponent:{dependencyType:"stateVariable",variableName:"constraintUsedByComponent"}}),definition:function({dependencyValues:e}){let t=Object.values(e.constraintUsedByComponent).some((e=>e));return{setValue:{constraintUsed:t}}}},e}}class ConstraintComponent extends BaseComponent{static componentType="_constraint";static rendererType=void 0;static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!1}})},e}}class ConstrainToGrid extends ConstraintComponent{static componentType="constrainToGrid";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0},e.dz={createComponentOfType:"number",createStateVariable:"dz",defaultValue:1,public:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0},e.zoffset={createComponentOfType:"number",createStateVariable:"zoffset",defaultValue:0,public:!0},e.ignoreGraphBounds={createComponentOfType:"boolean",createStateVariable:"ignoreGraphBounds",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!0}})},e.applyComponentConstraint={returnDependencies:()=>({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},ignoreGraphBounds:{dependencyType:"stateVariable",variableName:"ignoreGraphBounds"}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),"x1"in t){let n=findFiniteNumericalValue(t.x1);if(!Number.isFinite(n))return{};let a=e.dx,i=e.xoffset,s=Math.round((n-i)/a)*a+i;if(Number.isFinite(s)){if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphXmin,n=e.constraintAncestor.stateValues.graphXmax):"graph"===r&&(t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return{constrained:!0,variables:{x1:s}}}return{}}if("x2"in t){let n=findFiniteNumericalValue(t.x2);if(!Number.isFinite(n))return{};let a=e.dy,i=e.yoffset,s=Math.round((n-i)/a)*a+i;if(Number.isFinite(s)){if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphYmin,n=e.constraintAncestor.stateValues.graphYmax):"graph"===r&&(t=e.graphAncestor.stateValues.ymin,n=e.graphAncestor.stateValues.ymax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return{constrained:!0,variables:{x2:s}}}return{}}if("x3"in t){let n=findFiniteNumericalValue(t.x3);if(!Number.isFinite(n))return{};let r=e.dz,a=e.zoffset,i=Math.round((n-a)/r)*r+a;return Number.isFinite(i)?{constrained:!0,variables:{x3:i}}:{}}return{}}}})},e}}class ConstrainToGraph extends ConstraintComponent{static componentType="constrainToGraph";static createAttributesObject(){let e=super.createAttributesObject();return e.buffer={createComponentOfType:"number",createStateVariable:"buffer",defaultValue:.01,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!0}})},e.applyComponentConstraint={returnDependencies:()=>({constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},buffer:{dependencyType:"stateVariable",variableName:"buffer"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),!r)return{};if("x1"in t){let n,a,i=findFiniteNumericalValue(t.x1);if(!Number.isFinite(i))return{};if("constraints"===r?(n=e.constraintAncestor.stateValues.graphXmin,a=e.constraintAncestor.stateValues.graphXmax):(n=e.graphAncestor.stateValues.xmin,a=e.graphAncestor.stateValues.xmax),!Number.isFinite(n)||!Number.isFinite(a))return{};let s=n,o=a,l=e.buffer;if(l>0){let e=l*(a-n);s+=e,o-=e}return{constrained:!0,variables:{x1:Math.max(s,Math.min(o,i))}}}if("x2"in t){let n,a,i=findFiniteNumericalValue(t.x2);if(!Number.isFinite(i))return{};if("constraints"===r?(n=e.constraintAncestor.stateValues.graphYmin,a=e.constraintAncestor.stateValues.graphYmax):(n=e.graphAncestor.stateValues.ymin,a=e.graphAncestor.stateValues.ymax),!Number.isFinite(n)||!Number.isFinite(a))return{};let s=n,o=a,l=e.buffer;if(l>0){let e=l*(a-n);s+=e,o-=e}return{constrained:!0,variables:{x2:Math.max(s,Math.min(o,i))}}}return{}}}})},e}}class AttractToGrid extends ConstraintComponent{static componentType="attractToGrid";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0},e.dz={createComponentOfType:"number",createStateVariable:"dz",defaultValue:1,public:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0},e.zoffset={createComponentOfType:"number",createStateVariable:"zoffset",defaultValue:0,public:!0},e.xthreshold={createComponentOfType:"number",createStateVariable:"xthreshold",defaultValue:.2,public:!0},e.ythreshold={createComponentOfType:"number",createStateVariable:"ythreshold",defaultValue:.2,public:!0},e.zthreshold={createComponentOfType:"number",createStateVariable:"zthreshold",defaultValue:.2,public:!0},e.includeGridlines={createComponentOfType:"boolean",createStateVariable:"includeGridlines",defaultValue:!1,public:!0},e.ignoreGraphBounds={createComponentOfType:"boolean",createStateVariable:"ignoreGraphBounds",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({includeGridlines:{dependencyType:"stateVariable",variableName:"includeGridlines"}}),definition:({dependencyValues:e})=>({setValue:{independentComponentConstraints:e.includeGridlines}})},e.applyComponentConstraint={returnDependencies:()=>({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},xthreshold:{dependencyType:"stateVariable",variableName:"xthreshold"},ythreshold:{dependencyType:"stateVariable",variableName:"ythreshold"},zthreshold:{dependencyType:"stateVariable",variableName:"zthreshold"},constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},ignoreGraphBounds:{dependencyType:"stateVariable",variableName:"ignoreGraphBounds"}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),"x1"in t){let n=findFiniteNumericalValue(t.x1);if(!Number.isFinite(n))return{};let a=e.dx,i=e.xoffset,s=Math.round((n-i)/a)*a+i;if(!Number.isFinite(s))return{};if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphXmin,n=e.constraintAncestor.stateValues.graphXmax):"graph"===r&&(t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return Math.abs(n-s)n&&(s=Math.floor((n-i)/a)*a+i))}return Math.abs(n-s)({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},xthreshold:{dependencyType:"stateVariable",variableName:"xthreshold"},ythreshold:{dependencyType:"stateVariable",variableName:"ythreshold"},zthreshold:{dependencyType:"stateVariable",variableName:"zthreshold"},includeGridlines:{dependencyType:"stateVariable",variableName:"includeGridlines"},applyComponentConstraint:{dependencyType:"stateVariable",variableName:"applyComponentConstraint"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r={},a=!1;for(let i in t){let s=e.applyComponentConstraint({variables:{[i]:t[i]},scales:n});s.constrained&&(a=!0,r[i]=s.variables[i])}if(!a)return{};if(!e.includeGridlines){if(void 0!==t.x1&&void 0===r.x1)return{};if(void 0!==t.x2&&void 0===r.x2)return{};if(void 0!==t.x3&&void 0===r.x3)return{}}return{constrained:a,variables:r}}}})},e}}class ConstrainTo extends ConstraintComponent{static componentType="constrainTo";static returnChildGroups(){return[{group:"graphical",componentTypes:["_graphical"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nearestPointFunctions={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"],variableNames:["nearestPoint"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.graphicalChildren)n.stateValues.nearestPoint?t.push(n.stateValues.nearestPoint):console.warn(`cannot attract to ${n.componentName} as it doesn't have a nearestPoint state variable`);return{setValue:{nearestPointFunctions:t}}}},e.applyConstraint={returnDependencies:()=>({nearestPointFunctions:{dependencyType:"stateVariable",variableName:"nearestPointFunctions"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r=1/0,a={},i=!1,s={};for(let e in t)s[e]=findFiniteNumericalValue(t[e]);for(let o of e.nearestPointFunctions){let e=o({variables:t,scales:n});if(void 0===e)continue;let l={},u=0;if(void 0!==s.x1){if(void 0===e.x1)continue;l.x1=e.x1,u+=Math.pow(s.x1-e.x1,2)}if(void 0!==s.x2){if(void 0===e.x2)continue;l.x2=e.x2,u+=Math.pow(s.x2-e.x2,2)}if(void 0!==s.x3){if(void 0===e.x3)continue;l.x3=e.x3,u+=Math.pow(s.x3-e.x3,2)}u({thresholdAttr:{dependencyType:"attributeComponent",attributeName:"threshold",variableNames:["value"]},constraintsAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin"]}}),definition({dependencyValues:e}){if(e.thresholdAttr)return{setValue:{threshold:e.thresholdAttr.stateValues.value}};{let t=.02;return null!==e.constraintsAncestor&&null!==e.constraintsAncestor.stateValues.graphXmin||(t=.5),{useEssentialOrDefaultValue:{threshold:{defaultValue:t}}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.thresholdAttr?{success:!0,instructions:[{setDependency:"thresholdAttr",desiredValue:e.threshold}]}:{success:!0,instructions:[{setEssentialValue:"threshold",value:e.threshold}]}},e.nearestPointFunctions={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"],variableNames:["nearestPoint"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.graphicalChildren)n.stateValues.nearestPoint?t.push(n.stateValues.nearestPoint):console.warn(`cannot attract to ${n.componentName} as it doesn't have a nearestPoint state variable`);return{setValue:{nearestPointFunctions:t}}}},e.graphXscale={additionalStateVariablesDefined:["graphYscale"],returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["scales"]}}),definition({dependencyValues:e}){if(!e.graphAncestor)return{setValue:{graphXscale:null,graphYscale:null}};return{setValue:{graphXscale:e.graphAncestor.stateValues.xscale,graphYscale:e.graphAncestor.stateValues.yscale}}}},e.applyConstraint={returnDependencies:()=>({nearestPointFunctions:{dependencyType:"stateVariable",variableName:"nearestPointFunctions"},threshold:{dependencyType:"stateVariable",variableName:"threshold"},constraintsAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["scales"]}}),definition({dependencyValues:e}){let t=1,n=1;return e.constraintsAncestor&&([t,n]=e.constraintsAncestor.stateValues.scales),{setValue:{applyConstraint:function({variables:r,scales:a}){let i=1/0,s={},o={};for(let e in r)o[e]=findFiniteNumericalValue(r[e]);for(let l of e.nearestPointFunctions){let e=l({variables:r,scales:a});if(void 0===e)continue;let u={},c=0;if(void 0!==o.x1){if(void 0===e.x1)continue;u.x1=e.x1,c+=Math.pow((o.x1-e.x1)/t,2)}if(void 0!==o.x2){if(void 0===e.x2)continue;u.x2=e.x2,c+=Math.pow((o.x2-e.x2)/n,2)}if(void 0!==o.x3){if(void 0===e.x3)continue;u.x3=e.x3,c+=Math.pow(o.x3-e.x3,2)}ce.threshold*e.threshold?{}:{constrained:!0,variables:s}}}}}},e}}class ConstraintUnion extends ConstraintComponent{static componentType="constraintUnion";static returnChildGroups(){return[{group:"constraints",componentTypes:["_constraint"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.applyConstraint={returnDependencies:()=>({constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r;if(1===e.constraintChildren.length){let a=e.constraintChildren[0];return r=a.stateValues.applyConstraint?a.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:a.stateValues.applyComponentConstraint,scales:n}),r}let a,i=1/0,s={};for(let[o,l]of e.constraintChildren.entries()){if(r=l.stateValues.applyConstraint?l.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:l.stateValues.applyComponentConstraint,scales:n}),!r.constrained)continue;let e=0;for(let n in r.variables){let a=findFiniteNumericalValue(t[n]),i=findFiniteNumericalValue(r.variables[n]);if(!Number.isFinite(a)||!Number.isFinite(i)){e=1/0;break}e+=Math.pow(a-i,2)}e({constraintChild:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0},independentComponentConstraints:{dependencyType:"stateVariable",variableName:"independentComponentConstraints"},threshold:{dependencyType:"stateVariable",variableName:"threshold"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r,a=e.constraintChild[0];if(!a)return{};r=a.stateValues.applyConstraint?a.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:a.stateValues.applyComponentConstraint,scales:n});let i=0;for(let e in r.variables){let n=findFiniteNumericalValue(t[e]),a=findFiniteNumericalValue(r.variables[e]);if(!Number.isFinite(n)||!Number.isFinite(a))return{};i+=Math.pow(n-a,2)}return i>e.threshold*e.threshold?{}:r}}})},e}}class Intersection extends CompositeComponent{static componentType="intersection";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e}static returnChildGroups(){return[{group:"lines",componentTypes:["line"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.lineChildren={returnDependencies:()=>({lineChildren:{dependencyType:"child",childGroups:["lines"],variableNames:["numericalCoeff0","numericalCoeffvar1","numericalCoeffvar2","nDimensions"]}}),definition:({dependencyValues:e})=>({setValue:{lineChildren:e.lineChildren}})},e.readyToExpandWhenResolved={returnDependencies:()=>({lineChildren:{dependencyType:"stateVariable",variableName:"lineChildren"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n}){let r=await e.stateValues.lineChildren,a=r.length;if(0===a)return{replacements:[]};if(1===a){let a=r[0].componentName,i=await t[a].serialize({sourceAttributesToIgnoreRecursively:["isResponse"]});i.state||(i.state={}),i.state.draggable=!1,i.state.fixed=!0;let s=postProcessCopy({serializedComponents:[i],componentName:e.componentName}),o=e.attributes.newNamespace?.primitive;return s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:n}).serializedComponents,{replacements:s}}if(a>2)return console.warn("Haven't implemented intersection for more than two objects"),{replacements:[]};let i=r[0],s=r[1];if(2!==i.stateValues.nDimensions||2!==s.stateValues.nDimensions)return console.log("Intersection of lines implemented only in 2D"),{replacements:[]};let o=i.stateValues.numericalCoeffvar1,l=i.stateValues.numericalCoeffvar2,u=i.stateValues.numericalCoeff0,c=s.stateValues.numericalCoeffvar1,p=s.stateValues.numericalCoeffvar2,d=s.stateValues.numericalCoeff0;if(!(Number.isFinite(o)&&Number.isFinite(l)&&Number.isFinite(u)&&Number.isFinite(c)&&Number.isFinite(p)&&Number.isFinite(d)))return console.log("Intersection of lines implemented only for constant coefficients"),{replacements:[]};let m=o*p-c*l;if(Math.abs(m)<1e-14){if(Math.abs(d*o-u*c)>1e-14)return{replacements:[]};if(0===o&&0===l&&0===u||0===c&&0===p&&0===d)return{replacements:[]};{let a=r[0].componentName,i=await t[a].serialize({sourceAttributesToIgnoreRecursively:["isResponse"]});i.state||(i.state={}),i.state.draggable=!1,i.state.fixed=!0;let s=postProcessCopy({serializedComponents:[i],componentName:e.componentName}),o=e.attributes.newNamespace?.primitive;return s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:n}).serializedComponents,{replacements:s}}}let h=(d*l-u*p)/m,f=(u*c-d*o)/m,y=[{componentType:"point",state:{coords:me$3.fromAst(["vector",h,f]),draggable:!1,fixed:!0}}],g=e.attributes.newNamespace?.primitive;return y=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:y,parentName:e.componentName,parentCreatesNewNamespace:g,componentInfoObjects:n}).serializedComponents,{replacements:y}}static async calculateReplacementChanges({component:e,components:t,componentInfoObjects:n}){let r=[],a=(await this.createSerializedReplacements({component:e,components:t,componentInfoObjects:n})).replacements,i=a.length,s=!0;if(i===e.replacements.length){s=!1;for(let t=0;t({children:{dependencyType:"child",childGroups:["anything"],variableNames:["width"]},columns:{dependencyType:"stateVariable",variableName:"columns"}}),definition:function({dependencyValues:e}){let t=[],n=e.children.map((e=>e.stateValues.width));if(null!==e.columns){let r;if(-1!==e.columns.indexOf(","))r=e.columns.split(",").map(Number);else if(-1!==e.columns.indexOf("-")){let[t,n]=e.columns.split("-");r=[];for(let e=Number(t);e<=n;e++)r.push(e)}else r=[Number(e.columns)];let a={},i={};for(let e of r){let t=[],r=0;for(let a=0;ai&&(i=n[t]);t.push(i),r+=Number(i)}a[e]=t,i[e]=r}let s=-1;for(let e of r){let e=Number.POSITIVE_INFINITY,n=-1;for(let t of r)i[t]<=e&&t>s&&(e=i[t],n=t);e=this.state.threshold?{}:{variables:{x1:p,x2:d},constraintIndices:[i+1],constrained:!0}}}class ConditionalContent extends CompositeComponent{static componentType="conditionalContent";static includeBlankStringChildren=!0;static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static keepChildrenSerialized({serializedComponent:e,componentInfoObjects:t}){if(void 0===e.children)return[];let n=t.componentIsSpecifiedType,r=[];for(let[t,a]of e.children.entries())n(a,"case")||n(a,"else")||r.push(t);return r}static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.maximumNumberToShow={createComponentOfType:"number",createStateVariable:"maximumNumberToShow",defaultValue:null,public:!0},e.condition={createComponentOfType:"boolean"},e}static returnChildGroups(){return[{group:"cases",componentTypes:["case"]},{group:"elses",componentTypes:["else"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.baseConditionSatisfied={returnDependencies:()=>({conditionAttr:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t=!0;return e.conditionAttr&&(t=e.conditionAttr.stateValues.value),{setValue:{baseConditionSatisfied:t}}}},e.nCases={additionalStateVariablesDefined:["caseChildren"],returnDependencies:()=>({caseChildren:{dependencyType:"child",childGroups:["cases"]}}),definition:({dependencyValues:e})=>({setValue:{caseChildren:e.caseChildren,nCases:e.caseChildren.length}})},e.elseChild={returnDependencies:()=>({elseChild:{dependencyType:"child",childGroups:["elses"]}}),definition({dependencyValues:e}){let t=null;return e.elseChild.length>0&&(t=e.elseChild[0]),{setValue:{elseChild:t}}}},e.haveCasesOrElse={returnDependencies:()=>({nCases:{dependencyType:"stateVariable",variableName:"nCases"},elseChild:{dependencyType:"stateVariable",variableName:"elseChild"}}),definition:({dependencyValues:e})=>({setValue:{haveCasesOrElse:e.nCases>0||null!==e.elseChild}})},e.selectedIndices={returnDependencies:()=>({caseChildren:{dependencyType:"child",childGroups:["cases"],variableNames:["conditionSatisfied"]},elseChild:{dependencyType:"stateVariable",variableName:"elseChild"},maximumNumberToShow:{dependencyType:"stateVariable",variableName:"maximumNumberToShow"}}),definition({dependencyValues:e}){let t=[];for(let[n,r]of e.caseChildren.entries())r.stateValues.conditionSatisfied&&t.push(n);if(0===t.length&&e.elseChild&&t.push(e.caseChildren.length),null!==e.maximumNumberToShow&&t.length>e.maximumNumberToShow){let n=Math.max(0,Math.floor(e.maximumNumberToShow));t=t.slice(0,n)}return{setValue:{selectedIndices:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({baseConditionSatisfied:{dependencyType:"stateVariable",variableName:"baseConditionSatisfied"},haveCasesOrElse:{dependencyType:"stateVariable",variableName:"haveCasesOrElse"},selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r}){let a=await this.getReplacements(e,t,r);return n.previousSelectedIndices=[...await e.stateValues.selectedIndices],n.previousBaseConditionSatisfied=await e.stateValues.baseConditionSatisfied,{replacements:a}}static async getReplacements(e,t,n){if(!await e.stateValues.baseConditionSatisfied)return[];let r=[];if(await e.stateValues.haveCasesOrElse){let n=await e.stateValues.caseChildren;for(let[a,i]of(await e.stateValues.selectedIndices).entries()){let s,o,l;ie===i[t]))){if(r.previousBaseConditionSatisfied===s)return[];if(!s){let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:e.replacements.length};return r.previousBaseConditionSatisfied=s,[t]}if(e.replacements.length===e.serializedChildren.length){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};return r.previousBaseConditionSatisfied=s,[e]}}let o=[],l=await this.getReplacements(e,n,a),u={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:l,replacementsToWithhold:0};return o.push(u),r.previousSelectedIndices=[...i],r.previousBaseConditionSatisfied=s,o}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes;if(this.serializedChildren){let t=this.potentialRendererTypesFromSerializedComponents(this.serializedChildren);for(let n of t)e.includes(n)||e.push(n)}return e}}class AsList extends InlineComponent{static componentType="asList";static renderChildren=!0;static returnChildGroups(){return[{group:"inline",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.inlineChildren)"object"!=typeof n?t.push(n.toString()):"string"==typeof n.stateValues.text?t.push(n.stateValues.text):t.push("");return{setValue:{text:t.join(", ")}}}},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["text","latex"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.inlineChildren)"object"!=typeof n?t.push(n.toString()):"string"==typeof n.stateValues.latex?t.push(n.stateValues.latex):"string"==typeof n.stateValues.text?t.push(n.stateValues.text):t.push("");return{setValue:{latex:t.join(", ")}}}},e}}function normalizeIndex(e){if(null!==e&&""!==e){if(Number.isFinite(Number(e)))return Number(e)-1;if("string"==typeof e)return lettersToNumber(e)}}function lettersToNumber(e){let t=0,n=(e=e.toUpperCase()).length,r=n;for(;(r-=1)>-1;){let a=e.charCodeAt(r)-64;if(a<1||a>26)return void console.warn("Cannot convert "+e+" to a number");t+=a*Math.pow(26,n-1-r)}return t--,t} /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */collection$1("Map",(function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}}),collectionStrong);var NoSheetWithIdError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e){return _classCallCheck$1P(this,n),t.call(this,"There's no sheet with id = ".concat(e))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),NoSheetWithNameError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e){return _classCallCheck$1P(this,n),t.call(this,"There's no sheet with name '".concat(e,"'"))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),SheetNameAlreadyTakenError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e){return _classCallCheck$1P(this,n),t.call(this,"Sheet with name ".concat(e," already exists"))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),SheetSizeLimitExceededError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(){return _classCallCheck$1P(this,n),t.call(this,"Sheet size limit exceeded")}return _createClass$1P(n)}(_wrapNativeSuper(Error)),NotAFormulaError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(){return _classCallCheck$1P(this,n),t.call(this,"This is not a formula")}return _createClass$1P(n)}(_wrapNativeSuper(Error)),InvalidAddressError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e){return _classCallCheck$1P(this,n),t.call(this,"Address (row = ".concat(e.row,", col = ").concat(e.col,") is invalid"))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),InvalidArgumentsError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e){return _classCallCheck$1P(this,n),t.call(this,"Invalid arguments, expected ".concat(e))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),SheetsNotEqual=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e,r){return _classCallCheck$1P(this,n),t.call(this,"Sheets ".concat(e," and ").concat(r," are not equal."))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),NamedExpressionNameIsAlreadyTakenError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e){return _classCallCheck$1P(this,n),t.call(this,"Name of Named Expression '".concat(e,"' is already present"))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),NamedExpressionNameIsInvalidError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e){return _classCallCheck$1P(this,n),t.call(this,"Name of Named Expression '".concat(e,"' is invalid"))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),NamedExpressionDoesNotExistError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e){return _classCallCheck$1P(this,n),t.call(this,"Named Expression '".concat(e,"' does not exist"))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),NoOperationToUndoError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(){return _classCallCheck$1P(this,n),t.call(this,"There is no operation to undo")}return _createClass$1P(n)}(_wrapNativeSuper(Error)),NoOperationToRedoError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(){return _classCallCheck$1P(this,n),t.call(this,"There is no operation to redo")}return _createClass$1P(n)}(_wrapNativeSuper(Error)),NothingToPasteError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(){return _classCallCheck$1P(this,n),t.call(this,"There is nothing to paste")}return _createClass$1P(n)}(_wrapNativeSuper(Error));function replacer(e,t){switch(_typeof$1d(t)){case"function":case"symbol":return t.toString();case"bigint":return"BigInt("+t.toString()+")";default:return t instanceof RegExp?"RegExp("+t.toString()+")":t}}var UnableToParseError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e){return _classCallCheck$1P(this,n),t.call(this,"Unable to parse value: ".concat(JSON.stringify(e,replacer,4)))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),ExpectedValueOfTypeError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e,r){return _classCallCheck$1P(this,n),t.call(this,"Expected value of type: ".concat(e," for config parameter: ").concat(r))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),ConfigValueEmpty=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e){return _classCallCheck$1P(this,n),t.call(this,"Config parameter ".concat(e," cannot be empty."))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),ConfigValueTooSmallError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e,r){return _classCallCheck$1P(this,n),t.call(this,"Config parameter ".concat(e," should be at least ").concat(r))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),ConfigValueTooBigError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e,r){return _classCallCheck$1P(this,n),t.call(this,"Config parameter ".concat(e," should be at most ").concat(r))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),ExpectedOneOfValuesError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e,r){return _classCallCheck$1P(this,n),t.call(this,"Expected one of ".concat(e," for config parameter: ").concat(r))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),EvaluationSuspendedError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(){return _classCallCheck$1P(this,n),t.call(this,"Computations are suspended")}return _createClass$1P(n)}(_wrapNativeSuper(Error)),MissingTranslationError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e){return _classCallCheck$1P(this,n),t.call(this,"Translation for ".concat(e," is missing in the translation package you're using."))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),ProtectedFunctionTranslationError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e){return _classCallCheck$1P(this,n),t.call(this,"Cannot register translation for function with id: ".concat(e))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),LanguageNotRegisteredError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(){return _classCallCheck$1P(this,n),t.call(this,"Language not registered.")}return _createClass$1P(n)}(_wrapNativeSuper(Error)),LanguageAlreadyRegisteredError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(){return _classCallCheck$1P(this,n),t.call(this,"Language already registered.")}return _createClass$1P(n)}(_wrapNativeSuper(Error)),FunctionPluginValidationError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(){return _classCallCheck$1P(this,n),t.apply(this,arguments)}return _createClass$1P(n,null,[{key:"functionNotDeclaredInPlugin",value:function(e,t){return new n("Function with id ".concat(e," not declared in plugin ").concat(t))}},{key:"functionMethodNotFound",value:function(e,t){return new n("Function method ".concat(e," not found in plugin ").concat(t))}}]),n}(_wrapNativeSuper(Error)),ProtectedFunctionError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(){return _classCallCheck$1P(this,n),t.apply(this,arguments)}return _createClass$1P(n,null,[{key:"cannotRegisterFunctionWithId",value:function(e){return new n("Cannot register function with id ".concat(e))}},{key:"cannotUnregisterFunctionWithId",value:function(e){return new n("Cannot unregister function with id ".concat(e))}},{key:"cannotUnregisterProtectedPlugin",value:function(){return new n("Cannot unregister protected plugin")}}]),n}(_wrapNativeSuper(Error)),SourceLocationHasArrayError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(){return _classCallCheck$1P(this,n),t.call(this,"Cannot perform this operation, source location has an array inside.")}return _createClass$1P(n)}(_wrapNativeSuper(Error)),TargetLocationHasArrayError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(){return _classCallCheck$1P(this,n),t.call(this,"Cannot perform this operation, target location has an array inside.")}return _createClass$1P(n)}(_wrapNativeSuper(Error)),NoRelativeAddressesAllowedError=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(){return _classCallCheck$1P(this,n),t.call(this,"Relative addresses not allowed in named expressions.")}return _createClass$1P(n)}(_wrapNativeSuper(Error)),AliasAlreadyExisting=function(e){_inherits$X(n,e);var t=_createSuper$X(n);function n(e,r){return _classCallCheck$1P(this,n),t.call(this,"Alias id ".concat(e," in plugin ").concat(r," already defined as a function or alias."))}return _createClass$1P(n)}(_wrapNativeSuper(Error)),uncurryThis$d=functionUncurryThis,defineBuiltIn=defineBuiltIn$e,regexpExec$2=regexpExec$3,fails$9=fails$G,wellKnownSymbol$1=wellKnownSymbol$q,createNonEnumerableProperty=createNonEnumerableProperty$7,SPECIES=wellKnownSymbol$1("species"),RegExpPrototype=RegExp.prototype,fixRegexpWellKnownSymbolLogic=function(e,t,n,r){var a=wellKnownSymbol$1(e),i=!fails$9((function(){var t={};return t[a]=function(){return 7},7!=""[e](t)})),o=i&&!fails$9((function(){var t=!1,n=/a/;return"split"===e&&((n={}).constructor={},n.constructor[SPECIES]=function(){return n},n.flags="",n[a]=/./[a]),n.exec=function(){return t=!0,null},n[a](""),!t}));if(!i||!o||n){var s=uncurryThis$d(/./[a]),l=t(a,""[e],(function(e,t,n,r,a){var o=uncurryThis$d(e),l=t.exec;return l===regexpExec$2||l===RegExpPrototype.exec?i&&!a?{done:!0,value:s(t,n,r)}:{done:!0,value:o(n,t,r)}:{done:!1}}));defineBuiltIn(String.prototype,e,l[0]),defineBuiltIn(RegExpPrototype,a,l[1])}r&&createNonEnumerableProperty(RegExpPrototype[a],"sham",!0)},charAt$1=stringMultibyte.charAt,advanceStringIndex$2=function(e,t,n){return t+(n?charAt$1(e,t).length:1)},call$3=functionCall,anObject$4=anObject$k,isCallable$1=isCallable$q,classof=classofRaw$1,regexpExec$1=regexpExec$3,$TypeError$2=TypeError,regexpExecAbstract=function(e,t){var n=e.exec;if(isCallable$1(n)){var r=call$3(n,e,t);return null!==r&&anObject$4(r),r}if("RegExp"===classof(e))return call$3(regexpExec$1,e,t);throw $TypeError$2("RegExp#exec called on incompatible receiver")},apply$1=functionApply,call$2=functionCall,uncurryThis$c=functionUncurryThis,fixRegExpWellKnownSymbolLogic$1=fixRegexpWellKnownSymbolLogic,isRegExp$1=isRegexp,anObject$3=anObject$k,requireObjectCoercible$5=requireObjectCoercible$b,speciesConstructor=speciesConstructor$2,advanceStringIndex$1=advanceStringIndex$2,toLength$3=toLength$6,toString$8=toString$i,getMethod$1=getMethod$5,arraySlice$1=arraySliceSimple,callRegExpExec=regexpExecAbstract,regexpExec=regexpExec$3,stickyHelpers=regexpStickyHelpers,fails$8=fails$G,UNSUPPORTED_Y=stickyHelpers.UNSUPPORTED_Y,MAX_UINT32=4294967295,min$3=Math.min,$push=[].push,exec=uncurryThis$c(/./.exec),push$3=uncurryThis$c($push),stringSlice$4=uncurryThis$c("".slice),SPLIT_WORKS_WITH_OVERWRITTEN_EXEC=!fails$8((function(){var e=/(?:)/,t=e.exec;e.exec=function(){return t.apply(this,arguments)};var n="ab".split(e);return 2!==n.length||"a"!==n[0]||"b"!==n[1]}));fixRegExpWellKnownSymbolLogic$1("split",(function(e,t,n){var r;return r="c"=="abbc".split(/(b)*/)[1]||4!="test".split(/(?:)/,-1).length||2!="ab".split(/(?:ab)*/).length||4!=".".split(/(.?)(.?)/).length||".".split(/()()/).length>1||"".split(/.?/).length?function(e,n){var r=toString$8(requireObjectCoercible$5(this)),a=void 0===n?MAX_UINT32:n>>>0;if(0===a)return[];if(void 0===e)return[r];if(!isRegExp$1(e))return call$2(t,r,e,a);for(var i,o,s,l=[],u=(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.unicode?"u":"")+(e.sticky?"y":""),c=0,p=new RegExp(e.source,u+"g");(i=call$2(regexpExec,p,r))&&!((o=p.lastIndex)>c&&(push$3(l,stringSlice$4(r,c,i.index)),i.length>1&&i.index=a));)p.lastIndex===i.index&&p.lastIndex++;return c===r.length?!s&&exec(p,"")||push$3(l,""):push$3(l,stringSlice$4(r,c)),l.length>a?arraySlice$1(l,0,a):l}:"0".split(void 0,0).length?function(e,n){return void 0===e&&0===n?[]:call$2(t,this,e,n)}:t,[function(t,n){var a=requireObjectCoercible$5(this),i=null==t?void 0:getMethod$1(t,e);return i?call$2(i,t,a,n):call$2(r,toString$8(a),t,n)},function(e,a){var i=anObject$3(this),o=toString$8(e),s=n(r,i,o,a,r!==t);if(s.done)return s.value;var l=speciesConstructor(i,RegExp),u=i.unicode,c=(i.ignoreCase?"i":"")+(i.multiline?"m":"")+(i.unicode?"u":"")+(UNSUPPORTED_Y?"g":"y"),p=new l(UNSUPPORTED_Y?"^(?:"+i.source+")":i,c),d=void 0===a?MAX_UINT32:a>>>0;if(0===d)return[];if(0===o.length)return null===callRegExpExec(p,o)?[o]:[];for(var m=0,f=0,h=[];f=0:s>l;l+=u)l in o&&(a=n(a,o[l],l,i));return a}},arrayReduce={left:createMethod$2(!1),right:createMethod$2(!0)},$$w=_export,$reduce=arrayReduce.left,arrayMethodIsStrict$2=arrayMethodIsStrict$4,CHROME_VERSION=engineV8Version,IS_NODE=engineIsNode,STRICT_METHOD$2=arrayMethodIsStrict$2("reduce"),CHROME_BUG=!IS_NODE&&CHROME_VERSION>79&&CHROME_VERSION<83;$$w({target:"Array",proto:!0,forced:!STRICT_METHOD$2||CHROME_BUG},{reduce:function(e){var t=arguments.length;return $reduce(this,e,t,t>1?arguments[1]:void 0)}});var uncurryThis$b=functionUncurryThis,toObject$4=toObject$e,floor$3=Math.floor,charAt=uncurryThis$b("".charAt),replace=uncurryThis$b("".replace),stringSlice$3=uncurryThis$b("".slice),SUBSTITUTION_SYMBOLS=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,SUBSTITUTION_SYMBOLS_NO_NAMED=/\$([$&'`]|\d{1,2})/g,getSubstitution$1=function(e,t,n,r,a,i){var o=n+e.length,s=r.length,l=SUBSTITUTION_SYMBOLS_NO_NAMED;return void 0!==a&&(a=toObject$4(a),l=SUBSTITUTION_SYMBOLS),replace(i,l,(function(i,l){var u;switch(charAt(l,0)){case"$":return"$";case"&":return e;case"`":return stringSlice$3(t,0,n);case"'":return stringSlice$3(t,o);case"<":u=a[stringSlice$3(l,1,-1)];break;default:var c=+l;if(0===c)return i;if(c>s){var p=floor$3(c/10);return 0===p?i:p<=s?void 0===r[p-1]?charAt(l,1):r[p-1]+charAt(l,1):i}u=r[c-1]}return void 0===u?"":u}))},apply=functionApply,call$1=functionCall,uncurryThis$a=functionUncurryThis,fixRegExpWellKnownSymbolLogic=fixRegexpWellKnownSymbolLogic,fails$7=fails$G,anObject$2=anObject$k,isCallable=isCallable$q,toIntegerOrInfinity$3=toIntegerOrInfinity$7,toLength$2=toLength$6,toString$7=toString$i,requireObjectCoercible$4=requireObjectCoercible$b,advanceStringIndex=advanceStringIndex$2,getMethod=getMethod$5,getSubstitution=getSubstitution$1,regExpExec=regexpExecAbstract,wellKnownSymbol=wellKnownSymbol$q,REPLACE=wellKnownSymbol("replace"),max$1=Math.max,min$2=Math.min,concat=uncurryThis$a([].concat),push$2=uncurryThis$a([].push),stringIndexOf$1=uncurryThis$a("".indexOf),stringSlice$2=uncurryThis$a("".slice),maybeToString=function(e){return void 0===e?e:String(e)},REPLACE_KEEPS_$0="$0"==="a".replace(/./,"$0"),REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE=!!/./[REPLACE]&&""===/./[REPLACE]("a","$0"),REPLACE_SUPPORTS_NAMED_GROUPS=!fails$7((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$")})),ReferenceType;function _classCallCheck$1O(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1O(e,t){for(var n=0;n=f&&(m+=stringSlice$2(o,f,b)+C,f=b+y.length)}return m+stringSlice$2(o,f)}]}),!REPLACE_SUPPORTS_NAMED_GROUPS||!REPLACE_KEEPS_$0||REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE),function(e){e.RELATIVE="RELATIVE",e.ABSOLUTE="ABSOLUTE"}(ReferenceType||(ReferenceType={}));var ColumnAddress=function(){function e(t,n,r){_classCallCheck$1O(this,e),this.type=t,this.col=n,this.sheet=r}return _createClass$1O(e,[{key:"isColumnAbsolute",value:function(){return this.type===ReferenceType.ABSOLUTE}},{key:"isColumnRelative",value:function(){return this.type===ReferenceType.RELATIVE}},{key:"isAbsolute",value:function(){return this.type===ReferenceType.ABSOLUTE&&void 0!==this.sheet}},{key:"moved",value:function(t,n,r){var a=void 0===this.sheet?void 0:t;return new e(this.type,this.col+n,a)}},{key:"shiftedByColumns",value:function(t){return new e(this.type,this.col+t,this.sheet)}},{key:"toSimpleColumnAddress",value:function(e){var t=absoluteSheetReference(this,e),n=this.col;return this.isColumnRelative()&&(n=e.col+this.col),simpleColumnAddress(t,n)}},{key:"shiftRelativeDimensions",value:function(t,n){var r=this.isColumnRelative()?this.col+t:this.col;return new e(this.type,r,this.sheet)}},{key:"shiftAbsoluteDimensions",value:function(t,n){var r=this.isColumnAbsolute()?this.col+t:this.col;return new e(this.type,r,this.sheet)}},{key:"withSheet",value:function(t){return new e(this.type,this.col,t)}},{key:"isInvalid",value:function(e){return this.toSimpleColumnAddress(e).col<0}},{key:"hash",value:function(e){var t=e&&void 0!==this.sheet?"#".concat(this.sheet):"";switch(this.type){case ReferenceType.RELATIVE:return"".concat(t,"#COLR").concat(this.col);case ReferenceType.ABSOLUTE:return"".concat(t,"#COLA").concat(this.col)}}},{key:"unparse",value:function(e){var t=this.toSimpleColumnAddress(e);if(!invalidSimpleColumnAddress(t)){var n=columnIndexToLabel(t.col),r=this.type===ReferenceType.ABSOLUTE?"$":"";return"".concat(r).concat(n)}}},{key:"exceedsSheetSizeLimits",value:function(e){return this.col>=e}}],[{key:"absolute",value:function(t,n){return new e(ReferenceType.ABSOLUTE,t,n)}},{key:"relative",value:function(t,n){return new e(ReferenceType.RELATIVE,t,n)}},{key:"compareByAbsoluteAddress",value:function(e){return function(t,n){return t.toSimpleColumnAddress(e).col-n.toSimpleColumnAddress(e).col}}}]),e}();function _classCallCheck$1N(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1N(e,t){for(var n=0;n=e}}],[{key:"absolute",value:function(t,n){return new e(ReferenceType.ABSOLUTE,t,n)}},{key:"relative",value:function(t,n){return new e(ReferenceType.RELATIVE,t,n)}},{key:"compareByAbsoluteAddress",value:function(e){return function(t,n){return t.toSimpleRowAddress(e).row-n.toSimpleRowAddress(e).row}}}]),e}(),CellReferenceType;function _classCallCheck$1M(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1M(e,t){for(var n=0;n=t||this.col>=e}}],[{key:"fromColAndRow",value:function(t,n,r){var a=t.isColumnAbsolute()&&n.isRowAbsolute()?e.absolute.bind(this):t.isColumnAbsolute()?e.absoluteCol.bind(this):n.isRowAbsolute()?e.absoluteRow.bind(this):function(t,n,r){return e.relative(n,t,r)};return a(t.col,n.row,r)}},{key:"relative",value:function(t,n,r){return new e(n,t,CellReferenceType.CELL_REFERENCE_RELATIVE,r)}},{key:"absolute",value:function(t,n,r){return new e(t,n,CellReferenceType.CELL_REFERENCE_ABSOLUTE,r)}},{key:"absoluteCol",value:function(t,n,r){return new e(t,n,CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL,r)}},{key:"absoluteRow",value:function(t,n,r){return new e(t,n,CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW,r)}}]),e}();function isEmpty(e){return e&&0===e.length}function keys(e){return null==e?[]:Object.keys(e)}function values(e){for(var t=[],n=Object.keys(e),r=0;r=this.input.length)throw Error("Unexpected end of input");this.idx++};var t,n=/[0-9a-fA-F]/,r=/[0-9]/,a=/[1-9]/;function i(e){return e.charCodeAt(0)}function o(e,t){void 0!==e.length?e.forEach((function(e){t.push(e)})):t.push(e)}function s(e,t){if(!0===e[t])throw"duplicate flag "+t;e[t]=!0}function l(e){if(void 0===e)throw Error("Internal Error - Should never get here!")}var u=[];for(t=i("0");t<=i("9");t++)u.push(t);var c=[i("_")].concat(u);for(t=i("a");t<=i("z");t++)c.push(t);for(t=i("A");t<=i("Z");t++)c.push(t);var p=[i(" "),i("\f"),i("\n"),i("\r"),i("\t"),i("\v"),i("\t"),i(" "),i(" "),i(" "),i(" "),i(" "),i(" "),i(" "),i(" "),i(" "),i(" "),i(" "),i(" "),i(" "),i("\u2028"),i("\u2029"),i(" "),i(" "),i(" "),i("\ufeff")];function d(){}return d.prototype.visitChildren=function(e){for(var t in e){var n=e[t];e.hasOwnProperty(t)&&(void 0!==n.type?this.visit(n):Array.isArray(n)&&n.forEach((function(e){this.visit(e)}),this))}},d.prototype.visit=function(e){switch(e.type){case"Pattern":this.visitPattern(e);break;case"Flags":this.visitFlags(e);break;case"Disjunction":this.visitDisjunction(e);break;case"Alternative":this.visitAlternative(e);break;case"StartAnchor":this.visitStartAnchor(e);break;case"EndAnchor":this.visitEndAnchor(e);break;case"WordBoundary":this.visitWordBoundary(e);break;case"NonWordBoundary":this.visitNonWordBoundary(e);break;case"Lookahead":this.visitLookahead(e);break;case"NegativeLookahead":this.visitNegativeLookahead(e);break;case"Character":this.visitCharacter(e);break;case"Set":this.visitSet(e);break;case"Group":this.visitGroup(e);break;case"GroupBackReference":this.visitGroupBackReference(e);break;case"Quantifier":this.visitQuantifier(e)}this.visitChildren(e)},d.prototype.visitPattern=function(e){},d.prototype.visitFlags=function(e){},d.prototype.visitDisjunction=function(e){},d.prototype.visitAlternative=function(e){},d.prototype.visitStartAnchor=function(e){},d.prototype.visitEndAnchor=function(e){},d.prototype.visitWordBoundary=function(e){},d.prototype.visitNonWordBoundary=function(e){},d.prototype.visitLookahead=function(e){},d.prototype.visitNegativeLookahead=function(e){},d.prototype.visitCharacter=function(e){},d.prototype.visitSet=function(e){},d.prototype.visitGroup=function(e){},d.prototype.visitGroupBackReference=function(e){},d.prototype.visitQuantifier=function(e){},{RegExpParser:e,BaseRegExpVisitor:d,VERSION:"0.4.0"}},e.exports?e.exports=n():t.regexpToAst=n()}(regexpToAst);var regExpAstCache={},regExpParser=new regexpToAst.exports.RegExpParser;function getRegExpAst(e){var t=e.toString();if(regExpAstCache.hasOwnProperty(t))return regExpAstCache[t];var n=regExpParser.pattern(t);return regExpAstCache[t]=n,n}function clearRegExpParserCache(){regExpAstCache={}}var __extends$a=(extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},extendStatics(e,t)},function(e,t){function n(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),extendStatics,complementErrorMessage="Complement Sets are not supported for first char optimization",failedOptimizationPrefixMsg='Unable to use "first char" lexer optimizations:\n';function getOptimizedStartCodesIndices(e,t){void 0===t&&(t=!1);try{var n=getRegExpAst(e);return firstCharOptimizedIndices(n.value,{},n.flags.ignoreCase)}catch(n){if(n.message===complementErrorMessage)t&&PRINT_WARNING(failedOptimizationPrefixMsg+"\tUnable to optimize: < "+e.toString()+" >\n\tComplement Sets cannot be automatically optimized.\n\tThis will disable the lexer's first char optimizations.\n\tSee: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.");else{var r="";t&&(r="\n\tThis will disable the lexer's first char optimizations.\n\tSee: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details."),PRINT_ERROR(failedOptimizationPrefixMsg+"\n\tFailed parsing: < "+e.toString()+" >\n\tUsing the regexp-to-ast library version: "+regexpToAst.exports.VERSION+"\n\tPlease open an issue at: https://github.com/bd82/regexp-to-ast/issues"+r)}}return[]}function firstCharOptimizedIndices(e,t,n){switch(e.type){case"Disjunction":for(var r=0;r=minOptimizationVal)for(var i=r.from>=minOptimizationVal?r.from:minOptimizationVal,o=r.to,s=charCodeToOptimizedIndex(i),l=charCodeToOptimizedIndex(o),u=s;u<=l;u++)t[u]=u}}}));break;case"Group":firstCharOptimizedIndices(o.value,t,n);break;default:throw Error("Non Exhaustive Match")}var s=void 0!==o.quantifier&&0===o.quantifier.atLeast;if("Group"===o.type&&!1===isWholeOptional(o)||"Group"!==o.type&&!1===s)break}break;default:throw Error("non exhaustive match!")}return values(t)}function addOptimizedIdxToResult(e,t,n){var r=charCodeToOptimizedIndex(e);t[r]=r,!0===n&&handleIgnoreCase(e,t)}function handleIgnoreCase(e,t){var n=String.fromCharCode(e),r=n.toUpperCase();if(r!==n){t[a=charCodeToOptimizedIndex(r.charCodeAt(0))]=a}else{var a,i=n.toLowerCase();if(i!==n)t[a=charCodeToOptimizedIndex(i.charCodeAt(0))]=a}}function findCode(e,t){return find$1(e.value,(function(e){if("number"==typeof e)return contains(t,e);var n=e;return void 0!==find$1(t,(function(e){return n.from<=e&&e<=n.to}))}))}function isWholeOptional(e){return!(!e.quantifier||0!==e.quantifier.atLeast)||!!e.value&&(isArray$2(e.value)?every(e.value,isWholeOptional):isWholeOptional(e.value))}var CharCodeFinder=function(e){function t(t){var n=e.call(this)||this;return n.targetCharCodes=t,n.found=!1,n}return __extends$a(t,e),t.prototype.visitChildren=function(t){if(!0!==this.found){switch(t.type){case"Lookahead":return void this.visitLookahead(t);case"NegativeLookahead":return void this.visitNegativeLookahead(t)}e.prototype.visitChildren.call(this,t)}},t.prototype.visitCharacter=function(e){contains(this.targetCharCodes,e.value)&&(this.found=!0)},t.prototype.visitSet=function(e){e.complement?void 0===findCode(e,this.targetCharCodes)&&(this.found=!0):void 0!==findCode(e,this.targetCharCodes)&&(this.found=!0)},t}(regexpToAst.exports.BaseRegExpVisitor);function canMatchCharCode(e,t){if(t instanceof RegExp){var n=getRegExpAst(t),r=new CharCodeFinder(e);return r.visit(n),r.found}return void 0!==find$1(t,(function(t){return contains(e,t.charCodeAt(0))}))}var __extends$9=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),PATTERN="PATTERN",DEFAULT_MODE="defaultMode",MODES="modes",SUPPORT_STICKY="boolean"==typeof new RegExp("(?:)").sticky;function analyzeTokenTypes(e,t){var n,r=(t=defaults$4(t,{useSticky:SUPPORT_STICKY,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r","\n"],tracer:function(e,t){return t()}})).tracer;r("initCharCodeToOptimizedIndexMap",(function(){initCharCodeToOptimizedIndexMap()})),r("Reject Lexer.NA",(function(){n=reject(e,(function(e){return e[PATTERN]===Lexer.NA}))}));var a,i,o,s,l,u,c,p,d,m,f,h=!1;r("Transform Patterns",(function(){h=!1,a=map(n,(function(e){var n=e[PATTERN];if(isRegExp(n)){var r=n.source;return 1===r.length&&"^"!==r&&"$"!==r&&"."!==r?r:2!==r.length||"\\"!==r[0]||contains(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],r[1])?t.useSticky?addStickyFlag(n):addStartOfInput(n):r[1]}if(isFunction$1(n))return h=!0,{exec:n};if(has(n,"exec"))return h=!0,n;if("string"==typeof n){if(1===n.length)return n;var a=n.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),i=new RegExp(a);return t.useSticky?addStickyFlag(i):addStartOfInput(i)}throw Error("non exhaustive match")}))})),r("misc mapping",(function(){i=map(n,(function(e){return e.tokenTypeIdx})),o=map(n,(function(e){var t=e.GROUP;if(t!==Lexer.SKIPPED){if(isString$1(t))return t;if(isUndefined$1(t))return!1;throw Error("non exhaustive match")}})),s=map(n,(function(e){var t=e.LONGER_ALT;if(t)return indexOf(n,t)})),l=map(n,(function(e){return e.PUSH_MODE})),u=map(n,(function(e){return has(e,"POP_MODE")}))})),r("Line Terminator Handling",(function(){var e=getCharCodes(t.lineTerminatorCharacters);c=map(n,(function(e){return!1})),"onlyOffset"!==t.positionTracking&&(c=map(n,(function(t){return has(t,"LINE_BREAKS")?t.LINE_BREAKS:!1===checkLineBreaksIssues(t,e)?canMatchCharCode(e,t.PATTERN):void 0})))})),r("Misc Mapping #2",(function(){p=map(n,isCustomPattern),d=map(a,isShortPattern),m=reduce(n,(function(e,t){var n=t.GROUP;return isString$1(n)&&n!==Lexer.SKIPPED&&(e[n]=[]),e}),{}),f=map(a,(function(e,t){return{pattern:a[t],longerAlt:s[t],canLineTerminator:c[t],isCustom:p[t],short:d[t],group:o[t],push:l[t],pop:u[t],tokenTypeIdx:i[t],tokenType:n[t]}}))}));var y=!0,b=[];return t.safeMode||r("First Char Optimization",(function(){b=reduce(n,(function(e,n,r){if("string"==typeof n.PATTERN){var a=charCodeToOptimizedIndex(n.PATTERN.charCodeAt(0));addToMapOfArrays(e,a,f[r])}else if(isArray$2(n.START_CHARS_HINT)){var i;forEach$1(n.START_CHARS_HINT,(function(t){var n=charCodeToOptimizedIndex("string"==typeof t?t.charCodeAt(0):t);i!==n&&(i=n,addToMapOfArrays(e,n,f[r]))}))}else if(isRegExp(n.PATTERN))if(n.PATTERN.unicode)y=!1,t.ensureOptimizations&&PRINT_ERROR(failedOptimizationPrefixMsg+"\tUnable to analyze < "+n.PATTERN.toString()+" > pattern.\n\tThe regexp unicode flag is not currently supported by the regexp-to-ast library.\n\tThis will disable the lexer's first char optimizations.\n\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE");else{var o=getOptimizedStartCodesIndices(n.PATTERN,t.ensureOptimizations);isEmpty(o)&&(y=!1),forEach$1(o,(function(t){addToMapOfArrays(e,t,f[r])}))}else t.ensureOptimizations&&PRINT_ERROR(failedOptimizationPrefixMsg+"\tTokenType: <"+n.name+"> is using a custom token pattern without providing parameter.\n\tThis will disable the lexer's first char optimizations.\n\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE"),y=!1;return e}),[])})),r("ArrayPacking",(function(){b=packArray(b)})),{emptyGroups:m,patternIdxToConfig:f,charCodeToPatternIdxToConfig:b,hasCustom:h,canBeOptimized:y}}function validatePatterns(e,t){var n=[],r=findMissingPatterns(e);n=n.concat(r.errors);var a=findInvalidPatterns(r.valid),i=a.valid;return n=(n=(n=(n=(n=n.concat(a.errors)).concat(validateRegExpPattern(i))).concat(findInvalidGroupType(i))).concat(findModesThatDoNotExist(i,t))).concat(findUnreachablePatterns(i))}function validateRegExpPattern(e){var t=[],n=filter(e,(function(e){return isRegExp(e[PATTERN])}));return t=(t=(t=(t=(t=t.concat(findEndOfInputAnchor(n))).concat(findStartOfInputAnchor(n))).concat(findUnsupportedFlags(n))).concat(findDuplicatePatterns(n))).concat(findEmptyMatchRegExps(n))}function findMissingPatterns(e){var t=filter(e,(function(e){return!has(e,PATTERN)}));return{errors:map(t,(function(e){return{message:"Token Type: ->"+e.name+"<- missing static 'PATTERN' property",type:LexerDefinitionErrorType.MISSING_PATTERN,tokenTypes:[e]}})),valid:difference(e,t)}}function findInvalidPatterns(e){var t=filter(e,(function(e){var t=e[PATTERN];return!(isRegExp(t)||isFunction$1(t)||has(t,"exec")||isString$1(t))}));return{errors:map(t,(function(e){return{message:"Token Type: ->"+e.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:LexerDefinitionErrorType.INVALID_PATTERN,tokenTypes:[e]}})),valid:difference(e,t)}}var end_of_input=/[^\\][\$]/;function findEndOfInputAnchor(e){var t=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.found=!1,t}return __extends$9(t,e),t.prototype.visitEndAnchor=function(e){this.found=!0},t}(regexpToAst.exports.BaseRegExpVisitor);return map(filter(e,(function(e){var n=e[PATTERN];try{var r=getRegExpAst(n),a=new t;return a.visit(r),a.found}catch(e){return end_of_input.test(n.source)}})),(function(e){return{message:"Unexpected RegExp Anchor Error:\n\tToken Type: ->"+e.name+"<- static 'PATTERN' cannot contain end of input anchor '$'\n\tSee sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#ANCHORS\tfor details.",type:LexerDefinitionErrorType.EOI_ANCHOR_FOUND,tokenTypes:[e]}}))}function findEmptyMatchRegExps(e){return map(filter(e,(function(e){return e[PATTERN].test("")})),(function(e){return{message:"Token Type: ->"+e.name+"<- static 'PATTERN' must not match an empty string",type:LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,tokenTypes:[e]}}))}var start_of_input=/[^\\[][\^]|^\^/;function findStartOfInputAnchor(e){var t=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.found=!1,t}return __extends$9(t,e),t.prototype.visitStartAnchor=function(e){this.found=!0},t}(regexpToAst.exports.BaseRegExpVisitor);return map(filter(e,(function(e){var n=e[PATTERN];try{var r=getRegExpAst(n),a=new t;return a.visit(r),a.found}catch(e){return start_of_input.test(n.source)}})),(function(e){return{message:"Unexpected RegExp Anchor Error:\n\tToken Type: ->"+e.name+"<- static 'PATTERN' cannot contain start of input anchor '^'\n\tSee https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#ANCHORS\tfor details.",type:LexerDefinitionErrorType.SOI_ANCHOR_FOUND,tokenTypes:[e]}}))}function findUnsupportedFlags(e){return map(filter(e,(function(e){var t=e[PATTERN];return t instanceof RegExp&&(t.multiline||t.global)})),(function(e){return{message:"Token Type: ->"+e.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[e]}}))}function findDuplicatePatterns(e){var t=[],n=map(e,(function(n){return reduce(e,(function(e,r){return n.PATTERN.source!==r.PATTERN.source||contains(t,r)||r.PATTERN===Lexer.NA||(t.push(r),e.push(r)),e}),[])}));return map(filter(n=compact(n),(function(e){return e.length>1})),(function(e){var t=map(e,(function(e){return e.name}));return{message:"The same RegExp pattern ->"+first$1(e).PATTERN+"<-has been used in all of the following Token Types: "+t.join(", ")+" <-",type:LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,tokenTypes:e}}))}function findInvalidGroupType(e){return map(filter(e,(function(e){if(!has(e,"GROUP"))return!1;var t=e.GROUP;return t!==Lexer.SKIPPED&&t!==Lexer.NA&&!isString$1(t)})),(function(e){return{message:"Token Type: ->"+e.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,tokenTypes:[e]}}))}function findModesThatDoNotExist(e,t){return map(filter(e,(function(e){return void 0!==e.PUSH_MODE&&!contains(t,e.PUSH_MODE)})),(function(e){return{message:"Token Type: ->"+e.name+"<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->"+e.PUSH_MODE+"<-which does not exist",type:LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[e]}}))}function findUnreachablePatterns(e){var t=[],n=reduce(e,(function(e,t,n){var r=t.PATTERN;return r===Lexer.NA||(isString$1(r)?e.push({str:r,idx:n,tokenType:t}):isRegExp(r)&&noMetaChar(r)&&e.push({str:r.source,idx:n,tokenType:t})),e}),[]);return forEach$1(e,(function(e,r){forEach$1(n,(function(n){var a=n.str,i=n.idx,o=n.tokenType;if(r"+e.name+"<-in the lexer's definition.\nSee https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#UNREACHABLE";t.push({message:s,type:LexerDefinitionErrorType.UNREACHABLE_PATTERN,tokenTypes:[e,o]})}}))})),t}function testTokenType(e,t){if(isRegExp(t)){var n=t.exec(e);return null!==n&&0===n.index}if(isFunction$1(t))return t(e,0,[],{});if(has(t,"exec"))return t.exec(e,0,[],{});if("string"==typeof t)return t===e;throw Error("non exhaustive match")}function noMetaChar(e){return void 0===find$1([".","\\","[","]","|","^","$","(",")","?","*","+","{"],(function(t){return-1!==e.source.indexOf(t)}))}function addStartOfInput(e){var t=e.ignoreCase?"i":"";return new RegExp("^(?:"+e.source+")",t)}function addStickyFlag(e){var t=e.ignoreCase?"iy":"y";return new RegExp(""+e.source,t)}function performRuntimeChecks(e,t,n){var r=[];return has(e,DEFAULT_MODE)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+DEFAULT_MODE+"> property in its definition\n",type:LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),has(e,MODES)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+MODES+"> property in its definition\n",type:LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),has(e,MODES)&&has(e,DEFAULT_MODE)&&!has(e.modes,e.defaultMode)&&r.push({message:"A MultiMode Lexer cannot be initialized with a "+DEFAULT_MODE+": <"+e.defaultMode+">which does not exist\n",type:LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),has(e,MODES)&&forEach$1(e.modes,(function(e,t){forEach$1(e,(function(e,n){isUndefined$1(e)&&r.push({message:"A Lexer cannot be initialized using an undefined Token Type. Mode:<"+t+"> at index: <"+n+">\n",type:LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED})}))})),r}function performWarningRuntimeChecks(e,t,n){var r=[],a=!1,i=reject(compact(flatten(mapValues(e.modes,(function(e){return e})))),(function(e){return e[PATTERN]===Lexer.NA})),o=getCharCodes(n);return t&&forEach$1(i,(function(e){var t=checkLineBreaksIssues(e,o);if(!1!==t){var n={message:buildLineBreakIssueMessage(e,t),type:t.issue,tokenType:e};r.push(n)}else has(e,"LINE_BREAKS")?!0===e.LINE_BREAKS&&(a=!0):canMatchCharCode(o,e.PATTERN)&&(a=!0)})),t&&!a&&r.push({message:"Warning: No LINE_BREAKS Found.\n\tThis Lexer has been defined to track line and column information,\n\tBut none of the Token Types can be identified as matching a line terminator.\n\tSee https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \n\tfor details.",type:LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS}),r}function cloneEmptyGroups(e){var t={};return forEach$1(keys(e),(function(n){if(!isArray$2(e[n]))throw Error("non exhaustive match");t[n]=[]})),t}function isCustomPattern(e){var t=e.PATTERN;if(isRegExp(t))return!1;if(isFunction$1(t))return!0;if(has(t,"exec"))return!0;if(isString$1(t))return!1;throw Error("non exhaustive match")}function isShortPattern(e){return!(!isString$1(e)||1!==e.length)&&e.charCodeAt(0)}var LineTerminatorOptimizedTester={test:function(e){for(var t=e.length,n=this.lastIndex;n Token Type\n\t Root cause: "+t.errMsg+".\n\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR";if(t.issue===LexerDefinitionErrorType.CUSTOM_LINE_BREAK)return"Warning: A Custom Token Pattern should specify the option.\n\tThe problem is in the <"+e.name+"> Token Type\n\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK";throw Error("non exhaustive match")}function getCharCodes(e){return map(e,(function(e){return isString$1(e)&&e.length>0?e.charCodeAt(0):e}))}function addToMapOfArrays(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var minOptimizationVal=256;function charCodeToOptimizedIndex(e){return e255?255+~~(e/255):e}}function tokenStructuredMatcher(e,t){var n=e.tokenTypeIdx;return n===t.tokenTypeIdx||!0===t.isParent&&!0===t.categoryMatchesMap[n]}function tokenStructuredMatcherNoCategories(e,t){return e.tokenTypeIdx===t.tokenTypeIdx}var tokenShortNameIdx=1,tokenIdxToClass={};function augmentTokenTypes(e){var t=expandCategories(e);assignTokenDefaultProps(t),assignCategoriesMapProp(t),assignCategoriesTokensProp(t),forEach$1(t,(function(e){e.isParent=e.categoryMatches.length>0}))}function expandCategories(e){for(var t=cloneArr(e),n=e,r=!0;r;){var a=difference(n=compact(flatten(map(n,(function(e){return e.CATEGORIES})))),t);t=t.concat(a),isEmpty(a)?r=!1:n=a}return t}function assignTokenDefaultProps(e){forEach$1(e,(function(e){hasShortKeyProperty(e)||(tokenIdxToClass[tokenShortNameIdx]=e,e.tokenTypeIdx=tokenShortNameIdx++),hasCategoriesProperty(e)&&!isArray$2(e.CATEGORIES)&&(e.CATEGORIES=[e.CATEGORIES]),hasCategoriesProperty(e)||(e.CATEGORIES=[]),hasExtendingTokensTypesProperty(e)||(e.categoryMatches=[]),hasExtendingTokensTypesMapProperty(e)||(e.categoryMatchesMap={})}))}function assignCategoriesTokensProp(e){forEach$1(e,(function(e){e.categoryMatches=[],forEach$1(e.categoryMatchesMap,(function(t,n){e.categoryMatches.push(tokenIdxToClass[n].tokenTypeIdx)}))}))}function assignCategoriesMapProp(e){forEach$1(e,(function(e){singleAssignCategoriesToksMap([],e)}))}function singleAssignCategoriesToksMap(e,t){forEach$1(e,(function(e){t.categoryMatchesMap[e.tokenTypeIdx]=!0})),forEach$1(t.CATEGORIES,(function(n){var r=e.concat(t);contains(r,n)||singleAssignCategoriesToksMap(r,n)}))}function hasShortKeyProperty(e){return has(e,"tokenTypeIdx")}function hasCategoriesProperty(e){return has(e,"CATEGORIES")}function hasExtendingTokensTypesProperty(e){return has(e,"categoryMatches")}function hasExtendingTokensTypesMapProperty(e){return has(e,"categoryMatchesMap")}function isTokenType(e){return has(e,"tokenTypeIdx")}var defaultLexerErrorProvider={buildUnableToPopLexerModeMessage:function(e){return"Unable to pop Lexer Mode after encountering Token ->"+e.image+"<- The Mode Stack is empty"},buildUnexpectedCharactersMessage:function(e,t,n,r,a){return"unexpected character: ->"+e.charAt(t)+"<- at offset: "+t+", skipped "+n+" characters."}},LexerDefinitionErrorType;!function(e){e[e.MISSING_PATTERN=0]="MISSING_PATTERN",e[e.INVALID_PATTERN=1]="INVALID_PATTERN",e[e.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",e[e.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",e[e.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",e[e.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",e[e.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",e[e.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",e[e.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",e[e.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",e[e.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",e[e.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",e[e.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",e[e.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",e[e.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",e[e.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",e[e.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK"}(LexerDefinitionErrorType||(LexerDefinitionErrorType={}));var DEFAULT_LEXER_CONFIG={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:["\n","\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:defaultLexerErrorProvider,traceInitPerf:!1,skipValidations:!1};Object.freeze(DEFAULT_LEXER_CONFIG);var Lexer=function(){function e(e,t){var n=this;if(void 0===t&&(t=DEFAULT_LEXER_CONFIG),this.lexerDefinition=e,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.config=void 0,this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},"boolean"==typeof t)throw Error("The second argument to the Lexer constructor is now an ILexerConfig Object.\na boolean 2nd argument is no longer supported");this.config=merge$2(DEFAULT_LEXER_CONFIG,t);var r=this.config.traceInitPerf;!0===r?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):"number"==typeof r&&(this.traceInitMaxIdent=r,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",(function(){var r,a=!0;n.TRACE_INIT("Lexer Config handling",(function(){if(n.config.lineTerminatorsPattern===DEFAULT_LEXER_CONFIG.lineTerminatorsPattern)n.config.lineTerminatorsPattern=LineTerminatorOptimizedTester;else if(n.config.lineTerminatorCharacters===DEFAULT_LEXER_CONFIG.lineTerminatorCharacters)throw Error("Error: Missing property on the Lexer config.\n\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS");if(t.safeMode&&t.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');n.trackStartLines=/full|onlyStart/i.test(n.config.positionTracking),n.trackEndLines=/full/i.test(n.config.positionTracking),isArray$2(e)?((r={modes:{}}).modes[DEFAULT_MODE]=cloneArr(e),r[DEFAULT_MODE]=DEFAULT_MODE):(a=!1,r=cloneObj(e))})),!1===n.config.skipValidations&&(n.TRACE_INIT("performRuntimeChecks",(function(){n.lexerDefinitionErrors=n.lexerDefinitionErrors.concat(performRuntimeChecks(r,n.trackStartLines,n.config.lineTerminatorCharacters))})),n.TRACE_INIT("performWarningRuntimeChecks",(function(){n.lexerDefinitionWarning=n.lexerDefinitionWarning.concat(performWarningRuntimeChecks(r,n.trackStartLines,n.config.lineTerminatorCharacters))}))),r.modes=r.modes?r.modes:{},forEach$1(r.modes,(function(e,t){r.modes[t]=reject(e,(function(e){return isUndefined$1(e)}))}));var i=keys(r.modes);if(forEach$1(r.modes,(function(e,r){n.TRACE_INIT("Mode: <"+r+"> processing",(function(){var a;(n.modes.push(r),!1===n.config.skipValidations&&n.TRACE_INIT("validatePatterns",(function(){n.lexerDefinitionErrors=n.lexerDefinitionErrors.concat(validatePatterns(e,i))})),isEmpty(n.lexerDefinitionErrors))&&(augmentTokenTypes(e),n.TRACE_INIT("analyzeTokenTypes",(function(){a=analyzeTokenTypes(e,{lineTerminatorCharacters:n.config.lineTerminatorCharacters,positionTracking:t.positionTracking,ensureOptimizations:t.ensureOptimizations,safeMode:t.safeMode,tracer:n.TRACE_INIT.bind(n)})})),n.patternIdxToConfig[r]=a.patternIdxToConfig,n.charCodeToPatternIdxToConfig[r]=a.charCodeToPatternIdxToConfig,n.emptyGroups=merge$2(n.emptyGroups,a.emptyGroups),n.hasCustom=a.hasCustom||n.hasCustom,n.canModeBeOptimized[r]=a.canBeOptimized)}))})),n.defaultMode=r.defaultMode,!isEmpty(n.lexerDefinitionErrors)&&!n.config.deferDefinitionErrorsHandling){var o=map(n.lexerDefinitionErrors,(function(e){return e.message})).join("-----------------------\n");throw new Error("Errors detected in definition of Lexer:\n"+o)}forEach$1(n.lexerDefinitionWarning,(function(e){PRINT_WARNING(e.message)})),n.TRACE_INIT("Choosing sub-methods implementations",(function(){if(SUPPORT_STICKY?(n.chopInput=IDENTITY,n.match=n.matchWithTest):(n.updateLastIndex=NOOP,n.match=n.matchWithExec),a&&(n.handleModes=NOOP),!1===n.trackStartLines&&(n.computeNewColumn=IDENTITY),!1===n.trackEndLines&&(n.updateTokenEndLineColumnLocation=NOOP),/full/i.test(n.config.positionTracking))n.createTokenInstance=n.createFullToken;else if(/onlyStart/i.test(n.config.positionTracking))n.createTokenInstance=n.createStartOnlyToken;else{if(!/onlyOffset/i.test(n.config.positionTracking))throw Error('Invalid config option: "'+n.config.positionTracking+'"');n.createTokenInstance=n.createOffsetOnlyToken}n.hasCustom?(n.addToken=n.addTokenUsingPush,n.handlePayload=n.handlePayloadWithCustom):(n.addToken=n.addTokenUsingMemberAccess,n.handlePayload=n.handlePayloadNoCustom)})),n.TRACE_INIT("Failed Optimization Warnings",(function(){var e=reduce(n.canModeBeOptimized,(function(e,t,n){return!1===t&&e.push(n),e}),[]);if(t.ensureOptimizations&&!isEmpty(e))throw Error("Lexer Modes: < "+e.join(", ")+' > cannot be optimized.\n\t Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.\n\t Or inspect the console log for details on how to resolve these issues.')})),n.TRACE_INIT("clearRegExpParserCache",(function(){clearRegExpParserCache()})),n.TRACE_INIT("toFastProperties",(function(){toFastProperties(n)}))}))}return e.prototype.tokenize=function(e,t){if(void 0===t&&(t=this.defaultMode),!isEmpty(this.lexerDefinitionErrors)){var n=map(this.lexerDefinitionErrors,(function(e){return e.message})).join("-----------------------\n");throw new Error("Unable to Tokenize because Errors detected in definition of Lexer:\n"+n)}return this.tokenizeInternal(e,t)},e.prototype.tokenizeInternal=function(e,t){var n,r,a,i,o,s,l,u,c,p,d,m,f,h,y=this,b=e,g=b.length,v=0,T=0,N=this.hasCustom?0:Math.floor(e.length/10),C=new Array(N),A=[],S=this.trackStartLines?1:void 0,x=this.trackStartLines?1:void 0,w=cloneEmptyGroups(this.emptyGroups),V=this.trackStartLines,E=this.config.lineTerminatorsPattern,O=0,_=[],$=[],D=[],I=[];Object.freeze(I);var R=void 0;function P(){return _}function k(e){var t=charCodeToOptimizedIndex(e),n=$[t];return void 0===n?I:n}var M,F=function(e){if(1===D.length&&void 0===e.tokenType.PUSH_MODE){var t=y.config.errorMessageProvider.buildUnableToPopLexerModeMessage(e);A.push({offset:e.startOffset,line:void 0!==e.startLine?e.startLine:void 0,column:void 0!==e.startColumn?e.startColumn:void 0,length:e.image.length,message:t})}else{D.pop();var n=last(D);_=y.patternIdxToConfig[n],$=y.charCodeToPatternIdxToConfig[n],O=_.length;var r=y.canModeBeOptimized[n]&&!1===y.config.safeMode;R=$&&r?k:P}};function B(e){D.push(e),$=this.charCodeToPatternIdxToConfig[e],_=this.patternIdxToConfig[e],O=_.length,O=_.length;var t=this.canModeBeOptimized[e]&&!1===this.config.safeMode;R=$&&t?k:P}for(B.call(this,t);vo.length&&(o=a,s=l,M=G)}break}}if(null!==o){if(u=o.length,void 0!==(c=M.group)&&(p=M.tokenTypeIdx,d=this.createTokenInstance(o,v,p,M.tokenType,S,x,u),this.handlePayload(d,s),!1===c?T=this.addToken(C,T,d):w[c].push(d)),e=this.chopInput(e,u),v+=u,x=this.computeNewColumn(x,u),!0===V&&!0===M.canLineTerminator){var q=0,W=void 0,K=void 0;E.lastIndex=0;do{!0===(W=E.test(o))&&(K=E.lastIndex-1,q++)}while(!0===W);0!==q&&(S+=q,x=u-K,this.updateTokenEndLineColumnLocation(d,c,K,q,S,x,u))}this.handleModes(M,F,B,d)}else{for(var X=v,Z=S,Y=x,J=!1;!J&&v");var r=timer(t),a=r.time,i=r.value,o=a>10?console.warn:console.log;return this.traceInitIndent time: "+a+"ms"),this.traceInitIndent--,i}return t()},e.SKIPPED="This marks a skipped Token pattern, this means each token identified by it willbe consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.",e.NA=/NOT_APPLICABLE/,e}();function tokenLabel(e){return hasTokenLabel(e)?e.LABEL:e.name}function hasTokenLabel(e){return isString$1(e.LABEL)&&""!==e.LABEL}var PARENT="parent",CATEGORIES="categories",LABEL="label",GROUP="group",PUSH_MODE="push_mode",POP_MODE="pop_mode",LONGER_ALT="longer_alt",LINE_BREAKS="line_breaks",START_CHARS_HINT="start_chars_hint";function createToken(e){return createTokenInternal(e)}function createTokenInternal(e){var t=e.pattern,n={};if(n.name=e.name,isUndefined$1(t)||(n.PATTERN=t),has(e,PARENT))throw"The parent property is no longer supported.\nSee: https://github.com/SAP/chevrotain/issues/564#issuecomment-349062346 for details.";return has(e,CATEGORIES)&&(n.CATEGORIES=e[CATEGORIES]),augmentTokenTypes([n]),has(e,LABEL)&&(n.LABEL=e[LABEL]),has(e,GROUP)&&(n.GROUP=e[GROUP]),has(e,POP_MODE)&&(n.POP_MODE=e[POP_MODE]),has(e,PUSH_MODE)&&(n.PUSH_MODE=e[PUSH_MODE]),has(e,LONGER_ALT)&&(n.LONGER_ALT=e[LONGER_ALT]),has(e,LINE_BREAKS)&&(n.LINE_BREAKS=e[LINE_BREAKS]),has(e,START_CHARS_HINT)&&(n.START_CHARS_HINT=e[START_CHARS_HINT]),n}var EOF=createToken({name:"EOF",pattern:Lexer.NA});function createTokenInstance(e,t,n,r,a,i,o,s){return{image:t,startOffset:n,endOffset:r,startLine:a,endLine:i,startColumn:o,endColumn:s,tokenTypeIdx:e.tokenTypeIdx,tokenType:e}}function tokenMatcher(e,t){return tokenStructuredMatcher(e,t)}augmentTokenTypes([EOF]);var __extends$8=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),AbstractProduction=function(){function e(e){this.definition=e}return e.prototype.accept=function(e){e.visit(this),forEach$1(this.definition,(function(t){t.accept(e)}))},e}(),NonTerminal=function(e){function t(t){var n=e.call(this,[])||this;return n.idx=1,assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),Object.defineProperty(t.prototype,"definition",{get:function(){return void 0!==this.referencedRule?this.referencedRule.definition:[]},set:function(e){},enumerable:!0,configurable:!0}),t.prototype.accept=function(e){e.visit(this)},t}(AbstractProduction),Rule=function(e){function t(t){var n=e.call(this,t.definition)||this;return n.orgText="",assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),t}(AbstractProduction),Flat=function(e){function t(t){var n=e.call(this,t.definition)||this;return n.ignoreAmbiguities=!1,assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),t}(AbstractProduction),Option=function(e){function t(t){var n=e.call(this,t.definition)||this;return n.idx=1,assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),t}(AbstractProduction),RepetitionMandatory=function(e){function t(t){var n=e.call(this,t.definition)||this;return n.idx=1,assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),t}(AbstractProduction),RepetitionMandatoryWithSeparator=function(e){function t(t){var n=e.call(this,t.definition)||this;return n.idx=1,assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),t}(AbstractProduction),Repetition=function(e){function t(t){var n=e.call(this,t.definition)||this;return n.idx=1,assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),t}(AbstractProduction),RepetitionWithSeparator=function(e){function t(t){var n=e.call(this,t.definition)||this;return n.idx=1,assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),t}(AbstractProduction),Alternation=function(e){function t(t){var n=e.call(this,t.definition)||this;return n.idx=1,n.ignoreAmbiguities=!1,n.hasPredicates=!1,assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),t}(AbstractProduction),Terminal=function(){function e(e){this.idx=1,assign(this,pick(e,(function(e){return void 0!==e})))}return e.prototype.accept=function(e){e.visit(this)},e}();function serializeGrammar(e){return map(e,serializeProduction)}function serializeProduction(e){function t(e){return map(e,serializeProduction)}if(e instanceof NonTerminal)return{type:"NonTerminal",name:e.nonTerminalName,idx:e.idx};if(e instanceof Flat)return{type:"Flat",definition:t(e.definition)};if(e instanceof Option)return{type:"Option",idx:e.idx,definition:t(e.definition)};if(e instanceof RepetitionMandatory)return{type:"RepetitionMandatory",name:e.name,idx:e.idx,definition:t(e.definition)};if(e instanceof RepetitionMandatoryWithSeparator)return{type:"RepetitionMandatoryWithSeparator",name:e.name,idx:e.idx,separator:serializeProduction(new Terminal({terminalType:e.separator})),definition:t(e.definition)};if(e instanceof RepetitionWithSeparator)return{type:"RepetitionWithSeparator",name:e.name,idx:e.idx,separator:serializeProduction(new Terminal({terminalType:e.separator})),definition:t(e.definition)};if(e instanceof Repetition)return{type:"Repetition",name:e.name,idx:e.idx,definition:t(e.definition)};if(e instanceof Alternation)return{type:"Alternation",name:e.name,idx:e.idx,definition:t(e.definition)};if(e instanceof Terminal){var n={type:"Terminal",name:e.terminalType.name,label:tokenLabel(e.terminalType),idx:e.idx},r=e.terminalType.PATTERN;return e.terminalType.PATTERN&&(n.pattern=isRegExp(r)?r.source:r),n}if(e instanceof Rule)return{type:"Rule",name:e.name,orgText:e.orgText,definition:t(e.definition)};throw Error("non exhaustive match")}var RestWalker=function(){function e(){}return e.prototype.walk=function(e,t){var n=this;void 0===t&&(t=[]),forEach$1(e.definition,(function(r,a){var i=drop(e.definition,a+1);if(r instanceof NonTerminal)n.walkProdRef(r,i,t);else if(r instanceof Terminal)n.walkTerminal(r,i,t);else if(r instanceof Flat)n.walkFlat(r,i,t);else if(r instanceof Option)n.walkOption(r,i,t);else if(r instanceof RepetitionMandatory)n.walkAtLeastOne(r,i,t);else if(r instanceof RepetitionMandatoryWithSeparator)n.walkAtLeastOneSep(r,i,t);else if(r instanceof RepetitionWithSeparator)n.walkManySep(r,i,t);else if(r instanceof Repetition)n.walkMany(r,i,t);else{if(!(r instanceof Alternation))throw Error("non exhaustive match");n.walkOr(r,i,t)}}))},e.prototype.walkTerminal=function(e,t,n){},e.prototype.walkProdRef=function(e,t,n){},e.prototype.walkFlat=function(e,t,n){var r=t.concat(n);this.walk(e,r)},e.prototype.walkOption=function(e,t,n){var r=t.concat(n);this.walk(e,r)},e.prototype.walkAtLeastOne=function(e,t,n){var r=[new Option({definition:e.definition})].concat(t,n);this.walk(e,r)},e.prototype.walkAtLeastOneSep=function(e,t,n){var r=restForRepetitionWithSeparator(e,t,n);this.walk(e,r)},e.prototype.walkMany=function(e,t,n){var r=[new Option({definition:e.definition})].concat(t,n);this.walk(e,r)},e.prototype.walkManySep=function(e,t,n){var r=restForRepetitionWithSeparator(e,t,n);this.walk(e,r)},e.prototype.walkOr=function(e,t,n){var r=this,a=t.concat(n);forEach$1(e.definition,(function(e){var t=new Flat({definition:[e]});r.walk(t,a)}))},e}();function restForRepetitionWithSeparator(e,t,n){return[new Option({definition:[new Terminal({terminalType:e.separator})].concat(e.definition)})].concat(t,n)}var GAstVisitor=function(){function e(){}return e.prototype.visit=function(e){var t=e;switch(t.constructor){case NonTerminal:return this.visitNonTerminal(t);case Flat:return this.visitFlat(t);case Option:return this.visitOption(t);case RepetitionMandatory:return this.visitRepetitionMandatory(t);case RepetitionMandatoryWithSeparator:return this.visitRepetitionMandatoryWithSeparator(t);case RepetitionWithSeparator:return this.visitRepetitionWithSeparator(t);case Repetition:return this.visitRepetition(t);case Alternation:return this.visitAlternation(t);case Terminal:return this.visitTerminal(t);case Rule:return this.visitRule(t);default:throw Error("non exhaustive match")}},e.prototype.visitNonTerminal=function(e){},e.prototype.visitFlat=function(e){},e.prototype.visitOption=function(e){},e.prototype.visitRepetition=function(e){},e.prototype.visitRepetitionMandatory=function(e){},e.prototype.visitRepetitionMandatoryWithSeparator=function(e){},e.prototype.visitRepetitionWithSeparator=function(e){},e.prototype.visitAlternation=function(e){},e.prototype.visitTerminal=function(e){},e.prototype.visitRule=function(e){},e}(),__extends$7=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();function isSequenceProd(e){return e instanceof Flat||e instanceof Option||e instanceof Repetition||e instanceof RepetitionMandatory||e instanceof RepetitionMandatoryWithSeparator||e instanceof RepetitionWithSeparator||e instanceof Terminal||e instanceof Rule}function isOptionalProd(e,t){return void 0===t&&(t=[]),!!(e instanceof Option||e instanceof Repetition||e instanceof RepetitionWithSeparator)||(e instanceof Alternation?some(e.definition,(function(e){return isOptionalProd(e,t)})):!(e instanceof NonTerminal&&contains(t,e))&&(e instanceof AbstractProduction&&(e instanceof NonTerminal&&t.push(e),every(e.definition,(function(e){return isOptionalProd(e,t)})))))}function isBranchingProd(e){return e instanceof Alternation}function getProductionDslName(e){if(e instanceof NonTerminal)return"SUBRULE";if(e instanceof Option)return"OPTION";if(e instanceof Alternation)return"OR";if(e instanceof RepetitionMandatory)return"AT_LEAST_ONE";if(e instanceof RepetitionMandatoryWithSeparator)return"AT_LEAST_ONE_SEP";if(e instanceof RepetitionWithSeparator)return"MANY_SEP";if(e instanceof Repetition)return"MANY";if(e instanceof Terminal)return"CONSUME";throw Error("non exhaustive match")}var DslMethodsCollectorVisitor=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.separator="-",t.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]},t}return __extends$7(t,e),t.prototype.reset=function(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}},t.prototype.visitTerminal=function(e){var t=e.terminalType.name+this.separator+"Terminal";has(this.dslMethods,t)||(this.dslMethods[t]=[]),this.dslMethods[t].push(e)},t.prototype.visitNonTerminal=function(e){var t=e.nonTerminalName+this.separator+"Terminal";has(this.dslMethods,t)||(this.dslMethods[t]=[]),this.dslMethods[t].push(e)},t.prototype.visitOption=function(e){this.dslMethods.option.push(e)},t.prototype.visitRepetitionWithSeparator=function(e){this.dslMethods.repetitionWithSeparator.push(e)},t.prototype.visitRepetitionMandatory=function(e){this.dslMethods.repetitionMandatory.push(e)},t.prototype.visitRepetitionMandatoryWithSeparator=function(e){this.dslMethods.repetitionMandatoryWithSeparator.push(e)},t.prototype.visitRepetition=function(e){this.dslMethods.repetition.push(e)},t.prototype.visitAlternation=function(e){this.dslMethods.alternation.push(e)},t}(GAstVisitor),collectorVisitor=new DslMethodsCollectorVisitor;function collectMethods(e){collectorVisitor.reset(),e.accept(collectorVisitor);var t=collectorVisitor.dslMethods;return collectorVisitor.reset(),t}function first(e){if(e instanceof NonTerminal)return first(e.referencedRule);if(e instanceof Terminal)return firstForTerminal(e);if(isSequenceProd(e))return firstForSequence(e);if(isBranchingProd(e))return firstForBranching(e);throw Error("non exhaustive match")}function firstForSequence(e){for(var t,n=[],r=e.definition,a=0,i=r.length>a,o=!0;i&&o;)o=isOptionalProd(t=r[a]),n=n.concat(first(t)),a+=1,i=r.length>a;return uniq(n)}function firstForBranching(e){return uniq(flatten(map(e.definition,(function(e){return first(e)}))))}function firstForTerminal(e){return[e.terminalType]}var IN="_~IN~_",__extends$6=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),ResyncFollowsWalker=function(e){function t(t){var n=e.call(this)||this;return n.topProd=t,n.follows={},n}return __extends$6(t,e),t.prototype.startWalking=function(){return this.walk(this.topProd),this.follows},t.prototype.walkTerminal=function(e,t,n){},t.prototype.walkProdRef=function(e,t,n){var r=buildBetweenProdsFollowPrefix(e.referencedRule,e.idx)+this.topProd.name,a=t.concat(n),i=first(new Flat({definition:a}));this.follows[r]=i},t}(RestWalker);function computeAllProdsFollows(e){var t={};return forEach$1(e,(function(e){var n=new ResyncFollowsWalker(e).startWalking();assign(t,n)})),t}function buildBetweenProdsFollowPrefix(e,t){return e.name+t+IN}var BITS_FOR_METHOD_TYPE=4,BITS_FOR_OCCURRENCE_IDX=8,BITS_FOR_ALT_IDX=8,OR_IDX=1<1;forEach$1(e.definition,(function(r,a){if(!isUndefined$1(r.name)){var i=r.definition;i=n?[new Option({definition:r.definition})]:r.definition;var o=getKeyForAltIndex(t.ruleIdx,OR_IDX,e.idx,a);t.result.push({def:i,key:o,name:r.name,orgProd:r})}}))},t}(GAstVisitor);function expandAllNestedRuleNames(e,t){var n={allRuleNames:[]};return forEach$1(e,(function(e){var r=t[e.name];n.allRuleNames.push(e.name);var a=new NamedDSLMethodsCollectorVisitor(r);e.accept(a),forEach$1(a.result,(function(t){t.def,t.key;var r=t.name;n.allRuleNames.push(e.name+r)}))})),n}var __extends$4=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),AbstractNextPossibleTokensWalker=function(e){function t(t,n){var r=e.call(this)||this;return r.topProd=t,r.path=n,r.possibleTokTypes=[],r.nextProductionName="",r.nextProductionOccurrence=0,r.found=!1,r.isAtEndOfPath=!1,r}return __extends$4(t,e),t.prototype.startWalking=function(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=cloneArr(this.path.ruleStack).reverse(),this.occurrenceStack=cloneArr(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes},t.prototype.walk=function(t,n){void 0===n&&(n=[]),this.found||e.prototype.walk.call(this,t,n)},t.prototype.walkProdRef=function(e,t,n){if(e.referencedRule.name===this.nextProductionName&&e.idx===this.nextProductionOccurrence){var r=t.concat(n);this.updateExpectedNext(),this.walk(e.referencedRule,r)}},t.prototype.updateExpectedNext=function(){isEmpty(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())},t}(RestWalker),NextAfterTokenWalker=function(e){function t(t,n){var r=e.call(this,t,n)||this;return r.path=n,r.nextTerminalName="",r.nextTerminalOccurrence=0,r.nextTerminalName=r.path.lastTok.name,r.nextTerminalOccurrence=r.path.lastTokOccurrence,r}return __extends$4(t,e),t.prototype.walkTerminal=function(e,t,n){if(this.isAtEndOfPath&&e.terminalType.name===this.nextTerminalName&&e.idx===this.nextTerminalOccurrence&&!this.found){var r=t.concat(n),a=new Flat({definition:r});this.possibleTokTypes=first(a),this.found=!0}},t}(AbstractNextPossibleTokensWalker),AbstractNextTerminalAfterProductionWalker=function(e){function t(t,n){var r=e.call(this)||this;return r.topRule=t,r.occurrence=n,r.result={token:void 0,occurrence:void 0,isEndOfRule:void 0},r}return __extends$4(t,e),t.prototype.startWalking=function(){return this.walk(this.topRule),this.result},t}(RestWalker),NextTerminalAfterManyWalker=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$4(t,e),t.prototype.walkMany=function(t,n,r){if(t.idx===this.occurrence){var a=first$1(n.concat(r));this.result.isEndOfRule=void 0===a,a instanceof Terminal&&(this.result.token=a.terminalType,this.result.occurrence=a.idx)}else e.prototype.walkMany.call(this,t,n,r)},t}(AbstractNextTerminalAfterProductionWalker),NextTerminalAfterManySepWalker=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$4(t,e),t.prototype.walkManySep=function(t,n,r){if(t.idx===this.occurrence){var a=first$1(n.concat(r));this.result.isEndOfRule=void 0===a,a instanceof Terminal&&(this.result.token=a.terminalType,this.result.occurrence=a.idx)}else e.prototype.walkManySep.call(this,t,n,r)},t}(AbstractNextTerminalAfterProductionWalker),NextTerminalAfterAtLeastOneWalker=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$4(t,e),t.prototype.walkAtLeastOne=function(t,n,r){if(t.idx===this.occurrence){var a=first$1(n.concat(r));this.result.isEndOfRule=void 0===a,a instanceof Terminal&&(this.result.token=a.terminalType,this.result.occurrence=a.idx)}else e.prototype.walkAtLeastOne.call(this,t,n,r)},t}(AbstractNextTerminalAfterProductionWalker),NextTerminalAfterAtLeastOneSepWalker=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$4(t,e),t.prototype.walkAtLeastOneSep=function(t,n,r){if(t.idx===this.occurrence){var a=first$1(n.concat(r));this.result.isEndOfRule=void 0===a,a instanceof Terminal&&(this.result.token=a.terminalType,this.result.occurrence=a.idx)}else e.prototype.walkAtLeastOneSep.call(this,t,n,r)},t}(AbstractNextTerminalAfterProductionWalker);function possiblePathsFrom(e,t,n){void 0===n&&(n=[]),n=cloneArr(n);var r=[],a=0;function i(i){var o=possiblePathsFrom(i.concat(drop(e,a+1)),t,n);return r.concat(o)}for(;n.length=0;V--){var E={idx:f,def:b.definition[V].definition.concat(drop(m)),ruleStack:h,occurrenceStack:y};p.push(E),p.push(o)}else if(b instanceof Flat)p.push({idx:f,def:b.definition.concat(drop(m)),ruleStack:h,occurrenceStack:y});else{if(!(b instanceof Rule))throw Error("non exhaustive match");p.push(expandTopLevelRule(b,f,h,y))}}}else s&&last(p).idx<=u&&p.pop()}return c}function expandTopLevelRule(e,t,n,r){var a=cloneArr(n);a.push(e.name);var i=cloneArr(r);return i.push(1),{idx:t,def:e.definition,ruleStack:a,occurrenceStack:i}}var __extends$3=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),PROD_TYPE;function getProdType(e){if(e instanceof Option)return PROD_TYPE.OPTION;if(e instanceof Repetition)return PROD_TYPE.REPETITION;if(e instanceof RepetitionMandatory)return PROD_TYPE.REPETITION_MANDATORY;if(e instanceof RepetitionMandatoryWithSeparator)return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR;if(e instanceof RepetitionWithSeparator)return PROD_TYPE.REPETITION_WITH_SEPARATOR;if(e instanceof Alternation)return PROD_TYPE.ALTERNATION;throw Error("non exhaustive match")}function buildLookaheadFuncForOr(e,t,n,r,a,i){var o=getLookaheadPathsForOr(e,t,n);return i(o,r,areTokenCategoriesNotUsed(o)?tokenStructuredMatcherNoCategories:tokenStructuredMatcher,a)}function buildLookaheadFuncForOptionalProd(e,t,n,r,a,i){var o=getLookaheadPathsForOptionalProd(e,t,a,n),s=areTokenCategoriesNotUsed(o)?tokenStructuredMatcherNoCategories:tokenStructuredMatcher;return i(o[0],s,r)}function buildAlternativesLookAheadFunc(e,t,n,r){var a=e.length,i=every(e,(function(e){return every(e,(function(e){return 1===e.length}))}));if(t)return function(t){for(var r=map(t,(function(e){return e.GATE})),i=0;i1}))),(function(n){var r=first$1(n),a=t.buildDuplicateFoundError(e,n),i=getProductionDslName(r),o={message:a,type:ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,ruleName:e.name,dslName:i,occurrence:r.idx},s=getExtraProductionArgument(r);return s&&(o.parameter=s),o}))}function identifyProductionForDuplicates(e){return getProductionDslName(e)+"_#_"+e.idx+"_#_"+getExtraProductionArgument(e)}function getExtraProductionArgument(e){return e instanceof Terminal?e.terminalType.name:e instanceof NonTerminal?e.nonTerminalName:""}var OccurrenceValidationCollector=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.allProductions=[],t}return __extends$2(t,e),t.prototype.visitNonTerminal=function(e){this.allProductions.push(e)},t.prototype.visitOption=function(e){this.allProductions.push(e)},t.prototype.visitRepetitionWithSeparator=function(e){this.allProductions.push(e)},t.prototype.visitRepetitionMandatory=function(e){this.allProductions.push(e)},t.prototype.visitRepetitionMandatoryWithSeparator=function(e){this.allProductions.push(e)},t.prototype.visitRepetition=function(e){this.allProductions.push(e)},t.prototype.visitAlternation=function(e){this.allProductions.push(e)},t.prototype.visitTerminal=function(e){this.allProductions.push(e)},t}(GAstVisitor),validTermsPattern=/^[a-zA-Z_]\w*$/,validNestedRuleName=new RegExp(validTermsPattern.source.replace("^","^\\$"));function validateRuleName(e,t){var n=[],r=e.name;return r.match(validTermsPattern)||n.push({message:t.buildInvalidRuleNameError({topLevelRule:e,expectedPattern:validTermsPattern}),type:ParserDefinitionErrorType.INVALID_RULE_NAME,ruleName:r}),n}function validateNestedRuleName(e,t,n){var r,a=[];return t.name.match(validNestedRuleName)||(r=n.buildInvalidNestedRuleNameError(e,t),a.push({message:r,type:ParserDefinitionErrorType.INVALID_NESTED_RULE_NAME,ruleName:e.name})),a}function validateTokenName(e,t){var n=[];return e.name.match(validTermsPattern)||n.push({message:t.buildTokenNameError({tokenType:e,expectedPattern:validTermsPattern}),type:ParserDefinitionErrorType.INVALID_TOKEN_NAME}),n}function validateRuleDoesNotAlreadyExist(e,t,n,r){var a=[];if(reduce(t,(function(t,n){return n.name===e.name?t+1:t}),0)>1){var i=r.buildDuplicateRuleNameError({topLevelRule:e,grammarName:n});a.push({message:i,type:ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:e.name})}return a}function validateRuleIsOverridden(e,t,n){var r,a=[];return contains(t,e)||(r="Invalid rule override, rule: ->"+e+"<- cannot be overridden in the grammar: ->"+n+"<-as it is not defined in any of the super grammars ",a.push({message:r,type:ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,ruleName:e})),a}function validateNoLeftRecursion(e,t,n,r){void 0===r&&(r=[]);var a=[],i=getFirstNoneTerminal(t.definition);if(isEmpty(i))return[];var o=e.name;contains(i,e)&&a.push({message:n.buildLeftRecursionError({topLevelRule:e,leftRecursionPath:r}),type:ParserDefinitionErrorType.LEFT_RECURSION,ruleName:o});var s=map(difference(i,r.concat([e])),(function(t){var a=cloneArr(r);return a.push(t),validateNoLeftRecursion(e,t,n,a)}));return a.concat(flatten(s))}function getFirstNoneTerminal(e){var t=[];if(isEmpty(e))return t;var n=first$1(e);if(n instanceof NonTerminal)t.push(n.referencedRule);else if(n instanceof Flat||n instanceof Option||n instanceof RepetitionMandatory||n instanceof RepetitionMandatoryWithSeparator||n instanceof RepetitionWithSeparator||n instanceof Repetition)t=t.concat(getFirstNoneTerminal(n.definition));else if(n instanceof Alternation)t=flatten(map(n.definition,(function(e){return getFirstNoneTerminal(e.definition)})));else if(!(n instanceof Terminal))throw Error("non exhaustive match");var r=isOptionalProd(n),a=e.length>1;if(r&&a){var i=drop(e);return t.concat(getFirstNoneTerminal(i))}return t}var OrCollector=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.alternations=[],t}return __extends$2(t,e),t.prototype.visitAlternation=function(e){this.alternations.push(e)},t}(GAstVisitor);function validateEmptyOrAlternative(e,t){var n=new OrCollector;return e.accept(n),reduce(n.alternations,(function(n,r){var a=map(dropRight(r.definition),(function(n,a){return isEmpty(nextPossibleTokensAfter([n],[],null,1))?{message:t.buildEmptyAlternationError({topLevelRule:e,alternation:r,emptyChoiceIdx:a}),type:ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,ruleName:e.name,occurrence:r.idx,alternative:a+1}:null}));return n.concat(compact(a))}),[])}function validateAmbiguousAlternationAlternatives(e,t,n,r){var a=new OrCollector;e.accept(a);var i=a.alternations,o=n[e.name];return o&&(i=reject(i,(function(e){return o[getProductionDslName(e)+(0===e.idx?"":e.idx)]}))),reduce(i=reject(i,(function(e){return!0===e.ignoreAmbiguities})),(function(n,a){var i=a.idx,o=a.maxLookahead||t,s=getLookaheadPathsForOr(i,e,o,a),l=checkAlternativesAmbiguities(s,a,e,r),u=checkPrefixAlternativesAmbiguities(s,a,e,r);return n.concat(l,u)}),[])}var RepetionCollector=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.allProductions=[],t}return __extends$2(t,e),t.prototype.visitRepetitionWithSeparator=function(e){this.allProductions.push(e)},t.prototype.visitRepetitionMandatory=function(e){this.allProductions.push(e)},t.prototype.visitRepetitionMandatoryWithSeparator=function(e){this.allProductions.push(e)},t.prototype.visitRepetition=function(e){this.allProductions.push(e)},t}(GAstVisitor);function validateTooManyAlts(e,t){var n=new OrCollector;return e.accept(n),reduce(n.alternations,(function(n,r){return r.definition.length>255&&n.push({message:t.buildTooManyAlternativesError({topLevelRule:e,alternation:r}),type:ParserDefinitionErrorType.TOO_MANY_ALTS,ruleName:e.name,occurrence:r.idx}),n}),[])}function validateSomeNonEmptyLookaheadPath(e,t,n){var r=[];return forEach$1(e,(function(e){var a=new RepetionCollector;e.accept(a),forEach$1(a.allProductions,(function(a){var i=getProdType(a),o=a.maxLookahead||t;if(isEmpty(flatten(getLookaheadPathsForOptionalProd(a.idx,e,i,o)[0]))){var s=n.buildEmptyRepetitionError({topLevelRule:e,repetition:a});r.push({message:s,type:ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,ruleName:e.name})}}))})),r}function checkAlternativesAmbiguities(e,t,n,r){var a=[];return map(reduce(e,(function(n,r,i){return!0===t.definition[i].ignoreAmbiguities||forEach$1(r,(function(r){var o=[i];forEach$1(e,(function(e,n){i!==n&&containsPath(e,r)&&!0!==t.definition[n].ignoreAmbiguities&&o.push(n)})),o.length>1&&!containsPath(a,r)&&(a.push(r),n.push({alts:o,path:r}))})),n}),[]),(function(e){var a=map(e.alts,(function(e){return e+1}));return{message:r.buildAlternationAmbiguityError({topLevelRule:n,alternation:t,ambiguityIndices:a,prefixPath:e.path}),type:ParserDefinitionErrorType.AMBIGUOUS_ALTS,ruleName:n.name,occurrence:t.idx,alternatives:[e.alts]}}))}function checkPrefixAlternativesAmbiguities(e,t,n,r){var a=[],i=reduce(e,(function(e,t,n){var r=map(t,(function(e){return{idx:n,path:e}}));return e.concat(r)}),[]);return forEach$1(i,(function(e){if(!0!==t.definition[e.idx].ignoreAmbiguities){var o=e.idx,s=e.path,l=map(findAll(i,(function(e){return!0!==t.definition[e.idx].ignoreAmbiguities&&e.idx1}))),(function(r){var a=map(r,(function(e){return e.orgProd})),i=t.buildDuplicateNestedRuleNameError(e,a);n.push({message:i,type:ParserDefinitionErrorType.DUPLICATE_NESTED_NAME,ruleName:e.name})}))})),n}var defaultParserErrorProvider={buildMismatchTokenMessage:function(e){var t=e.expected,n=e.actual;return e.previous,e.ruleName,"Expecting "+(hasTokenLabel(t)?"--\x3e "+tokenLabel(t)+" <--":"token of type --\x3e "+t.name+" <--")+" but found --\x3e '"+n.image+"' <--"},buildNotAllInputParsedMessage:function(e){var t=e.firstRedundant;return e.ruleName,"Redundant input, expecting EOF but found: "+t.image},buildNoViableAltMessage:function(e){var t=e.expectedPathsPerAlt,n=e.actual;e.previous;var r=e.customUserDescription;e.ruleName;var a="Expecting: ",i="\nbut found: '"+first$1(n).image+"'";if(r)return a+r+i;var o=map(reduce(t,(function(e,t){return e.concat(t)}),[]),(function(e){return"["+map(e,(function(e){return tokenLabel(e)})).join(", ")+"]"}));return a+("one of these possible Token sequences:\n"+map(o,(function(e,t){return" "+(t+1)+". "+e})).join("\n"))+i},buildEarlyExitMessage:function(e){var t=e.expectedIterationPaths,n=e.actual,r=e.customUserDescription;e.ruleName;var a="Expecting: ",i="\nbut found: '"+first$1(n).image+"'";return r?a+r+i:a+("expecting at least one iteration which starts with one of these possible Token sequences::\n <"+map(t,(function(e){return"["+map(e,(function(e){return tokenLabel(e)})).join(",")+"]"})).join(" ,")+">")+i}};Object.freeze(defaultParserErrorProvider);var defaultGrammarResolverErrorProvider={buildRuleNotFoundError:function(e,t){return"Invalid grammar, reference to a rule which is not defined: ->"+t.nonTerminalName+"<-\ninside top level rule: ->"+e.name+"<-"}},defaultGrammarValidatorErrorProvider={buildDuplicateFoundError:function(e,t){var n,r=e.name,a=first$1(t),i=a.idx,o=getProductionDslName(a),s=(n=a)instanceof Terminal?n.terminalType.name:n instanceof NonTerminal?n.nonTerminalName:"",l="->"+o+(i>0?i:"")+"<- "+(s?"with argument: ->"+s+"<-":"")+"\n appears more than once ("+t.length+" times) in the top level rule: ->"+r+"<-. \n For further details see: https://sap.github.io/chevrotain/docs/FAQ.html#NUMERICAL_SUFFIXES \n ";return l=(l=l.replace(/[ \t]+/g," ")).replace(/\s\s+/g,"\n")},buildInvalidNestedRuleNameError:function(e,t){return"Invalid nested rule name: ->"+t.name+"<- inside rule: ->"+e.name+"<-\nit must match the pattern: ->"+validNestedRuleName.toString()+"<-.\nNote that this means a nested rule name must start with the '$'(dollar) sign."},buildDuplicateNestedRuleNameError:function(e,t){return"Duplicate nested rule name: ->"+first$1(t).name+"<- inside rule: ->"+e.name+"<-\nA nested name must be unique in the scope of a top level grammar rule."},buildNamespaceConflictError:function(e){return"Namespace conflict found in grammar.\nThe grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <"+e.name+">.\nTo resolve this make sure each Terminal and Non-Terminal names are unique\nThis is easy to accomplish by using the convention that Terminal names start with an uppercase letter\nand Non-Terminal names start with a lower case letter."},buildAlternationPrefixAmbiguityError:function(e){var t=map(e.prefixPath,(function(e){return tokenLabel(e)})).join(", "),n=0===e.alternation.idx?"":e.alternation.idx;return"Ambiguous alternatives: <"+e.ambiguityIndices.join(" ,")+"> due to common lookahead prefix\nin inside <"+e.topLevelRule.name+"> Rule,\n<"+t+"> may appears as a prefix path in all these alternatives.\nSee: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX\nFor Further details."},buildAlternationAmbiguityError:function(e){var t=map(e.prefixPath,(function(e){return tokenLabel(e)})).join(", "),n=0===e.alternation.idx?"":e.alternation.idx,r="Ambiguous Alternatives Detected: <"+e.ambiguityIndices.join(" ,")+"> in inside <"+e.topLevelRule.name+"> Rule,\n<"+t+"> may appears as a prefix path in all these alternatives.\n";return r+="See: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES\nFor Further details."},buildEmptyRepetitionError:function(e){var t=getProductionDslName(e.repetition);return 0!==e.repetition.idx&&(t+=e.repetition.idx),"The repetition <"+t+"> within Rule <"+e.topLevelRule.name+"> can never consume any tokens.\nThis could lead to an infinite loop."},buildTokenNameError:function(e){return"Invalid Grammar Token name: ->"+e.tokenType.name+"<- it must match the pattern: ->"+e.expectedPattern.toString()+"<-"},buildEmptyAlternationError:function(e){return"Ambiguous empty alternative: <"+(e.emptyChoiceIdx+1)+"> in inside <"+e.topLevelRule.name+"> Rule.\nOnly the last alternative may be an empty alternative."},buildTooManyAlternativesError:function(e){return"An Alternation cannot have more than 256 alternatives:\n inside <"+e.topLevelRule.name+"> Rule.\n has "+(e.alternation.definition.length+1)+" alternatives."},buildLeftRecursionError:function(e){var t=e.topLevelRule.name;return"Left Recursion found in grammar.\nrule: <"+t+"> can be invoked from itself (directly or indirectly)\nwithout consuming any Tokens. The grammar path that causes this is: \n "+(t+" --\x3e "+map(e.leftRecursionPath,(function(e){return e.name})).concat([t]).join(" --\x3e "))+"\n To fix this refactor your grammar to remove the left recursion.\nsee: https://en.wikipedia.org/wiki/LL_parser#Left_Factoring."},buildInvalidRuleNameError:function(e){return"Invalid grammar rule name: ->"+e.topLevelRule.name+"<- it must match the pattern: ->"+e.expectedPattern.toString()+"<-"},buildDuplicateRuleNameError:function(e){return"Duplicate definition, rule: ->"+(e.topLevelRule instanceof Rule?e.topLevelRule.name:e.topLevelRule)+"<- is already defined in the grammar: ->"+e.grammarName+"<-"}},__extends$1=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();function resolveGrammar$1(e,t){var n=new GastRefResolverVisitor(e,t);return n.resolveRefs(),n.errors}var GastRefResolverVisitor=function(e){function t(t,n){var r=e.call(this)||this;return r.nameToTopRule=t,r.errMsgProvider=n,r.errors=[],r}return __extends$1(t,e),t.prototype.resolveRefs=function(){var e=this;forEach$1(values(this.nameToTopRule),(function(t){e.currTopLevel=t,t.accept(e)}))},t.prototype.visitNonTerminal=function(e){var t=this.nameToTopRule[e.nonTerminalName];if(t)e.referencedRule=t;else{var n=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,e);this.errors.push({message:n,type:ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:e.nonTerminalName})}},t}(GAstVisitor);function resolveGrammar(e){e=defaults$4(e,{errMsgProvider:defaultGrammarResolverErrorProvider});var t={};return forEach$1(e.rules,(function(e){t[e.name]=e})),resolveGrammar$1(t,e.errMsgProvider)}function validateGrammar(e){return validateGrammar$1((e=defaults$4(e,{errMsgProvider:defaultGrammarValidatorErrorProvider,ignoredIssues:{}})).rules,e.maxLookahead,e.tokenTypes,e.ignoredIssues,e.errMsgProvider,e.grammarName)}var MISMATCHED_TOKEN_EXCEPTION="MismatchedTokenException",NO_VIABLE_ALT_EXCEPTION="NoViableAltException",EARLY_EXIT_EXCEPTION="EarlyExitException",NOT_ALL_INPUT_PARSED_EXCEPTION="NotAllInputParsedException",RECOGNITION_EXCEPTION_NAMES=[MISMATCHED_TOKEN_EXCEPTION,NO_VIABLE_ALT_EXCEPTION,EARLY_EXIT_EXCEPTION,NOT_ALL_INPUT_PARSED_EXCEPTION];function isRecognitionException(e){return contains(RECOGNITION_EXCEPTION_NAMES,e.name)}function MismatchedTokenException(e,t,n){this.name=MISMATCHED_TOKEN_EXCEPTION,this.message=e,this.token=t,this.previousToken=n,this.resyncedTokens=[]}function NoViableAltException(e,t,n){this.name=NO_VIABLE_ALT_EXCEPTION,this.message=e,this.token=t,this.previousToken=n,this.resyncedTokens=[]}function NotAllInputParsedException(e,t){this.name=NOT_ALL_INPUT_PARSED_EXCEPTION,this.message=e,this.token=t,this.resyncedTokens=[]}function EarlyExitException(e,t,n){this.name=EARLY_EXIT_EXCEPTION,this.message=e,this.token=t,this.previousToken=n,this.resyncedTokens=[]}Object.freeze(RECOGNITION_EXCEPTION_NAMES),MismatchedTokenException.prototype=Error.prototype,NoViableAltException.prototype=Error.prototype,NotAllInputParsedException.prototype=Error.prototype,EarlyExitException.prototype=Error.prototype;var EOF_FOLLOW_KEY={},IN_RULE_RECOVERY_EXCEPTION="InRuleRecoveryException";function InRuleRecoveryException(e){this.name=IN_RULE_RECOVERY_EXCEPTION,this.message=e}InRuleRecoveryException.prototype=Error.prototype;var Recoverable=function(){function e(){}return e.prototype.initRecoverable=function(e){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=has(e,"recoveryEnabled")?e.recoveryEnabled:DEFAULT_PARSER_CONFIG.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=attemptInRepetitionRecovery)},e.prototype.getTokenToInsert=function(e){var t=createTokenInstance(e,"",NaN,NaN,NaN,NaN,NaN,NaN);return t.isInsertedInRecovery=!0,t},e.prototype.canTokenTypeBeInsertedInRecovery=function(e){return!0},e.prototype.tryInRepetitionRecovery=function(e,t,n,r){for(var a=this,i=this.findReSyncTokenType(),o=this.exportLexerState(),s=[],l=!1,u=this.LA(1),c=this.LA(1),p=function(){var e=a.LA(0),t=new MismatchedTokenException(a.errorMessageProvider.buildMismatchTokenMessage({expected:r,actual:u,previous:e,ruleName:a.getCurrRuleFullName()}),u,a.LA(0));t.resyncedTokens=dropRight(s),a.SAVE_ERROR(t)};!l;){if(this.tokenMatcher(c,r))return void p();if(n.call(this))return p(),void e.apply(this,t);this.tokenMatcher(c,i)?l=!0:(c=this.SKIP_TOKEN(),this.addToResyncTokens(c,s))}this.importLexerState(o)},e.prototype.shouldInRepetitionRecoveryBeTried=function(e,t,n){return!1!==n&&(void 0!==e&&void 0!==t&&(!this.tokenMatcher(this.LA(1),e)&&(!this.isBackTracking()&&!this.canPerformInRuleRecovery(e,this.getFollowsForInRuleRecovery(e,t)))))},e.prototype.getFollowsForInRuleRecovery=function(e,t){var n=this.getCurrentGrammarPath(e,t);return this.getNextPossibleTokenTypes(n)},e.prototype.tryInRuleRecovery=function(e,t){if(this.canRecoverWithSingleTokenInsertion(e,t))return this.getTokenToInsert(e);if(this.canRecoverWithSingleTokenDeletion(e)){var n=this.SKIP_TOKEN();return this.consumeToken(),n}throw new InRuleRecoveryException("sad sad panda")},e.prototype.canPerformInRuleRecovery=function(e,t){return this.canRecoverWithSingleTokenInsertion(e,t)||this.canRecoverWithSingleTokenDeletion(e)},e.prototype.canRecoverWithSingleTokenInsertion=function(e,t){var n=this;if(!this.canTokenTypeBeInsertedInRecovery(e))return!1;if(isEmpty(t))return!1;var r=this.LA(1);return void 0!==find$1(t,(function(e){return n.tokenMatcher(r,e)}))},e.prototype.canRecoverWithSingleTokenDeletion=function(e){return this.tokenMatcher(this.LA(2),e)},e.prototype.isInCurrentRuleReSyncSet=function(e){var t=this.getCurrFollowKey();return contains(this.getFollowSetFromFollowKey(t),e)},e.prototype.findReSyncTokenType=function(){for(var e=this.flattenFollowSet(),t=this.LA(1),n=2;;){var r=t.tokenType;if(contains(e,r))return r;t=this.LA(n),n++}},e.prototype.getCurrFollowKey=function(){if(1===this.RULE_STACK.length)return EOF_FOLLOW_KEY;var e=this.getLastExplicitRuleShortName(),t=this.getLastExplicitRuleOccurrenceIndex(),n=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(e),idxInCallingRule:t,inRule:this.shortRuleNameToFullName(n)}},e.prototype.buildFullFollowKeyStack=function(){var e=this,t=this.RULE_STACK,n=this.RULE_OCCURRENCE_STACK;return isEmpty(this.LAST_EXPLICIT_RULE_STACK)||(t=map(this.LAST_EXPLICIT_RULE_STACK,(function(t){return e.RULE_STACK[t]})),n=map(this.LAST_EXPLICIT_RULE_STACK,(function(t){return e.RULE_OCCURRENCE_STACK[t]}))),map(t,(function(r,a){return 0===a?EOF_FOLLOW_KEY:{ruleName:e.shortRuleNameToFullName(r),idxInCallingRule:n[a],inRule:e.shortRuleNameToFullName(t[a-1])}}))},e.prototype.flattenFollowSet=function(){var e=this;return flatten(map(this.buildFullFollowKeyStack(),(function(t){return e.getFollowSetFromFollowKey(t)})))},e.prototype.getFollowSetFromFollowKey=function(e){if(e===EOF_FOLLOW_KEY)return[EOF];var t=e.ruleName+e.idxInCallingRule+IN+e.inRule;return this.resyncFollows[t]},e.prototype.addToResyncTokens=function(e,t){return this.tokenMatcher(e,EOF)||t.push(e),t},e.prototype.reSyncTo=function(e){for(var t=[],n=this.LA(1);!1===this.tokenMatcher(n,e);)n=this.SKIP_TOKEN(),this.addToResyncTokens(n,t);return dropRight(t)},e.prototype.attemptInRepetitionRecovery=function(e,t,n,r,a,i,o){},e.prototype.getCurrentGrammarPath=function(e,t){return{ruleStack:this.getHumanReadableRuleStack(),occurrenceStack:cloneArr(this.RULE_OCCURRENCE_STACK),lastTok:e,lastTokOccurrence:t}},e.prototype.getHumanReadableRuleStack=function(){var e=this;return isEmpty(this.LAST_EXPLICIT_RULE_STACK)?map(this.RULE_STACK,(function(t){return e.shortRuleNameToFullName(t)})):map(this.LAST_EXPLICIT_RULE_STACK,(function(t){return e.shortRuleNameToFullName(e.RULE_STACK[t])}))},e}();function attemptInRepetitionRecovery(e,t,n,r,a,i,o){var s=this.getKeyForAutomaticLookahead(r,a),l=this.firstAfterRepMap[s];if(void 0===l){var u=this.getCurrRuleFullName();l=new i(this.getGAstProductions()[u],a).startWalking(),this.firstAfterRepMap[s]=l}var c=l.token,p=l.occurrence,d=l.isEndOfRule;1===this.RULE_STACK.length&&d&&void 0===c&&(c=EOF,p=1),this.shouldInRepetitionRecoveryBeTried(c,p,o)&&this.tryInRepetitionRecovery(e,t,n,c)}var LooksAhead=function(){function e(){}return e.prototype.initLooksAhead=function(e){this.dynamicTokensEnabled=has(e,"dynamicTokensEnabled")?e.dynamicTokensEnabled:DEFAULT_PARSER_CONFIG.dynamicTokensEnabled,this.maxLookahead=has(e,"maxLookahead")?e.maxLookahead:DEFAULT_PARSER_CONFIG.maxLookahead,this.lookAheadFuncsCache=isES2015MapSupported()?new Map:[],isES2015MapSupported()?(this.getLaFuncFromCache=this.getLaFuncFromMap,this.setLaFuncCache=this.setLaFuncCacheUsingMap):(this.getLaFuncFromCache=this.getLaFuncFromObj,this.setLaFuncCache=this.setLaFuncUsingObj)},e.prototype.preComputeLookaheadFunctions=function(e){var t=this;forEach$1(e,(function(e){t.TRACE_INIT(e.name+" Rule Lookahead",(function(){var n=collectMethods(e),r=n.alternation,a=n.repetition,i=n.option,o=n.repetitionMandatory,s=n.repetitionMandatoryWithSeparator,l=n.repetitionWithSeparator;forEach$1(r,(function(n){var r=0===n.idx?"":n.idx;t.TRACE_INIT(""+getProductionDslName(n)+r,(function(){var r=buildLookaheadFuncForOr(n.idx,e,n.maxLookahead||t.maxLookahead,n.hasPredicates,t.dynamicTokensEnabled,t.lookAheadBuilderForAlternatives),a=getKeyForAutomaticLookahead(t.fullRuleNameToShort[e.name],OR_IDX,n.idx);t.setLaFuncCache(a,r)}))})),forEach$1(a,(function(n){t.computeLookaheadFunc(e,n.idx,MANY_IDX,PROD_TYPE.REPETITION,n.maxLookahead,getProductionDslName(n))})),forEach$1(i,(function(n){t.computeLookaheadFunc(e,n.idx,OPTION_IDX,PROD_TYPE.OPTION,n.maxLookahead,getProductionDslName(n))})),forEach$1(o,(function(n){t.computeLookaheadFunc(e,n.idx,AT_LEAST_ONE_IDX,PROD_TYPE.REPETITION_MANDATORY,n.maxLookahead,getProductionDslName(n))})),forEach$1(s,(function(n){t.computeLookaheadFunc(e,n.idx,AT_LEAST_ONE_SEP_IDX,PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,n.maxLookahead,getProductionDslName(n))})),forEach$1(l,(function(n){t.computeLookaheadFunc(e,n.idx,MANY_SEP_IDX,PROD_TYPE.REPETITION_WITH_SEPARATOR,n.maxLookahead,getProductionDslName(n))}))}))}))},e.prototype.computeLookaheadFunc=function(e,t,n,r,a,i){var o=this;this.TRACE_INIT(""+i+(0===t?"":t),(function(){var i=buildLookaheadFuncForOptionalProd(t,e,a||o.maxLookahead,o.dynamicTokensEnabled,r,o.lookAheadBuilderForOptional),s=getKeyForAutomaticLookahead(o.fullRuleNameToShort[e.name],n,t);o.setLaFuncCache(s,i)}))},e.prototype.lookAheadBuilderForOptional=function(e,t,n){return buildSingleAlternativeLookaheadFunction(e,t,n)},e.prototype.lookAheadBuilderForAlternatives=function(e,t,n,r){return buildAlternativesLookAheadFunc(e,t,n,r)},e.prototype.getKeyForAutomaticLookahead=function(e,t){return getKeyForAutomaticLookahead(this.getLastExplicitRuleShortName(),e,t)},e.prototype.getLaFuncFromCache=function(e){},e.prototype.getLaFuncFromMap=function(e){return this.lookAheadFuncsCache.get(e)},e.prototype.getLaFuncFromObj=function(e){return this.lookAheadFuncsCache[e]},e.prototype.setLaFuncCache=function(e,t){},e.prototype.setLaFuncCacheUsingMap=function(e,t){this.lookAheadFuncsCache.set(e,t)},e.prototype.setLaFuncUsingObj=function(e,t){this.lookAheadFuncsCache[e]=t},e}();function classNameFromInstance(e){return functionName(e.constructor)}var FUNC_NAME_REGEXP=/^\s*function\s*(\S*)\s*\(/,NAME="name",CstVisitorDefinitionError;function functionName(e){var t=e.name;return t||e.toString().match(FUNC_NAME_REGEXP)[1]}function defineNameProp(e,t){var n=Object.getOwnPropertyDescriptor(e,NAME);return!(!isUndefined$1(n)&&!n.configurable)&&(Object.defineProperty(e,NAME,{enumerable:!1,configurable:!0,writable:!1,value:t}),!0)}function defaultVisit(e,t){for(var n=keys(e),r=n.length,a=0;a:\n\t"+n.join("\n\n").replace(/\n/g,"\n\t"))}}}).constructor=n,n._RULE_NAMES=t,n}function createBaseVisitorConstructorWithDefaults(e,t,n){var r=function(){};defineNameProp(r,e+"BaseSemanticsWithDefaults");var a=Object.create(n.prototype);return forEach$1(t,(function(e){a[e]=defaultVisit})),(r.prototype=a).constructor=r,r}function validateVisitor(e,t){var n=validateMissingCstMethods(e,t),r=validateRedundantMethods(e,t);return n.concat(r)}function validateMissingCstMethods(e,t){return compact(map(t,(function(t){if(!isFunction$1(e[t]))return{msg:"Missing visitor method: <"+t+"> on "+functionName(e.constructor)+" CST Visitor.",type:CstVisitorDefinitionError.MISSING_METHOD,methodName:t}})))}!function(e){e[e.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",e[e.MISSING_METHOD=1]="MISSING_METHOD"}(CstVisitorDefinitionError||(CstVisitorDefinitionError={}));var VALID_PROP_NAMES=["constructor","visit","validateVisitor"];function validateRedundantMethods(e,t){var n=[];for(var r in e)validTermsPattern.test(r)&&isFunction$1(e[r])&&!contains(VALID_PROP_NAMES,r)&&!contains(t,r)&&n.push({msg:"Redundant visitor method: <"+r+"> on "+functionName(e.constructor)+" CST Visitor\nThere is no Grammar Rule corresponding to this method's name.\nFor utility methods on visitor classes use methods names that do not match /"+validTermsPattern.source+"/.",type:CstVisitorDefinitionError.REDUNDANT_METHOD,methodName:r});return n}var TreeBuilder=function(){function e(){}return e.prototype.initTreeBuilder=function(e){if(this.LAST_EXPLICIT_RULE_STACK=[],this.CST_STACK=[],this.outputCst=has(e,"outputCst")?e.outputCst:DEFAULT_PARSER_CONFIG.outputCst,this.nodeLocationTracking=has(e,"nodeLocationTracking")?e.nodeLocationTracking:DEFAULT_PARSER_CONFIG.nodeLocationTracking,this.outputCst)if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=setNodeLocationFull,this.setNodeLocationFromNode=setNodeLocationFull,this.cstPostRule=NOOP,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=NOOP,this.setNodeLocationFromNode=NOOP,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=setNodeLocationOnlyOffset,this.setNodeLocationFromNode=setNodeLocationOnlyOffset,this.cstPostRule=NOOP,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=NOOP,this.setNodeLocationFromNode=NOOP,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else{if(!/none/i.test(this.nodeLocationTracking))throw Error('Invalid config option: "'+e.nodeLocationTracking+'"');this.setNodeLocationFromToken=NOOP,this.setNodeLocationFromNode=NOOP,this.cstPostRule=NOOP,this.setInitialNodeLocation=NOOP}else this.cstInvocationStateUpdate=NOOP,this.cstFinallyStateUpdate=NOOP,this.cstPostTerminal=NOOP,this.cstPostNonTerminal=NOOP,this.cstPostRule=NOOP,this.getLastExplicitRuleShortName=this.getLastExplicitRuleShortNameNoCst,this.getPreviousExplicitRuleShortName=this.getPreviousExplicitRuleShortNameNoCst,this.getLastExplicitRuleOccurrenceIndex=this.getLastExplicitRuleOccurrenceIndexNoCst,this.manyInternal=this.manyInternalNoCst,this.orInternal=this.orInternalNoCst,this.optionInternal=this.optionInternalNoCst,this.atLeastOneInternal=this.atLeastOneInternalNoCst,this.manySepFirstInternal=this.manySepFirstInternalNoCst,this.atLeastOneSepFirstInternal=this.atLeastOneSepFirstInternalNoCst},e.prototype.setInitialNodeLocationOnlyOffsetRecovery=function(e){e.location={startOffset:NaN,endOffset:NaN}},e.prototype.setInitialNodeLocationOnlyOffsetRegular=function(e){e.location={startOffset:this.LA(1).startOffset,endOffset:NaN}},e.prototype.setInitialNodeLocationFullRecovery=function(e){e.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}},e.prototype.setInitialNodeLocationFullRegular=function(e){var t=this.LA(1);e.location={startOffset:t.startOffset,startLine:t.startLine,startColumn:t.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}},e.prototype.cstNestedInvocationStateUpdate=function(e,t){var n={name:e,fullName:this.shortRuleNameToFull[this.getLastExplicitRuleShortName()]+e,children:{}};this.setInitialNodeLocation(n),this.CST_STACK.push(n)},e.prototype.cstInvocationStateUpdate=function(e,t){this.LAST_EXPLICIT_RULE_STACK.push(this.RULE_STACK.length-1);var n={name:e,children:{}};this.setInitialNodeLocation(n),this.CST_STACK.push(n)},e.prototype.cstFinallyStateUpdate=function(){this.LAST_EXPLICIT_RULE_STACK.pop(),this.CST_STACK.pop()},e.prototype.cstNestedFinallyStateUpdate=function(){var e=this.CST_STACK.pop();this.cstPostRule(e)},e.prototype.cstPostRuleFull=function(e){var t=this.LA(0),n=e.location;n.startOffset<=t.startOffset==!0?(n.endOffset=t.endOffset,n.endLine=t.endLine,n.endColumn=t.endColumn):(n.startOffset=NaN,n.startLine=NaN,n.startColumn=NaN)},e.prototype.cstPostRuleOnlyOffset=function(e){var t=this.LA(0),n=e.location;n.startOffset<=t.startOffset==!0?n.endOffset=t.endOffset:n.startOffset=NaN},e.prototype.cstPostTerminal=function(e,t){var n=this.CST_STACK[this.CST_STACK.length-1];addTerminalToCst(n,t,e),this.setNodeLocationFromToken(n.location,t)},e.prototype.cstPostNonTerminal=function(e,t){if(!0!==this.isBackTracking()){var n=this.CST_STACK[this.CST_STACK.length-1];addNoneTerminalToCst(n,t,e),this.setNodeLocationFromNode(n.location,e.location)}},e.prototype.getBaseCstVisitorConstructor=function(){if(isUndefined$1(this.baseCstVisitorConstructor)){var e=createBaseSemanticVisitorConstructor(this.className,this.allRuleNames);return this.baseCstVisitorConstructor=e,e}return this.baseCstVisitorConstructor},e.prototype.getBaseCstVisitorConstructorWithDefaults=function(){if(isUndefined$1(this.baseCstVisitorWithDefaultsConstructor)){var e=createBaseVisitorConstructorWithDefaults(this.className,this.allRuleNames,this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=e,e}return this.baseCstVisitorWithDefaultsConstructor},e.prototype.nestedRuleBeforeClause=function(e,t){var n;return void 0!==e.NAME?(n=e.NAME,this.nestedRuleInvocationStateUpdate(n,t),n):void 0},e.prototype.nestedAltBeforeClause=function(e,t,n,r){var a,i=getKeyForAltIndex(this.getLastExplicitRuleShortName(),n,t,r);return void 0!==e.NAME?(a=e.NAME,this.nestedRuleInvocationStateUpdate(a,i),{shortName:i,nestedName:a}):void 0},e.prototype.nestedRuleFinallyClause=function(e,t){var n=this.CST_STACK,r=n[n.length-1];this.nestedRuleFinallyStateUpdate();var a=n[n.length-1];addNoneTerminalToCst(a,t,r),this.setNodeLocationFromNode(a.location,r.location)},e.prototype.getLastExplicitRuleShortName=function(){var e=this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length-1];return this.RULE_STACK[e]},e.prototype.getLastExplicitRuleShortNameNoCst=function(){var e=this.RULE_STACK;return e[e.length-1]},e.prototype.getPreviousExplicitRuleShortName=function(){var e=this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length-2];return this.RULE_STACK[e]},e.prototype.getPreviousExplicitRuleShortNameNoCst=function(){var e=this.RULE_STACK;return e[e.length-2]},e.prototype.getLastExplicitRuleOccurrenceIndex=function(){var e=this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length-1];return this.RULE_OCCURRENCE_STACK[e]},e.prototype.getLastExplicitRuleOccurrenceIndexNoCst=function(){var e=this.RULE_OCCURRENCE_STACK;return e[e.length-1]},e.prototype.nestedRuleInvocationStateUpdate=function(e,t){this.RULE_OCCURRENCE_STACK.push(1),this.RULE_STACK.push(t),this.cstNestedInvocationStateUpdate(e,t)},e.prototype.nestedRuleFinallyStateUpdate=function(){this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstNestedFinallyStateUpdate()},e}(),LexerAdapter=function(){function e(){}return e.prototype.initLexerAdapter=function(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1},Object.defineProperty(e.prototype,"input",{get:function(){return this.tokVector},set:function(e){if(!0!==this.selfAnalysisDone)throw Error("Missing invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=e,this.tokVectorLength=e.length},enumerable:!0,configurable:!0}),e.prototype.SKIP_TOKEN=function(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):END_OF_FILE},e.prototype.LA=function(e){var t=this.currIdx+e;return t<0||this.tokVectorLength<=t?END_OF_FILE:this.tokVector[t]},e.prototype.consumeToken=function(){this.currIdx++},e.prototype.exportLexerState=function(){return this.currIdx},e.prototype.importLexerState=function(e){this.currIdx=e},e.prototype.resetLexerState=function(){this.currIdx=-1},e.prototype.moveToTerminatedState=function(){this.currIdx=this.tokVector.length-1},e.prototype.getLexerPosition=function(){return this.exportLexerState()},e}(),RecognizerApi=function(){function e(){}return e.prototype.ACTION=function(e){return e.call(this)},e.prototype.consume=function(e,t,n){return this.consumeInternal(t,e,n)},e.prototype.subrule=function(e,t,n){return this.subruleInternal(t,e,n)},e.prototype.option=function(e,t){return this.optionInternal(t,e)},e.prototype.or=function(e,t){return this.orInternal(t,e)},e.prototype.many=function(e,t){return this.manyInternal(e,t)},e.prototype.atLeastOne=function(e,t){return this.atLeastOneInternal(e,t)},e.prototype.CONSUME=function(e,t){return this.consumeInternal(e,0,t)},e.prototype.CONSUME1=function(e,t){return this.consumeInternal(e,1,t)},e.prototype.CONSUME2=function(e,t){return this.consumeInternal(e,2,t)},e.prototype.CONSUME3=function(e,t){return this.consumeInternal(e,3,t)},e.prototype.CONSUME4=function(e,t){return this.consumeInternal(e,4,t)},e.prototype.CONSUME5=function(e,t){return this.consumeInternal(e,5,t)},e.prototype.CONSUME6=function(e,t){return this.consumeInternal(e,6,t)},e.prototype.CONSUME7=function(e,t){return this.consumeInternal(e,7,t)},e.prototype.CONSUME8=function(e,t){return this.consumeInternal(e,8,t)},e.prototype.CONSUME9=function(e,t){return this.consumeInternal(e,9,t)},e.prototype.SUBRULE=function(e,t){return this.subruleInternal(e,0,t)},e.prototype.SUBRULE1=function(e,t){return this.subruleInternal(e,1,t)},e.prototype.SUBRULE2=function(e,t){return this.subruleInternal(e,2,t)},e.prototype.SUBRULE3=function(e,t){return this.subruleInternal(e,3,t)},e.prototype.SUBRULE4=function(e,t){return this.subruleInternal(e,4,t)},e.prototype.SUBRULE5=function(e,t){return this.subruleInternal(e,5,t)},e.prototype.SUBRULE6=function(e,t){return this.subruleInternal(e,6,t)},e.prototype.SUBRULE7=function(e,t){return this.subruleInternal(e,7,t)},e.prototype.SUBRULE8=function(e,t){return this.subruleInternal(e,8,t)},e.prototype.SUBRULE9=function(e,t){return this.subruleInternal(e,9,t)},e.prototype.OPTION=function(e){return this.optionInternal(e,0)},e.prototype.OPTION1=function(e){return this.optionInternal(e,1)},e.prototype.OPTION2=function(e){return this.optionInternal(e,2)},e.prototype.OPTION3=function(e){return this.optionInternal(e,3)},e.prototype.OPTION4=function(e){return this.optionInternal(e,4)},e.prototype.OPTION5=function(e){return this.optionInternal(e,5)},e.prototype.OPTION6=function(e){return this.optionInternal(e,6)},e.prototype.OPTION7=function(e){return this.optionInternal(e,7)},e.prototype.OPTION8=function(e){return this.optionInternal(e,8)},e.prototype.OPTION9=function(e){return this.optionInternal(e,9)},e.prototype.OR=function(e){return this.orInternal(e,0)},e.prototype.OR1=function(e){return this.orInternal(e,1)},e.prototype.OR2=function(e){return this.orInternal(e,2)},e.prototype.OR3=function(e){return this.orInternal(e,3)},e.prototype.OR4=function(e){return this.orInternal(e,4)},e.prototype.OR5=function(e){return this.orInternal(e,5)},e.prototype.OR6=function(e){return this.orInternal(e,6)},e.prototype.OR7=function(e){return this.orInternal(e,7)},e.prototype.OR8=function(e){return this.orInternal(e,8)},e.prototype.OR9=function(e){return this.orInternal(e,9)},e.prototype.MANY=function(e){this.manyInternal(0,e)},e.prototype.MANY1=function(e){this.manyInternal(1,e)},e.prototype.MANY2=function(e){this.manyInternal(2,e)},e.prototype.MANY3=function(e){this.manyInternal(3,e)},e.prototype.MANY4=function(e){this.manyInternal(4,e)},e.prototype.MANY5=function(e){this.manyInternal(5,e)},e.prototype.MANY6=function(e){this.manyInternal(6,e)},e.prototype.MANY7=function(e){this.manyInternal(7,e)},e.prototype.MANY8=function(e){this.manyInternal(8,e)},e.prototype.MANY9=function(e){this.manyInternal(9,e)},e.prototype.MANY_SEP=function(e){this.manySepFirstInternal(0,e)},e.prototype.MANY_SEP1=function(e){this.manySepFirstInternal(1,e)},e.prototype.MANY_SEP2=function(e){this.manySepFirstInternal(2,e)},e.prototype.MANY_SEP3=function(e){this.manySepFirstInternal(3,e)},e.prototype.MANY_SEP4=function(e){this.manySepFirstInternal(4,e)},e.prototype.MANY_SEP5=function(e){this.manySepFirstInternal(5,e)},e.prototype.MANY_SEP6=function(e){this.manySepFirstInternal(6,e)},e.prototype.MANY_SEP7=function(e){this.manySepFirstInternal(7,e)},e.prototype.MANY_SEP8=function(e){this.manySepFirstInternal(8,e)},e.prototype.MANY_SEP9=function(e){this.manySepFirstInternal(9,e)},e.prototype.AT_LEAST_ONE=function(e){this.atLeastOneInternal(0,e)},e.prototype.AT_LEAST_ONE1=function(e){return this.atLeastOneInternal(1,e)},e.prototype.AT_LEAST_ONE2=function(e){this.atLeastOneInternal(2,e)},e.prototype.AT_LEAST_ONE3=function(e){this.atLeastOneInternal(3,e)},e.prototype.AT_LEAST_ONE4=function(e){this.atLeastOneInternal(4,e)},e.prototype.AT_LEAST_ONE5=function(e){this.atLeastOneInternal(5,e)},e.prototype.AT_LEAST_ONE6=function(e){this.atLeastOneInternal(6,e)},e.prototype.AT_LEAST_ONE7=function(e){this.atLeastOneInternal(7,e)},e.prototype.AT_LEAST_ONE8=function(e){this.atLeastOneInternal(8,e)},e.prototype.AT_LEAST_ONE9=function(e){this.atLeastOneInternal(9,e)},e.prototype.AT_LEAST_ONE_SEP=function(e){this.atLeastOneSepFirstInternal(0,e)},e.prototype.AT_LEAST_ONE_SEP1=function(e){this.atLeastOneSepFirstInternal(1,e)},e.prototype.AT_LEAST_ONE_SEP2=function(e){this.atLeastOneSepFirstInternal(2,e)},e.prototype.AT_LEAST_ONE_SEP3=function(e){this.atLeastOneSepFirstInternal(3,e)},e.prototype.AT_LEAST_ONE_SEP4=function(e){this.atLeastOneSepFirstInternal(4,e)},e.prototype.AT_LEAST_ONE_SEP5=function(e){this.atLeastOneSepFirstInternal(5,e)},e.prototype.AT_LEAST_ONE_SEP6=function(e){this.atLeastOneSepFirstInternal(6,e)},e.prototype.AT_LEAST_ONE_SEP7=function(e){this.atLeastOneSepFirstInternal(7,e)},e.prototype.AT_LEAST_ONE_SEP8=function(e){this.atLeastOneSepFirstInternal(8,e)},e.prototype.AT_LEAST_ONE_SEP9=function(e){this.atLeastOneSepFirstInternal(9,e)},e.prototype.RULE=function(e,t,n){if(void 0===n&&(n=DEFAULT_RULE_CONFIG),contains(this.definedRulesNames,e)){var r={message:defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({topLevelRule:e,grammarName:this.className}),type:ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:e};this.definitionErrors.push(r)}this.definedRulesNames.push(e);var a=this.defineRule(e,t,n);return this[e]=a,a},e.prototype.OVERRIDE_RULE=function(e,t,n){void 0===n&&(n=DEFAULT_RULE_CONFIG);var r=[];r=r.concat(validateRuleIsOverridden(e,this.definedRulesNames,this.className)),this.definitionErrors.push.apply(this.definitionErrors,r);var a=this.defineRule(e,t,n);return this[e]=a,a},e.prototype.BACKTRACK=function(e,t){return function(){this.isBackTrackingStack.push(1);var n=this.saveRecogState();try{return e.apply(this,t),!0}catch(e){if(isRecognitionException(e))return!1;throw e}finally{this.reloadRecogState(n),this.isBackTrackingStack.pop()}}},e.prototype.getGAstProductions=function(){return this.gastProductionsCache},e.prototype.getSerializedGastProductions=function(){return serializeGrammar(values(this.gastProductionsCache))},e}(),RecognizerEngine=function(){function e(){}return e.prototype.initRecognizerEngine=function(e,t){if(this.className=classNameFromInstance(this),this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=tokenStructuredMatcherNoCategories,this.definedRulesNames=[],this.tokensMap={},this.allRuleNames=[],this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},has(t,"serializedGrammar"))throw Error("The Parser's configuration can no longer contain a property.\n\tSee: https://sap.github.io/chevrotain/docs/changes/BREAKING_CHANGES.html#_6-0-0\n\tFor Further details.");if(isArray$2(e)){if(isEmpty(e))throw Error("A Token Vocabulary cannot be empty.\n\tNote that the first argument for the parser constructor\n\tis no longer a Token vector (since v4.0).");if("number"==typeof e[0].startOffset)throw Error("The Parser constructor no longer accepts a token vector as the first argument.\n\tSee: https://sap.github.io/chevrotain/docs/changes/BREAKING_CHANGES.html#_4-0-0\n\tFor Further details.")}if(isArray$2(e))this.tokensMap=reduce(e,(function(e,t){return e[t.name]=t,e}),{});else if(has(e,"modes")&&every(flatten(values(e.modes)),isTokenType)){var n=uniq(flatten(values(e.modes)));this.tokensMap=reduce(n,(function(e,t){return e[t.name]=t,e}),{})}else{if(!isObject$5(e))throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap=cloneObj(e)}this.tokensMap.EOF=EOF;var r=every(values(e),(function(e){return isEmpty(e.categoryMatches)}));this.tokenMatcher=r?tokenStructuredMatcherNoCategories:tokenStructuredMatcher,augmentTokenTypes(values(this.tokensMap))},e.prototype.defineRule=function(e,t,n){if(this.selfAnalysisDone)throw Error("Grammar rule <"+e+"> may not be defined after the 'performSelfAnalysis' method has been called'\nMake sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.");var r,a=has(n,"resyncEnabled")?n.resyncEnabled:DEFAULT_RULE_CONFIG.resyncEnabled,i=has(n,"recoveryValueFunc")?n.recoveryValueFunc:DEFAULT_RULE_CONFIG.recoveryValueFunc,o=this.ruleShortNameIdx<t},e.prototype.orInternalNoCst=function(e,t){var n=isArray$2(e)?e:e.DEF,r=this.getKeyForAutomaticLookahead(OR_IDX,t),a=this.getLaFuncFromCache(r).call(this,n);if(void 0!==a)return n[a].ALT.call(this);this.raiseNoAltException(t,e.ERR_MSG)},e.prototype.orInternal=function(e,t){var n=this.getKeyForAutomaticLookahead(OR_IDX,t),r=this.nestedRuleBeforeClause(e,n);try{var a=isArray$2(e)?e:e.DEF,i=this.getLaFuncFromCache(n).call(this,a);if(void 0!==i){var o=a[i],s=this.nestedAltBeforeClause(o,t,OR_IDX,i);try{return o.ALT.call(this)}finally{void 0!==s&&this.nestedRuleFinallyClause(s.shortName,s.nestedName)}}this.raiseNoAltException(t,e.ERR_MSG)}finally{void 0!==r&&this.nestedRuleFinallyClause(n,r)}},e.prototype.ruleFinallyStateUpdate=function(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),0===this.RULE_STACK.length&&!1===this.isAtEndOfInput()){var e=this.LA(1),t=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:e,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new NotAllInputParsedException(t,e))}},e.prototype.subruleInternal=function(e,t,n){var r;try{var a=void 0!==n?n.ARGS:void 0;return r=e.call(this,t,a),this.cstPostNonTerminal(r,void 0!==n&&void 0!==n.LABEL?n.LABEL:e.ruleName),r}catch(t){this.subruleInternalError(t,n,e.ruleName)}},e.prototype.subruleInternalError=function(e,t,n){throw isRecognitionException(e)&&void 0!==e.partialCstResult&&(this.cstPostNonTerminal(e.partialCstResult,void 0!==t&&void 0!==t.LABEL?t.LABEL:n),delete e.partialCstResult),e},e.prototype.consumeInternal=function(e,t,n){var r;try{var a=this.LA(1);!0===this.tokenMatcher(a,e)?(this.consumeToken(),r=a):this.consumeInternalError(e,a,n)}catch(n){r=this.consumeInternalRecovery(e,t,n)}return this.cstPostTerminal(void 0!==n&&void 0!==n.LABEL?n.LABEL:e.name,r),r},e.prototype.consumeInternalError=function(e,t,n){var r,a=this.LA(0);throw r=void 0!==n&&n.ERR_MSG?n.ERR_MSG:this.errorMessageProvider.buildMismatchTokenMessage({expected:e,actual:t,previous:a,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new MismatchedTokenException(r,t,a))},e.prototype.consumeInternalRecovery=function(e,t,n){if(!this.recoveryEnabled||"MismatchedTokenException"!==n.name||this.isBackTracking())throw n;var r=this.getFollowsForInRuleRecovery(e,t);try{return this.tryInRuleRecovery(e,r)}catch(e){throw e.name===IN_RULE_RECOVERY_EXCEPTION?n:e}},e.prototype.saveRecogState=function(){var e=this.errors,t=cloneArr(this.RULE_STACK);return{errors:e,lexerState:this.exportLexerState(),RULE_STACK:t,CST_STACK:this.CST_STACK,LAST_EXPLICIT_RULE_STACK:this.LAST_EXPLICIT_RULE_STACK}},e.prototype.reloadRecogState=function(e){this.errors=e.errors,this.importLexerState(e.lexerState),this.RULE_STACK=e.RULE_STACK},e.prototype.ruleInvocationStateUpdate=function(e,t,n){this.RULE_OCCURRENCE_STACK.push(n),this.RULE_STACK.push(e),this.cstInvocationStateUpdate(t,e)},e.prototype.isBackTracking=function(){return 0!==this.isBackTrackingStack.length},e.prototype.getCurrRuleFullName=function(){var e=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[e]},e.prototype.shortRuleNameToFullName=function(e){return this.shortRuleNameToFull[e]},e.prototype.isAtEndOfInput=function(){return this.tokenMatcher(this.LA(1),EOF)},e.prototype.reset=function(){this.resetLexerState(),this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.LAST_EXPLICIT_RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]},e}(),ErrorHandler=function(){function e(){}return e.prototype.initErrorHandler=function(e){this._errors=[],this.errorMessageProvider=defaults$4(e.errorMessageProvider,DEFAULT_PARSER_CONFIG.errorMessageProvider)},e.prototype.SAVE_ERROR=function(e){if(isRecognitionException(e))return e.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:cloneArr(this.RULE_OCCURRENCE_STACK)},this._errors.push(e),e;throw Error("Trying to save an Error which is not a RecognitionException")},Object.defineProperty(e.prototype,"errors",{get:function(){return cloneArr(this._errors)},set:function(e){this._errors=e},enumerable:!0,configurable:!0}),e.prototype.raiseEarlyExitException=function(e,t,n){for(var r=this.getCurrRuleFullName(),a=getLookaheadPathsForOptionalProd(e,this.getGAstProductions()[r],t,this.maxLookahead)[0],i=[],o=1;o<=this.maxLookahead;o++)i.push(this.LA(o));var s=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:a,actual:i,previous:this.LA(0),customUserDescription:n,ruleName:r});throw this.SAVE_ERROR(new EarlyExitException(s,this.LA(1),this.LA(0)))},e.prototype.raiseNoAltException=function(e,t){for(var n=this.getCurrRuleFullName(),r=getLookaheadPathsForOr(e,this.getGAstProductions()[n],this.maxLookahead),a=[],i=1;i<=this.maxLookahead;i++)a.push(this.LA(i));var o=this.LA(0),s=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:r,actual:a,previous:o,customUserDescription:t,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new NoViableAltException(s,this.LA(1),o))},e}(),ContentAssist=function(){function e(){}return e.prototype.initContentAssist=function(){},e.prototype.computeContentAssist=function(e,t){var n=this.gastProductionsCache[e];if(isUndefined$1(n))throw Error("Rule ->"+e+"<- does not exist in this grammar.");return nextPossibleTokensAfter([n],t,this.tokenMatcher,this.maxLookahead)},e.prototype.getNextPossibleTokenTypes=function(e){var t=first$1(e.ruleStack),n=this.getGAstProductions()[t];return new NextAfterTokenWalker(n,e).startWalking()},e}(),RECORDING_NULL_OBJECT={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(RECORDING_NULL_OBJECT);var HANDLE_SEPARATOR=!0,MAX_METHOD_IDX=Math.pow(2,BITS_FOR_OCCURRENCE_IDX)-1,RFT=createToken({name:"RECORDING_PHASE_TOKEN",pattern:Lexer.NA});augmentTokenTypes([RFT]);var RECORDING_PHASE_TOKEN=createTokenInstance(RFT,"This IToken indicates the Parser is in Recording Phase\n\tSee: https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording for details",-1,-1,-1,-1,-1,-1);Object.freeze(RECORDING_PHASE_TOKEN);var RECORDING_PHASE_CSTNODE={name:"This CSTNode indicates the Parser is in Recording Phase\n\tSee: https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording for details",children:{}},GastRecorder=function(){function e(){}return e.prototype.initGastRecorder=function(e){this.recordingProdStack=[],this.RECORDING_PHASE=!1},e.prototype.enableRecording=function(){var e=this;this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",(function(){for(var t=function(t){var n=t>0?t:"";e["CONSUME"+n]=function(e,n){return this.consumeInternalRecord(e,t,n)},e["SUBRULE"+n]=function(e,n){return this.subruleInternalRecord(e,t,n)},e["OPTION"+n]=function(e){return this.optionInternalRecord(e,t)},e["OR"+n]=function(e){return this.orInternalRecord(e,t)},e["MANY"+n]=function(e){this.manyInternalRecord(t,e)},e["MANY_SEP"+n]=function(e){this.manySepFirstInternalRecord(t,e)},e["AT_LEAST_ONE"+n]=function(e){this.atLeastOneInternalRecord(t,e)},e["AT_LEAST_ONE_SEP"+n]=function(e){this.atLeastOneSepFirstInternalRecord(t,e)}},n=0;n<10;n++)t(n);e.consume=function(e,t,n){return this.consumeInternalRecord(t,e,n)},e.subrule=function(e,t,n){return this.subruleInternalRecord(t,e,n)},e.option=function(e,t){return this.optionInternalRecord(t,e)},e.or=function(e,t){return this.orInternalRecord(t,e)},e.many=function(e,t){this.manyInternalRecord(e,t)},e.atLeastOne=function(e,t){this.atLeastOneInternalRecord(e,t)},e.ACTION=e.ACTION_RECORD,e.BACKTRACK=e.BACKTRACK_RECORD,e.LA=e.LA_RECORD}))},e.prototype.disableRecording=function(){var e=this;this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",(function(){for(var t=0;t<10;t++){var n=t>0?t:"";delete e["CONSUME"+n],delete e["SUBRULE"+n],delete e["OPTION"+n],delete e["OR"+n],delete e["MANY"+n],delete e["MANY_SEP"+n],delete e["AT_LEAST_ONE"+n],delete e["AT_LEAST_ONE_SEP"+n]}delete e.consume,delete e.subrule,delete e.option,delete e.or,delete e.many,delete e.atLeastOne,delete e.ACTION,delete e.BACKTRACK,delete e.LA}))},e.prototype.ACTION_RECORD=function(e){},e.prototype.BACKTRACK_RECORD=function(e,t){return function(){return!0}},e.prototype.LA_RECORD=function(e){return END_OF_FILE},e.prototype.topLevelRuleRecord=function(e,t){try{var n=new Rule({definition:[],name:e});return n.name=e,this.recordingProdStack.push(n),t.call(this),this.recordingProdStack.pop(),n}catch(e){if(!0!==e.KNOWN_RECORDER_ERROR)try{e.message=e.message+'\n\t This error was thrown during the "grammar recording phase" For more info see:\n\thttps://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording'}catch(t){throw e}throw e}},e.prototype.optionInternalRecord=function(e,t){return recordProd.call(this,Option,e,t)},e.prototype.atLeastOneInternalRecord=function(e,t){recordProd.call(this,RepetitionMandatory,t,e)},e.prototype.atLeastOneSepFirstInternalRecord=function(e,t){recordProd.call(this,RepetitionMandatoryWithSeparator,t,e,HANDLE_SEPARATOR)},e.prototype.manyInternalRecord=function(e,t){recordProd.call(this,Repetition,t,e)},e.prototype.manySepFirstInternalRecord=function(e,t){recordProd.call(this,RepetitionWithSeparator,t,e,HANDLE_SEPARATOR)},e.prototype.orInternalRecord=function(e,t){return recordOrProd.call(this,e,t)},e.prototype.subruleInternalRecord=function(e,t,n){if(assertMethodIdxIsValid(t),!e||!1===has(e,"ruleName")){var r=new Error(" argument is invalid expecting a Parser method reference but got: <"+JSON.stringify(e)+">\n inside top level rule: <"+this.recordingProdStack[0].name+">");throw r.KNOWN_RECORDER_ERROR=!0,r}var a=peek(this.recordingProdStack),i=e.ruleName,o=new NonTerminal({idx:t,nonTerminalName:i,referencedRule:void 0});return a.definition.push(o),this.outputCst?RECORDING_PHASE_CSTNODE:RECORDING_NULL_OBJECT},e.prototype.consumeInternalRecord=function(e,t,n){if(assertMethodIdxIsValid(t),!hasShortKeyProperty(e)){var r=new Error(" argument is invalid expecting a TokenType reference but got: <"+JSON.stringify(e)+">\n inside top level rule: <"+this.recordingProdStack[0].name+">");throw r.KNOWN_RECORDER_ERROR=!0,r}var a=peek(this.recordingProdStack),i=new Terminal({idx:t,terminalType:e});return a.definition.push(i),RECORDING_PHASE_TOKEN},e}();function recordProd(e,t,n,r){void 0===r&&(r=!1),assertMethodIdxIsValid(n);var a=peek(this.recordingProdStack),i=isFunction$1(t)?t:t.DEF,o=new e({definition:[],idx:n});return has(t,"NAME")&&(o.name=t.NAME),r&&(o.separator=t.SEP),has(t,"MAX_LOOKAHEAD")&&(o.maxLookahead=t.MAX_LOOKAHEAD),this.recordingProdStack.push(o),i.call(this),a.definition.push(o),this.recordingProdStack.pop(),RECORDING_NULL_OBJECT}function recordOrProd(e,t){var n=this;assertMethodIdxIsValid(t);var r=peek(this.recordingProdStack),a=!1===isArray$2(e),i=!1===a?e:e.DEF,o=new Alternation({definition:[],idx:t,ignoreAmbiguities:a&&!0===e.IGNORE_AMBIGUITIES});has(e,"NAME")&&(o.name=e.NAME),has(e,"MAX_LOOKAHEAD")&&(o.maxLookahead=e.MAX_LOOKAHEAD);var s=some(i,(function(e){return isFunction$1(e.GATE)}));return o.hasPredicates=s,r.definition.push(o),forEach$1(i,(function(e){var t=new Flat({definition:[]});o.definition.push(t),has(e,"NAME")&&(t.name=e.NAME),has(e,"IGNORE_AMBIGUITIES")?t.ignoreAmbiguities=e.IGNORE_AMBIGUITIES:has(e,"GATE")&&(t.ignoreAmbiguities=!0),n.recordingProdStack.push(t),e.ALT.call(n),n.recordingProdStack.pop()})),RECORDING_NULL_OBJECT}function getIdxSuffix(e){return 0===e?"":""+e}function assertMethodIdxIsValid(e){if(e<0||e>MAX_METHOD_IDX){var t=new Error("Invalid DSL Method idx value: <"+e+">\n\tIdx value must be a none negative value smaller than "+(MAX_METHOD_IDX+1));throw t.KNOWN_RECORDER_ERROR=!0,t}}var PerformanceTracer=function(){function e(){}return e.prototype.initPerformanceTracer=function(e){if(has(e,"traceInitPerf")){var t=e.traceInitPerf,n="number"==typeof t;this.traceInitMaxIdent=n?t:1/0,this.traceInitPerf=n?t>0:t}else this.traceInitMaxIdent=0,this.traceInitPerf=DEFAULT_PARSER_CONFIG.traceInitPerf;this.traceInitIndent=-1},e.prototype.TRACE_INIT=function(e,t){if(!0===this.traceInitPerf){this.traceInitIndent++;var n=new Array(this.traceInitIndent+1).join("\t");this.traceInitIndent");var r=timer(t),a=r.time,i=r.value,o=a>10?console.warn:console.log;return this.traceInitIndent time: "+a+"ms"),this.traceInitIndent--,i}return t()},e}(),__extends=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),END_OF_FILE=createTokenInstance(EOF,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(END_OF_FILE);var DEFAULT_PARSER_CONFIG=Object.freeze({recoveryEnabled:!1,maxLookahead:4,ignoredIssues:{},dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:defaultParserErrorProvider,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),DEFAULT_RULE_CONFIG=Object.freeze({recoveryValueFunc:function(){},resyncEnabled:!0}),ParserDefinitionErrorType;function EMPTY_ALT(e){return void 0===e&&(e=void 0),function(){return e}}!function(e){e[e.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",e[e.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",e[e.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",e[e.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",e[e.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",e[e.LEFT_RECURSION=5]="LEFT_RECURSION",e[e.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",e[e.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",e[e.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",e[e.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",e[e.INVALID_NESTED_RULE_NAME=10]="INVALID_NESTED_RULE_NAME",e[e.DUPLICATE_NESTED_NAME=11]="DUPLICATE_NESTED_NAME",e[e.NO_NON_EMPTY_LOOKAHEAD=12]="NO_NON_EMPTY_LOOKAHEAD",e[e.AMBIGUOUS_PREFIX_ALTS=13]="AMBIGUOUS_PREFIX_ALTS",e[e.TOO_MANY_ALTS=14]="TOO_MANY_ALTS"}(ParserDefinitionErrorType||(ParserDefinitionErrorType={}));var Parser=function(){function e(e,t){void 0===t&&(t=DEFAULT_PARSER_CONFIG),this.ignoredIssues=DEFAULT_PARSER_CONFIG.ignoredIssues,this.definitionErrors=[],this.selfAnalysisDone=!1;var n=this;n.initErrorHandler(t),n.initLexerAdapter(),n.initLooksAhead(t),n.initRecognizerEngine(e,t),n.initRecoverable(t),n.initTreeBuilder(t),n.initContentAssist(),n.initGastRecorder(t),n.initPerformanceTracer(t),has(t,"ignoredIssues")&&t.ignoredIssues!==DEFAULT_PARSER_CONFIG.ignoredIssues&&PRINT_WARNING("The IParserConfig property is soft-deprecated and will be removed in future versions.\n\tPlease use the flag on the relevant DSL method instead."),this.ignoredIssues=has(t,"ignoredIssues")?t.ignoredIssues:DEFAULT_PARSER_CONFIG.ignoredIssues,this.skipValidations=has(t,"skipValidations")?t.skipValidations:DEFAULT_PARSER_CONFIG.skipValidations}return e.performSelfAnalysis=function(e){e.performSelfAnalysis()},e.prototype.performSelfAnalysis=function(){var t=this;this.TRACE_INIT("performSelfAnalysis",(function(){var n;t.selfAnalysisDone=!0;var r=t.className;t.TRACE_INIT("toFastProps",(function(){toFastProperties(t)})),t.TRACE_INIT("Grammar Recording",(function(){try{t.enableRecording(),forEach$1(t.definedRulesNames,(function(e){var n=t[e].originalGrammarAction,r=void 0;t.TRACE_INIT(e+" Rule",(function(){r=t.topLevelRuleRecord(e,n)})),t.gastProductionsCache[e]=r}))}finally{t.disableRecording()}}));var a=[];if(t.TRACE_INIT("Grammar Resolving",(function(){a=resolveGrammar({rules:values(t.gastProductionsCache)}),t.definitionErrors.push.apply(t.definitionErrors,a)})),t.TRACE_INIT("Grammar Validations",(function(){if(isEmpty(a)&&!1===t.skipValidations){var e=validateGrammar({rules:values(t.gastProductionsCache),maxLookahead:t.maxLookahead,tokenTypes:values(t.tokensMap),ignoredIssues:t.ignoredIssues,errMsgProvider:defaultGrammarValidatorErrorProvider,grammarName:r});t.definitionErrors.push.apply(t.definitionErrors,e)}})),isEmpty(t.definitionErrors)&&(t.recoveryEnabled&&t.TRACE_INIT("computeAllProdsFollows",(function(){var e=computeAllProdsFollows(values(t.gastProductionsCache));t.resyncFollows=e})),t.TRACE_INIT("ComputeLookaheadFunctions",(function(){t.preComputeLookaheadFunctions(values(t.gastProductionsCache))}))),t.TRACE_INIT("expandAllNestedRuleNames",(function(){var e=expandAllNestedRuleNames(values(t.gastProductionsCache),t.fullRuleNameToShort);t.allRuleNames=e.allRuleNames})),!e.DEFER_DEFINITION_ERRORS_HANDLING&&!isEmpty(t.definitionErrors))throw n=map(t.definitionErrors,(function(e){return e.message})),new Error("Parser Definition Errors detected:\n "+n.join("\n-------------------------------\n"))}))},e.DEFER_DEFINITION_ERRORS_HANDLING=!1,e}();applyMixins(Parser,[Recoverable,LooksAhead,TreeBuilder,LexerAdapter,RecognizerEngine,RecognizerApi,ErrorHandler,ContentAssist,GastRecorder,PerformanceTracer]),function(e){function t(t,n){void 0===n&&(n=DEFAULT_PARSER_CONFIG);var r=cloneObj(n);return r.outputCst=!0,e.call(this,t,r)||this}__extends(t,e)}(Parser);var EmbeddedActionsParser=function(e){function t(t,n){void 0===n&&(n=DEFAULT_PARSER_CONFIG);var r=cloneObj(n);return r.outputCst=!1,e.call(this,t,r)||this}return __extends(t,e),t}(Parser);function _toConsumableArray$f(e){return _arrayWithoutHoles$f(e)||_iterableToArray$f(e)||_unsupportedIterableToArray$R(e)||_nonIterableSpread$f()}function _nonIterableSpread$f(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray$R(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$R(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$R(e,t):void 0}}function _iterableToArray$f(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles$f(e){if(Array.isArray(e))return _arrayLikeToArray$R(e)}function _arrayLikeToArray$R(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n/,categories:BooleanOp}),GreaterThanOp=createToken({name:"GreaterThanOp",pattern:/>/,categories:BooleanOp}),LessThanOp=createToken({name:"LessThanOp",pattern:/=/,categories:BooleanOp}),LessThanOrEqualOp=createToken({name:"LessThanOrEqualOp",pattern:/<=/,categories:BooleanOp}),ConcatenateOp=createToken({name:"ConcatenateOp",pattern:/&/}),simpleSheetName="[A-Za-z0-9_À-ʯ]+",quotedSheetName="'(((?!').|'')*)'",sheetNameRegexp="(".concat(simpleSheetName,"|").concat(quotedSheetName,")!"),CellReference=createToken({name:"CellReference",pattern:new RegExp("(".concat(sheetNameRegexp,")?\\").concat(ABSOLUTE_OPERATOR,"?[A-Za-z]+\\").concat(ABSOLUTE_OPERATOR,"?[0-9]+"))}),ColumnRange=createToken({name:"ColumnRange",pattern:new RegExp("(".concat(sheetNameRegexp,")?\\").concat(ABSOLUTE_OPERATOR,"?[A-Za-z]+").concat(RANGE_OPERATOR,"(").concat(sheetNameRegexp,")?\\").concat(ABSOLUTE_OPERATOR,"?[A-Za-z]+"))}),RowRange=createToken({name:"RowRange",pattern:new RegExp("(".concat(sheetNameRegexp,")?\\").concat(ABSOLUTE_OPERATOR,"?[0-9]+").concat(RANGE_OPERATOR,"(").concat(sheetNameRegexp,")?\\").concat(ABSOLUTE_OPERATOR,"?[0-9]+"))}),RangeSeparator=createToken({name:"RangeSeparator",pattern:"".concat(RANGE_OPERATOR)}),LParen=createToken({name:"LParen",pattern:/\(/}),RParen=createToken({name:"RParen",pattern:/\)/}),ArrayLParen=createToken({name:"ArrayLParen",pattern:/{/}),ArrayRParen=createToken({name:"ArrayRParen",pattern:/}/}),ProcedureName=createToken({name:"ProcedureName",pattern:/([A-Za-z\u00C0-\u02AF][A-Za-z0-9\u00C0-\u02AF._]*)\(/}),NamedExpression=createToken({name:"NamedExpression",pattern:/[A-Za-z\u00C0-\u02AF_][A-Za-z0-9\u00C0-\u02AF._]*/}),StringLiteral=createToken({name:"StringLiteral",pattern:/"([^"\\]*(\\.[^"\\]*)*)"/}),ErrorLiteral=createToken({name:"ErrorLiteral",pattern:/#[A-Za-z0-9\/]+[?!]?/}),buildLexerConfig=function(e){var t,n,r=e.translationPackage.getFunctionTranslation("OFFSET"),a=e.errorMapping,i=e.translationPackage.buildFunctionMapping(),o=createToken({name:"WhiteSpace",pattern:"standard"===e.ignoreWhiteSpace?ODFF_WHITESPACE_REGEXP:ALL_WHITESPACE_REGEXP}),s=createToken({name:"ArrayRowSep",pattern:e.arrayRowSeparator}),l=createToken({name:"ArrayColSep",pattern:e.arrayColumnSeparator});e.functionArgSeparator===e.arrayColumnSeparator?(t=l,n=[]):e.functionArgSeparator===e.arrayRowSeparator?(t=s,n=[]):n=[t=createToken({name:"ArgSeparator",pattern:e.functionArgSeparator})];var u=createToken({name:"NumberLiteral",pattern:new RegExp("(([".concat(e.decimalSeparator,"]\\d+)|(\\d+([").concat(e.decimalSeparator,"]\\d*)?))(e[+-]?\\d+)?"))}),c=createToken({name:"OffsetProcedureName",pattern:new RegExp(r,"i")}),p=[o,PlusOp,MinusOp,TimesOp,DivOp,PowerOp,EqualsOp,NotEqualOp,PercentOp,GreaterThanOrEqualOp,LessThanOrEqualOp,GreaterThanOp,LessThanOp,LParen,RParen,ArrayLParen,ArrayRParen,c,ProcedureName,RangeSeparator].concat(_toConsumableArray$f(n),[ColumnRange,RowRange,u,StringLiteral,ErrorLiteral,ConcatenateOp,BooleanOp,AdditionOp,MultiplicationOp,CellReference,NamedExpression,s,l]);return{ArgSeparator:t,NumberLiteral:u,OffsetProcedureName:c,ArrayRowSeparator:s,ArrayColSeparator:l,WhiteSpace:o,allTokens:p,errorMapping:a,functionMapping:i,decimalSeparator:e.decimalSeparator,maxColumns:e.maxColumns,maxRows:e.maxRows}};function _slicedToArray$u(e,t){return _arrayWithHoles$u(e)||_iterableToArrayLimit$u(e,t)||_unsupportedIterableToArray$Q(e,t)||_nonIterableRest$u()}function _nonIterableRest$u(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray$Q(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$Q(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$Q(e,t):void 0}}function _arrayLikeToArray$Q(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=0;)t=String.fromCharCode(e%26+97)+t,e=Math.floor(e/26)-1;return t.toUpperCase()}function sheetIndexToString(e,t){var n=t(e);if(void 0!==n)return simpleSheetNameRegex.test(n)?n:(n=n.replace(/'/g,"''"),"'".concat(n,"'"))}function extractSheetNumber(e,t){var n,r=null!==(n=e[3])&&void 0!==n?n:e[2];return r?t(r=r.replace(/''/g,"'")):null}var $$v=_export,uncurryThis$9=functionUncurryThis,IndexedObject=indexedObject,toIndexedObject$2=toIndexedObject$b,arrayMethodIsStrict$1=arrayMethodIsStrict$4,un$Join=uncurryThis$9([].join),ES3_STRINGS=IndexedObject!=Object,STRICT_METHOD$1=arrayMethodIsStrict$1("join",",");$$v({target:"Array",proto:!0,forced:ES3_STRINGS||!STRICT_METHOD$1},{join:function(e){return un$Join(toIndexedObject$2(this),void 0===e?",":e)}});var parsingError=function(e,t){return{type:e,message:t}},ParsingErrorType,AstNodeType,RangeSheetReferenceType;!function(e){e.LexingError="LexingError",e.ParserError="ParsingError",e.StaticOffsetError="StaticOffsetError",e.StaticOffsetOutOfRangeError="StaticOffsetOutOfRangeError",e.RangeOffsetNotAllowed="RangeOffsetNotAllowed"}(ParsingErrorType||(ParsingErrorType={})),function(e){e.EMPTY="EMPTY",e.NUMBER="NUMBER",e.STRING="STRING",e.MINUS_UNARY_OP="MINUS_UNARY_OP",e.PLUS_UNARY_OP="PLUS_UNARY_OP",e.PERCENT_OP="PERCENT_OP",e.CONCATENATE_OP="CONCATENATE_OP",e.EQUALS_OP="EQUALS_OP",e.NOT_EQUAL_OP="NOT_EQUAL_OP",e.GREATER_THAN_OP="GREATER_THAN_OP",e.LESS_THAN_OP="LESS_THAN_OP",e.GREATER_THAN_OR_EQUAL_OP="GREATER_THAN_OR_EQUAL_OP",e.LESS_THAN_OR_EQUAL_OP="LESS_THAN_OR_EQUAL_OP",e.PLUS_OP="PLUS_OP",e.MINUS_OP="MINUS_OP",e.TIMES_OP="TIMES_OP",e.DIV_OP="DIV_OP",e.POWER_OP="POWER_OP",e.FUNCTION_CALL="FUNCTION_CALL",e.NAMED_EXPRESSION="NAMED_EXPRESSION",e.PARENTHESIS="PARENTHESES",e.CELL_REFERENCE="CELL_REFERENCE",e.CELL_RANGE="CELL_RANGE",e.COLUMN_RANGE="COLUMN_RANGE",e.ROW_RANGE="ROW_RANGE",e.ERROR="ERROR",e.ERROR_WITH_RAW_INPUT="ERROR_WITH_RAW_INPUT",e.ARRAY="ARRAY"}(AstNodeType||(AstNodeType={})),function(e){e[e.RELATIVE=0]="RELATIVE",e[e.START_ABSOLUTE=1]="START_ABSOLUTE",e[e.BOTH_ABSOLUTE=2]="BOTH_ABSOLUTE"}(RangeSheetReferenceType||(RangeSheetReferenceType={}));var buildEmptyArgAst=function(e){return{type:AstNodeType.EMPTY,leadingWhitespace:null==e?void 0:e.image}},buildNumberAst=function(e,t){return{type:AstNodeType.NUMBER,value:e,leadingWhitespace:null==t?void 0:t.image}},buildStringAst=function(e){var t;return{type:AstNodeType.STRING,value:e.image.slice(1,-1),leadingWhitespace:null===(t=e.leadingWhitespace)||void 0===t?void 0:t.image}},buildCellReferenceAst=function(e,t){return{type:AstNodeType.CELL_REFERENCE,reference:e,leadingWhitespace:null==t?void 0:t.image}},buildCellRangeAst=function(e,t,n,r){return assertRangeConsistency(e,t,n),{type:AstNodeType.CELL_RANGE,start:e,end:t,sheetReferenceType:n,leadingWhitespace:r}},buildColumnRangeAst=function(e,t,n,r){return assertRangeConsistency(e,t,n),{type:AstNodeType.COLUMN_RANGE,start:e,end:t,sheetReferenceType:n,leadingWhitespace:null==r?void 0:r.image}},buildRowRangeAst=function(e,t,n,r){return assertRangeConsistency(e,t,n),{type:AstNodeType.ROW_RANGE,start:e,end:t,sheetReferenceType:n,leadingWhitespace:null==r?void 0:r.image}},buildConcatenateOpAst=function(e,t,n){return{type:AstNodeType.CONCATENATE_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}},buildEqualsOpAst=function(e,t,n){return{type:AstNodeType.EQUALS_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}},buildNotEqualOpAst=function(e,t,n){return{type:AstNodeType.NOT_EQUAL_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}},buildGreaterThanOpAst=function(e,t,n){return{type:AstNodeType.GREATER_THAN_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}},buildLessThanOpAst=function(e,t,n){return{type:AstNodeType.LESS_THAN_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}},buildGreaterThanOrEqualOpAst=function(e,t,n){return{type:AstNodeType.GREATER_THAN_OR_EQUAL_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}},buildLessThanOrEqualOpAst=function(e,t,n){return{type:AstNodeType.LESS_THAN_OR_EQUAL_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}},buildPlusOpAst=function(e,t,n){return{type:AstNodeType.PLUS_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}},buildMinusOpAst=function(e,t,n){return{type:AstNodeType.MINUS_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}},buildTimesOpAst=function(e,t,n){return{type:AstNodeType.TIMES_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}},buildDivOpAst=function(e,t,n){return{type:AstNodeType.DIV_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}},buildPowerOpAst=function(e,t,n){return{type:AstNodeType.POWER_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}},buildMinusUnaryOpAst=function(e,t){return{type:AstNodeType.MINUS_UNARY_OP,value:e,leadingWhitespace:null==t?void 0:t.image}},buildPlusUnaryOpAst=function(e,t){return{type:AstNodeType.PLUS_UNARY_OP,value:e,leadingWhitespace:null==t?void 0:t.image}},buildPercentOpAst=function(e,t){return{type:AstNodeType.PERCENT_OP,value:e,leadingWhitespace:null==t?void 0:t.image}},buildProcedureAst=function(e,t,n,r){return{type:AstNodeType.FUNCTION_CALL,procedureName:e,args:t,leadingWhitespace:null==n?void 0:n.image,internalWhitespace:null==r?void 0:r.image}},buildArrayAst=function(e,t,n){return{type:AstNodeType.ARRAY,args:e,leadingWhitespace:null==t?void 0:t.image,internalWhitespace:null==n?void 0:n.image}},buildNamedExpressionAst=function(e,t){return{type:AstNodeType.NAMED_EXPRESSION,expressionName:e,leadingWhitespace:null==t?void 0:t.image}},buildParenthesisAst=function(e,t,n){return{type:AstNodeType.PARENTHESIS,expression:e,leadingWhitespace:null==t?void 0:t.image,internalWhitespace:null==n?void 0:n.image}},buildCellErrorAst=function(e,t){return{type:AstNodeType.ERROR,error:e,leadingWhitespace:null==t?void 0:t.image}},buildErrorWithRawInputAst=function(e,t,n){return{type:AstNodeType.ERROR_WITH_RAW_INPUT,error:t,rawInput:e,leadingWhitespace:null==n?void 0:n.image}},buildParsingErrorAst=function(){return{type:AstNodeType.ERROR,error:CellError.parsingError()}},_binaryOpTokenMap;function assertRangeConsistency(e,t,n){if(void 0!==e.sheet&&void 0===t.sheet||void 0===e.sheet&&void 0!==t.sheet)throw new Error("Start address inconsistent with end address");if(void 0===e.sheet&&n!==RangeSheetReferenceType.RELATIVE||void 0!==e.sheet&&n===RangeSheetReferenceType.RELATIVE)throw new Error("Sheet address inconsistent with sheet reference type")}function imageWithWhitespace(e,t){return(null!=t?t:"")+e}function _defineProperty$1(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var binaryOpTokenMap=(_binaryOpTokenMap={},_defineProperty$1(_binaryOpTokenMap,AstNodeType.PLUS_OP,"+"),_defineProperty$1(_binaryOpTokenMap,AstNodeType.MINUS_OP,"-"),_defineProperty$1(_binaryOpTokenMap,AstNodeType.TIMES_OP,"*"),_defineProperty$1(_binaryOpTokenMap,AstNodeType.DIV_OP,"/"),_defineProperty$1(_binaryOpTokenMap,AstNodeType.CONCATENATE_OP,"&"),_defineProperty$1(_binaryOpTokenMap,AstNodeType.POWER_OP,"^"),_defineProperty$1(_binaryOpTokenMap,AstNodeType.EQUALS_OP,"="),_defineProperty$1(_binaryOpTokenMap,AstNodeType.NOT_EQUAL_OP,"<>"),_defineProperty$1(_binaryOpTokenMap,AstNodeType.GREATER_THAN_OP,">"),_defineProperty$1(_binaryOpTokenMap,AstNodeType.GREATER_THAN_OR_EQUAL_OP,">="),_defineProperty$1(_binaryOpTokenMap,AstNodeType.LESS_THAN_OP,"<"),_defineProperty$1(_binaryOpTokenMap,AstNodeType.LESS_THAN_OR_EQUAL_OP,"<="),_binaryOpTokenMap);function _classCallCheck$1L(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1L(e,t){for(var n=0;n0;)e[r]=e[--r];r!==i++&&(e[r]=n)}return e},merge$1=function(e,t,n,r){for(var a=t.length,i=n.length,o=0,s=0;o3)){if(IE_OR_EDGE)return!0;if(WEBKIT)return WEBKIT<603;var e,t,n,r,a="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:n=3;break;case 68:case 71:n=4;break;default:n=2}for(r=0;r<47;r++)test.push({k:t+r,v:n})}for(test.sort((function(e,t){return t.v-e.v})),r=0;rtoString$6(n)?1:-1}};$$u({target:"Array",proto:!0,forced:FORCED$4},{sort:function(e){void 0!==e&&aCallable(e);var t=toObject$3(this);if(STABLE_SORT)return void 0===e?un$Sort(t):un$Sort(t,e);var n,r,a=[],i=lengthOfArrayLike$2(t);for(r=0;re.length)&&(t=e.length);for(var n=0,r=new Array(t);n0&&(n=buildParsingErrorAst()),{ast:n,errors:r}}},{key:"reset",value:function(){_get$1(_getPrototypeOf$W(n.prototype),"reset",this).call(this),this.customParsingError=void 0}},{key:"formulaWithContext",value:function(e){return this.formulaAddress=e,this.formula()}},{key:"buildCellRange",value:function(e,t,r){if(void 0===e.sheet&&void 0!==t.sheet)return this.parsingError(ParsingErrorType.ParserError,"Malformed range expression");var a=n.fixSheetIdsForRangeEnds(e,t),i=a.firstEnd,o=a.secondEnd,s=a.sheetRefType,l=this.orderCellRangeEnds(i,o),u=l.start,c=l.end;return buildCellRangeAst(u,c,s,r)}},{key:"orderCellRangeEnds",value:function(e,t){var r=[e,t],a=r.map((function(e){return e.toColumnAddress()})).sort(ColumnAddress.compareByAbsoluteAddress(this.formulaAddress)),i=_slicedToArray$t(a,2),o=i[0],s=i[1],l=r.map((function(e){return e.toRowAddress()})).sort(RowAddress.compareByAbsoluteAddress(this.formulaAddress)),u=_slicedToArray$t(l,2),c=u[0],p=u[1],d=r.map((function(e){return e.sheet})).sort(n.compareSheetIds.bind(this)),m=_slicedToArray$t(d,2),f=m[0],h=m[1];return{start:CellAddress.fromColAndRow(o,c,f),end:CellAddress.fromColAndRow(s,p,h)}}},{key:"orderColumnRangeEnds",value:function(e,t){var r=[e,t],a=_slicedToArray$t(r.sort(ColumnAddress.compareByAbsoluteAddress(this.formulaAddress)),2),i=a[0],o=a[1],s=r.map((function(e){return e.sheet})).sort(n.compareSheetIds.bind(this)),l=_slicedToArray$t(s,2),u=l[0],c=l[1];return{start:new ColumnAddress(i.type,i.col,u),end:new ColumnAddress(o.type,o.col,c)}}},{key:"orderRowRangeEnds",value:function(e,t){var r=[e,t],a=_slicedToArray$t(r.sort(RowAddress.compareByAbsoluteAddress(this.formulaAddress)),2),i=a[0],o=a[1],s=r.map((function(e){return e.sheet})).sort(n.compareSheetIds.bind(this)),l=_slicedToArray$t(s,2),u=l[0],c=l[1];return{start:new RowAddress(i.type,i.row,u),end:new RowAddress(o.type,o.row,c)}}},{key:"handleOffsetHeuristic",value:function(e){var t=e[0];if(t.type!==AstNodeType.CELL_REFERENCE)return this.parsingError(ParsingErrorType.StaticOffsetError,"First argument to OFFSET is not a reference");var n,r=e[1];if(r.type===AstNodeType.NUMBER&&Number.isInteger(r.value))n=r.value;else if(r.type===AstNodeType.PLUS_UNARY_OP&&r.value.type===AstNodeType.NUMBER&&Number.isInteger(r.value.value))n=r.value.value;else{if(r.type!==AstNodeType.MINUS_UNARY_OP||r.value.type!==AstNodeType.NUMBER||!Number.isInteger(r.value.value))return this.parsingError(ParsingErrorType.StaticOffsetError,"Second argument to OFFSET is not a static number");n=-r.value.value}var a,i=e[2];if(i.type===AstNodeType.NUMBER&&Number.isInteger(i.value))a=i.value;else if(i.type===AstNodeType.PLUS_UNARY_OP&&i.value.type===AstNodeType.NUMBER&&Number.isInteger(i.value.value))a=i.value.value;else{if(i.type!==AstNodeType.MINUS_UNARY_OP||i.value.type!==AstNodeType.NUMBER||!Number.isInteger(i.value.value))return this.parsingError(ParsingErrorType.StaticOffsetError,"Third argument to OFFSET is not a static number");a=-i.value.value}var o,s=e[3];if(void 0===s)o=1;else{if(s.type!==AstNodeType.NUMBER)return this.parsingError(ParsingErrorType.StaticOffsetError,"Fourth argument to OFFSET is not a static number");if((o=s.value)<1)return this.parsingError(ParsingErrorType.StaticOffsetError,"Fourth argument to OFFSET is too small number");if(!Number.isInteger(o))return this.parsingError(ParsingErrorType.StaticOffsetError,"Fourth argument to OFFSET is not integer")}var l,u=e[4];if(void 0===u)l=1;else{if(u.type!==AstNodeType.NUMBER)return this.parsingError(ParsingErrorType.StaticOffsetError,"Fifth argument to OFFSET is not a static number");if((l=u.value)<1)return this.parsingError(ParsingErrorType.StaticOffsetError,"Fifth argument to OFFSET is too small number");if(!Number.isInteger(l))return this.parsingError(ParsingErrorType.StaticOffsetError,"Fifth argument to OFFSET is not integer")}var c=new CellAddress(t.reference.col+a,t.reference.row+n,t.reference.type),p=c.col,d=c.row;if(t.reference.type!==CellReferenceType.CELL_REFERENCE_RELATIVE&&t.reference.type!==CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL||(d+=this.formulaAddress.row),t.reference.type!==CellReferenceType.CELL_REFERENCE_RELATIVE&&t.reference.type!==CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW||(p+=this.formulaAddress.col),p<0||d<0)return buildCellErrorAst(new CellError(ErrorType.REF,ErrorMessage.OutOfSheet));if(1===l&&1===o)return buildCellReferenceAst(c);var m=new CellAddress(c.col+l-1,c.row+o-1,c.type);return buildCellRangeAst(c,m,RangeSheetReferenceType.RELATIVE)}},{key:"parsingError",value:function(e,t){return this.customParsingError=parsingError(e,t),buildParsingErrorAst()}}],[{key:"fixSheetIdsForRangeEnds",value:function(e,t){var r=n.rangeSheetReferenceType(e.sheet,t.sheet);return{firstEnd:e,secondEnd:void 0!==e.sheet&&void 0===t.sheet?t.withSheet(e.sheet):t,sheetRefType:r}}},{key:"compareSheetIds",value:function(e,t){return(e=null!=e?e:1/0)-(t=null!=t?t:1/0)}},{key:"rangeSheetReferenceType",value:function(e,t){return void 0===e?RangeSheetReferenceType.RELATIVE:void 0===t?RangeSheetReferenceType.START_ABSOLUTE:RangeSheetReferenceType.BOTH_ABSOLUTE}}]),n}(EmbeddedActionsParser),FormulaLexer=function(){function e(t){_classCallCheck$1J(this,e),this.lexerConfig=t,this.lexer=new Lexer(t.allTokens,{ensureOptimizations:!0})}return _createClass$1J(e,[{key:"tokenizeFormula",value:function(e){var t=this.lexer.tokenize(e),n=t.tokens;return n=this.trimTrailingWhitespaces(n),n=this.skipWhitespacesInsideRanges(n),n=this.skipWhitespacesBeforeArgSeparators(n),t.tokens=n,t}},{key:"skipWhitespacesInsideRanges",value:function(t){var n=this;return e.filterTokensByNeighbors(t,(function(e,t,r){return(tokenMatcher(e,CellReference)||tokenMatcher(e,RangeSeparator))&&tokenMatcher(t,n.lexerConfig.WhiteSpace)&&(tokenMatcher(r,CellReference)||tokenMatcher(r,RangeSeparator))}))}},{key:"skipWhitespacesBeforeArgSeparators",value:function(t){var n=this;return e.filterTokensByNeighbors(t,(function(e,t,r){return!tokenMatcher(e,n.lexerConfig.ArgSeparator)&&tokenMatcher(t,n.lexerConfig.WhiteSpace)&&tokenMatcher(r,n.lexerConfig.ArgSeparator)}))}},{key:"trimTrailingWhitespaces",value:function(e){return e.length>0&&tokenMatcher(e[e.length-1],this.lexerConfig.WhiteSpace)&&e.pop(),e}}],[{key:"filterTokensByNeighbors",value:function(e,t){if(e.length<3)return e;for(var n=0,r=[e[n++]];ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n0){var r=n.errors.map((function(e){return{type:ParsingErrorType.LexingError,message:e.message}}));return{ast:buildParsingErrorAst(),errors:r,hasVolatileFunction:!1,hasStructuralChangeFunction:!1,dependencies:[]}}var a=this.computeHashFromTokens(n.tokens,t),i=this.cache.get(a);if(void 0!==i)++this.statsCacheUsed;else{var o=this.bindWhitespacesToTokens(n.tokens),s=this.formulaParser.parseFromTokens(o,t);if(s.errors.length>0)return Object.assign(Object.assign({},s),{hasVolatileFunction:!1,hasStructuralChangeFunction:!1,dependencies:[]});i=this.cache.set(a,s.ast)}var l=i;return{ast:l.ast,errors:[],hasVolatileFunction:l.hasVolatileFunction,hasStructuralChangeFunction:l.hasStructuralChangeFunction,dependencies:l.relativeDependencies}}},{key:"fetchCachedResultForAst",value:function(e){var t=this.computeHashFromAst(e);return this.fetchCachedResult(t)}},{key:"fetchCachedResult",value:function(e){var t=this.cache.get(e);if(void 0===t)throw new Error("There is no AST with such key in the cache");return{ast:t.ast,errors:[],hasVolatileFunction:t.hasVolatileFunction,hasStructuralChangeFunction:t.hasStructuralChangeFunction,dependencies:t.relativeDependencies}}},{key:"computeHashFromTokens",value:function(e,t){for(var n,r="",a=0;a=0;--a){var i=this.tryEntries[a],o=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev=0;--r){var a=this.tryEntries[r];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),C(n),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:S(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),c}},e}function _classCallCheck$1F(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1F(e,t){for(var n=0;nt.toSimpleColumnAddress(e).col-n.toSimpleColumnAddress(e).col}isColumnAbsolute(){return this.type===ReferenceType.ABSOLUTE}isColumnRelative(){return this.type===ReferenceType.RELATIVE}isAbsolute(){return this.type===ReferenceType.ABSOLUTE&&void 0!==this.sheet}moved(e,t,n){const r=void 0===this.sheet?void 0:e;return new ColumnAddress(this.type,this.col+t,r)}shiftedByColumns(e){return new ColumnAddress(this.type,this.col+e,this.sheet)}toSimpleColumnAddress(e){const t=absoluteSheetReference(this,e);let n=this.col;return this.isColumnRelative()&&(n=e.col+this.col),simpleColumnAddress(t,n)}shiftRelativeDimensions(e,t){const n=this.isColumnRelative()?this.col+e:this.col;return new ColumnAddress(this.type,n,this.sheet)}shiftAbsoluteDimensions(e,t){const n=this.isColumnAbsolute()?this.col+e:this.col;return new ColumnAddress(this.type,n,this.sheet)}withSheet(e){return new ColumnAddress(this.type,this.col,e)}isInvalid(e){return this.toSimpleColumnAddress(e).col<0}hash(e){const t=e&&void 0!==this.sheet?`#${this.sheet}`:"";switch(this.type){case ReferenceType.RELATIVE:return`${t}#COLR${this.col}`;case ReferenceType.ABSOLUTE:return`${t}#COLA${this.col}`}}unparse(e){const t=this.toSimpleColumnAddress(e);if(invalidSimpleColumnAddress(t))return;const n=columnIndexToLabel(t.col);return`${this.type===ReferenceType.ABSOLUTE?"$":""}${n}`}exceedsSheetSizeLimits(e){return this.col>=e}} /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */var RowsSpan=function(){function e(t,n,r){if(_classCallCheck$1F(this,e),this.sheet=t,this.rowStart=n,this.rowEnd=r,n<0)throw Error("Starting row cant be less than 0");if(rr?null:new e(this.sheet,n,r)}},{key:"firstRow",value:function(){return new e(this.sheet,this.rowStart,this.rowStart)}}],[{key:"fromNumberOfRows",value:function(t,n,r){return new e(t,n,n+r-1)}},{key:"fromRowStartAndEnd",value:function(t,n,r){return new e(t,n,r)}}]),e}(),ColumnsSpan=function(){function e(t,n,r){if(_classCallCheck$1F(this,e),this.sheet=t,this.columnStart=n,this.columnEnd=r,n<0)throw Error("Starting column cant be less than 0");if(rr?null:new e(this.sheet,n,r)}},{key:"firstColumn",value:function(){return new e(this.sheet,this.columnStart,this.columnStart)}}],[{key:"fromNumberOfColumns",value:function(t,n,r){return new e(t,n,n+r-1)}},{key:"fromColumnStartAndEnd",value:function(t,n,r){return new e(t,n,r)}}]),e}();function _inherits$V(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&_setPrototypeOf$W(e,t)}function _setPrototypeOf$W(e,t){return _setPrototypeOf$W=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},_setPrototypeOf$W(e,t)}function _createSuper$V(e){var t=_isNativeReflectConstruct$W();return function(){var n,r=_getPrototypeOf$V(e);if(t){var a=_getPrototypeOf$V(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return _possibleConstructorReturn$V(this,n)}}function _possibleConstructorReturn$V(e,t){if(t&&("object"===_typeof$1a(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized$V(e)}function _assertThisInitialized$V(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _isNativeReflectConstruct$W(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function _getPrototypeOf$V(e){return _getPrototypeOf$V=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},_getPrototypeOf$V(e)}function _regeneratorRuntime$e(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */_regeneratorRuntime$e=function(){return e};var e={},t=Object.prototype,n=t.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},a=r.iterator||"@@iterator",i=r.asyncIterator||"@@asyncIterator",o=r.toStringTag||"@@toStringTag";function s(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{s({},"")}catch(e){s=function(e,t,n){return e[t]=n}}function l(e,t,n,r){var a=t&&t.prototype instanceof p?t:p,i=Object.create(a.prototype),o=new A(r||[]);return i._invoke=function(e,t,n){var r="suspendedStart";return function(a,i){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===a)throw i;return x()}for(n.method=a,n.arg=i;;){var o=n.delegate;if(o){var s=T(o,n);if(s){if(s===c)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var l=u(e,t,n);if("normal"===l.type){if(r=n.done?"completed":"suspendedYield",l.arg===c)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(r="completed",n.method="throw",n.arg=l.arg)}}}(e,n,o),i}function u(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}e.wrap=l;var c={};function p(){}function d(){}function m(){}var f={};s(f,a,(function(){return this}));var h=Object.getPrototypeOf,y=h&&h(h(S([])));y&&y!==t&&n.call(y,a)&&(f=y);var b=m.prototype=p.prototype=Object.create(f);function g(e){["next","throw","return"].forEach((function(t){s(e,t,(function(e){return this._invoke(t,e)}))}))}function v(e,t){function r(a,i,o,s){var l=u(e[a],e,i);if("throw"!==l.type){var c=l.arg,p=c.value;return p&&"object"==_typeof$1a(p)&&n.call(p,"__await")?t.resolve(p.__await).then((function(e){r("next",e,o,s)}),(function(e){r("throw",e,o,s)})):t.resolve(p).then((function(e){c.value=e,o(c)}),(function(e){return r("throw",e,o,s)}))}s(l.arg)}var a;this._invoke=function(e,n){function i(){return new t((function(t,a){r(e,n,t,a)}))}return a=a?a.then(i,i):i()}}function T(e,t){var n=e.iterator[t.method];if(void 0===n){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,T(e,t),"throw"===t.method))return c;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return c}var r=u(n,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,c;var a=r.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,c):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,c)}function N(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function C(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function A(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(N,this),this.reset(!0)}function S(e){if(e){var t=e[a];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,i=function t(){for(;++r=0;--a){var i=this.tryEntries[a],o=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev=0;--r){var a=this.tryEntries[r];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),C(n),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:S(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),c}},e}function _classCallCheck$1E(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1E(e,t){for(var n=0;ne.end.row)&&!(this.end.cole.end.col))}},{key:"addressInRange",value:function(e){return this.sheet===e.sheet&&(this.start.row<=e.row&&this.end.row>=e.row&&this.start.col<=e.col&&this.end.col>=e.col)}},{key:"columnInRange",value:function(e){return this.sheet===e.sheet&&(this.start.col<=e.col&&this.end.col>=e.col)}},{key:"rowInRange",value:function(e){return this.sheet===e.sheet&&(this.start.row<=e.row&&this.end.row>=e.row)}},{key:"containsRange",value:function(e){return this.addressInRange(e.start)&&this.addressInRange(e.end)}},{key:"intersectionWith",value:function(t){if(this.sheet===t.start.sheet){var n=Math.max(this.start.row,t.start.row),r=Math.min(this.end.row,t.end.row),a=Math.max(this.start.col,t.start.col),i=Math.min(this.end.col,t.end.col);if(!(n>r||a>i))return new e(simpleCellAddress(this.sheet,a,n),simpleCellAddress(this.sheet,i,r))}}},{key:"includesRow",value:function(e){return this.start.row=e}},{key:"includesColumn",value:function(e){return this.start.col=e}},{key:"shiftByRows",value:function(e){this.start.row+=e,this.end.row+=e}},{key:"expandByRows",value:function(e){this.end.row+=e}},{key:"shiftByColumns",value:function(e){this.start.col+=e,this.end.col+=e}},{key:"shifted",value:function(t,n){return e.spanFrom(simpleCellAddress(this.sheet,this.start.col+t,this.start.row+n),this.width(),this.height())}},{key:"expandByColumns",value:function(e){this.end.col+=e}},{key:"moveToSheet",value:function(e){this.start.sheet=e,this.end.sheet=e}},{key:"removeSpan",value:function(e){e instanceof RowsSpan?this.removeRows(e.start,e.end):this.removeColumns(e.start,e.end)}},{key:"shouldBeRemoved",value:function(){return this.width()<=0||this.height()<=0}},{key:"rangeWithSameWidth",value:function(t,n){return e.spanFrom(simpleCellAddress(this.sheet,this.start.col,t),this.width(),n)}},{key:"rangeWithSameHeight",value:function(t,n){return e.spanFrom(simpleCellAddress(this.sheet,t,this.start.row),n,this.height())}},{key:"toString",value:function(){return"".concat(this.start.sheet,",").concat(this.start.col,",").concat(this.start.row,",").concat(this.end.col,",").concat(this.end.row)}},{key:"width",value:function(){return this.end.col-this.start.col+1}},{key:"height",value:function(){return this.end.row-this.start.row+1}},{key:"size",value:function(){return this.height()*this.width()}},{key:"arrayOfAddressesInRange",value:function(){for(var e=[],t=0;t0)){e.next=30;break}if(!(n>0)){e.next=16;break}a=this.effectiveEndRow(r);case 3:if(!(a>=this.start.row)){e.next=14;break}i=this.effectiveEndColumn(r);case 5:if(!(i>=this.start.col)){e.next=11;break}return e.next=8,simpleCellAddress(this.start.sheet,i,a);case 8:i-=1,e.next=5;break;case 11:a-=1,e.next=3;break;case 14:e.next=28;break;case 16:o=this.start.row;case 17:if(!(o<=this.effectiveEndRow(r))){e.next=28;break}s=this.effectiveEndColumn(r);case 19:if(!(s>=this.start.col)){e.next=25;break}return e.next=22,simpleCellAddress(this.start.sheet,s,o);case 22:s-=1,e.next=19;break;case 25:o+=1,e.next=17;break;case 28:e.next=57;break;case 30:if(!(n>0)){e.next=45;break}l=this.effectiveEndRow(r);case 32:if(!(l>=this.start.row)){e.next=43;break}u=this.start.col;case 34:if(!(u<=this.effectiveEndColumn(r))){e.next=40;break}return e.next=37,simpleCellAddress(this.start.sheet,u,l);case 37:u+=1,e.next=34;break;case 40:l-=1,e.next=32;break;case 43:e.next=57;break;case 45:c=this.start.row;case 46:if(!(c<=this.effectiveEndRow(r))){e.next=57;break}p=this.start.col;case 48:if(!(p<=this.effectiveEndColumn(r))){e.next=54;break}return e.next=51,simpleCellAddress(this.start.sheet,p,c);case 51:p+=1,e.next=48;break;case 54:c+=1,e.next=46;break;case 57:case"end":return e.stop()}}),e,this)}))},{key:"getAddress",value:function(e,t){if(e<0||t<0||t>this.height()-1||e>this.width()-1)throw Error("Index out of bound");return simpleCellAddress(this.start.sheet,this.start.col+e,this.start.row+t)}},{key:"exceedsSheetSizeLimits",value:function(e,t){return this.end.col>=e||this.end.row>=t}},{key:"effectiveEndColumn",value:function(e){return this.end.col}},{key:"effectiveEndRow",value:function(e){return this.end.row}},{key:"effectiveWidth",value:function(e){return this.width()}},{key:"effectiveHeight",value:function(e){return this.height()}},{key:"removeRows",value:function(e,t){if(!(e>this.end.row)){if(tthis.end.col)){if(t=e}},{key:"effectiveEndRow",value:function(e){return this.effectiveHeight(e)-1}},{key:"effectiveHeight",value:function(e){return e.getSheetHeight(this.sheet)}},{key:"removeRows",value:function(e,t){}}],[{key:"fromColumnRange",value:function(e,t){var r=e.start.toSimpleColumnAddress(t),a=e.end.toSimpleColumnAddress(t);if(r.sheet!==a.sheet)throw new SheetsNotEqual(r.sheet,a.sheet);return new n(r.sheet,r.col,a.col)}}]),n}(AbsoluteCellRange),AbsoluteRowRange=function(e){_inherits$V(n,e);var t=_createSuper$V(n);function n(e,r,a){return _classCallCheck$1E(this,n),t.call(this,simpleCellAddress(e,0,r),simpleCellAddress(e,Number.POSITIVE_INFINITY,a))}return _createClass$1E(n,[{key:"shouldBeRemoved",value:function(){return this.height()<=0}},{key:"shiftByColumns",value:function(e){}},{key:"expandByColumns",value:function(e){}},{key:"shifted",value:function(e,t){return new n(this.sheet,this.start.row+t,this.end.row+t)}},{key:"rangeWithSameWidth",value:function(e,t){return new n(this.sheet,e,e+t-1)}},{key:"exceedsSheetSizeLimits",value:function(e,t){return this.end.row>=t}},{key:"effectiveEndColumn",value:function(e){return this.effectiveWidth(e)-1}},{key:"effectiveWidth",value:function(e){return e.getSheetWidth(this.sheet)}},{key:"removeColumns",value:function(e,t){}}],[{key:"fromRowRangeAst",value:function(e,t){var r=e.start.toSimpleRowAddress(t),a=e.end.toSimpleRowAddress(t);if(r.sheet!==a.sheet)throw new SheetsNotEqual(r.sheet,a.sheet);return new n(r.sheet,r.row,a.row)}}]),n}(AbsoluteCellRange),absolutizeDependencies=function(e,t){return e.map((function(e){return e.absolutize(t)}))},filterDependenciesOutOfScope=function(e){return e.filter((function(e){return e instanceof NamedExpressionDependency||(e instanceof AbsoluteCellRange?!(invalidSimpleCellAddress(e.start)||invalidSimpleCellAddress(e.end)):!invalidSimpleCellAddress(e))}))};function _defineProperties$1D(e,t){for(var n=0;nt.toSimpleRowAddress(e).row-n.toSimpleRowAddress(e).row}isRowAbsolute(){return this.type===ReferenceType.ABSOLUTE}isRowRelative(){return this.type===ReferenceType.RELATIVE}isAbsolute(){return this.type===ReferenceType.ABSOLUTE&&void 0!==this.sheet}moved(e,t,n){const r=void 0===this.sheet?void 0:e;return new RowAddress(this.type,this.row+n,r)}shiftedByRows(e){return new RowAddress(this.type,this.row+e,this.sheet)}toSimpleRowAddress(e){const t=absoluteSheetReference(this,e);let n=this.row;return this.isRowRelative()&&(n=e.row+this.row),simpleRowAddress(t,n)}shiftRelativeDimensions(e,t){const n=this.isRowRelative()?this.row+t:this.row;return new RowAddress(this.type,n,this.sheet)}shiftAbsoluteDimensions(e,t){const n=this.isRowAbsolute()?this.row+t:this.row;return new RowAddress(this.type,n,this.sheet)}withSheet(e){return new RowAddress(this.type,this.row,e)}isInvalid(e){return this.toSimpleRowAddress(e).row<0}hash(e){const t=e&&void 0!==this.sheet?`#${this.sheet}`:"";switch(this.type){case ReferenceType.RELATIVE:return`${t}#ROWR${this.row}`;case ReferenceType.ABSOLUTE:return`${t}#ROWA${this.row}`}}unparse(e){const t=this.toSimpleRowAddress(e);if(invalidSimpleRowAddress(t))return;return`${this.type===ReferenceType.ABSOLUTE?"$":""}${t.row+1}`}exceedsSheetSizeLimits(e){return this.row>=e}} /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */var InterpreterState=_createClass$1D((function e(t,n,r){_classCallCheck$1D(this,e),this.formulaAddress=t,this.arraysFlag=n,this.formulaVertex=r})),PROPER_FUNCTION_NAME=functionName$1.PROPER,fails$4=fails$G,whitespaces=whitespaces$2,non="​…᠎",stringTrimForced=function(e){return fails$4((function(){return!!whitespaces[e]()||non[e]()!==non||PROPER_FUNCTION_NAME&&whitespaces[e].name!==e}))},$$q=_export,$trim=stringTrim.trim,forcedStringTrimMethod=stringTrimForced;$$q({target:"String",proto:!0,forced:forcedStringTrimMethod("trim")},{trim:function(){return $trim(this)}});var $$p=_export,$includes=arrayIncludes.includes,fails$3=fails$G,addToUnscopables$3=addToUnscopables$5,BROKEN_ON_SPARSE=fails$3((function(){return!Array(1).includes()}));$$p({target:"Array",proto:!0,forced:BROKEN_ON_SPARSE},{includes:function(e){return $includes(this,e,arguments.length>1?arguments[1]:void 0)}}),addToUnscopables$3("includes");var unorm$1={exports:{}};!function(e){!function(t){for(var n=[null,0,{}],r=44032,a=4352,i=function(e,t){this.codepoint=e,this.feature=t},o={},s=[],l=0;l<=255;++l)s[l]=0;var u=[function(e,t,r){return t<60||13311>8&255]>10&&(o[t]=r),r},function(e,t,n){return n?e(t,n):new i(t,null)},function(e,t,n){var o;if(t=55296&&e<=56319},i.isLowSurrogate=function(e){return e>=56320&&e<=57343},i.prototype.prepFeature=function(){this.feature||(this.feature=i.fromCharCode(this.codepoint,!0).feature)},i.prototype.toString=function(){if(this.codepoint<65536)return String.fromCharCode(this.codepoint);var e=this.codepoint-65536;return String.fromCharCode(Math.floor(e/1024)+55296,e%1024+56320)},i.prototype.getDecomp=function(){return this.prepFeature(),this.feature[0]||null},i.prototype.isCompatibility=function(){return this.prepFeature(),!!this.feature[1]&&256&this.feature[1]},i.prototype.isExclude=function(){return this.prepFeature(),!!this.feature[1]&&512&this.feature[1]},i.prototype.getCanonicalClass=function(){return this.prepFeature(),this.feature[1]?255&this.feature[1]:0},i.prototype.getComposite=function(e){if(this.prepFeature(),!this.feature[2])return null;var t=this.feature[2][e.codepoint];return t?i.fromCharCode(t):null};var c=function(e){this.str=e,this.cursor=0};c.prototype.next=function(){if(this.str&&this.cursor0;--n){if(this.resBuf[n-1].getCanonicalClass()<=e)break}this.resBuf.splice(n,0,t)}while(0!==e);return this.resBuf.shift()};var m=function(e){this.it=e,this.procBuf=[],this.resBuf=[],this.lastClass=null};m.prototype.next=function(){for(;0===this.resBuf.length;){var e=this.it.next();if(!e){this.resBuf=this.procBuf,this.procBuf=[];break}if(0===this.procBuf.length)this.lastClass=e.getCanonicalClass(),this.procBuf.push(e);else{var t=this.procBuf[0].getComposite(e),n=e.getCanonicalClass();t&&(this.lastClassCellAddress.relative(t,e,n);return r(e.col,t.row,n)}static relative(e,t,n){return new CellAddress(t,e,CellReferenceType.CELL_REFERENCE_RELATIVE,n)}static absolute(e,t,n){return new CellAddress(e,t,CellReferenceType.CELL_REFERENCE_ABSOLUTE,n)}static absoluteCol(e,t,n){return new CellAddress(e,t,CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL,n)}static absoluteRow(e,t,n){return new CellAddress(e,t,CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW,n)}toSimpleCellAddress(e){const t=absoluteSheetReference(this,e);return this.type===CellReferenceType.CELL_REFERENCE_ABSOLUTE?simpleCellAddress(t,this.col,this.row):this.type===CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW?simpleCellAddress(t,e.col+this.col,this.row):this.type===CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL?simpleCellAddress(t,this.col,e.row+this.row):simpleCellAddress(t,e.col+this.col,e.row+this.row)}toColumnAddress(){const e=this.isColumnRelative()?ReferenceType.RELATIVE:ReferenceType.ABSOLUTE;return new ColumnAddress(e,this.col,this.sheet)}toRowAddress(){const e=this.isRowRelative()?ReferenceType.RELATIVE:ReferenceType.ABSOLUTE;return new RowAddress(e,this.row,this.sheet)}toSimpleColumnAddress(e){const t=absoluteSheetReference(this,e);let n=this.col;return this.isColumnRelative()&&(n+=e.col),simpleColumnAddress(t,n)}toSimpleRowAddress(e){const t=absoluteSheetReference(this,e);let n=this.row;return this.isRowRelative()&&(n+=e.row),simpleRowAddress(t,n)}isRowAbsolute(){return this.type===CellReferenceType.CELL_REFERENCE_ABSOLUTE||this.type===CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW}isColumnAbsolute(){return this.type===CellReferenceType.CELL_REFERENCE_ABSOLUTE||this.type===CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL}isColumnRelative(){return this.type===CellReferenceType.CELL_REFERENCE_RELATIVE||this.type===CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW}isRowRelative(){return this.type===CellReferenceType.CELL_REFERENCE_RELATIVE||this.type===CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL}isAbsolute(){return this.type===CellReferenceType.CELL_REFERENCE_ABSOLUTE&&void 0!==this.sheet}shiftedByRows(e){return new CellAddress(this.col,this.row+e,this.type,this.sheet)}shiftedByColumns(e){return new CellAddress(this.col+e,this.row,this.type,this.sheet)}moved(e,t,n){const r=void 0===this.sheet?void 0:e;return new CellAddress(this.col+t,this.row+n,this.type,r)}withSheet(e){return new CellAddress(this.col,this.row,this.type,e)}isInvalid(e){return invalidSimpleCellAddress(this.toSimpleCellAddress(e))}shiftRelativeDimensions(e,t){const n=this.isColumnAbsolute()?this.col:this.col+e,r=this.isRowAbsolute()?this.row:this.row+t;return new CellAddress(n,r,this.type,this.sheet)}shiftAbsoluteDimensions(e,t){const n=this.isColumnRelative()?this.col:this.col+e,r=this.isRowRelative()?this.row:this.row+t;return new CellAddress(n,r,this.type,this.sheet)}hash(e){const t=e&&void 0!==this.sheet?`#${this.sheet}`:"";switch(this.type){case CellReferenceType.CELL_REFERENCE_RELATIVE:return`${t}#${this.row}R${this.col}`;case CellReferenceType.CELL_REFERENCE_ABSOLUTE:return`${t}#${this.row}A${this.col}`;case CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL:return`${t}#${this.row}AC${this.col}`;case CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW:return`${t}#${this.row}AR${this.col}`}}unparse(e){const t=this.toSimpleCellAddress(e);if(invalidSimpleCellAddress(t))return;const n=columnIndexToLabel(t.col),r=this.type===CellReferenceType.CELL_REFERENCE_ABSOLUTE||this.type===CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW?"$":"";return`${this.type===CellReferenceType.CELL_REFERENCE_ABSOLUTE||this.type===CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL?"$":""}${n}${r}${t.row+1}`}exceedsSheetSizeLimits(e,t){return this.row>=t||this.col>=e}}function isEmpty(e){return e&&0===e.length}function keys(e){return null==e?[]:Object.keys(e)}function values(e){for(var t=[],n=Object.keys(e),r=0;r=this.input.length)throw Error("Unexpected end of input");this.idx++};var t,n=/[0-9a-fA-F]/,r=/[0-9]/,a=/[1-9]/;function i(e){return e.charCodeAt(0)}function s(e,t){void 0!==e.length?e.forEach((function(e){t.push(e)})):t.push(e)}function o(e,t){if(!0===e[t])throw"duplicate flag "+t;e[t]=!0}function l(e){if(void 0===e)throw Error("Internal Error - Should never get here!")}var u=[];for(t=i("0");t<=i("9");t++)u.push(t);var c=[i("_")].concat(u);for(t=i("a");t<=i("z");t++)c.push(t);for(t=i("A");t<=i("Z");t++)c.push(t);var p=[i(" "),i("\f"),i("\n"),i("\r"),i("\t"),i("\v"),i("\t"),i(" "),i(" "),i(" "),i(" "),i(" "),i(" "),i(" "),i(" "),i(" "),i(" "),i(" "),i(" "),i(" "),i("\u2028"),i("\u2029"),i(" "),i(" "),i(" "),i("\ufeff")];function d(){}return d.prototype.visitChildren=function(e){for(var t in e){var n=e[t];e.hasOwnProperty(t)&&(void 0!==n.type?this.visit(n):Array.isArray(n)&&n.forEach((function(e){this.visit(e)}),this))}},d.prototype.visit=function(e){switch(e.type){case"Pattern":this.visitPattern(e);break;case"Flags":this.visitFlags(e);break;case"Disjunction":this.visitDisjunction(e);break;case"Alternative":this.visitAlternative(e);break;case"StartAnchor":this.visitStartAnchor(e);break;case"EndAnchor":this.visitEndAnchor(e);break;case"WordBoundary":this.visitWordBoundary(e);break;case"NonWordBoundary":this.visitNonWordBoundary(e);break;case"Lookahead":this.visitLookahead(e);break;case"NegativeLookahead":this.visitNegativeLookahead(e);break;case"Character":this.visitCharacter(e);break;case"Set":this.visitSet(e);break;case"Group":this.visitGroup(e);break;case"GroupBackReference":this.visitGroupBackReference(e);break;case"Quantifier":this.visitQuantifier(e)}this.visitChildren(e)},d.prototype.visitPattern=function(e){},d.prototype.visitFlags=function(e){},d.prototype.visitDisjunction=function(e){},d.prototype.visitAlternative=function(e){},d.prototype.visitStartAnchor=function(e){},d.prototype.visitEndAnchor=function(e){},d.prototype.visitWordBoundary=function(e){},d.prototype.visitNonWordBoundary=function(e){},d.prototype.visitLookahead=function(e){},d.prototype.visitNegativeLookahead=function(e){},d.prototype.visitCharacter=function(e){},d.prototype.visitSet=function(e){},d.prototype.visitGroup=function(e){},d.prototype.visitGroupBackReference=function(e){},d.prototype.visitQuantifier=function(e){},{RegExpParser:e,BaseRegExpVisitor:d,VERSION:"0.4.0"}},e.exports?e.exports=n():t.regexpToAst=n()}(regexpToAst);var regExpAstCache={},regExpParser=new regexpToAst.exports.RegExpParser;function getRegExpAst(e){var t=e.toString();if(regExpAstCache.hasOwnProperty(t))return regExpAstCache[t];var n=regExpParser.pattern(t);return regExpAstCache[t]=n,n}function clearRegExpParserCache(){regExpAstCache={}}var __extends$a=(extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},extendStatics(e,t)},function(e,t){function n(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),extendStatics,complementErrorMessage="Complement Sets are not supported for first char optimization",failedOptimizationPrefixMsg='Unable to use "first char" lexer optimizations:\n';function getOptimizedStartCodesIndices(e,t){void 0===t&&(t=!1);try{var n=getRegExpAst(e);return firstCharOptimizedIndices(n.value,{},n.flags.ignoreCase)}catch(n){if(n.message===complementErrorMessage)t&&PRINT_WARNING(failedOptimizationPrefixMsg+"\tUnable to optimize: < "+e.toString()+" >\n\tComplement Sets cannot be automatically optimized.\n\tThis will disable the lexer's first char optimizations.\n\tSee: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.");else{var r="";t&&(r="\n\tThis will disable the lexer's first char optimizations.\n\tSee: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details."),PRINT_ERROR(failedOptimizationPrefixMsg+"\n\tFailed parsing: < "+e.toString()+" >\n\tUsing the regexp-to-ast library version: "+regexpToAst.exports.VERSION+"\n\tPlease open an issue at: https://github.com/bd82/regexp-to-ast/issues"+r)}}return[]}function firstCharOptimizedIndices(e,t,n){switch(e.type){case"Disjunction":for(var r=0;r=minOptimizationVal)for(var i=r.from>=minOptimizationVal?r.from:minOptimizationVal,s=r.to,o=charCodeToOptimizedIndex(i),l=charCodeToOptimizedIndex(s),u=o;u<=l;u++)t[u]=u}}}));break;case"Group":firstCharOptimizedIndices(s.value,t,n);break;default:throw Error("Non Exhaustive Match")}var o=void 0!==s.quantifier&&0===s.quantifier.atLeast;if("Group"===s.type&&!1===isWholeOptional(s)||"Group"!==s.type&&!1===o)break}break;default:throw Error("non exhaustive match!")}return values(t)}function addOptimizedIdxToResult(e,t,n){var r=charCodeToOptimizedIndex(e);t[r]=r,!0===n&&handleIgnoreCase(e,t)}function handleIgnoreCase(e,t){var n=String.fromCharCode(e),r=n.toUpperCase();if(r!==n){t[a=charCodeToOptimizedIndex(r.charCodeAt(0))]=a}else{var a,i=n.toLowerCase();if(i!==n)t[a=charCodeToOptimizedIndex(i.charCodeAt(0))]=a}}function findCode(e,t){return find(e.value,(function(e){if("number"==typeof e)return contains(t,e);var n=e;return void 0!==find(t,(function(e){return n.from<=e&&e<=n.to}))}))}function isWholeOptional(e){return!(!e.quantifier||0!==e.quantifier.atLeast)||!!e.value&&(isArray$2(e.value)?every(e.value,isWholeOptional):isWholeOptional(e.value))}var CharCodeFinder=function(e){function t(t){var n=e.call(this)||this;return n.targetCharCodes=t,n.found=!1,n}return __extends$a(t,e),t.prototype.visitChildren=function(t){if(!0!==this.found){switch(t.type){case"Lookahead":return void this.visitLookahead(t);case"NegativeLookahead":return void this.visitNegativeLookahead(t)}e.prototype.visitChildren.call(this,t)}},t.prototype.visitCharacter=function(e){contains(this.targetCharCodes,e.value)&&(this.found=!0)},t.prototype.visitSet=function(e){e.complement?void 0===findCode(e,this.targetCharCodes)&&(this.found=!0):void 0!==findCode(e,this.targetCharCodes)&&(this.found=!0)},t}(regexpToAst.exports.BaseRegExpVisitor);function canMatchCharCode(e,t){if(t instanceof RegExp){var n=getRegExpAst(t),r=new CharCodeFinder(e);return r.visit(n),r.found}return void 0!==find(t,(function(t){return contains(e,t.charCodeAt(0))}))}var __extends$9=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),PATTERN="PATTERN",DEFAULT_MODE="defaultMode",MODES="modes",SUPPORT_STICKY="boolean"==typeof new RegExp("(?:)").sticky;function analyzeTokenTypes(e,t){var n,r=(t=defaults$4(t,{useSticky:SUPPORT_STICKY,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r","\n"],tracer:function(e,t){return t()}})).tracer;r("initCharCodeToOptimizedIndexMap",(function(){initCharCodeToOptimizedIndexMap()})),r("Reject Lexer.NA",(function(){n=reject(e,(function(e){return e[PATTERN]===Lexer.NA}))}));var a,i,s,o,l,u,c,p,d,m,h,f=!1;r("Transform Patterns",(function(){f=!1,a=map(n,(function(e){var n=e[PATTERN];if(isRegExp(n)){var r=n.source;return 1===r.length&&"^"!==r&&"$"!==r&&"."!==r?r:2!==r.length||"\\"!==r[0]||contains(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],r[1])?t.useSticky?addStickyFlag(n):addStartOfInput(n):r[1]}if(isFunction$1(n))return f=!0,{exec:n};if(has(n,"exec"))return f=!0,n;if("string"==typeof n){if(1===n.length)return n;var a=n.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),i=new RegExp(a);return t.useSticky?addStickyFlag(i):addStartOfInput(i)}throw Error("non exhaustive match")}))})),r("misc mapping",(function(){i=map(n,(function(e){return e.tokenTypeIdx})),s=map(n,(function(e){var t=e.GROUP;if(t!==Lexer.SKIPPED){if(isString$1(t))return t;if(isUndefined$1(t))return!1;throw Error("non exhaustive match")}})),o=map(n,(function(e){var t=e.LONGER_ALT;if(t)return indexOf(n,t)})),l=map(n,(function(e){return e.PUSH_MODE})),u=map(n,(function(e){return has(e,"POP_MODE")}))})),r("Line Terminator Handling",(function(){var e=getCharCodes(t.lineTerminatorCharacters);c=map(n,(function(e){return!1})),"onlyOffset"!==t.positionTracking&&(c=map(n,(function(t){return has(t,"LINE_BREAKS")?t.LINE_BREAKS:!1===checkLineBreaksIssues(t,e)?canMatchCharCode(e,t.PATTERN):void 0})))})),r("Misc Mapping #2",(function(){p=map(n,isCustomPattern),d=map(a,isShortPattern),m=reduce(n,(function(e,t){var n=t.GROUP;return isString$1(n)&&n!==Lexer.SKIPPED&&(e[n]=[]),e}),{}),h=map(a,(function(e,t){return{pattern:a[t],longerAlt:o[t],canLineTerminator:c[t],isCustom:p[t],short:d[t],group:s[t],push:l[t],pop:u[t],tokenTypeIdx:i[t],tokenType:n[t]}}))}));var y=!0,g=[];return t.safeMode||r("First Char Optimization",(function(){g=reduce(n,(function(e,n,r){if("string"==typeof n.PATTERN){var a=charCodeToOptimizedIndex(n.PATTERN.charCodeAt(0));addToMapOfArrays(e,a,h[r])}else if(isArray$2(n.START_CHARS_HINT)){var i;forEach$1(n.START_CHARS_HINT,(function(t){var n=charCodeToOptimizedIndex("string"==typeof t?t.charCodeAt(0):t);i!==n&&(i=n,addToMapOfArrays(e,n,h[r]))}))}else if(isRegExp(n.PATTERN))if(n.PATTERN.unicode)y=!1,t.ensureOptimizations&&PRINT_ERROR(failedOptimizationPrefixMsg+"\tUnable to analyze < "+n.PATTERN.toString()+" > pattern.\n\tThe regexp unicode flag is not currently supported by the regexp-to-ast library.\n\tThis will disable the lexer's first char optimizations.\n\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE");else{var s=getOptimizedStartCodesIndices(n.PATTERN,t.ensureOptimizations);isEmpty(s)&&(y=!1),forEach$1(s,(function(t){addToMapOfArrays(e,t,h[r])}))}else t.ensureOptimizations&&PRINT_ERROR(failedOptimizationPrefixMsg+"\tTokenType: <"+n.name+"> is using a custom token pattern without providing parameter.\n\tThis will disable the lexer's first char optimizations.\n\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE"),y=!1;return e}),[])})),r("ArrayPacking",(function(){g=packArray(g)})),{emptyGroups:m,patternIdxToConfig:h,charCodeToPatternIdxToConfig:g,hasCustom:f,canBeOptimized:y}}function validatePatterns(e,t){var n=[],r=findMissingPatterns(e);n=n.concat(r.errors);var a=findInvalidPatterns(r.valid),i=a.valid;return n=(n=(n=(n=(n=n.concat(a.errors)).concat(validateRegExpPattern(i))).concat(findInvalidGroupType(i))).concat(findModesThatDoNotExist(i,t))).concat(findUnreachablePatterns(i))}function validateRegExpPattern(e){var t=[],n=filter(e,(function(e){return isRegExp(e[PATTERN])}));return t=(t=(t=(t=(t=t.concat(findEndOfInputAnchor(n))).concat(findStartOfInputAnchor(n))).concat(findUnsupportedFlags(n))).concat(findDuplicatePatterns(n))).concat(findEmptyMatchRegExps(n))}function findMissingPatterns(e){var t=filter(e,(function(e){return!has(e,PATTERN)}));return{errors:map(t,(function(e){return{message:"Token Type: ->"+e.name+"<- missing static 'PATTERN' property",type:LexerDefinitionErrorType.MISSING_PATTERN,tokenTypes:[e]}})),valid:difference(e,t)}}function findInvalidPatterns(e){var t=filter(e,(function(e){var t=e[PATTERN];return!(isRegExp(t)||isFunction$1(t)||has(t,"exec")||isString$1(t))}));return{errors:map(t,(function(e){return{message:"Token Type: ->"+e.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:LexerDefinitionErrorType.INVALID_PATTERN,tokenTypes:[e]}})),valid:difference(e,t)}}var end_of_input=/[^\\][\$]/;function findEndOfInputAnchor(e){var t=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.found=!1,t}return __extends$9(t,e),t.prototype.visitEndAnchor=function(e){this.found=!0},t}(regexpToAst.exports.BaseRegExpVisitor);return map(filter(e,(function(e){var n=e[PATTERN];try{var r=getRegExpAst(n),a=new t;return a.visit(r),a.found}catch(e){return end_of_input.test(n.source)}})),(function(e){return{message:"Unexpected RegExp Anchor Error:\n\tToken Type: ->"+e.name+"<- static 'PATTERN' cannot contain end of input anchor '$'\n\tSee sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#ANCHORS\tfor details.",type:LexerDefinitionErrorType.EOI_ANCHOR_FOUND,tokenTypes:[e]}}))}function findEmptyMatchRegExps(e){return map(filter(e,(function(e){return e[PATTERN].test("")})),(function(e){return{message:"Token Type: ->"+e.name+"<- static 'PATTERN' must not match an empty string",type:LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,tokenTypes:[e]}}))}var start_of_input=/[^\\[][\^]|^\^/;function findStartOfInputAnchor(e){var t=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.found=!1,t}return __extends$9(t,e),t.prototype.visitStartAnchor=function(e){this.found=!0},t}(regexpToAst.exports.BaseRegExpVisitor);return map(filter(e,(function(e){var n=e[PATTERN];try{var r=getRegExpAst(n),a=new t;return a.visit(r),a.found}catch(e){return start_of_input.test(n.source)}})),(function(e){return{message:"Unexpected RegExp Anchor Error:\n\tToken Type: ->"+e.name+"<- static 'PATTERN' cannot contain start of input anchor '^'\n\tSee https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#ANCHORS\tfor details.",type:LexerDefinitionErrorType.SOI_ANCHOR_FOUND,tokenTypes:[e]}}))}function findUnsupportedFlags(e){return map(filter(e,(function(e){var t=e[PATTERN];return t instanceof RegExp&&(t.multiline||t.global)})),(function(e){return{message:"Token Type: ->"+e.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[e]}}))}function findDuplicatePatterns(e){var t=[],n=map(e,(function(n){return reduce(e,(function(e,r){return n.PATTERN.source!==r.PATTERN.source||contains(t,r)||r.PATTERN===Lexer.NA||(t.push(r),e.push(r)),e}),[])}));return map(filter(n=compact(n),(function(e){return e.length>1})),(function(e){var t=map(e,(function(e){return e.name}));return{message:"The same RegExp pattern ->"+first$1(e).PATTERN+"<-has been used in all of the following Token Types: "+t.join(", ")+" <-",type:LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,tokenTypes:e}}))}function findInvalidGroupType(e){return map(filter(e,(function(e){if(!has(e,"GROUP"))return!1;var t=e.GROUP;return t!==Lexer.SKIPPED&&t!==Lexer.NA&&!isString$1(t)})),(function(e){return{message:"Token Type: ->"+e.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,tokenTypes:[e]}}))}function findModesThatDoNotExist(e,t){return map(filter(e,(function(e){return void 0!==e.PUSH_MODE&&!contains(t,e.PUSH_MODE)})),(function(e){return{message:"Token Type: ->"+e.name+"<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->"+e.PUSH_MODE+"<-which does not exist",type:LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[e]}}))}function findUnreachablePatterns(e){var t=[],n=reduce(e,(function(e,t,n){var r=t.PATTERN;return r===Lexer.NA||(isString$1(r)?e.push({str:r,idx:n,tokenType:t}):isRegExp(r)&&noMetaChar(r)&&e.push({str:r.source,idx:n,tokenType:t})),e}),[]);return forEach$1(e,(function(e,r){forEach$1(n,(function(n){var a=n.str,i=n.idx,s=n.tokenType;if(r"+e.name+"<-in the lexer's definition.\nSee https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#UNREACHABLE";t.push({message:o,type:LexerDefinitionErrorType.UNREACHABLE_PATTERN,tokenTypes:[e,s]})}}))})),t}function testTokenType(e,t){if(isRegExp(t)){var n=t.exec(e);return null!==n&&0===n.index}if(isFunction$1(t))return t(e,0,[],{});if(has(t,"exec"))return t.exec(e,0,[],{});if("string"==typeof t)return t===e;throw Error("non exhaustive match")}function noMetaChar(e){return void 0===find([".","\\","[","]","|","^","$","(",")","?","*","+","{"],(function(t){return-1!==e.source.indexOf(t)}))}function addStartOfInput(e){var t=e.ignoreCase?"i":"";return new RegExp("^(?:"+e.source+")",t)}function addStickyFlag(e){var t=e.ignoreCase?"iy":"y";return new RegExp(""+e.source,t)}function performRuntimeChecks(e,t,n){var r=[];return has(e,DEFAULT_MODE)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+DEFAULT_MODE+"> property in its definition\n",type:LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),has(e,MODES)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+MODES+"> property in its definition\n",type:LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),has(e,MODES)&&has(e,DEFAULT_MODE)&&!has(e.modes,e.defaultMode)&&r.push({message:"A MultiMode Lexer cannot be initialized with a "+DEFAULT_MODE+": <"+e.defaultMode+">which does not exist\n",type:LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),has(e,MODES)&&forEach$1(e.modes,(function(e,t){forEach$1(e,(function(e,n){isUndefined$1(e)&&r.push({message:"A Lexer cannot be initialized using an undefined Token Type. Mode:<"+t+"> at index: <"+n+">\n",type:LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED})}))})),r}function performWarningRuntimeChecks(e,t,n){var r=[],a=!1,i=reject(compact(flatten(mapValues(e.modes,(function(e){return e})))),(function(e){return e[PATTERN]===Lexer.NA})),s=getCharCodes(n);return t&&forEach$1(i,(function(e){var t=checkLineBreaksIssues(e,s);if(!1!==t){var n={message:buildLineBreakIssueMessage(e,t),type:t.issue,tokenType:e};r.push(n)}else has(e,"LINE_BREAKS")?!0===e.LINE_BREAKS&&(a=!0):canMatchCharCode(s,e.PATTERN)&&(a=!0)})),t&&!a&&r.push({message:"Warning: No LINE_BREAKS Found.\n\tThis Lexer has been defined to track line and column information,\n\tBut none of the Token Types can be identified as matching a line terminator.\n\tSee https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \n\tfor details.",type:LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS}),r}function cloneEmptyGroups(e){var t={};return forEach$1(keys(e),(function(n){if(!isArray$2(e[n]))throw Error("non exhaustive match");t[n]=[]})),t}function isCustomPattern(e){var t=e.PATTERN;if(isRegExp(t))return!1;if(isFunction$1(t))return!0;if(has(t,"exec"))return!0;if(isString$1(t))return!1;throw Error("non exhaustive match")}function isShortPattern(e){return!(!isString$1(e)||1!==e.length)&&e.charCodeAt(0)}var LineTerminatorOptimizedTester={test:function(e){for(var t=e.length,n=this.lastIndex;n Token Type\n\t Root cause: "+t.errMsg+".\n\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR";if(t.issue===LexerDefinitionErrorType.CUSTOM_LINE_BREAK)return"Warning: A Custom Token Pattern should specify the option.\n\tThe problem is in the <"+e.name+"> Token Type\n\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK";throw Error("non exhaustive match")}function getCharCodes(e){return map(e,(function(e){return isString$1(e)&&e.length>0?e.charCodeAt(0):e}))}function addToMapOfArrays(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var minOptimizationVal=256;function charCodeToOptimizedIndex(e){return e255?255+~~(e/255):e}}function tokenStructuredMatcher(e,t){var n=e.tokenTypeIdx;return n===t.tokenTypeIdx||!0===t.isParent&&!0===t.categoryMatchesMap[n]}function tokenStructuredMatcherNoCategories(e,t){return e.tokenTypeIdx===t.tokenTypeIdx}var tokenShortNameIdx=1,tokenIdxToClass={};function augmentTokenTypes(e){var t=expandCategories(e);assignTokenDefaultProps(t),assignCategoriesMapProp(t),assignCategoriesTokensProp(t),forEach$1(t,(function(e){e.isParent=e.categoryMatches.length>0}))}function expandCategories(e){for(var t=cloneArr(e),n=e,r=!0;r;){var a=difference(n=compact(flatten(map(n,(function(e){return e.CATEGORIES})))),t);t=t.concat(a),isEmpty(a)?r=!1:n=a}return t}function assignTokenDefaultProps(e){forEach$1(e,(function(e){hasShortKeyProperty(e)||(tokenIdxToClass[tokenShortNameIdx]=e,e.tokenTypeIdx=tokenShortNameIdx++),hasCategoriesProperty(e)&&!isArray$2(e.CATEGORIES)&&(e.CATEGORIES=[e.CATEGORIES]),hasCategoriesProperty(e)||(e.CATEGORIES=[]),hasExtendingTokensTypesProperty(e)||(e.categoryMatches=[]),hasExtendingTokensTypesMapProperty(e)||(e.categoryMatchesMap={})}))}function assignCategoriesTokensProp(e){forEach$1(e,(function(e){e.categoryMatches=[],forEach$1(e.categoryMatchesMap,(function(t,n){e.categoryMatches.push(tokenIdxToClass[n].tokenTypeIdx)}))}))}function assignCategoriesMapProp(e){forEach$1(e,(function(e){singleAssignCategoriesToksMap([],e)}))}function singleAssignCategoriesToksMap(e,t){forEach$1(e,(function(e){t.categoryMatchesMap[e.tokenTypeIdx]=!0})),forEach$1(t.CATEGORIES,(function(n){var r=e.concat(t);contains(r,n)||singleAssignCategoriesToksMap(r,n)}))}function hasShortKeyProperty(e){return has(e,"tokenTypeIdx")}function hasCategoriesProperty(e){return has(e,"CATEGORIES")}function hasExtendingTokensTypesProperty(e){return has(e,"categoryMatches")}function hasExtendingTokensTypesMapProperty(e){return has(e,"categoryMatchesMap")}function isTokenType(e){return has(e,"tokenTypeIdx")}var defaultLexerErrorProvider={buildUnableToPopLexerModeMessage:function(e){return"Unable to pop Lexer Mode after encountering Token ->"+e.image+"<- The Mode Stack is empty"},buildUnexpectedCharactersMessage:function(e,t,n,r,a){return"unexpected character: ->"+e.charAt(t)+"<- at offset: "+t+", skipped "+n+" characters."}},LexerDefinitionErrorType;!function(e){e[e.MISSING_PATTERN=0]="MISSING_PATTERN",e[e.INVALID_PATTERN=1]="INVALID_PATTERN",e[e.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",e[e.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",e[e.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",e[e.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",e[e.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",e[e.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",e[e.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",e[e.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",e[e.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",e[e.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",e[e.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",e[e.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",e[e.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",e[e.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",e[e.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK"}(LexerDefinitionErrorType||(LexerDefinitionErrorType={}));var DEFAULT_LEXER_CONFIG={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:["\n","\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:defaultLexerErrorProvider,traceInitPerf:!1,skipValidations:!1};Object.freeze(DEFAULT_LEXER_CONFIG);var Lexer=function(){function e(e,t){var n=this;if(void 0===t&&(t=DEFAULT_LEXER_CONFIG),this.lexerDefinition=e,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.config=void 0,this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},"boolean"==typeof t)throw Error("The second argument to the Lexer constructor is now an ILexerConfig Object.\na boolean 2nd argument is no longer supported");this.config=merge$1(DEFAULT_LEXER_CONFIG,t);var r=this.config.traceInitPerf;!0===r?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):"number"==typeof r&&(this.traceInitMaxIdent=r,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",(function(){var r,a=!0;n.TRACE_INIT("Lexer Config handling",(function(){if(n.config.lineTerminatorsPattern===DEFAULT_LEXER_CONFIG.lineTerminatorsPattern)n.config.lineTerminatorsPattern=LineTerminatorOptimizedTester;else if(n.config.lineTerminatorCharacters===DEFAULT_LEXER_CONFIG.lineTerminatorCharacters)throw Error("Error: Missing property on the Lexer config.\n\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS");if(t.safeMode&&t.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');n.trackStartLines=/full|onlyStart/i.test(n.config.positionTracking),n.trackEndLines=/full/i.test(n.config.positionTracking),isArray$2(e)?((r={modes:{}}).modes[DEFAULT_MODE]=cloneArr(e),r[DEFAULT_MODE]=DEFAULT_MODE):(a=!1,r=cloneObj(e))})),!1===n.config.skipValidations&&(n.TRACE_INIT("performRuntimeChecks",(function(){n.lexerDefinitionErrors=n.lexerDefinitionErrors.concat(performRuntimeChecks(r,n.trackStartLines,n.config.lineTerminatorCharacters))})),n.TRACE_INIT("performWarningRuntimeChecks",(function(){n.lexerDefinitionWarning=n.lexerDefinitionWarning.concat(performWarningRuntimeChecks(r,n.trackStartLines,n.config.lineTerminatorCharacters))}))),r.modes=r.modes?r.modes:{},forEach$1(r.modes,(function(e,t){r.modes[t]=reject(e,(function(e){return isUndefined$1(e)}))}));var i=keys(r.modes);if(forEach$1(r.modes,(function(e,r){n.TRACE_INIT("Mode: <"+r+"> processing",(function(){var a;(n.modes.push(r),!1===n.config.skipValidations&&n.TRACE_INIT("validatePatterns",(function(){n.lexerDefinitionErrors=n.lexerDefinitionErrors.concat(validatePatterns(e,i))})),isEmpty(n.lexerDefinitionErrors))&&(augmentTokenTypes(e),n.TRACE_INIT("analyzeTokenTypes",(function(){a=analyzeTokenTypes(e,{lineTerminatorCharacters:n.config.lineTerminatorCharacters,positionTracking:t.positionTracking,ensureOptimizations:t.ensureOptimizations,safeMode:t.safeMode,tracer:n.TRACE_INIT.bind(n)})})),n.patternIdxToConfig[r]=a.patternIdxToConfig,n.charCodeToPatternIdxToConfig[r]=a.charCodeToPatternIdxToConfig,n.emptyGroups=merge$1(n.emptyGroups,a.emptyGroups),n.hasCustom=a.hasCustom||n.hasCustom,n.canModeBeOptimized[r]=a.canBeOptimized)}))})),n.defaultMode=r.defaultMode,!isEmpty(n.lexerDefinitionErrors)&&!n.config.deferDefinitionErrorsHandling){var s=map(n.lexerDefinitionErrors,(function(e){return e.message})).join("-----------------------\n");throw new Error("Errors detected in definition of Lexer:\n"+s)}forEach$1(n.lexerDefinitionWarning,(function(e){PRINT_WARNING(e.message)})),n.TRACE_INIT("Choosing sub-methods implementations",(function(){if(SUPPORT_STICKY?(n.chopInput=IDENTITY,n.match=n.matchWithTest):(n.updateLastIndex=NOOP,n.match=n.matchWithExec),a&&(n.handleModes=NOOP),!1===n.trackStartLines&&(n.computeNewColumn=IDENTITY),!1===n.trackEndLines&&(n.updateTokenEndLineColumnLocation=NOOP),/full/i.test(n.config.positionTracking))n.createTokenInstance=n.createFullToken;else if(/onlyStart/i.test(n.config.positionTracking))n.createTokenInstance=n.createStartOnlyToken;else{if(!/onlyOffset/i.test(n.config.positionTracking))throw Error('Invalid config option: "'+n.config.positionTracking+'"');n.createTokenInstance=n.createOffsetOnlyToken}n.hasCustom?(n.addToken=n.addTokenUsingPush,n.handlePayload=n.handlePayloadWithCustom):(n.addToken=n.addTokenUsingMemberAccess,n.handlePayload=n.handlePayloadNoCustom)})),n.TRACE_INIT("Failed Optimization Warnings",(function(){var e=reduce(n.canModeBeOptimized,(function(e,t,n){return!1===t&&e.push(n),e}),[]);if(t.ensureOptimizations&&!isEmpty(e))throw Error("Lexer Modes: < "+e.join(", ")+' > cannot be optimized.\n\t Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.\n\t Or inspect the console log for details on how to resolve these issues.')})),n.TRACE_INIT("clearRegExpParserCache",(function(){clearRegExpParserCache()})),n.TRACE_INIT("toFastProperties",(function(){toFastProperties(n)}))}))}return e.prototype.tokenize=function(e,t){if(void 0===t&&(t=this.defaultMode),!isEmpty(this.lexerDefinitionErrors)){var n=map(this.lexerDefinitionErrors,(function(e){return e.message})).join("-----------------------\n");throw new Error("Unable to Tokenize because Errors detected in definition of Lexer:\n"+n)}return this.tokenizeInternal(e,t)},e.prototype.tokenizeInternal=function(e,t){var n,r,a,i,s,o,l,u,c,p,d,m,h,f,y=this,g=e,b=g.length,v=0,N=0,T=this.hasCustom?0:Math.floor(e.length/10),C=new Array(T),A=[],V=this.trackStartLines?1:void 0,x=this.trackStartLines?1:void 0,S=cloneEmptyGroups(this.emptyGroups),w=this.trackStartLines,E=this.config.lineTerminatorsPattern,D=0,O=[],I=[],R=[],_=[];Object.freeze(_);var M=void 0;function P(){return O}function F(e){var t=charCodeToOptimizedIndex(e),n=I[t];return void 0===n?_:n}var k,$=function(e){if(1===R.length&&void 0===e.tokenType.PUSH_MODE){var t=y.config.errorMessageProvider.buildUnableToPopLexerModeMessage(e);A.push({offset:e.startOffset,line:void 0!==e.startLine?e.startLine:void 0,column:void 0!==e.startColumn?e.startColumn:void 0,length:e.image.length,message:t})}else{R.pop();var n=last(R);O=y.patternIdxToConfig[n],I=y.charCodeToPatternIdxToConfig[n],D=O.length;var r=y.canModeBeOptimized[n]&&!1===y.config.safeMode;M=I&&r?F:P}};function B(e){R.push(e),I=this.charCodeToPatternIdxToConfig[e],O=this.patternIdxToConfig[e],D=O.length,D=O.length;var t=this.canModeBeOptimized[e]&&!1===this.config.safeMode;M=I&&t?F:P}for(B.call(this,t);vs.length&&(s=a,o=l,k=q)}break}}if(null!==s){if(u=s.length,void 0!==(c=k.group)&&(p=k.tokenTypeIdx,d=this.createTokenInstance(s,v,p,k.tokenType,V,x,u),this.handlePayload(d,o),!1===c?N=this.addToken(C,N,d):S[c].push(d)),e=this.chopInput(e,u),v+=u,x=this.computeNewColumn(x,u),!0===w&&!0===k.canLineTerminator){var H=0,W=void 0,K=void 0;E.lastIndex=0;do{!0===(W=E.test(s))&&(K=E.lastIndex-1,H++)}while(!0===W);0!==H&&(V+=H,x=u-K,this.updateTokenEndLineColumnLocation(d,c,K,H,V,x,u))}this.handleModes(k,$,B,d)}else{for(var Z=v,X=V,Y=x,Q=!1;!Q&&v");var r=timer(t),a=r.time,i=r.value,s=a>10?console.warn:console.log;return this.traceInitIndent time: "+a+"ms"),this.traceInitIndent--,i}return t()},e.SKIPPED="This marks a skipped Token pattern, this means each token identified by it willbe consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.",e.NA=/NOT_APPLICABLE/,e}();function tokenLabel(e){return hasTokenLabel(e)?e.LABEL:e.name}function hasTokenLabel(e){return isString$1(e.LABEL)&&""!==e.LABEL}var PARENT="parent",CATEGORIES="categories",LABEL="label",GROUP="group",PUSH_MODE="push_mode",POP_MODE="pop_mode",LONGER_ALT="longer_alt",LINE_BREAKS="line_breaks",START_CHARS_HINT="start_chars_hint";function createToken(e){return createTokenInternal(e)}function createTokenInternal(e){var t=e.pattern,n={};if(n.name=e.name,isUndefined$1(t)||(n.PATTERN=t),has(e,PARENT))throw"The parent property is no longer supported.\nSee: https://github.com/SAP/chevrotain/issues/564#issuecomment-349062346 for details.";return has(e,CATEGORIES)&&(n.CATEGORIES=e[CATEGORIES]),augmentTokenTypes([n]),has(e,LABEL)&&(n.LABEL=e[LABEL]),has(e,GROUP)&&(n.GROUP=e[GROUP]),has(e,POP_MODE)&&(n.POP_MODE=e[POP_MODE]),has(e,PUSH_MODE)&&(n.PUSH_MODE=e[PUSH_MODE]),has(e,LONGER_ALT)&&(n.LONGER_ALT=e[LONGER_ALT]),has(e,LINE_BREAKS)&&(n.LINE_BREAKS=e[LINE_BREAKS]),has(e,START_CHARS_HINT)&&(n.START_CHARS_HINT=e[START_CHARS_HINT]),n}var EOF=createToken({name:"EOF",pattern:Lexer.NA});function createTokenInstance(e,t,n,r,a,i,s,o){return{image:t,startOffset:n,endOffset:r,startLine:a,endLine:i,startColumn:s,endColumn:o,tokenTypeIdx:e.tokenTypeIdx,tokenType:e}}function tokenMatcher(e,t){return tokenStructuredMatcher(e,t)}augmentTokenTypes([EOF]);var __extends$8=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),AbstractProduction=function(){function e(e){this.definition=e}return e.prototype.accept=function(e){e.visit(this),forEach$1(this.definition,(function(t){t.accept(e)}))},e}(),NonTerminal=function(e){function t(t){var n=e.call(this,[])||this;return n.idx=1,assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),Object.defineProperty(t.prototype,"definition",{get:function(){return void 0!==this.referencedRule?this.referencedRule.definition:[]},set:function(e){},enumerable:!0,configurable:!0}),t.prototype.accept=function(e){e.visit(this)},t}(AbstractProduction),Rule=function(e){function t(t){var n=e.call(this,t.definition)||this;return n.orgText="",assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),t}(AbstractProduction),Flat=function(e){function t(t){var n=e.call(this,t.definition)||this;return n.ignoreAmbiguities=!1,assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),t}(AbstractProduction),Option=function(e){function t(t){var n=e.call(this,t.definition)||this;return n.idx=1,assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),t}(AbstractProduction),RepetitionMandatory=function(e){function t(t){var n=e.call(this,t.definition)||this;return n.idx=1,assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),t}(AbstractProduction),RepetitionMandatoryWithSeparator=function(e){function t(t){var n=e.call(this,t.definition)||this;return n.idx=1,assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),t}(AbstractProduction),Repetition=function(e){function t(t){var n=e.call(this,t.definition)||this;return n.idx=1,assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),t}(AbstractProduction),RepetitionWithSeparator=function(e){function t(t){var n=e.call(this,t.definition)||this;return n.idx=1,assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),t}(AbstractProduction),Alternation=function(e){function t(t){var n=e.call(this,t.definition)||this;return n.idx=1,n.ignoreAmbiguities=!1,n.hasPredicates=!1,assign(n,pick(t,(function(e){return void 0!==e}))),n}return __extends$8(t,e),t}(AbstractProduction),Terminal=function(){function e(e){this.idx=1,assign(this,pick(e,(function(e){return void 0!==e})))}return e.prototype.accept=function(e){e.visit(this)},e}();function serializeGrammar(e){return map(e,serializeProduction)}function serializeProduction(e){function t(e){return map(e,serializeProduction)}if(e instanceof NonTerminal)return{type:"NonTerminal",name:e.nonTerminalName,idx:e.idx};if(e instanceof Flat)return{type:"Flat",definition:t(e.definition)};if(e instanceof Option)return{type:"Option",idx:e.idx,definition:t(e.definition)};if(e instanceof RepetitionMandatory)return{type:"RepetitionMandatory",name:e.name,idx:e.idx,definition:t(e.definition)};if(e instanceof RepetitionMandatoryWithSeparator)return{type:"RepetitionMandatoryWithSeparator",name:e.name,idx:e.idx,separator:serializeProduction(new Terminal({terminalType:e.separator})),definition:t(e.definition)};if(e instanceof RepetitionWithSeparator)return{type:"RepetitionWithSeparator",name:e.name,idx:e.idx,separator:serializeProduction(new Terminal({terminalType:e.separator})),definition:t(e.definition)};if(e instanceof Repetition)return{type:"Repetition",name:e.name,idx:e.idx,definition:t(e.definition)};if(e instanceof Alternation)return{type:"Alternation",name:e.name,idx:e.idx,definition:t(e.definition)};if(e instanceof Terminal){var n={type:"Terminal",name:e.terminalType.name,label:tokenLabel(e.terminalType),idx:e.idx},r=e.terminalType.PATTERN;return e.terminalType.PATTERN&&(n.pattern=isRegExp(r)?r.source:r),n}if(e instanceof Rule)return{type:"Rule",name:e.name,orgText:e.orgText,definition:t(e.definition)};throw Error("non exhaustive match")}var RestWalker=function(){function e(){}return e.prototype.walk=function(e,t){var n=this;void 0===t&&(t=[]),forEach$1(e.definition,(function(r,a){var i=drop(e.definition,a+1);if(r instanceof NonTerminal)n.walkProdRef(r,i,t);else if(r instanceof Terminal)n.walkTerminal(r,i,t);else if(r instanceof Flat)n.walkFlat(r,i,t);else if(r instanceof Option)n.walkOption(r,i,t);else if(r instanceof RepetitionMandatory)n.walkAtLeastOne(r,i,t);else if(r instanceof RepetitionMandatoryWithSeparator)n.walkAtLeastOneSep(r,i,t);else if(r instanceof RepetitionWithSeparator)n.walkManySep(r,i,t);else if(r instanceof Repetition)n.walkMany(r,i,t);else{if(!(r instanceof Alternation))throw Error("non exhaustive match");n.walkOr(r,i,t)}}))},e.prototype.walkTerminal=function(e,t,n){},e.prototype.walkProdRef=function(e,t,n){},e.prototype.walkFlat=function(e,t,n){var r=t.concat(n);this.walk(e,r)},e.prototype.walkOption=function(e,t,n){var r=t.concat(n);this.walk(e,r)},e.prototype.walkAtLeastOne=function(e,t,n){var r=[new Option({definition:e.definition})].concat(t,n);this.walk(e,r)},e.prototype.walkAtLeastOneSep=function(e,t,n){var r=restForRepetitionWithSeparator(e,t,n);this.walk(e,r)},e.prototype.walkMany=function(e,t,n){var r=[new Option({definition:e.definition})].concat(t,n);this.walk(e,r)},e.prototype.walkManySep=function(e,t,n){var r=restForRepetitionWithSeparator(e,t,n);this.walk(e,r)},e.prototype.walkOr=function(e,t,n){var r=this,a=t.concat(n);forEach$1(e.definition,(function(e){var t=new Flat({definition:[e]});r.walk(t,a)}))},e}();function restForRepetitionWithSeparator(e,t,n){return[new Option({definition:[new Terminal({terminalType:e.separator})].concat(e.definition)})].concat(t,n)}var GAstVisitor=function(){function e(){}return e.prototype.visit=function(e){var t=e;switch(t.constructor){case NonTerminal:return this.visitNonTerminal(t);case Flat:return this.visitFlat(t);case Option:return this.visitOption(t);case RepetitionMandatory:return this.visitRepetitionMandatory(t);case RepetitionMandatoryWithSeparator:return this.visitRepetitionMandatoryWithSeparator(t);case RepetitionWithSeparator:return this.visitRepetitionWithSeparator(t);case Repetition:return this.visitRepetition(t);case Alternation:return this.visitAlternation(t);case Terminal:return this.visitTerminal(t);case Rule:return this.visitRule(t);default:throw Error("non exhaustive match")}},e.prototype.visitNonTerminal=function(e){},e.prototype.visitFlat=function(e){},e.prototype.visitOption=function(e){},e.prototype.visitRepetition=function(e){},e.prototype.visitRepetitionMandatory=function(e){},e.prototype.visitRepetitionMandatoryWithSeparator=function(e){},e.prototype.visitRepetitionWithSeparator=function(e){},e.prototype.visitAlternation=function(e){},e.prototype.visitTerminal=function(e){},e.prototype.visitRule=function(e){},e}(),__extends$7=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();function isSequenceProd(e){return e instanceof Flat||e instanceof Option||e instanceof Repetition||e instanceof RepetitionMandatory||e instanceof RepetitionMandatoryWithSeparator||e instanceof RepetitionWithSeparator||e instanceof Terminal||e instanceof Rule}function isOptionalProd(e,t){return void 0===t&&(t=[]),!!(e instanceof Option||e instanceof Repetition||e instanceof RepetitionWithSeparator)||(e instanceof Alternation?some(e.definition,(function(e){return isOptionalProd(e,t)})):!(e instanceof NonTerminal&&contains(t,e))&&(e instanceof AbstractProduction&&(e instanceof NonTerminal&&t.push(e),every(e.definition,(function(e){return isOptionalProd(e,t)})))))}function isBranchingProd(e){return e instanceof Alternation}function getProductionDslName(e){if(e instanceof NonTerminal)return"SUBRULE";if(e instanceof Option)return"OPTION";if(e instanceof Alternation)return"OR";if(e instanceof RepetitionMandatory)return"AT_LEAST_ONE";if(e instanceof RepetitionMandatoryWithSeparator)return"AT_LEAST_ONE_SEP";if(e instanceof RepetitionWithSeparator)return"MANY_SEP";if(e instanceof Repetition)return"MANY";if(e instanceof Terminal)return"CONSUME";throw Error("non exhaustive match")}var DslMethodsCollectorVisitor=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.separator="-",t.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]},t}return __extends$7(t,e),t.prototype.reset=function(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}},t.prototype.visitTerminal=function(e){var t=e.terminalType.name+this.separator+"Terminal";has(this.dslMethods,t)||(this.dslMethods[t]=[]),this.dslMethods[t].push(e)},t.prototype.visitNonTerminal=function(e){var t=e.nonTerminalName+this.separator+"Terminal";has(this.dslMethods,t)||(this.dslMethods[t]=[]),this.dslMethods[t].push(e)},t.prototype.visitOption=function(e){this.dslMethods.option.push(e)},t.prototype.visitRepetitionWithSeparator=function(e){this.dslMethods.repetitionWithSeparator.push(e)},t.prototype.visitRepetitionMandatory=function(e){this.dslMethods.repetitionMandatory.push(e)},t.prototype.visitRepetitionMandatoryWithSeparator=function(e){this.dslMethods.repetitionMandatoryWithSeparator.push(e)},t.prototype.visitRepetition=function(e){this.dslMethods.repetition.push(e)},t.prototype.visitAlternation=function(e){this.dslMethods.alternation.push(e)},t}(GAstVisitor),collectorVisitor=new DslMethodsCollectorVisitor;function collectMethods(e){collectorVisitor.reset(),e.accept(collectorVisitor);var t=collectorVisitor.dslMethods;return collectorVisitor.reset(),t}function first(e){if(e instanceof NonTerminal)return first(e.referencedRule);if(e instanceof Terminal)return firstForTerminal(e);if(isSequenceProd(e))return firstForSequence(e);if(isBranchingProd(e))return firstForBranching(e);throw Error("non exhaustive match")}function firstForSequence(e){for(var t,n=[],r=e.definition,a=0,i=r.length>a,s=!0;i&&s;)s=isOptionalProd(t=r[a]),n=n.concat(first(t)),a+=1,i=r.length>a;return uniq(n)}function firstForBranching(e){return uniq(flatten(map(e.definition,(function(e){return first(e)}))))}function firstForTerminal(e){return[e.terminalType]}var IN="_~IN~_",__extends$6=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),ResyncFollowsWalker=function(e){function t(t){var n=e.call(this)||this;return n.topProd=t,n.follows={},n}return __extends$6(t,e),t.prototype.startWalking=function(){return this.walk(this.topProd),this.follows},t.prototype.walkTerminal=function(e,t,n){},t.prototype.walkProdRef=function(e,t,n){var r=buildBetweenProdsFollowPrefix(e.referencedRule,e.idx)+this.topProd.name,a=t.concat(n),i=first(new Flat({definition:a}));this.follows[r]=i},t}(RestWalker);function computeAllProdsFollows(e){var t={};return forEach$1(e,(function(e){var n=new ResyncFollowsWalker(e).startWalking();assign(t,n)})),t}function buildBetweenProdsFollowPrefix(e,t){return e.name+t+IN}var BITS_FOR_METHOD_TYPE=4,BITS_FOR_OCCURRENCE_IDX=8,BITS_FOR_ALT_IDX=8,OR_IDX=1<1;forEach$1(e.definition,(function(r,a){if(!isUndefined$1(r.name)){var i=r.definition;i=n?[new Option({definition:r.definition})]:r.definition;var s=getKeyForAltIndex(t.ruleIdx,OR_IDX,e.idx,a);t.result.push({def:i,key:s,name:r.name,orgProd:r})}}))},t}(GAstVisitor);function expandAllNestedRuleNames(e,t){var n={allRuleNames:[]};return forEach$1(e,(function(e){var r=t[e.name];n.allRuleNames.push(e.name);var a=new NamedDSLMethodsCollectorVisitor(r);e.accept(a),forEach$1(a.result,(function(t){t.def,t.key;var r=t.name;n.allRuleNames.push(e.name+r)}))})),n}var __extends$4=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),AbstractNextPossibleTokensWalker=function(e){function t(t,n){var r=e.call(this)||this;return r.topProd=t,r.path=n,r.possibleTokTypes=[],r.nextProductionName="",r.nextProductionOccurrence=0,r.found=!1,r.isAtEndOfPath=!1,r}return __extends$4(t,e),t.prototype.startWalking=function(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=cloneArr(this.path.ruleStack).reverse(),this.occurrenceStack=cloneArr(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes},t.prototype.walk=function(t,n){void 0===n&&(n=[]),this.found||e.prototype.walk.call(this,t,n)},t.prototype.walkProdRef=function(e,t,n){if(e.referencedRule.name===this.nextProductionName&&e.idx===this.nextProductionOccurrence){var r=t.concat(n);this.updateExpectedNext(),this.walk(e.referencedRule,r)}},t.prototype.updateExpectedNext=function(){isEmpty(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())},t}(RestWalker),NextAfterTokenWalker=function(e){function t(t,n){var r=e.call(this,t,n)||this;return r.path=n,r.nextTerminalName="",r.nextTerminalOccurrence=0,r.nextTerminalName=r.path.lastTok.name,r.nextTerminalOccurrence=r.path.lastTokOccurrence,r}return __extends$4(t,e),t.prototype.walkTerminal=function(e,t,n){if(this.isAtEndOfPath&&e.terminalType.name===this.nextTerminalName&&e.idx===this.nextTerminalOccurrence&&!this.found){var r=t.concat(n),a=new Flat({definition:r});this.possibleTokTypes=first(a),this.found=!0}},t}(AbstractNextPossibleTokensWalker),AbstractNextTerminalAfterProductionWalker=function(e){function t(t,n){var r=e.call(this)||this;return r.topRule=t,r.occurrence=n,r.result={token:void 0,occurrence:void 0,isEndOfRule:void 0},r}return __extends$4(t,e),t.prototype.startWalking=function(){return this.walk(this.topRule),this.result},t}(RestWalker),NextTerminalAfterManyWalker=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$4(t,e),t.prototype.walkMany=function(t,n,r){if(t.idx===this.occurrence){var a=first$1(n.concat(r));this.result.isEndOfRule=void 0===a,a instanceof Terminal&&(this.result.token=a.terminalType,this.result.occurrence=a.idx)}else e.prototype.walkMany.call(this,t,n,r)},t}(AbstractNextTerminalAfterProductionWalker),NextTerminalAfterManySepWalker=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$4(t,e),t.prototype.walkManySep=function(t,n,r){if(t.idx===this.occurrence){var a=first$1(n.concat(r));this.result.isEndOfRule=void 0===a,a instanceof Terminal&&(this.result.token=a.terminalType,this.result.occurrence=a.idx)}else e.prototype.walkManySep.call(this,t,n,r)},t}(AbstractNextTerminalAfterProductionWalker),NextTerminalAfterAtLeastOneWalker=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$4(t,e),t.prototype.walkAtLeastOne=function(t,n,r){if(t.idx===this.occurrence){var a=first$1(n.concat(r));this.result.isEndOfRule=void 0===a,a instanceof Terminal&&(this.result.token=a.terminalType,this.result.occurrence=a.idx)}else e.prototype.walkAtLeastOne.call(this,t,n,r)},t}(AbstractNextTerminalAfterProductionWalker),NextTerminalAfterAtLeastOneSepWalker=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$4(t,e),t.prototype.walkAtLeastOneSep=function(t,n,r){if(t.idx===this.occurrence){var a=first$1(n.concat(r));this.result.isEndOfRule=void 0===a,a instanceof Terminal&&(this.result.token=a.terminalType,this.result.occurrence=a.idx)}else e.prototype.walkAtLeastOneSep.call(this,t,n,r)},t}(AbstractNextTerminalAfterProductionWalker);function possiblePathsFrom(e,t,n){void 0===n&&(n=[]),n=cloneArr(n);var r=[],a=0;function i(i){var s=possiblePathsFrom(i.concat(drop(e,a+1)),t,n);return r.concat(s)}for(;n.length=0;w--){var E={idx:h,def:g.definition[w].definition.concat(drop(m)),ruleStack:f,occurrenceStack:y};p.push(E),p.push(s)}else if(g instanceof Flat)p.push({idx:h,def:g.definition.concat(drop(m)),ruleStack:f,occurrenceStack:y});else{if(!(g instanceof Rule))throw Error("non exhaustive match");p.push(expandTopLevelRule(g,h,f,y))}}}else o&&last(p).idx<=u&&p.pop()}return c}function expandTopLevelRule(e,t,n,r){var a=cloneArr(n);a.push(e.name);var i=cloneArr(r);return i.push(1),{idx:t,def:e.definition,ruleStack:a,occurrenceStack:i}}var __extends$3=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),PROD_TYPE;function getProdType(e){if(e instanceof Option)return PROD_TYPE.OPTION;if(e instanceof Repetition)return PROD_TYPE.REPETITION;if(e instanceof RepetitionMandatory)return PROD_TYPE.REPETITION_MANDATORY;if(e instanceof RepetitionMandatoryWithSeparator)return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR;if(e instanceof RepetitionWithSeparator)return PROD_TYPE.REPETITION_WITH_SEPARATOR;if(e instanceof Alternation)return PROD_TYPE.ALTERNATION;throw Error("non exhaustive match")}function buildLookaheadFuncForOr(e,t,n,r,a,i){var s=getLookaheadPathsForOr(e,t,n);return i(s,r,areTokenCategoriesNotUsed(s)?tokenStructuredMatcherNoCategories:tokenStructuredMatcher,a)}function buildLookaheadFuncForOptionalProd(e,t,n,r,a,i){var s=getLookaheadPathsForOptionalProd(e,t,a,n),o=areTokenCategoriesNotUsed(s)?tokenStructuredMatcherNoCategories:tokenStructuredMatcher;return i(s[0],o,r)}function buildAlternativesLookAheadFunc(e,t,n,r){var a=e.length,i=every(e,(function(e){return every(e,(function(e){return 1===e.length}))}));if(t)return function(t){for(var r=map(t,(function(e){return e.GATE})),i=0;i1}))),(function(n){var r=first$1(n),a=t.buildDuplicateFoundError(e,n),i=getProductionDslName(r),s={message:a,type:ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,ruleName:e.name,dslName:i,occurrence:r.idx},o=getExtraProductionArgument(r);return o&&(s.parameter=o),s}))}function identifyProductionForDuplicates(e){return getProductionDslName(e)+"_#_"+e.idx+"_#_"+getExtraProductionArgument(e)}function getExtraProductionArgument(e){return e instanceof Terminal?e.terminalType.name:e instanceof NonTerminal?e.nonTerminalName:""}var OccurrenceValidationCollector=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.allProductions=[],t}return __extends$2(t,e),t.prototype.visitNonTerminal=function(e){this.allProductions.push(e)},t.prototype.visitOption=function(e){this.allProductions.push(e)},t.prototype.visitRepetitionWithSeparator=function(e){this.allProductions.push(e)},t.prototype.visitRepetitionMandatory=function(e){this.allProductions.push(e)},t.prototype.visitRepetitionMandatoryWithSeparator=function(e){this.allProductions.push(e)},t.prototype.visitRepetition=function(e){this.allProductions.push(e)},t.prototype.visitAlternation=function(e){this.allProductions.push(e)},t.prototype.visitTerminal=function(e){this.allProductions.push(e)},t}(GAstVisitor),validTermsPattern=/^[a-zA-Z_]\w*$/,validNestedRuleName=new RegExp(validTermsPattern.source.replace("^","^\\$"));function validateRuleName(e,t){var n=[],r=e.name;return r.match(validTermsPattern)||n.push({message:t.buildInvalidRuleNameError({topLevelRule:e,expectedPattern:validTermsPattern}),type:ParserDefinitionErrorType.INVALID_RULE_NAME,ruleName:r}),n}function validateNestedRuleName(e,t,n){var r,a=[];return t.name.match(validNestedRuleName)||(r=n.buildInvalidNestedRuleNameError(e,t),a.push({message:r,type:ParserDefinitionErrorType.INVALID_NESTED_RULE_NAME,ruleName:e.name})),a}function validateTokenName(e,t){var n=[];return e.name.match(validTermsPattern)||n.push({message:t.buildTokenNameError({tokenType:e,expectedPattern:validTermsPattern}),type:ParserDefinitionErrorType.INVALID_TOKEN_NAME}),n}function validateRuleDoesNotAlreadyExist(e,t,n,r){var a=[];if(reduce(t,(function(t,n){return n.name===e.name?t+1:t}),0)>1){var i=r.buildDuplicateRuleNameError({topLevelRule:e,grammarName:n});a.push({message:i,type:ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:e.name})}return a}function validateRuleIsOverridden(e,t,n){var r,a=[];return contains(t,e)||(r="Invalid rule override, rule: ->"+e+"<- cannot be overridden in the grammar: ->"+n+"<-as it is not defined in any of the super grammars ",a.push({message:r,type:ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,ruleName:e})),a}function validateNoLeftRecursion(e,t,n,r){void 0===r&&(r=[]);var a=[],i=getFirstNoneTerminal(t.definition);if(isEmpty(i))return[];var s=e.name;contains(i,e)&&a.push({message:n.buildLeftRecursionError({topLevelRule:e,leftRecursionPath:r}),type:ParserDefinitionErrorType.LEFT_RECURSION,ruleName:s});var o=map(difference(i,r.concat([e])),(function(t){var a=cloneArr(r);return a.push(t),validateNoLeftRecursion(e,t,n,a)}));return a.concat(flatten(o))}function getFirstNoneTerminal(e){var t=[];if(isEmpty(e))return t;var n=first$1(e);if(n instanceof NonTerminal)t.push(n.referencedRule);else if(n instanceof Flat||n instanceof Option||n instanceof RepetitionMandatory||n instanceof RepetitionMandatoryWithSeparator||n instanceof RepetitionWithSeparator||n instanceof Repetition)t=t.concat(getFirstNoneTerminal(n.definition));else if(n instanceof Alternation)t=flatten(map(n.definition,(function(e){return getFirstNoneTerminal(e.definition)})));else if(!(n instanceof Terminal))throw Error("non exhaustive match");var r=isOptionalProd(n),a=e.length>1;if(r&&a){var i=drop(e);return t.concat(getFirstNoneTerminal(i))}return t}var OrCollector=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.alternations=[],t}return __extends$2(t,e),t.prototype.visitAlternation=function(e){this.alternations.push(e)},t}(GAstVisitor);function validateEmptyOrAlternative(e,t){var n=new OrCollector;return e.accept(n),reduce(n.alternations,(function(n,r){var a=map(dropRight(r.definition),(function(n,a){return isEmpty(nextPossibleTokensAfter([n],[],null,1))?{message:t.buildEmptyAlternationError({topLevelRule:e,alternation:r,emptyChoiceIdx:a}),type:ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,ruleName:e.name,occurrence:r.idx,alternative:a+1}:null}));return n.concat(compact(a))}),[])}function validateAmbiguousAlternationAlternatives(e,t,n,r){var a=new OrCollector;e.accept(a);var i=a.alternations,s=n[e.name];return s&&(i=reject(i,(function(e){return s[getProductionDslName(e)+(0===e.idx?"":e.idx)]}))),reduce(i=reject(i,(function(e){return!0===e.ignoreAmbiguities})),(function(n,a){var i=a.idx,s=a.maxLookahead||t,o=getLookaheadPathsForOr(i,e,s,a),l=checkAlternativesAmbiguities(o,a,e,r),u=checkPrefixAlternativesAmbiguities(o,a,e,r);return n.concat(l,u)}),[])}var RepetionCollector=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.allProductions=[],t}return __extends$2(t,e),t.prototype.visitRepetitionWithSeparator=function(e){this.allProductions.push(e)},t.prototype.visitRepetitionMandatory=function(e){this.allProductions.push(e)},t.prototype.visitRepetitionMandatoryWithSeparator=function(e){this.allProductions.push(e)},t.prototype.visitRepetition=function(e){this.allProductions.push(e)},t}(GAstVisitor);function validateTooManyAlts(e,t){var n=new OrCollector;return e.accept(n),reduce(n.alternations,(function(n,r){return r.definition.length>255&&n.push({message:t.buildTooManyAlternativesError({topLevelRule:e,alternation:r}),type:ParserDefinitionErrorType.TOO_MANY_ALTS,ruleName:e.name,occurrence:r.idx}),n}),[])}function validateSomeNonEmptyLookaheadPath(e,t,n){var r=[];return forEach$1(e,(function(e){var a=new RepetionCollector;e.accept(a),forEach$1(a.allProductions,(function(a){var i=getProdType(a),s=a.maxLookahead||t;if(isEmpty(flatten(getLookaheadPathsForOptionalProd(a.idx,e,i,s)[0]))){var o=n.buildEmptyRepetitionError({topLevelRule:e,repetition:a});r.push({message:o,type:ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,ruleName:e.name})}}))})),r}function checkAlternativesAmbiguities(e,t,n,r){var a=[];return map(reduce(e,(function(n,r,i){return!0===t.definition[i].ignoreAmbiguities||forEach$1(r,(function(r){var s=[i];forEach$1(e,(function(e,n){i!==n&&containsPath(e,r)&&!0!==t.definition[n].ignoreAmbiguities&&s.push(n)})),s.length>1&&!containsPath(a,r)&&(a.push(r),n.push({alts:s,path:r}))})),n}),[]),(function(e){var a=map(e.alts,(function(e){return e+1}));return{message:r.buildAlternationAmbiguityError({topLevelRule:n,alternation:t,ambiguityIndices:a,prefixPath:e.path}),type:ParserDefinitionErrorType.AMBIGUOUS_ALTS,ruleName:n.name,occurrence:t.idx,alternatives:[e.alts]}}))}function checkPrefixAlternativesAmbiguities(e,t,n,r){var a=[],i=reduce(e,(function(e,t,n){var r=map(t,(function(e){return{idx:n,path:e}}));return e.concat(r)}),[]);return forEach$1(i,(function(e){if(!0!==t.definition[e.idx].ignoreAmbiguities){var s=e.idx,o=e.path,l=map(findAll(i,(function(e){return!0!==t.definition[e.idx].ignoreAmbiguities&&e.idx1}))),(function(r){var a=map(r,(function(e){return e.orgProd})),i=t.buildDuplicateNestedRuleNameError(e,a);n.push({message:i,type:ParserDefinitionErrorType.DUPLICATE_NESTED_NAME,ruleName:e.name})}))})),n}var defaultParserErrorProvider={buildMismatchTokenMessage:function(e){var t=e.expected,n=e.actual;return e.previous,e.ruleName,"Expecting "+(hasTokenLabel(t)?"--\x3e "+tokenLabel(t)+" <--":"token of type --\x3e "+t.name+" <--")+" but found --\x3e '"+n.image+"' <--"},buildNotAllInputParsedMessage:function(e){var t=e.firstRedundant;return e.ruleName,"Redundant input, expecting EOF but found: "+t.image},buildNoViableAltMessage:function(e){var t=e.expectedPathsPerAlt,n=e.actual;e.previous;var r=e.customUserDescription;e.ruleName;var a="Expecting: ",i="\nbut found: '"+first$1(n).image+"'";if(r)return a+r+i;var s=map(reduce(t,(function(e,t){return e.concat(t)}),[]),(function(e){return"["+map(e,(function(e){return tokenLabel(e)})).join(", ")+"]"}));return a+("one of these possible Token sequences:\n"+map(s,(function(e,t){return" "+(t+1)+". "+e})).join("\n"))+i},buildEarlyExitMessage:function(e){var t=e.expectedIterationPaths,n=e.actual,r=e.customUserDescription;e.ruleName;var a="Expecting: ",i="\nbut found: '"+first$1(n).image+"'";return r?a+r+i:a+("expecting at least one iteration which starts with one of these possible Token sequences::\n <"+map(t,(function(e){return"["+map(e,(function(e){return tokenLabel(e)})).join(",")+"]"})).join(" ,")+">")+i}};Object.freeze(defaultParserErrorProvider);var defaultGrammarResolverErrorProvider={buildRuleNotFoundError:function(e,t){return"Invalid grammar, reference to a rule which is not defined: ->"+t.nonTerminalName+"<-\ninside top level rule: ->"+e.name+"<-"}},defaultGrammarValidatorErrorProvider={buildDuplicateFoundError:function(e,t){var n,r=e.name,a=first$1(t),i=a.idx,s=getProductionDslName(a),o=(n=a)instanceof Terminal?n.terminalType.name:n instanceof NonTerminal?n.nonTerminalName:"",l="->"+s+(i>0?i:"")+"<- "+(o?"with argument: ->"+o+"<-":"")+"\n appears more than once ("+t.length+" times) in the top level rule: ->"+r+"<-. \n For further details see: https://sap.github.io/chevrotain/docs/FAQ.html#NUMERICAL_SUFFIXES \n ";return l=(l=l.replace(/[ \t]+/g," ")).replace(/\s\s+/g,"\n")},buildInvalidNestedRuleNameError:function(e,t){return"Invalid nested rule name: ->"+t.name+"<- inside rule: ->"+e.name+"<-\nit must match the pattern: ->"+validNestedRuleName.toString()+"<-.\nNote that this means a nested rule name must start with the '$'(dollar) sign."},buildDuplicateNestedRuleNameError:function(e,t){return"Duplicate nested rule name: ->"+first$1(t).name+"<- inside rule: ->"+e.name+"<-\nA nested name must be unique in the scope of a top level grammar rule."},buildNamespaceConflictError:function(e){return"Namespace conflict found in grammar.\nThe grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <"+e.name+">.\nTo resolve this make sure each Terminal and Non-Terminal names are unique\nThis is easy to accomplish by using the convention that Terminal names start with an uppercase letter\nand Non-Terminal names start with a lower case letter."},buildAlternationPrefixAmbiguityError:function(e){var t=map(e.prefixPath,(function(e){return tokenLabel(e)})).join(", "),n=0===e.alternation.idx?"":e.alternation.idx;return"Ambiguous alternatives: <"+e.ambiguityIndices.join(" ,")+"> due to common lookahead prefix\nin inside <"+e.topLevelRule.name+"> Rule,\n<"+t+"> may appears as a prefix path in all these alternatives.\nSee: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX\nFor Further details."},buildAlternationAmbiguityError:function(e){var t=map(e.prefixPath,(function(e){return tokenLabel(e)})).join(", "),n=0===e.alternation.idx?"":e.alternation.idx,r="Ambiguous Alternatives Detected: <"+e.ambiguityIndices.join(" ,")+"> in inside <"+e.topLevelRule.name+"> Rule,\n<"+t+"> may appears as a prefix path in all these alternatives.\n";return r+="See: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES\nFor Further details."},buildEmptyRepetitionError:function(e){var t=getProductionDslName(e.repetition);return 0!==e.repetition.idx&&(t+=e.repetition.idx),"The repetition <"+t+"> within Rule <"+e.topLevelRule.name+"> can never consume any tokens.\nThis could lead to an infinite loop."},buildTokenNameError:function(e){return"Invalid Grammar Token name: ->"+e.tokenType.name+"<- it must match the pattern: ->"+e.expectedPattern.toString()+"<-"},buildEmptyAlternationError:function(e){return"Ambiguous empty alternative: <"+(e.emptyChoiceIdx+1)+"> in inside <"+e.topLevelRule.name+"> Rule.\nOnly the last alternative may be an empty alternative."},buildTooManyAlternativesError:function(e){return"An Alternation cannot have more than 256 alternatives:\n inside <"+e.topLevelRule.name+"> Rule.\n has "+(e.alternation.definition.length+1)+" alternatives."},buildLeftRecursionError:function(e){var t=e.topLevelRule.name;return"Left Recursion found in grammar.\nrule: <"+t+"> can be invoked from itself (directly or indirectly)\nwithout consuming any Tokens. The grammar path that causes this is: \n "+(t+" --\x3e "+map(e.leftRecursionPath,(function(e){return e.name})).concat([t]).join(" --\x3e "))+"\n To fix this refactor your grammar to remove the left recursion.\nsee: https://en.wikipedia.org/wiki/LL_parser#Left_Factoring."},buildInvalidRuleNameError:function(e){return"Invalid grammar rule name: ->"+e.topLevelRule.name+"<- it must match the pattern: ->"+e.expectedPattern.toString()+"<-"},buildDuplicateRuleNameError:function(e){return"Duplicate definition, rule: ->"+(e.topLevelRule instanceof Rule?e.topLevelRule.name:e.topLevelRule)+"<- is already defined in the grammar: ->"+e.grammarName+"<-"}},__extends$1=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();function resolveGrammar$1(e,t){var n=new GastRefResolverVisitor(e,t);return n.resolveRefs(),n.errors}var GastRefResolverVisitor=function(e){function t(t,n){var r=e.call(this)||this;return r.nameToTopRule=t,r.errMsgProvider=n,r.errors=[],r}return __extends$1(t,e),t.prototype.resolveRefs=function(){var e=this;forEach$1(values(this.nameToTopRule),(function(t){e.currTopLevel=t,t.accept(e)}))},t.prototype.visitNonTerminal=function(e){var t=this.nameToTopRule[e.nonTerminalName];if(t)e.referencedRule=t;else{var n=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,e);this.errors.push({message:n,type:ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:e.nonTerminalName})}},t}(GAstVisitor);function resolveGrammar(e){e=defaults$4(e,{errMsgProvider:defaultGrammarResolverErrorProvider});var t={};return forEach$1(e.rules,(function(e){t[e.name]=e})),resolveGrammar$1(t,e.errMsgProvider)}function validateGrammar(e){return validateGrammar$1((e=defaults$4(e,{errMsgProvider:defaultGrammarValidatorErrorProvider,ignoredIssues:{}})).rules,e.maxLookahead,e.tokenTypes,e.ignoredIssues,e.errMsgProvider,e.grammarName)}var MISMATCHED_TOKEN_EXCEPTION="MismatchedTokenException",NO_VIABLE_ALT_EXCEPTION="NoViableAltException",EARLY_EXIT_EXCEPTION="EarlyExitException",NOT_ALL_INPUT_PARSED_EXCEPTION="NotAllInputParsedException",RECOGNITION_EXCEPTION_NAMES=[MISMATCHED_TOKEN_EXCEPTION,NO_VIABLE_ALT_EXCEPTION,EARLY_EXIT_EXCEPTION,NOT_ALL_INPUT_PARSED_EXCEPTION];function isRecognitionException(e){return contains(RECOGNITION_EXCEPTION_NAMES,e.name)}function MismatchedTokenException(e,t,n){this.name=MISMATCHED_TOKEN_EXCEPTION,this.message=e,this.token=t,this.previousToken=n,this.resyncedTokens=[]}function NoViableAltException(e,t,n){this.name=NO_VIABLE_ALT_EXCEPTION,this.message=e,this.token=t,this.previousToken=n,this.resyncedTokens=[]}function NotAllInputParsedException(e,t){this.name=NOT_ALL_INPUT_PARSED_EXCEPTION,this.message=e,this.token=t,this.resyncedTokens=[]}function EarlyExitException(e,t,n){this.name=EARLY_EXIT_EXCEPTION,this.message=e,this.token=t,this.previousToken=n,this.resyncedTokens=[]}Object.freeze(RECOGNITION_EXCEPTION_NAMES),MismatchedTokenException.prototype=Error.prototype,NoViableAltException.prototype=Error.prototype,NotAllInputParsedException.prototype=Error.prototype,EarlyExitException.prototype=Error.prototype;var EOF_FOLLOW_KEY={},IN_RULE_RECOVERY_EXCEPTION="InRuleRecoveryException";function InRuleRecoveryException(e){this.name=IN_RULE_RECOVERY_EXCEPTION,this.message=e}InRuleRecoveryException.prototype=Error.prototype;var Recoverable=function(){function e(){}return e.prototype.initRecoverable=function(e){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=has(e,"recoveryEnabled")?e.recoveryEnabled:DEFAULT_PARSER_CONFIG.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=attemptInRepetitionRecovery)},e.prototype.getTokenToInsert=function(e){var t=createTokenInstance(e,"",NaN,NaN,NaN,NaN,NaN,NaN);return t.isInsertedInRecovery=!0,t},e.prototype.canTokenTypeBeInsertedInRecovery=function(e){return!0},e.prototype.tryInRepetitionRecovery=function(e,t,n,r){for(var a=this,i=this.findReSyncTokenType(),s=this.exportLexerState(),o=[],l=!1,u=this.LA(1),c=this.LA(1),p=function(){var e=a.LA(0),t=new MismatchedTokenException(a.errorMessageProvider.buildMismatchTokenMessage({expected:r,actual:u,previous:e,ruleName:a.getCurrRuleFullName()}),u,a.LA(0));t.resyncedTokens=dropRight(o),a.SAVE_ERROR(t)};!l;){if(this.tokenMatcher(c,r))return void p();if(n.call(this))return p(),void e.apply(this,t);this.tokenMatcher(c,i)?l=!0:(c=this.SKIP_TOKEN(),this.addToResyncTokens(c,o))}this.importLexerState(s)},e.prototype.shouldInRepetitionRecoveryBeTried=function(e,t,n){return!1!==n&&(void 0!==e&&void 0!==t&&(!this.tokenMatcher(this.LA(1),e)&&(!this.isBackTracking()&&!this.canPerformInRuleRecovery(e,this.getFollowsForInRuleRecovery(e,t)))))},e.prototype.getFollowsForInRuleRecovery=function(e,t){var n=this.getCurrentGrammarPath(e,t);return this.getNextPossibleTokenTypes(n)},e.prototype.tryInRuleRecovery=function(e,t){if(this.canRecoverWithSingleTokenInsertion(e,t))return this.getTokenToInsert(e);if(this.canRecoverWithSingleTokenDeletion(e)){var n=this.SKIP_TOKEN();return this.consumeToken(),n}throw new InRuleRecoveryException("sad sad panda")},e.prototype.canPerformInRuleRecovery=function(e,t){return this.canRecoverWithSingleTokenInsertion(e,t)||this.canRecoverWithSingleTokenDeletion(e)},e.prototype.canRecoverWithSingleTokenInsertion=function(e,t){var n=this;if(!this.canTokenTypeBeInsertedInRecovery(e))return!1;if(isEmpty(t))return!1;var r=this.LA(1);return void 0!==find(t,(function(e){return n.tokenMatcher(r,e)}))},e.prototype.canRecoverWithSingleTokenDeletion=function(e){return this.tokenMatcher(this.LA(2),e)},e.prototype.isInCurrentRuleReSyncSet=function(e){var t=this.getCurrFollowKey();return contains(this.getFollowSetFromFollowKey(t),e)},e.prototype.findReSyncTokenType=function(){for(var e=this.flattenFollowSet(),t=this.LA(1),n=2;;){var r=t.tokenType;if(contains(e,r))return r;t=this.LA(n),n++}},e.prototype.getCurrFollowKey=function(){if(1===this.RULE_STACK.length)return EOF_FOLLOW_KEY;var e=this.getLastExplicitRuleShortName(),t=this.getLastExplicitRuleOccurrenceIndex(),n=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(e),idxInCallingRule:t,inRule:this.shortRuleNameToFullName(n)}},e.prototype.buildFullFollowKeyStack=function(){var e=this,t=this.RULE_STACK,n=this.RULE_OCCURRENCE_STACK;return isEmpty(this.LAST_EXPLICIT_RULE_STACK)||(t=map(this.LAST_EXPLICIT_RULE_STACK,(function(t){return e.RULE_STACK[t]})),n=map(this.LAST_EXPLICIT_RULE_STACK,(function(t){return e.RULE_OCCURRENCE_STACK[t]}))),map(t,(function(r,a){return 0===a?EOF_FOLLOW_KEY:{ruleName:e.shortRuleNameToFullName(r),idxInCallingRule:n[a],inRule:e.shortRuleNameToFullName(t[a-1])}}))},e.prototype.flattenFollowSet=function(){var e=this;return flatten(map(this.buildFullFollowKeyStack(),(function(t){return e.getFollowSetFromFollowKey(t)})))},e.prototype.getFollowSetFromFollowKey=function(e){if(e===EOF_FOLLOW_KEY)return[EOF];var t=e.ruleName+e.idxInCallingRule+IN+e.inRule;return this.resyncFollows[t]},e.prototype.addToResyncTokens=function(e,t){return this.tokenMatcher(e,EOF)||t.push(e),t},e.prototype.reSyncTo=function(e){for(var t=[],n=this.LA(1);!1===this.tokenMatcher(n,e);)n=this.SKIP_TOKEN(),this.addToResyncTokens(n,t);return dropRight(t)},e.prototype.attemptInRepetitionRecovery=function(e,t,n,r,a,i,s){},e.prototype.getCurrentGrammarPath=function(e,t){return{ruleStack:this.getHumanReadableRuleStack(),occurrenceStack:cloneArr(this.RULE_OCCURRENCE_STACK),lastTok:e,lastTokOccurrence:t}},e.prototype.getHumanReadableRuleStack=function(){var e=this;return isEmpty(this.LAST_EXPLICIT_RULE_STACK)?map(this.RULE_STACK,(function(t){return e.shortRuleNameToFullName(t)})):map(this.LAST_EXPLICIT_RULE_STACK,(function(t){return e.shortRuleNameToFullName(e.RULE_STACK[t])}))},e}();function attemptInRepetitionRecovery(e,t,n,r,a,i,s){var o=this.getKeyForAutomaticLookahead(r,a),l=this.firstAfterRepMap[o];if(void 0===l){var u=this.getCurrRuleFullName();l=new i(this.getGAstProductions()[u],a).startWalking(),this.firstAfterRepMap[o]=l}var c=l.token,p=l.occurrence,d=l.isEndOfRule;1===this.RULE_STACK.length&&d&&void 0===c&&(c=EOF,p=1),this.shouldInRepetitionRecoveryBeTried(c,p,s)&&this.tryInRepetitionRecovery(e,t,n,c)}var LooksAhead=function(){function e(){}return e.prototype.initLooksAhead=function(e){this.dynamicTokensEnabled=has(e,"dynamicTokensEnabled")?e.dynamicTokensEnabled:DEFAULT_PARSER_CONFIG.dynamicTokensEnabled,this.maxLookahead=has(e,"maxLookahead")?e.maxLookahead:DEFAULT_PARSER_CONFIG.maxLookahead,this.lookAheadFuncsCache=isES2015MapSupported()?new Map:[],isES2015MapSupported()?(this.getLaFuncFromCache=this.getLaFuncFromMap,this.setLaFuncCache=this.setLaFuncCacheUsingMap):(this.getLaFuncFromCache=this.getLaFuncFromObj,this.setLaFuncCache=this.setLaFuncUsingObj)},e.prototype.preComputeLookaheadFunctions=function(e){var t=this;forEach$1(e,(function(e){t.TRACE_INIT(e.name+" Rule Lookahead",(function(){var n=collectMethods(e),r=n.alternation,a=n.repetition,i=n.option,s=n.repetitionMandatory,o=n.repetitionMandatoryWithSeparator,l=n.repetitionWithSeparator;forEach$1(r,(function(n){var r=0===n.idx?"":n.idx;t.TRACE_INIT(""+getProductionDslName(n)+r,(function(){var r=buildLookaheadFuncForOr(n.idx,e,n.maxLookahead||t.maxLookahead,n.hasPredicates,t.dynamicTokensEnabled,t.lookAheadBuilderForAlternatives),a=getKeyForAutomaticLookahead(t.fullRuleNameToShort[e.name],OR_IDX,n.idx);t.setLaFuncCache(a,r)}))})),forEach$1(a,(function(n){t.computeLookaheadFunc(e,n.idx,MANY_IDX,PROD_TYPE.REPETITION,n.maxLookahead,getProductionDslName(n))})),forEach$1(i,(function(n){t.computeLookaheadFunc(e,n.idx,OPTION_IDX,PROD_TYPE.OPTION,n.maxLookahead,getProductionDslName(n))})),forEach$1(s,(function(n){t.computeLookaheadFunc(e,n.idx,AT_LEAST_ONE_IDX,PROD_TYPE.REPETITION_MANDATORY,n.maxLookahead,getProductionDslName(n))})),forEach$1(o,(function(n){t.computeLookaheadFunc(e,n.idx,AT_LEAST_ONE_SEP_IDX,PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,n.maxLookahead,getProductionDslName(n))})),forEach$1(l,(function(n){t.computeLookaheadFunc(e,n.idx,MANY_SEP_IDX,PROD_TYPE.REPETITION_WITH_SEPARATOR,n.maxLookahead,getProductionDslName(n))}))}))}))},e.prototype.computeLookaheadFunc=function(e,t,n,r,a,i){var s=this;this.TRACE_INIT(""+i+(0===t?"":t),(function(){var i=buildLookaheadFuncForOptionalProd(t,e,a||s.maxLookahead,s.dynamicTokensEnabled,r,s.lookAheadBuilderForOptional),o=getKeyForAutomaticLookahead(s.fullRuleNameToShort[e.name],n,t);s.setLaFuncCache(o,i)}))},e.prototype.lookAheadBuilderForOptional=function(e,t,n){return buildSingleAlternativeLookaheadFunction(e,t,n)},e.prototype.lookAheadBuilderForAlternatives=function(e,t,n,r){return buildAlternativesLookAheadFunc(e,t,n,r)},e.prototype.getKeyForAutomaticLookahead=function(e,t){return getKeyForAutomaticLookahead(this.getLastExplicitRuleShortName(),e,t)},e.prototype.getLaFuncFromCache=function(e){},e.prototype.getLaFuncFromMap=function(e){return this.lookAheadFuncsCache.get(e)},e.prototype.getLaFuncFromObj=function(e){return this.lookAheadFuncsCache[e]},e.prototype.setLaFuncCache=function(e,t){},e.prototype.setLaFuncCacheUsingMap=function(e,t){this.lookAheadFuncsCache.set(e,t)},e.prototype.setLaFuncUsingObj=function(e,t){this.lookAheadFuncsCache[e]=t},e}();function classNameFromInstance(e){return functionName(e.constructor)}var FUNC_NAME_REGEXP=/^\s*function\s*(\S*)\s*\(/,NAME="name",CstVisitorDefinitionError;function functionName(e){var t=e.name;return t||e.toString().match(FUNC_NAME_REGEXP)[1]}function defineNameProp(e,t){var n=Object.getOwnPropertyDescriptor(e,NAME);return!(!isUndefined$1(n)&&!n.configurable)&&(Object.defineProperty(e,NAME,{enumerable:!1,configurable:!0,writable:!1,value:t}),!0)}function defaultVisit(e,t){for(var n=keys(e),r=n.length,a=0;a:\n\t"+n.join("\n\n").replace(/\n/g,"\n\t"))}}}).constructor=n,n._RULE_NAMES=t,n}function createBaseVisitorConstructorWithDefaults(e,t,n){var r=function(){};defineNameProp(r,e+"BaseSemanticsWithDefaults");var a=Object.create(n.prototype);return forEach$1(t,(function(e){a[e]=defaultVisit})),(r.prototype=a).constructor=r,r}function validateVisitor(e,t){var n=validateMissingCstMethods(e,t),r=validateRedundantMethods(e,t);return n.concat(r)}function validateMissingCstMethods(e,t){return compact(map(t,(function(t){if(!isFunction$1(e[t]))return{msg:"Missing visitor method: <"+t+"> on "+functionName(e.constructor)+" CST Visitor.",type:CstVisitorDefinitionError.MISSING_METHOD,methodName:t}})))}!function(e){e[e.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",e[e.MISSING_METHOD=1]="MISSING_METHOD"}(CstVisitorDefinitionError||(CstVisitorDefinitionError={}));var VALID_PROP_NAMES=["constructor","visit","validateVisitor"];function validateRedundantMethods(e,t){var n=[];for(var r in e)validTermsPattern.test(r)&&isFunction$1(e[r])&&!contains(VALID_PROP_NAMES,r)&&!contains(t,r)&&n.push({msg:"Redundant visitor method: <"+r+"> on "+functionName(e.constructor)+" CST Visitor\nThere is no Grammar Rule corresponding to this method's name.\nFor utility methods on visitor classes use methods names that do not match /"+validTermsPattern.source+"/.",type:CstVisitorDefinitionError.REDUNDANT_METHOD,methodName:r});return n}var TreeBuilder=function(){function e(){}return e.prototype.initTreeBuilder=function(e){if(this.LAST_EXPLICIT_RULE_STACK=[],this.CST_STACK=[],this.outputCst=has(e,"outputCst")?e.outputCst:DEFAULT_PARSER_CONFIG.outputCst,this.nodeLocationTracking=has(e,"nodeLocationTracking")?e.nodeLocationTracking:DEFAULT_PARSER_CONFIG.nodeLocationTracking,this.outputCst)if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=setNodeLocationFull,this.setNodeLocationFromNode=setNodeLocationFull,this.cstPostRule=NOOP,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=NOOP,this.setNodeLocationFromNode=NOOP,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=setNodeLocationOnlyOffset,this.setNodeLocationFromNode=setNodeLocationOnlyOffset,this.cstPostRule=NOOP,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=NOOP,this.setNodeLocationFromNode=NOOP,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else{if(!/none/i.test(this.nodeLocationTracking))throw Error('Invalid config option: "'+e.nodeLocationTracking+'"');this.setNodeLocationFromToken=NOOP,this.setNodeLocationFromNode=NOOP,this.cstPostRule=NOOP,this.setInitialNodeLocation=NOOP}else this.cstInvocationStateUpdate=NOOP,this.cstFinallyStateUpdate=NOOP,this.cstPostTerminal=NOOP,this.cstPostNonTerminal=NOOP,this.cstPostRule=NOOP,this.getLastExplicitRuleShortName=this.getLastExplicitRuleShortNameNoCst,this.getPreviousExplicitRuleShortName=this.getPreviousExplicitRuleShortNameNoCst,this.getLastExplicitRuleOccurrenceIndex=this.getLastExplicitRuleOccurrenceIndexNoCst,this.manyInternal=this.manyInternalNoCst,this.orInternal=this.orInternalNoCst,this.optionInternal=this.optionInternalNoCst,this.atLeastOneInternal=this.atLeastOneInternalNoCst,this.manySepFirstInternal=this.manySepFirstInternalNoCst,this.atLeastOneSepFirstInternal=this.atLeastOneSepFirstInternalNoCst},e.prototype.setInitialNodeLocationOnlyOffsetRecovery=function(e){e.location={startOffset:NaN,endOffset:NaN}},e.prototype.setInitialNodeLocationOnlyOffsetRegular=function(e){e.location={startOffset:this.LA(1).startOffset,endOffset:NaN}},e.prototype.setInitialNodeLocationFullRecovery=function(e){e.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}},e.prototype.setInitialNodeLocationFullRegular=function(e){var t=this.LA(1);e.location={startOffset:t.startOffset,startLine:t.startLine,startColumn:t.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}},e.prototype.cstNestedInvocationStateUpdate=function(e,t){var n={name:e,fullName:this.shortRuleNameToFull[this.getLastExplicitRuleShortName()]+e,children:{}};this.setInitialNodeLocation(n),this.CST_STACK.push(n)},e.prototype.cstInvocationStateUpdate=function(e,t){this.LAST_EXPLICIT_RULE_STACK.push(this.RULE_STACK.length-1);var n={name:e,children:{}};this.setInitialNodeLocation(n),this.CST_STACK.push(n)},e.prototype.cstFinallyStateUpdate=function(){this.LAST_EXPLICIT_RULE_STACK.pop(),this.CST_STACK.pop()},e.prototype.cstNestedFinallyStateUpdate=function(){var e=this.CST_STACK.pop();this.cstPostRule(e)},e.prototype.cstPostRuleFull=function(e){var t=this.LA(0),n=e.location;n.startOffset<=t.startOffset==!0?(n.endOffset=t.endOffset,n.endLine=t.endLine,n.endColumn=t.endColumn):(n.startOffset=NaN,n.startLine=NaN,n.startColumn=NaN)},e.prototype.cstPostRuleOnlyOffset=function(e){var t=this.LA(0),n=e.location;n.startOffset<=t.startOffset==!0?n.endOffset=t.endOffset:n.startOffset=NaN},e.prototype.cstPostTerminal=function(e,t){var n=this.CST_STACK[this.CST_STACK.length-1];addTerminalToCst(n,t,e),this.setNodeLocationFromToken(n.location,t)},e.prototype.cstPostNonTerminal=function(e,t){if(!0!==this.isBackTracking()){var n=this.CST_STACK[this.CST_STACK.length-1];addNoneTerminalToCst(n,t,e),this.setNodeLocationFromNode(n.location,e.location)}},e.prototype.getBaseCstVisitorConstructor=function(){if(isUndefined$1(this.baseCstVisitorConstructor)){var e=createBaseSemanticVisitorConstructor(this.className,this.allRuleNames);return this.baseCstVisitorConstructor=e,e}return this.baseCstVisitorConstructor},e.prototype.getBaseCstVisitorConstructorWithDefaults=function(){if(isUndefined$1(this.baseCstVisitorWithDefaultsConstructor)){var e=createBaseVisitorConstructorWithDefaults(this.className,this.allRuleNames,this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=e,e}return this.baseCstVisitorWithDefaultsConstructor},e.prototype.nestedRuleBeforeClause=function(e,t){var n;return void 0!==e.NAME?(n=e.NAME,this.nestedRuleInvocationStateUpdate(n,t),n):void 0},e.prototype.nestedAltBeforeClause=function(e,t,n,r){var a,i=getKeyForAltIndex(this.getLastExplicitRuleShortName(),n,t,r);return void 0!==e.NAME?(a=e.NAME,this.nestedRuleInvocationStateUpdate(a,i),{shortName:i,nestedName:a}):void 0},e.prototype.nestedRuleFinallyClause=function(e,t){var n=this.CST_STACK,r=n[n.length-1];this.nestedRuleFinallyStateUpdate();var a=n[n.length-1];addNoneTerminalToCst(a,t,r),this.setNodeLocationFromNode(a.location,r.location)},e.prototype.getLastExplicitRuleShortName=function(){var e=this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length-1];return this.RULE_STACK[e]},e.prototype.getLastExplicitRuleShortNameNoCst=function(){var e=this.RULE_STACK;return e[e.length-1]},e.prototype.getPreviousExplicitRuleShortName=function(){var e=this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length-2];return this.RULE_STACK[e]},e.prototype.getPreviousExplicitRuleShortNameNoCst=function(){var e=this.RULE_STACK;return e[e.length-2]},e.prototype.getLastExplicitRuleOccurrenceIndex=function(){var e=this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length-1];return this.RULE_OCCURRENCE_STACK[e]},e.prototype.getLastExplicitRuleOccurrenceIndexNoCst=function(){var e=this.RULE_OCCURRENCE_STACK;return e[e.length-1]},e.prototype.nestedRuleInvocationStateUpdate=function(e,t){this.RULE_OCCURRENCE_STACK.push(1),this.RULE_STACK.push(t),this.cstNestedInvocationStateUpdate(e,t)},e.prototype.nestedRuleFinallyStateUpdate=function(){this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstNestedFinallyStateUpdate()},e}(),LexerAdapter=function(){function e(){}return e.prototype.initLexerAdapter=function(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1},Object.defineProperty(e.prototype,"input",{get:function(){return this.tokVector},set:function(e){if(!0!==this.selfAnalysisDone)throw Error("Missing invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=e,this.tokVectorLength=e.length},enumerable:!0,configurable:!0}),e.prototype.SKIP_TOKEN=function(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):END_OF_FILE},e.prototype.LA=function(e){var t=this.currIdx+e;return t<0||this.tokVectorLength<=t?END_OF_FILE:this.tokVector[t]},e.prototype.consumeToken=function(){this.currIdx++},e.prototype.exportLexerState=function(){return this.currIdx},e.prototype.importLexerState=function(e){this.currIdx=e},e.prototype.resetLexerState=function(){this.currIdx=-1},e.prototype.moveToTerminatedState=function(){this.currIdx=this.tokVector.length-1},e.prototype.getLexerPosition=function(){return this.exportLexerState()},e}(),RecognizerApi=function(){function e(){}return e.prototype.ACTION=function(e){return e.call(this)},e.prototype.consume=function(e,t,n){return this.consumeInternal(t,e,n)},e.prototype.subrule=function(e,t,n){return this.subruleInternal(t,e,n)},e.prototype.option=function(e,t){return this.optionInternal(t,e)},e.prototype.or=function(e,t){return this.orInternal(t,e)},e.prototype.many=function(e,t){return this.manyInternal(e,t)},e.prototype.atLeastOne=function(e,t){return this.atLeastOneInternal(e,t)},e.prototype.CONSUME=function(e,t){return this.consumeInternal(e,0,t)},e.prototype.CONSUME1=function(e,t){return this.consumeInternal(e,1,t)},e.prototype.CONSUME2=function(e,t){return this.consumeInternal(e,2,t)},e.prototype.CONSUME3=function(e,t){return this.consumeInternal(e,3,t)},e.prototype.CONSUME4=function(e,t){return this.consumeInternal(e,4,t)},e.prototype.CONSUME5=function(e,t){return this.consumeInternal(e,5,t)},e.prototype.CONSUME6=function(e,t){return this.consumeInternal(e,6,t)},e.prototype.CONSUME7=function(e,t){return this.consumeInternal(e,7,t)},e.prototype.CONSUME8=function(e,t){return this.consumeInternal(e,8,t)},e.prototype.CONSUME9=function(e,t){return this.consumeInternal(e,9,t)},e.prototype.SUBRULE=function(e,t){return this.subruleInternal(e,0,t)},e.prototype.SUBRULE1=function(e,t){return this.subruleInternal(e,1,t)},e.prototype.SUBRULE2=function(e,t){return this.subruleInternal(e,2,t)},e.prototype.SUBRULE3=function(e,t){return this.subruleInternal(e,3,t)},e.prototype.SUBRULE4=function(e,t){return this.subruleInternal(e,4,t)},e.prototype.SUBRULE5=function(e,t){return this.subruleInternal(e,5,t)},e.prototype.SUBRULE6=function(e,t){return this.subruleInternal(e,6,t)},e.prototype.SUBRULE7=function(e,t){return this.subruleInternal(e,7,t)},e.prototype.SUBRULE8=function(e,t){return this.subruleInternal(e,8,t)},e.prototype.SUBRULE9=function(e,t){return this.subruleInternal(e,9,t)},e.prototype.OPTION=function(e){return this.optionInternal(e,0)},e.prototype.OPTION1=function(e){return this.optionInternal(e,1)},e.prototype.OPTION2=function(e){return this.optionInternal(e,2)},e.prototype.OPTION3=function(e){return this.optionInternal(e,3)},e.prototype.OPTION4=function(e){return this.optionInternal(e,4)},e.prototype.OPTION5=function(e){return this.optionInternal(e,5)},e.prototype.OPTION6=function(e){return this.optionInternal(e,6)},e.prototype.OPTION7=function(e){return this.optionInternal(e,7)},e.prototype.OPTION8=function(e){return this.optionInternal(e,8)},e.prototype.OPTION9=function(e){return this.optionInternal(e,9)},e.prototype.OR=function(e){return this.orInternal(e,0)},e.prototype.OR1=function(e){return this.orInternal(e,1)},e.prototype.OR2=function(e){return this.orInternal(e,2)},e.prototype.OR3=function(e){return this.orInternal(e,3)},e.prototype.OR4=function(e){return this.orInternal(e,4)},e.prototype.OR5=function(e){return this.orInternal(e,5)},e.prototype.OR6=function(e){return this.orInternal(e,6)},e.prototype.OR7=function(e){return this.orInternal(e,7)},e.prototype.OR8=function(e){return this.orInternal(e,8)},e.prototype.OR9=function(e){return this.orInternal(e,9)},e.prototype.MANY=function(e){this.manyInternal(0,e)},e.prototype.MANY1=function(e){this.manyInternal(1,e)},e.prototype.MANY2=function(e){this.manyInternal(2,e)},e.prototype.MANY3=function(e){this.manyInternal(3,e)},e.prototype.MANY4=function(e){this.manyInternal(4,e)},e.prototype.MANY5=function(e){this.manyInternal(5,e)},e.prototype.MANY6=function(e){this.manyInternal(6,e)},e.prototype.MANY7=function(e){this.manyInternal(7,e)},e.prototype.MANY8=function(e){this.manyInternal(8,e)},e.prototype.MANY9=function(e){this.manyInternal(9,e)},e.prototype.MANY_SEP=function(e){this.manySepFirstInternal(0,e)},e.prototype.MANY_SEP1=function(e){this.manySepFirstInternal(1,e)},e.prototype.MANY_SEP2=function(e){this.manySepFirstInternal(2,e)},e.prototype.MANY_SEP3=function(e){this.manySepFirstInternal(3,e)},e.prototype.MANY_SEP4=function(e){this.manySepFirstInternal(4,e)},e.prototype.MANY_SEP5=function(e){this.manySepFirstInternal(5,e)},e.prototype.MANY_SEP6=function(e){this.manySepFirstInternal(6,e)},e.prototype.MANY_SEP7=function(e){this.manySepFirstInternal(7,e)},e.prototype.MANY_SEP8=function(e){this.manySepFirstInternal(8,e)},e.prototype.MANY_SEP9=function(e){this.manySepFirstInternal(9,e)},e.prototype.AT_LEAST_ONE=function(e){this.atLeastOneInternal(0,e)},e.prototype.AT_LEAST_ONE1=function(e){return this.atLeastOneInternal(1,e)},e.prototype.AT_LEAST_ONE2=function(e){this.atLeastOneInternal(2,e)},e.prototype.AT_LEAST_ONE3=function(e){this.atLeastOneInternal(3,e)},e.prototype.AT_LEAST_ONE4=function(e){this.atLeastOneInternal(4,e)},e.prototype.AT_LEAST_ONE5=function(e){this.atLeastOneInternal(5,e)},e.prototype.AT_LEAST_ONE6=function(e){this.atLeastOneInternal(6,e)},e.prototype.AT_LEAST_ONE7=function(e){this.atLeastOneInternal(7,e)},e.prototype.AT_LEAST_ONE8=function(e){this.atLeastOneInternal(8,e)},e.prototype.AT_LEAST_ONE9=function(e){this.atLeastOneInternal(9,e)},e.prototype.AT_LEAST_ONE_SEP=function(e){this.atLeastOneSepFirstInternal(0,e)},e.prototype.AT_LEAST_ONE_SEP1=function(e){this.atLeastOneSepFirstInternal(1,e)},e.prototype.AT_LEAST_ONE_SEP2=function(e){this.atLeastOneSepFirstInternal(2,e)},e.prototype.AT_LEAST_ONE_SEP3=function(e){this.atLeastOneSepFirstInternal(3,e)},e.prototype.AT_LEAST_ONE_SEP4=function(e){this.atLeastOneSepFirstInternal(4,e)},e.prototype.AT_LEAST_ONE_SEP5=function(e){this.atLeastOneSepFirstInternal(5,e)},e.prototype.AT_LEAST_ONE_SEP6=function(e){this.atLeastOneSepFirstInternal(6,e)},e.prototype.AT_LEAST_ONE_SEP7=function(e){this.atLeastOneSepFirstInternal(7,e)},e.prototype.AT_LEAST_ONE_SEP8=function(e){this.atLeastOneSepFirstInternal(8,e)},e.prototype.AT_LEAST_ONE_SEP9=function(e){this.atLeastOneSepFirstInternal(9,e)},e.prototype.RULE=function(e,t,n){if(void 0===n&&(n=DEFAULT_RULE_CONFIG),contains(this.definedRulesNames,e)){var r={message:defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({topLevelRule:e,grammarName:this.className}),type:ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:e};this.definitionErrors.push(r)}this.definedRulesNames.push(e);var a=this.defineRule(e,t,n);return this[e]=a,a},e.prototype.OVERRIDE_RULE=function(e,t,n){void 0===n&&(n=DEFAULT_RULE_CONFIG);var r=[];r=r.concat(validateRuleIsOverridden(e,this.definedRulesNames,this.className)),this.definitionErrors.push.apply(this.definitionErrors,r);var a=this.defineRule(e,t,n);return this[e]=a,a},e.prototype.BACKTRACK=function(e,t){return function(){this.isBackTrackingStack.push(1);var n=this.saveRecogState();try{return e.apply(this,t),!0}catch(e){if(isRecognitionException(e))return!1;throw e}finally{this.reloadRecogState(n),this.isBackTrackingStack.pop()}}},e.prototype.getGAstProductions=function(){return this.gastProductionsCache},e.prototype.getSerializedGastProductions=function(){return serializeGrammar(values(this.gastProductionsCache))},e}(),RecognizerEngine=function(){function e(){}return e.prototype.initRecognizerEngine=function(e,t){if(this.className=classNameFromInstance(this),this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=tokenStructuredMatcherNoCategories,this.definedRulesNames=[],this.tokensMap={},this.allRuleNames=[],this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},has(t,"serializedGrammar"))throw Error("The Parser's configuration can no longer contain a property.\n\tSee: https://sap.github.io/chevrotain/docs/changes/BREAKING_CHANGES.html#_6-0-0\n\tFor Further details.");if(isArray$2(e)){if(isEmpty(e))throw Error("A Token Vocabulary cannot be empty.\n\tNote that the first argument for the parser constructor\n\tis no longer a Token vector (since v4.0).");if("number"==typeof e[0].startOffset)throw Error("The Parser constructor no longer accepts a token vector as the first argument.\n\tSee: https://sap.github.io/chevrotain/docs/changes/BREAKING_CHANGES.html#_4-0-0\n\tFor Further details.")}if(isArray$2(e))this.tokensMap=reduce(e,(function(e,t){return e[t.name]=t,e}),{});else if(has(e,"modes")&&every(flatten(values(e.modes)),isTokenType)){var n=uniq(flatten(values(e.modes)));this.tokensMap=reduce(n,(function(e,t){return e[t.name]=t,e}),{})}else{if(!isObject$1(e))throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap=cloneObj(e)}this.tokensMap.EOF=EOF;var r=every(values(e),(function(e){return isEmpty(e.categoryMatches)}));this.tokenMatcher=r?tokenStructuredMatcherNoCategories:tokenStructuredMatcher,augmentTokenTypes(values(this.tokensMap))},e.prototype.defineRule=function(e,t,n){if(this.selfAnalysisDone)throw Error("Grammar rule <"+e+"> may not be defined after the 'performSelfAnalysis' method has been called'\nMake sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.");var r,a=has(n,"resyncEnabled")?n.resyncEnabled:DEFAULT_RULE_CONFIG.resyncEnabled,i=has(n,"recoveryValueFunc")?n.recoveryValueFunc:DEFAULT_RULE_CONFIG.recoveryValueFunc,s=this.ruleShortNameIdx<t},e.prototype.orInternalNoCst=function(e,t){var n=isArray$2(e)?e:e.DEF,r=this.getKeyForAutomaticLookahead(OR_IDX,t),a=this.getLaFuncFromCache(r).call(this,n);if(void 0!==a)return n[a].ALT.call(this);this.raiseNoAltException(t,e.ERR_MSG)},e.prototype.orInternal=function(e,t){var n=this.getKeyForAutomaticLookahead(OR_IDX,t),r=this.nestedRuleBeforeClause(e,n);try{var a=isArray$2(e)?e:e.DEF,i=this.getLaFuncFromCache(n).call(this,a);if(void 0!==i){var s=a[i],o=this.nestedAltBeforeClause(s,t,OR_IDX,i);try{return s.ALT.call(this)}finally{void 0!==o&&this.nestedRuleFinallyClause(o.shortName,o.nestedName)}}this.raiseNoAltException(t,e.ERR_MSG)}finally{void 0!==r&&this.nestedRuleFinallyClause(n,r)}},e.prototype.ruleFinallyStateUpdate=function(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),0===this.RULE_STACK.length&&!1===this.isAtEndOfInput()){var e=this.LA(1),t=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:e,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new NotAllInputParsedException(t,e))}},e.prototype.subruleInternal=function(e,t,n){var r;try{var a=void 0!==n?n.ARGS:void 0;return r=e.call(this,t,a),this.cstPostNonTerminal(r,void 0!==n&&void 0!==n.LABEL?n.LABEL:e.ruleName),r}catch(t){this.subruleInternalError(t,n,e.ruleName)}},e.prototype.subruleInternalError=function(e,t,n){throw isRecognitionException(e)&&void 0!==e.partialCstResult&&(this.cstPostNonTerminal(e.partialCstResult,void 0!==t&&void 0!==t.LABEL?t.LABEL:n),delete e.partialCstResult),e},e.prototype.consumeInternal=function(e,t,n){var r;try{var a=this.LA(1);!0===this.tokenMatcher(a,e)?(this.consumeToken(),r=a):this.consumeInternalError(e,a,n)}catch(n){r=this.consumeInternalRecovery(e,t,n)}return this.cstPostTerminal(void 0!==n&&void 0!==n.LABEL?n.LABEL:e.name,r),r},e.prototype.consumeInternalError=function(e,t,n){var r,a=this.LA(0);throw r=void 0!==n&&n.ERR_MSG?n.ERR_MSG:this.errorMessageProvider.buildMismatchTokenMessage({expected:e,actual:t,previous:a,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new MismatchedTokenException(r,t,a))},e.prototype.consumeInternalRecovery=function(e,t,n){if(!this.recoveryEnabled||"MismatchedTokenException"!==n.name||this.isBackTracking())throw n;var r=this.getFollowsForInRuleRecovery(e,t);try{return this.tryInRuleRecovery(e,r)}catch(e){throw e.name===IN_RULE_RECOVERY_EXCEPTION?n:e}},e.prototype.saveRecogState=function(){var e=this.errors,t=cloneArr(this.RULE_STACK);return{errors:e,lexerState:this.exportLexerState(),RULE_STACK:t,CST_STACK:this.CST_STACK,LAST_EXPLICIT_RULE_STACK:this.LAST_EXPLICIT_RULE_STACK}},e.prototype.reloadRecogState=function(e){this.errors=e.errors,this.importLexerState(e.lexerState),this.RULE_STACK=e.RULE_STACK},e.prototype.ruleInvocationStateUpdate=function(e,t,n){this.RULE_OCCURRENCE_STACK.push(n),this.RULE_STACK.push(e),this.cstInvocationStateUpdate(t,e)},e.prototype.isBackTracking=function(){return 0!==this.isBackTrackingStack.length},e.prototype.getCurrRuleFullName=function(){var e=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[e]},e.prototype.shortRuleNameToFullName=function(e){return this.shortRuleNameToFull[e]},e.prototype.isAtEndOfInput=function(){return this.tokenMatcher(this.LA(1),EOF)},e.prototype.reset=function(){this.resetLexerState(),this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.LAST_EXPLICIT_RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]},e}(),ErrorHandler=function(){function e(){}return e.prototype.initErrorHandler=function(e){this._errors=[],this.errorMessageProvider=defaults$4(e.errorMessageProvider,DEFAULT_PARSER_CONFIG.errorMessageProvider)},e.prototype.SAVE_ERROR=function(e){if(isRecognitionException(e))return e.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:cloneArr(this.RULE_OCCURRENCE_STACK)},this._errors.push(e),e;throw Error("Trying to save an Error which is not a RecognitionException")},Object.defineProperty(e.prototype,"errors",{get:function(){return cloneArr(this._errors)},set:function(e){this._errors=e},enumerable:!0,configurable:!0}),e.prototype.raiseEarlyExitException=function(e,t,n){for(var r=this.getCurrRuleFullName(),a=getLookaheadPathsForOptionalProd(e,this.getGAstProductions()[r],t,this.maxLookahead)[0],i=[],s=1;s<=this.maxLookahead;s++)i.push(this.LA(s));var o=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:a,actual:i,previous:this.LA(0),customUserDescription:n,ruleName:r});throw this.SAVE_ERROR(new EarlyExitException(o,this.LA(1),this.LA(0)))},e.prototype.raiseNoAltException=function(e,t){for(var n=this.getCurrRuleFullName(),r=getLookaheadPathsForOr(e,this.getGAstProductions()[n],this.maxLookahead),a=[],i=1;i<=this.maxLookahead;i++)a.push(this.LA(i));var s=this.LA(0),o=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:r,actual:a,previous:s,customUserDescription:t,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new NoViableAltException(o,this.LA(1),s))},e}(),ContentAssist=function(){function e(){}return e.prototype.initContentAssist=function(){},e.prototype.computeContentAssist=function(e,t){var n=this.gastProductionsCache[e];if(isUndefined$1(n))throw Error("Rule ->"+e+"<- does not exist in this grammar.");return nextPossibleTokensAfter([n],t,this.tokenMatcher,this.maxLookahead)},e.prototype.getNextPossibleTokenTypes=function(e){var t=first$1(e.ruleStack),n=this.getGAstProductions()[t];return new NextAfterTokenWalker(n,e).startWalking()},e}(),RECORDING_NULL_OBJECT={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(RECORDING_NULL_OBJECT);var HANDLE_SEPARATOR=!0,MAX_METHOD_IDX=Math.pow(2,BITS_FOR_OCCURRENCE_IDX)-1,RFT=createToken({name:"RECORDING_PHASE_TOKEN",pattern:Lexer.NA});augmentTokenTypes([RFT]);var RECORDING_PHASE_TOKEN=createTokenInstance(RFT,"This IToken indicates the Parser is in Recording Phase\n\tSee: https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording for details",-1,-1,-1,-1,-1,-1);Object.freeze(RECORDING_PHASE_TOKEN);var RECORDING_PHASE_CSTNODE={name:"This CSTNode indicates the Parser is in Recording Phase\n\tSee: https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording for details",children:{}},GastRecorder=function(){function e(){}return e.prototype.initGastRecorder=function(e){this.recordingProdStack=[],this.RECORDING_PHASE=!1},e.prototype.enableRecording=function(){var e=this;this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",(function(){for(var t=function(t){var n=t>0?t:"";e["CONSUME"+n]=function(e,n){return this.consumeInternalRecord(e,t,n)},e["SUBRULE"+n]=function(e,n){return this.subruleInternalRecord(e,t,n)},e["OPTION"+n]=function(e){return this.optionInternalRecord(e,t)},e["OR"+n]=function(e){return this.orInternalRecord(e,t)},e["MANY"+n]=function(e){this.manyInternalRecord(t,e)},e["MANY_SEP"+n]=function(e){this.manySepFirstInternalRecord(t,e)},e["AT_LEAST_ONE"+n]=function(e){this.atLeastOneInternalRecord(t,e)},e["AT_LEAST_ONE_SEP"+n]=function(e){this.atLeastOneSepFirstInternalRecord(t,e)}},n=0;n<10;n++)t(n);e.consume=function(e,t,n){return this.consumeInternalRecord(t,e,n)},e.subrule=function(e,t,n){return this.subruleInternalRecord(t,e,n)},e.option=function(e,t){return this.optionInternalRecord(t,e)},e.or=function(e,t){return this.orInternalRecord(t,e)},e.many=function(e,t){this.manyInternalRecord(e,t)},e.atLeastOne=function(e,t){this.atLeastOneInternalRecord(e,t)},e.ACTION=e.ACTION_RECORD,e.BACKTRACK=e.BACKTRACK_RECORD,e.LA=e.LA_RECORD}))},e.prototype.disableRecording=function(){var e=this;this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",(function(){for(var t=0;t<10;t++){var n=t>0?t:"";delete e["CONSUME"+n],delete e["SUBRULE"+n],delete e["OPTION"+n],delete e["OR"+n],delete e["MANY"+n],delete e["MANY_SEP"+n],delete e["AT_LEAST_ONE"+n],delete e["AT_LEAST_ONE_SEP"+n]}delete e.consume,delete e.subrule,delete e.option,delete e.or,delete e.many,delete e.atLeastOne,delete e.ACTION,delete e.BACKTRACK,delete e.LA}))},e.prototype.ACTION_RECORD=function(e){},e.prototype.BACKTRACK_RECORD=function(e,t){return function(){return!0}},e.prototype.LA_RECORD=function(e){return END_OF_FILE},e.prototype.topLevelRuleRecord=function(e,t){try{var n=new Rule({definition:[],name:e});return n.name=e,this.recordingProdStack.push(n),t.call(this),this.recordingProdStack.pop(),n}catch(e){if(!0!==e.KNOWN_RECORDER_ERROR)try{e.message=e.message+'\n\t This error was thrown during the "grammar recording phase" For more info see:\n\thttps://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording'}catch(t){throw e}throw e}},e.prototype.optionInternalRecord=function(e,t){return recordProd.call(this,Option,e,t)},e.prototype.atLeastOneInternalRecord=function(e,t){recordProd.call(this,RepetitionMandatory,t,e)},e.prototype.atLeastOneSepFirstInternalRecord=function(e,t){recordProd.call(this,RepetitionMandatoryWithSeparator,t,e,HANDLE_SEPARATOR)},e.prototype.manyInternalRecord=function(e,t){recordProd.call(this,Repetition,t,e)},e.prototype.manySepFirstInternalRecord=function(e,t){recordProd.call(this,RepetitionWithSeparator,t,e,HANDLE_SEPARATOR)},e.prototype.orInternalRecord=function(e,t){return recordOrProd.call(this,e,t)},e.prototype.subruleInternalRecord=function(e,t,n){if(assertMethodIdxIsValid(t),!e||!1===has(e,"ruleName")){var r=new Error(" argument is invalid expecting a Parser method reference but got: <"+JSON.stringify(e)+">\n inside top level rule: <"+this.recordingProdStack[0].name+">");throw r.KNOWN_RECORDER_ERROR=!0,r}var a=peek(this.recordingProdStack),i=e.ruleName,s=new NonTerminal({idx:t,nonTerminalName:i,referencedRule:void 0});return a.definition.push(s),this.outputCst?RECORDING_PHASE_CSTNODE:RECORDING_NULL_OBJECT},e.prototype.consumeInternalRecord=function(e,t,n){if(assertMethodIdxIsValid(t),!hasShortKeyProperty(e)){var r=new Error(" argument is invalid expecting a TokenType reference but got: <"+JSON.stringify(e)+">\n inside top level rule: <"+this.recordingProdStack[0].name+">");throw r.KNOWN_RECORDER_ERROR=!0,r}var a=peek(this.recordingProdStack),i=new Terminal({idx:t,terminalType:e});return a.definition.push(i),RECORDING_PHASE_TOKEN},e}();function recordProd(e,t,n,r){void 0===r&&(r=!1),assertMethodIdxIsValid(n);var a=peek(this.recordingProdStack),i=isFunction$1(t)?t:t.DEF,s=new e({definition:[],idx:n});return has(t,"NAME")&&(s.name=t.NAME),r&&(s.separator=t.SEP),has(t,"MAX_LOOKAHEAD")&&(s.maxLookahead=t.MAX_LOOKAHEAD),this.recordingProdStack.push(s),i.call(this),a.definition.push(s),this.recordingProdStack.pop(),RECORDING_NULL_OBJECT}function recordOrProd(e,t){var n=this;assertMethodIdxIsValid(t);var r=peek(this.recordingProdStack),a=!1===isArray$2(e),i=!1===a?e:e.DEF,s=new Alternation({definition:[],idx:t,ignoreAmbiguities:a&&!0===e.IGNORE_AMBIGUITIES});has(e,"NAME")&&(s.name=e.NAME),has(e,"MAX_LOOKAHEAD")&&(s.maxLookahead=e.MAX_LOOKAHEAD);var o=some(i,(function(e){return isFunction$1(e.GATE)}));return s.hasPredicates=o,r.definition.push(s),forEach$1(i,(function(e){var t=new Flat({definition:[]});s.definition.push(t),has(e,"NAME")&&(t.name=e.NAME),has(e,"IGNORE_AMBIGUITIES")?t.ignoreAmbiguities=e.IGNORE_AMBIGUITIES:has(e,"GATE")&&(t.ignoreAmbiguities=!0),n.recordingProdStack.push(t),e.ALT.call(n),n.recordingProdStack.pop()})),RECORDING_NULL_OBJECT}function getIdxSuffix(e){return 0===e?"":""+e}function assertMethodIdxIsValid(e){if(e<0||e>MAX_METHOD_IDX){var t=new Error("Invalid DSL Method idx value: <"+e+">\n\tIdx value must be a none negative value smaller than "+(MAX_METHOD_IDX+1));throw t.KNOWN_RECORDER_ERROR=!0,t}}var PerformanceTracer=function(){function e(){}return e.prototype.initPerformanceTracer=function(e){if(has(e,"traceInitPerf")){var t=e.traceInitPerf,n="number"==typeof t;this.traceInitMaxIdent=n?t:1/0,this.traceInitPerf=n?t>0:t}else this.traceInitMaxIdent=0,this.traceInitPerf=DEFAULT_PARSER_CONFIG.traceInitPerf;this.traceInitIndent=-1},e.prototype.TRACE_INIT=function(e,t){if(!0===this.traceInitPerf){this.traceInitIndent++;var n=new Array(this.traceInitIndent+1).join("\t");this.traceInitIndent");var r=timer(t),a=r.time,i=r.value,s=a>10?console.warn:console.log;return this.traceInitIndent time: "+a+"ms"),this.traceInitIndent--,i}return t()},e}(),__extends=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),END_OF_FILE=createTokenInstance(EOF,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(END_OF_FILE);var DEFAULT_PARSER_CONFIG=Object.freeze({recoveryEnabled:!1,maxLookahead:4,ignoredIssues:{},dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:defaultParserErrorProvider,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),DEFAULT_RULE_CONFIG=Object.freeze({recoveryValueFunc:function(){},resyncEnabled:!0}),ParserDefinitionErrorType;function EMPTY_ALT(e){return void 0===e&&(e=void 0),function(){return e}}!function(e){e[e.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",e[e.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",e[e.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",e[e.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",e[e.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",e[e.LEFT_RECURSION=5]="LEFT_RECURSION",e[e.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",e[e.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",e[e.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",e[e.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",e[e.INVALID_NESTED_RULE_NAME=10]="INVALID_NESTED_RULE_NAME",e[e.DUPLICATE_NESTED_NAME=11]="DUPLICATE_NESTED_NAME",e[e.NO_NON_EMPTY_LOOKAHEAD=12]="NO_NON_EMPTY_LOOKAHEAD",e[e.AMBIGUOUS_PREFIX_ALTS=13]="AMBIGUOUS_PREFIX_ALTS",e[e.TOO_MANY_ALTS=14]="TOO_MANY_ALTS"}(ParserDefinitionErrorType||(ParserDefinitionErrorType={}));var Parser=function(){function e(e,t){void 0===t&&(t=DEFAULT_PARSER_CONFIG),this.ignoredIssues=DEFAULT_PARSER_CONFIG.ignoredIssues,this.definitionErrors=[],this.selfAnalysisDone=!1;var n=this;n.initErrorHandler(t),n.initLexerAdapter(),n.initLooksAhead(t),n.initRecognizerEngine(e,t),n.initRecoverable(t),n.initTreeBuilder(t),n.initContentAssist(),n.initGastRecorder(t),n.initPerformanceTracer(t),has(t,"ignoredIssues")&&t.ignoredIssues!==DEFAULT_PARSER_CONFIG.ignoredIssues&&PRINT_WARNING("The IParserConfig property is soft-deprecated and will be removed in future versions.\n\tPlease use the flag on the relevant DSL method instead."),this.ignoredIssues=has(t,"ignoredIssues")?t.ignoredIssues:DEFAULT_PARSER_CONFIG.ignoredIssues,this.skipValidations=has(t,"skipValidations")?t.skipValidations:DEFAULT_PARSER_CONFIG.skipValidations}return e.performSelfAnalysis=function(e){e.performSelfAnalysis()},e.prototype.performSelfAnalysis=function(){var t=this;this.TRACE_INIT("performSelfAnalysis",(function(){var n;t.selfAnalysisDone=!0;var r=t.className;t.TRACE_INIT("toFastProps",(function(){toFastProperties(t)})),t.TRACE_INIT("Grammar Recording",(function(){try{t.enableRecording(),forEach$1(t.definedRulesNames,(function(e){var n=t[e].originalGrammarAction,r=void 0;t.TRACE_INIT(e+" Rule",(function(){r=t.topLevelRuleRecord(e,n)})),t.gastProductionsCache[e]=r}))}finally{t.disableRecording()}}));var a=[];if(t.TRACE_INIT("Grammar Resolving",(function(){a=resolveGrammar({rules:values(t.gastProductionsCache)}),t.definitionErrors.push.apply(t.definitionErrors,a)})),t.TRACE_INIT("Grammar Validations",(function(){if(isEmpty(a)&&!1===t.skipValidations){var e=validateGrammar({rules:values(t.gastProductionsCache),maxLookahead:t.maxLookahead,tokenTypes:values(t.tokensMap),ignoredIssues:t.ignoredIssues,errMsgProvider:defaultGrammarValidatorErrorProvider,grammarName:r});t.definitionErrors.push.apply(t.definitionErrors,e)}})),isEmpty(t.definitionErrors)&&(t.recoveryEnabled&&t.TRACE_INIT("computeAllProdsFollows",(function(){var e=computeAllProdsFollows(values(t.gastProductionsCache));t.resyncFollows=e})),t.TRACE_INIT("ComputeLookaheadFunctions",(function(){t.preComputeLookaheadFunctions(values(t.gastProductionsCache))}))),t.TRACE_INIT("expandAllNestedRuleNames",(function(){var e=expandAllNestedRuleNames(values(t.gastProductionsCache),t.fullRuleNameToShort);t.allRuleNames=e.allRuleNames})),!e.DEFER_DEFINITION_ERRORS_HANDLING&&!isEmpty(t.definitionErrors))throw n=map(t.definitionErrors,(function(e){return e.message})),new Error("Parser Definition Errors detected:\n "+n.join("\n-------------------------------\n"))}))},e.DEFER_DEFINITION_ERRORS_HANDLING=!1,e}();applyMixins(Parser,[Recoverable,LooksAhead,TreeBuilder,LexerAdapter,RecognizerEngine,RecognizerApi,ErrorHandler,ContentAssist,GastRecorder,PerformanceTracer]),function(e){function t(t,n){void 0===n&&(n=DEFAULT_PARSER_CONFIG);var r=cloneObj(n);return r.outputCst=!0,e.call(this,t,r)||this}__extends(t,e)}(Parser);var EmbeddedActionsParser=function(e){function t(t,n){void 0===n&&(n=DEFAULT_PARSER_CONFIG);var r=cloneObj(n);return r.outputCst=!1,e.call(this,t,r)||this}return __extends(t,e),t}(Parser); /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */function collatorFromConfig(e){var t=e.caseSensitive?e.accentSensitive?"variant":"case":e.accentSensitive?"accent":"base",n=e.caseFirst,r=e.ignorePunctuation;return new Intl.Collator(e.localeLang,{sensitivity:t,caseFirst:n,ignorePunctuation:r})}function _typeof$19(e){return _typeof$19="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$19(e)}function _inherits$U(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&_setPrototypeOf$V(e,t)}function _setPrototypeOf$V(e,t){return _setPrototypeOf$V=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},_setPrototypeOf$V(e,t)}function _createSuper$U(e){var t=_isNativeReflectConstruct$V();return function(){var n,r=_getPrototypeOf$U(e);if(t){var a=_getPrototypeOf$U(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return _possibleConstructorReturn$U(this,n)}}function _possibleConstructorReturn$U(e,t){if(t&&("object"===_typeof$19(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized$U(e)}function _assertThisInitialized$U(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _isNativeReflectConstruct$V(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function _getPrototypeOf$U(e){return _getPrototypeOf$U=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},_getPrototypeOf$U(e)}function _classCallCheck$1C(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1C(e,t){for(var n=0;n/,categories:BooleanOp}),GreaterThanOp=createToken({name:"GreaterThanOp",pattern:/>/,categories:BooleanOp}),LessThanOp=createToken({name:"LessThanOp",pattern:/=/,categories:BooleanOp}),LessThanOrEqualOp=createToken({name:"LessThanOrEqualOp",pattern:/<=/,categories:BooleanOp}),ConcatenateOp=createToken({name:"ConcatenateOp",pattern:/&/}),simpleSheetName="[A-Za-z0-9_À-ʯ]+",quotedSheetName="'(((?!').|'')*)'",sheetNameRegexp=`(${simpleSheetName}|${quotedSheetName})!`,CellReference=createToken({name:"CellReference",pattern:new RegExp(`(${sheetNameRegexp})?\\${ABSOLUTE_OPERATOR}?[A-Za-z]+\\${ABSOLUTE_OPERATOR}?[0-9]+`)}),ColumnRange=createToken({name:"ColumnRange",pattern:new RegExp(`(${sheetNameRegexp})?\\${ABSOLUTE_OPERATOR}?[A-Za-z]+${RANGE_OPERATOR}(${sheetNameRegexp})?\\${ABSOLUTE_OPERATOR}?[A-Za-z]+`)}),RowRange=createToken({name:"RowRange",pattern:new RegExp(`(${sheetNameRegexp})?\\${ABSOLUTE_OPERATOR}?[0-9]+${RANGE_OPERATOR}(${sheetNameRegexp})?\\${ABSOLUTE_OPERATOR}?[0-9]+`)}),RangeSeparator=createToken({name:"RangeSeparator",pattern:`${RANGE_OPERATOR}`}),LParen=createToken({name:"LParen",pattern:/\(/}),RParen=createToken({name:"RParen",pattern:/\)/}),ArrayLParen=createToken({name:"ArrayLParen",pattern:/{/}),ArrayRParen=createToken({name:"ArrayRParen",pattern:/}/}),ProcedureName=createToken({name:"ProcedureName",pattern:/([A-Za-z\u00C0-\u02AF][A-Za-z0-9\u00C0-\u02AF._]*)\(/}),NamedExpression=createToken({name:"NamedExpression",pattern:/[A-Za-z\u00C0-\u02AF_][A-Za-z0-9\u00C0-\u02AF._]*/}),StringLiteral=createToken({name:"StringLiteral",pattern:/"([^"\\]*(\\.[^"\\]*)*)"/}),ErrorLiteral=createToken({name:"ErrorLiteral",pattern:/#[A-Za-z0-9\/]+[?!]?/}),buildLexerConfig=e=>{const t=e.translationPackage.getFunctionTranslation("OFFSET"),n=e.errorMapping,r=e.translationPackage.buildFunctionMapping(),a=createToken({name:"WhiteSpace",pattern:"standard"===e.ignoreWhiteSpace?ODFF_WHITESPACE_REGEXP:ALL_WHITESPACE_REGEXP}),i=createToken({name:"ArrayRowSep",pattern:e.arrayRowSeparator}),s=createToken({name:"ArrayColSep",pattern:e.arrayColumnSeparator});let o,l;e.functionArgSeparator===e.arrayColumnSeparator?(o=s,l=[]):e.functionArgSeparator===e.arrayRowSeparator?(o=i,l=[]):(o=createToken({name:"ArgSeparator",pattern:e.functionArgSeparator}),l=[o]);const u=createToken({name:"NumberLiteral",pattern:new RegExp(`(([${e.decimalSeparator}]\\d+)|(\\d+([${e.decimalSeparator}]\\d*)?))(e[+-]?\\d+)?`)}),c=createToken({name:"OffsetProcedureName",pattern:new RegExp(t,"i")});return{ArgSeparator:o,NumberLiteral:u,OffsetProcedureName:c,ArrayRowSeparator:i,ArrayColSeparator:s,WhiteSpace:a,allTokens:[a,PlusOp,MinusOp,TimesOp,DivOp,PowerOp,EqualsOp,NotEqualOp,PercentOp,GreaterThanOrEqualOp,LessThanOrEqualOp,GreaterThanOp,LessThanOp,LParen,RParen,ArrayLParen,ArrayRParen,c,ProcedureName,RangeSeparator,...l,ColumnRange,RowRange,u,StringLiteral,ErrorLiteral,ConcatenateOp,BooleanOp,AdditionOp,MultiplicationOp,CellReference,NamedExpression,i,s],errorMapping:n,functionMapping:r,decimalSeparator:e.decimalSeparator,maxColumns:e.maxColumns,maxRows:e.maxRows}},addressRegex=new RegExp(`^(${sheetNameRegexp})?(\\${ABSOLUTE_OPERATOR}?)([A-Za-z]+)(\\${ABSOLUTE_OPERATOR}?)([0-9]+)$`),columnRegex=new RegExp(`^(${sheetNameRegexp})?(\\${ABSOLUTE_OPERATOR}?)([A-Za-z]+)$`),rowRegex=new RegExp(`^(${sheetNameRegexp})?(\\${ABSOLUTE_OPERATOR}?)([0-9]+)$`),simpleSheetNameRegex=new RegExp(`^${simpleSheetName}$`),cellAddressFromString=(e,t,n)=>{const r=addressRegex.exec(t),a=columnLabelToIndex(r[6]);let i=extractSheetNumber(r,e);if(void 0===i)return;null===i&&(i=void 0);const s=Number(r[8])-1;return r[5]===ABSOLUTE_OPERATOR&&r[7]===ABSOLUTE_OPERATOR?CellAddress.absolute(a,s,i):r[5]===ABSOLUTE_OPERATOR?CellAddress.absoluteCol(a,s-n.row,i):r[7]===ABSOLUTE_OPERATOR?CellAddress.absoluteRow(a-n.col,s,i):CellAddress.relative(s-n.row,a-n.col,i)},columnAddressFromString=(e,t,n)=>{const r=columnRegex.exec(t);let a=extractSheetNumber(r,e);if(void 0===a)return;null===a&&(a=void 0);const i=columnLabelToIndex(r[6]);return r[5]===ABSOLUTE_OPERATOR?ColumnAddress.absolute(i,a):ColumnAddress.relative(i-n.col,a)},rowAddressFromString=(e,t,n)=>{const r=rowRegex.exec(t);let a=extractSheetNumber(r,e);if(void 0===a)return;null===a&&(a=void 0);const i=Number(r[6])-1;return r[5]===ABSOLUTE_OPERATOR?RowAddress.absolute(i,a):RowAddress.relative(i-n.row,a)},simpleCellAddressFromString=(e,t,n)=>{const r=addressRegex.exec(t),a=columnLabelToIndex(r[6]);let i=extractSheetNumber(r,e);if(void 0===i)return;null===i&&(i=n);const s=Number(r[8])-1;return simpleCellAddress(i,a,s)},simpleCellRangeFromString=(e,t,n)=>{const r=t.split(RANGE_OPERATOR);if(2!==r.length)return;const[a,i]=r,s=simpleCellAddressFromString(e,a,n);if(void 0===s)return;const o=simpleCellAddressFromString(e,i,s.sheet);return void 0!==o&&s.sheet===o.sheet?simpleCellRange(s,o):void 0},simpleCellAddressToString=(e,t,n)=>{const r=columnIndexToLabel(t.col),a=sheetIndexToString(t.sheet,e);if(void 0!==a)return n!==t.sheet?`${a}!${r}${t.row+1}`:`${r}${t.row+1}`},simpleCellRangeToString=(e,t,n)=>{const r=simpleCellAddressToString(e,t.start,n),a=simpleCellAddressToString(e,t.end,t.start.sheet);return void 0===r||void 0===a?void 0:`${r}${RANGE_OPERATOR}${a}`};function columnLabelToIndex(e){return 1===e.length?e.toUpperCase().charCodeAt(0)-65:e.split("").reduce(((e,t)=>26*e+(t.toUpperCase().charCodeAt(0)-64)),0)-1}function columnIndexToLabel(e){let t="";for(;e>=0;)t=String.fromCharCode(e%26+97)+t,e=Math.floor(e/26)-1;return t.toUpperCase()}function sheetIndexToString(e,t){let n=t(e);if(void 0!==n)return simpleSheetNameRegex.test(n)?n:(n=n.replace(/'/g,"''"),`'${n}'`)}function extractSheetNumber(e,t){var n;let r=null!==(n=e[3])&&void 0!==n?n:e[2];return r?(r=r.replace(/''/g,"'"),t(r)):null} /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */var EmptyValue=Symbol("Empty value");function getRawValue(e){return e instanceof RichNumber?e.val:e}var RichNumber=function(){function e(t,n){_classCallCheck$1C(this,e),this.val=t,this.format=n}return _createClass$1C(e,[{key:"fromNumber",value:function(e){return new this.constructor(e)}}]),e}();function cloneNumber(e,t){if("number"==typeof e)return t;var n=e.fromNumber(t);return n.format=e.format,n}var DateNumber=function(e){_inherits$U(n,e);var t=_createSuper$U(n);function n(){return _classCallCheck$1C(this,n),t.apply(this,arguments)}return _createClass$1C(n,[{key:"getDetailedType",value:function(){return NumberType.NUMBER_DATE}}]),n}(RichNumber),CurrencyNumber=function(e){_inherits$U(n,e);var t=_createSuper$U(n);function n(){return _classCallCheck$1C(this,n),t.apply(this,arguments)}return _createClass$1C(n,[{key:"getDetailedType",value:function(){return NumberType.NUMBER_CURRENCY}}]),n}(RichNumber),TimeNumber=function(e){_inherits$U(n,e);var t=_createSuper$U(n);function n(){return _classCallCheck$1C(this,n),t.apply(this,arguments)}return _createClass$1C(n,[{key:"getDetailedType",value:function(){return NumberType.NUMBER_TIME}}]),n}(RichNumber),DateTimeNumber=function(e){_inherits$U(n,e);var t=_createSuper$U(n);function n(){return _classCallCheck$1C(this,n),t.apply(this,arguments)}return _createClass$1C(n,[{key:"getDetailedType",value:function(){return NumberType.NUMBER_DATETIME}}]),n}(RichNumber),PercentNumber=function(e){_inherits$U(n,e);var t=_createSuper$U(n);function n(){return _classCallCheck$1C(this,n),t.apply(this,arguments)}return _createClass$1C(n,[{key:"getDetailedType",value:function(){return NumberType.NUMBER_PERCENT}}]),n}(RichNumber),NumberType;function isExtendedNumber(e){return"number"==typeof e||e instanceof RichNumber}function getTypeOfExtendedNumber(e){return e instanceof RichNumber?e.getDetailedType():NumberType.NUMBER_RAW}function getFormatOfExtendedNumber(e){return e instanceof RichNumber?e.format:void 0}function getTypeFormatOfExtendedNumber(e){return e instanceof RichNumber?{type:e.getDetailedType(),format:e.format}:{type:NumberType.NUMBER_RAW}}function _slicedToArray$r(e,t){return _arrayWithHoles$r(e)||_iterableToArrayLimit$r(e,t)||_unsupportedIterableToArray$N(e,t)||_nonIterableRest$r()}function _nonIterableRest$r(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArrayLimit$r(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,a,i=[],o=!0,s=!1;try{for(n=n.call(e);!(o=(r=n.next()).done)&&(i.push(r.value),!t||i.length!==t);o=!0);}catch(e){s=!0,a=e}finally{try{o||null==n.return||n.return()}finally{if(s)throw a}}return i}}function _arrayWithHoles$r(e){if(Array.isArray(e))return e}function _toConsumableArray$e(e){return _arrayWithoutHoles$e(e)||_iterableToArray$e(e)||_unsupportedIterableToArray$N(e)||_nonIterableSpread$e()}function _nonIterableSpread$e(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray$e(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles$e(e){if(Array.isArray(e))return _arrayLikeToArray$N(e)}function _createForOfIteratorHelper$D(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$N(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$N(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$N(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$N(e,t):void 0}}function _arrayLikeToArray$N(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n0},this.geq=function(e,t){return a.compare(e,t)>=0},this.eq=function(e,t){return 0===a.compare(e,t)},this.neq=function(e,t){return 0!==a.compare(e,t)},this.pow=function(e,t){return Math.pow(getRawValue(e),getRawValue(t))},this.addWithEpsilonRaw=function(e,t){var n=e+t;return Math.abs(n)=0&&n*a>=r&&n<=r*a||r<=0&&n*a<=r&&n>=r*a?0:n>r?1:-1}},{key:"coerceScalarToNumberOrError",value:function(e){var t;return e instanceof CellError?e:null!==(t=this.coerceToMaybeNumber(e))&&void 0!==t?t:new CellError(ErrorType.VALUE,ErrorMessage.NumberCoercion)}},{key:"coerceToMaybeNumber",value:function(e){var t;return null!==(t=this.coerceNonDateScalarToMaybeNumber(e))&&void 0!==t?t:"string"==typeof e?this.dateTimeHelper.dateStringToDateNumber(e):void 0}},{key:"coerceNonDateScalarToMaybeNumber",value:function(e){return e===EmptyValue?0:"string"==typeof e?""===e?0:this.numberLiteralsHelper.numericStringToMaybeNumber(e.trim()):isExtendedNumber(e)?e:"boolean"==typeof e?Number(e):void 0}},{key:"coerceComplexExactRanges",value:function(e){var t,n=[],r=_createForOfIteratorHelper$D(e);try{for(r.s();!(t=r.n()).done;){var a=t.value;if(a instanceof SimpleRangeValue)n.push(a);else if(a!==EmptyValue){var i=this.coerceScalarToComplex(a);if(i instanceof CellError)return i;n.push(i)}}}catch(e){r.e(e)}finally{r.f()}for(var o=[],s=0,l=n;s1&&void 0!==arguments[1])||arguments[1];e=this.normalizeString(e);var r=this.config.useWildcards,a=this.config.useRegularExpressions;if(a)try{RegExp(e)}catch(e){a=!1,r=!1}return t=a?escapeNoCharacters(e,this.config.caseSensitive):r?escapeNonWildcards(e,this.config.caseSensitive):escapeAllCharacters(e,this.config.caseSensitive),this.config.matchWholeCell&&n?RegExp("^("+t+")$"):RegExp(t)}},{key:"normalizeString",value:function(e){return this.config.caseSensitive||(e=e.toLowerCase()),this.config.accentSensitive||(e=_normalizeString(e,"nfd").replace(/[\u0300-\u036f]/g,"")),e}},{key:"compare",value:function(e,t){if("string"==typeof e||"string"==typeof t){var n="string"==typeof e?this.dateTimeHelper.dateStringToDateNumber(e):e,r="string"==typeof t?this.dateTimeHelper.dateStringToDateNumber(t):t;if(isExtendedNumber(n)&&isExtendedNumber(r))return this.floatCmp(n,r)}return e===EmptyValue?e=coerceEmptyToValue(t):t===EmptyValue&&(t=coerceEmptyToValue(e)),"string"==typeof e&&"string"==typeof t?this.stringCmp(e,t):"boolean"==typeof e&&"boolean"==typeof t?numberCmp(coerceBooleanToNumber(e),coerceBooleanToNumber(t)):isExtendedNumber(e)&&isExtendedNumber(t)?this.floatCmp(e,t):e===EmptyValue&&t===EmptyValue?0:numberCmp(CellValueTypeOrd(getCellValueType(e)),CellValueTypeOrd(getCellValueType(t)))}},{key:"stringCmp",value:function(e,t){return this.collator.compare(e,t)}},{key:"manyToNumbers",value:function(e,t){var n,r=[],a=_createForOfIteratorHelper$D(e);try{for(a.s();!(n=a.n()).done;){var i=n.value;if(i instanceof SimpleRangeValue)r.push(i);else{var o=getRawValue(this.coerceScalarToNumberOrError(i));if(o instanceof CellError)return o;r.push(o)}}}catch(e){a.e(e)}finally{a.f()}for(var s=[],l=0,u=r;lr?1:n","=",".","+","-",",","\\","$","^","!"],ArgumentTypes;function needsEscape(e){return escapedCharacters.includes(e)}function escapeNonWildcards(e,t){for(var n="",r=0;r=0&&a=0&&i=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _slicedToArray$q(e,t){return _arrayWithHoles$q(e)||_iterableToArrayLimit$q(e,t)||_unsupportedIterableToArray$M(e,t)||_nonIterableRest$q()}function _nonIterableRest$q(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArrayLimit$q(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,a,i=[],o=!0,s=!1;try{for(n=n.call(e);!(o=(r=n.next()).done)&&(i.push(r.value),!t||i.length!==t);o=!0);}catch(e){s=!0,a=e}finally{try{o||null==n.return||n.return()}finally{if(s)throw a}}return i}}function _arrayWithHoles$q(e){if(Array.isArray(e))return e}function _toConsumableArray$d(e){return _arrayWithoutHoles$d(e)||_iterableToArray$d(e)||_unsupportedIterableToArray$M(e)||_nonIterableSpread$d()}function _nonIterableSpread$d(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray$M(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$M(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$M(e,t):void 0}}function _iterableToArray$d(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles$d(e){if(Array.isArray(e))return _arrayLikeToArray$M(e)}function _arrayLikeToArray$M(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n5&&void 0!==arguments[5]?arguments[5]:function(){return new CellError(ErrorType.NA,ErrorMessage.CellRefExpected)};if(0===e.length)return n.returnNumberWrapper(a(),r.returnNumberType);if(e.length>1)return new CellError(ErrorType.NA,ErrorMessage.WrongArgNumber);for(var s,l=e[0];l.type===AstNodeType.PARENTHESIS;)l=l.expression;if(l.type===AstNodeType.CELL_REFERENCE)s=l.reference.toSimpleCellAddress(t.formulaAddress);else if(l.type===AstNodeType.CELL_RANGE||l.type===AstNodeType.COLUMN_RANGE||l.type===AstNodeType.ROW_RANGE)try{s=AbsoluteCellRange.fromAst(l,t.formulaAddress).start}catch(e){return new CellError(ErrorType.REF,ErrorMessage.CellRefExpected)}return void 0!==s?n.returnNumberWrapper(i(s),r.returnNumberType):n.runFunction(e,t,r,o)},this.interpreter=t,this.dependencyGraph=t.dependencyGraph,this.columnSearch=t.columnSearch,this.config=t.config,this.serialization=t.serialization,this.arraySizePredictor=t.arraySizePredictor,this.dateTimeHelper=t.dateTimeHelper,this.arithmeticHelper=t.arithmeticHelper}return _createClass$1A(e,[{key:"evaluateAst",value:function(e,t){return this.interpreter.evaluateAst(e,t)}},{key:"arraySizeForAst",value:function(e,t){return this.arraySizePredictor.checkArraySizeForAst(e,t)}},{key:"listOfScalarValues",value:function(e,t){var n,r=[],a=_createForOfIteratorHelper$C(e);try{for(a.s();!(n=a.n()).done;){var i=n.value,o=this.evaluateAst(i,t);if(o instanceof SimpleRangeValue){var s,l=_createForOfIteratorHelper$C(o.valuesFromTopLeftCorner());try{for(l.s();!(s=l.n()).done;){var u=s.value;r.push([u,!0])}}catch(e){l.e(e)}finally{l.f()}}else r.push([o,!1])}}catch(e){a.e(e)}finally{a.f()}return r}},{key:"coerceToType",value:function(e,t,n){var r;if(e instanceof SimpleRangeValue)switch(t.argumentType){case ArgumentTypes.RANGE:case ArgumentTypes.ANY:r=e;break;default:var a=coerceRangeToScalar(e,n);if(void 0===a)return;e=a}if(!(e instanceof SimpleRangeValue))switch(t.argumentType){case ArgumentTypes.INTEGER:case ArgumentTypes.NUMBER:var i=this.coerceScalarToNumberOrError(e);if(!isExtendedNumber(i)){r=i;break}var o=getRawValue(i);if(void 0!==t.maxValue&&o>t.maxValue)return new CellError(ErrorType.NUM,ErrorMessage.ValueLarge);if(void 0!==t.minValue&&o=t.lessThan)return new CellError(ErrorType.NUM,ErrorMessage.ValueLarge);if(void 0!==t.greaterThan&&o<=t.greaterThan)return new CellError(ErrorType.NUM,ErrorMessage.ValueSmall);if(t.argumentType===ArgumentTypes.INTEGER&&!Number.isInteger(o))return new CellError(ErrorType.NUM,ErrorMessage.IntegerExpected);r=i;break;case ArgumentTypes.STRING:r=coerceScalarToString(e);break;case ArgumentTypes.BOOLEAN:r=coerceScalarToBoolean(e);break;case ArgumentTypes.SCALAR:case ArgumentTypes.NOERROR:case ArgumentTypes.ANY:r=e;break;case ArgumentTypes.RANGE:if(e instanceof CellError)return e;r=coerceToRange(e);break;case ArgumentTypes.COMPLEX:return this.arithmeticHelper.coerceScalarToComplex(getRawValue(e))}return t.passSubtype||void 0===r?r:getRawValue(r)}},{key:"metadata",value:function(e){var t=this.constructor.implementedFunctions[e];if(void 0!==t)return t;throw new Error("No metadata for function ".concat(e,"."))}},{key:"returnNumberWrapper",value:function(e,t,n){return void 0!==t&&isExtendedNumber(e)?this.arithmeticHelper.ExtendedNumberFactory(getRawValue(e),{type:t,format:n}):e}}]),e}();function _toConsumableArray$c(e){return _arrayWithoutHoles$c(e)||_iterableToArray$c(e)||_unsupportedIterableToArray$L(e)||_nonIterableSpread$c()}function _nonIterableSpread$c(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray$c(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles$c(e){if(Array.isArray(e))return _arrayLikeToArray$L(e)}function _createForOfIteratorHelper$B(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$L(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$L(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$L(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$L(e,t):void 0}}function _arrayLikeToArray$L(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n2&&void 0!==arguments[2]&&arguments[2];if(_classCallCheck$1z(this,e),this.width=t,this.height=n,this.isRef=r,t<=0||n<=0)throw Error("Incorrect array size")}return _createClass$1z(e,[{key:"isScalar",value:function(){return this.width<=1&&this.height<=1||this.isRef}}],[{key:"fromArray",value:function(t){return new e(t.length>0?t[0].length:0,t.length)}},{key:"error",value:function(){return new e(1,1,!0)}},{key:"scalar",value:function(){return new e(1,1,!1)}}]),e}();function arraySizeForBinaryOp(e,t){return new ArraySize(Math.max(e.width,t.width),Math.max(e.height,t.height))}function arraySizeForUnaryOp(e){return new ArraySize(e.width,e.height)}var ArraySizePredictor=function(){function e(t,n){_classCallCheck$1z(this,e),this.config=t,this.functionRegistry=n}return _createClass$1z(e,[{key:"checkArraySize",value:function(e,t){return this.checkArraySizeForAst(e,{formulaAddress:t,arraysFlag:this.config.useArrayArithmetic})}},{key:"checkArraySizeForAst",value:function(e,t){var n=this;switch(e.type){case AstNodeType.FUNCTION_CALL:return this.checkArraySizeForFunction(e,t);case AstNodeType.COLUMN_RANGE:case AstNodeType.ROW_RANGE:case AstNodeType.CELL_RANGE:var r=AbsoluteCellRange.fromAstOrUndef(e,t.formulaAddress);return void 0===r?ArraySize.error():new ArraySize(r.width(),r.height(),!0);case AstNodeType.ARRAY:var a,i=[],o=[],s=_createForOfIteratorHelper$B(e.args);try{for(s.s();!(a=s.n()).done;){var l=a.value.map((function(e){return n.checkArraySizeForAst(e,t)})),u=Math.min.apply(Math,_toConsumableArray$c(l.map((function(e){return e.height})))),c=l.reduce((function(e,t){return e+t.width}),0);i.push(u),o.push(c)}}catch(e){s.e(e)}finally{s.f()}var p=i.reduce((function(e,t){return e+t}),0),d=Math.min.apply(Math,o);return new ArraySize(d,p);case AstNodeType.STRING:case AstNodeType.NUMBER:return ArraySize.scalar();case AstNodeType.CELL_REFERENCE:return new ArraySize(1,1,!0);case AstNodeType.DIV_OP:case AstNodeType.CONCATENATE_OP:case AstNodeType.EQUALS_OP:case AstNodeType.GREATER_THAN_OP:case AstNodeType.GREATER_THAN_OR_EQUAL_OP:case AstNodeType.LESS_THAN_OP:case AstNodeType.LESS_THAN_OR_EQUAL_OP:case AstNodeType.MINUS_OP:case AstNodeType.NOT_EQUAL_OP:case AstNodeType.PLUS_OP:case AstNodeType.POWER_OP:case AstNodeType.TIMES_OP:var m=this.checkArraySizeForAst(e.left,t),f=this.checkArraySizeForAst(e.right,t);return!t.arraysFlag&&(m.height>1||m.width>1||f.height>1||f.width>1)?ArraySize.error():arraySizeForBinaryOp(m,f);case AstNodeType.MINUS_UNARY_OP:case AstNodeType.PLUS_UNARY_OP:case AstNodeType.PERCENT_OP:var h=this.checkArraySizeForAst(e.value,t);return!t.arraysFlag&&(h.height>1||h.width>1)?ArraySize.error():arraySizeForUnaryOp(h);case AstNodeType.PARENTHESIS:return this.checkArraySizeForAst(e.expression,t);case AstNodeType.EMPTY:default:return ArraySize.error()}}},{key:"checkArraySizeForFunction",value:function(e,t){var n=this,r=this.functionRegistry.getMetadata(e.procedureName),a=this.functionRegistry.getArraySizeFunction(e.procedureName);if(void 0!==a)return a(e,t);var i=e.args.map((function(e){var a;return n.checkArraySizeForAst(e,new InterpreterState(t.formulaAddress,t.arraysFlag||null!==(a=null==r?void 0:r.arrayFunction)&&void 0!==a&&a))}));if(void 0===r||r.expandRanges||!t.arraysFlag||r.vectorizationForbidden||void 0===r.parameters)return new ArraySize(1,1);var o=_toConsumableArray$c(r.parameters);if(void 0===r.repeatLastArgs&&o.length=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$K(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$K(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$K(e,t):void 0}}function _arrayLikeToArray$K(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=0;--a){var i=this.tryEntries[a],o=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev=0;--r){var a=this.tryEntries[r];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),C(n),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:S(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),c}},e}function _classCallCheck$1y(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1y(e,t){for(var n=0;n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$J(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$J(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$J(e,t):void 0}}function _arrayLikeToArray$J(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n({type:e,message:t});var ParsingErrorType,AstNodeType,RangeSheetReferenceType;!function(e){e.LexingError="LexingError",e.ParserError="ParsingError",e.StaticOffsetError="StaticOffsetError",e.StaticOffsetOutOfRangeError="StaticOffsetOutOfRangeError",e.RangeOffsetNotAllowed="RangeOffsetNotAllowed"}(ParsingErrorType||(ParsingErrorType={})),function(e){e.EMPTY="EMPTY",e.NUMBER="NUMBER",e.STRING="STRING",e.MINUS_UNARY_OP="MINUS_UNARY_OP",e.PLUS_UNARY_OP="PLUS_UNARY_OP",e.PERCENT_OP="PERCENT_OP",e.CONCATENATE_OP="CONCATENATE_OP",e.EQUALS_OP="EQUALS_OP",e.NOT_EQUAL_OP="NOT_EQUAL_OP",e.GREATER_THAN_OP="GREATER_THAN_OP",e.LESS_THAN_OP="LESS_THAN_OP",e.GREATER_THAN_OR_EQUAL_OP="GREATER_THAN_OR_EQUAL_OP",e.LESS_THAN_OR_EQUAL_OP="LESS_THAN_OR_EQUAL_OP",e.PLUS_OP="PLUS_OP",e.MINUS_OP="MINUS_OP",e.TIMES_OP="TIMES_OP",e.DIV_OP="DIV_OP",e.POWER_OP="POWER_OP",e.FUNCTION_CALL="FUNCTION_CALL",e.NAMED_EXPRESSION="NAMED_EXPRESSION",e.PARENTHESIS="PARENTHESES",e.CELL_REFERENCE="CELL_REFERENCE",e.CELL_RANGE="CELL_RANGE",e.COLUMN_RANGE="COLUMN_RANGE",e.ROW_RANGE="ROW_RANGE",e.ERROR="ERROR",e.ERROR_WITH_RAW_INPUT="ERROR_WITH_RAW_INPUT",e.ARRAY="ARRAY"}(AstNodeType||(AstNodeType={})),function(e){e[e.RELATIVE=0]="RELATIVE",e[e.START_ABSOLUTE=1]="START_ABSOLUTE",e[e.BOTH_ABSOLUTE=2]="BOTH_ABSOLUTE"}(RangeSheetReferenceType||(RangeSheetReferenceType={}));const buildEmptyArgAst=e=>({type:AstNodeType.EMPTY,leadingWhitespace:null==e?void 0:e.image}),buildNumberAst=(e,t)=>({type:AstNodeType.NUMBER,value:e,leadingWhitespace:null==t?void 0:t.image}),buildStringAst=e=>{var t;return{type:AstNodeType.STRING,value:e.image.slice(1,-1),leadingWhitespace:null===(t=e.leadingWhitespace)||void 0===t?void 0:t.image}},buildCellReferenceAst=(e,t)=>({type:AstNodeType.CELL_REFERENCE,reference:e,leadingWhitespace:null==t?void 0:t.image}),buildCellRangeAst=(e,t,n,r)=>(assertRangeConsistency(e,t,n),{type:AstNodeType.CELL_RANGE,start:e,end:t,sheetReferenceType:n,leadingWhitespace:r}),buildColumnRangeAst=(e,t,n,r)=>(assertRangeConsistency(e,t,n),{type:AstNodeType.COLUMN_RANGE,start:e,end:t,sheetReferenceType:n,leadingWhitespace:null==r?void 0:r.image}),buildRowRangeAst=(e,t,n,r)=>(assertRangeConsistency(e,t,n),{type:AstNodeType.ROW_RANGE,start:e,end:t,sheetReferenceType:n,leadingWhitespace:null==r?void 0:r.image}),buildConcatenateOpAst=(e,t,n)=>({type:AstNodeType.CONCATENATE_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}),buildEqualsOpAst=(e,t,n)=>({type:AstNodeType.EQUALS_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}),buildNotEqualOpAst=(e,t,n)=>({type:AstNodeType.NOT_EQUAL_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}),buildGreaterThanOpAst=(e,t,n)=>({type:AstNodeType.GREATER_THAN_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}),buildLessThanOpAst=(e,t,n)=>({type:AstNodeType.LESS_THAN_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}),buildGreaterThanOrEqualOpAst=(e,t,n)=>({type:AstNodeType.GREATER_THAN_OR_EQUAL_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}),buildLessThanOrEqualOpAst=(e,t,n)=>({type:AstNodeType.LESS_THAN_OR_EQUAL_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}),buildPlusOpAst=(e,t,n)=>({type:AstNodeType.PLUS_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}),buildMinusOpAst=(e,t,n)=>({type:AstNodeType.MINUS_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}),buildTimesOpAst=(e,t,n)=>({type:AstNodeType.TIMES_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}),buildDivOpAst=(e,t,n)=>({type:AstNodeType.DIV_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}),buildPowerOpAst=(e,t,n)=>({type:AstNodeType.POWER_OP,left:e,right:t,leadingWhitespace:null==n?void 0:n.image}),buildMinusUnaryOpAst=(e,t)=>({type:AstNodeType.MINUS_UNARY_OP,value:e,leadingWhitespace:null==t?void 0:t.image}),buildPlusUnaryOpAst=(e,t)=>({type:AstNodeType.PLUS_UNARY_OP,value:e,leadingWhitespace:null==t?void 0:t.image}),buildPercentOpAst=(e,t)=>({type:AstNodeType.PERCENT_OP,value:e,leadingWhitespace:null==t?void 0:t.image}),buildProcedureAst=(e,t,n,r)=>({type:AstNodeType.FUNCTION_CALL,procedureName:e,args:t,leadingWhitespace:null==n?void 0:n.image,internalWhitespace:null==r?void 0:r.image}),buildArrayAst=(e,t,n)=>({type:AstNodeType.ARRAY,args:e,leadingWhitespace:null==t?void 0:t.image,internalWhitespace:null==n?void 0:n.image}),buildNamedExpressionAst=(e,t)=>({type:AstNodeType.NAMED_EXPRESSION,expressionName:e,leadingWhitespace:null==t?void 0:t.image}),buildParenthesisAst=(e,t,n)=>({type:AstNodeType.PARENTHESIS,expression:e,leadingWhitespace:null==t?void 0:t.image,internalWhitespace:null==n?void 0:n.image}),buildCellErrorAst=(e,t)=>({type:AstNodeType.ERROR,error:e,leadingWhitespace:null==t?void 0:t.image}),buildErrorWithRawInputAst=(e,t,n)=>({type:AstNodeType.ERROR_WITH_RAW_INPUT,error:t,rawInput:e,leadingWhitespace:null==n?void 0:n.image}),buildParsingErrorAst=()=>({type:AstNodeType.ERROR,error:CellError.parsingError()});function assertRangeConsistency(e,t,n){if(void 0!==e.sheet&&void 0===t.sheet||void 0===e.sheet&&void 0!==t.sheet)throw new Error("Start address inconsistent with end address");if(void 0===e.sheet&&n!==RangeSheetReferenceType.RELATIVE||void 0!==e.sheet&&n===RangeSheetReferenceType.RELATIVE)throw new Error("Sheet address inconsistent with sheet reference type")}function imageWithWhitespace(e,t){return(null!=t?t:"")+e} /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */function _classCallCheck$1w(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1w(e,t){for(var n=0;n1?arguments[1]:void 0,n),i=r>2?arguments[2]:void 0,o=void 0===i?n:toAbsoluteIndex$2(i,n);o>a;)t[a++]=e;return t},$$o=_export,fill=arrayFill,addToUnscopables$2=addToUnscopables$5;function _typeof$16(e){return _typeof$16="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$16(e)}function _slicedToArray$p(e,t){return _arrayWithHoles$p(e)||_iterableToArrayLimit$p(e,t)||_unsupportedIterableToArray$I(e,t)||_nonIterableRest$p()}function _nonIterableRest$p(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArrayLimit$p(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,a,i=[],o=!0,s=!1;try{for(n=n.call(e);!(o=(r=n.next()).done)&&(i.push(r.value),!t||i.length!==t);o=!0);}catch(e){s=!0,a=e}finally{try{o||null==n.return||n.return()}finally{if(s)throw a}}return i}}function _arrayWithHoles$p(e){if(Array.isArray(e))return e}function _createForOfIteratorHelper$y(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$I(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$I(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$I(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$I(e,t):void 0}}function _arrayLikeToArray$I(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=0;--a){var i=this.tryEntries[a],o=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev=0;--r){var a=this.tryEntries[r];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),C(n),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:S(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),c}},e}function _classCallCheck$1u(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1u(e,t){for(var n=0;n=0;--a){var i=this.tryEntries[a],o=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev=0;--r){var a=this.tryEntries[r];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),C(n),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:S(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),c}},e}function _slicedToArray$o(e,t){return _arrayWithHoles$o(e)||_iterableToArrayLimit$o(e,t)||_unsupportedIterableToArray$H(e,t)||_nonIterableRest$o()}function _nonIterableRest$o(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArrayLimit$o(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,a,i=[],o=!0,s=!1;try{for(n=n.call(e);!(o=(r=n.next()).done)&&(i.push(r.value),!t||i.length!==t);o=!0);}catch(e){s=!0,a=e}finally{try{o||null==n.return||n.return()}finally{if(s)throw a}}return i}}function _arrayWithHoles$o(e){if(Array.isArray(e))return e}function _createForOfIteratorHelper$x(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$H(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$H(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$H(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$H(e,t):void 0}}function _arrayLikeToArray$H(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _toConsumableArray$b(e){return _arrayWithoutHoles$b(e)||_iterableToArray$b(e)||_unsupportedIterableToArray$G(e)||_nonIterableSpread$b()}function _nonIterableSpread$b(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray$G(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$G(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$G(e,t):void 0}}function _iterableToArray$b(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles$b(e){if(Array.isArray(e))return _arrayLikeToArray$G(e)}function _arrayLikeToArray$G(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);nu-r+n;i--)deletePropertyOrThrow(l,i-1)}else if(n>r)for(i=u-r;i>c;i--)s=i+n-1,(o=i+r-1)in l?l[s]=l[o]:deletePropertyOrThrow(l,s);for(i=0;i0?t[0].length:0,t.length),this.array=t}return _createClass$1s(e,[{key:"simpleRangeValue",value:function(){return SimpleRangeValue.onlyValues(this.array)}},{key:"addRows",value:function(e,t){var n;(n=this.array).splice.apply(n,[e,0].concat(_toConsumableArray$b(this.nullArrays(t,this.width())))),this.size.height+=t}},{key:"addColumns",value:function(e,t){for(var n=0;ne.height)throw"Resizing to smaller array";if(this.width()e.width)throw"Resizing to smaller array"}},{key:"outOfBound",value:function(e,t){return e<0||t<0||t>this.size.height-1||e>this.size.width-1}}],[{key:"fromInterpreterValue",value:function(t){return new e(t instanceof SimpleRangeValue?t.data:[[t]])}}]),e}(),ErroredArray=function(){function e(t,n){_classCallCheck$1s(this,e),this.error=t,this.size=n}return _createClass$1s(e,[{key:"get",value:function(e,t){return this.error}},{key:"width",value:function(){return this.size.width}},{key:"height",value:function(){return this.size.height}},{key:"simpleRangeValue",value:function(){return this.error}}]),e}();function _typeof$14(e){return _typeof$14="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$14(e)}function _inherits$S(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&_setPrototypeOf$T(e,t)}function _setPrototypeOf$T(e,t){return _setPrototypeOf$T=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},_setPrototypeOf$T(e,t)}function _createSuper$S(e){var t=_isNativeReflectConstruct$T();return function(){var n,r=_getPrototypeOf$S(e);if(t){var a=_getPrototypeOf$S(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return _possibleConstructorReturn$S(this,n)}}function _possibleConstructorReturn$S(e,t){if(t&&("object"===_typeof$14(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized$S(e)}function _assertThisInitialized$S(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _isNativeReflectConstruct$T(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function _getPrototypeOf$S(e){return _getPrototypeOf$S=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},_getPrototypeOf$S(e)}function _slicedToArray$n(e,t){return _arrayWithHoles$n(e)||_iterableToArrayLimit$n(e,t)||_unsupportedIterableToArray$F(e,t)||_nonIterableRest$n()}function _nonIterableRest$n(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray$F(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$F(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$F(e,t):void 0}}function _arrayLikeToArray$F(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n3&&void 0!==arguments[3]?arguments[3]:0;return _classCallCheck$1r(this,n),i=t.call(this,e,r,o),a.isRef?i.array=new ErroredArray(new CellError(ErrorType.REF,ErrorMessage.NoSpaceForArrayResult),ArraySize.error()):i.array=new NotComputedArray(a),i}return _createClass$1r(n,[{key:"width",get:function(){return this.array.width()}},{key:"height",get:function(){return this.array.height()}},{key:"sheet",get:function(){return this.cellAddress.sheet}},{key:"leftCorner",get:function(){return this.cellAddress}},{key:"setCellValue",value:function(e){if(e instanceof CellError)return this.setErrorValue(e),e;var t=ArrayValue.fromInterpreterValue(e);return t.resize(this.array.size),this.array=t,e}},{key:"getCellValue",value:function(){if(this.array instanceof NotComputedArray)throw Error("Array not computed yet.");return this.array.simpleRangeValue()}},{key:"valueOrUndef",value:function(){if(!(this.array instanceof NotComputedArray))return this.array.simpleRangeValue()}},{key:"getArrayCellValue",value:function(e){var t=e.col-this.cellAddress.col,n=e.row-this.cellAddress.row;try{return this.array.get(t,n)}catch(e){return new CellError(ErrorType.REF)}}},{key:"getArrayCellRawValue",value:function(e){var t=this.getArrayCellValue(e);return t instanceof CellError||t===EmptyValue?void 0:getRawValue(t)}},{key:"setArrayCellValue",value:function(e,t){var n=e.col-this.cellAddress.col,r=e.row-this.cellAddress.row;this.array instanceof ArrayValue&&this.array.set(n,r,t)}},{key:"setNoSpace",value:function(){return this.array=new ErroredArray(new CellError(ErrorType.SPILL,ErrorMessage.NoSpaceForArrayResult),ArraySize.error()),this.getCellValue()}},{key:"getRange",value:function(){return AbsoluteCellRange.spanFrom(this.cellAddress,this.width,this.height)}},{key:"getRangeOrUndef",value:function(){return AbsoluteCellRange.spanFromOrUndef(this.cellAddress,this.width,this.height)}},{key:"setAddress",value:function(e){this.cellAddress=e}},{key:"setFormula",value:function(e){this.formula=e}},{key:"spansThroughSheetRows",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t;return this.cellAddress.sheet===e&&this.cellAddress.row<=n&&t2&&void 0!==arguments[2]?arguments[2]:t;return this.cellAddress.sheet===e&&this.cellAddress.col<=n&&t",[AstNodeType.GREATER_THAN_OP]:">",[AstNodeType.GREATER_THAN_OR_EQUAL_OP]:">=",[AstNodeType.LESS_THAN_OP]:"<",[AstNodeType.LESS_THAN_OR_EQUAL_OP]:"<="},buildCacheEntry=(e,t,n,r)=>({ast:e,relativeDependencies:t,hasVolatileFunction:n,hasStructuralChangeFunction:r}); /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */var RangeVertex=function(){function e(t){_classCallCheck$1q(this,e),this.range=t,this.functionCache=new Map,this.criterionFunctionCache=new Map,this.dependentCacheRanges=new Set,this.bruteForce=!1}return _createClass$1q(e,[{key:"start",get:function(){return this.range.start}},{key:"end",get:function(){return this.range.end}},{key:"sheet",get:function(){return this.range.start.sheet}},{key:"getFunctionValue",value:function(e){return this.functionCache.get(e)}},{key:"setFunctionValue",value:function(e,t){this.functionCache.set(e,t)}},{key:"getCriterionFunctionValue",value:function(e,t){var n;return null===(n=this.getCriterionFunctionValues(e).get(t))||void 0===n?void 0:n[0]}},{key:"getCriterionFunctionValues",value:function(e){var t;return null!==(t=this.criterionFunctionCache.get(e))&&void 0!==t?t:new Map}},{key:"setCriterionFunctionValues",value:function(e,t){this.criterionFunctionCache.set(e,t)}},{key:"addDependentCacheRange",value:function(e){e!==this&&this.dependentCacheRanges.add(e)}},{key:"clearCache",value:function(){this.functionCache.clear(),this.criterionFunctionCache.clear(),this.dependentCacheRanges.forEach((function(e){return e.criterionFunctionCache.clear()})),this.dependentCacheRanges.clear()}},{key:"getStart",value:function(){return this.start}},{key:"getEnd",value:function(){return this.end}}]),e}(),collectAddressesDependentToRange=function(e,t,n,r,a){if(t instanceof RangeVertex){var i=t.range.intersectionWith(n);return void 0!==i?Array.from(i.addresses(a)):[]}var o,s;return t instanceof FormulaVertex?(o=t.getFormula(r),s=t.getAddress(r),collectDependencies(o,e).filter((function(e){return e instanceof AddressDependency})).map((function(e){return e.dependency.toSimpleCellAddress(s)})).filter((function(e){return n.addressInRange(e)}))):[]},NodeVisitStatus;function _createForOfIteratorHelper$v(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$E(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$E(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$E(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$E(e,t):void 0}}function _arrayLikeToArray$E(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n{switch(e.type){case AstNodeType.EMPTY:case AstNodeType.NUMBER:case AstNodeType.STRING:case AstNodeType.ERROR:case AstNodeType.ERROR_WITH_RAW_INPUT:case AstNodeType.CELL_REFERENCE:case AstNodeType.CELL_RANGE:case AstNodeType.COLUMN_RANGE:case AstNodeType.ROW_RANGE:case AstNodeType.NAMED_EXPRESSION:return!1;case AstNodeType.PERCENT_OP:case AstNodeType.PLUS_UNARY_OP:case AstNodeType.MINUS_UNARY_OP:return doesContainFunctions(e.value,t);case AstNodeType.CONCATENATE_OP:case AstNodeType.EQUALS_OP:case AstNodeType.NOT_EQUAL_OP:case AstNodeType.LESS_THAN_OP:case AstNodeType.GREATER_THAN_OP:case AstNodeType.LESS_THAN_OR_EQUAL_OP:case AstNodeType.GREATER_THAN_OR_EQUAL_OP:case AstNodeType.MINUS_OP:case AstNodeType.PLUS_OP:case AstNodeType.TIMES_OP:case AstNodeType.DIV_OP:case AstNodeType.POWER_OP:return doesContainFunctions(e.left,t)||doesContainFunctions(e.right,t);case AstNodeType.PARENTHESIS:return doesContainFunctions(e.expression,t);case AstNodeType.FUNCTION_CALL:return!!t(e.procedureName)||e.args.some((e=>doesContainFunctions(e,t)));case AstNodeType.ARRAY:return e.args.some((e=>e.some((e=>doesContainFunctions(e,t)))))}}; /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */!function(e){e[e.ON_STACK=0]="ON_STACK",e[e.PROCESSED=1]="PROCESSED",e[e.POPPED=2]="POPPED"}(NodeVisitStatus||(NodeVisitStatus={}));var Graph=function(){function e(t){_classCallCheck$1p(this,e),this.dependencyQuery=t,this.nodes=new Set,this.specialNodes=new Set,this.specialNodesStructuralChanges=new Set,this.specialNodesRecentlyChanged=new Set,this.infiniteRanges=new Set,this.edges=new Map}return _createClass$1p(e,[{key:"addNode",value:function(e){this.nodes.add(e),this.edges.has(e)||this.edges.set(e,new Set)}},{key:"addEdge",value:function(e,t){if(!this.nodes.has(e))throw new Error("Unknown node ".concat(e));if(!this.nodes.has(t))throw new Error("Unknown node ".concat(t));this.edges.get(e).add(t)}},{key:"removeEdge",value:function(e,t){if(!this.existsEdge(e,t))throw new Error("Edge does not exist");this.edges.get(e).delete(t)}},{key:"softRemoveEdge",value:function(e,t){var n;null===(n=this.edges.get(e))||void 0===n||n.delete(t)}},{key:"removeIncomingEdges",value:function(e){this.edges.forEach((function(t){t.delete(e)}))}},{key:"adjacentNodes",value:function(e){return this.edges.get(e)}},{key:"adjacentNodesCount",value:function(e){return this.adjacentNodes(e).size}},{key:"hasNode",value:function(e){return this.nodes.has(e)}},{key:"nodesCount",value:function(){return this.nodes.size}},{key:"edgesCount",value:function(){var e=0;return this.edges.forEach((function(t){return e+=t.size})),e}},{key:"removeNode",value:function(e){var t,n=_createForOfIteratorHelper$v(this.adjacentNodes(e).values());try{for(n.s();!(t=n.n()).done;){var r=t.value;this.markNodeAsSpecialRecentlyChanged(r)}}catch(e){n.e(e)}finally{n.f()}return this.edges.delete(e),this.nodes.delete(e),this.specialNodes.delete(e),this.specialNodesRecentlyChanged.delete(e),this.specialNodesStructuralChanges.delete(e),this.infiniteRanges.delete(e),this.removeDependencies(e)}},{key:"markNodeAsSpecial",value:function(e){this.specialNodes.add(e)}},{key:"markNodeAsSpecialRecentlyChanged",value:function(e){this.nodes.has(e)&&this.specialNodesRecentlyChanged.add(e)}},{key:"markNodeAsChangingWithStructure",value:function(e){this.specialNodesStructuralChanges.add(e)}},{key:"clearSpecialNodesRecentlyChanged",value:function(){this.specialNodesRecentlyChanged.clear()}},{key:"markNodeAsInfiniteRange",value:function(e){this.infiniteRanges.add(e)}},{key:"existsEdge",value:function(e,t){var n,r;return null!==(r=null===(n=this.edges.get(e))||void 0===n?void 0:n.has(t))&&void 0!==r&&r}},{key:"topSortWithScc",value:function(){return this.getTopSortedWithSccSubgraphFrom(Array.from(this.nodes),(function(){return!0}),(function(){}))}},{key:"getTopSortedWithSccSubgraphFrom",value:function(e,t,n){var r=this,a=new Map,i=new Map,o=new Map,s=new Set,l=new Map,u=[],c=0,p=new Set;e.reverse(),e.forEach((function(e){if(void 0===l.get(e)){var t=[e],n=[];l.set(e,NodeVisitStatus.ON_STACK);for(var d=function(){var e=t[t.length-1];switch(l.get(e)){case NodeVisitStatus.ON_STACK:a.set(e,c),i.set(e,c),n.push(e),c++,r.adjacentNodes(e).forEach((function(n){void 0===a.get(n)&&(t.push(n),o.set(n,e),l.set(n,NodeVisitStatus.ON_STACK))})),l.set(e,NodeVisitStatus.PROCESSED);break;case NodeVisitStatus.PROCESSED:var d;if(d=a.get(e),r.adjacentNodes(e).forEach((function(t){s.has(t)||(d=o.get(t)===e?Math.min(d,i.get(t)):Math.min(d,a.get(t)))})),i.set(e,d),d===a.get(e)){var m=[];do{m.push(n[n.length-1]),n.pop()}while(m[m.length-1]!==e);m.forEach((function(e){s.add(e)})),u.push.apply(u,m),m.length>1&&m.forEach((function(e){p.add(e)}))}t.pop(),l.set(e,NodeVisitStatus.POPPED);break;case NodeVisitStatus.POPPED:t.pop()}};t.length>0;)d()}}));var d=new Set(e),m=[],f=[];return u.reverse(),u.forEach((function(e){p.has(e)||r.adjacentNodes(e).has(e)?(f.push(e),n(e),r.adjacentNodes(e).forEach((function(e){return d.add(e)}))):(m.push(e),d.has(e)&&t(e)&&r.adjacentNodes(e).forEach((function(e){return d.add(e)})))})),{sorted:m,cycled:f}}},{key:"getDependencies",value:function(e){var t=[];return this.edges.forEach((function(n,r){n.has(e)&&t.push(r)})),t}},{key:"removeDependencies",value:function(e){var t,n=this.dependencyQuery(e),r=_createForOfIteratorHelper$v(n);try{for(r.s();!(t=r.n()).done;){var a=t.value;this.softRemoveEdge(a,e)}}catch(e){r.e(e)}finally{r.f()}return n}}]),e}();function _typeof$13(e){return _typeof$13="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$13(e)}function _regeneratorRuntime$a(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */_regeneratorRuntime$a=function(){return e};var e={},t=Object.prototype,n=t.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},a=r.iterator||"@@iterator",i=r.asyncIterator||"@@asyncIterator",o=r.toStringTag||"@@toStringTag";function s(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{s({},"")}catch(e){s=function(e,t,n){return e[t]=n}}function l(e,t,n,r){var a=t&&t.prototype instanceof p?t:p,i=Object.create(a.prototype),o=new A(r||[]);return i._invoke=function(e,t,n){var r="suspendedStart";return function(a,i){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===a)throw i;return x()}for(n.method=a,n.arg=i;;){var o=n.delegate;if(o){var s=T(o,n);if(s){if(s===c)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var l=u(e,t,n);if("normal"===l.type){if(r=n.done?"completed":"suspendedYield",l.arg===c)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(r="completed",n.method="throw",n.arg=l.arg)}}}(e,n,o),i}function u(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}e.wrap=l;var c={};function p(){}function d(){}function m(){}var f={};s(f,a,(function(){return this}));var h=Object.getPrototypeOf,y=h&&h(h(S([])));y&&y!==t&&n.call(y,a)&&(f=y);var b=m.prototype=p.prototype=Object.create(f);function g(e){["next","throw","return"].forEach((function(t){s(e,t,(function(e){return this._invoke(t,e)}))}))}function v(e,t){function r(a,i,o,s){var l=u(e[a],e,i);if("throw"!==l.type){var c=l.arg,p=c.value;return p&&"object"==_typeof$13(p)&&n.call(p,"__await")?t.resolve(p.__await).then((function(e){r("next",e,o,s)}),(function(e){r("throw",e,o,s)})):t.resolve(p).then((function(e){c.value=e,o(c)}),(function(e){return r("throw",e,o,s)}))}s(l.arg)}var a;this._invoke=function(e,n){function i(){return new t((function(t,a){r(e,n,t,a)}))}return a=a?a.then(i,i):i()}}function T(e,t){var n=e.iterator[t.method];if(void 0===n){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,T(e,t),"throw"===t.method))return c;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return c}var r=u(n,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,c;var a=r.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,c):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,c)}function N(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function C(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function A(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(N,this),this.reset(!0)}function S(e){if(e){var t=e[a];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,i=function t(){for(;++r=0;--a){var i=this.tryEntries[a],o=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev=0;--r){var a=this.tryEntries[r];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),C(n),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:S(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),c}},e}function _slicedToArray$m(e,t){return _arrayWithHoles$m(e)||_iterableToArrayLimit$m(e,t)||_unsupportedIterableToArray$D(e,t)||_nonIterableRest$m()}function _nonIterableRest$m(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArrayLimit$m(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,a,i=[],o=!0,s=!1;try{for(n=n.call(e);!(o=(r=n.next()).done)&&(i.push(r.value),!t||i.length!==t);o=!0);}catch(e){s=!0,a=e}finally{try{o||null==n.return||n.return()}finally{if(s)throw a}}return i}}function _arrayWithHoles$m(e){if(Array.isArray(e))return e}function _createForOfIteratorHelper$u(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$D(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$D(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$D(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$D(e,t):void 0}}function _arrayLikeToArray$D(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);nr.start.row&&t<=r.end.row?(r.range.expandByRows(n),{changedSize:!0,vertex:r}):void 0}))}},{key:"moveAllRangesInSheetAfterColumnByColumns",value:function(e,t,n){return this.updateVerticesFromSheet(e,(function(e,r){return t<=r.start.col?(r.range.shiftByColumns(n),{changedSize:!1,vertex:r}):t>r.start.col&&t<=r.end.col?(r.range.expandByColumns(n),{changedSize:!0,vertex:r}):void 0}))}},{key:"moveRangesInsideSourceRange",value:function(e,t,n,r){this.updateVerticesFromSheet(e.sheet,(function(a,i){return e.containsRange(i.range)?(i.range.shiftByColumns(t),i.range.shiftByRows(n),i.range.moveToSheet(r),{changedSize:!1,vertex:i}):void 0}))}},{key:"removeRangesInSheet",value:function(e){if(this.rangeMapping.has(e)){var t=this.rangeMapping.get(e).values();return this.rangeMapping.delete(e),t}return[][Symbol.iterator]()}},{key:"rangesInSheet",value:_regeneratorRuntime$a().mark((function e(t){var n;return _regeneratorRuntime$a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=this.rangeMapping.get(t)){e.next=3;break}return e.abrupt("return");case 3:return e.delegateYield(n.values(),"t0",4);case 4:case"end":return e.stop()}}),e,this)}))},{key:"rangeVerticesContainedInRange",value:_regeneratorRuntime$a().mark((function e(t){var n,r,a;return _regeneratorRuntime$a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=_createForOfIteratorHelper$u(this.rangesInSheet(t.sheet)),e.prev=1,n.s();case 3:if((r=n.n()).done){e.next=10;break}if(a=r.value,!t.containsRange(a.range)){e.next=8;break}return e.next=8,a;case 8:e.next=3;break;case 10:e.next=15;break;case 12:e.prev=12,e.t0=e.catch(1),n.e(e.t0);case 15:return e.prev=15,n.f(),e.finish(15);case 18:case"end":return e.stop()}}),e,this,[[1,12,15,18]])}))},{key:"findSmallerRange",value:function(e){if(e.height()>1&&Number.isFinite(e.height())){var t=simpleCellAddress(e.end.sheet,e.end.col,e.end.row-1),n=this.getRange(e.start,t);if(void 0!==n)return{smallerRangeVertex:n,restRange:new AbsoluteCellRange(simpleCellAddress(e.start.sheet,e.start.col,e.end.row),e.end)}}return{restRange:e}}},{key:"entriesFromSheet",value:_regeneratorRuntime$a().mark((function e(t){var n;return _regeneratorRuntime$a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=this.rangeMapping.get(t)){e.next=3;break}return e.abrupt("return");case 3:return e.delegateYield(n.entries(),"t0",4);case 4:case"end":return e.stop()}}),e,this)}))},{key:"removeByKey",value:function(e,t){this.rangeMapping.get(e).delete(t)}},{key:"getByKey",value:function(e,t){var n;return null===(n=this.rangeMapping.get(e))||void 0===n?void 0:n.get(t)}},{key:"updateVerticesFromSheet",value:function(e,t){var n,r=this,a=Array(),i=_createForOfIteratorHelper$u(this.entriesFromSheet(e));try{for(i.s();!(n=i.n()).done;){var o=_slicedToArray$m(n.value,2),s=o[0],l=t(s,o[1]);void 0!==l&&(this.removeByKey(e,s),a.push(l))}}catch(e){i.e(e)}finally{i.f()}return a.forEach((function(e){r.setRange(e.vertex)})),{verticesWithChangedSize:a.filter((function(e){return e.changedSize})).map((function(e){return e.vertex}))}}}]),e}();function keyFromAddresses(e,t){return"".concat(e.col,",").concat(e.row,",").concat(t.col,",").concat(t.row)}function keyFromRange(e){return keyFromAddresses(e.start,e.end)}var compareBy=function(e,t,n){var r=n(e.range.start),a=n(e.range.start);return r===a?n(e.range.end)-n(t.range.end):r-a},$$m=_export,toObject=toObject$e,nativeKeys=objectKeys$4,fails$2=fails$G,FAILS_ON_PRIMITIVES=fails$2((function(){nativeKeys(1)}));$$m({target:"Object",stat:!0,forced:FAILS_ON_PRIMITIVES},{keys:function(e){return nativeKeys(toObject(e))}});var DESCRIPTORS=descriptors,uncurryThis$7=functionUncurryThis,objectKeys=objectKeys$4,toIndexedObject=toIndexedObject$b,$propertyIsEnumerable=objectPropertyIsEnumerable.f,propertyIsEnumerable=uncurryThis$7($propertyIsEnumerable),push=uncurryThis$7([].push),createMethod$1=function(e){return function(t){for(var n,r=toIndexedObject(t),a=objectKeys(r),i=a.length,o=0,s=[];i>o;)n=a[o++],DESCRIPTORS&&!propertyIsEnumerable(r,n)||push(s,e?[n,r[n]]:r[n]);return s}},objectToArray={entries:createMethod$1(!0),values:createMethod$1(!1)},$$l=_export,$values=objectToArray.values;function _createForOfIteratorHelper$t(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$C(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$C(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$C(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$C(e,t):void 0}}function _arrayLikeToArray$C(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n`Function name ${e} not recognized.`,ErrorMessage.NamedExpressionName=e=>`Named expression ${e} not recognized.`,ErrorMessage.LicenseKey=e=>`License key is ${e}.` /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */function _typeof$12(e){return _typeof$12="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$12(e)}function _regeneratorRuntime$9(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */_regeneratorRuntime$9=function(){return e};var e={},t=Object.prototype,n=t.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},a=r.iterator||"@@iterator",i=r.asyncIterator||"@@asyncIterator",o=r.toStringTag||"@@toStringTag";function s(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{s({},"")}catch(e){s=function(e,t,n){return e[t]=n}}function l(e,t,n,r){var a=t&&t.prototype instanceof p?t:p,i=Object.create(a.prototype),o=new A(r||[]);return i._invoke=function(e,t,n){var r="suspendedStart";return function(a,i){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===a)throw i;return x()}for(n.method=a,n.arg=i;;){var o=n.delegate;if(o){var s=T(o,n);if(s){if(s===c)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var l=u(e,t,n);if("normal"===l.type){if(r=n.done?"completed":"suspendedYield",l.arg===c)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(r="completed",n.method="throw",n.arg=l.arg)}}}(e,n,o),i}function u(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}e.wrap=l;var c={};function p(){}function d(){}function m(){}var f={};s(f,a,(function(){return this}));var h=Object.getPrototypeOf,y=h&&h(h(S([])));y&&y!==t&&n.call(y,a)&&(f=y);var b=m.prototype=p.prototype=Object.create(f);function g(e){["next","throw","return"].forEach((function(t){s(e,t,(function(e){return this._invoke(t,e)}))}))}function v(e,t){function r(a,i,o,s){var l=u(e[a],e,i);if("throw"!==l.type){var c=l.arg,p=c.value;return p&&"object"==_typeof$12(p)&&n.call(p,"__await")?t.resolve(p.__await).then((function(e){r("next",e,o,s)}),(function(e){r("throw",e,o,s)})):t.resolve(p).then((function(e){c.value=e,o(c)}),(function(e){return r("throw",e,o,s)}))}s(l.arg)}var a;this._invoke=function(e,n){function i(){return new t((function(t,a){r(e,n,t,a)}))}return a=a?a.then(i,i):i()}}function T(e,t){var n=e.iterator[t.method];if(void 0===n){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,T(e,t),"throw"===t.method))return c;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return c}var r=u(n,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,c;var a=r.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,c):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,c)}function N(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function C(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function A(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(N,this),this.reset(!0)}function S(e){if(e){var t=e[a];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,i=function t(){for(;++r=0;--a){var i=this.tryEntries[a],o=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev=0;--r){var a=this.tryEntries[r];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),C(n),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:S(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),c}},e}function _createForOfIteratorHelper$s(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$B(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$B(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$B(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$B(e,t):void 0}}function _arrayLikeToArray$B(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n0&&void 0!==arguments[0]?arguments[0]:"".concat(this.sheetNamePrefix).concat(this.lastSheetId+2),t=canonicalize(e);if(this.mappingFromCanonicalName.has(t))throw new SheetNameAlreadyTakenError(e);this.lastSheetId++;var n=new Sheet(this.lastSheetId,e);return this.store(n),n.id}},{key:"removeSheet",value:function(e){var t=this.fetchSheetById(e);e==this.lastSheetId&&--this.lastSheetId,this.mappingFromCanonicalName.delete(t.canonicalName),this.mappingFromId.delete(t.id)}},{key:"getDisplayName",value:function(e){var t;return null===(t=this.mappingFromId.get(e))||void 0===t?void 0:t.displayName}},{key:"displayNames",value:_regeneratorRuntime$9().mark((function e(){var t,n,r;return _regeneratorRuntime$9().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=_createForOfIteratorHelper$s(this.mappingFromCanonicalName.values()),e.prev=1,t.s();case 3:if((n=t.n()).done){e.next=9;break}return r=n.value,e.next=7,r.displayName;case 7:e.next=3;break;case 9:e.next=14;break;case 11:e.prev=11,e.t0=e.catch(1),t.e(e.t0);case 14:return e.prev=14,t.f(),e.finish(14);case 17:case"end":return e.stop()}}),e,this,[[1,11,14,17]])}))},{key:"numberOfSheets",value:function(){return this.mappingFromCanonicalName.size}},{key:"hasSheetWithId",value:function(e){return this.mappingFromId.has(e)}},{key:"hasSheetWithName",value:function(e){return this.mappingFromCanonicalName.has(canonicalize(e))}},{key:"renameSheet",value:function(e,t){var n=this.fetchSheetById(e),r=n.displayName;if(r!==t){var a=this.mappingFromCanonicalName.get(canonicalize(t));if(void 0!==a&&a.id!==n.id)throw new SheetNameAlreadyTakenError(t);var i=n.canonicalName;return this.mappingFromCanonicalName.delete(i),n.displayName=t,this.store(n),r}}},{key:"sheetNames",value:function(){return Array.from(this.mappingFromId.values()).map((function(e){return e.displayName}))}},{key:"store",value:function(e){this.mappingFromId.set(e.id,e),this.mappingFromCanonicalName.set(e.canonicalName,e)}},{key:"fetchSheetById",value:function(e){var t=this.mappingFromId.get(e);if(void 0===t)throw new NoSheetWithIdError(e);return t}}]),e}();function _typeof$11(e){return _typeof$11="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$11(e)}function _construct(e,t,n){return _construct=_isNativeReflectConstruct$S()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var a=new(Function.bind.apply(e,r));return n&&_setPrototypeOf$S(a,n.prototype),a},_construct.apply(null,arguments)}function _isNativeReflectConstruct$S(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function _setPrototypeOf$S(e,t){return _setPrototypeOf$S=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},_setPrototypeOf$S(e,t)}function _regeneratorRuntime$8(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */_regeneratorRuntime$8=function(){return e};var e={},t=Object.prototype,n=t.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},a=r.iterator||"@@iterator",i=r.asyncIterator||"@@asyncIterator",o=r.toStringTag||"@@toStringTag";function s(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{s({},"")}catch(e){s=function(e,t,n){return e[t]=n}}function l(e,t,n,r){var a=t&&t.prototype instanceof p?t:p,i=Object.create(a.prototype),o=new A(r||[]);return i._invoke=function(e,t,n){var r="suspendedStart";return function(a,i){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===a)throw i;return x()}for(n.method=a,n.arg=i;;){var o=n.delegate;if(o){var s=T(o,n);if(s){if(s===c)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var l=u(e,t,n);if("normal"===l.type){if(r=n.done?"completed":"suspendedYield",l.arg===c)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(r="completed",n.method="throw",n.arg=l.arg)}}}(e,n,o),i}function u(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}e.wrap=l;var c={};function p(){}function d(){}function m(){}var f={};s(f,a,(function(){return this}));var h=Object.getPrototypeOf,y=h&&h(h(S([])));y&&y!==t&&n.call(y,a)&&(f=y);var b=m.prototype=p.prototype=Object.create(f);function g(e){["next","throw","return"].forEach((function(t){s(e,t,(function(e){return this._invoke(t,e)}))}))}function v(e,t){function r(a,i,o,s){var l=u(e[a],e,i);if("throw"!==l.type){var c=l.arg,p=c.value;return p&&"object"==_typeof$11(p)&&n.call(p,"__await")?t.resolve(p.__await).then((function(e){r("next",e,o,s)}),(function(e){r("throw",e,o,s)})):t.resolve(p).then((function(e){c.value=e,o(c)}),(function(e){return r("throw",e,o,s)}))}s(l.arg)}var a;this._invoke=function(e,n){function i(){return new t((function(t,a){r(e,n,t,a)}))}return a=a?a.then(i,i):i()}}function T(e,t){var n=e.iterator[t.method];if(void 0===n){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,T(e,t),"throw"===t.method))return c;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return c}var r=u(n,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,c;var a=r.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,c):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,c)}function N(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function C(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function A(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(N,this),this.reset(!0)}function S(e){if(e){var t=e[a];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,i=function t(){for(;++r=0;--a){var i=this.tryEntries[a],o=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev=0;--r){var a=this.tryEntries[r];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),C(n),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:S(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),c}},e}function _toConsumableArray$a(e){return _arrayWithoutHoles$a(e)||_iterableToArray$a(e)||_unsupportedIterableToArray$A(e)||_nonIterableSpread$a()}function _nonIterableSpread$a(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray$a(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles$a(e){if(Array.isArray(e))return _arrayLikeToArray$A(e)}function _createForOfIteratorHelper$r(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$A(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _slicedToArray$l(e,t){return _arrayWithHoles$l(e)||_iterableToArrayLimit$l(e,t)||_unsupportedIterableToArray$A(e,t)||_nonIterableRest$l()}function _nonIterableRest$l(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray$A(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$A(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$A(e,t):void 0}}function _arrayLikeToArray$A(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n0){var n=new EmptyCellVertex(e);this.exchangeGraphNode(t,n),0===this.graph.adjacentNodesCount(n)?(this.removeVertex(n),this.addressMapping.removeCell(e)):(this.graph.markNodeAsSpecialRecentlyChanged(n),this.addressMapping.setCell(e,n))}else this.removeVertex(t),this.addressMapping.removeCell(e);return this.getAndClearContentChanges()}},{key:"ensureThatVertexIsNonArrayCellVertex",value:function(e){if(e instanceof ArrayVertex)throw new Error("Illegal operation")}},{key:"clearRecentlyChangedVertices",value:function(){this.graph.clearSpecialNodesRecentlyChanged()}},{key:"verticesToRecompute",value:function(){return new Set([].concat(_toConsumableArray$a(this.graph.specialNodesRecentlyChanged),_toConsumableArray$a(this.volatileVertices())))}},{key:"processCellDependencies",value:function(e,t){var n=this;e.forEach((function(e){if(e instanceof AbsoluteCellRange){var r=e,a=n.getRange(r.start,r.end);void 0===a&&(a=new RangeVertex(r),n.rangeMapping.setRange(a)),n.graph.addNode(a),r.isFinite()||n.graph.markNodeAsInfiniteRange(a);var i=n.rangeMapping.findSmallerRange(r),o=i.smallerRangeVertex,s=i.restRange;if(void 0!==o){if(n.graph.addEdge(o,a),a.bruteForce){a.bruteForce=!1;var l,u=_createForOfIteratorHelper$r(r.addresses(n));try{for(u.s();!(l=u.n()).done;){var c=l.value;n.graph.removeEdge(n.fetchCell(c),a)}}catch(e){u.e(e)}finally{u.f()}}}else a.bruteForce=!0;var p=n.arrayMapping.getArray(s);if(void 0!==p)n.graph.addEdge(p,a);else{var d,m=_createForOfIteratorHelper$r(s.addresses(n));try{for(m.s();!(d=m.n()).done;){var f=d.value;n.graph.addEdge(n.fetchCellOrCreateEmpty(f),a)}}catch(e){m.e(e)}finally{m.f()}}n.graph.addEdge(a,t),r.isFinite()&&n.correctInfiniteRangesDependenciesByRangeVertex(a)}else if(e instanceof NamedExpressionDependency){var h=t.getAddress(n.lazilyTransformingAstService).sheet,y=n.fetchNamedExpressionVertex(e.name,h);n.graph.addEdge(y,t)}else n.graph.addEdge(n.fetchCellOrCreateEmpty(e),t)}))}},{key:"fetchNamedExpressionVertex",value:function(e,t){var n=this.namedExpressions.namedExpressionOrPlaceholder(e,t);return this.fetchCellOrCreateEmpty(n.address)}},{key:"exchangeNode",value:function(e,t){var n=this.fetchCellOrCreateEmpty(e),r=this.fetchCellOrCreateEmpty(t);this.addressMapping.removeCell(e),this.exchangeGraphNode(n,r)}},{key:"correctInfiniteRangesDependency",value:function(e){var t,n=void 0,r=_createForOfIteratorHelper$r(this.graph.infiniteRanges);try{for(r.s();!(t=r.n()).done;){var a=t.value;a.range.addressInRange(e)&&(n=null!=n?n:this.fetchCellOrCreateEmpty(e),this.graph.addEdge(n,a))}}catch(e){r.e(e)}finally{r.f()}}},{key:"fetchCellOrCreateEmpty",value:function(e){var t=this.addressMapping.getCell(e);return void 0===t&&(t=new EmptyCellVertex(e),this.graph.addNode(t),this.addressMapping.setCell(e,t)),t}},{key:"removeRows",value:function(e){var t=this;this.stats.measure(StatType.ADJUSTING_GRAPH,(function(){var n,r=_createForOfIteratorHelper$r(t.addressMapping.entriesFromRowsSpan(e));try{for(r.s();!(n=r.n()).done;){var a,i=_slicedToArray$l(n.value,2),o=i[0],s=i[1],l=_createForOfIteratorHelper$r(t.graph.adjacentNodes(s));try{for(l.s();!(a=l.n()).done;){var u=a.value;t.graph.markNodeAsSpecialRecentlyChanged(u)}}catch(e){l.e(e)}finally{l.f()}if(s instanceof ArrayVertex){if(!s.isLeftCorner(o))continue;t.shrinkArrayToCorner(s),t.arrayMapping.removeArray(s.getRange())}t.removeVertex(s)}}catch(e){r.e(e)}finally{r.f()}})),this.stats.measure(StatType.ADJUSTING_ADDRESS_MAPPING,(function(){t.addressMapping.removeRows(e)}));var n=this.stats.measure(StatType.ADJUSTING_RANGES,(function(){var n=t.truncateRanges(e,(function(e){return e.row}));return t.getArrayVerticesRelatedToRanges(n)}));return this.stats.measure(StatType.ADJUSTING_ARRAY_MAPPING,(function(){t.fixArraysAfterRemovingRows(e.sheet,e.rowStart,e.numberOfRows)})),this.addStructuralNodesToChangeSet(),{affectedArrays:n,contentChanges:this.getAndClearContentChanges()}}},{key:"removeSheet",value:function(e){var t,n=this,r=new Set,a=_createForOfIteratorHelper$r(this.addressMapping.sheetEntries(e));try{for(a.s();!(t=a.n()).done;){var i=_slicedToArray$l(t.value,2),o=i[0],s=i[1];if(s instanceof ArrayVertex){if(r.has(s))continue;r.add(s)}var l,u=_createForOfIteratorHelper$r(this.graph.adjacentNodes(s));try{for(u.s();!(l=u.n()).done;){var c=l.value;this.graph.markNodeAsSpecialRecentlyChanged(c)}}catch(e){u.e(e)}finally{u.f()}this.removeVertex(s),this.addressMapping.removeCell(o)}}catch(e){a.e(e)}finally{a.f()}this.stats.measure(StatType.ADJUSTING_ARRAY_MAPPING,(function(){var e,t=_createForOfIteratorHelper$r(r.values());try{for(t.s();!(e=t.n()).done;){var a=e.value;n.arrayMapping.removeArray(a.getRange())}}catch(e){t.e(e)}finally{t.f()}})),this.stats.measure(StatType.ADJUSTING_RANGES,(function(){var t,r=_createForOfIteratorHelper$r(n.rangeMapping.removeRangesInSheet(e));try{for(r.s();!(t=r.n()).done;){var a=t.value;n.removeVertex(a)}}catch(e){r.e(e)}finally{r.f()}n.stats.measure(StatType.ADJUSTING_ADDRESS_MAPPING,(function(){n.addressMapping.removeSheet(e)}))})),this.addStructuralNodesToChangeSet()}},{key:"clearSheet",value:function(e){var t,n=new Set,r=_createForOfIteratorHelper$r(this.addressMapping.sheetEntries(e));try{for(r.s();!(t=r.n()).done;){var a=_slicedToArray$l(t.value,2),i=a[0],o=a[1];o instanceof ArrayVertex?n.add(o):this.setCellEmpty(i)}}catch(e){r.e(e)}finally{r.f()}var s,l=_createForOfIteratorHelper$r(n.values());try{for(l.s();!(s=l.n()).done;){var u=s.value;this.setArrayEmpty(u)}}catch(e){l.e(e)}finally{l.f()}this.addStructuralNodesToChangeSet()}},{key:"removeColumns",value:function(e){var t=this;this.stats.measure(StatType.ADJUSTING_GRAPH,(function(){var n,r=_createForOfIteratorHelper$r(t.addressMapping.entriesFromColumnsSpan(e));try{for(r.s();!(n=r.n()).done;){var a,i=_slicedToArray$l(n.value,2),o=i[0],s=i[1],l=_createForOfIteratorHelper$r(t.graph.adjacentNodes(s));try{for(l.s();!(a=l.n()).done;){var u=a.value;t.graph.markNodeAsSpecialRecentlyChanged(u)}}catch(e){l.e(e)}finally{l.f()}if(s instanceof ArrayVertex){if(!s.isLeftCorner(o))continue;t.shrinkArrayToCorner(s),t.arrayMapping.removeArray(s.getRange())}t.removeVertex(s)}}catch(e){r.e(e)}finally{r.f()}})),this.stats.measure(StatType.ADJUSTING_ADDRESS_MAPPING,(function(){t.addressMapping.removeColumns(e)}));var n=this.stats.measure(StatType.ADJUSTING_RANGES,(function(){var n=t.truncateRanges(e,(function(e){return e.col}));return t.getArrayVerticesRelatedToRanges(n)}));return this.stats.measure(StatType.ADJUSTING_ARRAY_MAPPING,(function(){return t.fixArraysAfterRemovingColumns(e.sheet,e.columnStart,e.numberOfColumns)})),this.addStructuralNodesToChangeSet(),{affectedArrays:n,contentChanges:this.getAndClearContentChanges()}}},{key:"addRows",value:function(e){var t=this;this.stats.measure(StatType.ADJUSTING_ADDRESS_MAPPING,(function(){t.addressMapping.addRows(e.sheet,e.rowStart,e.numberOfRows)}));var n=this.stats.measure(StatType.ADJUSTING_RANGES,(function(){var n=t.rangeMapping.moveAllRangesInSheetAfterRowByRows(e.sheet,e.rowStart,e.numberOfRows);return t.fixRangesWhenAddingRows(e.sheet,e.rowStart,e.numberOfRows),t.getArrayVerticesRelatedToRanges(n.verticesWithChangedSize)}));this.stats.measure(StatType.ADJUSTING_ARRAY_MAPPING,(function(){t.fixArraysAfterAddingRow(e.sheet,e.rowStart,e.numberOfRows)}));var r,a=_createForOfIteratorHelper$r(this.addressMapping.verticesFromRowsSpan(e));try{for(a.s();!(r=a.n()).done;){var i=r.value;this.graph.markNodeAsSpecialRecentlyChanged(i)}}catch(e){a.e(e)}finally{a.f()}return this.addStructuralNodesToChangeSet(),{affectedArrays:n}}},{key:"addColumns",value:function(e){var t=this;this.stats.measure(StatType.ADJUSTING_ADDRESS_MAPPING,(function(){t.addressMapping.addColumns(e.sheet,e.columnStart,e.numberOfColumns)}));var n=this.stats.measure(StatType.ADJUSTING_RANGES,(function(){var n=t.rangeMapping.moveAllRangesInSheetAfterColumnByColumns(e.sheet,e.columnStart,e.numberOfColumns);return t.fixRangesWhenAddingColumns(e.sheet,e.columnStart,e.numberOfColumns),t.getArrayVerticesRelatedToRanges(n.verticesWithChangedSize)}));this.stats.measure(StatType.ADJUSTING_ARRAY_MAPPING,(function(){return t.fixArraysAfterAddingColumn(e.sheet,e.columnStart,e.numberOfColumns)}));var r,a=_createForOfIteratorHelper$r(this.addressMapping.verticesFromColumnsSpan(e));try{for(a.s();!(r=a.n()).done;){var i=r.value;this.graph.markNodeAsSpecialRecentlyChanged(i)}}catch(e){a.e(e)}finally{a.f()}return this.addStructuralNodesToChangeSet(),{affectedArrays:n,contentChanges:this.getAndClearContentChanges()}}},{key:"ensureNoArrayInRange",value:function(e){if(this.arrayMapping.isFormulaArrayInRange(e))throw Error("It is not possible to move / replace cells with array")}},{key:"isThereSpaceForArray",value:function(e){var t=e.getRangeOrUndef();if(void 0===t)return!1;var n,r=_createForOfIteratorHelper$r(t.addresses(this));try{for(r.s();!(n=r.n()).done;){var a=n.value,i=this.addressMapping.getCell(a);if(void 0!==i&&!(i instanceof EmptyCellVertex)&&i!==e)return!1}}catch(e){r.e(e)}finally{r.f()}return!0}},{key:"moveCells",value:function(e,t,n,r){var a,i=_createForOfIteratorHelper$r(e.addressesWithDirection(t,n,this));try{for(i.s();!(a=i.n()).done;){var o=a.value,s=simpleCellAddress(r,o.col+t,o.row+n),l=this.addressMapping.getCell(o),u=this.addressMapping.getCell(s);if(this.addressMapping.removeCell(o),void 0!==l){this.graph.markNodeAsSpecialRecentlyChanged(l),this.addressMapping.setCell(s,l);var c,p=void 0,d=_createForOfIteratorHelper$r(this.graph.adjacentNodes(l));try{for(d.s();!(c=d.n()).done;){var m=c.value;m instanceof RangeVertex&&!e.containsRange(m.range)&&(p=null!=p?p:this.fetchCellOrCreateEmpty(o),this.graph.addEdge(p,m),this.graph.removeEdge(l,m))}}catch(e){d.e(e)}finally{d.f()}p&&(this.graph.markNodeAsSpecialRecentlyChanged(p),this.addressMapping.setCell(o,p))}if(void 0!==u){void 0===l&&this.addressMapping.removeCell(s);var f,h=_createForOfIteratorHelper$r(this.graph.adjacentNodes(u));try{for(h.s();!(f=h.n()).done;){var y=f.value;l=null!=l?l:this.fetchCellOrCreateEmpty(s),this.graph.addEdge(l,y),this.graph.markNodeAsSpecialRecentlyChanged(l)}}catch(e){h.e(e)}finally{h.f()}this.removeVertex(u)}}}catch(e){i.e(e)}finally{i.f()}var b,g=_createForOfIteratorHelper$r(this.rangeMapping.rangeVerticesContainedInRange(e));try{for(g.s();!(b=g.n()).done;){var v,T=b.value,N=_createForOfIteratorHelper$r(this.graph.adjacentNodes(T));try{for(N.s();!(v=N.n()).done;){var C=v.value;if(C instanceof RangeVertex&&!e.containsRange(C.range)){this.graph.removeEdge(T,C);var A,S=_createForOfIteratorHelper$r(T.range.addresses(this));try{for(S.s();!(A=S.n()).done;){var x=A.value,w=this.fetchCellOrCreateEmpty(x);this.graph.addEdge(w,C),this.addressMapping.setCell(x,w),this.graph.markNodeAsSpecialRecentlyChanged(w)}}catch(e){S.e(e)}finally{S.f()}}}}catch(e){N.e(e)}finally{N.f()}}}catch(e){g.e(e)}finally{g.f()}this.rangeMapping.moveRangesInsideSourceRange(e,t,n,r)}},{key:"setArrayEmpty",value:function(e){var t,n=AbsoluteCellRange.spanFrom(e.getAddress(this.lazilyTransformingAstService),e.width,e.height),r=this.graph.adjacentNodes(e),a=_createForOfIteratorHelper$r(n.addresses(this));try{for(a.s();!(t=a.n()).done;){var i=t.value;this.addressMapping.removeCell(i)}}catch(e){a.e(e)}finally{a.f()}var o,s=_createForOfIteratorHelper$r(r.values());try{for(s.s();!(o=s.n()).done;){var l,u=o.value,c=collectAddressesDependentToRange(this.functionRegistry,u,e.getRange(),this.lazilyTransformingAstService,this),p=_createForOfIteratorHelper$r(c);try{for(p.s();!(l=p.n()).done;){var d=l.value,m=this.fetchCellOrCreateEmpty(d);this.graph.addEdge(m,u)}}catch(e){p.e(e)}finally{p.f()}c.length>0&&this.graph.markNodeAsSpecialRecentlyChanged(u)}}catch(e){s.e(e)}finally{s.f()}this.removeVertex(e),this.arrayMapping.removeArray(e.getRange())}},{key:"addVertex",value:function(e,t){this.graph.addNode(t),this.addressMapping.setCell(e,t)}},{key:"addArrayVertex",value:function(e,t){this.graph.addNode(t),this.setAddressMappingForArrayVertex(t,e)}},{key:"arrayFormulaNodes",value:_regeneratorRuntime$8().mark((function e(){var t,n,r;return _regeneratorRuntime$8().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=_createForOfIteratorHelper$r(this.graph.nodes),e.prev=1,t.s();case 3:if((n=t.n()).done){e.next=10;break}if(!((r=n.value)instanceof ArrayVertex)){e.next=8;break}return e.next=8,r;case 8:e.next=3;break;case 10:e.next=15;break;case 12:e.prev=12,e.t0=e.catch(1),t.e(e.t0);case 15:return e.prev=15,t.f(),e.finish(15);case 18:case"end":return e.stop()}}),e,this,[[1,12,15,18]])}))},{key:"entriesFromRowsSpan",value:_regeneratorRuntime$8().mark((function e(t){return _regeneratorRuntime$8().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.delegateYield(this.addressMapping.entriesFromRowsSpan(t),"t0",1);case 1:case"end":return e.stop()}}),e,this)}))},{key:"entriesFromColumnsSpan",value:_regeneratorRuntime$8().mark((function e(t){return _regeneratorRuntime$8().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.delegateYield(this.addressMapping.entriesFromColumnsSpan(t),"t0",1);case 1:case"end":return e.stop()}}),e,this)}))},{key:"existsVertex",value:function(e){return this.addressMapping.has(e)}},{key:"fetchCell",value:function(e){return this.addressMapping.fetchCell(e)}},{key:"getCell",value:function(e){return this.addressMapping.getCell(e)}},{key:"getCellValue",value:function(e){return this.addressMapping.getCellValue(e)}},{key:"getRawValue",value:function(e){return this.addressMapping.getRawValue(e)}},{key:"getScalarValue",value:function(e){var t=this.addressMapping.getCellValue(e);return t instanceof SimpleRangeValue?new CellError(ErrorType.VALUE,ErrorMessage.ScalarExpected):t}},{key:"existsEdge",value:function(e,t){return this.graph.existsEdge(e,t)}},{key:"getSheetId",value:function(e){return this.sheetMapping.fetch(e)}},{key:"getSheetHeight",value:function(e){return this.addressMapping.getHeight(e)}},{key:"getSheetWidth",value:function(e){return this.addressMapping.getWidth(e)}},{key:"getArray",value:function(e){return this.arrayMapping.getArray(e)}},{key:"setArray",value:function(e,t){this.arrayMapping.setArray(e,t)}},{key:"getRange",value:function(e,t){return this.rangeMapping.getRange(e,t)}},{key:"topSortWithScc",value:function(){return this.graph.topSortWithScc()}},{key:"markAsVolatile",value:function(e){this.graph.markNodeAsSpecial(e)}},{key:"markAsDependentOnStructureChange",value:function(e){this.graph.markNodeAsChangingWithStructure(e)}},{key:"forceApplyPostponedTransformations",value:function(){var e,t=_createForOfIteratorHelper$r(this.graph.nodes.values());try{for(t.s();!(e=t.n()).done;){var n=e.value;n instanceof FormulaCellVertex&&n.ensureRecentData(this.lazilyTransformingAstService)}}catch(e){t.e(e)}finally{t.f()}}},{key:"volatileVertices",value:function(){return this.graph.specialNodes}},{key:"getArrayVerticesRelatedToRanges",value:function(e){var t=this,n=e.map((function(e){return t.graph.hasNode(e)?Array.from(t.graph.adjacentNodes(e)).filter((function(e){return e instanceof ArrayVertex})):[]}));return _construct(Set,_toConsumableArray$a(n))}},{key:"rawValuesFromRange",value:_regeneratorRuntime$8().mark((function e(t){var n,r,a,i;return _regeneratorRuntime$8().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=_createForOfIteratorHelper$r(t.addresses(this)),e.prev=1,n.s();case 3:if((r=n.n()).done){e.next=11;break}if(a=r.value,(i=this.getScalarValue(a))===EmptyValue){e.next=9;break}return e.next=9,[getRawValue(i),a];case 9:e.next=3;break;case 11:e.next=16;break;case 13:e.prev=13,e.t0=e.catch(1),n.e(e.t0);case 16:return e.prev=16,n.f(),e.finish(16);case 19:case"end":return e.stop()}}),e,this,[[1,13,16,19]])}))},{key:"entriesFromRange",value:_regeneratorRuntime$8().mark((function e(t){var n,r,a;return _regeneratorRuntime$8().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=_createForOfIteratorHelper$r(t.addresses(this)),e.prev=1,n.s();case 3:if((r=n.n()).done){e.next=9;break}return a=r.value,e.next=7,[a,this.getCell(a)];case 7:e.next=3;break;case 9:e.next=14;break;case 11:e.prev=11,e.t0=e.catch(1),n.e(e.t0);case 14:return e.prev=14,n.f(),e.finish(14);case 17:case"end":return e.stop()}}),e,this,[[1,11,14,17]])}))},{key:"exchangeGraphNode",value:function(e,t){var n=this;this.graph.addNode(t);var r=this.graph.adjacentNodes(e);this.removeVertex(e),r.forEach((function(e){n.graph.hasNode(e)&&n.graph.addEdge(t,e)}))}},{key:"exchangeOrAddGraphNode",value:function(e,t){e?this.exchangeGraphNode(e,t):this.graph.addNode(t)}},{key:"computeListOfValuesInRange",value:function(e){var t,n=[],r=_createForOfIteratorHelper$r(e.addresses(this));try{for(r.s();!(t=r.n()).done;){var a=t.value,i=this.getScalarValue(a);n.push(i)}}catch(e){r.e(e)}finally{r.f()}return n}},{key:"shrinkArrayToCorner",value:function(e){this.cleanAddressMappingUnderArray(e);var t,n=_createForOfIteratorHelper$r(this.adjacentArrayVertices(e));try{for(n.s();!(t=n.n()).done;){var r=t.value,a=void 0;a=r instanceof FormulaVertex?this.formulaDirectDependenciesToArray(r,e):this.rangeDirectDependenciesToArray(r,e);var i,o=!1,s=_createForOfIteratorHelper$r(a);try{for(s.s();!(i=s.n()).done;){var l=_slicedToArray$l(i.value,2),u=l[0],c=l[1];e.isLeftCorner(u)&&(o=!0),this.graph.addEdge(c,r),this.graph.markNodeAsSpecialRecentlyChanged(c)}}catch(e){s.e(e)}finally{s.f()}o||this.graph.removeEdge(e,r)}}catch(e){n.e(e)}finally{n.f()}this.graph.markNodeAsSpecialRecentlyChanged(e)}},{key:"isArrayInternalCell",value:function(e){var t=this.getCell(e);return t instanceof ArrayVertex&&!t.isLeftCorner(e)}},{key:"getAndClearContentChanges",value:function(){var e=this.changes;return this.changes=ContentChanges.empty(),e}},{key:"getAdjacentNodesAddresses",value:function(e){var t=this,n=this.graph.adjacentNodes(e),r=[];return n.forEach((function(e){var n=e;n instanceof RangeVertex?r.push(simpleCellRange(n.start,n.end)):r.push(n.getAddress(t.lazilyTransformingAstService))})),r}},{key:"correctInfiniteRangesDependenciesByRangeVertex",value:function(e){var t,n=_createForOfIteratorHelper$r(this.graph.infiniteRanges);try{for(n.s();!(t=n.n()).done;){var r=t.value,a=r,i=e.range.intersectionWith(a.range);if(void 0!==i){var o,s=_createForOfIteratorHelper$r(i.addresses(this));try{for(s.s();!(o=s.n()).done;){var l=o.value;this.graph.addEdge(this.fetchCellOrCreateEmpty(l),r)}}catch(e){s.e(e)}finally{s.f()}}}}catch(e){n.e(e)}finally{n.f()}}},{key:"cleanAddressMappingUnderArray",value:function(e){var t,n=_createForOfIteratorHelper$r(e.getRange().addresses(this));try{for(n.s();!(t=n.n()).done;){var r=t.value,a=e.getArrayCellValue(r);this.getCell(r)===e?e.isLeftCorner(r)?this.changes.addChange(new CellError(ErrorType.REF),r,a):(this.addressMapping.removeCell(r),this.changes.addChange(EmptyValue,r,a)):this.changes.addChange(EmptyValue,r,a)}}catch(e){n.e(e)}finally{n.f()}}},{key:"formulaDirectDependenciesToArray",value:_regeneratorRuntime$8().mark((function e(t,n){var r,a,i,o,s,l,u,c;return _regeneratorRuntime$8().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(a=null!==(r=this.formulaDependencyQuery(t))&&void 0!==r?r:[],i=_slicedToArray$l(a,2),void 0!==(o=i[1])){e.next=3;break}return e.abrupt("return");case 3:s=_createForOfIteratorHelper$r(o),e.prev=4,s.s();case 6:if((l=s.n()).done){e.next=16;break}if(!((u=l.value)instanceof NamedExpressionDependency||u instanceof AbsoluteCellRange)){e.next=10;break}return e.abrupt("continue",14);case 10:if(!n.getRange().addressInRange(u)){e.next=14;break}return c=this.fetchCellOrCreateEmpty(u),e.next=14,[u,c];case 14:e.next=6;break;case 16:e.next=21;break;case 18:e.prev=18,e.t0=e.catch(4),s.e(e.t0);case 21:return e.prev=21,s.f(),e.finish(21);case 24:case"end":return e.stop()}}),e,this,[[4,18,21,24]])}))},{key:"rangeDirectDependenciesToArray",value:_regeneratorRuntime$8().mark((function e(t,n){var r,a,i,o,s,l;return _regeneratorRuntime$8().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:r=this.rangeMapping.findSmallerRange(t.range),a=r.restRange,i=_createForOfIteratorHelper$r(a.addresses(this)),e.prev=2,i.s();case 4:if((o=i.n()).done){e.next=12;break}if(s=o.value,!n.getRange().addressInRange(s)){e.next=10;break}return l=this.fetchCellOrCreateEmpty(s),e.next=10,[s,l];case 10:e.next=4;break;case 12:e.next=17;break;case 14:e.prev=14,e.t0=e.catch(2),i.e(e.t0);case 17:return e.prev=17,i.f(),e.finish(17);case 20:case"end":return e.stop()}}),e,this,[[2,14,17,20]])}))},{key:"adjacentArrayVertices",value:_regeneratorRuntime$8().mark((function e(t){var n,r,a,i;return _regeneratorRuntime$8().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=this.graph.adjacentNodes(t),r=_createForOfIteratorHelper$r(n),e.prev=2,r.s();case 4:if((a=r.n()).done){e.next=11;break}if(!((i=a.value)instanceof FormulaVertex||i instanceof RangeVertex)){e.next=9;break}return e.next=9,i;case 9:e.next=4;break;case 11:e.next=16;break;case 13:e.prev=13,e.t0=e.catch(2),r.e(e.t0);case 16:return e.prev=16,r.f(),e.finish(16);case 19:case"end":return e.stop()}}),e,this,[[2,13,16,19]])}))},{key:"addStructuralNodesToChangeSet",value:function(){var e,t=_createForOfIteratorHelper$r(this.graph.specialNodesStructuralChanges);try{for(t.s();!(e=t.n()).done;){var n=e.value;this.graph.markNodeAsSpecialRecentlyChanged(n)}}catch(e){t.e(e)}finally{t.f()}}},{key:"fixRangesWhenAddingRows",value:function(e,t,n){for(var r=0,a=Array.from(this.rangeMapping.rangesInSheet(e));r0;){var n=t.values().next().value;t.delete(n),this.graph.hasNode(n)&&0===this.graph.adjacentNodesCount(n)&&((n instanceof RangeVertex||n instanceof EmptyCellVertex)&&this.graph.removeNode(n).forEach((function(e){return t.add(e)})),n instanceof RangeVertex?this.rangeMapping.removeRange(n):n instanceof EmptyCellVertex&&this.addressMapping.removeCell(n.address))}}}],[{key:"buildEmpty",value:function(t,n,r,a,i){return new e(new AddressMapping(n.chooseAddressMappingPolicy),new RangeMapping,new SheetMapping(n.translationPackage),new ArrayMapping,i,t,r,a)}}]),e}();function _classCallCheck$1k(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1k(e,t){for(var n=0;nthis.OR([{ALT:()=>this.SUBRULE(this.booleanExpression)},{ALT:EMPTY_ALT(buildEmptyArgAst())}]))),this.procedureExpression=this.RULE("procedureExpression",(()=>{var e;const t=this.CONSUME(ProcedureName),n=t.image.toUpperCase().slice(0,-1),r=null!==(e=this.lexerConfig.functionMapping[n])&&void 0!==e?e:n,a=[];let i=this.SUBRULE(this.booleanExpressionOrEmpty);this.MANY((()=>{var e;const t=this.CONSUME(this.lexerConfig.ArgSeparator);i.type===AstNodeType.EMPTY&&(i.leadingWhitespace=null===(e=t.leadingWhitespace)||void 0===e?void 0:e.image),a.push(i),i=this.SUBRULE2(this.booleanExpressionOrEmpty)})),a.push(i),1===a.length&&a[0].type===AstNodeType.EMPTY&&(a.length=0);const s=this.CONSUME(RParen);return buildProcedureAst(r,a,t.leadingWhitespace,s.leadingWhitespace)})),this.namedExpressionExpression=this.RULE("namedExpressionExpression",(()=>{const e=this.CONSUME(NamedExpression);return buildNamedExpressionAst(e.image,e.leadingWhitespace)})),this.offsetProcedureExpression=this.RULE("offsetProcedureExpression",(()=>{const e=[];return this.CONSUME(this.lexerConfig.OffsetProcedureName),this.CONSUME(LParen),this.MANY_SEP({SEP:this.lexerConfig.ArgSeparator,DEF:()=>{e.push(this.SUBRULE(this.booleanExpression))}}),this.CONSUME(RParen),this.handleOffsetHeuristic(e)})),this.columnRangeExpression=this.RULE("columnRangeExpression",(()=>{const e=this.CONSUME(ColumnRange),[t,n]=e.image.split(":"),r=this.ACTION((()=>columnAddressFromString(this.sheetMapping,t,this.formulaAddress))),a=this.ACTION((()=>columnAddressFromString(this.sheetMapping,n,this.formulaAddress)));if(void 0===r||void 0===a)return buildCellErrorAst(new CellError(ErrorType.REF));if(r.exceedsSheetSizeLimits(this.lexerConfig.maxColumns)||a.exceedsSheetSizeLimits(this.lexerConfig.maxColumns))return buildErrorWithRawInputAst(e.image,new CellError(ErrorType.NAME),e.leadingWhitespace);if(void 0===r.sheet&&void 0!==a.sheet)return this.parsingError(ParsingErrorType.ParserError,"Malformed range expression");const{firstEnd:i,secondEnd:s,sheetRefType:o}=FormulaParser.fixSheetIdsForRangeEnds(r,a),{start:l,end:u}=this.orderColumnRangeEnds(i,s);return buildColumnRangeAst(l,u,o,e.leadingWhitespace)})),this.rowRangeExpression=this.RULE("rowRangeExpression",(()=>{const e=this.CONSUME(RowRange),[t,n]=e.image.split(":"),r=this.ACTION((()=>rowAddressFromString(this.sheetMapping,t,this.formulaAddress))),a=this.ACTION((()=>rowAddressFromString(this.sheetMapping,n,this.formulaAddress)));if(void 0===r||void 0===a)return buildCellErrorAst(new CellError(ErrorType.REF));if(r.exceedsSheetSizeLimits(this.lexerConfig.maxRows)||a.exceedsSheetSizeLimits(this.lexerConfig.maxRows))return buildErrorWithRawInputAst(e.image,new CellError(ErrorType.NAME),e.leadingWhitespace);if(void 0===r.sheet&&void 0!==a.sheet)return this.parsingError(ParsingErrorType.ParserError,"Malformed range expression");const{firstEnd:i,secondEnd:s,sheetRefType:o}=FormulaParser.fixSheetIdsForRangeEnds(r,a),{start:l,end:u}=this.orderRowRangeEnds(i,s);return buildRowRangeAst(l,u,o,e.leadingWhitespace)})),this.cellReference=this.RULE("cellReference",(()=>{const e=this.CONSUME(CellReference),t=this.ACTION((()=>cellAddressFromString(this.sheetMapping,e.image,this.formulaAddress)));return void 0===t?buildErrorWithRawInputAst(e.image,new CellError(ErrorType.REF),e.leadingWhitespace):t.exceedsSheetSizeLimits(this.lexerConfig.maxColumns,this.lexerConfig.maxRows)?buildErrorWithRawInputAst(e.image,new CellError(ErrorType.NAME),e.leadingWhitespace):buildCellReferenceAst(t,e.leadingWhitespace)})),this.endRangeReference=this.RULE("endRangeReference",(e=>{var t;const n=this.CONSUME(CellReference),r=this.ACTION((()=>cellAddressFromString(this.sheetMapping,e.image,this.formulaAddress))),a=this.ACTION((()=>cellAddressFromString(this.sheetMapping,n.image,this.formulaAddress)));return void 0===r||void 0===a?this.ACTION((()=>buildErrorWithRawInputAst(`${e.image}:${n.image}`,new CellError(ErrorType.REF),e.leadingWhitespace))):r.exceedsSheetSizeLimits(this.lexerConfig.maxColumns,this.lexerConfig.maxRows)||a.exceedsSheetSizeLimits(this.lexerConfig.maxColumns,this.lexerConfig.maxRows)?this.ACTION((()=>buildErrorWithRawInputAst(`${e.image}:${n.image}`,new CellError(ErrorType.NAME),e.leadingWhitespace))):this.buildCellRange(r,a,null===(t=e.leadingWhitespace)||void 0===t?void 0:t.image)})),this.endOfRangeExpression=this.RULE("endOfRangeExpression",(e=>this.OR([{ALT:()=>this.SUBRULE(this.endRangeReference,{ARGS:[e]})},{ALT:()=>{var t;const n=this.SUBRULE(this.offsetProcedureExpression),r=this.ACTION((()=>cellAddressFromString(this.sheetMapping,e.image,this.formulaAddress)));return void 0===r?buildCellErrorAst(new CellError(ErrorType.REF)):n.type===AstNodeType.CELL_REFERENCE?this.buildCellRange(r,n.reference,null===(t=e.leadingWhitespace)||void 0===t?void 0:t.image):this.parsingError(ParsingErrorType.RangeOffsetNotAllowed,"Range offset not allowed here")}}]))),this.cellRangeExpression=this.RULE("cellRangeExpression",(()=>{const e=this.CONSUME(CellReference);return this.CONSUME2(RangeSeparator),this.SUBRULE(this.endOfRangeExpression,{ARGS:[e]})})),this.endRangeWithOffsetStartReference=this.RULE("endRangeWithOffsetStartReference",(e=>{const t=this.CONSUME(CellReference),n=this.ACTION((()=>cellAddressFromString(this.sheetMapping,t.image,this.formulaAddress)));return void 0===n?this.ACTION((()=>buildCellErrorAst(new CellError(ErrorType.REF)))):this.buildCellRange(e.reference,n,e.leadingWhitespace)})),this.endOfRangeWithOffsetStartExpression=this.RULE("endOfRangeWithOffsetStartExpression",(e=>this.OR([{ALT:()=>this.SUBRULE(this.endRangeWithOffsetStartReference,{ARGS:[e]})},{ALT:()=>{const t=this.SUBRULE(this.offsetProcedureExpression);return t.type===AstNodeType.CELL_REFERENCE?this.buildCellRange(e.reference,t.reference,e.leadingWhitespace):this.parsingError(ParsingErrorType.RangeOffsetNotAllowed,"Range offset not allowed here")}}]))),this.offsetExpression=this.RULE("offsetExpression",(()=>{const e=this.SUBRULE(this.offsetProcedureExpression);let t;return this.OPTION((()=>{this.CONSUME(RangeSeparator),t=e.type===AstNodeType.CELL_RANGE?this.parsingError(ParsingErrorType.RangeOffsetNotAllowed,"Range offset not allowed here"):this.SUBRULE(this.endOfRangeWithOffsetStartExpression,{ARGS:[e]})})),void 0!==t?t:e})),this.insideArrayExpression=this.RULE("insideArrayExpression",(()=>{const e=[[]];return e[e.length-1].push(this.SUBRULE(this.booleanExpression)),this.MANY((()=>{this.OR([{ALT:()=>{this.CONSUME(this.lexerConfig.ArrayColSeparator),e[e.length-1].push(this.SUBRULE2(this.booleanExpression))}},{ALT:()=>{this.CONSUME(this.lexerConfig.ArrayRowSeparator),e.push([]),e[e.length-1].push(this.SUBRULE3(this.booleanExpression))}}])})),buildArrayAst(e)})),this.parenthesisExpression=this.RULE("parenthesisExpression",(()=>{const e=this.CONSUME(LParen),t=this.SUBRULE(this.booleanExpression),n=this.CONSUME(RParen);return buildParenthesisAst(t,e.leadingWhitespace,n.leadingWhitespace)})),this.arrayExpression=this.RULE("arrayExpression",(()=>this.OR([{ALT:()=>{const e=this.CONSUME(ArrayLParen),t=this.SUBRULE(this.insideArrayExpression),n=this.CONSUME(ArrayRParen);return buildArrayAst(t.args,e.leadingWhitespace,n.leadingWhitespace)}},{ALT:()=>this.SUBRULE(this.parenthesisExpression)}]))),this.numericStringToNumber=e=>{const t=e.replace(this.lexerConfig.decimalSeparator,".");return Number(t)},this.positiveAtomicExpression=this.RULE("positiveAtomicExpression",(()=>{var e;return this.OR(null!==(e=this.atomicExpCache)&&void 0!==e?e:this.atomicExpCache=[{ALT:()=>this.SUBRULE(this.arrayExpression)},{ALT:()=>this.SUBRULE(this.cellRangeExpression)},{ALT:()=>this.SUBRULE(this.columnRangeExpression)},{ALT:()=>this.SUBRULE(this.rowRangeExpression)},{ALT:()=>this.SUBRULE(this.offsetExpression)},{ALT:()=>this.SUBRULE(this.cellReference)},{ALT:()=>this.SUBRULE(this.procedureExpression)},{ALT:()=>this.SUBRULE(this.namedExpressionExpression)},{ALT:()=>{const e=this.CONSUME(this.lexerConfig.NumberLiteral);return buildNumberAst(this.numericStringToNumber(e.image),e.leadingWhitespace)}},{ALT:()=>{const e=this.CONSUME(StringLiteral);return buildStringAst(e)}},{ALT:()=>{const e=this.CONSUME(ErrorLiteral),t=e.image.toUpperCase(),n=this.lexerConfig.errorMapping[t];return n?buildCellErrorAst(new CellError(n),e.leadingWhitespace):this.parsingError(ParsingErrorType.ParserError,"Unknown error literal")}}])})),this.rightUnaryOpAtomicExpression=this.RULE("rightUnaryOpAtomicExpression",(()=>{const e=this.SUBRULE(this.positiveAtomicExpression),t=this.OPTION((()=>this.CONSUME(PercentOp)));return t?buildPercentOpAst(e,t.leadingWhitespace):e})),this.atomicExpression=this.RULE("atomicExpression",(()=>this.OR([{ALT:()=>{const e=this.CONSUME(AdditionOp),t=this.SUBRULE(this.atomicExpression);return tokenMatcher(e,PlusOp)?buildPlusUnaryOpAst(t,e.leadingWhitespace):tokenMatcher(e,MinusOp)?buildMinusUnaryOpAst(t,e.leadingWhitespace):(this.customParsingError=parsingError(ParsingErrorType.ParserError,"Mismatched token type"),this.customParsingError)}},{ALT:()=>this.SUBRULE2(this.rightUnaryOpAtomicExpression)}]))),this.powerExpression=this.RULE("powerExpression",(()=>{let e=this.SUBRULE(this.atomicExpression);return this.MANY((()=>{const t=this.CONSUME(PowerOp),n=this.SUBRULE2(this.atomicExpression);tokenMatcher(t,PowerOp)?e=buildPowerOpAst(e,n,t.leadingWhitespace):this.ACTION((()=>{throw Error("Operator not supported")}))})),e})),this.multiplicationExpression=this.RULE("multiplicationExpression",(()=>{let e=this.SUBRULE(this.powerExpression);return this.MANY((()=>{const t=this.CONSUME(MultiplicationOp),n=this.SUBRULE2(this.powerExpression);tokenMatcher(t,TimesOp)?e=buildTimesOpAst(e,n,t.leadingWhitespace):tokenMatcher(t,DivOp)?e=buildDivOpAst(e,n,t.leadingWhitespace):this.ACTION((()=>{throw Error("Operator not supported")}))})),e})),this.additionExpression=this.RULE("additionExpression",(()=>{let e=this.SUBRULE(this.multiplicationExpression);return this.MANY((()=>{const t=this.CONSUME(AdditionOp),n=this.SUBRULE2(this.multiplicationExpression);tokenMatcher(t,PlusOp)?e=buildPlusOpAst(e,n,t.leadingWhitespace):tokenMatcher(t,MinusOp)?e=buildMinusOpAst(e,n,t.leadingWhitespace):this.ACTION((()=>{throw Error("Operator not supported")}))})),e})),this.concatenateExpression=this.RULE("concatenateExpression",(()=>{let e=this.SUBRULE(this.additionExpression);return this.MANY((()=>{const t=this.CONSUME(ConcatenateOp),n=this.SUBRULE2(this.additionExpression);e=buildConcatenateOpAst(e,n,t.leadingWhitespace)})),e})),this.booleanExpression=this.RULE("booleanExpression",(()=>{let e=this.SUBRULE(this.concatenateExpression);return this.MANY((()=>{const t=this.CONSUME(BooleanOp),n=this.SUBRULE2(this.concatenateExpression);tokenMatcher(t,EqualsOp)?e=buildEqualsOpAst(e,n,t.leadingWhitespace):tokenMatcher(t,NotEqualOp)?e=buildNotEqualOpAst(e,n,t.leadingWhitespace):tokenMatcher(t,GreaterThanOp)?e=buildGreaterThanOpAst(e,n,t.leadingWhitespace):tokenMatcher(t,LessThanOp)?e=buildLessThanOpAst(e,n,t.leadingWhitespace):tokenMatcher(t,GreaterThanOrEqualOp)?e=buildGreaterThanOrEqualOpAst(e,n,t.leadingWhitespace):tokenMatcher(t,LessThanOrEqualOp)?e=buildLessThanOrEqualOpAst(e,n,t.leadingWhitespace):this.ACTION((()=>{throw Error("Operator not supported")}))})),e})),this.formula=this.RULE("formula",(()=>(this.CONSUME(EqualsOp),this.SUBRULE(this.booleanExpression)))),this.lexerConfig=e,this.sheetMapping=t,this.formulaAddress=simpleCellAddress(0,0,0),this.performSelfAnalysis()}parseFromTokens(e,t){this.input=e;let n=this.formulaWithContext(t),r=[];return this.customParsingError&&r.push(this.customParsingError),r=r.concat(this.errors.map((e=>({type:ParsingErrorType.ParserError,message:e.message})))),r.length>0&&(n=buildParsingErrorAst()),{ast:n,errors:r}}reset(){super.reset(),this.customParsingError=void 0}formulaWithContext(e){return this.formulaAddress=e,this.formula()}buildCellRange(e,t,n){if(void 0===e.sheet&&void 0!==t.sheet)return this.parsingError(ParsingErrorType.ParserError,"Malformed range expression");const{firstEnd:r,secondEnd:a,sheetRefType:i}=FormulaParser.fixSheetIdsForRangeEnds(e,t),{start:s,end:o}=this.orderCellRangeEnds(r,a);return buildCellRangeAst(s,o,i,n)}static fixSheetIdsForRangeEnds(e,t){const n=FormulaParser.rangeSheetReferenceType(e.sheet,t.sheet);return{firstEnd:e,secondEnd:void 0!==e.sheet&&void 0===t.sheet?t.withSheet(e.sheet):t,sheetRefType:n}}orderCellRangeEnds(e,t){const n=[e,t],[r,a]=n.map((e=>e.toColumnAddress())).sort(ColumnAddress.compareByAbsoluteAddress(this.formulaAddress)),[i,s]=n.map((e=>e.toRowAddress())).sort(RowAddress.compareByAbsoluteAddress(this.formulaAddress)),[o,l]=n.map((e=>e.sheet)).sort(FormulaParser.compareSheetIds.bind(this));return{start:CellAddress.fromColAndRow(r,i,o),end:CellAddress.fromColAndRow(a,s,l)}}orderColumnRangeEnds(e,t){const n=[e,t],[r,a]=n.sort(ColumnAddress.compareByAbsoluteAddress(this.formulaAddress)),[i,s]=n.map((e=>e.sheet)).sort(FormulaParser.compareSheetIds.bind(this));return{start:new ColumnAddress(r.type,r.col,i),end:new ColumnAddress(a.type,a.col,s)}}orderRowRangeEnds(e,t){const n=[e,t],[r,a]=n.sort(RowAddress.compareByAbsoluteAddress(this.formulaAddress)),[i,s]=n.map((e=>e.sheet)).sort(FormulaParser.compareSheetIds.bind(this));return{start:new RowAddress(r.type,r.row,i),end:new RowAddress(a.type,a.row,s)}}static compareSheetIds(e,t){return(e=null!=e?e:1/0)-(t=null!=t?t:1/0)}handleOffsetHeuristic(e){const t=e[0];if(t.type!==AstNodeType.CELL_REFERENCE)return this.parsingError(ParsingErrorType.StaticOffsetError,"First argument to OFFSET is not a reference");const n=e[1];let r;if(n.type===AstNodeType.NUMBER&&Number.isInteger(n.value))r=n.value;else if(n.type===AstNodeType.PLUS_UNARY_OP&&n.value.type===AstNodeType.NUMBER&&Number.isInteger(n.value.value))r=n.value.value;else{if(n.type!==AstNodeType.MINUS_UNARY_OP||n.value.type!==AstNodeType.NUMBER||!Number.isInteger(n.value.value))return this.parsingError(ParsingErrorType.StaticOffsetError,"Second argument to OFFSET is not a static number");r=-n.value.value}const a=e[2];let i;if(a.type===AstNodeType.NUMBER&&Number.isInteger(a.value))i=a.value;else if(a.type===AstNodeType.PLUS_UNARY_OP&&a.value.type===AstNodeType.NUMBER&&Number.isInteger(a.value.value))i=a.value.value;else{if(a.type!==AstNodeType.MINUS_UNARY_OP||a.value.type!==AstNodeType.NUMBER||!Number.isInteger(a.value.value))return this.parsingError(ParsingErrorType.StaticOffsetError,"Third argument to OFFSET is not a static number");i=-a.value.value}const s=e[3];let o;if(void 0===s)o=1;else{if(s.type!==AstNodeType.NUMBER)return this.parsingError(ParsingErrorType.StaticOffsetError,"Fourth argument to OFFSET is not a static number");if(o=s.value,o<1)return this.parsingError(ParsingErrorType.StaticOffsetError,"Fourth argument to OFFSET is too small number");if(!Number.isInteger(o))return this.parsingError(ParsingErrorType.StaticOffsetError,"Fourth argument to OFFSET is not integer")}const l=e[4];let u;if(void 0===l)u=1;else{if(l.type!==AstNodeType.NUMBER)return this.parsingError(ParsingErrorType.StaticOffsetError,"Fifth argument to OFFSET is not a static number");if(u=l.value,u<1)return this.parsingError(ParsingErrorType.StaticOffsetError,"Fifth argument to OFFSET is too small number");if(!Number.isInteger(u))return this.parsingError(ParsingErrorType.StaticOffsetError,"Fifth argument to OFFSET is not integer")}const c=new CellAddress(t.reference.col+i,t.reference.row+r,t.reference.type);let p=c.col,d=c.row;if(t.reference.type!==CellReferenceType.CELL_REFERENCE_RELATIVE&&t.reference.type!==CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL||(d+=this.formulaAddress.row),t.reference.type!==CellReferenceType.CELL_REFERENCE_RELATIVE&&t.reference.type!==CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW||(p+=this.formulaAddress.col),p<0||d<0)return buildCellErrorAst(new CellError(ErrorType.REF,ErrorMessage.OutOfSheet));if(1===u&&1===o)return buildCellReferenceAst(c);{const e=new CellAddress(c.col+u-1,c.row+o-1,c.type);return buildCellRangeAst(c,e,RangeSheetReferenceType.RELATIVE)}}parsingError(e,t){return this.customParsingError=parsingError(e,t),buildParsingErrorAst()}static rangeSheetReferenceType(e,t){return void 0===e?RangeSheetReferenceType.RELATIVE:void 0===t?RangeSheetReferenceType.START_ABSOLUTE:RangeSheetReferenceType.BOTH_ABSOLUTE}}class FormulaLexer{constructor(e){this.lexerConfig=e,this.lexer=new Lexer(e.allTokens,{ensureOptimizations:!0})}tokenizeFormula(e){const t=this.lexer.tokenize(e);let n=t.tokens;return n=this.trimTrailingWhitespaces(n),n=this.skipWhitespacesInsideRanges(n),n=this.skipWhitespacesBeforeArgSeparators(n),t.tokens=n,t}skipWhitespacesInsideRanges(e){return FormulaLexer.filterTokensByNeighbors(e,((e,t,n)=>(tokenMatcher(e,CellReference)||tokenMatcher(e,RangeSeparator))&&tokenMatcher(t,this.lexerConfig.WhiteSpace)&&(tokenMatcher(n,CellReference)||tokenMatcher(n,RangeSeparator))))}skipWhitespacesBeforeArgSeparators(e){return FormulaLexer.filterTokensByNeighbors(e,((e,t,n)=>!tokenMatcher(e,this.lexerConfig.ArgSeparator)&&tokenMatcher(t,this.lexerConfig.WhiteSpace)&&tokenMatcher(n,this.lexerConfig.ArgSeparator)))}static filterTokensByNeighbors(e,t){if(e.length<3)return e;let n=0;const r=[e[n++]];for(;n0&&tokenMatcher(e[e.length-1],this.lexerConfig.WhiteSpace)&&e.pop(),e}} /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */var ValueCellVertex=function(){function e(t,n){_classCallCheck$1j(this,e),this.parsedValue=t,this.rawValue=n}return _createClass$1j(e,[{key:"getValues",value:function(){return{parsedValue:this.parsedValue,rawValue:this.rawValue}}},{key:"setValues",value:function(e){this.parsedValue=e.parsedValue,this.rawValue=e.rawValue}},{key:"getCellValue",value:function(){return this.parsedValue}},{key:"setCellValue",value:function(e){throw"SetCellValue is deprecated for ValueCellVertex"}}]),e}();function _classCallCheck$1i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1i(e,t){for(var n=0;n=0;--a){var i=this.tryEntries[a],o=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev=0;--r){var a=this.tryEntries[r];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),C(n),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:S(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),c}},e}function _slicedToArray$k(e,t){return _arrayWithHoles$k(e)||_iterableToArrayLimit$k(e,t)||_unsupportedIterableToArray$z(e,t)||_nonIterableRest$k()}function _nonIterableRest$k(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArrayLimit$k(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,a,i=[],o=!0,s=!1;try{for(n=n.call(e);!(o=(r=n.next()).done)&&(i.push(r.value),!t||i.length!==t);o=!0);}catch(e){s=!0,a=e}finally{try{o||null==n.return||n.return()}finally{if(s)throw a}}return i}}function _arrayWithHoles$k(e){if(Array.isArray(e))return e}function _createForOfIteratorHelper$q(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$z(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$z(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$z(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$z(e,t):void 0}}function _arrayLikeToArray$z(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e&&(r.set(i+t,a),n.delete(i))})),r.forEach((function(e,t){n.set(t,e)}))})),this.height+=t}},{key:"addColumns",value:function(e,t){var n=this,r=new Map;this.mapping.forEach((function(a,i){i>=e&&(r.set(i+t,a),n.mapping.delete(i))})),r.forEach((function(e,t){n.mapping.set(t,e)})),this.width+=t}},{key:"removeRows",value:function(e){this.mapping.forEach((function(t){var n=new Map;t.forEach((function(r,a){a>=e.rowStart&&(t.delete(a),a>e.rowEnd&&n.set(a-e.numberOfRows,r))})),n.forEach((function(e,n){t.set(n,e)}))}));var t=Math.min(this.height-1,e.rowEnd),n=Math.max(0,t-e.rowStart+1);this.height=Math.max(0,this.height-n)}},{key:"removeColumns",value:function(e){var t=this,n=new Map;this.mapping.forEach((function(r,a){a>=e.columnStart&&(t.mapping.delete(a),a>e.columnEnd&&n.set(a-e.numberOfColumns,r))})),n.forEach((function(e,n){t.mapping.set(n,e)}));var r=Math.min(this.width-1,e.columnEnd),a=Math.max(0,r-e.columnStart+1);this.width=Math.max(0,this.width-a)}},{key:"getEntries",value:_regeneratorRuntime$7().mark((function e(t){var n,r,a,i,o,s,l,u,c,p;return _regeneratorRuntime$7().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=_createForOfIteratorHelper$q(this.mapping),e.prev=1,n.s();case 3:if((r=n.n()).done){e.next=24;break}a=_slicedToArray$k(r.value,2),i=a[0],o=a[1],s=_createForOfIteratorHelper$q(o),e.prev=6,s.s();case 8:if((l=s.n()).done){e.next=14;break}return u=_slicedToArray$k(l.value,2),c=u[0],p=u[1],e.next=12,[simpleCellAddress(t,i,c),p];case 12:e.next=8;break;case 14:e.next=19;break;case 16:e.prev=16,e.t0=e.catch(6),s.e(e.t0);case 19:return e.prev=19,s.f(),e.finish(19);case 22:e.next=3;break;case 24:e.next=29;break;case 26:e.prev=26,e.t1=e.catch(1),n.e(e.t1);case 29:return e.prev=29,n.f(),e.finish(29);case 32:case"end":return e.stop()}}),e,this,[[1,26,29,32],[6,16,19,22]])}))},{key:"verticesFromColumn",value:_regeneratorRuntime$7().mark((function e(t){var n,r,a,i,o;return _regeneratorRuntime$7().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(void 0!==(n=this.mapping.get(t))){e.next=3;break}return e.abrupt("return");case 3:r=_createForOfIteratorHelper$q(n),e.prev=4,r.s();case 6:if((a=r.n()).done){e.next=12;break}return(i=_slicedToArray$k(a.value,2))[0],o=i[1],e.next=10,o;case 10:e.next=6;break;case 12:e.next=17;break;case 14:e.prev=14,e.t0=e.catch(4),r.e(e.t0);case 17:return e.prev=17,r.f(),e.finish(17);case 20:case"end":return e.stop()}}),e,this,[[4,14,17,20]])}))},{key:"verticesFromRow",value:_regeneratorRuntime$7().mark((function e(t){var n,r,a,i;return _regeneratorRuntime$7().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=_createForOfIteratorHelper$q(this.mapping.values()),e.prev=1,n.s();case 3:if((r=n.n()).done){e.next=11;break}if(a=r.value,void 0===(i=a.get(t))){e.next=9;break}return e.next=9,i;case 9:e.next=3;break;case 11:e.next=16;break;case 13:e.prev=13,e.t0=e.catch(1),n.e(e.t0);case 16:return e.prev=16,n.f(),e.finish(16);case 19:case"end":return e.stop()}}),e,this,[[1,13,16,19]])}))},{key:"verticesFromColumnsSpan",value:_regeneratorRuntime$7().mark((function e(t){var n,r,a,i,o,s,l,u;return _regeneratorRuntime$7().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=_createForOfIteratorHelper$q(t.columns()),e.prev=1,n.s();case 3:if((r=n.n()).done){e.next=27;break}if(a=r.value,void 0!==(i=this.mapping.get(a))){e.next=8;break}return e.abrupt("continue",25);case 8:o=_createForOfIteratorHelper$q(i),e.prev=9,o.s();case 11:if((s=o.n()).done){e.next=17;break}return(l=_slicedToArray$k(s.value,2))[0],u=l[1],e.next=15,u;case 15:e.next=11;break;case 17:e.next=22;break;case 19:e.prev=19,e.t0=e.catch(9),o.e(e.t0);case 22:return e.prev=22,o.f(),e.finish(22);case 25:e.next=3;break;case 27:e.next=32;break;case 29:e.prev=29,e.t1=e.catch(1),n.e(e.t1);case 32:return e.prev=32,n.f(),e.finish(32);case 35:case"end":return e.stop()}}),e,this,[[1,29,32,35],[9,19,22,25]])}))},{key:"verticesFromRowsSpan",value:_regeneratorRuntime$7().mark((function e(t){var n,r,a,i,o,s,l;return _regeneratorRuntime$7().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=_createForOfIteratorHelper$q(this.mapping.values()),e.prev=1,n.s();case 3:if((r=n.n()).done){e.next=26;break}a=r.value,i=_createForOfIteratorHelper$q(t.rows()),e.prev=6,i.s();case 8:if((o=i.n()).done){e.next=16;break}if(s=o.value,void 0===(l=a.get(s))){e.next=14;break}return e.next=14,l;case 14:e.next=8;break;case 16:e.next=21;break;case 18:e.prev=18,e.t0=e.catch(6),i.e(e.t0);case 21:return e.prev=21,i.f(),e.finish(21);case 24:e.next=3;break;case 26:e.next=31;break;case 28:e.prev=28,e.t1=e.catch(1),n.e(e.t1);case 31:return e.prev=31,n.f(),e.finish(31);case 34:case"end":return e.stop()}}),e,this,[[1,28,31,34],[6,18,21,24]])}))},{key:"entriesFromRowsSpan",value:_regeneratorRuntime$7().mark((function e(t){var n,r,a,i,o,s,l,u,c;return _regeneratorRuntime$7().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=_createForOfIteratorHelper$q(this.mapping.entries()),e.prev=1,n.s();case 3:if((r=n.n()).done){e.next=26;break}a=_slicedToArray$k(r.value,2),i=a[0],o=a[1],s=_createForOfIteratorHelper$q(t.rows()),e.prev=6,s.s();case 8:if((l=s.n()).done){e.next=16;break}if(u=l.value,void 0===(c=o.get(u))){e.next=14;break}return e.next=14,[simpleCellAddress(t.sheet,i,u),c];case 14:e.next=8;break;case 16:e.next=21;break;case 18:e.prev=18,e.t0=e.catch(6),s.e(e.t0);case 21:return e.prev=21,s.f(),e.finish(21);case 24:e.next=3;break;case 26:e.next=31;break;case 28:e.prev=28,e.t1=e.catch(1),n.e(e.t1);case 31:return e.prev=31,n.f(),e.finish(31);case 34:case"end":return e.stop()}}),e,this,[[1,28,31,34],[6,18,21,24]])}))},{key:"entriesFromColumnsSpan",value:_regeneratorRuntime$7().mark((function e(t){var n,r,a,i,o,s,l,u,c;return _regeneratorRuntime$7().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=_createForOfIteratorHelper$q(t.columns()),e.prev=1,n.s();case 3:if((r=n.n()).done){e.next=26;break}if(a=r.value,void 0===(i=this.mapping.get(a))){e.next=24;break}o=_createForOfIteratorHelper$q(i.entries()),e.prev=8,o.s();case 10:if((s=o.n()).done){e.next=16;break}return l=_slicedToArray$k(s.value,2),u=l[0],c=l[1],e.next=14,[simpleCellAddress(t.sheet,a,u),c];case 14:e.next=10;break;case 16:e.next=21;break;case 18:e.prev=18,e.t0=e.catch(8),o.e(e.t0);case 21:return e.prev=21,o.f(),e.finish(21);case 24:e.next=3;break;case 26:e.next=31;break;case 28:e.prev=28,e.t1=e.catch(1),n.e(e.t1);case 31:return e.prev=31,n.f(),e.finish(31);case 34:case"end":return e.stop()}}),e,this,[[1,28,31,34],[8,18,21,24]])}))},{key:"vertices",value:_regeneratorRuntime$7().mark((function e(){var t,n,r,a,i,o,s,l;return _regeneratorRuntime$7().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=_createForOfIteratorHelper$q(this.mapping),e.prev=1,t.s();case 3:if((n=t.n()).done){e.next=25;break}(r=_slicedToArray$k(n.value,2))[0],a=r[1],i=_createForOfIteratorHelper$q(a),e.prev=6,i.s();case 8:if((o=i.n()).done){e.next=15;break}if((s=_slicedToArray$k(o.value,2))[0],void 0===(l=s[1])){e.next=13;break}return e.next=13,l;case 13:e.next=8;break;case 15:e.next=20;break;case 17:e.prev=17,e.t0=e.catch(6),i.e(e.t0);case 20:return e.prev=20,i.f(),e.finish(20);case 23:e.next=3;break;case 25:e.next=30;break;case 27:e.prev=27,e.t1=e.catch(1),t.e(e.t1);case 30:return e.prev=30,t.f(),e.finish(30);case 33:case"end":return e.stop()}}),e,this,[[1,27,30,33],[6,17,20,23]])}))}]),e}();function _typeof$$(e){return _typeof$$="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$$(e)}function _regeneratorRuntime$6(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */_regeneratorRuntime$6=function(){return e};var e={},t=Object.prototype,n=t.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},a=r.iterator||"@@iterator",i=r.asyncIterator||"@@asyncIterator",o=r.toStringTag||"@@toStringTag";function s(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{s({},"")}catch(e){s=function(e,t,n){return e[t]=n}}function l(e,t,n,r){var a=t&&t.prototype instanceof p?t:p,i=Object.create(a.prototype),o=new A(r||[]);return i._invoke=function(e,t,n){var r="suspendedStart";return function(a,i){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===a)throw i;return x()}for(n.method=a,n.arg=i;;){var o=n.delegate;if(o){var s=T(o,n);if(s){if(s===c)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var l=u(e,t,n);if("normal"===l.type){if(r=n.done?"completed":"suspendedYield",l.arg===c)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(r="completed",n.method="throw",n.arg=l.arg)}}}(e,n,o),i}function u(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}e.wrap=l;var c={};function p(){}function d(){}function m(){}var f={};s(f,a,(function(){return this}));var h=Object.getPrototypeOf,y=h&&h(h(S([])));y&&y!==t&&n.call(y,a)&&(f=y);var b=m.prototype=p.prototype=Object.create(f);function g(e){["next","throw","return"].forEach((function(t){s(e,t,(function(e){return this._invoke(t,e)}))}))}function v(e,t){function r(a,i,o,s){var l=u(e[a],e,i);if("throw"!==l.type){var c=l.arg,p=c.value;return p&&"object"==_typeof$$(p)&&n.call(p,"__await")?t.resolve(p.__await).then((function(e){r("next",e,o,s)}),(function(e){r("throw",e,o,s)})):t.resolve(p).then((function(e){c.value=e,o(c)}),(function(e){return r("throw",e,o,s)}))}s(l.arg)}var a;this._invoke=function(e,n){function i(){return new t((function(t,a){r(e,n,t,a)}))}return a=a?a.then(i,i):i()}}function T(e,t){var n=e.iterator[t.method];if(void 0===n){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,T(e,t),"throw"===t.method))return c;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return c}var r=u(n,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,c;var a=r.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,c):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,c)}function N(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function C(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function A(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(N,this),this.reset(!0)}function S(e){if(e){var t=e[a];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,i=function t(){for(;++r=0;--a){var i=this.tryEntries[a],o=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev=0;--r){var a=this.tryEntries[r];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),C(n),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:S(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),c}},e}function _toConsumableArray$9(e){return _arrayWithoutHoles$9(e)||_iterableToArray$9(e)||_unsupportedIterableToArray$y(e)||_nonIterableSpread$9()}function _nonIterableSpread$9(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray$y(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$y(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$y(e,t):void 0}}function _iterableToArray$9(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles$9(e){if(Array.isArray(e))return _arrayLikeToArray$y(e)}function _arrayLikeToArray$y(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);nvoid 0!==e?this.unparseAst(e,t):"")).join(this.config.functionArgSeparator),r=(this.config.translationPackage.isFunctionTranslated(e.procedureName)?this.config.translationPackage.getFunctionTranslation(e.procedureName):e.procedureName)+"("+n+imageWithWhitespace(")",e.internalWhitespace);return imageWithWhitespace(r,e.leadingWhitespace)}case AstNodeType.NAMED_EXPRESSION:return imageWithWhitespace((null===(n=this.namedExpressions.nearestNamedExpression(e.expressionName,t.sheet))||void 0===n?void 0:n.displayName)||e.expressionName,e.leadingWhitespace);case AstNodeType.CELL_REFERENCE:{let n;return n=void 0!==e.reference.sheet?this.unparseSheetName(e.reference.sheet)+"!":"",n+=null!==(r=e.reference.unparse(t))&&void 0!==r?r:this.config.translationPackage.getErrorTranslation(ErrorType.REF),imageWithWhitespace(n,e.leadingWhitespace)}case AstNodeType.COLUMN_RANGE:case AstNodeType.ROW_RANGE:case AstNodeType.CELL_RANGE:return imageWithWhitespace(this.formatRange(e,t),e.leadingWhitespace);case AstNodeType.PLUS_UNARY_OP:{const n=this.unparseAst(e.value,t);return imageWithWhitespace("+",e.leadingWhitespace)+n}case AstNodeType.MINUS_UNARY_OP:{const n=this.unparseAst(e.value,t);return imageWithWhitespace("-",e.leadingWhitespace)+n}case AstNodeType.PERCENT_OP:return this.unparseAst(e.value,t)+imageWithWhitespace("%",e.leadingWhitespace);case AstNodeType.ERROR:return imageWithWhitespace(this.config.translationPackage.getErrorTranslation(e.error?e.error.type:ErrorType.ERROR),e.leadingWhitespace);case AstNodeType.ERROR_WITH_RAW_INPUT:return imageWithWhitespace(e.rawInput,e.leadingWhitespace);case AstNodeType.PARENTHESIS:{const n="("+this.unparseAst(e.expression,t)+imageWithWhitespace(")",e.internalWhitespace);return imageWithWhitespace(n,e.leadingWhitespace)}case AstNodeType.ARRAY:{const n="{"+e.args.map((e=>e.map((e=>this.unparseAst(e,t))).join(this.config.arrayColumnSeparator))).join(this.config.arrayRowSeparator)+imageWithWhitespace("}",e.internalWhitespace);return imageWithWhitespace(n,e.leadingWhitespace)}default:{const n=this.unparseAst(e.left,t),r=this.unparseAst(e.right,t);return n+imageWithWhitespace(binaryOpTokenMap[e.type],e.leadingWhitespace)+r}}}unparseSheetName(e){const t=sheetIndexToString(e,this.sheetMappingFn);if(void 0===t)throw new NoSheetWithIdError(e);return t}formatRange(e,t){let n="",r="";void 0!==e.start.sheet&&e.sheetReferenceType!==RangeSheetReferenceType.RELATIVE&&(n=this.unparseSheetName(e.start.sheet)+"!"),void 0!==e.end.sheet&&e.sheetReferenceType===RangeSheetReferenceType.BOTH_ABSOLUTE&&(r=this.unparseSheetName(e.end.sheet)+"!");const a=e.start.unparse(t),i=e.end.unparse(t);return void 0===a||void 0===i?this.config.translationPackage.getErrorTranslation(ErrorType.REF):`${n}${a}:${r}${i}`}}function formatNumber(e,t){return e.toString().replace(".",t)} /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */var DetailedCellError=function(){function e(t,n,r){var a;_classCallCheck$1e(this,e),this.value=n,this.address=r,this.type=t.type,this.message=null!==(a=t.message)&&void 0!==a?a:""}return _createClass$1e(e,[{key:"toString",value:function(){return this.value}},{key:"valueOf",value:function(){return this.value}}]),e}(),uncurryThis$6=functionUncurryThis,defineBuiltIns$1=defineBuiltIns$3,getWeakData=internalMetadata.exports.getWeakData,anObject=anObject$k,isObject$2=isObject$o,anInstance=anInstance$4,iterate=iterate$5,ArrayIterationModule=arrayIteration,hasOwn=hasOwnProperty_1,InternalStateModule=internalState,setInternalState=InternalStateModule.set,internalStateGetterFor=InternalStateModule.getterFor,find=ArrayIterationModule.find,findIndex=ArrayIterationModule.findIndex,splice=uncurryThis$6([].splice),id=0,uncaughtFrozenStore=function(e){return e.frozen||(e.frozen=new UncaughtFrozenStore)},UncaughtFrozenStore=function(){this.entries=[]},findUncaughtFrozen=function(e,t){return find(e.entries,(function(e){return e[0]===t}))};UncaughtFrozenStore.prototype={get:function(e){var t=findUncaughtFrozen(this,e);if(t)return t[1]},has:function(e){return!!findUncaughtFrozen(this,e)},set:function(e,t){var n=findUncaughtFrozen(this,e);n?n[1]=t:this.entries.push([e,t])},delete:function(e){var t=findIndex(this.entries,(function(t){return t[0]===e}));return~t&&splice(this.entries,t,1),!!~t}};var collectionWeak$1={getConstructor:function(e,t,n,r){var a=e((function(e,a){anInstance(e,i),setInternalState(e,{type:t,id:id++,frozen:void 0}),null!=a&&iterate(a,e[r],{that:e,AS_ENTRIES:n})})),i=a.prototype,o=internalStateGetterFor(t),s=function(e,t,n){var r=o(e),a=getWeakData(anObject(t),!0);return!0===a?uncaughtFrozenStore(r).set(t,n):a[r.id]=n,e};return defineBuiltIns$1(i,{delete:function(e){var t=o(this);if(!isObject$2(e))return!1;var n=getWeakData(e);return!0===n?uncaughtFrozenStore(t).delete(e):n&&hasOwn(n,t.id)&&delete n[t.id]},has:function(e){var t=o(this);if(!isObject$2(e))return!1;var n=getWeakData(e);return!0===n?uncaughtFrozenStore(t).has(e):n&&hasOwn(n,t.id)}}),defineBuiltIns$1(i,n?{get:function(e){var t=o(this);if(isObject$2(e)){var n=getWeakData(e);return!0===n?uncaughtFrozenStore(t).get(e):n?n[t.id]:void 0}},set:function(e,t){return s(this,e,t)}}:{add:function(e){return s(this,e,!0)}}),a}},global$1=global$w,uncurryThis$5=functionUncurryThis,defineBuiltIns=defineBuiltIns$3,InternalMetadataModule=internalMetadata.exports,collection=collection$3,collectionWeak=collectionWeak$1,isObject$1=isObject$o,isExtensible=objectIsExtensible,enforceInternalState=internalState.enforce,NATIVE_WEAK_MAP=nativeWeakMap,IS_IE11=!global$1.ActiveXObject&&"ActiveXObject"in global$1,InternalWeakMap,wrapper=function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},$WeakMap=collection("WeakMap",wrapper,collectionWeak);if(NATIVE_WEAK_MAP&&IS_IE11){InternalWeakMap=collectionWeak.getConstructor(wrapper,"WeakMap",!0),InternalMetadataModule.enable();var WeakMapPrototype=$WeakMap.prototype,nativeDelete=uncurryThis$5(WeakMapPrototype.delete),nativeHas=uncurryThis$5(WeakMapPrototype.has),nativeGet=uncurryThis$5(WeakMapPrototype.get),nativeSet=uncurryThis$5(WeakMapPrototype.set);defineBuiltIns(WeakMapPrototype,{delete:function(e){if(isObject$1(e)&&!isExtensible(e)){var t=enforceInternalState(this);return t.frozen||(t.frozen=new InternalWeakMap),nativeDelete(this,e)||t.frozen.delete(e)}return nativeDelete(this,e)},has:function(e){if(isObject$1(e)&&!isExtensible(e)){var t=enforceInternalState(this);return t.frozen||(t.frozen=new InternalWeakMap),nativeHas(this,e)||t.frozen.has(e)}return nativeHas(this,e)},get:function(e){if(isObject$1(e)&&!isExtensible(e)){var t=enforceInternalState(this);return t.frozen||(t.frozen=new InternalWeakMap),nativeHas(this,e)?nativeGet(this,e):t.frozen.get(e)}return nativeGet(this,e)},set:function(e,t){if(isObject$1(e)&&!isExtensible(e)){var n=enforceInternalState(this);n.frozen||(n.frozen=new InternalWeakMap),nativeHas(this,e)?nativeSet(this,e,t):n.frozen.set(e,t)}else nativeSet(this,e,t);return this}})}var $$k=_export,uncurryThis$4=functionUncurryThis,notARegExp$1=notARegexp,requireObjectCoercible$3=requireObjectCoercible$b,toString$5=toString$i,correctIsRegExpLogic$1=correctIsRegexpLogic,stringIndexOf=uncurryThis$4("".indexOf);function _createForOfIteratorHelper$p(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$x(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$x(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$x(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$x(e,t):void 0}}function _arrayLikeToArray$x(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);nn)throw new ConfigValueTooBigError(t,n)}function configValueFromParamCheck(e,t,n,r){if(t(e))return e;if(void 0===e)return Config.defaultConfig[r];throw new ExpectedValueOfTypeError(n,r)}function configCheckIfParametersNotInConflict(){for(var e=new Map,t=arguments.length,n=new Array(t),r=0;r1&&i.push(s)}}catch(e){o.e(e)}finally{o.f()}if(i.length>0){i.forEach((function(e){return e.sort()}));var l=i.map((function(e){return"[".concat(e,"]")})).join("; ");throw new Error("Config initialization failed. Parameters in conflict: ".concat(l))}}function validateArgToType(e,t,n){if(_typeof$Z(e)!==t)throw new ExpectedValueOfTypeError(t,n)}$$k({target:"String",proto:!0,forced:!correctIsRegExpLogic$1("includes")},{includes:function(e){return!!~stringIndexOf(toString$5(requireObjectCoercible$3(this)),toString$5(notARegExp$1(e)),arguments.length>1?arguments[1]:void 0)}});var $$j=_export,uncurryThis$3=functionUncurryThis,getOwnPropertyDescriptor=objectGetOwnPropertyDescriptor.f,toLength$1=toLength$6,toString$4=toString$i,notARegExp=notARegexp,requireObjectCoercible$2=requireObjectCoercible$b,correctIsRegExpLogic=correctIsRegexpLogic,un$EndsWith=uncurryThis$3("".endsWith),slice=uncurryThis$3("".slice),min=Math.min,CORRECT_IS_REGEXP_LOGIC=correctIsRegExpLogic("endsWith"),MDN_POLYFILL_BUG=!CORRECT_IS_REGEXP_LOGIC&&!!function(){var e=getOwnPropertyDescriptor(String.prototype,"endsWith");return e&&!e.writable}(); + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class ParserWithCaching{constructor(e,t,n){this.config=e,this.functionRegistry=t,this.sheetMapping=n,this.statsCacheUsed=0,this.lexerConfig=buildLexerConfig(e),this.lexer=new FormulaLexer(this.lexerConfig),this.formulaParser=new FormulaParser(this.lexerConfig,this.sheetMapping),this.cache=new Cache(this.functionRegistry)}parse(e,t){const n=this.tokenizeFormula(e);if(n.errors.length>0){const e=n.errors.map((e=>({type:ParsingErrorType.LexingError,message:e.message})));return{ast:buildParsingErrorAst(),errors:e,hasVolatileFunction:!1,hasStructuralChangeFunction:!1,dependencies:[]}}const r=this.computeHashFromTokens(n.tokens,t);let a=this.cache.get(r);if(void 0!==a)++this.statsCacheUsed;else{const e=this.bindWhitespacesToTokens(n.tokens),i=this.formulaParser.parseFromTokens(e,t);if(i.errors.length>0)return Object.assign(Object.assign({},i),{hasVolatileFunction:!1,hasStructuralChangeFunction:!1,dependencies:[]});a=this.cache.set(r,i.ast)}const{ast:i,hasVolatileFunction:s,hasStructuralChangeFunction:o,relativeDependencies:l}=a;return{ast:i,errors:[],hasVolatileFunction:s,hasStructuralChangeFunction:o,dependencies:l}}fetchCachedResultForAst(e){const t=this.computeHashFromAst(e);return this.fetchCachedResult(t)}fetchCachedResult(e){const t=this.cache.get(e);if(void 0===t)throw new Error("There is no AST with such key in the cache");{const{ast:e,hasVolatileFunction:n,hasStructuralChangeFunction:r,relativeDependencies:a}=t;return{ast:e,errors:[],hasVolatileFunction:n,hasStructuralChangeFunction:r,dependencies:a}}}computeHashFromTokens(e,t){var n;let r="",a=0;for(;athis.computeHashOfAstNode(e))).join(this.config.functionArgSeparator),n=e.procedureName+"("+t+imageWithWhitespace(")",e.internalWhitespace);return imageWithWhitespace(n,e.leadingWhitespace)}case AstNodeType.CELL_REFERENCE:return imageWithWhitespace(e.reference.hash(!0),e.leadingWhitespace);case AstNodeType.COLUMN_RANGE:case AstNodeType.ROW_RANGE:case AstNodeType.CELL_RANGE:return imageWithWhitespace(e.start.hash(e.sheetReferenceType!==RangeSheetReferenceType.RELATIVE)+":"+e.end.hash(e.sheetReferenceType===RangeSheetReferenceType.BOTH_ABSOLUTE),e.leadingWhitespace);case AstNodeType.MINUS_UNARY_OP:return imageWithWhitespace("-"+this.computeHashOfAstNode(e.value),e.leadingWhitespace);case AstNodeType.PLUS_UNARY_OP:return imageWithWhitespace("+"+this.computeHashOfAstNode(e.value),e.leadingWhitespace);case AstNodeType.PERCENT_OP:return this.computeHashOfAstNode(e.value)+imageWithWhitespace("%",e.leadingWhitespace);case AstNodeType.ERROR:return imageWithWhitespace(this.config.translationPackage.getErrorTranslation(e.error?e.error.type:ErrorType.ERROR),e.leadingWhitespace);case AstNodeType.ERROR_WITH_RAW_INPUT:return imageWithWhitespace(e.rawInput,e.leadingWhitespace);case AstNodeType.ARRAY:return imageWithWhitespace("{"+e.args.map((e=>e.map((e=>this.computeHashOfAstNode(e))).join(","))).join(";")+imageWithWhitespace("}",e.internalWhitespace),e.leadingWhitespace);case AstNodeType.PARENTHESIS:{const t="("+this.computeHashOfAstNode(e.expression)+imageWithWhitespace(")",e.internalWhitespace);return imageWithWhitespace(t,e.leadingWhitespace)}default:return this.computeHashOfAstNode(e.left)+imageWithWhitespace(binaryOpTokenMap[e.type],e.leadingWhitespace)+this.computeHashOfAstNode(e.right)}}bindWhitespacesToTokens(e){const t=[],n=e[0];tokenMatcher(n,this.lexerConfig.WhiteSpace)||t.push(n);for(let n=1;n{switch(e.type){case AstNodeType.EMPTY:case AstNodeType.NUMBER:case AstNodeType.STRING:case AstNodeType.ERROR:return;case AstNodeType.NAMED_EXPRESSION:return void(r&&n.push(new NamedExpressionDependency(e.expressionName)));case AstNodeType.CELL_REFERENCE:return void(r&&n.push(new AddressDependency(e.reference)));case AstNodeType.CELL_RANGE:return void(r&&e.start.sheet===e.end.sheet&&n.push(new CellRangeDependency(e.start,e.end)));case AstNodeType.COLUMN_RANGE:return void(r&&e.start.sheet===e.end.sheet&&n.push(new ColumnRangeDependency(e.start,e.end)));case AstNodeType.ROW_RANGE:return void(r&&e.start.sheet===e.end.sheet&&n.push(new RowRangeDependency(e.start,e.end)));case AstNodeType.PERCENT_OP:case AstNodeType.PLUS_UNARY_OP:case AstNodeType.MINUS_UNARY_OP:return void collectDependenciesFn(e.value,t,n,!0);case AstNodeType.CONCATENATE_OP:case AstNodeType.EQUALS_OP:case AstNodeType.NOT_EQUAL_OP:case AstNodeType.LESS_THAN_OP:case AstNodeType.GREATER_THAN_OP:case AstNodeType.LESS_THAN_OR_EQUAL_OP:case AstNodeType.GREATER_THAN_OR_EQUAL_OP:case AstNodeType.MINUS_OP:case AstNodeType.PLUS_OP:case AstNodeType.TIMES_OP:case AstNodeType.DIV_OP:case AstNodeType.POWER_OP:return collectDependenciesFn(e.left,t,n,!0),void collectDependenciesFn(e.right,t,n,!0);case AstNodeType.PARENTHESIS:return void collectDependenciesFn(e.expression,t,n,r);case AstNodeType.FUNCTION_CALL:{const r=!t.doesFunctionNeedArgumentToBeComputed(e.procedureName);return void e.args.forEach((e=>collectDependenciesFn(e,t,n,r)))}}},collectDependencies=(e,t)=>{const n=new Array;return collectDependenciesFn(e,t,n,!0),n}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class AddressDependency{constructor(e){this.dependency=e}absolutize(e){return this.dependency.toSimpleCellAddress(e)}}class CellRangeDependency{constructor(e,t){this.start=e,this.end=t}absolutize(e){return new AbsoluteCellRange(this.start.toSimpleCellAddress(e),this.end.toSimpleCellAddress(e))}}class ColumnRangeDependency{constructor(e,t){this.start=e,this.end=t}absolutize(e){const t=this.start.toSimpleColumnAddress(e),n=this.end.toSimpleColumnAddress(e);return new AbsoluteColumnRange(t.sheet,t.col,n.col)}}class RowRangeDependency{constructor(e,t){this.start=e,this.end=t}absolutize(e){const t=this.start.toSimpleRowAddress(e),n=this.end.toSimpleRowAddress(e);return new AbsoluteRowRange(t.sheet,t.row,n.row)}}class NamedExpressionDependency{constructor(e){this.name=e}absolutize(e){return this}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class RowsSpan{constructor(e,t,n){if(this.sheet=e,this.rowStart=t,this.rowEnd=n,t<0)throw Error("Starting row cant be less than 0");if(nn?null:new RowsSpan(this.sheet,t,n)}firstRow(){return new RowsSpan(this.sheet,this.rowStart,this.rowStart)}}class ColumnsSpan{constructor(e,t,n){if(this.sheet=e,this.columnStart=t,this.columnEnd=n,t<0)throw Error("Starting column cant be less than 0");if(nn?null:new ColumnsSpan(this.sheet,t,n)}firstColumn(){return new ColumnsSpan(this.sheet,this.columnStart,this.columnStart)}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */const WRONG_RANGE_SIZE="AbsoluteCellRange: Wrong range size";function isSimpleCellRange(e){return!(!e||"object"!=typeof e&&"function"!=typeof e)&&("start"in e&&isSimpleCellAddress(e.start)&&"end"in e&&isSimpleCellAddress(e.end))}const simpleCellRange=(e,t)=>({start:e,end:t});class AbsoluteCellRange{constructor(e,t){if(e.sheet!==t.sheet)throw new SheetsNotEqual(e.sheet,t.sheet);this.start=simpleCellAddress(e.sheet,e.col,e.row),this.end=simpleCellAddress(t.sheet,t.col,t.row)}get sheet(){return this.start.sheet}static fromAst(e,t){return e.type===AstNodeType.CELL_RANGE?AbsoluteCellRange.fromCellRange(e,t):e.type===AstNodeType.COLUMN_RANGE?AbsoluteColumnRange.fromColumnRange(e,t):AbsoluteRowRange.fromRowRangeAst(e,t)}static fromAstOrUndef(e,t){try{return AbsoluteCellRange.fromAst(e,t)}catch(e){return}}static fromCellRange(e,t){return new AbsoluteCellRange(e.start.toSimpleCellAddress(t),e.end.toSimpleCellAddress(t))}static spanFrom(e,t,n){const r=AbsoluteCellRange.spanFromOrUndef(e,t,n);if(void 0===r)throw new Error(WRONG_RANGE_SIZE);return r}static spanFromOrUndef(e,t,n){if(!Number.isFinite(t)&&Number.isFinite(n)){if(0!==e.col)return;return new AbsoluteRowRange(e.sheet,e.row,e.row+n-1)}if(!Number.isFinite(n)&&Number.isFinite(t)){if(0!==e.row)return;return new AbsoluteColumnRange(e.sheet,e.col,e.col+t-1)}if(Number.isFinite(n)&&Number.isFinite(t))return new AbsoluteCellRange(e,simpleCellAddress(e.sheet,e.col+t-1,e.row+n-1))}static fromCoordinates(e,t,n,r,a){return new AbsoluteCellRange(simpleCellAddress(e,t,n),simpleCellAddress(e,r,a))}isFinite(){return Number.isFinite(this.size())}doesOverlap(e){return this.start.sheet==e.start.sheet&&(!(this.end.rowe.end.row)&&!(this.end.cole.end.col))}addressInRange(e){return this.sheet===e.sheet&&(this.start.row<=e.row&&this.end.row>=e.row&&this.start.col<=e.col&&this.end.col>=e.col)}columnInRange(e){return this.sheet===e.sheet&&(this.start.col<=e.col&&this.end.col>=e.col)}rowInRange(e){return this.sheet===e.sheet&&(this.start.row<=e.row&&this.end.row>=e.row)}containsRange(e){return this.addressInRange(e.start)&&this.addressInRange(e.end)}intersectionWith(e){if(this.sheet!==e.start.sheet)return;const t=Math.max(this.start.row,e.start.row),n=Math.min(this.end.row,e.end.row),r=Math.max(this.start.col,e.start.col),a=Math.min(this.end.col,e.end.col);return t>n||r>a?void 0:new AbsoluteCellRange(simpleCellAddress(this.sheet,r,t),simpleCellAddress(this.sheet,a,n))}includesRow(e){return this.start.row=e}includesColumn(e){return this.start.col=e}shiftByRows(e){this.start.row+=e,this.end.row+=e}expandByRows(e){this.end.row+=e}shiftByColumns(e){this.start.col+=e,this.end.col+=e}shifted(e,t){return AbsoluteCellRange.spanFrom(simpleCellAddress(this.sheet,this.start.col+e,this.start.row+t),this.width(),this.height())}expandByColumns(e){this.end.col+=e}moveToSheet(e){this.start.sheet=e,this.end.sheet=e}removeSpan(e){e instanceof RowsSpan?this.removeRows(e.start,e.end):this.removeColumns(e.start,e.end)}shouldBeRemoved(){return this.width()<=0||this.height()<=0}rangeWithSameWidth(e,t){return AbsoluteCellRange.spanFrom(simpleCellAddress(this.sheet,this.start.col,e),this.width(),t)}rangeWithSameHeight(e,t){return AbsoluteCellRange.spanFrom(simpleCellAddress(this.sheet,e,this.start.row),t,this.height())}toString(){return`${this.start.sheet},${this.start.col},${this.start.row},${this.end.col},${this.end.row}`}width(){return this.end.col-this.start.col+1}height(){return this.end.row-this.start.row+1}size(){return this.height()*this.width()}arrayOfAddressesInRange(){const e=[];for(let t=0;t0)if(t>0){let e=this.effectiveEndRow(n);for(;e>=this.start.row;){let t=this.effectiveEndColumn(n);for(;t>=this.start.col;)yield simpleCellAddress(this.start.sheet,t,e),t-=1;e-=1}}else{let e=this.start.row;for(;e<=this.effectiveEndRow(n);){let t=this.effectiveEndColumn(n);for(;t>=this.start.col;)yield simpleCellAddress(this.start.sheet,t,e),t-=1;e+=1}}else if(t>0){let e=this.effectiveEndRow(n);for(;e>=this.start.row;){let t=this.start.col;for(;t<=this.effectiveEndColumn(n);)yield simpleCellAddress(this.start.sheet,t,e),t+=1;e-=1}}else{let e=this.start.row;for(;e<=this.effectiveEndRow(n);){let t=this.start.col;for(;t<=this.effectiveEndColumn(n);)yield simpleCellAddress(this.start.sheet,t,e),t+=1;e+=1}}}getAddress(e,t){if(e<0||t<0||t>this.height()-1||e>this.width()-1)throw Error("Index out of bound");return simpleCellAddress(this.start.sheet,this.start.col+e,this.start.row+t)}exceedsSheetSizeLimits(e,t){return this.end.col>=e||this.end.row>=t}effectiveEndColumn(e){return this.end.col}effectiveEndRow(e){return this.end.row}effectiveWidth(e){return this.width()}effectiveHeight(e){return this.height()}removeRows(e,t){if(!(e>this.end.row)){if(tthis.end.col)){if(t=e}effectiveEndRow(e){return this.effectiveHeight(e)-1}effectiveHeight(e){return e.getSheetHeight(this.sheet)}removeRows(e,t){}}class AbsoluteRowRange extends AbsoluteCellRange{constructor(e,t,n){super(simpleCellAddress(e,0,t),simpleCellAddress(e,Number.POSITIVE_INFINITY,n))}static fromRowRangeAst(e,t){const n=e.start.toSimpleRowAddress(t),r=e.end.toSimpleRowAddress(t);if(n.sheet!==r.sheet)throw new SheetsNotEqual(n.sheet,r.sheet);return new AbsoluteRowRange(n.sheet,n.row,r.row)}shouldBeRemoved(){return this.height()<=0}shiftByColumns(e){}expandByColumns(e){}shifted(e,t){return new AbsoluteRowRange(this.sheet,this.start.row+t,this.end.row+t)}rangeWithSameWidth(e,t){return new AbsoluteRowRange(this.sheet,e,e+t-1)}exceedsSheetSizeLimits(e,t){return this.end.row>=t}effectiveEndColumn(e){return this.effectiveWidth(e)-1}effectiveWidth(e){return e.getSheetWidth(this.sheet)}removeColumns(e,t){}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */const absolutizeDependencies=(e,t)=>e.map((e=>e.absolutize(t))),filterDependenciesOutOfScope=e=>e.filter((e=>e instanceof NamedExpressionDependency||(e instanceof AbsoluteCellRange?!(invalidSimpleCellAddress(e.start)||invalidSimpleCellAddress(e.end)):!invalidSimpleCellAddress(e)))); +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class InterpreterState{constructor(e,t,n){this.formulaAddress=e,this.arraysFlag=t,this.formulaVertex=n}}var unorm$1={exports:{}};!function(e){!function(t){for(var n=[null,0,{}],r=44032,a=4352,i=function(e,t){this.codepoint=e,this.feature=t},s={},o=[],l=0;l<=255;++l)o[l]=0;var u=[function(e,t,r){return t<60||13311>8&255]>10&&(s[t]=r),r},function(e,t,n){return n?e(t,n):new i(t,null)},function(e,t,n){var s;if(t=55296&&e<=56319},i.isLowSurrogate=function(e){return e>=56320&&e<=57343},i.prototype.prepFeature=function(){this.feature||(this.feature=i.fromCharCode(this.codepoint,!0).feature)},i.prototype.toString=function(){if(this.codepoint<65536)return String.fromCharCode(this.codepoint);var e=this.codepoint-65536;return String.fromCharCode(Math.floor(e/1024)+55296,e%1024+56320)},i.prototype.getDecomp=function(){return this.prepFeature(),this.feature[0]||null},i.prototype.isCompatibility=function(){return this.prepFeature(),!!this.feature[1]&&256&this.feature[1]},i.prototype.isExclude=function(){return this.prepFeature(),!!this.feature[1]&&512&this.feature[1]},i.prototype.getCanonicalClass=function(){return this.prepFeature(),this.feature[1]?255&this.feature[1]:0},i.prototype.getComposite=function(e){if(this.prepFeature(),!this.feature[2])return null;var t=this.feature[2][e.codepoint];return t?i.fromCharCode(t):null};var c=function(e){this.str=e,this.cursor=0};c.prototype.next=function(){if(this.str&&this.cursor0;--n){if(this.resBuf[n-1].getCanonicalClass()<=e)break}this.resBuf.splice(n,0,t)}while(0!==e);return this.resBuf.shift()};var m=function(e){this.it=e,this.procBuf=[],this.resBuf=[],this.lastClass=null};m.prototype.next=function(){for(;0===this.resBuf.length;){var e=this.it.next();if(!e){this.resBuf=this.procBuf,this.procBuf=[];break}if(0===this.procBuf.length)this.lastClass=e.getCanonicalClass(),this.procBuf.push(e);else{var t=this.procBuf[0].getComposite(e),n=e.getCanonicalClass();t&&(this.lastClassthis.compare(e,t)<0,this.leq=(e,t)=>this.compare(e,t)<=0,this.gt=(e,t)=>this.compare(e,t)>0,this.geq=(e,t)=>this.compare(e,t)>=0,this.eq=(e,t)=>0===this.compare(e,t),this.neq=(e,t)=>0!==this.compare(e,t),this.pow=(e,t)=>Math.pow(getRawValue(e),getRawValue(t)),this.addWithEpsilonRaw=(e,t)=>{const n=e+t;return Math.abs(n){const n=inferExtendedNumberTypeAdditive(e,t);return this.ExtendedNumberFactory(this.addWithEpsilonRaw(getRawValue(e),getRawValue(t)),n)},this.unaryMinus=e=>cloneNumber(e,-getRawValue(e)),this.unaryPlus=e=>e,this.unaryPercent=e=>new PercentNumber(getRawValue(e)/100),this.concat=(e,t)=>e.concat(t),this.nonstrictadd=(e,t)=>e instanceof CellError?e:t instanceof CellError?t:"number"==typeof e?"number"==typeof t?this.addWithEpsilonRaw(e,t):e:"number"==typeof t?t:0,this.subtract=(e,t)=>{const n=inferExtendedNumberTypeAdditive(e,t),r=getRawValue(e);let a=r-getRawValue(t);return Math.abs(a){const n=getRawValue(e),r=getRawValue(t);if(0===r)return new CellError(ErrorType.DIV_BY_ZERO);{const a=inferExtendedNumberTypeMultiplicative(e,t);return this.ExtendedNumberFactory(n/r,a)}},this.multiply=(e,t)=>{const n=inferExtendedNumberTypeMultiplicative(e,t);return this.ExtendedNumberFactory(getRawValue(e)*getRawValue(t),n)},this.manyToExactComplex=e=>{const t=[];for(const n of e){if(n instanceof CellError)return n;if(isExtendedNumber(n)||"string"==typeof n){const e=this.coerceScalarToComplex(n);e instanceof CellError||t.push(e)}}return t},this.coerceNumbersExactRanges=e=>this.manyToNumbers(e,this.manyToExactNumbers),this.coerceNumbersCoerceRangesDropNulls=e=>this.manyToNumbers(e,this.manyToCoercedNumbersDropNulls),this.manyToExactNumbers=e=>{const t=[];for(const n of e){if(n instanceof CellError)return n;isExtendedNumber(n)&&t.push(getRawValue(n))}return t},this.manyToOnlyNumbersDropNulls=e=>{const t=[];for(const n of e){if(n instanceof CellError)return n;if(isExtendedNumber(n))t.push(getRawValue(n));else if(n!==EmptyValue)return new CellError(ErrorType.VALUE,ErrorMessage.NumberExpected)}return t},this.manyToCoercedNumbersDropNulls=e=>{const t=[];for(const n of e){if(n instanceof CellError)return n;if(n===EmptyValue)continue;const e=this.coerceScalarToNumberOrError(n);isExtendedNumber(e)&&t.push(getRawValue(e))}return t},this.collator=collatorFromConfig(e),this.actualEps=e.smartRounding?e.precisionEpsilon:0}eqMatcherFunction(e){const t=this.buildRegex(e);return e=>"string"==typeof e&&t.test(this.normalizeString(e))}neqMatcherFunction(e){const t=this.buildRegex(e);return e=>!("string"==typeof e&&t.test(this.normalizeString(e)))}searchString(e,t){var n;const r=this.buildRegex(e,!1).exec(t);return null!==(n=null==r?void 0:r.index)&&void 0!==n?n:-1}requiresRegex(e){if(!this.config.useRegularExpressions&&!this.config.useWildcards)return!this.config.matchWholeCell;for(let t=0;t=0&&n*a>=r&&n<=r*a||r<=0&&n*a<=r&&n>=r*a?0:n>r?1:-1}coerceScalarToNumberOrError(e){var t;return e instanceof CellError?e:null!==(t=this.coerceToMaybeNumber(e))&&void 0!==t?t:new CellError(ErrorType.VALUE,ErrorMessage.NumberCoercion)}coerceToMaybeNumber(e){var t;return null!==(t=this.coerceNonDateScalarToMaybeNumber(e))&&void 0!==t?t:"string"==typeof e?this.dateTimeHelper.dateStringToDateNumber(e):void 0}coerceNonDateScalarToMaybeNumber(e){if(e===EmptyValue)return 0;if("string"==typeof e){if(""===e)return 0;const t=this.coerceStringToMaybePercentNumber(e);if(void 0!==t)return t;const n=this.coerceStringToMaybeCurrencyNumber(e);return void 0!==n?n:this.numberLiteralsHelper.numericStringToMaybeNumber(e.trim())}return isExtendedNumber(e)?e:"boolean"==typeof e?Number(e):void 0}coerceStringToMaybePercentNumber(e){const t=e.trim();if(t.endsWith("%")){const e=t.slice(0,t.length-1).trim(),n=this.numberLiteralsHelper.numericStringToMaybeNumber(e);if(void 0!==n)return new PercentNumber(n/100)}}coerceStringToMaybeCurrencyNumber(e){const t=this.currencyMatcher(e.trim());if(void 0!==t){const[e,n]=t,r=this.numberLiteralsHelper.numericStringToMaybeNumber(n);if(void 0!==r)return new CurrencyNumber(r,e)}}currencyMatcher(e){for(const t of this.config.currencySymbol){if(e.startsWith(t))return[t,e.slice(t.length).trim()];if(e.endsWith(t))return[t,e.slice(0,e.length-t.length).trim()]}}coerceComplexExactRanges(e){const t=[];for(const n of e)if(n instanceof SimpleRangeValue)t.push(n);else if(n!==EmptyValue){const e=this.coerceScalarToComplex(n);if(e instanceof CellError)return e;t.push(e)}const n=[];for(const e of t)if(e instanceof SimpleRangeValue){const t=this.manyToExactComplex(e.valuesFromTopLeftCorner());if(t instanceof CellError)return t;n.push(...t)}else n.push(e);return n}coerceScalarToComplex(e){return e instanceof CellError?e:e===EmptyValue?[0,0]:isExtendedNumber(e)?[getRawValue(e),0]:"string"==typeof e?this.coerceStringToComplex(e):new CellError(ErrorType.NUM,ErrorMessage.ComplexNumberExpected)}ExtendedNumberFactory(e,t){const{type:n,format:r}=t;switch(n){case NumberType.NUMBER_RAW:return e;case NumberType.NUMBER_CURRENCY:return new CurrencyNumber(e,null!=r?r:this.config.currencySymbol[0]);case NumberType.NUMBER_DATE:return new DateNumber(e,r);case NumberType.NUMBER_DATETIME:return new DateTimeNumber(e,r);case NumberType.NUMBER_TIME:return new TimeNumber(e,r);case NumberType.NUMBER_PERCENT:return new PercentNumber(e,r)}}buildRegex(e,t=!0){let n;e=this.normalizeString(e);let r=this.config.useWildcards,a=this.config.useRegularExpressions;if(a)try{RegExp(e)}catch(e){a=!1,r=!1}return n=a?escapeNoCharacters(e,this.config.caseSensitive):r?escapeNonWildcards(e,this.config.caseSensitive):escapeAllCharacters(e,this.config.caseSensitive),this.config.matchWholeCell&&t?RegExp("^("+n+")$"):RegExp(n)}normalizeString(e){return this.config.caseSensitive||(e=e.toLowerCase()),this.config.accentSensitive||(e=normalizeString(e,"nfd").replace(/[\u0300-\u036f]/g,"")),e}compare(e,t){if("string"==typeof e||"string"==typeof t){const n="string"==typeof e?this.dateTimeHelper.dateStringToDateNumber(e):e,r="string"==typeof t?this.dateTimeHelper.dateStringToDateNumber(t):t;if(isExtendedNumber(n)&&isExtendedNumber(r))return this.floatCmp(n,r)}return e===EmptyValue?e=coerceEmptyToValue(t):t===EmptyValue&&(t=coerceEmptyToValue(e)),"string"==typeof e&&"string"==typeof t?this.stringCmp(e,t):"boolean"==typeof e&&"boolean"==typeof t?numberCmp(coerceBooleanToNumber(e),coerceBooleanToNumber(t)):isExtendedNumber(e)&&isExtendedNumber(t)?this.floatCmp(e,t):e===EmptyValue&&t===EmptyValue?0:numberCmp(CellValueTypeOrd(getCellValueType(e)),CellValueTypeOrd(getCellValueType(t)))}stringCmp(e,t){return this.collator.compare(e,t)}manyToNumbers(e,t){const n=[];for(const t of e)if(t instanceof SimpleRangeValue)n.push(t);else{const e=getRawValue(this.coerceScalarToNumberOrError(t));if(e instanceof CellError)return e;n.push(e)}const r=[];for(const e of n)if(e instanceof SimpleRangeValue){const n=t(e.valuesFromTopLeftCorner());if(n instanceof CellError)return n;r.push(...n)}else r.push(e);return r}coerceStringToComplex(e){const t=complexParsingRegexp.exec(e);if(null===t)return new CellError(ErrorType.NUM,ErrorMessage.ComplexNumberExpected);let n,r;return n=void 0!==t[6]?"-"===t[1]?[0,-1]:[0,1]:this.parseComplexToken(t[1]+t[3],t[5]),n instanceof CellError||void 0===t[8]?n:(r=void 0!==t[14]?"-"===t[9]?[0,-1]:[0,1]:this.parseComplexToken(t[9]+t[11],t[13]),r instanceof CellError?r:""!==t[5]||""===t[13]?new CellError(ErrorType.NUM,ErrorMessage.ComplexNumberExpected):"+"===t[8]?[n[0]+r[0],n[1]+r[1]]:[n[0]-r[0],n[1]-r[1]])}parseComplexToken(e,t){const n=getRawValue(this.coerceNonDateScalarToMaybeNumber(e));return void 0===n?new CellError(ErrorType.NUM,ErrorMessage.ComplexNumberExpected):""===t?[n,0]:[0,n]}}function coerceComplexToString([e,t],n){if(!isFinite(e)||!isFinite(t))return new CellError(ErrorType.NUM,ErrorMessage.NaN);if(n=null!=n?n:COMPLEX_NUMBER_SYMBOL,0===t)return`${e}`;const r=`${-1===t||1===t?"":Math.abs(t)}${n}`;return 0===e?`${t<0?"-":""}${r}`:`${e}${t<0?"-":"+"}${r}`}function coerceToRange(e){return e instanceof SimpleRangeValue?e:SimpleRangeValue.fromScalar(e)}function coerceBooleanToNumber(e){return Number(e)}function coerceEmptyToValue(e){return"string"==typeof e?"":isExtendedNumber(e)?0:"boolean"!=typeof e&&EmptyValue}function coerceScalarToBoolean(e){if(e instanceof CellError||"boolean"==typeof e)return e;if(e===EmptyValue)return!1;if(isExtendedNumber(e))return 0!==getRawValue(e);{const t=e.toUpperCase();return"TRUE"===t||"FALSE"!==t&&(""!==t&&void 0)}}function coerceScalarToString(e){return e instanceof CellError||"string"==typeof e?e:e===EmptyValue?"":isExtendedNumber(e)?getRawValue(e).toString():e?"TRUE":"FALSE"}function zeroIfEmpty(e){return e===EmptyValue?0:e}function numberCmp(e,t){const n=getRawValue(e),r=getRawValue(t);return n>r?1:n","=",".","+","-",",","\\","$","^","!"];function needsEscape(e){return escapedCharacters.includes(e)}function escapeNonWildcards(e,t){let n="";for(let r=0;r=0&&n=0&&nthis.arithmeticHelper.coerceScalarToNumberOrError(e),this.runFunction=(e,t,n,r)=>{var a,i,s,o,l;let u,c=n.parameters||[];if(u=n.expandRanges?this.listOfScalarValues(e,t):e.map((e=>[this.evaluateAst(e,t),!1])),void 0===n.repeatLastArgs&&c.lengthnew CellError(ErrorType.NA,ErrorMessage.CellRefExpected)))=>{if(0===e.length)return this.returnNumberWrapper(r(),n.returnNumberType);if(e.length>1)return new CellError(ErrorType.NA,ErrorMessage.WrongArgNumber);let s,o=e[0];for(;o.type===AstNodeType.PARENTHESIS;)o=o.expression;if(o.type===AstNodeType.CELL_REFERENCE)s=o.reference.toSimpleCellAddress(t.formulaAddress);else if(o.type===AstNodeType.CELL_RANGE||o.type===AstNodeType.COLUMN_RANGE||o.type===AstNodeType.ROW_RANGE)try{s=AbsoluteCellRange.fromAst(o,t.formulaAddress).start}catch(e){return new CellError(ErrorType.REF,ErrorMessage.CellRefExpected)}return void 0!==s?this.returnNumberWrapper(a(s),n.returnNumberType):this.runFunction(e,t,n,i)},this.interpreter=e,this.dependencyGraph=e.dependencyGraph,this.columnSearch=e.columnSearch,this.config=e.config,this.serialization=e.serialization,this.arraySizePredictor=e.arraySizePredictor,this.dateTimeHelper=e.dateTimeHelper,this.arithmeticHelper=e.arithmeticHelper}evaluateAst(e,t){return this.interpreter.evaluateAst(e,t)}arraySizeForAst(e,t){return this.arraySizePredictor.checkArraySizeForAst(e,t)}listOfScalarValues(e,t){const n=[];for(const r of e){const e=this.evaluateAst(r,t);if(e instanceof SimpleRangeValue)for(const t of e.valuesFromTopLeftCorner())n.push([t,!0]);else n.push([e,!1])}return n}coerceToType(e,t,n){let r;if(e instanceof SimpleRangeValue)switch(t.argumentType){case ArgumentTypes.RANGE:case ArgumentTypes.ANY:r=e;break;default:{const t=coerceRangeToScalar(e,n);if(void 0===t)return;e=t}}if(!(e instanceof SimpleRangeValue))switch(t.argumentType){case ArgumentTypes.INTEGER:case ArgumentTypes.NUMBER:const n=this.coerceScalarToNumberOrError(e);if(!isExtendedNumber(n)){r=n;break}const a=getRawValue(n);if(void 0!==t.maxValue&&a>t.maxValue)return new CellError(ErrorType.NUM,ErrorMessage.ValueLarge);if(void 0!==t.minValue&&a=t.lessThan)return new CellError(ErrorType.NUM,ErrorMessage.ValueLarge);if(void 0!==t.greaterThan&&a<=t.greaterThan)return new CellError(ErrorType.NUM,ErrorMessage.ValueSmall);if(t.argumentType===ArgumentTypes.INTEGER&&!Number.isInteger(a))return new CellError(ErrorType.NUM,ErrorMessage.IntegerExpected);r=n;break;case ArgumentTypes.STRING:r=coerceScalarToString(e);break;case ArgumentTypes.BOOLEAN:r=coerceScalarToBoolean(e);break;case ArgumentTypes.SCALAR:case ArgumentTypes.NOERROR:case ArgumentTypes.ANY:r=e;break;case ArgumentTypes.RANGE:if(e instanceof CellError)return e;r=coerceToRange(e);break;case ArgumentTypes.COMPLEX:return this.arithmeticHelper.coerceScalarToComplex(getRawValue(e))}return t.passSubtype||void 0===r?r:getRawValue(r)}metadata(e){const t=this.constructor.implementedFunctions[e];if(void 0!==t)return t;throw new Error(`No metadata for function ${e}.`)}returnNumberWrapper(e,t,n){return void 0!==t&&isExtendedNumber(e)?this.arithmeticHelper.ExtendedNumberFactory(getRawValue(e),{type:t,format:n}):e}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class ArraySize{constructor(e,t,n=!1){if(this.width=e,this.height=t,this.isRef=n,e<=0||t<=0)throw Error("Incorrect array size")}static fromArray(e){return new ArraySize(e.length>0?e[0].length:0,e.length)}static error(){return new ArraySize(1,1,!0)}static scalar(){return new ArraySize(1,1,!1)}isScalar(){return this.width<=1&&this.height<=1||this.isRef}}function arraySizeForBinaryOp(e,t){return new ArraySize(Math.max(e.width,t.width),Math.max(e.height,t.height))}function arraySizeForUnaryOp(e){return new ArraySize(e.width,e.height)}class ArraySizePredictor{constructor(e,t){this.config=e,this.functionRegistry=t}checkArraySize(e,t){return this.checkArraySizeForAst(e,{formulaAddress:t,arraysFlag:this.config.useArrayArithmetic})}checkArraySizeForAst(e,t){switch(e.type){case AstNodeType.FUNCTION_CALL:return this.checkArraySizeForFunction(e,t);case AstNodeType.COLUMN_RANGE:case AstNodeType.ROW_RANGE:case AstNodeType.CELL_RANGE:{const n=AbsoluteCellRange.fromAstOrUndef(e,t.formulaAddress);return void 0===n?ArraySize.error():new ArraySize(n.width(),n.height(),!0)}case AstNodeType.ARRAY:{const n=[],r=[];for(const a of e.args){const e=a.map((e=>this.checkArraySizeForAst(e,t))),i=Math.min(...e.map((e=>e.height))),s=e.reduce(((e,t)=>e+t.width),0);n.push(i),r.push(s)}const a=n.reduce(((e,t)=>e+t),0),i=Math.min(...r);return new ArraySize(i,a)}case AstNodeType.STRING:case AstNodeType.NUMBER:return ArraySize.scalar();case AstNodeType.CELL_REFERENCE:return new ArraySize(1,1,!0);case AstNodeType.DIV_OP:case AstNodeType.CONCATENATE_OP:case AstNodeType.EQUALS_OP:case AstNodeType.GREATER_THAN_OP:case AstNodeType.GREATER_THAN_OR_EQUAL_OP:case AstNodeType.LESS_THAN_OP:case AstNodeType.LESS_THAN_OR_EQUAL_OP:case AstNodeType.MINUS_OP:case AstNodeType.NOT_EQUAL_OP:case AstNodeType.PLUS_OP:case AstNodeType.POWER_OP:case AstNodeType.TIMES_OP:{const n=this.checkArraySizeForAst(e.left,t),r=this.checkArraySizeForAst(e.right,t);return!t.arraysFlag&&(n.height>1||n.width>1||r.height>1||r.width>1)?ArraySize.error():arraySizeForBinaryOp(n,r)}case AstNodeType.MINUS_UNARY_OP:case AstNodeType.PLUS_UNARY_OP:case AstNodeType.PERCENT_OP:{const n=this.checkArraySizeForAst(e.value,t);return!t.arraysFlag&&(n.height>1||n.width>1)?ArraySize.error():arraySizeForUnaryOp(n)}case AstNodeType.PARENTHESIS:return this.checkArraySizeForAst(e.expression,t);case AstNodeType.EMPTY:default:return ArraySize.error()}}checkArraySizeForFunction(e,t){const n=this.functionRegistry.getMetadata(e.procedureName),r=this.functionRegistry.getArraySizeFunction(e.procedureName);if(void 0!==r)return r(e,t);const a=e.args.map((e=>{var r;return this.checkArraySizeForAst(e,new InterpreterState(t.formulaAddress,t.arraysFlag||null!==(r=null==n?void 0:n.arrayFunction)&&void 0!==r&&r))}));if(void 0===n||n.expandRanges||!t.arraysFlag||n.vectorizationForbidden||void 0===n.parameters)return new ArraySize(1,1);const i=[...n.parameters];if(void 0===n.repeatLastArgs&&i.length{const t=this.dependencyGraph.getCellValue(e);return t instanceof SimpleRangeValue?(this._hasOnlyNumbers=!1,new CellError(ErrorType.VALUE,ErrorMessage.ScalarExpected)):(isExtendedNumber(t)||(this._hasOnlyNumbers=!1),t)})))}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class ContentChanges{constructor(){this.changes=new Map}static empty(){return new ContentChanges}addAll(e){for(const t of e.changes.values())this.add(t.address,t);return this}addChange(e,t,n){this.addInterpreterValue(e,t,n)}exportChanges(e){let t=[];return this.changes.forEach((n=>{const r=e.exportChange(n);Array.isArray(r)?t=t.concat(r):t.push(r)})),t}getChanges(){return Array.from(this.changes.values())}isEmpty(){return 0===this.changes.size}add(e,t){const n=t.value;if(n instanceof SimpleRangeValue)for(const t of n.effectiveAddressesFromData(e))this.changes.delete(`${t.sheet},${t.col},${t.row}`);this.changes.set(addressKey(e),t)}addInterpreterValue(e,t,n){this.add(t,{address:t,value:e,oldValue:n})}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */!function(e){e.BUILD_ENGINE_TOTAL="BUILD_ENGINE_TOTAL",e.PARSER="PARSER",e.GRAPH_BUILD="GRAPH_BUILD",e.COLLECT_DEPENDENCIES="COLLECT_DEPENDENCIES",e.PROCESS_DEPENDENCIES="PROCESS_DEPENDENCIES",e.TOP_SORT="TOP_SORT",e.BUILD_COLUMN_INDEX="BUILD_COLUMN_INDEX",e.EVALUATION="EVALUATION",e.VLOOKUP="VLOOKUP",e.TRANSFORM_ASTS="TRANSFORM_ASTS",e.TRANSFORM_ASTS_POSTPONED="TRANSFORM_ASTS_POSTPONED",e.ADJUSTING_ADDRESS_MAPPING="ADJUSTING_ADDRESS_MAPPING",e.ADJUSTING_ARRAY_MAPPING="ADJUSTING_ARRAY_MAPPING",e.ADJUSTING_RANGES="ADJUSTING_RANGES",e.ADJUSTING_GRAPH="ADJUSTING_GRAPH",e.CRITERION_FUNCTION_FULL_CACHE_USED="CRITERION_FUNCTION_FULL_CACHE_USED",e.CRITERION_FUNCTION_PARTIAL_CACHE_USED="CRITERION_FUNCTION_PARTIAL_CACHE_USED"}(StatType||(StatType={})); +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class Statistics{constructor(){this.stats=new Map([[StatType.CRITERION_FUNCTION_FULL_CACHE_USED,0],[StatType.CRITERION_FUNCTION_PARTIAL_CACHE_USED,0]]),this.startTimes=new Map}incrementCriterionFunctionFullCacheUsed(){var e;const t=(null!==(e=this.stats.get(StatType.CRITERION_FUNCTION_FULL_CACHE_USED))&&void 0!==e?e:0)+1;this.stats.set(StatType.CRITERION_FUNCTION_FULL_CACHE_USED,t)}incrementCriterionFunctionPartialCacheUsed(){var e;const t=(null!==(e=this.stats.get(StatType.CRITERION_FUNCTION_PARTIAL_CACHE_USED))&&void 0!==e?e:0)+1;this.stats.set(StatType.CRITERION_FUNCTION_PARTIAL_CACHE_USED,t)}reset(){this.stats.clear(),this.startTimes.clear(),this.stats.set(StatType.CRITERION_FUNCTION_FULL_CACHE_USED,0),this.stats.set(StatType.CRITERION_FUNCTION_PARTIAL_CACHE_USED,0)}start(e){if(this.startTimes.get(e))throw Error(`Statistics ${e} already started`);this.startTimes.set(e,Date.now())}end(e){var t;const n=Date.now(),r=this.startTimes.get(e);if(!r)throw Error(`Statistics ${e} not started`);{let a=null!==(t=this.stats.get(e))&&void 0!==t?t:0;a+=n-r,this.stats.set(e,a),this.startTimes.delete(e)}}measure(e,t){this.start(e);const n=t();return this.end(e),n}snapshot(){return new Map(this.stats)}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class EmptyStatistics extends Statistics{incrementCriterionFunctionFullCacheUsed(){}incrementCriterionFunctionPartialCacheUsed(){}start(e){}end(e){}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class AddressMapping{constructor(e){this.policy=e,this.mapping=new Map}getCell(e){const t=this.mapping.get(e.sheet);if(void 0===t)throw new NoSheetWithIdError(e.sheet);return t.getCell(e)}fetchCell(e){const t=this.mapping.get(e.sheet);if(void 0===t)throw new NoSheetWithIdError(e.sheet);const n=t.getCell(e);if(!n)throw Error("Vertex for address missing in AddressMapping");return n}strategyFor(e){const t=this.mapping.get(e);if(void 0===t)throw new NoSheetWithIdError(e);return t}addSheet(e,t){if(this.mapping.has(e))throw Error("Sheet already added");this.mapping.set(e,t)}autoAddSheet(e,t,n){const{height:r,width:a,fill:i}=n,s=this.policy.call(i);this.addSheet(e,new s(a,r))}getCellValue(e){const t=this.getCell(e);return void 0===t?EmptyValue:t instanceof ArrayVertex?t.getArrayCellValue(e):t.getCellValue()}getRawValue(e){const t=this.getCell(e);return t instanceof ValueCellVertex?t.getValues().rawValue:t instanceof ArrayVertex?t.getArrayCellRawValue(e):null}setCell(e,t){const n=this.mapping.get(e.sheet);if(!n)throw Error("Sheet not initialized");n.setCell(e,t)}moveCell(e,t){const n=this.mapping.get(e.sheet);if(!n)throw Error("Sheet not initialized.");if(e.sheet!==t.sheet)throw Error("Cannot move cells between sheets.");if(n.has(t))throw new Error("Cannot move cell. Destination already occupied.");const r=n.getCell(e);if(void 0===r)throw new Error("Cannot move cell. No cell with such address.");this.setCell(t,r),this.removeCell(e)}removeCell(e){const t=this.mapping.get(e.sheet);if(!t)throw Error("Sheet not initialized");t.removeCell(e)}has(e){const t=this.mapping.get(e.sheet);return void 0!==t&&t.has(e)}getHeight(e){const t=this.mapping.get(e);if(void 0===t)throw new NoSheetWithIdError(e);return t.getHeight()}getWidth(e){const t=this.mapping.get(e);if(!t)throw new NoSheetWithIdError(e);return t.getWidth()}addRows(e,t,n){const r=this.mapping.get(e);if(void 0===r)throw new NoSheetWithIdError(e);r.addRows(t,n)}removeRows(e){const t=this.mapping.get(e.sheet);if(void 0===t)throw new NoSheetWithIdError(e.sheet);t.removeRows(e)}removeSheet(e){this.mapping.delete(e)}addColumns(e,t,n){const r=this.mapping.get(e);if(void 0===r)throw new NoSheetWithIdError(e);r.addColumns(t,n)}removeColumns(e){const t=this.mapping.get(e.sheet);if(void 0===t)throw new NoSheetWithIdError(e.sheet);t.removeColumns(e)}*verticesFromRowsSpan(e){yield*this.mapping.get(e.sheet).verticesFromRowsSpan(e)}*verticesFromColumnsSpan(e){yield*this.mapping.get(e.sheet).verticesFromColumnsSpan(e)}*entriesFromRowsSpan(e){yield*this.mapping.get(e.sheet).entriesFromRowsSpan(e)}*entriesFromColumnsSpan(e){yield*this.mapping.get(e.sheet).entriesFromColumnsSpan(e)}*entries(){for(const[e,t]of this.mapping.entries())yield*t.getEntries(e)}*sheetEntries(e){const t=this.mapping.get(e);if(void 0===t)throw new NoSheetWithIdError(e);yield*t.getEntries(e)}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class ArrayMapping{constructor(){this.arrayMapping=new Map}getArray(e){const t=this.getArrayByCorner(e.start);if(null==t?void 0:t.getRange().sameAs(e))return t}getArrayByCorner(e){return this.arrayMapping.get(addressKey(e))}setArray(e,t){this.arrayMapping.set(addressKey(e.start),t)}removeArray(e){"string"==typeof e?this.arrayMapping.delete(e):this.arrayMapping.delete(addressKey(e.start))}count(){return this.arrayMapping.size}*arraysInRows(e){for(const[t,n]of this.arrayMapping.entries())n.spansThroughSheetRows(e.sheet,e.rowStart,e.rowEnd)&&(yield[t,n])}*arraysInCols(e){for(const[t,n]of this.arrayMapping.entries())n.spansThroughSheetColumn(e.sheet,e.columnStart,e.columnEnd)&&(yield[t,n])}isFormulaArrayInRow(e,t){for(const n of this.arrayMapping.values())if(n.spansThroughSheetRows(e,t))return!0;return!1}isFormulaArrayInAllRows(e){let t=!0;for(const n of e.rows())this.isFormulaArrayInRow(e.sheet,n)||(t=!1);return t}isFormulaArrayInColumn(e,t){for(const n of this.arrayMapping.values())if(n.spansThroughSheetColumn(e,t))return!0;return!1}isFormulaArrayInAllColumns(e){let t=!0;for(const n of e.columns())this.isFormulaArrayInColumn(e.sheet,n)||(t=!1);return t}isFormulaArrayInRange(e){for(const t of this.arrayMapping.values())if(t.getRange().doesOverlap(e))return!0;return!1}isFormulaArrayAtAddress(e){for(const t of this.arrayMapping.values())if(t.getRange().addressInRange(e))return!0;return!1}moveArrayVerticesAfterRowByRows(e,t,n){this.updateArrayVerticesInSheet(e,((e,r)=>{const a=r.getRange();return t<=a.start.row?[a.shifted(0,n),r]:void 0}))}moveArrayVerticesAfterColumnByColumns(e,t,n){this.updateArrayVerticesInSheet(e,((e,r)=>{const a=r.getRange();return t<=a.start.col?[a.shifted(n,0),r]:void 0}))}updateArrayVerticesInSheet(e,t){const n=Array();for(const[r,a]of this.arrayMapping.entries()){if(a.sheet!==e)continue;const i=t(r,a);void 0!==i&&(this.removeArray(r),n.push(i))}n.forEach((([e,t])=>{this.setArray(e,t)}))}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class NotComputedArray{constructor(e){this.size=e}width(){return this.size.width}height(){return this.size.height}get(e,t){throw Error("Array not computed yet.")}simpleRangeValue(){throw Error("Array not computed yet.")}}class ArrayValue{constructor(e){this.size=new ArraySize(e.length>0?e[0].length:0,e.length),this.array=e}static fromInterpreterValue(e){return new ArrayValue(e instanceof SimpleRangeValue?e.data:[[e]])}simpleRangeValue(){return SimpleRangeValue.onlyValues(this.array)}addRows(e,t){this.array.splice(e,0,...this.nullArrays(t,this.width())),this.size.height+=t}addColumns(e,t){for(let n=0;ne.height)throw"Resizing to smaller array";if(this.width()e.width)throw"Resizing to smaller array"}outOfBound(e,t){return e<0||t<0||t>this.size.height-1||e>this.size.width-1}}class ErroredArray{constructor(e,t){this.error=e,this.size=t}get(e,t){return this.error}width(){return this.size.width}height(){return this.size.height}simpleRangeValue(){return this.error}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class FormulaVertex{constructor(e,t,n){this.formula=e,this.cellAddress=t,this.version=n}get width(){return 1}get height(){return 1}static fromAst(e,t,n,r){return n.isScalar()?new FormulaCellVertex(e,t,r):new ArrayVertex(e,t,n,r)}getFormula(e){return this.ensureRecentData(e),this.formula}ensureRecentData(e){if(this.version!=e.version()){const[t,n,r]=e.applyTransformations(this.formula,this.cellAddress,this.version);this.formula=t,this.cellAddress=n,this.version=r}}getAddress(e){return this.ensureRecentData(e),this.cellAddress}}class ArrayVertex extends FormulaVertex{constructor(e,t,n,r=0){super(e,t,r),n.isRef?this.array=new ErroredArray(new CellError(ErrorType.REF,ErrorMessage.NoSpaceForArrayResult),ArraySize.error()):this.array=new NotComputedArray(n)}get width(){return this.array.width()}get height(){return this.array.height()}get sheet(){return this.cellAddress.sheet}get leftCorner(){return this.cellAddress}setCellValue(e){if(e instanceof CellError)return this.setErrorValue(e),e;const t=ArrayValue.fromInterpreterValue(e);return t.resize(this.array.size),this.array=t,e}getCellValue(){if(this.array instanceof NotComputedArray)throw Error("Array not computed yet.");return this.array.simpleRangeValue()}valueOrUndef(){if(!(this.array instanceof NotComputedArray))return this.array.simpleRangeValue()}getArrayCellValue(e){const t=e.col-this.cellAddress.col,n=e.row-this.cellAddress.row;try{return this.array.get(t,n)}catch(e){return new CellError(ErrorType.REF)}}getArrayCellRawValue(e){const t=this.getArrayCellValue(e);return t instanceof CellError||t===EmptyValue?void 0:getRawValue(t)}setArrayCellValue(e,t){const n=e.col-this.cellAddress.col,r=e.row-this.cellAddress.row;this.array instanceof ArrayValue&&this.array.set(n,r,t)}setNoSpace(){return this.array=new ErroredArray(new CellError(ErrorType.SPILL,ErrorMessage.NoSpaceForArrayResult),ArraySize.error()),this.getCellValue()}getRange(){return AbsoluteCellRange.spanFrom(this.cellAddress,this.width,this.height)}getRangeOrUndef(){return AbsoluteCellRange.spanFromOrUndef(this.cellAddress,this.width,this.height)}setAddress(e){this.cellAddress=e}setFormula(e){this.formula=e}spansThroughSheetRows(e,t,n=t){return this.cellAddress.sheet===e&&this.cellAddress.row<=n&&te.criterionFunctionCache.clear())),this.dependentCacheRanges.clear()}getStart(){return this.start}getEnd(){return this.end}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */const collectAddressesDependentToRange=(e,t,n,r,a)=>{if(t instanceof RangeVertex){const e=t.range.intersectionWith(n);return void 0!==e?Array.from(e.addresses(a)):[]}let i,s;return t instanceof FormulaVertex?(i=t.getFormula(r),s=t.getAddress(r),collectDependencies(i,e).filter((e=>e instanceof AddressDependency)).map((e=>e.dependency.toSimpleCellAddress(s))).filter((e=>n.addressInRange(e)))):[]}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */var NodeVisitStatus;!function(e){e[e.ON_STACK=0]="ON_STACK",e[e.PROCESSED=1]="PROCESSED",e[e.POPPED=2]="POPPED"}(NodeVisitStatus||(NodeVisitStatus={}));class Graph{constructor(e){this.dependencyQuery=e,this.nodes=new Set,this.specialNodes=new Set,this.specialNodesStructuralChanges=new Set,this.specialNodesRecentlyChanged=new Set,this.infiniteRanges=new Set,this.edges=new Map}addNode(e){this.nodes.add(e),this.edges.has(e)||this.edges.set(e,new Set)}addEdge(e,t){if(!this.nodes.has(e))throw new Error(`Unknown node ${e}`);if(!this.nodes.has(t))throw new Error(`Unknown node ${t}`);this.edges.get(e).add(t)}removeEdge(e,t){if(!this.existsEdge(e,t))throw new Error("Edge does not exist");this.edges.get(e).delete(t)}softRemoveEdge(e,t){var n;null===(n=this.edges.get(e))||void 0===n||n.delete(t)}removeIncomingEdges(e){this.edges.forEach((t=>{t.delete(e)}))}adjacentNodes(e){return this.edges.get(e)}adjacentNodesCount(e){return this.adjacentNodes(e).size}hasNode(e){return this.nodes.has(e)}nodesCount(){return this.nodes.size}edgesCount(){let e=0;return this.edges.forEach((t=>e+=t.size)),e}removeNode(e){for(const t of this.adjacentNodes(e).values())this.markNodeAsSpecialRecentlyChanged(t);return this.edges.delete(e),this.nodes.delete(e),this.specialNodes.delete(e),this.specialNodesRecentlyChanged.delete(e),this.specialNodesStructuralChanges.delete(e),this.infiniteRanges.delete(e),this.removeDependencies(e)}markNodeAsSpecial(e){this.specialNodes.add(e)}markNodeAsSpecialRecentlyChanged(e){this.nodes.has(e)&&this.specialNodesRecentlyChanged.add(e)}markNodeAsChangingWithStructure(e){this.specialNodesStructuralChanges.add(e)}clearSpecialNodesRecentlyChanged(){this.specialNodesRecentlyChanged.clear()}markNodeAsInfiniteRange(e){this.infiniteRanges.add(e)}existsEdge(e,t){var n,r;return null!==(r=null===(n=this.edges.get(e))||void 0===n?void 0:n.has(t))&&void 0!==r&&r}topSortWithScc(){return this.getTopSortedWithSccSubgraphFrom(Array.from(this.nodes),(()=>!0),(()=>{}))}getTopSortedWithSccSubgraphFrom(e,t,n){const r=new Map,a=new Map,i=new Map,s=new Set,o=new Map,l=[];let u=0;const c=new Set;e.reverse(),e.forEach((e=>{if(void 0!==o.get(e))return;const t=[e],n=[];for(o.set(e,NodeVisitStatus.ON_STACK);t.length>0;){const e=t[t.length-1];switch(o.get(e)){case NodeVisitStatus.ON_STACK:r.set(e,u),a.set(e,u),n.push(e),u++,this.adjacentNodes(e).forEach((n=>{void 0===r.get(n)&&(t.push(n),i.set(n,e),o.set(n,NodeVisitStatus.ON_STACK))})),o.set(e,NodeVisitStatus.PROCESSED);break;case NodeVisitStatus.PROCESSED:{let u;if(u=r.get(e),this.adjacentNodes(e).forEach((t=>{s.has(t)||(u=i.get(t)===e?Math.min(u,a.get(t)):Math.min(u,r.get(t)))})),a.set(e,u),u===r.get(e)){const t=[];do{t.push(n[n.length-1]),n.pop()}while(t[t.length-1]!==e);t.forEach((e=>{s.add(e)})),l.push(...t),t.length>1&&t.forEach((e=>{c.add(e)}))}t.pop(),o.set(e,NodeVisitStatus.POPPED);break}case NodeVisitStatus.POPPED:t.pop()}}}));const p=new Set(e),d=[],m=[];return l.reverse(),l.forEach((e=>{c.has(e)||this.adjacentNodes(e).has(e)?(m.push(e),n(e),this.adjacentNodes(e).forEach((e=>p.add(e)))):(d.push(e),p.has(e)&&t(e)&&this.adjacentNodes(e).forEach((e=>p.add(e))))})),{sorted:d,cycled:m}}getDependencies(e){const t=[];return this.edges.forEach(((n,r)=>{n.has(e)&&t.push(r)})),t}removeDependencies(e){const t=this.dependencyQuery(e);for(const n of t)this.softRemoveEdge(n,e);return t}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class RangeMapping{constructor(){this.rangeMapping=new Map}getMappingSize(e){var t,n;return null!==(n=null===(t=this.rangeMapping.get(e))||void 0===t?void 0:t.size)&&void 0!==n?n:0}setRange(e){let t=this.rangeMapping.get(e.getStart().sheet);void 0===t&&(t=new Map,this.rangeMapping.set(e.getStart().sheet,t));const n=keyFromAddresses(e.getStart(),e.getEnd());t.set(n,e)}removeRange(e){const t=e.getStart().sheet,n=this.rangeMapping.get(t);if(void 0===n)return;const r=keyFromAddresses(e.getStart(),e.getEnd());n.delete(r),0===n.size&&this.rangeMapping.delete(t)}getRange(e,t){const n=this.rangeMapping.get(e.sheet),r=keyFromAddresses(e,t);return null==n?void 0:n.get(r)}fetchRange(e,t){const n=this.getRange(e,t);if(!n)throw Error("Range does not exist");return n}truncateRanges(e,t){const n=Array(),r=Array(),a=Array(),i=e.sheet;for(const[s,o]of this.entriesFromSheet(e.sheet)){const l=o.range;e.start<=t(o.range.end)&&(l.removeSpan(e),l.shouldBeRemoved()?(this.removeByKey(i,s),n.push(o)):r.push([s,o]),a.push(o))}const s=[];r.sort(((e,n)=>compareBy(e[1],n[1],t)));for(const[e,t]of r){const n=keyFromRange(t.range);if(n===e)continue;const r=this.getByKey(i,n);this.removeByKey(i,e),void 0!==r&&t!=r?s.push([r,t]):this.setRange(t)}return{verticesToRemove:n,verticesToMerge:s,verticesWithChangedSize:a}}moveAllRangesInSheetAfterRowByRows(e,t,n){return this.updateVerticesFromSheet(e,((e,r)=>t<=r.start.row?(r.range.shiftByRows(n),{changedSize:!1,vertex:r}):t>r.start.row&&t<=r.end.row?(r.range.expandByRows(n),{changedSize:!0,vertex:r}):void 0))}moveAllRangesInSheetAfterColumnByColumns(e,t,n){return this.updateVerticesFromSheet(e,((e,r)=>t<=r.start.col?(r.range.shiftByColumns(n),{changedSize:!1,vertex:r}):t>r.start.col&&t<=r.end.col?(r.range.expandByColumns(n),{changedSize:!0,vertex:r}):void 0))}moveRangesInsideSourceRange(e,t,n,r){this.updateVerticesFromSheet(e.sheet,((a,i)=>e.containsRange(i.range)?(i.range.shiftByColumns(t),i.range.shiftByRows(n),i.range.moveToSheet(r),{changedSize:!1,vertex:i}):void 0))}removeRangesInSheet(e){if(this.rangeMapping.has(e)){const t=this.rangeMapping.get(e).values();return this.rangeMapping.delete(e),t}return[][Symbol.iterator]()}*rangesInSheet(e){const t=this.rangeMapping.get(e);t&&(yield*t.values())}*rangeVerticesContainedInRange(e){for(const t of this.rangesInSheet(e.sheet))e.containsRange(t.range)&&(yield t)}findSmallerRange(e){if(e.height()>1&&Number.isFinite(e.height())){const t=simpleCellAddress(e.end.sheet,e.end.col,e.end.row-1),n=this.getRange(e.start,t);if(void 0!==n){return{smallerRangeVertex:n,restRange:new AbsoluteCellRange(simpleCellAddress(e.start.sheet,e.start.col,e.end.row),e.end)}}}return{restRange:e}}*entriesFromSheet(e){const t=this.rangeMapping.get(e);t&&(yield*t.entries())}removeByKey(e,t){this.rangeMapping.get(e).delete(t)}getByKey(e,t){var n;return null===(n=this.rangeMapping.get(e))||void 0===n?void 0:n.get(t)}updateVerticesFromSheet(e,t){const n=Array();for(const[r,a]of this.entriesFromSheet(e)){const i=t(r,a);void 0!==i&&(this.removeByKey(e,r),n.push(i))}return n.forEach((e=>{this.setRange(e.vertex)})),{verticesWithChangedSize:n.filter((e=>e.changedSize)).map((e=>e.vertex))}}}function keyFromAddresses(e,t){return`${e.col},${e.row},${t.col},${t.row}`}function keyFromRange(e){return keyFromAddresses(e.start,e.end)}const compareBy=(e,t,n)=>{const r=n(e.range.start),a=n(e.range.start);if(r===a){return n(e.range.end)-n(t.range.end)}return r-a}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class TranslationPackage{constructor(e,t,n){this.functions=e,this.errors=t,this.ui=n,this._protectedTranslations={VERSION:"VERSION"},this.checkUI(),this.checkErrors(),this.checkFunctionTranslations(this.functions),Object.assign(this.functions,this._protectedTranslations)}extendFunctions(e){this.checkFunctionTranslations(e),Object.assign(this.functions,e)}buildFunctionMapping(){return Object.keys(this.functions).reduce(((e,t)=>(e[this.functions[t]]=t,e)),{})}buildErrorMapping(){return Object.keys(this.errors).reduce(((e,t)=>(e[this.errors[t]]=t,e)),{})}isFunctionTranslated(e){return void 0!==this.functions[e]}getFunctionTranslations(e){const t=[];for(const n of e)this.isFunctionTranslated(n)&&t.push(this.functions[n]);return t}getFunctionTranslation(e){const t=this.functions[e];if(void 0===t)throw new MissingTranslationError(`functions.${e}`);return t}getMaybeFunctionTranslation(e){return this.functions[e]}getErrorTranslation(e){if(e===ErrorType.LIC)return`#${ErrorType.LIC}!`;const t=this.errors[e];if(void 0===t)throw new MissingTranslationError(`errors.${e}`);return t}getUITranslation(e){const t=this.ui[e];if(void 0===t)throw new MissingTranslationError(`ui.${e}`);return t}checkUI(){for(const e of Object.values(UIElement))if(!(e in this.ui))throw new MissingTranslationError(`ui.${e}`)}checkErrors(){for(const e of Object.values(ErrorType))if(!(e in this.errors)&&e!==ErrorType.LIC)throw new MissingTranslationError(`errors.${e}`)}checkFunctionTranslations(e){const t=new Set(Object.getOwnPropertyNames(e));for(const e of Object.getOwnPropertyNames(this._protectedTranslations))if(t.has(e))throw new ProtectedFunctionTranslationError(e)}}function buildTranslationPackage(e){return new TranslationPackage(Object.assign({},e.functions),Object.assign({},e.errors),Object.assign({},e.ui))} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */var UIElement,ErrorType,CellType; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +function canonicalize(e){return e.toLowerCase()}!function(e){e.NEW_SHEET_PREFIX="NEW_SHEET_PREFIX"}(UIElement||(UIElement={}));class Sheet{constructor(e,t){this.id=e,this.displayName=t}get canonicalName(){return canonicalize(this.displayName)}}class SheetMapping{constructor(e){this.languages=e,this.mappingFromCanonicalName=new Map,this.mappingFromId=new Map,this.lastSheetId=-1,this.fetch=e=>{const t=this.mappingFromCanonicalName.get(canonicalize(e));if(void 0===t)throw new NoSheetWithNameError(e);return t.id},this.get=e=>{var t;return null===(t=this.mappingFromCanonicalName.get(canonicalize(e)))||void 0===t?void 0:t.id},this.fetchDisplayName=e=>this.fetchSheetById(e).displayName,this.sheetNamePrefix=e.getUITranslation(UIElement.NEW_SHEET_PREFIX)}addSheet(e=`${this.sheetNamePrefix}${this.lastSheetId+2}`){const t=canonicalize(e);if(this.mappingFromCanonicalName.has(t))throw new SheetNameAlreadyTakenError(e);this.lastSheetId++;const n=new Sheet(this.lastSheetId,e);return this.store(n),n.id}removeSheet(e){const t=this.fetchSheetById(e);e==this.lastSheetId&&--this.lastSheetId,this.mappingFromCanonicalName.delete(t.canonicalName),this.mappingFromId.delete(t.id)}getDisplayName(e){var t;return null===(t=this.mappingFromId.get(e))||void 0===t?void 0:t.displayName}*displayNames(){for(const e of this.mappingFromCanonicalName.values())yield e.displayName}numberOfSheets(){return this.mappingFromCanonicalName.size}hasSheetWithId(e){return this.mappingFromId.has(e)}hasSheetWithName(e){return this.mappingFromCanonicalName.has(canonicalize(e))}renameSheet(e,t){const n=this.fetchSheetById(e),r=n.displayName;if(r===t)return;const a=this.mappingFromCanonicalName.get(canonicalize(t));if(void 0!==a&&a.id!==n.id)throw new SheetNameAlreadyTakenError(t);const i=n.canonicalName;return this.mappingFromCanonicalName.delete(i),n.displayName=t,this.store(n),r}sheetNames(){return Array.from(this.mappingFromId.values()).map((e=>e.displayName))}store(e){this.mappingFromId.set(e.id,e),this.mappingFromCanonicalName.set(e.canonicalName,e)}fetchSheetById(e){const t=this.mappingFromId.get(e);if(void 0===t)throw new NoSheetWithIdError(e);return t}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class DependencyGraph{constructor(e,t,n,r,a,i,s,o){this.addressMapping=e,this.rangeMapping=t,this.sheetMapping=n,this.arrayMapping=r,this.stats=a,this.lazilyTransformingAstService=i,this.functionRegistry=s,this.namedExpressions=o,this.changes=ContentChanges.empty(),this.dependencyQueryAddresses=e=>{if(e instanceof RangeVertex)return this.rangeDependencyQuery(e).map((([e,t])=>e));{const t=this.formulaDependencyQuery(e);if(void 0!==t){const[e,n]=t;return n.map((t=>t instanceof NamedExpressionDependency?this.namedExpressions.namedExpressionOrPlaceholder(t.name,e.sheet).address:isSimpleCellAddress(t)?t:simpleCellRange(t.start,t.end)))}return[]}},this.dependencyQueryVertices=e=>{if(e instanceof RangeVertex)return this.rangeDependencyQuery(e).map((([e,t])=>t));{const t=this.formulaDependencyQuery(e);if(void 0!==t){const[e,n]=t;return n.map((t=>{if(t instanceof AbsoluteCellRange)return this.rangeMapping.fetchRange(t.start,t.end);if(t instanceof NamedExpressionDependency){const n=this.namedExpressions.namedExpressionOrPlaceholder(t.name,e.sheet);return this.addressMapping.fetchCell(n.address)}return this.addressMapping.fetchCell(t)}))}return[]}},this.rangeDependencyQuery=e=>{const t=[],{smallerRangeVertex:n,restRange:r}=this.rangeMapping.findSmallerRange(e.range);let a;void 0!==n&&this.graph.adjacentNodes(n).has(e)?(a=r,t.push([new AbsoluteCellRange(n.start,n.end),n])):a=e.range;for(const e of a.addresses(this)){const n=this.addressMapping.getCell(e);n instanceof EmptyCellVertex&&(n.address=e),void 0!==n&&t.push([e,n])}return t},this.formulaDependencyQuery=e=>{let t,n;if(!(e instanceof FormulaVertex))return;n=e.getAddress(this.lazilyTransformingAstService),t=e.getFormula(this.lazilyTransformingAstService);const r=collectDependencies(t,this.functionRegistry);return[n,absolutizeDependencies(r,n)]},this.graph=new Graph(this.dependencyQueryVertices)}static buildEmpty(e,t,n,r,a){return new DependencyGraph(new AddressMapping(t.chooseAddressMappingPolicy),new RangeMapping,new SheetMapping(t.translationPackage),new ArrayMapping,a,e,n,r)}setFormulaToCell(e,t,n,r,a,i){const s=FormulaVertex.fromAst(t,e,r,this.lazilyTransformingAstService.version());return this.exchangeOrAddFormulaVertex(s),this.processCellDependencies(n,s),this.graph.markNodeAsSpecialRecentlyChanged(s),a&&this.markAsVolatile(s),i&&this.markAsDependentOnStructureChange(s),this.correctInfiniteRangesDependency(e),this.getAndClearContentChanges()}setParsingErrorToCell(e,t){const n=this.shrinkPossibleArrayAndGetCell(e);return this.exchangeOrAddGraphNode(n,t),this.addressMapping.setCell(e,t),this.graph.markNodeAsSpecialRecentlyChanged(t),this.correctInfiniteRangesDependency(e),this.getAndClearContentChanges()}setValueToCell(e,t){const n=this.shrinkPossibleArrayAndGetCell(e);if(n instanceof ArrayVertex&&this.arrayMapping.removeArray(n.getRange()),n instanceof ValueCellVertex){n.getValues().rawValue!==t.rawValue&&(n.setValues(t),this.graph.markNodeAsSpecialRecentlyChanged(n))}else{const r=new ValueCellVertex(t.parsedValue,t.rawValue);this.exchangeOrAddGraphNode(n,r),this.addressMapping.setCell(e,r),this.graph.markNodeAsSpecialRecentlyChanged(r)}return this.correctInfiniteRangesDependency(e),this.getAndClearContentChanges()}setCellEmpty(e){const t=this.shrinkPossibleArrayAndGetCell(e);if(void 0===t)return ContentChanges.empty();if(this.graph.adjacentNodes(t).size>0){const n=new EmptyCellVertex(e);this.exchangeGraphNode(t,n),0===this.graph.adjacentNodesCount(n)?(this.removeVertex(n),this.addressMapping.removeCell(e)):(this.graph.markNodeAsSpecialRecentlyChanged(n),this.addressMapping.setCell(e,n))}else this.removeVertex(t),this.addressMapping.removeCell(e);return this.getAndClearContentChanges()}ensureThatVertexIsNonArrayCellVertex(e){if(e instanceof ArrayVertex)throw new Error("Illegal operation")}clearRecentlyChangedVertices(){this.graph.clearSpecialNodesRecentlyChanged()}verticesToRecompute(){return new Set([...this.graph.specialNodesRecentlyChanged,...this.volatileVertices()])}processCellDependencies(e,t){e.forEach((e=>{if(e instanceof AbsoluteCellRange){const n=e;let r=this.getRange(n.start,n.end);void 0===r&&(r=new RangeVertex(n),this.rangeMapping.setRange(r)),this.graph.addNode(r),n.isFinite()||this.graph.markNodeAsInfiniteRange(r);const{smallerRangeVertex:a,restRange:i}=this.rangeMapping.findSmallerRange(n);if(void 0!==a){if(this.graph.addEdge(a,r),r.bruteForce){r.bruteForce=!1;for(const e of n.addresses(this))this.graph.removeEdge(this.fetchCell(e),r)}}else r.bruteForce=!0;const s=this.arrayMapping.getArray(i);if(void 0!==s)this.graph.addEdge(s,r);else for(const e of i.addresses(this))this.graph.addEdge(this.fetchCellOrCreateEmpty(e),r);this.graph.addEdge(r,t),n.isFinite()&&this.correctInfiniteRangesDependenciesByRangeVertex(r)}else if(e instanceof NamedExpressionDependency){const n=t.getAddress(this.lazilyTransformingAstService).sheet,r=this.fetchNamedExpressionVertex(e.name,n);this.graph.addEdge(r,t)}else this.graph.addEdge(this.fetchCellOrCreateEmpty(e),t)}))}fetchNamedExpressionVertex(e,t){const n=this.namedExpressions.namedExpressionOrPlaceholder(e,t);return this.fetchCellOrCreateEmpty(n.address)}exchangeNode(e,t){const n=this.fetchCellOrCreateEmpty(e),r=this.fetchCellOrCreateEmpty(t);this.addressMapping.removeCell(e),this.exchangeGraphNode(n,r)}correctInfiniteRangesDependency(e){let t;for(const n of this.graph.infiniteRanges){const r=n;r.range.addressInRange(e)&&(t=null!=t?t:this.fetchCellOrCreateEmpty(e),this.graph.addEdge(t,r))}}fetchCellOrCreateEmpty(e){let t=this.addressMapping.getCell(e);return void 0===t&&(t=new EmptyCellVertex(e),this.graph.addNode(t),this.addressMapping.setCell(e,t)),t}removeRows(e){this.stats.measure(StatType.ADJUSTING_GRAPH,(()=>{for(const[t,n]of this.addressMapping.entriesFromRowsSpan(e)){for(const e of this.graph.adjacentNodes(n))this.graph.markNodeAsSpecialRecentlyChanged(e);if(n instanceof ArrayVertex){if(!n.isLeftCorner(t))continue;this.shrinkArrayToCorner(n),this.arrayMapping.removeArray(n.getRange())}this.removeVertex(n)}})),this.stats.measure(StatType.ADJUSTING_ADDRESS_MAPPING,(()=>{this.addressMapping.removeRows(e)}));const t=this.stats.measure(StatType.ADJUSTING_RANGES,(()=>{const t=this.truncateRanges(e,(e=>e.row));return this.getArrayVerticesRelatedToRanges(t)}));return this.stats.measure(StatType.ADJUSTING_ARRAY_MAPPING,(()=>{this.fixArraysAfterRemovingRows(e.sheet,e.rowStart,e.numberOfRows)})),this.addStructuralNodesToChangeSet(),{affectedArrays:t,contentChanges:this.getAndClearContentChanges()}}removeSheet(e){const t=new Set;for(const[n,r]of this.addressMapping.sheetEntries(e)){if(r instanceof ArrayVertex){if(t.has(r))continue;t.add(r)}for(const e of this.graph.adjacentNodes(r))this.graph.markNodeAsSpecialRecentlyChanged(e);this.removeVertex(r),this.addressMapping.removeCell(n)}this.stats.measure(StatType.ADJUSTING_ARRAY_MAPPING,(()=>{for(const e of t.values())this.arrayMapping.removeArray(e.getRange())})),this.stats.measure(StatType.ADJUSTING_RANGES,(()=>{const t=this.rangeMapping.removeRangesInSheet(e);for(const e of t)this.removeVertex(e);this.stats.measure(StatType.ADJUSTING_ADDRESS_MAPPING,(()=>{this.addressMapping.removeSheet(e)}))})),this.addStructuralNodesToChangeSet()}clearSheet(e){const t=new Set;for(const[n,r]of this.addressMapping.sheetEntries(e))r instanceof ArrayVertex?t.add(r):this.setCellEmpty(n);for(const e of t.values())this.setArrayEmpty(e);this.addStructuralNodesToChangeSet()}removeColumns(e){this.stats.measure(StatType.ADJUSTING_GRAPH,(()=>{for(const[t,n]of this.addressMapping.entriesFromColumnsSpan(e)){for(const e of this.graph.adjacentNodes(n))this.graph.markNodeAsSpecialRecentlyChanged(e);if(n instanceof ArrayVertex){if(!n.isLeftCorner(t))continue;this.shrinkArrayToCorner(n),this.arrayMapping.removeArray(n.getRange())}this.removeVertex(n)}})),this.stats.measure(StatType.ADJUSTING_ADDRESS_MAPPING,(()=>{this.addressMapping.removeColumns(e)}));const t=this.stats.measure(StatType.ADJUSTING_RANGES,(()=>{const t=this.truncateRanges(e,(e=>e.col));return this.getArrayVerticesRelatedToRanges(t)}));return this.stats.measure(StatType.ADJUSTING_ARRAY_MAPPING,(()=>this.fixArraysAfterRemovingColumns(e.sheet,e.columnStart,e.numberOfColumns))),this.addStructuralNodesToChangeSet(),{affectedArrays:t,contentChanges:this.getAndClearContentChanges()}}addRows(e){this.stats.measure(StatType.ADJUSTING_ADDRESS_MAPPING,(()=>{this.addressMapping.addRows(e.sheet,e.rowStart,e.numberOfRows)}));const t=this.stats.measure(StatType.ADJUSTING_RANGES,(()=>{const t=this.rangeMapping.moveAllRangesInSheetAfterRowByRows(e.sheet,e.rowStart,e.numberOfRows);return this.fixRangesWhenAddingRows(e.sheet,e.rowStart,e.numberOfRows),this.getArrayVerticesRelatedToRanges(t.verticesWithChangedSize)}));this.stats.measure(StatType.ADJUSTING_ARRAY_MAPPING,(()=>{this.fixArraysAfterAddingRow(e.sheet,e.rowStart,e.numberOfRows)}));for(const t of this.addressMapping.verticesFromRowsSpan(e))this.graph.markNodeAsSpecialRecentlyChanged(t);return this.addStructuralNodesToChangeSet(),{affectedArrays:t}}addColumns(e){this.stats.measure(StatType.ADJUSTING_ADDRESS_MAPPING,(()=>{this.addressMapping.addColumns(e.sheet,e.columnStart,e.numberOfColumns)}));const t=this.stats.measure(StatType.ADJUSTING_RANGES,(()=>{const t=this.rangeMapping.moveAllRangesInSheetAfterColumnByColumns(e.sheet,e.columnStart,e.numberOfColumns);return this.fixRangesWhenAddingColumns(e.sheet,e.columnStart,e.numberOfColumns),this.getArrayVerticesRelatedToRanges(t.verticesWithChangedSize)}));this.stats.measure(StatType.ADJUSTING_ARRAY_MAPPING,(()=>this.fixArraysAfterAddingColumn(e.sheet,e.columnStart,e.numberOfColumns)));for(const t of this.addressMapping.verticesFromColumnsSpan(e))this.graph.markNodeAsSpecialRecentlyChanged(t);return this.addStructuralNodesToChangeSet(),{affectedArrays:t,contentChanges:this.getAndClearContentChanges()}}ensureNoArrayInRange(e){if(this.arrayMapping.isFormulaArrayInRange(e))throw Error("It is not possible to move / replace cells with array")}isThereSpaceForArray(e){const t=e.getRangeOrUndef();if(void 0===t)return!1;for(const n of t.addresses(this)){const t=this.addressMapping.getCell(n);if(void 0!==t&&!(t instanceof EmptyCellVertex)&&t!==e)return!1}return!0}moveCells(e,t,n,r){for(const a of e.addressesWithDirection(t,n,this)){const i=simpleCellAddress(r,a.col+t,a.row+n);let s=this.addressMapping.getCell(a);const o=this.addressMapping.getCell(i);if(this.addressMapping.removeCell(a),void 0!==s){let t;this.graph.markNodeAsSpecialRecentlyChanged(s),this.addressMapping.setCell(i,s);for(const n of this.graph.adjacentNodes(s))n instanceof RangeVertex&&!e.containsRange(n.range)&&(t=null!=t?t:this.fetchCellOrCreateEmpty(a),this.graph.addEdge(t,n),this.graph.removeEdge(s,n));t&&(this.graph.markNodeAsSpecialRecentlyChanged(t),this.addressMapping.setCell(a,t))}if(void 0!==o){void 0===s&&this.addressMapping.removeCell(i);for(const e of this.graph.adjacentNodes(o))s=null!=s?s:this.fetchCellOrCreateEmpty(i),this.graph.addEdge(s,e),this.graph.markNodeAsSpecialRecentlyChanged(s);this.removeVertex(o)}}for(const t of this.rangeMapping.rangeVerticesContainedInRange(e))for(const n of this.graph.adjacentNodes(t))if(n instanceof RangeVertex&&!e.containsRange(n.range)){this.graph.removeEdge(t,n);for(const e of t.range.addresses(this)){const t=this.fetchCellOrCreateEmpty(e);this.graph.addEdge(t,n),this.addressMapping.setCell(e,t),this.graph.markNodeAsSpecialRecentlyChanged(t)}}this.rangeMapping.moveRangesInsideSourceRange(e,t,n,r)}setArrayEmpty(e){const t=AbsoluteCellRange.spanFrom(e.getAddress(this.lazilyTransformingAstService),e.width,e.height),n=this.graph.adjacentNodes(e);for(const e of t.addresses(this))this.addressMapping.removeCell(e);for(const t of n.values()){const n=collectAddressesDependentToRange(this.functionRegistry,t,e.getRange(),this.lazilyTransformingAstService,this);for(const e of n){const n=this.fetchCellOrCreateEmpty(e);this.graph.addEdge(n,t)}n.length>0&&this.graph.markNodeAsSpecialRecentlyChanged(t)}this.removeVertex(e),this.arrayMapping.removeArray(e.getRange())}addVertex(e,t){this.graph.addNode(t),this.addressMapping.setCell(e,t)}addArrayVertex(e,t){this.graph.addNode(t),this.setAddressMappingForArrayVertex(t,e)}*arrayFormulaNodes(){for(const e of this.graph.nodes)e instanceof ArrayVertex&&(yield e)}*entriesFromRowsSpan(e){yield*this.addressMapping.entriesFromRowsSpan(e)}*entriesFromColumnsSpan(e){yield*this.addressMapping.entriesFromColumnsSpan(e)}existsVertex(e){return this.addressMapping.has(e)}fetchCell(e){return this.addressMapping.fetchCell(e)}getCell(e){return this.addressMapping.getCell(e)}getCellValue(e){return this.addressMapping.getCellValue(e)}getRawValue(e){return this.addressMapping.getRawValue(e)}getScalarValue(e){const t=this.addressMapping.getCellValue(e);return t instanceof SimpleRangeValue?new CellError(ErrorType.VALUE,ErrorMessage.ScalarExpected):t}existsEdge(e,t){return this.graph.existsEdge(e,t)}getSheetId(e){return this.sheetMapping.fetch(e)}getSheetHeight(e){return this.addressMapping.getHeight(e)}getSheetWidth(e){return this.addressMapping.getWidth(e)}getArray(e){return this.arrayMapping.getArray(e)}setArray(e,t){this.arrayMapping.setArray(e,t)}getRange(e,t){return this.rangeMapping.getRange(e,t)}topSortWithScc(){return this.graph.topSortWithScc()}markAsVolatile(e){this.graph.markNodeAsSpecial(e)}markAsDependentOnStructureChange(e){this.graph.markNodeAsChangingWithStructure(e)}forceApplyPostponedTransformations(){for(const e of this.graph.nodes.values())e instanceof FormulaCellVertex&&e.ensureRecentData(this.lazilyTransformingAstService)}volatileVertices(){return this.graph.specialNodes}getArrayVerticesRelatedToRanges(e){const t=e.map((e=>this.graph.hasNode(e)?Array.from(this.graph.adjacentNodes(e)).filter((e=>e instanceof ArrayVertex)):[]));return new Set(...t)}*rawValuesFromRange(e){for(const t of e.addresses(this)){const e=this.getScalarValue(t);e!==EmptyValue&&(yield[getRawValue(e),t])}}*entriesFromRange(e){for(const t of e.addresses(this))yield[t,this.getCell(t)]}exchangeGraphNode(e,t){this.graph.addNode(t);const n=this.graph.adjacentNodes(e);this.removeVertex(e),n.forEach((e=>{this.graph.hasNode(e)&&this.graph.addEdge(t,e)}))}exchangeOrAddGraphNode(e,t){e?this.exchangeGraphNode(e,t):this.graph.addNode(t)}computeListOfValuesInRange(e){const t=[];for(const n of e.addresses(this)){const e=this.getScalarValue(n);t.push(e)}return t}shrinkArrayToCorner(e){this.cleanAddressMappingUnderArray(e);for(const t of this.adjacentArrayVertices(e)){let n;n=t instanceof FormulaVertex?this.formulaDirectDependenciesToArray(t,e):this.rangeDirectDependenciesToArray(t,e);let r=!1;for(const[a,i]of n)e.isLeftCorner(a)&&(r=!0),this.graph.addEdge(i,t),this.graph.markNodeAsSpecialRecentlyChanged(i);r||this.graph.removeEdge(e,t)}this.graph.markNodeAsSpecialRecentlyChanged(e)}isArrayInternalCell(e){const t=this.getCell(e);return t instanceof ArrayVertex&&!t.isLeftCorner(e)}getAndClearContentChanges(){const e=this.changes;return this.changes=ContentChanges.empty(),e}getAdjacentNodesAddresses(e){const t=this.graph.adjacentNodes(e),n=[];return t.forEach((e=>{const t=e;t instanceof RangeVertex?n.push(simpleCellRange(t.start,t.end)):n.push(t.getAddress(this.lazilyTransformingAstService))})),n}correctInfiniteRangesDependenciesByRangeVertex(e){for(const t of this.graph.infiniteRanges){const n=t,r=e.range.intersectionWith(n.range);if(void 0!==r)for(const e of r.addresses(this))this.graph.addEdge(this.fetchCellOrCreateEmpty(e),t)}}cleanAddressMappingUnderArray(e){const t=e.getRange();for(const n of t.addresses(this)){const t=e.getArrayCellValue(n);this.getCell(n)===e?e.isLeftCorner(n)?this.changes.addChange(new CellError(ErrorType.REF),n,t):(this.addressMapping.removeCell(n),this.changes.addChange(EmptyValue,n,t)):this.changes.addChange(EmptyValue,n,t)}}*formulaDirectDependenciesToArray(e,t){var n;const[,r]=null!==(n=this.formulaDependencyQuery(e))&&void 0!==n?n:[];if(void 0!==r)for(const e of r)if(!(e instanceof NamedExpressionDependency||e instanceof AbsoluteCellRange)&&t.getRange().addressInRange(e)){const t=this.fetchCellOrCreateEmpty(e);yield[e,t]}}*rangeDirectDependenciesToArray(e,t){const{restRange:n}=this.rangeMapping.findSmallerRange(e.range);for(const e of n.addresses(this))if(t.getRange().addressInRange(e)){const t=this.fetchCellOrCreateEmpty(e);yield[e,t]}}*adjacentArrayVertices(e){const t=this.graph.adjacentNodes(e);for(const e of t)(e instanceof FormulaVertex||e instanceof RangeVertex)&&(yield e)}addStructuralNodesToChangeSet(){for(const e of this.graph.specialNodesStructuralChanges)this.graph.markNodeAsSpecialRecentlyChanged(e)}fixRangesWhenAddingRows(e,t,n){const r=Array.from(this.rangeMapping.rangesInSheet(e));for(const e of r)if(e.range.includesRow(t+n))if(e.bruteForce){const r=e.range.rangeWithSameWidth(t,n);for(const t of r.addresses(this))this.graph.addEdge(this.fetchCellOrCreateEmpty(t),e)}else{let t=e,n=this.rangeMapping.findSmallerRange(t.range);if(void 0!==n.smallerRangeVertex)continue;for(;void 0===n.smallerRangeVertex;){const e=new RangeVertex(AbsoluteCellRange.spanFrom(t.range.start,t.range.width(),t.range.height()-1));this.rangeMapping.setRange(e),this.graph.addNode(e);const r=new AbsoluteCellRange(simpleCellAddress(t.range.start.sheet,t.range.start.col,t.range.end.row),t.range.end);this.addAllFromRange(r,t),this.graph.addEdge(e,t),t=e,n=this.rangeMapping.findSmallerRange(t.range)}this.graph.addEdge(n.smallerRangeVertex,t),this.addAllFromRange(n.restRange,t),this.graph.removeEdge(n.smallerRangeVertex,e)}}addAllFromRange(e,t){for(const n of e.addresses(this))this.graph.addEdge(this.fetchCellOrCreateEmpty(n),t)}fixRangesWhenAddingColumns(e,t,n){for(const r of this.rangeMapping.rangesInSheet(e))if(r.range.includesColumn(t+n)){let a;a=r.bruteForce?r.range.rangeWithSameHeight(t,n):AbsoluteCellRange.spanFrom(simpleCellAddress(e,t,r.range.end.row),n,1);for(const e of a.addresses(this))this.graph.addEdge(this.fetchCellOrCreateEmpty(e),r)}}exchangeOrAddFormulaVertex(e){const t=e.getAddress(this.lazilyTransformingAstService),n=AbsoluteCellRange.spanFrom(t,e.width,e.height),r=this.shrinkPossibleArrayAndGetCell(t);if(e instanceof ArrayVertex&&this.setArray(n,e),this.exchangeOrAddGraphNode(r,e),this.addressMapping.setCell(t,e),e instanceof ArrayVertex){if(!this.isThereSpaceForArray(e))return;for(const t of n.addresses(this)){if(e.isLeftCorner(t))continue;const n=this.getCell(t);this.exchangeOrAddGraphNode(n,e)}}for(const t of n.addresses(this))this.addressMapping.setCell(t,e)}setAddressMappingForArrayVertex(e,t){if(this.addressMapping.setCell(t,e),!(e instanceof ArrayVertex))return;const n=AbsoluteCellRange.spanFromOrUndef(t,e.width,e.height);if(void 0!==n&&(this.setArray(n,e),this.isThereSpaceForArray(e)))for(const t of n.addresses(this))this.addressMapping.setCell(t,e)}truncateRanges(e,t){const{verticesToRemove:n,verticesToMerge:r,verticesWithChangedSize:a}=this.rangeMapping.truncateRanges(e,t);for(const[e,t]of r)this.mergeRangeVertices(e,t);for(const e of n)this.removeVertexAndCleanupDependencies(e);return a}fixArraysAfterAddingRow(e,t,n){if(this.arrayMapping.moveArrayVerticesAfterRowByRows(e,t,n),!(t<=0))for(const[,r]of this.arrayMapping.arraysInRows(RowsSpan.fromRowStartAndEnd(e,t-1,t-1))){const a=r.getRange();for(let i=a.start.col;i<=a.end.col;++i)for(let s=t;s<=a.end.row;++s){const t=simpleCellAddress(e,i,s),a=simpleCellAddress(e,i,s+n),o=r.getArrayCellValue(t);this.addressMapping.moveCell(a,t),this.changes.addChange(EmptyValue,a,o)}}}fixArraysAfterRemovingRows(e,t,n){if(this.arrayMapping.moveArrayVerticesAfterRowByRows(e,t,-n),!(t<=0))for(const[,n]of this.arrayMapping.arraysInRows(RowsSpan.fromRowStartAndEnd(e,t-1,t-1)))if(this.isThereSpaceForArray(n))for(const e of n.getRange().addresses(this))this.addressMapping.setCell(e,n);else this.setNoSpaceIfArray(n)}fixArraysAfterAddingColumn(e,t,n){if(this.arrayMapping.moveArrayVerticesAfterColumnByColumns(e,t,n),!(t<=0))for(const[,r]of this.arrayMapping.arraysInCols(ColumnsSpan.fromColumnStartAndEnd(e,t-1,t-1))){const a=r.getRange();for(let i=a.start.row;i<=a.end.row;++i)for(let s=t;s<=a.end.col;++s){const t=simpleCellAddress(e,s,i),a=simpleCellAddress(e,s+n,i),o=r.getArrayCellValue(t);this.addressMapping.moveCell(a,t),this.changes.addChange(EmptyValue,a,o)}}}fixArraysAfterRemovingColumns(e,t,n){if(this.arrayMapping.moveArrayVerticesAfterColumnByColumns(e,t,-n),!(t<=0))for(const[,n]of this.arrayMapping.arraysInCols(ColumnsSpan.fromColumnStartAndEnd(e,t-1,t-1)))if(this.isThereSpaceForArray(n))for(const e of n.getRange().addresses(this))this.addressMapping.setCell(e,n);else this.setNoSpaceIfArray(n)}shrinkPossibleArrayAndGetCell(e){const t=this.getCell(e);return t instanceof ArrayVertex?(this.setNoSpaceIfArray(t),this.getCell(e)):t}setNoSpaceIfArray(e){e instanceof ArrayVertex&&(this.shrinkArrayToCorner(e),e.setNoSpace())}removeVertex(e){this.removeVertexAndCleanupDependencies(e),e instanceof RangeVertex&&this.rangeMapping.removeRange(e)}mergeRangeVertices(e,t){const n=this.graph.adjacentNodes(t);this.removeVertexAndCleanupDependencies(t),this.graph.softRemoveEdge(e,t),n.forEach((t=>{this.graph.hasNode(t)&&this.graph.addEdge(e,t)}))}removeVertexAndCleanupDependencies(e){const t=new Set(this.graph.removeNode(e));for(;t.size>0;){const e=t.values().next().value;t.delete(e),this.graph.hasNode(e)&&0===this.graph.adjacentNodesCount(e)&&((e instanceof RangeVertex||e instanceof EmptyCellVertex)&&this.graph.removeNode(e).forEach((e=>t.add(e))),e instanceof RangeVertex?this.rangeMapping.removeRange(e):e instanceof EmptyCellVertex&&this.addressMapping.removeCell(e.address))}}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class EmptyCellVertex{constructor(e){this.address=e}getCellValue(){return EmptyValue}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class ValueCellVertex{constructor(e,t){this.parsedValue=e,this.rawValue=t}getValues(){return{parsedValue:this.parsedValue,rawValue:this.rawValue}}setValues(e){this.parsedValue=e.parsedValue,this.rawValue=e.rawValue}getCellValue(){return this.parsedValue}setCellValue(e){throw"SetCellValue is deprecated for ValueCellVertex"}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class ParsingErrorVertex{constructor(e,t){this.errors=e,this.rawInput=t}getCellValue(){return CellError.parsingError()}getFormula(){return this.rawInput}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class SparseStrategy{constructor(e,t){this.width=e,this.height=t,this.mapping=new Map}getCell(e){var t;return null===(t=this.mapping.get(e.col))||void 0===t?void 0:t.get(e.row)}setCell(e,t){this.width=Math.max(this.width,e.col+1),this.height=Math.max(this.height,e.row+1);let n=this.mapping.get(e.col);n||(n=new Map,this.mapping.set(e.col,n)),n.set(e.row,t)}has(e){var t;return!!(null===(t=this.mapping.get(e.col))||void 0===t?void 0:t.get(e.row))}getHeight(){return this.height}getWidth(){return this.width}removeCell(e){var t;null===(t=this.mapping.get(e.col))||void 0===t||t.delete(e.row)}addRows(e,t){this.mapping.forEach((n=>{const r=new Map;n.forEach(((a,i)=>{i>=e&&(r.set(i+t,a),n.delete(i))})),r.forEach(((e,t)=>{n.set(t,e)}))})),this.height+=t}addColumns(e,t){const n=new Map;this.mapping.forEach(((r,a)=>{a>=e&&(n.set(a+t,r),this.mapping.delete(a))})),n.forEach(((e,t)=>{this.mapping.set(t,e)})),this.width+=t}removeRows(e){this.mapping.forEach((t=>{const n=new Map;t.forEach(((r,a)=>{a>=e.rowStart&&(t.delete(a),a>e.rowEnd&&n.set(a-e.numberOfRows,r))})),n.forEach(((e,n)=>{t.set(n,e)}))}));const t=Math.min(this.height-1,e.rowEnd),n=Math.max(0,t-e.rowStart+1);this.height=Math.max(0,this.height-n)}removeColumns(e){const t=new Map;this.mapping.forEach(((n,r)=>{r>=e.columnStart&&(this.mapping.delete(r),r>e.columnEnd&&t.set(r-e.numberOfColumns,n))})),t.forEach(((e,t)=>{this.mapping.set(t,e)}));const n=Math.min(this.width-1,e.columnEnd),r=Math.max(0,n-e.columnStart+1);this.width=Math.max(0,this.width-r)}*getEntries(e){for(const[t,n]of this.mapping)for(const[r,a]of n)yield[simpleCellAddress(e,t,r),a]}*verticesFromColumn(e){const t=this.mapping.get(e);if(void 0!==t)for(const[e,n]of t)yield n}*verticesFromRow(e){for(const t of this.mapping.values()){const n=t.get(e);void 0!==n&&(yield n)}}*verticesFromColumnsSpan(e){for(const t of e.columns()){const e=this.mapping.get(t);if(void 0!==e)for(const[t,n]of e)yield n}}*verticesFromRowsSpan(e){for(const t of this.mapping.values())for(const n of e.rows()){const e=t.get(n);void 0!==e&&(yield e)}}*entriesFromRowsSpan(e){for(const[t,n]of this.mapping.entries())for(const r of e.rows()){const a=n.get(r);void 0!==a&&(yield[simpleCellAddress(e.sheet,t,r),a])}}*entriesFromColumnsSpan(e){for(const t of e.columns()){const n=this.mapping.get(t);if(void 0!==n)for(const[r,a]of n.entries())yield[simpleCellAddress(e.sheet,t,r),a]}}*vertices(){for(const[e,t]of this.mapping)for(const[e,n]of t)void 0!==n&&(yield n)}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class DenseStrategy{constructor(e,t){this.width=e,this.height=t,this.mapping=new Array(t);for(let n=0;ne instanceof ArrayVertex?e.isLeftCorner(t)?CellType.ARRAYFORMULA:CellType.ARRAY:e instanceof FormulaCellVertex||e instanceof ParsingErrorVertex?CellType.FORMULA:e instanceof ValueCellVertex?CellType.VALUE:CellType.EMPTY;var CellValueNoNumber,CellValueJustNumber;!function(e){e.EMPTY="EMPTY",e.NUMBER="NUMBER",e.STRING="STRING",e.BOOLEAN="BOOLEAN",e.ERROR="ERROR"}(CellValueNoNumber||(CellValueNoNumber={})),function(e){e.NUMBER="NUMBER"}(CellValueJustNumber||(CellValueJustNumber={}));const CellValueType=Object.assign(Object.assign({},CellValueNoNumber),CellValueJustNumber),CellValueDetailedType=Object.assign(Object.assign({},CellValueNoNumber),NumberType),CellValueTypeOrd=e=>{switch(e){case CellValueType.EMPTY:return 0;case CellValueType.NUMBER:return 1;case CellValueType.STRING:return 2;case CellValueType.BOOLEAN:return 3;case CellValueType.ERROR:return 4}throw new Error("Cell value not computed")},getCellValueType=e=>{if(e===EmptyValue)return CellValueType.EMPTY;if(e instanceof CellError||e instanceof SimpleRangeValue)return CellValueType.ERROR;if("string"==typeof e)return CellValueType.STRING;if(isExtendedNumber(e))return CellValueType.NUMBER;if("boolean"==typeof e)return CellValueType.BOOLEAN;throw new Error("Cell value not computed")},getCellValueDetailedType=e=>isExtendedNumber(e)?getTypeOfExtendedNumber(e):getCellValueType(e),getCellValueFormat=e=>isExtendedNumber(e)?getFormatOfExtendedNumber(e):void 0;class CellError{constructor(e,t,n){this.type=e,this.message=t,this.root=n}static parsingError(){return new CellError(ErrorType.ERROR,ErrorMessage.ParseError)}attachRootVertex(e){return void 0===this.root?new CellError(this.type,this.message,e):this}}const simpleRowAddress=(e,t)=>({sheet:e,row:t}),invalidSimpleRowAddress=e=>e.row<0,simpleColumnAddress=(e,t)=>({sheet:e,col:t}),invalidSimpleColumnAddress=e=>e.col<0,simpleCellAddress=(e,t,n)=>({sheet:e,col:t,row:n}),invalidSimpleCellAddress=e=>e.col<0||e.row<0,movedSimpleCellAddress=(e,t,n,r)=>simpleCellAddress(t,e.col+n,e.row+r),addressKey=e=>`${e.sheet},${e.row},${e.col}`;function isSimpleCellAddress(e){return!(!e||"object"!=typeof e&&"function"!=typeof e)&&("col"in e&&"number"==typeof e.col&&"row"in e&&"number"==typeof e.row&&"sheet"in e&&"number"==typeof e.sheet)}const absoluteSheetReference=(e,t)=>{var n;return null!==(n=e.sheet)&&void 0!==n?n:t.sheet},equalSimpleCellAddress=(e,t)=>e.sheet===t.sheet&&e.col===t.col&&e.row===t.row; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class DetailedCellError{constructor(e,t,n){var r;this.value=t,this.address=n,this.type=e.type,this.message=null!==(r=e.message)&&void 0!==r?r:""}toString(){return this.value}valueOf(){return this.value}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */function configValueFromParam(e,t,n){if(void 0===e)return Config.defaultConfig[n];if("string"==typeof t){if(typeof e===t)return e;throw new ExpectedValueOfTypeError(t,n)}if(t.includes(e))return e;throw new ExpectedOneOfValuesError(t.map((e=>`'${e}'`)).join(" "),n)}function validateNumberToBeAtLeast(e,t,n){if(en)throw new ConfigValueTooBigError(t,n)}function configValueFromParamCheck(e,t,n,r){if(t(e))return e;if(void 0===e)return Config.defaultConfig[r];throw new ExpectedValueOfTypeError(n,r)}function configCheckIfParametersNotInConflict(...e){const t=new Map;e.forEach((e=>{const n=t.get(e.value)||[];n.push(e.name),t.set(e.value,n)}));const n=[];for(const e of t.values())e.length>1&&n.push(e);if(n.length>0){n.forEach((e=>e.sort()));const e=n.map((e=>`[${e}]`)).join("; ");throw new Error(`Config initialization failed. Parameters in conflict: ${e}`)}}function validateArgToType(e,t,n){if(typeof e!==t)throw new ExpectedValueOfTypeError(t,n)} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */function defaultParseToDateTime(e,t,n){let r=(e=e.replace(/\s\s+/g," ").trim().toLowerCase()).substring(e.length-2);"am"===r||"pm"===r?e=e.substring(0,e.length-2).trim():(r=e.substring(e.length-1),"a"===r||"p"===r?e=e.substring(0,e.length-1).trim():r=void 0);const a=e.split(/[ /.-]/g);a.length>=2&&a[a.length-2].includes(":")&&(a[a.length-2]=a[a.length-2]+"."+a[a.length-1],a.pop());const i=a[a.length-1].split(":");if(void 0!==r&&i.push(r),1===a.length)return defaultParseToTime(i,n);if(1===i.length)return defaultParseToDate(a,t);const s=defaultParseToDate(a.slice(0,a.length-1),t),o=defaultParseToTime(i,n);return void 0===s||void 0===o?void 0:Object.assign(Object.assign({},s),o)}const secondsExtendedRegexp=/^ss(\.(s+|0+))?$/;function defaultParseToTime(e,t){if(void 0===t)return;(t=t.toLowerCase()).endsWith("am/pm")?t=t.substring(0,t.length-5).trim():t.endsWith("a/p")&&(t=t.substring(0,t.length-3).trim());const n=t.split(":");let r;if("am"===e[e.length-1]||"a"===e[e.length-1]?(r=!1,e.pop()):"pm"!==e[e.length-1]&&"p"!==e[e.length-1]||(r=!0,e.pop()),e.length!==n.length)return;const a=n.indexOf("hh"),i=n.indexOf("mm"),s=n.findIndex((e=>secondsExtendedRegexp.test(e))),o=-1!==a?e[a]:"0";if(!/^\d+$/.test(o))return;let l=Number(o);if(void 0!==r){if(l<0||l>12)return;l%=12,r&&(l+=12)}const u=-1!==i?e[i]:"0";if(!/^\d+$/.test(u))return;const c=Number(u),p=-1!==s?e[s]:"0";if(!/^\d+(\.\d+)?$/.test(p))return;return{hours:l,minutes:c,seconds:Math.round(1e3*Number(p))/1e3}}function defaultParseToDate(e,t){if(void 0===t)return;const n=t.toLowerCase().split(/[ /.-]/g);if(e.length!==n.length)return;const r=n.indexOf("mm"),a=n.indexOf("dd"),i=n.indexOf("yyyy"),s=n.indexOf("yy");if(!(r in e)||!(a in e)||!(i in e)&&!(s in e))return;if(i in e&&s in e)return;let o;if(i in e){const t=e[i];if(!/^\d+$/.test(t))return;if(o=Number(t),o<1e3||o>9999)return}else{const t=e[s];if(!/^\d+$/.test(t))return;if(o=Number(t),o<0||o>99)return}const l=e[r];if(!/^\d+$/.test(l))return;const u=Number(l),c=e[a];if(!/^\d+$/.test(c))return;return{year:o,month:u,day:Number(c)}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */const numDays=[31,28,31,30,31,30,31,31,30,31,30,31],prefSumDays=[0,31,59,90,120,151,181,212,243,273,304,334],SECONDS_PER_MINUTE=60,MINUTES_PER_HOUR=60,HOURS_PER_DAY=24;function instanceOfSimpleDate(e){return!(!e||"object"!=typeof e&&"function"!=typeof e)&&("year"in e&&"number"==typeof e.year&&"month"in e&&"number"==typeof e.month&&"day"in e&&"number"==typeof e.day)}function instanceOfSimpleTime(e){return!(!e||"object"!=typeof e&&"function"!=typeof e)&&("hours"in e&&"number"==typeof e.hours&&"minutes"in e&&"number"==typeof e.minutes&&"seconds"in e&&"number"==typeof e.seconds)}const maxDate={year:9999,month:12,day:31};class DateTimeHelper{constructor(e){this.config=e,this.minDateAbsoluteValue=this.dateToNumberFromZero(e.nullDate),this.maxDateValue=this.dateToNumber(maxDate),this.leapYear1900=e.leapYear1900,!this.leapYear1900&&0<=this.dateToNumber({year:1900,month:2,day:28})?this.epochYearZero=this.numberToSimpleDate(2).year:this.epochYearZero=this.numberToSimpleDate(1).year,this.parseDateTime=e.parseDateTime}getWithinBounds(e){return e<=this.maxDateValue&&e>=0?e:void 0}dateStringToDateNumber(e){const{dateTime:t,dateFormat:n="",timeFormat:r=""}=this.parseDateTimeFromConfigFormats(e);if(void 0!==t)return instanceOfSimpleTime(t)?instanceOfSimpleDate(t)?new DateTimeNumber(timeToNumber(t)+this.dateToNumber(t),n+" "+r):new TimeNumber(timeToNumber(t),r):instanceOfSimpleDate(t)?new DateNumber(this.dateToNumber(t),n):0}parseDateTimeFromConfigFormats(e){return this.parseDateTimeFromFormats(e,this.config.dateFormats,this.config.timeFormats)}getNullYear(){return this.config.nullYear}getEpochYearZero(){return this.epochYearZero}isValidDate(e){return!(isNaN(e.year)||isNaN(e.month)||isNaN(e.day))&&(e.day===Math.round(e.day)&&e.month===Math.round(e.month)&&e.year===Math.round(e.year)&&(!(e.year<1582)&&(!(e.month<1||e.month>12)&&(!(e.day<1)&&(this.isLeapYear(e.year)&&2===e.month?e.day<=29:e.day<=numDays[e.month-1])))))}dateToNumber(e){return this.dateToNumberFromZero(e)-this.minDateAbsoluteValue}relativeNumberToAbsoluteNumber(e){return e+this.minDateAbsoluteValue-(this.leapYear1900?1:0)}numberToSimpleDate(e){const t=Math.floor(e)+this.minDateAbsoluteValue;let n=Math.floor(t/365.2425);this.dateToNumberFromZero({year:n+1,month:1,day:1})<=t?n++:this.dateToNumberFromZero({year:n-1,month:1,day:1})>t&&n--;const r=t-this.dateToNumberFromZero({year:n,month:1,day:1}),a=dayToMonth(r-(this.isLeapYear(n)&&r>=59?1:0));return{year:n,month:a+1,day:r-prefSumDays[a]-(this.isLeapYear(n)&&a>1?1:0)+1}}numberToSimpleDateTime(e){const t=numberToSimpleTime(e%1),n=Math.floor(t.hours/HOURS_PER_DAY);t.hours=t.hours%HOURS_PER_DAY;const r=this.numberToSimpleDate(Math.floor(e)+n);return Object.assign(Object.assign({},r),t)}leapYearsCount(e){return Math.floor(e/4)-Math.floor(e/100)+Math.floor(e/400)+(this.config.leapYear1900&&e>=1900?1:0)}daysInMonth(e,t){return this.isLeapYear(e)&&2===t?29:numDays[t-1]}endOfMonth(e){return{year:e.year,month:e.month,day:this.daysInMonth(e.year,e.month)}}toBasisUS(e,t){return 31===e.day&&(e.day=30),30===e.day&&31===t.day&&(t.day=30),2===e.month&&e.day===this.daysInMonth(e.year,e.month)&&(e.day=30,2===t.month&&t.day===this.daysInMonth(t.year,t.month)&&(t.day=30)),[e,t]}yearLengthForBasis(e,t){return e.year!==t.year?e.year+1!==t.year||e.month=0&&r.year<100&&(r.year2||2===e.month&&e.day>=29?this.leapYearsCount(e.year):this.leapYearsCount(e.year-1)}dateToNumberFromZero(e){return 365*e.year+prefSumDays[e.month-1]+e.day-1+(e.month<=2?this.leapYearsCount(e.year-1):this.leapYearsCount(e.year))}isLeapYear(e){return!(e%4)&&(!!(e%100)||(!(e%400)||1900===e&&this.config.leapYear1900))}}function dayToMonth(e){let t=0;return prefSumDays[t+6]<=e&&(t+=6),prefSumDays[t+3]<=e&&(t+=3),prefSumDays[t+2]<=e?t+=2:prefSumDays[t+1]<=e&&(t+=1),t}function offsetMonth(e,t){const n=12*e.year+e.month-1+t;return{year:Math.floor(n/12),month:n%12+1,day:e.day}}function truncateDayInMonth(e){return{year:e.year,month:e.month,day:Math.min(e.day,numDays[e.month-1])}}function roundToNearestSecond(e){return Math.round(3600*e*24)/86400}function roundToEpsilon(e,t=1){return Math.round(e*t)/t}function numberToSimpleTime(e){const t=e*HOURS_PER_DAY*MINUTES_PER_HOUR*SECONDS_PER_MINUTE,n=roundToEpsilon(t%SECONDS_PER_MINUTE,1e5)%SECONDS_PER_MINUTE,r=(t-n)/SECONDS_PER_MINUTE,a=Math.round(r%MINUTES_PER_HOUR)%MINUTES_PER_HOUR,i=(r-a)/MINUTES_PER_HOUR;return{hours:Math.round(i),minutes:a,seconds:n}}function timeToNumber(e){return((e.seconds/60+e.minutes)/60+e.hours)/24}function toBasisEU(e){return{year:e.year,month:e.month,day:Math.min(30,e.day)}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class AlwaysDense{call(){return DenseStrategy}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */const dateFormatRegex=/(\\.|dd|DD|d|D|mm|MM|m|M|YYYY|YY|yyyy|yy|HH|hh|H|h|ss(\.(0+|s+))?|s|AM\/PM|am\/pm|A\/P|a\/p|\[mm]|\[MM]|\[hh]|\[HH])/g,numberFormatRegex=/(\\.|[#0]+(\.[#0]*)?)/g;var TokenType,FormatExpressionType;function formatToken(e,t){return{type:e,value:t}}function matchDateFormat(e){dateFormatRegex.lastIndex=0;const t=[];let n;do{n=dateFormatRegex.exec(e),null!==n&&t.push(n)}while(n);return t}function matchNumberFormat(e){numberFormatRegex.lastIndex=0;const t=numberFormatRegex.exec(e);return null!==t?[t]:[]}function createTokens(e,t){const n=[];let r=0;for(let a=0;aisEscapeToken(e)))?void 0:{type:FormatExpressionType.DATE,tokens:createTokens(t,e)}}function parseForNumberFormat(e){const t=matchNumberFormat(e);return t.every((e=>isEscapeToken(e)))?void 0:{type:FormatExpressionType.NUMBER,tokens:createTokens(t,e)}}function isEscapeToken(e){return e[0].startsWith("\\")} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */function format(e,t,n,r){const a=n.stringifyDateTime(r.numberToSimpleDateTime(e),t);if(void 0!==a)return a;const i=n.stringifyDuration(numberToSimpleTime(e),t);if(void 0!==i)return i;const s=parseForNumberFormat(t);return void 0!==s?numberFormat(s.tokens,e):t}function padLeft(e,t){let n=e+"";for(;n.lengthc.length){c=padLeft(c,countChars(s.substr(0,s.length-c.length),"0")+c.length)}p=padRight(p,countChars(o.substr(p.length,o.length-p.length),"0")+p.length),n+=c+l+p}return n}function defaultStringifyDuration(e,t){const n=parseForDateTimeFormat(t);if(void 0===n)return;const r=n.tokens;let a="";for(const t of r)if(t.type!==TokenType.FREE_TEXT)switch(t.value.toLowerCase()){case"h":case"hh":a+=padLeft(e.hours,t.value.length),e.hours=0;break;case"[hh]":a+=padLeft(e.hours,t.value.length-2),e.hours=0;break;case"m":case"mm":a+=padLeft(e.minutes,t.value.length),e.minutes=0;break;case"[mm]":a+=padLeft(e.minutes+60*e.hours,t.value.length-2),e.minutes=0,e.hours=0;break;case"s":case"ss":a+=padLeft(Math.floor(e.seconds),t.value.length);break;default:if(secondsExtendedRegexp.test(t.value)){const n=Math.max(t.value.length-3,0);a+=(e.seconds<10?"0":"")+Math.floor(e.seconds*Math.pow(10,n))/Math.pow(10,n);continue}return}else a+=t.value;return a}function defaultStringifyDateTime(e,t){const n=parseForDateTimeFormat(t);if(void 0===n)return;const r=n.tokens;let a="",i=!1;const s=r.some((e=>e.type===TokenType.FORMAT&&("a/p"===e.value||"A/P"===e.value||"am/pm"===e.value||"AM/PM"===e.value)));for(let t=0;tparseInt(e,16),_pi=e=>parseInt(e,10),_nm=e=>(e+"").replace(/\-/g,""),_ss=(e,t,n)=>e.substr(t,n),_cp=e=>e.codePointAt(0)-65;function extractTime(e){return 25===_nm(e)[_rl]?_hd(_ss(_nm(e),_hd("12"),_cp("F")))/(_hd(_ss(_nm(e),_cp("C"),_cp("Y")>>4))||1+(~~![][_rl]<<3)):0}function checkKeySchema(e){if((e=(e+"").replace(/\-/g,""))[_rl]!==_cp("Z"))return!1;let t=0;return[[0,_cp("G")+1],[_cp("H"),_cp("H")-1],[_cp("G")+_cp("H"),_cp("G")]].reduce(((n,[r,a],i)=>(n|=(_pi(`${_pi(_hd(_ss(e,t+r-(0===i?0:2),a+(i?2:0)))+(_hd(_ss(e,t+r+a,2))+[]).padStart(2,"0"))}`)%97||2)>>1,t+=2,n)),_cp("A"))===[]+1>>1} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */const consoleMessages={invalid:()=>"The license key for HyperFormula is invalid.",expired:({keyValidityDate:e})=>`The license key for HyperFormula expired on ${e}, and is not valid for the installed version.`,missing:()=>"The license key for HyperFormula is missing."};let _notified=!1;function checkLicenseKeyValidity(e){const t={template:"missing",vars:{}};if("gpl-v3"===e||"internal-use-in-handsontable"===e)t.template="valid";else if("string"==typeof e&&checkKeySchema(e)){const[n,r,a]="08/09/2022".split("/"),i=Math.floor(new Date(`${r}/${n}/${a}`).getTime()/864e5),s=extractTime(e);t.vars.keyValidityDate=formatDate(new Date(864e5*(s+1))),t.template=i>s?"expired":"valid"}else""!==e&&(t.template="invalid");return _notified||"valid"===t.template||(console.warn(consoleMessages[t.template](t.vars)),_notified=!0),t.template}function formatDate(e){return`${["January","February","March","April","May","June","July","August","September","October","November","December"][e.getMonth()]} ${e.getDate()}, ${e.getFullYear()}`} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */var CellContent,ClipboardOperationType,ClipboardCellType;function isFormula(e){return e.startsWith("=")}function isBoolean(e){const t=e.toLowerCase();return"true"===t||"false"===t}function isError(e,t){const n=e.toUpperCase();return/#[A-Za-z0-9\/]+[?!]?/.test(n)&&Object.prototype.hasOwnProperty.call(t,n)}!function(e){e.Number=class{constructor(e){this.value=e,this.value=cloneNumber(this.value,fixNegativeZero(getRawValue(this.value)))}};e.String=class{constructor(e){this.value=e}};e.Boolean=class{constructor(e){this.value=e}};class t{static getSingletonInstance(){return t.instance||(t.instance=new t),t.instance}}e.Empty=t;e.Formula=class{constructor(e){this.formula=e}};e.Error=class{constructor(e,t){this.value=new CellError(e,t)}}}(CellContent||(CellContent={}));class CellContentParser{constructor(e,t,n){this.config=e,this.dateHelper=t,this.numberLiteralsHelper=n}parse(e){if(null==e)return CellContent.Empty.getSingletonInstance();if("number"==typeof e)return isNumberOverflow(e)?new CellContent.Error(ErrorType.NUM,ErrorMessage.ValueLarge):new CellContent.Number(e);if("boolean"==typeof e)return new CellContent.Boolean(e);if(e instanceof Date){const t=this.dateHelper.dateToNumber({day:e.getDate(),month:e.getMonth()+1,year:e.getFullYear()})+timeToNumber({hours:e.getHours(),minutes:e.getMinutes(),seconds:e.getSeconds()+e.getMilliseconds()/1e3});return t<0?new CellContent.Error(ErrorType.NUM,ErrorMessage.DateBounds):t%1==0?new CellContent.Number(new DateNumber(t,"Date()")):t<1?new CellContent.Number(new TimeNumber(t,"Date()")):new CellContent.Number(new DateTimeNumber(t,"Date()"))}if("string"==typeof e){if(isBoolean(e))return new CellContent.Boolean("true"===e.toLowerCase());if(isFormula(e))return new CellContent.Formula(e);if(isError(e,this.config.errorMapping))return new CellContent.Error(this.config.errorMapping[e.toUpperCase()]);{let t,n=e.trim(),r=0;if(n.endsWith("%"))r=1,n=n.slice(0,n.length-1);else{const e=this.currencyMatcher(n);void 0!==e&&(r=2,[t,n]=e)}const a=this.numberLiteralsHelper.numericStringToMaybeNumber(n);if(void 0!==a){let e;return e=1===r?new PercentNumber(a/100):2===r?new CurrencyNumber(a,t):a,new CellContent.Number(e)}const i=this.dateHelper.dateStringToDateNumber(n);return void 0!==i?new CellContent.Number(i):new CellContent.String(e.startsWith("'")?e.slice(1):e)}}throw new UnableToParseError(e)}currencyMatcher(e){for(const t of this.config.currencySymbol){if(e.startsWith(t))return[t,e.slice(t.length)];if(e.endsWith(t))return[t,e.slice(0,e.length-t.length)]}}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */!function(e){e[e.COPY=0]="COPY",e[e.CUT=1]="CUT"}(ClipboardOperationType||(ClipboardOperationType={})),function(e){e[e.VALUE=0]="VALUE",e[e.EMPTY=1]="EMPTY",e[e.FORMULA=2]="FORMULA",e[e.PARSING_ERROR=3]="PARSING_ERROR"}(ClipboardCellType||(ClipboardCellType={}));class Clipboard{constructor(e,t,n,r,a){this.sourceLeftCorner=e,this.width=t,this.height=n,this.type=r,this.content=a}*getContent(e){if(void 0!==this.content)for(let t=0;te.added))}normalizeExpressionName(e){return e.toLowerCase()}}class WorksheetStore{constructor(){this.mapping=new Map}add(e){this.mapping.set(this.normalizeExpressionName(e.displayName),e)}get(e){return this.mapping.get(this.normalizeExpressionName(e))}has(e){return this.mapping.has(this.normalizeExpressionName(e))}getAllNamedExpressions(){return Array.from(this.mapping.values()).filter((e=>e.added))}isNameAvailable(e){const t=this.normalizeExpressionName(e);return!this.mapping.has(t)}remove(e){const t=this.normalizeExpressionName(e);this.mapping.get(t)&&this.mapping.delete(t)}normalizeExpressionName(e){return e.toLowerCase()}}class NamedExpressions{constructor(){this.nextNamedExpressionRow=0,this.workbookStore=new WorkbookStore,this.worksheetStores=new Map,this.addressCache=new Map}isNameAvailable(e,t){var n,r;return void 0===t?this.workbookStore.isNameAvailable(e):null===(r=null===(n=this.worksheetStore(t))||void 0===n?void 0:n.isNameAvailable(e))||void 0===r||r}namedExpressionInAddress(e){const t=this.addressCache.get(e);return t&&t.added?t:void 0}namedExpressionForScope(e,t){var n;return void 0===t?this.workbookStore.getExisting(e):null===(n=this.worksheetStore(t))||void 0===n?void 0:n.get(e)}nearestNamedExpression(e,t){var n,r;return null!==(r=null===(n=this.worksheetStore(t))||void 0===n?void 0:n.get(e))&&void 0!==r?r:this.workbookStore.getExisting(e)}isExpressionInScope(e,t){var n,r;return null!==(r=null===(n=this.worksheetStore(t))||void 0===n?void 0:n.has(e))&&void 0!==r&&r}isNameValid(e){return!/^[A-Za-z]+[0-9]+$/.test(e)&&/^[A-Za-z\u00C0-\u02AF_][A-Za-z0-9\u00C0-\u02AF._]*$/.test(e)}addNamedExpression(e,t,n){const r=void 0===t?this.workbookStore:this.worksheetStoreOrCreate(t);let a=r.get(e);return void 0!==a?(a.added=!0,a.displayName=e,a.options=n):(a=new InternalNamedExpression(e,this.nextAddress(),!0,n),r.add(a)),this.addressCache.set(a.address.row,a),a}restoreNamedExpression(e,t){const n=void 0===t?this.workbookStore:this.worksheetStoreOrCreate(t);return e.added=!0,n.add(e),this.addressCache.set(e.address.row,e),e}namedExpressionOrPlaceholder(e,t){var n;return null!==(n=this.worksheetStoreOrCreate(t).get(e))&&void 0!==n?n:this.workbookNamedExpressionOrPlaceholder(e)}workbookNamedExpressionOrPlaceholder(e){let t=this.workbookStore.get(e);return void 0===t&&(t=new InternalNamedExpression(e,this.nextAddress(),!1),this.workbookStore.add(t)),t}remove(e,t){let n;n=void 0===t?this.workbookStore:this.worksheetStore(t);const r=null==n?void 0:n.get(e);if(void 0===n||void 0===r||!r.added)throw"Named expression does not exist";n.remove(e),n instanceof WorksheetStore&&0===n.mapping.size&&this.worksheetStores.delete(t),this.addressCache.delete(r.address.row)}getAllNamedExpressionsNamesInScope(e){return this.getAllNamedExpressions().filter((({scope:t})=>t===e)).map((e=>e.expression.displayName))}getAllNamedExpressionsNames(){return this.getAllNamedExpressions().map((e=>e.expression.displayName))}getAllNamedExpressions(){const e=[];return this.workbookStore.getAllNamedExpressions().forEach((t=>{e.push({expression:t,scope:void 0})})),this.worksheetStores.forEach(((t,n)=>{t.getAllNamedExpressions().forEach((t=>{e.push({expression:t,scope:n})}))})),e}getAllNamedExpressionsForScope(e){var t,n;return void 0===e?this.workbookStore.getAllNamedExpressions():null!==(n=null===(t=this.worksheetStores.get(e))||void 0===t?void 0:t.getAllNamedExpressions())&&void 0!==n?n:[]}worksheetStoreOrCreate(e){let t=this.worksheetStores.get(e);return t||(t=new WorksheetStore,this.worksheetStores.set(e,t)),t}worksheetStore(e){return this.worksheetStores.get(e)}nextAddress(){return simpleCellAddress(NamedExpressions.SHEET_FOR_WORKBOOK_EXPRESSIONS,0,this.nextNamedExpressionRow++)}}NamedExpressions.SHEET_FOR_WORKBOOK_EXPRESSIONS=-1;const doesContainRelativeReferences=e=>{switch(e.type){case AstNodeType.EMPTY:case AstNodeType.NUMBER:case AstNodeType.STRING:case AstNodeType.ERROR:case AstNodeType.ERROR_WITH_RAW_INPUT:return!1;case AstNodeType.CELL_REFERENCE:return!e.reference.isAbsolute();case AstNodeType.CELL_RANGE:case AstNodeType.COLUMN_RANGE:case AstNodeType.ROW_RANGE:return!e.start.isAbsolute();case AstNodeType.NAMED_EXPRESSION:return!1;case AstNodeType.PERCENT_OP:case AstNodeType.PLUS_UNARY_OP:case AstNodeType.MINUS_UNARY_OP:return doesContainRelativeReferences(e.value);case AstNodeType.CONCATENATE_OP:case AstNodeType.EQUALS_OP:case AstNodeType.NOT_EQUAL_OP:case AstNodeType.LESS_THAN_OP:case AstNodeType.GREATER_THAN_OP:case AstNodeType.LESS_THAN_OR_EQUAL_OP:case AstNodeType.GREATER_THAN_OR_EQUAL_OP:case AstNodeType.MINUS_OP:case AstNodeType.PLUS_OP:case AstNodeType.TIMES_OP:case AstNodeType.DIV_OP:case AstNodeType.POWER_OP:return doesContainRelativeReferences(e.left)||doesContainRelativeReferences(e.right);case AstNodeType.PARENTHESIS:return doesContainRelativeReferences(e.expression);case AstNodeType.FUNCTION_CALL:return e.args.some((e=>doesContainRelativeReferences(e)));case AstNodeType.ARRAY:return e.args.some((e=>e.some((e=>doesContainRelativeReferences(e)))))}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class Transformer{performEagerTransformations(e,t){for(const n of e.arrayFormulaNodes()){const[r,a]=this.transformSingleAst(n.getFormula(e.lazilyTransformingAstService),n.getAddress(e.lazilyTransformingAstService)),i=t.rememberNewAst(r);n.setFormula(i),n.setAddress(a)}}transformSingleAst(e,t){return[this.transformAst(e,t),this.fixNodeAddress(t)]}transformAst(e,t){switch(e.type){case AstNodeType.CELL_REFERENCE:return this.transformCellReferenceAst(e,t);case AstNodeType.CELL_RANGE:return this.transformCellRangeAst(e,t);case AstNodeType.COLUMN_RANGE:return this.transformColumnRangeAst(e,t);case AstNodeType.ROW_RANGE:return this.transformRowRangeAst(e,t);case AstNodeType.EMPTY:case AstNodeType.ERROR:case AstNodeType.NUMBER:case AstNodeType.NAMED_EXPRESSION:case AstNodeType.ERROR_WITH_RAW_INPUT:case AstNodeType.STRING:return e;case AstNodeType.PERCENT_OP:case AstNodeType.MINUS_UNARY_OP:case AstNodeType.PLUS_UNARY_OP:return Object.assign(Object.assign({},e),{value:this.transformAst(e.value,t)});case AstNodeType.FUNCTION_CALL:return Object.assign(Object.assign({},e),{procedureName:e.procedureName,args:e.args.map((e=>this.transformAst(e,t)))});case AstNodeType.PARENTHESIS:return Object.assign(Object.assign({},e),{expression:this.transformAst(e.expression,t)});case AstNodeType.ARRAY:return Object.assign(Object.assign({},e),{args:e.args.map((e=>e.map((e=>this.transformAst(e,t)))))});default:return Object.assign(Object.assign({},e),{left:this.transformAst(e.left,t),right:this.transformAst(e.right,t)})}}transformCellReferenceAst(e,t){const n=this.transformCellAddress(e.reference,t);return n instanceof CellAddress?Object.assign(Object.assign({},e),{reference:n}):n===ErrorType.REF?buildCellErrorAst(new CellError(ErrorType.REF)):e}transformCellRangeAst(e,t){const n=this.transformCellRange(e.start,e.end,t);return Array.isArray(n)?Object.assign(Object.assign({},e),{start:n[0],end:n[1]}):n===ErrorType.REF?buildCellErrorAst(new CellError(ErrorType.REF)):e}transformColumnRangeAst(e,t){const n=this.transformColumnRange(e.start,e.end,t);return Array.isArray(n)?Object.assign(Object.assign({},e),{start:n[0],end:n[1]}):n===ErrorType.REF?buildCellErrorAst(new CellError(ErrorType.REF)):e}transformRowRangeAst(e,t){const n=this.transformRowRange(e.start,e.end,t);return Array.isArray(n)?Object.assign(Object.assign({},e),{start:n[0],end:n[1]}):n===ErrorType.REF?buildCellErrorAst(new CellError(ErrorType.REF)):e}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class AddColumnsTransformer extends Transformer{constructor(e){super(),this.columnsSpan=e}get sheet(){return this.columnsSpan.sheet}isIrreversible(){return!1}transformRowRangeAst(e,t){return e}transformCellRange(e,t,n){return this.transformRange(e,t,n)}transformRowRange(e,t,n){throw Error("Not implemented")}transformColumnRange(e,t,n){return this.transformRange(e,t,n)}transformCellAddress(e,t){const n=absoluteSheetReference(e,t);if(n!==this.columnsSpan.sheet&&t.sheet!==this.columnsSpan.sheet)return!1;const r=e.toSimpleColumnAddress(t);if(n===this.columnsSpan.sheet&&t.sheet!==this.columnsSpan.sheet)return this.columnsSpan.columnStart<=r.col&&e.shiftedByColumns(this.columnsSpan.numberOfColumns);if(t.sheet===this.columnsSpan.sheet&&n!==this.columnsSpan.sheet)return!e.isColumnAbsolute()&&(!(t.colthis.columnsSpan.columnEnd)return e.shiftedByColumns(-this.columnsSpan.numberOfColumns)}if(this.columnsSpan.sheet===t.sheet&&this.columnsSpan.sheet!==n){if(e.isColumnAbsolute())return!1;if(t.colthis.columnsSpan.columnEnd)return e.shiftedByColumns(this.columnsSpan.numberOfColumns)}if(this.columnsSpan.sheet===t.sheet&&this.columnsSpan.sheet===n)if(e.isColumnAbsolute()){if(e.colthis.columnsSpan.columnEnd)return e.shiftedByColumns(-this.columnsSpan.numberOfColumns)}else{const n=e.toSimpleColumnAddress(t);if(n.colthis.columnsSpan.columnEnd)return e.shiftedByColumns(this.columnsSpan.numberOfColumns)}else if(n.col>this.columnsSpan.columnEnd){if(t.colthis.columnsSpan.columnEnd)return!1}}return ErrorType.REF}fixNodeAddress(e){return this.columnsSpan.sheet===e.sheet&&this.columnsSpan.columnStart<=e.col?Object.assign(Object.assign({},e),{col:e.col-this.columnsSpan.numberOfColumns}):e}transformRange(e,t,n){const r=absoluteSheetReference(e,n);let a=e,i=t;if(this.columnsSpan.sheet===r){const r=e.toSimpleColumnAddress(n),s=t.toSimpleColumnAddress(n);if(this.columnsSpan.columnStart<=r.col&&this.columnsSpan.columnEnd>=s.col)return ErrorType.REF;r.col>=this.columnsSpan.columnStart&&r.col<=this.columnsSpan.columnEnd&&(a=e.shiftedByColumns(this.columnsSpan.columnEnd-r.col+1)),s.col>=this.columnsSpan.columnStart&&s.col<=this.columnsSpan.columnEnd&&(i=t.shiftedByColumns(-(s.col-this.columnsSpan.columnStart+1)))}const s=this.transformCellAddress(a,n),o=this.transformCellAddress(i,n);if(!1===s&&!1===o)return[a,i];if(s===ErrorType.REF||o===ErrorType.REF)throw Error("Cannot happen");return[s||a,o||i]}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class RemoveRowsTransformer extends Transformer{constructor(e){super(),this.rowsSpan=e}get sheet(){return this.rowsSpan.sheet}isIrreversible(){return!0}transformColumnRangeAst(e,t){return e}transformCellAddress(e,t){const n=absoluteSheetReference(e,t);if(this.rowsSpan.sheet!==t.sheet&&this.rowsSpan.sheet!==n)return!1;if(this.rowsSpan.sheet!==t.sheet&&this.rowsSpan.sheet===n){const n=e.toSimpleRowAddress(t);if(n.rowthis.rowsSpan.rowEnd)return e.shiftedByRows(-this.rowsSpan.numberOfRows)}if(this.rowsSpan.sheet===t.sheet&&this.rowsSpan.sheet!==n){if(e.isRowAbsolute())return!1;if(t.rowthis.rowsSpan.rowEnd)return e.shiftedByRows(this.rowsSpan.numberOfRows)}if(this.rowsSpan.sheet===t.sheet&&this.rowsSpan.sheet===n)if(e.isRowAbsolute()){if(e.rowthis.rowsSpan.rowEnd)return e.shiftedByRows(-this.rowsSpan.numberOfRows)}else{const n=e.toSimpleRowAddress(t);if(n.rowthis.rowsSpan.rowEnd)return e.shiftedByRows(this.rowsSpan.numberOfRows)}else if(n.row>this.rowsSpan.rowEnd){if(t.rowthis.rowsSpan.rowEnd)return!1}}return ErrorType.REF}transformCellRange(e,t,n){return this.transformRange(e,t,n)}transformRowRange(e,t,n){return this.transformRange(e,t,n)}transformColumnRange(e,t,n){throw Error("Not implemented")}fixNodeAddress(e){return this.rowsSpan.sheet===e.sheet&&this.rowsSpan.rowStart<=e.row?Object.assign(Object.assign({},e),{row:e.row-this.rowsSpan.numberOfRows}):e}transformRange(e,t,n){const r=absoluteSheetReference(e,n);let a=e,i=t;if(this.rowsSpan.sheet===r){const r=e.toSimpleRowAddress(n),s=t.toSimpleRowAddress(n);if(this.rowsSpan.rowStart<=r.row&&this.rowsSpan.rowEnd>=s.row)return ErrorType.REF;r.row>=this.rowsSpan.rowStart&&r.row<=this.rowsSpan.rowEnd&&(a=e.shiftedByRows(this.rowsSpan.rowEnd-r.row+1)),s.row>=this.rowsSpan.rowStart&&s.row<=this.rowsSpan.rowEnd&&(i=t.shiftedByRows(-(s.row-this.rowsSpan.rowStart+1)))}const s=this.transformCellAddress(a,n),o=this.transformCellAddress(i,n);return!1===s&&!1===o?[a,i]:s===ErrorType.REF||o===ErrorType.REF?ErrorType.REF:[s||a,o||i]}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class RemoveSheetTransformer extends Transformer{constructor(e){super(),this.sheet=e}isIrreversible(){return!0}performEagerTransformations(e,t){for(const t of e.arrayFormulaNodes()){const[n]=this.transformSingleAst(t.getFormula(e.lazilyTransformingAstService),t.getAddress(e.lazilyTransformingAstService));t.setFormula(n)}}fixNodeAddress(e){return e}transformCellAddress(e,t){return this.transformAddress(e)}transformCellRange(e,t,n){return this.transformAddress(e)}transformColumnRange(e,t,n){return this.transformAddress(e)}transformRowRange(e,t,n){return this.transformAddress(e)}transformAddress(e){return e.sheet===this.sheet&&ErrorType.REF}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */function validateAsSheet(e){if(!Array.isArray(e))throw new InvalidArgumentsError("an array of arrays.");for(let t=0;t0&&(n=a+1)}const a=t*n;return{height:n,width:t,fill:0===a?0:r/a}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class RemoveRowsCommand{constructor(e,t){this.sheet=e,this.indexes=t}normalizedIndexes(){return normalizeRemovedIndexes(this.indexes)}rowsSpans(){return this.normalizedIndexes().map((e=>RowsSpan.fromNumberOfRows(this.sheet,e[0],e[1])))}}class AddRowsCommand{constructor(e,t){this.sheet=e,this.indexes=t}normalizedIndexes(){return normalizeAddedIndexes(this.indexes)}rowsSpans(){return this.normalizedIndexes().map((e=>RowsSpan.fromNumberOfRows(this.sheet,e[0],e[1])))}}class AddColumnsCommand{constructor(e,t){this.sheet=e,this.indexes=t}normalizedIndexes(){return normalizeAddedIndexes(this.indexes)}columnsSpans(){return this.normalizedIndexes().map((e=>ColumnsSpan.fromNumberOfColumns(this.sheet,e[0],e[1])))}}class RemoveColumnsCommand{constructor(e,t){this.sheet=e,this.indexes=t}normalizedIndexes(){return normalizeRemovedIndexes(this.indexes)}columnsSpans(){return this.normalizedIndexes().map((e=>ColumnsSpan.fromNumberOfColumns(this.sheet,e[0],e[1])))}}class Operations{constructor(e,t,n,r,a,i,s,o,l){this.dependencyGraph=t,this.columnSearch=n,this.cellContentParser=r,this.parser=a,this.stats=i,this.lazilyTransformingAstService=s,this.namedExpressions=o,this.arraySizePredictor=l,this.changes=ContentChanges.empty(),this.allocateNamedExpressionAddressSpace(),this.maxColumns=e.maxColumns,this.maxRows=e.maxRows}get sheetMapping(){return this.dependencyGraph.sheetMapping}get addressMapping(){return this.dependencyGraph.addressMapping}removeRows(e){const t=[];for(const n of e.rowsSpans()){const e=this.doRemoveRows(n);e&&t.push(e)}return t}addRows(e){for(const t of e.rowsSpans())this.doAddRows(t)}addColumns(e){for(const t of e.columnsSpans())this.doAddColumns(t)}removeColumns(e){const t=[];for(const n of e.columnsSpans()){const e=this.doRemoveColumns(n);e&&t.push(e)}return t}removeSheet(e){let t;this.dependencyGraph.removeSheet(e),this.stats.measure(StatType.TRANSFORM_ASTS,(()=>{const n=new RemoveSheetTransformer(e);n.performEagerTransformations(this.dependencyGraph,this.parser),t=this.lazilyTransformingAstService.addTransformation(n)})),this.sheetMapping.removeSheet(e),this.columnSearch.removeSheet(e);const n=this.namedExpressions.getAllNamedExpressionsForScope(e).map((t=>this.removeNamedExpression(t.normalizeExpressionName(),e)));return{version:t,scopedNamedExpressions:n}}removeSheetByName(e){const t=this.sheetMapping.fetch(e);return this.removeSheet(t)}clearSheet(e){this.dependencyGraph.clearSheet(e),this.columnSearch.removeSheet(e)}addSheet(e){const t=this.sheetMapping.addSheet(e),n=[];return this.dependencyGraph.addressMapping.autoAddSheet(t,n,findBoundaries(n)),this.sheetMapping.fetchDisplayName(t)}renameSheet(e,t){return this.sheetMapping.renameSheet(e,t)}moveRows(e,t,n,r){const a=RowsSpan.fromNumberOfRows(e,r,n);this.lazilyTransformingAstService.beginCombinedMode(e),this.doAddRows(a),r{const e=new MoveCellsTransformer(a,s,o,l);e.performEagerTransformations(this.dependencyGraph,this.parser),d=this.lazilyTransformingAstService.addTransformation(e)})),this.dependencyGraph.moveCells(a,s,o,l);const m=this.updateNamedExpressionsForMovedCells(e,t,n,r);return{version:d,overwrittenCellsData:u,addedGlobalNamedExpressions:m}}setRowOrder(e,t){const n=[];let r=[];for(const[a,i]of t)if(a!==i){const t=AbsoluteCellRange.spanFrom({sheet:e,col:0,row:a},1/0,1),s=this.getRangeClipboardCells(t);r=r.concat(s),n.push(s.map((([{sheet:e,col:t},n])=>[{sheet:e,col:t,row:i},n])))}return n.forEach((t=>this.restoreClipboardCells(e,t.values()))),r}setColumnOrder(e,t){const n=[];let r=[];for(const[a,i]of t)if(a!==i){const t=AbsoluteCellRange.spanFrom({sheet:e,col:a,row:0},1,1/0),s=this.getRangeClipboardCells(t);r=r.concat(s),n.push(s.map((([{sheet:e,col:t,row:n},r])=>[{sheet:e,col:i,row:n},r])))}return n.forEach((t=>this.restoreClipboardCells(e,t.values()))),r}addNamedExpression(e,t,n,r){const a=this.namedExpressions.addNamedExpression(e,n,r);this.storeNamedExpressionInCell(a.address,t),this.adjustNamedExpressionEdges(a,e,n)}restoreNamedExpression(e,t,n){const r=e.displayName;this.restoreCell(e.address,t);const a=this.namedExpressions.restoreNamedExpression(e,n);this.adjustNamedExpressionEdges(a,r,n)}changeNamedExpressionExpression(e,t,n,r){const a=this.namedExpressions.namedExpressionForScope(e,n);if(!a)throw new NamedExpressionDoesNotExistError(e);const i=a.copy();a.options=r;const s=this.getClipboardCell(a.address);return this.storeNamedExpressionInCell(a.address,t),[i,s]}removeNamedExpression(e,t){const n=this.namedExpressions.namedExpressionForScope(e,t);if(!n)throw new NamedExpressionDoesNotExistError(e);this.namedExpressions.remove(n.displayName,t);const r=this.getClipboardCell(n.address);if(void 0!==t){const t=this.namedExpressions.workbookNamedExpressionOrPlaceholder(e);this.dependencyGraph.exchangeNode(n.address,t.address)}else this.dependencyGraph.setCellEmpty(n.address);return[n,r]}ensureItIsPossibleToMoveCells(e,t,n,r){if(invalidSimpleCellAddress(e)||!(isPositiveInteger$1(t)&&isPositiveInteger$1(n)||isRowOrColumnRange(e,t,n))||invalidSimpleCellAddress(r)||!this.sheetMapping.hasSheetWithId(e.sheet)||!this.sheetMapping.hasSheetWithId(r.sheet))throw new InvalidArgumentsError("a valid range of cells to move.");const a=AbsoluteCellRange.spanFrom(e,t,n),i=AbsoluteCellRange.spanFrom(r,t,n);if(i.exceedsSheetSizeLimits(this.maxColumns,this.maxRows))throw new SheetSizeLimitExceededError;if(this.dependencyGraph.arrayMapping.isFormulaArrayInRange(a))throw new SourceLocationHasArrayError;if(this.dependencyGraph.arrayMapping.isFormulaArrayInRange(i))throw new TargetLocationHasArrayError}restoreClipboardCells(e,t){const n=[];for(const[r,a]of t)if(this.restoreCell(r,a),a.type===ClipboardCellType.FORMULA){const{dependencies:t}=this.parser.fetchCachedResult(a.hash);n.push(...this.updateNamedExpressionsForTargetAddress(e,r,t))}return n}restoreCell(e,t){switch(t.type){case ClipboardCellType.VALUE:this.setValueToCell(t,e);break;case ClipboardCellType.FORMULA:this.setFormulaToCellFromCache(t.hash,e);break;case ClipboardCellType.EMPTY:this.setCellEmpty(e);break;case ClipboardCellType.PARSING_ERROR:this.setParsingErrorToCell(t.rawInput,t.errors,e)}}getOldContent(e){const t=this.dependencyGraph.getCell(e);if(void 0===t||t instanceof EmptyCellVertex)return[e,{type:ClipboardCellType.EMPTY}];if(t instanceof ValueCellVertex)return[e,Object.assign({type:ClipboardCellType.VALUE},t.getValues())];if(t instanceof FormulaVertex)return[t.getAddress(this.lazilyTransformingAstService),{type:ClipboardCellType.FORMULA,hash:this.parser.computeHashFromAst(t.getFormula(this.lazilyTransformingAstService))}];if(t instanceof ParsingErrorVertex)return[e,{type:ClipboardCellType.PARSING_ERROR,rawInput:t.rawInput,errors:t.errors}];throw Error("Trying to copy unsupported type")}getClipboardCell(e){const t=this.dependencyGraph.getCell(e);if(void 0===t||t instanceof EmptyCellVertex)return{type:ClipboardCellType.EMPTY};if(t instanceof ValueCellVertex)return Object.assign({type:ClipboardCellType.VALUE},t.getValues());if(t instanceof ArrayVertex){const n=t.getArrayCellValue(e);return n===EmptyValue?{type:ClipboardCellType.EMPTY}:{type:ClipboardCellType.VALUE,parsedValue:n,rawValue:t.getArrayCellRawValue(e)}}if(t instanceof FormulaCellVertex)return{type:ClipboardCellType.FORMULA,hash:this.parser.computeHashFromAst(t.getFormula(this.lazilyTransformingAstService))};if(t instanceof ParsingErrorVertex)return{type:ClipboardCellType.PARSING_ERROR,rawInput:t.rawInput,errors:t.errors};throw Error("Trying to copy unsupported type")}getSheetClipboardCells(e){const t=this.dependencyGraph.getSheetHeight(e),n=this.dependencyGraph.getSheetWidth(e),r=new Array(t);for(let a=0;a0)this.setParsingErrorToCell(n.formula,a,e);else{const n=this.arraySizePredictor.checkArraySize(r,e);this.setFormulaToCell(e,n,t)}}else n instanceof CellContent.Empty?this.setCellEmpty(e):this.setValueToCell({parsedValue:n.value,rawValue:t},e);return r}setSheetContent(e,t){this.clearSheet(e);for(let n=0;n!equalSimpleCellAddress(e.address,t)))),this.changes.addAll(r),this.changes.addChange(e.parsedValue,t)}setCellEmpty(e){if(this.dependencyGraph.isArrayInternalCell(e))return;const t=this.dependencyGraph.getCellValue(e),n=this.dependencyGraph.setCellEmpty(e);this.columnSearch.remove(getRawValue(t),e),this.columnSearch.applyChanges(n.getChanges()),this.changes.addAll(n),this.changes.addChange(EmptyValue,e)}setFormulaToCellFromCache(e,t){const{ast:n,hasVolatileFunction:r,hasStructuralChangeFunction:a,dependencies:i}=this.parser.fetchCachedResult(e),s=absolutizeDependencies(i,t),[o]=new CleanOutOfScopeDependenciesTransformer(t.sheet).transformSingleAst(n,t);this.parser.rememberNewAst(o);const l=filterDependenciesOutOfScope(s),u=this.arraySizePredictor.checkArraySize(n,t);this.dependencyGraph.setFormulaToCell(t,o,l,u,r,a)}rowEffectivelyNotInSheet(e,t){return e>=this.dependencyGraph.addressMapping.getHeight(t)}getAndClearContentChanges(){const e=this.changes;return this.changes=ContentChanges.empty(),e}forceApplyPostponedTransformations(){this.dependencyGraph.forceApplyPostponedTransformations()}doRemoveRows(e){if(this.rowEffectivelyNotInSheet(e.rowStart,e.sheet))return;const t=[];for(const[n]of this.dependencyGraph.entriesFromRowsSpan(e))t.push({address:n,cellType:this.getClipboardCell(n)});const{affectedArrays:n,contentChanges:r}=this.dependencyGraph.removeRows(e);let a;return this.columnSearch.applyChanges(r.getChanges()),this.stats.measure(StatType.TRANSFORM_ASTS,(()=>{const t=new RemoveRowsTransformer(e);t.performEagerTransformations(this.dependencyGraph,this.parser),a=this.lazilyTransformingAstService.addTransformation(t)})),this.rewriteAffectedArrays(n),{version:a,removedCells:t,rowFrom:e.rowStart,rowCount:e.numberOfRows}}doRemoveColumns(e){if(this.columnEffectivelyNotInSheet(e.columnStart,e.sheet))return;const t=[];for(const[n]of this.dependencyGraph.entriesFromColumnsSpan(e))t.push({address:n,cellType:this.getClipboardCell(n)});const{affectedArrays:n,contentChanges:r}=this.dependencyGraph.removeColumns(e);let a;return this.columnSearch.applyChanges(r.getChanges()),this.columnSearch.removeColumns(e),this.stats.measure(StatType.TRANSFORM_ASTS,(()=>{const t=new RemoveColumnsTransformer(e);t.performEagerTransformations(this.dependencyGraph,this.parser),a=this.lazilyTransformingAstService.addTransformation(t)})),this.rewriteAffectedArrays(n),{version:a,removedCells:t,columnFrom:e.columnStart,columnCount:e.numberOfColumns}}doAddRows(e){if(this.rowEffectivelyNotInSheet(e.rowStart,e.sheet))return;const{affectedArrays:t}=this.dependencyGraph.addRows(e);this.stats.measure(StatType.TRANSFORM_ASTS,(()=>{const t=new AddRowsTransformer(e);t.performEagerTransformations(this.dependencyGraph,this.parser),this.lazilyTransformingAstService.addTransformation(t)})),this.rewriteAffectedArrays(t)}rewriteAffectedArrays(e){for(const t of e.values()){if(t.array.size.isRef)continue;const e=t.getFormula(this.lazilyTransformingAstService),n=t.getAddress(this.lazilyTransformingAstService),r=this.parser.computeHashFromAst(e);this.setFormulaToCellFromCache(r,n)}}doAddColumns(e){if(this.columnEffectivelyNotInSheet(e.columnStart,e.sheet))return;const{affectedArrays:t,contentChanges:n}=this.dependencyGraph.addColumns(e);this.columnSearch.addColumns(e),this.columnSearch.applyChanges(n.getChanges()),this.stats.measure(StatType.TRANSFORM_ASTS,(()=>{const t=new AddColumnsTransformer(e);t.performEagerTransformations(this.dependencyGraph,this.parser),this.lazilyTransformingAstService.addTransformation(t)})),this.rewriteAffectedArrays(t)}columnEffectivelyNotInSheet(e,t){return e>=this.dependencyGraph.addressMapping.getWidth(t)}adjustNamedExpressionEdges(e,t,n){if(void 0===n)return;const r=this.dependencyGraph.fetchCellOrCreateEmpty(e.address),a=this.namedExpressions.workbookNamedExpressionOrPlaceholder(t),i=this.dependencyGraph.fetchCellOrCreateEmpty(a.address);for(const t of this.dependencyGraph.graph.adjacentNodes(i))if(t instanceof FormulaCellVertex&&t.getAddress(this.lazilyTransformingAstService).sheet===n){const n=t.getFormula(this.lazilyTransformingAstService),a=t.getAddress(this.lazilyTransformingAstService),{dependencies:s}=this.parser.fetchCachedResultForAst(n);for(const n of absolutizeDependencies(s,a))n instanceof NamedExpressionDependency&&n.name.toLowerCase()===e.displayName.toLowerCase()&&(this.dependencyGraph.graph.removeEdge(i,t),this.dependencyGraph.graph.addEdge(r,t))}}storeNamedExpressionInCell(e,t){const n=this.cellContentParser.parse(t);if(n instanceof CellContent.Formula){const t=this.parser.parse(n.formula,simpleCellAddress(-1,0,0));if(doesContainRelativeReferences(t.ast))throw new NoRelativeAddressesAllowedError;const{ast:r,hasVolatileFunction:a,hasStructuralChangeFunction:i,dependencies:s}=t;this.dependencyGraph.setFormulaToCell(e,r,absolutizeDependencies(s,e),ArraySize.scalar(),a,i)}else n instanceof CellContent.Empty?this.setCellEmpty(e):this.setValueToCell({parsedValue:n.value,rawValue:t},e)}updateNamedExpressionsForMovedCells(e,t,n,r){if(e.sheet===r.sheet)return[];const a=[],i=AbsoluteCellRange.spanFrom(r,t,n);for(const t of i.addresses(this.dependencyGraph)){const n=this.addressMapping.fetchCell(t);if(n instanceof FormulaCellVertex&&t.sheet!==e.sheet){const r=n.getFormula(this.lazilyTransformingAstService),{dependencies:i}=this.parser.fetchCachedResultForAst(r);a.push(...this.updateNamedExpressionsForTargetAddress(e.sheet,t,i))}}return a}updateNamedExpressionsForTargetAddress(e,t,n){if(e===t.sheet)return[];const r=[],a=this.addressMapping.fetchCell(t);for(const i of absolutizeDependencies(n,t)){if(!(i instanceof NamedExpressionDependency))continue;const n=i.name,s=this.dependencyGraph.fetchNamedExpressionVertex(n,e),o=this.namedExpressions.isExpressionInScope(n,t.sheet)?this.dependencyGraph.fetchNamedExpressionVertex(n,t.sheet):this.copyOrFetchGlobalNamedExpressionVertex(n,s,r);o!==s&&(this.dependencyGraph.graph.softRemoveEdge(s,a),this.dependencyGraph.graph.addEdge(o,a))}return r}allocateNamedExpressionAddressSpace(){this.dependencyGraph.addressMapping.addSheet(-1,new SparseStrategy(0,0))}copyOrFetchGlobalNamedExpressionVertex(e,t,n){let r=this.namedExpressions.namedExpressionForScope(e);if(void 0===r)if(r=this.namedExpressions.addNamedExpression(e),n.push(r.normalizeExpressionName()),t instanceof FormulaCellVertex){const e=this.parser.fetchCachedResultForAst(t.getFormula(this.lazilyTransformingAstService)),{ast:n,hasVolatileFunction:a,hasStructuralChangeFunction:i,dependencies:s}=e;this.dependencyGraph.setFormulaToCell(r.address,n,absolutizeDependencies(s,r.address),ArraySize.scalar(),a,i)}else t instanceof EmptyCellVertex?this.setCellEmpty(r.address):t instanceof ValueCellVertex&&this.setValueToCell(t.getValues(),r.address);return this.dependencyGraph.fetchCellOrCreateEmpty(r.address)}}function normalizeRemovedIndexes(e){if(e.length<=1)return e;const t=[...e].sort((([e],[t])=>e-t)),n=t.reduce(((e,[t,n])=>{const r=e[e.length-1],a=r[0]+r[1];return t<=a?r[1]+=Math.max(0,n-(a-t)):e.push([t,n]),e}),[t[0]]);let r=0;for(let e=0;ee-t)),n=t.reduce(((e,[t,n])=>{const r=e[e.length-1];return t===r[0]?r[1]=Math.max(r[1],n):e.push([t,n]),e}),[t[0]]);let r=0;for(let e=0;e0}function isRowOrColumnRange(e,t,n){return 0===e.row&&isPositiveInteger$1(t)&&n===Number.POSITIVE_INFINITY||0===e.col&&isPositiveInteger$1(n)&&t===Number.POSITIVE_INFINITY} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class BaseUndoEntry{}class RemoveRowsUndoEntry extends BaseUndoEntry{constructor(e,t){super(),this.command=e,this.rowsRemovals=t}doUndo(e){e.undoRemoveRows(this)}doRedo(e){e.redoRemoveRows(this)}}class MoveCellsUndoEntry extends BaseUndoEntry{constructor(e,t,n,r,a,i,s){super(),this.sourceLeftCorner=e,this.width=t,this.height=n,this.destinationLeftCorner=r,this.overwrittenCellsData=a,this.addedGlobalNamedExpressions=i,this.version=s}doUndo(e){e.undoMoveCells(this)}doRedo(e){e.redoMoveCells(this)}}class AddRowsUndoEntry extends BaseUndoEntry{constructor(e){super(),this.command=e}doUndo(e){e.undoAddRows(this)}doRedo(e){e.redoAddRows(this)}}class SetRowOrderUndoEntry extends BaseUndoEntry{constructor(e,t,n){super(),this.sheetId=e,this.rowMapping=t,this.oldContent=n}doUndo(e){e.undoSetRowOrder(this)}doRedo(e){e.redoSetRowOrder(this)}}class SetColumnOrderUndoEntry extends BaseUndoEntry{constructor(e,t,n){super(),this.sheetId=e,this.columnMapping=t,this.oldContent=n}doUndo(e){e.undoSetColumnOrder(this)}doRedo(e){e.redoSetColumnOrder(this)}}class SetSheetContentUndoEntry extends BaseUndoEntry{constructor(e,t,n){super(),this.sheetId=e,this.oldSheetContent=t,this.newSheetContent=n}doUndo(e){e.undoSetSheetContent(this)}doRedo(e){e.redoSetSheetContent(this)}}class MoveRowsUndoEntry extends BaseUndoEntry{constructor(e,t,n,r,a){super(),this.sheet=e,this.startRow=t,this.numberOfRows=n,this.targetRow=r,this.version=a,this.undoStart=this.startRowthis.targetRow?this.startRow+this.numberOfRows:this.startRow}doUndo(e){e.undoMoveRows(this)}doRedo(e){e.redoMoveRows(this)}}class MoveColumnsUndoEntry extends BaseUndoEntry{constructor(e,t,n,r,a){super(),this.sheet=e,this.startColumn=t,this.numberOfColumns=n,this.targetColumn=r,this.version=a,this.undoStart=this.startColumnthis.targetColumn?this.startColumn+this.numberOfColumns:this.startColumn}doUndo(e){e.undoMoveColumns(this)}doRedo(e){e.redoMoveColumns(this)}}class AddColumnsUndoEntry extends BaseUndoEntry{constructor(e){super(),this.command=e}doUndo(e){e.undoAddColumns(this)}doRedo(e){e.redoAddColumns(this)}}class RemoveColumnsUndoEntry extends BaseUndoEntry{constructor(e,t){super(),this.command=e,this.columnsRemovals=t}doUndo(e){e.undoRemoveColumns(this)}doRedo(e){e.redoRemoveColumns(this)}}class AddSheetUndoEntry extends BaseUndoEntry{constructor(e){super(),this.sheetName=e}doUndo(e){e.undoAddSheet(this)}doRedo(e){e.redoAddSheet(this)}}class RemoveSheetUndoEntry extends BaseUndoEntry{constructor(e,t,n,r,a){super(),this.sheetName=e,this.sheetId=t,this.oldSheetContent=n,this.scopedNamedExpressions=r,this.version=a}doUndo(e){e.undoRemoveSheet(this)}doRedo(e){e.redoRemoveSheet(this)}}class RenameSheetUndoEntry extends BaseUndoEntry{constructor(e,t,n){super(),this.sheetId=e,this.oldName=t,this.newName=n}doUndo(e){e.undoRenameSheet(this)}doRedo(e){e.redoRenameSheet(this)}}class ClearSheetUndoEntry extends BaseUndoEntry{constructor(e,t){super(),this.sheetId=e,this.oldSheetContent=t}doUndo(e){e.undoClearSheet(this)}doRedo(e){e.redoClearSheet(this)}}class SetCellContentsUndoEntry extends BaseUndoEntry{constructor(e){super(),this.cellContents=e}doUndo(e){e.undoSetCellContents(this)}doRedo(e){e.redoSetCellContents(this)}}class PasteUndoEntry extends BaseUndoEntry{constructor(e,t,n,r){super(),this.targetLeftCorner=e,this.oldContent=t,this.newContent=n,this.addedGlobalNamedExpressions=r}doUndo(e){e.undoPaste(this)}doRedo(e){e.redoPaste(this)}}class AddNamedExpressionUndoEntry extends BaseUndoEntry{constructor(e,t,n,r){super(),this.name=e,this.newContent=t,this.scope=n,this.options=r}doUndo(e){e.undoAddNamedExpression(this)}doRedo(e){e.redoAddNamedExpression(this)}}class RemoveNamedExpressionUndoEntry extends BaseUndoEntry{constructor(e,t,n){super(),this.namedExpression=e,this.content=t,this.scope=n}doUndo(e){e.undoRemoveNamedExpression(this)}doRedo(e){e.redoRemoveNamedExpression(this)}}class ChangeNamedExpressionUndoEntry extends BaseUndoEntry{constructor(e,t,n,r,a){super(),this.namedExpression=e,this.newContent=t,this.oldContent=n,this.scope=r,this.options=a}doUndo(e){e.undoChangeNamedExpression(this)}doRedo(e){e.redoChangeNamedExpression(this)}}class BatchUndoEntry extends BaseUndoEntry{constructor(){super(...arguments),this.operations=[]}add(e){this.operations.push(e)}*reversedOperations(){for(let e=this.operations.length-1;e>=0;e--)yield this.operations[e]}doUndo(e){e.undoBatch(this)}doRedo(e){e.redoBatch(this)}}class UndoRedo{constructor(e,t){this.operations=t,this.oldData=new Map,this.undoStack=[],this.redoStack=[],this.undoLimit=e.undoLimit}saveOperation(e){void 0!==this.batchUndoEntry?this.batchUndoEntry.add(e):this.addUndoEntry(e)}beginBatchMode(){this.batchUndoEntry=new BatchUndoEntry}commitBatchMode(){if(void 0===this.batchUndoEntry)throw"Batch mode wasn't started";this.addUndoEntry(this.batchUndoEntry),this.batchUndoEntry=void 0}storeDataForVersion(e,t,n){this.oldData.has(e)||this.oldData.set(e,[]);this.oldData.get(e).push([t,n])}clearRedoStack(){this.redoStack=[]}clearUndoStack(){this.undoStack=[]}isUndoStackEmpty(){return 0===this.undoStack.length}isRedoStackEmpty(){return 0===this.redoStack.length}undo(){const e=this.undoStack.pop();if(!e)throw"Attempted to undo without operation on stack";this.undoEntry(e),this.redoStack.push(e)}undoBatch(e){for(const t of e.reversedOperations())this.undoEntry(t)}undoRemoveRows(e){this.operations.forceApplyPostponedTransformations();const{command:{sheet:t},rowsRemovals:n}=e;for(let e=n.length-1;e>=0;--e){const r=n[e];this.operations.addRows(new AddRowsCommand(t,[[r.rowFrom,r.rowCount]]));for(const{address:e,cellType:t}of r.removedCells)this.operations.restoreCell(e,t);this.restoreOldDataFromVersion(r.version-1)}}undoRemoveColumns(e){this.operations.forceApplyPostponedTransformations();const{command:{sheet:t},columnsRemovals:n}=e;for(let e=n.length-1;e>=0;--e){const r=n[e];this.operations.addColumns(new AddColumnsCommand(t,[[r.columnFrom,r.columnCount]]));for(const{address:e,cellType:t}of r.removedCells)this.operations.restoreCell(e,t);this.restoreOldDataFromVersion(r.version-1)}}undoAddRows(e){const t=e.command.rowsSpans();for(let n=t.length-1;n>=0;--n){const r=t[n];this.operations.removeRows(new RemoveRowsCommand(e.command.sheet,[[r.rowStart,r.numberOfRows]]))}}undoAddColumns(e){const t=e.command.columnsSpans();for(let n=t.length-1;n>=0;--n){const r=t[n];this.operations.removeColumns(new RemoveColumnsCommand(e.command.sheet,[[r.columnStart,r.numberOfColumns]]))}}undoSetCellContents(e){for(const t of e.cellContents){const e=t.address,[n,r]=t.oldContent;equalSimpleCellAddress(e,n)||this.operations.setCellEmpty(e),this.operations.restoreCell(n,r)}}undoPaste(e){this.restoreOperationOldContent(e.oldContent);for(const t of e.addedGlobalNamedExpressions)this.operations.removeNamedExpression(t)}undoMoveRows(e){const{sheet:t}=e;this.operations.moveRows(t,e.undoStart,e.numberOfRows,e.undoEnd),this.restoreOldDataFromVersion(e.version-1)}undoMoveColumns(e){const{sheet:t}=e;this.operations.moveColumns(t,e.undoStart,e.numberOfColumns,e.undoEnd),this.restoreOldDataFromVersion(e.version-1)}undoMoveCells(e){this.operations.forceApplyPostponedTransformations(),this.operations.moveCells(e.destinationLeftCorner,e.width,e.height,e.sourceLeftCorner),this.restoreOperationOldContent(e.overwrittenCellsData),this.restoreOldDataFromVersion(e.version-1);for(const t of e.addedGlobalNamedExpressions)this.operations.removeNamedExpression(t)}undoAddSheet(e){const{sheetName:t}=e;this.operations.removeSheetByName(t)}undoRemoveSheet(e){this.operations.forceApplyPostponedTransformations();const{oldSheetContent:t,sheetId:n}=e;this.operations.addSheet(e.sheetName);for(let e=0;ee[1])).reduce(((e,t)=>e+t),0);if(n+r>this.maxRows)throw new SheetSizeLimitExceededError;for(const[e,n]of t)if(!isNonnegativeInteger(e)||!isPositiveInteger(n))throw new InvalidArgumentsError("row number to be nonnegative and number of rows to add to be positive.")}ensureItIsPossibleToRemoveRows(e,...t){for(const[n,r]of t){const t=n+r-1;if(!isNonnegativeInteger(n)||!isNonnegativeInteger(t))throw new InvalidArgumentsError("starting and ending row to be nonnegative.");if(te[1])).reduce(((e,t)=>e+t),0);if(n+r>this.maxColumns)throw new SheetSizeLimitExceededError;for(const[e,n]of t)if(!isNonnegativeInteger(e)||!isPositiveInteger(n))throw new InvalidArgumentsError("column number to be nonnegative and number of columns to add to be positive.")}ensureItIsPossibleToRemoveColumns(e,...t){for(const[n,r]of t){const t=n+r-1;if(!isNonnegativeInteger(n)||!isNonnegativeInteger(t))throw new InvalidArgumentsError("starting and ending column to be nonnegative.");if(t=t)throw new InvalidArgumentsError("a valid range of rows to move.");const s=this.dependencyGraph.getSheetWidth(e),o=AbsoluteCellRange.spanFrom(a,s,n);if(this.dependencyGraph.arrayMapping.isFormulaArrayInRange(o))throw new SourceLocationHasArrayError;if(r>0&&this.dependencyGraph.arrayMapping.isFormulaArrayInAllRows(RowsSpan.fromNumberOfRows(e,r-1,2)))throw new TargetLocationHasArrayError}ensureItIsPossibleToMoveColumns(e,t,n,r){this.ensureItIsPossibleToAddColumns(e,[r,n]);const a=simpleCellAddress(e,t,0),i=simpleCellAddress(e,r,0);if(!this.sheetMapping.hasSheetWithId(e)||invalidSimpleCellAddress(a)||invalidSimpleCellAddress(i)||!isPositiveInteger(n)||r<=t+n&&r>=t)throw new InvalidArgumentsError("a valid range of columns to move.");const s=this.dependencyGraph.getSheetHeight(e),o=AbsoluteCellRange.spanFrom(a,n,s);if(this.dependencyGraph.arrayMapping.isFormulaArrayInRange(o))throw new SourceLocationHasArrayError;if(r>0&&this.dependencyGraph.arrayMapping.isFormulaArrayInAllColumns(ColumnsSpan.fromNumberOfColumns(e,r-1,2)))throw new TargetLocationHasArrayError}ensureItIsPossibleToAddSheet(e){if(this.sheetMapping.hasSheetWithName(e))throw new SheetNameAlreadyTakenError(e)}ensureItIsPossibleToRenameSheet(e,t){if(!this.sheetMapping.hasSheetWithId(e))throw new NoSheetWithIdError(e);const n=this.sheetMapping.get(t);if(void 0!==n&&n!==e)throw new SheetNameAlreadyTakenError(t)}ensureItIsPossibleToChangeContent(e){if(invalidSimpleCellAddress(e))throw new InvalidAddressError(e);if(!this.sheetMapping.hasSheetWithId(e.sheet))throw new NoSheetWithIdError(e.sheet)}ensureItIsPossibleToChangeCellContents(e,t){const n=findBoundaries(t),r=AbsoluteCellRange.spanFrom(e,n.width,n.height);this.ensureRangeInSizeLimits(r);for(const e of r.addresses(this.dependencyGraph))this.ensureItIsPossibleToChangeContent(e)}ensureItIsPossibleToChangeSheetContents(e,t){const n=findBoundaries(t),r=AbsoluteCellRange.spanFrom(simpleCellAddress(e,0,0),n.width,n.height);this.ensureRangeInSizeLimits(r)}ensureRangeInSizeLimits(e){if(e.exceedsSheetSizeLimits(this.maxColumns,this.maxRows))throw new SheetSizeLimitExceededError}isThereSomethingToUndo(){return!this.undoRedo.isUndoStackEmpty()}isThereSomethingToRedo(){return!this.undoRedo.isRedoStackEmpty()}getAndClearContentChanges(){return this.operations.getAndClearContentChanges()}ensureScopeIdIsValid(e){if(void 0!==e&&!this.sheetMapping.hasSheetWithId(e))throw new NoSheetWithIdError(e)}validateRowOrColumnMapping(e,t,n){const r="row"===n?this.dependencyGraph.getSheetHeight(e):this.dependencyGraph.getSheetWidth(e),a=t.map((([e,t])=>e)).sort(((e,t)=>e-t)),i=t.map((([e,t])=>t)).sort(((e,t)=>e-t));for(let e=0;e=r)throw new InvalidArgumentsError(`${n} numbers to be nonnegative integers and less than sheet ${"row"===n?"height":"width"}.`);if(a[e]===a[e+1])throw new InvalidArgumentsError(`source ${n} numbers to be unique.`);if(a[e]!==i[e])throw new InvalidArgumentsError(`target ${n} numbers to be permutation of source ${n} numbers.`)}}ensureNamedExpressionNameIsValid(e,t){if(!this.namedExpressions.isNameValid(e))throw new NamedExpressionNameIsInvalidError(e);if(!this.namedExpressions.isNameAvailable(e,t))throw new NamedExpressionNameIsAlreadyTakenError(e)}ensureNamedExpressionIsValid(e){const t=this.cellContentParser.parse(e);if(t instanceof CellContent.Formula){const e=this.parser.parse(t.formula,simpleCellAddress(-1,0,0));if(doesContainRelativeReferences(e.ast))throw new NoRelativeAddressesAllowedError}}}function isPositiveInteger(e){return Number.isInteger(e)&&e>0}function isNonnegativeInteger(e){return Number.isInteger(e)&&e>=0} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class Evaluator{constructor(e,t,n,r,a,i){this.config=e,this.stats=t,this.interpreter=n,this.lazilyTransformingAstService=r,this.dependencyGraph=a,this.columnSearch=i}run(){this.stats.start(StatType.TOP_SORT);const{sorted:e,cycled:t}=this.dependencyGraph.topSortWithScc();this.stats.end(StatType.TOP_SORT),this.stats.measure(StatType.EVALUATION,(()=>{this.recomputeFormulas(t,e)}))}partialRun(e){const t=ContentChanges.empty();return this.stats.measure(StatType.EVALUATION,(()=>{this.dependencyGraph.graph.getTopSortedWithSccSubgraphFrom(e,(e=>{if(e instanceof FormulaVertex){const n=e.isComputed()?e.getCellValue():void 0,r=this.recomputeFormulaVertexValue(e);if(r!==n){const a=e.getAddress(this.lazilyTransformingAstService);return t.addChange(r,a),this.columnSearch.change(getRawValue(n),getRawValue(r),a),!0}return!1}return!(e instanceof RangeVertex)||(e.clearCache(),!0)}),(e=>{if(e instanceof RangeVertex)e.clearCache();else if(e instanceof FormulaVertex){const n=e.getAddress(this.lazilyTransformingAstService);this.columnSearch.remove(getRawValue(e.valueOrUndef()),n);const r=new CellError(ErrorType.CYCLE,void 0,e);e.setCellValue(r),t.addChange(r,n)}}))})),t}runAndForget(e,t,n){const r=[];for(const e of absolutizeDependencies(n,t))if(e instanceof AbsoluteCellRange){const t=e;if(void 0===this.dependencyGraph.getRange(t.start,t.end)){const e=new RangeVertex(t);this.dependencyGraph.rangeMapping.setRange(e),r.push(e)}}const a=this.evaluateAstToCellValue(e,new InterpreterState(t,this.config.useArrayArithmetic));return r.forEach((e=>{this.dependencyGraph.rangeMapping.removeRange(e)})),a}recomputeFormulas(e,t){e.forEach((e=>{e instanceof FormulaVertex&&e.setCellValue(new CellError(ErrorType.CYCLE,void 0,e))})),t.forEach((e=>{if(e instanceof FormulaVertex){const t=this.recomputeFormulaVertexValue(e),n=e.getAddress(this.lazilyTransformingAstService);this.columnSearch.add(getRawValue(t),n)}else e instanceof RangeVertex&&e.clearCache()}))}recomputeFormulaVertexValue(e){const t=e.getAddress(this.lazilyTransformingAstService);if(e instanceof ArrayVertex&&(e.array.size.isRef||!this.dependencyGraph.isThereSpaceForArray(e)))return e.setNoSpace();{const n=e.getFormula(this.lazilyTransformingAstService),r=this.evaluateAstToCellValue(n,new InterpreterState(t,this.config.useArrayArithmetic,e));return e.setCellValue(r)}}evaluateAstToCellValue(e,t){const n=this.interpreter.evaluateAst(e,t);return n instanceof SimpleRangeValue?n:n===EmptyValue&&this.config.evaluateNullToZero?0:n}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class ExportedCellChange{constructor(e,t){this.address=e,this.newValue=t}get col(){return this.address.col}get row(){return this.address.row}get sheet(){return this.address.sheet}get value(){return this.newValue}}class ExportedNamedExpressionChange{constructor(e,t){this.name=e,this.newValue=t}}class Exporter{constructor(e,t,n,r){this.config=e,this.namedExpressions=t,this.sheetIndexMapping=n,this.lazilyTransformingService=r}exportChange(e){const t=e.value,n=e.address;if(n.sheet===NamedExpressions.SHEET_FOR_WORKBOOK_EXPRESSIONS){const e=this.namedExpressions.namedExpressionInAddress(n.row);if(!e)throw new Error("Missing named expression");return new ExportedNamedExpressionChange(e.displayName,this.exportScalarOrRange(t))}if(t instanceof SimpleRangeValue){const e=[];for(const[r,a]of t.entriesFromTopLeftCorner(n))e.push(new ExportedCellChange(a,this.exportValue(r)));return e}return new ExportedCellChange(n,this.exportValue(t))}exportValue(e){return e instanceof SimpleRangeValue?this.detailedError(new CellError(ErrorType.VALUE,ErrorMessage.ScalarExpected)):this.config.smartRounding&&isExtendedNumber(e)?this.cellValueRounding(getRawValue(e)):e instanceof CellError?this.detailedError(e):e===EmptyValue?null:getRawValue(e)}exportScalarOrRange(e){return e instanceof SimpleRangeValue?e.rawData().map((e=>e.map((e=>this.exportValue(e))))):this.exportValue(e)}detailedError(e){var t,n;let r;const a=null===(t=e.root)||void 0===t?void 0:t.getAddress(this.lazilyTransformingService);return void 0!==a&&(r=a.sheet===NamedExpressions.SHEET_FOR_WORKBOOK_EXPRESSIONS?null===(n=this.namedExpressions.namedExpressionInAddress(a.row))||void 0===n?void 0:n.displayName:simpleCellAddressToString(this.sheetIndexMapping,a,-1)),new DetailedCellError(e,this.config.translationPackage.getErrorTranslation(e.type),r)}cellValueRounding(e){if(0===e)return e;const t=Math.floor(Math.log10(Math.abs(e))),n=Math.pow(10,this.config.precisionRounding-t);return e<0?-Math.round(-e*n)/n:Math.round(e*n)/n}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class GraphBuilder{constructor(e,t,n,r,a,i){this.dependencyGraph=e,this.columnSearch=t,this.parser=n,this.cellContentParser=r,this.stats=a,this.arraySizePredictor=i,this.buildStrategy=new SimpleStrategy(e,t,n,a,r,i)}buildGraph(e,t){const n=t.measure(StatType.COLLECT_DEPENDENCIES,(()=>this.buildStrategy.run(e)));this.dependencyGraph.getAndClearContentChanges(),t.measure(StatType.PROCESS_DEPENDENCIES,(()=>this.processDependencies(n)))}processDependencies(e){e.forEach(((e,t)=>{this.dependencyGraph.processCellDependencies(e,t)}))}}class SimpleStrategy{constructor(e,t,n,r,a,i){this.dependencyGraph=e,this.columnIndex=t,this.parser=n,this.stats=r,this.cellContentParser=a,this.arraySizePredictor=i}run(e){const t=new Map;for(const n in e){const r=this.dependencyGraph.getSheetId(n),a=e[n];for(let e=0;ethis.parser.parse(o.formula,s)));if(e.errors.length>0){this.shrinkArrayIfNeeded(s);const t=new ParsingErrorVertex(e.errors,o.formula);this.dependencyGraph.addVertex(s,t)}else{this.shrinkArrayIfNeeded(s);const n=this.arraySizePredictor.checkArraySize(e.ast,s);if(n.isScalar()){const n=new FormulaCellVertex(e.ast,s,0);t.set(n,absolutizeDependencies(e.dependencies,s)),this.dependencyGraph.addVertex(s,n),e.hasVolatileFunction&&this.dependencyGraph.markAsVolatile(n),e.hasStructuralChangeFunction&&this.dependencyGraph.markAsDependentOnStructureChange(n)}else{const r=new ArrayVertex(e.ast,s,new ArraySize(n.width,n.height));t.set(r,absolutizeDependencies(e.dependencies,s)),this.dependencyGraph.addArrayVertex(s,r)}}}else if(o instanceof CellContent.Empty);else{this.shrinkArrayIfNeeded(s);const e=new ValueCellVertex(o.value,i);this.columnIndex.add(getRawValue(o.value),s),this.dependencyGraph.addVertex(s,e)}}}}return t}shrinkArrayIfNeeded(e){const t=this.dependencyGraph.getCell(e);t instanceof ArrayVertex&&this.dependencyGraph.shrinkArrayToCorner(t)}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */const LICENSE_STATUS_MAP=new Map([["gpl-v3",1],["missing",2],["invalid",3],["expired",4]]);class VersionPlugin extends FunctionPlugin{version(e,t){return this.runFunction(e.args,t,this.metadata("VERSION"),(()=>{const{licenseKeyValidityState:e,licenseKey:t}=this.config;let n;return LICENSE_STATUS_MAP.has(t)?n=LICENSE_STATUS_MAP.get(t):LICENSE_STATUS_MAP.has(e)?n=LICENSE_STATUS_MAP.get(e):"valid"===e&&(n=t.slice(-5)),`HyperFormula v${HyperFormula.version}, ${n}`}))}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +function validateAndReturnMetadataFromName(e,t){var n;let r=t.implementedFunctions[e];const a=null===(n=t.aliases)||void 0===n?void 0:n[e];if(void 0!==a){if(void 0!==r)throw new AliasAlreadyExisting(e,t.name);r=t.implementedFunctions[a]}if(void 0===r)throw FunctionPluginValidationError.functionNotDeclaredInPlugin(e,t.name);return r}VersionPlugin.implementedFunctions={VERSION:{method:"version",parameters:[]}};class FunctionRegistry{constructor(e){if(this.config=e,this.functions=new Map,this.arraySizeFunctions=new Map,this.volatileFunctions=new Set,this.arrayFunctions=new Set,this.structuralChangeFunctions=new Set,this.functionsWhichDoesNotNeedArgumentsToBeComputed=new Set,this.functionsMetadata=new Map,this.doesFunctionNeedArgumentToBeComputed=e=>this.functionsWhichDoesNotNeedArgumentsToBeComputed.has(e),this.isFunctionVolatile=e=>this.volatileFunctions.has(e),this.isArrayFunction=e=>this.arrayFunctions.has(e),this.isFunctionDependentOnSheetStructureChange=e=>this.structuralChangeFunctions.has(e),e.functionPlugins.length>0){this.instancePlugins=new Map;for(const t of e.functionPlugins)FunctionRegistry.loadPluginFunctions(t,this.instancePlugins)}else this.instancePlugins=new Map(FunctionRegistry.plugins);for(const[e,t]of FunctionRegistry.protectedFunctions())FunctionRegistry.loadFunctionUnprotected(t,e,this.instancePlugins);for(const[e,t]of this.instancePlugins.entries())this.categorizeFunction(e,validateAndReturnMetadataFromName(e,t))}static registerFunctionPlugin(e,t){this.loadPluginFunctions(e,this.plugins),void 0!==t&&this.loadTranslations(t)}static registerFunction(e,t,n){this.loadPluginFunction(t,e,this.plugins),void 0!==n&&this.loadTranslations(n)}static unregisterFunction(e){if(this.functionIsProtected(e))throw ProtectedFunctionError.cannotUnregisterFunctionWithId(e);this.plugins.delete(e)}static unregisterFunctionPlugin(e){for(const t of this.protectedPlugins())if(t===e)throw ProtectedFunctionError.cannotUnregisterProtectedPlugin();for(const[t,n]of this.plugins.entries())n===e&&this.plugins.delete(t)}static unregisterAll(){this.plugins.clear()}static getRegisteredFunctionIds(){return[...Array.from(this.plugins.keys()),...Array.from(this._protectedPlugins.keys())]}static getPlugins(){return Array.from(new Set(this.plugins.values()).values())}static getFunctionPlugin(e){return this.functionIsProtected(e)?void 0:this.plugins.get(e)}static functionIsProtected(e){return this._protectedPlugins.has(e)}static loadTranslations(e){const t=new Set(HyperFormula.getRegisteredLanguagesCodes());Object.keys(e).forEach((n=>{t.has(n)&&HyperFormula.getLanguage(n).extendFunctions(e[n])}))}static loadPluginFunctions(e,t){Object.keys(e.implementedFunctions).forEach((n=>{this.loadPluginFunction(e,n,t)})),void 0!==e.aliases&&Object.keys(e.aliases).forEach((n=>{this.loadPluginFunction(e,n,t)}))}static loadPluginFunction(e,t,n){if(this.functionIsProtected(t))throw ProtectedFunctionError.cannotRegisterFunctionWithId(t);this.loadFunctionUnprotected(e,t,n)}static loadFunctionUnprotected(e,t,n){const r=validateAndReturnMetadataFromName(t,e).method;if(!Object.prototype.hasOwnProperty.call(e.prototype,r))throw FunctionPluginValidationError.functionMethodNotFound(r,e.name);n.set(t,e)}static*protectedFunctions(){for(const[e,t]of this._protectedPlugins)void 0!==t&&(yield[e,t])}static*protectedPlugins(){for(const[,e]of this._protectedPlugins)void 0!==e&&(yield e)}initializePlugins(e){const t=[];for(const[n,r]of this.instancePlugins.entries()){let a=t.find((e=>e instanceof r));void 0===a&&(a=new r(e),t.push(a));const i=validateAndReturnMetadataFromName(n,r),s=i.method;this.functions.set(n,[s,a]);const o=i.arraySizeMethod;void 0!==o&&this.arraySizeFunctions.set(n,[o,a])}}getFunctionPlugin(e){if(!FunctionRegistry.functionIsProtected(e))return this.instancePlugins.get(e)}getFunction(e){const t=this.functions.get(e);if(void 0!==t&&this.config.translationPackage.isFunctionTranslated(e)){const[e,n]=t;return(t,r)=>n[e](t,r)}}getArraySizeFunction(e){const t=this.arraySizeFunctions.get(e);if(void 0!==t&&this.config.translationPackage.isFunctionTranslated(e)){const[e,n]=t;return(t,r)=>n[e](t,r)}}getMetadata(e){return this.functionsMetadata.get(e)}getPlugins(){const e=new Set;for(const[t,n]of this.instancePlugins)FunctionRegistry.functionIsProtected(t)||e.add(n);return Array.from(e)}getRegisteredFunctionIds(){return Array.from(this.functions.keys())}categorizeFunction(e,t){t.isVolatile&&this.volatileFunctions.add(e),t.arrayFunction&&this.arrayFunctions.add(e),t.doesNotNeedArgumentsToBeComputed&&this.functionsWhichDoesNotNeedArgumentsToBeComputed.add(e),t.isDependentOnSheetStructureChange&&this.structuralChangeFunctions.add(e),this.functionsMetadata.set(e,t)}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +var CriterionType;FunctionRegistry.plugins=new Map,FunctionRegistry._protectedPlugins=new Map([["VERSION",VersionPlugin],["OFFSET",void 0]]),function(e){e.GREATER_THAN="GREATER_THAN",e.GREATER_THAN_OR_EQUAL="GREATER_THAN_OR_EQUAL",e.LESS_THAN="LESS_THAN",e.LESS_THAN_OR_EQUAL="LESS_THAN_OR_EQUAL",e.NOT_EQUAL="NOT_EQUAL",e.EQUAL="EQUAL"}(CriterionType||(CriterionType={}));const buildCriterion=(e,t)=>({operator:e,value:t});class CriterionBuilder{constructor(e){var t,n,r,a;this.trueString=null!==(n=null===(t=e.translationPackage.getMaybeFunctionTranslation("TRUE"))||void 0===t?void 0:t.toLowerCase())&&void 0!==n?n:"true",this.falseString=null!==(a=null===(r=e.translationPackage.getMaybeFunctionTranslation("FALSE"))||void 0===r?void 0:r.toLowerCase())&&void 0!==a?a:"false"}fromCellValue(e,t){if("string"!=typeof e&&"boolean"!=typeof e&&"number"!=typeof e)return;const n=this.parseCriterion(e,t);return void 0!==n?{raw:e,lambda:buildCriterionLambda(n,t)}:void 0}parseCriterion(e,t){if("number"==typeof e||"boolean"==typeof e)return buildCriterion(CriterionType.EQUAL,e);if("string"==typeof e){const n=ANY_CRITERION_REGEX.exec(e);let r,a;n?(a=StrToCriterionType(n[1]),r=n[2]):(a=CriterionType.EQUAL,r=e);const i=t.coerceToMaybeNumber(r),s=r.toLowerCase()===this.trueString||r.toLowerCase()!==this.falseString&&void 0;if(void 0===a)return;if(""===r)return buildCriterion(a,null);if(void 0!==i)return buildCriterion(a,getRawValue(i));if(a===CriterionType.EQUAL||a===CriterionType.NOT_EQUAL)return buildCriterion(a,null!=s?s:r)}}}const ANY_CRITERION_REGEX=/([<>=]+)(.*)/;function StrToCriterionType(e){switch(e){case">":return CriterionType.GREATER_THAN;case">=":return CriterionType.GREATER_THAN_OR_EQUAL;case"<":return CriterionType.LESS_THAN;case"<=":return CriterionType.LESS_THAN_OR_EQUAL;case"<>":return CriterionType.NOT_EQUAL;case"=":return CriterionType.EQUAL;default:return}}const buildCriterionLambda=(e,t)=>{switch(e.operator){case CriterionType.GREATER_THAN:return"number"==typeof e.value?n=>"number"==typeof n&&t.floatCmp(n,e.value)>0:e=>!1;case CriterionType.GREATER_THAN_OR_EQUAL:return"number"==typeof e.value?n=>"number"==typeof n&&t.floatCmp(n,e.value)>=0:e=>!1;case CriterionType.LESS_THAN:return"number"==typeof e.value?n=>"number"==typeof n&&t.floatCmp(n,e.value)<0:e=>!1;case CriterionType.LESS_THAN_OR_EQUAL:return"number"==typeof e.value?n=>"number"==typeof n&&t.floatCmp(n,e.value)<=0:e=>!1;case CriterionType.EQUAL:return"number"==typeof e.value?n=>{if("number"==typeof n)return 0===t.floatCmp(n,e.value);if("string"==typeof n){if(""===n)return!1;const r=t.coerceToMaybeNumber(n);return void 0!==r&&0===t.floatCmp(r,e.value)}return!1}:"string"==typeof e.value?t.eqMatcherFunction(e.value):"boolean"==typeof e.value?t=>"boolean"==typeof t&&t===e.value:e=>e===EmptyValue;case CriterionType.NOT_EQUAL:return"number"==typeof e.value?n=>{if("number"==typeof n)return 0!==t.floatCmp(n,e.value);if("string"==typeof n){if(""===n)return!0;const r=t.coerceToMaybeNumber(n);return void 0===r||0!==t.floatCmp(r,e.value)}return!0}:"string"==typeof e.value?t.neqMatcherFunction(e.value):"boolean"==typeof e.value?t=>"boolean"!=typeof t||t!==e.value:e=>e!==EmptyValue}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class Interpreter{constructor(e,t,n,r,a,i,s,o,l,u){this.config=e,this.dependencyGraph=t,this.columnSearch=n,this.stats=r,this.arithmeticHelper=a,this.functionRegistry=i,this.namedExpressions=s,this.serialization=o,this.arraySizePredictor=l,this.dateTimeHelper=u,this.equalOp=(e,t)=>binaryErrorWrapper(this.arithmeticHelper.eq,e,t),this.notEqualOp=(e,t)=>binaryErrorWrapper(this.arithmeticHelper.neq,e,t),this.greaterThanOp=(e,t)=>binaryErrorWrapper(this.arithmeticHelper.gt,e,t),this.lessThanOp=(e,t)=>binaryErrorWrapper(this.arithmeticHelper.lt,e,t),this.greaterThanOrEqualOp=(e,t)=>binaryErrorWrapper(this.arithmeticHelper.geq,e,t),this.lessThanOrEqualOp=(e,t)=>binaryErrorWrapper(this.arithmeticHelper.leq,e,t),this.concatOp=(e,t)=>binaryErrorWrapper(this.arithmeticHelper.concat,coerceScalarToString(e),coerceScalarToString(t)),this.plusOp=(e,t)=>binaryErrorWrapper(this.arithmeticHelper.addWithEpsilon,this.arithmeticHelper.coerceScalarToNumberOrError(e),this.arithmeticHelper.coerceScalarToNumberOrError(t)),this.minusOp=(e,t)=>binaryErrorWrapper(this.arithmeticHelper.subtract,this.arithmeticHelper.coerceScalarToNumberOrError(e),this.arithmeticHelper.coerceScalarToNumberOrError(t)),this.timesOp=(e,t)=>binaryErrorWrapper(this.arithmeticHelper.multiply,this.arithmeticHelper.coerceScalarToNumberOrError(e),this.arithmeticHelper.coerceScalarToNumberOrError(t)),this.powerOp=(e,t)=>binaryErrorWrapper(this.arithmeticHelper.pow,this.arithmeticHelper.coerceScalarToNumberOrError(e),this.arithmeticHelper.coerceScalarToNumberOrError(t)),this.divOp=(e,t)=>binaryErrorWrapper(this.arithmeticHelper.divide,this.arithmeticHelper.coerceScalarToNumberOrError(e),this.arithmeticHelper.coerceScalarToNumberOrError(t)),this.unaryMinusOp=e=>unaryErrorWrapper(this.arithmeticHelper.unaryMinus,this.arithmeticHelper.coerceScalarToNumberOrError(e)),this.percentOp=e=>unaryErrorWrapper(this.arithmeticHelper.unaryPercent,this.arithmeticHelper.coerceScalarToNumberOrError(e)),this.unaryPlusOp=e=>this.arithmeticHelper.unaryPlus(e),this.functionRegistry.initializePlugins(this),this.criterionBuilder=new CriterionBuilder(e)}evaluateAst(e,t){let n=this.evaluateAstWithoutPostprocessing(e,t);if(isExtendedNumber(n)){if(isNumberOverflow(getRawValue(n)))return new CellError(ErrorType.NUM,ErrorMessage.NaN);n=cloneNumber(n,fixNegativeZero(getRawValue(n)))}return n instanceof SimpleRangeValue&&1===n.height()&&1===n.width()&&([[n]]=n.data),wrapperForRootVertex(n,t.formulaVertex)}evaluateAstWithoutPostprocessing(e,t){switch(e.type){case AstNodeType.EMPTY:return EmptyValue;case AstNodeType.CELL_REFERENCE:{const n=e.reference.toSimpleCellAddress(t.formulaAddress);return invalidSimpleCellAddress(n)?new CellError(ErrorType.REF,ErrorMessage.BadRef):this.dependencyGraph.getCellValue(n)}case AstNodeType.NUMBER:case AstNodeType.STRING:return e.value;case AstNodeType.CONCATENATE_OP:{const n=this.evaluateAst(e.left,t),r=this.evaluateAst(e.right,t);return this.binaryRangeWrapper(this.concatOp,n,r,t)}case AstNodeType.EQUALS_OP:{const n=this.evaluateAst(e.left,t),r=this.evaluateAst(e.right,t);return this.binaryRangeWrapper(this.equalOp,n,r,t)}case AstNodeType.NOT_EQUAL_OP:{const n=this.evaluateAst(e.left,t),r=this.evaluateAst(e.right,t);return this.binaryRangeWrapper(this.notEqualOp,n,r,t)}case AstNodeType.GREATER_THAN_OP:{const n=this.evaluateAst(e.left,t),r=this.evaluateAst(e.right,t);return this.binaryRangeWrapper(this.greaterThanOp,n,r,t)}case AstNodeType.LESS_THAN_OP:{const n=this.evaluateAst(e.left,t),r=this.evaluateAst(e.right,t);return this.binaryRangeWrapper(this.lessThanOp,n,r,t)}case AstNodeType.GREATER_THAN_OR_EQUAL_OP:{const n=this.evaluateAst(e.left,t),r=this.evaluateAst(e.right,t);return this.binaryRangeWrapper(this.greaterThanOrEqualOp,n,r,t)}case AstNodeType.LESS_THAN_OR_EQUAL_OP:{const n=this.evaluateAst(e.left,t),r=this.evaluateAst(e.right,t);return this.binaryRangeWrapper(this.lessThanOrEqualOp,n,r,t)}case AstNodeType.PLUS_OP:{const n=this.evaluateAst(e.left,t),r=this.evaluateAst(e.right,t);return this.binaryRangeWrapper(this.plusOp,n,r,t)}case AstNodeType.MINUS_OP:{const n=this.evaluateAst(e.left,t),r=this.evaluateAst(e.right,t);return this.binaryRangeWrapper(this.minusOp,n,r,t)}case AstNodeType.TIMES_OP:{const n=this.evaluateAst(e.left,t),r=this.evaluateAst(e.right,t);return this.binaryRangeWrapper(this.timesOp,n,r,t)}case AstNodeType.POWER_OP:{const n=this.evaluateAst(e.left,t),r=this.evaluateAst(e.right,t);return this.binaryRangeWrapper(this.powerOp,n,r,t)}case AstNodeType.DIV_OP:{const n=this.evaluateAst(e.left,t),r=this.evaluateAst(e.right,t);return this.binaryRangeWrapper(this.divOp,n,r,t)}case AstNodeType.PLUS_UNARY_OP:{const n=this.evaluateAst(e.value,t);return this.unaryRangeWrapper(this.unaryPlusOp,n,t)}case AstNodeType.MINUS_UNARY_OP:{const n=this.evaluateAst(e.value,t);return this.unaryRangeWrapper(this.unaryMinusOp,n,t)}case AstNodeType.PERCENT_OP:{const n=this.evaluateAst(e.value,t);return this.unaryRangeWrapper(this.percentOp,n,t)}case AstNodeType.FUNCTION_CALL:{if("valid"!==this.config.licenseKeyValidityState&&!FunctionRegistry.functionIsProtected(e.procedureName))return new CellError(ErrorType.LIC,ErrorMessage.LicenseKey(this.config.licenseKeyValidityState));const n=this.functionRegistry.getFunction(e.procedureName);return void 0!==n?n(e,new InterpreterState(t.formulaAddress,t.arraysFlag||this.functionRegistry.isArrayFunction(e.procedureName),t.formulaVertex)):new CellError(ErrorType.NAME,ErrorMessage.FunctionName(e.procedureName))}case AstNodeType.NAMED_EXPRESSION:{const n=this.namedExpressions.nearestNamedExpression(e.expressionName,t.formulaAddress.sheet);return n?this.dependencyGraph.getCellValue(n.address):new CellError(ErrorType.NAME,ErrorMessage.NamedExpressionName(e.expressionName))}case AstNodeType.CELL_RANGE:{if(!this.rangeSpansOneSheet(e))return new CellError(ErrorType.REF,ErrorMessage.RangeManySheets);const n=AbsoluteCellRange.fromCellRange(e,t.formulaAddress),r=this.dependencyGraph.getArray(n);if(r){const e=r.array;if(e instanceof NotComputedArray)throw new Error("Array should be already computed");if(e instanceof CellError)return e;if(e instanceof ArrayValue)return SimpleRangeValue.fromRange(e.raw(),n,this.dependencyGraph);throw new Error("Unknown array")}return SimpleRangeValue.onlyRange(n,this.dependencyGraph)}case AstNodeType.COLUMN_RANGE:{if(!this.rangeSpansOneSheet(e))return new CellError(ErrorType.REF,ErrorMessage.RangeManySheets);const n=AbsoluteColumnRange.fromColumnRange(e,t.formulaAddress);return SimpleRangeValue.onlyRange(n,this.dependencyGraph)}case AstNodeType.ROW_RANGE:{if(!this.rangeSpansOneSheet(e))return new CellError(ErrorType.REF,ErrorMessage.RangeManySheets);const n=AbsoluteRowRange.fromRowRangeAst(e,t.formulaAddress);return SimpleRangeValue.onlyRange(n,this.dependencyGraph)}case AstNodeType.PARENTHESIS:return this.evaluateAst(e.expression,t);case AstNodeType.ARRAY:{let n;const r=[];for(const a of e.args){let e;const i=[];for(const n of a){const r=coerceToRange(this.evaluateAst(n,t)),a=r.height();if(void 0===e)e=a,i.push(...r.data);else{if(e!==a)return new CellError(ErrorType.REF,ErrorMessage.SizeMismatch);for(let e=0;et.map(e)));return SimpleRangeValue.onlyValues(n)}return e(t)}binaryRangeWrapper(e,t,n,r){var a,i;if(t instanceof SimpleRangeValue&&!r.arraysFlag&&(t=null!==(a=coerceRangeToScalar(t,r))&&void 0!==a?a:new CellError(ErrorType.VALUE,ErrorMessage.ScalarExpected)),t instanceof CellError)return t;if(n instanceof SimpleRangeValue&&!r.arraysFlag&&(n=null!==(i=coerceRangeToScalar(n,r))&&void 0!==i?i:new CellError(ErrorType.VALUE,ErrorMessage.ScalarExpected)),n instanceof CellError)return n;if(t instanceof SimpleRangeValue||n instanceof SimpleRangeValue){if(!(t instanceof SimpleRangeValue)){if(n.isAdHoc()){const r=n.data;for(let n=0;nn.performEagerTransformations(e,t)))}transformSingleAst(e,t){let[n,r]=[e,t];return this.transformations.forEach((e=>{[n,r]=e.transformSingleAst(n,r)})),[n,r]}isIrreversible(){return!0}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class LazilyTransformingAstService{constructor(e){this.stats=e,this.transformations=[]}version(){return this.transformations.length}addTransformation(e){return void 0!==this.combinedTransformer?this.combinedTransformer.add(e):this.transformations.push(e),this.version()}beginCombinedMode(e){this.combinedTransformer=new CombinedTransformer(e)}commitCombinedMode(){if(void 0===this.combinedTransformer)throw"Combined mode wasn't started";return this.transformations.push(this.combinedTransformer),this.combinedTransformer=void 0,this.version()}applyTransformations(e,t,n){this.stats.start(StatType.TRANSFORM_ASTS_POSTPONED);for(let r=n;rgetRawValue(n.getCellValue(simpleCellAddress(e.sheet,e.start.col,t))):t=>getRawValue(n.getCellValue(simpleCellAddress(e.sheet,t,e.start.row)));const o=lowerBound$2(s,t,i,a);return typeof s(o)!=typeof t?-1:o-i}function lowerBound$2(e,t,n,r){for(;n<=r;){const a=Math.floor((n+r)/2),i=compare(t,e(a));if(i>0)n=a+1;else if(i<0)r=a-1;else{if(n==a)return a;r=a}}return r}function compare(e,t){return typeof e==typeof t?e===EmptyValue?0:et?1:0:e===EmptyValue?-1:t===EmptyValue?1:t instanceof CellError||"number"==typeof e&&"string"==typeof t||"number"==typeof e&&"boolean"==typeof t?-1:"string"==typeof e&&"number"==typeof t?1:"string"==typeof e&&"boolean"==typeof t?-1:1} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class AdvancedFind{constructor(e){this.dependencyGraph=e}advancedFind(e,t){let n;const r=t.range;n=void 0===r?t.valuesFromTopLeftCorner():this.dependencyGraph.computeListOfValuesInRange(r);for(let t=0;t"string"==typeof e?forceNormalizeString(e):e)).indexOf(e):n?rangeLowerBound(r,e,this.dependencyGraph,"row"):this.dependencyGraph.computeListOfValuesInRange(r).findIndex((t=>(t="string"==typeof(t=getRawValue(t))?forceNormalizeString(t):t)===e))}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class ColumnIndex{constructor(e,t,n){this.dependencyGraph=e,this.config=t,this.stats=n,this.index=new Map,this.transformingService=this.dependencyGraph.lazilyTransformingAstService,this.binarySearchStrategy=new ColumnBinarySearch(e,t)}add(e,t){if(!(e===EmptyValue||e instanceof CellError))if(e instanceof SimpleRangeValue)for(const[n,r]of e.entriesFromTopLeftCorner(t))this.addSingleCellValue(getRawValue(n),r);else this.addSingleCellValue(e,t)}remove(e,t){if(void 0!==e)if(e instanceof SimpleRangeValue)for(const[n,r]of e.entriesFromTopLeftCorner(t))this.removeSingleValue(getRawValue(n),r);else this.removeSingleValue(e,t)}change(e,t,n){e!==t&&(this.remove(e,n),this.add(t,n))}applyChanges(e){for(const t of e)void 0!==t.oldValue&&this.change(getRawValue(t.oldValue),getRawValue(t.value),t.address)}moveValues(e,t,n,r){for(const[a,i]of e){const e=movedSimpleCellAddress(i,r,t,n);this.remove(a,i),this.add(a,e)}}removeValues(e){for(const[t,n]of e)this.remove(t,n)}find(e,t,n){const r=t.range;if(void 0===r)return this.binarySearchStrategy.find(e,t,n);this.ensureRecentData(r.sheet,r.start.col,e);const a=this.getColumnMap(r.sheet,r.start.col);if(!a)return-1;"string"==typeof e&&(e=forceNormalizeString(e));const i=a.get(e);if(!i)return this.binarySearchStrategy.find(e,t,n);const s=upperBound(i.index,r.start.row),o=i.index[s];return o<=r.end.row?o-r.start.row:this.binarySearchStrategy.find(e,t,n)}advancedFind(e,t){return this.binarySearchStrategy.advancedFind(e,t)}addColumns(e){const t=this.index.get(e.sheet);t&&t.splice(e.columnStart,0,...Array(e.numberOfColumns))}removeColumns(e){const t=this.index.get(e.sheet);t&&t.splice(e.columnStart,e.numberOfColumns)}removeSheet(e){this.index.delete(e)}getColumnMap(e,t){this.index.has(e)||this.index.set(e,[]);const n=this.index.get(e);let r=n[t];return r||(r=new Map,n[t]=r),r}getValueIndex(e,t,n){const r=this.getColumnMap(e,t);let a=this.getColumnMap(e,t).get(n);return a||(a={version:this.transformingService.version(),index:[]},r.set(n,a)),a}ensureRecentData(e,t,n){const r=this.getValueIndex(e,t,n),a=this.transformingService.version();if(r.version===a)return;const i=this.transformingService.getTransformationsFrom(r.version,(t=>t.sheet===e&&(t instanceof AddRowsTransformer||t instanceof RemoveRowsTransformer)));for(const e of i)e instanceof AddRowsTransformer?this.addRows(t,e.rowsSpan,n):e instanceof RemoveRowsTransformer&&this.removeRows(t,e.rowsSpan,n);r.version=a}addSingleCellValue(e,t){this.stats.measure(StatType.BUILD_COLUMN_INDEX,(()=>{this.ensureRecentData(t.sheet,t.col,e),"string"==typeof e&&(e=forceNormalizeString(e));const n=this.getValueIndex(t.sheet,t.col,e);this.addValue(n,t.row)}))}removeSingleValue(e,t){this.stats.measure(StatType.BUILD_COLUMN_INDEX,(()=>{this.ensureRecentData(t.sheet,t.col,e);const n=this.getColumnMap(t.sheet,t.col);"string"==typeof e&&(e=forceNormalizeString(e));const r=n.get(e);if(!r)return;const a=upperBound(r.index,t.row);r.index.splice(a,1),0===r.index.length&&n.delete(e),0===n.size&&delete this.index.get(t.sheet)[t.col]}))}addRows(e,t,n){const r=this.getValueIndex(t.sheet,e,n);this.shiftRows(r,t.rowStart,t.numberOfRows)}removeRows(e,t,n){const r=this.getValueIndex(t.sheet,e,n);this.removeRowsFromValues(r,t),this.shiftRows(r,t.rowEnd+1,-t.numberOfRows)}addValue(e,t){const n=lowerBound$1(e.index,t);e.index[n]!==t&&(n===e.index.length-1?e.index.push(t):e.index.splice(n+1,0,t))}removeRowsFromValues(e,t){const n=upperBound(e.index,t.rowStart),r=lowerBound$1(e.index,t.rowEnd);e.index[n]<=t.rowEnd&&e.index.splice(n,r-n+1)}shiftRows(e,t,n){for(let r=upperBound(e.index,t);re[a])n=a+1;else{if(!(te[a])n=a+1;else{if(!(tthis.getCellValue(e)))}getSheetFormulas(e){return this.genericSheetGetter(e,(e=>this.getCellFormula(e)))}genericSheetGetter(e,t){const n=this.dependencyGraph.getSheetHeight(e),r=this.dependencyGraph.getSheetWidth(e),a=new Array(n);for(let i=0;i=0&&(null===a[i][e]||void 0===a[i][e]);e--)a[i].pop()}for(let e=n-1;e>=0&&0===a[e].length;e--)a.pop();return a}genericAllSheetsGetter(e){const t={};for(const n of this.dependencyGraph.sheetMapping.displayNames()){const r=this.dependencyGraph.sheetMapping.fetch(n);t[n]=e(r)}return t}getSheetSerialized(e){return this.genericSheetGetter(e,(e=>this.getCellSerialized(e)))}getAllSheetsValues(){return this.genericAllSheetsGetter((e=>this.getSheetValues(e)))}getAllSheetsFormulas(){return this.genericAllSheetsGetter((e=>this.getSheetFormulas(e)))}getAllSheetsSerialized(){return this.genericAllSheetsGetter((e=>this.getSheetSerialized(e)))}getAllNamedExpressionsSerialized(){const e=[];let t=0;for(const n of this.dependencyGraph.sheetMapping.displayNames()){const r=this.dependencyGraph.sheetMapping.fetch(n);e[r]=t,t++}return this.dependencyGraph.namedExpressions.getAllNamedExpressions().map((t=>({name:t.expression.displayName,expression:this.getCellSerialized(t.expression.address),scope:void 0!==t.scope?e[t.scope]:void 0,options:t.expression.options})))}withNewConfig(e,t){const n=new Unparser(e,buildLexerConfig(e),this.dependencyGraph.sheetMapping.fetchDisplayName,t);return new Serialization(this.dependencyGraph,n,this.exporter)}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class BuildEngineFactory{static buildFromSheets(e,t={},n=[]){const r=new Config(t);return this.buildEngine(r,e,n)}static buildFromSheet(e,t={},n=[]){const r=new Config(t),a=r.translationPackage.getUITranslation(UIElement.NEW_SHEET_PREFIX)+"1";return this.buildEngine(r,{[a]:e},n)}static buildEmpty(e={},t=[]){return this.buildEngine(new Config(e),{},t)}static rebuildWithConfig(e,t,n,r){return this.buildEngine(e,t,n,r)}static buildEngine(e,t={},n=[],r=(e.useStats?new Statistics:new EmptyStatistics)){r.start(StatType.BUILD_ENGINE_TOTAL);const a=new NamedExpressions,i=new FunctionRegistry(e),s=new LazilyTransformingAstService(r),o=DependencyGraph.buildEmpty(s,e,i,a,r),l=buildColumnSearchStrategy(o,e,r),u=o.sheetMapping,c=o.addressMapping;for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const r=t[n];validateAsSheet(r);const a=findBoundaries(r);if(a.height>e.maxRows||a.width>e.maxColumns)throw new SheetSizeLimitExceededError;const i=u.addSheet(n);c.autoAddSheet(i,r,a)}const p=new ParserWithCaching(e,i,u.get);s.parser=p;const d=new Unparser(e,buildLexerConfig(e),u.fetchDisplayName,a),m=new DateTimeHelper(e),h=new NumberLiteralHelper(e),f=new ArithmeticHelper(e,m,h),y=new CellContentParser(e,m,h),g=new ArraySizePredictor(e,i),b=new Operations(e,o,l,y,p,r,s,a,g),v=new UndoRedo(e,b);s.undoRedo=v;const N=new ClipboardOperations(e,o,b),T=new CrudOperations(e,b,v,N,o,l,p,y,s,a);n.forEach((e=>{T.ensureItIsPossibleToAddNamedExpression(e.name,e.expression,e.scope),T.operations.addNamedExpression(e.name,e.expression,e.scope,e.options)}));const C=new Exporter(e,a,u.fetchDisplayName,s),A=new Serialization(o,d,C),V=new Interpreter(e,o,l,r,f,i,a,A,g,m);r.measure(StatType.GRAPH_BUILD,(()=>{new GraphBuilder(o,l,p,y,r,g).buildGraph(t,r)}));const x=new Evaluator(e,r,V,s,o,l);return x.run(),r.end(StatType.BUILD_ENGINE_TOTAL),{config:e,stats:r,dependencyGraph:o,columnSearch:l,parser:p,unparser:d,cellContentParser:y,evaluator:x,lazilyTransformingAstService:s,crudOperations:T,exporter:C,namedExpressions:a,serialization:A,functionRegistry:i}}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */function objectDestroy(e){for(const[t,n]of Object.entries(e))n instanceof Function?e[t]=postMortem(n):delete e[t]}function postMortem(e){return()=>{throw new Error(`The "${e}" method cannot be called because this HyperFormula instance has been destroyed`)}}var tinyEmitter={exports:{}};function E$2(){}E$2.prototype={on:function(e,t,n){var r=this.e||(this.e={});return(r[e]||(r[e]=[])).push({fn:t,ctx:n}),this},once:function(e,t,n){var r=this;function a(){r.off(e,a),t.apply(n,arguments)}return a._=t,this.on(e,a,n)},emit:function(e){for(var t=[].slice.call(arguments,1),n=((this.e||(this.e={}))[e]||[]).slice(),r=0,a=n.length;rthis.getSheetDimensions(e)))}getSheetDimensions(e){return validateArgToType(e,"number","sheetId"),{width:this.dependencyGraph.getSheetWidth(e),height:this.dependencyGraph.getSheetHeight(e)}}getAllSheetsValues(){return this.ensureEvaluationIsNotSuspended(),this._serialization.getAllSheetsValues()}getAllSheetsFormulas(){return this._serialization.getAllSheetsFormulas()}getAllSheetsSerialized(){return this.ensureEvaluationIsNotSuspended(),this._serialization.getAllSheetsSerialized()}updateConfig(e){const t=this._config.mergeConfig(e),n=this._config.mergeConfig({language:e.language}),r=this._serialization.withNewConfig(n,this._namedExpressions).getAllSheetsSerialized(),a=this._serialization.getAllNamedExpressionsSerialized(),i=BuildEngineFactory.rebuildWithConfig(t,r,a,this._stats);this._config=i.config,this._stats=i.stats,this._dependencyGraph=i.dependencyGraph,this._columnSearch=i.columnSearch,this._parser=i.parser,this._unparser=i.unparser,this._cellContentParser=i.cellContentParser,this._evaluator=i.evaluator,this._lazilyTransformingAstService=i.lazilyTransformingAstService,this._crudOperations=i.crudOperations,this._exporter=i.exporter,this._namedExpressions=i.namedExpressions,this._serialization=i.serialization,this._functionRegistry=i.functionRegistry}getConfig(){return this._config.getConfig()}rebuildAndRecalculate(){this.updateConfig({})}getStats(){return this._stats.snapshot()}undo(){return this._crudOperations.undo(),this.recomputeIfDependencyGraphNeedsIt()}redo(){return this._crudOperations.redo(),this.recomputeIfDependencyGraphNeedsIt()}isThereSomethingToUndo(){return this._crudOperations.isThereSomethingToUndo()}isThereSomethingToRedo(){return this._crudOperations.isThereSomethingToRedo()}isItPossibleToSetCellContents(e){let t;if(isSimpleCellAddress(e))t=new AbsoluteCellRange(e,e);else{if(!isSimpleCellRange(e))throw new ExpectedValueOfTypeError("SimpleCellAddress | SimpleCellRange","address");t=new AbsoluteCellRange(e.start,e.end)}try{this._crudOperations.ensureRangeInSizeLimits(t);for(const e of t.addresses(this._dependencyGraph))this._crudOperations.ensureItIsPossibleToChangeContent(e)}catch(e){return!1}return!0}setCellContents(e,t){return this._crudOperations.setCellContents(e,t),this.recomputeIfDependencyGraphNeedsIt()}swapRowIndexes(e,t){return validateArgToType(e,"number","sheetId"),this._crudOperations.setRowOrder(e,t),this.recomputeIfDependencyGraphNeedsIt()}isItPossibleToSwapRowIndexes(e,t){validateArgToType(e,"number","sheetId");try{return this._crudOperations.validateSwapRowIndexes(e,t),this._crudOperations.testRowOrderForArrays(e,t),!0}catch(e){return!1}}setRowOrder(e,t){validateArgToType(e,"number","sheetId");const n=this._crudOperations.mappingFromOrder(e,t,"row");return this.swapRowIndexes(e,n)}isItPossibleToSetRowOrder(e,t){validateArgToType(e,"number","sheetId");try{const n=this._crudOperations.mappingFromOrder(e,t,"row");return this._crudOperations.validateSwapRowIndexes(e,n),this._crudOperations.testRowOrderForArrays(e,n),!0}catch(e){return!1}}swapColumnIndexes(e,t){return validateArgToType(e,"number","sheetId"),this._crudOperations.setColumnOrder(e,t),this.recomputeIfDependencyGraphNeedsIt()}isItPossibleToSwapColumnIndexes(e,t){validateArgToType(e,"number","sheetId");try{return this._crudOperations.validateSwapColumnIndexes(e,t),this._crudOperations.testColumnOrderForArrays(e,t),!0}catch(e){return!1}}setColumnOrder(e,t){validateArgToType(e,"number","sheetId");const n=this._crudOperations.mappingFromOrder(e,t,"column");return this.swapColumnIndexes(e,n)}isItPossibleToSetColumnOrder(e,t){validateArgToType(e,"number","sheetId");try{const n=this._crudOperations.mappingFromOrder(e,t,"column");return this._crudOperations.validateSwapColumnIndexes(e,n),this._crudOperations.testColumnOrderForArrays(e,n),!0}catch(e){return!1}}isItPossibleToAddRows(e,...t){validateArgToType(e,"number","sheetId");const n=normalizeAddedIndexes(t);try{return this._crudOperations.ensureItIsPossibleToAddRows(e,...n),!0}catch(e){return!1}}addRows(e,...t){return validateArgToType(e,"number","sheetId"),this._crudOperations.addRows(e,...t),this.recomputeIfDependencyGraphNeedsIt()}isItPossibleToRemoveRows(e,...t){validateArgToType(e,"number","sheetId");const n=normalizeRemovedIndexes(t);try{return this._crudOperations.ensureItIsPossibleToRemoveRows(e,...n),!0}catch(e){return!1}}removeRows(e,...t){return validateArgToType(e,"number","sheetId"),this._crudOperations.removeRows(e,...t),this.recomputeIfDependencyGraphNeedsIt()}isItPossibleToAddColumns(e,...t){validateArgToType(e,"number","sheetId");const n=normalizeAddedIndexes(t);try{return this._crudOperations.ensureItIsPossibleToAddColumns(e,...n),!0}catch(e){return!1}}addColumns(e,...t){return validateArgToType(e,"number","sheetId"),this._crudOperations.addColumns(e,...t),this.recomputeIfDependencyGraphNeedsIt()}isItPossibleToRemoveColumns(e,...t){validateArgToType(e,"number","sheetId");const n=normalizeRemovedIndexes(t);try{return this._crudOperations.ensureItIsPossibleToRemoveColumns(e,...n),!0}catch(e){return!1}}removeColumns(e,...t){return validateArgToType(e,"number","sheetId"),this._crudOperations.removeColumns(e,...t),this.recomputeIfDependencyGraphNeedsIt()}isItPossibleToMoveCells(e,t){if(!isSimpleCellAddress(t))throw new ExpectedValueOfTypeError("SimpleCellAddress","destinationLeftCorner");if(!isSimpleCellRange(e))throw new ExpectedValueOfTypeError("SimpleCellRange","source");try{const n=new AbsoluteCellRange(e.start,e.end);return this._crudOperations.operations.ensureItIsPossibleToMoveCells(n.start,n.width(),n.height(),t),!0}catch(e){return!1}}moveCells(e,t){if(!isSimpleCellAddress(t))throw new ExpectedValueOfTypeError("SimpleCellAddress","destinationLeftCorner");if(!isSimpleCellRange(e))throw new ExpectedValueOfTypeError("SimpleCellRange","source");const n=new AbsoluteCellRange(e.start,e.end);return this._crudOperations.moveCells(n.start,n.width(),n.height(),t),this.recomputeIfDependencyGraphNeedsIt()}isItPossibleToMoveRows(e,t,n,r){validateArgToType(e,"number","sheetId"),validateArgToType(t,"number","startRow"),validateArgToType(n,"number","numberOfRows"),validateArgToType(r,"number","targetRow");try{return this._crudOperations.ensureItIsPossibleToMoveRows(e,t,n,r),!0}catch(e){return!1}}moveRows(e,t,n,r){return validateArgToType(e,"number","sheetId"),validateArgToType(t,"number","startRow"),validateArgToType(n,"number","numberOfRows"),validateArgToType(r,"number","targetRow"),this._crudOperations.moveRows(e,t,n,r),this.recomputeIfDependencyGraphNeedsIt()}isItPossibleToMoveColumns(e,t,n,r){validateArgToType(e,"number","sheetId"),validateArgToType(t,"number","startColumn"),validateArgToType(n,"number","numberOfColumns"),validateArgToType(r,"number","targetColumn");try{return this._crudOperations.ensureItIsPossibleToMoveColumns(e,t,n,r),!0}catch(e){return!1}}moveColumns(e,t,n,r){return validateArgToType(e,"number","sheetId"),validateArgToType(t,"number","startColumn"),validateArgToType(n,"number","numberOfColumns"),validateArgToType(r,"number","targetColumn"),this._crudOperations.moveColumns(e,t,n,r),this.recomputeIfDependencyGraphNeedsIt()}copy(e){if(!isSimpleCellRange(e))throw new ExpectedValueOfTypeError("SimpleCellRange","source");const t=new AbsoluteCellRange(e.start,e.end);return this._crudOperations.copy(t.start,t.width(),t.height()),this.getRangeValues(e)}cut(e){if(!isSimpleCellRange(e))throw new ExpectedValueOfTypeError("SimpleCellRange","source");const t=new AbsoluteCellRange(e.start,e.end);return this._crudOperations.cut(t.start,t.width(),t.height()),this.getRangeValues(e)}paste(e){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","targetLeftCorner");return this.ensureEvaluationIsNotSuspended(),this._crudOperations.paste(e),this.recomputeIfDependencyGraphNeedsIt()}isClipboardEmpty(){return this._crudOperations.isClipboardEmpty()}clearClipboard(){this._crudOperations.clearClipboard()}clearRedoStack(){this._crudOperations.undoRedo.clearRedoStack()}clearUndoStack(){this._crudOperations.undoRedo.clearUndoStack()}getRangeValues(e){if(!isSimpleCellRange(e))throw new ExpectedValueOfTypeError("SimpleCellRange","source");return new AbsoluteCellRange(e.start,e.end).arrayOfAddressesInRange().map((e=>e.map((e=>this.getCellValue(e)))))}getRangeFormulas(e){if(!isSimpleCellRange(e))throw new ExpectedValueOfTypeError("SimpleCellRange","source");return new AbsoluteCellRange(e.start,e.end).arrayOfAddressesInRange().map((e=>e.map((e=>this.getCellFormula(e)))))}getRangeSerialized(e){if(!isSimpleCellRange(e))throw new ExpectedValueOfTypeError("SimpleCellRange","source");return new AbsoluteCellRange(e.start,e.end).arrayOfAddressesInRange().map((e=>e.map((e=>this.getCellSerialized(e)))))}getFillRangeData(e,t,n=!1){if(!isSimpleCellRange(e))throw new ExpectedValueOfTypeError("SimpleCellRange","source");if(!isSimpleCellRange(t))throw new ExpectedValueOfTypeError("SimpleCellRange","target");const r=new AbsoluteCellRange(e.start,e.end),a=new AbsoluteCellRange(t.start,t.end);return this.ensureEvaluationIsNotSuspended(),a.arrayOfAddressesInRange().map((a=>a.map((a=>{const i=((a.row-(n?t:e).start.row)%r.height()+r.height())%r.height()+e.start.row,s=((a.col-(n?t:e).start.col)%r.width()+r.width())%r.width()+e.start.col;return this._serialization.getCellSerialized({row:i,col:s,sheet:r.sheet},a)}))))}isItPossibleToAddSheet(e){validateArgToType(e,"string","sheetName");try{return this._crudOperations.ensureItIsPossibleToAddSheet(e),!0}catch(e){return!1}}addSheet(e){void 0!==e&&validateArgToType(e,"string","sheetName");const t=this._crudOperations.addSheet(e);return this._emitter.emit(Events.SheetAdded,t),t}isItPossibleToRemoveSheet(e){validateArgToType(e,"number","sheetId");try{return this._crudOperations.ensureScopeIdIsValid(e),!0}catch(e){return!1}}removeSheet(e){validateArgToType(e,"number","sheetId");const t=this.sheetMapping.getDisplayName(e);this._crudOperations.removeSheet(e);const n=this.recomputeIfDependencyGraphNeedsIt();return this._emitter.emit(Events.SheetRemoved,t,n),n}isItPossibleToClearSheet(e){validateArgToType(e,"number","sheetId");try{return this._crudOperations.ensureScopeIdIsValid(e),!0}catch(e){return!1}}clearSheet(e){return validateArgToType(e,"number","sheetId"),this._crudOperations.clearSheet(e),this.recomputeIfDependencyGraphNeedsIt()}isItPossibleToReplaceSheetContent(e,t){validateArgToType(e,"number","sheetId");try{return this._crudOperations.ensureScopeIdIsValid(e),this._crudOperations.ensureItIsPossibleToChangeSheetContents(e,t),!0}catch(e){return!1}}setSheetContent(e,t){return validateArgToType(e,"number","sheetId"),this._crudOperations.setSheetContent(e,t),this.recomputeIfDependencyGraphNeedsIt()}simpleCellAddressFromString(e,t){return validateArgToType(e,"string","cellAddress"),validateArgToType(t,"number","sheetId"),simpleCellAddressFromString(this.sheetMapping.get,e,t)}simpleCellRangeFromString(e,t){return validateArgToType(e,"string","cellRange"),validateArgToType(t,"number","sheetId"),simpleCellRangeFromString(this.sheetMapping.get,e,t)}simpleCellAddressToString(e,t){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");return validateArgToType(t,"number","sheetId"),simpleCellAddressToString(this.sheetMapping.fetchDisplayName,e,t)}simpleCellRangeToString(e,t){if(!isSimpleCellRange(e))throw new ExpectedValueOfTypeError("SimpleCellRange","cellRange");return validateArgToType(t,"number","sheetId"),simpleCellRangeToString(this.sheetMapping.fetchDisplayName,e,t)}getCellDependents(e){let t;if(isSimpleCellAddress(e))t=this._dependencyGraph.addressMapping.getCell(e);else{if(!isSimpleCellRange(e))throw new ExpectedValueOfTypeError("SimpleCellAddress | SimpleCellRange",e);t=this._dependencyGraph.rangeMapping.getRange(e.start,e.end)}return void 0===t?[]:this._dependencyGraph.getAdjacentNodesAddresses(t)}getCellPrecedents(e){let t;if(isSimpleCellAddress(e))t=this._dependencyGraph.addressMapping.getCell(e);else{if(!isSimpleCellRange(e))throw new ExpectedValueOfTypeError("SimpleCellAddress | SimpleCellRange",e);t=this._dependencyGraph.rangeMapping.getRange(e.start,e.end)}return void 0===t?[]:this._dependencyGraph.dependencyQueryAddresses(t)}getSheetName(e){return validateArgToType(e,"number","sheetId"),this.sheetMapping.getDisplayName(e)}getSheetNames(){return this.sheetMapping.sheetNames()}getSheetId(e){return validateArgToType(e,"string","sheetName"),this.sheetMapping.get(e)}doesSheetExist(e){return validateArgToType(e,"string","sheetName"),this.sheetMapping.hasSheetWithName(e)}getCellType(e){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");const t=this.dependencyGraph.getCell(e);return getCellType(t,e)}doesCellHaveSimpleValue(e){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");return this.getCellType(e)===CellType.VALUE}doesCellHaveFormula(e){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");const t=this.getCellType(e);return t===CellType.FORMULA||t===CellType.ARRAYFORMULA}isCellEmpty(e){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");return this.getCellType(e)===CellType.EMPTY}isCellPartOfArray(e){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");const t=this.getCellType(e);return t===CellType.ARRAY||t===CellType.ARRAYFORMULA}getCellValueType(e){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");this.ensureEvaluationIsNotSuspended();const t=this.dependencyGraph.getCellValue(e);return getCellValueType(t)}getCellValueDetailedType(e){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");this.ensureEvaluationIsNotSuspended();const t=this.dependencyGraph.getCellValue(e);return getCellValueDetailedType(t)}getCellValueFormat(e){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");this.ensureEvaluationIsNotSuspended();const t=this.dependencyGraph.getCellValue(e);return getCellValueFormat(t)}countSheets(){return this.sheetMapping.numberOfSheets()}isItPossibleToRenameSheet(e,t){validateArgToType(e,"number","sheetId"),validateArgToType(t,"string","newName");try{return this._crudOperations.ensureItIsPossibleToRenameSheet(e,t),!0}catch(e){return!1}}renameSheet(e,t){validateArgToType(e,"number","sheetId"),validateArgToType(t,"string","newName");const n=this._crudOperations.renameSheet(e,t);void 0!==n&&this._emitter.emit(Events.SheetRenamed,n,t)}batch(e){this.suspendEvaluation(),this._crudOperations.beginUndoRedoBatchMode();try{e()}catch(e){throw this._crudOperations.commitUndoRedoBatchMode(),this.resumeEvaluation(),e}return this._crudOperations.commitUndoRedoBatchMode(),this.resumeEvaluation()}suspendEvaluation(){this._evaluationSuspended=!0,this._emitter.emit(Events.EvaluationSuspended)}resumeEvaluation(){this._evaluationSuspended=!1;const e=this.recomputeIfDependencyGraphNeedsIt();return this._emitter.emit(Events.EvaluationResumed,e),e}isEvaluationSuspended(){return this._evaluationSuspended}isItPossibleToAddNamedExpression(e,t,n){validateArgToType(e,"string","expressionName"),void 0!==n&&validateArgToType(n,"number","scope");try{return this._crudOperations.ensureItIsPossibleToAddNamedExpression(e,t,n),!0}catch(e){return!1}}addNamedExpression(e,t,n,r){validateArgToType(e,"string","expressionName"),void 0!==n&&validateArgToType(n,"number","scope"),this._crudOperations.addNamedExpression(e,t,n,r);const a=this.recomputeIfDependencyGraphNeedsIt();return this._emitter.emit(Events.NamedExpressionAdded,e,a),a}getNamedExpressionValue(e,t){validateArgToType(e,"string","expressionName"),void 0!==t&&validateArgToType(t,"number","scope"),this.ensureEvaluationIsNotSuspended(),this._crudOperations.ensureScopeIdIsValid(t);const n=this._namedExpressions.namedExpressionForScope(e,t);return n?this._serialization.getCellValue(n.address):void 0}getNamedExpressionFormula(e,t){validateArgToType(e,"string","expressionName"),void 0!==t&&validateArgToType(t,"number","scope"),this._crudOperations.ensureScopeIdIsValid(t);const n=this._namedExpressions.namedExpressionForScope(e,t);return void 0===n?void 0:this._serialization.getCellFormula(n.address)}getNamedExpression(e,t){validateArgToType(e,"string","expressionName"),void 0!==t&&validateArgToType(t,"number","scope");const n=this._namedExpressions.namedExpressionForScope(e,t);if(void 0===n)return;return{name:e,scope:t,expression:this._serialization.getCellFormula(n.address),options:n.options}}isItPossibleToChangeNamedExpression(e,t,n){validateArgToType(e,"string","expressionName"),void 0!==n&&validateArgToType(n,"number","scope");try{return this._crudOperations.ensureItIsPossibleToChangeNamedExpression(e,t,n),!0}catch(e){return!1}}changeNamedExpression(e,t,n,r){return validateArgToType(e,"string","expressionName"),void 0!==n&&validateArgToType(n,"number","scope"),this._crudOperations.changeNamedExpressionExpression(e,n,t,r),this.recomputeIfDependencyGraphNeedsIt()}isItPossibleToRemoveNamedExpression(e,t){validateArgToType(e,"string","expressionName"),void 0!==t&&validateArgToType(t,"number","scope");try{return this._crudOperations.isItPossibleToRemoveNamedExpression(e,t),!0}catch(e){return!1}}removeNamedExpression(e,t){validateArgToType(e,"string","expressionName"),void 0!==t&&validateArgToType(t,"number","scope");const n=this._crudOperations.removeNamedExpression(e,t);if(n){const e=this.recomputeIfDependencyGraphNeedsIt();return this._emitter.emit(Events.NamedExpressionRemoved,n.displayName,e),e}return[]}listNamedExpressions(e){return void 0!==e&&validateArgToType(e,"number","scope"),this._crudOperations.ensureScopeIdIsValid(e),this._namedExpressions.getAllNamedExpressionsNamesInScope(e)}getAllNamedExpressionsSerialized(){return this._serialization.getAllNamedExpressionsSerialized()}normalizeFormula(e){validateArgToType(e,"string","formulaString");const{ast:t,address:n}=this.extractTemporaryFormula(e);if(void 0===t)throw new NotAFormulaError;return this._unparser.unparse(t,n)}calculateFormula(e,t){validateArgToType(e,"string","formulaString"),validateArgToType(t,"number","sheetId"),this._crudOperations.ensureScopeIdIsValid(t);const{ast:n,address:r,dependencies:a}=this.extractTemporaryFormula(e,t);if(void 0===n)throw new NotAFormulaError;const i=this.evaluator.runAndForget(n,r,a);return this._exporter.exportScalarOrRange(i)}validateFormula(e){validateArgToType(e,"string","formulaString");const{ast:t}=this.extractTemporaryFormula(e);return void 0!==t&&!(t.type===AstNodeType.ERROR&&!t.error)}getRegisteredFunctionNames(){return HyperFormula.getLanguage(this._config.language).getFunctionTranslations(this._functionRegistry.getRegisteredFunctionIds())}getFunctionPlugin(e){return validateArgToType(e,"string","functionId"),this._functionRegistry.getFunctionPlugin(e)}getAllFunctionPlugins(){return this._functionRegistry.getPlugins()}numberToDateTime(e){return validateArgToType(e,"number","val"),this._evaluator.interpreter.dateTimeHelper.numberToSimpleDateTime(e)}numberToDate(e){return validateArgToType(e,"number","val"),this._evaluator.interpreter.dateTimeHelper.numberToSimpleDate(e)}numberToTime(e){return validateArgToType(e,"number","val"),numberToSimpleTime(e)}on(e,t){this._emitter.on(e,t)}once(e,t){this._emitter.once(e,t)}off(e,t){this._emitter.off(e,t)}destroy(){objectDestroy(this)}ensureEvaluationIsNotSuspended(){if(this._evaluationSuspended)throw new EvaluationSuspendedError}extractTemporaryFormula(e,t=1){const n=this._cellContentParser.parse(e),r={sheet:t,col:0,row:0};if(!(n instanceof CellContent.Formula))return{address:r,dependencies:[]};const{ast:a,errors:i,dependencies:s}=this._parser.parse(n.formula,r);return i.length>0?{address:r,dependencies:[]}:{ast:a,address:r,dependencies:s}}recomputeIfDependencyGraphNeedsIt(){if(this._evaluationSuspended)return[];{const e=this._crudOperations.getAndClearContentChanges(),t=Array.from(this.dependencyGraph.verticesToRecompute());this.dependencyGraph.clearRecentlyChangedVertices(),t.length>0&&e.addAll(this.evaluator.partialRun(t));const n=e.exportChanges(this._exporter);return e.isEmpty()||this._emitter.emit(Events.ValuesUpdated,n),n}}}HyperFormula.version="2.1.0",HyperFormula.buildDate="08/09/2022 13:04:38",HyperFormula.releaseDate="08/09/2022",HyperFormula.languages={},HyperFormula.registeredLanguages=new Map; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +const privatePool=new WeakMap;class Config{constructor(e={},t=!0){const{accentSensitive:n,binarySearchThreshold:r,caseSensitive:a,caseFirst:i,chooseAddressMappingPolicy:s,currencySymbol:o,dateFormats:l,decimalSeparator:u,evaluateNullToZero:c,functionArgSeparator:p,functionPlugins:d,ignorePunctuation:m,leapYear1900:h,localeLang:f,language:y,ignoreWhiteSpace:g,licenseKey:b,matchWholeCell:v,arrayColumnSeparator:N,arrayRowSeparator:T,maxRows:C,maxColumns:A,nullYear:V,nullDate:x,parseDateTime:S,precisionEpsilon:w,precisionRounding:E,stringifyDateTime:D,stringifyDuration:O,smartRounding:I,timeFormats:R,thousandSeparator:_,useArrayArithmetic:M,useStats:P,undoLimit:F,useColumnIndex:k,useRegularExpressions:$,useWildcards:B}=e;t&&Config.warnDeprecatedOptions(e),this.useArrayArithmetic=configValueFromParam(M,"boolean","useArrayArithmetic"),this.accentSensitive=configValueFromParam(n,"boolean","accentSensitive"),this.caseSensitive=configValueFromParam(a,"boolean","caseSensitive"),this.caseFirst=configValueFromParam(i,["upper","lower","false"],"caseFirst"),this.ignorePunctuation=configValueFromParam(m,"boolean","ignorePunctuation"),this.chooseAddressMappingPolicy=null!=s?s:Config.defaultConfig.chooseAddressMappingPolicy,this.dateFormats=[...configValueFromParamCheck(l,Array.isArray,"array","dateFormats")],this.timeFormats=[...configValueFromParamCheck(R,Array.isArray,"array","timeFormats")],this.functionArgSeparator=configValueFromParam(p,"string","functionArgSeparator"),this.decimalSeparator=configValueFromParam(u,[".",","],"decimalSeparator"),this.language=configValueFromParam(y,"string","language"),this.ignoreWhiteSpace=configValueFromParam(g,["standard","any"],"ignoreWhiteSpace"),this.licenseKey=configValueFromParam(b,"string","licenseKey"),this.thousandSeparator=configValueFromParam(_,["",","," ","."],"thousandSeparator"),this.arrayColumnSeparator=configValueFromParam(N,[",",";"],"arrayColumnSeparator"),this.arrayRowSeparator=configValueFromParam(T,[";","|"],"arrayRowSeparator"),this.localeLang=configValueFromParam(f,"string","localeLang"),this.functionPlugins=[...null!=d?d:Config.defaultConfig.functionPlugins],this.smartRounding=configValueFromParam(I,"boolean","smartRounding"),this.evaluateNullToZero=configValueFromParam(c,"boolean","evaluateNullToZero"),this.nullYear=configValueFromParam(V,"number","nullYear"),validateNumberToBeAtLeast(this.nullYear,"nullYear",0),validateNumberToBeAtMost(this.nullYear,"nullYear",100),this.precisionRounding=configValueFromParam(E,"number","precisionRounding"),validateNumberToBeAtLeast(this.precisionRounding,"precisionRounding",0),this.precisionEpsilon=configValueFromParam(w,"number","precisionEpsilon"),validateNumberToBeAtLeast(this.precisionEpsilon,"precisionEpsilon",0),this.useColumnIndex=configValueFromParam(k,"boolean","useColumnIndex"),this.useStats=configValueFromParam(P,"boolean","useStats"),this.binarySearchThreshold=null!=r?r:Config.defaultConfig.binarySearchThreshold,this.parseDateTime=configValueFromParam(S,"function","parseDateTime"),this.stringifyDateTime=configValueFromParam(D,"function","stringifyDateTime"),this.stringifyDuration=configValueFromParam(O,"function","stringifyDuration"),this.translationPackage=HyperFormula.getLanguage(this.language),this.errorMapping=this.translationPackage.buildErrorMapping(),this.nullDate=configValueFromParamCheck(x,instanceOfSimpleDate,"IDate","nullDate"),this.leapYear1900=configValueFromParam(h,"boolean","leapYear1900"),this.undoLimit=configValueFromParam(F,"number","undoLimit"),this.useRegularExpressions=configValueFromParam($,"boolean","useRegularExpressions"),this.useWildcards=configValueFromParam(B,"boolean","useWildcards"),this.matchWholeCell=configValueFromParam(v,"boolean","matchWholeCell"),validateNumberToBeAtLeast(this.undoLimit,"undoLimit",0),this.maxRows=configValueFromParam(C,"number","maxRows"),validateNumberToBeAtLeast(this.maxRows,"maxRows",1),this.maxColumns=configValueFromParam(A,"number","maxColumns"),this.currencySymbol=this.setupCurrencySymbol(o),validateNumberToBeAtLeast(this.maxColumns,"maxColumns",1),privatePool.set(this,{licenseKeyValidityState:checkLicenseKeyValidity(this.licenseKey)}),configCheckIfParametersNotInConflict({value:this.decimalSeparator,name:"decimalSeparator"},{value:this.functionArgSeparator,name:"functionArgSeparator"},{value:this.thousandSeparator,name:"thousandSeparator"}),configCheckIfParametersNotInConflict({value:this.arrayRowSeparator,name:"arrayRowSeparator"},{value:this.arrayColumnSeparator,name:"arrayColumnSeparator"})}setupCurrencySymbol(e){const t=[...configValueFromParamCheck(e,Array.isArray,"array","currencySymbol")];return t.forEach((e=>{if("string"!=typeof e)throw new ExpectedValueOfTypeError("string[]","currencySymbol");if(""===e)throw new ConfigValueEmpty("currencySymbol")})),t}get licenseKeyValidityState(){return privatePool.get(this).licenseKeyValidityState}getConfig(){return getFullConfigFromPartial(this)}mergeConfig(e){const t=Object.assign({},this.getConfig(),e);return Config.warnDeprecatedOptions(e),new Config(t,!1)}static warnDeprecatedOptions(e){Config.warnDeprecatedIfUsed(e.binarySearchThreshold,"binarySearchThreshold","1.1")}static warnDeprecatedIfUsed(e,t,n,r){void 0!==e&&(void 0===r?console.warn(`${t} option is deprecated since ${n}`):console.warn(`${t} option is deprecated since ${n}, please use ${r}`))}}function getFullConfigFromPartial(e){var t;const n={};for(const r in Config.defaultConfig){const a=null!==(t=e[r])&&void 0!==t?t:Config.defaultConfig[r];Array.isArray(a)?n[r]=[...a]:n[r]=a}return n}function getDefaultConfig(){return getFullConfigFromPartial({})} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */Config.defaultConfig={accentSensitive:!1,binarySearchThreshold:20,currencySymbol:["$"],caseSensitive:!1,caseFirst:"lower",chooseAddressMappingPolicy:new AlwaysDense,dateFormats:["DD/MM/YYYY","DD/MM/YY"],decimalSeparator:".",evaluateNullToZero:!1,functionArgSeparator:",",functionPlugins:[],ignorePunctuation:!1,language:"enGB",ignoreWhiteSpace:"standard",licenseKey:"",leapYear1900:!1,localeLang:"en",matchWholeCell:!0,arrayColumnSeparator:",",arrayRowSeparator:";",maxRows:4e4,maxColumns:18278,nullYear:30,nullDate:{year:1899,month:12,day:30},parseDateTime:defaultParseToDateTime,precisionEpsilon:1e-13,precisionRounding:14,smartRounding:!0,stringifyDateTime:defaultStringifyDateTime,stringifyDuration:defaultStringifyDuration,timeFormats:["hh:mm","hh:mm:ss.sss"],thousandSeparator:"",undoLimit:20,useRegularExpressions:!1,useWildcards:!0,useColumnIndex:!1,useStats:!1,useArrayArithmetic:!1};const dictionary={errors:{CYCLE:"#CYCLE!",DIV_BY_ZERO:"#DIV/0!",ERROR:"#ERROR!",NA:"#N/A",NAME:"#NAME?",NUM:"#NUM!",REF:"#REF!",SPILL:"#SPILL!",VALUE:"#VALUE!"},functions:{FILTER:"FILTER",ARRAY_CONSTRAIN:"ARRAY_CONSTRAIN",ARRAYFORMULA:"ARRAYFORMULA",ABS:"ABS",ACOS:"ACOS",ACOSH:"ACOSH",ACOT:"ACOT",ACOTH:"ACOTH",AND:"AND",ARABIC:"ARABIC",ASIN:"ASIN",ASINH:"ASINH",ATAN2:"ATAN2",ATAN:"ATAN",ATANH:"ATANH",AVERAGE:"AVERAGE",AVERAGEA:"AVERAGEA",AVERAGEIF:"AVERAGEIF",BASE:"BASE",BIN2DEC:"BIN2DEC",BIN2HEX:"BIN2HEX",BIN2OCT:"BIN2OCT",BITAND:"BITAND",BITLSHIFT:"BITLSHIFT",BITOR:"BITOR",BITRSHIFT:"BITRSHIFT",BITXOR:"BITXOR",CEILING:"CEILING",CHAR:"CHAR",CHOOSE:"CHOOSE",CLEAN:"CLEAN",CODE:"CODE",COLUMN:"COLUMN",COLUMNS:"COLUMNS",CONCATENATE:"CONCATENATE",CORREL:"CORREL",COS:"COS",COSH:"COSH",COT:"COT",COTH:"COTH",COUNT:"COUNT",COUNTA:"COUNTA",COUNTBLANK:"COUNTBLANK",COUNTIF:"COUNTIF",COUNTIFS:"COUNTIFS",COUNTUNIQUE:"COUNTUNIQUE",CSC:"CSC",CSCH:"CSCH",CUMIPMT:"CUMIPMT",CUMPRINC:"CUMPRINC",DATE:"DATE",DATEDIF:"DATEDIF",DATEVALUE:"DATEVALUE",DAY:"DAY",DAYS360:"DAYS360",DAYS:"DAYS",DB:"DB",DDB:"DDB",DEC2BIN:"DEC2BIN",DEC2HEX:"DEC2HEX",DEC2OCT:"DEC2OCT",DECIMAL:"DECIMAL",DEGREES:"DEGREES",DELTA:"DELTA",DOLLARDE:"DOLLARDE",DOLLARFR:"DOLLARFR",EDATE:"EDATE",EFFECT:"EFFECT",EOMONTH:"EOMONTH",ERF:"ERF",ERFC:"ERFC",EVEN:"EVEN",EXACT:"EXACT",EXP:"EXP",FALSE:"FALSE",FIND:"FIND",FORMULATEXT:"FORMULATEXT",FV:"FV",FVSCHEDULE:"FVSCHEDULE",HEX2BIN:"HEX2BIN",HEX2DEC:"HEX2DEC",HEX2OCT:"HEX2OCT",HLOOKUP:"HLOOKUP",HOUR:"HOUR",IF:"IF",IFERROR:"IFERROR",IFNA:"IFNA",INDEX:"INDEX",INT:"INT",INTERVAL:"INTERVAL",IPMT:"IPMT",ISBINARY:"ISBINARY",ISBLANK:"ISBLANK",ISERR:"ISERR",ISERROR:"ISERROR",ISEVEN:"ISEVEN",ISFORMULA:"ISFORMULA",ISLOGICAL:"ISLOGICAL",ISNA:"ISNA",ISNONTEXT:"ISNONTEXT",ISNUMBER:"ISNUMBER",ISODD:"ISODD",ISOWEEKNUM:"ISOWEEKNUM",ISPMT:"ISPMT",ISREF:"ISREF",ISTEXT:"ISTEXT",LEFT:"LEFT",LEN:"LEN",LN:"LN",LOG10:"LOG10",LOG:"LOG",LOWER:"LOWER",MATCH:"MATCH",MAX:"MAX",MAXA:"MAXA",MAXIFS:"MAXIFS",MAXPOOL:"MAXPOOL",MEDIAN:"MEDIAN",MEDIANPOOL:"MEDIANPOOL",MID:"MID",MIN:"MIN",MINA:"MINA",MINIFS:"MINIFS",MINUTE:"MINUTE",MIRR:"MIRR",MMULT:"MMULT",MOD:"MOD",MONTH:"MONTH",NA:"NA",NETWORKDAYS:"NETWORKDAYS","NETWORKDAYS.INTL":"NETWORKDAYS.INTL",NOMINAL:"NOMINAL",NOT:"NOT",NOW:"NOW",NPER:"NPER",NPV:"NPV",OCT2BIN:"OCT2BIN",OCT2DEC:"OCT2DEC",OCT2HEX:"OCT2HEX",ODD:"ODD",OFFSET:"OFFSET",OR:"OR",PI:"PI",PMT:"PMT",PDURATION:"PDURATION",PRODUCT:"PRODUCT",POWER:"POWER",PPMT:"PPMT",PROPER:"PROPER",PV:"PV",RADIANS:"RADIANS",RAND:"RAND",RATE:"RATE",REPLACE:"REPLACE",REPT:"REPT",RIGHT:"RIGHT",ROMAN:"ROMAN",ROUND:"ROUND",ROUNDDOWN:"ROUNDDOWN",ROUNDUP:"ROUNDUP",ROW:"ROW",ROWS:"ROWS",RRI:"RRI",SEARCH:"SEARCH",SEC:"SEC",SECH:"SECH",SECOND:"SECOND",SHEET:"SHEET",SHEETS:"SHEETS",SIN:"SIN",SINH:"SINH",SLN:"SLN",SPLIT:"SPLIT",SQRT:"SQRT",STDEVA:"STDEVA","STDEV.P":"STDEV.P",STDEVPA:"STDEVPA","STDEV.S":"STDEV.S",SUBSTITUTE:"SUBSTITUTE",SUBTOTAL:"SUBTOTAL",SUM:"SUM",SUMIF:"SUMIF",SUMIFS:"SUMIFS",SUMPRODUCT:"SUMPRODUCT",SUMSQ:"SUMSQ",SWITCH:"SWITCH",SYD:"SYD",T:"T",TAN:"TAN",TANH:"TANH",TBILLEQ:"TBILLEQ",TBILLPRICE:"TBILLPRICE",TBILLYIELD:"TBILLYIELD",TEXT:"TEXT",TIME:"TIME",TIMEVALUE:"TIMEVALUE",TODAY:"TODAY",TRANSPOSE:"TRANSPOSE",TRIM:"TRIM",TRUE:"TRUE",TRUNC:"TRUNC",UNICHAR:"UNICHAR",UNICODE:"UNICODE",UPPER:"UPPER",VARA:"VARA","VAR.P":"VAR.P",VARPA:"VARPA","VAR.S":"VAR.S",VLOOKUP:"VLOOKUP",WEEKDAY:"WEEKDAY",WEEKNUM:"WEEKNUM",WORKDAY:"WORKDAY","WORKDAY.INTL":"WORKDAY.INTL",XNPV:"XNPV",XOR:"XOR",YEAR:"YEAR",YEARFRAC:"YEARFRAC","HF.ADD":"HF.ADD","HF.CONCAT":"HF.CONCAT","HF.DIVIDE":"HF.DIVIDE","HF.EQ":"HF.EQ","HF.GT":"HF.GT","HF.GTE":"HF.GTE","HF.LT":"HF.LT","HF.LTE":"HF.LTE","HF.MINUS":"HF.MINUS","HF.MULTIPLY":"HF.MULTIPLY","HF.NE":"HF.NE","HF.POW":"HF.POW","HF.UMINUS":"HF.UMINUS","HF.UNARY_PERCENT":"HF.UNARY_PERCENT","HF.UPLUS":"HF.UPLUS",VARP:"VARP",VAR:"VAR",STDEVP:"STDEVP",STDEV:"STDEV","EXPON.DIST":"EXPON.DIST",FISHER:"FISHER",FISHERINV:"FISHERINV",GAMMA:"GAMMA","GAMMA.DIST":"GAMMA.DIST",GAMMALN:"GAMMALN","GAMMALN.PRECISE":"GAMMALN.PRECISE","GAMMA.INV":"GAMMA.INV",GAUSS:"GAUSS",FACT:"FACT",FACTDOUBLE:"FACTDOUBLE",COMBIN:"COMBIN",COMBINA:"COMBINA",GCD:"GCD",LCM:"LCM",MROUND:"MROUND",MULTINOMIAL:"MULTINOMIAL",QUOTIENT:"QUOTIENT",RANDBETWEEN:"RANDBETWEEN",SERIESSUM:"SERIESSUM",SIGN:"SIGN",SQRTPI:"SQRTPI",SUMX2MY2:"SUMX2MY2",SUMX2PY2:"SUMX2PY2",SUMXMY2:"SUMXMY2",EXPONDIST:"EXPONDIST",GAMMADIST:"GAMMADIST",GAMMAINV:"GAMMAINV","BETA.DIST":"BETA.DIST",BETADIST:"BETADIST","BETA.INV":"BETA.INV",BETAINV:"BETAINV","BINOM.DIST":"BINOM.DIST",BINOMDIST:"BINOMDIST","BINOM.INV":"BINOM.INV",BESSELI:"BESSELI",BESSELJ:"BESSELJ",BESSELK:"BESSELK",BESSELY:"BESSELY","CHISQ.DIST":"CHISQ.DIST","CHISQ.DIST.RT":"CHISQ.DIST.RT","CHISQ.INV":"CHISQ.INV","CHISQ.INV.RT":"CHISQ.INV.RT",CHIDIST:"CHIDIST",CHIINV:"CHIINV","F.DIST":"F.DIST","F.DIST.RT":"F.DIST.RT","F.INV":"F.INV","F.INV.RT":"F.INV.RT",FDIST:"FDIST",FINV:"FINV",WEIBULL:"WEIBULL","WEIBULL.DIST":"WEIBULL.DIST",POISSON:"POISSON","POISSON.DIST":"POISSON.DIST","HYPGEOM.DIST":"HYPGEOM.DIST",HYPGEOMDIST:"HYPGEOMDIST","T.DIST":"T.DIST","T.DIST.2T":"T.DIST.2T","T.DIST.RT":"T.DIST.RT","T.INV":"T.INV","T.INV.2T":"T.INV.2T",TDIST:"TDIST",TINV:"TINV",LOGINV:"LOGINV","LOGNORM.DIST":"LOGNORM.DIST","LOGNORM.INV":"LOGNORM.INV",LOGNORMDIST:"LOGNORMDIST","NORM.DIST":"NORM.DIST","NORM.INV":"NORM.INV","NORM.S.DIST":"NORM.S.DIST","NORM.S.INV":"NORM.S.INV",NORMDIST:"NORMDIST",NORMINV:"NORMINV",NORMSDIST:"NORMSDIST",NORMSINV:"NORMSINV",PHI:"PHI","NEGBINOM.DIST":"NEGBINOM.DIST",NEGBINOMDIST:"NEGBINOMDIST",COMPLEX:"COMPLEX",IMABS:"IMABS",IMAGINARY:"IMAGINARY",IMARGUMENT:"IMARGUMENT",IMCONJUGATE:"IMCONJUGATE",IMCOS:"IMCOS",IMCOSH:"IMCOSH",IMCOT:"IMCOT",IMCSC:"IMCSC",IMCSCH:"IMCSCH",IMDIV:"IMDIV",IMEXP:"IMEXP",IMLN:"IMLN",IMLOG10:"IMLOG10",IMLOG2:"IMLOG2",IMPOWER:"IMPOWER",IMPRODUCT:"IMPRODUCT",IMREAL:"IMREAL",IMSEC:"IMSEC",IMSECH:"IMSECH",IMSIN:"IMSIN",IMSINH:"IMSINH",IMSQRT:"IMSQRT",IMSUB:"IMSUB",IMSUM:"IMSUM",IMTAN:"IMTAN",LARGE:"LARGE",SMALL:"SMALL",AVEDEV:"AVEDEV",CONFIDENCE:"CONFIDENCE","CONFIDENCE.NORM":"CONFIDENCE.NORM","CONFIDENCE.T":"CONFIDENCE.T",DEVSQ:"DEVSQ",GEOMEAN:"GEOMEAN",HARMEAN:"HARMEAN",CRITBINOM:"CRITBINOM","COVARIANCE.P":"COVARIANCE.P","COVARIANCE.S":"COVARIANCE.S",COVAR:"COVAR",PEARSON:"PEARSON",RSQ:"RSQ",STANDARDIZE:"STANDARDIZE","Z.TEST":"Z.TEST",ZTEST:"ZTEST","F.TEST":"F.TEST",FTEST:"FTEST",STEYX:"STEYX",SLOPE:"SLOPE","CHISQ.TEST":"CHISQ.TEST",CHITEST:"CHITEST","T.TEST":"T.TEST",TTEST:"TTEST",SKEW:"SKEW","SKEW.P":"SKEW.P",WEIBULLDIST:"WEIBULLDIST",VARS:"VARS",TINV2T:"TINV2T",TDISTRT:"TDISTRT",TDIST2T:"TDIST2T",STDEVS:"STDEVS",FINVRT:"FINVRT",FDISTRT:"FDISTRT",CHIDISTRT:"CHIDISTRT",CHIINVRT:"CHIINVRT",COVARIANCEP:"COVARIANCEP",COVARIANCES:"COVARIANCES",LOGNORMINV:"LOGNORMINV",POISSONDIST:"POISSONDIST",SKEWP:"SKEWP","CEILING.MATH":"CEILING.MATH",FLOOR:"FLOOR","FLOOR.MATH":"FLOOR.MATH","CEILING.PRECISE":"CEILING.PRECISE","FLOOR.PRECISE":"FLOOR.PRECISE","ISO.CEILING":"ISO.CEILING"},langCode:"enGB",ui:{NEW_SHEET_PREFIX:"Sheet"}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class ArrayPlugin extends FunctionPlugin{arrayformula(e,t){return this.runFunction(e.args,t,this.metadata("ARRAYFORMULA"),(e=>e))}arrayformulaArraySize(e,t){if(1!==e.args.length)return ArraySize.error();const n=this.metadata("ARRAYFORMULA"),r=e.args.map((e=>{var r;return this.arraySizeForAst(e,new InterpreterState(t.formulaAddress,t.arraysFlag||null!==(r=null==n?void 0:n.arrayFunction)&&void 0!==r&&r))}));return r[0]}arrayconstrain(e,t){return this.runFunction(e.args,t,this.metadata("ARRAY_CONSTRAIN"),((e,t,n)=>{t=Math.min(t,e.height()),n=Math.min(n,e.width());const r=e.data,a=[];for(let e=0;e{var r;return this.arraySizeForAst(e,new InterpreterState(t.formulaAddress,t.arraysFlag||null!==(r=null==n?void 0:n.arrayFunction)&&void 0!==r&&r))}));let{height:a,width:i}=r[0];return e.args[1].type===AstNodeType.NUMBER&&(a=Math.min(a,e.args[1].value)),e.args[2].type===AstNodeType.NUMBER&&(i=Math.min(i,e.args[2].value)),a<1||i<1||!Number.isInteger(a)||!Number.isInteger(i)?ArraySize.error():new ArraySize(i,a)}filter(e,t){return this.runFunction(e.args,t,this.metadata("FILTER"),((e,...t)=>{for(const n of t)if(e.width()!==n.width()||e.height()!==n.height())return new CellError(ErrorType.NA,ErrorMessage.EqualLength);if(e.width()>1&&e.height()>1)return new CellError(ErrorType.NA,ErrorMessage.WrongDimension);const n=e.data,r=[];for(let a=0;a0&&r.push(i)}return r.length>0?SimpleRangeValue.onlyValues(r):new CellError(ErrorType.NA,ErrorMessage.EmptyRange)}))}filterArraySize(e,t){if(e.args.length<=1)return ArraySize.error();const n=this.metadata("FILTER"),r=e.args.map((e=>{var r;return this.arraySizeForAst(e,new InterpreterState(t.formulaAddress,t.arraysFlag||null!==(r=null==n?void 0:n.arrayFunction)&&void 0!==r&&r))})),a=Math.max(...r.map((e=>e.width))),i=Math.max(...r.map((e=>e.height)));return new ArraySize(a,i)}}ArrayPlugin.implementedFunctions={ARRAYFORMULA:{method:"arrayformula",arraySizeMethod:"arrayformulaArraySize",arrayFunction:!0,parameters:[{argumentType:ArgumentTypes.ANY}]},ARRAY_CONSTRAIN:{method:"arrayconstrain",arraySizeMethod:"arrayconstrainArraySize",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.INTEGER,minValue:1},{argumentType:ArgumentTypes.INTEGER,minValue:1}],vectorizationForbidden:!0},FILTER:{method:"filter",arraySizeMethod:"filterArraySize",arrayFunction:!0,parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}],repeatLastArgs:1}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class AbsPlugin extends FunctionPlugin{abs(e,t){return this.runFunction(e.args,t,this.metadata("ABS"),Math.abs)}}AbsPlugin.implementedFunctions={ABS:{method:"abs",parameters:[{argumentType:ArgumentTypes.NUMBER}]}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +const MAX_48BIT_INTEGER=0xffffffffffff,SHIFT_MIN_POSITIONS=-53,SHIFT_MAX_POSITIONS=53;class BitShiftPlugin extends FunctionPlugin{bitlshift(e,t){return this.runFunction(e.args,t,this.metadata("BITLSHIFT"),shiftLeft)}bitrshift(e,t){return this.runFunction(e.args,t,this.metadata("BITRSHIFT"),shiftRight)}}function shiftLeft(e,t){return t<0?shiftRight(e,-t):validate(e*Math.pow(2,t))}function shiftRight(e,t){return t<0?shiftLeft(e,-t):validate(Math.floor(e/Math.pow(2,t)))}function validate(e){return e>MAX_48BIT_INTEGER?new CellError(ErrorType.NUM,ErrorMessage.BitshiftLong):e} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */BitShiftPlugin.implementedFunctions={BITLSHIFT:{method:"bitlshift",parameters:[{argumentType:ArgumentTypes.INTEGER,minValue:0},{argumentType:ArgumentTypes.INTEGER,minValue:SHIFT_MIN_POSITIONS,maxValue:SHIFT_MAX_POSITIONS}]},BITRSHIFT:{method:"bitrshift",parameters:[{argumentType:ArgumentTypes.INTEGER,minValue:0},{argumentType:ArgumentTypes.INTEGER,minValue:SHIFT_MIN_POSITIONS,maxValue:SHIFT_MAX_POSITIONS}]}};class BitwiseLogicOperationsPlugin extends FunctionPlugin{bitand(e,t){return this.runFunction(e.args,t,this.metadata("BITAND"),((e,t)=>e&t))}bitor(e,t){return this.runFunction(e.args,t,this.metadata("BITOR"),((e,t)=>e|t))}bitxor(e,t){return this.runFunction(e.args,t,this.metadata("BITXOR"),((e,t)=>e^t))}}BitwiseLogicOperationsPlugin.implementedFunctions={BITAND:{method:"bitand",parameters:[{argumentType:ArgumentTypes.INTEGER,minValue:0},{argumentType:ArgumentTypes.INTEGER,minValue:0}]},BITOR:{method:"bitor",parameters:[{argumentType:ArgumentTypes.INTEGER,minValue:0},{argumentType:ArgumentTypes.INTEGER,minValue:0}]},BITXOR:{method:"bitxor",parameters:[{argumentType:ArgumentTypes.INTEGER,minValue:0},{argumentType:ArgumentTypes.INTEGER,minValue:0}]}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class BooleanPlugin extends FunctionPlugin{literalTrue(e,t){return this.runFunction(e.args,t,this.metadata("TRUE"),(()=>!0))}literalFalse(e,t){return this.runFunction(e.args,t,this.metadata("FALSE"),(()=>!1))}conditionalIf(e,t){return this.runFunction(e.args,t,this.metadata("IF"),((e,t,n)=>e?t:n))}and(e,t){return this.runFunction(e.args,t,this.metadata("AND"),((...e)=>!e.some((e=>!e))))}or(e,t){return this.runFunction(e.args,t,this.metadata("OR"),((...e)=>e.some((e=>e))))}not(e,t){return this.runFunction(e.args,t,this.metadata("NOT"),(e=>!e))}xor(e,t){return this.runFunction(e.args,t,this.metadata("XOR"),((...e)=>{let t=0;return e.forEach((e=>{e&&t++})),t%2==1}))}switch(e,t){return this.runFunction(e.args,t,this.metadata("SWITCH"),((e,...t)=>{const n=t.length;let r=0;for(;r+1e instanceof CellError?t:e))}ifna(e,t){return this.runFunction(e.args,t,this.metadata("IFNA"),((e,t)=>e instanceof CellError&&e.type===ErrorType.NA?t:e))}choose(e,t){return this.runFunction(e.args,t,this.metadata("CHOOSE"),((e,...t)=>e>t.length?new CellError(ErrorType.NUM,ErrorMessage.Selector):t[e-1]))}}BooleanPlugin.implementedFunctions={TRUE:{method:"literalTrue",parameters:[]},FALSE:{method:"literalFalse",parameters:[]},IF:{method:"conditionalIf",parameters:[{argumentType:ArgumentTypes.BOOLEAN},{argumentType:ArgumentTypes.SCALAR,passSubtype:!0},{argumentType:ArgumentTypes.SCALAR,defaultValue:!1,passSubtype:!0}]},AND:{method:"and",parameters:[{argumentType:ArgumentTypes.BOOLEAN}],repeatLastArgs:1,expandRanges:!0},OR:{method:"or",parameters:[{argumentType:ArgumentTypes.BOOLEAN}],repeatLastArgs:1,expandRanges:!0},XOR:{method:"xor",parameters:[{argumentType:ArgumentTypes.BOOLEAN}],repeatLastArgs:1,expandRanges:!0},NOT:{method:"not",parameters:[{argumentType:ArgumentTypes.BOOLEAN}]},SWITCH:{method:"switch",parameters:[{argumentType:ArgumentTypes.NOERROR},{argumentType:ArgumentTypes.SCALAR,passSubtype:!0},{argumentType:ArgumentTypes.SCALAR,passSubtype:!0}],repeatLastArgs:1},IFERROR:{method:"iferror",parameters:[{argumentType:ArgumentTypes.SCALAR,passSubtype:!0},{argumentType:ArgumentTypes.SCALAR,passSubtype:!0}]},IFNA:{method:"ifna",parameters:[{argumentType:ArgumentTypes.SCALAR,passSubtype:!0},{argumentType:ArgumentTypes.SCALAR,passSubtype:!0}]},CHOOSE:{method:"choose",parameters:[{argumentType:ArgumentTypes.INTEGER,minValue:1},{argumentType:ArgumentTypes.SCALAR,passSubtype:!0}],repeatLastArgs:1}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class CharPlugin extends FunctionPlugin{char(e,t){return this.runFunction(e.args,t,this.metadata("CHAR"),(e=>e<1||e>=256?new CellError(ErrorType.VALUE,ErrorMessage.CharacterCodeBounds):String.fromCharCode(Math.trunc(e))))}unichar(e,t){return this.runFunction(e.args,t,this.metadata("CHAR"),(e=>e<1||e>=1114112?new CellError(ErrorType.VALUE,ErrorMessage.CharacterCodeBounds):String.fromCodePoint(Math.trunc(e))))}}CharPlugin.implementedFunctions={CHAR:{method:"char",parameters:[{argumentType:ArgumentTypes.NUMBER}]},UNICHAR:{method:"unichar",parameters:[{argumentType:ArgumentTypes.NUMBER}]}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class CodePlugin extends FunctionPlugin{code(e,t){return this.runFunction(e.args,t,this.metadata("CODE"),(e=>0===e.length?new CellError(ErrorType.VALUE,ErrorMessage.EmptyString):e.charCodeAt(0)))}unicode(e,t){return this.runFunction(e.args,t,this.metadata("UNICODE"),(e=>{var t;return null!==(t=e.codePointAt(0))&&void 0!==t?t:new CellError(ErrorType.VALUE,ErrorMessage.EmptyString)}))}}CodePlugin.implementedFunctions={CODE:{method:"code",parameters:[{argumentType:ArgumentTypes.STRING}]},UNICODE:{method:"unicode",parameters:[{argumentType:ArgumentTypes.STRING}]}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class CountBlankPlugin extends FunctionPlugin{countblank(e,t){return this.runFunction(e.args,t,this.metadata("COUNTBLANK"),((...e)=>{let t=0;return e.forEach((e=>{e===EmptyValue&&t++})),t}))}}CountBlankPlugin.implementedFunctions={COUNTBLANK:{method:"countblank",parameters:[{argumentType:ArgumentTypes.SCALAR}],repeatLastArgs:1,expandRanges:!0}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class CountUniquePlugin extends FunctionPlugin{countunique(e,t){return this.runFunction(e.args,t,this.metadata("COUNTUNIQUE"),((...e)=>{const t=new Set,n=new Set;for(const r of e)r instanceof CellError?n.add(r.type):""!==r&&t.add(r);return t.size+n.size}))}}CountUniquePlugin.implementedFunctions={COUNTUNIQUE:{method:"countunique",parameters:[{argumentType:ArgumentTypes.SCALAR}],repeatLastArgs:1,expandRanges:!0}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class DateTimePlugin extends FunctionPlugin{constructor(){super(...arguments),this.isoweeknumCore=e=>{const t=Math.floor(this.dateTimeHelper.relativeNumberToAbsoluteNumber(e)),n=this.dateTimeHelper.numberToSimpleDate(e),r=this.dateTimeHelper.dateToNumber({year:n.year,month:1,day:1}),a=this.dateTimeHelper.relativeNumberToAbsoluteNumber(r),i=a+((4-a)%7+7)%7,s=Math.floor((t-1)/7)-Math.floor((i-1)/7)+1;return 0===s?this.isoweeknumCore(e-7)+1:s},this.days360Core=(e,t,n)=>{const r=this.dateTimeHelper.numberToSimpleDate(e),a=this.dateTimeHelper.numberToSimpleDate(t);let i,s;return n?(i=toBasisEU(r),s=toBasisEU(a)):[i,s]=this.dateTimeHelper.toBasisUS(r,a),360*(s.year-i.year)+30*(s.month-i.month)+s.day-i.day}}date(e,t){return this.runFunction(e.args,t,this.metadata("DATE"),((e,t,n)=>{const r=Math.trunc(n);let a=Math.trunc(t),i=Math.trunc(e);i{const r=timeToNumber({hours:Math.trunc(e),minutes:Math.trunc(t),seconds:Math.trunc(n)});return r<0?new CellError(ErrorType.NUM,ErrorMessage.NegativeTime):r%1}))}eomonth(e,t){return this.runFunction(e.args,t,this.metadata("EOMONTH"),((e,t)=>{const n=this.dateTimeHelper.numberToSimpleDate(e);let r=this.dateTimeHelper.dateToNumber(this.dateTimeHelper.endOfMonth(offsetMonth(n,t)));return r=this.dateTimeHelper.getWithinBounds(r),void 0===r?new CellError(ErrorType.NUM,ErrorMessage.DateBounds):r}))}day(e,t){return this.runFunction(e.args,t,this.metadata("DAY"),(e=>this.dateTimeHelper.numberToSimpleDate(e).day))}days(e,t){return this.runFunction(e.args,t,this.metadata("DAYS"),((e,t)=>Math.trunc(e)-Math.trunc(t)))}month(e,t){return this.runFunction(e.args,t,this.metadata("MONTH"),(e=>this.dateTimeHelper.numberToSimpleDate(e).month))}year(e,t){return this.runFunction(e.args,t,this.metadata("YEAR"),(e=>this.dateTimeHelper.numberToSimpleDate(e).year))}hour(e,t){return this.runFunction(e.args,t,this.metadata("HOUR"),(e=>numberToSimpleTime(roundToNearestSecond(e)%1).hours))}minute(e,t){return this.runFunction(e.args,t,this.metadata("MINUTE"),(e=>numberToSimpleTime(roundToNearestSecond(e)%1).minutes))}second(e,t){return this.runFunction(e.args,t,this.metadata("SECOND"),(e=>numberToSimpleTime(roundToNearestSecond(e)%1).seconds))}text(e,t){return this.runFunction(e.args,t,this.metadata("TEXT"),((e,t)=>format(e,t,this.config,this.dateTimeHelper)))}weekday(e,t){return this.runFunction(e.args,t,this.metadata("WEEKDAY"),((e,t)=>{const n=Math.floor(this.dateTimeHelper.relativeNumberToAbsoluteNumber(e));if(3===t)return(n-1)%7;const r=weekdayOffsets.get(t);return void 0===r?new CellError(ErrorType.NUM,ErrorMessage.BadMode):(n-r)%7+1}))}weeknum(e,t){return this.runFunction(e.args,t,this.metadata("WEEKNUM"),((e,t)=>{const n=Math.floor(this.dateTimeHelper.relativeNumberToAbsoluteNumber(e)),r=this.dateTimeHelper.numberToSimpleDate(e),a=this.dateTimeHelper.dateToNumber({year:r.year,month:1,day:1}),i=this.dateTimeHelper.relativeNumberToAbsoluteNumber(a);if(21===t)return this.isoweeknumCore(e);const s=weekdayOffsets.get(t);return void 0===s?new CellError(ErrorType.NUM,ErrorMessage.BadMode):Math.floor((n-s)/7)-Math.floor((i-s)/7)+1}))}isoweeknum(e,t){return this.runFunction(e.args,t,this.metadata("ISOWEEKNUM"),this.isoweeknumCore)}datevalue(e,t){return this.runFunction(e.args,t,this.metadata("DATEVALUE"),(e=>{const{dateTime:t}=this.dateTimeHelper.parseDateTimeFromConfigFormats(e);return void 0===t?new CellError(ErrorType.VALUE,ErrorMessage.IncorrectDateTime):instanceOfSimpleDate(t)?(instanceOfSimpleTime(t)?Math.trunc(timeToNumber(t)):0)+this.dateTimeHelper.dateToNumber(t):0}))}timevalue(e,t){return this.runFunction(e.args,t,this.metadata("TIMEVALUE"),(e=>{const t=this.dateTimeHelper.dateStringToDateNumber(e);return void 0===t?new CellError(ErrorType.VALUE,ErrorMessage.IncorrectDateTime):getRawValue(t)%1}))}now(e,t){return this.runFunction(e.args,t,this.metadata("NOW"),(()=>{const e=new Date(Date.now());return timeToNumber({hours:e.getHours(),minutes:e.getMinutes(),seconds:e.getSeconds()})+this.dateTimeHelper.dateToNumber({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate()})}))}today(e,t){return this.runFunction(e.args,t,this.metadata("TODAY"),(()=>{const e=new Date(Date.now());return this.dateTimeHelper.dateToNumber({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate()})}))}edate(e,t){return this.runFunction(e.args,t,this.metadata("EDATE"),((e,t)=>{const n=truncateDayInMonth(offsetMonth(this.dateTimeHelper.numberToSimpleDate(e),t));let r=this.dateTimeHelper.dateToNumber(n);return r=this.dateTimeHelper.getWithinBounds(r),void 0===r?new CellError(ErrorType.NUM,ErrorMessage.DateBounds):r}))}datedif(e,t){return this.runFunction(e.args,t,this.metadata("DATEDIF"),((e,t,n)=>{if(e>t)return new CellError(ErrorType.NUM,ErrorMessage.StartEndDate);if("D"===n)return Math.floor(t)-Math.floor(e);const r=this.dateTimeHelper.numberToSimpleDate(e),a=this.dateTimeHelper.numberToSimpleDate(t);switch(n){case"M":return 12*(a.year-r.year)+(a.month-r.month)-(a.dayr.month||a.month===r.month&&a.day>=r.day?a.year-r.year:a.year-r.year-1;case"MD":if(a.day>=r.day)return a.day-r.day;{const e=1===a.month?12:a.month-1,t=1===a.month?a.year-1:a.year;return this.dateTimeHelper.daysInMonth(t,e)+a.day-r.day}case"YD":return a.month>r.month||a.month===r.month&&a.day>=r.day?Math.floor(t)-this.dateTimeHelper.dateToNumber({year:a.year,month:r.month,day:r.day}):Math.floor(t)-Math.floor(e)-365*(a.year-r.year-1)-this.dateTimeHelper.leapYearsCount(a.year-1)+this.dateTimeHelper.leapYearsCount(r.year);default:return new CellError(ErrorType.NUM,ErrorMessage.BadMode)}}))}days360(e,t){return this.runFunction(e.args,t,this.metadata("DAYS360"),this.days360Core)}yearfrac(e,t){return this.runFunction(e.args,t,this.metadata("YEARFRAC"),((e,t,n)=>{switch((e=Math.trunc(e))>(t=Math.trunc(t))&&([e,t]=[t,e]),n){case 0:return this.days360Core(e,t,!1)/360;case 1:return(t-e)/this.dateTimeHelper.yearLengthForBasis(this.dateTimeHelper.numberToSimpleDate(e),this.dateTimeHelper.numberToSimpleDate(t));case 2:return(t-e)/360;case 3:return(t-e)/365;case 4:return this.days360Core(e,t,!0)/360}throw new Error("Should not be reachable.")}))}interval(e,t){return this.runFunction(e.args,t,this.metadata("INTERVAL"),(e=>{const t=(e=Math.trunc(e))%60,n=(e=Math.trunc(e/60))%60,r=(e=Math.trunc(e/60))%24,a=(e=Math.trunc(e/24))%30,i=(e=Math.trunc(e/30))%12,s=Math.trunc(e/12);return"P"+(s>0?s+"Y":"")+(i>0?i+"M":"")+(a>0?a+"D":"")+"T"+(r>0?r+"H":"")+(n>0?n+"M":"")+(t>0?t+"S":"")}))}networkdays(e,t){return this.runFunction(e.args,t,this.metadata("NETWORKDAYS"),((e,t,n)=>this.networkdayscore(e,t,1,n)))}networkdaysintl(e,t){return this.runFunction(e.args,t,this.metadata("NETWORKDAYS.INTL"),((e,t,n,r)=>this.networkdayscore(e,t,n,r)))}workday(e,t){return this.runFunction(e.args,t,this.metadata("WORKDAY"),((e,t,n)=>this.workdaycore(e,t,1,n)))}workdayintl(e,t){return this.runFunction(e.args,t,this.metadata("WORKDAY.INTL"),((e,t,n,r)=>this.workdaycore(e,t,n,r)))}networkdayscore(e,t,n,r){let a=1;(e=Math.trunc(e))>(t=Math.trunc(t))&&([e,t]=[t,e],a=-1);const i=computeWeekendPattern(n);if(i instanceof CellError)return i;const s=this.simpleRangeToFilteredHolidays(i,r);return s instanceof CellError?s:a*this.countWorkdays(e,t,i,s)}workdaycore(e,t,n,r){e=Math.trunc(e),t=Math.trunc(t);const a=computeWeekendPattern(n);if(a instanceof CellError)return a;const i=this.simpleRangeToFilteredHolidays(a,r);if(i instanceof CellError)return i;if(t>0){let n=1;for(;this.countWorkdays(e+1,e+n,a,i)e-t)).filter((t=>{const n=(this.dateTimeHelper.relativeNumberToAbsoluteNumber(t)-1)%7;return"0"===e.charAt(n)}))}}function lowerBound(e,t){if(0===t.length)return 0;if(e<=t[0])return 0;if(t[t.length-1]=e?r=a:n=a}return r}function computeWeekendPattern(e){var t;return"number"!=typeof e&&"string"!=typeof e?new CellError(ErrorType.VALUE,ErrorMessage.WrongType):"string"==typeof e?7===e.length&&/^(0|1)*$/.test(e)&&"1111111"!==e?e:new CellError(ErrorType.NUM,ErrorMessage.WeekendString):null!==(t=workdayPatterns.get(e))&&void 0!==t?t:new CellError(ErrorType.NUM,ErrorMessage.BadMode)}DateTimePlugin.implementedFunctions={DATE:{method:"date",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER}],returnNumberType:NumberType.NUMBER_DATE},TIME:{method:"time",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER}],returnNumberType:NumberType.NUMBER_TIME},MONTH:{method:"month",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0}]},YEAR:{method:"year",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0}]},HOUR:{method:"hour",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0}]},MINUTE:{method:"minute",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0}]},SECOND:{method:"second",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0}]},TEXT:{method:"text",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.STRING}]},EOMONTH:{method:"eomonth",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER}],returnNumberType:NumberType.NUMBER_DATE},DAY:{method:"day",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0}]},DAYS:{method:"days",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0}]},WEEKDAY:{method:"weekday",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]},WEEKNUM:{method:"weeknum",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]},ISOWEEKNUM:{method:"isoweeknum",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0}]},DATEVALUE:{method:"datevalue",parameters:[{argumentType:ArgumentTypes.STRING}],returnNumberType:NumberType.NUMBER_DATE},TIMEVALUE:{method:"timevalue",parameters:[{argumentType:ArgumentTypes.STRING}],returnNumberType:NumberType.NUMBER_TIME},NOW:{method:"now",parameters:[],isVolatile:!0,returnNumberType:NumberType.NUMBER_DATETIME},TODAY:{method:"today",parameters:[],isVolatile:!0,returnNumberType:NumberType.NUMBER_DATE},EDATE:{method:"edate",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER}],returnNumberType:NumberType.NUMBER_DATE},DAYS360:{method:"days360",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.BOOLEAN,defaultValue:!1}]},DATEDIF:{method:"datedif",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.STRING}]},YEARFRAC:{method:"yearfrac",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.INTEGER,defaultValue:0,minValue:0,maxValue:4}]},INTERVAL:{method:"interval",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0}]},NETWORKDAYS:{method:"networkdays",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.RANGE,optionalArg:!0}]},"NETWORKDAYS.INTL":{method:"networkdaysintl",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NOERROR,defaultValue:1},{argumentType:ArgumentTypes.RANGE,optionalArg:!0}]},WORKDAY:{method:"workday",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.RANGE,optionalArg:!0}]},"WORKDAY.INTL":{method:"workdayintl",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NOERROR,defaultValue:1},{argumentType:ArgumentTypes.RANGE,optionalArg:!0}]}};const weekdayOffsets=new Map([[1,0],[2,1],[11,1],[12,2],[13,3],[14,4],[15,5],[16,6],[17,0]]),workdayPatterns=new Map([[1,"0000011"],[2,"1000001"],[3,"1100000"],[4,"0110000"],[5,"0011000"],[6,"0001100"],[7,"0000110"],[11,"0000001"],[12,"1000000"],[13,"0100000"],[14,"0010000"],[15,"0001000"],[16,"0000100"],[17,"0000010"]]); +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class DegreesPlugin extends FunctionPlugin{degrees(e,t){return this.runFunction(e.args,t,this.metadata("DEGREES"),(e=>e*(180/Math.PI)))}}DegreesPlugin.implementedFunctions={DEGREES:{method:"degrees",parameters:[{argumentType:ArgumentTypes.NUMBER}]}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class DeltaPlugin extends FunctionPlugin{delta(e,t){return this.runFunction(e.args,t,this.metadata("DELTA"),((e,t)=>e===t?1:0))}}DeltaPlugin.implementedFunctions={DELTA:{method:"delta",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,defaultValue:0}]}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class ExpPlugin extends FunctionPlugin{exp(e,t){return this.runFunction(e.args,t,this.metadata("EXP"),Math.exp)}}ExpPlugin.implementedFunctions={EXP:{method:"exp",parameters:[{argumentType:ArgumentTypes.NUMBER}]}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class FinancialPlugin extends FunctionPlugin{pmt(e,t){return this.runFunction(e.args,t,this.metadata("PMT"),pmtCore)}ipmt(e,t){return this.runFunction(e.args,t,this.metadata("IPMT"),ipmtCore)}ppmt(e,t){return this.runFunction(e.args,t,this.metadata("PPMT"),ppmtCore)}fv(e,t){return this.runFunction(e.args,t,this.metadata("FV"),fvCore)}cumipmt(e,t){return this.runFunction(e.args,t,this.metadata("CUMIPMT"),((e,t,n,r,a,i)=>{if(r>a)return new CellError(ErrorType.NUM,ErrorMessage.EndStartPeriod);let s=0;for(let o=r;o<=a;o++)s+=ipmtCore(e,o,t,n,0,i);return s}))}cumprinc(e,t){return this.runFunction(e.args,t,this.metadata("CUMPRINC"),((e,t,n,r,a,i)=>{if(r>a)return new CellError(ErrorType.NUM,ErrorMessage.EndStartPeriod);let s=0;for(let o=r;o<=a;o++)s+=ppmtCore(e,o,t,n,0,i);return s}))}db(e,t){return this.runFunction(e.args,t,this.metadata("DB"),((e,t,n,r,a)=>{if(12===a&&r>n||r>n+1)return new CellError(ErrorType.NUM,ErrorMessage.PeriodLong);if(t>=e)return 0;const i=Math.round(1e3*(1-Math.pow(t/e,1/n)))/1e3,s=e*i*a/12;if(1===r)return s;let o=s;for(let t=0;t{if(r>n)return new CellError(ErrorType.NUM);let i,s=a/n;s>=1?(s=1,i=1===r?e:0):i=e*Math.pow(1-s,r-1);const o=e*Math.pow(1-s,r);return Math.max(i-Math.max(t,o),0)}))}dollarde(e,t){return this.runFunction(e.args,t,this.metadata("DOLLARDE"),((e,t)=>{if(t<1)return new CellError(ErrorType.DIV_BY_ZERO);for(t=Math.trunc(t);t>10;)t/=10;return Math.trunc(e)+10*(e-Math.trunc(e))/t}))}dollarfr(e,t){return this.runFunction(e.args,t,this.metadata("DOLLARFR"),((e,t)=>{if(t<1)return new CellError(ErrorType.DIV_BY_ZERO);for(t=Math.trunc(t);t>10;)t/=10;return Math.trunc(e)+(e-Math.trunc(e))*t/10}))}effect(e,t){return this.runFunction(e.args,t,this.metadata("EFFECT"),((e,t)=>(t=Math.trunc(t),Math.pow(1+e/t,t)-1)))}ispmt(e,t){return this.runFunction(e.args,t,this.metadata("ISPMT"),((e,t,n,r)=>0===n?new CellError(ErrorType.DIV_BY_ZERO):r*e*(t/n-1)))}nominal(e,t){return this.runFunction(e.args,t,this.metadata("NOMINAL"),((e,t)=>(t=Math.trunc(t),(Math.pow(e+1,1/t)-1)*t)))}nper(e,t){return this.runFunction(e.args,t,this.metadata("NPER"),((e,t,n,r,a)=>0===e?0===t?new CellError(ErrorType.DIV_BY_ZERO):(-n-r)/t:(a&&(t*=1+e),Math.log((t-r*e)/(n*e+t))/Math.log(1+e))))}rate(e,t){return this.runFunction(e.args,t,this.metadata("RATE"),((e,t,n,r,a,i)=>{if(i<=-1)return new CellError(ErrorType.VALUE);const s=1e-7;let o=i;a=a?1:0;for(let i=0;i<50;i++){if(o<=-1)return new CellError(ErrorType.NUM);let i,l;if(Math.abs(o)(a=a?1:0,-1===e?new CellError(0===t?ErrorType.NUM:ErrorType.DIV_BY_ZERO):0===e?-n*t-r:((1-Math.pow(1+e,t))*n*(1+e*a)/e-r)/Math.pow(1+e,t))))}rri(e,t){return this.runFunction(e.args,t,this.metadata("RRI"),((e,t,n)=>0===t||n<0&&t>0||n>0&&t<0?new CellError(ErrorType.NUM):Math.pow(n/t,1/e)-1))}sln(e,t){return this.runFunction(e.args,t,this.metadata("SLN"),((e,t,n)=>0===n?new CellError(ErrorType.DIV_BY_ZERO):(e-t)/n))}syd(e,t){return this.runFunction(e.args,t,this.metadata("SYD"),((e,t,n,r)=>r>n?new CellError(ErrorType.NUM):(e-t)*(n-r+1)*2/(n*(n+1))))}tbilleq(e,t){return this.runFunction(e.args,t,this.metadata("TBILLEQ"),((e,t,n)=>{if((e=Math.round(e))>=(t=Math.round(t)))return new CellError(ErrorType.NUM);const r=this.dateTimeHelper.numberToSimpleDate(e),a=this.dateTimeHelper.numberToSimpleDate(t);if(a.year>r.year+1||a.year===r.year+1&&(a.month>r.month||a.month===r.month&&a.day>r.day))return new CellError(ErrorType.NUM);const i=360-n*(t-e);return 0===i?0:i<0?new CellError(ErrorType.NUM):365*n/i}))}tbillprice(e,t){return this.runFunction(e.args,t,this.metadata("TBILLPRICE"),((e,t,n)=>{if((e=Math.round(e))>=(t=Math.round(t)))return new CellError(ErrorType.NUM);const r=this.dateTimeHelper.numberToSimpleDate(e),a=this.dateTimeHelper.numberToSimpleDate(t);if(a.year>r.year+1||a.year===r.year+1&&(a.month>r.month||a.month===r.month&&a.day>r.day))return new CellError(ErrorType.NUM);const i=360-n*(t-e);return 0===i?0:i<0?new CellError(ErrorType.NUM):100*(1-n*(t-e)/360)}))}tbillyield(e,t){return this.runFunction(e.args,t,this.metadata("TBILLYIELD"),((e,t,n)=>{if((e=Math.round(e))>=(t=Math.round(t)))return new CellError(ErrorType.NUM);const r=this.dateTimeHelper.numberToSimpleDate(e),a=this.dateTimeHelper.numberToSimpleDate(t);return a.year>r.year+1||a.year===r.year+1&&(a.month>r.month||a.month===r.month&&a.day>r.day)?new CellError(ErrorType.NUM):360*(100-n)/(n*(t-e))}))}fvschedule(e,t){return this.runFunction(e.args,t,this.metadata("FVSCHEDULE"),((e,t)=>{const n=t.valuesFromTopLeftCorner();for(const e of n)if(e instanceof CellError)return e;for(const t of n)if(isExtendedNumber(t))e*=1+getRawValue(t);else if(t!==EmptyValue)return new CellError(ErrorType.VALUE,ErrorMessage.NumberExpected);return e}))}npv(e,t){return this.runFunction(e.args,t,this.metadata("NPV"),((e,...t)=>{const n=this.arithmeticHelper.coerceNumbersExactRanges(t);return n instanceof CellError?n:npvCore(e,n)}))}mirr(e,t){return this.runFunction(e.args,t,this.metadata("MIRR"),((e,t,n)=>{const r=this.arithmeticHelper.manyToExactNumbers(e.valuesFromTopLeftCorner());if(r instanceof CellError)return r;let a=!1,i=!1;const s=[],o=[];for(const e of r)e>0?(a=!0,s.push(e),o.push(0)):e<0?(i=!0,o.push(e),s.push(0)):(o.push(0),s.push(0));if(!a||!i)return new CellError(ErrorType.DIV_BY_ZERO);const l=r.length,u=npvCore(n,s);if(u instanceof CellError)return u;const c=npvCore(t,o);return c instanceof CellError?c:Math.pow(-u*Math.pow(1+n,l)/c/(1+t),1/(l-1))-1}))}pduration(e,t){return this.runFunction(e.args,t,this.metadata("PDURATION"),((e,t,n)=>(Math.log(n)-Math.log(t))/Math.log(1+e)))}xnpv(e,t){return this.runFunction(e.args,t,this.metadata("XNPV"),((e,t,n)=>{const r=t.valuesFromTopLeftCorner();for(const e of r)if("number"!=typeof e)return new CellError(ErrorType.VALUE,ErrorMessage.NumberExpected);const a=r,i=n.valuesFromTopLeftCorner();for(const e of i)if("number"!=typeof e)return new CellError(ErrorType.VALUE,ErrorMessage.NumberExpected);const s=i;if(s.length!==a.length)return new CellError(ErrorType.NUM,ErrorMessage.EqualLength);const o=s.length;let l=0;if(s[0]<0)return new CellError(ErrorType.NUM,ErrorMessage.ValueSmall);for(let t=0;t=0;r--){if(n+=t[r],-1===e){if(0===n)continue;return new CellError(ErrorType.DIV_BY_ZERO)}n/=1+e}return n} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */FinancialPlugin.implementedFunctions={PMT:{method:"pmt",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,defaultValue:0},{argumentType:ArgumentTypes.NUMBER,defaultValue:0}],returnNumberType:NumberType.NUMBER_CURRENCY},IPMT:{method:"ipmt",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,defaultValue:0},{argumentType:ArgumentTypes.NUMBER,defaultValue:0}],returnNumberType:NumberType.NUMBER_CURRENCY},PPMT:{method:"ppmt",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,defaultValue:0},{argumentType:ArgumentTypes.NUMBER,defaultValue:0}],returnNumberType:NumberType.NUMBER_CURRENCY},FV:{method:"fv",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,defaultValue:0},{argumentType:ArgumentTypes.NUMBER,defaultValue:0}],returnNumberType:NumberType.NUMBER_CURRENCY},CUMIPMT:{method:"cumipmt",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.INTEGER,minValue:1},{argumentType:ArgumentTypes.INTEGER,minValue:1},{argumentType:ArgumentTypes.INTEGER,minValue:0,maxValue:1}],returnNumberType:NumberType.NUMBER_CURRENCY},CUMPRINC:{method:"cumprinc",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.INTEGER,minValue:1},{argumentType:ArgumentTypes.INTEGER,minValue:1},{argumentType:ArgumentTypes.INTEGER,minValue:0,maxValue:1}],returnNumberType:NumberType.NUMBER_CURRENCY},DB:{method:"db",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.INTEGER,minValue:0},{argumentType:ArgumentTypes.INTEGER,minValue:0},{argumentType:ArgumentTypes.INTEGER,minValue:1,maxValue:12,defaultValue:12}],returnNumberType:NumberType.NUMBER_CURRENCY},DDB:{method:"ddb",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.INTEGER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0,defaultValue:2}],returnNumberType:NumberType.NUMBER_CURRENCY},DOLLARDE:{method:"dollarde",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,minValue:0}]},DOLLARFR:{method:"dollarfr",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,minValue:0}]},EFFECT:{method:"effect",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:1}],returnNumberType:NumberType.NUMBER_PERCENT},ISPMT:{method:"ispmt",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER}]},NOMINAL:{method:"nominal",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:1}],returnNumberType:NumberType.NUMBER_PERCENT},NPER:{method:"nper",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,defaultValue:0},{argumentType:ArgumentTypes.NUMBER,defaultValue:0}]},PV:{method:"pv",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,defaultValue:0},{argumentType:ArgumentTypes.NUMBER,defaultValue:0}],returnNumberType:NumberType.NUMBER_CURRENCY},RATE:{method:"rate",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,defaultValue:0},{argumentType:ArgumentTypes.NUMBER,defaultValue:0},{argumentType:ArgumentTypes.NUMBER,defaultValue:.1}],returnNumberType:NumberType.NUMBER_PERCENT},RRI:{method:"rri",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER}],returnNumberType:NumberType.NUMBER_PERCENT},SLN:{method:"sln",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER}],returnNumberType:NumberType.NUMBER_CURRENCY},SYD:{method:"syd",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0}],returnNumberType:NumberType.NUMBER_CURRENCY},TBILLEQ:{method:"tbilleq",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0}],returnNumberType:NumberType.NUMBER_PERCENT},TBILLPRICE:{method:"tbillprice",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0}],returnNumberType:NumberType.NUMBER_CURRENCY},TBILLYIELD:{method:"tbillyield",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0}],returnNumberType:NumberType.NUMBER_PERCENT},FVSCHEDULE:{method:"fvschedule",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.RANGE}],returnNumberType:NumberType.NUMBER_CURRENCY},NPV:{method:"npv",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1,returnNumberType:NumberType.NUMBER_CURRENCY},MIRR:{method:"mirr",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER}],returnNumberType:NumberType.NUMBER_PERCENT},PDURATION:{method:"pduration",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0}]},XNPV:{method:"xnpv",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:-1},{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]}};class FormulaTextPlugin extends FunctionPlugin{formulatext(e,t){return this.runFunctionWithReferenceArgument(e.args,t,this.metadata("FORMULATEXT"),(()=>new CellError(ErrorType.NA,ErrorMessage.WrongArgNumber)),(e=>{var t;return null!==(t=this.serialization.getCellFormula(e))&&void 0!==t?t:new CellError(ErrorType.NA,ErrorMessage.Formula)}))}}FormulaTextPlugin.implementedFunctions={FORMULATEXT:{method:"formulatext",parameters:[{argumentType:ArgumentTypes.NOERROR}],doesNotNeedArgumentsToBeComputed:!0,isDependentOnSheetStructureChange:!0,vectorizationForbidden:!0}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class InformationPlugin extends FunctionPlugin{isbinary(e,t){return this.runFunction(e.args,t,this.metadata("ISBINARY"),(e=>/^[01]{1,10}$/.test(e)))}iserr(e,t){return this.runFunction(e.args,t,this.metadata("ISERR"),(e=>e instanceof CellError&&e.type!==ErrorType.NA))}iserror(e,t){return this.runFunction(e.args,t,this.metadata("ISERROR"),(e=>e instanceof CellError))}isformula(e,t){return this.runFunctionWithReferenceArgument(e.args,t,this.metadata("ISFORMULA"),(()=>new CellError(ErrorType.NA,ErrorMessage.WrongArgNumber)),(e=>this.dependencyGraph.addressMapping.getCell(e)instanceof FormulaVertex))}isblank(e,t){return this.runFunction(e.args,t,this.metadata("ISBLANK"),(e=>e===EmptyValue))}isna(e,t){return this.runFunction(e.args,t,this.metadata("ISNA"),(e=>e instanceof CellError&&e.type==ErrorType.NA))}isnumber(e,t){return this.runFunction(e.args,t,this.metadata("ISNUMBER"),isExtendedNumber)}islogical(e,t){return this.runFunction(e.args,t,this.metadata("ISLOGICAL"),(e=>"boolean"==typeof e))}isref(e,t){return this.runFunction(e.args,t,this.metadata("ISREF"),(e=>e instanceof CellError&&(e.type==ErrorType.REF||e.type==ErrorType.CYCLE)))}istext(e,t){return this.runFunction(e.args,t,this.metadata("ISTEXT"),(e=>"string"==typeof e))}isnontext(e,t){return this.runFunction(e.args,t,this.metadata("ISNONTEXT"),(e=>!("string"==typeof e)))}column(e,t){return this.runFunctionWithReferenceArgument(e.args,t,this.metadata("COLUMN"),(()=>t.formulaAddress.col+1),(e=>e.col+1))}columns(e,t){if(1!==e.args.length)return new CellError(ErrorType.NA,ErrorMessage.WrongArgNumber);if(e.args.some((e=>e.type===AstNodeType.EMPTY)))return new CellError(ErrorType.NUM,ErrorMessage.EmptyArg);let n=e.args[0];for(;n.type===AstNodeType.PARENTHESIS;)n=n.expression;if(n.type===AstNodeType.CELL_RANGE||n.type===AstNodeType.COLUMN_RANGE)return n.end.col-n.start.col+1;if(n.type===AstNodeType.CELL_REFERENCE)return 1;if(n.type===AstNodeType.ROW_RANGE)return this.config.maxColumns;{const e=this.evaluateAst(n,t);return e instanceof SimpleRangeValue?e.width():e instanceof CellError?e:1}}row(e,t){return this.runFunctionWithReferenceArgument(e.args,t,this.metadata("ROW"),(()=>t.formulaAddress.row+1),(e=>e.row+1))}rows(e,t){if(1!==e.args.length)return new CellError(ErrorType.NA,ErrorMessage.WrongArgNumber);if(e.args.some((e=>e.type===AstNodeType.EMPTY)))return new CellError(ErrorType.NUM,ErrorMessage.EmptyArg);let n=e.args[0];for(;n.type===AstNodeType.PARENTHESIS;)n=n.expression;if(n.type===AstNodeType.CELL_RANGE||n.type===AstNodeType.ROW_RANGE)return n.end.row-n.start.row+1;if(n.type===AstNodeType.CELL_REFERENCE)return 1;if(n.type===AstNodeType.COLUMN_RANGE)return this.config.maxRows;{const e=this.evaluateAst(n,t);return e instanceof SimpleRangeValue?e.height():e instanceof CellError?e:1}}index(e,t){return this.runFunction(e.args,t,this.metadata("INDEX"),((e,t,n)=>{var r,a,i,s,o,l;return n<1||t<1?new CellError(ErrorType.VALUE,ErrorMessage.LessThanOne):n>e.width()||t>e.height()?new CellError(ErrorType.NUM,ErrorMessage.ValueLarge):null!==(l=null!==(i=null===(a=null===(r=null==e?void 0:e.data)||void 0===r?void 0:r[t-1])||void 0===a?void 0:a[n-1])&&void 0!==i?i:null===(o=null===(s=null==e?void 0:e.data)||void 0===s?void 0:s[0])||void 0===o?void 0:o[0])&&void 0!==l?l:new CellError(ErrorType.VALUE,ErrorMessage.CellRangeExpected)}))}na(e,t){return new CellError(ErrorType.NA)}sheet(e,t){return this.runFunctionWithReferenceArgument(e.args,t,this.metadata("SHEET"),(()=>t.formulaAddress.sheet+1),(e=>e.sheet+1),(e=>{const t=this.dependencyGraph.sheetMapping.get(e);return void 0!==t?t+1:new CellError(ErrorType.NA,ErrorMessage.SheetRef)}))}sheets(e,t){return this.runFunctionWithReferenceArgument(e.args,t,this.metadata("SHEETS"),(()=>this.dependencyGraph.sheetMapping.numberOfSheets()),(()=>1),(()=>new CellError(ErrorType.VALUE,ErrorMessage.CellRefExpected)))}}InformationPlugin.implementedFunctions={COLUMN:{method:"column",parameters:[{argumentType:ArgumentTypes.NOERROR,optional:!0}],isDependentOnSheetStructureChange:!0,doesNotNeedArgumentsToBeComputed:!0,vectorizationForbidden:!0},COLUMNS:{method:"columns",parameters:[{argumentType:ArgumentTypes.RANGE}],isDependentOnSheetStructureChange:!0,doesNotNeedArgumentsToBeComputed:!0,vectorizationForbidden:!0},ISBINARY:{method:"isbinary",parameters:[{argumentType:ArgumentTypes.STRING}]},ISERR:{method:"iserr",parameters:[{argumentType:ArgumentTypes.SCALAR}]},ISFORMULA:{method:"isformula",parameters:[{argumentType:ArgumentTypes.NOERROR}],doesNotNeedArgumentsToBeComputed:!0,vectorizationForbidden:!0},ISNA:{method:"isna",parameters:[{argumentType:ArgumentTypes.SCALAR}]},ISREF:{method:"isref",parameters:[{argumentType:ArgumentTypes.SCALAR}],vectorizationForbidden:!0},ISERROR:{method:"iserror",parameters:[{argumentType:ArgumentTypes.SCALAR}]},ISBLANK:{method:"isblank",parameters:[{argumentType:ArgumentTypes.SCALAR}]},ISNUMBER:{method:"isnumber",parameters:[{argumentType:ArgumentTypes.SCALAR}]},ISLOGICAL:{method:"islogical",parameters:[{argumentType:ArgumentTypes.SCALAR}]},ISTEXT:{method:"istext",parameters:[{argumentType:ArgumentTypes.SCALAR}]},ISNONTEXT:{method:"isnontext",parameters:[{argumentType:ArgumentTypes.SCALAR}]},INDEX:{method:"index",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]},NA:{method:"na",parameters:[]},ROW:{method:"row",parameters:[{argumentType:ArgumentTypes.NOERROR,optional:!0}],isDependentOnSheetStructureChange:!0,doesNotNeedArgumentsToBeComputed:!0,vectorizationForbidden:!0},ROWS:{method:"rows",parameters:[{argumentType:ArgumentTypes.RANGE}],isDependentOnSheetStructureChange:!0,doesNotNeedArgumentsToBeComputed:!0,vectorizationForbidden:!0},SHEET:{method:"sheet",parameters:[{argumentType:ArgumentTypes.STRING}],doesNotNeedArgumentsToBeComputed:!0,vectorizationForbidden:!0},SHEETS:{method:"sheets",parameters:[{argumentType:ArgumentTypes.STRING}],doesNotNeedArgumentsToBeComputed:!0,vectorizationForbidden:!0}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class IsEvenPlugin extends FunctionPlugin{iseven(e,t){return this.runFunction(e.args,t,this.metadata("ISEVEN"),(e=>e%2==0))}}IsEvenPlugin.implementedFunctions={ISEVEN:{method:"iseven",parameters:[{argumentType:ArgumentTypes.NUMBER}]}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class IsOddPlugin extends FunctionPlugin{isodd(e,t){return this.runFunction(e.args,t,this.metadata("ISODD"),(e=>e%2==1))}}IsOddPlugin.implementedFunctions={ISODD:{method:"isodd",parameters:[{argumentType:ArgumentTypes.NUMBER}]}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. */ -function defaultParseToDateTime(e,t,n){var r=(e=e.replace(/\s\s+/g," ").trim().toLowerCase()).substring(e.length-2);"am"===r||"pm"===r?e=e.substring(0,e.length-2).trim():"a"===(r=e.substring(e.length-1))||"p"===r?e=e.substring(0,e.length-1).trim():r=void 0;var a=e.split(/[ /.-]/g);a.length>=2&&a[a.length-2].includes(":")&&(a[a.length-2]=a[a.length-2]+"."+a[a.length-1],a.pop());var i=a[a.length-1].split(":");if(void 0!==r&&i.push(r),1===a.length)return defaultParseToTime(i,n);if(1===i.length)return defaultParseToDate(a,t);var o=defaultParseToDate(a.slice(0,a.length-1),t),s=defaultParseToTime(i,n);return void 0===o||void 0===s?void 0:Object.assign(Object.assign({},o),s)}$$j({target:"String",proto:!0,forced:!MDN_POLYFILL_BUG&&!CORRECT_IS_REGEXP_LOGIC},{endsWith:function(e){var t=toString$4(requireObjectCoercible$2(this));notARegExp(e);var n=arguments.length>1?arguments[1]:void 0,r=t.length,a=void 0===n?r:min(toLength$1(n),r),i=toString$4(e);return un$EndsWith?un$EndsWith(t,i,a):slice(t,a-i.length,a)===i}});var secondsExtendedRegexp=/^ss\.(s+|0+)$/;function defaultParseToTime(e,t){if(void 0!==t){(t=t.toLowerCase()).endsWith("am/pm")?t=t.substring(0,t.length-5).trim():t.endsWith("a/p")&&(t=t.substring(0,t.length-3).trim());var n=t.split(":"),r=void 0;"am"===e[e.length-1]||"a"===e[e.length-1]?(r=!1,e.pop()):"pm"!==e[e.length-1]&&"p"!==e[e.length-1]||(r=!0,e.pop());var a=0;if(n.length>=1&&secondsExtendedRegexp.test(n[n.length-1])&&(a=n[n.length-1].length-3,n[n.length-1]="ss"),e.length===n.length){var i=n.indexOf("hh"),o=n.indexOf("mm"),s=n.indexOf("ss"),l=-1!==i?e[i]:"0";if(/^\d+$/.test(l)){var u=Number(l);if(void 0!==r){if(u<0||u>12)return;u%=12,r&&(u+=12)}var c=-1!==o?e[o]:"0";if(/^\d+$/.test(c)){var p=Number(c),d=-1!==s?e[s]:"0";if(/^\d+(\.\d+)?$/.test(d)){var m=Number(d);return{hours:u,minutes:p,seconds:m=Math.round(m*Math.pow(10,a))/Math.pow(10,a)}}}}}}}function defaultParseToDate(e,t){if(void 0!==t){var n=t.toLowerCase().split(/[ /.-]/g);if(e.length===n.length){var r=n.indexOf("mm"),a=n.indexOf("dd"),i=n.indexOf("yyyy"),o=n.indexOf("yy");if(r in e&&a in e&&(i in e||o in e)&&(!(i in e)||!(o in e))){var s;if(i in e){var l=e[i];if(!/^\d+$/.test(l))return;if((s=Number(l))<1e3||s>9999)return}else{var u=e[o];if(!/^\d+$/.test(u))return;if((s=Number(u))<0||s>99)return}var c=e[r];if(/^\d+$/.test(c)){var p=Number(c),d=e[a];if(/^\d+$/.test(d))return{year:s,month:p,day:Number(d)}}}}}}function _createForOfIteratorHelper$o(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$w(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$w(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$w(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$w(e,t):void 0}}function _arrayLikeToArray$w(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=0?e:void 0}},{key:"dateStringToDateNumber",value:function(e){var t=this.parseDateTimeFromConfigFormats(e),n=t.dateTime,r=t.dateFormat,a=void 0===r?"":r,i=t.timeFormat,o=void 0===i?"":i;if(void 0!==n)return instanceOfSimpleTime(n)?instanceOfSimpleDate(n)?new DateTimeNumber(timeToNumber(n)+this.dateToNumber(n),a+" "+o):new TimeNumber(timeToNumber(n),o):instanceOfSimpleDate(n)?new DateNumber(this.dateToNumber(n),a):0}},{key:"parseDateTimeFromConfigFormats",value:function(e){return this.parseDateTimeFromFormats(e,this.config.dateFormats,this.config.timeFormats)}},{key:"getNullYear",value:function(){return this.config.nullYear}},{key:"getEpochYearZero",value:function(){return this.epochYearZero}},{key:"isValidDate",value:function(e){return!(isNaN(e.year)||isNaN(e.month)||isNaN(e.day))&&(e.day===Math.round(e.day)&&e.month===Math.round(e.month)&&e.year===Math.round(e.year)&&(!(e.year<1582)&&(!(e.month<1||e.month>12)&&(!(e.day<1)&&(this.isLeapYear(e.year)&&2===e.month?e.day<=29:e.day<=numDays[e.month-1])))))}},{key:"dateToNumber",value:function(e){return this.dateToNumberFromZero(e)-this.minDateAboluteValue}},{key:"relativeNumberToAbsoluteNumber",value:function(e){return e+this.minDateAboluteValue-(this.leapYear1900?1:0)}},{key:"numberToSimpleDate",value:function(e){var t=Math.floor(e)+this.minDateAboluteValue,n=Math.floor(t/365.2425);this.dateToNumberFromZero({year:n+1,month:1,day:1})<=t?n++:this.dateToNumberFromZero({year:n-1,month:1,day:1})>t&&n--;var r=t-this.dateToNumberFromZero({year:n,month:1,day:1}),a=dayToMonth(r-(this.isLeapYear(n)&&r>=59?1:0));return{year:n,month:a+1,day:r-prefSumDays[a]-(this.isLeapYear(n)&&a>1?1:0)+1}}},{key:"numberToSimpleDateTime",value:function(e){return Object.assign(Object.assign({},this.numberToSimpleDate(Math.floor(e))),numberToSimpleTime(e%1))}},{key:"leapYearsCount",value:function(e){return Math.floor(e/4)-Math.floor(e/100)+Math.floor(e/400)+(this.config.leapYear1900&&e>=1900?1:0)}},{key:"daysInMonth",value:function(e,t){return this.isLeapYear(e)&&2===t?29:numDays[t-1]}},{key:"endOfMonth",value:function(e){return{year:e.year,month:e.month,day:this.daysInMonth(e.year,e.month)}}},{key:"toBasisUS",value:function(e,t){return 31===e.day&&(e.day=30),30===e.day&&31===t.day&&(t.day=30),2===e.month&&e.day===this.daysInMonth(e.year,e.month)&&(e.day=30,2===t.month&&t.day===this.daysInMonth(t.year,t.month)&&(t.day=30)),[e,t]}},{key:"yearLengthForBasis",value:function(e,t){return e.year!==t.year?e.year+1!==t.year||e.month=0&&r.year<100&&(r.year2||2===e.month&&e.day>=29?this.leapYearsCount(e.year):this.leapYearsCount(e.year-1)}},{key:"dateToNumberFromZero",value:function(e){return 365*e.year+prefSumDays[e.month-1]+e.day-1+(e.month<=2?this.leapYearsCount(e.year-1):this.leapYearsCount(e.year))}},{key:"isLeapYear",value:function(e){return!(e%4)&&(!!(e%100)||(!(e%400)||1900===e&&this.config.leapYear1900))}}]),e}();function dayToMonth(e){var t=0;return prefSumDays[t+6]<=e&&(t+=6),prefSumDays[t+3]<=e&&(t+=3),prefSumDays[t+2]<=e?t+=2:prefSumDays[t+1]<=e&&(t+=1),t}function offsetMonth(e,t){var n=12*e.year+e.month-1+t;return{year:Math.floor(n/12),month:n%12+1,day:e.day}}function truncateDayInMonth(e){return{year:e.year,month:e.month,day:Math.min(e.day,numDays[e.month-1])}}function roundToNearestSecond(e){return Math.round(3600*e*24)/86400}function numberToSimpleTime(e){e=Math.round(24*e*60*60*1e5)/864e7,e*=24;var t=Math.floor(e);e-=t,e*=60;var n=Math.floor(e);return e-=n,e*=60,{hours:t,minutes:n,seconds:Math.round(1e5*e)/1e5}}function timeToNumber(e){return((e.seconds/60+e.minutes)/60+e.hours)/24}function toBasisEU(e){return{year:e.year,month:e.month,day:Math.min(30,e.day)}}function _classCallCheck$1c(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1c(e,t){for(var n=0;n0;(r>>>=1)&&(t+=t))1&r&&(n+=t);return n},$$i=_export,uncurryThis$2=functionUncurryThis,toIntegerOrInfinity=toIntegerOrInfinity$7,thisNumberValue=thisNumberValue$2,$repeat$1=stringRepeat,fails$1=fails$G,$RangeError$1=RangeError,$String=String,floor=Math.floor,repeat$2=uncurryThis$2($repeat$1),stringSlice$1=uncurryThis$2("".slice),un$ToFixed=uncurryThis$2(1..toFixed),pow=function(e,t,n){return 0===t?n:t%2==1?pow(e,t-1,n*e):pow(e*e,t/2,n)},log$5=function(e){for(var t=0,n=e;n>=4096;)t+=12,n/=4096;for(;n>=2;)t+=1,n/=2;return t},multiply=function(e,t,n){for(var r=-1,a=n;++r<6;)a+=t*e[r],e[r]=a%1e7,a=floor(a/1e7)},divide=function(e,t){for(var n=6,r=0;--n>=0;)r+=e[n],e[n]=floor(r/t),r=r%t*1e7},dataToString=function(e){for(var t=6,n="";--t>=0;)if(""!==n||0===t||0!==e[t]){var r=$String(e[t]);n=""===n?r:n+repeat$2("0",7-r.length)+r}return n},FORCED$2=fails$1((function(){return"0.000"!==un$ToFixed(8e-5,3)||"1"!==un$ToFixed(.9,0)||"1.25"!==un$ToFixed(1.255,2)||"1000000000000000128"!==un$ToFixed(0xde0b6b3a7640080,0)}))||!fails$1((function(){un$ToFixed({})}));$$i({target:"Number",proto:!0,forced:FORCED$2},{toFixed:function(e){var t,n,r,a,i=thisNumberValue(this),o=toIntegerOrInfinity(e),s=[0,0,0,0,0,0],l="",u="0";if(o<0||o>20)throw $RangeError$1("Incorrect fraction digits");if(i!=i)return"NaN";if(i<=-1e21||i>=1e21)return $String(i);if(i<0&&(l="-",i=-i),i>1e-21)if(n=(t=log$5(i*pow(2,69,1))-69)<0?i*pow(2,-t,1):i/pow(2,t,1),n*=4503599627370496,(t=52-t)>0){for(multiply(s,0,n),r=o;r>=7;)multiply(s,1e7,0),r-=7;for(multiply(s,pow(10,r,1),0),r=t-1;r>=23;)divide(s,1<<23),r-=23;divide(s,1<0?l+((a=u.length)<=o?"0."+repeat$2("0",o-a)+u:stringSlice$1(u,0,a-o)+"."+stringSlice$1(u,a-o)):l+u}}); +class LogarithmPlugin extends FunctionPlugin{log10(e,t){return this.runFunction(e.args,t,this.metadata("LOG10"),Math.log10)}log(e,t){return this.runFunction(e.args,t,this.metadata("LOG"),((e,t)=>Math.log(e)/Math.log(t)))}ln(e,t){return this.runFunction(e.args,t,this.metadata("LN"),Math.log)}}LogarithmPlugin.implementedFunctions={LOG10:{method:"log10",parameters:[{argumentType:ArgumentTypes.NUMBER}]},LOG:{method:"log",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,defaultValue:10,greaterThan:0}]},LN:{method:"ln",parameters:[{argumentType:ArgumentTypes.NUMBER}]}}; /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. + * Copyright (c) 2022 Handsoncode. All rights reserved. */ -var dateFormatRegex=/(\\.|dd|DD|d|D|mm|MM|m|M|YYYY|YY|yyyy|yy|HH|hh|H|h|ss(\.(0+|s+))?|s|AM\/PM|am\/pm|A\/P|a\/p|\[mm]|\[MM]|\[hh]|\[HH])/g,numberFormatRegex=/(\\.|[#0]+(\.[#0]*)?)/g,TokenType,FormatExpressionType;function formatToken(e,t){return{type:e,value:t}}function matchDateFormat(e){dateFormatRegex.lastIndex=0;var t,n=[];do{null!==(t=dateFormatRegex.exec(e))&&n.push(t)}while(t);return n}function matchNumberFormat(e){numberFormatRegex.lastIndex=0;var t=numberFormatRegex.exec(e);return null!==t?[t]:[]}function createTokens(e,t){for(var n=[],r=0,a=0;a=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$v(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$v(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$v(e,t):void 0}}function _arrayLikeToArray$v(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);nc.length)c=padLeft(c,countChars(o.substr(0,o.length-c.length),"0")+c.length);n+=c+l+(p=padRight(p,countChars(s.substr(p.length,s.length-p.length),"0")+p.length))}else n+=a.value}return n}function defaultStringifyDuration(e,t){var n=parseForDateTimeFormat(t);if(void 0!==n){var r,a="",i=_createForOfIteratorHelper$n(n.tokens);try{for(i.s();!(r=i.n()).done;){var o=r.value;if(o.type!==TokenType.FREE_TEXT)if(secondsExtendedRegexp.test(o.value)){var s=o.value.length-3;a+=(e.seconds<10?"0":"")+Math.round(e.seconds*Math.pow(10,s))/Math.pow(10,s)}else switch(o.value.toLowerCase()){case"h":case"hh":a+=padLeft(e.hours,o.value.length),e.hours=0;break;case"[hh]":a+=padLeft(e.hours,o.value.length-2),e.hours=0;break;case"m":case"mm":a+=padLeft(e.minutes,o.value.length),e.minutes=0;break;case"[mm]":a+=padLeft(e.minutes+60*e.hours,o.value.length-2),e.minutes=0,e.hours=0;break;case"s":case"ss":a+=padLeft(e.seconds,o.value.length);break;default:return}else a+=o.value}}catch(e){i.e(e)}finally{i.f()}return a}}function defaultStringifyDateTime(e,t){var n=parseForDateTimeFormat(t);if(void 0!==n){for(var r=n.tokens,a="",i=!1,o=r.some((function(e){return e.type===TokenType.FORMAT&&("a/p"===e.value||"A/P"===e.value||"am/pm"===e.value||"AM/PM"===e.value)})),s=0;sa&&(i=stringSlice(i,0,a)),e?o+i:i+o)}},stringPad={start:createMethod(!1),end:createMethod(!0)},userAgent=engineUserAgent,stringPadWebkitBug=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(userAgent),$$g=_export,$padStart=stringPad.start,WEBKIT_BUG=stringPadWebkitBug;function _slicedToArray$i(e,t){return _arrayWithHoles$i(e)||_iterableToArrayLimit$i(e,t)||_unsupportedIterableToArray$u(e,t)||_nonIterableRest$i()}function _nonIterableRest$i(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray$u(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$u(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$u(e,t):void 0}}function _arrayLikeToArray$u(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);nPI))}sqrtpi(e,t){return this.runFunction(e.args,t,this.metadata("SQRTPI"),(e=>Math.sqrt(PI*e)))}} /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */$$g({target:"String",proto:!0,forced:WEBKIT_BUG},{padStart:function(e){return $padStart(this,e,arguments.length>1?arguments[1]:void 0)}});var _rl="length",_hd=function(e){return parseInt(e,16)},_pi=function(e){return parseInt(e,10)},_nm=function(e){return(e+"").replace(/\-/g,"")},_ss=function(e,t,n){return e.substr(t,n)},_cp=function(e){return e.codePointAt(0)-65};function extractTime(e){return 25===_nm(e)[_rl]?_hd(_ss(_nm(e),_hd("12"),_cp("F")))/(_hd(_ss(_nm(e),_cp("C"),_cp("Y")>>4))||1+(~~![][_rl]<<3)):0}function checkKeySchema(e){if((e=(e+"").replace(/\-/g,""))[_rl]!==_cp("Z"))return!1;var t=0;return[[0,_cp("G")+1],[_cp("H"),_cp("H")-1],[_cp("G")+_cp("H"),_cp("G")]].reduce((function(n,r,a){var i=_slicedToArray$i(r,2),o=i[0],s=i[1];return n|=(_pi("".concat(_pi(_hd(_ss.apply(void 0,[e].concat([t+o-(0===a?0:2),s+(a?2:0)])))+(_hd(_ss.apply(void 0,[e].concat([t+o+s,2])))+[]).padStart(2,"0"))))%97||2)>>1,t+=2,n}),_cp("A"))===[]+1>>1}function _slicedToArray$h(e,t){return _arrayWithHoles$h(e)||_iterableToArrayLimit$h(e,t)||_unsupportedIterableToArray$t(e,t)||_nonIterableRest$h()}function _nonIterableRest$h(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray$t(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$t(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$t(e,t):void 0}}function _arrayLikeToArray$t(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);ns?"expired":"valid"}else""!==e&&(t.template="invalid");return _notified||"valid"===t.template||(console.warn(consoleMessages[t.template](t.vars)),_notified=!0),t.template}function formatDate(e){var t=["January","February","March","April","May","June","July","August","September","October","November","December"][e.getMonth()],n=e.getDate(),r=e.getFullYear();return"".concat(t," ").concat(n,", ").concat(r)}function _createForOfIteratorHelper$m(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$s(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _slicedToArray$g(e,t){return _arrayWithHoles$g(e)||_iterableToArrayLimit$g(e,t)||_unsupportedIterableToArray$s(e,t)||_nonIterableRest$g()}function _nonIterableRest$g(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray$s(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$s(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$s(e,t):void 0}}function _arrayLikeToArray$s(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=0;--a){var i=this.tryEntries[a],o=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev=0;--r){var a=this.tryEntries[r];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),C(n),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:S(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),c}},e}function _classCallCheck$1a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1a(e,t){for(var n=0;n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$r(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$r(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$r(e,t):void 0}}function _arrayLikeToArray$r(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);nthis.columnsSpan.columnEnd)return e.shiftedByColumns(-this.columnsSpan.numberOfColumns)}if(this.columnsSpan.sheet===t.sheet&&this.columnsSpan.sheet!==n){if(e.isColumnAbsolute())return!1;if(t.colthis.columnsSpan.columnEnd)return e.shiftedByColumns(this.columnsSpan.numberOfColumns)}if(this.columnsSpan.sheet===t.sheet&&this.columnsSpan.sheet===n)if(e.isColumnAbsolute()){if(e.colthis.columnsSpan.columnEnd)return e.shiftedByColumns(-this.columnsSpan.numberOfColumns)}else{var a=e.toSimpleColumnAddress(t);if(a.colthis.columnsSpan.columnEnd)return e.shiftedByColumns(this.columnsSpan.numberOfColumns)}else if(a.col>this.columnsSpan.columnEnd){if(t.colthis.columnsSpan.columnEnd)return!1}}return ErrorType.REF}},{key:"fixNodeAddress",value:function(e){return this.columnsSpan.sheet===e.sheet&&this.columnsSpan.columnStart<=e.col?Object.assign(Object.assign({},e),{col:e.col-this.columnsSpan.numberOfColumns}):e}},{key:"transformRange",value:function(e,t,n){var r=absoluteSheetReference(e,n),a=e,i=t;if(this.columnsSpan.sheet===r){var o=e.toSimpleColumnAddress(n),s=t.toSimpleColumnAddress(n);if(this.columnsSpan.columnStart<=o.col&&this.columnsSpan.columnEnd>=s.col)return ErrorType.REF;o.col>=this.columnsSpan.columnStart&&o.col<=this.columnsSpan.columnEnd&&(a=e.shiftedByColumns(this.columnsSpan.columnEnd-o.col+1)),s.col>=this.columnsSpan.columnStart&&s.col<=this.columnsSpan.columnEnd&&(i=t.shiftedByColumns(-(s.col-this.columnsSpan.columnStart+1)))}var l=this.transformCellAddress(a,n),u=this.transformCellAddress(i,n);if(!1===l&&!1===u)return[a,i];if(l===ErrorType.REF||u===ErrorType.REF)throw Error("Cannot happen");return[l||a,u||i]}}]),n}(Transformer);function _typeof$R(e){return _typeof$R="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$R(e)}function _classCallCheck$12(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$12(e,t){for(var n=0;nthis.rowsSpan.rowEnd)return e.shiftedByRows(-this.rowsSpan.numberOfRows)}if(this.rowsSpan.sheet===t.sheet&&this.rowsSpan.sheet!==n){if(e.isRowAbsolute())return!1;if(t.rowthis.rowsSpan.rowEnd)return e.shiftedByRows(this.rowsSpan.numberOfRows)}if(this.rowsSpan.sheet===t.sheet&&this.rowsSpan.sheet===n)if(e.isRowAbsolute()){if(e.rowthis.rowsSpan.rowEnd)return e.shiftedByRows(-this.rowsSpan.numberOfRows)}else{var a=e.toSimpleRowAddress(t);if(a.rowthis.rowsSpan.rowEnd)return e.shiftedByRows(this.rowsSpan.numberOfRows)}else if(a.row>this.rowsSpan.rowEnd){if(t.rowthis.rowsSpan.rowEnd)return!1}}return ErrorType.REF}},{key:"transformCellRange",value:function(e,t,n){return this.transformRange(e,t,n)}},{key:"transformRowRange",value:function(e,t,n){return this.transformRange(e,t,n)}},{key:"transformColumnRange",value:function(e,t,n){throw Error("Not implemented")}},{key:"fixNodeAddress",value:function(e){return this.rowsSpan.sheet===e.sheet&&this.rowsSpan.rowStart<=e.row?Object.assign(Object.assign({},e),{row:e.row-this.rowsSpan.numberOfRows}):e}},{key:"transformRange",value:function(e,t,n){var r=absoluteSheetReference(e,n),a=e,i=t;if(this.rowsSpan.sheet===r){var o=e.toSimpleRowAddress(n),s=t.toSimpleRowAddress(n);if(this.rowsSpan.rowStart<=o.row&&this.rowsSpan.rowEnd>=s.row)return ErrorType.REF;o.row>=this.rowsSpan.rowStart&&o.row<=this.rowsSpan.rowEnd&&(a=e.shiftedByRows(this.rowsSpan.rowEnd-o.row+1)),s.row>=this.rowsSpan.rowStart&&s.row<=this.rowsSpan.rowEnd&&(i=t.shiftedByRows(-(s.row-this.rowsSpan.rowStart+1)))}var l=this.transformCellAddress(a,n),u=this.transformCellAddress(i,n);return!1===l&&!1===u?[a,i]:l===ErrorType.REF||u===ErrorType.REF?ErrorType.REF:[l||a,u||i]}}]),n}(Transformer);function _typeof$Q(e){return _typeof$Q="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$Q(e)}function _slicedToArray$e(e,t){return _arrayWithHoles$e(e)||_iterableToArrayLimit$e(e,t)||_unsupportedIterableToArray$q(e,t)||_nonIterableRest$e()}function _nonIterableRest$e(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArrayLimit$e(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,a,i=[],o=!0,s=!1;try{for(n=n.call(e);!(o=(r=n.next()).done)&&(i.push(r.value),!t||i.length!==t);o=!0);}catch(e){s=!0,a=e}finally{try{o||null==n.return||n.return()}finally{if(s)throw a}}return i}}function _arrayWithHoles$e(e){if(Array.isArray(e))return e}function _createForOfIteratorHelper$k(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$q(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$q(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$q(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$q(e,t):void 0}}function _arrayLikeToArray$q(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n{if(!e.hasOnlyNumbers()||!t.hasOnlyNumbers())return new CellError(ErrorType.VALUE,ErrorMessage.NumberRange);if(t.height()!==e.width())return new CellError(ErrorType.VALUE,ErrorMessage.ArrayDimensions);const n=arraySizeForMultiplication(e.size,t.size),r=this.createKernel((function(e,t,n){let r=0;for(let a=0;a{var r;return this.arraySizeForAst(e,new InterpreterState(t.formulaAddress,t.arraysFlag||null!==(r=null==n?void 0:n.arrayFunction)&&void 0!==r&&r))})),[a,i]=r;return arraySizeForMultiplication(a,i)}maxpool(e,t){return this.runFunction(e.args,t,this.metadata("MAXPOOL"),((e,t,n=t)=>{if(!e.hasOnlyNumbers())return new CellError(ErrorType.VALUE,ErrorMessage.NumberRange);const r=arraySizeForPoolFunction(e.size,t,n),a=this.createKernel((function(e,t,n){const r=this.thread.x*n,a=this.thread.y*n;let i=e[a][r];for(let n=0;n{if(!e.hasOnlyNumbers())return new CellError(ErrorType.VALUE,ErrorMessage.NumberRange);const r=arraySizeForPoolFunction(e.size,t,n),a=this.createKernel((function(e,t,n){const r=this.thread.x*n,a=this.thread.y*n;let i=e[a][r];for(let n=0;nn&&i++;if(t%2==0){if(i===o/2){c=n;break}i>o/2?l=n:u=n}else{if(i===(o-1)/2){c=n;break}i>(o-1)/2?l=n:u=n}}return c}),r)(e.rawNumbers(),t,n);return SimpleRangeValue.onlyNumbers(a)}))}maxpoolArraySize(e,t){if(e.args.length<2||e.args.length>3)return ArraySize.error();const n=this.metadata("MAXPOOL"),r=e.args.map((e=>{var r;return this.arraySizeForAst(e,new InterpreterState(t.formulaAddress,t.arraysFlag||null!==(r=null==n?void 0:n.arrayFunction)&&void 0!==r&&r))})),a=r[0],i=e.args[1];let s;s=i.type===AstNodeType.NUMBER?i.value:1;let o=s;if(3===e.args.length){const t=e.args[2];o=t.type===AstNodeType.NUMBER?t.value:1}return s>a.width||s>a.height||o>s||(a.width-s)%o!=0||(a.height-s)%o!=0?ArraySize.error():arraySizeForPoolFunction(a,s,o)}medianpoolArraySize(e,t){return this.maxpoolArraySize(e,t)}transpose(e,t){return this.runFunction(e.args,t,this.metadata("TRANSPOSE"),(e=>{const t=e.rawData(),n=e.size,r=[];for(let e=0;e{var r;return this.arraySizeForAst(e,new InterpreterState(t.formulaAddress,t.arraysFlag||null!==(r=null==n?void 0:n.arrayFunction)&&void 0!==r&&r))})),[a]=r;return new ArraySize(a.height,a.width)}createKernel(e,t){return function(...n){const r=[];for(let a=0;a0&&(n=a+1)}var l=t*n;return{height:n,width:t,fill:0===l?0:r/l}}function _toConsumableArray$8(e){return _arrayWithoutHoles$8(e)||_iterableToArray$8(e)||_unsupportedIterableToArray$p(e)||_nonIterableSpread$8()}function _nonIterableSpread$8(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray$8(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles$8(e){if(Array.isArray(e))return _arrayLikeToArray$p(e)}function _slicedToArray$d(e,t){return _arrayWithHoles$d(e)||_iterableToArrayLimit$d(e,t)||_unsupportedIterableToArray$p(e,t)||_nonIterableRest$d()}function _nonIterableRest$d(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArrayLimit$d(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,a,i=[],o=!0,s=!1;try{for(n=n.call(e);!(o=(r=n.next()).done)&&(i.push(r.value),!t||i.length!==t);o=!0);}catch(e){s=!0,a=e}finally{try{o||null==n.return||n.return()}finally{if(s)throw a}}return i}}function _arrayWithHoles$d(e){if(Array.isArray(e))return e}function _createForOfIteratorHelper$j(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$p(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$p(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$p(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$p(e,t):void 0}}function _arrayLikeToArray$p(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n0)this.setParsingErrorToCell(n.formula,o,e);else{var s=this.arraySizePredictor.checkArraySize(i,e);this.setFormulaToCell(e,s,a)}}else n instanceof CellContent.Empty?this.setCellEmpty(e):this.setValueToCell({parsedValue:n.value,rawValue:t},e);return r}},{key:"setSheetContent",value:function(e,t){this.clearSheet(e);for(var n=0;n=this.dependencyGraph.addressMapping.getHeight(t)}},{key:"getAndClearContentChanges",value:function(){var e=this.changes;return this.changes=ContentChanges.empty(),e}},{key:"forceApplyPostponedTransformations",value:function(){this.dependencyGraph.forceApplyPostponedTransformations()}},{key:"doRemoveRows",value:function(e){var t=this;if(!this.rowEffectivelyNotInSheet(e.rowStart,e.sheet)){var n,r=[],a=_createForOfIteratorHelper$j(this.dependencyGraph.entriesFromRowsSpan(e));try{for(a.s();!(n=a.n()).done;){var i=_slicedToArray$d(n.value,1)[0];r.push({address:i,cellType:this.getClipboardCell(i)})}}catch(e){a.e(e)}finally{a.f()}var o,s=this.dependencyGraph.removeRows(e),l=s.affectedArrays,u=s.contentChanges;return this.columnSearch.applyChanges(u.getChanges()),this.stats.measure(StatType.TRANSFORM_ASTS,(function(){var n=new RemoveRowsTransformer(e);n.performEagerTransformations(t.dependencyGraph,t.parser),o=t.lazilyTransformingAstService.addTransformation(n)})),this.rewriteAffectedArrays(l),{version:o,removedCells:r,rowFrom:e.rowStart,rowCount:e.numberOfRows}}}},{key:"doRemoveColumns",value:function(e){var t=this;if(!this.columnEffectivelyNotInSheet(e.columnStart,e.sheet)){var n,r=[],a=_createForOfIteratorHelper$j(this.dependencyGraph.entriesFromColumnsSpan(e));try{for(a.s();!(n=a.n()).done;){var i=_slicedToArray$d(n.value,1)[0];r.push({address:i,cellType:this.getClipboardCell(i)})}}catch(e){a.e(e)}finally{a.f()}var o,s=this.dependencyGraph.removeColumns(e),l=s.affectedArrays,u=s.contentChanges;return this.columnSearch.applyChanges(u.getChanges()),this.columnSearch.removeColumns(e),this.stats.measure(StatType.TRANSFORM_ASTS,(function(){var n=new RemoveColumnsTransformer(e);n.performEagerTransformations(t.dependencyGraph,t.parser),o=t.lazilyTransformingAstService.addTransformation(n)})),this.rewriteAffectedArrays(l),{version:o,removedCells:r,columnFrom:e.columnStart,columnCount:e.numberOfColumns}}}},{key:"doAddRows",value:function(e){var t=this;if(!this.rowEffectivelyNotInSheet(e.rowStart,e.sheet)){var n=this.dependencyGraph.addRows(e).affectedArrays;this.stats.measure(StatType.TRANSFORM_ASTS,(function(){var n=new AddRowsTransformer(e);n.performEagerTransformations(t.dependencyGraph,t.parser),t.lazilyTransformingAstService.addTransformation(n)})),this.rewriteAffectedArrays(n)}}},{key:"rewriteAffectedArrays",value:function(e){var t,n=_createForOfIteratorHelper$j(e.values());try{for(n.s();!(t=n.n()).done;){var r=t.value;if(!r.array.size.isRef){var a=r.getFormula(this.lazilyTransformingAstService),i=r.getAddress(this.lazilyTransformingAstService),o=this.parser.computeHashFromAst(a);this.setFormulaToCellFromCache(o,i)}}}catch(e){n.e(e)}finally{n.f()}}},{key:"doAddColumns",value:function(e){var t=this;if(!this.columnEffectivelyNotInSheet(e.columnStart,e.sheet)){var n=this.dependencyGraph.addColumns(e),r=n.affectedArrays,a=n.contentChanges;this.columnSearch.addColumns(e),this.columnSearch.applyChanges(a.getChanges()),this.stats.measure(StatType.TRANSFORM_ASTS,(function(){var n=new AddColumnsTransformer(e);n.performEagerTransformations(t.dependencyGraph,t.parser),t.lazilyTransformingAstService.addTransformation(n)})),this.rewriteAffectedArrays(r)}}},{key:"columnEffectivelyNotInSheet",value:function(e,t){return e>=this.dependencyGraph.addressMapping.getWidth(t)}},{key:"adjustNamedExpressionEdges",value:function(e,t,n){if(void 0!==n){var r,a=this.dependencyGraph.fetchCellOrCreateEmpty(e.address),i=this.namedExpressions.workbookNamedExpressionOrPlaceholder(t),o=this.dependencyGraph.fetchCellOrCreateEmpty(i.address),s=_createForOfIteratorHelper$j(this.dependencyGraph.graph.adjacentNodes(o));try{for(s.s();!(r=s.n()).done;){var l=r.value;if(l instanceof FormulaCellVertex&&l.getAddress(this.lazilyTransformingAstService).sheet===n){var u,c=l.getFormula(this.lazilyTransformingAstService),p=l.getAddress(this.lazilyTransformingAstService),d=this.parser.fetchCachedResultForAst(c).dependencies,m=_createForOfIteratorHelper$j(absolutizeDependencies(d,p));try{for(m.s();!(u=m.n()).done;){var f=u.value;f instanceof NamedExpressionDependency&&f.name.toLowerCase()===e.displayName.toLowerCase()&&(this.dependencyGraph.graph.removeEdge(o,l),this.dependencyGraph.graph.addEdge(a,l))}}catch(e){m.e(e)}finally{m.f()}}}}catch(e){s.e(e)}finally{s.f()}}}},{key:"storeNamedExpressionInCell",value:function(e,t){var n=this.cellContentParser.parse(t);if(n instanceof CellContent.Formula){var r=this.parser.parse(n.formula,simpleCellAddress(-1,0,0));if(doesContainRelativeReferences(r.ast))throw new NoRelativeAddressesAllowedError;var a=r.ast,i=r.hasVolatileFunction,o=r.hasStructuralChangeFunction,s=r.dependencies;this.dependencyGraph.setFormulaToCell(e,a,absolutizeDependencies(s,e),ArraySize.scalar(),i,o)}else n instanceof CellContent.Empty?this.setCellEmpty(e):this.setValueToCell({parsedValue:n.value,rawValue:t},e)}},{key:"updateNamedExpressionsForMovedCells",value:function(e,t,n,r){if(e.sheet===r.sheet)return[];var a,i=[],o=_createForOfIteratorHelper$j(AbsoluteCellRange.spanFrom(r,t,n).addresses(this.dependencyGraph));try{for(o.s();!(a=o.n()).done;){var s=a.value,l=this.addressMapping.fetchCell(s);if(l instanceof FormulaCellVertex&&s.sheet!==e.sheet){var u=l.getFormula(this.lazilyTransformingAstService),c=this.parser.fetchCachedResultForAst(u).dependencies;i.push.apply(i,_toConsumableArray$8(this.updateNamedExpressionsForTargetAddress(e.sheet,s,c)))}}}catch(e){o.e(e)}finally{o.f()}return i}},{key:"updateNamedExpressionsForTargetAddress",value:function(e,t,n){if(e===t.sheet)return[];var r,a=[],i=this.addressMapping.fetchCell(t),o=_createForOfIteratorHelper$j(absolutizeDependencies(n,t));try{for(o.s();!(r=o.n()).done;){var s=r.value;if(s instanceof NamedExpressionDependency){var l=s.name,u=this.dependencyGraph.fetchNamedExpressionVertex(l,e),c=this.namedExpressions.isExpressionInScope(l,t.sheet)?this.dependencyGraph.fetchNamedExpressionVertex(l,t.sheet):this.copyOrFetchGlobalNamedExpressionVertex(l,u,a);c!==u&&(this.dependencyGraph.graph.softRemoveEdge(u,i),this.dependencyGraph.graph.addEdge(c,i))}}}catch(e){o.e(e)}finally{o.f()}return a}},{key:"allocateNamedExpressionAddressSpace",value:function(){this.dependencyGraph.addressMapping.addSheet(-1,new SparseStrategy(0,0))}},{key:"copyOrFetchGlobalNamedExpressionVertex",value:function(e,t,n){var r=this.namedExpressions.namedExpressionForScope(e);if(void 0===r)if(r=this.namedExpressions.addNamedExpression(e),n.push(r.normalizeExpressionName()),t instanceof FormulaCellVertex){var a=this.parser.fetchCachedResultForAst(t.getFormula(this.lazilyTransformingAstService)),i=a.ast,o=a.hasVolatileFunction,s=a.hasStructuralChangeFunction,l=a.dependencies;this.dependencyGraph.setFormulaToCell(r.address,i,absolutizeDependencies(l,r.address),ArraySize.scalar(),o,s)}else t instanceof EmptyCellVertex?this.setCellEmpty(r.address):t instanceof ValueCellVertex&&this.setValueToCell(t.getValues(),r.address);return this.dependencyGraph.fetchCellOrCreateEmpty(r.address)}}]),e}();function normalizeRemovedIndexes(e){if(e.length<=1)return e;for(var t=_toConsumableArray$8(e).sort((function(e,t){return _slicedToArray$d(e,1)[0]-_slicedToArray$d(t,1)[0]})),n=t.reduce((function(e,t){var n=_slicedToArray$d(t,2),r=n[0],a=n[1],i=e[e.length-1],o=i[0]+i[1];return r<=o?i[1]+=Math.max(0,a-(o-r)):e.push([r,a]),e}),[t[0]]),r=0,a=0;a0}function isRowOrColumnRange(e,t,n){return 0===e.row&&isPositiveInteger$1(t)&&n===Number.POSITIVE_INFINITY||0===e.col&&isPositiveInteger$1(n)&&t===Number.POSITIVE_INFINITY}function _typeof$P(e){return _typeof$P="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$P(e)}function _slicedToArray$c(e,t){return _arrayWithHoles$c(e)||_iterableToArrayLimit$c(e,t)||_unsupportedIterableToArray$o(e,t)||_nonIterableRest$c()}function _nonIterableRest$c(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArrayLimit$c(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,a,i=[],o=!0,s=!1;try{for(n=n.call(e);!(o=(r=n.next()).done)&&(i.push(r.value),!t||i.length!==t);o=!0);}catch(e){s=!0,a=e}finally{try{o||null==n.return||n.return()}finally{if(s)throw a}}return i}}function _arrayWithHoles$c(e){if(Array.isArray(e))return e}function _createForOfIteratorHelper$i(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$o(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$o(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$o(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$o(e,t):void 0}}function _arrayLikeToArray$o(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=0;--a){var i=this.tryEntries[a],o=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev=0;--r){var a=this.tryEntries[r];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),C(n),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:S(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),c}},e}function _inherits$K(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&_setPrototypeOf$K(e,t)}function _setPrototypeOf$K(e,t){return _setPrototypeOf$K=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},_setPrototypeOf$K(e,t)}function _createSuper$K(e){var t=_isNativeReflectConstruct$K();return function(){var n,r=_getPrototypeOf$K(e);if(t){var a=_getPrototypeOf$K(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return _possibleConstructorReturn$K(this,n)}}function _possibleConstructorReturn$K(e,t){if(t&&("object"===_typeof$P(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized$K(e)}function _assertThisInitialized$K(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _isNativeReflectConstruct$K(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function _getPrototypeOf$K(e){return _getPrototypeOf$K=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},_getPrototypeOf$K(e)}function _defineProperties$$(e,t){for(var n=0;ns.targetRow?s.startRow+s.numberOfRows:s.startRow,s}return _createClass$$(n,[{key:"doUndo",value:function(e){e.undoMoveRows(this)}},{key:"doRedo",value:function(e){e.redoMoveRows(this)}}]),n}(BaseUndoEntry),MoveColumnsUndoEntry=function(e){_inherits$K(n,e);var t=_createSuper$K(n);function n(e,r,a,i,o){var s;return _classCallCheck$$(this,n),(s=t.call(this)).sheet=e,s.startColumn=r,s.numberOfColumns=a,s.targetColumn=i,s.version=o,s.undoStart=s.startColumns.targetColumn?s.startColumn+s.numberOfColumns:s.startColumn,s}return _createClass$$(n,[{key:"doUndo",value:function(e){e.undoMoveColumns(this)}},{key:"doRedo",value:function(e){e.redoMoveColumns(this)}}]),n}(BaseUndoEntry),AddColumnsUndoEntry=function(e){_inherits$K(n,e);var t=_createSuper$K(n);function n(e){var r;return _classCallCheck$$(this,n),(r=t.call(this)).command=e,r}return _createClass$$(n,[{key:"doUndo",value:function(e){e.undoAddColumns(this)}},{key:"doRedo",value:function(e){e.redoAddColumns(this)}}]),n}(BaseUndoEntry),RemoveColumnsUndoEntry=function(e){_inherits$K(n,e);var t=_createSuper$K(n);function n(e,r){var a;return _classCallCheck$$(this,n),(a=t.call(this)).command=e,a.columnsRemovals=r,a}return _createClass$$(n,[{key:"doUndo",value:function(e){e.undoRemoveColumns(this)}},{key:"doRedo",value:function(e){e.redoRemoveColumns(this)}}]),n}(BaseUndoEntry),AddSheetUndoEntry=function(e){_inherits$K(n,e);var t=_createSuper$K(n);function n(e){var r;return _classCallCheck$$(this,n),(r=t.call(this)).sheetName=e,r}return _createClass$$(n,[{key:"doUndo",value:function(e){e.undoAddSheet(this)}},{key:"doRedo",value:function(e){e.redoAddSheet(this)}}]),n}(BaseUndoEntry),RemoveSheetUndoEntry=function(e){_inherits$K(n,e);var t=_createSuper$K(n);function n(e,r,a,i,o){var s;return _classCallCheck$$(this,n),(s=t.call(this)).sheetName=e,s.sheetId=r,s.oldSheetContent=a,s.scopedNamedExpressions=i,s.version=o,s}return _createClass$$(n,[{key:"doUndo",value:function(e){e.undoRemoveSheet(this)}},{key:"doRedo",value:function(e){e.redoRemoveSheet(this)}}]),n}(BaseUndoEntry),RenameSheetUndoEntry=function(e){_inherits$K(n,e);var t=_createSuper$K(n);function n(e,r,a){var i;return _classCallCheck$$(this,n),(i=t.call(this)).sheetId=e,i.oldName=r,i.newName=a,i}return _createClass$$(n,[{key:"doUndo",value:function(e){e.undoRenameSheet(this)}},{key:"doRedo",value:function(e){e.redoRenameSheet(this)}}]),n}(BaseUndoEntry),ClearSheetUndoEntry=function(e){_inherits$K(n,e);var t=_createSuper$K(n);function n(e,r){var a;return _classCallCheck$$(this,n),(a=t.call(this)).sheetId=e,a.oldSheetContent=r,a}return _createClass$$(n,[{key:"doUndo",value:function(e){e.undoClearSheet(this)}},{key:"doRedo",value:function(e){e.redoClearSheet(this)}}]),n}(BaseUndoEntry),SetCellContentsUndoEntry=function(e){_inherits$K(n,e);var t=_createSuper$K(n);function n(e){var r;return _classCallCheck$$(this,n),(r=t.call(this)).cellContents=e,r}return _createClass$$(n,[{key:"doUndo",value:function(e){e.undoSetCellContents(this)}},{key:"doRedo",value:function(e){e.redoSetCellContents(this)}}]),n}(BaseUndoEntry),PasteUndoEntry=function(e){_inherits$K(n,e);var t=_createSuper$K(n);function n(e,r,a,i){var o;return _classCallCheck$$(this,n),(o=t.call(this)).targetLeftCorner=e,o.oldContent=r,o.newContent=a,o.addedGlobalNamedExpressions=i,o}return _createClass$$(n,[{key:"doUndo",value:function(e){e.undoPaste(this)}},{key:"doRedo",value:function(e){e.redoPaste(this)}}]),n}(BaseUndoEntry),AddNamedExpressionUndoEntry=function(e){_inherits$K(n,e);var t=_createSuper$K(n);function n(e,r,a,i){var o;return _classCallCheck$$(this,n),(o=t.call(this)).name=e,o.newContent=r,o.scope=a,o.options=i,o}return _createClass$$(n,[{key:"doUndo",value:function(e){e.undoAddNamedExpression(this)}},{key:"doRedo",value:function(e){e.redoAddNamedExpression(this)}}]),n}(BaseUndoEntry),RemoveNamedExpressionUndoEntry=function(e){_inherits$K(n,e);var t=_createSuper$K(n);function n(e,r,a){var i;return _classCallCheck$$(this,n),(i=t.call(this)).namedExpression=e,i.content=r,i.scope=a,i}return _createClass$$(n,[{key:"doUndo",value:function(e){e.undoRemoveNamedExpression(this)}},{key:"doRedo",value:function(e){e.redoRemoveNamedExpression(this)}}]),n}(BaseUndoEntry),ChangeNamedExpressionUndoEntry=function(e){_inherits$K(n,e);var t=_createSuper$K(n);function n(e,r,a,i,o){var s;return _classCallCheck$$(this,n),(s=t.call(this)).namedExpression=e,s.newContent=r,s.oldContent=a,s.scope=i,s.options=o,s}return _createClass$$(n,[{key:"doUndo",value:function(e){e.undoChangeNamedExpression(this)}},{key:"doRedo",value:function(e){e.redoChangeNamedExpression(this)}}]),n}(BaseUndoEntry),BatchUndoEntry=function(e){_inherits$K(n,e);var t=_createSuper$K(n);function n(){var e;return _classCallCheck$$(this,n),(e=t.apply(this,arguments)).operations=[],e}return _createClass$$(n,[{key:"add",value:function(e){this.operations.push(e)}},{key:"reversedOperations",value:_regeneratorRuntime$4().mark((function e(){var t;return _regeneratorRuntime$4().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=this.operations.length-1;case 1:if(!(t>=0)){e.next=7;break}return e.next=4,this.operations[t];case 4:t--,e.next=1;break;case 7:case"end":return e.stop()}}),e,this)}))},{key:"doUndo",value:function(e){e.undoBatch(this)}},{key:"doRedo",value:function(e){e.redoBatch(this)}}]),n}(BaseUndoEntry),UndoRedo=function(){function e(t,n){_classCallCheck$$(this,e),this.operations=n,this.oldData=new Map,this.undoStack=[],this.redoStack=[],this.undoLimit=t.undoLimit}return _createClass$$(e,[{key:"saveOperation",value:function(e){void 0!==this.batchUndoEntry?this.batchUndoEntry.add(e):this.addUndoEntry(e)}},{key:"beginBatchMode",value:function(){this.batchUndoEntry=new BatchUndoEntry}},{key:"commitBatchMode",value:function(){if(void 0===this.batchUndoEntry)throw"Batch mode wasn't started";this.addUndoEntry(this.batchUndoEntry),this.batchUndoEntry=void 0}},{key:"storeDataForVersion",value:function(e,t,n){this.oldData.has(e)||this.oldData.set(e,[]),this.oldData.get(e).push([t,n])}},{key:"clearRedoStack",value:function(){this.redoStack=[]}},{key:"clearUndoStack",value:function(){this.undoStack=[]}},{key:"isUndoStackEmpty",value:function(){return 0===this.undoStack.length}},{key:"isRedoStackEmpty",value:function(){return 0===this.redoStack.length}},{key:"undo",value:function(){var e=this.undoStack.pop();if(!e)throw"Attempted to undo without operation on stack";this.undoEntry(e),this.redoStack.push(e)}},{key:"undoBatch",value:function(e){var t,n=_createForOfIteratorHelper$i(e.reversedOperations());try{for(n.s();!(t=n.n()).done;){var r=t.value;this.undoEntry(r)}}catch(e){n.e(e)}finally{n.f()}}},{key:"undoRemoveRows",value:function(e){this.operations.forceApplyPostponedTransformations();for(var t=e.command.sheet,n=e.rowsRemovals,r=n.length-1;r>=0;--r){var a=n[r];this.operations.addRows(new AddRowsCommand(t,[[a.rowFrom,a.rowCount]]));var i,o=_createForOfIteratorHelper$i(a.removedCells);try{for(o.s();!(i=o.n()).done;){var s=i.value,l=s.address,u=s.cellType;this.operations.restoreCell(l,u)}}catch(e){o.e(e)}finally{o.f()}this.restoreOldDataFromVersion(a.version-1)}}},{key:"undoRemoveColumns",value:function(e){this.operations.forceApplyPostponedTransformations();for(var t=e.command.sheet,n=e.columnsRemovals,r=n.length-1;r>=0;--r){var a=n[r];this.operations.addColumns(new AddColumnsCommand(t,[[a.columnFrom,a.columnCount]]));var i,o=_createForOfIteratorHelper$i(a.removedCells);try{for(o.s();!(i=o.n()).done;){var s=i.value,l=s.address,u=s.cellType;this.operations.restoreCell(l,u)}}catch(e){o.e(e)}finally{o.f()}this.restoreOldDataFromVersion(a.version-1)}}},{key:"undoAddRows",value:function(e){for(var t=e.command.rowsSpans(),n=t.length-1;n>=0;--n){var r=t[n];this.operations.removeRows(new RemoveRowsCommand(e.command.sheet,[[r.rowStart,r.numberOfRows]]))}}},{key:"undoAddColumns",value:function(e){for(var t=e.command.columnsSpans(),n=t.length-1;n>=0;--n){var r=t[n];this.operations.removeColumns(new RemoveColumnsCommand(e.command.sheet,[[r.columnStart,r.numberOfColumns]]))}}},{key:"undoSetCellContents",value:function(e){var t,n=_createForOfIteratorHelper$i(e.cellContents);try{for(n.s();!(t=n.n()).done;){var r=t.value,a=r.address,i=_slicedToArray$c(r.oldContent,2),o=i[0],s=i[1];equalSimpleCellAddress(a,o)||this.operations.setCellEmpty(a),this.operations.restoreCell(o,s)}}catch(e){n.e(e)}finally{n.f()}}},{key:"undoPaste",value:function(e){this.restoreOperationOldContent(e.oldContent);var t,n=_createForOfIteratorHelper$i(e.addedGlobalNamedExpressions);try{for(n.s();!(t=n.n()).done;){var r=t.value;this.operations.removeNamedExpression(r)}}catch(e){n.e(e)}finally{n.f()}}},{key:"undoMoveRows",value:function(e){var t=e.sheet;this.operations.moveRows(t,e.undoStart,e.numberOfRows,e.undoEnd),this.restoreOldDataFromVersion(e.version-1)}},{key:"undoMoveColumns",value:function(e){var t=e.sheet;this.operations.moveColumns(t,e.undoStart,e.numberOfColumns,e.undoEnd),this.restoreOldDataFromVersion(e.version-1)}},{key:"undoMoveCells",value:function(e){this.operations.forceApplyPostponedTransformations(),this.operations.moveCells(e.destinationLeftCorner,e.width,e.height,e.sourceLeftCorner),this.restoreOperationOldContent(e.overwrittenCellsData),this.restoreOldDataFromVersion(e.version-1);var t,n=_createForOfIteratorHelper$i(e.addedGlobalNamedExpressions);try{for(n.s();!(t=n.n()).done;){var r=t.value;this.operations.removeNamedExpression(r)}}catch(e){n.e(e)}finally{n.f()}}},{key:"undoAddSheet",value:function(e){var t=e.sheetName;this.operations.removeSheetByName(t)}},{key:"undoRemoveSheet",value:function(e){this.operations.forceApplyPostponedTransformations();var t=e.oldSheetContent,n=e.sheetId;this.operations.addSheet(e.sheetName);for(var r=0;r=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$n(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$n(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$n(e,t):void 0}}function _arrayLikeToArray$n(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n1?t-1:0),r=1;r1?t-1:0),r=1;r1?t-1:0),r=1;r1?t-1:0),r=1;r1?n-1:0),a=1;athis.maxRows)throw new SheetSizeLimitExceededError;for(var o=0,s=r;o1?t-1:0),r=1;r1?n-1:0),a=1;athis.maxColumns)throw new SheetSizeLimitExceededError;for(var o=0,s=r;o1?t-1:0),r=1;r=t)throw new InvalidArgumentsError("a valid range of rows to move.");var o=this.dependencyGraph.getSheetWidth(e),s=AbsoluteCellRange.spanFrom(a,o,n);if(this.dependencyGraph.arrayMapping.isFormulaArrayInRange(s))throw new SourceLocationHasArrayError;if(r>0&&this.dependencyGraph.arrayMapping.isFormulaArrayInAllRows(RowsSpan.fromNumberOfRows(e,r-1,2)))throw new TargetLocationHasArrayError}},{key:"ensureItIsPossibleToMoveColumns",value:function(e,t,n,r){this.ensureItIsPossibleToAddColumns(e,[r,n]);var a=simpleCellAddress(e,t,0),i=simpleCellAddress(e,r,0);if(!this.sheetMapping.hasSheetWithId(e)||invalidSimpleCellAddress(a)||invalidSimpleCellAddress(i)||!isPositiveInteger(n)||r<=t+n&&r>=t)throw new InvalidArgumentsError("a valid range of columns to move.");var o=this.dependencyGraph.getSheetHeight(e),s=AbsoluteCellRange.spanFrom(a,n,o);if(this.dependencyGraph.arrayMapping.isFormulaArrayInRange(s))throw new SourceLocationHasArrayError;if(r>0&&this.dependencyGraph.arrayMapping.isFormulaArrayInAllColumns(ColumnsSpan.fromNumberOfColumns(e,r-1,2)))throw new TargetLocationHasArrayError}},{key:"ensureItIsPossibleToAddSheet",value:function(e){if(this.sheetMapping.hasSheetWithName(e))throw new SheetNameAlreadyTakenError(e)}},{key:"ensureItIsPossibleToRenameSheet",value:function(e,t){if(!this.sheetMapping.hasSheetWithId(e))throw new NoSheetWithIdError(e);var n=this.sheetMapping.get(t);if(void 0!==n&&n!==e)throw new SheetNameAlreadyTakenError(t)}},{key:"ensureItIsPossibleToChangeContent",value:function(e){if(invalidSimpleCellAddress(e))throw new InvalidAddressError(e);if(!this.sheetMapping.hasSheetWithId(e.sheet))throw new NoSheetWithIdError(e.sheet)}},{key:"ensureItIsPossibleToChangeCellContents",value:function(e,t){var n=findBoundaries(t),r=AbsoluteCellRange.spanFrom(e,n.width,n.height);this.ensureRangeInSizeLimits(r);var a,i=_createForOfIteratorHelper$h(r.addresses(this.dependencyGraph));try{for(i.s();!(a=i.n()).done;){var o=a.value;this.ensureItIsPossibleToChangeContent(o)}}catch(e){i.e(e)}finally{i.f()}}},{key:"ensureItIsPossibleToChangeSheetContents",value:function(e,t){var n=findBoundaries(t),r=AbsoluteCellRange.spanFrom(simpleCellAddress(e,0,0),n.width,n.height);this.ensureRangeInSizeLimits(r)}},{key:"ensureRangeInSizeLimits",value:function(e){if(e.exceedsSheetSizeLimits(this.maxColumns,this.maxRows))throw new SheetSizeLimitExceededError}},{key:"isThereSomethingToUndo",value:function(){return!this.undoRedo.isUndoStackEmpty()}},{key:"isThereSomethingToRedo",value:function(){return!this.undoRedo.isRedoStackEmpty()}},{key:"getAndClearContentChanges",value:function(){return this.operations.getAndClearContentChanges()}},{key:"ensureScopeIdIsValid",value:function(e){if(void 0!==e&&!this.sheetMapping.hasSheetWithId(e))throw new NoSheetWithIdError(e)}},{key:"validateRowOrColumnMapping",value:function(e,t,n){for(var r="row"===n?this.dependencyGraph.getSheetHeight(e):this.dependencyGraph.getSheetWidth(e),a=t.map((function(e){var t=_slicedToArray$b(e,2),n=t[0];return t[1],n})).sort((function(e,t){return e-t})),i=t.map((function(e){var t=_slicedToArray$b(e,2);return t[0],t[1]})).sort((function(e,t){return e-t})),o=0;o=r)throw new InvalidArgumentsError("".concat(n," numbers to be nonnegative integers and less than sheet ").concat("row"===n?"height":"width","."));if(a[o]===a[o+1])throw new InvalidArgumentsError("source ".concat(n," numbers to be unique."));if(a[o]!==i[o])throw new InvalidArgumentsError("target ".concat(n," numbers to be permutation of source ").concat(n," numbers."))}}},{key:"ensureNamedExpressionNameIsValid",value:function(e,t){if(!this.namedExpressions.isNameValid(e))throw new NamedExpressionNameIsInvalidError(e);if(!this.namedExpressions.isNameAvailable(e,t))throw new NamedExpressionNameIsAlreadyTakenError(e)}},{key:"ensureNamedExpressionIsValid",value:function(e){var t=this.cellContentParser.parse(e);if(t instanceof CellContent.Formula){var n=this.parser.parse(t.formula,simpleCellAddress(-1,0,0));if(doesContainRelativeReferences(n.ast))throw new NoRelativeAddressesAllowedError}}}]),e}();function isPositiveInteger(e){return Number.isInteger(e)&&e>0}function isNonnegativeInteger(e){return Number.isInteger(e)&&e>=0}function _createForOfIteratorHelper$g(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$m(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$m(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$m(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$m(e,t):void 0}}function _arrayLikeToArray$m(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$l(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$l(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$l(e,t):void 0}}function _arrayLikeToArray$l(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n0){t.shrinkArrayIfNeeded(i);var c=new ParsingErrorVertex(u.errors,l.formula);t.dependencyGraph.addVertex(i,c)}else{t.shrinkArrayIfNeeded(i);var p=t.arraySizePredictor.checkArraySize(u.ast,i);if(p.isScalar()){var d=new FormulaCellVertex(u.ast,i,0);n.set(d,absolutizeDependencies(u.dependencies,i)),t.dependencyGraph.addVertex(i,d),u.hasVolatileFunction&&t.dependencyGraph.markAsVolatile(d),u.hasStructuralChangeFunction&&t.dependencyGraph.markAsDependentOnStructureChange(d)}else{var m=new ArrayVertex(u.ast,i,new ArraySize(p.width,p.height));n.set(m,absolutizeDependencies(u.dependencies,i)),t.dependencyGraph.addArrayVertex(i,m)}}}else if(l instanceof CellContent.Empty);else{t.shrinkArrayIfNeeded(i);var f=new ValueCellVertex(l.value,r);t.columnIndex.add(getRawValue(l.value),i),t.dependencyGraph.addVertex(i,f)}},u=0;u1?arguments[1]:void 0)}}),addToUnscopables$1(FIND);var LICENSE_STATUS_MAP=new Map([["gpl-v3",1],["missing",2],["invalid",3],["expired",4]]),VersionPlugin=function(e){_inherits$J(n,e);var t=_createSuper$J(n);function n(){return _classCallCheck$W(this,n),t.apply(this,arguments)}return _createClass$W(n,[{key:"version",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("VERSION"),(function(){var e,t=n.config,r=t.licenseKeyValidityState,a=t.licenseKey;return LICENSE_STATUS_MAP.has(a)?e=LICENSE_STATUS_MAP.get(a):LICENSE_STATUS_MAP.has(r)?e=LICENSE_STATUS_MAP.get(r):"valid"===r&&(e=a.slice(-5)),"HyperFormula v".concat(HyperFormula.version,", ").concat(e)}))}}]),n}(FunctionPlugin);function _typeof$N(e){return _typeof$N="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$N(e)}function _regeneratorRuntime$3(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */_regeneratorRuntime$3=function(){return e};var e={},t=Object.prototype,n=t.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},a=r.iterator||"@@iterator",i=r.asyncIterator||"@@asyncIterator",o=r.toStringTag||"@@toStringTag";function s(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{s({},"")}catch(e){s=function(e,t,n){return e[t]=n}}function l(e,t,n,r){var a=t&&t.prototype instanceof p?t:p,i=Object.create(a.prototype),o=new A(r||[]);return i._invoke=function(e,t,n){var r="suspendedStart";return function(a,i){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===a)throw i;return x()}for(n.method=a,n.arg=i;;){var o=n.delegate;if(o){var s=T(o,n);if(s){if(s===c)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var l=u(e,t,n);if("normal"===l.type){if(r=n.done?"completed":"suspendedYield",l.arg===c)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(r="completed",n.method="throw",n.arg=l.arg)}}}(e,n,o),i}function u(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}e.wrap=l;var c={};function p(){}function d(){}function m(){}var f={};s(f,a,(function(){return this}));var h=Object.getPrototypeOf,y=h&&h(h(S([])));y&&y!==t&&n.call(y,a)&&(f=y);var b=m.prototype=p.prototype=Object.create(f);function g(e){["next","throw","return"].forEach((function(t){s(e,t,(function(e){return this._invoke(t,e)}))}))}function v(e,t){function r(a,i,o,s){var l=u(e[a],e,i);if("throw"!==l.type){var c=l.arg,p=c.value;return p&&"object"==_typeof$N(p)&&n.call(p,"__await")?t.resolve(p.__await).then((function(e){r("next",e,o,s)}),(function(e){r("throw",e,o,s)})):t.resolve(p).then((function(e){c.value=e,o(c)}),(function(e){return r("throw",e,o,s)}))}s(l.arg)}var a;this._invoke=function(e,n){function i(){return new t((function(t,a){r(e,n,t,a)}))}return a=a?a.then(i,i):i()}}function T(e,t){var n=e.iterator[t.method];if(void 0===n){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,T(e,t),"throw"===t.method))return c;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return c}var r=u(n,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,c;var a=r.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,c):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,c)}function N(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function C(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function A(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(N,this),this.reset(!0)}function S(e){if(e){var t=e[a];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,i=function t(){for(;++r=0;--a){var i=this.tryEntries[a],o=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev=0;--r){var a=this.tryEntries[r];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),C(n),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:S(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),c}},e}function _toConsumableArray$7(e){return _arrayWithoutHoles$7(e)||_iterableToArray$7(e)||_unsupportedIterableToArray$k(e)||_nonIterableSpread$7()}function _nonIterableSpread$7(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray$7(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles$7(e){if(Array.isArray(e))return _arrayLikeToArray$k(e)}function _slicedToArray$9(e,t){return _arrayWithHoles$9(e)||_iterableToArrayLimit$9(e,t)||_unsupportedIterableToArray$k(e,t)||_nonIterableRest$9()}function _nonIterableRest$9(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArrayLimit$9(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,a,i=[],o=!0,s=!1;try{for(n=n.call(e);!(o=(r=n.next()).done)&&(i.push(r.value),!t||i.length!==t);o=!0);}catch(e){s=!0,a=e}finally{try{o||null==n.return||n.return()}finally{if(s)throw a}}return i}}function _arrayWithHoles$9(e){if(Array.isArray(e))return e}function _createForOfIteratorHelper$e(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$k(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$k(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$k(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$k(e,t):void 0}}function _arrayLikeToArray$k(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n0){this.instancePlugins=new Map;var r,a=_createForOfIteratorHelper$e(t.functionPlugins);try{for(a.s();!(r=a.n()).done;){var i=r.value;e.loadPluginFunctions(i,this.instancePlugins)}}catch(e){a.e(e)}finally{a.f()}}else this.instancePlugins=new Map(e.plugins);var o,s=_createForOfIteratorHelper$e(e.protectedFunctions());try{for(s.s();!(o=s.n()).done;){var l=_slicedToArray$9(o.value,2),u=l[0],c=l[1];e.loadFunctionUnprotected(c,u,this.instancePlugins)}}catch(e){s.e(e)}finally{s.f()}var p,d=_createForOfIteratorHelper$e(this.instancePlugins.entries());try{for(d.s();!(p=d.n()).done;){var m=_slicedToArray$9(p.value,2),f=m[0],h=m[1];this.categorizeFunction(f,validateAndReturnMetadataFromName(f,h))}}catch(e){d.e(e)}finally{d.f()}}return _createClass$V(e,[{key:"initializePlugins",value:function(e){var t,n=this,r=[],a=_createForOfIteratorHelper$e(this.instancePlugins.entries());try{var i=function(){var a=_slicedToArray$9(t.value,2),i=a[0],o=a[1],s=r.find((function(e){return e instanceof o}));void 0===s&&(s=new o(e),r.push(s));var l=validateAndReturnMetadataFromName(i,o),u=l.method;n.functions.set(i,[u,s]);var c=l.arraySizeMethod;void 0!==c&&n.arraySizeFunctions.set(i,[c,s])};for(a.s();!(t=a.n()).done;)i()}catch(e){a.e(e)}finally{a.f()}}},{key:"getFunctionPlugin",value:function(t){if(!e.functionIsProtected(t))return this.instancePlugins.get(t)}},{key:"getFunction",value:function(e){var t=this.functions.get(e);if(void 0!==t&&this.config.translationPackage.isFunctionTranslated(e)){var n=_slicedToArray$9(t,2),r=n[0],a=n[1];return function(e,t){return a[r](e,t)}}}},{key:"getArraySizeFunction",value:function(e){var t=this.arraySizeFunctions.get(e);if(void 0!==t&&this.config.translationPackage.isFunctionTranslated(e)){var n=_slicedToArray$9(t,2),r=n[0],a=n[1];return function(e,t){return a[r](e,t)}}}},{key:"getMetadata",value:function(e){return this.functionsMetadata.get(e)}},{key:"getPlugins",value:function(){var t,n=new Set,r=_createForOfIteratorHelper$e(this.instancePlugins);try{for(r.s();!(t=r.n()).done;){var a=_slicedToArray$9(t.value,2),i=a[0],o=a[1];e.functionIsProtected(i)||n.add(o)}}catch(e){r.e(e)}finally{r.f()}return Array.from(n)}},{key:"getRegisteredFunctionIds",value:function(){return Array.from(this.functions.keys())}},{key:"categorizeFunction",value:function(e,t){t.isVolatile&&this.volatileFunctions.add(e),t.arrayFunction&&this.arrayFunctions.add(e),t.doesNotNeedArgumentsToBeComputed&&this.functionsWhichDoesNotNeedArgumentsToBeComputed.add(e),t.isDependentOnSheetStructureChange&&this.structuralChangeFunctions.add(e),this.functionsMetadata.set(e,t)}}],[{key:"registerFunctionPlugin",value:function(e,t){this.loadPluginFunctions(e,this.plugins),void 0!==t&&this.loadTranslations(t)}},{key:"registerFunction",value:function(e,t,n){this.loadPluginFunction(t,e,this.plugins),void 0!==n&&this.loadTranslations(n)}},{key:"unregisterFunction",value:function(e){if(this.functionIsProtected(e))throw ProtectedFunctionError.cannotUnregisterFunctionWithId(e);this.plugins.delete(e)}},{key:"unregisterFunctionPlugin",value:function(e){var t,n=_createForOfIteratorHelper$e(this.protectedPlugins());try{for(n.s();!(t=n.n()).done;){if(t.value===e)throw ProtectedFunctionError.cannotUnregisterProtectedPlugin()}}catch(e){n.e(e)}finally{n.f()}var r,a=_createForOfIteratorHelper$e(this.plugins.entries());try{for(a.s();!(r=a.n()).done;){var i=_slicedToArray$9(r.value,2),o=i[0];i[1]===e&&this.plugins.delete(o)}}catch(e){a.e(e)}finally{a.f()}}},{key:"unregisterAll",value:function(){this.plugins.clear()}},{key:"getRegisteredFunctionIds",value:function(){return[].concat(_toConsumableArray$7(Array.from(this.plugins.keys())),_toConsumableArray$7(Array.from(this._protectedPlugins.keys())))}},{key:"getPlugins",value:function(){return Array.from(new Set(this.plugins.values()).values())}},{key:"getFunctionPlugin",value:function(e){return this.functionIsProtected(e)?void 0:this.plugins.get(e)}},{key:"functionIsProtected",value:function(e){return this._protectedPlugins.has(e)}},{key:"loadTranslations",value:function(e){var t=new Set(HyperFormula.getRegisteredLanguagesCodes());Object.keys(e).forEach((function(n){t.has(n)&&HyperFormula.getLanguage(n).extendFunctions(e[n])}))}},{key:"loadPluginFunctions",value:function(e,t){var n=this;Object.keys(e.implementedFunctions).forEach((function(r){n.loadPluginFunction(e,r,t)})),void 0!==e.aliases&&Object.keys(e.aliases).forEach((function(r){n.loadPluginFunction(e,r,t)}))}},{key:"loadPluginFunction",value:function(e,t,n){if(this.functionIsProtected(t))throw ProtectedFunctionError.cannotRegisterFunctionWithId(t);this.loadFunctionUnprotected(e,t,n)}},{key:"loadFunctionUnprotected",value:function(e,t,n){var r=validateAndReturnMetadataFromName(t,e).method;if(!Object.prototype.hasOwnProperty.call(e.prototype,r))throw FunctionPluginValidationError.functionMethodNotFound(r,e.name);n.set(t,e)}},{key:"protectedFunctions",value:_regeneratorRuntime$3().mark((function e(){var t,n,r,a,i;return _regeneratorRuntime$3().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=_createForOfIteratorHelper$e(this._protectedPlugins),e.prev=1,t.s();case 3:if((n=t.n()).done){e.next=10;break}if(r=_slicedToArray$9(n.value,2),a=r[0],void 0===(i=r[1])){e.next=8;break}return e.next=8,[a,i];case 8:e.next=3;break;case 10:e.next=15;break;case 12:e.prev=12,e.t0=e.catch(1),t.e(e.t0);case 15:return e.prev=15,t.f(),e.finish(15);case 18:case"end":return e.stop()}}),e,this,[[1,12,15,18]])}))},{key:"protectedPlugins",value:_regeneratorRuntime$3().mark((function e(){var t,n,r,a;return _regeneratorRuntime$3().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=_createForOfIteratorHelper$e(this._protectedPlugins),e.prev=1,t.s();case 3:if((n=t.n()).done){e.next=10;break}if(r=_slicedToArray$9(n.value,2),void 0===(a=r[1])){e.next=8;break}return e.next=8,a;case 8:e.next=3;break;case 10:e.next=15;break;case 12:e.prev=12,e.t0=e.catch(1),t.e(e.t0);case 15:return e.prev=15,t.f(),e.finish(15);case 18:case"end":return e.stop()}}),e,this,[[1,12,15,18]])}))}]),e}(),CriterionType;function _classCallCheck$U(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$U(e,t){for(var n=0;n=]+)(.*)/;function StrToCriterionType(e){switch(e){case">":return CriterionType.GREATER_THAN;case">=":return CriterionType.GREATER_THAN_OR_EQUAL;case"<":return CriterionType.LESS_THAN;case"<=":return CriterionType.LESS_THAN_OR_EQUAL;case"<>":return CriterionType.NOT_EQUAL;case"=":return CriterionType.EQUAL;default:return}}var buildCriterionLambda=function(e,t){switch(e.operator){case CriterionType.GREATER_THAN:return"number"==typeof e.value?function(n){return"number"==typeof n&&t.floatCmp(n,e.value)>0}:function(e){return!1};case CriterionType.GREATER_THAN_OR_EQUAL:return"number"==typeof e.value?function(n){return"number"==typeof n&&t.floatCmp(n,e.value)>=0}:function(e){return!1};case CriterionType.LESS_THAN:return"number"==typeof e.value?function(n){return"number"==typeof n&&t.floatCmp(n,e.value)<0}:function(e){return!1};case CriterionType.LESS_THAN_OR_EQUAL:return"number"==typeof e.value?function(n){return"number"==typeof n&&t.floatCmp(n,e.value)<=0}:function(e){return!1};case CriterionType.EQUAL:return"number"==typeof e.value?function(n){if("number"==typeof n)return 0===t.floatCmp(n,e.value);if("string"==typeof n){if(""===n)return!1;var r=t.coerceToMaybeNumber(n);return void 0!==r&&0===t.floatCmp(r,e.value)}return!1}:"string"==typeof e.value?t.eqMatcherFunction(e.value):"boolean"==typeof e.value?function(t){return"boolean"==typeof t&&t===e.value}:function(e){return e===EmptyValue};case CriterionType.NOT_EQUAL:return"number"==typeof e.value?function(n){if("number"==typeof n)return 0!==t.floatCmp(n,e.value);if("string"==typeof n){if(""===n)return!0;var r=t.coerceToMaybeNumber(n);return void 0===r||0!==t.floatCmp(r,e.value)}return!0}:"string"==typeof e.value?t.neqMatcherFunction(e.value):"boolean"==typeof e.value?function(t){return"boolean"!=typeof t||t!==e.value}:function(e){return e!==EmptyValue}}};function _toConsumableArray$6(e){return _arrayWithoutHoles$6(e)||_iterableToArray$6(e)||_unsupportedIterableToArray$j(e)||_nonIterableSpread$6()}function _nonIterableSpread$6(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray$6(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles$6(e){if(Array.isArray(e))return _arrayLikeToArray$j(e)}function _createForOfIteratorHelper$d(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$j(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _slicedToArray$8(e,t){return _arrayWithHoles$8(e)||_iterableToArrayLimit$8(e,t)||_unsupportedIterableToArray$j(e,t)||_nonIterableRest$8()}function _nonIterableRest$8(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray$j(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$j(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$j(e,t):void 0}}function _arrayLikeToArray$j(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n{const t=this.arithmeticHelper.coerceNumbersExactRanges(e);return t instanceof CellError?t:0===t.length?new CellError(ErrorType.NUM,ErrorMessage.OneValue):(t.sort(((e,t)=>e-t)),t.length%2==0?(t[t.length/2-1]+t[t.length/2])/2:t[Math.floor(t.length/2)])}))}large(e,t){return this.runFunction(e.args,t,this.metadata("LARGE"),((e,t)=>{const n=this.arithmeticHelper.manyToExactNumbers(e.valuesFromTopLeftCorner());return n instanceof CellError?n:(n.sort(((e,t)=>e-t)),(t=Math.trunc(t))>n.length?new CellError(ErrorType.NUM,ErrorMessage.ValueLarge):n[n.length-t])}))}small(e,t){return this.runFunction(e.args,t,this.metadata("SMALL"),((e,t)=>{const n=this.arithmeticHelper.manyToExactNumbers(e.valuesFromTopLeftCorner());return n instanceof CellError?n:(n.sort(((e,t)=>e-t)),(t=Math.trunc(t))>n.length?new CellError(ErrorType.NUM,ErrorMessage.ValueLarge):n[t-1])}))}}MedianPlugin.implementedFunctions={MEDIAN:{method:"median",parameters:[{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1},LARGE:{method:"large",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.NUMBER,minValue:1}]},SMALL:{method:"small",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.NUMBER,minValue:1}]}}; /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */var CombinedTransformer=function(){function e(t){_classCallCheck$S(this,e),this.sheet=t,this.transformations=[]}return _createClass$S(e,[{key:"add",value:function(e){this.transformations.push(e)}},{key:"performEagerTransformations",value:function(e,t){this.transformations.forEach((function(n){return n.performEagerTransformations(e,t)}))}},{key:"transformSingleAst",value:function(e,t){var n=e,r=t;return this.transformations.forEach((function(e){var t=_slicedToArray$7(e.transformSingleAst(n,r),2);n=t[0],r=t[1]})),[n,r]}},{key:"isIrreversible",value:function(){return!0}}]),e}();function _typeof$M(e){return _typeof$M="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$M(e)}function _regeneratorRuntime$2(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */_regeneratorRuntime$2=function(){return e};var e={},t=Object.prototype,n=t.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},a=r.iterator||"@@iterator",i=r.asyncIterator||"@@asyncIterator",o=r.toStringTag||"@@toStringTag";function s(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{s({},"")}catch(e){s=function(e,t,n){return e[t]=n}}function l(e,t,n,r){var a=t&&t.prototype instanceof p?t:p,i=Object.create(a.prototype),o=new A(r||[]);return i._invoke=function(e,t,n){var r="suspendedStart";return function(a,i){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===a)throw i;return x()}for(n.method=a,n.arg=i;;){var o=n.delegate;if(o){var s=T(o,n);if(s){if(s===c)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var l=u(e,t,n);if("normal"===l.type){if(r=n.done?"completed":"suspendedYield",l.arg===c)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(r="completed",n.method="throw",n.arg=l.arg)}}}(e,n,o),i}function u(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}e.wrap=l;var c={};function p(){}function d(){}function m(){}var f={};s(f,a,(function(){return this}));var h=Object.getPrototypeOf,y=h&&h(h(S([])));y&&y!==t&&n.call(y,a)&&(f=y);var b=m.prototype=p.prototype=Object.create(f);function g(e){["next","throw","return"].forEach((function(t){s(e,t,(function(e){return this._invoke(t,e)}))}))}function v(e,t){function r(a,i,o,s){var l=u(e[a],e,i);if("throw"!==l.type){var c=l.arg,p=c.value;return p&&"object"==_typeof$M(p)&&n.call(p,"__await")?t.resolve(p.__await).then((function(e){r("next",e,o,s)}),(function(e){r("throw",e,o,s)})):t.resolve(p).then((function(e){c.value=e,o(c)}),(function(e){return r("throw",e,o,s)}))}s(l.arg)}var a;this._invoke=function(e,n){function i(){return new t((function(t,a){r(e,n,t,a)}))}return a=a?a.then(i,i):i()}}function T(e,t){var n=e.iterator[t.method];if(void 0===n){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,T(e,t),"throw"===t.method))return c;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return c}var r=u(n,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,c;var a=r.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,c):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,c)}function N(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function C(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function A(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(N,this),this.reset(!0)}function S(e){if(e){var t=e[a];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,i=function t(){for(;++r=0;--a){var i=this.tryEntries[a],o=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev=0;--r){var a=this.tryEntries[r];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),C(n),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:S(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),c}},e}function _slicedToArray$6(e,t){return _arrayWithHoles$6(e)||_iterableToArrayLimit$6(e,t)||_unsupportedIterableToArray$h(e,t)||_nonIterableRest$6()}function _nonIterableRest$6(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray$h(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$h(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$h(e,t):void 0}}function _arrayLikeToArray$h(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n0)n=a+1;else if(i<0)r=a-1;else{if(n==a)return a;r=a}}return r}function compare(e,t){return _typeof$L(e)===_typeof$L(t)?e===EmptyValue?0:et?1:0:e===EmptyValue?-1:t===EmptyValue?1:t instanceof CellError||"number"==typeof e&&"string"==typeof t||"number"==typeof e&&"boolean"==typeof t?-1:"string"==typeof e&&"number"==typeof t?1:"string"==typeof e&&"boolean"==typeof t?-1:1}function _classCallCheck$Q(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$Q(e,t){for(var n=0;n1?arguments[1]:void 0)}}),addToUnscopables(FIND_INDEX);var AdvancedFind=function(){function e(t){_classCallCheck$Q(this,e),this.dependencyGraph=t}return _createClass$Q(e,[{key:"advancedFind",value:function(e,t){var n,r=t.range;n=void 0===r?t.valuesFromTopLeftCorner():this.dependencyGraph.computeListOfValuesInRange(r);for(var a=0;a=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$g(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$g(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$g(e,t):void 0}}function _arrayLikeToArray$g(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);ne[a])n=a+1;else{if(!(te[a])n=a+1;else{if(!(t0===t?new CellError(ErrorType.DIV_BY_ZERO):e%t))}} /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */function buildColumnSearchStrategy(e,t,n){return t.useColumnIndex?new ColumnIndex(e,t,n):new ColumnBinarySearch(e,t)}function _classCallCheck$N(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$N(e,t){for(var n=0;n0?this.sum/this.count:void 0}varSValue(){return this.count>1?(this.sumsq-this.sum*this.sum/this.count)/(this.count-1):void 0}varPValue(){return this.count>0?(this.sumsq-this.sum*this.sum/this.count)/this.count:void 0}}MomentsAggregate.empty=new MomentsAggregate(0,0,0);class NumericAggregationPlugin extends FunctionPlugin{constructor(){super(...arguments),this.addWithEpsilonRaw=(e,t)=>this.arithmeticHelper.addWithEpsilonRaw(e,t)}sum(e,t){return this.doSum(e.args,t)}sumsq(e,t){return this.reduce(e.args,t,0,"SUMSQ",this.addWithEpsilonRaw,(e=>Math.pow(getRawValue(e),2)),strictlyNumbers)}max(e,t){return this.doMax(e.args,t)}maxa(e,t){return zeroForInfinite$1(this.reduce(e.args,t,Number.NEGATIVE_INFINITY,"MAXA",((e,t)=>Math.max(e,t)),getRawValue,numbersBooleans))}min(e,t){return this.doMin(e.args,t)}mina(e,t){return zeroForInfinite$1(this.reduce(e.args,t,Number.POSITIVE_INFINITY,"MINA",((e,t)=>Math.min(e,t)),getRawValue,numbersBooleans))}count(e,t){return this.doCount(e.args,t)}counta(e,t){return this.doCounta(e.args,t)}average(e,t){return this.doAverage(e.args,t)}averagea(e,t){var n;const r=this.reduce(e.args,t,MomentsAggregate.empty,"_AGGREGATE_A",((e,t)=>e.compose(t)),(e=>MomentsAggregate.single(getRawValue(e))),numbersBooleans);return r instanceof CellError?r:null!==(n=r.averageValue())&&void 0!==n?n:new CellError(ErrorType.DIV_BY_ZERO)}vars(e,t){return this.doVarS(e.args,t)}varp(e,t){return this.doVarP(e.args,t)}vara(e,t){var n;const r=this.reduceAggregateA(e.args,t);return r instanceof CellError?r:null!==(n=r.varSValue())&&void 0!==n?n:new CellError(ErrorType.DIV_BY_ZERO)}varpa(e,t){var n;const r=this.reduceAggregateA(e.args,t);return r instanceof CellError?r:null!==(n=r.varPValue())&&void 0!==n?n:new CellError(ErrorType.DIV_BY_ZERO)}stdevs(e,t){return this.doStdevS(e.args,t)}stdevp(e,t){return this.doStdevP(e.args,t)}stdeva(e,t){const n=this.reduceAggregateA(e.args,t);if(n instanceof CellError)return n;{const e=n.varSValue();return void 0===e?new CellError(ErrorType.DIV_BY_ZERO):Math.sqrt(e)}}stdevpa(e,t){const n=this.reduceAggregateA(e.args,t);if(n instanceof CellError)return n;{const e=n.varPValue();return void 0===e?new CellError(ErrorType.DIV_BY_ZERO):Math.sqrt(e)}}product(e,t){return this.doProduct(e.args,t)}subtotal(e,t){if(e.args.length<2)return new CellError(ErrorType.NA,ErrorMessage.WrongArgNumber);const n=this.coerceToType(this.evaluateAst(e.args[0],t),{argumentType:ArgumentTypes.NUMBER},t),r=e.args.slice(1);switch(n){case 1:case 101:return this.doAverage(r,t);case 2:case 102:return this.doCount(r,t);case 3:case 103:return this.doCounta(r,t);case 4:case 104:return this.doMax(r,t);case 5:case 105:return this.doMin(r,t);case 6:case 106:return this.doProduct(r,t);case 7:case 107:return this.doStdevS(r,t);case 8:case 108:return this.doStdevP(r,t);case 9:case 109:return this.doSum(r,t);case 10:case 110:return this.doVarS(r,t);case 11:case 111:return this.doVarP(r,t);default:return new CellError(ErrorType.VALUE,ErrorMessage.BadMode)}}reduceAggregate(e,t){return this.reduce(e,t,MomentsAggregate.empty,"_AGGREGATE",((e,t)=>e.compose(t)),(e=>MomentsAggregate.single(getRawValue(e))),strictlyNumbers)}reduceAggregateA(e,t){return this.reduce(e,t,MomentsAggregate.empty,"_AGGREGATE_A",((e,t)=>e.compose(t)),(e=>MomentsAggregate.single(getRawValue(e))),numbersBooleans)}doAverage(e,t){var n;const r=this.reduceAggregate(e,t);return r instanceof CellError?r:null!==(n=r.averageValue())&&void 0!==n?n:new CellError(ErrorType.DIV_BY_ZERO)}doVarS(e,t){var n;const r=this.reduceAggregate(e,t);return r instanceof CellError?r:null!==(n=r.varSValue())&&void 0!==n?n:new CellError(ErrorType.DIV_BY_ZERO)}doVarP(e,t){var n;const r=this.reduceAggregate(e,t);return r instanceof CellError?r:null!==(n=r.varPValue())&&void 0!==n?n:new CellError(ErrorType.DIV_BY_ZERO)}doStdevS(e,t){const n=this.reduceAggregate(e,t);if(n instanceof CellError)return n;{const e=n.varSValue();return void 0===e?new CellError(ErrorType.DIV_BY_ZERO):Math.sqrt(e)}}doStdevP(e,t){const n=this.reduceAggregate(e,t);if(n instanceof CellError)return n;{const e=n.varPValue();return void 0===e?new CellError(ErrorType.DIV_BY_ZERO):Math.sqrt(e)}}doCount(e,t){return this.reduce(e,t,0,"COUNT",((e,t)=>e+t),getRawValue,(e=>isExtendedNumber(e)?1:0))}doCounta(e,t){return this.reduce(e,t,0,"COUNTA",((e,t)=>e+t),getRawValue,(e=>e===EmptyValue?0:1))}doMax(e,t){return zeroForInfinite$1(this.reduce(e,t,Number.NEGATIVE_INFINITY,"MAX",((e,t)=>Math.max(e,t)),getRawValue,strictlyNumbers))}doMin(e,t){return zeroForInfinite$1(this.reduce(e,t,Number.POSITIVE_INFINITY,"MIN",((e,t)=>Math.min(e,t)),getRawValue,strictlyNumbers))}doSum(e,t){return this.reduce(e,t,0,"SUM",this.addWithEpsilonRaw,getRawValue,strictlyNumbers)}doProduct(e,t){return this.reduce(e,t,1,"PRODUCT",((e,t)=>e*t),getRawValue,strictlyNumbers)}reduce(e,t,n,r,a,i,s){return e.length<1?new CellError(ErrorType.NA,ErrorMessage.WrongArgNumber):e.reduce(((e,o)=>{if(e instanceof CellError)return e;if(o.type===AstNodeType.CELL_RANGE||o.type===AstNodeType.COLUMN_RANGE||o.type===AstNodeType.ROW_RANGE){const l=this.evaluateRange(o,t,n,r,a,i,s);return l instanceof CellError?l:a(l,e)}let l;if(l=this.evaluateAst(o,t),l instanceof SimpleRangeValue){const t=Array.from(l.valuesFromTopLeftCorner()).map(s).filter((e=>void 0!==e));return t.map((e=>e instanceof CellError?e:i(e))).reduce(((e,t)=>e instanceof CellError?e:t instanceof CellError?t:a(e,t)),e)}if(o.type===AstNodeType.CELL_REFERENCE){if(l=s(l),void 0===l)return e}else if(l=this.coerceScalarToNumberOrError(l),l=s(l),void 0===l)return e;return l instanceof CellError?l:a(e,i(l))}),n)}evaluateRange(e,t,n,r,a,i,s){let o;try{o=AbsoluteCellRange.fromAst(e,t.formulaAddress)}catch(e){if(e instanceof SheetsNotEqual)return new CellError(ErrorType.REF,ErrorMessage.RangeManySheets);throw e}const l=this.dependencyGraph.getRange(o.start,o.end);if(void 0===l)throw new Error("Range does not exists in graph");let u=l.getFunctionValue(r);if(void 0===u){u=this.getRangeValues(r,o,l,i,s).reduce(((e,t)=>e instanceof CellError?e:t instanceof CellError?t:a(e,t)),n),l.setFunctionValue(r,u)}return u}getRangeValues(e,t,n,r,a){const i=[],{smallerRangeVertex:s,restRange:o}=this.dependencyGraph.rangeMapping.findSmallerRange(t);let l;if(void 0!==s&&this.dependencyGraph.existsEdge(s,n)){const t=s.getFunctionValue(e);if(void 0!==t)i.push(t);else for(const e of s.range.addresses(this.dependencyGraph)){const t=a(this.dependencyGraph.getScalarValue(e));t instanceof CellError?i.push(t):void 0!==t&&i.push(r(t))}l=o}else l=t;for(const e of l.addresses(this.dependencyGraph)){const t=a(this.dependencyGraph.getScalarValue(e));t instanceof CellError?i.push(t):void 0!==t&&i.push(r(t))}return i}}function strictlyNumbers(e){return isExtendedNumber(e)||e instanceof CellError?e:void 0}function numbersBooleans(e){return"boolean"==typeof e?coerceBooleanToNumber(e):isExtendedNumber(e)||e instanceof CellError?e:"string"==typeof e?0:void 0} /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */var NumberLiteralHelper=function(){function e(t){_classCallCheck$N(this,e),this.config=t;var n="."===this.config.thousandSeparator?"\\".concat(this.config.thousandSeparator):this.config.thousandSeparator,r="."===this.config.decimalSeparator?"\\".concat(this.config.decimalSeparator):this.config.decimalSeparator;this.numberPattern=new RegExp("^([+-]?((".concat(r,"\\d+)|(\\d+(").concat(n,"\\d{3,})*(").concat(r,"\\d*)?)))(e[+-]?\\d+)?$")),this.allThousandSeparatorsRegex=new RegExp("".concat(n),"g")}return _createClass$N(e,[{key:"numericStringToMaybeNumber",value:function(e){if(this.numberPattern.test(e)){var t=this.numericStringToNumber(e);if(isNaN(t))return;return t}}},{key:"numericStringToNumber",value:function(e){var t=e.replace(this.allThousandSeparatorsRegex,"").replace(this.config.decimalSeparator,".");return Number(t)}}]),e}();function _createForOfIteratorHelper$b(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$f(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$f(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$f(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$f(e,t):void 0}}function _arrayLikeToArray$f(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=0&&(null===a[i][l]||void 0===a[i][l]);l--)a[i].pop()}for(var u=n-1;u>=0&&0===a[u].length;u--)a.pop();return a}},{key:"genericAllSheetsGetter",value:function(e){var t,n={},r=_createForOfIteratorHelper$b(this.dependencyGraph.sheetMapping.displayNames());try{for(r.s();!(t=r.n()).done;){var a=t.value,i=this.dependencyGraph.sheetMapping.fetch(a);n[a]=e(i)}}catch(e){r.e(e)}finally{r.f()}return n}},{key:"getSheetSerialized",value:function(e){var t=this;return this.genericSheetGetter(e,(function(e){return t.getCellSerialized(e)}))}},{key:"getAllSheetsValues",value:function(){var e=this;return this.genericAllSheetsGetter((function(t){return e.getSheetValues(t)}))}},{key:"getAllSheetsFormulas",value:function(){var e=this;return this.genericAllSheetsGetter((function(t){return e.getSheetFormulas(t)}))}},{key:"getAllSheetsSerialized",value:function(){var e=this;return this.genericAllSheetsGetter((function(t){return e.getSheetSerialized(t)}))}},{key:"getAllNamedExpressionsSerialized",value:function(){var e,t=this,n=[],r=0,a=_createForOfIteratorHelper$b(this.dependencyGraph.sheetMapping.displayNames());try{for(a.s();!(e=a.n()).done;){var i=e.value,o=this.dependencyGraph.sheetMapping.fetch(i);n[o]=r,r++}}catch(e){a.e(e)}finally{a.f()}return this.dependencyGraph.namedExpressions.getAllNamedExpressions().map((function(e){return{name:e.expression.displayName,expression:t.getCellSerialized(e.expression.address),scope:void 0!==e.scope?n[e.scope]:void 0,options:e.expression.options}}))}},{key:"withNewConfig",value:function(t,n){var r=new Unparser(t,buildLexerConfig(t),this.dependencyGraph.sheetMapping.fetchDisplayName,n);return new e(this.dependencyGraph,r,this.exporter)}}]),e}();function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _classCallCheck$L(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$L(e,t){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=new Config(t);return this.buildEngine(r,e,n)}},{key:"buildFromSheet",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=new Config(t),a=r.translationPackage.getUITranslation(UIElement.NEW_SHEET_PREFIX)+"1";return this.buildEngine(r,_defineProperty({},a,e),n)}},{key:"buildEmpty",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return this.buildEngine(new Config(e),{},t)}},{key:"rebuildWithConfig",value:function(e,t,n,r){return this.buildEngine(e,t,n,r)}},{key:"buildEngine",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e.useStats?new Statistics:new EmptyStatistics;r.start(StatType.BUILD_ENGINE_TOTAL);var a=new NamedExpressions,i=new FunctionRegistry(e),o=new LazilyTransformingAstService(r),s=DependencyGraph.buildEmpty(o,e,i,a,r),l=buildColumnSearchStrategy(s,e,r),u=s.sheetMapping,c=s.addressMapping;for(var p in t)if(Object.prototype.hasOwnProperty.call(t,p)){var d=t[p];validateAsSheet(d);var m=findBoundaries(d);if(m.height>e.maxRows||m.width>e.maxColumns)throw new SheetSizeLimitExceededError;var f=u.addSheet(p);c.autoAddSheet(f,d,m)}var h=new ParserWithCaching(e,i,u.get);o.parser=h;var y=new Unparser(e,buildLexerConfig(e),u.fetchDisplayName,a),b=new DateTimeHelper(e),g=new NumberLiteralHelper(e),v=new ArithmeticHelper(e,b,g),T=new CellContentParser(e,b,g),N=new ArraySizePredictor(e,i),C=new Operations(e,s,l,T,h,r,o,a,N),A=new UndoRedo(e,C);o.undoRedo=A;var S=new ClipboardOperations(e,s,C),x=new CrudOperations(e,C,A,S,s,l,h,T,o,a);n.forEach((function(e){x.ensureItIsPossibleToAddNamedExpression(e.name,e.expression,e.scope),x.operations.addNamedExpression(e.name,e.expression,e.scope,e.options)}));var w=new Exporter(e,a,u.fetchDisplayName,o),V=new Serialization(s,y,w),E=new Interpreter(e,s,l,r,v,i,a,V,N,b);r.measure(StatType.GRAPH_BUILD,(function(){new GraphBuilder(s,l,h,T,r,N).buildGraph(t,r)}));var O=new Evaluator(e,r,E,o,s,l);return O.run(),r.end(StatType.BUILD_ENGINE_TOTAL),{config:e,stats:r,dependencyGraph:s,columnSearch:l,parser:h,unparser:y,cellContentParser:T,evaluator:O,lazilyTransformingAstService:o,crudOperations:x,exporter:w,namedExpressions:a,serialization:V,functionRegistry:i}}}]),e}(),$$c=_export,$entries=objectToArray.entries;function _slicedToArray$4(e,t){return _arrayWithHoles$4(e)||_iterableToArrayLimit$4(e,t)||_unsupportedIterableToArray$e(e,t)||_nonIterableRest$4()}function _nonIterableRest$4(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray$e(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$e(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$e(e,t):void 0}}function _arrayLikeToArray$e(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n1?r-1:0),i=1;i=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$d(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$d(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$d(e,t):void 0}}function _arrayLikeToArray$d(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n1?t-1:0),r=1;r1?n-1:0),a=1;a1?t-1:0),r=1;r1?n-1:0),a=1;a1?t-1:0),r=1;r1?n-1:0),a=1;a1?t-1:0),r=1;r1?n-1:0),a=1;a2&&void 0!==arguments[2]&&arguments[2];if(!isSimpleCellRange(e))throw new ExpectedValueOfTypeError("SimpleCellRange","source");if(!isSimpleCellRange(t))throw new ExpectedValueOfTypeError("SimpleCellRange","target");var a=new AbsoluteCellRange(e.start,e.end),i=new AbsoluteCellRange(t.start,t.end);return this.ensureEvaluationIsNotSuspended(),i.arrayOfAddressesInRange().map((function(i){return i.map((function(i){var o=((i.row-(r?t:e).start.row)%a.height()+a.height())%a.height()+e.start.row,s=((i.col-(r?t:e).start.col)%a.width()+a.width())%a.width()+e.start.col;return n._serialization.getCellSerialized({row:o,col:s,sheet:a.sheet},i)}))}))}},{key:"isItPossibleToAddSheet",value:function(e){validateArgToType(e,"string","sheetName");try{return this._crudOperations.ensureItIsPossibleToAddSheet(e),!0}catch(e){return!1}}},{key:"addSheet",value:function(e){void 0!==e&&validateArgToType(e,"string","sheetName");var t=this._crudOperations.addSheet(e);return this._emitter.emit(Events.SheetAdded,t),t}},{key:"isItPossibleToRemoveSheet",value:function(e){validateArgToType(e,"number","sheetId");try{return this._crudOperations.ensureScopeIdIsValid(e),!0}catch(e){return!1}}},{key:"removeSheet",value:function(e){validateArgToType(e,"number","sheetId");var t=this.sheetMapping.getDisplayName(e);this._crudOperations.removeSheet(e);var n=this.recomputeIfDependencyGraphNeedsIt();return this._emitter.emit(Events.SheetRemoved,t,n),n}},{key:"isItPossibleToClearSheet",value:function(e){validateArgToType(e,"number","sheetId");try{return this._crudOperations.ensureScopeIdIsValid(e),!0}catch(e){return!1}}},{key:"clearSheet",value:function(e){return validateArgToType(e,"number","sheetId"),this._crudOperations.clearSheet(e),this.recomputeIfDependencyGraphNeedsIt()}},{key:"isItPossibleToReplaceSheetContent",value:function(e,t){validateArgToType(e,"number","sheetId");try{return this._crudOperations.ensureScopeIdIsValid(e),this._crudOperations.ensureItIsPossibleToChangeSheetContents(e,t),!0}catch(e){return!1}}},{key:"setSheetContent",value:function(e,t){return validateArgToType(e,"number","sheetId"),this._crudOperations.setSheetContent(e,t),this.recomputeIfDependencyGraphNeedsIt()}},{key:"simpleCellAddressFromString",value:function(e,t){return validateArgToType(e,"string","cellAddress"),validateArgToType(t,"number","sheetId"),simpleCellAddressFromString(this.sheetMapping.get,e,t)}},{key:"simpleCellRangeFromString",value:function(e,t){return validateArgToType(e,"string","cellRange"),validateArgToType(t,"number","sheetId"),simpleCellRangeFromString(this.sheetMapping.get,e,t)}},{key:"simpleCellAddressToString",value:function(e,t){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");return validateArgToType(t,"number","sheetId"),simpleCellAddressToString(this.sheetMapping.fetchDisplayName,e,t)}},{key:"simpleCellRangeToString",value:function(e,t){if(!isSimpleCellRange(e))throw new ExpectedValueOfTypeError("SimpleCellRange","cellRange");return validateArgToType(t,"number","sheetId"),simpleCellRangeToString(this.sheetMapping.fetchDisplayName,e,t)}},{key:"getCellDependents",value:function(e){var t;if(isSimpleCellAddress(e))t=this._dependencyGraph.addressMapping.getCell(e);else{if(!isSimpleCellRange(e))throw new ExpectedValueOfTypeError("SimpleCellAddress | SimpleCellRange",e);t=this._dependencyGraph.rangeMapping.getRange(e.start,e.end)}return void 0===t?[]:this._dependencyGraph.getAdjacentNodesAddresses(t)}},{key:"getCellPrecedents",value:function(e){var t;if(isSimpleCellAddress(e))t=this._dependencyGraph.addressMapping.getCell(e);else{if(!isSimpleCellRange(e))throw new ExpectedValueOfTypeError("SimpleCellAddress | SimpleCellRange",e);t=this._dependencyGraph.rangeMapping.getRange(e.start,e.end)}return void 0===t?[]:this._dependencyGraph.dependencyQueryAddresses(t)}},{key:"getSheetName",value:function(e){return validateArgToType(e,"number","sheetId"),this.sheetMapping.getDisplayName(e)}},{key:"getSheetNames",value:function(){return this.sheetMapping.sheetNames()}},{key:"getSheetId",value:function(e){return validateArgToType(e,"string","sheetName"),this.sheetMapping.get(e)}},{key:"doesSheetExist",value:function(e){return validateArgToType(e,"string","sheetName"),this.sheetMapping.hasSheetWithName(e)}},{key:"getCellType",value:function(e){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");var t=this.dependencyGraph.getCell(e);return getCellType(t,e)}},{key:"doesCellHaveSimpleValue",value:function(e){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");return this.getCellType(e)===CellType.VALUE}},{key:"doesCellHaveFormula",value:function(e){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");var t=this.getCellType(e);return t===CellType.FORMULA||t===CellType.ARRAYFORMULA}},{key:"isCellEmpty",value:function(e){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");return this.getCellType(e)===CellType.EMPTY}},{key:"isCellPartOfArray",value:function(e){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");var t=this.getCellType(e);return t===CellType.ARRAY||t===CellType.ARRAYFORMULA}},{key:"getCellValueType",value:function(e){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");this.ensureEvaluationIsNotSuspended();var t=this.dependencyGraph.getCellValue(e);return getCellValueType(t)}},{key:"getCellValueDetailedType",value:function(e){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");this.ensureEvaluationIsNotSuspended();var t=this.dependencyGraph.getCellValue(e);return getCellValueDetailedType(t)}},{key:"getCellValueFormat",value:function(e){if(!isSimpleCellAddress(e))throw new ExpectedValueOfTypeError("SimpleCellAddress","cellAddress");this.ensureEvaluationIsNotSuspended();var t=this.dependencyGraph.getCellValue(e);return getCellValueFormat(t)}},{key:"countSheets",value:function(){return this.sheetMapping.numberOfSheets()}},{key:"isItPossibleToRenameSheet",value:function(e,t){validateArgToType(e,"number","sheetId"),validateArgToType(t,"string","newName");try{return this._crudOperations.ensureItIsPossibleToRenameSheet(e,t),!0}catch(e){return!1}}},{key:"renameSheet",value:function(e,t){validateArgToType(e,"number","sheetId"),validateArgToType(t,"string","newName");var n=this._crudOperations.renameSheet(e,t);void 0!==n&&this._emitter.emit(Events.SheetRenamed,n,t)}},{key:"batch",value:function(e){this.suspendEvaluation(),this._crudOperations.beginUndoRedoBatchMode();try{e()}catch(e){throw this._crudOperations.commitUndoRedoBatchMode(),this.resumeEvaluation(),e}return this._crudOperations.commitUndoRedoBatchMode(),this.resumeEvaluation()}},{key:"suspendEvaluation",value:function(){this._evaluationSuspended=!0,this._emitter.emit(Events.EvaluationSuspended)}},{key:"resumeEvaluation",value:function(){this._evaluationSuspended=!1;var e=this.recomputeIfDependencyGraphNeedsIt();return this._emitter.emit(Events.EvaluationResumed,e),e}},{key:"isEvaluationSuspended",value:function(){return this._evaluationSuspended}},{key:"isItPossibleToAddNamedExpression",value:function(e,t,n){validateArgToType(e,"string","expressionName"),void 0!==n&&validateArgToType(n,"number","scope");try{return this._crudOperations.ensureItIsPossibleToAddNamedExpression(e,t,n),!0}catch(e){return!1}}},{key:"addNamedExpression",value:function(e,t,n,r){validateArgToType(e,"string","expressionName"),void 0!==n&&validateArgToType(n,"number","scope"),this._crudOperations.addNamedExpression(e,t,n,r);var a=this.recomputeIfDependencyGraphNeedsIt();return this._emitter.emit(Events.NamedExpressionAdded,e,a),a}},{key:"getNamedExpressionValue",value:function(e,t){validateArgToType(e,"string","expressionName"),void 0!==t&&validateArgToType(t,"number","scope"),this.ensureEvaluationIsNotSuspended(),this._crudOperations.ensureScopeIdIsValid(t);var n=this._namedExpressions.namedExpressionForScope(e,t);return n?this._serialization.getCellValue(n.address):void 0}},{key:"getNamedExpressionFormula",value:function(e,t){validateArgToType(e,"string","expressionName"),void 0!==t&&validateArgToType(t,"number","scope"),this._crudOperations.ensureScopeIdIsValid(t);var n=this._namedExpressions.namedExpressionForScope(e,t);return void 0===n?void 0:this._serialization.getCellFormula(n.address)}},{key:"getNamedExpression",value:function(e,t){validateArgToType(e,"string","expressionName"),void 0!==t&&validateArgToType(t,"number","scope");var n=this._namedExpressions.namedExpressionForScope(e,t);if(void 0!==n)return{name:e,scope:t,expression:this._serialization.getCellFormula(n.address),options:n.options}}},{key:"isItPossibleToChangeNamedExpression",value:function(e,t,n){validateArgToType(e,"string","expressionName"),void 0!==n&&validateArgToType(n,"number","scope");try{return this._crudOperations.ensureItIsPossibleToChangeNamedExpression(e,t,n),!0}catch(e){return!1}}},{key:"changeNamedExpression",value:function(e,t,n,r){return validateArgToType(e,"string","expressionName"),void 0!==n&&validateArgToType(n,"number","scope"),this._crudOperations.changeNamedExpressionExpression(e,n,t,r),this.recomputeIfDependencyGraphNeedsIt()}},{key:"isItPossibleToRemoveNamedExpression",value:function(e,t){validateArgToType(e,"string","expressionName"),void 0!==t&&validateArgToType(t,"number","scope");try{return this._crudOperations.isItPossibleToRemoveNamedExpression(e,t),!0}catch(e){return!1}}},{key:"removeNamedExpression",value:function(e,t){validateArgToType(e,"string","expressionName"),void 0!==t&&validateArgToType(t,"number","scope");var n=this._crudOperations.removeNamedExpression(e,t);if(n){var r=this.recomputeIfDependencyGraphNeedsIt();return this._emitter.emit(Events.NamedExpressionRemoved,n.displayName,r),r}return[]}},{key:"listNamedExpressions",value:function(e){return void 0!==e&&validateArgToType(e,"number","scope"),this._crudOperations.ensureScopeIdIsValid(e),this._namedExpressions.getAllNamedExpressionsNamesInScope(e)}},{key:"getAllNamedExpressionsSerialized",value:function(){return this._serialization.getAllNamedExpressionsSerialized()}},{key:"normalizeFormula",value:function(e){validateArgToType(e,"string","formulaString");var t=this.extractTemporaryFormula(e),n=t.ast,r=t.address;if(void 0===n)throw new NotAFormulaError;return this._unparser.unparse(n,r)}},{key:"calculateFormula",value:function(e,t){validateArgToType(e,"string","formulaString"),validateArgToType(t,"number","sheetId"),this._crudOperations.ensureScopeIdIsValid(t);var n=this.extractTemporaryFormula(e,t),r=n.ast,a=n.address,i=n.dependencies;if(void 0===r)throw new NotAFormulaError;var o=this.evaluator.runAndForget(r,a,i);return this._exporter.exportScalarOrRange(o)}},{key:"validateFormula",value:function(e){validateArgToType(e,"string","formulaString");var t=this.extractTemporaryFormula(e).ast;return void 0!==t&&!(t.type===AstNodeType.ERROR&&!t.error)}},{key:"getRegisteredFunctionNames",value:function(){return e.getLanguage(this._config.language).getFunctionTranslations(this._functionRegistry.getRegisteredFunctionIds())}},{key:"getFunctionPlugin",value:function(e){return validateArgToType(e,"string","functionId"),this._functionRegistry.getFunctionPlugin(e)}},{key:"getAllFunctionPlugins",value:function(){return this._functionRegistry.getPlugins()}},{key:"numberToDateTime",value:function(e){return validateArgToType(e,"number","val"),this._evaluator.interpreter.dateTimeHelper.numberToSimpleDateTime(e)}},{key:"numberToDate",value:function(e){return validateArgToType(e,"number","val"),this._evaluator.interpreter.dateTimeHelper.numberToSimpleDate(e)}},{key:"numberToTime",value:function(e){return validateArgToType(e,"number","val"),numberToSimpleTime(e)}},{key:"on",value:function(e,t){this._emitter.on(e,t)}},{key:"once",value:function(e,t){this._emitter.once(e,t)}},{key:"off",value:function(e,t){this._emitter.off(e,t)}},{key:"destroy",value:function(){objectDestroy(this)}},{key:"ensureEvaluationIsNotSuspended",value:function(){if(this._evaluationSuspended)throw new EvaluationSuspendedError}},{key:"extractTemporaryFormula",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,n=this._cellContentParser.parse(e),r={sheet:t,col:0,row:0};if(!(n instanceof CellContent.Formula))return{address:r,dependencies:[]};var a=this._parser.parse(n.formula,r),i=a.ast,o=a.errors,s=a.dependencies;return o.length>0?{address:r,dependencies:[]}:{ast:i,address:r,dependencies:s}}},{key:"recomputeIfDependencyGraphNeedsIt",value:function(){if(this._evaluationSuspended)return[];var e=this._crudOperations.getAndClearContentChanges(),t=Array.from(this.dependencyGraph.verticesToRecompute());this.dependencyGraph.clearRecentlyChangedVertices(),t.length>0&&e.addAll(this.evaluator.partialRun(t));var n=e.exportChanges(this._exporter);return e.isEmpty()||this._emitter.emit(Events.ValuesUpdated,n),n}}],[{key:"defaultConfig",get:function(){return getDefaultConfig()}},{key:"buildFromArray",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return this.buildFromEngineState(BuildEngineFactory.buildFromSheet(e,t,n))}},{key:"buildFromSheets",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return this.buildFromEngineState(BuildEngineFactory.buildFromSheets(e,t,n))}},{key:"buildEmpty",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return this.buildFromEngineState(BuildEngineFactory.buildEmpty(e,t))}},{key:"getLanguage",value:function(e){validateArgToType(e,"string","languageCode");var t=this.registeredLanguages.get(e);if(void 0===t)throw new LanguageNotRegisteredError;return t}},{key:"registerLanguage",value:function(e,t){if(validateArgToType(e,"string","languageCode"),this.registeredLanguages.has(e))throw new LanguageAlreadyRegisteredError;this.registeredLanguages.set(e,buildTranslationPackage(t))}},{key:"unregisterLanguage",value:function(e){if(validateArgToType(e,"string","languageCode"),!this.registeredLanguages.has(e))throw new LanguageNotRegisteredError;this.registeredLanguages.delete(e)}},{key:"getRegisteredLanguagesCodes",value:function(){return Array.from(this.registeredLanguages.keys())}},{key:"registerFunctionPlugin",value:function(e,t){FunctionRegistry.registerFunctionPlugin(e,t)}},{key:"unregisterFunctionPlugin",value:function(e){FunctionRegistry.unregisterFunctionPlugin(e)}},{key:"registerFunction",value:function(e,t,n){validateArgToType(e,"string","functionId"),FunctionRegistry.registerFunction(e,t,n)}},{key:"unregisterFunction",value:function(e){validateArgToType(e,"string","functionId"),FunctionRegistry.unregisterFunction(e)}},{key:"unregisterAllFunctions",value:function(){FunctionRegistry.unregisterAll()}},{key:"getRegisteredFunctionNames",value:function(e){validateArgToType(e,"string","code");var t=FunctionRegistry.getRegisteredFunctionIds();return this.getLanguage(e).getFunctionTranslations(t)}},{key:"getFunctionPlugin",value:function(e){return validateArgToType(e,"string","functionId"),FunctionRegistry.getFunctionPlugin(e)}},{key:"getAllFunctionPlugins",value:function(){return FunctionRegistry.getPlugins()}},{key:"buildFromEngineState",value:function(t){return new e(t.config,t.stats,t.dependencyGraph,t.columnSearch,t.parser,t.unparser,t.cellContentParser,t.evaluator,t.lazilyTransformingAstService,t.crudOperations,t.exporter,t.namedExpressions,t.serialization,t.functionRegistry)}}]),e}();function _toConsumableArray$3(e){return _arrayWithoutHoles$3(e)||_iterableToArray$3(e)||_unsupportedIterableToArray$c(e)||_nonIterableSpread$3()}function _nonIterableSpread$3(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray$c(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$c(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$c(e,t):void 0}}function _iterableToArray$3(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles$3(e){if(Array.isArray(e))return _arrayLikeToArray$c(e)}function _arrayLikeToArray$c(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n0&&void 0!==arguments[0]?arguments[0]:{},n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];_classCallCheck$I(this,e);var r=t.accentSensitive,a=t.binarySearchThreshold,i=t.caseSensitive,o=t.caseFirst,s=t.chooseAddressMappingPolicy,l=t.currencySymbol,u=t.dateFormats,c=t.decimalSeparator,p=t.evaluateNullToZero,d=t.functionArgSeparator,m=t.functionPlugins,f=t.ignorePunctuation,h=t.leapYear1900,y=t.localeLang,b=t.language,g=t.ignoreWhiteSpace,v=t.licenseKey,T=t.matchWholeCell,N=t.arrayColumnSeparator,C=t.arrayRowSeparator,A=t.maxRows,S=t.maxColumns,x=t.nullYear,w=t.nullDate,V=t.parseDateTime,E=t.precisionEpsilon,O=t.precisionRounding,_=t.stringifyDateTime,$=t.stringifyDuration,D=t.smartRounding,I=t.timeFormats,R=t.thousandSeparator,P=t.useArrayArithmetic,k=t.useStats,M=t.undoLimit,F=t.useColumnIndex,B=t.useRegularExpressions,L=t.useWildcards;n&&e.warnDeprecatedOptions(t),this.useArrayArithmetic=configValueFromParam(P,"boolean","useArrayArithmetic"),this.accentSensitive=configValueFromParam(r,"boolean","accentSensitive"),this.caseSensitive=configValueFromParam(i,"boolean","caseSensitive"),this.caseFirst=configValueFromParam(o,["upper","lower","false"],"caseFirst"),this.ignorePunctuation=configValueFromParam(f,"boolean","ignorePunctuation"),this.chooseAddressMappingPolicy=null!=s?s:e.defaultConfig.chooseAddressMappingPolicy,this.dateFormats=_toConsumableArray$3(configValueFromParamCheck(u,Array.isArray,"array","dateFormats")),this.timeFormats=_toConsumableArray$3(configValueFromParamCheck(I,Array.isArray,"array","timeFormats")),this.functionArgSeparator=configValueFromParam(d,"string","functionArgSeparator"),this.decimalSeparator=configValueFromParam(c,[".",","],"decimalSeparator"),this.language=configValueFromParam(b,"string","language"),this.ignoreWhiteSpace=configValueFromParam(g,["standard","any"],"ignoreWhiteSpace"),this.licenseKey=configValueFromParam(v,"string","licenseKey"),this.thousandSeparator=configValueFromParam(R,["",","," ","."],"thousandSeparator"),this.arrayColumnSeparator=configValueFromParam(N,[",",";"],"arrayColumnSeparator"),this.arrayRowSeparator=configValueFromParam(C,[";","|"],"arrayRowSeparator"),this.localeLang=configValueFromParam(y,"string","localeLang"),this.functionPlugins=_toConsumableArray$3(null!=m?m:e.defaultConfig.functionPlugins),this.smartRounding=configValueFromParam(D,"boolean","smartRounding"),this.evaluateNullToZero=configValueFromParam(p,"boolean","evaluateNullToZero"),this.nullYear=configValueFromParam(x,"number","nullYear"),validateNumberToBeAtLeast(this.nullYear,"nullYear",0),validateNumberToBeAtMost(this.nullYear,"nullYear",100),this.precisionRounding=configValueFromParam(O,"number","precisionRounding"),validateNumberToBeAtLeast(this.precisionRounding,"precisionRounding",0),this.precisionEpsilon=configValueFromParam(E,"number","precisionEpsilon"),validateNumberToBeAtLeast(this.precisionEpsilon,"precisionEpsilon",0),this.useColumnIndex=configValueFromParam(F,"boolean","useColumnIndex"),this.useStats=configValueFromParam(k,"boolean","useStats"),this.binarySearchThreshold=null!=a?a:e.defaultConfig.binarySearchThreshold,this.parseDateTime=configValueFromParam(V,"function","parseDateTime"),this.stringifyDateTime=configValueFromParam(_,"function","stringifyDateTime"),this.stringifyDuration=configValueFromParam($,"function","stringifyDuration"),this.translationPackage=HyperFormula.getLanguage(this.language),this.errorMapping=this.translationPackage.buildErrorMapping(),this.nullDate=configValueFromParamCheck(w,instanceOfSimpleDate,"IDate","nullDate"),this.leapYear1900=configValueFromParam(h,"boolean","leapYear1900"),this.undoLimit=configValueFromParam(M,"number","undoLimit"),this.useRegularExpressions=configValueFromParam(B,"boolean","useRegularExpressions"),this.useWildcards=configValueFromParam(L,"boolean","useWildcards"),this.matchWholeCell=configValueFromParam(T,"boolean","matchWholeCell"),validateNumberToBeAtLeast(this.undoLimit,"undoLimit",0),this.maxRows=configValueFromParam(A,"number","maxRows"),validateNumberToBeAtLeast(this.maxRows,"maxRows",1),this.maxColumns=configValueFromParam(S,"number","maxColumns"),this.currencySymbol=this.setupCurrencySymbol(l),validateNumberToBeAtLeast(this.maxColumns,"maxColumns",1),privatePool.set(this,{licenseKeyValidityState:checkLicenseKeyValidity(this.licenseKey)}),configCheckIfParametersNotInConflict({value:this.decimalSeparator,name:"decimalSeparator"},{value:this.functionArgSeparator,name:"functionArgSeparator"},{value:this.thousandSeparator,name:"thousandSeparator"}),configCheckIfParametersNotInConflict({value:this.arrayRowSeparator,name:"arrayRowSeparator"},{value:this.arrayColumnSeparator,name:"arrayColumnSeparator"})}return _createClass$I(e,[{key:"setupCurrencySymbol",value:function(e){var t=_toConsumableArray$3(configValueFromParamCheck(e,Array.isArray,"array","currencySymbol"));return t.forEach((function(e){if("string"!=typeof e)throw new ExpectedValueOfTypeError("string[]","currencySymbol");if(""===e)throw new ConfigValueEmpty("currencySymbol")})),t}},{key:"licenseKeyValidityState",get:function(){return privatePool.get(this).licenseKeyValidityState}},{key:"getConfig",value:function(){return getFullConfigFromPartial(this)}},{key:"mergeConfig",value:function(t){var n=Object.assign({},this.getConfig(),t);return e.warnDeprecatedOptions(t),new e(n,!1)}}],[{key:"warnDeprecatedOptions",value:function(t){e.warnDeprecatedIfUsed(t.binarySearchThreshold,"binarySearchThreshold","1.1")}},{key:"warnDeprecatedIfUsed",value:function(e,t,n,r){void 0!==e&&(void 0===r?console.warn("".concat(t," option is deprecated since ").concat(n)):console.warn("".concat(t," option is deprecated since ").concat(n,", please use ").concat(r)))}}]),e}();function getFullConfigFromPartial(e){var t,n={};for(var r in Config.defaultConfig){var a=null!==(t=e[r])&&void 0!==t?t:Config.defaultConfig[r];Array.isArray(a)?n[r]=_toConsumableArray$3(a):n[r]=a}return n}function getDefaultConfig(){return getFullConfigFromPartial({})} + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class RadiansPlugin extends FunctionPlugin{radians(e,t){return this.runFunction(e.args,t,this.metadata("RADIANS"),(e=>e*(Math.PI/180)))}}RadiansPlugin.implementedFunctions={RADIANS:{method:"radians",parameters:[{argumentType:ArgumentTypes.NUMBER}]}}; /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */Config.defaultConfig={accentSensitive:!1,binarySearchThreshold:20,currencySymbol:["$"],caseSensitive:!1,caseFirst:"lower",chooseAddressMappingPolicy:new AlwaysDense,dateFormats:["DD/MM/YYYY","DD/MM/YY"],decimalSeparator:".",evaluateNullToZero:!1,functionArgSeparator:",",functionPlugins:[],ignorePunctuation:!1,language:"enGB",ignoreWhiteSpace:"standard",licenseKey:"",leapYear1900:!1,localeLang:"en",matchWholeCell:!0,arrayColumnSeparator:",",arrayRowSeparator:";",maxRows:4e4,maxColumns:18278,nullYear:30,nullDate:{year:1899,month:12,day:30},parseDateTime:defaultParseToDateTime,precisionEpsilon:1e-13,precisionRounding:14,smartRounding:!0,stringifyDateTime:defaultStringifyDateTime,stringifyDuration:defaultStringifyDuration,timeFormats:["hh:mm","hh:mm:ss.sss"],thousandSeparator:"",undoLimit:20,useRegularExpressions:!1,useWildcards:!0,useColumnIndex:!1,useStats:!1,useArrayArithmetic:!1};var dictionary={errors:{CYCLE:"#CYCLE!",DIV_BY_ZERO:"#DIV/0!",ERROR:"#ERROR!",NA:"#N/A",NAME:"#NAME?",NUM:"#NUM!",REF:"#REF!",SPILL:"#SPILL!",VALUE:"#VALUE!"},functions:{FILTER:"FILTER",ARRAY_CONSTRAIN:"ARRAY_CONSTRAIN",ARRAYFORMULA:"ARRAYFORMULA",ABS:"ABS",ACOS:"ACOS",ACOSH:"ACOSH",ACOT:"ACOT",ACOTH:"ACOTH",AND:"AND",ARABIC:"ARABIC",ASIN:"ASIN",ASINH:"ASINH",ATAN2:"ATAN2",ATAN:"ATAN",ATANH:"ATANH",AVERAGE:"AVERAGE",AVERAGEA:"AVERAGEA",AVERAGEIF:"AVERAGEIF",BASE:"BASE",BIN2DEC:"BIN2DEC",BIN2HEX:"BIN2HEX",BIN2OCT:"BIN2OCT",BITAND:"BITAND",BITLSHIFT:"BITLSHIFT",BITOR:"BITOR",BITRSHIFT:"BITRSHIFT",BITXOR:"BITXOR",CEILING:"CEILING",CHAR:"CHAR",CHOOSE:"CHOOSE",CLEAN:"CLEAN",CODE:"CODE",COLUMN:"COLUMN",COLUMNS:"COLUMNS",CONCATENATE:"CONCATENATE",CORREL:"CORREL",COS:"COS",COSH:"COSH",COT:"COT",COTH:"COTH",COUNT:"COUNT",COUNTA:"COUNTA",COUNTBLANK:"COUNTBLANK",COUNTIF:"COUNTIF",COUNTIFS:"COUNTIFS",COUNTUNIQUE:"COUNTUNIQUE",CSC:"CSC",CSCH:"CSCH",CUMIPMT:"CUMIPMT",CUMPRINC:"CUMPRINC",DATE:"DATE",DATEDIF:"DATEDIF",DATEVALUE:"DATEVALUE",DAY:"DAY",DAYS360:"DAYS360",DAYS:"DAYS",DB:"DB",DDB:"DDB",DEC2BIN:"DEC2BIN",DEC2HEX:"DEC2HEX",DEC2OCT:"DEC2OCT",DECIMAL:"DECIMAL",DEGREES:"DEGREES",DELTA:"DELTA",DOLLARDE:"DOLLARDE",DOLLARFR:"DOLLARFR",EDATE:"EDATE",EFFECT:"EFFECT",EOMONTH:"EOMONTH",ERF:"ERF",ERFC:"ERFC",EVEN:"EVEN",EXACT:"EXACT",EXP:"EXP",FALSE:"FALSE",FIND:"FIND",FORMULATEXT:"FORMULATEXT",FV:"FV",FVSCHEDULE:"FVSCHEDULE",HEX2BIN:"HEX2BIN",HEX2DEC:"HEX2DEC",HEX2OCT:"HEX2OCT",HLOOKUP:"HLOOKUP",HOUR:"HOUR",IF:"IF",IFERROR:"IFERROR",IFNA:"IFNA",INDEX:"INDEX",INT:"INT",INTERVAL:"INTERVAL",IPMT:"IPMT",ISBINARY:"ISBINARY",ISBLANK:"ISBLANK",ISERR:"ISERR",ISERROR:"ISERROR",ISEVEN:"ISEVEN",ISFORMULA:"ISFORMULA",ISLOGICAL:"ISLOGICAL",ISNA:"ISNA",ISNONTEXT:"ISNONTEXT",ISNUMBER:"ISNUMBER",ISODD:"ISODD",ISOWEEKNUM:"ISOWEEKNUM",ISPMT:"ISPMT",ISREF:"ISREF",ISTEXT:"ISTEXT",LEFT:"LEFT",LEN:"LEN",LN:"LN",LOG10:"LOG10",LOG:"LOG",LOWER:"LOWER",MATCH:"MATCH",MAX:"MAX",MAXA:"MAXA",MAXPOOL:"MAXPOOL",MEDIAN:"MEDIAN",MEDIANPOOL:"MEDIANPOOL",MID:"MID",MIN:"MIN",MINA:"MINA",MINUTE:"MINUTE",MIRR:"MIRR",MMULT:"MMULT",MOD:"MOD",MONTH:"MONTH",NA:"NA",NETWORKDAYS:"NETWORKDAYS","NETWORKDAYS.INTL":"NETWORKDAYS.INTL",NOMINAL:"NOMINAL",NOT:"NOT",NOW:"NOW",NPER:"NPER",NPV:"NPV",OCT2BIN:"OCT2BIN",OCT2DEC:"OCT2DEC",OCT2HEX:"OCT2HEX",ODD:"ODD",OFFSET:"OFFSET",OR:"OR",PI:"PI",PMT:"PMT",PDURATION:"PDURATION",PRODUCT:"PRODUCT",POWER:"POWER",PPMT:"PPMT",PROPER:"PROPER",PV:"PV",RADIANS:"RADIANS",RAND:"RAND",RATE:"RATE",REPLACE:"REPLACE",REPT:"REPT",RIGHT:"RIGHT",ROMAN:"ROMAN",ROUND:"ROUND",ROUNDDOWN:"ROUNDDOWN",ROUNDUP:"ROUNDUP",ROW:"ROW",ROWS:"ROWS",RRI:"RRI",SEARCH:"SEARCH",SEC:"SEC",SECH:"SECH",SECOND:"SECOND",SHEET:"SHEET",SHEETS:"SHEETS",SIN:"SIN",SINH:"SINH",SLN:"SLN",SPLIT:"SPLIT",SQRT:"SQRT",STDEVA:"STDEVA","STDEV.P":"STDEV.P",STDEVPA:"STDEVPA","STDEV.S":"STDEV.S",SUBSTITUTE:"SUBSTITUTE",SUBTOTAL:"SUBTOTAL",SUM:"SUM",SUMIF:"SUMIF",SUMIFS:"SUMIFS",SUMPRODUCT:"SUMPRODUCT",SUMSQ:"SUMSQ",SWITCH:"SWITCH",SYD:"SYD",T:"T",TAN:"TAN",TANH:"TANH",TBILLEQ:"TBILLEQ",TBILLPRICE:"TBILLPRICE",TBILLYIELD:"TBILLYIELD",TEXT:"TEXT",TIME:"TIME",TIMEVALUE:"TIMEVALUE",TODAY:"TODAY",TRANSPOSE:"TRANSPOSE",TRIM:"TRIM",TRUE:"TRUE",TRUNC:"TRUNC",UNICHAR:"UNICHAR",UNICODE:"UNICODE",UPPER:"UPPER",VARA:"VARA","VAR.P":"VAR.P",VARPA:"VARPA","VAR.S":"VAR.S",VLOOKUP:"VLOOKUP",WEEKDAY:"WEEKDAY",WEEKNUM:"WEEKNUM",WORKDAY:"WORKDAY","WORKDAY.INTL":"WORKDAY.INTL",XNPV:"XNPV",XOR:"XOR",YEAR:"YEAR",YEARFRAC:"YEARFRAC","HF.ADD":"HF.ADD","HF.CONCAT":"HF.CONCAT","HF.DIVIDE":"HF.DIVIDE","HF.EQ":"HF.EQ","HF.GT":"HF.GT","HF.GTE":"HF.GTE","HF.LT":"HF.LT","HF.LTE":"HF.LTE","HF.MINUS":"HF.MINUS","HF.MULTIPLY":"HF.MULTIPLY","HF.NE":"HF.NE","HF.POW":"HF.POW","HF.UMINUS":"HF.UMINUS","HF.UNARY_PERCENT":"HF.UNARY_PERCENT","HF.UPLUS":"HF.UPLUS",VARP:"VARP",VAR:"VAR",STDEVP:"STDEVP",STDEV:"STDEV","EXPON.DIST":"EXPON.DIST",FISHER:"FISHER",FISHERINV:"FISHERINV",GAMMA:"GAMMA","GAMMA.DIST":"GAMMA.DIST",GAMMALN:"GAMMALN","GAMMALN.PRECISE":"GAMMALN.PRECISE","GAMMA.INV":"GAMMA.INV",GAUSS:"GAUSS",FACT:"FACT",FACTDOUBLE:"FACTDOUBLE",COMBIN:"COMBIN",COMBINA:"COMBINA",GCD:"GCD",LCM:"LCM",MROUND:"MROUND",MULTINOMIAL:"MULTINOMIAL",QUOTIENT:"QUOTIENT",RANDBETWEEN:"RANDBETWEEN",SERIESSUM:"SERIESSUM",SIGN:"SIGN",SQRTPI:"SQRTPI",SUMX2MY2:"SUMX2MY2",SUMX2PY2:"SUMX2PY2",SUMXMY2:"SUMXMY2",EXPONDIST:"EXPONDIST",GAMMADIST:"GAMMADIST",GAMMAINV:"GAMMAINV","BETA.DIST":"BETA.DIST",BETADIST:"BETADIST","BETA.INV":"BETA.INV",BETAINV:"BETAINV","BINOM.DIST":"BINOM.DIST",BINOMDIST:"BINOMDIST","BINOM.INV":"BINOM.INV",BESSELI:"BESSELI",BESSELJ:"BESSELJ",BESSELK:"BESSELK",BESSELY:"BESSELY","CHISQ.DIST":"CHISQ.DIST","CHISQ.DIST.RT":"CHISQ.DIST.RT","CHISQ.INV":"CHISQ.INV","CHISQ.INV.RT":"CHISQ.INV.RT",CHIDIST:"CHIDIST",CHIINV:"CHIINV","F.DIST":"F.DIST","F.DIST.RT":"F.DIST.RT","F.INV":"F.INV","F.INV.RT":"F.INV.RT",FDIST:"FDIST",FINV:"FINV",WEIBULL:"WEIBULL","WEIBULL.DIST":"WEIBULL.DIST",POISSON:"POISSON","POISSON.DIST":"POISSON.DIST","HYPGEOM.DIST":"HYPGEOM.DIST",HYPGEOMDIST:"HYPGEOMDIST","T.DIST":"T.DIST","T.DIST.2T":"T.DIST.2T","T.DIST.RT":"T.DIST.RT","T.INV":"T.INV","T.INV.2T":"T.INV.2T",TDIST:"TDIST",TINV:"TINV",LOGINV:"LOGINV","LOGNORM.DIST":"LOGNORM.DIST","LOGNORM.INV":"LOGNORM.INV",LOGNORMDIST:"LOGNORMDIST","NORM.DIST":"NORM.DIST","NORM.INV":"NORM.INV","NORM.S.DIST":"NORM.S.DIST","NORM.S.INV":"NORM.S.INV",NORMDIST:"NORMDIST",NORMINV:"NORMINV",NORMSDIST:"NORMSDIST",NORMSINV:"NORMSINV",PHI:"PHI","NEGBINOM.DIST":"NEGBINOM.DIST",NEGBINOMDIST:"NEGBINOMDIST",COMPLEX:"COMPLEX",IMABS:"IMABS",IMAGINARY:"IMAGINARY",IMARGUMENT:"IMARGUMENT",IMCONJUGATE:"IMCONJUGATE",IMCOS:"IMCOS",IMCOSH:"IMCOSH",IMCOT:"IMCOT",IMCSC:"IMCSC",IMCSCH:"IMCSCH",IMDIV:"IMDIV",IMEXP:"IMEXP",IMLN:"IMLN",IMLOG10:"IMLOG10",IMLOG2:"IMLOG2",IMPOWER:"IMPOWER",IMPRODUCT:"IMPRODUCT",IMREAL:"IMREAL",IMSEC:"IMSEC",IMSECH:"IMSECH",IMSIN:"IMSIN",IMSINH:"IMSINH",IMSQRT:"IMSQRT",IMSUB:"IMSUB",IMSUM:"IMSUM",IMTAN:"IMTAN",LARGE:"LARGE",SMALL:"SMALL",AVEDEV:"AVEDEV",CONFIDENCE:"CONFIDENCE","CONFIDENCE.NORM":"CONFIDENCE.NORM","CONFIDENCE.T":"CONFIDENCE.T",DEVSQ:"DEVSQ",GEOMEAN:"GEOMEAN",HARMEAN:"HARMEAN",CRITBINOM:"CRITBINOM","COVARIANCE.P":"COVARIANCE.P","COVARIANCE.S":"COVARIANCE.S",COVAR:"COVAR",PEARSON:"PEARSON",RSQ:"RSQ",STANDARDIZE:"STANDARDIZE","Z.TEST":"Z.TEST",ZTEST:"ZTEST","F.TEST":"F.TEST",FTEST:"FTEST",STEYX:"STEYX",SLOPE:"SLOPE","CHISQ.TEST":"CHISQ.TEST",CHITEST:"CHITEST","T.TEST":"T.TEST",TTEST:"TTEST",SKEW:"SKEW","SKEW.P":"SKEW.P",WEIBULLDIST:"WEIBULLDIST",VARS:"VARS",TINV2T:"TINV2T",TDISTRT:"TDISTRT",TDIST2T:"TDIST2T",STDEVS:"STDEVS",FINVRT:"FINVRT",FDISTRT:"FDISTRT",CHIDISTRT:"CHIDISTRT",CHIINVRT:"CHIINVRT",COVARIANCEP:"COVARIANCEP",COVARIANCES:"COVARIANCES",LOGNORMINV:"LOGNORMINV",POISSONDIST:"POISSONDIST",SKEWP:"SKEWP","CEILING.MATH":"CEILING.MATH",FLOOR:"FLOOR","FLOOR.MATH":"FLOOR.MATH","CEILING.PRECISE":"CEILING.PRECISE","FLOOR.PRECISE":"FLOOR.PRECISE","ISO.CEILING":"ISO.CEILING"},langCode:"enGB",ui:{NEW_SHEET_PREFIX:"Sheet"}};function _typeof$I(e){return _typeof$I="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$I(e)}function _toConsumableArray$2(e){return _arrayWithoutHoles$2(e)||_iterableToArray$2(e)||_unsupportedIterableToArray$b(e)||_nonIterableSpread$2()}function _nonIterableSpread$2(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray$2(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles$2(e){if(Array.isArray(e))return _arrayLikeToArray$b(e)}function _createForOfIteratorHelper$9(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$b(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$b(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$b(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$b(e,t):void 0}}function _arrayLikeToArray$b(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n1?t-1:0),r=1;r1&&e.height()>1)return new CellError(ErrorType.NA,ErrorMessage.WrongDimension);for(var s=e.data,l=[],u=0;u0&&l.push(c)}return l.length>0?SimpleRangeValue.onlyValues(l):new CellError(ErrorType.NA,ErrorMessage.EmptyRange)}))}},{key:"filterArraySize",value:function(e,t){var n=this;if(e.args.length<=1)return ArraySize.error();var r=this.metadata("FILTER"),a=e.args.map((function(e){var a;return n.arraySizeForAst(e,new InterpreterState(t.formulaAddress,t.arraysFlag||null!==(a=null==r?void 0:r.arrayFunction)&&void 0!==a&&a))})),i=Math.max.apply(Math,_toConsumableArray$2(a.map((function(e){return e.width})))),o=Math.max.apply(Math,_toConsumableArray$2(a.map((function(e){return e.height}))));return new ArraySize(i,o)}}]),n}(FunctionPlugin);function _typeof$H(e){return _typeof$H="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$H(e)}function _classCallCheck$G(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$G(e,t){for(var n=0;nMAX_48BIT_INTEGER?new CellError(ErrorType.NUM,ErrorMessage.BitshiftLong):e}function _typeof$F(e){return _typeof$F="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$F(e)}function _classCallCheck$E(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$E(e,t){for(var n=0;n1?t-1:0),a=1;a(arguments.length<=1?0:arguments.length-1)?new CellError(ErrorType.NUM,ErrorMessage.Selector):e-1+1<1||arguments.length<=e-1+1?void 0:arguments[e-1+1]}))}}]),n}(FunctionPlugin);BooleanPlugin.implementedFunctions={TRUE:{method:"literalTrue",parameters:[]},FALSE:{method:"literalFalse",parameters:[]},IF:{method:"conditionalIf",parameters:[{argumentType:ArgumentTypes.BOOLEAN},{argumentType:ArgumentTypes.SCALAR,passSubtype:!0},{argumentType:ArgumentTypes.SCALAR,defaultValue:!1,passSubtype:!0}]},AND:{method:"and",parameters:[{argumentType:ArgumentTypes.BOOLEAN}],repeatLastArgs:1,expandRanges:!0},OR:{method:"or",parameters:[{argumentType:ArgumentTypes.BOOLEAN}],repeatLastArgs:1,expandRanges:!0},XOR:{method:"xor",parameters:[{argumentType:ArgumentTypes.BOOLEAN}],repeatLastArgs:1,expandRanges:!0},NOT:{method:"not",parameters:[{argumentType:ArgumentTypes.BOOLEAN}]},SWITCH:{method:"switch",parameters:[{argumentType:ArgumentTypes.NOERROR},{argumentType:ArgumentTypes.SCALAR,passSubtype:!0},{argumentType:ArgumentTypes.SCALAR,passSubtype:!0}],repeatLastArgs:1},IFERROR:{method:"iferror",parameters:[{argumentType:ArgumentTypes.SCALAR,passSubtype:!0},{argumentType:ArgumentTypes.SCALAR,passSubtype:!0}]},IFNA:{method:"ifna",parameters:[{argumentType:ArgumentTypes.SCALAR,passSubtype:!0},{argumentType:ArgumentTypes.SCALAR,passSubtype:!0}]},CHOOSE:{method:"choose",parameters:[{argumentType:ArgumentTypes.INTEGER,minValue:1},{argumentType:ArgumentTypes.SCALAR,passSubtype:!0}],repeatLastArgs:1}};var $$b=_export,trunc=mathTrunc;$$b({target:"Math",stat:!0},{trunc:trunc});var $$a=_export,uncurryThis=functionUncurryThis,toAbsoluteIndex=toAbsoluteIndex$6,$RangeError=RangeError,fromCharCode=String.fromCharCode,$fromCodePoint=String.fromCodePoint,join=uncurryThis([].join),INCORRECT_LENGTH=!!$fromCodePoint&&1!=$fromCodePoint.length;function _typeof$D(e){return _typeof$D="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$D(e)}function _classCallCheck$C(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$C(e,t){for(var n=0;na;){if(t=+arguments[a++],toAbsoluteIndex(t,1114111)!==t)throw $RangeError(t+" is not a valid code point");n[a]=t<65536?fromCharCode(t):fromCharCode(55296+((t-=65536)>>10),t%1024+56320)}return join(n,"")}});var CharPlugin=function(e){_inherits$B(n,e);var t=_createSuper$B(n);function n(){return _classCallCheck$C(this,n),t.apply(this,arguments)}return _createClass$C(n,[{key:"char",value:function(e,t){return this.runFunction(e.args,t,this.metadata("CHAR"),(function(e){return e<1||e>=256?new CellError(ErrorType.VALUE,ErrorMessage.CharacterCodeBounds):String.fromCharCode(Math.trunc(e))}))}},{key:"unichar",value:function(e,t){return this.runFunction(e.args,t,this.metadata("CHAR"),(function(e){return e<1||e>=1114112?new CellError(ErrorType.VALUE,ErrorMessage.CharacterCodeBounds):String.fromCodePoint(Math.trunc(e))}))}}]),n}(FunctionPlugin);function _typeof$C(e){return _typeof$C="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$C(e)}function _classCallCheck$B(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$B(e,t){for(var n=0;n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _slicedToArray$3(e,t){return _arrayWithHoles$3(e)||_iterableToArrayLimit$3(e,t)||_unsupportedIterableToArray$a(e,t)||_nonIterableRest$3()}function _nonIterableRest$3(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray$a(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$a(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$a(e,t):void 0}}function _arrayLikeToArray$a(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);nt)return new CellError(ErrorType.NUM,ErrorMessage.StartEndDate);if("D"===r)return Math.floor(t)-Math.floor(e);var a=n.dateTimeHelper.numberToSimpleDate(e),i=n.dateTimeHelper.numberToSimpleDate(t);switch(r){case"M":return 12*(i.year-a.year)+(i.month-a.month)-(i.daya.month||i.month===a.month&&i.day>=a.day?i.year-a.year:i.year-a.year-1;case"MD":if(i.day>=a.day)return i.day-a.day;var o=1===i.month?12:i.month-1,s=1===i.month?i.year-1:i.year;return n.dateTimeHelper.daysInMonth(s,o)+i.day-a.day;case"YD":return i.month>a.month||i.month===a.month&&i.day>=a.day?Math.floor(t)-n.dateTimeHelper.dateToNumber({year:i.year,month:a.month,day:a.day}):Math.floor(t)-Math.floor(e)-365*(i.year-a.year-1)-n.dateTimeHelper.leapYearsCount(i.year-1)+n.dateTimeHelper.leapYearsCount(a.year);default:return new CellError(ErrorType.NUM,ErrorMessage.BadMode)}}))}},{key:"days360",value:function(e,t){return this.runFunction(e.args,t,this.metadata("DAYS360"),this.days360Core)}},{key:"yearfrac",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("YEARFRAC"),(function(e,t,r){if((e=Math.trunc(e))>(t=Math.trunc(t))){var a=[t,e];e=a[0],t=a[1]}switch(r){case 0:return n.days360Core(e,t,!1)/360;case 1:return(t-e)/n.dateTimeHelper.yearLengthForBasis(n.dateTimeHelper.numberToSimpleDate(e),n.dateTimeHelper.numberToSimpleDate(t));case 2:return(t-e)/360;case 3:return(t-e)/365;case 4:return n.days360Core(e,t,!0)/360}throw new Error("Should not be reachable.")}))}},{key:"interval",value:function(e,t){return this.runFunction(e.args,t,this.metadata("INTERVAL"),(function(e){var t=(e=Math.trunc(e))%60,n=(e=Math.trunc(e/60))%60,r=(e=Math.trunc(e/60))%24,a=(e=Math.trunc(e/24))%30,i=(e=Math.trunc(e/30))%12,o=Math.trunc(e/12);return"P"+(o>0?o+"Y":"")+(i>0?i+"M":"")+(a>0?a+"D":"")+"T"+(r>0?r+"H":"")+(n>0?n+"M":"")+(t>0?t+"S":"")}))}},{key:"networkdays",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("NETWORKDAYS"),(function(e,t,r){return n.networkdayscore(e,t,1,r)}))}},{key:"networkdaysintl",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("NETWORKDAYS.INTL"),(function(e,t,r,a){return n.networkdayscore(e,t,r,a)}))}},{key:"workday",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("WORKDAY"),(function(e,t,r){return n.workdaycore(e,t,1,r)}))}},{key:"workdayintl",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("WORKDAY.INTL"),(function(e,t,r,a){return n.workdaycore(e,t,r,a)}))}},{key:"networkdayscore",value:function(e,t,n,r){var a=1;if((e=Math.trunc(e))>(t=Math.trunc(t))){var i=[t,e];e=i[0],t=i[1],a=-1}var o=computeWeekendPattern(n);if(o instanceof CellError)return o;var s=this.simpleRangeToFilteredHolidays(o,r);return s instanceof CellError?s:a*this.countWorkdays(e,t,o,s)}},{key:"workdaycore",value:function(e,t,n,r){e=Math.trunc(e),t=Math.trunc(t);var a=computeWeekendPattern(n);if(a instanceof CellError)return a;var i=this.simpleRangeToFilteredHolidays(a,r);if(i instanceof CellError)return i;if(t>0){for(var o=1;this.countWorkdays(e+1,e+o,a,i)=e?r=a:n=a}return r}function computeWeekendPattern(e){var t;return"number"!=typeof e&&"string"!=typeof e?new CellError(ErrorType.VALUE,ErrorMessage.WrongType):"string"==typeof e?7===e.length&&/^(0|1)*$/.test(e)&&"1111111"!==e?e:new CellError(ErrorType.NUM,ErrorMessage.WeekendString):null!==(t=workdayPatterns.get(e))&&void 0!==t?t:new CellError(ErrorType.NUM,ErrorMessage.BadMode)}DateTimePlugin.implementedFunctions={DATE:{method:"date",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER}],returnNumberType:NumberType.NUMBER_DATE},TIME:{method:"time",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER}],returnNumberType:NumberType.NUMBER_TIME},MONTH:{method:"month",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0}]},YEAR:{method:"year",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0}]},HOUR:{method:"hour",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0}]},MINUTE:{method:"minute",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0}]},SECOND:{method:"second",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0}]},TEXT:{method:"text",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.STRING}]},EOMONTH:{method:"eomonth",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER}],returnNumberType:NumberType.NUMBER_DATE},DAY:{method:"day",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0}]},DAYS:{method:"days",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0}]},WEEKDAY:{method:"weekday",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]},WEEKNUM:{method:"weeknum",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]},ISOWEEKNUM:{method:"isoweeknum",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0}]},DATEVALUE:{method:"datevalue",parameters:[{argumentType:ArgumentTypes.STRING}],returnNumberType:NumberType.NUMBER_DATE},TIMEVALUE:{method:"timevalue",parameters:[{argumentType:ArgumentTypes.STRING}],returnNumberType:NumberType.NUMBER_TIME},NOW:{method:"now",parameters:[],isVolatile:!0,returnNumberType:NumberType.NUMBER_DATETIME},TODAY:{method:"today",parameters:[],isVolatile:!0,returnNumberType:NumberType.NUMBER_DATE},EDATE:{method:"edate",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER}],returnNumberType:NumberType.NUMBER_DATE},DAYS360:{method:"days360",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.BOOLEAN,defaultValue:!1}]},DATEDIF:{method:"datedif",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.STRING}]},YEARFRAC:{method:"yearfrac",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.INTEGER,defaultValue:0,minValue:0,maxValue:4}]},INTERVAL:{method:"interval",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0}]},NETWORKDAYS:{method:"networkdays",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.RANGE,optionalArg:!0}]},"NETWORKDAYS.INTL":{method:"networkdaysintl",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NOERROR,defaultValue:1},{argumentType:ArgumentTypes.RANGE,optionalArg:!0}]},WORKDAY:{method:"workday",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.RANGE,optionalArg:!0}]},"WORKDAY.INTL":{method:"workdayintl",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NOERROR,defaultValue:1},{argumentType:ArgumentTypes.RANGE,optionalArg:!0}]}};var weekdayOffsets=new Map([[1,0],[2,1],[11,1],[12,2],[13,3],[14,4],[15,5],[16,6],[17,0]]),workdayPatterns=new Map([[1,"0000011"],[2,"1000001"],[3,"1100000"],[4,"0110000"],[5,"0011000"],[6,"0001100"],[7,"0000110"],[11,"0000001"],[12,"1000000"],[13,"0100000"],[14,"0010000"],[15,"0001000"],[16,"0000100"],[17,"0000010"]]);function _typeof$y(e){return _typeof$y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$y(e)}function _classCallCheck$x(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$x(e,t){for(var n=0;n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$9(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$9(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$9(e,t):void 0}}function _arrayLikeToArray$9(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);na)return new CellError(ErrorType.NUM,ErrorMessage.EndStartPeriod);for(var o=0,s=r;s<=a;s++)o+=ipmtCore(e,s,t,n,0,i);return o}))}},{key:"cumprinc",value:function(e,t){return this.runFunction(e.args,t,this.metadata("CUMPRINC"),(function(e,t,n,r,a,i){if(r>a)return new CellError(ErrorType.NUM,ErrorMessage.EndStartPeriod);for(var o=0,s=r;s<=a;s++)o+=ppmtCore(e,s,t,n,0,i);return o}))}},{key:"db",value:function(e,t){return this.runFunction(e.args,t,this.metadata("DB"),(function(e,t,n,r,a){if(12===a&&r>n||r>n+1)return new CellError(ErrorType.NUM,ErrorMessage.PeriodLong);if(t>=e)return 0;var i=Math.round(1e3*(1-Math.pow(t/e,1/n)))/1e3,o=e*i*a/12;if(1===r)return o;for(var s=o,l=0;ln)return new CellError(ErrorType.NUM);var i,o=a/n;o>=1?(o=1,i=1===r?e:0):i=e*Math.pow(1-o,r-1);var s=e*Math.pow(1-o,r);return Math.max(i-Math.max(t,s),0)}))}},{key:"dollarde",value:function(e,t){return this.runFunction(e.args,t,this.metadata("DOLLARDE"),(function(e,t){if(t<1)return new CellError(ErrorType.DIV_BY_ZERO);for(t=Math.trunc(t);t>10;)t/=10;return Math.trunc(e)+10*(e-Math.trunc(e))/t}))}},{key:"dollarfr",value:function(e,t){return this.runFunction(e.args,t,this.metadata("DOLLARFR"),(function(e,t){if(t<1)return new CellError(ErrorType.DIV_BY_ZERO);for(t=Math.trunc(t);t>10;)t/=10;return Math.trunc(e)+(e-Math.trunc(e))*t/10}))}},{key:"effect",value:function(e,t){return this.runFunction(e.args,t,this.metadata("EFFECT"),(function(e,t){return t=Math.trunc(t),Math.pow(1+e/t,t)-1}))}},{key:"ispmt",value:function(e,t){return this.runFunction(e.args,t,this.metadata("ISPMT"),(function(e,t,n,r){return 0===n?new CellError(ErrorType.DIV_BY_ZERO):r*e*(t/n-1)}))}},{key:"nominal",value:function(e,t){return this.runFunction(e.args,t,this.metadata("NOMINAL"),(function(e,t){return t=Math.trunc(t),(Math.pow(e+1,1/t)-1)*t}))}},{key:"nper",value:function(e,t){return this.runFunction(e.args,t,this.metadata("NPER"),(function(e,t,n,r,a){return 0===e?0===t?new CellError(ErrorType.DIV_BY_ZERO):(-n-r)/t:(a&&(t*=1+e),Math.log((t-r*e)/(n*e+t))/Math.log(1+e))}))}},{key:"rate",value:function(e,t){return this.runFunction(e.args,t,this.metadata("RATE"),(function(e,t,n,r,a,i){if(i<=-1)return new CellError(ErrorType.VALUE);var o=1e-7,s=i;a=a?1:0;for(var l=0;l<50;l++){if(s<=-1)return new CellError(ErrorType.NUM);var u=void 0;if(Math.abs(s)0||n>0&&t<0?new CellError(ErrorType.NUM):Math.pow(n/t,1/e)-1}))}},{key:"sln",value:function(e,t){return this.runFunction(e.args,t,this.metadata("SLN"),(function(e,t,n){return 0===n?new CellError(ErrorType.DIV_BY_ZERO):(e-t)/n}))}},{key:"syd",value:function(e,t){return this.runFunction(e.args,t,this.metadata("SYD"),(function(e,t,n,r){return r>n?new CellError(ErrorType.NUM):(e-t)*(n-r+1)*2/(n*(n+1))}))}},{key:"tbilleq",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("TBILLEQ"),(function(e,t,r){if((e=Math.round(e))>=(t=Math.round(t)))return new CellError(ErrorType.NUM);var a=n.dateTimeHelper.numberToSimpleDate(e),i=n.dateTimeHelper.numberToSimpleDate(t);if(i.year>a.year+1||i.year===a.year+1&&(i.month>a.month||i.month===a.month&&i.day>a.day))return new CellError(ErrorType.NUM);var o=360-r*(t-e);return 0===o?0:o<0?new CellError(ErrorType.NUM):365*r/o}))}},{key:"tbillprice",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("TBILLPRICE"),(function(e,t,r){if((e=Math.round(e))>=(t=Math.round(t)))return new CellError(ErrorType.NUM);var a=n.dateTimeHelper.numberToSimpleDate(e),i=n.dateTimeHelper.numberToSimpleDate(t);if(i.year>a.year+1||i.year===a.year+1&&(i.month>a.month||i.month===a.month&&i.day>a.day))return new CellError(ErrorType.NUM);var o=360-r*(t-e);return 0===o?0:o<0?new CellError(ErrorType.NUM):100*(1-r*(t-e)/360)}))}},{key:"tbillyield",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("TBILLYIELD"),(function(e,t,r){if((e=Math.round(e))>=(t=Math.round(t)))return new CellError(ErrorType.NUM);var a=n.dateTimeHelper.numberToSimpleDate(e),i=n.dateTimeHelper.numberToSimpleDate(t);return i.year>a.year+1||i.year===a.year+1&&(i.month>a.month||i.month===a.month&&i.day>a.day)?new CellError(ErrorType.NUM):360*(100-r)/(r*(t-e))}))}},{key:"fvschedule",value:function(e,t){return this.runFunction(e.args,t,this.metadata("FVSCHEDULE"),(function(e,t){var n,r=t.valuesFromTopLeftCorner(),a=_createForOfIteratorHelper$7(r);try{for(a.s();!(n=a.n()).done;){var i=n.value;if(i instanceof CellError)return i}}catch(e){a.e(e)}finally{a.f()}var o,s=_createForOfIteratorHelper$7(r);try{for(s.s();!(o=s.n()).done;){var l=o.value;if(isExtendedNumber(l))e*=1+getRawValue(l);else if(l!==EmptyValue)return new CellError(ErrorType.VALUE,ErrorMessage.NumberExpected)}}catch(e){s.e(e)}finally{s.f()}return e}))}},{key:"npv",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("NPV"),(function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),a=1;a0?(o=!0,l.push(p),u.push(0)):p<0?(s=!0,u.push(p),l.push(0)):(u.push(0),l.push(0))}}catch(e){c.e(e)}finally{c.f()}if(!o||!s)return new CellError(ErrorType.DIV_BY_ZERO);var d=a.length,m=npvCore(r,l);if(m instanceof CellError)return m;var f=npvCore(t,u);return f instanceof CellError?f:Math.pow(-m*Math.pow(1+r,d)/f/(1+t),1/(d-1))-1}))}},{key:"pduration",value:function(e,t){return this.runFunction(e.args,t,this.metadata("PDURATION"),(function(e,t,n){return(Math.log(n)-Math.log(t))/Math.log(1+e)}))}},{key:"xnpv",value:function(e,t){return this.runFunction(e.args,t,this.metadata("XNPV"),(function(e,t,n){var r,a=t.valuesFromTopLeftCorner(),i=_createForOfIteratorHelper$7(a);try{for(i.s();!(r=i.n()).done;){if("number"!=typeof r.value)return new CellError(ErrorType.VALUE,ErrorMessage.NumberExpected)}}catch(e){i.e(e)}finally{i.f()}var o,s=a,l=n.valuesFromTopLeftCorner(),u=_createForOfIteratorHelper$7(l);try{for(u.s();!(o=u.n()).done;){if("number"!=typeof o.value)return new CellError(ErrorType.VALUE,ErrorMessage.NumberExpected)}}catch(e){u.e(e)}finally{u.f()}var c=l;if(c.length!==s.length)return new CellError(ErrorType.NUM,ErrorMessage.EqualLength);var p=c.length,d=0;if(c[0]<0)return new CellError(ErrorType.NUM,ErrorMessage.ValueSmall);for(var m=0;m=0;r--){if(n+=t[r],-1===e){if(0===n)continue;return new CellError(ErrorType.DIV_BY_ZERO)}n/=1+e}return n}function _typeof$u(e){return _typeof$u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$u(e)}function _classCallCheck$t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$t(e,t){for(var n=0;ne.width()||t>e.height()?new CellError(ErrorType.NUM,ErrorMessage.ValueLarge):null!==(l=null!==(i=null===(a=null===(r=null==e?void 0:e.data)||void 0===r?void 0:r[t-1])||void 0===a?void 0:a[n-1])&&void 0!==i?i:null===(s=null===(o=null==e?void 0:e.data)||void 0===o?void 0:o[0])||void 0===s?void 0:s[0])&&void 0!==l?l:new CellError(ErrorType.VALUE,ErrorMessage.CellRangeExpected)}))}},{key:"na",value:function(e,t){return new CellError(ErrorType.NA)}},{key:"sheet",value:function(e,t){var n=this;return this.runFunctionWithReferenceArgument(e.args,t,this.metadata("SHEET"),(function(){return t.formulaAddress.sheet+1}),(function(e){return e.sheet+1}),(function(e){var t=n.dependencyGraph.sheetMapping.get(e);return void 0!==t?t+1:new CellError(ErrorType.NA,ErrorMessage.SheetRef)}))}},{key:"sheets",value:function(e,t){var n=this;return this.runFunctionWithReferenceArgument(e.args,t,this.metadata("SHEETS"),(function(){return n.dependencyGraph.sheetMapping.numberOfSheets()}),(function(){return 1}),(function(){return new CellError(ErrorType.VALUE,ErrorMessage.CellRefExpected)}))}}]),n}(FunctionPlugin);function _typeof$s(e){return _typeof$s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$s(e)}function _classCallCheck$r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$r(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n2&&void 0!==arguments[2]?arguments[2]:t;if(!e.hasOnlyNumbers())return new CellError(ErrorType.VALUE,ErrorMessage.NumberRange);var a=arraySizeForPoolFunction(e.size,t,r),i=n.createKernel((function(e,t,n){for(var r=this.thread.x*n,a=this.thread.y*n,i=e[a][r],o=0;o2&&void 0!==arguments[2]?arguments[2]:t;if(!e.hasOnlyNumbers())return new CellError(ErrorType.VALUE,ErrorMessage.NumberRange);var a=arraySizeForPoolFunction(e.size,t,r),i=n.createKernel((function(e,t,n){for(var r=this.thread.x*n,a=this.thread.y*n,i=e[a][r],o=0;oy&&b++;if(t%2==0){if(b===p/2){f=y;break}b>p/2?d=y:m=y}else{if(b===(p-1)/2){f=y;break}b>(p-1)/2?d=y:m=y}}return f}),a)(e.rawNumbers(),t,r);return SimpleRangeValue.onlyNumbers(i)}))}},{key:"maxpoolArraySize",value:function(e,t){var n=this;if(e.args.length<2||e.args.length>3)return ArraySize.error();var r,a=this.metadata("MAXPOOL"),i=e.args.map((function(e){var r;return n.arraySizeForAst(e,new InterpreterState(t.formulaAddress,t.arraysFlag||null!==(r=null==a?void 0:a.arrayFunction)&&void 0!==r&&r))})),o=i[0],s=e.args[1],l=r=s.type===AstNodeType.NUMBER?s.value:1;if(3===e.args.length){var u=e.args[2];l=u.type===AstNodeType.NUMBER?u.value:1}return r>o.width||r>o.height||l>r||(o.width-r)%l!=0||(o.height-r)%l!=0?ArraySize.error():arraySizeForPoolFunction(o,r,l)}},{key:"medianpoolArraySize",value:function(e,t){return this.maxpoolArraySize(e,t)}},{key:"transpose",value:function(e,t){return this.runFunction(e.args,t,this.metadata("TRANSPOSE"),(function(e){for(var t=e.rawData(),n=e.size,r=[],a=0;ar.length?new CellError(ErrorType.NUM,ErrorMessage.ValueLarge):r[r.length-t])}))}},{key:"small",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("SMALL"),(function(e,t){var r=n.arithmeticHelper.manyToExactNumbers(e.valuesFromTopLeftCorner());return r instanceof CellError?r:(r.sort((function(e,t){return e-t})),(t=Math.trunc(t))>r.length?new CellError(ErrorType.NUM,ErrorMessage.ValueLarge):r[t-1])}))}}]),n}(FunctionPlugin);function _typeof$m(e){return _typeof$m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$m(e)}function _classCallCheck$l(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$l(e,t){for(var n=0;n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$7(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$7(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$7(e,t):void 0}}function _arrayLikeToArray$7(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n0?this.sum/this.count:void 0}},{key:"varSValue",value:function(){return this.count>1?(this.sumsq-this.sum*this.sum/this.count)/(this.count-1):void 0}},{key:"varPValue",value:function(){return this.count>0?(this.sumsq-this.sum*this.sum/this.count)/this.count:void 0}}],[{key:"single",value:function(t){return new e(t*t,t,1)}}]),e}();MomentsAggregate.empty=new MomentsAggregate(0,0,0);var NumericAggregationPlugin=function(e){_inherits$j(n,e);var t=_createSuper$j(n);function n(){var e;return _classCallCheck$k(this,n),(e=t.apply(this,arguments)).addWithEpsilonRaw=function(t,n){return e.arithmeticHelper.addWithEpsilonRaw(t,n)},e}return _createClass$k(n,[{key:"sum",value:function(e,t){return this.doSum(e.args,t)}},{key:"sumsq",value:function(e,t){return this.reduce(e.args,t,0,"SUMSQ",this.addWithEpsilonRaw,(function(e){return Math.pow(getRawValue(e),2)}),strictlyNumbers)}},{key:"max",value:function(e,t){return this.doMax(e.args,t)}},{key:"maxa",value:function(e,t){return zeroForInfinite(this.reduce(e.args,t,Number.NEGATIVE_INFINITY,"MAXA",(function(e,t){return Math.max(e,t)}),getRawValue,numbersBooleans))}},{key:"min",value:function(e,t){return this.doMin(e.args,t)}},{key:"mina",value:function(e,t){return zeroForInfinite(this.reduce(e.args,t,Number.POSITIVE_INFINITY,"MINA",(function(e,t){return Math.min(e,t)}),getRawValue,numbersBooleans))}},{key:"count",value:function(e,t){return this.doCount(e.args,t)}},{key:"counta",value:function(e,t){return this.doCounta(e.args,t)}},{key:"average",value:function(e,t){return this.doAverage(e.args,t)}},{key:"averagea",value:function(e,t){var n,r=this.reduce(e.args,t,MomentsAggregate.empty,"_AGGREGATE_A",(function(e,t){return e.compose(t)}),(function(e){return MomentsAggregate.single(getRawValue(e))}),numbersBooleans);return r instanceof CellError?r:null!==(n=r.averageValue())&&void 0!==n?n:new CellError(ErrorType.DIV_BY_ZERO)}},{key:"vars",value:function(e,t){return this.doVarS(e.args,t)}},{key:"varp",value:function(e,t){return this.doVarP(e.args,t)}},{key:"vara",value:function(e,t){var n,r=this.reduceAggregateA(e.args,t);return r instanceof CellError?r:null!==(n=r.varSValue())&&void 0!==n?n:new CellError(ErrorType.DIV_BY_ZERO)}},{key:"varpa",value:function(e,t){var n,r=this.reduceAggregateA(e.args,t);return r instanceof CellError?r:null!==(n=r.varPValue())&&void 0!==n?n:new CellError(ErrorType.DIV_BY_ZERO)}},{key:"stdevs",value:function(e,t){return this.doStdevS(e.args,t)}},{key:"stdevp",value:function(e,t){return this.doStdevP(e.args,t)}},{key:"stdeva",value:function(e,t){var n=this.reduceAggregateA(e.args,t);if(n instanceof CellError)return n;var r=n.varSValue();return void 0===r?new CellError(ErrorType.DIV_BY_ZERO):Math.sqrt(r)}},{key:"stdevpa",value:function(e,t){var n=this.reduceAggregateA(e.args,t);if(n instanceof CellError)return n;var r=n.varPValue();return void 0===r?new CellError(ErrorType.DIV_BY_ZERO):Math.sqrt(r)}},{key:"product",value:function(e,t){return this.doProduct(e.args,t)}},{key:"subtotal",value:function(e,t){if(e.args.length<2)return new CellError(ErrorType.NA,ErrorMessage.WrongArgNumber);var n=this.coerceToType(this.evaluateAst(e.args[0],t),{argumentType:ArgumentTypes.NUMBER},t),r=e.args.slice(1);switch(n){case 1:case 101:return this.doAverage(r,t);case 2:case 102:return this.doCount(r,t);case 3:case 103:return this.doCounta(r,t);case 4:case 104:return this.doMax(r,t);case 5:case 105:return this.doMin(r,t);case 6:case 106:return this.doProduct(r,t);case 7:case 107:return this.doStdevS(r,t);case 8:case 108:return this.doStdevP(r,t);case 9:case 109:return this.doSum(r,t);case 10:case 110:return this.doVarS(r,t);case 11:case 111:return this.doVarP(r,t);default:return new CellError(ErrorType.VALUE,ErrorMessage.BadMode)}}},{key:"reduceAggregate",value:function(e,t){return this.reduce(e,t,MomentsAggregate.empty,"_AGGREGATE",(function(e,t){return e.compose(t)}),(function(e){return MomentsAggregate.single(getRawValue(e))}),strictlyNumbers)}},{key:"reduceAggregateA",value:function(e,t){return this.reduce(e,t,MomentsAggregate.empty,"_AGGREGATE_A",(function(e,t){return e.compose(t)}),(function(e){return MomentsAggregate.single(getRawValue(e))}),numbersBooleans)}},{key:"doAverage",value:function(e,t){var n,r=this.reduceAggregate(e,t);return r instanceof CellError?r:null!==(n=r.averageValue())&&void 0!==n?n:new CellError(ErrorType.DIV_BY_ZERO)}},{key:"doVarS",value:function(e,t){var n,r=this.reduceAggregate(e,t);return r instanceof CellError?r:null!==(n=r.varSValue())&&void 0!==n?n:new CellError(ErrorType.DIV_BY_ZERO)}},{key:"doVarP",value:function(e,t){var n,r=this.reduceAggregate(e,t);return r instanceof CellError?r:null!==(n=r.varPValue())&&void 0!==n?n:new CellError(ErrorType.DIV_BY_ZERO)}},{key:"doStdevS",value:function(e,t){var n=this.reduceAggregate(e,t);if(n instanceof CellError)return n;var r=n.varSValue();return void 0===r?new CellError(ErrorType.DIV_BY_ZERO):Math.sqrt(r)}},{key:"doStdevP",value:function(e,t){var n=this.reduceAggregate(e,t);if(n instanceof CellError)return n;var r=n.varPValue();return void 0===r?new CellError(ErrorType.DIV_BY_ZERO):Math.sqrt(r)}},{key:"doCount",value:function(e,t){return this.reduce(e,t,0,"COUNT",(function(e,t){return e+t}),getRawValue,(function(e){return isExtendedNumber(e)?1:0}))}},{key:"doCounta",value:function(e,t){return this.reduce(e,t,0,"COUNTA",(function(e,t){return e+t}),getRawValue,(function(e){return e===EmptyValue?0:1}))}},{key:"doMax",value:function(e,t){return zeroForInfinite(this.reduce(e,t,Number.NEGATIVE_INFINITY,"MAX",(function(e,t){return Math.max(e,t)}),getRawValue,strictlyNumbers))}},{key:"doMin",value:function(e,t){return zeroForInfinite(this.reduce(e,t,Number.POSITIVE_INFINITY,"MIN",(function(e,t){return Math.min(e,t)}),getRawValue,strictlyNumbers))}},{key:"doSum",value:function(e,t){return this.reduce(e,t,0,"SUM",this.addWithEpsilonRaw,getRawValue,strictlyNumbers)}},{key:"doProduct",value:function(e,t){return this.reduce(e,t,1,"PRODUCT",(function(e,t){return e*t}),getRawValue,strictlyNumbers)}},{key:"reduce",value:function(e,t,n,r,a,i,o){var s=this;return e.length<1?new CellError(ErrorType.NA,ErrorMessage.WrongArgNumber):e.reduce((function(e,l){if(e instanceof CellError)return e;if(l.type===AstNodeType.CELL_RANGE||l.type===AstNodeType.COLUMN_RANGE||l.type===AstNodeType.ROW_RANGE){var u=s.evaluateRange(l,t,n,r,a,i,o);return u instanceof CellError?u:a(u,e)}var c;if((c=s.evaluateAst(l,t))instanceof SimpleRangeValue){var p=Array.from(c.valuesFromTopLeftCorner()).map(o).filter((function(e){return void 0!==e}));return p.map((function(e){return e instanceof CellError?e:i(e)})).reduce((function(e,t){return e instanceof CellError?e:t instanceof CellError?t:a(e,t)}),e)}if(l.type===AstNodeType.CELL_REFERENCE){if(void 0===(c=o(c)))return e}else if(c=s.coerceScalarToNumberOrError(c),void 0===(c=o(c)))return e;return c instanceof CellError?c:a(e,i(c))}),n)}},{key:"evaluateRange",value:function(e,t,n,r,a,i,o){var s;try{s=AbsoluteCellRange.fromAst(e,t.formulaAddress)}catch(e){if(e instanceof SheetsNotEqual)return new CellError(ErrorType.REF,ErrorMessage.RangeManySheets);throw e}var l=s.start,u=s.end,c=this.dependencyGraph.getRange(l,u);if(void 0===c)throw new Error("Range does not exists in graph");var p=c.getFunctionValue(r);void 0===p&&(p=this.getRangeValues(r,s,i,o).reduce((function(e,t){return e instanceof CellError?e:t instanceof CellError?t:a(e,t)}),n),c.setFunctionValue(r,p));return p}},{key:"getRangeValues",value:function(e,t,n,r){var a,i=[],o=this.dependencyGraph.rangeMapping.findSmallerRange(t),s=o.smallerRangeVertex,l=o.restRange,u=this.dependencyGraph.getRange(t.start,t.end);if(void 0!==s&&this.dependencyGraph.existsEdge(s,u)){var c=s.getFunctionValue(e);if(void 0!==c)i.push(c);else{var p,d=_createForOfIteratorHelper$6(s.range.addresses(this.dependencyGraph));try{for(d.s();!(p=d.n()).done;){var m=p.value,f=r(this.dependencyGraph.getScalarValue(m));f instanceof CellError?i.push(f):void 0!==f&&i.push(n(f))}}catch(e){d.e(e)}finally{d.f()}}a=l}else a=t;var h,y=_createForOfIteratorHelper$6(a.addresses(this.dependencyGraph));try{for(y.s();!(h=y.n()).done;){var b=h.value,g=r(this.dependencyGraph.getScalarValue(b));g instanceof CellError?i.push(g):void 0!==g&&i.push(n(g))}}catch(e){y.e(e)}finally{y.f()}return i}}]),n}(FunctionPlugin);function strictlyNumbers(e){return isExtendedNumber(e)||e instanceof CellError?e:void 0}function numbersBooleans(e){return"boolean"==typeof e?coerceBooleanToNumber(e):isExtendedNumber(e)||e instanceof CellError?e:"string"==typeof e?0:void 0}function _typeof$k(e){return _typeof$k="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$k(e)}function _classCallCheck$j(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$j(e,t){for(var n=0;nn)&&a.test(e))return e}function decimalToBaseWithExactPadding(e,t,n){if(e>maxValFromBase(t))return new CellError(ErrorType.NUM,ErrorMessage.ValueBaseLarge);if(en?new CellError(ErrorType.NUM,ErrorMessage.ValueBaseLong):padLeft(r,n)}function minValFromBase(e){return-Math.pow(e,MAX_LENGTH)/2}function maxValFromBase(e){return-minValFromBase(e)-1}function decimalToBaseWithMinimumPadding(e,t,n){var r=decimalToRadixComplement(e,t);return void 0!==n&&n>r.length?padLeft(r,n):r}function decimalToRadixComplement(e,t){return(e+(e<0?Math.pow(t,MAX_LENGTH):0)).toString(t).toUpperCase()}function twoComplementToDecimal(e,t){var n=parseInt(e,t),r=Math.pow(t,MAX_LENGTH);return n>=r/2?n-r:n}function _typeof$h(e){return _typeof$h="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$h(e)}function _classCallCheck$g(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$g(e,t){for(var n=0;n0&&t<0?new CellError(ErrorType.NUM,ErrorMessage.DistinctSigns):Math.ceil(e/t)*t}))}},{key:"ceilingprecise",value:function(e,t){return this.runFunction(e.args,t,this.metadata("CEILING.PRECISE"),(function(e,t){return 0===t||0===e?0:(t=Math.abs(t),Math.ceil(e/t)*t)}))}},{key:"floormath",value:function(e,t){return this.runFunction(e.args,t,this.metadata("FLOOR.MATH"),(function(e,t,n){return 0===t||0===e?0:(t=Math.abs(t),1===n&&e<0&&(t*=-1),Math.floor(e/t)*t)}))}},{key:"floor",value:function(e,t){return this.runFunction(e.args,t,this.metadata("FLOOR"),(function(e,t){return 0===e?0:0===t?new CellError(ErrorType.DIV_BY_ZERO):e>0&&t<0?new CellError(ErrorType.NUM,ErrorMessage.DistinctSigns):Math.floor(e/t)*t}))}},{key:"floorprecise",value:function(e,t){return this.runFunction(e.args,t,this.metadata("FLOOR.PRECISE"),(function(e,t){return 0===t||0===e?0:(t=Math.abs(t),Math.floor(e/t)*t)}))}}]),n}(FunctionPlugin);function _typeof$f(e){return _typeof$f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$f(e)}function _classCallCheck$e(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$e(e,t){for(var n=0;n=0;--a){var i=this.tryEntries[a],o=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev=0;--r){var a=this.tryEntries[r];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),C(n),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:S(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),c}},e}SqrtPlugin.implementedFunctions={SQRT:{method:"sqrt",parameters:[{argumentType:ArgumentTypes.NUMBER}]}};var _marked$1=_regeneratorRuntime$1().mark(empty); + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +const MAX_LENGTH=10,DECIMAL_NUMBER_OF_BITS=255,MIN_BASE=2,MAX_BASE=36,ALPHABET="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";class RadixConversionPlugin extends FunctionPlugin{dec2bin(e,t){return this.runFunction(e.args,t,this.metadata("DEC2BIN"),((e,t)=>decimalToBaseWithExactPadding(e,2,t)))}dec2oct(e,t){return this.runFunction(e.args,t,this.metadata("DEC2OCT"),((e,t)=>decimalToBaseWithExactPadding(e,8,t)))}dec2hex(e,t){return this.runFunction(e.args,t,this.metadata("DEC2HEX"),((e,t)=>decimalToBaseWithExactPadding(e,16,t)))}bin2dec(e,t){return this.runFunction(e.args,t,this.metadata("BIN2DEC"),(e=>{const t=coerceStringToBase(e,2,MAX_LENGTH);return void 0===t?new CellError(ErrorType.NUM,ErrorMessage.NotBinary):twoComplementToDecimal(t,2)}))}bin2oct(e,t){return this.runFunction(e.args,t,this.metadata("BIN2OCT"),((e,t)=>{const n=coerceStringToBase(e,2,MAX_LENGTH);return void 0===n?new CellError(ErrorType.NUM,ErrorMessage.NotBinary):decimalToBaseWithExactPadding(twoComplementToDecimal(n,2),8,t)}))}bin2hex(e,t){return this.runFunction(e.args,t,this.metadata("BIN2HEX"),((e,t)=>{const n=coerceStringToBase(e,2,MAX_LENGTH);return void 0===n?new CellError(ErrorType.NUM,ErrorMessage.NotBinary):decimalToBaseWithExactPadding(twoComplementToDecimal(n,2),16,t)}))}oct2dec(e,t){return this.runFunction(e.args,t,this.metadata("OCT2DEC"),(e=>{const t=coerceStringToBase(e,8,MAX_LENGTH);return void 0===t?new CellError(ErrorType.NUM,ErrorMessage.NotOctal):twoComplementToDecimal(t,8)}))}oct2bin(e,t){return this.runFunction(e.args,t,this.metadata("OCT2BIN"),((e,t)=>{const n=coerceStringToBase(e,8,MAX_LENGTH);return void 0===n?new CellError(ErrorType.NUM,ErrorMessage.NotOctal):decimalToBaseWithExactPadding(twoComplementToDecimal(n,8),2,t)}))}oct2hex(e,t){return this.runFunction(e.args,t,this.metadata("OCT2HEX"),((e,t)=>{const n=coerceStringToBase(e,8,MAX_LENGTH);return void 0===n?new CellError(ErrorType.NUM,ErrorMessage.NotOctal):decimalToBaseWithExactPadding(twoComplementToDecimal(n,8),16,t)}))}hex2dec(e,t){return this.runFunction(e.args,t,this.metadata("HEX2DEC"),(e=>{const t=coerceStringToBase(e,16,MAX_LENGTH);return void 0===t?new CellError(ErrorType.NUM,ErrorMessage.NotHex):twoComplementToDecimal(t,16)}))}hex2bin(e,t){return this.runFunction(e.args,t,this.metadata("HEX2BIN"),((e,t)=>{const n=coerceStringToBase(e,16,MAX_LENGTH);return void 0===n?new CellError(ErrorType.NUM,ErrorMessage.NotHex):decimalToBaseWithExactPadding(twoComplementToDecimal(n,16),2,t)}))}hex2oct(e,t){return this.runFunction(e.args,t,this.metadata("HEX2OCT"),((e,t)=>{const n=coerceStringToBase(e,16,MAX_LENGTH);return void 0===n?new CellError(ErrorType.NUM,ErrorMessage.NotHex):decimalToBaseWithExactPadding(twoComplementToDecimal(n,16),8,t)}))}base(e,t){return this.runFunction(e.args,t,this.metadata("BASE"),decimalToBaseWithMinimumPadding)}decimal(e,t){return this.runFunction(e.args,t,this.metadata("DECIMAL"),((e,t)=>{const n=coerceStringToBase(e,t,DECIMAL_NUMBER_OF_BITS);return void 0===n?new CellError(ErrorType.NUM,ErrorMessage.NotHex):parseInt(n,t)}))}}function coerceStringToBase(e,t,n){const r=ALPHABET.substr(0,t),a=new RegExp(`^[${r}]+$`);if(!(e.length>n)&&a.test(e))return e}function decimalToBaseWithExactPadding(e,t,n){if(e>maxValFromBase(t))return new CellError(ErrorType.NUM,ErrorMessage.ValueBaseLarge);if(en?new CellError(ErrorType.NUM,ErrorMessage.ValueBaseLong):padLeft(r,n)}function minValFromBase(e){return-Math.pow(e,MAX_LENGTH)/2}function maxValFromBase(e){return-minValFromBase(e)-1}function decimalToBaseWithMinimumPadding(e,t,n){const r=decimalToRadixComplement(e,t);return void 0!==n&&n>r.length?padLeft(r,n):r}function decimalToRadixComplement(e,t){return(e+(e<0?Math.pow(t,MAX_LENGTH):0)).toString(t).toUpperCase()}function twoComplementToDecimal(e,t){const n=parseInt(e,t),r=Math.pow(t,MAX_LENGTH);return n>=r/2?n-r:n} /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */function empty(){return _regeneratorRuntime$1().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:case"end":return e.stop()}}),_marked$1)}function split(e){var t=e[Symbol.iterator](),n=t.next(),r=n.done,a=n.value;return r?{rest:empty()}:{value:a,rest:t}}function _typeof$d(e){return _typeof$d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$d(e)}function _regeneratorRuntime(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */_regeneratorRuntime=function(){return e};var e={},t=Object.prototype,n=t.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},a=r.iterator||"@@iterator",i=r.asyncIterator||"@@asyncIterator",o=r.toStringTag||"@@toStringTag";function s(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{s({},"")}catch(e){s=function(e,t,n){return e[t]=n}}function l(e,t,n,r){var a=t&&t.prototype instanceof p?t:p,i=Object.create(a.prototype),o=new A(r||[]);return i._invoke=function(e,t,n){var r="suspendedStart";return function(a,i){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===a)throw i;return x()}for(n.method=a,n.arg=i;;){var o=n.delegate;if(o){var s=T(o,n);if(s){if(s===c)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var l=u(e,t,n);if("normal"===l.type){if(r=n.done?"completed":"suspendedYield",l.arg===c)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(r="completed",n.method="throw",n.arg=l.arg)}}}(e,n,o),i}function u(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}e.wrap=l;var c={};function p(){}function d(){}function m(){}var f={};s(f,a,(function(){return this}));var h=Object.getPrototypeOf,y=h&&h(h(S([])));y&&y!==t&&n.call(y,a)&&(f=y);var b=m.prototype=p.prototype=Object.create(f);function g(e){["next","throw","return"].forEach((function(t){s(e,t,(function(e){return this._invoke(t,e)}))}))}function v(e,t){function r(a,i,o,s){var l=u(e[a],e,i);if("throw"!==l.type){var c=l.arg,p=c.value;return p&&"object"==_typeof$d(p)&&n.call(p,"__await")?t.resolve(p.__await).then((function(e){r("next",e,o,s)}),(function(e){r("throw",e,o,s)})):t.resolve(p).then((function(e){c.value=e,o(c)}),(function(e){return r("throw",e,o,s)}))}s(l.arg)}var a;this._invoke=function(e,n){function i(){return new t((function(t,a){r(e,n,t,a)}))}return a=a?a.then(i,i):i()}}function T(e,t){var n=e.iterator[t.method];if(void 0===n){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,T(e,t),"throw"===t.method))return c;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return c}var r=u(n,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,c;var a=r.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,c):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,c)}function N(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function C(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function A(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(N,this),this.reset(!0)}function S(e){if(e){var t=e[a];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,i=function t(){for(;++r=0;--a){var i=this.tryEntries[a],o=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),l=n.call(i,"finallyLoc");if(s&&l){if(this.prev=0;--r){var a=this.tryEntries[r];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),C(n),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:S(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),c}},e}var _marked=_regeneratorRuntime().mark(getRangeValues),_marked2=_regeneratorRuntime().mark(ifFilter);function _slicedToArray$1(e,t){return _arrayWithHoles$1(e)||_iterableToArrayLimit$1(e,t)||_unsupportedIterableToArray$6(e,t)||_nonIterableRest$1()}function _nonIterableRest$1(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArrayLimit$1(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,a,i=[],o=!0,s=!1;try{for(n=n.call(e);!(o=(r=n.next()).done)&&(i.push(r.value),!t||i.length!==t);o=!0);}catch(e){s=!0,a=e}finally{try{o||null==n.return||n.return()}finally{if(s)throw a}}return i}}function _arrayWithHoles$1(e){if(Array.isArray(e))return e}function _createForOfIteratorHelper$5(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$6(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$6(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$6(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$6(e,t):void 0}}function _arrayLikeToArray$6(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);nn.start.row){var r=simpleCellAddress(n.end.sheet,n.end.col,n.end.row-1),a=e.getRange(n.start,r);if(void 0!==a)return{smallerRangeVertex:a,restValuesRange:n.withStart(simpleCellAddress(n.start.sheet,n.start.col,n.end.row)),restConditionRanges:t.map((function(e){return e.withStart(simpleCellAddress(e.start.sheet,e.start.col,e.end.row))}))}}return{restValuesRange:n,restConditionRanges:t}},CriterionFunctionCompute=function(){function e(t,n,r,a,i){_classCallCheck$d(this,e),this.interpreter=t,this.cacheKey=n,this.reduceInitialValue=r,this.composeFunction=a,this.mapFunction=i,this.dependencyGraph=this.interpreter.dependencyGraph}return _createClass$d(e,[{key:"compute",value:function(e,t){var n,r=this,a=_createForOfIteratorHelper$5(t);try{for(a.s();!(n=a.n()).done;){if(!n.value.conditionRange.sameDimensionsAs(e))return new CellError(ErrorType.VALUE,ErrorMessage.EqualLength)}}catch(e){a.e(e)}finally{a.f()}var i=this.tryToGetRangeVertexForRangeValue(e),o=t.map((function(e){return r.tryToGetRangeVertexForRangeValue(e.conditionRange)}));if(i&&o.every((function(e){return void 0!==e}))){var s=t.map((function(e){return e.criterionPackage.raw})).join(","),l=this.findAlreadyComputedValueInCache(i,this.cacheKey(t),s);if(void 0!==l)return this.interpreter.stats.incrementCriterionFunctionFullCacheUsed(),l;var u=this.buildNewCriterionCache(this.cacheKey(t),t.map((function(e){return e.conditionRange.range})),e.range);return u.has(s)||u.set(s,[this.evaluateRangeValue(e,t),t.map((function(e){return e.criterionPackage.lambda}))]),i.setCriterionFunctionValues(this.cacheKey(t),u),o.forEach((function(e){void 0!==e&&e.addDependentCacheRange(i)})),u.get(s)[0]}return this.evaluateRangeValue(e,t)}},{key:"tryToGetRangeVertexForRangeValue",value:function(e){var t=e.range;return void 0===t?void 0:this.dependencyGraph.getRange(t.start,t.end)}},{key:"reduceFunction",value:function(e){var t,n=this.reduceInitialValue,r=_createForOfIteratorHelper$5(e);try{for(r.s();!(t=r.n()).done;){var a=t.value;n=this.composeFunction(n,a)}}catch(e){r.e(e)}finally{r.f()}return n}},{key:"findAlreadyComputedValueInCache",value:function(e,t,n){return e.getCriterionFunctionValue(t,n)}},{key:"evaluateRangeValue",value:function(e,t){var n=t.map((function(e){return e.criterionPackage.lambda})),r=Array.from(e.valuesFromTopLeftCorner()).map(this.mapFunction)[Symbol.iterator](),a=ifFilter(n,t.map((function(e){return e.conditionRange.iterateValuesFromTopLeftCorner()})),r);return this.reduceFunction(a)}},{key:"buildNewCriterionCache",value:function(e,t,n){var r,a=this,i=this.dependencyGraph.getRange(n.start,n.end),o=findSmallerRangeForMany(this.dependencyGraph,t,n),s=o.smallerRangeVertex,l=o.restConditionRanges,u=o.restValuesRange;r=void 0!==s&&this.dependencyGraph.existsEdge(s,i)?s.getCriterionFunctionValues(e):new Map;var c=new Map;return r.forEach((function(e,t){var n=_slicedToArray$1(e,2),r=n[0],i=n[1],o=ifFilter(i,l.map((function(e){return getRangeValues(a.dependencyGraph,e)})),Array.from(getRangeValues(a.dependencyGraph,u)).map(a.mapFunction)[Symbol.iterator]()),s=a.composeFunction(r,a.reduceFunction(o));a.interpreter.stats.incrementCriterionFunctionPartialCacheUsed(),c.set(t,[s,i])})),c}}]),e}(),Condition=_createClass$d((function e(t,n){_classCallCheck$d(this,e),this.conditionRange=t,this.criterionPackage=n}));function getRangeValues(e,t){var n,r,a;return _regeneratorRuntime().wrap((function(i){for(;;)switch(i.prev=i.next){case 0:n=_createForOfIteratorHelper$5(t.addresses(e)),i.prev=1,n.s();case 3:if((r=n.n()).done){i.next=9;break}return a=r.value,i.next=7,getRawValue(e.getScalarValue(a));case 7:i.next=3;break;case 9:i.next=14;break;case 11:i.prev=11,i.t0=i.catch(1),n.e(i.t0);case 14:return i.prev=14,n.f(),i.finish(14);case 17:case"end":return i.stop()}}),_marked,null,[[1,11,14,17]])}function ifFilter(e,t,n){var r,a,i,o;return _regeneratorRuntime().wrap((function(s){for(;;)switch(s.prev=s.next){case 0:r=_createForOfIteratorHelper$5(n),s.prev=1,r.s();case 3:if((a=r.n()).done){s.next=15;break}if(i=a.value,(o=t.map((function(e){return split(e)}))).every((function(e){return Object.prototype.hasOwnProperty.call(e,"value")}))){s.next=8;break}return s.abrupt("return");case 8:if(!zip(o.map((function(e){return e.value})),e).every((function(e){var t=_slicedToArray$1(e,2),n=t[0];return(0,t[1])(n)}))){s.next=12;break}return s.next=12,i;case 12:t=o.map((function(e){return e.rest}));case 13:s.next=3;break;case 15:s.next=20;break;case 17:s.prev=17,s.t0=s.catch(1),r.e(s.t0);case 20:return s.prev=20,r.f(),s.finish(20);case 23:case"end":return s.stop()}}),_marked2,null,[[1,17,20,23]])}function zip(e,t){for(var n=[],r=0;re.length)&&(t=e.length);for(var n=0,r=new Array(t);n0?this.sum/this.count:void 0}}],[{key:"single",value:function(t){return new e(t,1)}}]),e}();function sumifCacheKey(e){var t=e.map((function(e){return"".concat(e.conditionRange.range.sheet,",").concat(e.conditionRange.range.start.col,",").concat(e.conditionRange.range.start.row)}));return["SUMIF"].concat(_toConsumableArray(t)).join(",")}function averageifCacheKey(e){var t=e.map((function(e){return"".concat(e.conditionRange.range.sheet,",").concat(e.conditionRange.range.start.col,",").concat(e.conditionRange.range.start.row)}));return["AVERAGEIF"].concat(_toConsumableArray(t)).join(",")}function countifsCacheKey(e){var t=e.map((function(e){return"".concat(e.conditionRange.range.sheet,",").concat(e.conditionRange.range.start.col,",").concat(e.conditionRange.range.start.row)}));return["COUNTIFS"].concat(_toConsumableArray(t)).join(",")}AverageResult.empty=new AverageResult(0,0);var SumifPlugin=function(e){_inherits$c(n,e);var t=_createSuper$c(n);function n(){return _classCallCheck$c(this,n),t.apply(this,arguments)}return _createClass$c(n,[{key:"sumif",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("SUMIF"),(function(e,t,r){var a=n.interpreter.criterionBuilder.fromCellValue(t,n.arithmeticHelper);return void 0===a?new CellError(ErrorType.VALUE,ErrorMessage.BadCriterion):(r=null!=r?r:e,new CriterionFunctionCompute(n.interpreter,sumifCacheKey,0,(function(e,t){return n.arithmeticHelper.nonstrictadd(e,t)}),(function(e){return getRawValue(e)})).compute(r,[new Condition(e,a)]))}))}},{key:"sumifs",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("SUMIFS"),(function(e){for(var t=[],r=0;r<(arguments.length<=1?0:arguments.length-1);r+=2){var a=r+1<1||arguments.length<=r+1?void 0:arguments[r+1],i=n.interpreter.criterionBuilder.fromCellValue(r+1+1<1||arguments.length<=r+1+1?void 0:arguments[r+1+1],n.arithmeticHelper);if(void 0===i)return new CellError(ErrorType.VALUE,ErrorMessage.BadCriterion);t.push(new Condition(a,i))}return new CriterionFunctionCompute(n.interpreter,sumifCacheKey,0,(function(e,t){return n.arithmeticHelper.nonstrictadd(e,t)}),(function(e){return getRawValue(e)})).compute(e,t)}))}},{key:"averageif",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("AVERAGEIF"),(function(e,t,r){var a=n.interpreter.criterionBuilder.fromCellValue(t,n.arithmeticHelper);if(void 0===a)return new CellError(ErrorType.VALUE,ErrorMessage.BadCriterion);r=null!=r?r:e;var i=new CriterionFunctionCompute(n.interpreter,averageifCacheKey,AverageResult.empty,(function(e,t){return e.compose(t)}),(function(e){return isExtendedNumber(e)?AverageResult.single(getRawValue(e)):AverageResult.empty})).compute(r,[new Condition(e,a)]);return i instanceof CellError?i:i.averageValue()||new CellError(ErrorType.DIV_BY_ZERO)}))}},{key:"countif",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("COUNTIF"),(function(e,t){var r=n.interpreter.criterionBuilder.fromCellValue(t,n.arithmeticHelper);return void 0===r?new CellError(ErrorType.VALUE,ErrorMessage.BadCriterion):new CriterionFunctionCompute(n.interpreter,(function(){return"COUNTIF"}),0,(function(e,t){return e+t}),(function(){return 1})).compute(e,[new Condition(e,r)])}))}},{key:"countifs",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("COUNTIFS"),(function(){for(var e=[],t=0;t=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$4(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$4(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$4(e,t):void 0}}function _arrayLikeToArray$4(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=n.length||t<0?new CellError(ErrorType.VALUE,ErrorMessage.IndexBounds):n[t]}))}},{key:"len",value:function(e,t){return this.runFunction(e.args,t,this.metadata("LEN"),(function(e){return e.length}))}},{key:"lower",value:function(e,t){return this.runFunction(e.args,t,this.metadata("LOWER"),(function(e){return e.toLowerCase()}))}},{key:"trim",value:function(e,t){return this.runFunction(e.args,t,this.metadata("TRIM"),(function(e){return e.replace(/^ +| +$/g,"").replace(/ +/g," ")}))}},{key:"proper",value:function(e,t){return this.runFunction(e.args,t,this.metadata("PROPER"),(function(e){return e.replace(/(?:[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDF70-\uDF81\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDEB8\uDF00-\uDF1A\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE70-\uDEBE\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD837[\uDF00-\uDF1E]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB]|\uD839[\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF38\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])+/g,(function(e){return e.charAt(0).toUpperCase()+e.substring(1).toLowerCase()}))}))}},{key:"clean",value:function(e,t){return this.runFunction(e.args,t,this.metadata("CLEAN"),(function(e){return e.replace(/[\u0000-\u001F]/g,"")}))}},{key:"exact",value:function(e,t){return this.runFunction(e.args,t,this.metadata("EXACT"),(function(e,t){return e===t}))}},{key:"rept",value:function(e,t){return this.runFunction(e.args,t,this.metadata("REPT"),(function(e,t){return t<0?new CellError(ErrorType.VALUE,ErrorMessage.NegativeCount):e.repeat(t)}))}},{key:"right",value:function(e,t){return this.runFunction(e.args,t,this.metadata("RIGHT"),(function(e,t){return t<0?new CellError(ErrorType.VALUE,ErrorMessage.NegativeLength):0===t?"":e.slice(-t)}))}},{key:"left",value:function(e,t){return this.runFunction(e.args,t,this.metadata("LEFT"),(function(e,t){return t<0?new CellError(ErrorType.VALUE,ErrorMessage.NegativeLength):e.slice(0,t)}))}},{key:"mid",value:function(e,t){return this.runFunction(e.args,t,this.metadata("MID"),(function(e,t,n){return t<1?new CellError(ErrorType.VALUE,ErrorMessage.LessThanOne):n<0?new CellError(ErrorType.VALUE,ErrorMessage.NegativeLength):e.substring(t-1,t+n-1)}))}},{key:"replace",value:function(e,t){return this.runFunction(e.args,t,this.metadata("REPLACE"),(function(e,t,n,r){return t<1?new CellError(ErrorType.VALUE,ErrorMessage.LessThanOne):n<0?new CellError(ErrorType.VALUE,ErrorMessage.NegativeLength):e.substring(0,t-1)+r+e.substring(t+n-1)}))}},{key:"search",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("SEARCH"),(function(e,t,r){if(r<1||r>t.length)return new CellError(ErrorType.VALUE,ErrorMessage.LengthBounds);var a,i=t.substring(r-1).toLowerCase();return a=n.arithmeticHelper.requiresRegex(e)?n.arithmeticHelper.searchString(e,i):i.indexOf(e.toLowerCase()),(a+=r)>0?a:new CellError(ErrorType.VALUE,ErrorMessage.PatternNotFound)}))}},{key:"substitute",value:function(e,t){return this.runFunction(e.args,t,this.metadata("SUBSTITUTE"),(function(e,t,n,r){var a,i=new RegExp(t,"g");if(void 0===r)return e.replace(i,n);if(r<1)return new CellError(ErrorType.VALUE,ErrorMessage.LessThanOne);for(var o=0;null!==(a=i.exec(e));)if(r===++o)return e.substring(0,a.index)+n+e.substring(i.lastIndex);return e}))}},{key:"find",value:function(e,t){return this.runFunction(e.args,t,this.metadata("FIND"),(function(e,t,n){if(n<1||n>t.length)return new CellError(ErrorType.VALUE,ErrorMessage.IndexBounds);var r=t.substring(n-1).indexOf(e)+n;return r>0?r:new CellError(ErrorType.VALUE,ErrorMessage.PatternNotFound)}))}},{key:"t",value:function(e,t){return this.runFunction(e.args,t,this.metadata("T"),(function(e){return e instanceof CellError||"string"==typeof e?e:""}))}},{key:"upper",value:function(e,t){return this.runFunction(e.args,t,this.metadata("UPPER"),(function(e){return e.toUpperCase()}))}}]),n}(FunctionPlugin);TextPlugin.implementedFunctions={CONCATENATE:{method:"concatenate",parameters:[{argumentType:ArgumentTypes.STRING}],repeatLastArgs:1,expandRanges:!0},EXACT:{method:"exact",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.STRING}]},SPLIT:{method:"split",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER}]},LEN:{method:"len",parameters:[{argumentType:ArgumentTypes.STRING}]},LOWER:{method:"lower",parameters:[{argumentType:ArgumentTypes.STRING}]},MID:{method:"mid",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER}]},TRIM:{method:"trim",parameters:[{argumentType:ArgumentTypes.STRING}]},T:{method:"t",parameters:[{argumentType:ArgumentTypes.SCALAR}]},PROPER:{method:"proper",parameters:[{argumentType:ArgumentTypes.STRING}]},CLEAN:{method:"clean",parameters:[{argumentType:ArgumentTypes.STRING}]},REPT:{method:"rept",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER}]},RIGHT:{method:"right",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]},LEFT:{method:"left",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]},REPLACE:{method:"replace",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.STRING}]},SEARCH:{method:"search",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]},SUBSTITUTE:{method:"substitute",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER,optionalArg:!0}]},FIND:{method:"find",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]},UPPER:{method:"upper",parameters:[{argumentType:ArgumentTypes.STRING}]}};var $expm1=Math.expm1,exp$3=Math.exp,mathExpm1=!$expm1||$expm1(10)>22025.465794806718||$expm1(10)<22025.465794806718||-2e-17!=$expm1(-2e-17)?function(e){var t=+e;return 0==t?t:t>-1e-6&&t<1e-6?t+t*t/2:exp$3(t)-1}:$expm1,$$8=_export,fails=fails$G,expm1$2=mathExpm1,abs$2=Math.abs,exp$2=Math.exp,E$3=Math.E,FORCED$1=fails((function(){return-2e-17!=Math.sinh(-2e-17)}));$$8({target:"Math",stat:!0,forced:FORCED$1},{sinh:function(e){var t=+e;return abs$2(t)<1?(expm1$2(t)-expm1$2(-t))/2:(exp$2(t-1)-exp$2(-t-1))*(E$3/2)}});var $$7=_export,$asinh=Math.asinh,log$3=Math.log,sqrt$1=Math.sqrt;function asinh(e){var t=+e;return isFinite(t)&&0!=t?t<0?-asinh(-t):log$3(t+sqrt$1(t*t+1)):t}$$7({target:"Math",stat:!0,forced:!($asinh&&1/$asinh(0)>0)},{asinh:asinh});var $$6=_export,expm1$1=mathExpm1,$cosh=Math.cosh,abs$1=Math.abs,E$2=Math.E;$$6({target:"Math",stat:!0,forced:!$cosh||$cosh(710)===1/0},{cosh:function(e){var t=expm1$1(abs$1(e)-1)+1;return(t+1/(t*E$2*E$2))*(E$2/2)}});var log$2=Math.log,mathLog1p=Math.log1p||function(e){var t=+e;return t>-1e-8&&t<1e-8?t-t*t/2:log$2(1+t)},$$5=_export,log1p=mathLog1p,$acosh=Math.acosh,log$1=Math.log,sqrt=Math.sqrt,LN2=Math.LN2,FORCED=!$acosh||710!=Math.floor($acosh(Number.MAX_VALUE))||$acosh(1/0)!=1/0;$$5({target:"Math",stat:!0,forced:FORCED},{acosh:function(e){var t=+e;return t<1?NaN:t>94906265.62425156?log$1(t)+LN2:log1p(t-1+sqrt(t-1)*sqrt(t+1))}});var $$4=_export,expm1=mathExpm1,exp$1=Math.exp;$$4({target:"Math",stat:!0},{tanh:function(e){var t=+e,n=expm1(t),r=expm1(-t);return n==1/0?1:r==1/0?-1:(n-r)/(exp$1(t)+exp$1(-t))}});var $$3=_export,$atanh=Math.atanh,log=Math.log;function _typeof$9(e){return _typeof$9="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$9(e)}function _classCallCheck$9(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$9(e,t){for(var n=0;ni.width()?new CellError(ErrorType.REF,ErrorMessage.IndexLarge):n.doVlookup(zeroIfEmpty(e),t,r-1,a)}))}},{key:"hlookup",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("HLOOKUP"),(function(e,t,r,a){var i=t.range;return void 0===i?new CellError(ErrorType.VALUE,ErrorMessage.WrongType):r<1?new CellError(ErrorType.VALUE,ErrorMessage.LessThanOne):r>i.height()?new CellError(ErrorType.REF,ErrorMessage.IndexLarge):n.doHlookup(zeroIfEmpty(e),t,r-1,a)}))}},{key:"match",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("MATCH"),(function(e,t,r){return n.doMatch(zeroIfEmpty(e),t,r)}))}},{key:"searchInRange",value:function(e,t,n,r){return!n&&"string"==typeof e&&this.arithmeticHelper.requiresRegex(e)?r.advancedFind(this.arithmeticHelper.eqMatcherFunction(e),t):r.find(e,t,n)}},{key:"doVlookup",value:function(e,t,n,r){this.dependencyGraph.stats.start(StatType.VLOOKUP);var a,i=t.range;a=void 0===i?SimpleRangeValue.onlyValues(t.data.map((function(e){return[e[0]]}))):SimpleRangeValue.onlyRange(AbsoluteCellRange.spanFrom(i.start,1,i.height()),this.dependencyGraph);var o,s=this.searchInRange(e,a,r,this.columnSearch);if(this.dependencyGraph.stats.end(StatType.VLOOKUP),-1===s)return new CellError(ErrorType.NA,ErrorMessage.ValueNotFound);if(void 0===i)o=t.data[s][n];else{var l=simpleCellAddress(i.sheet,i.start.col+n,i.start.row+s);o=this.dependencyGraph.getCellValue(l)}return o instanceof SimpleRangeValue?new CellError(ErrorType.VALUE,ErrorMessage.WrongType):o}},{key:"doHlookup",value:function(e,t,n,r){var a,i=t.range;a=void 0===i?SimpleRangeValue.onlyValues([t.data[0]]):SimpleRangeValue.onlyRange(AbsoluteCellRange.spanFrom(i.start,i.width(),1),this.dependencyGraph);var o,s=this.searchInRange(e,a,r,this.rowSearch);if(-1===s)return new CellError(ErrorType.NA,ErrorMessage.ValueNotFound);if(void 0===i)o=t.data[n][s];else{var l=simpleCellAddress(i.sheet,i.start.col+s,i.start.row+n);o=this.dependencyGraph.getCellValue(l)}return o instanceof SimpleRangeValue?new CellError(ErrorType.VALUE,ErrorMessage.WrongType):o}},{key:"doMatch",value:function(e,t,n){if(t.width()>1&&t.height()>1)return new CellError(ErrorType.NA);if(1===t.width()){var r=this.columnSearch.find(e,t,0!==n);return-1===r?new CellError(ErrorType.NA,ErrorMessage.ValueNotFound):r+1}var a=this.rowSearch.find(e,t,0!==n);return-1===a?new CellError(ErrorType.NA,ErrorMessage.ValueNotFound):a+1}}]),n}(FunctionPlugin);function _typeof$6(e){return _typeof$6="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$6(e)}function _classCallCheck$6(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$6(e,t){for(var n=0;n4?new CellError(ErrorType.VALUE,ErrorMessage.ValueLarge):romanMode(e,t)}))}},{key:"arabic",value:function(e,t){return this.runFunction(e.args,t,this.metadata("ARABIC"),(function(e){var t=!1;if((e=e.trim().toUpperCase()).startsWith("-")&&(t=!0,""===(e=e.slice(1))))return new CellError(ErrorType.VALUE,ErrorMessage.InvalidRoman);var n={input:e,acc:0};return eatToken(n,{token:"MMM",val:3e3},{token:"MM",val:2e3},{token:"M",val:1e3}),eatToken(n,{token:"IM",val:999},{token:"VM",val:995},{token:"XM",val:990},{token:"LM",val:950},{token:"CM",val:900}),eatToken(n,{token:"D",val:500},{token:"ID",val:499},{token:"VD",val:495},{token:"XD",val:490},{token:"LD",val:450},{token:"CD",val:400}),eatToken(n,{token:"CCC",val:300},{token:"CC",val:200},{token:"C",val:100}),eatToken(n,{token:"IC",val:99},{token:"VC",val:95},{token:"XC",val:90}),eatToken(n,{token:"L",val:50},{token:"IL",val:49},{token:"VL",val:45},{token:"XL",val:40}),eatToken(n,{token:"XXX",val:30},{token:"XX",val:20},{token:"X",val:10}),eatToken(n,{token:"IX",val:9}),eatToken(n,{token:"V",val:5},{token:"IV",val:4}),eatToken(n,{token:"III",val:3},{token:"II",val:2},{token:"I",val:1}),""!==n.input?new CellError(ErrorType.VALUE,ErrorMessage.InvalidRoman):t?-n.acc:n.acc}))}}]),n}(FunctionPlugin);function eatToken(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r=3&&(absorb(n,"VM",995,1e3),absorb(n,"VD",495,500)),t>=2&&(absorb(n,"XM",990,1e3),absorb(n,"XD",490,500)),t>=1&&(absorb(n,"LM",950,1e3),absorb(n,"LD",450,500)),absorb(n,"CM",900,1e3),absorb(n,"CD",400,500),absorb(n,"D",500,900),n.acc+="C".repeat(Math.floor(n.val/100)),n.val%=100,t>=2&&(absorb(n,"IC",99,100),absorb(n,"IL",49,50)),t>=1&&(absorb(n,"VC",95,100),absorb(n,"VL",45,50)),absorb(n,"XC",90,100),absorb(n,"XL",40,50),absorb(n,"L",50,90),n.acc+="X".repeat(Math.floor(n.val/10)),n.val%=10,absorb(n,"IX",9,10),absorb(n,"IV",4,5),absorb(n,"V",5,9),n.acc+="I".repeat(n.val),n.acc}function absorb(e,t,n,r){e.val>=n&&e.valt{const n=Math.pow(10,t);return e<0?-Math.ceil(-e*n)/n:Math.ceil(e*n)/n}))}rounddown(e,t){return this.runFunction(e.args,t,this.metadata("ROUNDDOWN"),((e,t)=>{const n=Math.pow(10,t);return e<0?-Math.floor(-e*n)/n:Math.floor(e*n)/n}))}round(e,t){return this.runFunction(e.args,t,this.metadata("ROUND"),((e,t)=>{const n=Math.pow(10,t);return e<0?-Math.round(-e*n)/n:Math.round(e*n)/n}))}intFunc(e,t){return this.runFunction(e.args,t,this.metadata("INT"),(e=>e<0?-Math.floor(-e):Math.floor(e)))}even(e,t){return this.runFunction(e.args,t,this.metadata("EVEN"),(e=>e<0?-findNextEvenNumber(-e):findNextEvenNumber(e)))}odd(e,t){return this.runFunction(e.args,t,this.metadata("ODD"),(e=>e<0?-findNextOddNumber(-e):findNextOddNumber(e)))}ceilingmath(e,t){return this.runFunction(e.args,t,this.metadata("CEILING.MATH"),((e,t,n)=>0===t||0===e?0:(t=Math.abs(t),1===n&&e<0&&(t=-t),Math.ceil(e/t)*t)))}ceiling(e,t){return this.runFunction(e.args,t,this.metadata("CEILING"),((e,t)=>0===e?0:0===t?new CellError(ErrorType.DIV_BY_ZERO):e>0&&t<0?new CellError(ErrorType.NUM,ErrorMessage.DistinctSigns):Math.ceil(e/t)*t))}ceilingprecise(e,t){return this.runFunction(e.args,t,this.metadata("CEILING.PRECISE"),((e,t)=>0===t||0===e?0:(t=Math.abs(t),Math.ceil(e/t)*t)))}floormath(e,t){return this.runFunction(e.args,t,this.metadata("FLOOR.MATH"),((e,t,n)=>0===t||0===e?0:(t=Math.abs(t),1===n&&e<0&&(t*=-1),Math.floor(e/t)*t)))}floor(e,t){return this.runFunction(e.args,t,this.metadata("FLOOR"),((e,t)=>0===e?0:0===t?new CellError(ErrorType.DIV_BY_ZERO):e>0&&t<0?new CellError(ErrorType.NUM,ErrorMessage.DistinctSigns):Math.floor(e/t)*t))}floorprecise(e,t){return this.runFunction(e.args,t,this.metadata("FLOOR.PRECISE"),((e,t)=>0===t||0===e?0:(t=Math.abs(t),Math.floor(e/t)*t)))}}RoundingPlugin.implementedFunctions={ROUNDUP:{method:"roundup",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,defaultValue:0}]},ROUNDDOWN:{method:"rounddown",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,defaultValue:0}]},ROUND:{method:"round",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,defaultValue:0}]},INT:{method:"intFunc",parameters:[{argumentType:ArgumentTypes.NUMBER}]},EVEN:{method:"even",parameters:[{argumentType:ArgumentTypes.NUMBER}]},ODD:{method:"odd",parameters:[{argumentType:ArgumentTypes.NUMBER}]},"CEILING.MATH":{method:"ceilingmath",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,defaultValue:1},{argumentType:ArgumentTypes.NUMBER,defaultValue:0}]},CEILING:{method:"ceiling",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER}]},"CEILING.PRECISE":{method:"ceilingprecise",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]},"FLOOR.MATH":{method:"floormath",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,defaultValue:1},{argumentType:ArgumentTypes.NUMBER,defaultValue:0}]},FLOOR:{method:"floor",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER}]},"FLOOR.PRECISE":{method:"floorprecise",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]}},RoundingPlugin.aliases={"ISO.CEILING":"CEILING.PRECISE",TRUNC:"ROUNDDOWN"}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class SqrtPlugin extends FunctionPlugin{sqrt(e,t){return this.runFunction(e.args,t,this.metadata("SQRT"),Math.sqrt)}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +function*empty(){}function split(e){const t=e[Symbol.iterator](),{done:n,value:r}=t.next();return n?{rest:empty()}:{value:r,rest:t}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */SqrtPlugin.implementedFunctions={SQRT:{method:"sqrt",parameters:[{argumentType:ArgumentTypes.NUMBER}]}};const findSmallerRangeForMany=(e,t,n)=>{if(n.end.row>n.start.row){const r=simpleCellAddress(n.end.sheet,n.end.col,n.end.row-1),a=e.getRange(n.start,r);if(void 0!==a)return{smallerRangeVertex:a,restValuesRange:n.withStart(simpleCellAddress(n.start.sheet,n.start.col,n.end.row)),restConditionRanges:t.map((e=>e.withStart(simpleCellAddress(e.start.sheet,e.start.col,e.end.row))))}}return{restValuesRange:n,restConditionRanges:t}};class CriterionFunctionCompute{constructor(e,t,n,r,a){this.interpreter=e,this.cacheKey=t,this.reduceInitialValue=n,this.composeFunction=r,this.mapFunction=a,this.dependencyGraph=this.interpreter.dependencyGraph}compute(e,t){for(const n of t)if(!n.conditionRange.sameDimensionsAs(e))return new CellError(ErrorType.VALUE,ErrorMessage.EqualLength);const n=this.tryToGetRangeVertexForRangeValue(e),r=t.map((e=>this.tryToGetRangeVertexForRangeValue(e.conditionRange)));if(n&&r.every((e=>void 0!==e))){const a=t.map((e=>e.criterionPackage.raw)).join(","),i=this.findAlreadyComputedValueInCache(n,this.cacheKey(t),a);if(void 0!==i)return this.interpreter.stats.incrementCriterionFunctionFullCacheUsed(),i;const s=this.buildNewCriterionCache(this.cacheKey(t),t.map((e=>e.conditionRange.range)),e.range);return s.has(a)||s.set(a,[this.evaluateRangeValue(e,t),t.map((e=>e.criterionPackage.lambda))]),n.setCriterionFunctionValues(this.cacheKey(t),s),r.forEach((e=>{void 0!==e&&e.addDependentCacheRange(n)})),s.get(a)[0]}return this.evaluateRangeValue(e,t)}tryToGetRangeVertexForRangeValue(e){const t=e.range;return void 0===t?void 0:this.dependencyGraph.getRange(t.start,t.end)}reduceFunction(e){let t=this.reduceInitialValue;for(const n of e)t=this.composeFunction(t,n);return t}findAlreadyComputedValueInCache(e,t,n){return e.getCriterionFunctionValue(t,n)}evaluateRangeValue(e,t){const n=t.map((e=>e.criterionPackage.lambda)),r=Array.from(e.valuesFromTopLeftCorner()).map(this.mapFunction)[Symbol.iterator](),a=ifFilter(n,t.map((e=>e.conditionRange.iterateValuesFromTopLeftCorner())),r);return this.reduceFunction(a)}buildNewCriterionCache(e,t,n){const r=this.dependencyGraph.getRange(n.start,n.end),{smallerRangeVertex:a,restConditionRanges:i,restValuesRange:s}=findSmallerRangeForMany(this.dependencyGraph,t,n);let o;o=void 0!==a&&this.dependencyGraph.existsEdge(a,r)?a.getCriterionFunctionValues(e):new Map;const l=new Map;return o.forEach((([e,t],n)=>{const r=ifFilter(t,i.map((e=>getRangeValues(this.dependencyGraph,e))),Array.from(getRangeValues(this.dependencyGraph,s)).map(this.mapFunction)[Symbol.iterator]()),a=this.composeFunction(e,this.reduceFunction(r));this.interpreter.stats.incrementCriterionFunctionPartialCacheUsed(),l.set(n,[a,t])})),l}}class Condition{constructor(e,t){this.conditionRange=e,this.criterionPackage=t}}function*getRangeValues(e,t){for(const n of t.addresses(e))yield getRawValue(e.getScalarValue(n))}function*ifFilter(e,t,n){for(const r of n){const n=t.map((e=>split(e)));if(!n.every((e=>Object.prototype.hasOwnProperty.call(e,"value"))))return;zip(n.map((e=>getRawValue(e.value))),e).every((([e,t])=>t(e)))&&(yield r),t=n.map((e=>e.rest))}}function zip(e,t){const n=[];for(let r=0;r0?this.sum/this.count:void 0}}function conditionalAggregationFunctionCacheKey(e){return t=>{const n=t.map((e=>`${e.conditionRange.range.sheet},${e.conditionRange.range.start.col},${e.conditionRange.range.start.row}`));return[e,...n].join(",")}}function zeroForInfinite(e){return isExtendedNumber(e)&&!Number.isFinite(getRawValue(e))?0:e}function mapToRawScalarValue(e){return e instanceof CellError?e:isExtendedNumber(e)?getRawValue(e):void 0}AverageResult.empty=new AverageResult(0,0);class ConditionalAggregationPlugin extends FunctionPlugin{sumif(e,t){const n="SUMIF";return this.runFunction(e.args,t,this.metadata(n),((e,t,r)=>this.computeConditionalAggregationFunction(null!=r?r:e,[e,t],n,0,((e,t)=>this.arithmeticHelper.nonstrictadd(e,t)),mapToRawScalarValue)))}sumifs(e,t){const n="SUMIFS";return this.runFunction(e.args,t,this.metadata(n),((e,...t)=>this.computeConditionalAggregationFunction(e,t,n,0,((e,t)=>this.arithmeticHelper.nonstrictadd(e,t)),mapToRawScalarValue)))}averageif(e,t){const n="AVERAGEIF";return this.runFunction(e.args,t,this.metadata(n),((e,t,r)=>{const a=this.computeConditionalAggregationFunction(null!=r?r:e,[e,t],n,AverageResult.empty,((e,t)=>e.compose(t)),(e=>isExtendedNumber(e)?AverageResult.single(getRawValue(e)):AverageResult.empty));return a instanceof CellError?a:a.averageValue()||new CellError(ErrorType.DIV_BY_ZERO)}))}countif(e,t){const n="COUNTIF";return this.runFunction(e.args,t,this.metadata(n),((e,t)=>this.computeConditionalAggregationFunction(e,[e,t],n,0,((e,t)=>e+t),(()=>1))))}countifs(e,t){const n="COUNTIFS";return this.runFunction(e.args,t,this.metadata(n),((...e)=>this.computeConditionalAggregationFunction(e[0],e,n,0,((e,t)=>e+t),(()=>1))))}minifs(e,t){const n="MINIFS",r=(e,t)=>void 0===t||void 0===e?void 0===t?e:t:Math.min(e,t);return this.runFunction(e.args,t,this.metadata(n),((e,...t)=>zeroForInfinite(this.computeConditionalAggregationFunction(e,t,n,Number.POSITIVE_INFINITY,r,mapToRawScalarValue))))}maxifs(e,t){const n="MAXIFS",r=(e,t)=>void 0===t||void 0===e?void 0===t?e:t:Math.max(e,t);return this.runFunction(e.args,t,this.metadata(n),((e,...t)=>zeroForInfinite(this.computeConditionalAggregationFunction(e,t,n,Number.NEGATIVE_INFINITY,r,mapToRawScalarValue))))}computeConditionalAggregationFunction(e,t,n,r,a,i){const s=[];for(let e=0;e{const t=e[0].width(),n=e[0].height();for(const r of e)if(r.width()!==t||r.height()!==n)return new CellError(ErrorType.VALUE,ErrorMessage.EqualLength);let r=0;const a=e.map((e=>e.iterateValuesFromTopLeftCorner()));for(let e=0;e"".concat(...e)))}split(e,t){return this.runFunction(e.args,t,this.metadata("SPLIT"),((e,t)=>{const n=e.split(" ");return t>=n.length||t<0?new CellError(ErrorType.VALUE,ErrorMessage.IndexBounds):n[t]}))}len(e,t){return this.runFunction(e.args,t,this.metadata("LEN"),(e=>e.length))}lower(e,t){return this.runFunction(e.args,t,this.metadata("LOWER"),(e=>e.toLowerCase()))}trim(e,t){return this.runFunction(e.args,t,this.metadata("TRIM"),(e=>e.replace(/^ +| +$/g,"").replace(/ +/g," ")))}proper(e,t){return this.runFunction(e.args,t,this.metadata("PROPER"),(e=>e.replace(/\p{L}+/gu,(e=>e.charAt(0).toUpperCase()+e.substring(1).toLowerCase()))))}clean(e,t){return this.runFunction(e.args,t,this.metadata("CLEAN"),(e=>e.replace(/[\u0000-\u001F]/g,"")))}exact(e,t){return this.runFunction(e.args,t,this.metadata("EXACT"),((e,t)=>e===t))}rept(e,t){return this.runFunction(e.args,t,this.metadata("REPT"),((e,t)=>t<0?new CellError(ErrorType.VALUE,ErrorMessage.NegativeCount):e.repeat(t)))}right(e,t){return this.runFunction(e.args,t,this.metadata("RIGHT"),((e,t)=>t<0?new CellError(ErrorType.VALUE,ErrorMessage.NegativeLength):0===t?"":e.slice(-t)))}left(e,t){return this.runFunction(e.args,t,this.metadata("LEFT"),((e,t)=>t<0?new CellError(ErrorType.VALUE,ErrorMessage.NegativeLength):e.slice(0,t)))}mid(e,t){return this.runFunction(e.args,t,this.metadata("MID"),((e,t,n)=>t<1?new CellError(ErrorType.VALUE,ErrorMessage.LessThanOne):n<0?new CellError(ErrorType.VALUE,ErrorMessage.NegativeLength):e.substring(t-1,t+n-1)))}replace(e,t){return this.runFunction(e.args,t,this.metadata("REPLACE"),((e,t,n,r)=>t<1?new CellError(ErrorType.VALUE,ErrorMessage.LessThanOne):n<0?new CellError(ErrorType.VALUE,ErrorMessage.NegativeLength):e.substring(0,t-1)+r+e.substring(t+n-1)))}search(e,t){return this.runFunction(e.args,t,this.metadata("SEARCH"),((e,t,n)=>{if(n<1||n>t.length)return new CellError(ErrorType.VALUE,ErrorMessage.LengthBounds);const r=t.substring(n-1).toLowerCase();let a;return a=this.arithmeticHelper.requiresRegex(e)?this.arithmeticHelper.searchString(e,r):r.indexOf(e.toLowerCase()),a+=n,a>0?a:new CellError(ErrorType.VALUE,ErrorMessage.PatternNotFound)}))}substitute(e,t){return this.runFunction(e.args,t,this.metadata("SUBSTITUTE"),((e,t,n,r)=>{const a=new RegExp(t,"g");if(void 0===r)return e.replace(a,n);if(r<1)return new CellError(ErrorType.VALUE,ErrorMessage.LessThanOne);let i,s=0;for(;null!==(i=a.exec(e));)if(r===++s)return e.substring(0,i.index)+n+e.substring(a.lastIndex);return e}))}find(e,t){return this.runFunction(e.args,t,this.metadata("FIND"),((e,t,n)=>{if(n<1||n>t.length)return new CellError(ErrorType.VALUE,ErrorMessage.IndexBounds);const r=t.substring(n-1).indexOf(e)+n;return r>0?r:new CellError(ErrorType.VALUE,ErrorMessage.PatternNotFound)}))}t(e,t){return this.runFunction(e.args,t,this.metadata("T"),(e=>e instanceof CellError||"string"==typeof e?e:""))}upper(e,t){return this.runFunction(e.args,t,this.metadata("UPPER"),(e=>e.toUpperCase()))}}TextPlugin.implementedFunctions={CONCATENATE:{method:"concatenate",parameters:[{argumentType:ArgumentTypes.STRING}],repeatLastArgs:1,expandRanges:!0},EXACT:{method:"exact",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.STRING}]},SPLIT:{method:"split",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER}]},LEN:{method:"len",parameters:[{argumentType:ArgumentTypes.STRING}]},LOWER:{method:"lower",parameters:[{argumentType:ArgumentTypes.STRING}]},MID:{method:"mid",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER}]},TRIM:{method:"trim",parameters:[{argumentType:ArgumentTypes.STRING}]},T:{method:"t",parameters:[{argumentType:ArgumentTypes.SCALAR}]},PROPER:{method:"proper",parameters:[{argumentType:ArgumentTypes.STRING}]},CLEAN:{method:"clean",parameters:[{argumentType:ArgumentTypes.STRING}]},REPT:{method:"rept",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER}]},RIGHT:{method:"right",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]},LEFT:{method:"left",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]},REPLACE:{method:"replace",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.STRING}]},SEARCH:{method:"search",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]},SUBSTITUTE:{method:"substitute",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER,optionalArg:!0}]},FIND:{method:"find",parameters:[{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.STRING},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]},UPPER:{method:"upper",parameters:[{argumentType:ArgumentTypes.STRING}]}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class TrigonometryPlugin extends FunctionPlugin{acos(e,t){return this.runFunction(e.args,t,this.metadata("ACOS"),Math.acos)}asin(e,t){return this.runFunction(e.args,t,this.metadata("ASIN"),Math.asin)}cos(e,t){return this.runFunction(e.args,t,this.metadata("COS"),Math.cos)}sin(e,t){return this.runFunction(e.args,t,this.metadata("SIN"),Math.sin)}tan(e,t){return this.runFunction(e.args,t,this.metadata("TAN"),Math.tan)}atan(e,t){return this.runFunction(e.args,t,this.metadata("ATAN"),Math.atan)}atan2(e,t){return this.runFunction(e.args,t,this.metadata("ATAN2"),((e,t)=>0===e&&0===t?new CellError(ErrorType.DIV_BY_ZERO):Math.atan2(t,e)))}cot(e,t){return this.runFunction(e.args,t,this.metadata("COT"),(e=>0===e?new CellError(ErrorType.DIV_BY_ZERO):1/Math.tan(e)))}acot(e,t){return this.runFunction(e.args,t,this.metadata("ACOT"),(e=>0===e?PI/2:Math.atan(1/e)))}sec(e,t){return this.runFunction(e.args,t,this.metadata("SEC"),(e=>1/Math.cos(e)))}csc(e,t){return this.runFunction(e.args,t,this.metadata("CSC"),(e=>0===e?new CellError(ErrorType.DIV_BY_ZERO):1/Math.sin(e)))}sinh(e,t){return this.runFunction(e.args,t,this.metadata("SINH"),Math.sinh)}asinh(e,t){return this.runFunction(e.args,t,this.metadata("ASINH"),Math.asinh)}cosh(e,t){return this.runFunction(e.args,t,this.metadata("COSH"),Math.cosh)}acosh(e,t){return this.runFunction(e.args,t,this.metadata("ACOSH"),Math.acosh)}tanh(e,t){return this.runFunction(e.args,t,this.metadata("TANH"),Math.tanh)}atanh(e,t){return this.runFunction(e.args,t,this.metadata("ATANH"),Math.atanh)}coth(e,t){return this.runFunction(e.args,t,this.metadata("COTH"),(e=>0===e?new CellError(ErrorType.DIV_BY_ZERO):1/Math.tanh(e)))}acoth(e,t){return this.runFunction(e.args,t,this.metadata("ACOTH"),(e=>0===e?new CellError(ErrorType.NUM,ErrorMessage.NonZero):Math.atanh(1/e)))}sech(e,t){return this.runFunction(e.args,t,this.metadata("SECH"),(e=>1/Math.cosh(e)))}csch(e,t){return this.runFunction(e.args,t,this.metadata("CSCH"),(e=>0===e?new CellError(ErrorType.DIV_BY_ZERO):1/Math.sinh(e)))}}TrigonometryPlugin.implementedFunctions={ACOS:{method:"acos",parameters:[{argumentType:ArgumentTypes.NUMBER}]},ASIN:{method:"asin",parameters:[{argumentType:ArgumentTypes.NUMBER}]},COS:{method:"cos",parameters:[{argumentType:ArgumentTypes.NUMBER}]},SIN:{method:"sin",parameters:[{argumentType:ArgumentTypes.NUMBER}]},TAN:{method:"tan",parameters:[{argumentType:ArgumentTypes.NUMBER}]},ATAN:{method:"atan",parameters:[{argumentType:ArgumentTypes.NUMBER}]},ATAN2:{method:"atan2",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER}]},COT:{method:"cot",parameters:[{argumentType:ArgumentTypes.NUMBER}]},SEC:{method:"sec",parameters:[{argumentType:ArgumentTypes.NUMBER}]},CSC:{method:"csc",parameters:[{argumentType:ArgumentTypes.NUMBER}]},SINH:{method:"sinh",parameters:[{argumentType:ArgumentTypes.NUMBER}]},COSH:{method:"cosh",parameters:[{argumentType:ArgumentTypes.NUMBER}]},TANH:{method:"tanh",parameters:[{argumentType:ArgumentTypes.NUMBER}]},COTH:{method:"coth",parameters:[{argumentType:ArgumentTypes.NUMBER}]},SECH:{method:"sech",parameters:[{argumentType:ArgumentTypes.NUMBER}]},CSCH:{method:"csch",parameters:[{argumentType:ArgumentTypes.NUMBER}]},ACOT:{method:"acot",parameters:[{argumentType:ArgumentTypes.NUMBER}]},ASINH:{method:"asinh",parameters:[{argumentType:ArgumentTypes.NUMBER}]},ACOSH:{method:"acosh",parameters:[{argumentType:ArgumentTypes.NUMBER}]},ATANH:{method:"atanh",parameters:[{argumentType:ArgumentTypes.NUMBER}]},ACOTH:{method:"acoth",parameters:[{argumentType:ArgumentTypes.NUMBER}]}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class RowSearchStrategy extends AdvancedFind{constructor(e,t){super(t),this.config=e,this.dependencyGraph=t}find(e,t,n){"string"==typeof e&&(e=forceNormalizeString(e));const r=t.range;return void 0===r?t.valuesFromTopLeftCorner().map(getRawValue).indexOf(e):n?rangeLowerBound(r,e,this.dependencyGraph,"col"):this.dependencyGraph.computeListOfValuesInRange(r).findIndex((t=>(t="string"==typeof(t=getRawValue(t))?forceNormalizeString(t):t)===e))}} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class LookupPlugin extends FunctionPlugin{constructor(){super(...arguments),this.rowSearch=new RowSearchStrategy(this.config,this.dependencyGraph)}vlookup(e,t){return this.runFunction(e.args,t,this.metadata("VLOOKUP"),((e,t,n,r)=>{const a=t.range;return void 0===a?new CellError(ErrorType.VALUE,ErrorMessage.WrongType):n<1?new CellError(ErrorType.VALUE,ErrorMessage.LessThanOne):n>a.width()?new CellError(ErrorType.REF,ErrorMessage.IndexLarge):this.doVlookup(zeroIfEmpty(e),t,n-1,r)}))}hlookup(e,t){return this.runFunction(e.args,t,this.metadata("HLOOKUP"),((e,t,n,r)=>{const a=t.range;return void 0===a?new CellError(ErrorType.VALUE,ErrorMessage.WrongType):n<1?new CellError(ErrorType.VALUE,ErrorMessage.LessThanOne):n>a.height()?new CellError(ErrorType.REF,ErrorMessage.IndexLarge):this.doHlookup(zeroIfEmpty(e),t,n-1,r)}))}match(e,t){return this.runFunction(e.args,t,this.metadata("MATCH"),((e,t,n)=>this.doMatch(zeroIfEmpty(e),t,n)))}searchInRange(e,t,n,r){return!n&&"string"==typeof e&&this.arithmeticHelper.requiresRegex(e)?r.advancedFind(this.arithmeticHelper.eqMatcherFunction(e),t):r.find(e,t,n)}doVlookup(e,t,n,r){this.dependencyGraph.stats.start(StatType.VLOOKUP);const a=t.range;let i;i=void 0===a?SimpleRangeValue.onlyValues(t.data.map((e=>[e[0]]))):SimpleRangeValue.onlyRange(AbsoluteCellRange.spanFrom(a.start,1,a.height()),this.dependencyGraph);const s=this.searchInRange(e,i,r,this.columnSearch);if(this.dependencyGraph.stats.end(StatType.VLOOKUP),-1===s)return new CellError(ErrorType.NA,ErrorMessage.ValueNotFound);let o;if(void 0===a)o=t.data[s][n];else{const e=simpleCellAddress(a.sheet,a.start.col+n,a.start.row+s);o=this.dependencyGraph.getCellValue(e)}return o instanceof SimpleRangeValue?new CellError(ErrorType.VALUE,ErrorMessage.WrongType):o}doHlookup(e,t,n,r){const a=t.range;let i;i=void 0===a?SimpleRangeValue.onlyValues([t.data[0]]):SimpleRangeValue.onlyRange(AbsoluteCellRange.spanFrom(a.start,a.width(),1),this.dependencyGraph);const s=this.searchInRange(e,i,r,this.rowSearch);if(-1===s)return new CellError(ErrorType.NA,ErrorMessage.ValueNotFound);let o;if(void 0===a)o=t.data[n][s];else{const e=simpleCellAddress(a.sheet,a.start.col+s,a.start.row+n);o=this.dependencyGraph.getCellValue(e)}return o instanceof SimpleRangeValue?new CellError(ErrorType.VALUE,ErrorMessage.WrongType):o}doMatch(e,t,n){if(t.width()>1&&t.height()>1)return new CellError(ErrorType.NA);if(1===t.width()){const r=this.columnSearch.find(e,t,0!==n);return-1===r?new CellError(ErrorType.NA,ErrorMessage.ValueNotFound):r+1}{const r=this.rowSearch.find(e,t,0!==n);return-1===r?new CellError(ErrorType.NA,ErrorMessage.ValueNotFound):r+1}}}LookupPlugin.implementedFunctions={VLOOKUP:{method:"vlookup",parameters:[{argumentType:ArgumentTypes.NOERROR},{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.BOOLEAN,defaultValue:!0}]},HLOOKUP:{method:"hlookup",parameters:[{argumentType:ArgumentTypes.NOERROR},{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.BOOLEAN,defaultValue:!0}]},MATCH:{method:"match",parameters:[{argumentType:ArgumentTypes.NOERROR},{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]}}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class RomanPlugin extends FunctionPlugin{roman(e,t){return this.runFunction(e.args,t,this.metadata("ROMAN"),((e,t)=>(e=Math.trunc(e),!1===t?t=4:!0===t&&(t=0),(t=getRawValue(this.coerceScalarToNumberOrError(t)))instanceof CellError?t:(t=Math.trunc(t))<0?new CellError(ErrorType.VALUE,ErrorMessage.ValueSmall):t>4?new CellError(ErrorType.VALUE,ErrorMessage.ValueLarge):romanMode(e,t))))}arabic(e,t){return this.runFunction(e.args,t,this.metadata("ARABIC"),(e=>{let t=!1;if((e=e.trim().toUpperCase()).startsWith("-")&&(t=!0,""===(e=e.slice(1))))return new CellError(ErrorType.VALUE,ErrorMessage.InvalidRoman);const n={input:e,acc:0};return eatToken(n,{token:"MMM",val:3e3},{token:"MM",val:2e3},{token:"M",val:1e3}),eatToken(n,{token:"IM",val:999},{token:"VM",val:995},{token:"XM",val:990},{token:"LM",val:950},{token:"CM",val:900}),eatToken(n,{token:"D",val:500},{token:"ID",val:499},{token:"VD",val:495},{token:"XD",val:490},{token:"LD",val:450},{token:"CD",val:400}),eatToken(n,{token:"CCC",val:300},{token:"CC",val:200},{token:"C",val:100}),eatToken(n,{token:"IC",val:99},{token:"VC",val:95},{token:"XC",val:90}),eatToken(n,{token:"L",val:50},{token:"IL",val:49},{token:"VL",val:45},{token:"XL",val:40}),eatToken(n,{token:"XXX",val:30},{token:"XX",val:20},{token:"X",val:10}),eatToken(n,{token:"IX",val:9}),eatToken(n,{token:"V",val:5},{token:"IV",val:4}),eatToken(n,{token:"III",val:3},{token:"II",val:2},{token:"I",val:1}),""!==n.input?new CellError(ErrorType.VALUE,ErrorMessage.InvalidRoman):t?-n.acc:n.acc}))}}function eatToken(e,...t){for(const n of t)if(e.input.startsWith(n.token)){e.input=e.input.slice(n.token.length),e.acc+=n.val;break}}function romanMode(e,t){const n={val:e%1e3,acc:"M".repeat(Math.floor(e/1e3))};return 4===t&&(absorb(n,"IM",999,1e3),absorb(n,"ID",499,500)),t>=3&&(absorb(n,"VM",995,1e3),absorb(n,"VD",495,500)),t>=2&&(absorb(n,"XM",990,1e3),absorb(n,"XD",490,500)),t>=1&&(absorb(n,"LM",950,1e3),absorb(n,"LD",450,500)),absorb(n,"CM",900,1e3),absorb(n,"CD",400,500),absorb(n,"D",500,900),n.acc+="C".repeat(Math.floor(n.val/100)),n.val%=100,t>=2&&(absorb(n,"IC",99,100),absorb(n,"IL",49,50)),t>=1&&(absorb(n,"VC",95,100),absorb(n,"VL",45,50)),absorb(n,"XC",90,100),absorb(n,"XL",40,50),absorb(n,"L",50,90),n.acc+="X".repeat(Math.floor(n.val/10)),n.val%=10,absorb(n,"IX",9,10),absorb(n,"IV",4,5),absorb(n,"V",5,9),n.acc+="I".repeat(n.val),n.acc}function absorb(e,t,n,r){e.val>=n&&e.valn)r=_bessel_iter(t,n,i(t),c(t),-1);else{for(var a=!1,o=0,s=0,l=1,u=0,p=2/t,d=2*M$2.floor((n+M$2.floor(M$2.sqrt(40*n)))/2);d>0;d--)u=d*p*l-o,o=l,l=u,M$2.abs(l)>1e10&&(l*=1e-10,o*=1e-10,r*=1e-10,s*=1e-10),a&&(s+=l),a=!a,d==n&&(r=o);r/=s=2*s-l}return r}}(),bessely=function(){var e=.636619772,t=[-2957821389,7062834065,-512359803.6,10879881.29,-86327.92757,228.4622733].reverse(),n=[40076544269,745249964.8,7189466.438,47447.2647,226.1030244,1].reverse(),r=[1,-.001098628627,2734510407e-14,-2073370639e-15,2.093887211e-7].reverse(),a=[-.01562499995,.0001430488765,-6911147651e-15,7.621095161e-7,-9.34945152e-8].reverse();var i=[-4900604943e3,127527439e4,-51534381390,734926455.1,-4237922.726,8511.937935].reverse(),o=[249958057e5,424441966400,3733650367,22459040.02,102042.605,354.9632885,1].reverse(),s=[1,.00183105,-3516396496e-14,2457520174e-15,-2.40337019e-7].reverse(),l=[.04687499995,-.0002002690873,8449199096e-15,-8.8228987e-7,1.05787412e-7].reverse();return _bessel_wrap((function(i){var o=0,s=0,l=0,u=i*i,c=i-.785398164;return i<8?o=(s=_horner(t,u))/(l=_horner(n,u))+e*besselj(i,0)*M$2.log(i):(s=_horner(r,u=64/u),l=_horner(a,u),o=M$2.sqrt(e/i)*(M$2.sin(c)*s+M$2.cos(c)*l*8/i)),o}),(function(t){var n=0,r=0,a=0,u=t*t,c=t-2.356194491;return t<8?n=(r=t*_horner(i,u))/(a=_horner(o,u))+e*(besselj(t,1)*M$2.log(t)-1/t):(r=_horner(s,u=64/u),a=_horner(l,u),n=M$2.sqrt(e/t)*(M$2.sin(c)*r+M$2.cos(c)*a*8/t)),n}),"BESSELY",1,-1)}(),besseli=(b0_a=[1,3.5156229,3.0899424,1.2067492,.2659732,.0360768,.0045813].reverse(),b0_b=[.39894228,.01328592,.00225319,-.00157565,.00916281,-.02057706,.02635537,-.01647633,.00392377].reverse(),b1_a=[.5,.87890594,.51498869,.15084934,.02658733,.00301532,32411e-8].reverse(),b1_b=[.39894228,-.03988024,-.00362018,.00163801,-.01031555,.02282967,-.02895312,.01787654,-.00420059].reverse(),function e(t,n){if(0===(n=Math.round(n)))return function(e){return e<=3.75?_horner(b0_a,e*e/14.0625):M$2.exp(M$2.abs(e))/M$2.sqrt(M$2.abs(e))*_horner(b0_b,3.75/M$2.abs(e))}(t);if(1===n)return function(e){return e<3.75?e*_horner(b1_a,e*e/14.0625):(e<0?-1:1)*M$2.exp(M$2.abs(e))/M$2.sqrt(M$2.abs(e))*_horner(b1_b,3.75/M$2.abs(e))}(t);if(n<0)return NaN;if(0===M$2.abs(t))return 0;if(t==1/0)return 1/0;var r,a=0,i=2/M$2.abs(t),o=0,s=1,l=0;for(r=2*M$2.round((n+M$2.round(M$2.sqrt(40*n)))/2);r>0;r--)l=r*i*s+o,o=s,s=l,M$2.abs(s)>1e10&&(s*=1e-10,o*=1e-10,a*=1e-10),r==n&&(a=o);return a*=e(t,0)/s,t<0&&n%2?-a:a}),b0_a,b0_b,b1_a,b1_b,besselk=function(){var e=[-.57721566,.4227842,.23069756,.0348859,.00262698,1075e-7,74e-7].reverse(),t=[1.25331414,-.07832358,.02189568,-.01062446,.00587872,-.0025154,53208e-8].reverse();var n=[1,.15443144,-.67278579,-.18156897,-.01919402,-.00110404,-4686e-8].reverse(),r=[1.25331414,.23498619,-.0365562,.01504268,-.00780353,.00325614,-68245e-8].reverse();return _bessel_wrap((function(n){return n<=2?-M$2.log(n/2)*besseli(n,0)+_horner(e,n*n/4):M$2.exp(-n)/M$2.sqrt(n)*_horner(t,2/n)}),(function(e){return e<=2?M$2.log(e/2)*besseli(e,1)+1/e*_horner(n,e*e/4):M$2.exp(-e)/M$2.sqrt(e)*_horner(r,2/e)}),"BESSELK",2,1)}(); +var M$2=Math;function _horner(e,t){for(var n=0,r=0;nn)r=_bessel_iter(t,n,i(t),c(t),-1);else{for(var a=!1,s=0,o=0,l=1,u=0,p=2/t,d=2*M$2.floor((n+M$2.floor(M$2.sqrt(40*n)))/2);d>0;d--)u=d*p*l-s,s=l,l=u,M$2.abs(l)>1e10&&(l*=1e-10,s*=1e-10,r*=1e-10,o*=1e-10),a&&(o+=l),a=!a,d==n&&(r=s);r/=o=2*o-l}return r}}(),bessely=function(){var e=.636619772,t=[-2957821389,7062834065,-512359803.6,10879881.29,-86327.92757,228.4622733].reverse(),n=[40076544269,745249964.8,7189466.438,47447.2647,226.1030244,1].reverse(),r=[1,-.001098628627,2734510407e-14,-2073370639e-15,2.093887211e-7].reverse(),a=[-.01562499995,.0001430488765,-6911147651e-15,7.621095161e-7,-9.34945152e-8].reverse();var i=[-4900604943e3,127527439e4,-51534381390,734926455.1,-4237922.726,8511.937935].reverse(),s=[249958057e5,424441966400,3733650367,22459040.02,102042.605,354.9632885,1].reverse(),o=[1,.00183105,-3516396496e-14,2457520174e-15,-2.40337019e-7].reverse(),l=[.04687499995,-.0002002690873,8449199096e-15,-8.8228987e-7,1.05787412e-7].reverse();return _bessel_wrap((function(i){var s=0,o=0,l=0,u=i*i,c=i-.785398164;return i<8?s=(o=_horner(t,u))/(l=_horner(n,u))+e*besselj(i,0)*M$2.log(i):(o=_horner(r,u=64/u),l=_horner(a,u),s=M$2.sqrt(e/i)*(M$2.sin(c)*o+M$2.cos(c)*l*8/i)),s}),(function(t){var n=0,r=0,a=0,u=t*t,c=t-2.356194491;return t<8?n=(r=t*_horner(i,u))/(a=_horner(s,u))+e*(besselj(t,1)*M$2.log(t)-1/t):(r=_horner(o,u=64/u),a=_horner(l,u),n=M$2.sqrt(e/t)*(M$2.sin(c)*r+M$2.cos(c)*a*8/t)),n}),"BESSELY",1,-1)}(),besseli=(b0_a=[1,3.5156229,3.0899424,1.2067492,.2659732,.0360768,.0045813].reverse(),b0_b=[.39894228,.01328592,.00225319,-.00157565,.00916281,-.02057706,.02635537,-.01647633,.00392377].reverse(),b1_a=[.5,.87890594,.51498869,.15084934,.02658733,.00301532,32411e-8].reverse(),b1_b=[.39894228,-.03988024,-.00362018,.00163801,-.01031555,.02282967,-.02895312,.01787654,-.00420059].reverse(),function e(t,n){if(0===(n=Math.round(n)))return function(e){return e<=3.75?_horner(b0_a,e*e/14.0625):M$2.exp(M$2.abs(e))/M$2.sqrt(M$2.abs(e))*_horner(b0_b,3.75/M$2.abs(e))}(t);if(1===n)return function(e){return e<3.75?e*_horner(b1_a,e*e/14.0625):(e<0?-1:1)*M$2.exp(M$2.abs(e))/M$2.sqrt(M$2.abs(e))*_horner(b1_b,3.75/M$2.abs(e))}(t);if(n<0)return NaN;if(0===M$2.abs(t))return 0;if(t==1/0)return 1/0;var r,a=0,i=2/M$2.abs(t),s=0,o=1,l=0;for(r=2*M$2.round((n+M$2.round(M$2.sqrt(40*n)))/2);r>0;r--)l=r*i*o+s,s=o,o=l,M$2.abs(o)>1e10&&(o*=1e-10,s*=1e-10,a*=1e-10),r==n&&(a=s);return a*=e(t,0)/o,t<0&&n%2?-a:a}),b0_a,b0_b,b1_a,b1_b,besselk=function(){var e=[-.57721566,.4227842,.23069756,.0348859,.00262698,1075e-7,74e-7].reverse(),t=[1.25331414,-.07832358,.02189568,-.01062446,.00587872,-.0025154,53208e-8].reverse();var n=[1,.15443144,-.67278579,-.18156897,-.01919402,-.00110404,-4686e-8].reverse(),r=[1.25331414,.23498619,-.0365562,.01504268,-.00780353,.00325614,-68245e-8].reverse();return _bessel_wrap((function(n){return n<=2?-M$2.log(n/2)*besseli(n,0)+_horner(e,n*n/4):M$2.exp(-n)/M$2.sqrt(n)*_horner(t,2/n)}),(function(e){return e<=2?M$2.log(e/2)*besseli(e,1)+1/e*_horner(n,e*e/4):M$2.exp(-e)/M$2.sqrt(e)*_horner(r,2/e)}),"BESSELK",2,1)}(); /** * @license Copyright (c) 2013 jStat @@ -336,8 +813,29 @@ var M$2=Math;function _horner(e,t){for(var n=0,r=0;n0;o--)r=l,l=n*l-u+i[o],u=r;return a=t*Math.exp(-e*e+.5*(i[0]+n*l)-u),s?a-1:1-a}function erfc(e){return 1-erf(e)}function erfcinv(e){var t,n,r,a,i=0;if(e>=2)return-100;if(e<=0)return 100;for(a=e<1?e:2-e,t=-.70711*((2.30753+.27061*(r=Math.sqrt(-2*Math.log(a/2))))/(1+r*(.99229+.04481*r))-r);i<2;i++)t+=(n=erfc(t)-a)/(1.1283791670955126*Math.exp(-t*t)-t*n);return e<1?t:-t}var exponential={pdf:function(e,t){return e<0?0:t*Math.exp(-t*e)},cdf:function(e,t){return e<0?0:1-Math.exp(-t*e)}};function gammafn(e){var t,n,r,a,i=[-1.716185138865495,24.76565080557592,-379.80425647094563,629.3311553128184,866.9662027904133,-31451.272968848367,-36144.413418691176,66456.14382024054],o=[-30.8402300119739,315.35062697960416,-1015.1563674902192,-3107.771671572311,22538.11842098015,4755.846277527881,-134659.9598649693,-115132.2596755535],s=!1,l=0,u=0,c=0,p=e;if(e>171.6243769536076)return 1/0;if(p<=0){if(!(a=p%1))return 1/0;s=(1&p?-1:1)*Math.PI/Math.sin(Math.PI*a),p=1-p}for(r=p,n=p<1?p++:(p-=l=(0|p)-1)-1,t=0;t<8;++t)c=(c+i[t])*n,u=u*n+o[t];if(a=c/u+1,rp)for(t=0;t=1?e:1/e)+.4*e+17);if(t<0||e<=0)return NaN;if(t=1)return Math.max(100,t+100*Math.sqrt(t));if(e<=0)return 0;for(t>1?(o=Math.log(u),s=Math.exp(u*(o-1)-c),i=e<.5?e:1-e,n=(2.30753+.27061*(r=Math.sqrt(-2*Math.log(i))))/(1+r*(.99229+.04481*r))-r,e<.5&&(n=-n),n=Math.max(.001,t*Math.pow(1-1/(9*t)-n/(3*Math.sqrt(t)),3))):n=e<(r=1-t*(.253+.12*t))?Math.pow(e/r,1/t):1-Math.log(1-(e-r)/(1-r));l<12;l++){if(n<=0)return 0;if((n-=r=(a=(lowRegGamma(t,n)-e)/(r=t>1?s*Math.exp(-(n-u)+u*(Math.log(n)-o)):Math.exp(-n+u*Math.log(n)-c)))/(1-.5*Math.min(1,a*((t-1)/n-1))))<=0&&(n=.5*(n+r)),Math.abs(r)<1e-8*n)break}return n}var normal={pdf:function(e,t,n){return Math.exp(-.5*Math.log(2*Math.PI)-Math.log(n)-Math.pow(e-t,2)/(2*n*n))},cdf:function(e,t,n){return.5*(1+erf((e-t)/Math.sqrt(2*n*n)))},inv:function(e,t,n){return-1.4142135623730951*n*erfcinv(2*e)+t}},beta={pdf:function(e,t,n){return e>1||e<0?0:1==t&&1==n?1:t<512&&n<512?Math.pow(e,t-1)*Math.pow(1-e,n-1)/betafn(t,n):Math.exp((t-1)*Math.log(e)+(n-1)*Math.log(1-e)-betaln(t,n))},cdf:function(e,t,n){return e>1||e<0?+(e>1):ibeta(e,t,n)},inv:function(e,t,n){return ibetainv(e,t,n)}};function betafn(e,t){if(!(e<=0||t<=0))return e+t>170?Math.exp(betaln(e,t)):gammafn(e)*gammafn(t)/gammafn(e+t)}function betaln(e,t){return gammaln(e)+gammaln(t)-gammaln(e+t)}function ibetainv(e,t,n){var r,a,i,o,s,l,u,c,p,d,m=t-1,f=n-1,h=0;if(e<=0)return 0;if(e>=1)return 1;for(t>=1&&n>=1?(i=e<.5?e:1-e,l=(2.30753+.27061*(o=Math.sqrt(-2*Math.log(i))))/(1+o*(.99229+.04481*o))-o,e<.5&&(l=-l),u=(l*l-3)/6,c=2/(1/(2*t-1)+1/(2*n-1)),p=l*Math.sqrt(u+c)/c-(1/(2*n-1)-1/(2*t-1))*(u+5/6-2/(3*c)),l=t/(t+n*Math.exp(2*p))):(r=Math.log(t/(t+n)),a=Math.log(n/(t+n)),l=e<(o=Math.exp(t*r)/t)/(p=o+(s=Math.exp(n*a)/n))?Math.pow(t*p*e,1/t):1-Math.pow(n*p*(1-e),1/n)),d=-gammaln(t)-gammaln(n)+gammaln(t+n);h<10;h++){if(0===l||1===l)return l;if((l-=o=(s=(ibeta(l,t,n)-e)/(o=Math.exp(m*Math.log(l)+f*Math.log(1-l)+d)))/(1-.5*Math.min(1,s*(m/l-f/(1-l)))))<=0&&(l=.5*(l+o)),l>=1&&(l=.5*(l+o+1)),Math.abs(o)<1e-8*l&&h>0)break}return l}function ibeta(e,t,n){var r=0===e||1===e?0:Math.exp(gammaln(t+n)-gammaln(t)-gammaln(n)+t*Math.log(e)+n*Math.log(1-e));return!(e<0||e>1)&&(e<(t+1)/(t+n+2)?r*betacf(e,t,n)/t:1-r*betacf(1-e,n,t)/n)}function betacf(e,t,n){var r,a,i,o,s=1e-30,l=1,u=t+n,c=t+1,p=t-1,d=1,m=1-u*e/c;for(Math.abs(m)=t)return 1;if(n<0||n>1||t<=0)return NaN;var i=n,o=(e=Math.floor(e))+1,s=t-e,l=o+s,u=Math.exp(gammaln(l)-gammaln(s)-gammaln(o)+o*Math.log(i)+s*Math.log(1-i));return r=i<(o+1)/(l+2)?u*betinc(i,o,s,a):1-u*betinc(1-i,s,o,a),Math.round(1/a*(1-r))/(1/a)}};function betinc(e,t,n,r){for(var a,i=0,o=1,s=1,l=1,u=0,c=0;Math.abs((s-c)/s)>r;)c=s,o=l+(a=-(t+u)*(t+n+u)*e/(t+2*u)/(t+2*u+1))*o,s=(i=s+a*i)+(a=(u+=1)*(n-u)*e/(t+2*u-1)/(t+2*u))*s,i/=l=o+a*l,o/=l,s/=l,l=1;return s/t}function combination(e,t){return e>170||t>170?Math.exp(combinationln(e,t)):factorial(e)/factorial(t)/factorial(e-t)}function combinationln(e,t){return factorialln(e)-factorialln(t)-factorialln(e-t)}function factorialln(e){return e<0?NaN:gammaln(e+1)}function factorial(e){return e<0?NaN:gammafn(e+1)}var chisquare={pdf:function(e,t){return e<0?0:0===e&&2===t?.5:Math.exp((t/2-1)*Math.log(e)-e/2-t/2*Math.log(2)-gammaln(t/2))},cdf:function(e,t){return e<0?0:lowRegGamma(t/2,e/2)},inv:function(e,t){return 2*gammapinv(e,.5*t)}},centralF={pdf:function(e,t,n){var r;return e<0?0:t<=2?0===e&&t<2?1/0:0===e&&2===t?1:1/betafn(t/2,n/2)*Math.pow(t/n,t/2)*Math.pow(e,t/2-1)*Math.pow(1+t/n*e,-(t+n)/2):(r=t*e/(n+e*t),t*(n/(n+e*t))/2*binomial.pdf((t-2)/2,(t+n-2)/2,r))},cdf:function(e,t,n){return e<0?0:ibeta(t*e/(t*e+n),t/2,n/2)},inv:function(e,t,n){return n/(t*(1/ibetainv(e,t/2,n/2)-1))}},weibull={pdf:function(e,t,n){return e<0||t<0||n<0?0:n/t*Math.pow(e/t,n-1)*Math.exp(-Math.pow(e/t,n))},cdf:function(e,t,n){return e<0?0:1-Math.exp(-Math.pow(e/t,n))}},poisson={pdf:function(e,t){return t<0||e%1!=0||e<0?0:Math.pow(t,e)*Math.exp(-t)/factorial(e)},cdf:function(e,t){var n=0;if(e<0)return 0;for(var r=0;n<=e;n++)r+=poisson.pdf(n,t);return r}},hypgeom={pdf:function(e,t,n,r){if(e<0||er||e>n)return 0;if(2*n>t)return 2*r>t?hypgeom.pdf(t-n-r+e,t,t-n,t-r):hypgeom.pdf(r-e,t,t-n,r);if(2*r>t)return hypgeom.pdf(n-e,t,n,t-r);if(n1&&i=a||t>=r)return 1;if(2*r>n)return 2*a>n?e(n-r-a+t,n,n-r,n-a):1-hypgeom.cdf(a-t-1,n,n-r,a);if(2*a>n)return 1-hypgeom.cdf(r-t-1,n,r,n-a);if(r1&&s1e100?1e100:t,1/(Math.sqrt(t)*betafn(.5,t/2))*Math.pow(1+e*e/t,-(t+1)/2)},cdf:function(e,t){var n=t/2;return ibeta((e+Math.sqrt(e*e+t))/(2*Math.sqrt(e*e+t)),n,n)},inv:function(e,t){var n=ibetainv(2*Math.min(e,1-e),.5*t,.5);return n=Math.sqrt(t*(1-n)/n),e>.5?n:-n}},lognormal={pdf:function(e,t,n){return e<=0?0:Math.exp(-Math.log(e)-.5*Math.log(2*Math.PI)-Math.log(n)-Math.pow(Math.log(e)-t,2)/(2*n*n))},cdf:function(e,t,n){return e<0?0:.5+.5*erf((Math.log(e)-t)/Math.sqrt(2*n*n))},inv:function(e,t,n){return Math.exp(-1.4142135623730951*n*erfcinv(2*e)+t)}},negbin={pdf:function(e,t,n){return e===e>>>0&&(e<0?0:combination(e+t-1,t-1)*Math.pow(1-n,e)*Math.pow(n,t))},cdf:function(e,t,n){var r=0,a=0;if(e<0)return 0;for(;a<=e;a++)r+=negbin.pdf(a,t,n);return r}};function sum(e){for(var t=0,n=e.length;--n>=0;)t+=e[n];return t}function mean(e){return sum(e)/e.length}function sumsqerr(e){for(var t,n=mean(e),r=0,a=e.length;--a>=0;)r+=(t=e[a]-n)*t;return r}function variance(e,t){return sumsqerr(e)/(e.length-(t?1:0))}function stdev(e,t){return Math.sqrt(variance(e,t))}function normalci(){var e,t=[].slice.call(arguments),n=new Array(2);return e=4===t.length?Math.abs(normal.inv(t[1]/2,0,1)*t[2]/Math.sqrt(t[3])):Math.abs(normal.inv(t[1]/2,0,1)*stdev(t[2])/Math.sqrt(t[2].length)),n[0]=t[0]-e,n[1]=t[0]+e,n}function tci(){var e,t=[].slice.call(arguments),n=new Array(2);return e=4===t.length?Math.abs(studentt.inv(t[1]/2,t[3]-1)*t[2]/Math.sqrt(t[3])):Math.abs(studentt.inv(t[1]/2,t[2].length-1)*stdev(t[2],!0)/Math.sqrt(t[2].length)),n[0]=t[0]-e,n[1]=t[0]+e,n}function product(e){for(var t=1,n=e.length;--n>=0;)t*=e[n];return t}function geomean(e){return Math.pow(product(e),1/e.length)}function covariance(e,t){var n,r=mean(e),a=mean(t),i=e.length,o=new Array(i);for(n=0;n=i?new CellError(ErrorType.NUM,ErrorMessage.ValueLarge):(e=(e-a)/(i-a),r?beta.cdf(e,t,n):beta.pdf(e,t,n))}))}},{key:"betainv",value:function(e,t){return this.runFunction(e.args,t,this.metadata("BETA.INV"),(function(e,t,n,r,a){return r>=a?new CellError(ErrorType.NUM,ErrorMessage.WrongOrder):beta.inv(e,t,n)*(a-r)+r}))}},{key:"binomialdist",value:function(e,t){return this.runFunction(e.args,t,this.metadata("BINOM.DIST"),(function(e,t,n,r){return e>t?new CellError(ErrorType.NUM,ErrorMessage.WrongOrder):(e=Math.trunc(e),t=Math.trunc(t),r?binomial.cdf(e,t,n):binomial.pdf(e,t,n))}))}},{key:"binomialinv",value:function(e,t){return this.runFunction(e.args,t,this.metadata("BINOM.INV"),(function(e,t,n){for(var r=-1,a=e=Math.trunc(e);a>r+1;){var i=Math.trunc((r+a)/2);binomial.cdf(i,e,t)>=n?a=i:r=i}return a}))}},{key:"besselifn",value:function(e,t){return this.runFunction(e.args,t,this.metadata("BESSELI"),(function(e,t){return besseli(e,Math.trunc(t))}))}},{key:"besseljfn",value:function(e,t){return this.runFunction(e.args,t,this.metadata("BESSELJ"),(function(e,t){return besselj(e,Math.trunc(t))}))}},{key:"besselkfn",value:function(e,t){return this.runFunction(e.args,t,this.metadata("BESSELK"),(function(e,t){return besselk(e,Math.trunc(t))}))}},{key:"besselyfn",value:function(e,t){return this.runFunction(e.args,t,this.metadata("BESSELY"),(function(e,t){return bessely(e,Math.trunc(t))}))}},{key:"chisqdist",value:function(e,t){return this.runFunction(e.args,t,this.metadata("CHISQ.DIST"),(function(e,t,n){return t=Math.trunc(t),n?chisquare.cdf(e,t):chisquare.pdf(e,t)}))}},{key:"chisqdistrt",value:function(e,t){return this.runFunction(e.args,t,this.metadata("CHISQ.DIST.RT"),(function(e,t){return 1-chisquare.cdf(e,Math.trunc(t))}))}},{key:"chisqinv",value:function(e,t){return this.runFunction(e.args,t,this.metadata("CHISQ.INV"),(function(e,t){return chisquare.inv(e,Math.trunc(t))}))}},{key:"chisqinvrt",value:function(e,t){return this.runFunction(e.args,t,this.metadata("CHISQ.INV.RT"),(function(e,t){return chisquare.inv(1-e,Math.trunc(t))}))}},{key:"fdist",value:function(e,t){return this.runFunction(e.args,t,this.metadata("F.DIST"),(function(e,t,n,r){return t=Math.trunc(t),n=Math.trunc(n),r?centralF.cdf(e,t,n):centralF.pdf(e,t,n)}))}},{key:"fdistrt",value:function(e,t){return this.runFunction(e.args,t,this.metadata("F.DIST.RT"),(function(e,t,n){return 1-centralF.cdf(e,Math.trunc(t),Math.trunc(n))}))}},{key:"finv",value:function(e,t){return this.runFunction(e.args,t,this.metadata("F.INV"),(function(e,t,n){return centralF.inv(e,Math.trunc(t),Math.trunc(n))}))}},{key:"finvrt",value:function(e,t){return this.runFunction(e.args,t,this.metadata("F.INV.RT"),(function(e,t,n){return centralF.inv(1-e,Math.trunc(t),Math.trunc(n))}))}},{key:"weibulldist",value:function(e,t){return this.runFunction(e.args,t,this.metadata("WEIBULL.DIST"),(function(e,t,n,r){return r?weibull.cdf(e,n,t):weibull.pdf(e,n,t)}))}},{key:"poissondist",value:function(e,t){return this.runFunction(e.args,t,this.metadata("POISSON.DIST"),(function(e,t,n){return e=Math.trunc(e),n?poisson.cdf(e,t):poisson.pdf(e,t)}))}},{key:"hypgeomdist",value:function(e,t){return this.runFunction(e.args,t,this.metadata("HYPGEOM.DIST"),(function(e,t,n,r,a){return e>t||e>n||t>r||n>r||e+r=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$3(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$3(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$3(e,t):void 0}}function _arrayLikeToArray$3(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=1;n-=2)t*=n;return t}))}},{key:"combin",value:function(e,t){return this.runFunction(e.args,t,this.metadata("COMBIN"),(function(e,t){return t>e?new CellError(ErrorType.NUM,ErrorMessage.WrongOrder):_combin(e=Math.trunc(e),t=Math.trunc(t))}))}},{key:"combina",value:function(e,t){return this.runFunction(e.args,t,this.metadata("COMBINA"),(function(e,t){return(e=Math.trunc(e))+(t=Math.trunc(t))-1>=1030?new CellError(ErrorType.NUM,ErrorMessage.ValueLarge):0===e&&0===t?1:_combin(e+t-1,t)}))}},{key:"gcd",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("GCD"),(function(){for(var e=arguments.length,t=new Array(e),r=0;rNumber.MAX_SAFE_INTEGER?new CellError(ErrorType.NUM,ErrorMessage.ValueLarge):o}))}},{key:"lcm",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("LCM"),(function(){for(var e=arguments.length,t=new Array(e),r=0;rNumber.MAX_SAFE_INTEGER?new CellError(ErrorType.NUM,ErrorMessage.ValueLarge):o}))}},{key:"mround",value:function(e,t){return this.runFunction(e.args,t,this.metadata("MROUND"),(function(e,t){return 0===t?0:e>0&&t<0||e<0&&t>0?new CellError(ErrorType.NUM,ErrorMessage.DistinctSigns):Math.round(e/t)*t}))}},{key:"multinomial",value:function(e,t){return this.runFunction(e.args,t,this.metadata("MULTINOMIAL"),(function(){for(var e=0,t=1,n=arguments.length,r=new Array(n),a=0;a0?1:e<0?-1:0}))}},{key:"sumx2my2",value:function(e,t){return this.runFunction(e.args,t,this.metadata("SUMX2MY2"),(function(e,t){var n=e.valuesFromTopLeftCorner(),r=t.valuesFromTopLeftCorner();if(n.length!==r.length)return new CellError(ErrorType.NA,ErrorMessage.EqualLength);for(var a=n.length,i=0,o=0;oe&&(t=e-t);for(var n=1,r=1;r<=t;r++)n*=(e-t+r)/r;return Math.round(n)}function binaryGCD(e,t){if(e0;){var r=[t,e%t];e=r[0],t=r[1]}return e}function binaryLCM(e,t){return 0===e||0===t?0:e*(t/binaryGCD(e,t))}function _typeof$2(e){return _typeof$2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof$2(e)}function _createForOfIteratorHelper$2(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray$2(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_unsupportedIterableToArray$2(e,t)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray$2(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$2(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$2(e,t):void 0}}function _arrayLikeToArray$2(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray$1(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray$1(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray$1(e,t):void 0}}function _arrayLikeToArray$1(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n1&&r>1?(n-1)*(r-1):n*r-1)}))}},{key:"ttest",value:function(e,t){var n=this;return this.runFunction(e.args,t,this.metadata("T.TEST"),(function(e,t,r,a){var i=n.arithmeticHelper.manyToExactNumbers(e.valuesFromTopLeftCorner()),o=n.arithmeticHelper.manyToExactNumbers(t.valuesFromTopLeftCorner());if(i instanceof CellError)return i;if(o instanceof CellError)return o;var s=i.length,l=o.length;if(1===a){if(l!==s)return new CellError(ErrorType.NA,ErrorMessage.EqualLength);if(s<=1)return new CellError(ErrorType.DIV_BY_ZERO,ErrorMessage.TwoValues);for(var u=Array(s),c=0;c0;s--)a=l,l=r*l-u+t[s],u=a;return i=n*Math.exp(-e*e+.5*(t[0]+r*l)-u),o?i-1:1-i}function erfc(e){return 1-erf(e)}function erfcinv(e){let t,n,r,a,i=0;if(e>=2)return-100;if(e<=0)return 100;for(a=e<1?e:2-e,r=Math.sqrt(-2*Math.log(a/2)),t=-.70711*((2.30753+.27061*r)/(1+r*(.99229+.04481*r))-r);i<2;i++)n=erfc(t)-a,t+=n/(1.1283791670955126*Math.exp(-t*t)-t*n);return e<1?t:-t}const exponential={pdf:(e,t)=>e<0?0:t*Math.exp(-t*e),cdf:(e,t)=>e<0?0:1-Math.exp(-t*e)};function gammafn(e){const t=[-1.716185138865495,24.76565080557592,-379.80425647094563,629.3311553128184,866.9662027904133,-31451.272968848367,-36144.413418691176,66456.14382024054],n=[-30.8402300119739,315.35062697960416,-1015.1563674902192,-3107.771671572311,22538.11842098015,4755.846277527881,-134659.9598649693,-115132.2596755535];let r,a,i,s,o=!1,l=0,u=0,c=0,p=e;if(e>171.6243769536076)return 1/0;if(p<=0){if(s=p%1,!s)return 1/0;o=(1&p?-1:1)*Math.PI/Math.sin(Math.PI*s),p=1-p}for(i=p,a=p<1?p++:(p-=l=(0|p)-1)-1,r=0;r<8;++r)c=(c+t[r])*a,u=u*a+n[r];if(s=c/u+1,ip)for(r=0;r=1?e:1/e)+.4*e+17);let d;if(t<0||e<=0)return NaN;if(t=1)return Math.max(100,t+100*Math.sqrt(t));if(e<=0)return 0;for(t>1?(c=Math.log(r),p=Math.exp(r*(c-1)-a),u=e<.5?e:1-e,o=Math.sqrt(-2*Math.log(u)),i=(2.30753+.27061*o)/(1+o*(.99229+.04481*o))-o,e<.5&&(i=-i),i=Math.max(.001,t*Math.pow(1-1/(9*t)-i/(3*Math.sqrt(t)),3))):(o=1-t*(.253+.12*t),i=e1?p*Math.exp(-(i-r)+r*(Math.log(i)-c)):Math.exp(-i+r*Math.log(i)-a),l=s/o,i-=o=l/(1-.5*Math.min(1,l*((t-1)/i-1))),i<=0&&(i=.5*(i+o)),Math.abs(o)<1e-8*i)break}return i}const normal={pdf:function(e,t,n){return Math.exp(-.5*Math.log(2*Math.PI)-Math.log(n)-Math.pow(e-t,2)/(2*n*n))},cdf:function(e,t,n){return.5*(1+erf((e-t)/Math.sqrt(2*n*n)))},inv:function(e,t,n){return-1.4142135623730951*n*erfcinv(2*e)+t}},beta={pdf:function(e,t,n){return e>1||e<0?0:1==t&&1==n?1:t<512&&n<512?Math.pow(e,t-1)*Math.pow(1-e,n-1)/betafn(t,n):Math.exp((t-1)*Math.log(e)+(n-1)*Math.log(1-e)-betaln(t,n))},cdf:function(e,t,n){return e>1||e<0?+(e>1):ibeta(e,t,n)},inv:function(e,t,n){return ibetainv(e,t,n)}};function betafn(e,t){if(!(e<=0||t<=0))return e+t>170?Math.exp(betaln(e,t)):gammafn(e)*gammafn(t)/gammafn(e+t)}function betaln(e,t){return gammaln(e)+gammaln(t)-gammaln(e+t)}function ibetainv(e,t,n){var r,a,i,s,o,l,u,c,p,d,m=t-1,h=n-1,f=0;if(e<=0)return 0;if(e>=1)return 1;for(t>=1&&n>=1?(i=e<.5?e:1-e,l=(2.30753+.27061*(s=Math.sqrt(-2*Math.log(i))))/(1+s*(.99229+.04481*s))-s,e<.5&&(l=-l),u=(l*l-3)/6,c=2/(1/(2*t-1)+1/(2*n-1)),p=l*Math.sqrt(u+c)/c-(1/(2*n-1)-1/(2*t-1))*(u+5/6-2/(3*c)),l=t/(t+n*Math.exp(2*p))):(r=Math.log(t/(t+n)),a=Math.log(n/(t+n)),l=e<(s=Math.exp(t*r)/t)/(p=s+(o=Math.exp(n*a)/n))?Math.pow(t*p*e,1/t):1-Math.pow(n*p*(1-e),1/n)),d=-gammaln(t)-gammaln(n)+gammaln(t+n);f<10;f++){if(0===l||1===l)return l;if((l-=s=(o=(ibeta(l,t,n)-e)/(s=Math.exp(m*Math.log(l)+h*Math.log(1-l)+d)))/(1-.5*Math.min(1,o*(m/l-h/(1-l)))))<=0&&(l=.5*(l+s)),l>=1&&(l=.5*(l+s+1)),Math.abs(s)<1e-8*l&&f>0)break}return l}function ibeta(e,t,n){var r=0===e||1===e?0:Math.exp(gammaln(t+n)-gammaln(t)-gammaln(n)+t*Math.log(e)+n*Math.log(1-e));return!(e<0||e>1)&&(e<(t+1)/(t+n+2)?r*betacf(e,t,n)/t:1-r*betacf(1-e,n,t)/n)}function betacf(e,t,n){var r,a,i,s,o=1e-30,l=1,u=t+n,c=t+1,p=t-1,d=1,m=1-u*e/c;for(Math.abs(m)=t)return 1;if(n<0||n>1||t<=0)return NaN;var i=n,s=(e=Math.floor(e))+1,o=t-e,l=s+o,u=Math.exp(gammaln(l)-gammaln(o)-gammaln(s)+s*Math.log(i)+o*Math.log(1-i));return r=i<(s+1)/(l+2)?u*betinc(i,s,o,a):1-u*betinc(1-i,o,s,a),Math.round(1/a*(1-r))/(1/a)}};function betinc(e,t,n,r){for(var a,i=0,s=1,o=1,l=1,u=0,c=0;Math.abs((o-c)/o)>r;)c=o,s=l+(a=-(t+u)*(t+n+u)*e/(t+2*u)/(t+2*u+1))*s,o=(i=o+a*i)+(a=(u+=1)*(n-u)*e/(t+2*u-1)/(t+2*u))*o,i/=l=s+a*l,s/=l,o/=l,l=1;return o/t}function combination(e,t){return e>170||t>170?Math.exp(combinationln(e,t)):factorial(e)/factorial(t)/factorial(e-t)}function combinationln(e,t){return factorialln(e)-factorialln(t)-factorialln(e-t)}function factorialln(e){return e<0?NaN:gammaln(e+1)}function factorial(e){return e<0?NaN:gammafn(e+1)}const chisquare={pdf:function(e,t){return e<0?0:0===e&&2===t?.5:Math.exp((t/2-1)*Math.log(e)-e/2-t/2*Math.log(2)-gammaln(t/2))},cdf:function(e,t){return e<0?0:lowRegGamma(t/2,e/2)},inv:function(e,t){return 2*gammapinv(e,.5*t)}},centralF={pdf:function(e,t,n){var r;return e<0?0:t<=2?0===e&&t<2?1/0:0===e&&2===t?1:1/betafn(t/2,n/2)*Math.pow(t/n,t/2)*Math.pow(e,t/2-1)*Math.pow(1+t/n*e,-(t+n)/2):(r=t*e/(n+e*t),t*(n/(n+e*t))/2*binomial.pdf((t-2)/2,(t+n-2)/2,r))},cdf:function(e,t,n){return e<0?0:ibeta(t*e/(t*e+n),t/2,n/2)},inv:function(e,t,n){return n/(t*(1/ibetainv(e,t/2,n/2)-1))}},weibull={pdf:function(e,t,n){return e<0||t<0||n<0?0:n/t*Math.pow(e/t,n-1)*Math.exp(-Math.pow(e/t,n))},cdf:function(e,t,n){return e<0?0:1-Math.exp(-Math.pow(e/t,n))}},poisson={pdf:function(e,t){return t<0||e%1!=0||e<0?0:Math.pow(t,e)*Math.exp(-t)/factorial(e)},cdf:function(e,t){var n=0;if(e<0)return 0;for(var r=0;n<=e;n++)r+=poisson.pdf(n,t);return r}},hypgeom={pdf:function(e,t,n,r){if(e<0||er||e>n)return 0;if(2*n>t)return 2*r>t?hypgeom.pdf(t-n-r+e,t,t-n,t-r):hypgeom.pdf(r-e,t,t-n,r);if(2*r>t)return hypgeom.pdf(n-e,t,n,t-r);if(n1&&i=a||t>=r)return 1;if(2*r>n)return 2*a>n?e(n-r-a+t,n,n-r,n-a):1-hypgeom.cdf(a-t-1,n,n-r,a);if(2*a>n)return 1-hypgeom.cdf(r-t-1,n,r,n-a);if(r1&&o1e100?1e100:t,1/(Math.sqrt(t)*betafn(.5,t/2))*Math.pow(1+e*e/t,-(t+1)/2)},cdf:function(e,t){var n=t/2;return ibeta((e+Math.sqrt(e*e+t))/(2*Math.sqrt(e*e+t)),n,n)},inv:function(e,t){var n=ibetainv(2*Math.min(e,1-e),.5*t,.5);return n=Math.sqrt(t*(1-n)/n),e>.5?n:-n}},lognormal={pdf:function(e,t,n){return e<=0?0:Math.exp(-Math.log(e)-.5*Math.log(2*Math.PI)-Math.log(n)-Math.pow(Math.log(e)-t,2)/(2*n*n))},cdf:function(e,t,n){return e<0?0:.5+.5*erf((Math.log(e)-t)/Math.sqrt(2*n*n))},inv:function(e,t,n){return Math.exp(-1.4142135623730951*n*erfcinv(2*e)+t)}},negbin={pdf:function(e,t,n){return e===e>>>0&&(e<0?0:combination(e+t-1,t-1)*Math.pow(1-n,e)*Math.pow(n,t))},cdf:function(e,t,n){var r=0,a=0;if(e<0)return 0;for(;a<=e;a++)r+=negbin.pdf(a,t,n);return r}};function sum(e){for(var t=0,n=e.length;--n>=0;)t+=e[n];return t}function mean(e){return sum(e)/e.length}function sumsqerr(e){for(var t,n=mean(e),r=0,a=e.length;--a>=0;)r+=(t=e[a]-n)*t;return r}function variance(e,t){return sumsqerr(e)/(e.length-(t?1:0))}function stdev(e,t){return Math.sqrt(variance(e,t))}function normalci(){var e,t=[].slice.call(arguments),n=new Array(2);return e=4===t.length?Math.abs(normal.inv(t[1]/2,0,1)*t[2]/Math.sqrt(t[3])):Math.abs(normal.inv(t[1]/2,0,1)*stdev(t[2])/Math.sqrt(t[2].length)),n[0]=t[0]-e,n[1]=t[0]+e,n}function tci(){var e,t=[].slice.call(arguments),n=new Array(2);return e=4===t.length?Math.abs(studentt.inv(t[1]/2,t[3]-1)*t[2]/Math.sqrt(t[3])):Math.abs(studentt.inv(t[1]/2,t[2].length-1)*stdev(t[2],!0)/Math.sqrt(t[2].length)),n[0]=t[0]-e,n[1]=t[0]+e,n}function product(e){for(var t=1,n=e.length;--n>=0;)t*=e[n];return t}function geomean(e){return Math.pow(product(e),1/e.length)}function covariance(e,t){var n,r=mean(e),a=mean(t),i=e.length,s=new Array(i);for(n=0;nvoid 0===t?erf(e):erf(t)-erf(e)))}erfc(e,t){return this.runFunction(e.args,t,this.metadata("ERFC"),erfc)}expondist(e,t){return this.runFunction(e.args,t,this.metadata("EXPON.DIST"),((e,t,n)=>n?exponential.cdf(e,t):exponential.pdf(e,t)))}fisher(e,t){return this.runFunction(e.args,t,this.metadata("FISHER"),(e=>Math.log((1+e)/(1-e))/2))}fisherinv(e,t){return this.runFunction(e.args,t,this.metadata("FISHERINV"),(e=>1-2/(Math.exp(2*e)+1)))}gamma(e,t){return this.runFunction(e.args,t,this.metadata("GAMMA"),gammafn)}gammadist(e,t){return this.runFunction(e.args,t,this.metadata("GAMMA.DIST"),((e,t,n,r)=>r?gamma.cdf(e,t,n):gamma.pdf(e,t,n)))}gammaln(e,t){return this.runFunction(e.args,t,this.metadata("GAMMALN"),gammaln)}gammainv(e,t){return this.runFunction(e.args,t,this.metadata("GAMMA.INV"),gamma.inv)}gauss(e,t){return this.runFunction(e.args,t,this.metadata("GAUSS"),(e=>normal.cdf(e,0,1)-.5))}betadist(e,t){return this.runFunction(e.args,t,this.metadata("BETA.DIST"),((e,t,n,r,a,i)=>e<=a?new CellError(ErrorType.NUM,ErrorMessage.ValueSmall):e>=i?new CellError(ErrorType.NUM,ErrorMessage.ValueLarge):(e=(e-a)/(i-a),r?beta.cdf(e,t,n):beta.pdf(e,t,n))))}betainv(e,t){return this.runFunction(e.args,t,this.metadata("BETA.INV"),((e,t,n,r,a)=>r>=a?new CellError(ErrorType.NUM,ErrorMessage.WrongOrder):beta.inv(e,t,n)*(a-r)+r))}binomialdist(e,t){return this.runFunction(e.args,t,this.metadata("BINOM.DIST"),((e,t,n,r)=>e>t?new CellError(ErrorType.NUM,ErrorMessage.WrongOrder):(e=Math.trunc(e),t=Math.trunc(t),r?binomial.cdf(e,t,n):binomial.pdf(e,t,n))))}binomialinv(e,t){return this.runFunction(e.args,t,this.metadata("BINOM.INV"),((e,t,n)=>{let r=-1,a=e=Math.trunc(e);for(;a>r+1;){const i=Math.trunc((r+a)/2);binomial.cdf(i,e,t)>=n?a=i:r=i}return a}))}besselifn(e,t){return this.runFunction(e.args,t,this.metadata("BESSELI"),((e,t)=>besseli(e,Math.trunc(t))))}besseljfn(e,t){return this.runFunction(e.args,t,this.metadata("BESSELJ"),((e,t)=>besselj(e,Math.trunc(t))))}besselkfn(e,t){return this.runFunction(e.args,t,this.metadata("BESSELK"),((e,t)=>besselk(e,Math.trunc(t))))}besselyfn(e,t){return this.runFunction(e.args,t,this.metadata("BESSELY"),((e,t)=>bessely(e,Math.trunc(t))))}chisqdist(e,t){return this.runFunction(e.args,t,this.metadata("CHISQ.DIST"),((e,t,n)=>(t=Math.trunc(t),n?chisquare.cdf(e,t):chisquare.pdf(e,t))))}chisqdistrt(e,t){return this.runFunction(e.args,t,this.metadata("CHISQ.DIST.RT"),((e,t)=>1-chisquare.cdf(e,Math.trunc(t))))}chisqinv(e,t){return this.runFunction(e.args,t,this.metadata("CHISQ.INV"),((e,t)=>chisquare.inv(e,Math.trunc(t))))}chisqinvrt(e,t){return this.runFunction(e.args,t,this.metadata("CHISQ.INV.RT"),((e,t)=>chisquare.inv(1-e,Math.trunc(t))))}fdist(e,t){return this.runFunction(e.args,t,this.metadata("F.DIST"),((e,t,n,r)=>(t=Math.trunc(t),n=Math.trunc(n),r?centralF.cdf(e,t,n):centralF.pdf(e,t,n))))}fdistrt(e,t){return this.runFunction(e.args,t,this.metadata("F.DIST.RT"),((e,t,n)=>1-centralF.cdf(e,Math.trunc(t),Math.trunc(n))))}finv(e,t){return this.runFunction(e.args,t,this.metadata("F.INV"),((e,t,n)=>centralF.inv(e,Math.trunc(t),Math.trunc(n))))}finvrt(e,t){return this.runFunction(e.args,t,this.metadata("F.INV.RT"),((e,t,n)=>centralF.inv(1-e,Math.trunc(t),Math.trunc(n))))}weibulldist(e,t){return this.runFunction(e.args,t,this.metadata("WEIBULL.DIST"),((e,t,n,r)=>r?weibull.cdf(e,n,t):weibull.pdf(e,n,t)))}poissondist(e,t){return this.runFunction(e.args,t,this.metadata("POISSON.DIST"),((e,t,n)=>(e=Math.trunc(e),n?poisson.cdf(e,t):poisson.pdf(e,t))))}hypgeomdist(e,t){return this.runFunction(e.args,t,this.metadata("HYPGEOM.DIST"),((e,t,n,r,a)=>e>t||e>n||t>r||n>r||e+r(t=Math.trunc(t),n?studentt.cdf(e,t):studentt.pdf(e,t))))}tdist2t(e,t){return this.runFunction(e.args,t,this.metadata("T.DIST.2T"),((e,t)=>2*(1-studentt.cdf(e,Math.trunc(t)))))}tdistrt(e,t){return this.runFunction(e.args,t,this.metadata("T.DIST.RT"),((e,t)=>1-studentt.cdf(e,Math.trunc(t))))}tdistold(e,t){return this.runFunction(e.args,t,this.metadata("TDIST"),((e,t,n)=>n*(1-studentt.cdf(e,Math.trunc(t)))))}tinv(e,t){return this.runFunction(e.args,t,this.metadata("T.INV"),((e,t)=>studentt.inv(e,Math.trunc(t))))}tinv2t(e,t){return this.runFunction(e.args,t,this.metadata("T.INV.2T"),((e,t)=>studentt.inv(1-e/2,Math.trunc(t))))}lognormdist(e,t){return this.runFunction(e.args,t,this.metadata("LOGNORM.DIST"),((e,t,n,r)=>r?lognormal.cdf(e,t,n):lognormal.pdf(e,t,n)))}lognorminv(e,t){return this.runFunction(e.args,t,this.metadata("LOGNORM.INV"),((e,t,n)=>lognormal.inv(e,t,n)))}normdist(e,t){return this.runFunction(e.args,t,this.metadata("NORM.DIST"),((e,t,n,r)=>r?normal.cdf(e,t,n):normal.pdf(e,t,n)))}norminv(e,t){return this.runFunction(e.args,t,this.metadata("NORM.INV"),((e,t,n)=>normal.inv(e,t,n)))}normsdist(e,t){return this.runFunction(e.args,t,this.metadata("NORM.S.DIST"),((e,t)=>t?normal.cdf(e,0,1):normal.pdf(e,0,1)))}normsinv(e,t){return this.runFunction(e.args,t,this.metadata("NORM.S.INV"),(e=>normal.inv(e,0,1)))}phi(e,t){return this.runFunction(e.args,t,this.metadata("PHI"),(e=>normal.pdf(e,0,1)))}negbinomdist(e,t){return this.runFunction(e.args,t,this.metadata("NEGBINOM.DIST"),((e,t,n,r)=>(e=Math.trunc(e),t=Math.trunc(t),r?negbin.cdf(e,t,n):negbin.pdf(e,t,n))))}confidencenorm(e,t){return this.runFunction(e.args,t,this.metadata("CONFIDENCE.NORM"),((e,t,n)=>normalci(1,e,t,Math.trunc(n))[1]-1))}confidencet(e,t){return this.runFunction(e.args,t,this.metadata("CONFIDENCE.T"),((e,t,n)=>1===(n=Math.trunc(n))?new CellError(ErrorType.DIV_BY_ZERO):tci(1,e,t,n)[1]-1))}standardize(e,t){return this.runFunction(e.args,t,this.metadata("STANDARDIZE"),((e,t,n)=>(e-t)/n))}}StatisticalPlugin.implementedFunctions={ERF:{method:"erf",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,optionalArg:!0}]},ERFC:{method:"erfc",parameters:[{argumentType:ArgumentTypes.NUMBER}]},"EXPON.DIST":{method:"expondist",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.BOOLEAN}]},FISHER:{method:"fisher",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:-1,lessThan:1}]},FISHERINV:{method:"fisherinv",parameters:[{argumentType:ArgumentTypes.NUMBER}]},GAMMA:{method:"gamma",parameters:[{argumentType:ArgumentTypes.NUMBER}]},"GAMMA.DIST":{method:"gammadist",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.BOOLEAN}]},GAMMALN:{method:"gammaln",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:0}]},"GAMMA.INV":{method:"gammainv",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0,lessThan:1},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0}]},GAUSS:{method:"gauss",parameters:[{argumentType:ArgumentTypes.NUMBER}]},"BETA.DIST":{method:"betadist",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.BOOLEAN},{argumentType:ArgumentTypes.NUMBER,defaultValue:0},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]},"BETA.INV":{method:"betainv",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:0,maxValue:1},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,defaultValue:0},{argumentType:ArgumentTypes.NUMBER,defaultValue:1}]},"BINOM.DIST":{method:"binomialdist",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0,maxValue:1},{argumentType:ArgumentTypes.BOOLEAN}]},"BINOM.INV":{method:"binomialinv",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0,maxValue:1},{argumentType:ArgumentTypes.NUMBER,greaterThan:0,lessThan:1}]},BESSELI:{method:"besselifn",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,minValue:0}]},BESSELJ:{method:"besseljfn",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,minValue:0}]},BESSELK:{method:"besselkfn",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,minValue:0}]},BESSELY:{method:"besselyfn",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,minValue:0}]},"CHISQ.DIST":{method:"chisqdist",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,minValue:1,maxValue:1e10},{argumentType:ArgumentTypes.BOOLEAN}]},"CHISQ.DIST.RT":{method:"chisqdistrt",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,minValue:1,maxValue:1e10}]},"CHISQ.INV":{method:"chisqinv",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0,maxValue:1},{argumentType:ArgumentTypes.NUMBER,minValue:1,maxValue:1e10}]},"CHISQ.INV.RT":{method:"chisqinvrt",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0,maxValue:1},{argumentType:ArgumentTypes.NUMBER,minValue:1}]},"F.DIST":{method:"fdist",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:1},{argumentType:ArgumentTypes.NUMBER,minValue:1},{argumentType:ArgumentTypes.BOOLEAN}]},"F.DIST.RT":{method:"fdistrt",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:1},{argumentType:ArgumentTypes.NUMBER,minValue:1}]},"F.INV":{method:"finv",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0,maxValue:1},{argumentType:ArgumentTypes.NUMBER,minValue:1},{argumentType:ArgumentTypes.NUMBER,minValue:1}]},"F.INV.RT":{method:"finvrt",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0,maxValue:1},{argumentType:ArgumentTypes.NUMBER,minValue:1},{argumentType:ArgumentTypes.NUMBER,minValue:1}]},"WEIBULL.DIST":{method:"weibulldist",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.BOOLEAN}]},"POISSON.DIST":{method:"poissondist",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.BOOLEAN}]},"HYPGEOM.DIST":{method:"hypgeomdist",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.BOOLEAN}]},"T.DIST":{method:"tdist",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,minValue:1},{argumentType:ArgumentTypes.BOOLEAN}]},"T.DIST.2T":{method:"tdist2t",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:1}]},"T.DIST.RT":{method:"tdistrt",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,minValue:1}]},TDIST:{method:"tdistold",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:1},{argumentType:ArgumentTypes.INTEGER,minValue:1,maxValue:2}]},"T.INV":{method:"tinv",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:0,lessThan:1},{argumentType:ArgumentTypes.NUMBER,minValue:1}]},"T.INV.2T":{method:"tinv2t",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:0,maxValue:1},{argumentType:ArgumentTypes.NUMBER,minValue:1}]},"LOGNORM.DIST":{method:"lognormdist",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.BOOLEAN}]},"LOGNORM.INV":{method:"lognorminv",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:0,lessThan:1},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,greaterThan:0}]},"NORM.DIST":{method:"normdist",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.BOOLEAN}]},"NORM.INV":{method:"norminv",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:0,lessThan:1},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,greaterThan:0}]},"NORM.S.DIST":{method:"normsdist",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.BOOLEAN}]},"NORM.S.INV":{method:"normsinv",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:0,lessThan:1}]},PHI:{method:"phi",parameters:[{argumentType:ArgumentTypes.NUMBER}]},"NEGBINOM.DIST":{method:"negbinomdist",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:1},{argumentType:ArgumentTypes.NUMBER,minValue:0,maxValue:1},{argumentType:ArgumentTypes.BOOLEAN}]},"CONFIDENCE.NORM":{method:"confidencenorm",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:0,lessThan:1},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,minValue:1}]},"CONFIDENCE.T":{method:"confidencet",parameters:[{argumentType:ArgumentTypes.NUMBER,greaterThan:0,lessThan:1},{argumentType:ArgumentTypes.NUMBER,greaterThan:0},{argumentType:ArgumentTypes.NUMBER,minValue:1}]},STANDARDIZE:{method:"standardize",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,greaterThan:0}]}},StatisticalPlugin.aliases={NEGBINOMDIST:"NEGBINOM.DIST",EXPONDIST:"EXPON.DIST",BETADIST:"BETA.DIST",NORMDIST:"NORM.DIST",NORMINV:"NORM.INV",NORMSDIST:"NORM.S.DIST",NORMSINV:"NORM.S.INV",LOGNORMDIST:"LOGNORM.DIST",LOGINV:"LOGNORM.INV",TINV:"T.INV.2T",HYPGEOMDIST:"HYPGEOM.DIST",POISSON:"POISSON.DIST",WEIBULL:"WEIBULL.DIST",FINV:"F.INV.RT",FDIST:"F.DIST.RT",CHIDIST:"CHISQ.DIST.RT",CHIINV:"CHISQ.INV.RT",GAMMADIST:"GAMMA.DIST","GAMMALN.PRECISE":"GAMMALN",GAMMAINV:"GAMMA.INV",BETAINV:"BETA.INV",BINOMDIST:"BINOM.DIST",CONFIDENCE:"CONFIDENCE.NORM",CRITBINOM:"BINOM.INV",WEIBULLDIST:"WEIBULL.DIST",TINV2T:"T.INV.2T",TDISTRT:"T.DIST.RT",TDIST2T:"T.DIST.2T",FINVRT:"F.INV.RT",FDISTRT:"F.DIST.RT",CHIDISTRT:"CHISQ.DIST.RT",CHIINVRT:"CHISQ.INV.RT",LOGNORMINV:"LOGNORM.INV",POISSONDIST:"POISSON.DIST"}; +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ +class MathPlugin extends FunctionPlugin{fact(e,t){return this.runFunction(e.args,t,this.metadata("FACT"),(e=>{e=Math.trunc(e);let t=1;for(let n=1;n<=e;n++)t*=n;return t}))}factdouble(e,t){return this.runFunction(e.args,t,this.metadata("FACTDOUBLE"),(e=>{let t=1;for(let n=e=Math.trunc(e);n>=1;n-=2)t*=n;return t}))}combin(e,t){return this.runFunction(e.args,t,this.metadata("COMBIN"),((e,t)=>t>e?new CellError(ErrorType.NUM,ErrorMessage.WrongOrder):combin(e=Math.trunc(e),t=Math.trunc(t))))}combina(e,t){return this.runFunction(e.args,t,this.metadata("COMBINA"),((e,t)=>(e=Math.trunc(e))+(t=Math.trunc(t))-1>=1030?new CellError(ErrorType.NUM,ErrorMessage.ValueLarge):0===e&&0===t?1:combin(e+t-1,t)))}gcd(e,t){return this.runFunction(e.args,t,this.metadata("GCD"),((...e)=>{const t=this.arithmeticHelper.coerceNumbersCoerceRangesDropNulls(e);if(t instanceof CellError)return t;let n=0;for(const e of t){if(e<0)return new CellError(ErrorType.NUM,ErrorMessage.ValueSmall);n=binaryGCD(n,Math.trunc(e))}return n>Number.MAX_SAFE_INTEGER?new CellError(ErrorType.NUM,ErrorMessage.ValueLarge):n}))}lcm(e,t){return this.runFunction(e.args,t,this.metadata("LCM"),((...e)=>{const t=this.arithmeticHelper.coerceNumbersCoerceRangesDropNulls(e);if(t instanceof CellError)return t;let n=1;for(const e of t){if(e<0)return new CellError(ErrorType.NUM,ErrorMessage.ValueSmall);n=binaryLCM(n,Math.trunc(e))}return n>Number.MAX_SAFE_INTEGER?new CellError(ErrorType.NUM,ErrorMessage.ValueLarge):n}))}mround(e,t){return this.runFunction(e.args,t,this.metadata("MROUND"),((e,t)=>0===t?0:e>0&&t<0||e<0&&t>0?new CellError(ErrorType.NUM,ErrorMessage.DistinctSigns):Math.round(e/t)*t))}multinomial(e,t){return this.runFunction(e.args,t,this.metadata("MULTINOMIAL"),((...e)=>{let t=0,n=1;for(let r of e){if(r<0)return new CellError(ErrorType.NUM,ErrorMessage.ValueSmall);r=Math.trunc(r);for(let e=1;e<=r;e++)n*=(t+e)/e;t+=r}return Math.round(n)}))}quotient(e,t){return this.runFunction(e.args,t,this.metadata("QUOTIENT"),((e,t)=>0===t?new CellError(ErrorType.DIV_BY_ZERO):Math.trunc(e/t)))}seriessum(e,t){return this.runFunction(e.args,t,this.metadata("SERIESSUM"),((e,t,n,r)=>{const a=this.arithmeticHelper.manyToOnlyNumbersDropNulls(r.valuesFromTopLeftCorner());if(a instanceof CellError)return a;let i=0;a.reverse();for(const t of a)i*=Math.pow(e,n),i+=t;return i*Math.pow(e,t)}))}sign(e,t){return this.runFunction(e.args,t,this.metadata("SIGN"),(e=>e>0?1:e<0?-1:0))}sumx2my2(e,t){return this.runFunction(e.args,t,this.metadata("SUMX2MY2"),((e,t)=>{const n=e.valuesFromTopLeftCorner(),r=t.valuesFromTopLeftCorner();if(n.length!==r.length)return new CellError(ErrorType.NA,ErrorMessage.EqualLength);const a=n.length;let i=0;for(let e=0;e{const n=e.valuesFromTopLeftCorner(),r=t.valuesFromTopLeftCorner();if(n.length!==r.length)return new CellError(ErrorType.NA,ErrorMessage.EqualLength);const a=n.length;let i=0;for(let e=0;e{const n=e.valuesFromTopLeftCorner(),r=t.valuesFromTopLeftCorner();if(n.length!==r.length)return new CellError(ErrorType.NA,ErrorMessage.EqualLength);const a=n.length;let i=0;for(let e=0;ee&&(t=e-t);let n=1;for(let r=1;r<=t;r++)n*=(e-t+r)/r;return Math.round(n)}function binaryGCD(e,t){for(e0;)[e,t]=[t,e%t];return e}function binaryLCM(e,t){return 0===e||0===t?0:e*(t/binaryGCD(e,t))} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */MathPlugin.implementedFunctions={FACT:{method:"fact",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0,maxValue:170}]},FACTDOUBLE:{method:"factdouble",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0,maxValue:288}]},COMBIN:{method:"combin",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0,lessThan:1030},{argumentType:ArgumentTypes.NUMBER,minValue:0}]},COMBINA:{method:"combina",parameters:[{argumentType:ArgumentTypes.NUMBER,minValue:0},{argumentType:ArgumentTypes.NUMBER,minValue:0}]},GCD:{method:"gcd",parameters:[{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1},LCM:{method:"lcm",parameters:[{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1},MROUND:{method:"mround",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER}]},MULTINOMIAL:{method:"multinomial",parameters:[{argumentType:ArgumentTypes.NUMBER}],repeatLastArgs:1,expandRanges:!0},QUOTIENT:{method:"quotient",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER}]},SERIESSUM:{method:"seriessum",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.RANGE}]},SIGN:{method:"sign",parameters:[{argumentType:ArgumentTypes.NUMBER}]},SUMX2MY2:{method:"sumx2my2",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},SUMX2PY2:{method:"sumx2py2",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},SUMXMY2:{method:"sumxmy2",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]}};class ComplexPlugin extends FunctionPlugin{complex(e,t){return this.runFunction(e.args,t,this.metadata("COMPLEX"),((e,t,n)=>"i"!==n&&"j"!==n?new CellError(ErrorType.VALUE,ErrorMessage.ShouldBeIorJ):coerceComplexToString([e,t],n)))}imabs(e,t){return this.runFunction(e.args,t,this.metadata("IMABS"),abs)}imaginary(e,t){return this.runFunction(e.args,t,this.metadata("IMAGINARY"),(([e,t])=>t))}imreal(e,t){return this.runFunction(e.args,t,this.metadata("IMREAL"),(([e,t])=>e))}imargument(e,t){return this.runFunction(e.args,t,this.metadata("IMARGUMENT"),(([e,t])=>0===e&&0===t?new CellError(ErrorType.DIV_BY_ZERO):Math.atan2(t,e)))}imconjugate(e,t){return this.runFunction(e.args,t,this.metadata("IMCONJUGATE"),(([e,t])=>coerceComplexToString([e,-t])))}imcos(e,t){return this.runFunction(e.args,t,this.metadata("IMCOS"),(e=>coerceComplexToString(cos(e))))}imcosh(e,t){return this.runFunction(e.args,t,this.metadata("IMCOSH"),(e=>coerceComplexToString(cosh(e))))}imcot(e,t){return this.runFunction(e.args,t,this.metadata("IMCOT"),(e=>coerceComplexToString(div(cos(e),sin(e)))))}imcsc(e,t){return this.runFunction(e.args,t,this.metadata("IMCSC"),(e=>coerceComplexToString(div([1,0],sin(e)))))}imcsch(e,t){return this.runFunction(e.args,t,this.metadata("IMCSCH"),(e=>coerceComplexToString(div([1,0],sinh(e)))))}imsec(e,t){return this.runFunction(e.args,t,this.metadata("IMSEC"),(e=>coerceComplexToString(div([1,0],cos(e)))))}imsech(e,t){return this.runFunction(e.args,t,this.metadata("IMSECH"),(e=>coerceComplexToString(div([1,0],cosh(e)))))}imsin(e,t){return this.runFunction(e.args,t,this.metadata("IMSIN"),(e=>coerceComplexToString(sin(e))))}imsinh(e,t){return this.runFunction(e.args,t,this.metadata("IMSINH"),(e=>coerceComplexToString(sinh(e))))}imtan(e,t){return this.runFunction(e.args,t,this.metadata("IMTAN"),(e=>coerceComplexToString(div(sin(e),cos(e)))))}imdiv(e,t){return this.runFunction(e.args,t,this.metadata("IMDIV"),((e,t)=>coerceComplexToString(div(e,t))))}improduct(e,t){return this.runFunction(e.args,t,this.metadata("IMPRODUCT"),((...e)=>{const t=this.arithmeticHelper.coerceComplexExactRanges(e);if(t instanceof CellError)return t;let n=[1,0];for(const e of t)n=mul(n,e);return coerceComplexToString(n)}))}imsum(e,t){return this.runFunction(e.args,t,this.metadata("IMSUM"),((...e)=>{const t=this.arithmeticHelper.coerceComplexExactRanges(e);if(t instanceof CellError)return t;let n=[0,0];for(const e of t)n=add(n,e);return coerceComplexToString(n)}))}imsub(e,t){return this.runFunction(e.args,t,this.metadata("IMSUB"),((e,t)=>coerceComplexToString(sub(e,t))))}imexp(e,t){return this.runFunction(e.args,t,this.metadata("IMEXP"),(e=>coerceComplexToString(exp(e))))}imln(e,t){return this.runFunction(e.args,t,this.metadata("IMLN"),(e=>coerceComplexToString(ln$1(e))))}imlog10(e,t){return this.runFunction(e.args,t,this.metadata("IMLOG10"),(e=>{const[t,n]=ln$1(e),r=Math.log(10);return coerceComplexToString([t/r,n/r])}))}imlog2(e,t){return this.runFunction(e.args,t,this.metadata("IMLOG2"),(e=>{const[t,n]=ln$1(e),r=Math.log(2);return coerceComplexToString([t/r,n/r])}))}impower(e,t){return this.runFunction(e.args,t,this.metadata("IMPOWER"),((e,t)=>coerceComplexToString(power(e,t))))}imsqrt(e,t){return this.runFunction(e.args,t,this.metadata("IMSQRT"),(e=>coerceComplexToString(power(e,.5))))}}function add([e,t],[n,r]){return[e+n,t+r]}function sub([e,t],[n,r]){return[e-n,t-r]}function mul([e,t],[n,r]){return[e*n-t*r,e*r+n*t]}function div([e,t],[n,r]){const a=Math.pow(n,2)+Math.pow(r,2),[i,s]=mul([e,t],[n,-r]);return[i/a,s/a]}function cos([e,t]){return[Math.cos(e)*Math.cosh(t),-Math.sin(e)*Math.sinh(t)]}function cosh([e,t]){return[Math.cosh(e)*Math.cos(t),Math.sinh(e)*Math.sin(t)]}function sin([e,t]){return[Math.sin(e)*Math.cosh(t),Math.cos(e)*Math.sinh(t)]}function sinh([e,t]){return[Math.sinh(e)*Math.cos(t),Math.cosh(e)*Math.sin(t)]}function exp([e,t]){return[Math.exp(e)*Math.cos(t),Math.exp(e)*Math.sin(t)]}function abs([e,t]){return Math.sqrt(e*e+t*t)}function ln$1([e,t]){return[Math.log(abs([e,t])),Math.atan2(t,e)]}function power(e,t){const[n,r]=ln$1(e);return exp([t*n,t*r])} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */ComplexPlugin.implementedFunctions={COMPLEX:{method:"complex",parameters:[{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.STRING,defaultValue:"i"}]},IMABS:{method:"imabs",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMAGINARY:{method:"imaginary",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMREAL:{method:"imreal",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMARGUMENT:{method:"imargument",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMCONJUGATE:{method:"imconjugate",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMCOS:{method:"imcos",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMCOSH:{method:"imcosh",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMCOT:{method:"imcot",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMCSC:{method:"imcsc",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMCSCH:{method:"imcsch",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMSEC:{method:"imsec",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMSECH:{method:"imsech",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMSIN:{method:"imsin",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMSINH:{method:"imsinh",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMTAN:{method:"imtan",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMDIV:{method:"imdiv",parameters:[{argumentType:ArgumentTypes.COMPLEX},{argumentType:ArgumentTypes.COMPLEX}]},IMPRODUCT:{method:"improduct",parameters:[{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1},IMSUM:{method:"imsum",parameters:[{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1},IMSUB:{method:"imsub",parameters:[{argumentType:ArgumentTypes.COMPLEX},{argumentType:ArgumentTypes.COMPLEX}]},IMEXP:{method:"imexp",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMLN:{method:"imln",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMLOG10:{method:"imlog10",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMLOG2:{method:"imlog2",parameters:[{argumentType:ArgumentTypes.COMPLEX}]},IMPOWER:{method:"impower",parameters:[{argumentType:ArgumentTypes.COMPLEX},{argumentType:ArgumentTypes.NUMBER}]},IMSQRT:{method:"imsqrt",parameters:[{argumentType:ArgumentTypes.COMPLEX}]}};class StatisticalAggregationPlugin extends FunctionPlugin{avedev(e,t){return this.runFunction(e.args,t,this.metadata("AVEDEV"),((...e)=>{const t=this.arithmeticHelper.coerceNumbersExactRanges(e);if(t instanceof CellError)return t;if(0===t.length)return new CellError(ErrorType.DIV_BY_ZERO);const n=mean(t);return t.reduce(((e,t)=>e+Math.abs(t-n)),0)/t.length}))}devsq(e,t){return this.runFunction(e.args,t,this.metadata("DEVSQ"),((...e)=>{const t=this.arithmeticHelper.coerceNumbersExactRanges(e);return t instanceof CellError?t:0===t.length?0:sumsqerr(t)}))}geomean(e,t){return this.runFunction(e.args,t,this.metadata("GEOMEAN"),((...e)=>{const t=this.arithmeticHelper.coerceNumbersExactRanges(e);if(t instanceof CellError)return t;if(0===t.length)return new CellError(ErrorType.NUM,ErrorMessage.OneValue);for(const e of t)if(e<=0)return new CellError(ErrorType.NUM,ErrorMessage.ValueSmall);return geomean(t)}))}harmean(e,t){return this.runFunction(e.args,t,this.metadata("HARMEAN"),((...e)=>{const t=this.arithmeticHelper.coerceNumbersExactRanges(e);if(t instanceof CellError)return t;if(0===t.length)return new CellError(ErrorType.NUM,ErrorMessage.OneValue);for(const e of t)if(e<=0)return new CellError(ErrorType.NUM,ErrorMessage.ValueSmall);return t.length/t.reduce(((e,t)=>e+1/t),0)}))}correl(e,t){return this.runFunction(e.args,t,this.metadata("CORREL"),((e,t)=>{if(e.numberOfElements()!==t.numberOfElements())return new CellError(ErrorType.NA,ErrorMessage.EqualLength);const n=parseTwoArrays(e,t);if(n instanceof CellError)return n;return n[0].length<=1?new CellError(ErrorType.DIV_BY_ZERO,ErrorMessage.TwoValues):corrcoeff(n[0],n[1])}))}rsq(e,t){return this.runFunction(e.args,t,this.metadata("RSQ"),((e,t)=>{if(e.numberOfElements()!==t.numberOfElements())return new CellError(ErrorType.NA,ErrorMessage.EqualLength);const n=parseTwoArrays(e,t);if(n instanceof CellError)return n;return n[0].length<=1?new CellError(ErrorType.DIV_BY_ZERO,ErrorMessage.TwoValues):Math.pow(corrcoeff(n[0],n[1]),2)}))}covariancep(e,t){return this.runFunction(e.args,t,this.metadata("COVARIANCE.P"),((e,t)=>{if(e.numberOfElements()!==t.numberOfElements())return new CellError(ErrorType.NA,ErrorMessage.EqualLength);const n=parseTwoArrays(e,t);if(n instanceof CellError)return n;const r=n[0].length;return r<1?new CellError(ErrorType.DIV_BY_ZERO,ErrorMessage.OneValue):1===r?0:covariance(n[0],n[1])*(r-1)/r}))}covariances(e,t){return this.runFunction(e.args,t,this.metadata("COVARIANCE.S"),((e,t)=>{if(e.numberOfElements()!==t.numberOfElements())return new CellError(ErrorType.NA,ErrorMessage.EqualLength);const n=parseTwoArrays(e,t);if(n instanceof CellError)return n;return n[0].length<=1?new CellError(ErrorType.DIV_BY_ZERO,ErrorMessage.TwoValues):covariance(n[0],n[1])}))}ztest(e,t){return this.runFunction(e.args,t,this.metadata("Z.TEST"),((e,t,n)=>{const r=this.arithmeticHelper.manyToExactNumbers(e.valuesFromTopLeftCorner());if(r instanceof CellError)return r;const a=r.length;if(void 0===n){if(a<2)return new CellError(ErrorType.DIV_BY_ZERO,ErrorMessage.TwoValues);n=stdev(r,!0)}return a<1?new CellError(ErrorType.NA,ErrorMessage.OneValue):0===n?new CellError(ErrorType.DIV_BY_ZERO):1-normal.cdf((mean(r)-t)/(n/Math.sqrt(a)),0,1)}))}ftest(e,t){return this.runFunction(e.args,t,this.metadata("F.TEST"),((e,t)=>{const n=this.arithmeticHelper.manyToExactNumbers(e.valuesFromTopLeftCorner()),r=this.arithmeticHelper.manyToExactNumbers(t.valuesFromTopLeftCorner());if(n instanceof CellError)return n;if(r instanceof CellError)return r;if(n.length<=1||r.length<=1)return new CellError(ErrorType.DIV_BY_ZERO);const a=variance(n,!0),i=variance(r,!0);if(0===a||0===i)return new CellError(ErrorType.DIV_BY_ZERO);const s=a/i,o=centralF.cdf(s,n.length-1,r.length-1);return 2*Math.min(o,1-o)}))}steyx(e,t){return this.runFunction(e.args,t,this.metadata("STEYX"),((e,t)=>{if(e.numberOfElements()!==t.numberOfElements())return new CellError(ErrorType.NA,ErrorMessage.EqualLength);const n=parseTwoArrays(e,t);if(n instanceof CellError)return n;const r=n[0].length;return r<=2?new CellError(ErrorType.DIV_BY_ZERO,ErrorMessage.ThreeValues):Math.sqrt((sumsqerr(n[0])-Math.pow(covariance(n[0],n[1])*(r-1),2)/sumsqerr(n[1]))/(r-2))}))}slope(e,t){return this.runFunction(e.args,t,this.metadata("SLOPE"),((e,t)=>{if(e.numberOfElements()!==t.numberOfElements())return new CellError(ErrorType.NA,ErrorMessage.EqualLength);const n=parseTwoArrays(e,t);if(n instanceof CellError)return n;const r=n[0].length;return r<=1?new CellError(ErrorType.DIV_BY_ZERO,ErrorMessage.TwoValues):covariance(n[0],n[1])*(r-1)/sumsqerr(n[1])}))}chisqtest(e,t){return this.runFunction(e.args,t,this.metadata("CHISQ.TEST"),((e,t)=>{const n=e.height(),r=e.width();if(t.height()!==n||t.width()!==r)return new CellError(ErrorType.NA,ErrorMessage.EqualLength);const a=parseTwoArrays(e,t);if(a instanceof CellError)return a;if(a[0].length<=1)return new CellError(ErrorType.DIV_BY_ZERO,ErrorMessage.TwoValues);let i=0;for(let e=0;e1&&r>1?(n-1)*(r-1):n*r-1)}))}ttest(e,t){return this.runFunction(e.args,t,this.metadata("T.TEST"),((e,t,n,r)=>{const a=this.arithmeticHelper.manyToExactNumbers(e.valuesFromTopLeftCorner()),i=this.arithmeticHelper.manyToExactNumbers(t.valuesFromTopLeftCorner());if(a instanceof CellError)return a;if(i instanceof CellError)return i;const s=a.length,o=i.length;if(1===r){if(o!==s)return new CellError(ErrorType.NA,ErrorMessage.EqualLength);if(s<=1)return new CellError(ErrorType.DIV_BY_ZERO,ErrorMessage.TwoValues);const e=Array(s);for(let t=0;t{const t=this.arithmeticHelper.coerceNumbersExactRanges(e);if(t instanceof CellError)return t;const n=t.length;if(n<3)return new CellError(ErrorType.DIV_BY_ZERO,ErrorMessage.ThreeValues);const r=mean(t),a=stdev(t,!0);return 0===a?new CellError(ErrorType.DIV_BY_ZERO):t.reduce(((e,t)=>e+Math.pow((t-r)/a,3)),0)*n/(n-1)/(n-2)}))}skewp(e,t){return this.runFunction(e.args,t,this.metadata("SKEW.P"),((...e)=>{const t=this.arithmeticHelper.coerceNumbersExactRanges(e);if(t instanceof CellError)return t;const n=t.length;if(n<3)return new CellError(ErrorType.DIV_BY_ZERO,ErrorMessage.ThreeValues);const r=mean(t),a=stdev(t,!1);return 0===a?new CellError(ErrorType.DIV_BY_ZERO):t.reduce(((e,t)=>e+Math.pow((t-r)/a,3)),0)/n}))}}function parseTwoArrays(e,t){const n=e.iterateValuesFromTopLeftCorner(),r=t.iterateValuesFromTopLeftCorner();let a,i;const s=[],o=[];for(;a=n.next(),i=r.next(),!a.done&&!i.done;){const e=a.value,t=i.value;if(e instanceof CellError)return e;if(t instanceof CellError)return t;isExtendedNumber(e)&&isExtendedNumber(t)&&(s.push(getRawValue(e)),o.push(getRawValue(t)))}return[s,o]} +/** + * @license + * Copyright (c) 2022 Handsoncode. All rights reserved. + */StatisticalAggregationPlugin.implementedFunctions={AVEDEV:{method:"avedev",parameters:[{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1},DEVSQ:{method:"devsq",parameters:[{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1},GEOMEAN:{method:"geomean",parameters:[{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1},HARMEAN:{method:"harmean",parameters:[{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1},CORREL:{method:"correl",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},RSQ:{method:"rsq",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},"COVARIANCE.P":{method:"covariancep",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},"COVARIANCE.S":{method:"covariances",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},"Z.TEST":{method:"ztest",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,optionalArg:!0}]},"F.TEST":{method:"ftest",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},STEYX:{method:"steyx",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},SLOPE:{method:"slope",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},"CHISQ.TEST":{method:"chisqtest",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},"T.TEST":{method:"ttest",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.INTEGER,minValue:1,maxValue:2},{argumentType:ArgumentTypes.INTEGER,minValue:1,maxValue:3}]},SKEW:{method:"skew",parameters:[{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1},"SKEW.P":{method:"skewp",parameters:[{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1}},StatisticalAggregationPlugin.aliases={COVAR:"COVARIANCE.P",FTEST:"F.TEST",PEARSON:"CORREL",ZTEST:"Z.TEST",CHITEST:"CHISQ.TEST",TTEST:"T.TEST",COVARIANCEP:"COVARIANCE.P",COVARIANCES:"COVARIANCE.S",SKEWP:"SKEW.P"};var plugins=Object.freeze({__proto__:null,ArrayPlugin:ArrayPlugin,AbsPlugin:AbsPlugin,BitShiftPlugin:BitShiftPlugin,BitwiseLogicOperationsPlugin:BitwiseLogicOperationsPlugin,BooleanPlugin:BooleanPlugin,CharPlugin:CharPlugin,CodePlugin:CodePlugin,CountBlankPlugin:CountBlankPlugin,CountUniquePlugin:CountUniquePlugin,DateTimePlugin:DateTimePlugin,DegreesPlugin:DegreesPlugin,DeltaPlugin:DeltaPlugin,ExpPlugin:ExpPlugin,FinancialPlugin:FinancialPlugin,FormulaTextPlugin:FormulaTextPlugin,InformationPlugin:InformationPlugin,IsEvenPlugin:IsEvenPlugin,IsOddPlugin:IsOddPlugin,LogarithmPlugin:LogarithmPlugin,MathConstantsPlugin:MathConstantsPlugin,MatrixPlugin:MatrixPlugin,MedianPlugin:MedianPlugin,ModuloPlugin:ModuloPlugin,NumericAggregationPlugin:NumericAggregationPlugin,PowerPlugin:PowerPlugin,RadiansPlugin:RadiansPlugin,RadixConversionPlugin:RadixConversionPlugin,RandomPlugin:RandomPlugin,RoundingPlugin:RoundingPlugin,SqrtPlugin:SqrtPlugin,ConditionalAggregationPlugin:ConditionalAggregationPlugin,SumprodPlugin:SumprodPlugin,TextPlugin:TextPlugin,TrigonometryPlugin:TrigonometryPlugin,LookupPlugin:LookupPlugin,RomanPlugin:RomanPlugin,SimpleArithmerticPlugin:SimpleArithmerticPlugin,StatisticalPlugin:StatisticalPlugin,MathPlugin:MathPlugin,ComplexPlugin:ComplexPlugin,StatisticalAggregationPlugin:StatisticalAggregationPlugin}); /** * @license - * Copyright (c) 2021 Handsoncode. All rights reserved. - */StatisticalAggregationPlugin.implementedFunctions={AVEDEV:{method:"avedev",parameters:[{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1},DEVSQ:{method:"devsq",parameters:[{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1},GEOMEAN:{method:"geomean",parameters:[{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1},HARMEAN:{method:"harmean",parameters:[{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1},CORREL:{method:"correl",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},RSQ:{method:"rsq",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},"COVARIANCE.P":{method:"covariancep",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},"COVARIANCE.S":{method:"covariances",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},"Z.TEST":{method:"ztest",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.NUMBER},{argumentType:ArgumentTypes.NUMBER,optionalArg:!0}]},"F.TEST":{method:"ftest",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},STEYX:{method:"steyx",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},SLOPE:{method:"slope",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},"CHISQ.TEST":{method:"chisqtest",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE}]},"T.TEST":{method:"ttest",parameters:[{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.RANGE},{argumentType:ArgumentTypes.INTEGER,minValue:1,maxValue:2},{argumentType:ArgumentTypes.INTEGER,minValue:1,maxValue:3}]},SKEW:{method:"skew",parameters:[{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1},"SKEW.P":{method:"skewp",parameters:[{argumentType:ArgumentTypes.ANY}],repeatLastArgs:1}},StatisticalAggregationPlugin.aliases={COVAR:"COVARIANCE.P",FTEST:"F.TEST",PEARSON:"CORREL",ZTEST:"Z.TEST",CHITEST:"CHISQ.TEST",TTEST:"T.TEST",COVARIANCEP:"COVARIANCE.P",COVARIANCES:"COVARIANCE.S",SKEWP:"SKEW.P"};var plugins=Object.freeze({__proto__:null,ArrayPlugin:ArrayPlugin,AbsPlugin:AbsPlugin,BitShiftPlugin:BitShiftPlugin,BitwiseLogicOperationsPlugin:BitwiseLogicOperationsPlugin,BooleanPlugin:BooleanPlugin,CharPlugin:CharPlugin,CodePlugin:CodePlugin,CountBlankPlugin:CountBlankPlugin,CountUniquePlugin:CountUniquePlugin,DateTimePlugin:DateTimePlugin,DegreesPlugin:DegreesPlugin,DeltaPlugin:DeltaPlugin,ExpPlugin:ExpPlugin,FinancialPlugin:FinancialPlugin,FormulaTextPlugin:FormulaTextPlugin,InformationPlugin:InformationPlugin,IsEvenPlugin:IsEvenPlugin,IsOddPlugin:IsOddPlugin,LogarithmPlugin:LogarithmPlugin,MathConstantsPlugin:MathConstantsPlugin,MatrixPlugin:MatrixPlugin,MedianPlugin:MedianPlugin,ModuloPlugin:ModuloPlugin,NumericAggregationPlugin:NumericAggregationPlugin,PowerPlugin:PowerPlugin,RadiansPlugin:RadiansPlugin,RadixConversionPlugin:RadixConversionPlugin,RandomPlugin:RandomPlugin,RoundingPlugin:RoundingPlugin,SqrtPlugin:SqrtPlugin,SumifPlugin:SumifPlugin,SumprodPlugin:SumprodPlugin,TextPlugin:TextPlugin,TrigonometryPlugin:TrigonometryPlugin,LookupPlugin:LookupPlugin,RomanPlugin:RomanPlugin,SimpleArithmerticPlugin:SimpleArithmerticPlugin,StatisticalPlugin:StatisticalPlugin,MathPlugin:MathPlugin,ComplexPlugin:ComplexPlugin,StatisticalAggregationPlugin:StatisticalAggregationPlugin});function _typeof(e){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(e)}function _createForOfIteratorHelper(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n({cellRelatedChildren:{dependencyType:"child",childGroups:["cells","rows","columns","cellBlocks"],variableNames:["rowNum","colNum","prescribedCellsWithColNum","prescribedCellsWithRowNum","prescribedCellsRowsColumnsBlocks"],variablesOptional:!0}}),definition({dependencyValues:e,componentInfoObjects:t}){let n=determineCellMapping({cellRelatedChildren:e.cellRelatedChildren,componentInfoObjects:t});return{setValue:{cellNameToRowCol:n.cellNameToRowCol,cellNamesByRowCol:n.cellNamesByRowCol}}}},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({minNumRows:{dependencyType:"stateVariable",variableName:"minNumRows"},cellNamesByRowCol:{dependencyType:"stateVariable",variableName:"cellNamesByRowCol"},dataFrameChild:{dependencyType:"child",childGroups:["dataFrames"],variableNames:["numRows"]}}),definition({dependencyValues:e}){let t=e.minNumRows;return Number.isFinite(t)||(t=4),t=Math.max(t,e.cellNamesByRowCol.length),e.dataFrameChild.length>0&&(t=Math.max(t,e.dataFrameChild[0].stateValues.numRows)),{setValue:{numRows:t}}}},e.numColumns={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({minNumColumns:{dependencyType:"stateVariable",variableName:"minNumColumns"},cellNamesByRowCol:{dependencyType:"stateVariable",variableName:"cellNamesByRowCol"},dataFrameChild:{dependencyType:"child",childGroups:["dataFrames"],variableNames:["numColumns"]}}),definition({dependencyValues:e}){let t=e.minNumColumns;Number.isFinite(t)||(t=4);for(let n of e.cellNamesByRowCol)n&&(t=Math.max(t,n.length));return e.dataFrameChild.length>0&&(t=Math.max(t,e.dataFrameChild[0].stateValues.numColumns)),{setValue:{numColumns:t}}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},forRenderer:!0,returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]},numRows:{dependencyType:"stateVariable",variableName:"numRows"}}),definition({dependencyValues:e}){if(null===e.heightAttr){let t;return t=Number.isFinite(e.numRows)&&e.numRows>=0?40+23*e.numRows:132,{setValue:{height:{size:t,isAbsolute:!0}}}}return{setValue:{height:e.heightAttr.stateValues.componentSize}}}},e.cells={public:!0,shadowingInstructions:{createComponentOfType:"cell",returnWrappingComponents:e=>"cell"===e?[]:"row"===e?[["row"]]:"column"===e?[["column"]]:[["row"],["cellBlock"]]},forRenderer:!0,isArray:!0,entryPrefixes:["cell","row","column","range","rows","columns"],nDimensions:2,defaultValueByArrayKey:()=>"",hasEssential:!0,shadowVariable:!0,stateVariablesDeterminingDependencies:["cellNamesByRowCol"],returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnEntryDimensions:e=>["range","rows","columns"].includes(e)?2:1,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("cell"===e){let e,r,a=/^([a-zA-Z]+)([1-9]\d*)$/,i=t.match(a);if(i)r=i[1],e=i[2];else{let n=/^\(([a-zA-Z]+|\d+),([a-zA-Z]+|\d+)\)$/;if(i=t.match(n),!i)return[];e=i[1],r=i[2]}let o=normalizeIndex(e),s=normalizeIndex(r);return o>=0&&s>=0&&(!n||o=0))return[];if(!n)return[String(e)+",0"];if(!(e=0))return[];if(!n)return["0,"+String(e)];if(!(e=0&&a>=0&&r>=0&&i>=0))return[];if(!n)return[String(e)+","+String(r)];let l=Math.min(Math.min(e,a),n[0]-1),u=Math.min(Math.max(e,a),n[0]-1),c=Math.min(Math.min(r,i),n[1]-1),p=Math.min(Math.max(r,i),n[1]-1),d=[];for(let e=l;e<=u;e++){let t=[],n=String(e)+",";for(let e=c;e<=p;e++)t.push(n+e);d.push(t)}return d}{if(!n)return[String(0)+","+String(0)];let e=[];for(let t=0;t"cell("+e.split(",").map((e=>Number(e)+1)).join(",")+")",arrayVarNameFromPropIndex(e,t){if("cells"===t||"rows"===t)return 1===e.length?"row"+e[0]:`cell(${e[0]},${e[1]})`;if("columns"===t)return 1===e.length?"column"+e[0]:`cell(${e[1]},${e[0]})`;if("row"===t.slice(0,3)){return`cell(${t.slice(3)},${e[0]})`}if("column"===t.slice(0,6)){let n=t.slice(6);return`cell(${e[0]},${n})`}return null},returnArrayDependenciesByKey({stateValues:e,arrayKeys:t}){let n={},r=e.cellNamesByRowCol;for(let e of t){let[t,a]=e.split(",");r[t]&&r[t][a]&&(n[e]={cellText:{dependencyType:"stateVariable",componentName:r[t][a],variableName:"text",variablesOptional:!0}})}return{dependenciesByKey:n,globalDependencies:{dataFrameChild:{dependencyType:"child",childGroups:["dataFrames"],variableNames:["dataFrame","numRows","numColumns"]}}}},arrayDefinitionByKey({dependencyValuesByKey:e,globalDependencyValues:t,arrayKeys:n}){let r,a,i={},o={},s=null;t.dataFrameChild.length>0&&(s=t.dataFrameChild[0],r=s.stateValues.numRows,a=s.stateValues.numColumns);for(let t of n){let[n,l]=t.split(",");void 0!==e[t].cellText?i[t]=e[t].cellText:n0&&(l.setValue={cells:i}),Object.keys(o).length>0&&(l.useEssentialOrDefaultValue={cells:o}),l},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.cells)if(void 0!==t[r].cellText)n.push({setDependency:t[r].cellText,desiredValue:e.cells[r]});else{let t=e.cells[r];n.push({setEssentialValue:"cells",value:{[r]:null===t?"":String(t)}})}return{success:!0,instructions:n}}},e.evaluatedCells={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"cell",returnWrappingComponents:e=>"evaluatedCell"===e?[]:"evaluatedRow"===e?[["row"]]:"evaluatedColumn"===e?[["column"]]:[["row"],["cellBlock"]]},entryPrefixes:["evaluatedCell","evaluatedRow","evaluatedColumn","evaluatedRange","evaluatedRows","evaluatedColumns"],nDimensions:2,stateVariablesDeterminingDependencies:["cellNamesByRowCol"],returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnEntryDimensions:e=>["evaluatedRange","evaluatedRows","evaluatedColumns"].includes(e)?2:1,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("evaluatedCell"===e){let e,r,a=/^([a-zA-Z]+)([1-9]\d*)$/,i=t.match(a);if(i)r=i[1],e=i[2];else{let n=/^\(([a-zA-Z]+|\d+),([a-zA-Z]+|\d+)\)$/;if(i=t.match(n),!i)return[];e=i[1],r=i[2]}let o=normalizeIndex(e),s=normalizeIndex(r);return o>=0&&s>=0&&(!n||o=0))return[];if(!n)return[String(e)+",0"];if(!(e=0))return[];if(!n)return["0,"+String(e)];if(!(e=0&&a>=0&&r>=0&&i>=0))return[];if(!n)return[String(e)+","+String(r)];let l=Math.min(Math.min(e,a),n[0]-1),u=Math.min(Math.max(e,a),n[0]-1),c=Math.min(Math.min(r,i),n[1]-1),p=Math.min(Math.max(r,i),n[1]-1),d=[];for(let e=l;e<=u;e++){let t=[],n=String(e)+",";for(let e=c;e<=p;e++)t.push(n+e);d.push(t)}return d}{if(!n)return[String(0)+","+String(0)];let e=[];for(let t=0;t"evaluatedCell("+e.split(",").map((e=>Number(e)+1)).join(",")+")",arrayVarNameFromPropIndex(e,t){if("evaluatedCells"===t||"evaluatedRows"===t)return 1===e.length?"evaluatedRow"+e[0]:`evaluatedCell(${e[0]},${e[1]})`;if("evaluatedColumns"===t)return 1===e.length?"evaluatedColumn"+e[0]:`evaluatedCell(${e[1]},${e[0]})`;if("evaluatedRow"===t.slice(0,12)){return`evaluatedCell(${t.slice(12)},${e[0]})`}if("evaluatedColumn"===t.slice(0,15)){let n=t.slice(15);return`evaluatedCell(${e[0]},${n})`}return null},returnArrayDependenciesByKey:()=>({globalDependencies:{cells:{dependencyType:"stateVariable",variableName:"cells"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=HyperFormula.buildFromArray(e.cells,{licenseKey:"gpl-v3"}).getSheetValues(0),n={};for(let e in t){let r=t[e];for(let t in r)n[[e,t]]=r[t]}return{setValue:{evaluatedCells:n}}}},e.pointsInCells={isArray:!0,nDimensions:2,public:!0,shadowingInstructions:{createComponentOfType:"point"},entryPrefixes:["pointsInCell","pointsInRow","pointsInColumn","pointsInRange","pointsInRows","pointsInColumns"],returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnEntryDimensions:e=>["pointsInRange","pointsInRows","pointsInColumns"].includes(e)?2:1,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointsInCell"===e){let e,r,a=/^([a-zA-Z]+)([1-9]\d*)$/,i=t.match(a);if(i)r=i[1],e=i[2];else{let n=/^\(([a-zA-Z]+|\d+),([a-zA-Z]+|\d+)\)$/;if(i=t.match(n),!i)return[];e=i[1],r=i[2]}let o=normalizeIndex(e),s=normalizeIndex(r);return o>=0&&s>=0&&(!n||o=0))return[];if(!n)return[String(e),",0"];if(!(e>=0&&e=0))return[];if(!n)return["0,"+String(e)];if(!(e=0&&a>=0&&r>=0&&i>=0))return[];if(!n)return[String(e)+","+String(r)];let l=Math.min(Math.min(e,a),n[0]-1),u=Math.min(Math.max(e,a),n[0]-1),c=Math.min(Math.min(r,i),n[1]-1),p=Math.min(Math.max(r,i),n[1]-1),d=[];for(let e=l;e<=u;e++){let t=[],n=String(e)+",";for(let e=c;e<=p;e++)t.push(n+e);d.push(t)}return d}{if(!n)return[String(0)+","+String(0)];let e=[];for(let t=0;t"pointsInCell("+e.split(",").map((e=>Number(e)+1)).join(",")+")",arrayVarNameFromPropIndex(e,t){if("pointsInCells"===t||"pointsInRows"===t)return 1===e.length?"pointsInRow"+e[0]:`pointsInCell(${e[0]},${e[1]})`;if("pointsInColumns"===t)return 1===e.length?"pointsInColumn"+e[0]:`pointsInCell(${e[1]},${e[0]})`;if("pointsInRow"===t.slice(0,11)){return`pointsInCell(${t.slice(11)},${e[0]})`}if("pointsInColumn"===t.slice(0,14)){let n=t.slice(14);return`pointsInCell(${e[0]},${n})`}return null},returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e)+1)).join(",");t[n]={cellText:{dependencyType:"stateVariable",variableName:`evaluatedCell(${e})`,variablesOptional:!0}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t,a=e[r].cellText;if(a){try{t=me$3.fromAst(textToAst$1.convert(a))}catch(e){n[r]=null;continue}!Array.isArray(t.tree)||"tuple"!==t.tree[0]&&"vector"!==t.tree[0]?n[r]=null:n[r]=t}else n[r]=null}return{setValue:{pointsInCells:n}}}},e}async onChange({changes:e,source:t,actionId:n}){if(e){let t={};for(let n of e){let[e,r,a,i]=n;t[[e,r]]=null===i?"":i}return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"cells",value:t}],actionId:n,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:t}})}this.coreFunctions.resolveAction({actionId:n})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={onChange:this.onChange.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)}}function determineCellMapping({cellRelatedChildren:e,rowOffset:t=0,colOffset:n=0,cellNameToRowCol:r={},cellNamesByRowCol:a=[],componentInfoObjects:i}){var o=t,s=n,l=n,u=t,c=n,p=t,d=n;for(let m of e)if(i.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"cell"})){let e=m,i=normalizeIndex(e.stateValues.rowNum),u=normalizeIndex(e.stateValues.colNum);void 0===i?(i=o,void 0===u?u=l:u+=n):(i+=t,void 0===u?u=s:u+=n),addCellToMapping({cell:e,rowIndex:i,colIndex:u,cellNameToRowCol:r,cellNamesByRowCol:a}),p=Math.max(i,p),d=Math.max(u,d),o=i,s=u,l=u+1}else if(i.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"row"})){let e=m,i=normalizeIndex(e.stateValues.rowNum);void 0===i?i=u:i+=t;let c=e.stateValues.prescribedCellsWithColNum,f=n;for(let e of c){let t=normalizeIndex(e.stateValues.colNum);void 0===t?t=f:t+=n,addCellToMapping({cell:e,rowIndex:i,colIndex:t,cellNameToRowCol:r,cellNamesByRowCol:a}),f=t+1,p=Math.max(i,p),d=Math.max(t,d)}u=i+1,o=i+1,l=s=n}else if(i.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"column"})){let e=m,i=normalizeIndex(e.stateValues.colNum);void 0===i?i=c:i+=n;let u=e.stateValues.prescribedCellsWithRowNum,f=t;for(let e of u){let n=normalizeIndex(e.stateValues.rowNum);void 0===n?n=f:n+=t,addCellToMapping({cell:e,rowIndex:n,colIndex:i,cellNameToRowCol:r,cellNamesByRowCol:a}),f=n+1,p=Math.max(n,p),d=Math.max(i,d)}c=i+1,o=t,l=s=i+1}else if(i.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"cellBlock"})){let e=m,u=normalizeIndex(e.stateValues.rowNum),c=normalizeIndex(e.stateValues.colNum);void 0===u?(u=o,void 0===c?c=l:c+=n):(u+=t,void 0===c?c=s:c+=n);let f=determineCellMapping({cellRelatedChildren:e.stateValues.prescribedCellsRowsColumnsBlocks,rowOffset:u,colOffset:c,cellNameToRowCol:r,cellNamesByRowCol:a,componentInfoObjects:i});p=Math.max(f.maxRowIndex,p),d=Math.max(f.maxColIndex,d),o=u,s=c,l=f.maxColIndex+1}return{maxRowIndex:p,maxColIndex:d,cellNameToRowCol:r,cellNamesByRowCol:a}}function addCellToMapping({cell:e,rowIndex:t,colIndex:n,cellNameToRowCol:r,cellNamesByRowCol:a}){if(r[e.componentName]=[t,n],void 0===a[t]&&(a[t]=[]),void 0!==a[t][n]){console.warn(`Cell is overwriting previous cell at rowNum=${t+1}, colNum=${n+1}`),r[a[t][n]]=null}a[t][n]=e.componentName}class DiscreteSimulationResultList extends BlockComponent{static componentType="DiscreteSimulationResultList";static rendererType="spreadsheet";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:100,isAbsolute:!1},public:!0,forRenderer:!0},e.minNumRows={createComponentOfType:"number",createStateVariable:"minNumRows",defaultValue:1,public:!0,forRenderer:!0},e.minNumColumns={createComponentOfType:"number",createStateVariable:"minNumColumns",defaultValue:1,public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize"},e.columnHeaders={createComponentOfType:"boolean",createStateVariable:"columnHeaders",defaultValue:!0,public:!0,forRenderer:!0},e.rowHeaders={createComponentOfType:"boolean",createStateVariable:"rowHeaders",defaultValue:!0,public:!0,forRenderer:!0},e.fixedRowsTop={createComponentOfType:"integer",createStateVariable:"fixedRowsTop",defaultValue:0,clamp:[0,1/0],public:!0,forRenderer:!0},e.fixedColumnsLeft={createComponentOfType:"integer",createStateVariable:"fixedColumnsLeft",defaultValue:0,clamp:[0,1/0],public:!0,forRenderer:!0},e.hiddenColumns={createComponentOfType:"numberList",createStateVariable:"hiddenColumns",defaultValue:[],public:!0,forRenderer:!0},e.hiddenRows={createComponentOfType:"numberList",createStateVariable:"hiddenRows",defaultValue:[],public:!0,forRenderer:!0},e.allIterates={createComponentOfType:"mathList",createStateVariable:"allIterates",defaultValue:[]},e.headerRow={createComponentOfType:"textList",createStateVariable:"headerRow",defaultValue:null},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({allIterates:{dependencyType:"stateVariable",variableName:"allIterates"},headerRow:{dependencyType:"stateVariable",variableName:"headerRow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition({dependencyValues:e,usedDefault:t}){let n=[],r=1,a=!1;if(e.allIterates.length>0&&Array.isArray(e.allIterates[0].tree)&&["vector","tuple"].includes(e.allIterates[0].tree[0])&&(r=e.allIterates[0].tree.length-1,a=!0),e.headerRow){let t=[],a=Math.min(e.headerRow.length,r+1);for(let n=0;n({minNumRows:{dependencyType:"stateVariable",variableName:"minNumRows"},cells:{dependencyType:"stateVariable",variableName:"cells"}}),definition({dependencyValues:e}){let t=e.minNumRows;return Number.isFinite(t)||(t=4),t=Math.max(t,e.cells.length),{setValue:{numRows:t}}}},e.numColumns={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({minNumColumns:{dependencyType:"stateVariable",variableName:"minNumColumns"},cells:{dependencyType:"stateVariable",variableName:"cells"}}),definition({dependencyValues:e}){let t=e.minNumColumns;Number.isFinite(t)||(t=4);for(let n of e.cells)n&&(t=Math.max(t,n.length));return{setValue:{numColumns:t}}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},forRenderer:!0,returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]},numRows:{dependencyType:"stateVariable",variableName:"numRows"}}),definition({dependencyValues:e}){if(null===e.heightAttr){let t;return t=Number.isFinite(e.numRows)&&e.numRows>=0?50+20*e.numRows:130,{setValue:{height:{size:t,isAbsolute:!0}}}}return{setValue:{height:e.heightAttr.stateValues.componentSize}}}},e}async onChange({changes:e,source:t,actionId:n}){if(e){let t={};for(let n of e){let[e,r,a,i]=n;t[[e,r]]=null===i?"":i}return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"cells",value:t}],actionId:n,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:t}})}this.coreFunctions.resolveAction({actionId:n})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={onChange:this.onChange.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class DiscreteSimulationResultPolyline extends GraphicalComponent{static componentType="discreteSimulationResultPolyline";static rendererType="polyline";actions={movePolyline:this.movePolyline.bind(this),finalizePolylinePosition:this.finalizePolylinePosition.bind(this)};static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.allIterates={createComponentOfType:"mathList",createStateVariable:"allIteratesSub",defaultValue:[]},e.seriesNumber={createComponentOfType:"number",createStateVariable:"seriesNumber",defaultValue:null},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" polyline"}}}},e.allIterates={returnDependencies:()=>({allIteratesSub:{dependencyType:"stateVariable",variableName:"allIteratesSub"}}),definition:function({dependencyValues:e}){return{setValue:{allIterates:e.allIteratesSub.filter((e=>Number.isFinite(e.tree)||Array.isArray(e.tree)&&["tuple","vector"].includes(e.tree[0])&&e.tree.slice(1).every(Number.isFinite)))}}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({allIterates:{dependencyType:"stateVariable",variableName:"allIterates"}}),definition:function({dependencyValues:e}){return{setValue:{nVertices:e.allIterates.length}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:function({dependencyValues:e}){return{setValue:{nDimensions:2}}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},getAllArrayKeys(e,t=!0,n){function r(e){if(1===e.length)return Array.from(Array(e[0]),((e,t)=>String(t)));{let n=e[0],a=r(e.slice(1)),i=[];for(let e=0;ee+","+t))):i.push(a.map((t=>e+","+t)));return i}}if(n){if(0!==n.length&&e){let t=[...e];return t[0]=n[0],r(t)}return[]}return e&&0!==e.length?r(e):[]},returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices,2],returnArrayDependenciesByKey:()=>({globalDependencies:{seriesNumber:{dependencyType:"stateVariable",variableName:"seriesNumber"},allIterates:{dependencyType:"stateVariable",variableName:"allIterates"}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n={};for(let r=0;r({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={vertex:{dependencyType:"stateVariable",variableName:"vertex"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalVertices:n}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,o=[],s=i[0]?.[0],l=i[0]?.[1];for(let e=1;e=1?{x1:f,x2:h}:{x1:l+b*a*n,x2:u+b*y*s};let g=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/s,2);g0&&(p.x3=0),p}}}}},e}async movePolyline({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){let a={};for(let t in e)a[t+",0"]=me$3.fromAst(e[t][0]),a[t+",1"]=me$3.fromAst(e[t][1]);return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}async finalizePolylinePosition(){return await this.actions.movePolyline({pointCoords:await this.stateValues.numericalVertices,transient:!1})}}class Cell extends BaseComponent{static componentType="cell";static rendererType="cell";static renderChildren=!0;static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="text";static createAttributesObject(){let e=super.createAttributesObject();return e.rowNum={createComponentOfType:"text",createStateVariable:"rowNum",defaultValue:null,public:!0},e.colNum={createComponentOfType:"text",createStateVariable:"colNum",defaultValue:null,public:!0},e.colSpan={createComponentOfType:"integer",createStateVariable:"colSpan",defaultValue:1,public:!0,forRenderer:!0},e.halign={createComponentOfType:"text"},e.bottom={createComponentOfType:"text"},e.right={createComponentOfType:"text"},e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.halign={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,defaultValue:"left",returnDependencies:()=>({halignAttr:{dependencyType:"attributeComponent",attributeName:"halign",variableNames:["value"]},parentHalign:{dependencyType:"parentStateVariable",variableName:"halign"},tabularHalign:{dependencyType:"ancestor",componentType:"tabular",variableNames:["halign"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.halignAttr){let t=e.halignAttr.stateValues.value;return["left","center","right","justify"].includes(t)||(t="left"),{setValue:{halign:t}}}return!t.parentHalign&&e.parentHalign?{setValue:{halign:e.parentHalign}}:!t.tabularHalign&&e.tabularHalign?{setValue:{halign:e.tabularHalign.stateValues.halign}}:{useEssentialOrDefaultValue:{halign:!0}}}},e.bottom={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,defaultValue:"none",returnDependencies:()=>({bottomAttr:{dependencyType:"attributeComponent",attributeName:"bottom",variableNames:["value"]},parentBottom:{dependencyType:"parentStateVariable",variableName:"bottom"},tabularBottom:{dependencyType:"ancestor",componentType:"tabular",variableNames:["bottom"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.bottomAttr){let t=e.bottomAttr.stateValues.value;return["none","minor","medium","major"].includes(t)||(t="none"),{setValue:{bottom:t}}}return!t.parentBottom&&e.parentBottom?{setValue:{bottom:e.parentBottom}}:!t.tabularBottom&&e.tabularBottom?{setValue:{bottom:e.tabularBottom.stateValues.bottom}}:{useEssentialOrDefaultValue:{bottom:!0}}}},e.right={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,defaultValue:"none",returnDependencies:()=>({rightAttr:{dependencyType:"attributeComponent",attributeName:"right",variableNames:["value"]},tabularRight:{dependencyType:"ancestor",componentType:"tabular",variableNames:["right"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.rightAttr){let t=e.rightAttr.stateValues.value;return["none","minor","medium","major"].includes(t)||(t="none"),{setValue:{right:t}}}return!t.tabularRight&&e.tabularRight?{setValue:{right:e.tabularRight.stateValues.right}}:{useEssentialOrDefaultValue:{right:!0}}}},e.inHeader={public:!0,shadowingInstructions:{createComponentOfType:"booloean"},forRenderer:!0,defaultValue:!1,returnDependencies:()=>({parentHeader:{dependencyType:"parentStateVariable",variableName:"header"}}),definition:({dependencyValues:e})=>({setValue:{inHeader:!0===e.parentHeader}})},e.onlyMathChild={returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"]},otherChildren:{dependencyType:"child",childGroups:["anything"]}}),definition:({dependencyValues:e})=>({setValue:{onlyMathChild:1===e.mathChild.length&&0===e.otherChildren.length}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({children:{dependencyType:"child",childGroups:["maths","anything"],variableNames:["text"],variablesOptional:!0},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition({dependencyValues:e}){if(0===e.children.length)return{useEssentialOrDefaultValue:{text:{defaultValue:e.prefill}}};let t="";for(let n of e.children)"object"==typeof n?n.stateValues.text&&(t+=n.stateValues.text):t+=n.toString();return{setValue:{text:t}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>0===t.children.length?{success:!0,instructions:[{setEssentialValue:"text",value:null===e.text?"":String(e.text)}]}:1===t.children.length?"object"==typeof t.children[0]&&void 0===t.children[0].stateValues.text?{success:!1}:{success:!0,instructions:[{setDependency:"children",desiredValue:e.text,childIndex:0,variableIndex:0}]}:{success:!1}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},stateVariablesDeterminingDependencies:["onlyMathChild"],returnDependencies:({stateValues:e})=>e.onlyMathChild?{mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}:{text:{dependencyType:"stateVariable",variableName:"text"}},definition({dependencyValues:e}){if(e.mathChild)return{setValue:{math:e.mathChild[0].stateValues.value}};{let t;try{t=me$3.fromAst(textToAst$1.convert(e.text))}catch(e){t=me$3.fromAst("_")}return{setValue:{math:t}}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r}){if(t.mathChild)return{success:!0,instructions:[{setDependency:"mathChild",desiredValue:e.math,childIndex:0,variableIndex:0}]};return{success:!0,instructions:[{setDependency:"text",desiredValue:(await preprocessMathInverseDefinition({desiredValue:e.math,stateValues:n,variableName:"math",workspace:r})).desiredValue.toString()}]}}},e.number={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({math:{dependencyType:"stateVariable",variableName:"math"}}),definition({dependencyValues:e}){let t=e.math.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),{setValue:{number:t}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"math",desiredValue:me$3.fromAst(e.number)}]})},e}static adapters=["text","math","number"]}class Row extends BaseComponent{static componentType="row";static rendererType="row";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.rowNum={createComponentOfType:"text",createStateVariable:"rowNum",defaultValue:null,public:!0},e.header={createComponentOfType:"boolean",createStateVariable:"header",defaultValue:!1,public:!0,forRenderer:!0},e.halign={createComponentOfType:"text"},e.valign={createComponentOfType:"text"},e.left={createComponentOfType:"text"},e.bottom={createComponentOfType:"text"},e}static returnChildGroups(){return[{group:"cells",componentTypes:["cell"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.halign={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"left",hasEssential:!0,returnDependencies:()=>({halignAttr:{dependencyType:"attributeComponent",attributeName:"halign",variableNames:["value"]},parentHalign:{dependencyType:"parentStateVariable",variableName:"halign"}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.halignAttr){let t=e.halignAttr.stateValues.value;return["left","center","right","justify"].includes(t)||(t="left"),{setValue:{halign:t}}}return null===e.parentHalign||t.parentHalign?{useEssentialOrDefaultValue:{halign:!0}}:{setValue:{halign:e.parentHalign}}}},e.valign={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,defaultValue:"middle",hasEssential:!0,returnDependencies:()=>({valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},parentValign:{dependencyType:"parentStateVariable",variableName:"valign"}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.valignAttr){let t=e.valignAttr.stateValues.value;return["top","middle","bottom"].includes(t)||(t="middle"),{setValue:{valign:t}}}return null===e.parentValign||t.parentValign?{useEssentialOrDefaultValue:{valign:!0}}:{setValue:{valign:e.parentValign}}}},e.left={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,defaultValue:"none",hasEssential:!0,returnDependencies:()=>({leftAttr:{dependencyType:"attributeComponent",attributeName:"left",variableNames:["value"]},parentLeft:{dependencyType:"parentStateVariable",variableName:"left"}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.leftAttr){let t=e.leftAttr.stateValues.value;return["none","minor","medium","major"].includes(t)||(t="none"),{setValue:{left:t}}}return null===e.parentLeft||t.parentLeft?{useEssentialOrDefaultValue:{left:!0}}:{setValue:{left:e.parentLeft}}}},e.bottom={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"none",hasEssential:!0,returnDependencies:()=>({bottomAttr:{dependencyType:"attributeComponent",attributeName:"bottom",variableNames:["value"]},parentBottom:{dependencyType:"parentStateVariable",variableName:"bottom"}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.bottomAttr){let t=e.bottomAttr.stateValues.value;return["none","minor","medium","major"].includes(t)||(t="none"),{setValue:{bottom:t}}}return null===e.parentBottom||t.parentBottom?{useEssentialOrDefaultValue:{bottom:!0}}:{setValue:{bottom:e.parentBottom}}}},e.prescribedCellsWithColNum={returnDependencies:()=>({cellChildren:{dependencyType:"child",childGroups:["cells"],variableNames:["colNum"]}}),definition:({dependencyValues:e})=>({setValue:{prescribedCellsWithColNum:e.cellChildren}})},e}}class Column extends BaseComponent{static componentType="column";static rendererType="containerBlock";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.colNum={createComponentOfType:"text",createStateVariable:"colNum",defaultValue:null,public:!0},e}static returnChildGroups(){return[{group:"cells",componentTypes:["cell"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.prescribedCellsWithRowNum={returnDependencies:()=>({cellChildren:{dependencyType:"child",childGroups:["cells"],variableNames:["rowNum"]}}),definition:({dependencyValues:e})=>({setValue:{prescribedCellsWithRowNum:e.cellChildren}})},e}}class CellBlock extends BaseComponent{static componentType="cellBlock";static rendererType="containerBlock";static createAttributesObject(){let e=super.createAttributesObject();return e.rowNum={createComponentOfType:"text",createStateVariable:"rowNum",defaultValue:null,public:!0},e.colNum={createComponentOfType:"text",createStateVariable:"colNum",defaultValue:null,public:!0},e}static returnChildGroups(){return[{group:"children",componentTypes:["cell","row","column","cellblock"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.prescribedCellsRowsColumnsBlocks={returnDependencies:()=>({cellRelatedChildren:{dependencyType:"child",childGroups:["children"],variableNames:["rowNum","colNum","prescribedCellsWithColNum","prescribedCellsWithRowNum","prescribedCellsRowsColumnsBlocks"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{prescribedCellsRowsColumnsBlocks:e.cellRelatedChildren}})},e}}class Tabular extends BlockComponent{static componentType="tabular";static rendererType="tabular";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:100,isAbsolute:!1},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:null,public:!0,forRenderer:!0},e.halign={createComponentOfType:"text",createStateVariable:"halign",defaultValue:"left",public:!0,validValues:["left","center","right","justify"]},e.valign={createComponentOfType:"text",createStateVariable:"valign",defaultValue:"middle",public:!0,validValues:["top","middle","bottom"]},e.top={createComponentOfType:"text",createStateVariable:"top",defaultValue:"none",public:!0,validValues:["none","minor","medium","major"],forRenderer:!0},e.left={createComponentOfType:"text",createStateVariable:"left",defaultValue:"none",public:!0,validValues:["none","minor","medium","major"]},e.bottom={createComponentOfType:"text",createStateVariable:"bottom",defaultValue:"none",public:!0,validValues:["none","minor","medium","major"]},e.right={createComponentOfType:"text",createStateVariable:"right",defaultValue:"none",public:!0,validValues:["none","minor","medium","major"]},e}static returnChildGroups(){return[{group:"rows",componentTypes:["row"]}]}static returnStateVariableDefinitions(){return super.returnStateVariableDefinitions()}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class Table extends BlockComponent{static componentType="table";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.suppressTableNameInTitle={createComponentOfType:"boolean",createStateVariable:"suppressTableNameInTitle",defaultValue:!1,forRenderer:!0},e.number={createComponentOfType:"boolean",createStateVariable:"number",defaultValue:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"titles",componentTypes:["title"]},{group:"inlinesBlocks",componentTypes:["_inline","_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.tableEnumeration={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["number"],additionalStateVariablesDefined:[{variableName:"tableName",public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0}],returnDependencies({stateValues:e}){let t={};return e.number&&(t.tableCounter={dependencyType:"counter",counterName:"table"}),t},definition({dependencyValues:e}){if(void 0===e.tableCounter)return{setValue:{tableEnumeration:null,tableName:"Table"}};let t=String(e.tableCounter);return{setValue:{tableEnumeration:t,tableName:"Table "+t}}}},e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[0].componentName),{setValue:{titleChildName:t}}}},e.title={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"],variableNames:["text"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[0].stateValues.text),{setValue:{title:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class Figure extends BlockComponent{static componentType="figure";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.suppressFigureNameInCaption={createComponentOfType:"boolean",createStateVariable:"suppressFigureNameInCaption",defaultValue:!1,forRenderer:!0},e.number={createComponentOfType:"boolean",createStateVariable:"number",defaultValue:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"captions",componentTypes:["caption"]},{group:"inlinesBlocks",componentTypes:["_inline","_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.figureEnumeration={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["number"],additionalStateVariablesDefined:[{variableName:"figureName",public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0}],returnDependencies({stateValues:e}){let t={};return e.number&&(t.figureCounter={dependencyType:"counter",counterName:"figure"}),t},definition({dependencyValues:e}){if(void 0===e.figureCounter)return{setValue:{figureEnumeration:null,figureName:"Figure"}};let t=String(e.figureCounter);return{setValue:{figureEnumeration:t,figureName:"Figure "+t}}}},e.captionChildName={forRenderer:!0,returnDependencies:()=>({captionChild:{dependencyType:"child",childGroups:["captions"]}}),definition({dependencyValues:e}){let t=null;return e.captionChild.length>0&&(t=e.captionChild[0].componentName),{setValue:{captionChildName:t}}}},e.caption={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({captionChild:{dependencyType:"child",childGroups:["captions"],variableNames:["text"]}}),definition({dependencyValues:e}){let t=null;return e.captionChild.length>0&&(t=e.captionChild[0].stateValues.text),{setValue:{caption:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class TextListFromString extends InlineComponent{static componentType="textListFromString";static rendererType="asList";static renderChildren=!0;static stateVariableForAttributeValue="texts";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.stringChildren.length}}}},e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={stringChild:{dependencyType:"child",childGroups:["strings"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)1===e[r].stringChild.length&&(n[r]=e[r].stringChild[0]);return{setValue:{texts:n}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"texts"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e}}class VariantControl extends BaseComponent{static componentType="variantControl";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.nVariants={createPrimitiveOfType:"integer"},e.uniqueVariants={createPrimitiveOfType:"boolean"},e.variantsToInclude={createComponentOfType:"textListFromString"},e.variantsToExclude={createComponentOfType:"textListFromString"},e.variantNames={createComponentOfType:"textListFromString"},e.seeds={createComponentOfType:"textListFromString"},e}}class SelectFromSequence extends Sequence{static componentType="selectFromSequence";static assignNamesToReplacements=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.numberToSelect={createComponentOfType:"integer",createStateVariable:"numberToSelect",defaultValue:1,public:!0},e.withReplacement={createComponentOfType:"boolean",createStateVariable:"withReplacement",defaultValue:!1,public:!0},e.sortResults={createComponentOfType:"boolean",createStateVariable:"sortResults",defaultValue:!1,public:!0},e.excludeCombinations={createComponentOfType:"_componentListOfListsWithSelectableType"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();e.excludedCombinations={returnDependencies:()=>({excludeCombinations:{dependencyType:"attributeComponent",attributeName:"excludeCombinations",variableNames:["lists"]},type:{dependencyType:"stateVariable",variableName:"type"},numberToSelect:{dependencyType:"stateVariable",variableName:"numberToSelect"}}),definition:function({dependencyValues:e}){if(null!==e.excludeCombinations){let t=e.excludeCombinations.stateValues.lists.map((t=>t.slice(0,e.numberToSelect))).filter((t=>t.length===e.numberToSelect));if("number"===e.type)for(;;){let e=mergeContainingCombinations(t);if(!e.merged)break;t=e.combinations}return{setValue:{excludedCombinations:t}}}return{setValue:{excludedCombinations:[]}}}},e.variants={returnDependencies:()=>({variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){return{setValue:{variants:e.variants}}}},e.selectedValues={immutable:!0,hasEssential:!0,shadowVariable:!0,additionalStateVariablesDefined:[{variableName:"selectedIndices",hasEssential:!0,shadowVariable:!0,immutable:!0}],returnDependencies:({sharedParameters:e})=>({numberToSelect:{dependencyType:"stateVariable",variableName:"numberToSelect"},withReplacement:{dependencyType:"stateVariable",variableName:"withReplacement"},length:{dependencyType:"stateVariable",variableName:"length"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"},exclude:{dependencyType:"stateVariable",variableName:"exclude"},excludedCombinations:{dependencyType:"stateVariable",variableName:"excludedCombinations"},type:{dependencyType:"stateVariable",variableName:"type"},lowercase:{dependencyType:"stateVariable",variableName:"lowercase"},sortResults:{dependencyType:"stateVariable",variableName:"sortResults"},variants:{dependencyType:"stateVariable",variableName:"variants"},variantRng:{dependencyType:"value",value:e.variantRng,doNotProxy:!0}}),definition:makeSelection},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:()=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{generatedVariantInfo:{indices:e.selectedIndices,meta:{createdBy:t}}}})};let t=e.readyToExpandWhenResolved.returnDependencies;return e.readyToExpandWhenResolved.returnDependencies=function(){let e=t();return e.selectedValues={dependencyType:"stateVariable",variableName:"selectedValues"},e},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n}){let r=await e.stateValues.type;"letters"===r&&(r="text");let a=e.attributes.newNamespace?.primitive,i={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(i[t]=e.attributes[t]);let o={};Object.keys(i).length>0&&(o=convertAttributesForComponentType({attributes:i,componentType:r,componentInfoObjects:t,compositeCreatesNewNamespace:a,flags:n}));let s=[];for(let t of await e.stateValues.selectedValues)s.push({componentType:r,attributes:o,state:{value:t,fixed:!0}});return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:t}).serializedComponents}}static calculateReplacementChanges(){return[]}static determineNumberOfUniqueVariants({serializedComponent:e}){let t=1,n=!1,r=e.attributes.type.primitive,a=e.attributes.numberToSelect?.component;if(a){if("integer"!==a.componentType||1!==a.children?.length||"string"!=typeof a.children[0])return console.log("cannot determine unique variants of selectFromSequence as numberToSelect isn't constant number."),{success:!1};if(t=Number(a.children[0]),!(Number.isInteger(t)&&t>=0))return console.log("cannot determine unique variants of selectFromSequence as numberToSelect isn't a non-negative integer."),{success:!1}}let i=e.attributes.withReplacement?.component;if(i){if("boolean"!==i.componentType)return console.log("cannot determine unique variants of selectFromSequence as withReplacement isn't constant boolean."),{success:!1};if(1===i.children?.length&&"string"==typeof i.children[0])n="true"===i.children[0].toLowerCase();else{if(void 0!==i.children&&0!==i.children.length||"boolean"!=typeof i.state?.value)return console.log("cannot determine unique variants of selectFromSequence as withReplacement isn't constant boolean."),{success:!1};n=i.state.value}}let o={from:null,to:null,step:null,length:null},s=e.attributes.from?.component;if(s){let e=s.children[0];if(1!==e.children?.length||"string"!=typeof e.children[0])return console.log("cannot determine unique variants of selectFromSequence as from isn't a constant."),{success:!1};{let t;if("number"===r){if(t=Number(e.children[0]),!Number.isFinite(t))return console.log("cannot determine unique variants of selectFromSequence of number type as from isn't a number."),{success:!1}}else if("letters"===r){if(t=lettersToNumber$1(e.children[0]),!Number.isFinite(t))return console.log("cannot determine unique variants of selectFromSequence of letters type as from isn't a combination of letters."),{success:!1}}else{let n=getFromText({functionSymbols:["f","g"]});try{t=n(e.children[0])}catch(e){return console.log("cannot determine unique variants of selectFromSequence of math type as from isn't a valid math expression."),{success:!1}}}o.from=t}}let l=e.attributes.to?.component;if(l){let e=l.children[0];if(1!==e.children?.length||"string"!=typeof e.children[0])return console.log("cannot determine unique variants of selectFromSequence as to isn't a constant."),{success:!1};{let t;if("number"===r){if(t=Number(e.children[0]),!Number.isFinite(t))return console.log("cannot determine unique variants of selectFromSequence of number type as to isn't a number."),{success:!1}}else if("letters"===r){if(t=lettersToNumber$1(e.children[0]),!Number.isFinite(t))return console.log("cannot determine unique variants of selectFromSequence of letters type as to isn't a combination of letters."),{success:!1}}else{let n=getFromText({functionSymbols:["f","g"]});try{t=n(e.children[0])}catch(e){return console.log("cannot determine unique variants of selectFromSequence of math type as to isn't a valid math expression."),{success:!1}}}o.to=t}}let u=e.attributes.step?.component;if(u){if(1!==u.children?.length||"string"!=typeof u.children[0])return console.log("cannot determine unique variants of selectFromSequence as step isn't a constant."),{success:!1};{let e;if("number"===r){if(e=Number(u.children[0]),!Number.isFinite(e))return console.log("cannot determine unique variants of selectFromSequence of number type as step isn't a number."),{success:!1}}else if("letters"===r){if(e=Number(u.children[0]),!Number.isInteger(e))return console.log("cannot determine unique variants of selectFromSequence of letters type as step isn't an integer."),{success:!1}}else{let t=getFromText({functionSymbols:["f","g"]});try{e=t(u.children[0])}catch(e){return console.log("cannot determine unique variants of selectFromSequence of math type as step isn't a valid math expression."),{success:!1}}}o.step=e}}let c=e.attributes.length?.component;if(c){if(1!==c.children?.length||"string"!=typeof c.children[0])return console.log("cannot determine unique variants of selectFromSequence as length isn't a constant."),{success:!1};{let e=Number(c.children[0]);if(!Number.isInteger(e))return console.log("cannot determine unique variants of selectFromSequence as length isn't an integer."),{success:!1};o.length=e}}if(e.attributes.excludeCombinations)return console.log("have not implemented unique variants of a selectFromSequence with excludeCombinations"),{success:!1};let p=[],d=e.attributes.exclude?.component;if(d){if("math"===r)return console.log("have not implemented unique variants of a selectFromSequence of type math with exclude"),{success:!1};if(!d.children.every((e=>1===e.children?.length&&"string"==typeof e.children[0])))return console.log("have not implemented unique variants of a selectFromSequence with non-constant exclude"),{success:!1};if(p="letters"===r?d.children.map((e=>lettersToNumber$1(e.children[0]))):d.children.map((e=>Number(e.children[0]))),!p.every(Number.isFinite))return console.log("have not implemented unique variants of a selectFromSequence with non-constant exclude"),{success:!1}}o=calculateSequenceParameters(o);let m=o.length,f=[];if(p.length>0&&"math"!==r){p.sort(((e,t)=>e-t)),p=p.filter(((e,t,n)=>e!=n[t-1]));for(let e of p){if(eo.length-1+1e-10)break;Math.abs(t-Math.round(t))<1e-10&&(m--,f.push(t))}}if(m<=0)return{success:!1};let h,y={excludeIndices:f,nOptions:m,numberToSelect:t,withReplacement:n};if(e.variants.uniqueVariantData=y,n||1===t)h=Math.pow(m,t);else{h=m;for(let e=m-1;e>m-t;e--)h*=e}return e.variants.numberOfVariants=h,{success:!0,numberOfVariants:h}}static getUniqueVariant({serializedComponent:e,variantIndex:t}){let n=e.variants?.numberOfVariants;if(void 0===n)return{success:!1};if(!Number.isInteger(t)||t<1||t>n)return{success:!1};let r=e.variants.uniqueVariantData,a=r.excludeIndices,i=r.nOptions,o=r.numberToSelect,s=r.withReplacement,l=function(e){let t=e;for(let e of a)t>=e&&t++;return t};if(1===o)return{success:!0,desiredVariant:{indices:[l(t-1)+1]}};let u=enumerateSelectionCombinations({numberOfIndices:o,numberOfOptions:i,maxNumber:t,withReplacement:s})[t-1].map(l).map((e=>e+1));return{success:!0,desiredVariant:{indices:u}}}}function makeSelection({dependencyValues:e}){if(e.numberToSelect<1)return{setEssentialValue:{selectedValues:[],selectedIndices:[]},setValue:{selectedValues:[],selectedIndices:[]}};let t=1;if(e.withReplacement||(t=e.numberToSelect),t>e.length)throw Error("Cannot select "+t+" values from a sequence of length "+e.length);if(e.variants&&void 0!==e.variants.desiredVariant){let t=e.variants.desiredVariant.indices;if(void 0!==t){if(t.length!==e.numberToSelect)throw Error("Number of indices specified for select must match number to select");if(t=t.map(Number),!t.every(Number.isInteger))throw Error("All indices specified for select must be integers");let n=e.length;t=t.map((e=>((e-1)%n+n)%n+1));let r=[];for(let n of t){let t=returnSequenceValueForIndex({index:n-1,from:e.from,step:e.step,length:e.length,exclude:e.exclude,type:e.type,lowercase:e.lowercase});if(null===t)throw Error("Specified index of selectfromsequence that was excluded");r.push(t)}if(checkForExcludedCombination({type:e.type,excludedCombinations:e.excludedCombinations,values:r}))throw Error("Specified indices of selectfromsequence that was an excluded combination");return{setEssentialValue:{selectedValues:r,selectedIndices:t},setValue:{selectedValues:r,selectedIndices:t}}}}let n,r,a=e.excludedCombinations.length;if("number"===e.type){a=0;let t=e.length-e.exclude.length;for(let n of e.excludedCombinations){let r=n.reduce(((e,t)=>e+(Number.isNaN(t)?1:0)),0);if(r>0)if(e.withReplacement)a+=Math.pow(t,r);else{let n=t-e.numberToSelect+r,i=n;for(let e=1;e.7*i){let t=0;for(let n=0;n.7*t){if("number"!==e.type||!e.excludedCombinations.some((e=>e.some(Number.isNaN))))throw Error("Excluded over 70% of combinations in selectFromSequence");if(a-=estimateNumberOfDuplicateCombinations(e.excludedCombinations,e.length-e.exclude.length,e.withReplacement),a>.7*t)throw Error("Excluded over 70% of combinations in selectFromSequence")}}let o=!1;for(let a=0;a<200;a++){let a=selectValuesAndIndices({stateValues:e,numberUniqueRequired:t,numberToSelect:e.numberToSelect,withReplacement:e.withReplacement,rng:e.variantRng});if(n=a.selectedValues,r=a.selectedIndices,!checkForExcludedCombination({type:e.type,excludedCombinations:e.excludedCombinations,values:n})){o=!0;break}}if(!o)throw Error("By extremely unlikely fluke, couldn't select combination of random values")}if(e.sortResults){let t=[];for(let[e,a]of n.entries())t.push({value:a,index:r[e]});"number"===e.type?t.sort(((e,t)=>e.value-t.value)):"letters"===e.type&&t.sort(((e,t)=>lettersToNumber$1(e.value)-lettersToNumber$1(t.value))),n=t.map((e=>e.value)),r=t.map((e=>e.index))}return{setEssentialValue:{selectedValues:n,selectedIndices:r},setValue:{selectedValues:n,selectedIndices:r}}}function selectValuesAndIndices({stateValues:e,numberUniqueRequired:t=1,numberToSelect:n=1,withReplacement:r=!1,rng:a}){let i=[],o=[];if(e.exclude.length+t<.5*e.length){for(let t=0;tl)throw Error("Cannot select "+t+" unique values from sequence of length "+l);if(1===t){for(let e=0;e0;e--){const t=a(),n=Math.floor(t*(e+1));[s[e],s[n]]=[s[n],s[e]]}let u=s.slice(0,n);return i=u.map((e=>e.value)),o=u.map((e=>e.originalIndex+1)),{selectedValues:i,selectedIndices:o}}function checkForExcludedCombination({type:e,excludedCombinations:t,values:n}){return"math"===e?t.some((e=>e.every(((e,t)=>e.equals(n[t]))))):"number"===e?t.some((e=>e.every(((e,t)=>Number.isNaN(e)||Math.abs(e-n[t])<=1e-14*Math.max(Math.abs(e),Math.abs(n[t])))))):t.some((e=>e.every(((e,t)=>e===n[t]))))}function mergeContainingCombinations(e){if(0===e.length)return{merged:!1,combinations:[]};let t=[e[0]],n=!1;for(let r of e.slice(1)){let e=[],a=!1;for(let n of t){if(a){e.push(n);continue}let t=[];a=!0;let i=null;for(let e=0;e!Number.isNaN(e)));[...new Set(e)].length===e.length&&a.push(s)}}}for(;;){let e=mergeContainingCombinations(a);if(!e.merged)break;a=e.combinations}let i=0;if(a.length>0)for(let e of a){let r=e.reduce(((e,t)=>e+(Number.isNaN(t)?1:0)),0);if(r>0)if(n)i+=Math.pow(t,r);else{let n=t-e.length+r,a=n;for(let e=1;e"string"==typeof e||e.doenetAttributes&&e.doenetAttributes.createdFromMacro)))return{success:!1};let r;r=t.type?t.type:"math",["math","text","number","boolean"].includes(r)||(console.warn(`Invalid type ${r}`),r="math");let a=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:r,forceComponentType:!0})({matchedChildren:e,componentInfoObjects:n});if(a.success){return{success:!0,newChildren:a.newChildren.map((e=>({componentType:"option",children:[e]}))),newAttributes:{addLevelToAssignNames:{primitive:!0}}}}return{success:!1}}}),e}static returnChildGroups(){return[{group:"options",componentTypes:["option"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.variants={returnDependencies:()=>({variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){return{setValue:{variants:e.variants}}}},e.currentVariantName={returnDependencies:({sharedParameters:e})=>({variantName:{dependencyType:"value",value:e.variantName}}),definition:({dependencyValues:e})=>({setValue:{currentVariantName:e.variantName}})},e.allVariantNames={returnDependencies:({sharedParameters:e})=>({allVariantNames:{dependencyType:"value",value:e.allVariantNames}}),definition:({dependencyValues:e})=>({setValue:{allVariantNames:e.allVariantNames}})},e.nOptions={additionalStateVariablesDefined:["optionChildren"],returnDependencies:()=>({optionChildren:{dependencyType:"child",childGroups:["options"],variableNames:["selectForVariants","selectWeight"]}}),definition:({dependencyValues:e})=>({setValue:{optionChildren:e.optionChildren,nOptions:e.optionChildren.length}})},e.availableVariants={returnDependencies:()=>({optionChildren:{dependencyType:"stateVariable",variableName:"optionChildren"},numberToSelect:{dependencyType:"stateVariable",variableName:"numberToSelect"},allVariantNames:{dependencyType:"stateVariable",variableName:"allVariantNames"}}),definition:function({dependencyValues:e}){let t={};for(let[n,r]of e.optionChildren.entries())for(let e of r.stateValues.selectForVariants){let r=e.toLowerCase();void 0===t[r]&&(t[r]=[]),t[r].push(n+1)}for(let n in t)if(t[n].length!==e.numberToSelect)throw Error("Invalid variant name for select. Variant name "+n+" appears in "+t[n].length+" options but number to select is "+numberToSelect);if(Object.keys(t).length>0){for(let n of e.allVariantNames)if(!(n in t))throw Error("Some variants are specified for select but no options are specified for possible variant name: "+n);for(let n in t)if(!e.allVariantNames.includes(n))throw Error("Variant name "+n+" that is specified for select is not a possible variant name.")}return{setValue:{availableVariants:t}}}},e.selectedIndices={immutable:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:({sharedParameters:e})=>({numberToSelect:{dependencyType:"stateVariable",variableName:"numberToSelect"},withReplacement:{dependencyType:"stateVariable",variableName:"withReplacement"},optionChildren:{dependencyType:"stateVariable",variableName:"optionChildren"},nOptions:{dependencyType:"stateVariable",variableName:"nOptions"},currentVariantName:{dependencyType:"stateVariable",variableName:"currentVariantName"},variants:{dependencyType:"stateVariable",variableName:"variants"},availableVariants:{dependencyType:"stateVariable",variableName:"availableVariants"},variantRng:{dependencyType:"value",value:e.variantRng,doNotProxy:!0}}),definition:function({dependencyValues:e}){if(!(e.numberToSelect>=1)||0===e.nOptions)return{setEssentialValue:{selectedIndices:[]},setValue:{selectedIndices:[]}};if(e.variants&&void 0!==e.variants.desiredVariant){let t=e.variants.desiredVariant.indices;if(void 0!==t){if(t.length!==e.numberToSelect)throw Error("Number of indices specified for select must match number to select");if(t=t.map(Number),!t.every(Number.isInteger))throw Error("All indices specified for select must be integers");let n=e.nOptions;return t=t.map((e=>((e-1)%n+n)%n+1)),{setEssentialValue:{selectedIndices:t},setValue:{selectedIndices:t}}}}let t=e.availableVariants[e.currentVariantName];if(void 0!==t){if(e.numberToSelect>1){t=[...t];for(let n=e.numberToSelect-1;n>0;n--){const r=e.variantRng(),a=Math.floor(r*(n+1));[t[n],t[a]]=[t[a],t[n]]}}return{setEssentialValue:{selectedIndices:t},setValue:{selectedIndices:t}}}let n=[],r=1;if(e.withReplacement||(r=e.numberToSelect),r>e.nOptions)throw Error("Cannot select "+r+" components from only "+e.nOptions);let a=e.optionChildren.map((e=>e.stateValues.selectWeight)),i=a.reduce(((e,t)=>e+t));a=a.map((e=>e/i));let o=a.reduce(((e,t,n)=>[...e,t+(e[n-1]||0)]),[]),s=[...Array(o.length).keys()].map((e=>e+1));for(let t=0;tr?u=e:l=e}let c=s[u];n.push(c),!e.withReplacement&&te+t)),a=a.map((e=>e/i)),o=a.reduce(((e,t,n)=>[...e,t+(e[n-1]||0)]),[]))}return{setEssentialValue:{selectedIndices:n},setValue:{selectedIndices:n}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={providePreviousValuesInDefinition:!0,returnDependencies:({componentInfoObjects:e})=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(e.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t,previousValues:n}){let r={indices:e.selectedIndices,meta:{createdBy:t}},a=r.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?a.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&a.push(...t.stateValues.generatedVariantInfo.subvariants);for(let[e,t]of a.entries())if(!t.subvariants&&n.generatedVariantInfo){let t=n.generatedVariantInfo.subvariants;t[e].subvariants&&(a[e]=Object.assign({},a[e]),a[e].subvariants=t[e].subvariants)}return{setValue:{generatedVariantInfo:r}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n}){let r=[],a=await e.stateValues.optionChildren;for(let n of await e.stateValues.selectedIndices){let e=a[n-1].componentName,i=t[e],o=deepClone(await i.stateValues.serializedChildren),s={componentType:"option",state:{rendered:!0},doenetAttributes:Object.assign({},i.doenetAttributes),children:o,originalName:e};i.attributes.newNamespace&&(s.attributes={newNamespace:{primitive:!0}}),r.push(s)}let i=gatherVariantComponents({serializedComponents:r,componentInfoObjects:n});if(e.variants&&void 0!==e.variants.desiredVariant){let t=e.variants.desiredVariant;if(void 0!==t&&void 0!==t.subvariants)for(let e in t.subvariants){let n=t.subvariants[e],r=i[e];if(void 0===r)break;r.variants.desiredVariant=n}}let o=e.attributes.newNamespace?.primitive,s=e.doenetAttributes.assignNames;s&&await e.stateValues.addLevelToAssignNames&&(s=s.map((e=>[e])));for(let e of r)!e.attributes?.newNamespace?.primitive&&e.children&&markToCreateAllUniqueNames(e.children);let l=[];for(let[t,a]of r.entries()){let r=processAssignNames({assignNames:s,serializedComponents:[a],parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:n,indOffset:t});l.push(r.serializedComponents[0])}return{replacements:l}}static calculateReplacementChanges(){return[]}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){let n=e.variants?.numberOfVariants;if(void 0!==n)return{success:!0,numberOfVariants:n};let r=1,a=!1,i=e.attributes.numberToSelect?.component;if(i){if("integer"!==i.componentType||1!==i.children?.length||"string"!=typeof i.children[0])return console.log("cannot determine unique variants of selectFromSequence as numberToSelect isn't constant number."),{success:!1};if(r=Number(i.children[0]),!(Number.isInteger(r)&&r>=0))return console.log("cannot determine unique variants of selectFromSequence as numberToSelect isn't a non-negative integer."),{success:!1}}let o=e.attributes.withReplacement?.component;if(o){if("boolean"!==o.componentType)return console.log("cannot determine unique variants of selectFromSequence as withReplacement isn't constant boolean."),{success:!1};if(1===o.children?.length&&"string"==typeof o.children[0])a="true"===o.children[0].toLowerCase();else{if(void 0!==o.children&&0!==o.children.length||"boolean"!=typeof o.state?.value)return console.log("cannot determine unique variants of selectFromSequence as withReplacement isn't constant boolean."),{success:!1};a=o.state.value}}for(let t of e.children)if(t.attributes?.selectWeight||t.attributes?.selectForVariants)return console.log("Unique variants for select disabled if have an option with selectWeight or selectForVariants specified"),{success:!1};void 0===e.variants&&(e.variants={});let s=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t});e.variants.descendantVariantComponents=s;let l=[];for(let e of s){let n=t.allComponentClasses[e.componentType].determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!n.success)return{success:!1};l.push(n.numberOfVariants)}let u={numberOfVariantsByChild:l,numberToSelect:r,withReplacement:a};if(0===l.length)n=1;else if(a||1===r){let e=l.reduce(((e,t)=>e+t));n=Math.pow(e,r)}else{let e=l.length;if(r>e)return{success:!1};let t=l[0],a=l.slice(1).every((e=>e===t));if(a){let a=e;for(let t=e-1;t>e-r;t--)a*=t;n=a*Math.pow(t,r)}else n=countOptions(l,r)}return e.variants.numberOfVariants=n,e.variants.uniqueVariants=!0,e.variants.uniqueVariantData=u,{success:!0,numberOfVariants:n}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};let a,i=e.variants.uniqueVariantData,o=i.numberOfVariantsByChild,s=i.numberToSelect,l=i.withReplacement,u=e.children.length,c=e.children;if(0===o.length)return{success:!0,desiredVariant:{indices:[]}};a=1===s?[...Array(u).keys()].map((e=>[e])):enumerateSelectionCombinations({numberOfIndices:s,numberOfOptions:u,withReplacement:l});let p,d,m=a.length,f=a.map((e=>({combination:e,numberOfPossibilities:e.reduce(((e,t)=>e*o[t]),1)}))),h=[...Array(m).keys()],y=0,b=h.length,g=t-1;for(;b>0;){let e=h.map((e=>f[e])).reduce(((e,t)=>Math.min(e,t.numberOfPossibilities)),1/0),t=e-y;if(gf[e].numberOfPossibilities>y)),b=h.length}let v=a[p],T=enumerateCombinations({numberOfOptionsByIndex:v.map((e=>o[e])),maxNumber:d})[d-1].map((e=>e+1)),N=[],C=!1;for(let[e,t]of v.entries())if(o[t]>1){let r=c[t],a=n.allComponentClasses[r.componentType].getUniqueVariant({serializedComponent:r,variantIndex:T[e],componentInfoObjects:n});if(!a.success)return{success:!1};N.push(a.desiredVariant),C=!0}else N.push({});let A={indices:v.map((e=>e+1))};return C&&(A.subvariants=N),{success:!0,desiredVariant:A}}}let countOptions=function(e,t){if(0===t)return 0;if(1===t)return e.reduce(((e,t)=>e+t));let n=0;for(let r in e){let a=e[r],i=[...e];i.splice(r,1),n+=a*countOptions(i,t-1)}return n};class AnimateFromSequence extends BaseComponent{constructor(e){super(e),this.advanceAnimation=this.advanceAnimation.bind(this)}static componentType="animateFromSequence";static rendererType=void 0;static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject(),t=returnStandardSequenceAttributes();return Object.assign(e,t),e.prop={createPrimitiveOfType:"string"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.animationOn={createComponentOfType:"boolean",createStateVariable:"animationOn",defaultValue:!1,public:!0,triggerActionOnChange:"changedAnimationOn"},e.animationMode={createComponentOfType:"text",createStateVariable:"animationMode",defaultValue:"increase",validValues:["increase","decrease","increase once","decrease once","oscillate"],toLowerCase:!0,public:!0},e.animationInterval={createComponentOfType:"number",createStateVariable:"animationInterval",defaultValue:1e3,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStandardSequenceStateVariableDefinitions();return Object.assign(e,t),e.possibleValues={additionalStateVariablesDefined:["numberValues"],returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},length:{dependencyType:"stateVariable",variableName:"length"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"},exclude:{dependencyType:"stateVariable",variableName:"exclude"},lowercase:{dependencyType:"stateVariable",variableName:"lowercase"}}),definition({dependencyValues:e}){let t=returnSequenceValues(e);return{setValue:{possibleValues:t,numberValues:t.length}}}},e.selectedIndex={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{selectedIndex:!0}}),inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>({success:!0,instructions:[{setEssentialValue:"selectedIndex",value:me$3.math.mod(e.selectedIndex-1,await t.numberValues)+1}]})},e.value={public:!0,shadowingInstructions:{hasVariableComponentType:!0},returnDependencies:()=>({possibleValues:{dependencyType:"stateVariable",variableName:"possibleValues"},selectedIndex:{dependencyType:"stateVariable",variableName:"selectedIndex"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition:({dependencyValues:e})=>({setValue:{value:e.possibleValues[e.selectedIndex-1]},setCreateComponentOfType:{value:e.type}}),async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if("number"===t.type){let r=e.value;if(r instanceof me$3.class&&(r=r.evaluate_to_constant()),!Number.isFinite(r))return{success:!1};let a=-1,i=t.possibleValues.length-1;for(;a0?i=e:a=e}let o=i;return-1!==a&&Math.abs(r-t.possibleValues[a])({animationMode:{dependencyType:"stateVariable",variableName:"animationMode"}}),definition:({dependencyValues:e})=>({useEssentialOrDefaultValue:{currentAnimationDirection:{get defaultValue(){return"decrease"===e.animationMode.substring(0,8)?"decrease":"increase"}}}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.currentAnimationDirection.toLowerCase();return["increase","decrease"].includes(t)||(t="increase"),{success:!0,instructions:[{setEssentialValue:"currentAnimationDirection",value:t}]}}},e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){let t=null;return e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.propName={returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.targetIdentities={stateVariablesDeterminingDependencies:["targetComponent","componentIndex"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={};return null!==e.targetComponent&&(t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})?n.targets={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,componentIndex:e.componentIndex}:null!==e.componentIndex&&1!==e.componentIndex||(n.targets={dependencyType:"stateVariable",variableName:"targetComponent"})),n},definition({dependencyValues:e}){let t=null;return e.targets&&(t=e.targets,Array.isArray(t)||(t=[t])),{setValue:{targetIdentities:t}}}},e.targets={stateVariablesDeterminingDependencies:["targetIdentities","propName","propIndex"],returnDependencies:function({stateValues:e}){let t={targetIdentities:{dependencyType:"stateVariable",variableName:"targetIdentities"}};if(null!==e.targetIdentities)for(let[n,r]of e.targetIdentities.entries()){let a;if(e.propName){let t=e.propIndex;t&&(t=[...t]),a={dependencyType:"stateVariable",componentName:r.componentName,variableName:e.propName,returnAsComponentObject:!0,variablesOptional:!0,propIndex:t,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0}}else a={dependencyType:"stateVariable",componentName:r.componentName,variableName:"value",returnAsComponentObject:!0,variablesOptional:!0};t["target"+n]=a}return t},definition({dependencyValues:e}){let t=null;if(null!==e.targetIdentities){t=[];for(let n in e.targetIdentities)e["target"+n]&&t.push(e["target"+n])}return{setValue:{targets:t}}}},e.valueToIndex={returnDependencies:()=>({possibleValues:{dependencyType:"stateVariable",variableName:"possibleValues"}}),definition:function({dependencyValues:e}){let t={};for(let[n,r]of e.possibleValues.entries())t[r]=n;return{setValue:{valueToIndex:t}}}},e}async changedAnimationOn({stateValues:e,previousValues:t,actionId:n}){let r=[];if(e.animationOn)if(t.animationOn)this.coreFunctions.resolveAction({actionId:n});else{let e=await this.stateValues.currentAnimationDirection,t=await this.stateValues.animationMode,a=await this.stateValues.numberValues,i=await this.stateValues.selectedIndex,o=await this.findIndexFromTarget();"increase"===e?o===a&&("increase once"===t?o=1:"oscillate"===t&&(e="decrease",r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"currentAnimationDirection",value:e}))):"decrease"===e&&1===o&&("decrease once"===t?o=a:"oscillate"===t&&(e="increase",r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"currentAnimationDirection",value:e}))),o!==i&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedIndex",value:o});let s=await this.getUpdateInstructionsToSetTargetsToValue((await this.stateValues.possibleValues)[me$3.math.mod(o-1,a)]);r.push(...s),await this.coreFunctions.performUpdate({updateInstructions:r,actionId:n,event:{verb:"played",object:{componentName:this.componentName,componentType:this.componentType},context:{startIndex:o,animationDirection:e,animationMode:t}}}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName}),this.animationId=nanoid(),await this.coreFunctions.requestAnimationFrame({action:{actionName:"advanceAnimation",componentName:this.componentName},delay:await this.stateValues.animationInterval,animationId:this.animationId,actionArgs:{previousAnimationId:this.animationId}})}else t.animationOn?(await this.coreFunctions.cancelAnimationFrame(this.animationId),this.canceledAnimationId=this.animationId,await this.coreFunctions.triggerChainedActions({componentName:this.componentName}),this.coreFunctions.requestRecordEvent({verb:"paused",object:{componentName:this.componentName,componentType:this.componentType},context:{endIndex:await this.stateValues.selectedIndex}})):this.coreFunctions.resolveAction({actionId:n})}async findIndexFromTarget(){let e=await this.stateValues.targets,t=await this.stateValues.selectedIndex;if(null===e)return t;let n,r=e[0];if(r?.stateValues&&(n=Object.keys(r.stateValues)[0]),!n)return t;let a=r.stateValues[n],i=await this.stateValues.type;if("number"===i&&a instanceof me$3.class&&(a=a.evaluate_to_constant(),!Number.isFinite(a)))return t;let o=(await this.stateValues.valueToIndex)[a];if(void 0!==o)return o+1;if("number"!==i)return t;let s=await this.stateValues.possibleValues,l=function(e=0,t=s.length-1){if(t<=e+1)return a>s[e]?t:e;let n=Math.round((t+e)/2);return a>s[n]?l(n,t):l(e,n)},u=l();if(0!==u){let e=s[u-1],t=s[u];Math.abs(a-e)=await this.stateValues.numberValues&&("increase once"===i?a=!1:"oscillate"===i&&(r="decrease")));let s=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedIndex",value:n}],l=await this.getUpdateInstructionsToSetTargetsToValue((await this.stateValues.possibleValues)[me$3.math.mod(n-1,await this.stateValues.numberValues)]);s.push(...l),a||s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"animationOn",value:!1}),r&&s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"currentAnimationDirection",value:r}),await this.coreFunctions.performUpdate({updateInstructions:s,actionId:t}),a&&(this.animationId=nanoid(),await this.coreFunctions.requestAnimationFrame({action:{actionName:"advanceAnimation",componentName:this.componentName},delay:await this.stateValues.animationInterval,animationId:this.animationId,actionArgs:{previousAnimationId:this.animationId}}))}startAnimation({actionId:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"animationOn",value:!0}],actionId:e})}stopAnimation({actionId:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"animationOn",value:!1}],actionId:e})}async toggleAnimation({actionId:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"animationOn",value:!await this.stateValues.animationOn}],actionId:e})}actions={changedAnimationOn:this.changedAnimationOn.bind(this),advanceAnimation:this.advanceAnimation.bind(this),startAnimation:this.startAnimation.bind(this),stopAnimation:this.stopAnimation.bind(this),toggleAnimation:this.toggleAnimation.bind(this)};async getUpdateInstructionsToSetTargetsToValue(e){let t=await this.stateValues.targets;if(null==t)return[];let n=[];for(let r of t){let t=Object.keys(r.stateValues)[0];void 0!==t?n.push({updateType:"updateValue",componentName:r.componentName,stateVariable:t,value:e}):await this.stateValues.propName?console.warn(`Cannot animate prop="${await this.stateValues.propName}" of ${await this.stateValues.target} as could not find prop ${await this.stateValues.propName} on a component of type ${r.componentType}`):console.warn(`Cannot animate ${await this.stateValues.target} as could not find a value state variable on a component of type ${r.componentType}`)}return n}}class Evaluate extends MathComponent{static componentType="evaluate";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.forceSymbolic={createComponentOfType:"boolean",createStateVariable:"forceSymbolic",defaultValue:!1,public:!0},e.forceNumeric={createComponentOfType:"boolean",createStateVariable:"forceNumeric",defaultValue:!1,public:!0},e.function={createComponentOfType:"function"},e.input={createComponentOfType:"mathList"},e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e}static returnChildGroups(){return[]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.codePre,delete e.expressionWithCodes,delete e.mathChildrenFunctionSymbols,delete e.codesAdjacentToStrings,delete e.mathChildrenByVectorComponent,delete e.mathChildrenWithCanBeModified,delete e.unordered,e.canBeModified={returnDependencies:()=>({}),definition:()=>({setValue:{canBeModified:!1}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:10,hasEssential:!0,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["displayDigits"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:e.functionAttr?t.functionAttr?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:e.functionAttr.stateValues.displayDecimals}}}:{setValue:{displayDecimals:e.functionAttr.stateValues.displayDecimals}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:e.functionAttr?t.functionAttr?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:e.functionAttr.stateValues.displaySmallAsZero}}}:{setValue:{displaySmallAsZero:e.functionAttr.stateValues.displaySmallAsZero}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:e.functionAttr?t.functionAttr?{useEssentialOrDefaultValue:{padZeros:{defaultValue:e.functionAttr.stateValues.padZeros}}}:{setValue:{padZeros:e.functionAttr.stateValues.padZeros}}:{useEssentialOrDefaultValue:{padZeros:!0}}},e.unnormalizedValue={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({inputAttr:{dependencyType:"attributeComponent",attributeName:"input",variableNames:["nComponents","maths"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["symbolicfs","numericalfs","symbolic","nInputs","nOutputs"]},forceSymbolic:{dependencyType:"stateVariable",variableName:"forceSymbolic"},forceNumeric:{dependencyType:"stateVariable",variableName:"forceNumeric"}}),definition({dependencyValues:e}){if(!e.functionAttr||!e.inputAttr)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};let t=e.inputAttr.stateValues.maths;if(1===t.length){let e=t[0].tree;Array.isArray(e)&&["vector","tuple"].includes(e[0])&&(t=e.slice(1).map((e=>me$3.fromAst(e))))}if(t.length!==e.functionAttr.stateValues.nInputs)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};let n,r=[],a=e.functionAttr,i=a.stateValues.nOutputs;if(e.forceNumeric||!a.stateValues.symbolic&&!e.forceSymbolic){let e=t.map((e=>e.evaluate_to_constant())).map((e=>null===e?NaN:e));for(let t=0;t=0&&Number.isFinite(r))){let e="Invalid mean ("+r+") or standard deviation ("+n+") for a gaussian random variable.";return console.warn(e),Array(t).fill(NaN)}let e=[];for(let a=0;a0)for(let n=0;n({type:{dependencyType:"stateVariable",variableName:"type"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"}}),definition({dependencyValues:e}){let t;return t="discreteuniform"===e.type?e.specifiedStep:null,{setValue:{step:t}}}},e.from={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"to",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"nDiscreteValues"}],returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},step:{dependencyType:"stateVariable",variableName:"step"}}),definition({dependencyValues:e}){if(!["discreteuniform","uniform"].includes(e.type))return{setValue:{from:null,to:null,nDiscreteValues:null}};let t=e.step,n=e.specifiedFrom,r=e.specifiedTo,a=null;if(null===r)null===n&&(n=0),"uniform"===e.type?r=n+1:(r=n+t,a=2);else if(null===n)if("uniform"===e.type)n=0;else{let e=0;a=Math.floor((r-e)/t+1),a<1?(a=0,n=null):n=r-(a-1)*t}else"discreteuniform"===e.type&&(a=Math.floor((r-n)/t+1),a<1?a=0:r=n+(a-1)*t);return{setValue:{from:n,to:r,nDiscreteValues:a}}}},e.mean={stateVariablesDeterminingDependencies:["type"],public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies({stateValues:e}){let t={type:{dependencyType:"stateVariable",variableName:"type"}};return"gaussian"===e.type?t.specifiedMean={dependencyType:"stateVariable",variableName:"specifiedMean"}:(t.from={dependencyType:"stateVariable",variableName:"from"},t.to={dependencyType:"stateVariable",variableName:"to"}),t},definition({dependencyValues:e}){let t;return t="gaussian"===e.type?e.specifiedMean:(e.from+e.to)/2,{setValue:{mean:t}}}},e.variance={stateVariablesDeterminingDependencies:["type"],public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies({stateValues:e}){let t={type:{dependencyType:"stateVariable",variableName:"type"}};return"gaussian"===e.type?(t.specifiedVariance={dependencyType:"stateVariable",variableName:"specifiedVariance"},t.specifiedStandardDeviation={dependencyType:"stateVariable",variableName:"specifiedStandardDeviation"}):(t.from={dependencyType:"stateVariable",variableName:"from"},t.to={dependencyType:"stateVariable",variableName:"to"},"discreteuniform"===e.type&&(t.step={dependencyType:"stateVariable",variableName:"step"},t.nDiscreteValues={dependencyType:"stateVariable",variableName:"nDiscreteValues"})),t},definition({dependencyValues:e,usedDefault:t}){let n;return n="gaussian"===e.type?t.specifiedVariance&&!t.specifiedStandardDeviation?e.specifiedStandardDeviation**2:e.specifiedVariance:"discreteuniform"===e.type?(e.nDiscreteValues**2-1)*e.step**2/12:(e.to-e.from)**2/12,{setValue:{variance:n}}}},e.standardDeviation={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({variance:{dependencyType:"stateVariable",variableName:"variance"}}),definition:({dependencyValues:e})=>({setValue:{standardDeviation:Math.sqrt(e.variance)}})},e.sampledValues={shadowVariable:!0,hasEssential:!0,stateVariablesDeterminingDependencies:["variantDeterminesSeed"],returnDependencies({stateValues:e,sharedParameters:t}){let n={numberOfSamples:{dependencyType:"stateVariable",variableName:"numberOfSamples"},type:{dependencyType:"stateVariable",variableName:"type"},from:{dependencyType:"stateVariable",variableName:"from"},to:{dependencyType:"stateVariable",variableName:"to"},step:{dependencyType:"stateVariable",variableName:"step"},nDiscreteValues:{dependencyType:"stateVariable",variableName:"nDiscreteValues"},mean:{dependencyType:"stateVariable",variableName:"mean"},standardDeviation:{dependencyType:"stateVariable",variableName:"standardDeviation"}};return e.variantDeterminesSeed?n.rng={dependencyType:"value",value:t.variantRng,doNotProxy:!0}:n.rng={dependencyType:"value",value:t.rngWithDateSeed,doNotProxy:!0},n},definition({dependencyValues:e}){if(e.numberOfSamples<1)return{setEssentialValue:{sampledValues:[]},setValue:{sampledValues:[]}};let t=sampleFromRandomNumbers(e);return{setEssentialValue:{sampledValues:t},setValue:{sampledValues:t}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"sampledValues",value:e.sampledValues}]})},e.readyToExpandWhenResolved={returnDependencies:()=>({sampledValues:{dependencyType:"stateVariable",variableName:"sampledValues"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e})=>({variantSeed:{dependencyType:"value",value:e.variantSeed}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{generatedVariantInfo:{seed:e.variantSeed,meta:{createdBy:t}}}})},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,startNum:n=0,flags:r}){let a=e.attributes.newNamespace?.primitive,i={};for(let t of["displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(i[t]=e.attributes[t]);let o=[];for(let s of(await e.stateValues.sampledValues).slice(n)){let e={};Object.keys(i).length>0&&(e=convertAttributesForComponentType({attributes:i,componentType:"number",componentInfoObjects:t,compositeCreatesNewNamespace:a,flags:r})),o.push({componentType:"number",attributes:e,state:{value:s}})}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:o,parentName:e.componentName,parentCreatesNewNamespace:a,indOffset:n,componentInfoObjects:t}).serializedComponents}}static async calculateReplacementChanges({component:e,componentInfoObjects:t,flags:n}){let r=[],a=await e.stateValues.sampledValues;if(a.length0){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};r.push(e)}if(a.length>e.replacements.length){let a=await this.createSerializedReplacements({component:e,componentInfoObjects:t,startNum:e.replacements.length,flags:n}),i={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:e.replacements.length,numberReplacementsToReplace:0,serializedReplacements:a.replacements,assignNamesOffset:e.replacements.length};r.push(i)}}let i=Math.min(e.replacements.length,a.length);for(let t=0;t({variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){return{setValue:{variants:e.variants}}}},e.step.immutable=!0,e.from.immutable=!0,e.from.additionalStateVariablesDefined[0].immutable=!0,e.from.additionalStateVariablesDefined[1].immutable=!0,e.mean.immutable=!0,e.variance.immutable=!0,e.standardDeviation.immutable=!0,delete e.sampledValues,e.selectedValues={immutable:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:({sharedParameters:e})=>({numberOfSamples:{dependencyType:"stateVariable",variableName:"numberToSelect"},type:{dependencyType:"stateVariable",variableName:"type"},from:{dependencyType:"stateVariable",variableName:"from"},to:{dependencyType:"stateVariable",variableName:"to"},step:{dependencyType:"stateVariable",variableName:"step"},nDiscreteValues:{dependencyType:"stateVariable",variableName:"nDiscreteValues"},mean:{dependencyType:"stateVariable",variableName:"mean"},standardDeviation:{dependencyType:"stateVariable",variableName:"standardDeviation"},variants:{dependencyType:"stateVariable",variableName:"variants"},rng:{dependencyType:"value",value:e.variantRng,doNotProxy:!0}}),definition({dependencyValues:e}){if(e.numberOfSamples<1)return{setEssentialValue:{selectedValues:[]},setValue:{selectedValues:[]}};if(e.variants&&e.variants.desiredVariant){let t=e.variants.desiredVariant.values;if(t){if(t.length!==e.numberOfSamples)throw Error("Number of values specified for selectRandomNumber must match number to select");return{setEssentialValue:{selectedValues:t},setValue:{selectedValues:t}}}}let t=sampleFromRandomNumbers(e);return{setEssentialValue:{selectedValues:t},setValue:{selectedValues:t}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:()=>({selectedValues:{dependencyType:"stateVariable",variableName:"selectedValues"}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{generatedVariantInfo:{values:e.selectedValues,meta:{createdBy:t}}}})},e.readyToExpandWhenResolved={returnDependencies:()=>({selectedValues:{dependencyType:"stateVariable",variableName:"selectedValues"}}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n}){let r=e.attributes.newNamespace?.primitive,a={};for(let t of["displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(a[t]=e.attributes[t]);let i=[];for(let o of await e.stateValues.selectedValues){let e={};Object.keys(a).length>0&&(e=convertAttributesForComponentType({attributes:a,componentType:"number",componentInfoObjects:t,compositeCreatesNewNamespace:r,flags:n})),i.push({componentType:"number",attributes:e,state:{value:o}})}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:i,parentName:e.componentName,parentCreatesNewNamespace:r,componentInfoObjects:t}).serializedComponents}}}delete SelectRandomNumbers.stateVariableToEvaluateAfterReplacements,delete SelectRandomNumbers.calculateReplacementChanges;class Substitute extends CompositeComponent{static componentType="substitute";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"math",toLowerCase:!0,validValues:["math","text"],public:!0},e.match={createComponentOfType:"_componentWithSelectableType",createStateVariable:"match",defaultValue:null},e.replacement={createComponentOfType:"_componentWithSelectableType",createStateVariable:"replacement",defaultValue:null},e.simplify={createComponentOfType:"text",createStateVariable:"simplify",defaultValue:"none",public:!0,toLowerCase:!0,valueTransformations:{true:"full"},validValues:["none","full","numbers","numberspreserveorder"]},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.matchWholeWord={createComponentOfType:"boolean",createStateVariable:"matchWholeWord",defaultValue:!1,public:!0},e.matchCase={createComponentOfType:"boolean",createStateVariable:"matchCase",defaultValue:!1,public:!0},e.preserveCase={createComponentOfType:"boolean",createStateVariable:"preserveCase",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){let n=t.type;return["math","text"].includes(n)||(n="math"),{success:!0,newChildren:[{componentType:n,children:e}]}}}),e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},child:{dependencyType:"child",childGroups:["anything"],variableNames:["displayDigits"],variablesOptional:!0}}),definition({dependencyValues:e,usedDefault:t}){if("math"!==e.type)return{setValue:{displayDigits:null}};if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({type:{dependencyType:"stateVariable",variableName:"type"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},child:{dependencyType:"child",childGroups:["anything"],variableNames:["displayDecimals"],variablesOptional:!0}}),definition:({dependencyValues:e,usedDefault:t})=>"math"!==e.type?{setValue:{displayDecimals:null}}:null===e.displayDecimalsAttr||t.displayDecimalsAttr?1!==e.child.length||t.child[0]&&t.child[0].displayDecimals?{useEssentialOrDefaultValue:{displayDecimals:!0}}:{setValue:{displayDecimals:e.child[0].stateValues.displayDecimals}}:{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},child:{dependencyType:"child",childGroups:["anything"],variableNames:["displaySmallAsZero"],variablesOptional:!0}}),definition:({dependencyValues:e,usedDefault:t})=>"math"!==e.type?{setValue:{displaySmallAsZero:null}}:null===e.displaySmallAsZeroAttr||t.displaySmallAsZeroAttr?1!==e.child.length||t.child[0]&&t.child[0].displaySmallAsZero?{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}:{setValue:{displaySmallAsZero:e.child[0].stateValues.displaySmallAsZero}}:{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},child:{dependencyType:"child",childGroups:["anything"],variableNames:["padZeros"],variablesOptional:!0}}),definition:({dependencyValues:e,usedDefault:t})=>"math"!==e.type?{setValue:{padZeros:null}}:null===e.padZerosAttr||t.padZerosAttr?1!==e.child.length||t.child[0]&&t.child[0].padZeros?{useEssentialOrDefaultValue:{padZeros:!0}}:{setValue:{padZeros:e.child[0].stateValues.padZeros}}:{setValue:{padZeros:e.padZerosAttr.stateValues.value}}},e.originalValue={returnDependencies:()=>({child:{dependencyType:"child",childGroups:["anything"],variableNames:["value"]}}),definition:({dependencyValues:e})=>e.child.length>0?{setValue:{originalValue:e.child[0].stateValues.value}}:{setValue:{originalValue:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.child.length>0?{success:!0,instructions:[{setDependency:"child",desiredValue:e.originalValue,childIndex:0,variableIndex:0}]}:{success:!1}},e.value={returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},originalValue:{dependencyType:"stateVariable",variableName:"originalValue"},match:{dependencyType:"stateVariable",variableName:"match"},replacement:{dependencyType:"stateVariable",variableName:"replacement"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},matchWholeWord:{dependencyType:"stateVariable",variableName:"matchWholeWord"},matchCase:{dependencyType:"stateVariable",variableName:"matchCase"},preserveCase:{dependencyType:"stateVariable",variableName:"preserveCase"}}),definition({dependencyValues:e}){if(null===e.originalValue)return{setValue:{value:null}};if(null===e.match||null===e.replacement)return{setValue:{value:e.originalValue}};if("text"===e.type){let t,n=e.originalValue,r="g";e.matchCase||(r="gi"),t=e.matchWholeWord?new RegExp("\\b"+escapeRegExp(e.match)+"\\b",r):new RegExp(escapeRegExp(e.match),r);let a=e.replacement;if(e.preserveCase){let e=returnPreserveCaseReplacer(a);n=n.replace(t,e)}else n=n.replace(t,a);return{setValue:{value:n}}}{let t=e.originalValue.subscripts_to_strings();return t=t.substitute({[e.match.subscripts_to_strings().tree]:e.replacement.subscripts_to_strings()}),t=t.strings_to_subscripts(),t=normalizeMathExpression({value:t,simplify:e.simplify}),{setValue:{value:t}}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("text"===t.type){let n,r,a=e.value,i="g";t.matchCase||(i="gi");let o=t.match,s=t.replacement;if(t.matchWholeWord)if(n=new RegExp("\\b"+escapeRegExp(o)+"\\b",i),t.matchCase&&t.preserveCase){let e=returnPreserveCaseReplacer(s);r=new RegExp("\\b"+escapeRegExp(e(o))+"\\b",i)}else r=new RegExp("\\b"+escapeRegExp(s)+"\\b",i);else if(n=new RegExp(escapeRegExp(o),i),t.matchCase&&t.preserveCase){let e=returnPreserveCaseReplacer(s);r=new RegExp(escapeRegExp(e(o)),i)}else r=new RegExp(escapeRegExp(s),i);return-1!==t.originalValue.search(r)||-1!==a.search(n)?{success:!1}:(a=a.replace(r,o),{success:!0,instructions:[{setDependency:"originalValue",desiredValue:a}]})}{let n=e.value.subscripts_to_strings(),r=t.match.subscripts_to_strings(),a=t.replacement.subscripts_to_strings();return"string"!=typeof r.tree||"string"!=typeof a.tree||(t.originalValue.variables(!0).includes(a.tree)||n.variables().includes(r.tree))?{success:!1}:(n=n.substitute({[a.tree]:r}),n=n.strings_to_subscripts(),{success:!0,instructions:[{setDependency:"originalValue",desiredValue:n}]})}}},e.readyToExpandWhenResolved={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n}){let r=e.attributes.newNamespace?.primitive,a=await e.stateValues.type,i={componentType:a,state:{value:await e.stateValues.value},downstreamDependencies:{[e.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:"value"}]}};if("math"===a){let t={},n={displayDigits:"integer",displayDecimals:"integer",displaySmallAsZero:"number",padZeros:"boolean"};for(let r in n){let a={componentType:n[r],downstreamDependencies:{[e.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:r}]}};t[r]={component:a}}i.attributes=t}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:[i],parentName:e.componentName,parentCreatesNewNamespace:r,componentInfoObjects:t}).serializedComponents}}}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function returnPreserveCaseReplacer(e){return function(t){return t.toUpperCase()===t?e.toUpperCase():t.toLowerCase()===t?e.toLowerCase():t[0].match(/[a-z]/)?e[0].toLowerCase()+e.substring(1):t[0].match(/[A-Z]/)?e[0].toUpperCase()+e.substring(1):e}}class PeriodicSet extends MathComponent{static componentType="periodicSet";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.minIndex={createComponentOfType:"integer",createStateVariable:"minIndex",defaultValue:-1/0,public:!0},e.maxIndex={createComponentOfType:"integer",createStateVariable:"maxIndex",defaultValue:1/0,public:!0},e.offsets={createComponentOfType:"mathList",createStateVariable:"offsets",defaultValue:null,public:!0},e.period={createComponentOfType:"math",createStateVariable:"period",defaultValue:null,public:!0},e.minIndexAsList={createComponentOfType:"integer",createStateVariable:"minIndexAsList",defaultValue:-1,public:!0},e.maxIndexAsList={createComponentOfType:"integer",createStateVariable:"maxIndexAsList",defaultValue:1,public:!0},e}static returnChildGroups(){return[]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.codePre,delete e.expressionWithCodes,delete e.mathChildrenFunctionSymbols,delete e.codesAdjacentToStrings,delete e.mathChildrenByVectorComponent,delete e.mathChildrenWithCanBeModified,delete e.unordered,e.canBeModified={returnDependencies:()=>({}),definition:()=>({setValue:{canBeModified:!1}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}if(!(null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals)&&null!==e.displayDigitsAttr){if(!t.displayDigitsAttr)return{setValue:{displayDigits:e.displayDigitsAttr.stateValues.value}};r=!0,n=e.displayDigitsAttr.stateValues.value}return r?{useEssentialOrDefaultValue:{displayDigits:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDigits:!0}}}},e.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:null,returnDependencies:()=>({mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.nOffsets={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({offsets:{dependencyType:"stateVariable",variableName:"offsets"}}),definition({dependencyValues:e}){let t=0;return null!==e.offsets&&(t=e.offsets.length),{setValue:{nOffsets:t}}}},e.unnormalizedValue={returnDependencies:()=>({offsets:{dependencyType:"stateVariable",variableName:"offsets"},period:{dependencyType:"stateVariable",variableName:"period"},minIndex:{dependencyType:"stateVariable",variableName:"minIndex"},maxIndex:{dependencyType:"stateVariable",variableName:"maxIndex"}}),definition({dependencyValues:e}){if(null===e.offsets||0===e.offsets.length||1===e.offsets.length&&"_"===e.offsets[0].tree||null===e.period||"_"===e.period.tree)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};let t=[],n=e.period.tree,r=e.minIndex,a=e.maxIndex;for(let i of e.offsets)t.push(["tuple",i.tree,n,r,a]);return{setValue:{unnormalizedValue:me$3.fromAst(["periodic_set",...t])}}}},e.redundantOffsets={additionalStateVariablesDefined:["uniqueOffsets"],public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({nOffsets:{dependencyType:"stateVariable",variableName:"nOffsets"},offsets:{dependencyType:"stateVariable",variableName:"offsets"},period:{dependencyType:"stateVariable",variableName:"period"}}),definition({dependencyValues:e}){let t=!1,n=[];if(null!==e.period){let r=e.period.evaluate_to_constant();if(null!==r)for(let a=0;a({uniqueOffsets:{dependencyType:"stateVariable",variableName:"uniqueOffsets"},period:{dependencyType:"stateVariable",variableName:"period"},minIndexAsList:{dependencyType:"stateVariable",variableName:"minIndexAsList"},maxIndexAsList:{dependencyType:"stateVariable",variableName:"maxIndexAsList"}}),definition({dependencyValues:e}){let t=[];if(null!==e.period){let n=e.period.evaluate_to_constant();if(null!==n){let r=e.period.simplify(),a=!0,i=[];for(let t of e.uniqueOffsets){let e=t.evaluate_to_constant();if(null===e){a=!1;break}{let a=t.subtract(r.multiply(Math.floor(e/n))).simplify(),o=a.evaluate_to_constant();i.push({num:o,offset:a})}}if(a){t.push(me$3.fromAst(["ldots"])),i.sort(((e,t)=>e.num-t.num));let n=-1,a=1;Number.isFinite(e.minIndexAsList)&&(n=e.minIndexAsList),Number.isFinite(e.maxIndexAsList)&&(a=e.maxIndexAsList);for(let e=n;e<=a;e++)for(let n of i)t.push(n.offset.add(r.multiply(e)).simplify());t.push(me$3.fromAst(["ldots"]))}}}return{setValue:{asList:t}}}},e}}class Image extends BlockComponent{static componentType="image";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"specifiedWidth",defaultValue:null},e.size={createComponentOfType:"text",createStateVariable:"specifiedSize",defaultValue:"medium",toLowerCase:!0,validValues:sizePossibilities},e.aspectRatio={createComponentOfType:"number"},e.height={createComponentOfType:"_componentSize"},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",validValues:["block","inline"],defaultValue:"block",forRenderer:!0,public:!0},e.horizontalAlign={createComponentOfType:"text",createStateVariable:"horizontalAlign",toLowerCase:!0,validValues:["center","left","right"],defaultValue:"center",forRenderer:!0,public:!0},e.description={createComponentOfType:"text",createStateVariable:"description",defaultValue:"",public:!0,forRenderer:!0},e.source={createComponentOfType:"text",createStateVariable:"source",defaultValue:"",public:!0,forRenderer:!0},e.asFileName={createComponentOfType:"text",createStateVariable:"asFileName",defaultValue:null,public:!0,forRenderer:!0},e.mimeType={createComponentOfType:"text",createStateVariable:"mimeType",defaultValue:null,public:!0,forRenderer:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.size={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({specifiedSize:{dependencyType:"stateVariable",variableName:"specifiedSize"},specifiedWidth:{dependencyType:"stateVariable",variableName:"specifiedWidth"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xscale"]}}),definition({dependencyValues:e,usedDefault:t}){const n="medium";if(t.specifiedSize){if(t.specifiedWidth)return{setValue:{size:n}};{let t=e.specifiedWidth;if(null===t)return{setValue:{size:n}};let r,{isAbsolute:a,size:i}=t;if(a){let t;if(e.graphAncestor){let n=e.graphAncestor.stateValues.xscale;t=orderedPercentWidthMidpoints.map((e=>e/100*n))}else t=orderedWidthMidpoints;for(let[e,n]of t.entries())if(i<=n){r=sizePossibilities[e];break}r||(r=n)}else{for(let[e,t]of orderedPercentWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=n)}return{setValue:{size:r}}}}return{setValue:{size:e.specifiedSize}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"specifiedSize",desiredValue:e.size}]})},e.width={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},returnDependencies:()=>({specifiedSize:{dependencyType:"stateVariable",variableName:"specifiedSize"},size:{dependencyType:"stateVariable",variableName:"size"},specifiedWidth:{dependencyType:"stateVariable",variableName:"specifiedWidth"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xscale"]}}),definition({dependencyValues:e,usedDefault:t}){if(e.graphAncestor){if(e.graphAncestor.stateValues.xscale,t.specifiedSize){if(t.specifiedWidth)return{setValue:{width:{isAbsolute:!1,size:percentWidthsBySize.medium}}};{let t,n=e.specifiedWidth;return t=n||{isAbsolute:!1,size:percentWidthsBySize.medium},{setValue:{width:t}}}}return{setValue:{width:{isAbsolute:!1,size:percentWidthsBySize[e.size]}}}}return{setValue:{width:{isAbsolute:!0,size:widthsBySize[e.size]}}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"specifiedWidth",desiredValue:e.width}]})},e.widthForGraph={forRenderer:!0,returnDependencies:()=>({width:{dependencyType:"stateVariable",variableName:"width"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xscale"]}}),definition({dependencyValues:e}){let t=e.width;return e.graphAncestor&&!t.isAbsolute&&(t={isAbsolute:!0,size:t.size/100*e.graphAncestor.stateValues.xscale}),{setValue:{widthForGraph:t}}}},e.aspectRatio={public:!0,forRenderer:!0,hasEssential:!0,defaultValue:null,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]}}),definition({dependencyValues:e}){if(null!==e.aspectRatioAttr){let t=e.aspectRatioAttr.stateValues.value;return Number.isFinite(t)||(t=null),{setValue:{aspectRatio:t}}}return{useEssentialOrDefaultValue:{aspectRatio:!0}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(null!==t.aspectRatioAttr)return{success:!0,instructions:[{setDependency:"aspectRatioAttr",desiredValue:e.aspectRatio,variableIndex:0}]};{let t=e.aspectRatio;return t>0||(t=null),{success:!0,instructions:[{setEssentialValue:"aspectRatio",value:t}]}}}},e.cid={forRenderer:!0,returnDependencies:()=>({source:{dependencyType:"stateVariable",variableName:"source"}}),definition:function({dependencyValues:e}){if(!e.source||"doenet:"!==e.source.substring(0,7).toLowerCase())return{setValue:{cid:null}};let t=null,n=e.source.match(/[:&]cid=([^&]+)/i);return n&&(t=n[1]),{setValue:{cid:t}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveImage({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={moveImage:this.moveImage.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class Video extends BlockComponent{static componentType="video";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize"},e.size={createComponentOfType:"text"},e.aspectRatio={createComponentOfType:"number"},e.height={createComponentOfType:"_componentSize"},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",validValues:["block","inline"],defaultValue:"block",forRenderer:!0,public:!0},e.horizontalAlign={createComponentOfType:"text",createStateVariable:"horizontalAlign",validValues:["center","left","right"],defaultValue:"center",forRenderer:!0,public:!0},e.youtube={createComponentOfType:"text",createStateVariable:"youtube",defaultValue:null,public:!0,forRenderer:!0},e.source={createComponentOfType:"text",createStateVariable:"source",defaultValue:null,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.size={public:!0,defaultValue:"full",hasEssential:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({sizeAttr:{dependencyType:"attributeComponent",attributeName:"size",variableNames:["value"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]}}),definition({dependencyValues:e}){const t="full";if(e.sizeAttr){let n=e.sizeAttr.stateValues.value.toLowerCase();return sizePossibilities.includes(n)||(n=t),{setValue:{size:n}}}if(e.widthAttr){let n=e.widthAttr.stateValues.componentSize;if(null===n)return{setValue:{size:t}};let r,{isAbsolute:a,size:i}=n;if(a){for(let[e,t]of orderedWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}else{for(let[e,t]of orderedPercentWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}return{setValue:{size:r}}}return{useEssentialOrDefaultValue:{size:!0}}}},e.width={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},returnDependencies:()=>({size:{dependencyType:"stateVariable",variableName:"size"}}),definition:({dependencyValues:e})=>({setValue:{width:{isAbsolute:!0,size:widthsBySize[e.size]}}})},e.aspectRatio={public:!0,forRenderer:!0,defaultValue:"16 / 9",hasEssential:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},width:{dependencyType:"stateVariable",variableName:"width"}}),definition({dependencyValues:e}){if(null!==e.aspectRatioAttr){let t=e.aspectRatioAttr.stateValues.value;return Number.isFinite(t)||(t=1),{setValue:{aspectRatio:t}}}return{useEssentialOrDefaultValue:{aspectRatio:!0}}}},e.state={hasEssential:!0,defaultValue:"initializing",forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},ignoreFixed:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{state:!0}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.state.toLowerCase();return["stopped","playing"].includes(t)?{success:!0,instructions:[{setEssentialValue:"state",value:t}]}:{success:!1}}},e.time={hasEssential:!0,defaultValue:0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"number"},ignoreFixed:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{time:!0}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.time;return t>=0?{success:!0,instructions:[{setEssentialValue:"time",value:t}]}:{success:!1}}},e.duration={hasEssential:!0,defaultValue:null,public:!0,shadowingInstructions:{createComponentOfType:"number"},ignoreFixed:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{duration:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"duration",value:e.duration}]})},e.segmentsWatched={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{segmentsWatched:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"segmentsWatched",value:e.segmentsWatched}]})},e.secondsWatched={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({segmentsWatched:{dependencyType:"stateVariable",variableName:"segmentsWatched"}}),definition({dependencyValues:e}){let t=0;return e.segmentsWatched&&(t=e.segmentsWatched.reduce(((e,t)=>e+t[1]-t[0]),0)),{setValue:{secondsWatched:t}}}},e.fractionWatched={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({secondsWatched:{dependencyType:"stateVariable",variableName:"secondsWatched"},duration:{dependencyType:"stateVariable",variableName:"duration"}}),definition:({dependencyValues:e})=>({setValue:{fractionWatched:e.secondsWatched/e.duration}})},e}recordVideoStarted({beginTime:e,duration:t,rate:n}){this.coreFunctions.requestRecordEvent({verb:"played",object:{componentName:this.componentName,componentType:this.componentType,duration:t},context:{startingPoint:e,rate:n}}),this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"playing"}],overrideReadOnly:!0})}async recordVideoWatched({beginTime:e,endTime:t,duration:n,rates:r}){this.coreFunctions.requestRecordEvent({verb:"watched",object:{componentName:this.componentName,componentType:this.componentType,duration:n},context:{startingPoint:e,endingPoint:t,rates:r}});let a,i=await this.stateValues.segmentsWatched;if(e<1?e=0:t>n-2&&(t=n),i){a=[];let n=!1;for(let[r,o]of i.entries()){if(to[1]+1?a.push(o):(e=Math.min(o[0],e),t=Math.max(o[1],t))}n||a.push([e,t])}else a=[[e,t]];return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"segmentsWatched",value:a}],canSkipUpdatingRenderer:!0}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}recordVideoPaused({endTime:e,duration:t}){this.coreFunctions.requestRecordEvent({verb:"paused",object:{componentName:this.componentName,componentType:this.componentType,duration:t},context:{endingPoint:e}}),this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"stopped"}],overrideReadOnly:!0})}recordVideoSkipped({beginTime:e,endTime:t,duration:n}){this.coreFunctions.requestRecordEvent({verb:"skipped",object:{componentName:this.componentName,componentType:this.componentType,duration:n},context:{startingPoint:e,endingPoint:t}})}recordVideoCompleted({duration:e}){this.coreFunctions.requestRecordEvent({verb:"completed",object:{componentName:this.componentName,componentType:this.componentType,duration:e}}),this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"stopped"}],overrideReadOnly:!0})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}recordVideoReady({duration:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"stopped"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"duration",value:e}],overrideReadOnly:!0,doNotSave:!0})}playVideo(){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"playing"}],overrideReadOnly:!0})}pauseVideo(){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"stopped"}],overrideReadOnly:!0})}setTime({time:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"time",value:e}],overrideReadOnly:!0})}actions={recordVideoStarted:this.recordVideoStarted.bind(this),recordVideoWatched:this.recordVideoWatched.bind(this),recordVideoPaused:this.recordVideoPaused.bind(this),recordVideoSkipped:this.recordVideoSkipped.bind(this),recordVideoCompleted:this.recordVideoCompleted.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this),recordVideoReady:this.recordVideoReady.bind(this),playVideo:this.playVideo.bind(this),pauseVideo:this.pauseVideo.bind(this),setTime:this.setTime.bind(this)}}class Embed extends BlockComponent{static componentType="embed";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:500,isAbsolute:!0},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:500,isAbsolute:!0},public:!0,forRenderer:!0},e.geogebra={createComponentOfType:"text",createStateVariable:"geogebra",defaultValue:null,public:!0,forRenderer:!0},e.encodedGeogebraContent={createComponentOfType:"text",createStateVariable:"encodedGeogebraContent",defaultValue:null,public:!0,forRenderer:!0},e.fromMathInsight={createComponentOfType:"text",createStateVariable:"fromMathInsight",defaultValue:null,public:!0,forRenderer:!0},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class Hint extends BlockComponent{static componentType="hint";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"titles",componentTypes:["title"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.showHints={forRenderer:!0,returnDependencies:()=>({hide:{dependencyType:"stateVariable",variableName:"hide"},showHintsFlag:{dependencyType:"flag",flagName:"showHints"}}),definition:({dependencyValues:e})=>({setValue:{showHints:e.showHintsFlag&&!e.hide}})},e.open={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{open:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"open",value:e.open}]})},e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[e.titleChild.length-1].componentName),{setValue:{titleChildName:t}}}},e.childIndicesToRender={returnDependencies:()=>({titleChildren:{dependencyType:"child",childGroups:["titles"]},allChildren:{dependencyType:"child",childGroups:["anything","titles"]},titleChildName:{dependencyType:"stateVariable",variableName:"titleChildName"}}),definition({dependencyValues:e}){let t=[],n=e.titleChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())"object"==typeof a&&n.includes(a.componentName)&&a.componentName!==e.titleChildName||t.push(r);return{setValue:{childIndicesToRender:t}}}},e.title={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.titleChild.length?{setValue:{title:"Hint"}}:{setValue:{title:e.titleChild[e.titleChild.length-1].stateValues.text}}},e}async revealHint({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!0}],overrideReadOnly:!0,actionId:e,event:{verb:"viewed",object:{componentName:this.componentName,componentType:this.componentType}}})}async closeHint({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!1}],overrideReadOnly:!0,actionId:e,event:{verb:"closed",object:{componentName:this.componentName,componentType:this.componentType}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={revealHint:this.revealHint.bind(this),closeHint:this.closeHint.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class Solution extends BlockComponent{static componentType="solution";static renderChildren=!0;static sendToRendererEvenIfHidden=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.hide={createComponentOfType:"boolean"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){return{success:!0,newChildren:[{componentType:"_solutionContainer",children:e}]}}}),e}static returnChildGroups(){return[{group:"inlinesBlocks",componentTypes:["_inline","_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.hide={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,returnDependencies:()=>({hideAttr:{dependencyType:"attributeComponent",attributeName:"hide",variableNames:["value"]},displayMode:{dependencyType:"flag",flagName:"solutionDisplayMode"}}),definition:({dependencyValues:e})=>"none"===e.displayMode?{setValue:{hide:!0}}:null!==e.hideAttr?{setValue:{hide:e.hideAttr.stateValues.value}}:{useEssentialOrDefaultValue:{hide:!0}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>"none"===t.displayMode?{success:!1}:null!==t.hideAttr?{success:!0,instructions:[{setDependency:"hideAttr",desiredValue:e.hide,variableIndex:0}]}:{success:!0,instructions:[{setSetVariable:"hide",value:e.hide}]}},e.open={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,returnDependencies:()=>({displayMode:{dependencyType:"flag",flagName:"solutionDisplayMode"}}),definition:({dependencyValues:e})=>"displayed"===e.displayMode?{setValue:{open:!0}}:"none"===e.displayMode?{setValue:{open:!1}}:{useEssentialOrDefaultValue:{open:!0}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>"displayed"===t.displayMode||"none"===t.displayMode?{success:!1}:{success:!0,instructions:[{setEssentialValue:"open",value:e.open}]}},e.canBeClosed={forRenderer:!0,returnDependencies:()=>({displayMode:{dependencyType:"flag",flagName:"solutionDisplayMode"}}),definition:({dependencyValues:e})=>"button"===e.displayMode?{setValue:{canBeClosed:!0}}:{setValue:{canBeClosed:!1}}},e.message={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,defaultValue:"",hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{message:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"message",value:e.message}]})},e}async revealSolution({actionId:e}){let t,{allowView:n,message:r,scoredComponent:a}=await this.coreFunctions.recordSolutionView(),i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:n},{updateType:"updateValue",componentName:this.componentName,stateVariable:"message",value:r}];return n&&(i.push({updateType:"updateValue",componentName:a,stateVariable:"viewedSolution",value:!0}),t={verb:"viewed",object:{componentName:this.componentName,componentType:this.componentType}}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:t,overrideReadOnly:!0})}async closeSolution({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!1}],overrideReadOnly:!0,actionId:e,event:{verb:"closed",object:{componentName:this.componentName,componentType:this.componentType}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={revealSolution:this.revealSolution.bind(this),closeSolution:this.closeSolution.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)};static includeBlankStringChildren=!0}class IntComma extends Text{static componentType="intcomma";static rendererType="text";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"originalValue"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType},returnDependencies:()=>({originalValue:{dependencyType:"stateVariable",variableName:"originalValue"}}),definition:function({dependencyValues:e}){let t=e.originalValue,n=/^(-?\d+)(\d{3})/,r=t.match(n);for(;null!==r;)t=t.replace(n,"$1,$2"),r=t.match(n);return{setValue:{value:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}}const e$1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split("");var t$1=function(e){let t=(e=e||"_")+"-";for(let e=0;e<7;e++)t+=e$1[Math.floor(Math.random()*e$1.length)];return t};let r$1={"!":"¡","?":"¿Ɂ",'"':'“”"❝❞',"'":"‘‛❛❜","-":"—–",a:"ªÀÁÂÃÄÅàáâãäåĀāĂ㥹ǍǎǞǟǠǡǺǻȀȁȂȃȦȧȺΆΑΔΛάαλАадѦѧӐӑӒӓƛɅæ",b:"ßþƀƁƂƃƄƅɃΒβϐϦБВЪЬвъьѢѣҌҍ",c:"¢©ÇçĆćĈĉĊċČčƆƇƈȻȼͻͼͽϲϹϽϾСсєҀҁҪҫ",d:"ÐĎďĐđƉƊȡƋƌǷ",e:"ÈÉÊËèéêëĒēĔĕĖėĘęĚěƎƏƐǝȄȅȆȇȨȩɆɇΈΕΞΣέεξϱϵ϶ЀЁЕЭеѐёҼҽҾҿӖӗӘәӚӛӬӭ",f:"ƑƒϜϝӺӻҒғſ",g:"ĜĝĞğĠġĢģƓǤǥǦǧǴǵ",h:"ĤĥĦħƕǶȞȟΉΗЂЊЋНнђћҢңҤҥҺһӉӊ",I:"ÌÍÎÏ",i:"ìíîïĨĩĪīĬĭĮįİıƖƗȈȉȊȋΊΐΪίιϊІЇії",j:"ĴĵǰȷɈɉϳЈј",k:"ĶķĸƘƙǨǩΚκЌЖКжкќҚқҜҝҞҟҠҡ",l:"ĹĺĻļĽľĿŀŁłƚƪǀǏǐȴȽΙӀӏ",m:"ΜϺϻМмӍӎ",n:"ÑñŃńŅņŇňʼnŊŋƝƞǸǹȠȵΝΠήηϞЍИЙЛПийлпѝҊҋӅӆӢӣӤӥπ",o:"ÒÓÔÕÖØðòóôõöøŌōŎŏŐőƟƠơǑǒǪǫǬǭǾǿȌȍȎȏȪȫȬȭȮȯȰȱΌΘΟθοσόϕϘϙϬϭϴОФоѲѳӦӧӨөӪӫ",p:"ƤƿΡρϷϸϼРрҎҏÞ",q:"Ɋɋ",r:"ŔŕŖŗŘřƦȐȑȒȓɌɍЃГЯгяѓҐґ",s:"ŚśŜŝŞşŠšƧƨȘșȿЅѕ",t:"ŢţŤťŦŧƫƬƭƮȚțȶȾΓΤτϮТт",u:"µÙÚÛÜùúûüŨũŪūŬŭŮůŰűŲųƯưƱƲǓǔǕǖǗǘǙǚǛǜȔȕȖȗɄΰμυϋύ",v:"νѴѵѶѷ",w:"ŴŵƜωώϖϢϣШЩшщѡѿ",x:"×ΧχϗϰХхҲҳӼӽӾӿ",y:"ÝýÿŶŷŸƳƴȲȳɎɏΎΥΫγψϒϓϔЎУучўѰѱҮүҰұӮӯӰӱӲӳ",z:"ŹźŻżŽžƩƵƶȤȥɀΖζ"},a$1={};Object.keys(r$1).forEach((function(e){r$1[e].split("").forEach((function(t){a$1[t]=e}))}));var n$1=e=>{let t=e.split("");return t.forEach(((e,n)=>{a$1[e]&&(t[n]=a$1[e])})),t.join("")};const i$1=/([A-Z]\.)+[A-Z]?,?$/,o$1=/^[A-Z]\.,?$/,s$1=/[A-Z]{2,}('s|,)?$/,l$1=/([a-z]\.)+[a-z]\.?$/;var u$1=function(e){return!0===i$1.test(e)||!0===l$1.test(e)||!0===o$1.test(e)||!0===s$1.test(e)};const c$2=n$1,h$1=u$1,d$1=/[a-z\u00C0-\u00FF] ?\/ ?[a-z\u00C0-\u00FF]/,g$1=function(e){let t=e=(e=(e=e||"").toLowerCase()).trim();return e=c$2(e),!0===d$1.test(e)&&(e=e.replace(/\/.*/,"")),e=(e=(e=(e=(e=(e=(e=e.replace(/^[#@]/,"")).replace(/[,;.!?]+$/,"")).replace(/[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]+/g,"'")).replace(/[\u0022\u00AB\u00BB\u201C\u201D\u201E\u201F\u2033\u2034\u2036\u2037\u2E42\u301D\u301E\u301F\uFF02]+/g,'"')).replace(/\u2026/g,"...")).replace(/\u2013/g,"-")).replace(/([aeiou][ktrp])in$/,"$1ing"),!0===/^(re|un)-?[^aeiou]./.test(e)&&(e=e.replace("-","")),h$1(e)&&(e=e.replace(/\./g,"")),!1===/^[:;]/.test(e)&&(e=(e=(e=e.replace(/\.{3,}$/g,"")).replace(/[",\.!:;\?\)]+$/g,"")).replace(/^['"\(]+/g,"")),""===(e=(e=e.replace(/[\u200B-\u200D\uFEFF]/g,"")).trim())&&(e=t),e.replace(/([0-9]),([0-9])/g,"$1$2")},p$1=function(e){return(e=e.replace(/['’]s$/,"")).replace(/s['’]$/,"s")},m$1=/^[ \n\t\.\[\](){}⟨⟩:,،、‒–—―…!‹›«»‐\-?‘’;\/⁄·&*•^†‡°¡¿※№÷׺ª%‰+−=‱¶′″‴§~\|‖¦©℗®℠™¤₳฿\u0022\uFF02\u0027\u201C\u201F\u201B\u201E\u2E42\u201A\u2035\u2036\u2037\u301D\u0060\u301F]+/,f$1=/[ \n\t\.'\[\](){}⟨⟩:,،、‒–—―…!‹›«»‐\-?‘’;\/⁄·&*@•^†‡°¡¿※#№÷׺ª‰+−=‱¶′″‴§~\|‖¦©℗®℠™¤₳฿\u0022\uFF02\u201D\u00B4\u301E]+$/,b$1=/\//,y$1=/['’]/,v$1=/^[a-z]\.([a-z]\.)+/i,w$1=/^[-+\.][0-9]/,k$1=/^'[0-9]{2}/;var A$1=e=>{let t=e,n="",r="";""===(e=(e=e.replace(m$1,(t=>(n=t,"-"!==n&&"+"!==n&&"."!==n||!w$1.test(e)?"'"===n&&k$1.test(e)?(n="",t):"":(n="",t))))).replace(f$1,(a=>(r=a,y$1.test(a)&&/[sn]['’]$/.test(t)&&!1===y$1.test(n)?(r=r.replace(y$1,""),"'"):!0===v$1.test(e)?(r=r.replace(/\./,""),"."):""))))&&(t=t.replace(/ *$/,(e=>(r=e||"",""))),e=t,n="");let a=g$1(e);const i={text:e,clean:a,reduced:p$1(a),pre:n,post:r};return b$1.test(e)&&e.split(b$1).forEach((e=>{i.alias=i.alias||{},i.alias[e.trim()]=!0})),i},D$1={};!function(e){const t=/^[A-Z][a-z'\u00C0-\u00FF]/,n=/^[A-Z]+s?$/;e.toUpperCase=function(){return this.text=this.text.toUpperCase(),this},e.toLowerCase=function(){return this.text=this.text.toLowerCase(),this},e.toTitleCase=function(){return this.text=this.text.replace(/^ *[a-z\u00C0-\u00FF]/,(e=>e.toUpperCase())),this},e.isUpperCase=function(){return n.test(this.text)},e.isTitleCase=function(){return t.test(this.text)},e.titleCase=e.isTitleCase}(D$1);var $$1={};!function(e){const t=/(\u0022|\uFF02|\u0027|\u201C|\u2018|\u201F|\u201B|\u201E|\u2E42|\u201A|\u00AB|\u2039|\u2035|\u2036|\u2037|\u301D|\u0060|\u301F)/,n=/(\u0022|\uFF02|\u0027|\u201D|\u2019|\u201D|\u2019|\u201D|\u201D|\u2019|\u00BB|\u203A|\u2032|\u2033|\u2034|\u301E|\u00B4|\u301E)/;e.hasPost=function(e){return-1!==this.post.indexOf(e)},e.hasPre=function(e){return-1!==this.pre.indexOf(e)},e.hasQuote=function(){return t.test(this.pre)||n.test(this.post)},e.hasQuotation=e.hasQuote,e.hasComma=function(){return this.hasPost(",")},e.hasPeriod=function(){return!0===this.hasPost(".")&&!1===this.hasPost("...")},e.hasExclamation=function(){return this.hasPost("!")},e.hasQuestionMark=function(){return this.hasPost("?")||this.hasPost("¿")},e.hasEllipses=function(){return this.hasPost("..")||this.hasPost("…")||this.hasPre("..")||this.hasPre("…")},e.hasSemicolon=function(){return this.hasPost(";")},e.hasSlash=function(){return/\//.test(this.text)},e.hasHyphen=function(){const e=/^(-|–|—)$/;return e.test(this.post)||e.test(this.pre)},e.hasDash=function(){const e=/ (-|–|—) /;return e.test(this.post)||e.test(this.pre)},e.hasContraction=function(){return Boolean(this.implicit)},e.addPunctuation=function(e){return","!==e&&";"!==e||(this.post=this.post.replace(e,"")),this.post=e+this.post,this}}($$1);var P$1={};const E$1=function(e,t,n=3){if(e===t)return 1;if(e.lengthn?r:n)+1;if(Math.abs(n-r)>(a||100))return a||100;let i,o,s,l,u,c,p=[];for(let e=0;e4)return n;s=t[i-1],l=o===s?0:1,u=p[a-1][i]+1,(c=p[a][i-1]+1)1&&i>1&&o===t[i-2]&&e[a-2]===s&&(c=p[a-2][i-2]+l)t.fuzzy)return!0;if(!0===t.soft&&(n=E$1(t.word,e.root),n>t.fuzzy))return!0}return t.word===e.clean||t.word===e.text||t.word===e.reduced}return void 0!==t.tag?!0===e.tags[t.tag]:void 0!==t.method?"function"==typeof e[t.method]&&!0===e[t.method]():void 0!==t.regex?t.regex.test(e.clean):void 0!==t.fastOr?!(!e.implicit||!0!==t.fastOr.hasOwnProperty(e.implicit))||t.fastOr.hasOwnProperty(e.reduced)||t.fastOr.hasOwnProperty(e.text):void 0!==t.choices&&("and"===t.operator?t.choices.every((t=>H$1(e,t,n,r))):t.choices.some((t=>H$1(e,t,n,r))))}(e,t,n,r);return!0===t.negative?!a:a};const j$1=H$1,N$1=u$1,x$1={};P$1.doesMatch=function(e,t,n){return j$1(this,e,t,n)},P$1.isAcronym=function(){return N$1(this.text)},P$1.isImplicit=function(){return""===this.text&&Boolean(this.implicit)},P$1.isKnown=function(){return Object.keys(this.tags).some((e=>!0!==x$1[e]))},P$1.setRoot=function(e){let t=e.transforms,n=this.implicit||this.clean;if(this.tags.Plural&&(n=t.toSingular(n,e)),this.tags.Verb&&!this.tags.Negative&&!this.tags.Infinitive){let r=null;this.tags.PastTense?r="PastTense":this.tags.Gerund?r="Gerund":this.tags.PresentTense?r="PresentTense":this.tags.Participle?r="Participle":this.tags.Actor&&(r="Actor"),n=t.toInfinitive(n,e,r)}this.root=n};var F$1={};const C$1=n$1,B$1=/[\s-]/,G$1=/^[A-Z-]+$/;F$1.textOut=function(e,t,n){e=e||{};let r=this.text,a=this.pre,i=this.post;return!0===e.reduced&&(r=this.reduced||""),!0===e.root&&(r=this.root||""),!0===e.implicit&&this.implicit&&(r=this.implicit||""),!0===e.normal&&(r=this.clean||this.text||""),!0===e.root&&(r=this.root||this.reduced||""),!0===e.unicode&&(r=C$1(r)),!0===e.titlecase&&(this.tags.ProperNoun&&!this.titleCase()||(this.tags.Acronym?r=r.toUpperCase():G$1.test(r)&&!this.tags.Acronym&&(r=r.toLowerCase()))),!0===e.lowercase&&(r=r.toLowerCase()),!0===e.acronyms&&this.tags.Acronym&&(r=r.replace(/\./g,"")),!0!==e.whitespace&&!0!==e.root||(a="",i=" ",!1!==B$1.test(this.post)&&!e.last||this.implicit||(i="")),!0!==e.punctuation||e.root||(!0===this.hasPost(".")?i="."+i:!0===this.hasPost("?")?i="?"+i:!0===this.hasPost("!")?i="!"+i:!0===this.hasPost(",")?i=","+i:!0===this.hasEllipses()&&(i="..."+i)),!0!==t&&(a=""),!0!==n&&(i=""),!0===e.abbreviations&&this.tags.Abbreviation&&(i=i.replace(/^\./,"")),a+r+i};var z$1={};const I$1={Auxiliary:1,Possessive:1},O$1=function(e,t){let n=Object.keys(e.tags);const r=t.tags;return n=n.sort(((e,t)=>I$1[t]||!r[t]?-1:r[t]?r[e]?r[e].lineage.length>r[t].lineage.length?1:r[e].isA.length>r[t].isA.length?-1:0:0:1)),n},T$2={text:!0,tags:!0,implicit:!0,whitespace:!0,clean:!1,id:!1,index:!1,offset:!1,bestTag:!1};z$1.json=function(e,t){e=e||{};let n={};return(e=Object.assign({},T$2,e)).text&&(n.text=this.text),e.normal&&(n.normal=this.clean),e.tags&&(n.tags=Object.keys(this.tags)),e.clean&&(n.clean=this.clean),(e.id||e.offset)&&(n.id=this.id),e.implicit&&null!==this.implicit&&(n.implicit=this.implicit),e.whitespace&&(n.pre=this.pre,n.post=this.post),e.bestTag&&(n.bestTag=O$1(this,t)[0]),n};var V$1=Object.assign({},D$1,$$1,P$1,F$1,z$1),M$1={},J$1={};function L$1(){return"undefined"!=typeof window&&window.document}const S$1=function(e,t){for(e=e.toString();e.lengthe.charAt(0).toUpperCase()+e.substr(1);const _$1=J$1,K$1=function(e,t,n,r){let a=r.tags;if(""===t||"."===t||"-"===t)return;if("#"===t[0]&&(t=t.replace(/^#/,"")),t=_$1.titleCase(t),!0===e.tags[t])return;const i=r.isVerbose();!0===i&&_$1.logTag(e,t,n),e.tags[t]=!0,!0===a.hasOwnProperty(t)&&(a[t].isA.forEach((t=>{e.tags[t]=!0,!0===i&&_$1.logTag(e,"→ "+t)})),e.unTag(a[t].notA,"←",r))},q$1=J$1,W$1=/^[a-z]/,R$1=function(e,t,n,r){const a=r.isVerbose();if("*"===t)return e.tags={},e;var i;t=t.replace(/^#/,""),!0===W$1.test(t)&&(t=(i=t).charAt(0).toUpperCase()+i.substr(1)),!0===e.tags[t]&&(delete e.tags[t],!0===a&&q$1.logUntag(e,t,n));const o=r.tags;if(o[t]){let n=o[t].lineage;for(let t=0;te.clone()));return t.forEach(((e,n)=>{this.pool.add(e),t[n+1]&&(e.next=t[n+1].id),t[n-1]&&(e.prev=t[n-1].id)})),this.buildFrom(t[0].id,t.length)},lastTerm:function(){let e=this.terms();return e[e.length-1]},hasId:function(e){if(0===this.length||!e)return!1;if(this.start===e)return!0;if(this.cache.terms){let t=this.cache.terms;for(let n=0;n""!==e.text)).length},fullSentence:function(){let e=this.terms(0);for(;e.prev;)e=this.pool.get(e.prev);let t=e.id,n=1;for(;e.next;)e=this.pool.get(e.next),n+=1;return this.buildFrom(t,n)}},oe$1={text:function(e={},t,n){"string"==typeof e&&(e="normal"===e?{whitespace:!0,unicode:!0,lowercase:!0,punctuation:!0,acronyms:!0,abbreviations:!0,implicit:!0,normal:!0}:"clean"===e?{titlecase:!1,lowercase:!0,punctuation:!0,whitespace:!0,unicode:!0,implicit:!0,normal:!0}:"reduced"===e?{punctuation:!1,titlecase:!1,lowercase:!0,whitespace:!0,unicode:!0,implicit:!0,reduced:!0}:"implicit"===e?{punctuation:!0,implicit:!0,whitespace:!0,trim:!0}:"root"===e?{titlecase:!1,lowercase:!0,punctuation:!0,whitespace:!0,unicode:!0,implicit:!0,root:!0}:{});let r=this.terms(),a=!1;r[0]&&null===r[0].prev&&null===r[r.length-1].next&&(a=!0);let i=r.reduce(((i,o,s)=>{if(0===s&&""===o.text&&null!==o.implicit&&!e.implicit)return i;e.last=n&&s===r.length-1;let l=!0,u=!0;return!1===a&&(0===s&&t&&(l=!1),s===r.length-1&&n&&(u=!1)),i+o.textOut(e,l,u)}),"");return!0===a&&n&&(i=i.replace(/ +$/,"")),!0===e.trim&&(i=i.trim()),i}},se$1={trim:function(){let e=this.terms();if(e.length>0){e[0].pre=e[0].pre.replace(/^\s+/,"");let t=e[e.length-1];t.post=t.post.replace(/\s+$/,"")}return this}},le$1={};const ue$1=/[.?!]\s*$/,ce$1=function(e,t){t[0].pre=e[0].pre;let n=e[e.length-1],r=t[t.length-1];r.post=function(e,t){return ue$1.test(t)?t+e.match(/\s*$/):e}(n.post,r.post),n.post="",""===n.post&&(n.post+=" ")},he$1=/ /,de$1=function(e,t,n){let r=e.terms(),a=t.terms();ce$1(r,a),function(e,t,n){let r=e[e.length-1],a=t[t.length-1],i=r.next;r.next=t[0].id,a.next=i,i&&(n.get(i).prev=a.id);let o=e[0].id;o&&(t[0].prev=o)}(r,a,e.pool);let i=[e],o=e.start,s=[n];return s=s.concat(n.parents()),s.forEach((e=>{let t=e.list.filter((e=>e.hasId(o)));i=i.concat(t)})),i=function(e){return e.filter(((t,n)=>e.indexOf(t)===n))}(i),i.forEach((e=>{e.length+=t.length})),e.cache={},e},ge$1=function(e,t,n){const r=e.start;let a=t.terms();!function(e){let t=e[e.length-1];!1===he$1.test(t.post)&&(t.post+=" ")}(a),function(e,t,n){let r=n[n.length-1];r.next=e.start;let a=e.pool,i=a.get(e.start);i.prev&&(a.get(i.prev).next=t.start),n[0].prev=e.terms(0).prev,e.terms(0).prev=r.id}(e,t,a);let i=[e],o=[n];return o=o.concat(n.parents()),o.forEach((e=>{let n=e.list.filter((e=>e.hasId(r)||e.hasId(t.start)));i=i.concat(n)})),i=function(e){return e.filter(((t,n)=>e.indexOf(t)===n))}(i),i.forEach((e=>{e.length+=t.length,e.start===r&&(e.start=t.start),e.cache={}})),e},pe$1=function(e,t){let n=t.pool(),r=e.terms(),a=n.get(r[0].prev)||{},i=n.get(r[r.length-1].next)||{};r[0].implicit&&a.implicit&&(a.set(a.implicit),a.post+=" "),function(e,t,n,r){let a=e.parents();a.push(e),a.forEach((e=>{let a=e.list.find((e=>e.hasId(t)));a&&(a.length-=n,a.start===t&&(a.start=r.id),a.cache={})})),e.list=e.list.filter((e=>!(!e.start||!e.length)))}(t,e.start,e.length,i),a&&(a.next=i.id),i&&(i.prev=a.id)};le$1.append=function(e,t){return de$1(this,e,t),this},le$1.prepend=function(e,t){return ge$1(this,e,t),this},le$1.delete=function(e){return pe$1(this,e),this},le$1.replace=function(e,t){let n=this.length;de$1(this,e,t);let r=this.buildFrom(this.start,this.length);r.length=n,pe$1(r,t)},le$1.splitOn=function(e){let t=this.terms(),n={before:null,match:null,after:null},r=t.findIndex((t=>t.id===e.start));if(-1===r)return n;let a=t.slice(0,r);a.length>0&&(n.before=this.buildFrom(a[0].id,a.length));let i=t.slice(r,r+e.length);i.length>0&&(n.match=this.buildFrom(i[0].id,i.length));let o=t.slice(r+e.length,t.length);return o.length>0&&(n.after=this.buildFrom(o[0].id,o.length,this.pool)),n};var me$2={json:function(e={},t){let n={};return e.text&&(n.text=this.text()),e.normal&&(n.normal=this.text("normal")),e.clean&&(n.clean=this.text("clean")),e.reduced&&(n.reduced=this.text("reduced")),e.implicit&&(n.implicit=this.text("implicit")),e.root&&(n.root=this.text("root")),e.trim&&(n.text&&(n.text=n.text.trim()),n.normal&&(n.normal=n.normal.trim()),n.reduced&&(n.reduced=n.reduced.trim())),e.terms&&(!0===e.terms&&(e.terms={}),n.terms=this.terms().map((n=>n.json(e.terms,t)))),n}},fe$1={lookAhead:function(e){e||(e=".*");let t=this.pool,n=[];const r=function(e){let a=t.get(e);a&&(n.push(a),a.prev&&r(a.next))};let a=this.terms(),i=a[a.length-1];return r(i.next),0===n.length?[]:this.buildFrom(n[0].id,n.length).match(e)},lookBehind:function(e){e||(e=".*");let t=this.pool,n=[];const r=function(e){let a=t.get(e);a&&(n.push(a),a.prev&&r(a.prev))};let a=t.get(this.start);return r(a.prev),0===n.length?[]:this.buildFrom(n[n.length-1].id,n.length).match(e)}},be$1=Object.assign({},ie$1,oe$1,se$1,le$1,me$2,fe$1),ye$1={},ve$1,we$1=function(e,t){if(0===t.length)return!0;for(let e=0;e0)return!0;if(!0===n.anything&&!0===n.negative)return!0}return!1},ke$1={};(ve$1=ke$1).getGreedy=function(e,t){let n=Object.assign({},e.regs[e.r],{start:!1,end:!1}),r=e.t;for(;e.t{let a=0,i=e.t+r+t+a;if(void 0===e.terms[i])return!1;let o=e.terms[i].doesMatch(n,i+e.start_i,e.phrase_length);if(!0===o&&!0===n.greedy)for(let t=1;t{let r=n.every(((t,n)=>{let r=e.t+n;return void 0!==e.terms[r]&&e.terms[r].doesMatch(t,r,e.phrase_length)}));return!0===r&&n.length>t&&(t=n.length),r}))&&t},ve$1.getGroup=function(e,t,n){if(e.groups[e.groupId])return e.groups[e.groupId];const r=e.terms[t].id;return e.groups[e.groupId]={group:String(n),start:r,length:0},e.groups[e.groupId]};const Ae$1=t$1,De=ke$1;var $e$1=function(e,t,n,r){let a={t:0,terms:e,r:0,regs:t,groups:{},start_i:n,phrase_length:r,hasGroup:!1,groupId:null,previousGroup:null};for(;a.r!e.optional)))break;return null}if(!0===e.anything&&!0===e.greedy){let n=De.greedyTo(a,t[a.r+1]);if(null===n||0===n)return null;if(void 0!==e.min&&n-a.te.max){a.t=a.t+e.max;continue}!0===a.hasGroup&&(De.getGroup(a,a.t,e.named).length=n-a.t),a.t=n;continue}if(void 0!==e.choices&&"or"===e.operator){let t=De.doOrBlock(a);if(t){if(!0===e.negative)return null;!0===a.hasGroup&&(De.getGroup(a,a.t,e.named).length+=t),a.t+=t;continue}if(!e.optional)return null}if(void 0!==e.choices&&"and"===e.operator){let t=De.doAndBlock(a);if(t){if(!0===e.negative)return null;!0===a.hasGroup&&(De.getGroup(a,a.t,e.named).length+=t),a.t+=t;continue}if(!e.optional)return null}let n=a.terms[a.t],i=n.doesMatch(e,a.start_i+a.t,a.phrase_length);if(!0===e.anything||!0===i||De.isEndGreedy(e,a)){let i=a.t;if(e.optional&&t[a.r+1]&&e.negative)continue;if(e.optional&&t[a.r+1]){let r=n.doesMatch(t[a.r+1],a.start_i+a.t,a.phrase_length);if(e.negative||r){let e=a.terms[a.t+1];e&&e.doesMatch(t[a.r+1],a.start_i+a.t,a.phrase_length)||(a.r+=1)}}if(a.t+=1,!0===e.end&&a.t!==a.terms.length&&!0!==e.greedy)return null;if(!0===e.greedy){if(a.t=De.getGreedy(a,t[a.r+1]),null===a.t)return null;if(e.min&&e.min>a.t)return null;if(!0===e.end&&a.start_i+a.t!==r)return null}if(!0===a.hasGroup){const t=De.getGroup(a,i,e.named);a.t>1&&e.greedy?t.length+=a.t-i:t.length++}}else{if(e.negative){let t=Object.assign({},e);if(t.negative=!1,!0===a.terms[a.t].doesMatch(t,a.start_i+a.t,a.phrase_length))return null}if(!0!==e.optional){if(a.terms[a.t].isImplicit()&&t[a.r-1]&&a.terms[a.t+1]){if(a.terms[a.t-1]&&a.terms[a.t-1].implicit===t[a.r-1].word)return null;if(a.terms[a.t+1].doesMatch(e,a.start_i+a.t,a.phrase_length)){a.t+=2;continue}}return null}}}return{match:a.terms.slice(0,a.t),groups:a.groups}},Pe$1=function(e,t,n){if(!n||0===n.length)return n;if(t.some((e=>e.end))){let t=e[e.length-1];n=n.filter((({match:e})=>-1!==e.indexOf(t)))}return n};const Ee$1=/(?:^|\s)([\!\[\^]*(?:<[^<]*>)?\/.*?[^\\\/]\/[\?\]\+\*\$~]*)(?:\s|$)/,He=/([\!\[\^]*(?:<[^<]*>)?\([^\)]+[^\\\)]\)[\?\]\+\*\$~]*)(?:\s|$)/,je$1=/ /g,Ne$1=e=>/^[\!\[\^]*(<[^<]*>)?\//.test(e)&&/\/[\?\]\+\*\$~]*$/.test(e),xe$1=function(e){return(e=e.map((e=>e.trim()))).filter((e=>e))};var Fe$1=function(e){let t=e.split(Ee$1),n=[];t.forEach((e=>{Ne$1(e)?n.push(e):n=n.concat(e.split(He))})),n=xe$1(n);let r=[];return n.forEach((e=>{(e=>/^[\!\[\^]*(<[^<]*>)?\(/.test(e)&&/\)[\?\]\+\*\$~]*$/.test(e))(e)||Ne$1(e)?r.push(e):r=r.concat(e.split(je$1))})),r=xe$1(r),r};const Ce$1=/\{([0-9]+,?[0-9]*)\}/,Be=/&&/,Ge=new RegExp(/^<\s*?(\S+)\s*?>/),ze$1=function(e){return e[e.length-1]},Ie=function(e){return e[0]},Oe$1=function(e){return e.substr(1)},Te=function(e){return e.substr(0,e.length-1)},Ve$1=function(e){return e=Oe$1(e),Te(e)},Me$1=function(e){let t={};for(let n=0;n<2;n+=1){if("$"===ze$1(e)&&(t.end=!0,e=Te(e)),"^"===Ie(e)&&(t.start=!0,e=Oe$1(e)),("["===Ie(e)||"]"===ze$1(e))&&(t.named=!0,"["===Ie(e)?t.groupType="]"===ze$1(e)?"single":"start":t.groupType="end",e=(e=e.replace(/^\[/,"")).replace(/\]$/,""),"<"===Ie(e))){const n=Ge.exec(e);n.length>=2&&(t.named=n[1],e=e.replace(n[0],""))}if("+"===ze$1(e)&&(t.greedy=!0,e=Te(e)),"*"!==e&&"*"===ze$1(e)&&"\\*"!==e&&(t.greedy=!0,e=Te(e)),"?"===ze$1(e)&&(t.optional=!0,e=Te(e)),"!"===Ie(e)&&(t.negative=!0,e=Oe$1(e)),"("===Ie(e)&&")"===ze$1(e)){Be.test(e)?(t.choices=e.split(Be),t.operator="and"):(t.choices=e.split("|"),t.operator="or"),t.choices[0]=Oe$1(t.choices[0]);let n=t.choices.length-1;t.choices[n]=Te(t.choices[n]),t.choices=t.choices.map((e=>e.trim())),t.choices=t.choices.filter((e=>e)),t.choices=t.choices.map((e=>e.split(/ /g).map(Me$1))),e=""}if("/"===Ie(e)&&"/"===ze$1(e))return e=Ve$1(e),t.regex=new RegExp(e),t;if("~"===Ie(e)&&"~"===ze$1(e))return e=Ve$1(e),t.soft=!0,t.word=e,t}return!0===Ce$1.test(e)&&(e=e.replace(Ce$1,((e,n)=>{let r=n.split(/,/g);return 1===r.length?(t.min=Number(r[0]),t.max=Number(r[0])):(t.min=Number(r[0]),t.max=Number(r[1]||999)),t.greedy=!0,t.optional=!0,""}))),"#"===Ie(e)?(t.tag=Oe$1(e),t.tag=(n=t.tag).charAt(0).toUpperCase()+n.substr(1),t):"@"===Ie(e)?(t.method=Oe$1(e),t):"."===e?(t.anything=!0,t):"*"===e?(t.anything=!0,t.greedy=!0,t.optional=!0,t):(e&&(e=(e=e.replace("\\*","*")).replace("\\.","."),t.word=e.toLowerCase()),t);var n},Je=Fe$1,Le=Me$1,Se=function(e,t={}){return e.filter((e=>e.groupType)).length>0&&(e=function(e){let t,n=!1,r=-1;for(let a=0;a{if(void 0!==e.choices&&!0===e.choices.every((e=>{if(1!==e.length)return!1;let t=e[0];return void 0!==t.word&&!0!==t.negative&&!0!==t.optional&&!0!==t.method}))){let t={};e.choices.forEach((e=>{t[e[0].word]=!0})),e.fastOr=t,delete e.choices}return e}))}(e)),e};var _e=function(e,t={}){if(null==e||""===e)return[];if("object"==typeof e){if(function(e){return"[object Array]"===Object.prototype.toString.call(e)}(e)){if(0===e.length||!e[0])return[];if("object"==typeof e[0])return e;if("string"==typeof e[0])return function(e){return[{choices:e.map((e=>[{word:e}])),operator:"or"}]}(e)}return e&&"Doc"===e.isA?function(e){if(!e||!e.list||!e.list[0])return[];let t=[];return e.list.forEach((e=>{let n=[];e.terms().forEach((e=>{n.push(e.id)})),t.push(n)})),[{idBlocks:t}]}(e):[]}"number"==typeof e&&(e=String(e));let n=Je(e);return n=n.map((e=>Le(e))),n=Se(n,t),n=function(e,t){return!0===t.fuzzy&&(t.fuzzy=.85),"number"==typeof t.fuzzy&&(e=e.map((e=>(t.fuzzy>0&&e.word&&(e.fuzzy=t.fuzzy),e.choices&&e.choices.forEach((e=>{e.forEach((e=>{e.fuzzy=t.fuzzy}))})),e)))),e}(n,t),n};const Ke=we$1,qe=$e$1,We=Pe$1,Re=_e,Ue=function(e,t){let n=[],r=t[0].idBlocks;for(let t=0;t{0!==r.length&&r.every(((n,r)=>e[t+r].id===n))&&(n.push({match:e.slice(t,t+r.length)}),t+=r.length-1)}));return n};var Qe=function(e,t,n=!1){if("string"==typeof t&&(t=Re(t)),!0===Ke(e,t))return[];const r=t.filter((e=>!0!==e.optional&&!0!==e.negative)).length;let a=e.terms(),i=[];if(t[0].idBlocks){let e=Ue(a,t);if(e&&e.length>0)return We(a,t,e)}if(!0===t[0].start){let e=qe(a,t,0,a.length);return e&&e.match&&e.match.length>0&&(e.match=e.match.filter((e=>e)),i.push(e)),We(a,t,i)}for(let e=0;ea.length);e+=1){let r=qe(a.slice(e),t,e,a.length);if(r&&r.match&&r.match.length>0&&(e+=r.match.length-1,r.match=r.match.filter((e=>e)),i.push(r),!0===n))return We(a,t,i)}return We(a,t,i)};const Ze=Qe,Xe=Qe,Ye=function(e,t){let n={};Ze(e,t).forEach((({match:e})=>{e.forEach((e=>{n[e.id]=!0}))}));let r=e.terms(),a=[],i=[];return r.forEach((e=>{!0!==n[e.id]?i.push(e):i.length>0&&(a.push(i),i=[])})),i.length>0&&a.push(i),a};ye$1.match=function(e,t=!1){let n=Xe(this,e,t);return n=n.map((({match:e,groups:t})=>{let n=this.buildFrom(e[0].id,e.length,t);return n.cache.terms=e,n})),n},ye$1.has=function(e){return Xe(this,e,!0).length>0},ye$1.not=function(e){let t=Ye(this,e);return t=t.map((e=>this.buildFrom(e[0].id,e.length))),t},ye$1.canBe=function(e,t){let n=[],r=this.terms(),a=!1;for(let i=0;ie.length>0)).map((e=>this.buildFrom(e[0].id,e.length))),n};const et=be$1,tt=ye$1;class rt{constructor(e,t,n){this.start=e,this.length=t,this.isA="Phrase",Object.defineProperty(this,"pool",{enumerable:!1,writable:!0,value:n}),Object.defineProperty(this,"cache",{enumerable:!1,writable:!0,value:{}}),Object.defineProperty(this,"groups",{enumerable:!1,writable:!0,value:{}})}}rt.prototype.buildFrom=function(e,t,n){let r=new rt(e,t,this.pool);return n&&Object.keys(n).length>0?r.groups=n:r.groups=this.groups,r},Object.assign(rt.prototype,tt),Object.assign(rt.prototype,et);const at={term:"terms"};Object.keys(at).forEach((e=>rt.prototype[e]=rt.prototype[at[e]]));var nt=rt;class it{constructor(e={}){Object.defineProperty(this,"words",{enumerable:!1,value:e})}add(e){return this.words[e.id]=e,this}get(e){return this.words[e]}remove(e){delete this.words[e]}merge(e){return Object.assign(this.words,e.words),this}stats(){return{words:Object.keys(this.words).length}}}it.prototype.clone=function(){let e=Object.keys(this.words).reduce(((e,t)=>{let n=this.words[t].clone();return e[n.id]=n,e}),{});return new it(e)};var ot=it,st=e=>{e.forEach(((t,n)=>{n>0&&(t.prev=e[n-1].id),e[n+1]&&(t.next=e[n+1].id)}))};const lt=/(\S.+?[.!?\u203D\u2E18\u203C\u2047-\u2049])(?=\s+|$)/g,ut=/\S/,ct=/[ .][A-Z]\.? *$/i,ht=/(?:\u2026|\.{2,}) *$/,dt=/((?:\r?\n|\r)+)/,gt=/[a-z0-9\u00C0-\u00FF\u00a9\u00ae\u2000-\u3300\ud000-\udfff]/i,pt=/^\s+/,mt=function(e,t,n,r){if(r.hasLetter=function(e,t){return t||gt.test(e)}(t,r.hasLetter),!r.hasLetter)return!1;if(function(e,t){return-1!==t.indexOf(".")&&ct.test(e)}(e,t))return!1;if(function(e,t){return-1!==t.indexOf(".")&&ht.test(e)}(e,t))return!1;let a=e.replace(/[.!?\u203D\u2E18\u203C\u2047-\u2049] *$/,"").split(" "),i=a[a.length-1].toLowerCase();return!n.hasOwnProperty(i)};var ft=function(e,t){let n=t.cache.abbreviations;e=e||"";let r=[],a=[];if(!(e=String(e))||"string"!=typeof e||!1===ut.test(e))return r;let i=function(e){let t=[],n=e.split(dt);for(let e=0;e0&&(r.push(t),o=a[e+1]||"",s.hasLetter=!1),a[e]=""}if(0===r.length)return[e];for(let e=1;e(e[t]=!0,e)),{});const At=function(e){return!0!==/^(re|un|micro|macro|trans|bi|mono|over)-?[^aeiou]./.test(e)&&(!0!==/^([a-z\u00C0-\u00FF/]+)(-|–|—)(like|ish|less|able)/i.test(e)&&(!0===/^([a-z\u00C0-\u00FF`"'/]+)(-|–|—)([a-z0-9\u00C0-\u00FF].*)/i.test(e)||!0===/^([0-9]{1,4})(-|–|—)([a-z\u00C0-\u00FF`"'/-]+$)/i.test(e)))},Dt=function(e){let t=[];const n=e.split(/[-–—]/);let r="-",a=e.match(/[-–—]/);a&&a[0]&&(r=a);for(let e=0;e0?(t[t.length-1]+=a,t.push(r)):t.push(a+r),a=""):a+=r}return a&&(0===t.length&&(t[0]=""),t[t.length-1]+=a),t=function(e){for(let t=1;te)),t};var xt=function(e="",t,n){let r=null;return"string"!=typeof e&&("number"==typeof e?e=String(e):function(e){return"[object Array]"===Object.prototype.toString.call(e)}(e)&&(r=e)),r=r||jt(e,t),r=r.map((e=>Nt(e))),n=n||new Et,r.map((e=>{e=e.map((e=>{let t=new $t(e);return n.add(t),t})),Ht(e);let t=new Pt(e[0].id,e.length,n);return t.cache.terms=e,t}))};const Ft=ne$1,Ct=nt,Bt=ot,Gt=st;var zt=function(e,t){let n=new Bt;return e.map(((e,r)=>{let a=e.terms.map(((a,i)=>{let o=new Ft(a.text);return o.pre=void 0!==a.pre?a.pre:"",void 0===a.post&&(a.post=" ",i>=e.terms.length-1&&(a.post=". ",r>=e.terms.length-1&&(a.post="."))),o.post=void 0!==a.post?a.post:" ",a.tags&&a.tags.forEach((e=>o.tag(e,"",t))),n.add(o),o}));return Gt(a),new Ct(a[0].id,a.length,n)}))};const It=["Person","Place","Organization"],Ot=["Noun","Verb","Adjective","Adverb","Value","QuestionWord"],Tt={Noun:"blue",Verb:"green",Negative:"green",Date:"red",Value:"red",Adjective:"magenta",Preposition:"cyan",Conjunction:"cyan",Determiner:"cyan",Adverb:"cyan"},Vt=function(e){return Object.keys(e).forEach((t=>{e[t].color?e[t].color=e[t].color:Tt[t]?e[t].color=Tt[t]:e[t].isA.some((n=>!!Tt[n]&&(e[t].color=Tt[n],!0)))})),e},Mt=function(e){return Object.keys(e).forEach((t=>{let n=e[t],r=n.isA.length;for(let t=0;tn.indexOf(e)===t))}(n.isA)})),e},Jt=function(e){let t=Object.keys(e);return t.forEach((n=>{let r=e[n];r.notA=r.notA||[],r.isA.forEach((t=>{if(e[t]&&e[t].notA){let n="string"==typeof e[t].notA?[e[t].isA]:e[t].notA||[];r.notA=r.notA.concat(n)}}));for(let a=0;an.indexOf(e)===t))}(r.notA)})),e},Lt=function(e){let t=Object.keys(e);return t.forEach((n=>{let r=e[n];r.lineage=[];for(let a=0;a{let n=e[t];n.isA=n.isA||[],"string"==typeof n.isA&&(n.isA=[n.isA]),n.notA=n.notA||[],"string"==typeof n.notA&&(n.notA=[n.notA])})),e}(e),e=Mt(e),e=Jt(e),e=Vt(e),Lt(e)};const _t={Noun:{notA:["Verb","Adjective","Adverb"]},Singular:{isA:"Noun",notA:"Plural"},ProperNoun:{isA:"Noun"},Person:{isA:["ProperNoun","Singular"],notA:["Place","Organization","Date"]},FirstName:{isA:"Person"},MaleName:{isA:"FirstName",notA:["FemaleName","LastName"]},FemaleName:{isA:"FirstName",notA:["MaleName","LastName"]},LastName:{isA:"Person",notA:["FirstName"]},NickName:{isA:"Person",notA:["FirstName","LastName"]},Honorific:{isA:"Noun",notA:["FirstName","LastName","Value"]},Place:{isA:"Singular",notA:["Person","Organization"]},Country:{isA:["Place","ProperNoun"],notA:["City"]},City:{isA:["Place","ProperNoun"],notA:["Country"]},Region:{isA:["Place","ProperNoun"]},Address:{isA:"Place"},Organization:{isA:["Singular","ProperNoun"],notA:["Person","Place"]},SportsTeam:{isA:"Organization"},School:{isA:"Organization"},Company:{isA:"Organization"},Plural:{isA:"Noun",notA:["Singular"]},Uncountable:{isA:"Noun"},Pronoun:{isA:"Noun",notA:It},Actor:{isA:"Noun",notA:It},Activity:{isA:"Noun",notA:["Person","Place"]},Unit:{isA:"Noun",notA:It},Demonym:{isA:["Noun","ProperNoun"],notA:It},Possessive:{isA:"Noun"}},Kt={Verb:{notA:["Noun","Adjective","Adverb","Value","Expression"]},PresentTense:{isA:"Verb",notA:["PastTense","FutureTense"]},Infinitive:{isA:"PresentTense",notA:["PastTense","Gerund"]},Imperative:{isA:"Infinitive"},Gerund:{isA:"PresentTense",notA:["PastTense","Copula","FutureTense"]},PastTense:{isA:"Verb",notA:["FutureTense"]},FutureTense:{isA:"Verb"},Copula:{isA:"Verb"},Modal:{isA:"Verb",notA:["Infinitive"]},PerfectTense:{isA:"Verb",notA:"Gerund"},Pluperfect:{isA:"Verb"},Participle:{isA:"PastTense"},PhrasalVerb:{isA:"Verb"},Particle:{isA:"PhrasalVerb"},Auxiliary:{notA:["Noun","Adjective","Value"]}},qt={Value:{notA:["Verb","Adjective","Adverb"]},Ordinal:{isA:"Value",notA:["Cardinal"]},Cardinal:{isA:"Value",notA:["Ordinal"]},Fraction:{isA:"Value",notA:["Noun"]},RomanNumeral:{isA:"Cardinal",notA:["Ordinal","TextValue"]},TextValue:{isA:"Value",notA:["NumericValue"]},NumericValue:{isA:"Value",notA:["TextValue"]},Money:{isA:"Cardinal"},Percent:{isA:"Value"}},Wt={Adjective:{notA:["Noun","Verb","Adverb","Value"]},Comparable:{isA:["Adjective"]},Comparative:{isA:["Adjective"]},Superlative:{isA:["Adjective"],notA:["Comparative"]},NumberRange:{},Adverb:{notA:["Noun","Verb","Adjective","Value"]},Date:{notA:["Verb","Adverb","Preposition","Adjective"]},Month:{isA:["Date","Singular"],notA:["Year","WeekDay","Time"]},WeekDay:{isA:["Date","Noun"]},Timezone:{isA:["Date","Noun"],notA:["Adjective","ProperNoun"]},Time:{isA:["Date"],notA:["AtMention"]},Determiner:{notA:Ot},Conjunction:{notA:Ot},Preposition:{notA:Ot},QuestionWord:{notA:["Determiner"]},Currency:{isA:["Noun"]},Expression:{notA:["Noun","Adjective","Verb","Adverb"]},Abbreviation:{},Url:{notA:["HashTag","PhoneNumber","Verb","Adjective","Value","AtMention","Email"]},PhoneNumber:{notA:["HashTag","Verb","Adjective","Value","AtMention","Email"]},HashTag:{},AtMention:{isA:["Noun"],notA:["HashTag","Verb","Adjective","Value","Email"]},Emoji:{notA:["HashTag","Verb","Adjective","Value","AtMention"]},Emoticon:{notA:["HashTag","Verb","Adjective","Value","AtMention"]},Email:{notA:["HashTag","Verb","Adjective","Value","AtMention"]},Acronym:{notA:["Plural","RomanNumeral"]},Negative:{notA:["Noun","Adjective","Value"]},Condition:{notA:["Verb","Adjective","Noun","Value"]}},Rt=St,Ut=function(e,t){Object.keys(e).forEach((n=>{t[n]=e[n]}))};var Qt=(()=>{let e={};return Ut(_t,e),Ut(Kt,e),Ut(qt,e),Ut(Wt,e),e=Rt(e),e})();const Zt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",Xt=Zt.split("").reduce((function(e,t,n){return e[t]=n,e}),{});var Yt=function(e){if(void 0!==Xt[e])return Xt[e];let t=0,n=1,r=36,a=1;for(;n=0;n--,a*=36){let r=e.charCodeAt(n)-48;r>10&&(r-=7),t+=r*a}return t};const er=function(e,t,n){const r=Yt(t);return r{let i=e.nodes[r];"!"===i[0]&&(t.push(a),i=i.slice(1));const o=i.split(/([A-Z0-9,]+)/g);for(let i=0;i{const n=t.split("¦");return e[n[0]]=n[1],e}),{}),n={};return Object.keys(t).forEach((function(e){const r=tr(t[e]);"true"===e&&(e=!0);for(let t=0;t{e[t]=["Abbreviation","Unit"]},Cardinal:(e,t)=>{e[t]=["TextValue","Cardinal"]},TextOrdinal:(e,t)=>{e[t]=["Ordinal","TextValue"],e[t+"s"]=["TextValue","Fraction"]},Singular:(e,t,n)=>{e[t]="Singular";let r=n.transforms.toPlural(t,n);e[r]=e[r]||"Plural"},Infinitive:(e,t,n)=>{e[t]="Infinitive";let r=n.transforms.conjugate(t,n),a=Object.keys(r);for(let t=0;t{e[t]="Comparable";let r=n.transforms.adjectives(t),a=Object.keys(r);for(let t=0;t{e[t]=["PhrasalVerb","Infinitive"];let r=t.split(" "),a=n.transforms.conjugate(r[0],n),i=Object.keys(a);for(let t=0;t{e[t]="Demonym";let r=n.transforms.toPlural(t,n);e[r]=e[r]||["Demonym","Plural"]}},or=function(e,t,n){Object.keys(e).forEach((r=>{let a=e[r];"Abbreviation"!==a&&"Unit"!==a||(n.cache.abbreviations[r]=!0);let i=r.split(" ");i.length>1&&(n.hasCompound[i[0]]=!0),void 0===ir[a]?void 0!==t[r]?("string"==typeof t[r]&&(t[r]=[t[r]]),"string"==typeof a?t[r].push(a):t[r]=t[r].concat(a)):t[r]=a:ir[a](t,r,n)}))};var sr={buildOut:function(e){let t=Object.assign({},nr);return Object.keys(rr).forEach((n=>{let r=ar(rr[n]);Object.keys(r).forEach((e=>{r[e]=n})),or(r,t,e)})),t},addWords:or},lr=function(e){let t=e.irregulars.nouns,n=Object.keys(t);for(let r=0;r{e.words[i[t]]=e.words[i[t]]||t,"Participle"===e.words[i[t]]&&(e.words[i[t]]=t)}))}};const ur={g:"Gerund",prt:"Participle",perf:"PerfectTense",pst:"PastTense",fut:"FuturePerfect",pres:"PresentTense",pluperf:"Pluperfect",a:"Actor"};let cr={act:{a:"_or"},ache:{pst:"ached",g:"aching"},age:{g:"ageing",pst:"aged",pres:"ages"},aim:{a:"_er",g:"_ing",pst:"_ed"},arise:{prt:"_n",pst:"arose"},babysit:{a:"_ter",pst:"babysat"},ban:{a:"",g:"_ning",pst:"_ned"},be:{a:"",g:"am",prt:"been",pst:"was",pres:"is"},beat:{a:"_er",g:"_ing",prt:"_en"},become:{prt:"_"},begin:{g:"_ning",prt:"begun",pst:"began"},being:{g:"are",pst:"were",pres:"are"},bend:{prt:"bent"},bet:{a:"_ter",prt:"_"},bind:{pst:"bound"},bite:{g:"biting",prt:"bitten",pst:"bit"},bleed:{pst:"bled",prt:"bled"},blow:{prt:"_n",pst:"blew"},boil:{a:"_er"},brake:{prt:"broken"},break:{pst:"broke"},breed:{pst:"bred"},bring:{pst:"brought",prt:"brought"},broadcast:{pst:"_"},budget:{pst:"_ed"},build:{pst:"built",prt:"built"},burn:{prt:"_ed"},burst:{prt:"_"},buy:{pst:"bought",prt:"bought"},can:{a:"",fut:"_",g:"",pst:"could",perf:"could",pluperf:"could",pres:"_"},catch:{pst:"caught"},choose:{g:"choosing",prt:"chosen",pst:"chose"},cling:{prt:"clung"},come:{prt:"_",pst:"came",g:"coming"},compete:{a:"competitor",g:"competing",pst:"_d"},cost:{pst:"_"},creep:{prt:"crept"},cut:{prt:"_"},deal:{pst:"_t",prt:"_t"},develop:{a:"_er",g:"_ing",pst:"_ed"},die:{g:"dying",pst:"_d"},dig:{g:"_ging",pst:"dug",prt:"dug"},dive:{prt:"_d"},do:{pst:"did",pres:"_es"},draw:{prt:"_n",pst:"drew"},dream:{prt:"_t"},drink:{prt:"drunk",pst:"drank"},drive:{g:"driving",prt:"_n",pst:"drove"},drop:{g:"_ping",pst:"_ped"},eat:{a:"_er",g:"_ing",prt:"_en",pst:"ate"},edit:{pst:"_ed",g:"_ing"},egg:{pst:"_ed"},fall:{prt:"_en",pst:"fell"},feed:{prt:"fed",pst:"fed"},feel:{a:"_er",pst:"felt"},fight:{pst:"fought",prt:"fought"},find:{pst:"found"},flee:{g:"_ing",prt:"fled"},fling:{prt:"flung"},fly:{prt:"flown",pst:"flew"},forbid:{pst:"forbade"},forget:{g:"_ing",prt:"forgotten",pst:"forgot"},forgive:{g:"forgiving",prt:"_n",pst:"forgave"},free:{a:"",g:"_ing"},freeze:{g:"freezing",prt:"frozen",pst:"froze"},get:{pst:"got",prt:"gotten"},give:{g:"giving",prt:"_n",pst:"gave"},go:{prt:"_ne",pst:"went",pres:"goes"},grow:{prt:"_n"},guide:{pst:"_d"},hang:{pst:"hung",prt:"hung"},have:{g:"having",pst:"had",prt:"had",pres:"has"},hear:{pst:"_d",prt:"_d"},hide:{prt:"hidden",pst:"hid"},hit:{prt:"_"},hold:{pst:"held",prt:"held"},hurt:{pst:"_",prt:"_"},ice:{g:"icing",pst:"_d"},imply:{pst:"implied",pres:"implies"},is:{a:"",g:"being",pst:"was",pres:"_"},keep:{prt:"kept"},kneel:{prt:"knelt"},know:{prt:"_n"},lay:{pst:"laid",prt:"laid"},lead:{pst:"led",prt:"led"},leap:{prt:"_t"},leave:{pst:"left",prt:"left"},lend:{prt:"lent"},lie:{g:"lying",pst:"lay"},light:{pst:"lit",prt:"lit"},log:{g:"_ging",pst:"_ged"},loose:{prt:"lost"},lose:{g:"losing",pst:"lost"},make:{pst:"made",prt:"made"},mean:{pst:"_t",prt:"_t"},meet:{a:"_er",g:"_ing",pst:"met",prt:"met"},miss:{pres:"_"},name:{g:"naming"},patrol:{g:"_ling",pst:"_led"},pay:{pst:"paid",prt:"paid"},prove:{prt:"_n"},puke:{g:"puking"},put:{prt:"_"},quit:{prt:"_"},read:{pst:"_",prt:"_"},ride:{prt:"ridden"},reside:{pst:"_d"},ring:{pst:"rang",prt:"rung"},rise:{fut:"will have _n",g:"rising",prt:"_n",pst:"rose",pluperf:"had _n"},rub:{g:"_bing",pst:"_bed"},run:{g:"_ning",prt:"_",pst:"ran"},say:{pst:"said",prt:"said",pres:"_s"},seat:{pst:"sat",prt:"sat"},see:{g:"_ing",prt:"_n",pst:"saw"},seek:{prt:"sought"},sell:{pst:"sold",prt:"sold"},send:{prt:"sent"},set:{prt:"_"},sew:{prt:"_n"},shake:{prt:"_n"},shave:{prt:"_d"},shed:{g:"_ding",pst:"_",pres:"_s"},shine:{pst:"shone",prt:"shone"},shoot:{pst:"shot",prt:"shot"},show:{pst:"_ed"},shut:{prt:"_"},sing:{prt:"sung",pst:"sang"},sink:{pst:"sank",pluperf:"had sunk"},sit:{pst:"sat"},ski:{pst:"_ied"},slay:{prt:"slain"},sleep:{prt:"slept"},slide:{pst:"slid",prt:"slid"},smash:{pres:"_es"},sneak:{prt:"snuck"},speak:{fut:"will have spoken",prt:"spoken",pst:"spoke",perf:"have spoken",pluperf:"had spoken"},speed:{prt:"sped"},spend:{prt:"spent"},spill:{prt:"_ed",pst:"spilt"},spin:{g:"_ning",pst:"spun",prt:"spun"},spit:{prt:"spat"},split:{prt:"_"},spread:{pst:"_"},spring:{prt:"sprung"},stand:{pst:"stood"},steal:{a:"_er",pst:"stole"},stick:{pst:"stuck"},sting:{pst:"stung"},stink:{pst:"stunk",prt:"stunk"},stream:{a:"_er"},strew:{prt:"_n"},strike:{g:"striking",pst:"struck"},suit:{a:"_er",g:"_ing",pst:"_ed"},sware:{prt:"sworn"},swear:{pst:"swore"},sweep:{prt:"swept"},swim:{g:"_ming",pst:"swam"},swing:{pst:"swung"},take:{fut:"will have _n",pst:"took",perf:"have _n",pluperf:"had _n"},teach:{pst:"taught",pres:"_es"},tear:{pst:"tore"},tell:{pst:"told"},think:{pst:"thought"},thrive:{prt:"_d"},tie:{g:"tying",pst:"_d"},undergo:{prt:"_ne"},understand:{pst:"understood"},upset:{prt:"_"},wait:{a:"_er",g:"_ing",pst:"_ed"},wake:{pst:"woke"},wear:{pst:"wore"},weave:{prt:"woven"},wed:{pst:"wed"},weep:{prt:"wept"},win:{g:"_ning",pst:"won"},wind:{prt:"wound"},withdraw:{pst:"withdrew"},wring:{prt:"wrung"},write:{g:"writing",prt:"written",pst:"wrote"}},hr=Object.keys(cr);for(let e=0;e{let r=cr[t][e];r=r.replace("_",t),n[ur[e]]=r})),cr[t]=n}var dr=cr;const gr={b:[{reg:/([^aeiou][aeiou])b$/i,repl:{pr:"$1bs",pa:"$1bbed",gr:"$1bbing"}}],d:[{reg:/(end)$/i,repl:{pr:"$1s",pa:"ent",gr:"$1ing",ar:"$1er"}},{reg:/(eed)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing",ar:"$1er"}},{reg:/(ed)$/i,repl:{pr:"$1s",pa:"$1ded",ar:"$1der",gr:"$1ding"}},{reg:/([^aeiou][ou])d$/i,repl:{pr:"$1ds",pa:"$1dded",gr:"$1dding"}}],e:[{reg:/(eave)$/i,repl:{pr:"$1s",pa:"$1d",gr:"eaving",ar:"$1r"}},{reg:/(ide)$/i,repl:{pr:"$1s",pa:"ode",gr:"iding",ar:"ider"}},{reg:/(t|sh?)(ake)$/i,repl:{pr:"$1$2s",pa:"$1ook",gr:"$1aking",ar:"$1$2r"}},{reg:/w(ake)$/i,repl:{pr:"w$1s",pa:"woke",gr:"waking",ar:"w$1r"}},{reg:/m(ake)$/i,repl:{pr:"m$1s",pa:"made",gr:"making",ar:"m$1r"}},{reg:/(a[tg]|i[zn]|ur|nc|gl|is)e$/i,repl:{pr:"$1es",pa:"$1ed",gr:"$1ing"}},{reg:/([bd]l)e$/i,repl:{pr:"$1es",pa:"$1ed",gr:"$1ing"}},{reg:/(om)e$/i,repl:{pr:"$1es",pa:"ame",gr:"$1ing"}}],g:[{reg:/([^aeiou][aou])g$/i,repl:{pr:"$1gs",pa:"$1gged",gr:"$1gging"}}],h:[{reg:/(..)([cs]h)$/i,repl:{pr:"$1$2es",pa:"$1$2ed",gr:"$1$2ing"}}],k:[{reg:/(ink)$/i,repl:{pr:"$1s",pa:"unk",gr:"$1ing",ar:"$1er"}}],m:[{reg:/([^aeiou][aeiou])m$/i,repl:{pr:"$1ms",pa:"$1mmed",gr:"$1mming"}}],n:[{reg:/(en)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}}],p:[{reg:/(e)(ep)$/i,repl:{pr:"$1$2s",pa:"$1pt",gr:"$1$2ing",ar:"$1$2er"}},{reg:/([^aeiou][aeiou])p$/i,repl:{pr:"$1ps",pa:"$1pped",gr:"$1pping"}},{reg:/([aeiu])p$/i,repl:{pr:"$1ps",pa:"$1p",gr:"$1pping"}}],r:[{reg:/([td]er)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}},{reg:/(er)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}}],s:[{reg:/(ish|tch|ess)$/i,repl:{pr:"$1es",pa:"$1ed",gr:"$1ing"}}],t:[{reg:/(ion|end|e[nc]t)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}},{reg:/(.eat)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}},{reg:/([aeiu])t$/i,repl:{pr:"$1ts",pa:"$1t",gr:"$1tting"}},{reg:/([^aeiou][aeiou])t$/i,repl:{pr:"$1ts",pa:"$1tted",gr:"$1tting"}}],w:[{reg:/(.llow)$/i,repl:{pr:"$1s",pa:"$1ed"}},{reg:/(..)(ow)$/i,repl:{pr:"$1$2s",pa:"$1ew",gr:"$1$2ing",prt:"$1$2n"}}],y:[{reg:/(i|f|rr)y$/i,repl:{pr:"$1ies",pa:"$1ied",gr:"$1ying"}}],z:[{reg:/([aeiou]zz)$/i,repl:{pr:"$1es",pa:"$1ed",gr:"$1ing"}}]},pr={pr:"PresentTense",pa:"PastTense",gr:"Gerund",prt:"Participle",ar:"Actor"},mr=function(e,t){let n={},r=Object.keys(t.repl);for(let a=0;a"e"===e.charAt(e.length-1)?e.replace(/e$/,"ing"):e+"ing",PresentTense:e=>"s"===e.charAt(e.length-1)?e+"es":!0===fr.test(e)?e.slice(0,-1)+"ies":e+"s",PastTense:e=>"e"===e.charAt(e.length-1)?e+"d":"ed"===e.substr(-2)?e:!0===fr.test(e)?e.slice(0,-1)+"ied":e+"ed"};var vr=function(e="",t){let n={};return t&&t.irregulars&&!0===t.irregulars.verbs.hasOwnProperty(e)&&(n=Object.assign({},t.irregulars.verbs[e])),n=Object.assign({},br(e),n),void 0===n.Gerund&&(n.Gerund=yr.Gerund(e)),void 0===n.PastTense&&(n.PastTense=yr.PastTense(e)),void 0===n.PresentTense&&(n.PresentTense=yr.PresentTense(e)),n};const wr=[/ght$/,/nge$/,/ough$/,/ain$/,/uel$/,/[au]ll$/,/ow$/,/oud$/,/...p$/],kr=[/ary$/],Ar={nice:"nicest",late:"latest",hard:"hardest",inner:"innermost",outer:"outermost",far:"furthest",worse:"worst",bad:"worst",good:"best",big:"biggest",large:"largest"},Dr=[{reg:/y$/i,repl:"iest"},{reg:/([aeiou])t$/i,repl:"$1ttest"},{reg:/([aeou])de$/i,repl:"$1dest"},{reg:/nge$/i,repl:"ngest"},{reg:/([aeiou])te$/i,repl:"$1test"}],$r=[/ght$/,/nge$/,/ough$/,/ain$/,/uel$/,/[au]ll$/,/ow$/,/old$/,/oud$/,/e[ae]p$/],Pr=[/ary$/,/ous$/],Er={grey:"greyer",gray:"grayer",green:"greener",yellow:"yellower",red:"redder",good:"better",well:"better",bad:"worse",sad:"sadder",big:"bigger"},Hr=[{reg:/y$/i,repl:"ier"},{reg:/([aeiou])t$/i,repl:"$1tter"},{reg:/([aeou])de$/i,repl:"$1der"},{reg:/nge$/i,repl:"nger"}],jr={toSuperlative:function(e){if(Ar.hasOwnProperty(e))return Ar[e];for(let t=0;t(e[a[t]]=t,e)),{}));var a;if(r.hasOwnProperty(e))return r[e];for(let t=0;t(Ir[t].forEach((n=>e[n]=t)),e)),{});const Or=zr,Tr=Ir,Vr=Qt,Mr=sr,Jr=lr,Lr=St,Sr={nouns:{addendum:"addenda",alga:"algae",alumna:"alumnae",alumnus:"alumni",analysis:"analyses",antenna:"antennae",appendix:"appendices",avocado:"avocados",axis:"axes",bacillus:"bacilli",barracks:"barracks",beau:"beaux",bus:"buses",cactus:"cacti",chateau:"chateaux",child:"children",circus:"circuses",clothes:"clothes",corpus:"corpora",criterion:"criteria",curriculum:"curricula",database:"databases",deer:"deer",diagnosis:"diagnoses",echo:"echoes",embargo:"embargoes",epoch:"epochs",foot:"feet",formula:"formulae",fungus:"fungi",genus:"genera",goose:"geese",halo:"halos",hippopotamus:"hippopotami",index:"indices",larva:"larvae",leaf:"leaves",libretto:"libretti",loaf:"loaves",man:"men",matrix:"matrices",memorandum:"memoranda",modulus:"moduli",mosquito:"mosquitoes",mouse:"mice",nebula:"nebulae",nucleus:"nuclei",octopus:"octopi",opus:"opera",ovum:"ova",ox:"oxen",parenthesis:"parentheses",person:"people",phenomenon:"phenomena",prognosis:"prognoses",quiz:"quizzes",radius:"radii",referendum:"referenda",rodeo:"rodeos",sex:"sexes",shoe:"shoes",sombrero:"sombreros",stimulus:"stimuli",stomach:"stomachs",syllabus:"syllabi",synopsis:"synopses",tableau:"tableaux",thesis:"theses",thief:"thieves",tooth:"teeth",tornado:"tornados",tuxedo:"tuxedos",vertebra:"vertebrae"},verbs:dr},_r={conjugate:vr,adjectives:Nr,toPlural:Cr,toSingular:Gr,toInfinitive:function(e,t,n){if(!e)return"";if(!0===t.words.hasOwnProperty(e)){let n=t.irregulars.verbs,r=Object.keys(n);for(let t=0;t{let r=e[n];n=n.toLowerCase().trim(),t[n]=r})),Mr.addWords(t,this.words,this)}addConjugations(e){return Object.assign(this.irregulars.verbs,e),this}addPlurals(e){return Object.assign(this.irregulars.nouns,e),this}addTags(e){return e=Object.assign({},e),this.tags=Object.assign(this.tags,e),this.tags=Lr(this.tags),this}postProcess(e){return this.taggers.push(e),this}stats(){return{words:Object.keys(this.words).length,plurals:Object.keys(this.irregulars.nouns).length,conjugations:Object.keys(this.irregulars.verbs).length,compounds:Object.keys(this.hasCompound).length,postProcessors:this.taggers.length}}}const Wr=function(e){return JSON.parse(JSON.stringify(e))};qr.prototype.clone=function(){let e=new qr;return e.words=Object.assign({},this.words),e.hasCompound=Object.assign({},this.hasCompound),e.irregulars=Wr(this.irregulars),e.tags=Wr(this.tags),e.transforms=this.transforms,e.taggers=this.taggers,e};var Rr=qr,Ur={};!function(e){e.all=function(){return this.parents()[0]||this},e.parent=function(){return this.from?this.from:this},e.parents=function(e){let t=[];const n=function(e){e.from&&(t.push(e.from),n(e.from))};return n(this),t=t.reverse(),"number"==typeof e?t[e]:t},e.clone=function(e){let t=this.list.map((t=>t.clone(e)));return this.buildFrom(t)},e.wordCount=function(){return this.list.reduce(((e,t)=>e+t.wordCount()),0)},e.wordcount=e.wordCount}(Ur);var Qr={};!function(e){e.first=function(e){return void 0===e?this.get(0):this.slice(0,e)},e.last=function(e){if(void 0===e)return this.get(this.list.length-1);let t=this.list.length;return this.slice(t-e,t)},e.slice=function(e,t){let n=this.list.slice(e,t);return this.buildFrom(n)},e.eq=function(e){let t=this.list[e];return void 0===t?this.buildFrom([]):this.buildFrom([t])},e.get=e.eq,e.firstTerms=function(){return this.match("^.")},e.firstTerm=e.firstTerms,e.lastTerms=function(){return this.match(".$")},e.lastTerm=e.lastTerms,e.termList=function(e){let t=[];for(let n=0;nr.groups[e]));for(let e=0;ea.groups[e].group===t)),i.forEach((e=>{n.push(a.buildFrom(a.groups[e].start,a.groups[e].length))}))}return e.buildFrom(n)}(this,e)||this.buildFrom([]))},e.group=e.groups,e.sentences=function(e){let t=[];return this.list.forEach((e=>{t.push(e.fullSentence())})),"number"==typeof e?this.buildFrom([t[e]]):this.buildFrom(t)},e.sentence=e.sentences}(Qr);var Zr={},Xr=function(e,t){if(e._cache&&!0===e._cache.set){let{words:n,tags:r}=function(e){let t=[],n=[];return e.forEach((e=>{!0!==e.optional&&!0!==e.negative&&(void 0!==e.tag&&t.push(e.tag),void 0!==e.word&&n.push(e.word))})),{tags:t,words:n}}(t);for(let t=0;te.concat(t.match(a))),[]);return void 0!==r.group&&null!==r.group&&""!==r.group?this.buildFrom(i).groups(r.group):this.buildFrom(i)},e.not=function(e,r={}){let a=t(e,r);if(0===a.length||!1===n(this,a))return this;let i=this.list.reduce(((e,t)=>e.concat(t.not(a))),[]);return this.buildFrom(i)},e.matchOne=function(e,r={}){let a=t(e,r);if(!1===n(this,a))return this.buildFrom([]);for(let e=0;e!0===e.has(a)));return this.buildFrom(i)},e.ifNo=function(e,n={}){let r=t(e,n),a=this.list.filter((e=>!1===e.has(r)));return this.buildFrom(a)},e.has=function(e,r={}){let a=t(e,r);return!1!==n(this,a)&&this.list.some((e=>!0===e.has(a)))},e.lookAhead=function(e,n={}){e||(e=".*");let r=t(e,n),a=[];return this.list.forEach((e=>{a=a.concat(e.lookAhead(r))})),a=a.filter((e=>e)),this.buildFrom(a)},e.lookAfter=e.lookAhead,e.lookBehind=function(e,n={}){e||(e=".*");let r=t(e,n),a=[];return this.list.forEach((e=>{a=a.concat(e.lookBehind(r))})),a=a.filter((e=>e)),this.buildFrom(a)},e.lookBefore=e.lookBehind,e.before=function(e,n={}){let r=t(e,n),a=this.if(r).list.map((e=>{let t=e.terms().map((e=>e.id)),n=e.match(r)[0],a=t.indexOf(n.start);return 0===a||-1===a?null:e.buildFrom(e.start,a)}));return a=a.filter((e=>null!==e)),this.buildFrom(a)},e.after=function(e,n={}){let r=t(e,n),a=this.if(r).list.map((e=>{let t=e.terms(),n=t.map((e=>e.id)),a=e.match(r)[0],i=n.indexOf(a.start);if(-1===i||!t[i+a.length])return null;let o=t[i+a.length].id,s=e.length-i-a.length;return e.buildFrom(o,s)}));return a=a.filter((e=>null!==e)),this.buildFrom(a)},e.hasAfter=function(e,t={}){return this.filter((n=>n.lookAfter(e,t).found))},e.hasBefore=function(e,t={}){return this.filter((n=>n.lookBefore(e,t).found))}}(Zr);var Yr={};const ea=function(e,t,n,r){let a=[];"string"==typeof e&&(a=e.split(" ")),t.list.forEach((i=>{let o=i.terms();!0===n&&(o=o.filter((n=>n.canBe(e,t.world)))),o.forEach(((n,i)=>{a.length>1?a[i]&&"."!==a[i]&&n.tag(a[i],r,t.world):n.tag(e,r,t.world)}))}))};Yr.tag=function(e,t){return e?(ea(e,this,!1,t),this):this},Yr.tagSafe=function(e,t){return e?(ea(e,this,!0,t),this):this},Yr.unTag=function(e,t){return this.list.forEach((n=>{n.terms().forEach((n=>n.unTag(e,t,this.world)))})),this},Yr.canBe=function(e){if(!e)return this;let t=this.world,n=this.list.reduce(((n,r)=>n.concat(r.canBe(e,t))),[]);return this.buildFrom(n)};var ta={map:function(e){if(!e)return this;let t=this.list.map(((t,n)=>{let r=this.buildFrom([t]);r.from=null;let a=e(r,n);return a&&a.list&&a.list[0]?a.list[0]:a}));return t=t.filter((e=>e)),0===t.length?this.buildFrom(t):"object"!=typeof t[0]||"Phrase"!==t[0].isA?t:this.buildFrom(t)},forEach:function(e,t){return e?(this.list.forEach(((n,r)=>{let a=this.buildFrom([n]);!0===t&&(a.from=null),e(a,r)})),this):this},filter:function(e){if(!e)return this;let t=this.list.filter(((t,n)=>{let r=this.buildFrom([t]);return r.from=null,e(r,n)}));return this.buildFrom(t)},find:function(e){if(!e)return this;let t=this.list.find(((t,n)=>{let r=this.buildFrom([t]);return r.from=null,e(r,n)}));return t?this.buildFrom([t]):void 0},some:function(e){return e?this.list.some(((t,n)=>{let r=this.buildFrom([t]);return r.from=null,e(r,n)})):this},random:function(e){if(!this.found)return this;let t=Math.floor(Math.random()*this.list.length);if(void 0===e){let e=[this.list[t]];return this.buildFrom(e)}return t+e>this.length&&(t=this.length-e,t=t<0?0:t),this.slice(t,t+e)}},ra={},aa=function(e,t,n){let r=function(e,t=[]){let n={};return e.forEach(((e,r)=>{let a=!0;void 0!==t[r]&&(a=t[r]);let i=function(e){return e.split(/[ -]/g)}(e=(e=(e||"").toLowerCase()).replace(/[,;.!?]+$/,"")).map((e=>e.trim()));n[i[0]]=n[i[0]]||{},1===i.length?n[i[0]].value=a:(n[i[0]].more=n[i[0]].more||[],n[i[0]].more.push({rest:i.slice(1),value:a}))})),n}(e,t),a=[];for(let e=0;ee.reduced));for(let e=0;e{void 0!==i[e+n.rest.length]&&!0===n.rest.every(((t,n)=>t===i[e+n+1]))&&a.push({id:t.terms()[e].id,value:n.value,length:n.rest.length+1})})),void 0!==r[i[e]].value&&a.push({id:t.terms()[e].id,value:r[i[e]].value,length:1}))}return a};!function(e){const t=aa;e.lookup=function(e){let n=[],r=(a=e)&&"[object Object]"===Object.prototype.toString.call(a);var a;!0===r&&(e=Object.keys(e).map((t=>(n.push(e[t]),t)))),"string"==typeof e&&(e=[e]),!0!==this._cache.set&&this.cache();let i=t(e,n,this),o=this.list[0];if(!0===r){let e={};return i.forEach((t=>{e[t.value]=e[t.value]||[],e[t.value].push(o.buildFrom(t.id,t.length))})),Object.keys(e).forEach((t=>{e[t]=this.buildFrom(e[t])})),e}return i=i.map((e=>o.buildFrom(e.id,e.length))),this.buildFrom(i)},e.lookUp=e.lookup}(ra);var na={cache:function(e){e=e||{};let t={},n={};return this._cache.words=t,this._cache.tags=n,this._cache.set=!0,this.list.forEach(((r,a)=>{r.cache=r.cache||{},r.terms().forEach((r=>{t[r.reduced]&&!t.hasOwnProperty(r.reduced)||(t[r.reduced]=t[r.reduced]||[],t[r.reduced].push(a),Object.keys(r.tags).forEach((e=>{n[e]=n[e]||[],n[e].push(a)})),e.root&&(r.setRoot(this.world),t[r.root]=[a]))}))})),this},uncache:function(){return this._cache={},this.list.forEach((e=>{e.cache={}})),this.parents().forEach((e=>{e._cache={},e.list.forEach((e=>{e.cache={}}))})),this}},ia={};const oa=xt;ia.replaceWith=function(e,t={}){return e?(!0===t&&(t={keepTags:!0}),!1===t&&(t={keepTags:!1}),t=t||{},this.uncache(),this.list.forEach((n=>{let r,a=e;if("function"==typeof e&&(a=e(n)),a&&"object"==typeof a&&"Doc"===a.isA)r=a.list,this.pool().merge(a.pool());else{if("string"!=typeof a)return;{!1!==t.keepCase&&n.terms(0).isTitleCase()&&(a=(i=a).charAt(0).toUpperCase()+i.substr(1)),r=oa(a,this.world,this.pool());let e=this.buildFrom(r);e.tagger(),r=e.list}}var i;if(!0===t.keepTags){let e=n.json({terms:{tags:!0}}).terms;r[0].terms().forEach(((t,n)=>{e[n]&&t.tagSafe(e[n].tags,"keptTag",this.world)}))}n.replace(r[0],this)})),this):this.delete()},ia.replace=function(e,t,n){return void 0===t?this.replaceWith(e,n):(this.match(e).replaceWith(t,n),this)};var sa={};!function(e){const t=xt,n=function(e){return e&&"[object Object]"===Object.prototype.toString.call(e)},r=function(e,n){let r=t(e,n.world)[0],a=n.buildFrom([r]);return a.tagger(),n.list=a.list,n};e.append=function(e=""){return e?this.found?(this.uncache(),this.list.forEach((r=>{let a;n(e)&&"Doc"===e.isA?a=e.list[0].clone():"string"==typeof e&&(a=t(e,this.world,this.pool())[0]),this.buildFrom([a]).tagger(),r.append(a,this)})),this):r(e,this):this},e.insertAfter=e.append,e.insertAt=e.append,e.prepend=function(e){return e?this.found?(this.uncache(),this.list.forEach((r=>{let a;n(e)&&"Doc"===e.isA?a=e.list[0].clone():"string"==typeof e&&(a=t(e,this.world,this.pool())[0]),this.buildFrom([a]).tagger(),r.prepend(a,this)})),this):r(e,this):this},e.insertBefore=e.prepend,e.concat=function(){this.uncache();let e=this.list.slice(0);for(let n=0;ne.delete(this))),this},e.remove=e.delete}(sa);var la={};const ua={clean:!0,reduced:!0,root:!0};la.text=function(e){e=e||{};let t=!1;0===this.parents().length&&(t=!0),("root"===e||"object"==typeof e&&e.root)&&this.list.forEach((e=>{e.terms().forEach((e=>{null===e.root&&e.setRoot(this.world)}))}));let n=this.list.reduce(((n,r,a)=>{const i=!t&&0===a,o=!t&&a===this.list.length-1;return n+r.text(e,i,o)}),"");return!0!==ua[e]&&!0!==e.reduced&&!0!==e.clean&&!0!==e.root||(n=n.trim()),n};var ca={},ha=function(e,t,n){let r=function(e){let t=0,n=0,r={};return e.termList().forEach((e=>{r[e.id]={index:n,start:t+e.pre.length,length:e.text.length},t+=e.pre.length+e.text.length+e.post.length,n+=1})),r}(e.all());(n.terms.index||n.index)&&t.forEach((e=>{e.terms.forEach((e=>{e.index=r[e.id].index})),e.index=e.terms[0].index})),(n.terms.offset||n.offset)&&t.forEach((e=>{e.terms.forEach((e=>{e.offset=r[e.id]||{}})),e.offset={index:e.terms[0].offset.index,start:e.terms[0].offset.start-e.text.indexOf(e.terms[0].text),length:e.text.length}}))};!function(e){const t=ha,n={text:!0,terms:!0,trim:!0};e.json=function(e={}){if("number"==typeof e&&this.list[e])return this.list[e].json(n);!0===(e=function(e){return(e=Object.assign({},n,e)).unique&&(e.reduced=!0),e.offset&&(e.text=!0,e.terms&&!0!==e.terms||(e.terms={}),e.terms.offset=!0),(e.index||e.terms.index)&&(e.terms=!0===e.terms?{}:e.terms,e.terms.id=!0),e}(e)).root&&this.list.forEach((e=>{e.terms().forEach((e=>{null===e.root&&e.setRoot(this.world)}))}));let r=this.list.map((t=>t.json(e,this.world)));if((e.terms.offset||e.offset||e.terms.index||e.index)&&t(this,r,e),e.frequency||e.freq||e.count){let e={};this.list.forEach((t=>{let n=t.text("reduced");e[n]=e[n]||0,e[n]+=1})),this.list.forEach(((t,n)=>{r[n].count=e[t.text("reduced")]}))}if(e.unique){let e={};r=r.filter((t=>!0!==e[t.reduced]&&(e[t.reduced]=!0,!0)))}return r},e.data=e.json}(ca);var da={},ga={exports:{}};!function(e){const t="",n=function(e,t){for(e=e.toString();e.length{console.log('\n%c"'+e.text()+'"',"color: #e6d7b3;"),e.terms().forEach((e=>{let a=Object.keys(e.tags),i=e.text||"-";e.implicit&&(i="["+e.implicit+"]");let o="'"+i+"'";o=n(o,8);let s=a.find((e=>t[e]&&t[e].color)),l="steelblue";t[s]&&(l=t[s].color,l=r[l]),console.log(` ${o} - %c${a.join(", ")}`,`color: ${l||"steelblue"};`)}))}))}(e),e):(console.log(a.blue("=====")),e.list.forEach((t=>{console.log(a.blue(" -----")),t.terms().forEach((t=>{let r=Object.keys(t.tags),i=t.text||"-";t.implicit&&(i="["+t.implicit+"]"),i=a.yellow(i);let o="'"+i+"'";o=n(o,18);let s=a.blue(" | ")+o+" - "+function(e,t){return(e=e.map((e=>{if(!t.tags.hasOwnProperty(e))return e;const n=t.tags[e].color||"blue";return a[n](e)}))).join(", ")}(r,e.world);console.log(s)}))})),console.log(""),e)}}();const pa=ga.exports,ma=function(e){let t=e.json({text:!1,terms:!1,reduced:!0}),n={};t.forEach((e=>{n[e.reduced]||(e.count=0,n[e.reduced]=e),n[e.reduced].count+=1}));let r=Object.keys(n).map((e=>n[e]));return r.sort(((e,t)=>e.count>t.count?-1:e.counte.text)).filter((e=>e));if("freq"===e||"frequency"===e)return ma(this);if("terms"===e){let e=[];return this.json({text:!1,terms:{text:!0}}).forEach((t=>{let n=t.terms.map((e=>e.text));n=n.filter((e=>e)),e=e.concat(n)})),e}return"tags"===e?this.list.map((e=>e.terms().reduce(((e,t)=>(e[t.clean||t.implicit]=Object.keys(t.tags),e)),{}))):"debug"===e?(pa(this),this):this.text()};var fa={};const ba={alpha:(e,t)=>{let n=e.text("clean"),r=t.text("clean");return nr?1:0},length:(e,t)=>{let n=e.text().trim().length,r=t.text().trim().length;return nr?-1:0},wordCount:(e,t)=>{let n=e.wordCount(),r=t.wordCount();return nr?-1:0}};ba.alphabetical=ba.alpha,ba.wordcount=ba.wordCount;const ya={index:!0,sequence:!0,seq:!0,sequential:!0,chron:!0,chronological:!0};fa.sort=function(e){return"freq"===(e=e||"alpha")||"frequency"===e||"topk"===e?function(e){let t={};const n={case:!0,punctuation:!1,whitespace:!0,unicode:!0};return e.list.forEach((e=>{let r=e.text(n);t[r]=t[r]||0,t[r]+=1})),e.list.sort(((e,r)=>{let a=t[e.text(n)],i=t[r.text(n)];return ai?-1:0})),e}(this):ya.hasOwnProperty(e)?function(e){let t={};return e.json({terms:{offset:!0}}).forEach((e=>{t[e.terms[0].id]=e.terms[0].offset.start})),e.list=e.list.sort(((e,n)=>t[e.start]>t[n.start]?1:t[e.start]{let n=e.text("reduced").trim()||e.text("implicit").trim();return!0!==t.hasOwnProperty(n)&&(t[n]=!0,!0)})),this.buildFrom(e)};var va={};const wa=n$1,ka=/[\[\]{}⟨⟩:,،、‒–—―…‹›«»‐\-;\/⁄·*\•^†‡°¡¿※№÷׺ª%‰=‱¶§~|‖¦©℗®℠™¤₳฿]/g,Aa=/['‘’“”"′″‴]+/g,Da={whitespace:function(e){let t=e.list.map((e=>e.terms()));t.forEach(((e,n)=>{e.forEach(((r,a)=>{!0!==r.hasDash()?(r.pre=r.pre.replace(/\s/g,""),r.post=r.post.replace(/\s/g,""),(e.length-1!==a||t[n+1])&&(r.implicit&&!0===Boolean(r.text)||!0!==r.hasHyphen()&&(r.post+=" "))):r.post=" - "}))}))},punctuation:function(e){e.forEach((e=>{!0===e.hasHyphen()&&(e.post=" "),e.pre=e.pre.replace(ka,""),e.post=e.post.replace(ka,""),e.post=e.post.replace(/\.\.\./,""),!0===/!/.test(e.post)&&(e.post=e.post.replace(/!/g,""),e.post="!"+e.post),!0===/\?/.test(e.post)&&(e.post=e.post.replace(/[\?!]*/,""),e.post="?"+e.post)}))},unicode:function(e){e.forEach((e=>{!0!==e.isImplicit()&&(e.text=wa(e.text))}))},quotations:function(e){e.forEach((e=>{e.post=e.post.replace(Aa,""),e.pre=e.pre.replace(Aa,"")}))},adverbs:function(e){e.match("#Adverb").not("(not|nary|seldom|never|barely|almost|basically|so)").remove()},abbreviations:function(e){e.list.forEach((e=>{let t=e.terms();t.forEach(((e,n)=>{!0===e.tags.Abbreviation&&t[n+1]&&(e.post=e.post.replace(/^\./,""))}))}))}},$a={whitespace:!0,unicode:!0,punctuation:!0,emoji:!0,acronyms:!0,abbreviations:!0,case:!1,contractions:!1,parentheses:!1,quotations:!1,adverbs:!1,possessives:!1,verbs:!1,nouns:!1,honorifics:!1},Pa={light:{},medium:{case:!0,contractions:!0,parentheses:!0,quotations:!0,adverbs:!0}};Pa.heavy=Object.assign({},Pa.medium,{possessives:!0,verbs:!0,nouns:!0,honorifics:!0}),va.normalize=function(e){"string"==typeof(e=e||{})&&(e=Pa[e]||{}),e=Object.assign({},$a,e),this.uncache();let t=this.termList();return e.case&&this.toLowerCase(),e.whitespace&&Da.whitespace(this),e.unicode&&Da.unicode(t),e.punctuation&&Da.punctuation(t),e.emoji&&this.remove("(#Emoji|#Emoticon)"),e.acronyms&&this.acronyms().strip(),e.abbreviations&&Da.abbreviations(this),(e.contraction||e.contractions)&&this.contractions().expand(),e.parentheses&&this.parentheses().unwrap(),(e.quotations||e.quotes)&&Da.quotations(t),e.adverbs&&Da.adverbs(this),(e.possessive||e.possessives)&&this.possessives().strip(),e.verbs&&this.verbs().toInfinitive(),(e.nouns||e.plurals)&&this.nouns().toSingular(),e.honorifics&&this.remove("#Honorific"),this};var Ea={};!function(e){const t=_e;e.splitOn=function(e){if(!e)return this.parent().splitOn(this);let n=t(e),r=[];return this.list.forEach((e=>{let t=e.match(n);if(0===t.length)return void r.push(e);let a=e;t.forEach((e=>{let t=a.splitOn(e);t.before&&r.push(t.before),t.match&&r.push(t.match),a=t.after})),a&&r.push(a)})),this.buildFrom(r)},e.splitAfter=function(e){if(!e)return this.parent().splitAfter(this);let n=t(e),r=[];return this.list.forEach((e=>{let t=e.match(n);if(0===t.length)return void r.push(e);let a=e;t.forEach((e=>{let t=a.splitOn(e);t.before&&t.match?(t.before.length+=t.match.length,r.push(t.before)):t.match&&r.push(t.match),a=t.after})),a&&r.push(a)})),this.buildFrom(r)},e.split=e.splitAfter,e.splitBefore=function(e){if(!e)return this.parent().splitBefore(this);let n=t(e),r=[];return this.list.forEach((e=>{let t=e.match(n);if(0===t.length)return void r.push(e);let a=e;t.forEach((e=>{let t=a.splitOn(e);t.before&&r.push(t.before),t.match&&t.after&&(t.match.length+=t.after.length),a=t.match})),a&&r.push(a)})),this.buildFrom(r)},e.segment=function(e,t){e=e||{},t=t||{text:!0};let n=this,r=Object.keys(e);return r.forEach((e=>{n=n.splitOn(e)})),n.list.forEach((t=>{for(let n=0;n{let n=e.json(t);return n.segment=e.segment||null,n}))}}(Ea);var Ha={};const ja=function(e,t){let n=e.world;return e.list.forEach((e=>{e.terms().forEach((e=>e[t](n)))})),e};Ha.toLowerCase=function(){return ja(this,"toLowerCase")},Ha.toUpperCase=function(){return ja(this,"toUpperCase")},Ha.toTitleCase=function(){return ja(this,"toTitleCase")},Ha.toCamelCase=function(){return this.list.forEach((e=>{let t=e.terms();t.forEach(((e,n)=>{0!==n&&e.toTitleCase(),n!==t.length-1&&(e.post="")}))})),this};var Na={};!function(e){e.pre=function(e,t){return void 0===e?this.list[0].terms(0).pre:(this.list.forEach((n=>{let r=n.terms(0);!0===t?r.pre+=e:r.pre=e})),this)},e.post=function(e,t){return void 0===e?this.list.map((e=>{let t=e.terms();return t[t.length-1].post})):(this.list.forEach((n=>{let r=n.terms(),a=r[r.length-1];!0===t?a.post+=e:a.post=e})),this)},e.trim=function(){return this.list=this.list.map((e=>e.trim())),this},e.hyphenate=function(){return this.list.forEach((e=>{let t=e.terms();t.forEach(((e,n)=>{0!==n&&(e.pre=""),t[n+1]&&(e.post="-")}))})),this},e.dehyphenate=function(){const e=/(-|–|—)/;return this.list.forEach((t=>{t.terms().forEach((t=>{e.test(t.post)&&(t.post=" ")}))})),this},e.deHyphenate=e.dehyphenate,e.toQuotations=function(e,t){return e=e||'"',t=t||'"',this.list.forEach((n=>{let r=n.terms();r[0].pre=e+r[0].pre;let a=r[r.length-1];a.post=t+a.post})),this},e.toQuotation=e.toQuotations,e.toParentheses=function(e,t){return e=e||"(",t=t||")",this.list.forEach((n=>{let r=n.terms();r[0].pre=e+r[0].pre;let a=r[r.length-1];a.post=t+a.post})),this}}(Na);var xa={join:function(e){this.uncache();let t=this.list[0],n=t.length,r={};for(let n=1;n{e.list.forEach((e=>{let n=e.terms();for(let r=0;r!0!==r[e.start]))})),this.buildFrom([t])}},Fa={};const Ca=/[,\)"';:\-–—\.…]/,Ba=function(e,t){if(!e.found)return;let n=e.termList();for(let e=0;e{e.implicit=e.clean})),n[0].text+=t,n.slice(1).forEach((e=>{e.text=""}));for(let e=0;e{za[e[0]]=function(t){let n=this.match(e[1]);return"number"==typeof t&&(n=n.get(t)),n}})),za.emojis=za.emoji,za.atmentions=za.atMentions,za.words=za.terms,za.phoneNumbers=function(e){let t=this.splitAfter("@hasComma");return t=t.match("#PhoneNumber+"),"number"==typeof e&&(t=t.get(e)),t},za.money=function(e){let t=this.match("#Money #Currency?");return"number"==typeof e&&(t=t.get(e)),t},za.places=function(e){let t=this.match("(#City && @hasComma) (#Region|#Country)"),n=this.not(t).splitAfter("@hasComma");return n=n.concat(t),n.sort("index"),n=n.match("#Place+"),"number"==typeof e&&(n=n.get(e)),n},za.organizations=function(e){let t=this.clauses();return t=t.match("#Organization+"),"number"==typeof e&&(t=t.get(e)),t},za.entities=function(e){let t=this.clauses(),n=t.people();return n=n.concat(t.places()),n=n.concat(t.organizations()),n=n.not(["someone","man","woman","mother","brother","sister","father"]),n.sort("sequence"),"number"==typeof e&&(n=n.get(e)),n},za.things=za.entities,za.topics=za.entities;var Ia=za;const Oa=/^(under|over)-?.{3}/,Ta=function(e,t,n){let r=n.words,a=e[t].reduced+" "+e[t+1].reduced;return void 0!==r[a]&&!0===r.hasOwnProperty(a)?(e[t].tag(r[a],"lexicon-two",n),e[t+1].tag(r[a],"lexicon-two",n),1):t+20){a+=n;continue}}if(void 0===n[i]||!0!==n.hasOwnProperty(i))if(i===e[a].reduced||!0!==n.hasOwnProperty(e[a].reduced)){if(!0===Oa.test(i)){let r=i.replace(/^(under|over)-?/,"");!0===n.hasOwnProperty(r)&&e[a].tag(n[r],"noprefix-lexicon",t)}}else e[a].tag(n[e[a].reduced],"lexicon",t);else e[a].tag(n[i],"lexicon",t)}return e};const Ma=/[\'‘’‛‵′`´]$/,Ja=/^(m|k|cm|km|m)\/(s|h|hr)$/,La=[[/^[\w\.]+@[\w\.]+\.[a-z]{2,3}$/,"Email"],[/^#[a-z0-9_\u00C0-\u00FF]{2,}$/,"HashTag"],[/^@1?[0-9](am|pm)$/i,"Time"],[/^@1?[0-9]:[0-9]{2}(am|pm)?$/i,"Time"],[/^@\w{2,}$/,"AtMention"],[/^(https?:\/\/|www\.)+\w+\.[a-z]{2,3}/,"Url"],[/^[a-z0-9./].+\.(com|net|gov|org|ly|edu|info|biz|dev|ru|jp|de|in|uk|br|io|ai)/,"Url"],[/^'[0-9]{2}$/,"Year"],[/^[012]?[0-9](:[0-5][0-9])(:[0-5][0-9])$/,"Time"],[/^[012]?[0-9](:[0-5][0-9])?(:[0-5][0-9])? ?(am|pm)$/i,"Time"],[/^[012]?[0-9](:[0-5][0-9])(:[0-5][0-9])? ?(am|pm)?$/i,"Time"],[/^[PMCE]ST$/,"Time"],[/^utc ?[+-]?[0-9]+?$/,"Time"],[/^[a-z0-9]*? o\'?clock$/,"Time"],[/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}/i,"Date"],[/^[0-9]{1,4}-[0-9]{1,2}-[0-9]{1,4}$/,"Date"],[/^[0-9]{1,4}\/[0-9]{1,2}\/[0-9]{1,4}$/,"Date"],[/^[0-9]{1,4}-[a-z]{2,9}-[0-9]{1,4}$/i,"Date"],[/^gmt[+-][0-9][0-9]?$/i,"Timezone"],[/^utc[+-][0-9][0-9]?$/i,"Timezone"],[/^ma?c\'.*/,"LastName"],[/^o\'[drlkn].*/,"LastName"],[/^ma?cd[aeiou]/,"LastName"],[/^(lol)+[sz]$/,"Expression"],[/^woo+a*?h?$/,"Expression"],[/^(un|de|re)\\-[a-z\u00C0-\u00FF]{2}/,"Verb"],[/^[0-9]{1,4}\.[0-9]{1,2}\.[0-9]{1,4}$/,"Date"],[/^[0-9]{3}-[0-9]{4}$/,"PhoneNumber"],[/^(\+?[0-9][ -])?[0-9]{3}[ -]?[0-9]{3}-[0-9]{4}$/,"PhoneNumber"],[/^[-+]?[\$\xA2-\xA5\u058F\u060B\u09F2\u09F3\u09FB\u0AF1\u0BF9\u0E3F\u17DB\u20A0-\u20BD\uA838\uFDFC\uFE69\uFF04\uFFE0\uFFE1\uFFE5\uFFE6][-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?(k|m|b|bn)?\+?$/,["Money","Value"]],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?[\$\xA2-\xA5\u058F\u060B\u09F2\u09F3\u09FB\u0AF1\u0BF9\u0E3F\u17DB\u20A0-\u20BD\uA838\uFDFC\uFE69\uFF04\uFFE0\uFFE1\uFFE5\uFFE6]\+?$/,["Money","Value"]],[/^[-+]?[\$£]?[0-9]([0-9,.])+?(usd|eur|jpy|gbp|cad|aud|chf|cny|hkd|nzd|kr|rub)$/i,["Money","Value"]],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?\+?$/,["Cardinal","NumericValue"]],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?(st|nd|rd|r?th)$/,["Ordinal","NumericValue"]],[/^\.[0-9]+\+?$/,["Cardinal","NumericValue"]],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?%\+?$/,["Percent","Cardinal","NumericValue"]],[/^\.[0-9]+%$/,["Percent","Cardinal","NumericValue"]],[/^[0-9]{1,4}\/[0-9]{1,4}(st|nd|rd|th)?s?$/,["Fraction","NumericValue"]],[/^[0-9.]{1,3}[a-z]{0,2}[-–—][0-9]{1,3}[a-z]{0,2}$/,["Value","NumberRange"]],[/^[0-9][0-9]?(:[0-9][0-9])?(am|pm)? ?[-–—] ?[0-9][0-9]?(:[0-9][0-9])?(am|pm)?$/,["Time","NumberRange"]],[/^[0-9.]+([a-z]{1,4})$/,"Value"]],Sa=/^[IVXLCDM]{2,}$/,_a=/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,Ka="Adjective",qa="Infinitive",Wa="PresentTense",Ra="Singular",Ua="PastTense",Qa="Expression",Za="Adjective",Xa="Infinitive",Ya="PresentTense",en="Singular",tn="PastTense",rn="Adverb",an="Plural",nn="Verb",on="LastName",sn={a:[[/.[aeiou]na$/,"Noun"],[/.[oau][wvl]ska$/,"LastName"],[/.[^aeiou]ica$/,Ra],[/^([hyj]a)+$/,Qa]],c:[[/.[^aeiou]ic$/,Ka]],d:[[/[aeiou](pp|ll|ss|ff|gg|tt|rr|bb|nn|mm)ed$/,Ua],[/.[aeo]{2}[bdgmnprvz]ed$/,Ua],[/.[aeiou][sg]hed$/,Ua],[/.[aeiou]red$/,Ua],[/.[aeiou]r?ried$/,Ua],[/.[bcdgtr]led$/,Ua],[/.[aoui]f?led$/,Ua],[/.[iao]sed$/,Ua],[/[aeiou]n?[cs]ed$/,Ua],[/[aeiou][rl]?[mnf]ed$/,Ua],[/[aeiou][ns]?c?ked$/,Ua],[/[aeiou][nl]?ged$/,Ua],[/.[tdbwxz]ed$/,Ua],[/[^aeiou][aeiou][tvx]ed$/,Ua],[/.[cdlmnprstv]ied$/,Ua],[/[^aeiou]ard$/,Ra],[/[aeiou][^aeiou]id$/,Ka],[/.[vrl]id$/,Ka]],e:[[/.[lnr]ize$/,qa],[/.[^aeiou]ise$/,qa],[/.[aeiou]te$/,qa],[/.[^aeiou][ai]ble$/,Ka],[/.[^aeiou]eable$/,Ka],[/.[ts]ive$/,Ka],[/[a-z]-like$/,Ka]],h:[[/.[^aeiouf]ish$/,Ka],[/.v[iy]ch$/,"LastName"],[/^ug?h+$/,Qa],[/^uh[ -]?oh$/,Qa],[/[a-z]-ish$/,Ka]],i:[[/.[oau][wvl]ski$/,"LastName"]],k:[[/^(k){2}$/,Qa]],l:[[/.[gl]ial$/,Ka],[/.[^aeiou]ful$/,Ka],[/.[nrtumcd]al$/,Ka],[/.[^aeiou][ei]al$/,Ka]],m:[[/.[^aeiou]ium$/,Ra],[/[^aeiou]ism$/,Ra],[/^h*u*m+$/,Qa],[/^\d+ ?[ap]m$/,"Date"]],n:[[/.[lsrnpb]ian$/,Ka],[/[^aeiou]ician$/,"Actor"],[/[aeiou][ktrp]in$/,"Gerund"]],o:[[/^no+$/,Qa],[/^(yo)+$/,Qa],[/^woo+[pt]?$/,Qa]],r:[[/.[bdfklmst]ler$/,"Noun"],[/[aeiou][pns]er$/,Ra],[/[^i]fer$/,qa],[/.[^aeiou][ao]pher$/,"Actor"],[/.[lk]er$/,"Noun"],[/.ier$/,"Comparative"]],t:[[/.[di]est$/,"Superlative"],[/.[icldtgrv]ent$/,Ka],[/[aeiou].*ist$/,Ka],[/^[a-z]et$/,"Verb"]],s:[[/.[^aeiou]ises$/,Wa],[/.[rln]ates$/,Wa],[/.[^z]ens$/,"Verb"],[/.[lstrn]us$/,Ra],[/.[aeiou]sks$/,Wa],[/.[aeiou]kes$/,Wa],[/[aeiou][^aeiou]is$/,Ra],[/[a-z]\'s$/,"Noun"],[/^yes+$/,Qa]],v:[[/.[^aeiou][ai][kln]ov$/,"LastName"]],y:[[/.[cts]hy$/,Ka],[/.[st]ty$/,Ka],[/.[gk]y$/,Ka],[/.[tnl]ary$/,Ka],[/.[oe]ry$/,Ra],[/[rdntkbhs]ly$/,"Adverb"],[/...lly$/,"Adverb"],[/[bszmp]{2}y$/,Ka],[/.(gg|bb|zz)ly$/,Ka],[/.[ai]my$/,Ka],[/[ea]{2}zy$/,Ka],[/.[^aeiou]ity$/,Ra]]},ln=[null,null,{ea:en,ia:"Noun",ic:Za,ly:rn,"'n":nn,"'t":nn},{oed:tn,ued:tn,xed:tn," so":rn,"'ll":"Modal","'re":"Copula",azy:Za,eer:"Noun",end:nn,ped:tn,ffy:Za,ify:Xa,ing:"Gerund",ize:Xa,lar:Za,mum:Za,nes:Ya,nny:Za,oid:Za,ous:Za,que:Za,rol:en,sis:en,zes:Ya},{amed:tn,aped:tn,ched:tn,lked:tn,nded:tn,cted:tn,dged:tn,akis:on,cede:Xa,chuk:on,czyk:on,ects:Ya,ends:nn,enko:on,ette:en,fies:Ya,fore:rn,gate:Xa,gone:Za,ices:an,ints:an,ines:an,ions:an,less:rn,llen:Za,made:Za,nsen:on,oses:Ya,ould:"Modal",some:Za,sson:on,tage:Xa,teen:"Value",tion:en,tive:Za,tors:"Noun",vice:en},{tized:tn,urned:tn,eased:tn,ances:an,bound:Za,ettes:an,fully:rn,ishes:Ya,ities:an,marek:on,nssen:on,ology:"Noun",ports:an,rough:Za,tches:Ya,tieth:"Ordinal",tures:an,wards:rn,where:rn},{auskas:on,keeper:"Actor",logist:"Actor",teenth:"Value"},{opoulos:on,borough:"Place",sdottir:on}],un=/^(\u00a9|\u00ae|[\u2319-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])/,cn={":(":!0,":)":!0,":P":!0,":p":!0,":O":!0,":3":!0,":|":!0,":/":!0,":\\":!0,":$":!0,":*":!0,":@":!0,":-(":!0,":-)":!0,":-P":!0,":-p":!0,":-O":!0,":-3":!0,":-|":!0,":-/":!0,":-\\":!0,":-$":!0,":-*":!0,":-@":!0,":^(":!0,":^)":!0,":^P":!0,":^p":!0,":^O":!0,":^3":!0,":^|":!0,":^/":!0,":^\\":!0,":^$":!0,":^*":!0,":^@":!0,"):":!0,"(:":!0,"$:":!0,"*:":!0,")-:":!0,"(-:":!0,"$-:":!0,"*-:":!0,")^:":!0,"(^:":!0,"$^:":!0,"*^:":!0,"<3":!0,"2){let e=r.clean[r.clean.length-2];if("s"===e)return void r.tag(["Possessive","Noun"],"end-tick",n);"n"===e&&r.tag(["Gerund"],"chillin",n)}Ja.test(r.text)&&r.tag("Unit","per-sec",n)},regex:function(e,t){let n=e.text;for(let r=0;r=2&&Sa.test(n)&&_a.test(n)&&e.tag("RomanNumeral","xvii",t)},suffix:function(e,t){!function(e,t){const n=e.clean.length;let r=7;n<=r&&(r=n-1);for(let a=r;a>1;a-=1){let r=e.clean.substr(n-a,n);if(!0===ln[r.length].hasOwnProperty(r)){let n=ln[r.length][r];e.tagSafe(n,"suffix -"+r,t);break}}}(e,t),function(e,t){let n=e.clean,r=n[n.length-1];if(!0===sn.hasOwnProperty(r)){let a=sn[r];for(let i=0;i{let n=e.pre+e.text+e.post;var r;n=n.trim(),n=n.replace(/[.!?,]$/,""),!0===(e=>!(":"!==e.charAt(0)||null===e.match(/:.?$/)||e.match(" ")||e.length>35))(n)&&(e.tag("Emoji","comma-emoji",t),e.text=n,e.pre=e.pre.replace(":",""),e.post=e.post.replace(":","")),e.text.match(un)&&(e.tag("Emoji","unicode-emoji",t),e.text=n),!0===(r=(r=n).replace(/^[:;]/,":"),cn.hasOwnProperty(r))&&(e.tag("Emoticon","emoticon-emoji",t),e.text=n)}};var dn=function(e,t){let n=e.world;hn.lexicon(t,n);for(let e=0;ea.tags[e]));if(void 0!==e){let n=gn.afterThisPos[e];r.tag(n,"after-"+e,t);continue}}let i=e[n+1];if(i){if(!0===gn.beforeThisWord.hasOwnProperty(i.clean)){let e=gn.beforeThisWord[i.clean];r.tag(e,"before-"+i.clean,t);continue}let e=mn.find((e=>i.tags[e]));if(void 0!==e){let n=gn.beforeThisPos[e];r.tag(n,"before-"+e,t);continue}}}};const bn=/^[A-Z][a-z'\u00C0-\u00FF]/,yn=/[0-9]/;var vn=function(e){let t=e.world;e.list.forEach((e=>{let n=e.terms();for(let e=1;e{if(!0!==e.isKnown()&&!0===wn.test(e.clean)){let r=e.clean.replace(kn,"");r&&r.length>3&&void 0!==n[r]&&!0===n.hasOwnProperty(r)&&e.tag(n[r],"stem-"+r,t)}}))};const Dn=["Uncountable","Pronoun","Place","Value","Person","Month","WeekDay","Holiday"],$n={isSingular:[/(ax|test)is$/i,/(octop|vir|radi|nucle|fung|cact|stimul)us$/i,/(octop|vir)i$/i,/(rl)f$/i,/(alias|status)$/i,/(bu)s$/i,/(al|ad|at|er|et|ed|ad)o$/i,/(ti)um$/i,/(ti)a$/i,/sis$/i,/(?:(^f)fe|(lr)f)$/i,/hive$/i,/s[aeiou]+ns$/i,/(^aeiouy|qu)y$/i,/(x|ch|ss|sh|z)$/i,/(matr|vert|ind|cort)(ix|ex)$/i,/(m|l)ouse$/i,/(m|l)ice$/i,/(antenn|formul|nebul|vertebr|vit)a$/i,/.sis$/i,/^(?!talis|.*hu)(.*)man$/i],isPlural:[/(^v)ies$/i,/ises$/i,/ives$/i,/(antenn|formul|nebul|vertebr|vit)ae$/i,/(octop|vir|radi|nucle|fung|cact|stimul)i$/i,/(buffal|tomat|tornad)oes$/i,/(analy|ba|diagno|parenthe|progno|synop|the)ses$/i,/(vert|ind|cort)ices$/i,/(matr|append)ices$/i,/(x|ch|ss|sh|s|z|o)es$/i,/is$/i,/men$/i,/news$/i,/.tia$/i,/(^f)ves$/i,/(lr)ves$/i,/(^aeiouy|qu)ies$/i,/(m|l)ice$/i,/(cris|ax|test)es$/i,/(alias|status)es$/i,/ics$/i]},Pn=[/ss$/,/sis$/,/[^aeiou][uo]s$/,/'s$/],En=[/i$/,/ae$/];var Hn=function(e,t){if(e.tags.Noun&&!e.tags.Acronym){let n=e.clean;if(e.tags.Singular||e.tags.Plural)return;if(n.length<=3)return void e.tag("Singular","short-singular",t);if(Dn.find((t=>e.tags[t])))return;if($n.isPlural.find((e=>e.test(n))))return void e.tag("Plural","plural-rules",t);if($n.isSingular.find((e=>e.test(n))))return void e.tag("Singular","singular-rules",t);if(!0===/s$/.test(n)){if(Pn.find((e=>e.test(n))))return;return void e.tag("Plural","plural-fallback",t)}if(En.find((e=>e.test(n))))return;e.tag("Singular","singular-fallback",t)}};let jn=["academy","administration","agence","agences","agencies","agency","airlines","airways","army","assoc","associates","association","assurance","authority","autorite","aviation","bank","banque","board","boys","brands","brewery","brotherhood","brothers","building society","bureau","cafe","caisse","capital","care","cathedral","center","central bank","centre","chemicals","choir","chronicle","church","circus","clinic","clinique","club","co","coalition","coffee","collective","college","commission","committee","communications","community","company","comprehensive","computers","confederation","conference","conseil","consulting","containers","corporation","corps","corp","council","crew","daily news","data","departement","department","department store","departments","design","development","directorate","division","drilling","education","eglise","electric","electricity","energy","ensemble","enterprise","enterprises","entertainment","estate","etat","evening news","faculty","federation","financial","fm","foundation","fund","gas","gazette","girls","government","group","guild","health authority","herald","holdings","hospital","hotel","hotels","inc","industries","institut","institute","institute of technology","institutes","insurance","international","interstate","investment","investments","investors","journal","laboratory","labs","liberation army","limited","local authority","local health authority","machines","magazine","management","marine","marketing","markets","media","memorial","mercantile exchange","ministere","ministry","military","mobile","motor","motors","musee","museum","news","news service","observatory","office","oil","optical","orchestra","organization","partners","partnership","people's party","petrol","petroleum","pharmacare","pharmaceutical","pharmaceuticals","pizza","plc","police","polytechnic","post","power","press","productions","quartet","radio","regional authority","regional health authority","reserve","resources","restaurant","restaurants","savings","school","securities","service","services","social club","societe","society","sons","standard","state police","state university","stock exchange","subcommittee","syndicat","systems","telecommunications","telegraph","television","times","tribunal","tv","union","university","utilities","workers"].reduce((function(e,t){return e[t]="Noun",e}),{});const Nn=function(e){return!(!e.tags.Noun||e.tags.Pronoun||e.tags.Comma||e.tags.Possessive||!(e.tags.Organization||e.tags.Acronym||e.tags.Place||e.titleCase()))},xn=/^[A-Z]('s|,)?$/,Fn=/([A-Z]\.){2}[A-Z]?/i,Cn={I:!0,A:!0},Bn={neighbours:fn,case:vn,stem:An,plural:Hn,organizations:function(e,t){for(let n=0;n{!0!==e.tags.RomanNumeral&&(!0===Fn.test(e.text)&&e.tag("Acronym","period-acronym",t),e.isUpperCase()&&function(e,t){let n=e.reduced;return!!e.tags.Acronym||!t.words[n]&&!(n.length>5)&&e.isAcronym()}(e,t)?(e.tag("Acronym","acronym-step",t),e.tag("Noun","acronym-infer",t)):!Cn.hasOwnProperty(e.text)&&xn.test(e.text)&&(e.tag("Acronym","one-letter-acronym",t),e.tag("Noun","one-letter-infer",t)),e.tags.Organization&&e.text.length<=3&&e.tag("Acronym","acronym-org",t),e.tags.Organization&&e.isUpperCase()&&e.text.length<=6&&e.tag("Acronym","acronym-org-case",t))}))}};var Gn=function(e,t){let n=e.world;return Bn.neighbours(t,n),Bn.case(e),Bn.stem(t,n),t.forEach((t=>{!1===t.isKnown()&&t.tag("Noun","noun-fallback",e.world)})),Bn.organizations(t,n),Bn.acronyms(t,n),t.forEach((t=>{Bn.plural(t,e.world)})),e};const zn=/n't$/,In={"won't":["will","not"],wont:["will","not"],"can't":["can","not"],cant:["can","not"],cannot:["can","not"],"shan't":["should","not"],dont:["do","not"],dun:["do","not"]},On=/([a-z\u00C0-\u00FF]+)[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]([a-z]{1,2})$/i,Tn={ll:"will",ve:"have",re:"are",m:"am","n't":"not"},Vn={wanna:["want","to"],gonna:["going","to"],im:["i","am"],alot:["a","lot"],ive:["i","have"],imma:["I","will"],"where'd":["where","did"],whered:["where","did"],"when'd":["when","did"],whend:["when","did"],howd:["how","did"],whatd:["what","did"],dunno:["do","not","know"],brb:["be","right","back"],gtg:["got","to","go"],irl:["in","real","life"],tbh:["to","be","honest"],imo:["in","my","opinion"],til:["today","i","learned"],rn:["right","now"],twas:["it","was"],"@":["at"]},Mn=/([a-z\u00C0-\u00FF]+)[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]s$/i,Jn={that:!0,there:!0},Ln={here:!0,there:!0,everywhere:!0},Sn=/[a-z\u00C0-\u00FF]'d$/,_n={how:!0,what:!0},Kn=/^([0-9.]{1,3}[a-z]{0,2}) ?[-–—] ?([0-9]{1,3}[a-z]{0,2})$/i,qn=/^([0-9][0-9]?(:[0-9][0-9])?(am|pm)?) ?[-–—] ?([0-9][0-9]?(:[0-9][0-9])?(am|pm)?)$/i,Wn=/^(l|c|d|j|m|n|qu|s|t)[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]([a-z\u00C0-\u00FF]+)$/i,Rn={l:"le",c:"ce",d:"de",j:"je",m:"me",n:"ne",qu:"que",s:"se",t:"tu"},Un=Va,Qn=xt,Zn=function(e,t){return!0===In.hasOwnProperty(e.clean)?In[e.clean]:"ain't"===e.clean||"aint"===e.clean?function(e,t){let n=t.terms(),r=n.indexOf(e),a=n.slice(0,r).find((e=>e.tags.Noun));return a&&a.tags.Plural?["are","not"]:["is","not"]}(e,t):!0===zn.test(e.clean)?[e.clean.replace(zn,""),"not"]:null},Xn=function(e){let t=e.text.match(On);return null===t?null:Tn.hasOwnProperty(t[2])?[t[1],Tn[t[2]]]:null},Yn=function(e){return Vn.hasOwnProperty(e.clean)?Vn[e.clean]:null},ei=function(e,t,n){let r=e.text.match(Mn);if(null!==r){if(!0===((e,t)=>{if(e.tags.Possessive)return!0;if(e.tags.Pronoun||e.tags.QuestionWord)return!1;if(Jn.hasOwnProperty(e.reduced))return!1;let n=t.get(e.next);if(!n)return!0;if(n.tags.Verb)return!!n.tags.Infinitive||!!n.tags.PresentTense;if(n.tags.Noun)return!0!==Ln.hasOwnProperty(n.reduced);let r=t.get(n.next);return!(!r||!r.tags.Noun||r.tags.Pronoun)||(n.tags.Adjective||n.tags.Adverb||n.tags.Verb,!1)})(e,t.pool))return e.tag("#Possessive","isPossessive",n),null;if(null!==r)return((e,t)=>{let n=t.terms(),r=n.indexOf(e);return n.slice(r+1,r+3).find((e=>e.tags.PastTense))})(e,t)?[r[1],"has"]:[r[1],"is"]}return null},ti=function(e,t){if(Sn.test(e.clean)){let n=e.clean.replace(/'d$/,""),r=t.terms(),a=r.indexOf(e),i=r.slice(a+1,a+4);for(let e=0;e{e.implicit=e.text,e.text="",e.clean="",e.pre="",e.post="",0===Object.keys(e.tags).length&&(e.tags.Noun=!0)})),n};var li=function(e){let t=e.world;return e.list.forEach((n=>{let r=n.terms();for(let a=0;ae.list[t])),e.buildFrom(n)};var ci=function(e){let t=ui(e,"Infinitive");return t.found&&(t=t.ifNo("@hasQuestionMark"),t=t.ifNo("(i|we|they)"),t.not("will be").match("[#Infinitive] (#Determiner|#Possessive) #Noun").notIf("(our|their)").match("#Infinitive").tag("Imperative","shut-the"),t.match("^[#Infinitive] #Adverb?$",0).tag("Imperative","go-fast"),t.match("[(do && #Infinitive)] not? #Verb",0).tag("Imperative","do-not"),t.match("[#Infinitive] (it|some) (#Comparative|#Preposition|please|now|again)",0).tag("Imperative","do-it")),t=function(e,t){let n=e._cache.words.like||[];return n=n.map((t=>e.list[t])),e.buildFrom(n)}(e),t.match("#Adverb like").notIf("(really|generally|typically|usually|sometimes|often|just) [like]").tag("Adverb","adverb-like"),t=ui(e,"Adjective"),t.match("#Determiner #Adjective$").notIf("(#Comparative|#Superlative)").terms(1).tag("Noun","the-adj-1"),t=ui(e,"FirstName"),t.match("#FirstName (#Noun|@titleCase)").ifNo("^#Possessive").ifNo("(#Pronoun|#Plural)").ifNo("@hasComma .").lastTerm().tag("#LastName","firstname-noun"),t=ui(e,"Value"),t=t.match("#Value #PresentTense").ifNo("#Copula"),t.found&&(!0===t.has("(one|1)")?t.terms(1).tag("Singular","one-presentTense"):t.terms(1).tag("Plural","value-presentTense")),e.match("^(well|so|okay)").tag("Expression","well-"),e.match("#Value [of a second]",0).unTag("Value","of-a-second"),e.match("#Value [seconds]",0).unTag("Value","30-seconds").tag(["Unit","Plural"]),t=ui(e,"Gerund"),t.match("(be|been) (#Adverb|not)+? #Gerund").not("#Verb$").tag("Auxiliary","be-walking"),e.match("(try|use|attempt|build|make) #Verb").ifNo("(@hasComma|#Negative|#PhrasalVerb|#Copula|will|be)").lastTerm().tag("#Noun","do-verb"),t=ui(e,"Possessive"),t=t.match("#Possessive [#Infinitive]",0),t.lookBehind("(let|made|make|force|ask)").found||t.tag("Noun","her-match"),e},hi=function(e){let t={};for(let n=0;n{e.reg=ji(e.match);let t=function(e){let t=[];if(1===e.reg.filter((e=>void 0!==e.fastOr)).length){let n=e.reg.findIndex((e=>void 0!==e.fastOr));Object.keys(e.reg[n].fastOr).forEach((r=>{let a=Object.assign({},e);a.reg=a.reg.slice(0),a.reg[n]=Object.assign({},a.reg[n]),a.reg[n].word=r,delete a.reg[n].operator,delete a.reg[n].fastOr,t.push(a)}))}return t}(e);t.length>0?Fi=Fi.concat(t):Fi.push(e)})),Fi.forEach((e=>(e.required=function(e){let t=[],n=[];return e.forEach((e=>{!0!==e.optional&&!0!==e.negative&&(void 0!==e.tag&&t.push(e.tag),void 0!==e.word&&n.push(e.word))})),{tags:Ni(t),words:Ni(n)}}(e.reg),e)));const Ci=Fi,Bi=hi,Gi=ci,zi=function(e){Ci.forEach((t=>{let n=[];t.required.words.forEach((t=>{n.push(e._cache.words[t]||[])})),t.required.tags.forEach((t=>{n.push(e._cache.tags[t]||[])}));let r=function(e){if(0===e.length)return[];let t={};e.forEach((e=>{e=Bi(e);for(let n=0;nt[n]===e.length)),n=n.map((e=>Number(e))),n}(n);if(0===r.length)return;let a=r.map((t=>e.list[t])),i=e.buildFrom(a).match(t.reg,t.group);i.found&&(!0===t.safe?i.tagSafe(t.tag,t.reason):i.tag(t.tag,t.reason))}))},Ii=dn,Oi=Gn,Ti=li,Vi=function(e){return zi(e),Gi(e),e};var Mi=function(e){let t=e.termList();return e=Ii(e,t),e=Oi(e,t),(e=Ti(e)).cache(),(e=Vi(e)).uncache(),e.world.taggers.forEach((t=>{t(e)})),e},Ji=function(e){class t extends e{stripPeriods(){return this.termList().forEach((e=>{!0===e.tags.Abbreviation&&e.next&&(e.post=e.post.replace(/^\./,""));let t=e.text.replace(/\./,"");e.set(t)})),this}addPeriods(){return this.termList().forEach((e=>{e.post=e.post.replace(/^\./,""),e.post="."+e.post})),this}}return t.prototype.unwrap=t.prototype.stripPeriods,e.prototype.abbreviations=function(e){let n=this.match("#Abbreviation");return"number"==typeof e&&(n=n.get(e)),new t(n.list,this,this.world)},e};const Li=/\./;var Si=function(e){class t extends e{stripPeriods(){return this.termList().forEach((e=>{let t=e.text.replace(/\./g,"");e.set(t)})),this}addPeriods(){return this.termList().forEach((e=>{let t=e.text.replace(/\./g,"");t=t.split("").join("."),!1===Li.test(e.post)&&(t+="."),e.set(t)})),this}}return t.prototype.unwrap=t.prototype.stripPeriods,t.prototype.strip=t.prototype.stripPeriods,e.prototype.acronyms=function(e){let n=this.match("#Acronym");return"number"==typeof e&&(n=n.get(e)),new t(n.list,this,this.world)},e},_i=function(e){return e.prototype.clauses=function(t){let n=this.if("@hasComma").notIf("@hasComma @hasComma").notIf("@hasComma . .? (and|or) .").notIf("(#City && @hasComma) #Country").notIf("(#WeekDay && @hasComma) #Date").notIf("(#Date && @hasComma) #Year").notIf("@hasComma (too|also)$").match("@hasComma"),r=this.splitAfter(n),a=r.quotations();r=r.splitOn(a);let i=r.parentheses();r=r.splitOn(i);let o=r.if("#Copula #Adjective #Conjunction (#Pronoun|#Determiner) #Verb").match("#Conjunction");r=r.splitBefore(o);let s=r.if("if .{2,9} then .").match("then");r=r.splitBefore(s),r=r.splitBefore("as well as ."),r=r.splitBefore("such as ."),r=r.splitBefore("in addition to ."),r=r.splitAfter("@hasSemicolon"),r=r.splitAfter("@hasDash");let l=r.filter((e=>e.wordCount()>5&&e.match("#Verb+").length>=2));if(l.found){let e=l.splitAfter("#Noun .* #Verb .* #Noun+");r=r.splitOn(e.eq(0))}return"number"==typeof t&&(r=r.get(t)),new e(r.list,this,this.world)},e},Ki=function(e){class t extends e{constructor(e,t,n){super(e,t,n),this.contracted=null}expand(){return this.list.forEach((e=>{let t=e.terms(),n=t[0].isTitleCase();t.forEach(((e,n)=>{e.set(e.implicit||e.text),e.implicit=void 0,n{let r=t(n).beforeLast;r.append(e),r.termList(0).addPunctuation(",")})),this}remove(e){return this.items().if(e).remove()}hasOxfordComma(){return this.filter((e=>t(e).hasOxford))}addOxfordComma(){let e=this.items(),t=e.eq(e.length-2);return t.found&&!1===t.has("@hasComma")&&t.post(", "),this}removeOxfordComma(){let e=this.items(),t=e.eq(e.length-2);return t.found&&!0===t.has("@hasComma")&&t.post(" "),this}}return n.prototype.things=n.prototype.items,e.prototype.lists=function(e){let t=this.if("@hasComma+ .? (and|or) not? ."),r=t.match("(#Noun|#Adjective|#Determiner|#Article)+ #Conjunction not? (#Article|#Determiner)? #Adjective? #Noun+").if("#Noun"),a=t.match("(#Adjective|#Adverb)+ #Conjunction not? #Adverb? #Adjective+"),i=t.match("(#Verb|#Adverb)+ #Conjunction not? #Adverb? #Verb+"),o=r.concat(a);return o=o.concat(i),o=o.if("@hasComma"),"number"==typeof e&&(o=t.get(e)),new n(o.list,this,this.world)},e};const Wi={hour:"an",heir:"an",heirloom:"an",honest:"an",honour:"an",honor:"an",uber:"an"},Ri={a:!0,e:!0,f:!0,h:!0,i:!0,l:!0,m:!0,n:!0,o:!0,r:!0,s:!0,x:!0},Ui=[/^onc?e/i,/^u[bcfhjkqrstn][aeiou]/i,/^eul/i],Qi={isSingular:[/(ax|test)is$/i,/(octop|vir|radi|nucle|fung|cact|stimul)us$/i,/(octop|vir)i$/i,/(rl)f$/i,/(alias|status)$/i,/(bu)s$/i,/(al|ad|at|er|et|ed|ad)o$/i,/(ti)um$/i,/(ti)a$/i,/sis$/i,/(?:(^f)fe|(lr)f)$/i,/hive$/i,/(^aeiouy|qu)y$/i,/(x|ch|ss|sh|z)$/i,/(matr|vert|ind|cort)(ix|ex)$/i,/(m|l)ouse$/i,/(m|l)ice$/i,/(antenn|formul|nebul|vertebr|vit)a$/i,/.sis$/i,/^(?!talis|.*hu)(.*)man$/i],isPlural:[/(antenn|formul|nebul|vertebr|vit)ae$/i,/(octop|vir|radi|nucle|fung|cact|stimul)i$/i,/men$/i,/.tia$/i,/(m|l)ice$/i]},Zi=/s$/,Xi={he:"his",she:"hers",they:"theirs",we:"ours",i:"mine",you:"yours",her:"hers",their:"theirs",our:"ours",my:"mine",your:"yours"},Yi=function(e){return!0===e.has("#Plural")||!0!==e.has("(#Pronoun|#Place|#Value|#Person|#Uncountable|#Month|#WeekDay|#Holiday|#Possessive)")},eo=function(e){if(e.has("#Person")||e.has("#Place"))return"";if(e.has("#Plural"))return"the";let t=e.text("normal").trim();if(Wi.hasOwnProperty(t))return Wi[t];let n=t.substr(0,1);if(e.has("^@isAcronym")&&Ri.hasOwnProperty(n))return"an";for(let e=0;et.test(e)))&&(!0===Zi.test(e)||!!Qi.isPlural.find((t=>t.test(e)))||null)},ro=function(e){let t=e.text("text").trim();return Xi.hasOwnProperty(t)?(e.replaceWith(Xi[t],!0),void e.tag("Possessive","toPossessive")):/s$/.test(t)?(t+="'",e.replaceWith(t,!0),void e.tag("Possessive","toPossessive")):(t+="'s",e.replaceWith(t,!0),void e.tag("Possessive","toPossessive"))},ao=function(e){let t={main:e};if(e.has("#Noun (of|by|for) .")){let n=e.splitAfter("[#Noun+]",0);t.main=n.eq(0),t.post=n.eq(1)}return t},no={json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0];r.article=eo(t),n.push(r)})),null!==t?n[t]:n},adjectives:function(){let e=this.lookAhead("^(that|who|which)? (was|is|will)? be? #Adverb? #Adjective+");return e=e.concat(this.lookBehind("#Adjective+ #Adverb?$")),e=e.match("#Adjective"),e.sort("index")},isPlural:function(){return this.if("#Plural")},hasPlural:function(){return this.filter((e=>Yi(e)))},toPlural:function(e){let t=this.world.transforms.toPlural;return this.forEach((n=>{if(n.has("#Plural")||!1===Yi(n))return;let r=ao(n).main,a=r.text("reduced");if((r.has("#Singular")||!0!==to(a))&&(a=t(a,this.world),r.replace(a).tag("#Plural"),e)){let e=r.lookBefore("(an|a) #Adjective?$").not("#Adjective");!0===e.found&&e.remove()}})),this},toSingular:function(e){let t=this.world.transforms.toSingular;return this.forEach((n=>{if(n.has("^#Singular+$")||!1===Yi(n))return;let r=ao(n).main,a=r.text("reduced");if((r.has("#Plural")||!0===to(a))&&(a=t(a,this.world),r.replace(a).tag("#Singular"),e)){let e=n,t=n.lookBefore("#Adjective");t.found&&(e=t);let r=eo(e);e.insertBefore(r)}})),this},toPossessive:function(){return this.forEach((e=>{ro(e)})),this}};var io=function(e){class t extends e{}return Object.assign(t.prototype,no),e.prototype.nouns=function(e,n={}){let r=this.match("(#City && @hasComma) (#Region|#Country)"),a=this.not(r).splitAfter("@hasComma");a=a.concat(r);let i=a.quotations();return i.found&&(a=a.splitOn(i.eq(0))),a=a.match("#Noun+ (of|by)? the? #Noun+?"),!0!==n.keep_anaphora&&(a=a.not("#Pronoun"),a=a.not("(there|these)"),a=a.not("(#Month|#WeekDay)"),a=a.not("(my|our|your|their|her|his)")),a=a.not("(of|for|by|the)$"),"number"==typeof e&&(a=a.get(e)),new t(a.list,this,this.world)},e};const oo=/\(/,so=/\)/;var lo=function(e){class t extends e{unwrap(){return this.list.forEach((e=>{let t=e.terms(0);t.pre=t.pre.replace(oo,"");let n=e.lastTerm();n.post=n.post.replace(so,"")})),this}}return e.prototype.parentheses=function(e){let n=[];return this.list.forEach((e=>{let t=e.terms();for(let r=0;r{e.terms().forEach((e=>{let t=e.text.replace(/'s$/,"");e.set(t||e.text)}))})),this}}return e.prototype.possessives=function(e){let n=this.match("#Noun+? #Possessive");return"number"==typeof e&&(n=n.get(e)),new t(n.list,this,this.world)},e};const co={'"':'"',""":""","'":"'","“":"”","‘":"’","‟":"”","‛":"’","„":"”","⹂":"”","‚":"’","«":"»","‹":"›","‵":"′","‶":"″","‷":"‴","〝":"〞","`":"´","〟":"〞"},ho=RegExp("("+Object.keys(co).join("|")+")");var go=function(e){class t extends e{unwrap(){return this}}return e.prototype.quotations=function(e){let n=[];return this.list.forEach((e=>{let t=e.terms();for(let r=0;r{let t=!1,n=wo(e),r=e.negative.found;e.verb.lookBehind("i (#Adverb|#Verb)?$").found&&(t=!0);let a={PastTense:"was",PresentTense:"is",FutureTense:"will be",Infinitive:"is",Gerund:"being",Actor:"",PerfectTense:"been",Pluperfect:"been"};return n&&(a.PastTense="were",a.PresentTense="are",a.Infinitive="are"),!0===t&&(a.PastTense="was",a.PresentTense="am",a.Infinitive="am"),r&&(a.PastTense+=" not",a.PresentTense+=" not",a.FutureTense="will not be",a.Infinitive+=" not",a.PerfectTense="not "+a.PerfectTense,a.Pluperfect="not "+a.Pluperfect,a.Gerund="not "+a.Gerund),a},Do=function(e){let t=e.verb.text();return{PastTense:t+" have",PresentTense:t,FutureTense:t,Infinitive:t}},$o=mo;var Po=function(e,t){let n=e.verb;if(n.has("#Copula")||"be"===n.out("normal")&&e.auxiliary.has("will"))return Ao(e);if(e.auxiliary.has("are")&&n.has("#Gerund")){let n=e.original.clone(),r=n.clone().replace("are","were"),a=n.clone().replace("are","will be"),i=ko(e,t);return{PastTense:r.text(),PresentTense:n.text(),FutureTense:a.text(),Infinitive:i}}if(n.has("#Modal"))return Do(e);let r=ko(e,t);if(!r)return{};let a=t.transforms.conjugate(r,t);a.Infinitive=r;let i=$o(e);!0===i&&(a.PresentTense=a.Infinitive);let o=e.verb.termList(0).hasHyphen();if(e.particle.found){let t=e.particle.text(),n=!0===o?"-":" ";Object.keys(a).forEach((e=>a[e]+=n+t))}const s=e.negative.found;return a.FutureTense=a.FutureTense||"will "+a.Infinitive,s&&(a.PastTense="did not "+a.Infinitive,a.FutureTense="will not "+a.Infinitive,i?(a.PresentTense="do not "+a.Infinitive,a.Infinitive="do not "+a.Infinitive):(a.PresentTense="does not "+a.Infinitive,a.Infinitive="does not "+a.Infinitive),a.Gerund="not "+a.Gerund),a};const Eo=Po;var Ho={useParticiple:function(e){return!!e.auxiliary.has("(could|should|would|may|can|must)")||!!e.auxiliary.has("am .+? being")||!!e.auxiliary.has("had .+? been")},toParticiple:function(e,t){if(e.auxiliary.has("(have|had)")&&e.verb.has("#Participle"))return;let n=Eo(e,t),r=n.Participle||n.PastTense;r&&e.verb.replaceWith(r,!1),e.auxiliary.has("am .+? being")&&(e.auxiliary.remove("am"),e.auxiliary.replace("being","have been")),e.auxiliary.has("have")||e.auxiliary.append("have"),e.verb.tag("Participle","toParticiple"),e.auxiliary.replace("can","could"),e.auxiliary.replace("be have","have been"),e.auxiliary.replace("not have","have not"),e.auxiliary.tag("Auxiliary")}};const jo=function(e,t){let n=e.verb;if(!e.negative.found){if(e.auxiliary.found)return e.auxiliary.eq(0).append("not"),void(e.auxiliary.has("#Modal have not")&&e.auxiliary.replace("have not","not have"));if(n.has("(#Copula|will|has|had|do)"))n.append("not");else{if(n.has("#PastTense")){let r=fo(e,t);return n.replaceWith(r,!0),void n.prepend("did not")}if(n.has("#PresentTense")){let r=fo(e,t);return n.replaceWith(r,!0),void(bo(e)?n.prepend("do not"):n.prepend("does not"))}if(n.has("#Gerund")){let r=fo(e,t);return n.replaceWith(r,!0),void n.prepend("not")}bo(e)?n.prepend("does not"):n.prepend("do not")}}},No=function(e){let t={adverb:e.match("#Adverb+"),negative:e.match("#Negative"),auxiliary:e.match("#Auxiliary+").not("(#Negative|#Adverb)"),particle:e.match("#Particle"),verb:e.match("#Verb+").not("(#Adverb|#Negative|#Auxiliary|#Particle)"),original:e,subject:vo(e)};if(t.verb.has("(#PresentTense|#PastTense|#Infinitive) #Gerund$")&&(t.verb=t.verb.not("#Gerund$")),!t.verb.found)return Object.keys(t).forEach((e=>{t[e]=t[e].not(".")})),t.verb=e,t;if(t.adverb&&t.adverb.found){let n=t.adverb.text("reduced")+"$";e.has(n)&&(t.adverbAfter=!0)}return t},xo=mo,Fo=yo,Co=Po,{toParticiple:Bo,useParticiple:Go}=Ho,zo=function(e){return e.auxiliary.remove("(will|are|am|being)"),e.auxiliary.remove("(did|does)"),e.auxiliary.remove("(had|has|have)"),e.particle.remove(),e.negative.remove(),e},Io={json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=No(t);r.parts={},Object.keys(a).forEach((e=>{a[e]&&"Doc"===a[e].isA?r.parts[e]=a[e].text("normal"):r.parts[e]=a[e]})),r.isNegative=t.has("#Negative"),r.conjugations=Co(a,this.world),n.push(r)})),null!==t?n[t]:n},adverbs:function(){let e=[];this.forEach((t=>{let n=No(t).adverb;n.found&&(e=e.concat(n.list))}));let t=this.lookBehind("#Adverb+$");return t.found&&(e=t.list.concat(e)),t=this.lookAhead("^#Adverb+"),t.found&&(e=e.concat(t.list)),this.buildFrom(e)},isPlural:function(){let e=[];return this.forEach((t=>{let n=No(t);!0===xo(n,this.world)&&e.push(t.list[0])})),this.buildFrom(e)},isSingular:function(){let e=[];return this.forEach((t=>{let n=No(t);!1===xo(n,this.world)&&e.push(t.list[0])})),this.buildFrom(e)},conjugate:function(){let e=[];return this.forEach((t=>{let n=No(t),r=Co(n,this.world);e.push(r)})),e},toPastTense:function(){return this.forEach((e=>{let t=No(e);if(Go(t))return void Bo(t,this.world);if(e.has("#Imperative"))return;if(e.has("be")&&e.lookBehind("to$").found)return;if(t.verb.has("#Gerund")&&t.auxiliary.has("(is|will|was)"))return void e.replace("is","was");let n=Co(t,this.world).PastTense;n&&(t=zo(t),t.verb.replaceWith(n,!1),t.auxiliary.remove("(do|did|will)"))})),this},toPresentTense:function(){return this.forEach((e=>{if(e.has("#Imperative"))return;let t=No(e),n=Co(t,this.world),r=n.PresentTense;if(e.lookBehind("(i|we) (#Adverb|#Verb)?$").found&&(r=n.Infinitive),r){if(t.auxiliary.has("(have|had) been"))return t.auxiliary.replace("(have|had) been","am being"),void(n.Particle&&(r=n.Particle||n.PastTense));t.verb.replaceWith(r,!1),t.verb.tag("PresentTense"),t=zo(t),t.auxiliary.remove("#Modal"),t.auxiliary.remove("(do|did|will)")}})),this},toFutureTense:function(){return this.forEach((e=>{let t=No(e);if(Go(t))return;if(e.has("#Imperative"))return;let n=Co(t,this.world).FutureTense;n&&(t=zo(t),t.auxiliary.remove("#Modal"),t.verb.replaceWith(n,!1),t.verb.tag("FutureTense"),t.auxiliary.remove("(do|did|will)"))})),this},toInfinitive:function(){return this.forEach((e=>{let t=No(e),n=Co(t,this.world).Infinitive;n&&(e.replaceWith(n,!1),e.tag("Infinitive"))})),this},toGerund:function(){return this.forEach((e=>{let t=No(e),n=Co(t,this.world).Gerund;n&&(e.replaceWith(n,!1),e.tag("Gerund"))})),this},toParticiple:function(){return this.forEach((e=>{let t=No(e),n=!t.auxiliary.found;Bo(t,this.world),n&&(t.verb.prepend(t.auxiliary.text()),t.auxiliary.remove())})),this},isNegative:function(){return this.if("#Negative")},isPositive:function(){return this.ifNo("#Negative")},isImperative:function(){return this.if("#Imperative")},toNegative:function(){return this.list.forEach((e=>{let t=this.buildFrom([e]),n=No(t);jo(n,t.world)})),this},toPositive:function(){let e=this.match("do not #Verb");return e.found&&e.remove("do not"),this.remove("#Negative")},subject:function(){let e=[];return this.forEach((t=>{let n=Fo(t);n.list[0]&&e.push(n.list[0])})),this.buildFrom(e)}},Oo=Ia,To=[Ji,Si,_i,Ki,qi,io,lo,uo,go,function(e){class t extends e{}return Object.assign(t.prototype,Io),t.prototype.negate=t.prototype.toNegative,e.prototype.verbs=function(e){let n=this.match("(#Adverb|#Auxiliary|#Verb|#Negative|#Particle)+");n=n.not("^#Adverb+"),n=n.not("#Adverb+$");let r=n.match("(#Adverb && @hasComma) #Adverb"),a=n.not(r).splitAfter("@hasComma");return a=a.concat(r),a.sort("index"),a=a.if("#Verb"),a.has("(is|was)$")&&(a=a.splitBefore("(is|was)$")),a.has("#PresentTense #Adverb #PresentTense")&&(a=a.splitBefore("#Adverb #PresentTense")),"number"==typeof e&&(a=a.get(e)),new t(a.list,this,this.world)},e},function(e){class t extends e{}return e.prototype.people=function(e){let n=this.splitAfter("@hasComma");return n=n.match("#Person+"),"number"==typeof e&&(n=n.get(e)),new t(n.list,this,this.world)},e}],Vo={misc:Ga,selections:Ia},Mo=Mi,Jo=xt,Lo=function(e){return Object.keys(Oo).forEach((t=>e.prototype[t]=Oo[t])),To.forEach((t=>t(e))),e};class So{constructor(e,t,n){this.list=e,Object.defineProperty(this,"from",{enumerable:!1,value:t,writable:!0}),void 0===n&&void 0!==t&&(n=t.world),Object.defineProperty(this,"world",{enumerable:!1,value:n,writable:!0}),Object.defineProperty(this,"_cache",{enumerable:!1,writable:!0,value:{}}),Object.defineProperty(this,"found",{get:()=>this.list.length>0}),Object.defineProperty(this,"length",{get:()=>this.list.length}),Object.defineProperty(this,"isA",{get:()=>"Doc"})}tagger(){return Mo(this)}pool(){return this.list.length>0?this.list[0].pool:this.all().list[0].pool}}So.prototype.buildFrom=function(e){return e=e.map((e=>e.clone(!0))),new So(e,this,this.world)},So.prototype.fromText=function(e){let t=Jo(e,this.world,this.pool());return this.buildFrom(t)},Object.assign(So.prototype,Vo.misc),Object.assign(So.prototype,Vo.selections),Lo(So);const _o={untag:"unTag",and:"match",notIf:"ifNo",only:"if",onlyIf:"if"};Object.keys(_o).forEach((e=>So.prototype[e]=So.prototype[_o[e]]));const Ko=Va,qo=xt,Wo=zt,Ro=So,Uo=nt,Qo=ne$1,Zo=ot,Xo=function(e){let t=e.termList();return Ko(t,e.world),e.world.taggers.forEach((t=>{t(e)})),e},Yo=_e;var es=function e(t){let n=t;const r=function(e="",t){t&&n.addWords(t);let r=qo(e,n),a=new Ro(r,null,n);return a.tagger(),a};return r.tokenize=function(e="",t){let r=n;t&&(r=r.clone(),r.words={},r.addWords(t));let a=qo(e,r),i=new Ro(a,null,r);return(t||i.world.taggers.length>0)&&Xo(i),i},r.extend=function(e){return e(Ro,n,this,Uo,Qo,Zo),this},r.fromJSON=function(e){let t=Wo(e,n);return new Ro(t,null,n)},r.clone=function(){return e(n.clone())},r.verbose=function(e=!0){return n.verbose(e),this},r.world=function(){return n},r.parseMatch=function(e,t){return Yo(e,t)},r.version="13.11.4",r.import=r.load,r.plugin=r.extend,r}(new Rr),nlp=es,e=function(e,t){let n=e.match("#Value+? #Money+ #Currency+ (and #Money+ #Currency+)+?");return e.match("#Money").forEach((e=>{e.lookAfter("#Currency").found||(n=n.concat(e))})),"number"==typeof t&&(n=n.get(t)),n};const n="twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|fourty";var t=function(e,t){let r=e.match("#Value+");if(r.has("#NumericValue #NumericValue")&&(r.has("#Value @hasComma #Value")?r.splitAfter("@hasComma"):r.has("#NumericValue #Fraction")?r.splitAfter("#NumericValue #Fraction"):r=r.splitAfter("#NumericValue")),r.has("#Value #Value #Value")&&!r.has("#Multiple")&&r.has("("+n+") #Cardinal #Cardinal")&&(r=r.splitAfter("("+n+") #Cardinal")),r.has("#Value #Value")){r.has("#NumericValue #NumericValue")&&(r=r.splitOn("#Year")),r.has("("+n+") (eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen)")&&(r=r.splitAfter("("+n+")"));let e=r.match("#Cardinal #Cardinal");if(e.found&&!r.has("(point|decimal|#Fraction)")&&!e.has("#Cardinal (#Multiple|point|decimal)")){let t=r.has(`(one|two|three|four|five|six|seven|eight|nine) (${n})`),a=e.has("("+n+") #Cardinal"),i=e.has("#Multiple #Value");t||a||i||e.terms().forEach((e=>{r=r.splitOn(e)}))}r.match("#Ordinal #Ordinal").match("#TextValue").found&&!r.has("#Multiple")&&(r.has("("+n+") #Ordinal")||(r=r.splitAfter("#Ordinal"))),r.has("#Ordinal #Cardinal")&&(r=r.splitBefore("#Cardinal+")),r.has("#TextValue #NumericValue")&&!r.has("("+n+"|#Multiple)")&&(r=r.splitBefore("#NumericValue+"))}return r.has("#NumberRange")&&(r=r.splitAfter("#NumberRange")),"number"==typeof t&&(r=r.get(t)),r},r=function(e,t){let n=e.match("#Fraction+");return n=n.filter((e=>!e.lookBehind("#Value and$").found)),"number"==typeof t&&(n=n.eq(t)),n},a=function(e,t){let n=e.match("#Percent+");return n=n.concat(e.match("[#Cardinal] percent",0)),"number"==typeof t&&(n=n.eq(t)),n},i={ones:{zeroth:0,first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,zero:0,one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9},teens:{tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,ten:10,eleven:11,twelve:12,thirteen:13,fourteen:14,fifteen:15,sixteen:16,seventeen:17,eighteen:18,nineteen:19},tens:{twentieth:20,thirtieth:30,fortieth:40,fourtieth:40,fiftieth:50,sixtieth:60,seventieth:70,eightieth:80,ninetieth:90,twenty:20,thirty:30,forty:40,fourty:40,fifty:50,sixty:60,seventy:70,eighty:80,ninety:90},multiples:{hundredth:100,thousandth:1e3,millionth:1e6,billionth:1e9,trillionth:1e12,quadrillionth:1e15,quintillionth:1e18,sextillionth:1e21,septillionth:1e24,hundred:100,thousand:1e3,million:1e6,billion:1e9,trillion:1e12,quadrillion:1e15,quintillion:1e18,sextillion:1e21,septillion:1e24,grand:1e3}};const s=i,o=i,u=e=>{const t=[{reg:/^(minus|negative)[\s\-]/i,mult:-1},{reg:/^(a\s)?half[\s\-](of\s)?/i,mult:.5}];for(let n=0;n{if(s.ones.hasOwnProperty(e)){if(t.ones||t.teens)return!1}else if(s.teens.hasOwnProperty(e)){if(t.ones||t.teens||t.tens)return!1}else if(s.tens.hasOwnProperty(e)&&(t.ones||t.teens||t.tens))return!1;return!0},c$1=function(e){let t="0.";for(let n=0;n(e=(e=(e=(e=(e=(e=(e=e.replace(/1st$/,"1")).replace(/2nd$/,"2")).replace(/3rd$/,"3")).replace(/([4567890])r?th$/,"$1")).replace(/^[$€¥£¢]/,"")).replace(/[%$€¥£¢]$/,"")).replace(/,/g,"")).replace(/([0-9])([a-z\u00C0-\u00FF]{1,2})$/,"$1"),f=/^([0-9,\. ]+)\/([0-9,\. ]+)$/,d={"a few":3,"a couple":2,"a dozen":12,"two dozen":24,zero:0},y=e=>Object.keys(e).reduce(((t,n)=>t+e[n]),0);var p=function(e){if(!0===d.hasOwnProperty(e))return d[e];if("a"===e||"an"===e)return 1;const t=u(e);let n=null,r={},a=0,i=!1;const o=(e=t.str).split(/[ -]/);for(let e=0;e#Value+] out of every? [#Value+]");if(!0!==t.found)return null;let{num:n,den:r}=t.groups();return n&&r?(n=x(n),r=x(r),"number"==typeof n&&"number"==typeof r?{numerator:n,denominator:r}:null):null}(e)||function(e){let t=e.match("[(#Cardinal|a)+] [#Fraction+]");if(!0!==t.found)return null;let{num:n,dem:r}=t.groups();n=n.has("a")?1:x(n);let a=r.text("reduced");return b.test(a)&&(a=a.replace(b,""),r.replaceWith(a)),r=$.hasOwnProperty(a)?$[a]:x(r),"number"==typeof n&&"number"==typeof r?{numerator:n,denominator:r}:null}(e)||function(e){let t=e.match("^#Ordinal$");return!0!==t.found?null:e.lookAhead("^of .")?{numerator:1,denominator:x(t)}:null}(e)||null;return null!==t&&t.numerator&&t.denominator&&(t.decimal=t.numerator/t.denominator,t.decimal=(e=>{let t=Math.round(1e3*e)/1e3;return 0===t&&0!==e?e:t})(t.decimal)),t};const w=p,k=v;var C=function(e){let t=e.text("reduced"),n=/[0-9],[0-9]/.test(e.text("text")),r=function(e,t,n){let r=(e=e.replace(/,/g,"")).split(/^([^0-9]*)([0-9.,]*)([^0-9]*)$/);if(r&&r[2]&&t.terms().length<2){let t=parseFloat(r[2]||e);"number"!=typeof t&&(t=null);let n=r[3]||"";return"st"!==n&&"nd"!==n&&"rd"!==n&&"th"!==n||(n=""),"m"!==n&&"M"!==n||(t*=1e6,n=""),"k"!==n&&"k"!==n||(t*=1e3,n=""),{prefix:r[1]||"",num:t,suffix:n}}return null}(t,e);if(null!==r)return r.hasComma=n,r;let a=e.match("#Fraction #Fraction+$");a=!1===a.found?e.match("^#Fraction$"):a;let i=null;a.found&&(i=k(a),t=(e=(e=e.not(a)).not("and$")).text("reduced"));let o=0;return t&&(o=w(t)||0),i&&i.decimal&&(o+=i.decimal),{hasComma:n,prefix:"",num:o,suffix:""}},O=function(e){if(e<1e6)return String(e);let t;return t="number"==typeof e?e.toFixed(0):e,-1===t.indexOf("e+")?t:t.replace(".","").split("e+").reduce((function(e,t){return e+Array(t-e.length+2).join(0)}))};const V=O,F=[["ninety",90],["eighty",80],["seventy",70],["sixty",60],["fifty",50],["forty",40],["thirty",30],["twenty",20]],M=["","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],E=[[1e24,"septillion"],[1e20,"hundred sextillion"],[1e21,"sextillion"],[1e20,"hundred quintillion"],[1e18,"quintillion"],[1e17,"hundred quadrillion"],[1e15,"quadrillion"],[1e14,"hundred trillion"],[1e12,"trillion"],[1e11,"hundred billion"],[1e9,"billion"],[1e8,"hundred million"],[1e6,"million"],[1e5,"hundred thousand"],[1e3,"thousand"],[100,"hundred"],[1,"one"]],N=function(e){let t=[];if(e>100)return t;for(let n=0;n=F[n][1]&&(e-=F[n][1],t.push(F[n][0]));return M[e]&&t.push(M[e]),t};var P=function(e){if(0===e||"0"===e)return"zero";e>1e21&&(e=V(e));let t=[];e<0&&(t.push("minus"),e=Math.abs(e));let n=function(e){let t=e,n=[];return E.forEach((r=>{if(e>=r[0]){let e=Math.floor(t/r[0]);t-=e*r[0],e&&n.push({unit:r[1],count:e})}})),n}(e);for(let e=0;e1&&t.push("and")),t=t.concat(N(n[e].count)),t.push(r)}return t=t.concat((e=>{const t=["zero","one","two","three","four","five","six","seven","eight","nine"];let n=[],r=V(e).match(/\.([0-9]+)/);if(!r||!r[0])return n;n.push("point");let a=r[0].split("");for(let e=0;ee)),0===t.length&&(t[0]=""),t.join(" ")};const z=O,A=P,j={one:"first",two:"second",three:"third",five:"fifth",eight:"eighth",nine:"ninth",twelve:"twelfth",twenty:"twentieth",thirty:"thirtieth",forty:"fortieth",fourty:"fourtieth",fifty:"fiftieth",sixty:"sixtieth",seventy:"seventieth",eighty:"eightieth",ninety:"ninetieth"};var q=e=>{let t=A(e).split(" "),n=t[t.length-1];return j.hasOwnProperty(n)?t[t.length-1]=j[n]:t[t.length-1]=n.replace(/y$/,"i")+"th",t.join(" ")},S={prefixes:{"¢":"cents",$:"dollars","£":"pounds","¥":"yen","€":"euros","₡":"colón","฿":"baht","₭":"kip","₩":"won","₹":"rupees","₽":"ruble","₺":"liras"},suffixes:{"%":"percent",s:"seconds",cm:"centimetres",km:"kilometres"}};const T$1=O,R=P,L=function(e){if(!e&&0!==e)return null;let t=e%100;if(t>10&&t<20)return String(e)+"th";const n={0:"th",1:"st",2:"nd",3:"rd"};let r=z(e),a=r.slice(r.length-1,r.length);return r+=n[a]?n[a]:"th",r},W=q,B=S.prefixes,D=S.suffixes,U={usd:!0,eur:!0,jpy:!0,gbp:!0,cad:!0,aud:!0,chf:!0,cny:!0,hkd:!0,nzd:!0,kr:!0,rub:!0},K=function(e){return B.hasOwnProperty(e.prefix)&&(e.suffix+=B[e.prefix],e.prefix=""),D.hasOwnProperty(e.suffix)&&(e.suffix=D[e.suffix]),U.hasOwnProperty(e.suffix)&&(e.suffix=e.suffix.toUpperCase()),e.suffix&&(e.suffix=" "+e.suffix),e};var Y=function(e,t,n){let r=String(e.num);return t?(e=K(e),n?(r=W(r),`${e.prefix||""}${r}${e.suffix||""}`):(r=R(r),`${e.prefix||""}${r}${e.suffix||""}`)):n?(r=L(r),`${(e=K(e)).prefix||""}${r}${e.suffix||""}`):(!0===e.hasComma&&(r=e.num.toLocaleString()),r=T$1(r),`${e.prefix||""}${r}${e.suffix||""}`)};const G=C,H=function(e,t,n){if(!1===e)return;let r=t.lookAhead("^(#Unit|#Noun)");r.has("(#Address|#Money|#Percent)")||t.has("#Ordinal")||(1===n.num?r.nouns().toSingular():r.has("#Singular")&&r.nouns().toPlural())},I=Y,Q=p;let Z={json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=G(t);r.prefix=a.prefix,r.number=a.num,r.suffix=a.suffix,r.cardinal=I(a,!1,!1),r.ordinal=I(a,!1,!0),r.textCardinal=I(a,!0,!1),r.textOrdinal=I(a,!0,!0),n.push(r)})),null!==t?n[t]:n},units:function(){let e=this.lookAhead("(#Unit|#Noun)+");return e=e.splitAfter("@hasComma").first(),e=e.not("#Pronoun"),e.first()},isOrdinal:function(){return this.if("#Ordinal")},isCardinal:function(){return this.if("#Cardinal")},toNumber:function(){return this.forEach((e=>{let t=G(e);if(null===t.num)return;let n=I(t,!1,e.has("#Ordinal"));e.replaceWith(n,!0),e.tag("NumericValue")})),this},toLocaleString:function(){return this.forEach((e=>{let t=G(e);if(null===t.num)return;t.num=t.num.toLocaleString();let n=I(t,!1,e.has("#Ordinal"));e.replaceWith(n,!0)})),this},toText:function(){return this.forEach((e=>{let t=G(e);if(null===t.num)return;let n=I(t,!0,e.has("#Ordinal"));e.replaceWith(n,!0),e.tag("TextValue")})),this},toCardinal:function(e){return this.if("#Ordinal").forEach((t=>{let n=G(t);if(null===n.num)return;let r=I(n,t.has("#TextValue"),!1);if(t.has("#NumberRange")){let e=t.termList()[0];e.text&&""===e.post&&(e.post=" ")}t.replaceWith(r,!0),t.tag("Cardinal"),H(e,t,n)})),this},toOrdinal:function(){return this.if("#Cardinal").forEach((e=>{let t=G(e);if(null===t.num)return;let n=I(t,e.has("#TextValue"),!0);if(e.has("#NumberRange")){let t=e.termList()[0];t.text&&""===t.post&&(t.post=" ")}e.replaceWith(n,!0),e.tag("Ordinal");let r=this.lookAhead("^#Plural");r.found&&r.nouns().toSingular()})),this},isEqual:function(e){return this.filter((t=>G(t).num===e))},greaterThan:function(e){return this.filter((t=>G(t).num>e))},lessThan:function(e){return this.filter((t=>G(t).num{let r=G(n).num;return r>e&&r{let r=G(n);if(r.num=e,null===r.num)return;let a=I(r,n.has("#TextValue"),n.has("#Ordinal"));(n=n.not("#Currency")).replaceWith(a,!0),H(t,n,r)}))),this},add:function(e,t){return e?("string"==typeof e&&(e=Q(e)),this.forEach((n=>{let r=G(n);if(null===r.num)return;r.num+=e;let a=I(r,n.has("#TextValue"),n.has("#Ordinal"));(n=n.not("#Currency")).replaceWith(a,!0),H(t,n,r)})),this):this},subtract:function(e,t){return this.add(-1*e,t)},increment:function(e){return this.add(1,e),this},decrement:function(e){return this.add(-1,e),this},romanNumerals:function(e){let t=this.match("#RomanNumeral").numbers();return"number"==typeof e&&(t=t.get(e)),t},normalize:function(){const e={"%":!0};return this.forEach((t=>{let n=G(t);if(null!==n.num&&n.suffix&&!0!==e[n.suffix]){let e=n.prefix||"";t=t.replaceWith(e+n.num+" "+n.suffix)}})),this},get:function(e){let t=[];return this.forEach((e=>{t.push(G(e).num)})),void 0!==e?t[e]||null:t||null}};Z.toNice=Z.toLocaleString,Z.isBetween=Z.between,Z.minus=Z.subtract,Z.plus=Z.add,Z.equals=Z.isEqual;var J=Z;const X=C,_=function(e){let t=X(e).num;return"number"==typeof t?t/100:null};var ee={get:function(e){let t=[];return this.forEach((e=>{let n=_(e);null!==n&&t.push(n)})),void 0!==e?t[e]||null:t||null},json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=_(t);if(r.number=a,null!==a){let e=100*a;r.textNumber=`${e} percent`,r.cardinal=`${e}%`}n.push(r)})),null!==t?n[t]||{}:n},toFraction:function(){return this.forEach((e=>{let t=_(e);if(null!==t){t*=100,t=Math.round(100*t)/100;let n=`${t}/100`;this.replace(e,n)}})),this}},ne=[{dem:"american",name:"dollar",iso:"usd",sub:"cent",sym:["$","US$","U$"]},{name:"euro",iso:"eur",sub:"cent",sym:["€"]},{dem:"british",name:"pound",iso:"gbp",sub:"penny",alias:{sterling:!0},sym:["£"]},{name:"renminbi",iso:"cny",plural:"yuán",alias:{yuan:!0},sym:["元"]},{dem:"japanese",name:"yen",iso:"jpy",sub:"sen",sym:["¥","円","圓"]},{dem:"swedish",name:"krona",iso:"sek",sub:"öre",alias:{ore:!0,kronor:!0},sym:["kr"]},{dem:"estonian",name:"kroon",iso:"eek",sub:"sent",sym:["kr"]},{dem:"norwegian",name:"krone",iso:"nok",sub:"øre",sym:["kr"]},{dem:"icelandic",name:"króna",iso:"isk",sym:["kr"]},{dem:"danish",name:"krone",iso:"dkk",sub:"øre",sym:["kr."]},{dem:"zambian",name:"kwacha",iso:"zmw",sub:"ngwee",sym:["K"]},{dem:"malawian",name:"kwacha",iso:"mwk",sub:"tambala",sym:["K"]},{dem:"greek",name:"drachma",iso:"grd",sub:"leptοn",sym:["Δρχ.","Δρ.","₯"]},{dem:"eastern caribbean",name:"dollar",iso:"xcd",sub:"cent",sym:["$"]},{dem:"finnish",name:"markka",iso:"fim",sub:"penni",sym:["mk"]},{dem:"polish",name:"złoty",iso:"pln",sub:"grosz",sym:["zł"]},{dem:"slovenian",name:"tolar",iso:"sit",sub:"stotin",sym:[]},{dem:"australian",name:"dollar",iso:"aud",sub:"cent",sym:["$","A$","AU$"]},{dem:"deutsche",name:"mark",iso:"dem",sub:"pfennig",sym:["DM"]},{dem:"thai",name:"baht",iso:"thb",sub:"satang",sym:["฿"]},{dem:"canadian",name:"dollar",iso:"cad",sub:"cent",sym:["$","Can$","C$","CA$","CAD"]},{dem:"mexican",name:"peso",iso:"mxn",sub:"centavo",sym:["$","Mex$"]},{dem:"spanish",name:"peseta",iso:"esp",sub:"céntimo",sym:["Pta"]},{dem:"new zealand",name:"dollar",iso:"nzd",sub:"cent",sym:["$","NZ$"]},{dem:"chilean",name:"peso",iso:"clp",sub:"centavo",sym:["Cifrão","$"]},{dem:"nigerian",name:"naira",iso:"ngn",sub:"kobo",sym:["₦"]},{dem:"austrian",name:"schilling",iso:"ats",sub:"groschen",sym:["S","öS"]},{dem:"guatemalan",name:"quetzal",iso:"gtq",sub:"centavo",sym:["Q"]},{dem:"philippine",name:"peso",iso:"php",sub:"sentimo",sym:["₱"]},{dem:"hungarian",name:"forint",iso:"huf",sym:["Ft"]},{dem:"russian",name:"ruble",iso:"rub",sub:"kopeyka",sym:["₽","руб","р."]},{dem:"kuwaiti",name:"dinar",iso:"kwd",sub:"fils",sym:["د.ك","KD"]},{dem:"israeli",name:"new shekel",iso:"ils",sub:"agora",sym:["₪"]},{dem:"latvian",name:"lats",iso:"lvl",sub:"santīms",sym:["Ls"]},{dem:"kazakhstani",name:"tenge",iso:"kzt",sub:"tıyn",sym:["₸"]},{dem:"iraqi",name:"dinar",iso:"iqd",sub:"fils",sym:["د.ع"]},{dem:"bahamian",name:"dollar",iso:"bsd",sub:"cent",sym:["$","B$"]},{dem:"seychellois",name:"rupee",iso:"scr",sub:"cent",sym:["SCR","SR"]},{dem:"albanian",name:"lek",iso:"all",sub:"qindarkë",sym:["L"]},{dem:"bulgarian",name:"lev",iso:"bgn",sub:"stotinka",sym:["лв."]},{dem:"irish",name:"pound",iso:"iep",sym:["£","IR£"]},{name:"cfp franc",iso:"xpf",sym:["f"]},{dem:"south african",name:"rand",iso:"zar",sub:"cent",sym:["R"]},{dem:"south korean",name:"won",iso:"krw",sub:"jeon",plural:"won",sym:["₩"]},{dem:"north korean",name:"won",iso:"kpw",sub:"chon",plural:"won",sym:["₩"]},{dem:"portuguese",name:"escudo",iso:"pte",sub:"centavo",sym:[]},{dem:"ghanaian",name:"cedi",iso:"ghs",sub:"pesewa",sym:["GH₵"]},{dem:"hong kong",name:"dollar",iso:"hkd",sub:"毫",sym:["$"]},{dem:"new taiwan",name:"dollar",iso:"twd",sub:"dime",sym:["NT$"]},{dem:"east german",name:"mark",iso:"ddm",sub:"pfennig",sym:["M"]},{dem:"namibian",name:"dollar",iso:"nad",sub:"cent",sym:["$"]},{dem:"malaysian",name:"ringgit",iso:"myr",sub:"sen",sym:["RM"]},{dem:"swiss",name:"franc",iso:"chf",sym:["Rp."]},{dem:"panamanian",name:"balboa",iso:"pab",sub:"centésimo",sym:["B/."]},{dem:"indonesian",name:"rupiah",iso:"idr",sub:"sen",sym:["Rp"]},{dem:"brunei",name:"dollar",iso:"bnd",sub:"sen",sym:["$","B$"]},{dem:"venezuelan",name:"bolívar",iso:"vef",sub:"céntimo",sym:["Bs.F","Bs."]},{dem:"macedonian",name:"denar",iso:"mkd",sub:"deni",sym:["den"]},{dem:"mauritanian",name:"ouguiya",iso:"mru",sub:"khoums",sym:["UM"]},{dem:"argentine",name:"peso",iso:"ars",sub:"centavo",sym:["$"]},{dem:"libyan",name:"dinar",iso:"lyd",sub:"dirham",sym:["LD","ل.د"]},{dem:"jordanian",name:"dinar",iso:"jod",sub:"dirham",sym:["د.أ"]},{dem:"french",name:"franc",iso:"frf",sub:"centime",sym:["F","Fr","FF","₣"]},{dem:"syrian",name:"pound",iso:"syp",sub:"piastre",sym:["LS","£S"]},{dem:"belize",name:"dollar",iso:"bzd",sub:"cent",sym:["$"]},{dem:"saudi",name:"riyal",iso:"sar",sub:"halalah",sym:["SAR","ر.س"," ﷼"]},{dem:"surinamese",name:"dollar",iso:"srd",sub:"cent",sym:["$"]},{dem:"singapore",name:"dollar",iso:"sgd",sub:"cent",sym:["S$","$"]},{dem:"nepalese",name:"rupee",iso:"npr",sub:"paisa",sym:["रु ₨","Re"]},{dem:"nicaraguan",name:"córdoba",iso:"nio",sub:"centavo",sym:["C$"]},{dem:"bangladeshi",name:"taka",iso:"bdt",sub:"poysha",sym:["৳"]},{dem:"indian",name:"rupee",iso:"inr",sub:"paisa",sym:["₹"]},{dem:"maldivian",name:"rufiyaa",iso:"mvr",sub:"laari",sym:["Rf","MRf","MVR",".ރ "]},{dem:"sri lankan",name:"rupee",iso:"lkr",sub:"cents",sym:["Rs","රු","ரூ"]},{dem:"bhutanese",name:"ngultrum",iso:"btn",sub:"chhertum",sym:["Nu."]},{dem:"turkish",name:"lira",iso:"try",sub:"kuruş",sym:["YTL"]},{dem:"serbian",name:"dinar",iso:"rsd",sub:"para",sym:["din","дин"]},{dem:"bosnia and herzegovina",name:"convertible mark",iso:"bam",sub:"fening",sym:["KM"]},{dem:"botswana",name:"pula",iso:"bwp",sub:"thebe",sym:["p"]},{dem:"swazi",name:"lilangeni",iso:"szl",sub:"cent",sym:["L","E"]},{dem:"lithuanian",name:"litas",iso:"ltl",sub:"centas",sym:["Lt","ct"]},{dem:"mauritian",name:"rupee",iso:"mur",sub:"cent",sym:["₨"]},{dem:"pakistani",name:"rupee",iso:"pkr",sub:"paisa",sym:["₨"]},{dem:"maltese",name:"lira",iso:"mtl",sub:"cent",sym:["₤","Lm"]},{dem:"cypriot",name:"pound",iso:"cyp",sub:"cent",sym:["£"]},{dem:"moldovan",name:"leu",iso:"mdl",sym:["l"]},{dem:"croatian",name:"kuna",iso:"hrk",sub:"lipa",sym:["kn"]},{dem:"afghan",name:"afghani",iso:"afn",sub:"pul",sym:["؋","Af","Afs"]},{dem:"ecuadorian",name:"sucre",iso:"ecs",sub:"centavo",sym:["S/."]},{dem:"sierra leonean",name:"leone",iso:"sll",sub:"cent",sym:["Le"]}];const te=ne,re=C,ae={};let ie={};te.forEach((e=>{e.sym.forEach((t=>{ae[t]=ae[t]||e.iso})),ae[e.iso]=ae[e.iso]||e.iso,e.sub&&(ie[e.sub]=!0)}));let se=`(${Object.keys(ie).join("|")})`;const oe=Y,ue=function(e){let t=0,n=e.match(`and #Money+ ${se}`);if(n.found){e=e.not(n);let r=re(n.match("#Value+"));r&&r.num&&(t=r.num/100)}let r=re(e),a=r.num||0;a+=t;let i=((o=r).suffix&&ae.hasOwnProperty(o.suffix)?te.find((e=>e.iso===ae[o.suffix])):o.prefix&&ae.hasOwnProperty(o.prefix)?te.find((e=>e.iso===ae[o.prefix])):null)||function(e){let t=e.match("#Currency+");t.nouns().toSingular();let n=t.text("reduced");return te.find((e=>(n===`${e.dem} ${e.name}`||n===e.iso||n===e.sub||n===e.name||!(!e.alias||!0!==e.alias[n]))&&e))}(e)||{};var o;let s="";return i&&i.sym&&(s=i.sym[0],a&&e.has(`${se}`)&&(a/=100)),{num:a,iso:i.iso,demonym:i.dem,currency:i.name,plural:i.plural,symbol:s}},le=function(e=""){return e.replace(/\w\S*/g,(function(e){return e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()}))};var me$1={get:function(e){let t=[];return this.forEach((e=>{t.push(ue(e))})),void 0!==e?t[e]||null:t||null},currency:function(e){let t=[];return this.forEach((e=>{let n=ue(e);n&&t.push(n)})),"number"==typeof e?t[e]||null:t||null},json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=ue(t);if(r.number=a.num,a.iso&&(r.iso=a.iso.toUpperCase(),r.symbol=a.symbol,r.currency=le(a.demonym)+" "+le(a.currency)),r.textFmt=oe(a,!0,!1),a.currency){let e=a.currency;1!==a.num&&(e=a.plural||e+"s"),r.textFmt+=" "+e}n.push(r)})),null!==t?n[t]||{}:n}},ce={};const he=P,fe=q;ce.toText=function(e){if(!e.numerator||!e.denominator)return"";let t=he(e.numerator),n=fe(e.denominator);return 2===e.denominator&&(n="half"),t&&n?(1!==e.numerator&&(n+="s"),`${t} ${n}`):""},ce.textCardinal=function(e){return e.numerator&&e.denominator?`${he(e.numerator)} out of ${he(e.denominator)}`:""},ce.toDecimal=function(e){return e.decimal};const de=v,ye=ce,pe={get:function(e){let t=[];return this.forEach((e=>{t.push(de(e))})),void 0!==e?t[e]||null:t||null},toDecimal(){return this.forEach((e=>{let t=de(e);if(t){let n=ye.toDecimal(t);e.replaceWith(String(n),!0),e.tag("NumericValue"),e.unTag("Fraction")}})),this},json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=de(t)||{},i=ye.toDecimal(a);r.numerator=a.numerator,r.denominator=a.denominator,r.number=i,r.textOrdinal=ye.toText(a),r.textCardinal=ye.textCardinal(a),n.push(r)})),null!==t?n[t]||{}:n},normalize:function(){return this.forEach((e=>{let t=de(e);if(t&&"number"==typeof t.numerator&&"number"==typeof t.denominator){let n=`${t.numerator}/${t.denominator}`;this.replace(e,n)}})),this},toText:function(e){let t=[];return this.forEach((e=>{let t=de(e)||{},n=ye.toText(t);e.replaceWith(n,!0),e.tag("Fraction")})),void 0!==e?t[e]:t},toPercentage:function(){return this.forEach((e=>{let t=de(e);if(t.decimal||0===t.decimal){let n=100*t.decimal;n=Math.round(100*n)/100,this.replace(e,`${n}%`)}})),this}};pe.toNumber=pe.toDecimal;var be=pe;const ge=function(e){return e.match("(hundred|thousand|million|billion|trillion|quadrillion|quintillion|sextillion|septillion)").tag("#Multiple","fraction-tagger"),e.match("[(half|quarter)] of? (a|an)",0).tag("Fraction","millionth"),e.match("#Adverb [half]",0).tag("Fraction","nearly-half"),e.match("[half] the",0).tag("Fraction","half-the"),e.match("#Value (halves|halfs|quarters)").tag("Fraction","two-halves"),e.match("a #Ordinal").tag("Fraction","a-quarter"),e.match("(#Fraction && /s$/)").lookBefore("#Cardinal+$").tag("Fraction"),e.match("[#Cardinal+ #Ordinal] of .",0).tag("Fraction","ordinal-of"),e.match("[(#NumericValue && #Ordinal)] of .",0).tag("Fraction","num-ordinal-of"),e.match("(a|one) #Cardinal?+ #Ordinal").tag("Fraction","a-ordinal"),e.match("#Cardinal+ out? of every? #Cardinal").tag("Fraction","fraction-tagger"),e},xe=function(e){const t="money-tagger";e.match("#Money and #Money #Currency?").tag("Money","money-and-money"),e.match("#Money").not("#TextValue").match("/\\.[0-9]{3}$/").unTag("#Money","three-decimal money"),e.ifNo("#Value").match("#Currency #Verb").unTag("Currency","no-currency"),e.match("#Value #Currency [and] #Value (cents|ore|centavos|sens)",0).tag("Money",t);let n=e.match("[#Value] [(mark|rand|won|rub|ore)]");return n.group("num").tag("Money",t),n.group("currency").tag("Currency",t),e};var $e=function(e){(e=xe(e)).match("the [/[0-9]+s$/]").tag("#Plural","number-tag"),e.match("half a? #Value").tag("Value","half-a-value"),e.match("#Value [and a (half|quarter)]",0).tag(["TextValue","#Fraction"],"value-and-a-half"),(e=ge(e)).match("#Cardinal and #Fraction #Fraction").tag("Value","number-tag")};const ve={mark:!0,sucre:!0,leone:!0,afghani:!0,rand:!0,try:!0,mop:!0,won:!0,all:!0,rub:!0,eek:!0,sit:!0,bam:!0,npr:!0,leu:!0};let we={kronor:"Currency"};ne.forEach((e=>{e.iso&&!ve[e.iso]&&(we[e.iso]=["Acronym","Currency"]);let t=e.name;if(t&&!ve[t]&&(we[t]="Currency",we[t+"s"]="Currency"),e.dem){let n=e.dem;we[`${n} ${t}`]="Currency",we[`${n} ${t}s`]="Currency"}e.sub&&(we[e.sub]="Currency")}));const ke=e,Ce=t,Oe=r,Ve=a,Fe=J,Me=ee,Ee=me$1,Ne=be,Pe=$e,ze={Fraction:{isA:["Value"]},Multiple:{isA:"Value"}},Ae=we;var je=function(e,t){t.addWords(Ae),t.addTags(ze),t.postProcess(Pe);class n extends e{}Object.assign(n.prototype,Fe);class r extends n{}Object.assign(r.prototype,Ee);class a extends n{}Object.assign(a.prototype,Ne);class i extends n{}Object.assign(i.prototype,Me);const o={numbers:function(e){let t=Ce(this,e);return new n(t.list,this,this.world)},percentages:function(e){let t=Ve(this,e);return new i(t.list,this,this.world)},fractions:function(e){let t=Oe(this,e);return new a(t.list,this,this.world)},money:function(e){let t=ke(this,e);return new r(t.list,this,this.world)}};return o.values=o.numbers,o.percents=o.percentages,Object.assign(e.prototype,o),e},compromise_numbers=je;nlp.extend(compromise_numbers);class Pluralize extends Text{static componentType="pluralize";static rendererType="text";static createAttributesObject(){let e=super.createAttributesObject();return e.pluralForm={createComponentOfType:"text",createStateVariable:"pluralForm",defaultValue:null,public:!0},e.basedOnNumber={createComponentOfType:"number",createStateVariable:"basedOnNumber",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePrePluralize"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valuePrePluralize:{dependencyType:"stateVariable",variableName:"valuePrePluralize"},pluralForm:{dependencyType:"stateVariable",variableName:"pluralForm"},basedOnNumber:{dependencyType:"stateVariable",variableName:"basedOnNumber"}}),definition:function({dependencyValues:e}){let t,n=nlp(e.valuePrePluralize),r=n.values().toNumber().all().terms().json();if(0===r.length)return{setValue:{value:e.valuePrePluralize}};if(null!==e.basedOnNumber&&(t=numberDesignatesPlural(e.basedOnNumber)),1===r.length)return void 0===t&&(t=!0),t?null!==e.pluralForm?{setValue:{value:e.pluralForm}}:{setValue:{value:n.nouns().toPlural().all().out("text")}}:{setValue:{value:e.valuePrePluralize}};if(void 0===t){let e=[],a=[],i=n.nouns().json();for(let[t,n]of r.entries()){let r=i[e.length];n.terms[0].tags.includes("Value")&&a.push(t),void 0!==r&&r.text===n.text&&e.push(t)}t=[];let o=n.values().numbers().json(),s=-1;for(let n of e){for(;Number(a[s+1])({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}}function numberDesignatesPlural(e){return 1!==e}class Feedback extends BlockComponent{static componentType="feedback";static renderChildren=!0;static primaryStateVariableForDefinition="feedbackText";static createAttributesObject(){let e=super.createAttributesObject();return delete e.hide,e.condition={createComponentOfType:"boolean"},e.updateWith={createPrimitiveOfType:"string"},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.updateWith={returnDependencies:()=>({updateWithAttr:{dependencyType:"attributePrimitive",attributeName:"updateWith"}}),definition:({dependencyValues:e})=>({setValue:{updateWith:e.updateWithAttr}})},e.updateWithComponentNames={chainActionOnActionOfStateVariableTargets:{triggeredAction:"updateHide"},stateVariablesDeterminingDependencies:["updateWith"],returnDependencies:({stateValues:e})=>e.updateWith?{updateWithComponentName:{dependencyType:"expandTargetName",target:e.updateWith}}:{},definition:({dependencyValues:e})=>e.updateWithComponentName?{setValue:{updateWithComponentNames:[e.updateWithComponentName]}}:{setValue:{updateWithComponentNames:[]}}},e.hideWhenUpdated={returnDependencies:()=>({condition:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]},showFeedback:{dependencyType:"flag",flagName:"showFeedback"}}),definition:function({dependencyValues:e}){if(!e.showFeedback)return{setValue:{hideWhenUpdated:!0}};let t;return t=null!==e.condition&&!e.condition.stateValues.value,{setValue:{hideWhenUpdated:t}}}},e.hide={forRenderer:!0,defaultValue:!0,hasEssential:!0,stateVariablesDeterminingDependencies:["updateWith"],returnDependencies:({stateValues:e})=>e.updateWith?{}:{condition:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]},showFeedback:{dependencyType:"flag",flagName:"showFeedback"}},definition:function({dependencyValues:e}){if(!("condition"in e))return{useEssentialOrDefaultValue:{hide:!0}};if(!e.showFeedback)return{setValue:{hide:!0}};let t;return t=null!==e.condition&&!e.condition.stateValues.value,{setValue:{hide:t}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>"condition"in t?{success:!1}:{success:!0,instructions:[{setEssentialValue:"hide",value:e.hide}]}},e.feedbackText={forRenderer:!0,defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{feedbackText:!0}})},e}async updateHide({actionId:e}){let t=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"hide",value:await this.stateValues.hideWhenUpdated}];return await this.coreFunctions.performUpdate({updateInstructions:t,actionId:e})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={updateHide:this.updateHide.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class CollaborateGroups extends BaseComponent{static componentType="collaborateGroups";static rendererType=void 0;static stateVariableForAttributeValue="collaborateGroups";static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"atLeastZeroPoints",componentType:"point",comparison:"atLeast",number:0}),r=breakStringsAndOthersIntoComponentsByStringCommas(),a=t.newLeaf({name:"exactlyOneString",componentType:"string",number:1,isSugar:!0,logicToWaitOnSugar:["atLeastZeroPoints"],replacementFunction:r});return t.newOperator({name:"pointsXorSugar",operator:"xor",propositions:[a,n],setAsBase:!0}),t}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.collaborateGroups={returnDependencies:()=>({pointChildren:{dependencyType:"child",childLogicName:"atLeastZeroPoints",variableNames:["xs","coords","nDimensions"]}}),definition:function({dependencyValues:e}){let t={};for(let n of e.pointChildren)if(2!==n.stateValues.nDimensions)console.warn(`invalid collaborate group: ${n.stateValues.coords.toString()}`);else{let e=n.stateValues.xs[0].evaluate_to_constant(),r=n.stateValues.xs[1].evaluate_to_constant();Number.isInteger(e)&&e>0&&Number.isInteger(r)&&r>0?(void 0===t[e]&&(t[e]=[]),t[e].push(r)):console.warn(`invalid collaborate group: ${n.stateValues.coords.toString()}`)}return{setValue:{collaborateGroups:{groups:t,matchGroup:function({groupNumber:e,numberOfGroups:n}={}){if(n>1){let r=t[n];return void 0!==r&&r.includes(e)}return!0}}}}}},e}}class CollaborateGroupSetup extends BaseComponent{static componentType="collaborateGroupSetup";static returnChildLogic(e){let t=super.returnChildLogic(e);return t.newLeaf({name:"atMostOnePossibleNumberOfGroups",componentType:"possibleNumberOfGroups",comparison:"atMost",number:1,setAsBase:!0}),t}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.possibleNumberOfGroups={returnDependencies:()=>({pngChild:{dependencyType:"child",childLogicName:"atMostOnePossibleNumberOfGroups",variableNames:["numbers"]}}),definition:function({dependencyValues:e}){return 0===e.pngChild.length?{setValue:{possibleNumberOfGroups:[1]}}:{setValue:{possibleNumberOfGroups:e.pngChild[0].stateValues.numbers}}}},e}}class ConsiderAsResponses extends BaseComponent{static componentType="considerAsResponses";static rendererType=void 0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.childrenWithNValues={returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"],variableNames:["nValues"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{childrenWithNValues:e.children}})},e.childrenAsResponses={returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"],variableNames:["value","values","componentType"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{childrenAsResponses:e.children}})},e}}class Case extends Template{static componentType="case";static createAttributesObject(){let e=super.createAttributesObject();return e.condition={createComponentOfType:"boolean"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.conditionSatisfied={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({condition:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t;return t=null===e.condition||e.condition.stateValues.value,{setValue:{conditionSatisfied:t}}}},e}static createSerializedReplacements({component:e,componentInfoObjects:t}){return e.stateValues.conditionSatisfied?super.createSerializedReplacements({component:e,componentInfoObjects:t}):{replacements:[]}}}var dist={},formats={};Object.defineProperty(formats,"__esModule",{value:!0}),formats.FORMATS=formats.FORMAT_PLAIN=formats.FORMAT_HTML=void 0;var FORMAT_HTML="html";formats.FORMAT_HTML=FORMAT_HTML;var FORMAT_PLAIN="plain";formats.FORMAT_PLAIN=FORMAT_PLAIN;var FORMATS=[FORMAT_HTML,FORMAT_PLAIN];formats.FORMATS=FORMATS;var units={};Object.defineProperty(units,"__esModule",{value:!0}),units.UNITS=units.UNIT_PARAGRAPH=units.UNIT_PARAGRAPHS=units.UNIT_SENTENCE=units.UNIT_SENTENCES=units.UNIT_WORD=units.UNIT_WORDS=void 0;var UNIT_WORDS="words";units.UNIT_WORDS=UNIT_WORDS;var UNIT_WORD="word";units.UNIT_WORD=UNIT_WORD;var UNIT_SENTENCES="sentences";units.UNIT_SENTENCES=UNIT_SENTENCES;var UNIT_SENTENCE="sentence";units.UNIT_SENTENCE=UNIT_SENTENCE;var UNIT_PARAGRAPHS="paragraphs";units.UNIT_PARAGRAPHS=UNIT_PARAGRAPHS;var UNIT_PARAGRAPH="paragraph";units.UNIT_PARAGRAPH=UNIT_PARAGRAPH;var UNITS=[UNIT_WORDS,UNIT_WORD,UNIT_SENTENCES,UNIT_SENTENCE,UNIT_PARAGRAPHS,UNIT_PARAGRAPH];units.UNITS=UNITS;var words={};Object.defineProperty(words,"__esModule",{value:!0}),words.WORDS=void 0;var WORDS=["ad","adipisicing","aliqua","aliquip","amet","anim","aute","cillum","commodo","consectetur","consequat","culpa","cupidatat","deserunt","do","dolor","dolore","duis","ea","eiusmod","elit","enim","esse","est","et","eu","ex","excepteur","exercitation","fugiat","id","in","incididunt","ipsum","irure","labore","laboris","laborum","Lorem","magna","minim","mollit","nisi","non","nostrud","nulla","occaecat","officia","pariatur","proident","qui","quis","reprehenderit","sint","sit","sunt","tempor","ullamco","ut","velit","veniam","voluptate"];words.WORDS=WORDS;var LoremIpsum={},lineEndings={};Object.defineProperty(lineEndings,"__esModule",{value:!0}),lineEndings.LINE_ENDINGS=void 0;var LINE_ENDINGS={POSIX:"\n",WIN32:"\r\n"};lineEndings.LINE_ENDINGS=LINE_ENDINGS;var generator={},util={},capitalize={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=function(e){var t=e.trim();return t.charAt(0).toUpperCase()+t.slice(1)};e.default=t}(capitalize);var isNode={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=function(){return!!e.exports};t.default=n}(isNode,isNode.exports);var isReactNative={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=function(){var e=!1;try{e="ReactNative"===navigator.product}catch(t){e=!1}return e};e.default=t}(isReactNative);var isWindows={},platforms={};Object.defineProperty(platforms,"__esModule",{value:!0}),platforms.SUPPORTED_PLATFORMS=void 0;var SUPPORTED_PLATFORMS={DARWIN:"darwin",LINUX:"linux",WIN32:"win32"};platforms.SUPPORTED_PLATFORMS=SUPPORTED_PLATFORMS,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=platforms,n=function(){var e=!1;try{e=browser$1.platform===t.SUPPORTED_PLATFORMS.WIN32}catch(t){e=!1}return e};e.default=n}(isWindows);var makeArrayOfLength={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return Array.apply(null,Array(e)).map((function(e,t){return t}))};e.default=t}(makeArrayOfLength);var makeArrayOfStrings={},hasRequiredMakeArrayOfStrings,hasRequiredUtil;function requireMakeArrayOfStrings(){return hasRequiredMakeArrayOfStrings||(hasRequiredMakeArrayOfStrings=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=requireUtil(),n=function(e,n){return(0,t.makeArrayOfLength)(e).map((function(){return n()}))};e.default=n}(makeArrayOfStrings)),makeArrayOfStrings}function requireUtil(){return hasRequiredUtil||(hasRequiredUtil=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"capitalize",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(e,"isNode",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(e,"isReactNative",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(e,"isWindows",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(e,"makeArrayOfLength",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(e,"makeArrayOfStrings",{enumerable:!0,get:function(){return o.default}});var t=s(capitalize),n=s(isNode.exports),r=s(isReactNative),a=s(isWindows),i=s(makeArrayOfLength),o=s(requireMakeArrayOfStrings());function s(e){return e&&e.__esModule?e:{default:e}}}(util)),util}!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=words,n=requireUtil();function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},a=n.sentencesPerParagraph,o=void 0===a?{max:7,min:3}:a,s=n.wordsPerSentence,l=void 0===s?{max:15,min:5}:s,u=n.random;n.seed;var c=n.words,p=void 0===c?t.WORDS:c;if(r(this,e),i(this,"sentencesPerParagraph",void 0),i(this,"wordsPerSentence",void 0),i(this,"random",void 0),i(this,"words",void 0),o.min>o.max)throw new Error("Minimum number of sentences per paragraph (".concat(o.min,") cannot exceed maximum (").concat(o.max,")."));if(l.min>l.max)throw new Error("Minimum number of words per sentence (".concat(l.min,") cannot exceed maximum (").concat(l.max,")."));this.sentencesPerParagraph=o,this.words=p,this.wordsPerSentence=l,this.random=u||Math.random}var o,s,l;return o=e,s=[{key:"generateRandomInteger",value:function(e,t){return Math.floor(this.random()*(t-e+1)+e)}},{key:"generateRandomWords",value:function(e){var t=this,r=this.wordsPerSentence,a=r.min,i=r.max,o=e||this.generateRandomInteger(a,i);return(0,n.makeArrayOfLength)(o).reduce((function(e,n){return"".concat(t.pluckRandomWord()," ").concat(e)}),"").trim()}},{key:"generateRandomSentence",value:function(e){return"".concat((0,n.capitalize)(this.generateRandomWords(e)),".")}},{key:"generateRandomParagraph",value:function(e){var t=this,r=this.sentencesPerParagraph,a=r.min,i=r.max,o=e||this.generateRandomInteger(a,i);return(0,n.makeArrayOfLength)(o).reduce((function(e,n){return"".concat(t.generateRandomSentence()," ").concat(e)}),"").trim()}},{key:"pluckRandomWord",value:function(){var e=this.words.length-1,t=this.generateRandomInteger(0,e);return this.words[t]}}],s&&a(o.prototype,s),l&&a(o,l),e}(),s=o;e.default=s}(generator),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t,n=formats,r=lineEndings,a=(t=generator)&&t.__esModule?t:{default:t},i=requireUtil();function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.FORMAT_PLAIN,i=arguments.length>2?arguments[2]:void 0;if(o(this,e),this.format=r,this.suffix=i,l(this,"generator",void 0),-1===n.FORMATS.indexOf(r.toLowerCase()))throw new Error("".concat(r," is an invalid format. Please use ").concat(n.FORMATS.join(" or "),"."));this.generator=new a.default(t)}var t,u,c;return t=e,(u=[{key:"getLineEnding",value:function(){return this.suffix?this.suffix:!(0,i.isReactNative)()&&(0,i.isNode)()&&(0,i.isWindows)()?r.LINE_ENDINGS.WIN32:r.LINE_ENDINGS.POSIX}},{key:"formatString",value:function(e){return this.format===n.FORMAT_HTML?"

".concat(e,"

"):e}},{key:"formatStrings",value:function(e){var t=this;return e.map((function(e){return t.formatString(e)}))}},{key:"generateWords",value:function(e){return this.formatString(this.generator.generateRandomWords(e))}},{key:"generateSentences",value:function(e){return this.formatString(this.generator.generateRandomParagraph(e))}},{key:"generateParagraphs",value:function(e){var t=this.generator.generateRandomParagraph.bind(this.generator);return this.formatStrings((0,i.makeArrayOfStrings)(e,t)).join(this.getLineEnding())}}])&&s(t.prototype,u),c&&s(t,c),e}(),c=u;e.default=c}(LoremIpsum),function(e){Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"LoremIpsum",{enumerable:!0,get:function(){return i.default}}),e.loremIpsum=void 0;var t,n=formats,r=units,a=words,i=(t=LoremIpsum)&&t.__esModule?t:{default:t};e.loremIpsum=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.count,o=void 0===t?1:t,s=e.format,l=void 0===s?n.FORMAT_PLAIN:s,u=e.paragraphLowerBound,c=void 0===u?3:u,p=e.paragraphUpperBound,d=void 0===p?7:p,m=e.random,f=e.sentenceLowerBound,h=void 0===f?5:f,y=e.sentenceUpperBound,b=void 0===y?15:y,g=e.units,v=void 0===g?r.UNIT_SENTENCES:g,T=e.words,N=void 0===T?a.WORDS:T,C=e.suffix,A=void 0===C?"":C,S={random:m,sentencesPerParagraph:{max:d,min:c},words:N,wordsPerSentence:{max:b,min:h}},x=new i.default(S,l,A);switch(v){case r.UNIT_PARAGRAPHS:case r.UNIT_PARAGRAPH:return x.generateParagraphs(o);case r.UNIT_SENTENCES:case r.UNIT_SENTENCE:return x.generateSentences(o);case r.UNIT_WORDS:case r.UNIT_WORD:return x.generateWords(o);default:return""}}}(dist);class Lorem extends CompositeComponent{static componentType="lorem";static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.minSentencesPerParagraph={createComponentOfType:"number",createStateVariable:"minSentencesPerParagraph",defaultValue:4,public:!0},e.maxSentencesPerParagraph={createComponentOfType:"number",createStateVariable:"maxSentencesPerParagraph",defaultValue:8,public:!0},e.minWordsPerSentence={createComponentOfType:"number",createStateVariable:"minWordsPerSentence",defaultValue:4,public:!0},e.maxWordsPerSentence={createComponentOfType:"number",createStateVariable:"maxWordsPerSentence",defaultValue:8,public:!0},e.generateWords={createComponentOfType:"number",createStateVariable:"generateWords",defaultValue:null},e.generateSentences={createComponentOfType:"number",createStateVariable:"generateSentences",defaultValue:null},e.generateParagraphs={createComponentOfType:"number",createStateVariable:"generateParagraphs",defaultValue:null},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.readyToExpandWhenResolved={returnDependencies:()=>({minSentencesPerParagraph:{dependencyType:"stateVariable",variableName:"minSentencesPerParagraph"},maxSentencesPerParagraph:{dependencyType:"stateVariable",variableName:"maxSentencesPerParagraph"},minWordsPerSentence:{dependencyType:"stateVariable",variableName:"minWordsPerSentence"},maxWordsPerSentence:{dependencyType:"stateVariable",variableName:"maxWordsPerSentence"},generateWords:{dependencyType:"stateVariable",variableName:"generateWords"},generateSentences:{dependencyType:"stateVariable",variableName:"generateSentences"},generateParagraphs:{dependencyType:"stateVariable",variableName:"generateParagraphs"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{generatedVariantInfo:{seed:e.variantSeed,meta:{createdBy:t}}}})},e}static async createSerializedReplacements({component:e,componentInfoObjects:t}){const n=new dist.LoremIpsum({sentencesPerParagraph:{max:await e.stateValues.maxSentencesPerParagraph,min:await e.stateValues.minSentencesPerParagraph},wordsPerSentence:{max:await e.stateValues.maxWordsPerSentence,min:await e.stateValues.minWordsPerSentence},random:e.sharedParameters.variantRng});let r=[];if(null!==await e.stateValues.generateParagraphs){let t=await e.stateValues.generateParagraphs;if(Number.isInteger(t)&&t>0){r=n.generateParagraphs(t).split("\n").map((e=>({componentType:"p",children:[e]})))}}else if(null!==await e.stateValues.generateSentences){let t=await e.stateValues.generateSentences;if(Number.isInteger(t)&&t>0){let e=n.generateSentences(t).split(". ");for(let t of e.slice(0,e.length-1))r.push({componentType:"text",children:[t+"."]}),r.push(" ");r.push({componentType:"text",children:[e[e.length-1]]})}}else if(null!==await e.stateValues.generateWords){let t=await e.stateValues.generateWords;if(Number.isInteger(t)&&t>0){let e=n.generateWords(t).split(" ").map((e=>({componentType:"text",children:[e]})));r.push(e[0]);for(let t of e.slice(1))r.push(" "),r.push(t)}}let a=e.attributes.newNamespace?.primitive;return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:r,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:t}).serializedComponents}}static async calculateReplacementChanges({component:e,componentInfoObjects:t}){let n=await this.createSerializedReplacements({component:e,componentInfoObjects:t});return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:n.replacements}]}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n})}}class UpdateValue extends InlineComponent{static componentType="updateValue";static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"math",toLowerCase:!0,validValues:["math","number","boolean","text"]},e.prop={createPrimitiveOfType:"string"},e.newValue={createComponentOfType:"_componentWithSelectableType"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.triggerWhen={createComponentOfType:"boolean",createStateVariable:"triggerWhen",defaultValue:!1,triggerActionOnChange:"updateValueIfTriggerNewlyTrue"},e.triggerWith={createPrimitiveOfType:"string"},e.triggerWhenObjectsClicked={createPrimitiveOfType:"string"},e.simplify={createComponentOfType:"text",createStateVariable:"simplify",defaultValue:"none",public:!0,toLowerCase:!0,valueTransformations:{true:"full"},validValues:["none","full","numbers","numberspreserveorder"]},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();Object.assign(e,t),e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){let t=null;return e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.propName={returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.targetIdentities={stateVariablesDeterminingDependencies:["targetComponent","componentIndex"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={};return null!==e.targetComponent&&(t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})?n.targets={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,componentIndex:e.componentIndex}:null!==e.componentIndex&&1!==e.componentIndex||(n.targets={dependencyType:"stateVariable",variableName:"targetComponent"})),n},definition({dependencyValues:e}){let t=null;return e.targets&&(t=e.targets,Array.isArray(t)||(t=[t])),{setValue:{targetIdentities:t}}}},e.targets={stateVariablesDeterminingDependencies:["targetIdentities","propName","propIndex"],returnDependencies:function({stateValues:e}){let t={targetIdentities:{dependencyType:"stateVariable",variableName:"targetIdentities"}};if(null!==e.targetIdentities)for(let[n,r]of e.targetIdentities.entries()){let a;if(e.propName){let t=e.propIndex;t&&(t=[...t]),a={dependencyType:"stateVariable",componentName:r.componentName,variableName:e.propName,returnAsComponentObject:!0,variablesOptional:!0,propIndex:t,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0}}else a={dependencyType:"componentIdentity",componentName:r.componentName};t["target"+n]=a}return t},definition({dependencyValues:e}){let t=null;if(null!==e.targetIdentities){t=[];for(let n in e.targetIdentities)e["target"+n]&&t.push(e["target"+n])}return{setValue:{targets:t}}}},e.newValue={returnDependencies:()=>({newValueAttr:{dependencyType:"attributeComponent",attributeName:"newValue",variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"},simplify:{dependencyType:"stateVariable",variableName:"simplify"}}),definition:function({dependencyValues:e}){if(null===e.newValueAttr)return{setValue:{newValue:null}};let t=e.newValueAttr.stateValues.value;return"math"===e.type&&(t=normalizeMathExpression({value:t,simplify:e.simplify})),{setValue:{newValue:t}}}},e.insideTriggerSet={returnDependencies:()=>({parentTriggerSet:{dependencyType:"parentStateVariable",parentComponentType:"triggerSet",variableName:"updateValueAndActionsToTrigger"}}),definition:({dependencyValues:e})=>({setValue:{insideTriggerSet:null!==e.parentTriggerSet}})},e.triggerWith={returnDependencies:()=>({triggerWith:{dependencyType:"attributePrimitive",attributeName:"triggerWith"},triggerWhenObjectsClicked:{dependencyType:"attributePrimitive",attributeName:"triggerWhenObjectsClicked"},triggerWhen:{dependencyType:"attributeComponent",attributeName:"triggerWhen"},insideTriggerSet:{dependencyType:"stateVariable",variableName:"insideTriggerSet"}}),definition({dependencyValues:e}){if(e.triggerWhen||e.insideTriggerSet)return{setValue:{triggerWith:null}};{let t=[];if(null!==e.triggerWith)for(let n of e.triggerWith.split(/\s+/).filter((e=>e)))t.push({target:n});if(null!==e.triggerWhenObjectsClicked)for(let n of e.triggerWhenObjectsClicked.split(/\s+/).filter((e=>e)))t.push({target:n,triggeringAction:"click"});return 0===t.length&&(t=null),{setValue:{triggerWith:t}}}}},e.triggerWithTargetIds={chainActionOnActionOfStateVariableTargets:{triggeredAction:"updateValue"},stateVariablesDeterminingDependencies:["triggerWith"],returnDependencies({stateValues:e}){let t={triggerWith:{dependencyType:"stateVariable",variableName:"triggerWith"}};if(e.triggerWith)for(let[n,r]of e.triggerWith.entries())t[`triggerWithTargetComponentName${n}`]={dependencyType:"expandTargetName",target:r.target};return t},definition({dependencyValues:e}){let t=[];if(e.triggerWith)for(let[n,r]of e.triggerWith.entries()){let a=e[`triggerWithTargetComponentName${n}`];r.triggeringAction&&(a+="|"+r.triggeringAction),t.includes(a)||t.push(a)}return{setValue:{triggerWithTargetIds:t}}},markStale:()=>({updateActionChaining:!0})};let n=e.hidden.returnDependencies,r=e.hidden.definition;return e.hidden.returnDependencies=function(e){let t=n(e);return t.triggerWhen={dependencyType:"attributeComponent",attributeName:"triggerWhen"},t.triggerWith={dependencyType:"stateVariable",variableName:"triggerWith"},t.insideTriggerSet={dependencyType:"stateVariable",variableName:"insideTriggerSet"},t},e.hidden.definition=function(e){return e.dependencyValues.triggerWhen||e.dependencyValues.triggerWith||e.dependencyValues.insideTriggerSet?{setValue:{hidden:!0}}:r(e)},e}async updateValue({actionId:e}){let t=await this.stateValues.targets,n=await this.stateValues.newValue;if(null===t||null===n)return;let r=[];for(let e of t){let t="value";e.stateValues&&(t=Object.keys(e.stateValues)[0],void 0===t)?console.warn(`Cannot update prop="${await this.stateValues.propName}" of ${await this.stateValues.target} as could not find prop ${await this.stateValues.propName} on a component of type ${e.componentType}`):r.push({updateType:"updateValue",componentName:e.componentName,stateVariable:t,value:n})}return await this.coreFunctions.performUpdate({updateInstructions:r,actionId:e,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:n,responseText:n.toString()}}}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}async updateValueIfTriggerNewlyTrue({stateValues:e,previousValues:t,actionId:n}){if(await e.triggerWhen&&!1===t.triggerWhen&&!await this.stateValues.insideTriggerSet)return await this.updateValue({actionId:n});this.coreFunctions.resolveAction({actionId:n})}actions={updateValue:this.updateValue.bind(this),updateValueIfTriggerNewlyTrue:this.updateValueIfTriggerNewlyTrue.bind(this)}}class CallAction extends InlineComponent{static componentType="callAction";static acceptTarget=!0;static keepChildrenSerialized({serializedComponent:e,componentInfoObjects:t}){if(void 0===e.children)return[];{let n=[];for(let[r,a]of e.children.entries())t.componentIsSpecifiedType(a,"label")||n.push(r);return n}}static createAttributesObject(){let e=super.createAttributesObject();return e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.actionName={createComponentOfType:"text",createStateVariable:"actionName",defaultValue:null,public:!0},e.triggerWhen={createComponentOfType:"boolean",createStateVariable:"triggerWhen",defaultValue:!1,triggerActionOnChange:"callActionIfTriggerNewlyTrue"},e.triggerWith={createPrimitiveOfType:"string"},e.triggerWhenObjectsClicked={createPrimitiveOfType:"string"},e.numbers={createComponentOfType:"numberList"},e.number={createComponentOfType:"number"},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();Object.assign(e,t),e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){let t=null;return e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.targetName={returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"}}),definition({dependencyValues:e}){let t=null;return e.targetComponent&&(t=e.targetComponent.componentName),{setValue:{targetName:t}}}},e.insideTriggerSet={returnDependencies:()=>({parentTriggerSet:{dependencyType:"parentStateVariable",parentComponentType:"triggerSet",variableName:"updateValueAndActionsToTrigger"}}),definition:({dependencyValues:e})=>({setValue:{insideTriggerSet:null!==e.parentTriggerSet}})},e.triggerWith={returnDependencies:()=>({triggerWith:{dependencyType:"attributePrimitive",attributeName:"triggerWith"},triggerWhenObjectsClicked:{dependencyType:"attributePrimitive",attributeName:"triggerWhenObjectsClicked"},triggerWhen:{dependencyType:"attributeComponent",attributeName:"triggerWhen"},insideTriggerSet:{dependencyType:"stateVariable",variableName:"insideTriggerSet"}}),definition({dependencyValues:e}){if(e.triggerWhen||e.insideTriggerSet)return{setValue:{triggerWith:null}};{let t=[];if(null!==e.triggerWith)for(let n of e.triggerWith.split(/\s+/).filter((e=>e)))t.push({target:n});if(null!==e.triggerWhenObjectsClicked)for(let n of e.triggerWhenObjectsClicked.split(/\s+/).filter((e=>e)))t.push({target:n,triggeringAction:"click"});return 0===t.length&&(t=null),{setValue:{triggerWith:t}}}}},e.triggerWithTargetIds={chainActionOnActionOfStateVariableTargets:{triggeredAction:"callAction"},stateVariablesDeterminingDependencies:["triggerWith"],returnDependencies({stateValues:e}){let t={triggerWith:{dependencyType:"stateVariable",variableName:"triggerWith"}};if(e.triggerWith)for(let[n,r]of e.triggerWith.entries())t[`triggerWithTargetComponentName${n}`]={dependencyType:"expandTargetName",target:r.target};return t},definition({dependencyValues:e}){let t=[];if(e.triggerWith)for(let[n,r]of e.triggerWith.entries()){let a=e[`triggerWithTargetComponentName${n}`];r.triggeringAction&&(a+="|"+r.triggeringAction),t.includes(a)||t.push(a)}return{setValue:{triggerWithTargetIds:t}}},markStale:()=>({updateActionChaining:!0})};let n=e.hidden.returnDependencies,r=e.hidden.definition;return e.hidden.returnDependencies=function(e){let t=n(e);return t.triggerWhen={dependencyType:"attributeComponent",attributeName:"triggerWhen"},t.triggerWith={dependencyType:"stateVariable",variableName:"triggerWith"},t.insideTriggerSet={dependencyType:"stateVariable",variableName:"insideTriggerSet"},t},e.hidden.definition=function(e){return e.dependencyValues.triggerWhen||e.dependencyValues.triggerWith||e.dependencyValues.insideTriggerSet?{setValue:{hidden:!0}}:r(e)},e}async callAction({actionId:e}){let t=await this.stateValues.targetName,n=await this.stateValues.actionName;if(null!==t&&null!==n){let r={};this.serializedChildren.length>0&&(r.serializedComponents=deepClone(this.serializedChildren)),this.attributes.number&&(r.number=await this.attributes.number.component.stateValues.value),this.attributes.numbers&&(r.numbers=await this.attributes.numbers.component.stateValues.numbers),e&&(r.actionId=e),await this.coreFunctions.performAction({componentName:t,actionName:n,args:r,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType}},caseInsensitiveMatch:!0}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}else this.coreFunctions.resolveAction({actionId:e})}async callActionIfTriggerNewlyTrue({stateValues:e,previousValues:t,actionId:n}){if(e.triggerWhen&&!1===t.triggerWhen&&!await this.stateValues.insideTriggerSet)return await this.callAction({actionId:n});this.coreFunctions.resolveAction({actionId:n})}actions={callAction:this.callAction.bind(this),callActionIfTriggerNewlyTrue:this.callActionIfTriggerNewlyTrue.bind(this)}}class triggerSet extends InlineComponent{static componentType="triggerSet";static createAttributesObject(){let e=super.createAttributesObject();return e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.triggerWhen={createComponentOfType:"boolean",createStateVariable:"triggerWhen",defaultValue:!1,triggerActionOnChange:"triggerActionsIfTriggerNewlyTrue"},e.triggerWith={createPrimitiveOfType:"string"},e.triggerWhenObjectsClicked={createPrimitiveOfType:"string"},e}static returnChildGroups(){return[{group:"updateValuesCallActions",componentTypes:["updateValue","callAction"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();Object.assign(e,t),e.updateValueAndActionsToTrigger={returnDependencies:()=>({updateValueAndCallActionChildren:{dependencyType:"child",childGroups:["updateValuesCallActions"]}}),definition:({dependencyValues:e})=>({setValue:{updateValueAndActionsToTrigger:e.updateValueAndCallActionChildren}})},e.triggerWith={returnDependencies:()=>({triggerWith:{dependencyType:"attributePrimitive",attributeName:"triggerWith"},triggerWhenObjectsClicked:{dependencyType:"attributePrimitive",attributeName:"triggerWhenObjectsClicked"},triggerWhen:{dependencyType:"attributeComponent",attributeName:"triggerWhen"}}),definition({dependencyValues:e}){if(e.triggerWhen)return{setValue:{triggerWith:null}};{let t=[];if(null!==e.triggerWith)for(let n of e.triggerWith.split(/\s+/).filter((e=>e)))t.push({target:n});if(null!==e.triggerWhenObjectsClicked)for(let n of e.triggerWhenObjectsClicked.split(/\s+/).filter((e=>e)))t.push({target:n,triggeringAction:"click"});return 0===t.length&&(t=null),{setValue:{triggerWith:t}}}}},e.triggerWithTargetIds={chainActionOnActionOfStateVariableTargets:{triggeredAction:"triggerActions"},stateVariablesDeterminingDependencies:["triggerWith"],returnDependencies({stateValues:e}){let t={triggerWith:{dependencyType:"stateVariable",variableName:"triggerWith"}};if(e.triggerWith)for(let[n,r]of e.triggerWith.entries())t[`triggerWithTargetComponentName${n}`]={dependencyType:"expandTargetName",target:r.target};return t},definition({dependencyValues:e}){let t=[];if(e.triggerWith)for(let[n,r]of e.triggerWith.entries()){let a=e[`triggerWithTargetComponentName${n}`];r.triggeringAction&&(a+="|"+r.triggeringAction),t.includes(a)||t.push(a)}return{setValue:{triggerWithTargetIds:t}}},markStale:()=>({updateActionChaining:!0})};let n=e.hidden.returnDependencies,r=e.hidden.definition;return e.hidden.returnDependencies=function(e){let t=n(e);return t.triggerWhen={dependencyType:"attributeComponent",attributeName:"triggerWhen"},t.triggerWith={dependencyType:"stateVariable",variableName:"triggerWith"},t},e.hidden.definition=function(e){return e.dependencyValues.triggerWhen||e.dependencyValues.triggerWith?{setValue:{hidden:!0}}:r(e)},e}async triggerActions({actionId:e}){for(let e of await this.stateValues.updateValueAndActionsToTrigger)this.componentInfoObjects.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"updateValue"})?await this.coreFunctions.performAction({componentName:e.componentName,actionName:"updateValue"}):this.componentInfoObjects.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"callAction"})&&await this.coreFunctions.performAction({componentName:e.componentName,actionName:"callAction"});return this.coreFunctions.resolveAction({actionId:e}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}async triggerActionsIfTriggerNewlyTrue({stateValues:e,previousValues:t,actionId:n}){if(e.triggerWhen&&!1===t.triggerWhen)return await this.triggerActions({actionId:n});this.coreFunctions.resolveAction({actionId:n})}actions={triggerActions:this.triggerActions.bind(this),triggerActionsIfTriggerNewlyTrue:this.triggerActionsIfTriggerNewlyTrue.bind(this)}}class FunctionIterates extends InlineComponent{static componentType="functionIterates";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.nIterates={createComponentOfType:"integer",createStateVariable:"nIterates",defaultValue:0,public:!0},e.forceSymbolic={createComponentOfType:"boolean",createStateVariable:"forceSymbolic",defaultValue:!1,public:!0},e.forceNumeric={createComponentOfType:"boolean",createStateVariable:"forceNumeric",defaultValue:!1,public:!0},e.initialValue={createComponentOfType:"math",createStateVariable:"initialValue",defaultValue:me$3.fromAst("_")},e.function={createComponentOfType:"function"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["nInputs","nOutputs"]}}),definition:({dependencyValues:e})=>e.functionAttr?e.functionAttr.stateValues.nInputs!==e.functionAttr.stateValues.nOutputs?(console.warn("Function iterates are possible only if the number of inputs is equal to the number of outputs"),{setValue:{nDimensions:0}}):{setValue:{nDimensions:e.functionAttr.stateValues.nInputs}}:{setValue:{nDimensions:0}}},e.allIterates={public:!0,shadowingInstructions:{createComponentOfType:"mathList"},returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["symbolicfs","numericalfs","symbolic"]},forceSymbolic:{dependencyType:"stateVariable",variableName:"forceSymbolic"},forceNumeric:{dependencyType:"stateVariable",variableName:"forceNumeric"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},initialValue:{dependencyType:"stateVariable",variableName:"initialValue"},nIterates:{dependencyType:"stateVariable",variableName:"nIterates"}}),definition({dependencyValues:e}){let t=[],n=e.functionAttr,r=e.initialValue,a=!e.forceNumeric&&(n.stateValues.symbolic||e.forceSymbolic),i=e.nIterates;if(!n||0===e.nDimensions||!(1===e.nDimensions||Array.isArray(r.tree)&&["vector","tuple"].includes(r.tree[0])&&r.tree.length===e.nDimensions+1))return t=Array(i).fill(me$3.fromAst("_")),{setValue:{allIterates:t}};if(a)if(1===e.nDimensions){let e=n.stateValues.symbolicfs[0],a=r;for(let n=0;nme$3.fromAst(e).evaluate_to_constant())).map((e=>null==e?NaN:e));for(let n=0;n({initialValue:{dependencyType:"stateVariable",variableName:"initialValue"},allIterates:{dependencyType:"stateVariable",variableName:"allIterates"}}),definition:({dependencyValues:e})=>({setValue:{allIteratesWithInitial:[e.initialValue,...e.allIterates]}})},e.iterates={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["iterate"],returnArraySizeDependencies:()=>({nIterates:{dependencyType:"stateVariable",variableName:"nIterates"}}),returnArraySize:({dependencyValues:e})=>[e.nIterates],returnArrayDependenciesByKey:()=>({globalDependencies:{allIterates:{dependencyType:"stateVariable",variableName:"allIterates"}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n={};for(let r=0;r!Number.isFinite(e.nIterates)||e.nIterates<0?{}:e.nIterates>0?{finalIterate:{dependencyType:"stateVariable",variableName:`iterate${e.nIterates}`}}:{finalIterate:{dependencyType:"stateVariable",variableName:"initialValue"}},definition:({dependencyValues:e})=>({setValue:{finalIterate:e.finalIterate}})},e}}class Module extends Template{static componentType="module";static renderedDefault=!0;static acceptAnyAttribute=!0;static createAttributesObject(){let e=super.createAttributesObject();return delete e.styleNumber,e}}class CustomAttribute extends CompositeComponent{static componentType="customAttribute";static assignNamesToReplacements=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.componentType={createPrimitiveOfType:"string"},e.attribute={createPrimitiveOfType:"string"},e.defaultValue={leaveRaw:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.componentNameForAttributes={returnDependencies:()=>({parentVariableContainingName:{dependencyType:"parentStateVariable",variableName:"componentNameForAttributes"}}),definition:({dependencyValues:e})=>({setValue:{componentNameForAttributes:e.parentVariableContainingName}})},e.attributeName={returnDependencies:()=>({attribute:{dependencyType:"attributePrimitive",attributeName:"attribute"}}),definition:({dependencyValues:e})=>({setValue:{attributeName:e.attribute}})},e.readyToExpandWhenResolved={stateVariablesDeterminingDependencies:["componentNameForAttributes"],returnDependencies:({stateValues:e})=>({componentIdentity:{dependencyType:"componentIdentity",componentName:e.componentNameForAttributes}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a}){let i=e.attributes.newNamespace?.primitive,o=r.componentTypeLowerCaseMapping[e.attributes.componentType.primitive.toLowerCase()];if(!r.allComponentClasses[o])return console.warn(`Could not find component type ${o}`),{replacements:[]};let s=t[await e.stateValues.componentNameForAttributes],l={};for(let e in s.attributes)l[e.toLowerCase()]=e;let u=await e.stateValues.attributeName,c=l[u.toLowerCase()],p=s.attributes[c];if(void 0===p){if(void 0===e.attributes.defaultValue)return console.warn("Cannot create component from attribute if neither attribute nor default value specified"),{replacements:[]};p=e.attributes.defaultValue}let d=s.constructor,m=Object.keys(d.createAttributesObject()).map((e=>e.toLowerCase()));if(m.push("name","target","assignnames"),m.includes(u.toLowerCase()))return console.warn(`Cannot add attribute ${u} of a ${d.componentType} as it already exists in ${d.componentType} class`),{replacements:[]};let f=componentFromAttribute({attrObj:{createComponentOfType:o},value:p,componentInfoObjects:r}).component;if(f.children&&(applyMacros(f.children,r),i))for(let e of f.children)if("copy"===e.componentType){let t=e.doenetAttributes.target;/[a-zA-Z_]/.test(t[0])&&(e.doenetAttributes.target="../"+t)}return applySugar({serializedComponents:[f],isAttributeComponent:!0,componentInfoObjects:r}),setTNamesToAbsolute([f]),{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:[f],parentName:e.componentName,parentCreatesNewNamespace:i,componentInfoObjects:r}).serializedComponents}}}class Setup extends CompositeComponent{static componentType="setup";static returnChildGroups(){return[{group:"styleDefinitions",componentTypes:["styleDefinitions"]},{group:"feedbackDefinitions",componentTypes:["feedbackDefinitions"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.componentNameForAttributes={returnDependencies:()=>({sourceCompositeIdentity:{dependencyType:"sourceCompositeIdentity"}}),definition({dependencyValues:e}){let t=null;return e.sourceCompositeIdentity&&(t=e.sourceCompositeIdentity.componentName),{setValue:{componentNameForAttributes:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}}class Footnote extends InlineComponent{static componentType="footnote";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text?t+=n.stateValues.text:t+=" ";return{setValue:{text:t}}}},e.footnoteTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({footnoteCounter:{dependencyType:"counter",counterName:"footnote"}}),definition:({dependencyValues:e})=>({setValue:{footnoteTag:String(e.footnoteCounter)}})},e}}class Caption extends BlockComponent{static componentType="caption";static rendererType="containerBlock";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlinesBlocks",componentTypes:["_inline","_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlinesBlocks"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text?t+=n.stateValues.text:t+=" ";return{setValue:{text:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class Endpoint extends Point{static componentType="endpoint";static rendererType="point";static createAttributesObject(){let e=super.createAttributesObject();return e.open={createComponentOfType:"boolean",createStateVariable:"open",defaultValue:!1,public:!0,forRenderer:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}async switchPoint({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!await this.stateValues.open}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{open:!await this.stateValues.open}}});this.coreFunctions.resolveAction({actionId:e})}}class Sort extends CompositeComponent{static componentType="sort";static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static assignNamesToReplacements=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.sortVectorsBy={createComponentOfType:"text",createStateVariable:"sortVectorsBy",defaultValue:"displacement",public:!0,toLowerCase:!0,validValues:["displacement","tail"]},e.sortByComponent={createComponentOfType:"integer",createStateVariable:"sortByComponent",defaultValue:"1",public:!0},e.sortByProp={createPrimitiveOfType:"string"},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.propName={returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"sortByProp"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.componentNamesForValues={returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"],variableNames:["componentNamesInList"],variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.children)n.stateValues.componentNamesInList?t.push(...n.stateValues.componentNamesInList):t.push(n.componentName);return{setValue:{componentNamesForValues:t}}}},e.sortedValues={stateVariablesDeterminingDependencies:["componentNamesForValues","sortByComponent","propName"],returnDependencies({stateValues:e}){let t={sortVectorsBy:{dependencyType:"stateVariable",variableName:"sortVectorsBy"},sortByComponent:{dependencyType:"stateVariable",variableName:"sortByComponent"},propName:{dependencyType:"stateVariable",variableName:"propName"}};if(e.propName)for(let[n,r]of e.componentNamesForValues.entries())t[`component${n}`]={dependencyType:"stateVariable",componentName:r,variableName:e.propName,variablesOptional:!0,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,returnAsComponentObject:!0};else for(let[n,r]of e.componentNamesForValues.entries())t[`component${n}`]={dependencyType:"multipleStateVariables",componentName:r,variableNames:["value",`x${e.sortByComponent}`,`tailX${e.sortByComponent}`],variablesOptional:!0};return t},definition({dependencyValues:e,componentInfoObjects:t}){let n=[],r=!0;for(let a in e){if("component"!==a.substring(0,9))continue;let i=e[a];if(e.propName){let e=Object.values(i.stateValues)[0];n.push({componentName:i.componentName,numericalValue:Number(e),textValue:String(e)}),Number.isFinite(e)||(r=!1)}else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"number"}))n.push({componentName:i.componentName,numericalValue:i.stateValues.value,textValue:String(i.stateValues.value)});else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"text"})){let e=NaN,t=i.stateValues.value;n.push({componentName:i.componentName,numericalValue:e,textValue:t}),r=!1}else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"math"})){let e=i.stateValues.value.evaluate_to_constant();null===e&&(e=NaN,r=!1),n.push({componentName:i.componentName,numericalValue:e,textValue:i.stateValues.value.toString()})}else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"point"})){let t=i.stateValues[`x${e.sortByComponent}`],a=NaN,o="";t&&(a=t.evaluate_to_constant(),null===a&&(a=NaN,r=!1),o=t.toString()),n.push({componentName:i.componentName,numericalValue:a,textValue:o})}else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"vector"})){let t=NaN,a="",o=i.stateValues[`x${e.sortByComponent}`];o="displacement"===e.sortVectorsBy?i.stateValues[`x${e.sortByComponent}`]:i.stateValues[`tailX${e.sortByComponent}`],o&&(t=o.evaluate_to_constant(),null===t&&(t=NaN,r=!1),a=o.toString()),n.push({componentName:i.componentName,numericalValue:t,textValue:a})}}return r?n.sort(((e,t)=>e.numericalValue-t.numericalValue)):n.sort(((e,t)=>e.textValue>t.textValue?1:e.textValue({sortedValues:{dependencyType:"stateVariable",variableName:"sortedValues"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n,workspace:r}){let a=[],i=[];for(let n of await e.stateValues.sortedValues){let e;if(void 0===n.listInd)e=t[n.componentName];else{e=t[n.componentName].activeChildren[n.listInd]}e&&(i.push(e.componentName),a.push(await e.serialize({sourceAttributesToIgnoreRecursively:["isResponse"]})))}r.uniqueIdentifiersUsed=[],a=postProcessCopy({serializedComponents:a,componentName:e.componentName,uniqueIdentifiersUsed:r.uniqueIdentifiersUsed,addShadowDependencies:!0,markAsPrimaryShadow:!0});let o=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:a,parentName:e.componentName,parentCreatesNewNamespace:await e.stateValues.newNamespace,componentInfoObjects:n});return r.componentsCopied=i,{replacements:o.serializedComponents}}static async calculateReplacementChanges({component:e,components:t,componentInfoObjects:n,workspace:r}){let a=[];for(let n of await e.stateValues.sortedValues){let e;if(void 0===n.listInd)e=t[n.componentName];else{e=t[n.componentName].activeChildren[n.listInd]}e&&a.push(e.componentName)}if(a.length==r.componentsCopied.length&&r.componentsCopied.every(((e,t)=>e===a[t])))return[];let i=(await this.createSerializedReplacements({component:e,components:t,componentInfoObjects:n,workspace:r})).replacements;return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:i}]}}class Shuffle extends CompositeComponent{static componentType="shuffle";static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static assignNamesToReplacements=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.originalComponentNames={additionalStateVariablesDefined:["nComponents"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"],variableNames:["componentNamesInList"],variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.children)n.stateValues.componentNamesInList?t.push(...n.stateValues.componentNamesInList):t.push(n.componentName);return{setValue:{originalComponentNames:t,nComponents:t.length}}}},e.componentOrder={returnDependencies:({sharedParameters:e})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},rngClass:{dependencyType:"value",value:e.rngClass,doNotProxy:!0},nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},variants:{dependencyType:"variants"}}),definition({dependencyValues:e}){let t=e.nComponents,n=e.variants?.desiredVariant?.indices;if(void 0!==n)if(n.length!==t)console.warn("Ignoring indices specified for shuffle as number of indices doesn't match number of components.");else{if(n=n.map(Number),!n.every(Number.isInteger))throw Error("All indices specified for shuffle must be integers");if(n.every((e=>e>=1&&e<=t)))return{setValue:{componentOrder:n}};console.warn("Ignoring indices specified for shuffle as some indices out of range.")}let r=e.rngClass(e.variantSeed+"co"),a=[...Array(t).keys()].map((e=>e+1));for(let e=t-1;e>0;e--){const t=r(),n=Math.floor(t*(e+1));[a[e],a[n]]=[a[n],a[e]]}return{setValue:{componentOrder:a}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({sortedValues:{dependencyType:"stateVariable",variableName:"componentOrder"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({componentInfoObjects:e,sharedParameters:t})=>({variantSeed:{dependencyType:"value",value:t.variantSeed},componentOrder:{dependencyType:"stateVariable",variableName:"componentOrder"},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(e.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t},indices:e.componentOrder},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n})}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n,workspace:r}){let a=[],i=[],o=await e.stateValues.originalComponentNames;for(let n of await e.stateValues.componentOrder){let e=t[o[n-1]];e&&(i.push(e.componentName),a.push(await e.serialize({sourceAttributesToIgnoreRecursively:["isResponse"]})))}r.uniqueIdentifiersUsed=[],a=postProcessCopy({serializedComponents:a,componentName:e.componentName,uniqueIdentifiersUsed:r.uniqueIdentifiersUsed,addShadowDependencies:!0,markAsPrimaryShadow:!0});let s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:a,parentName:e.componentName,parentCreatesNewNamespace:await e.stateValues.newNamespace,componentInfoObjects:n});return r.componentsCopied=i,{replacements:s.serializedComponents}}static async calculateReplacementChanges({component:e,components:t,componentInfoObjects:n,workspace:r}){let a=[],i=await e.stateValues.originalComponentNames;for(let n of await e.stateValues.componentOrder){let e=t[i[n-1]];e&&a.push(e.componentName)}if(a.length==r.componentsCopied.length&&r.componentsCopied.every(((e,t)=>e===a[t])))return[];let o=(await this.createSerializedReplacements({component:e,components:t,componentInfoObjects:n,workspace:r})).replacements;return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:o}]}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){let n=0;for(let r of e.children)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})){if(!r.attributes.createComponentOfType?.primitive)return{success:!1};if(void 0!==r.attributes.nComponents?.primitive){let e=Number(r.attributes.nComponents?.primitive);if(!(Number.isInteger(e)&&e>=0))return{success:!1};n+=e}else n++}else n++;let r=1;for(let e=2;e<=n;e++)r*=e;let a=super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!a.success)return{success:!1};let i=a.numberOfVariants*r;return e.variants.numberOfVariants=i,e.variants.uniqueVariantData={numberOfVariantsByDescendant:e.variants.uniqueVariantData.numberOfVariantsByDescendant,numberOfPermutations:r,nComponents:n},{success:!0,numberOfVariants:i}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};let a=e.variants.uniqueVariantData.numberOfVariantsByDescendant,i=e.variants.descendantVariantComponents,o=e.variants.uniqueVariantData.numberOfPermutations,s=e.variants.uniqueVariantData.nComponents,l=[...a];l.push(o);let u=enumerateCombinations({numberOfOptionsByIndex:l,maxNumber:t})[t-1].map((e=>e+1)),c=u.pop(),p=u,d=[...Array(s).keys()].map((e=>e+1)),m=enumeratePermutations({values:d,maxNumber:c})[c-1],f=!1,h=[];for(let e=0;e1){let t=i[e],r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:p[e],componentInfoObjects:n});if(!r.success)return{success:!1};h.push(r.desiredVariant),f=!0}else h.push({});let y={indices:m};return f&&(y.subvariants=h),{success:!0,desiredVariant:y}}}class SolveEquations extends InlineComponent{static componentType="solveEquations";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.variables={createComponentOfType:"variables"},e.nDiscretizationPoints={createComponentOfType:"number",createStateVariable:"nDiscretizationPoints",defaultValue:100,public:!0},e.minVar={createComponentOfType:"number",createStateVariable:"minVar",defaultValue:null},e.maxVar={createComponentOfType:"number",createStateVariable:"maxVar",defaultValue:null},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){return e.every((e=>"string"==typeof e||e.doenetAttributes&&e.doenetAttributes.createdFromMacro))?1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}:{success:!1}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"strings",componentTypes:["string"]}]}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({}),returnArraySize:({dependencyValues:e})=>[1],returnArrayDependenciesByKey:({arrayKeys:e})=>({globalDependencies:{variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t,arrayKeys:n,usedDefault:r}){let a=[];return null!==e.variablesAttr&&(a=e.variablesAttr.stateValues.variables),{setValue:{variables:returnNVariables(t[0],a)}}}},t.variable={isAlias:!0,targetVariableName:"variable1"},t.allSolutions={returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},variables:{dependencyType:"stateVariable",variableName:"variables"},minVar:{dependencyType:"stateVariable",variableName:"minVar"},maxVar:{dependencyType:"stateVariable",variableName:"maxVar"},nDiscretizationPoints:{dependencyType:"stateVariable",variableName:"nDiscretizationPoints"}}),definition({dependencyValues:t}){if(0===t.mathChild.length)return{setValue:{allSolutions:[]}};let n=t.mathChild[0].stateValues.value;if(!Array.isArray(n.tree)||3!==n.tree.length||"="!==n.tree[0])return{setValue:{allSolutions:[]}};let r=t.minVar,a=t.maxVar,i=[],o=t.variables[0].subscripts_to_strings().tree,s=me$3.fromAst(["+",n.tree[1],["-",n.tree[2]]]).subscripts_to_strings(),l=s.f(),u=e=>l({[o]:e}),c=function(e){try{return u(e)}catch(e){return NaN}};if(Number.isFinite(r)||(r=-10),Number.isFinite(a)||(a=10),r>a)return{setValue:{allSolutions:[]}};let p=[r,a],d=[r];for(let e=0;enormalizeMathExpression({value:s.substitute({[o]:e}).strings_to_subscripts(),simplify:!0,expand:!0}).evaluate_to_constant())(e);return null!==n?n:NaN}})),y=d[0],b=h[0];for(let e=0;e0)for(let t=0;t<10;t++)if(y=.1*y+.9*n,o=.1*o+.9*n,b=c(y),s=c(o),b*s<0){b*u<0?(i.push(e.fzero(c,[l,y])),i.push(n)):(i.includes(n)||i.push(n),n=o,r=s),a=!0;break}}a||i.includes(n)||i.push(n)}else if(r*b<0)i.push(e.fzero(c,[y,n]));else if(0!==b&&t0&&(r>0&&b>r||r<0&&br?c:e=>-c(e);let o=e.fminbr(t,[y,a],void 0,1e-10);if(o.success){let t=o.x,a=c(t);a*b<0?(i.push(e.fzero(c,[y,t])),n=t,r=a):0===a&&i.push(t)}}}y=n,b=r}i=i.filter((e=>e>=r&&e<=a));let g=i.map((e=>me$3.fromAst(e)));return{setValue:{allSolutions:g}}}},t.numberSolutions={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allSolutions:{dependencyType:"stateVariable",variableName:"allSolutions"}}),definition:({dependencyValues:e})=>({setValue:{numberSolutions:e.allSolutions.length}})},t.solutions={public:!0,shadowingInstructions:{createComponentOfType:"math"},isArray:!0,entryPrefixes:["solution"],returnArraySizeDependencies:()=>({numberSolutions:{dependencyType:"stateVariable",variableName:"numberSolutions"}}),returnArraySize:({dependencyValues:e})=>[e.numberSolutions],returnArrayDependenciesByKey:()=>({globalDependencies:{allSolutions:{dependencyType:"stateVariable",variableName:"allSolutions"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({parentOpen:{dependencyType:"parentStateVariable",variableName:"open"}}),markStale:()=>({updateReplacements:!0}),definition:({dependencyValues:e})=>({setValue:{rendered:Boolean(e.parentOpen)}})},e}static async calculateReplacementChanges({component:e,componentInfoObjects:t}){if(await e.stateValues.rendered&&0===e.replacements.length){let n=(await this.createSerializedReplacements({component:e,componentInfoObjects:t})).replacements;if(n.length>0){return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:0,serializedReplacements:n}]}return[]}return[]}}class SubsetOfRealsInput extends BlockComponent{static componentType="subsetOfRealsInput";static variableForPlainMacro="subsetValue";static variableForPlainCopy="subsetValue";static createAttributesObject(){let e=super.createAttributesObject();return e.xmin={createComponentOfType:"number",createStateVariable:"xmin",defaultValue:-10,public:!0,forRenderer:!0},e.xmax={createComponentOfType:"number",createStateVariable:"xmax",defaultValue:10,public:!0,forRenderer:!0},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:800,public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:300,public:!0,forRenderer:!0},e.xlabel={createComponentOfType:"text",createStateVariable:"xlabel",defaultValue:"",public:!0,forRenderer:!0},e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:.5,public:!0},e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x"),public:!0},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e.bindValueTo={createComponentOfType:"subsetOfReals"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.subsetValue={public:!0,shadowingInstructions:{createComponentOfType:"subsetOfReals"},hasEssential:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["subsetValue"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"},variable:{dependencyType:"stateVariable",variableName:"variable"},format:{dependencyType:"stateVariable",variableName:"format"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{subsetValue:e.bindValueTo.stateValues.subsetValue}}:{useEssentialOrDefaultValue:{subsetValue:{get defaultValue(){return parseValueIntoSubset({inputString:e.prefill,format:e.format,variable:e.variable})}}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.subsetValue,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"subsetValue",value:e.subsetValue}]}},e.pointsFromSubset={additionalStateVariablesDefined:["intervalsFromSubset"],returnDependencies:()=>({subsetValue:{dependencyType:"stateVariable",variableName:"subsetValue"}}),definition({dependencyValues:e}){function t(e,t){let n=[],r=[];if(e.points&&(n=e.points),e.intervals&&(r=e.intervals),t.points){let e=n.map((e=>e.value));for(let r of t.points){let t=e.indexOf(r.value);-1===t?n.push(r):n[t].inSubset||=r.inSubset}}return t.intervals&&r.push(...t.intervals),{points:n,intervals:r}}let{points:n,intervals:r}=function e(n){if(null===n||n.isEmpty())return{};if(n instanceof theModule.Union){let r=[],a=[];for(let i of n.subsets){let n=e(i);({points:r,intervals:a}=t({points:r,intervals:a},n))}return{points:r,intervals:a}}if(n instanceof theModule.RealLine)return{intervals:[[-1/0,1/0]]};if(n instanceof theModule.Singleton)return{points:[{value:n.element,inSubset:!0}]};if(n instanceof theModule.OpenInterval){let e=[[n.left,n.right]],t=[];return Number.isFinite(n.left)&&t.push({value:n.left,inSubset:!1}),Number.isFinite(n.right)&&t.push({value:n.right,inSubset:!1}),{intervals:e,points:t}}return{}}(e.subsetValue),a=n||[],i=r||[];return a.sort(((e,t)=>e.value-t.value)),i.sort(((e,t)=>e[0]-t[0])),{setValue:{pointsFromSubset:a,intervalsFromSubset:i}}}},e.additionalPoints={defaultValue:[],hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{additionalPoints:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>e.additionalPoints.every(Number.isFinite)?{success:!0,instructions:[{setEssentialValue:"additionalPoints",value:[...e.additionalPoints].sort(((e,t)=>e-t))}]}:{success:!1}},e.points={additionalStateVariablesDefined:[{variableName:"intervals",forRenderer:!0}],forRenderer:!0,returnDependencies:()=>({pointsFromSubset:{dependencyType:"stateVariable",variableName:"pointsFromSubset"},intervalsFromSubset:{dependencyType:"stateVariable",variableName:"intervalsFromSubset"},additionalPoints:{dependencyType:"stateVariable",variableName:"additionalPoints"}}),definition({dependencyValues:e}){let t=[...e.pointsFromSubset],n=[...e.intervalsFromSubset],r=[...e.additionalPoints].sort(((e,t)=>e-t)),a=[],i=[],o=0,s=1/0,l=0;r.length>0&&(s=r[0]);let u=n[0],c=-1/0;t.push({value:1/0,inSubset:!1});for(let e of t){let t=!1;for(u&&u[0]e.value));if(!e.includes(r)){let e=!1;for(let t of i)if(t[0]r){e=!0;break}if(e)return o.push(r),await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:o}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{addedPoint:r,intervalsFromSubset:i,pointsFromSubset:a,additionalPoints:o}}});{a.push({value:r,inSubset:!0});let e=await this.createUpdateInstructions({intervalsFromSubset:i,pointsFromSubset:a,modifiedAdditionalPoints:!1,additionalPoints:o});return await this.coreFunctions.performUpdate({updateInstructions:e,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{addedPoint:r,intervalsFromSubset:i,pointsFromSubset:a,additionalPoints:o}}})}}}this.coreFunctions.resolveAction({actionId:t})}async deletePoint({pointInd:e,actionId:t}){let n=await this.stateValues.points[e],r=[...await this.stateValues.additionalPoints],a=[...await this.stateValues.pointsFromSubset],i=[...await this.stateValues.intervalsFromSubset];if(n.isAdditional)return r.splice(n.additionalPointInd,1),await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:r}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{deletedPoint:n.value,intervalsFromSubset:i,pointsFromSubset:a,additionalPoints:r}}});{let o=!1,s=a.map((e=>e.value)).indexOf(n.value),l=i.map((e=>e[1])).indexOf(n.value),u=i.map((e=>e[0])).indexOf(n.value);if(-1!==l)if(-1!==u)i[l]=[i[l][0],i[u][1]],i.splice(u,1),a.splice(s,1);else{let t=(await this.stateValues.points)[e-1];if(t&&t.isAdditional)i[l]=[i[l][0],t.value],r.splice(n.additionalPointInd,1),o=!0,a.splice(s,1,t);else if(i.splice(l,1),a.splice(s,1),t&&!t.inSubset){let e=i.map((e=>e[1])).indexOf(t.value);-1===e&&(r.push(t.value),o=!0)}}else if(-1!==u){let t=(await this.stateValues.points)[e+1];if(t&&t.isAdditional)i[u]=[t.value,i[u][1]],r.splice(n.additionalPointInd,1),o=!0,a.splice(s,1,t);else if(i.splice(u,1),a.splice(s,1),t&&!t.inSubset){let e=i.map((e=>e[0])).indexOf(t.value);-1===e&&(r.push(t.value),o=!0)}}else a.splice(s,1);let c=await this.createUpdateInstructions({intervalsFromSubset:i,pointsFromSubset:a,modifiedAdditionalPoints:o,additionalPoints:r});return await this.coreFunctions.performUpdate({updateInstructions:c,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{deletedPoint:n.value,intervalsFromSubset:i,pointsFromSubset:a,additionalPoints:r}}})}}async createUpdateInstructions({intervalsFromSubset:e,pointsFromSubset:t,modifiedAdditionalPoints:n,additionalPoints:r}){let a,i=await this.stateValues.dx,o=e=>Math.round(e/i)*i,s=[];for(let t of e)s.push(new theModule.OpenInterval(o(t[0]),o(t[1])));for(let e of t)e.inSubset&&s.push(new theModule.Singleton(o(e.value)));a=0===s.length?new theModule.EmptySet:1===s.length?s[0]:new theModule.Union(s);let l=[{componentName:this.componentName,updateType:"updateValue",stateVariable:"subsetValue",value:a}];return n&&l.push({componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:r.map(o)}),l}async movePoint({pointInd:e,value:t,transient:n,actionId:r}){let a=await this.stateValues.dx,i=Math.round(Math.max(await this.stateValues.xmin,Math.min(await this.stateValues.xmax,t))/a)*a,o=await this.stateValues.points,s=o[e],l=o[e-1];l&&(i=Math.max(i,l.value+a));let u=o[e+1];u&&(i=Math.min(i,u.value-a));let c=[...await this.stateValues.additionalPoints],p=[...await this.stateValues.pointsFromSubset],d=[...await this.stateValues.intervalsFromSubset];if(s.isAdditional)return c[s.additionalPointInd]=i,n?await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:c}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:c}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{movedPoint:i,intervalsFromSubset:d,pointsFromSubset:p,additionalPoints:c}}});{let e=p.map((e=>e.value)).indexOf(s.value),t=d.map((e=>e[1])).indexOf(s.value),a=d.map((e=>e[0])).indexOf(s.value);p[e]={value:i,inSubset:p[e].inSubset},-1!==t&&(d[t]=[d[t][0],i]),-1!==a&&(d[a]=[i,d[a][1]]);let o=await this.createUpdateInstructions({intervalsFromSubset:d,pointsFromSubset:p,modifiedAdditionalPoints:!1});return n?await this.coreFunctions.performUpdate({updateInstructions:o,transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:o,actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{movedPoint:i,intervalsFromSubset:d,pointsFromSubset:p,additionalPoints:c}}})}}async togglePoint({pointInd:e,actionId:t}){let n=(await this.stateValues.points)[e],r=[...await this.stateValues.pointsFromSubset],a=[...await this.stateValues.intervalsFromSubset],i=[...await this.stateValues.additionalPoints],o=!1;if(n.isAdditional)if(i.splice(n.additionalPointInd,1),o=!0,n.inSubset){for(let[e,t]of a.entries())if(t[0]n.value){let r=[[t[0],n.value],[n.value,t[1]]];a.splice(e,1,...r);break}}else r.push({value:n.value,inSubset:!0});else{let e=r.map((e=>e.value)).indexOf(n.value),t=a.map((e=>e[1])).indexOf(n.value),s=a.map((e=>e[0])).indexOf(n.value);-1!==t?-1!==s?(a[t]=[a[t][0],a[s][1]],a.splice(s,1),r.splice(e,1),i.push(n.value),o=!0):r[e]={value:n.value,inSubset:!n.inSubset}:-1!==s?r[e]={value:n.value,inSubset:!n.inSubset}:(r.splice(e,1),i.push(n.value),o=!0)}let s=await this.createUpdateInstructions({intervalsFromSubset:a,pointsFromSubset:r,modifiedAdditionalPoints:o,additionalPoints:i});return await this.coreFunctions.performUpdate({updateInstructions:s,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{toggledPoint:n.value,intervalsFromSubset:a,pointsFromSubset:r,additionalPoints:i}}})}async toggleInterval({intervalInd:e,actionId:t}){let n=(await this.stateValues.intervals)[e],r=await this.stateValues.points,a=r[e-1],i=r[e],o=[...await this.stateValues.pointsFromSubset],s=[...await this.stateValues.intervalsFromSubset],l=[...await this.stateValues.additionalPoints],u=!1;if(n.inSubset){let e,t;for(let[r,a]of s.entries())if(a[0]<=n.left&&a[1]>=n.right){t=a,e=r;break}if(n.left===t[0])if(n.right===t[1]){if(s.splice(e,1),a&&!a.inSubset){let e=s.map((e=>e[1])).indexOf(a.value);if(-1===e){let e=o.map((e=>e.value)).indexOf(a.value);o.splice(e,1),l.push(a.value),u=!0}}if(i&&!i.inSubset){let e=s.map((e=>e[0])).indexOf(i.value);if(-1===e){let e=o.map((e=>e.value)).indexOf(i.value);o.splice(e,1),l.push(i.value),u=!0}}}else{if(s[e]=[n.right,t[1]],a&&!a.inSubset){let e=s.map((e=>e[1])).indexOf(a.value);if(-1===e){let e=o.map((e=>e.value)).indexOf(a.value);o.splice(e,1),l.push(a.value),u=!0}}o.push({value:i.value,inSubset:!0}),l.splice(i.additionalPointInd,1),u=!0}else if(n.right===t[1]){if(s[e]=[t[0],n.left],i&&!i.inSubset){let e=s.map((e=>e[0])).indexOf(i.value);if(-1===e){let e=o.map((e=>e.value)).indexOf(i.value);o.splice(e,1),l.push(i.value),u=!0}}o.push({value:a.value,inSubset:!0}),l.splice(a.additionalPointInd,1),u=!0}else{let r=[[t[0],n.left],[n.right,t[1]]];s.splice(e,1,...r),o.push({value:a.value,inSubset:!0}),o.push({value:i.value,inSubset:!0}),l.splice(i.additionalPointInd,1),l.splice(a.additionalPointInd,1),u=!0}}else{let e=s.map((e=>e[1])).indexOf(n.left),t=s.map((e=>e[0])).indexOf(n.right);if(-1===e)-1===t?(s.push([n.left,n.right]),i&&i.isAdditional&&(l.splice(i.additionalPointInd,1),u=!0),a&&a.isAdditional&&(l.splice(a.additionalPointInd,1),u=!0)):(i.inSubset?(s[t]=[n.left,s[t][1]],l.push(i.value),u=!0):s.push([n.left,n.right]),a&&a.isAdditional&&(l.splice(a.additionalPointInd,1),u=!0));else if(-1===t)a.inSubset?(s[e]=[s[e][0],n.right],l.push(a.value),u=!0):s.push([n.left,n.right]),i&&i.isAdditional&&(l.splice(i.additionalPointInd,1),u=!0);else if(a.inSubset)if(i.inSubset){let n=[s[e][0],s[t][1]];s.splice(e,2,n),l.push(a.value),l.push(i.value),u=!0}else s[e]=[s[e][0],n.right],l.push(a.value),u=!0;else i.inSubset?(s[t]=[n.left,s[t][1]],l.push(i.value),u=!0):s.push([n.left,n.right])}let c=await this.createUpdateInstructions({intervalsFromSubset:s,pointsFromSubset:o,modifiedAdditionalPoints:u,additionalPoints:l});return await this.coreFunctions.performUpdate({updateInstructions:c,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{toggledInterval:[n.left,n.right],intervalsFromSubset:s,pointsFromSubset:o,additionalPoints:l}}})}async clear({actionId:e}){let t=await this.createUpdateInstructions({intervalsFromSubset:[],pointsFromSubset:[],modifiedAdditionalPoints:!0,additionalPoints:[]});return await this.coreFunctions.performUpdate({updateInstructions:t,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{cleared:!0,intervalsFromSubset:[],pointsFromSubset:[],additionalPoints:[]}}})}async setToR({actionId:e}){let t=await this.createUpdateInstructions({intervalsFromSubset:[[-1/0,1/0]],pointsFromSubset:[],modifiedAdditionalPoints:!0,additionalPoints:[]});return await this.coreFunctions.performUpdate({updateInstructions:t,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{setToR:!0,intervalsFromSubset:[[-1/0,1/0]],pointsFromSubset:[],additionalPoints:[]}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={addPoint:this.addPoint.bind(this),deletePoint:this.deletePoint.bind(this),movePoint:this.movePoint.bind(this),togglePoint:this.togglePoint.bind(this),toggleInterval:this.toggleInterval.bind(this),clear:this.clear.bind(this),setToR:this.setToR.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)}}function parseValueIntoSubset({inputString:e,format:t,variable:n}){if(!e)return new theModule.EmptySet;let r;if("latex"===t)try{r=me$3.fromLatex(e)}catch(t){return console.warn(`Invalid latex for subsetOfRealsInput: ${e}`),new theModule.EmptySet}else if("text"===t)try{r=me$3.fromText(e)}catch(t){return console.warn(`Invalid text for subsetOfRealsInput: ${e}`),new theModule.EmptySet}return buildSubsetFromMathExpression(r,n)}class SubsetOfReals extends MathComponent{static componentType="subsetOfReals";static rendererType="math";static primaryStateVariableForDefinition="subsetValue";static createAttributesObject(){let e=super.createAttributesObject();return e.createIntervals.defaultValue=!0,e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x")},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",defaultValue:"intervals",public:!0,toLowerCase:!0,validValues:["intervals","inequalities"]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"unnormalizedValue",newName:"unnormalizedValuePreliminary"}),e.value.shadowingInstructions.createComponentOfType="math",e.haveSingleSubsetChild={returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"]}}),definition:({dependencyValues:e,componentInfoObjects:t})=>({setValue:{haveSingleSubsetChild:1===e.mathChildren.length&&1===e.mathChildren.filter((e=>t.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"subsetOfReals"}))).length}})},e.subsetValue={stateVariablesDeterminingDependencies:["haveSingleSubsetChild"],returnDependencies({stateValues:e}){let t={haveSingleSubsetChild:{dependencyType:"stateVariable",variableName:"haveSingleSubsetChild"}};return e.haveSingleSubsetChild?t.subsetChild={dependencyType:"child",childGroups:["maths"],variableNames:["subsetValue"]}:(t.unnormalizedValuePreliminary={dependencyType:"stateVariable",variableName:"unnormalizedValuePreliminary"},t.variable={dependencyType:"stateVariable",variableName:"variable"}),t},definition({dependencyValues:e}){let t;return t=e.haveSingleSubsetChild?e.subsetChild[0].stateValues.subsetValue:buildSubsetFromMathExpression(e.unnormalizedValuePreliminary,e.variable),{setValue:{subsetValue:t}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(t.haveSingleSubsetChild)return{success:!0,instructions:[{setDependency:"subsetChild",desiredValue:e.subsetValue,childIndex:0,variableIndex:0}]};return{success:!0,instructions:[{setDependency:"unnormalizedValuePreliminary",desiredValue:mathExpressionFromSubsetValue({subsetValue:e.subsetValue,variable:t.variable,displayMode:await n.displayMode})}]}}},e.unnormalizedValue={returnDependencies:()=>({subsetValue:{dependencyType:"stateVariable",variableName:"subsetValue"},displayMode:{dependencyType:"stateVariable",variableName:"displayMode"},variable:{dependencyType:"stateVariable",variableName:"variable"}}),definition:({dependencyValues:e})=>({setValue:{unnormalizedValue:mathExpressionFromSubsetValue(e)}}),inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>({success:!0,instructions:[{setDependency:"subsetValue",desiredValue:buildSubsetFromMathExpression(e.unnormalizedValue,t.variable)}]})},e}}function mathExpressionFromSubsetValue({subsetValue:e,variable:t,displayMode:n="intervals"}){function r(e){return null===e?"_":"intervals"===n?e.closedInterval?["interval",["tuple",e.left,e.right],["tuple",!0,!0]]:e.openClosedInterval?["interval",["tuple",e.left,e.right],["tuple",!1,!0]]:e.closedOpenInterval?["interval",["tuple",e.left,e.right],["tuple",!0,!1]]:e.toMathExpression().tree:e.closedInterval?["lts",["tuple",e.left,t,e.right],["tuple",!1,!1]]:e.openClosedInterval?e.left===-1/0?["le",t,e.right]:["lts",["tuple",e.left,t,e.right],["tuple",!0,!1]]:e.closedOpenInterval?e.right===1/0?["ge",t,e.left]:["lts",["tuple",e.left,t,e.right],["tuple",!1,!0]]:e instanceof theModule.OpenInterval?e.left===-1/0?["<",t,e.right]:e.right===1/0?[">",t,e.left]:["lts",["tuple",e.left,t,e.right],["tuple",!0,!0]]:e instanceof theModule.Singleton?["=",t,e.element]:e.isEmpty()?["in",t,"∅"]:e instanceof theModule.RealLine?["in",t,"R"]:null}let a;if(e instanceof theModule.Union){let t=e.subsets.filter((e=>e instanceof theModule.Singleton)),i=e.subsets.filter((e=>e instanceof theModule.OpenInterval));for(let e=0;e(void 0===e.left?e.element:e.left)-(void 0===t.left?t.element:t.left))).map((e=>r(e)));a=o.length>1?"intervals"===n?me$3.fromAst(["union",...o]):me$3.fromAst(["or",...o]):me$3.fromAst(o[0])}else a=me$3.fromAst(r(e));return a}class Split extends CompositeComponent{static componentType="split";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"text",toLowerCase:!0,validValues:["text"]},e.splitBy={createComponentOfType:"text",createStateVariable:"splitBy",defaultValue:"letter",toLowerCase:!0,validValues:["letter","word","comma"]},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){let n=t.type;return["text"].includes(n)||(n="text"),{success:!0,newChildren:[{componentType:n,children:e}]}}}),e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.originalValue={returnDependencies:()=>({child:{dependencyType:"child",childGroups:["anything"],variableNames:["value"]}}),definition:({dependencyValues:e})=>e.child.length>0?{setValue:{originalValue:e.child[0].stateValues.value}}:{setValue:{originalValue:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.child.length>0?{success:!0,instructions:[{setDependency:"child",desiredValue:e.originalValue,childIndex:0,variableIndex:0}]}:{success:!1}},e.splitValues={returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},originalValue:{dependencyType:"stateVariable",variableName:"originalValue"},splitBy:{dependencyType:"stateVariable",variableName:"splitBy"}}),definition({dependencyValues:e}){if(null===e.originalValue)return{setValue:{splitValues:[]}};let t=[];return t="letter"===e.splitBy?[...e.originalValue]:"word"===e.splitBy?e.originalValue.split(/\s+/):"comma"===e.splitBy?e.originalValue.split(/\s*,\s*/):[e.originalValue],{setValue:{splitValues:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({splitValues:{dependencyType:"stateVariable",variableName:"splitValues"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t}){let n=e.attributes.newNamespace?.primitive,r={componentType:"textList",state:{textsShadow:await e.stateValues.splitValues},downstreamDependencies:{[e.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:"splitValues"}]}};return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:[r],parentName:e.componentName,parentCreatesNewNamespace:n,componentInfoObjects:t}).serializedComponents}}}class BestFitLine extends Line{static componentType="bestFitLine";static rendererType="line";static createAttributesObject(){let e=super.createAttributesObject();return delete e.draggable,delete e.equation,delete e.through,delete e.slope,e.points={createComponentOfType:"_pointListComponent"},e}static returnSugarInstructions(){return[]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.draggable={shadowingInstructions:{createComponentOfType:"boolean"},public:!0,forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{draggable:!1}})},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({}),definition:()=>({setValue:{nDimensions:2}})},delete e.nPointsPrescribed,delete e.basedOnSlope,delete e.dForSlope,delete e.essentialPoint1x,delete e.essentialPoint1y,delete e.equationIdentity,delete e.equation.stateVariablesDeterminingDependencies,e.equation.returnDependencies=()=>({points:{dependencyType:"attributeComponent",attributeName:"points",variableNames:["points","nDimensions"]},variables:{dependencyType:"stateVariable",variableName:"variables"}}),e.equation.definition=function({dependencyValues:e}){if(!e.points||e.points.stateValues.nDimensions<2||e.points.stateValues.points.length<1){let e=me$3.fromAst("_");return{setValue:{equation:e,coeff0:e,coeffvar1:e,coeffvar2:e}}}let t=[],n=[];for(let r of e.points.stateValues.points){let e=r.slice(0,2).map((e=>e&&e.evaluate_to_constant()));e.every(Number.isFinite)&&(t.push([1,e[0]]),n.push([e[1]]))}if(0===t.length){let e=me$3.fromAst("_");return{setValue:{equation:e,coeff0:e,coeffvar1:e,coeffvar2:e}}}t=me$3.math.matrix(t),n=me$3.math.matrix(n);let r=me$3.math.transpose(t),a=me$3.math.multiply(r,n),i=me$3.math.multiply(r,t),o=me$3.math.lusolve(i,a),s=me$3.fromAst(me$3.math.subset(o,me$3.math.index(0,0))),l=me$3.fromAst(me$3.math.subset(o,me$3.math.index(1,0))),u=me$3.fromAst(-1),c=e.variables,p=me$3.fromAst(["+",["*","a","x"],"c"]).substitute({a:l,c:s,x:c[0],y:c[1]}).simplify();return{setValue:{equation:me$3.fromAst(["=","y","r"]).substitute({r:p}),coeff0:s,coeffvar1:l,coeffvar2:u}}},delete e.equation.inverseDefinition,delete e.points.stateVariablesDeterminingDependencies,e.points.returnArrayDependenciesByKey=function(){return{globalDependencies:{coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"},variables:{dependencyType:"stateVariable",variableName:"variables"},lastPointsFromInverting:{dependencyType:"stateVariable",variableName:"lastPointsFromInverting"}}}},e}}class RegionBetweenCurveXAxis extends GraphicalComponent{static componentType="regionBetweenCurveXAxis";static createAttributesObject(){let e=super.createAttributesObject();return e.boundaryValues={createComponentOfType:"numberList",createStateVariable:"boundaryValues",defaultValue:[0,1],forRenderer:!0,public:!0},e.function={createComponentOfType:"function"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescription:e.selectedStyle.fillColorWord}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" region"}}}},e.function={additionalStateVariablesDefined:[{variableName:"haveFunction",forRenderer:!0},{variableName:"fDefinition",forRenderer:!0}],returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["numericalfs","nInputs","nOutputs","fDefinition"]}}),definition:({dependencyValues:e})=>null===e.functionAttr||1!==e.functionAttr.stateValues.nInputs||1!==e.functionAttr.stateValues.nOutputs?{setValue:{function:()=>NaN,haveFunction:!1,fDefinition:{}}}:{setValue:{function:e.functionAttr.stateValues.numericalfs[0],haveFunction:!0,fDefinition:e.functionAttr.stateValues.fDefinition}}},e}}class RegionHalfPlane extends GraphicalComponent{static componentType="regionHalfPlane";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.horizontal={createComponentOfType:"boolean",createStateVariable:"horizontal",defaultValue:!0,public:!0},e.boundaryValue={createComponentOfType:"number",createStateVariable:"boundaryValue",defaultValue:0,public:!0},e.greaterThan={createComponentOfType:"boolean",createStateVariable:"greaterThan",defaultValue:!0,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nearestPoint={returnDependencies:()=>({horizontal:{dependencyType:"stateVariable",variableName:"horizontal"},boundaryValue:{dependencyType:"stateVariable",variableName:"boundaryValue"},greaterThan:{dependencyType:"stateVariable",variableName:"greaterThan"}}),definition({dependencyValues:e}){let t=e.boundaryValue;return{setValue:{nearestPoint:function({variables:n,scales:r}){if(!Number.isFinite(t))return{};if(e.horizontal){if(e.greaterThan){if(n.x1t){let e=Object.assign({},n);return e.x1=t,e}return{}}if(e.greaterThan){if(n.x2t){let e=Object.assign({},n);return e.x2=t,e}return{}}}}}},e}}class CodeEditor extends BlockComponent{static componentType="codeEditor";static variableForPlainMacro="value";static variableForPlainCopy="value";static renderChildren=!0;static processWhenJustUpdatedForNewComponent=!0;static get stateVariablesShadowedForReference(){return["value"]}static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e.bindValueTo={createComponentOfType:"text"},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:600,isAbsolute:!0},forRenderer:!0,public:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:400,isAbsolute:!0},forRenderer:!0,public:!0},e.viewerRatio={createComponentOfType:"number",createStateVariable:"viewerRatio",defaultValue:.5,forRenderer:!0,public:!0},e.showResults={createComponentOfType:"boolean",createStateVariable:"showResults",defaultValue:!1,forRenderer:!0,public:!0},e.renderedName={createPrimitiveOfType:"string"},e.staticName={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){if(e.length>0)return{success:!1};let n={componentType:"codeViewer",children:[{componentType:"renderDoenetML"}]},r=[n];if(t.renderedName&&(n.attributes={renderedName:{primitive:t.renderedName}},n.children[0].props={name:t.renderedName}),t.staticName){let e={componentType:"codeViewer",attributes:{hide:{component:{componentType:"boolean",state:{value:!0}}}},children:[{componentType:"renderDoenetML",props:{name:t.staticName}}]};r.push(e)}return{success:!0,newChildren:r}}}),e}static returnChildGroups(){return[{group:"codeViewers",componentTypes:["codeViewer"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.viewerHeight={returnDependencies:()=>({height:{dependencyType:"stateVariable",variableName:"height"},viewerRatio:{dependencyType:"stateVariable",variableName:"viewerRatio"}}),definition:function({dependencyValues:e}){if(!e.height.isAbsolute)throw Error("Codeeditor relative height not implemented");return{setValue:{viewerHeight:{size:e.height.size*e.viewerRatio,isAbsolute:!0}}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{variablesToCheck:"value",defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.value&&!n?{setValue:{immediateValue:e.value},makeEssential:{immediateValue:!0}}:{useEssentialOrDefaultValue:{immediateValue:{variablesToCheck:"immediateValue",defaultValue:e.value}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"text"}})},e.viewerChild={returnDependencies:()=>({viewerChild:{dependencyType:"child",childGroups:["codeViewers"]}}),definition:({dependencyValues:e})=>e.viewerChild.length>0?{setValue:{viewerChild:e.viewerChild}}:{setValue:{viewerChild:null}}},e}updateImmediateValue({text:e,actionId:t}){if(!this.stateValues.disabled)return this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}updateValue({actionId:e}){if(!this.stateValues.disabled&&this.stateValues.immediateValue!==this.stateValues.value){let t=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:this.stateValues.immediateValue},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}],n={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:this.stateValues.immediateValue,responseText:this.stateValues.immediateValue}};return this.stateValues.answerAncestor&&(n.context={answerAncestor:this.stateValues.answerAncestor.componentName}),this.coreFunctions.performUpdate({updateInstructions:t,actionId:e,event:n}).then((()=>{this.coreFunctions.triggerChainedActions({componentName:this.componentName}),this.attributes.staticName&&2===this.definingChildren.length&&"codeViewer"===this.definingChildren[1].componentType&&this.coreFunctions.performAction({componentName:this.definingChildren[1].componentName,actionName:"updateComponents"})}))}this.coreFunctions.resolveAction({actionId:e})}async updateComponents(){1===this.definingChildren.length&&"codeViewer"===this.definingChildren[0].componentType&&await this.coreFunctions.performAction({componentName:this.definingChildren[0].componentName,actionName:"updateComponents"})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={updateImmediateValue:this.updateImmediateValue.bind(this),updateValue:this.updateValue.bind(this),updateComponents:this.updateComponents.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class CodeViewer extends BlockComponent{static componentType="codeViewer";static renderChildren=!0;static includeBlankStringChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.codeSource={createPrimitiveOfType:"string",createStateVariable:"rawCodeSource",defaultValue:null},e.width={createComponentOfType:"_componentSize"},e.height={createComponentOfType:"_componentSize"},e.hasCodeEditorParent={createComponentOfType:"boolean"},e.renderedName={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){if(e.length>0)return{success:!1};let n={componentType:"renderDoenetML"};return t.codeSource&&(n.attributes={codeSource:{primitive:t.codeSource}}),t.renderedName&&(n.props={name:t.renderedName}),{success:!0,newChildren:[n]}}}),e}static returnChildGroups(){return[{group:"children",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.hasCodeEditorParent={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({codeEditorParent:{dependencyType:"parentIdentity",parentComponentType:"codeEditor"}}),definition:function({dependencyValues:e}){return e.codeEditorParent?{setValue:{hasCodeEditorParent:!0}}:{setValue:{hasCodeEditorParent:!1}}}},e.width={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},hasEssential:!0,forRenderer:!0,defaultValue:{size:600,isAbsolute:!0},returnDependencies:()=>({widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},parentWidth:{dependencyType:"parentStateVariable",variableName:"width",parentComponentType:"codeEditor"}}),definition:function({dependencyValues:e}){return e.widthAttr?{setValue:{width:e.widthAttr.stateValues.componentSize}}:e.parentWidth?{setValue:{width:e.parentWidth}}:{useEssentialOrDefaultValue:{width:!0}}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},hasEssential:!0,forRenderer:!0,defaultValue:{size:400,isAbsolute:!0},returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]},parentViewerHeight:{dependencyType:"parentStateVariable",variableName:"viewerHeight",parentComponentType:"codeEditor"}}),definition:function({dependencyValues:e}){return e.heightAttr?{setValue:{height:e.heightAttr.stateValues.componentSize}}:e.parentViewerHeight?{setValue:{height:e.parentViewerHeight}}:{useEssentialOrDefaultValue:{height:!0}}}},e.codeSourceComponentName={stateVariablesDeterminingDependencies:["rawCodeSource"],returnDependencies:({stateValues:e})=>e.rawCodeSource?{codeSourceComponentName:{dependencyType:"expandTargetName",target:e.rawCodeSource}}:{},definition:({dependencyValues:e})=>({setValue:{codeSourceComponentName:e.codeSourceComponentName}})},e.codeSource={returnDependencies:()=>({codeSourceComponentName:{dependencyType:"stateVariable",variableName:"codeSourceComponentName"},codeEditorParent:{dependencyType:"parentIdentity",parentComponentType:"codeEditor"}}),definition:function({dependencyValues:e}){return e.codeSourceComponentName?{setValue:{codeSource:e.codeSourceComponentName}}:e.codeEditorParent?{setValue:{codeSource:e.codeEditorParent.componentName}}:{setValue:{codeSource:null}}}},e}async updateComponents(){1===this.definingChildren.length&&"renderDoenetML"===this.definingChildren[0].componentType&&await this.coreFunctions.performAction({componentName:this.definingChildren[0].componentName,actionName:"updateComponents"})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={updateComponents:this.updateComponents.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class RenderDoenetML extends CompositeComponent{static componentType="renderDoenetML";static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="triggerUpdates";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.codeSource={createPrimitiveOfType:"string",createStateVariable:"rawCodeSource",defaultValue:null},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.codeSourceComponentName={stateVariablesDeterminingDependencies:["rawCodeSource"],returnDependencies:({stateValues:e})=>e.rawCodeSource?{codeSourceComponentName:{dependencyType:"expandTargetName",target:e.rawCodeSource}}:{},definition:({dependencyValues:e})=>({setValue:{codeSourceComponentName:e.codeSourceComponentName}})},e.codeSource={returnDependencies:()=>({codeSourceComponentName:{dependencyType:"stateVariable",variableName:"codeSourceComponentName"},parentCodeSource:{dependencyType:"parentStateVariable",parentComponentType:"codeViewer",variableName:"codeSource"}}),definition:function({dependencyValues:e}){return e.codeSourceComponentName?{setValue:{codeSource:e.codeSourceComponentName}}:e.parentCodeSource?{setValue:{codeSource:e.parentCodeSource}}:{setValue:{codeSource:null}}}},e.doenetML={stateVariablesDeterminingDependencies:["codeSource"],returnDependencies:({stateValues:e})=>({doenetML:{dependencyType:"stateVariable",componentName:e.codeSource,variableName:"text",variablesOptional:!0}}),definition({dependencyValues:e}){let t="";return e.doenetML&&(t=e.doenetML,"string"!=typeof t&&(t="")),{setValue:{doenetML:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({doenetML:{dependencyType:"stateVariable",variableName:"doenetML"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.triggerUpdates={defaultValue:!0,hasEssential:!0,returnDependencies:()=>({}),markStale:()=>({updateReplacements:!0}),definition:()=>({useEssentialOrDefaultValue:{triggerUpdates:{}}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"triggerUpdates",value:e.triggerUpdates}]})},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=(await e.stateValues.doenetML).trim();r.previousDoenetML=i;try{a=(await expandDoenetMLsToFullSerializedComponents({cids:[],doenetMLs:[i],componentInfoObjects:t,flags:n})).fullSerializedComponents[0]}catch(e){return console.warn("error in user entered doenetML"),console.warn(e.message),{replacements:[]}}let o=e.componentName.split("/").map((e=>({namespace:e,componentCounts:{},namesUsed:{}})));return createComponentNames({serializedComponents:a,componentInfoObjects:t,namespaceStack:o}),restrictTNamesToNamespace({components:a,namespace:`${e.componentName}/`}),{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:a,parentName:e.componentName,parentCreatesNewNamespace:!0,componentInfoObjects:t,originalNamesAreConsistent:!0}).serializedComponents}}static async calculateReplacementChanges({component:e,componentChanges:t,componentInfoObjects:n,flags:r,workspace:a}){let i=(await e.stateValues.doenetML).trim();if(a.previousDoenetML===i)return[];a.previousDoenetML=i;let o=(await this.createSerializedReplacements({component:e,componentInfoObjects:n,flags:r,workspace:a})).replacements;return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:o}]}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}async updateComponents({actionId:e}){let t=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"triggerUpdates",value:!0}];await this.coreFunctions.performUpdate({updateInstructions:t,actionId:e})}actions={updateComponents:this.updateComponents.bind(this)}}class HasSameFactoring extends BooleanComponent{static componentType="hasSameFactoring";static rendererType="boolean";static createAttributesObject(){let e=super.createAttributesObject();return e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x")},e.restrictDivision={createComponentOfType:"boolean",createStateVariable:"restrictDivision",defaultValue:!1},e.monomialFactorMustMatch={createComponentOfType:"boolean",createStateVariable:"monomialFactorMustMatch",defaultValue:!1},e.allowOnlySignDifferences={createComponentOfType:"boolean",createStateVariable:"allowOnlySignDifferences",defaultValue:!1},e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.parsedExpression,delete e.mathChildrenByCode,e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},variable:{dependencyType:"stateVariable",variableName:"variable"},restrictDivision:{dependencyType:"stateVariable",variableName:"restrictDivision"},monomialFactorMustMatch:{dependencyType:"stateVariable",variableName:"monomialFactorMustMatch"},allowOnlySignDifferences:{dependencyType:"stateVariable",variableName:"allowOnlySignDifferences"}}),definition:function({dependencyValues:e}){if(2!==e.mathChildren.length)return{setValue:{value:!1}};let t=e.mathChildren[0].stateValues.value,n=e.mathChildren[1].stateValues.value;if(1!==checkEquality({object1:t,object2:n,isUnordered:!1,partialMatches:!1,symbolicEquality:!1,allowedErrorInNumbers:e.allowedErrorInNumbers,includeErrorInNumberExponents:e.includeErrorInNumberExponents,allowedErrorIsAbsolute:e.allowedErrorIsAbsolute,nSignErrorsMatched:e.nSignErrorsMatched}).fraction_equal)return{setValue:{value:!1}};if(Array.isArray(t.tree)&&"-"===t.tree[0]&&(t=me$3.fromAst(t.tree[1])),Array.isArray(n.tree)&&"-"===n.tree[0]&&(n=me$3.fromAst(n.tree[1])),e.restrictDivision||e.monomialFactorMustMatch||e.allowOnlySignDifferences||(Array.isArray(t.tree)&&"/"===t.tree[0]&&0===me$3.fromAst(t.tree[2]).variables().length&&(t=me$3.fromAst(t.tree[1]),Array.isArray(t.tree)&&"-"===t.tree[0]&&(t=me$3.fromAst(t.tree[1]))),Array.isArray(n.tree)&&"/"===n.tree[0]&&0===me$3.fromAst(n.tree[2]).variables().length&&(n=me$3.fromAst(n.tree[1]),Array.isArray(n.tree)&&"-"===n.tree[0]&&(n=me$3.fromAst(n.tree[1])))),t=me$3.fromAst(expandPositiveIntegerPowers(t.tree)),n=me$3.fromAst(expandPositiveIntegerPowers(n.tree)),!Array.isArray(t.tree)||"*"!==t.tree[0])return Array.isArray(n.tree)&&"*"===n.tree[0]?{setValue:{value:!1}}:{setValue:{value:!0}};if(!Array.isArray(n.tree)||"*"!==n.tree[0])return{setValue:{value:!1}};if(e.monomialFactorMustMatch||e.allowOnlySignDifferences){let e=findMonomialFromFactors(t.tree.slice(1)),r=findMonomialFromFactors(n.tree.slice(1));if(!e.equals(r)){let t=me$3.fromAst(["-",r.tree]);if(!e.equals(t))return{setValue:{value:!1}}}}if(e.allowOnlySignDifferences){let r=normalizeFactorSigns(t),a=normalizeFactorSigns(n);return{setValue:{value:r.equalsViaSyntax(a,{allowed_error_in_numbers:e.allowedErrorInNumbers,include_error_in_number_exponents:e.includeErrorInNumberExponents,allowed_error_is_absolute:e.allowedErrorIsAbsolute})}}}let r=t.tree.slice(1).filter((e=>me$3.fromAst(e).variables().length>0)),a=n.tree.slice(1).filter((e=>me$3.fromAst(e).variables().length>0));if(r.length!==a.length)return{setValue:{value:!1}};let i=0,o=0,s=0,l=0,u=e.variable.subscripts_to_strings().tree;for(let e of r){let t=me$3.fromAst(e).subscripts_to_strings().derivative(u).derivative(u).simplify();if(0===t.tree)o++;else{if(0!==t.variables().length)return{setValue:{value:!1}};i++}}for(let e of a){let t=me$3.fromAst(e).subscripts_to_strings().derivative(u).derivative(u).simplify();if(0===t.tree)l++;else{if(0!==t.variables().length)return{setValue:{value:!1}};s++}}return{setValue:{value:o===l&&i===s}}}},e}}function expandPositiveIntegerPowers(e){if(!Array.isArray(e))return e;if("^"===e[0]){let t=e[1],n=e[2];Number.isInteger(n)&&n>0&&(e=["*",...Array(n).fill(t)])}if("*"===e[0]){let t=e;e=["*"];for(let n of t.slice(1))if(Array.isArray(n)&&"^"===n[0]){let t=n[1],r=n[2];Number.isInteger(r)&&r>0?e.push(...Array(r).fill(t)):e.push(n)}else e.push(n)}return e}function findMonomialFromFactors(e){let t,n=[],r=!1;for(let t of e)if("string"==typeof t||0===me$3.fromAst(t).variables().length){if(!r){if(n.length>0)return me$3.fromAst("_");r=!0}n.push(t)}else r=!1;return t=0===n.length?1:1===n.length?n[0]:["*",...n],me$3.fromAst(t)}function normalizeFactorSigns(e){let t=e.simplify().tree;if("-"===t[0]&&(t=t[1]),"*"!==t[0])return me$3.fromAst(t).simplify();let n=["*"];for(let e of t.slice(1))if("number"==typeof e)e<0?n.push(-e):n.push(e);else if(Array.isArray(e))if("-"===e[0])n.push(e[1]);else if("+"===e[0]){let t=!1,r=e[1];if("number"==typeof r)r<0&&(t=!0);else if(Array.isArray(r))if("-"===r[0])t=!0;else if("*"===r[0]){let e=r[1];"number"==typeof e?e<0&&(t=!0):Array.isArray(e)&&"-"===e[0]&&(t=!0)}t?n.push(me$3.fromAst(["-",e]).simplify().tree):n.push(e)}else n.push(e);else n.push(e);return me$3.fromAst(n).simplify()}class DataFrame extends BaseComponent{static componentType="dataFrame";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.source={createComponentOfType:"text",createStateVariable:"source",required:!0,public:!0,forRenderer:!0},e.hasHeader={createComponentOfType:"boolean",createStateVariable:"hasHeader",defaultValue:!0,public:!0},e.columnTypes={createComponentOfType:"textList",createStateVariable:"columnTypesPrelim",defaultValue:[]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.cid={forRenderer:!0,returnDependencies:()=>({source:{dependencyType:"stateVariable",variableName:"source"}}),definition:function({dependencyValues:e}){if(!e.source||"doenet:"!==e.source.substring(0,7).toLowerCase())return{setValue:{cid:null}};let t=null,n=e.source.match(/[:&]cid=([^&]+)/i);return n&&(t=n[1]),{setValue:{cid:t}}}},e.dataFrame={stateVariablesDeterminingDependencies:["cid","source"],additionalStateVariablesDefined:[{variableName:"numRows",public:!0,shadowingInstructions:{createComponentOfType:"integer"}},{variableName:"numColumns",public:!0,shadowingInstructions:{createComponentOfType:"integer"}},{variableName:"columnTypes",public:!0,shadowingInstructions:{createComponentOfType:"textList"}},{variableName:"columnNames",public:!0,shadowingInstructions:{createComponentOfType:"textList"}}],returnDependencies:({stateValues:e})=>({fileContents:{dependencyType:"file",cid:e.cid,uri:e.source,fileType:"csv"},hasHeader:{dependencyType:"stateVariable",variableName:"hasHeader"},columnTypesPrelim:{dependencyType:"stateVariable",variableName:"columnTypesPrelim"}}),definition:function({dependencyValues:e,componentName:t}){let n=[],r=[],a=e.fileContents.trim().split("\n").map((e=>e.trim().split(",").map((e=>e.trim())))),i=a[0]?.length,o=!1;for(let e of a.slice(1))if(e.length!==i){o=!0;break}if(o)return console.warn(`Data has invalid shape. Rows has inconsistent lengths. Found in componentName :${t}`),{setValue:{dataFrame:null,numRows:u,numColumns:i,columnTypes:n,columnNames:r}};let s={},l=[];if(e.hasHeader?(s.columnNames=a[0].map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1)),e))),l=a.slice(1)):(s.columnNames=[...Array(i).keys()].map((e=>`col${e+1}`)),l=a),[...new Set(s.columnNames)].length({numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{dataFrame:{dependencyType:"stateVariable",variableName:"dataFrame"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},columnTypes:{dependencyType:"stateVariable",variableName:"columnTypes"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t){let t=0,a=0;if("number"===e.columnTypes[r]){for(let n=0;n({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({statisticsToDisplayPrelim:{dependencyType:"stateVariable",variableName:"statisticsToDisplayPrelim"}}),definition:function({dependencyValues:e}){let t=["mean","stdev","variance","stderr","count","minimum","quartile1","median","quartile3","maximum","range","sum"],n=[],r=e.statisticsToDisplayPrelim.map((e=>e.toLowerCase()));if(r.includes("default"))n=["mean","stdev","count","minimum","quartile1","median","quartile3","maximum"];else if(r.includes("all"))n=[...t];else for(let e of t)r.includes(e)&&n.push(e);return{setValue:{statisticsToDisplay:n}}}},e.sourceName={stateVariablesDeterminingDependencies:["source"],returnDependencies:({stateValues:e})=>({sourceName:{dependencyType:"expandTargetName",target:e.source}}),definition({dependencyValues:e}){let t=null;return e.sourceName&&(t=e.sourceName),{setValue:{sourceName:t}}}},e.dataColumn={stateVariablesDeterminingDependencies:["sourceName"],additionalStateVariablesDefined:[{variableName:"columnName",public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0}],returnDependencies:({stateValues:e})=>({dataFrame:{dependencyType:"stateVariable",componentName:e.sourceName,variableName:"dataFrame",variableOptional:!0},desiredColumn:{dependencyType:"stateVariable",variableName:"desiredColumn"}}),definition({dependencyValues:e}){let t=null,n=null;if(e.dataFrame){let r=e.dataFrame,a=r.columnNames.indexOf(e.desiredColumn);if(-1!==a){n=e.desiredColumn,t=[];for(let e of r.data)null!==e[a]&&t.push(e[a])}}return{setValue:{dataColumn:t,columnName:n}}}},e.count={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=e.dataColumn.length),{setValue:{count:t}}}},e.sum={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=e.dataColumn.reduce(((e,t)=>e+t))),{setValue:{sum:t}}}},e.mean={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return null!==e.dataColumn&&(t=me$3.math.mean(e.dataColumn)),{setValue:{mean:t}}}},e.stdev={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.std(e.dataColumn)),{setValue:{stdev:t}}}},e.variance={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.variance(e.dataColumn)),{setValue:{variance:t}}}},e.stderr={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({stdev:{dependencyType:"stateVariable",variableName:"stdev"},count:{dependencyType:"stateVariable",variableName:"count"}}),definition({dependencyValues:e}){let t=null;return null!==e.stdev&&(t=e.stdev/Math.sqrt(e.count)),{setValue:{stderr:t}}}},e.minimum={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=Math.min(...e.dataColumn)),{setValue:{minimum:t}}}},e.maximum={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=Math.max(...e.dataColumn)),{setValue:{maximum:t}}}},e.median={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.median(e.dataColumn)),{setValue:{median:t}}}},e.quartile1={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.quantileSeq(e.dataColumn,.25)),{setValue:{quartile1:t}}}},e.quartile3={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.quantileSeq(e.dataColumn,.75)),{setValue:{quartile3:t}}}},e.range={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({minimum:{dependencyType:"stateVariable",variableName:"minimum"},maximum:{dependencyType:"stateVariable",variableName:"maximum"}}),definition({dependencyValues:e}){let t=null;return null!==e.minimum&&(t=e.maximum-e.minimum),{setValue:{range:t}}}},e.summaryStatistics={forRenderer:!0,stateVariablesDeterminingDependencies:["statisticsToDisplay"],returnDependencies({stateValues:e}){let t={displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}};return e.statisticsToDisplay.includes("mean")&&(t.mean={dependencyType:"stateVariable",variableName:"mean"}),e.statisticsToDisplay.includes("stdev")&&(t.stdev={dependencyType:"stateVariable",variableName:"stdev"}),e.statisticsToDisplay.includes("variance")&&(t.variance={dependencyType:"stateVariable",variableName:"variance"}),e.statisticsToDisplay.includes("stderr")&&(t.stderr={dependencyType:"stateVariable",variableName:"stderr"}),e.statisticsToDisplay.includes("count")&&(t.count={dependencyType:"stateVariable",variableName:"count"}),e.statisticsToDisplay.includes("minimum")&&(t.minimum={dependencyType:"stateVariable",variableName:"minimum"}),e.statisticsToDisplay.includes("quartile1")&&(t.quartile1={dependencyType:"stateVariable",variableName:"quartile1"}),e.statisticsToDisplay.includes("median")&&(t.median={dependencyType:"stateVariable",variableName:"median"}),e.statisticsToDisplay.includes("quartile3")&&(t.quartile3={dependencyType:"stateVariable",variableName:"quartile3"}),e.statisticsToDisplay.includes("maximum")&&(t.maximum={dependencyType:"stateVariable",variableName:"maximum"}),e.statisticsToDisplay.includes("range")&&(t.range={dependencyType:"stateVariable",variableName:"range"}),e.statisticsToDisplay.includes("sum")&&(t.sum={dependencyType:"stateVariable",variableName:"sum"}),t},definition({dependencyValues:e,usedDefault:t}){let n={};return void 0!==e.mean&&(n.mean=roundForDisplay({value:e.mean,dependencyValues:e,usedDefault:t})),void 0!==e.stdev&&(n.stdev=roundForDisplay({value:e.stdev,dependencyValues:e,usedDefault:t})),void 0!==e.variance&&(n.variance=roundForDisplay({value:e.variance,dependencyValues:e,usedDefault:t})),void 0!==e.stderr&&(n.stderr=roundForDisplay({value:e.stderr,dependencyValues:e,usedDefault:t})),void 0!==e.count&&(n.count=roundForDisplay({value:e.count,dependencyValues:e,usedDefault:t})),void 0!==e.minimum&&(n.minimum=roundForDisplay({value:e.minimum,dependencyValues:e,usedDefault:t})),void 0!==e.quartile1&&(n.quartile1=roundForDisplay({value:e.quartile1,dependencyValues:e,usedDefault:t})),void 0!==e.median&&(n.median=roundForDisplay({value:e.median,dependencyValues:e,usedDefault:t})),void 0!==e.quartile3&&(n.quartile3=roundForDisplay({value:e.quartile3,dependencyValues:e,usedDefault:t})),void 0!==e.maximum&&(n.maximum=roundForDisplay({value:e.maximum,dependencyValues:e,usedDefault:t})),void 0!==e.range&&(n.range=roundForDisplay({value:e.range,dependencyValues:e,usedDefault:t})),void 0!==e.sum&&(n.sum=roundForDisplay({value:e.sum,dependencyValues:e,usedDefault:t})),{setValue:{summaryStatistics:n}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class Chart extends BlockComponent{static componentType="chart";static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createComponentOfType:"text",createStateVariable:"type",defaultValue:"histogram",toLowerCase:!0,validValues:["histogram","dotplot","frequencytable","box","bar"],forRenderer:!0},e.column={createComponentOfType:"text",createStateVariable:"desiredColumn",defaultValue:null},e.xmin={createComponentOfType:"number",createStateVariable:"xminPrelim",defaultValue:-10},e.xmax={createComponentOfType:"number",createStateVariable:"xmaxPrelim",defaultValue:10},e.ymin={createComponentOfType:"number",createStateVariable:"yminPrelim",defaultValue:-10},e.ymax={createComponentOfType:"number",createStateVariable:"ymaxPrelim",defaultValue:10},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:300,isAbsolute:!0},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:300,isAbsolute:!0},public:!0,forRenderer:!0},e.identicalAxisScales={createComponentOfType:"boolean",createStateVariable:"identicalAxisScales",defaultValue:!1,public:!0,forRenderer:!0},e.displayXAxis={createComponentOfType:"boolean",createStateVariable:"displayXAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxis={createComponentOfType:"boolean",createStateVariable:"displayYAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayXAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayXAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayYAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.xlabel={createComponentOfType:"text",createStateVariable:"xlabel",defaultValue:"",public:!0,forRenderer:!0},e.xlabelPosition={createComponentOfType:"text",createStateVariable:"xlabelPosition",defaultValue:"right",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["right","left"]},e.ylabel={createComponentOfType:"text",createStateVariable:"ylabel",defaultValue:"",public:!0,forRenderer:!0},e.ylabelPosition={createComponentOfType:"text",createStateVariable:"ylabelPosition",defaultValue:"top",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["top","bottom"]},e.ylabelAlignment={createComponentOfType:"text",createStateVariable:"ylabelAlignment",defaultValue:"left",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["left","right"]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.dataFrame={forRenderer:!0,returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent",variableNames:["dataFrame"],variablesOptional:!0}}),definition({dependencyValues:e}){console.log("definition of dataFrame",e);let t=null;return e.targetComponent?.stateValues.dataFrame&&(t=e.targetComponent.stateValues.dataFrame),{setValue:{dataFrame:t}}}},e.columnName={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"colInd",forRenderer:!0}],returnDependencies:()=>({desiredColumn:{dependencyType:"stateVariable",variableName:"desiredColumn"},dataFrame:{dependencyType:"stateVariable",variableName:"dataFrame"}}),definition({dependencyValues:e}){let t=null,n=null;return e.dataFrame&&(n=e.dataFrame.columnNames.indexOf(e.desiredColumn),-1!==n?t=e.desiredColumn:n=null),{setValue:{columnName:t,colInd:n}}}},e.xmin={stateVariablesDeterminingDependencies:["identicalAxisScales"],defaultValue:-10,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},xminPrelim:{dependencyType:"stateVariable",variableName:"xminPrelim"}};return e.identicalAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.width={dependencyType:"stateVariable",variableName:"width"},t.height={dependencyType:"stateVariable",variableName:"height"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales)return{setValue:{xmin:e.xminPrelim}};if(!t.xminPrelim)return{setValue:{xmin:e.xminPrelim}};let n=!t.xmaxPrelim,r=!t.yminPrelim,a=!t.ymaxPrelim;if(r&&a){let t=e.width.size/e.height.size,r=(e.ymaxPrelim-e.yminPrelim)*t;return n?{setValue:{xmin:e.xmaxPrelim-r}}:{setValue:{xmin:-r/2}}}return n?{setValue:{xmin:e.xmaxPrelim-20}}:{setValue:{xmin:-10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xminPrelim",desiredValue:e.xmin}]}},e.xmax={stateVariablesDeterminingDependencies:["identicalAxisScales"],defaultValue:-10,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},xmaxPrelim:{dependencyType:"stateVariable",variableName:"xmaxPrelim"}};return e.identicalAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.width={dependencyType:"stateVariable",variableName:"width"},t.height={dependencyType:"stateVariable",variableName:"height"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales)return{setValue:{xmax:e.xmaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,o=a&&i,s=n&&r,l=e.xminPrelim;if(o){let t=e.width.size/e.height.size,a=(e.ymaxPrelim-e.yminPrelim)*t;if(s){let t=e.xmaxPrelim-l;return{setValue:{xmax:l+Math.max(t,a)}}}return n?{setValue:{xmax:l+a}}:r?{setValue:{xmax:e.xmaxPrelim}}:{setValue:{xmax:a/2}}}return r?{setValue:{xmax:e.xmaxPrelim}}:n?{setValue:{xmax:l+20}}:{setValue:{xmax:10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xmaxPrelim",desiredValue:e.xmax}]}},e.ymin={stateVariablesDeterminingDependencies:["identicalAxisScales"],defaultValue:-10,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},yminPrelim:{dependencyType:"stateVariable",variableName:"yminPrelim"}};return e.identicalAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.width={dependencyType:"stateVariable",variableName:"width"},t.height={dependencyType:"stateVariable",variableName:"height"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales)return{setValue:{ymin:e.yminPrelim}};if(!t.yminPrelim)return{setValue:{ymin:e.yminPrelim}};let n=!t.ymaxPrelim,r=!t.xminPrelim,a=!t.xmaxPrelim,i=r&&a,o=e.width.size/e.height.size;if(i){let t=(e.xmaxPrelim-e.xminPrelim)/o;return n?{setValue:{ymin:e.ymaxPrelim-t}}:{setValue:{ymin:-t/2}}}return n?{setValue:{ymin:e.ymaxPrelim-20/o}}:{setValue:{ymin:-10/o}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"yminPrelim",desiredValue:e.ymin}]}},e.ymax={stateVariablesDeterminingDependencies:["identicalAxisScales"],defaultValue:-10,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},ymaxPrelim:{dependencyType:"stateVariable",variableName:"ymaxPrelim"}};return e.identicalAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.width={dependencyType:"stateVariable",variableName:"width"},t.height={dependencyType:"stateVariable",variableName:"height"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales)return{setValue:{ymax:e.ymaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,o=a&&i,s=n&&r,l=e.yminPrelim,u=e.width.size/e.height.size;if(s){let t=(e.xmaxPrelim-e.xminPrelim)/u;if(o){let n=e.ymaxPrelim-l;return{setValue:{ymax:l+Math.max(n,t)}}}return a?{setValue:{ymax:l+t}}:i?{setValue:{ymax:e.ymaxPrelim}}:{setValue:{ymax:t/2}}}return i?{setValue:{ymax:e.ymaxPrelim}}:a?{setValue:{ymax:l+20/u}}:{setValue:{ymax:10/u}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"ymaxPrelim",desiredValue:e.ymax}]}},e.xscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({xmin:{dependencyType:"stateVariable",variableName:"xmin"},xmax:{dependencyType:"stateVariable",variableName:"xmax"}}),definition:({dependencyValues:e})=>({setValue:{xscale:e.xmax-e.xmin}})},e.yscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({ymin:{dependencyType:"stateVariable",variableName:"ymin"},ymax:{dependencyType:"stateVariable",variableName:"ymax"}}),definition:({dependencyValues:e})=>({setValue:{yscale:e.ymax-e.ymin}})},e}async changeAxisLimits({xmin:e,xmax:t,ymin:n,ymax:r,actionId:a}){let i=[];return void 0!==e&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmin",value:e}),void 0!==t&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmax",value:t}),void 0!==n&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymin",value:n}),void 0!==r&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymax",value:r}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{xmin:e,xmax:t,ymin:n,ymax:r}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}actions={changeAxisLimits:this.changeAxisLimits.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)}}class Legend extends GraphicalComponent{static componentType="legend";static createAttributesObject(){let e=super.createAttributesObject();return e.position={createComponentOfType:"text",createStateVariable:"position",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e.displayClosedSwatches={createComponentOfType:"boolean",createStateVariable:"displayClosedSwatches",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.graphicalElementNames={returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["graphicalDescendants"]}}),definition:({dependencyValues:e})=>e.graphAncestor?{setValue:{graphicalElementNames:e.graphAncestor.stateValues.graphicalDescendants.map((e=>e.componentName))}}:{setValue:{graphicalElementNames:null}}},e.legendElements={forRenderer:!0,stateVariablesDeterminingDependencies:["graphicalElementNames"],returnDependencies:({stateValues:e})=>{let t={labelChildren:{dependencyType:"child",childGroups:["labels"],variableNames:["value","hasLatex","forObjectComponentName"]},displayClosedSwatches:{dependencyType:"stateVariable",variableName:"displayClosedSwatches"}};if(e.graphicalElementNames){t.numGraphicalElements={dependencyType:"value",value:e.graphicalElementNames.length};for(let[n,r]of e.graphicalElementNames.entries())t[`graphicalElement${n}`]={dependencyType:"multipleStateVariables",componentName:r,variableNames:["selectedStyle","styleNumber","filled"],variablesOptional:!0},t[`graphicalElement${n}AdapterSource`]={dependencyType:"adapterSource",componentName:r},t[`graphicalElement${n}ShadowSource`]={dependencyType:"shadowSource",componentName:r}}return t},definition({dependencyValues:e,componentInfoObjects:t}){let n=[];if(e.numGraphicalElements>0){let r=[],a=[],i=[],o=[];for(let t=0;te.componentName)),l=[],u={};for(let n of e.labelChildren){let c={value:n.stateValues.value,hasLatex:n.stateValues.hasLatex};if(n.stateValues.forObjectComponentName){u[n.stateValues.forObjectComponentName]=c;let l=s.indexOf(n.stateValues.forObjectComponentName);if(-1!==l){let n=o[l];t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"point"})?r.push(n.stateValues.styleNumber):e.displayClosedSwatches&&t.allComponentClasses[n.componentType].representsClosedPath?a.push(n.stateValues.styleNumber):"legend"!==n.componentType&&i.push(n.stateValues.styleNumber)}}l.push({labelInfo:c,forObject:n.stateValues.forObjectComponentName})}for(let c of l){let l;if(c.forObject){let e=s.indexOf(c.forObject);-1!==e&&(l=o[e],o.splice(e,1),s.splice(e,1))}else for(let n=0;n({graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>e.graphAncestor?{setValue:{graphLimits:e.graphAncestor.stateValues}}:{setValue:{graphLimits:null}}},e}}class MatchesPattern extends BooleanComponent{static componentType="matchesPattern";static rendererType="boolean";static createAttributesObject(){let e=super.createAttributesObject();return e.pattern={createComponentOfType:"math"},e.allowImplicitIdentities={createComponentOfType:"boolean",createStateVariable:"allowImplicitIdentities",defaultValue:!1,public:!0},e.allowPermutations={createComponentOfType:"boolean",createStateVariable:"allowPermutations",defaultValue:!0,public:!0},e.requireNumericMatches={createComponentOfType:"boolean",createStateVariable:"requireNumericMatches",defaultValue:!1,public:!0},e.requireVariableMatches={createComponentOfType:"boolean",createStateVariable:"requireVariableMatches",defaultValue:!1,public:!0},e.excludeMatches={createComponentOfType:"mathList",createStateVariable:"excludeMatches",defaultValue:[],public:!0},e.matchExpressionWithBlanks={createComponentOfType:"boolean",createStateVariable:"matchExpressionWithBlanks",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){return 0===e.length||1===e.length&&t.componentIsSpecifiedType(e[0],"math")?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.parsedExpression,delete e.mathChildrenByCode,e.pattern={additionalStateVariablesDefined:["patternVariables"],returnDependencies:()=>({patternAttr:{dependencyType:"attributeComponent",attributeName:"pattern",variableNames:["value"]}}),definition({dependencyValues:e}){let t=[];if(!e.patternAttr)return{setValue:{pattern:"_",patternVariables:t}};let n=e.patternAttr.stateValues.value.variables(),r=703;let a=function e(a){if("_"===a){let e=numberToLetters(r);for(r++;n.includes(e);)e=numberToLetters(r),r++;return t.push(e),e}return Array.isArray(a)?[a[0],...a.slice(1).map(e)]:a}(e.patternAttr.stateValues.value.tree);return{setValue:{pattern:a,patternVariables:t}}}},e.value={additionalStateVariablesDefined:[{variableName:"allPatternMatches"}],public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({pattern:{dependencyType:"stateVariable",variableName:"pattern"},patternVariables:{dependencyType:"stateVariable",variableName:"patternVariables"},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},allowImplicitIdentities:{dependencyType:"stateVariable",variableName:"allowImplicitIdentities"},allowPermutations:{dependencyType:"stateVariable",variableName:"allowPermutations"},requireNumericMatches:{dependencyType:"stateVariable",variableName:"requireNumericMatches"},requireVariableMatches:{dependencyType:"stateVariable",variableName:"requireVariableMatches"},excludeMatches:{dependencyType:"stateVariable",variableName:"excludeMatches"},matchExpressionWithBlanks:{dependencyType:"stateVariable",variableName:"matchExpressionWithBlanks"}}),definition:function({dependencyValues:e}){if(0===e.mathChildren.length)return{setValue:{value:!1,allPatternMatches:[]}};let t=e.mathChildren[0].stateValues.value;if(t.variables().includes("_")&&!e.matchExpressionWithBlanks)return{setValue:{value:!1,allPatternMatches:[]}};let n={};if(e.requireNumericMatches){let t=e=>null!==me$3.fromAst(e).evaluate_to_constant();e.patternVariables.forEach((e=>n[e]=t))}else if(e.requireVariableMatches){let t=e=>"string"==typeof e;e.patternVariables.forEach((e=>n[e]=t))}else e.patternVariables.forEach((e=>n[e]=!0));let r={variables:n,allow_permutations:e.allowPermutations};e.allowImplicitIdentities&&(r.allow_implicit_identities=e.patternVariables);let a=t.match(e.pattern,r),i=!1,o=[];return a&&(Object.values(a).map((e=>me$3.fromAst(e))).some((t=>e.excludeMatches.some((e=>t.variables().some((t=>e.equalsViaSyntax(me$3.fromAst(t))))))))||(i=!0,o=e.patternVariables.map((e=>me$3.fromAst(a[e]))))),{setValue:{value:i,allPatternMatches:o}}}},e.nMatches={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allPatternMatches:{dependencyType:"stateVariable",variableName:"allPatternMatches"}}),definition:({dependencyValues:e})=>({setValue:{nMatches:e.allPatternMatches.length},checkForActualChange:{nMatches:!0}})},e.patternMatches={public:!0,shadowingInstructions:{createComponentOfType:"math"},isArray:!0,nDimensions:1,entryPrefixes:["patternMatch"],returnArraySizeDependencies:()=>({nMatches:{dependencyType:"stateVariable",variableName:"nMatches"}}),returnArraySize:({dependencyValues:e})=>[e.nMatches],returnArrayDependenciesByKey:()=>({globalDependencies:{allPatternMatches:{dependencyType:"stateVariable",variableName:"allPatternMatches"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({setValue:{unordered:!1}})},e.matrixSizePre={returnDependencies:()=>({rowChildren:{dependencyType:"child",childGroups:["rows"],variableNames:["nComponents"]},colChildren:{dependencyType:"child",childGroups:["columns"],variableNames:["nComponents"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["matrixSize"]},nRowsAttr:{dependencyType:"attributeComponent",attributeName:"nRows",variableNames:["value"]},nColumnsAttr:{dependencyType:"attributeComponent",attributeName:"nColumns",variableNames:["value"]}}),definition({dependencyValues:e}){let t=null,n=null;return e.nRowsAttr&&(t=e.nRowsAttr.stateValues.value,Number.isFinite(t)&&t>0||(t=null)),e.nColumnsAttr&&(n=e.nColumnsAttr.stateValues.value,Number.isFinite(n)&&n>0||(n=null)),e.rowChildren.length>0?(null===t&&(t=e.rowChildren.length),null===n&&(n=Math.max(1,...e.rowChildren.map((e=>e.stateValues.nComponents))))):e.colChildren.length>0?(null===n&&(n=e.colChildren.length),null===t&&(t=Math.max(1,...e.colChildren.map((e=>e.stateValues.nComponents))))):1===e.mathChildren.length?(null===t&&(t=e.mathChildren[0].stateValues.matrixSize[0]),null===n&&(n=e.mathChildren[0].stateValues.matrixSize[1])):null===t?null===n?(t=0,n=0):t=1:null===n&&(n=1),{setValue:{matrixSizePre:[t,n]}}}},e.matrixPre={isArray:!0,nDimensions:2,hasEssential:!0,returnArraySizeDependencies:()=>({matrixSizePre:{dependencyType:"stateVariable",variableName:"matrixSizePre"}}),returnArraySize:({dependencyValues:e})=>e.matrixSizePre,returnArrayDependenciesByKey:({arrayKeys:e})=>{let t={};for(let n of e){let[e,r]=n.split(",");t[n]={rowChild:{dependencyType:"child",childGroups:["rows"],childIndices:[e],variableNames:["math"+(Number(r)+1)]},colChild:{dependencyType:"child",childGroups:["columns"],childIndices:[r],variableNames:["math"+(Number(e)+1)]},mathChild:{dependencyType:"child",childGroups:["maths"],childIndices:[0],variableNames:["matrixEntry"+(Number(e)+1)+"_"+(Number(r)+1)]}}}return{globalDependencies:{defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"},rowChildIdentities:{dependencyType:"child",childGroups:["rows"]},colChildIdentities:{dependencyType:"child",childGroups:["columns"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a={},i={},o=e.rowChildIdentities.length>0,s=e.colChildIdentities.length>0;for(let r of n){let n,[l,u]=r.split(",");n=o?t[r].rowChild[0]?.stateValues["math"+(Number(u)+1)]:s?t[r].colChild[0]?.stateValues["math"+(Number(l)+1)]:t[r].mathChild[0]?.stateValues["matrixEntry"+(Number(l)+1)+"_"+(Number(u)+1)],void 0===n?i[r]={defaultValue:e.defaultEntry}:a[r]=n}return{setValue:{matrixPre:a},useEssentialOrDefaultValue:{matrixPre:i}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r}){let a=[],i={},o=t.rowChildIdentities.length>0,s=t.colChildIdentities.length>0;for(let t in e.matrixPre){let[l,u]=t.split(",");if(o){let o=n[t].rowChild[0]?.stateValues["math"+(Number(u)+1)];void 0===o?i[t]=e.matrixPre[t]:a.push({setDependency:r[t].rowChild,desiredValue:e.matrixPre[t],childIndex:0,variableIndex:0})}else if(s){let o=n[t].colChild[0]?.stateValues["math"+(Number(l)+1)];void 0===o?i[t]=e.matrixPre[t]:a.push({setDependency:r[t].colChild,desiredValue:e.matrixPre[t],childIndex:0,variableIndex:0})}else{let o=n[t].mathChild[0]?.stateValues["matrixEntry"+(Number(l)+1)+"_"+(Number(u)+1)];void 0===o?i[t]=e.matrixPre[t]:a.push({setDependency:r[t].mathChild,desiredValue:e.matrixPre[t],childIndex:0,variableIndex:0})}}return Object.keys(i).length>0&&a.push({setEssentialValue:"matrixPre",value:i}),{success:!0,instructions:a}}},e.unnormalizedValue={returnDependencies:()=>({matrixPre:{dependencyType:"stateVariable",variableName:"matrixPre"},matrixSizePre:{dependencyType:"stateVariable",variableName:"matrixSizePre"}}),definition({dependencyValues:e}){let t=["tuple"];for(let n=0;ne.tree))]);return{setValue:{unnormalizedValue:me$3.fromAst(["matrix",["tuple",...e.matrixSizePre],t])}}},inverseDefinition({dependencyValues:e,desiredStateVariableValues:t}){let n=t.unnormalizedValue.tree;if(!Array.isArray(n)||"matrix"!==n[0]||n[1]?.[1]!==e.matrixSizePre[0]||n[1]?.[2]!==e.matrixSizePre[1])return{success:!1};let r={};for(let t=0;t({modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"}}),definition:({dependencyValues:e})=>({setValue:{canBeModified:e.modifyIndirectly&&!e.fixed}})},e}}class EigenDecomposition extends BaseComponent{static componentType="eigenDecomposition";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:14,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.decomposition={returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition({dependencyValues:e}){if(0===e.mathChild.length)return{setValue:{decomposition:null}};let t=e.mathChild[0].stateValues.value.tree;if(!Array.isArray(t)||"matrix"!==t[0])return{setValue:{decomposition:null}};let n=t[1][1],r=t[1][2];if(!Number.isInteger(n)||r!==n)return{setValue:{decomposition:null}};let a,i=[];for(let e=0;e({decomposition:{dependencyType:"stateVariable",variableName:"decomposition"}}),returnArraySize({dependencyValues:e}){let t;return t=e.decomposition?e.decomposition.values.length:0,[t]},returnArrayDependenciesByKey:()=>({globalDependencies:{decomposition:{dependencyType:"stateVariable",variableName:"decomposition"}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n=[];for(let r=0;r"eigenvectorX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("eigenvectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("eigenvectors"===t)return 1===e.length?"eigenvector"+e[0]:`eigenvectorX${e[0]}_${e[1]}`;if("eigenvector"===t.slice(0,11)){let n=Number(t.slice(11));if(Number.isInteger(n)&&n>0)return`eigenvectorX${n}_${e[0]}`}return null},entryPrefixes:["eigenvectorX","eigenvector"],returnArraySizeDependencies:()=>({decomposition:{dependencyType:"stateVariable",variableName:"decomposition"}}),returnArraySize({dependencyValues:e}){let t;return t=e.decomposition?e.decomposition.values.length:0,[t,t]},returnArrayDependenciesByKey:()=>({globalDependencies:{decomposition:{dependencyType:"stateVariable",variableName:"decomposition"}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n={};for(let r=0;rme$3.math.divide(e,i)));for(let e=0;e({mathTextLikeChildren:{dependencyType:"child",childGroups:["mathTextLike"],variableNames:["text","latex"]}}),e.value.definition=function({dependencyValues:e}){if(0===e.mathTextLikeChildren.length)return{useEssentialOrDefaultValue:{value:!0}};let t="";for(let n of e.mathTextLikeChildren)"string"==typeof n?t+=n:void 0!==n.stateValues.latex?t+=n.stateValues.latex:t+=n.stateValues.text;return{setValue:{value:t}}},e.value.inverseDefinition=function({desiredStateVariableValues:e,dependencyValues:t}){let n=t.mathTextLikeChildren.length;return n>1?{success:!1}:1===n?{success:!0,instructions:[{setDependency:"textLikeChildren",desiredValue:e.value,childIndex:0,variableIndex:void 0===t.textLikeChildren[0].stateValues?.latex?0:1}]}:{success:!0,instructions:[{setEssentialValue:"value",value:null===e.value?"":String(e.value)}]}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.text}]})},e.latex={isAlias:!0,targetVariableName:"value"},e}}const unitConversions={"":1,px:1,pixel:1,pixels:1,"%":1,em:100,in:96,inch:96,inches:96,pt:1.333333333333,mm:3.7795296,millimeter:3.7795296,millimeters:3.7795296,cm:37.795296,centimeter:37.795296,centimeters:37.795296};class ComponentSize extends InlineComponent{static componentType="_componentSize";static rendererType="text";static primaryStateVariableForDefinition="componentSize";static stateVariableForAttributeValue="componentSize";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/..+/,replacementFunction:function({matchedChildren:e}){let t=e[e.length-1];if("string"==typeof t){let n=/([a-zA-z]+|%)$/,r=t.trim(),a=r.match(n);if(a){let t=a[1];if(t in unitConversions){let n=r.slice(0,a.index),i=e.slice(0,e.length-1);return n.length>0&&i.push(n),{success:!0,newChildren:[{componentType:"number",children:i},t]}}}}return{success:!0,newChildren:[{componentType:"number",children:e}]}}}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"numbers",componentTypes:["number"]},{group:"componentSizes",componentTypes:["_componentSize"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.componentSize={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},hasEssential:!0,returnDependencies:()=>({componentSizeChild:{dependencyType:"child",childGroups:["componentSizes"],variableNames:["componentSize"]},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},stringChild:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},parentDefaultAbsoluteSize:{dependencyType:"parentStateVariable",variableName:"defaultAbsoluteSize"}}),definition({dependencyValues:e}){let t=void 0!==e.parentDefaultAbsoluteSize&&e.parentDefaultAbsoluteSize;if(0===e.stringChild.length)return 0===e.numberChild.length?0===e.componentSizeChild.length?{useEssentialOrDefaultValue:{componentSize:{defaultValue:{size:100,isAbsolute:t}}}}:{setValue:{componentSize:e.componentSizeChild[0].stateValues.componentSize}}:{setValue:{componentSize:{size:e.numberChild[0].stateValues.value,isAbsolute:!0}}};{let t,n;if(e.numberChild.length>0)t=e.numberChild[0].stateValues.value,n=e.stringChild[0].trim();else{let r=e.stringChild[0].trim().match(/^(-?[\d.]+)\s*(.*)$/);if(null===r)return{setValue:{componentSize:null}};t=r[1],n=r[2].trim()}if(t=Number(t),!Number.isFinite(t))return{setValue:{componentSize:null}};let r=!("%"===n||"em"===n),a=unitConversions[n];return void 0===a&&(a=1),{setValue:{componentSize:{size:a*t,isAbsolute:r}}}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(0===t.stringChild.length)return 0===t.numberChild.length?0===t.componentSizeChild.length?{success:!0,instructions:[{setEssentialValue:"componentSize",value:e.componentSize}]}:{success:!0,instructions:[{setDependency:"componentSizeChild",desiredValue:e.componentSize,childIndex:0,variableIndex:0}]}:e.componentSize.isAbsolute?{success:!0,instructions:[{setDependency:"numberChild",desiredValue:e.componentSize.size,childIndex:0,variableIndex:0}]}:{success:!1};if(t.numberChild.length>0){let n=t.stringChild[0].trim(),r=!("%"===n||"em"===n);if(e.componentSize.isAbsolute!==r)return{success:!1};let a=unitConversions[n];return void 0===a&&(a=1),{success:!0,instructions:[{setDependency:"numberChild",desiredValue:e.componentSize.size/a,childIndex:0,variableIndex:0}]}}{let t=e.componentSize.size;return e.componentSize.isAbsolute?t+="px":t+="%",{success:!0,instructions:[{setDependency:"stringChild",desiredValue:t,childIndex:0,variableIndex:0}]}}}},e.number={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({componentSize:{dependencyType:"stateVariable",variableName:"componentSize"}}),definition({dependencyValues:e}){let t=null;return e.componentSize&&(t=e.componentSize.size),{setValue:{number:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(!t.componentSize)return{success:!1};return{success:!0,instructions:[{setDependency:"componentSize",desiredValue:{size:e.number,isAbsolute:t.componentSize.isAbsolute}}]}}},e.math=mathStateVariableFromNumberStateVariable({numberVariableName:"number",mathVariableName:"math",isPublic:!0}),e.isAbsolute={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({componentSize:{dependencyType:"stateVariable",variableName:"componentSize"}}),definition({dependencyValues:e}){let t=null;return e.componentSize&&(t=e.componentSize.isAbsolute),{setValue:{isAbsolute:t}}}},e.text={forRenderer:!0,returnDependencies:()=>({componentSize:{dependencyType:"stateVariable",variableName:"componentSize"}}),definition({dependencyValues:e}){let t="";return e.componentSize&&(t=e.componentSize.size,e.componentSize.isAbsolute?t+="px":t+="%"),{setValue:{text:t}}}},e}static adapters=["number","math"]}class ComponentSizeList extends BaseComponent{static componentType="_componentSizeList";static rendererType="asList";static renderChildren=!0;static stateVariableForAttributeValue="componentSizes";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=[],n=[],r=function(){n.length>0&&(t.push({componentType:"_componentSize",children:n}),n=[])};for(let t of e)if("string"==typeof t){let e=t.split(/\s+/);0===e[0].length&&(r(),e=e.slice(1));for(let[t,a]of e.entries())a.length>0?(n.push(a),t({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({componentSizeListChildren:{dependencyType:"child",childGroups:["componentSizeLists"],variableNames:["nComponents"]},componentSizeAndComponentSizeListChildren:{dependencyType:"child",childGroups:["componentSizes","componentSizeLists"],skipComponentNames:!0}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;for(let[i,o]of e.componentSizeAndComponentSizeListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:o.componentType,baseComponentType:"_componentSizeList"})){let t=e.componentSizeListChildren[a];a++;for(let e=0;e({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={componentSizeAndComponentSizeListChildren:{dependencyType:"child",childGroups:["componentSizes","componentSizeLists"],variableNames:["componentSize","componentSize"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentInfoObjects:r}){let a={};for(let i of n){let n=t[i].componentSizeAndComponentSizeListChildren[0];if(n)if(r.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"_componentSizeList"})){let t=e.childIndexByArrayKey[i][1]+1;a[i]=n.stateValues["componentSize"+t]}else a[i]=n.stateValues.componentSize}return{setValue:{componentSizes:a}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a,componentInfoObjects:i}){let o=[];for(let t in e.componentSizes){if(!n[t])continue;let a=n[t].componentSizeAndComponentSizeListChildren[0];a&&(i.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_componentSizeList"})?o.push({setDependency:r[t].componentSizeAndComponentSizeListChildren,desiredValue:e.componentSizes[t],childIndex:0,variableIndex:1}):o.push({setDependency:r[t].componentSizeAndComponentSizeListChildren,desiredValue:e.componentSizes[t],childIndex:0,variableIndex:0}))}return{success:!0,instructions:o}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"componentSizes"},e}}var ComponentSize$1=Object.freeze({__proto__:null,ComponentSize:ComponentSize,ComponentSizeList:ComponentSizeList});const componentTypeArray=[...Object.values(Aliases),...Object.values(MMeMen),...Object.values(MdMdnMrow),...Object.values(BooleanOperators),...Object.values(BooleanOperatorsOfMath),...Object.values(MathOperators),...Object.values(FunctionOperators),...Object.values(TextOperatorsOfMath),...Object.values(Extrema$1),...Object.values(ParagraphMarkup),...Object.values(SingleCharacterComponents),...Object.values(Sectioning),...Object.values(Lists),...Object.values(DynamicalSystems),...Object.values(Chemistry),...Object.values(FeedbackDefinitions$1),...Object.values(StyleDefinitions$1),...Object.values(SideBySide$1),...Object.values(ComponentWithSelectableType$1),...Object.values(Indexing),...Object.values(Divisions),...Object.values(Verbatim),...Object.values(Paginator$1),...Object.values(MatrixInput$1),Document,Text,TextList$1,TextList,P$2,BooleanComponent,BooleanList,MathComponent,MathList,TupleList,NumberList,NumberListFromString,Copy,Extract,Collect,Ref,Point,Coords,Line,LineSegment,Ray,Polyline,Polygon,Triangle,Rectangle,Circle,Parabola,Curve,BezierControls,ControlVectors,Vector,Angle,Answer,Award,When,MathInput,Textinput,BooleanInput,Choiceinput,Choice,NumberComponent,Integer,Graph$1,Variables,Variable,Function$2,Interval,Template,Option$1,Sequence,Slider,Spreadsheet,DiscreteSimulationResultList,DiscreteSimulationResultPolyline,Cell,Row,Column,CellBlock,Tabular,Table,Figure,Markers,Panel,Map$1,Sources,Constraints,ConstrainToGrid,ConstrainToGraph,AttractToGrid,ConstrainTo,AttractTo,ConstraintUnion,AttractToConstraint,Intersection,ConstrainToAngles,AttractToAngles,ConditionalContent,AsList,VariantControl,TextListFromString,SelectFromSequence,Select,Group,AnimateFromSequence,Evaluate,SelectRandomNumbers,SampleRandomNumbers,Substitute,PeriodicSet,Image,Video,Embed,Hint,Solution,IntComma,Pluralize,Feedback,CollaborateGroups,CollaborateGroupSetup,ConsiderAsResponses,Case,Lorem,UpdateValue,CallAction,triggerSet,FunctionIterates,Module,CustomAttribute,Setup,Footnote,Caption,Endpoint,Sort,Shuffle,SolveEquations,SolutionContainer,SubsetOfRealsInput,SubsetOfReals,Split,BestFitLine,RegionBetweenCurveXAxis,RegionHalfPlane,CodeEditor,CodeViewer,RenderDoenetML,HasSameFactoring,DataFrame,SummaryStatistics,Chart,Legend,Label,MatchesPattern,Matrix,EigenDecomposition,Latex,BaseComponent,InlineComponent,BlockComponent,GraphicalComponent,ConstraintComponent,Input,CompositeComponent,PointListComponent,IntervalListComponent,LineListComponent,VectorListComponent,AngleListComponent,BooleanOperator,BooleanBaseOperatorOfMath,MathOperator,MathOperatorOneInput,FunctionOperator,...Object.values(ComponentSize$1),SectioningComponent,InlineRenderInlineChildren,TextOrInline,SingleCharacter];function allComponentClasses(){const e={},t=new Set;for(let n of componentTypeArray){let r=n.componentType;if(void 0===r)throw Error("Cannot create component as componentType is undefined for class "+n);let a=r.toLowerCase();if(t.has(a))throw Error("component type "+r+" defined in two classes");e[r]=n,t.add(a)}return e}function componentTypesCreatingVariants(){const e={},t=new Set;for(let n of componentTypeArray)if(n.createsVariants){let r=n.componentType;if(void 0===r)throw Error("Cannot create component as componentType is undefined for class "+n);let a=r.toLowerCase();if(t.has(a))throw Error("component type "+r+" defined in two classes");e[r]=n,t.add(a)}return e}function createComponentInfoObjects(){let e=allComponentClasses(),t=componentTypesCreatingVariants(),n={};for(let t in e)n[t.toLowerCase()]=t;let r={};for(let t in e)Object.defineProperty(r,t,{get:function(){let n=e[t].returnStateVariableInfo();return delete r[t],r[t]=n}.bind(this),configurable:!0});let a={};for(let t in e)Object.defineProperty(a,t,{get:function(){let n=e[t].returnStateVariableInfo({onlyPublic:!0});return delete a[t],a[t]=n}.bind(this),configurable:!0});function i({inheritedComponentType:t,baseComponentType:n}){if(t===n)return!0;if("string"===t)return"_base"===n||"_inline"===n;if("string"===n)return!1;let r=e[n];return!!r&&r.isPrototypeOf(e[t])}let o=(e,t)=>i({inheritedComponentType:e,baseComponentType:t});return{allComponentClasses:e,componentTypesCreatingVariants:t,componentTypeLowerCaseMapping:n,isInheritedComponentType:i,isCompositeComponent:function({componentType:t,includeNonStandard:n=!0}){let r=e[t];return!!r&&(i({inheritedComponentType:t,baseComponentType:"_composite"})&&(n||!r.treatAsComponentForRecursiveReplacements))},stateVariableInfo:r,publicStateVariableInfo:a,componentIsSpecifiedType:(e,t)=>o(e.componentType,t)||o(e.attributes?.createComponentOfType?.primitive,t)}}function idbReady(){var e;return!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise((function(t){var n=function(){return indexedDB.databases().finally(t)};e=setInterval(n,100),n()})).finally((function(){return clearInterval(e)})):Promise.resolve()}function promisifyRequest(e){return new Promise(((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)}))}function createStore(e,t){const n=idbReady().then((()=>{const n=indexedDB.open(e);return n.onupgradeneeded=()=>n.result.createObjectStore(t),promisifyRequest(n)}));return(e,r)=>n.then((n=>r(n.transaction(t,e).objectStore(t))))}let defaultGetStoreFunc;function defaultGetStore(){return defaultGetStoreFunc||(defaultGetStoreFunc=createStore("keyval-store","keyval")),defaultGetStoreFunc}function set(e,t,n=defaultGetStore()){return n("readwrite",(n=>(n.put(t,e),promisifyRequest(n.transaction))))}const toastType=Object.freeze({ERROR:{timeout:-1,background:"rgba(193, 41, 46, 1)",gradientEnd:"rgba()"},ALERT:{timeout:-1,background:"rgba(255, 230, 0, 1)"},ACTION:{timeout:-1,background:"rgba()"},INFO:{timeout:3e3,background:"rgba(26, 90, 153,1)"},SUCCESS:{timeout:3e3,background:"rgba(41, 193, 67, 1)"},CONFIRMATION:{timeout:5e3,background:"rgba(26,90,153,1)"}});var axios$3={exports:{}},axios$2={exports:{}},bind$2=function(e,t){return function(){for(var n=new Array(arguments.length),r=0;r0;)o[i=r[a]]||(t[i]=e[i],o[i]=!0);e=Object.getPrototypeOf(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t}function endsWith(e,t,n){e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;var r=e.indexOf(t,n);return-1!==r&&r===n}function toArray(e){if(!e)return null;var t=e.length;if(isUndefined(t))return null;for(var n=new Array(t);t-- >0;)n[t]=e[t];return n}var isTypedArray=(TypedArray="undefined"!=typeof Uint8Array&&Object.getPrototypeOf(Uint8Array),function(e){return TypedArray&&e instanceof TypedArray}),TypedArray,utils$9={isArray:isArray$1,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer$1,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString,isNumber:isNumber,isObject:isObject,isPlainObject:isPlainObject,isUndefined:isUndefined,isDate:isDate,isFile:isFile,isBlob:isBlob,isFunction:isFunction,isStream:isStream,isURLSearchParams:isURLSearchParams,isStandardBrowserEnv:isStandardBrowserEnv,forEach:forEach,merge:merge,extend:extend,trim:trim,stripBOM:stripBOM,inherits:inherits,toFlatObject:toFlatObject,kindOf:kindOf,kindOfTest:kindOfTest,endsWith:endsWith,toArray:toArray,isTypedArray:isTypedArray,isFileList:isFileList},utils$8=utils$9;function encode(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var buildURL$1=function(e,t,n){if(!t)return e;var r;if(n)r=n(t);else if(utils$8.isURLSearchParams(t))r=t.toString();else{var a=[];utils$8.forEach(t,(function(e,t){null!=e&&(utils$8.isArray(e)?t+="[]":e=[e],utils$8.forEach(e,(function(e){utils$8.isDate(e)?e=e.toISOString():utils$8.isObject(e)&&(e=JSON.stringify(e)),a.push(encode(t)+"="+encode(e))})))})),r=a.join("&")}if(r){var i=e.indexOf("#");-1!==i&&(e=e.slice(0,i)),e+=(-1===e.indexOf("?")?"?":"&")+r}return e},utils$7=utils$9;function InterceptorManager$1(){this.handlers=[]}InterceptorManager$1.prototype.use=function(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1},InterceptorManager$1.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},InterceptorManager$1.prototype.forEach=function(e){utils$7.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var InterceptorManager_1=InterceptorManager$1,utils$6=utils$9,normalizeHeaderName$1=function(e,t){utils$6.forEach(e,(function(n,r){r!==t&&r.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[r])}))},AxiosError_1,hasRequiredAxiosError;function requireAxiosError(){if(hasRequiredAxiosError)return AxiosError_1;hasRequiredAxiosError=1;var e=utils$9;function t(e,t,n,r,a){Error.call(this),this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),a&&(this.response=a)}e.inherits(t,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var n=t.prototype,r={};return["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED"].forEach((function(e){r[e]={value:e}})),Object.defineProperties(t,r),Object.defineProperty(n,"isAxiosError",{value:!0}),t.from=function(r,a,i,o,s,l){var u=Object.create(n);return e.toFlatObject(r,u,(function(e){return e!==Error.prototype})),t.call(u,r.message,a,i,o,s),u.name=r.name,l&&Object.assign(u,l),u},AxiosError_1=t}var transitional={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,inited=!1;function init(){inited=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,n=e.length;t0)throw new Error("Invalid string. Length must be a multiple of 4");i="="===e[s-2]?2:"="===e[s-1]?1:0,o=new Arr(3*s/4-i),r=i>0?s-4:s;var l=0;for(t=0,n=0;t>16&255,o[l++]=a>>8&255,o[l++]=255&a;return 2===i?(a=revLookup[e.charCodeAt(t)]<<2|revLookup[e.charCodeAt(t+1)]>>4,o[l++]=255&a):1===i&&(a=revLookup[e.charCodeAt(t)]<<10|revLookup[e.charCodeAt(t+1)]<<4|revLookup[e.charCodeAt(t+2)]>>2,o[l++]=a>>8&255,o[l++]=255&a),o}function tripletToBase64(e){return lookup[e>>18&63]+lookup[e>>12&63]+lookup[e>>6&63]+lookup[63&e]}function encodeChunk(e,t,n){for(var r,a=[],i=t;il?l:s+o));return 1===r?(t=e[n-1],a+=lookup[t>>2],a+=lookup[t<<4&63],a+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],a+=lookup[t>>10],a+=lookup[t>>4&63],a+=lookup[t<<2&63],a+="="),i.push(a),i.join("")}function read(e,t,n,r,a){var i,o,s=8*a-r-1,l=(1<>1,c=-7,p=n?a-1:0,d=n?-1:1,m=e[t+p];for(p+=d,i=m&(1<<-c)-1,m>>=-c,c+=s;c>0;i=256*i+e[t+p],p+=d,c-=8);for(o=i&(1<<-c)-1,i>>=-c,c+=r;c>0;o=256*o+e[t+p],p+=d,c-=8);if(0===i)i=1-u;else{if(i===l)return o?NaN:1/0*(m?-1:1);o+=Math.pow(2,r),i-=u}return(m?-1:1)*o*Math.pow(2,i-r)}function write(e,t,n,r,a,i){var o,s,l,u=8*i-a-1,c=(1<>1,d=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,m=r?0:i-1,f=r?1:-1,h=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-o))<1&&(o--,l*=2),(t+=o+p>=1?d/l:d*Math.pow(2,1-p))*l>=2&&(o++,l/=2),o+p>=c?(s=0,o=c):o+p>=1?(s=(t*l-1)*Math.pow(2,a),o+=p):(s=t*Math.pow(2,p-1)*Math.pow(2,a),o=0));a>=8;e[n+m]=255&s,m+=f,s/=256,a-=8);for(o=o<0;e[n+m]=255&o,m+=f,o/=256,u-=8);e[n+m-f]|=128*h}var toString={}.toString,isArray=Array.isArray||function(e){return"[object Array]"==toString.call(e)},INSPECT_MAX_BYTES=50;function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(e,t){if(kMaxLength()=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|e}function internalIsBuffer(e){return!(null==e||!e._isBuffer)}function byteLength(e,t){if(internalIsBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return utf8ToBytes(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return base64ToBytes(e).length;default:if(r)return utf8ToBytes(e).length;t=(""+t).toLowerCase(),r=!0}}function slowToString(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return hexSlice(this,t,n);case"utf8":case"utf-8":return utf8Slice(this,t,n);case"ascii":return asciiSlice(this,t,n);case"latin1":case"binary":return latin1Slice(this,t,n);case"base64":return base64Slice(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function swap(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function bidirectionalIndexOf(e,t,n,r,a){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)return-1;n=0}if("string"==typeof t&&(t=Buffer.from(t,r)),internalIsBuffer(t))return 0===t.length?-1:arrayIndexOf(e,t,n,r,a);if("number"==typeof t)return t&=255,Buffer.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):arrayIndexOf(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(e,t,n,r,a){var i,o=1,s=e.length,l=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,s/=2,l/=2,n/=2}function u(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(a){var c=-1;for(i=n;is&&(n=s-l),i=n;i>=0;i--){for(var p=!0,d=0;da&&(r=a):r=a;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");r>i/2&&(r=i/2);for(var o=0;o239?4:u>223?3:u>191?2:1;if(a+p<=n)switch(p){case 1:u<128&&(c=u);break;case 2:128==(192&(i=e[a+1]))&&(l=(31&u)<<6|63&i)>127&&(c=l);break;case 3:i=e[a+1],o=e[a+2],128==(192&i)&&128==(192&o)&&(l=(15&u)<<12|(63&i)<<6|63&o)>2047&&(l<55296||l>57343)&&(c=l);break;case 4:i=e[a+1],o=e[a+2],s=e[a+3],128==(192&i)&&128==(192&o)&&128==(192&s)&&(l=(15&u)<<18|(63&i)<<12|(63&o)<<6|63&s)>65535&&l<1114112&&(c=l)}null===c?(c=65533,p=1):c>65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|1023&c),r.push(c),a+=p}return decodeCodePointsArray(r)}Buffer.TYPED_ARRAY_SUPPORT=void 0===global$x.TYPED_ARRAY_SUPPORT||global$x.TYPED_ARRAY_SUPPORT,kMaxLength(),Buffer.poolSize=8192,Buffer._augment=function(e){return e.__proto__=Buffer.prototype,e},Buffer.from=function(e,t,n){return from(null,e,t,n)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array),Buffer.alloc=function(e,t,n){return alloc(null,e,t,n)},Buffer.allocUnsafe=function(e){return allocUnsafe(null,e)},Buffer.allocUnsafeSlow=function(e){return allocUnsafe(null,e)},Buffer.isBuffer=isBuffer,Buffer.compare=function(e,t){if(!internalIsBuffer(e)||!internalIsBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,a=0,i=Math.min(n,r);a0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},Buffer.prototype.compare=function(e,t,n,r,a){if(!internalIsBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(a>>>=0)-(r>>>=0),o=(n>>>=0)-(t>>>=0),s=Math.min(i,o),l=this.slice(r,a),u=e.slice(t,n),c=0;ca)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return hexWrite(this,e,t,n);case"utf8":case"utf-8":return utf8Write(this,e,t,n);case"ascii":return asciiWrite(this,e,t,n);case"latin1":case"binary":return latin1Write(this,e,t,n);case"base64":return base64Write(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(e){var t=e.length;if(t<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,e);for(var n="",r=0;rr)&&(n=r);for(var a="",i=t;in)throw new RangeError("Trying to access beyond buffer length")}function checkInt(e,t,n,r,a,i){if(!internalIsBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||te.length)throw new RangeError("Index out of range")}function objectWriteUInt16(e,t,n,r){t<0&&(t=65535+t+1);for(var a=0,i=Math.min(e.length-n,2);a>>8*(r?a:1-a)}function objectWriteUInt32(e,t,n,r){t<0&&(t=4294967295+t+1);for(var a=0,i=Math.min(e.length-n,4);a>>8*(r?a:3-a)&255}function checkIEEE754(e,t,n,r,a,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function writeFloat(e,t,n,r,a){return a||checkIEEE754(e,t,n,4),write(e,t,n,r,23,4),n+4}function writeDouble(e,t,n,r,a){return a||checkIEEE754(e,t,n,8),write(e,t,n,r,52,8),n+8}Buffer.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t0&&(a*=256);)r+=this[e+--t]*a;return r},Buffer.prototype.readUInt8=function(e,t){return t||checkOffset(e,1,this.length),this[e]},Buffer.prototype.readUInt16LE=function(e,t){return t||checkOffset(e,2,this.length),this[e]|this[e+1]<<8},Buffer.prototype.readUInt16BE=function(e,t){return t||checkOffset(e,2,this.length),this[e]<<8|this[e+1]},Buffer.prototype.readUInt32LE=function(e,t){return t||checkOffset(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},Buffer.prototype.readUInt32BE=function(e,t){return t||checkOffset(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},Buffer.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||checkOffset(e,t,this.length);for(var r=this[e],a=1,i=0;++i=(a*=128)&&(r-=Math.pow(2,8*t)),r},Buffer.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||checkOffset(e,t,this.length);for(var r=t,a=1,i=this[e+--r];r>0&&(a*=256);)i+=this[e+--r]*a;return i>=(a*=128)&&(i-=Math.pow(2,8*t)),i},Buffer.prototype.readInt8=function(e,t){return t||checkOffset(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},Buffer.prototype.readInt16LE=function(e,t){t||checkOffset(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},Buffer.prototype.readInt16BE=function(e,t){t||checkOffset(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},Buffer.prototype.readInt32LE=function(e,t){return t||checkOffset(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},Buffer.prototype.readInt32BE=function(e,t){return t||checkOffset(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},Buffer.prototype.readFloatLE=function(e,t){return t||checkOffset(e,4,this.length),read(this,e,!0,23,4)},Buffer.prototype.readFloatBE=function(e,t){return t||checkOffset(e,4,this.length),read(this,e,!1,23,4)},Buffer.prototype.readDoubleLE=function(e,t){return t||checkOffset(e,8,this.length),read(this,e,!0,52,8)},Buffer.prototype.readDoubleBE=function(e,t){return t||checkOffset(e,8,this.length),read(this,e,!1,52,8)},Buffer.prototype.writeUIntLE=function(e,t,n,r){(e=+e,t|=0,n|=0,r)||checkInt(this,e,t,n,Math.pow(2,8*n)-1,0);var a=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+a]=e/i&255;return t+n},Buffer.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},Buffer.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):objectWriteUInt16(this,e,t,!0),t+2},Buffer.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):objectWriteUInt16(this,e,t,!1),t+2},Buffer.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):objectWriteUInt32(this,e,t,!0),t+4},Buffer.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):objectWriteUInt32(this,e,t,!1),t+4},Buffer.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);checkInt(this,e,t,n,a-1,-a)}var i=0,o=1,s=0;for(this[t]=255&e;++i>0)-s&255;return t+n},Buffer.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);checkInt(this,e,t,n,a-1,-a)}var i=n-1,o=1,s=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(e/o>>0)-s&255;return t+n},Buffer.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},Buffer.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):objectWriteUInt16(this,e,t,!0),t+2},Buffer.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):objectWriteUInt16(this,e,t,!1),t+2},Buffer.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):objectWriteUInt32(this,e,t,!0),t+4},Buffer.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):objectWriteUInt32(this,e,t,!1),t+4},Buffer.prototype.writeFloatLE=function(e,t,n){return writeFloat(this,e,t,!0,n)},Buffer.prototype.writeFloatBE=function(e,t,n){return writeFloat(this,e,t,!1,n)},Buffer.prototype.writeDoubleLE=function(e,t,n){return writeDouble(this,e,t,!0,n)},Buffer.prototype.writeDoubleBE=function(e,t,n){return writeDouble(this,e,t,!1,n)},Buffer.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--a)e[a+t]=this[a+n];else if(i<1e3||!Buffer.TYPED_ARRAY_SUPPORT)for(a=0;a>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&i.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&i.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function asciiToBytes(e){for(var t=[],n=0;n>8,a=n%256,i.push(a),i.push(r);return i}function base64ToBytes(e){return toByteArray(base64clean(e))}function blitBuffer(e,t,n,r){for(var a=0;a=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function isnan(e){return e!=e}function isBuffer(e){return null!=e&&(!!e._isBuffer||isFastBuffer(e)||isSlowBuffer(e))}function isFastBuffer(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function isSlowBuffer(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&isFastBuffer(e.slice(0,0))}function requireToFormData(){if(hasRequiredToFormData)return toFormData_1;hasRequiredToFormData=1;var e=utils$9;return toFormData_1=function(t,n){n=n||new FormData;var r=[];function a(t){return null===t?"":e.isDate(t)?t.toISOString():e.isArrayBuffer(t)||e.isTypedArray(t)?"function"==typeof Blob?new Blob([t]):Buffer.from(t):t}return function t(i,o){if(e.isPlainObject(i)||e.isArray(i)){if(-1!==r.indexOf(i))throw Error("Circular reference detected in "+o);r.push(i),e.forEach(i,(function(r,i){if(!e.isUndefined(r)){var s,l=o?o+"."+i:i;if(r&&!o&&"object"==typeof r)if(e.endsWith(i,"{}"))r=JSON.stringify(r);else if(e.endsWith(i,"[]")&&(s=e.toArray(r)))return void s.forEach((function(t){!e.isUndefined(t)&&n.append(l,a(t))}));t(r,l)}})),r.pop()}else n.append(o,a(i))}(t),n},toFormData_1}function requireSettle(){if(hasRequiredSettle)return settle;hasRequiredSettle=1;var e=requireAxiosError();return settle=function(t,n,r){var a=r.config.validateStatus;r.status&&a&&!a(r.status)?n(new e("Request failed with status code "+r.status,[e.ERR_BAD_REQUEST,e.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):t(r)},settle}function requireCookies(){if(hasRequiredCookies)return cookies;hasRequiredCookies=1;var e=utils$9;return cookies=e.isStandardBrowserEnv()?{write:function(t,n,r,a,i,o){var s=[];s.push(t+"="+encodeURIComponent(n)),e.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),e.isString(a)&&s.push("path="+a),e.isString(i)&&s.push("domain="+i),!0===o&&s.push("secure"),document.cookie=s.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}},cookies}var isAbsoluteURL$1=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)},combineURLs$1=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},isAbsoluteURL=isAbsoluteURL$1,combineURLs=combineURLs$1,buildFullPath$1=function(e,t){return e&&!isAbsoluteURL(t)?combineURLs(e,t):t},parseHeaders,hasRequiredParseHeaders,isURLSameOrigin,hasRequiredIsURLSameOrigin,CanceledError_1,hasRequiredCanceledError,parseProtocol,hasRequiredParseProtocol,xhr,hasRequiredXhr,_null,hasRequired_null;function requireParseHeaders(){if(hasRequiredParseHeaders)return parseHeaders;hasRequiredParseHeaders=1;var e=utils$9,t=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];return parseHeaders=function(n){var r,a,i,o={};return n?(e.forEach(n.split("\n"),(function(n){if(i=n.indexOf(":"),r=e.trim(n.substr(0,i)).toLowerCase(),a=e.trim(n.substr(i+1)),r){if(o[r]&&t.indexOf(r)>=0)return;o[r]="set-cookie"===r?(o[r]?o[r]:[]).concat([a]):o[r]?o[r]+", "+a:a}})),o):o},parseHeaders}function requireIsURLSameOrigin(){if(hasRequiredIsURLSameOrigin)return isURLSameOrigin;hasRequiredIsURLSameOrigin=1;var e=utils$9;return isURLSameOrigin=e.isStandardBrowserEnv()?function(){var t,n=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");function a(e){var t=e;return n&&(r.setAttribute("href",t),t=r.href),r.setAttribute("href",t),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:"/"===r.pathname.charAt(0)?r.pathname:"/"+r.pathname}}return t=a(window.location.href),function(n){var r=e.isString(n)?a(n):n;return r.protocol===t.protocol&&r.host===t.host}}():function(){return!0}}function requireCanceledError(){if(hasRequiredCanceledError)return CanceledError_1;hasRequiredCanceledError=1;var e=requireAxiosError();function t(t){e.call(this,null==t?"canceled":t,e.ERR_CANCELED),this.name="CanceledError"}return utils$9.inherits(t,e,{__CANCEL__:!0}),CanceledError_1=t}function requireParseProtocol(){return hasRequiredParseProtocol||(hasRequiredParseProtocol=1,parseProtocol=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}),parseProtocol}function requireXhr(){if(hasRequiredXhr)return xhr;hasRequiredXhr=1;var e=utils$9,t=requireSettle(),n=requireCookies(),r=buildURL$1,a=buildFullPath$1,i=requireParseHeaders(),o=requireIsURLSameOrigin(),s=transitional,l=requireAxiosError(),u=requireCanceledError(),c=requireParseProtocol();return xhr=function(p){return new Promise((function(d,m){var f,h=p.data,y=p.headers,b=p.responseType;function g(){p.cancelToken&&p.cancelToken.unsubscribe(f),p.signal&&p.signal.removeEventListener("abort",f)}e.isFormData(h)&&e.isStandardBrowserEnv()&&delete y["Content-Type"];var v=new XMLHttpRequest;if(p.auth){var T=p.auth.username||"",N=p.auth.password?unescape(encodeURIComponent(p.auth.password)):"";y.Authorization="Basic "+btoa(T+":"+N)}var C=a(p.baseURL,p.url);function A(){if(v){var e="getAllResponseHeaders"in v?i(v.getAllResponseHeaders()):null,n={data:b&&"text"!==b&&"json"!==b?v.response:v.responseText,status:v.status,statusText:v.statusText,headers:e,config:p,request:v};t((function(e){d(e),g()}),(function(e){m(e),g()}),n),v=null}}if(v.open(p.method.toUpperCase(),r(C,p.params,p.paramsSerializer),!0),v.timeout=p.timeout,"onloadend"in v?v.onloadend=A:v.onreadystatechange=function(){v&&4===v.readyState&&(0!==v.status||v.responseURL&&0===v.responseURL.indexOf("file:"))&&setTimeout(A)},v.onabort=function(){v&&(m(new l("Request aborted",l.ECONNABORTED,p,v)),v=null)},v.onerror=function(){m(new l("Network Error",l.ERR_NETWORK,p,v,v)),v=null},v.ontimeout=function(){var e=p.timeout?"timeout of "+p.timeout+"ms exceeded":"timeout exceeded",t=p.transitional||s;p.timeoutErrorMessage&&(e=p.timeoutErrorMessage),m(new l(e,t.clarifyTimeoutError?l.ETIMEDOUT:l.ECONNABORTED,p,v)),v=null},e.isStandardBrowserEnv()){var S=(p.withCredentials||o(C))&&p.xsrfCookieName?n.read(p.xsrfCookieName):void 0;S&&(y[p.xsrfHeaderName]=S)}"setRequestHeader"in v&&e.forEach(y,(function(e,t){void 0===h&&"content-type"===t.toLowerCase()?delete y[t]:v.setRequestHeader(t,e)})),e.isUndefined(p.withCredentials)||(v.withCredentials=!!p.withCredentials),b&&"json"!==b&&(v.responseType=p.responseType),"function"==typeof p.onDownloadProgress&&v.addEventListener("progress",p.onDownloadProgress),"function"==typeof p.onUploadProgress&&v.upload&&v.upload.addEventListener("progress",p.onUploadProgress),(p.cancelToken||p.signal)&&(f=function(e){v&&(m(!e||e&&e.type?new u:e),v.abort(),v=null)},p.cancelToken&&p.cancelToken.subscribe(f),p.signal&&(p.signal.aborted?f():p.signal.addEventListener("abort",f))),h||(h=null);var x=c(C);x&&-1===["http","https","file"].indexOf(x)?m(new l("Unsupported protocol "+x+":",l.ERR_BAD_REQUEST,p)):v.send(h)}))},xhr}function require_null(){return hasRequired_null?_null:(hasRequired_null=1,_null=null)}var utils$5=utils$9,normalizeHeaderName=normalizeHeaderName$1,AxiosError$1=requireAxiosError(),transitionalDefaults=transitional,toFormData=requireToFormData(),DEFAULT_CONTENT_TYPE={"Content-Type":"application/x-www-form-urlencoded"};function setContentTypeIfUnset(e,t){!utils$5.isUndefined(e)&&utils$5.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}function getDefaultAdapter(){var e;return("undefined"!=typeof XMLHttpRequest||void 0!==browser$1&&"[object process]"===Object.prototype.toString.call(browser$1))&&(e=requireXhr()),e}function stringifySafely(e,t,n){if(utils$5.isString(e))try{return(t||JSON.parse)(e),utils$5.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(n||JSON.stringify)(e)}var defaults$3={transitional:transitionalDefaults,adapter:getDefaultAdapter(),transformRequest:[function(e,t){if(normalizeHeaderName(t,"Accept"),normalizeHeaderName(t,"Content-Type"),utils$5.isFormData(e)||utils$5.isArrayBuffer(e)||utils$5.isBuffer(e)||utils$5.isStream(e)||utils$5.isFile(e)||utils$5.isBlob(e))return e;if(utils$5.isArrayBufferView(e))return e.buffer;if(utils$5.isURLSearchParams(e))return setContentTypeIfUnset(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var n,r=utils$5.isObject(e),a=t&&t["Content-Type"];if((n=utils$5.isFileList(e))||r&&"multipart/form-data"===a){var i=this.env&&this.env.FormData;return toFormData(n?{"files[]":e}:e,i&&new i)}return r||"application/json"===a?(setContentTypeIfUnset(t,"application/json"),stringifySafely(e)):e}],transformResponse:[function(e){var t=this.transitional||defaults$3.transitional,n=t&&t.silentJSONParsing,r=t&&t.forcedJSONParsing,a=!n&&"json"===this.responseType;if(a||r&&utils$5.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(a){if("SyntaxError"===e.name)throw AxiosError$1.from(e,AxiosError$1.ERR_BAD_RESPONSE,this,null,this.response);throw e}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:require_null()},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};utils$5.forEach(["delete","get","head"],(function(e){defaults$3.headers[e]={}})),utils$5.forEach(["post","put","patch"],(function(e){defaults$3.headers[e]=utils$5.merge(DEFAULT_CONTENT_TYPE)}));var defaults_1=defaults$3,utils$4=utils$9,defaults$2=defaults_1,transformData$1=function(e,t,n){var r=this||defaults$2;return utils$4.forEach(n,(function(n){e=n.call(r,e,t)})),e},isCancel$1,hasRequiredIsCancel;function requireIsCancel(){return hasRequiredIsCancel?isCancel$1:(hasRequiredIsCancel=1,isCancel$1=function(e){return!(!e||!e.__CANCEL__)})}var utils$3=utils$9,transformData=transformData$1,isCancel=requireIsCancel(),defaults$1=defaults_1,CanceledError=requireCanceledError();function throwIfCancellationRequested(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new CanceledError}var dispatchRequest$1=function(e){return throwIfCancellationRequested(e),e.headers=e.headers||{},e.data=transformData.call(e,e.data,e.headers,e.transformRequest),e.headers=utils$3.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),utils$3.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||defaults$1.adapter)(e).then((function(t){return throwIfCancellationRequested(e),t.data=transformData.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return isCancel(t)||(throwIfCancellationRequested(e),t&&t.response&&(t.response.data=transformData.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},utils$2=utils$9,mergeConfig$2=function(e,t){t=t||{};var n={};function r(e,t){return utils$2.isPlainObject(e)&&utils$2.isPlainObject(t)?utils$2.merge(e,t):utils$2.isPlainObject(t)?utils$2.merge({},t):utils$2.isArray(t)?t.slice():t}function a(n){return utils$2.isUndefined(t[n])?utils$2.isUndefined(e[n])?void 0:r(void 0,e[n]):r(e[n],t[n])}function i(e){if(!utils$2.isUndefined(t[e]))return r(void 0,t[e])}function o(n){return utils$2.isUndefined(t[n])?utils$2.isUndefined(e[n])?void 0:r(void 0,e[n]):r(void 0,t[n])}function s(n){return n in t?r(e[n],t[n]):n in e?r(void 0,e[n]):void 0}var l={url:i,method:i,data:i,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:s};return utils$2.forEach(Object.keys(e).concat(Object.keys(t)),(function(e){var t=l[e]||a,r=t(e);utils$2.isUndefined(r)&&t!==s||(n[e]=r)})),n},data,hasRequiredData;function requireData(){return hasRequiredData?data:(hasRequiredData=1,data={version:"0.27.2"})}var VERSION=requireData().version,AxiosError=requireAxiosError(),validators$1={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){validators$1[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}}));var deprecatedWarnings={};function assertOptions(e,t,n){if("object"!=typeof e)throw new AxiosError("options must be an object",AxiosError.ERR_BAD_OPTION_VALUE);for(var r=Object.keys(e),a=r.length;a-- >0;){var i=r[a],o=t[i];if(o){var s=e[i],l=void 0===s||o(s,i,e);if(!0!==l)throw new AxiosError("option "+i+" must be "+l,AxiosError.ERR_BAD_OPTION_VALUE)}else if(!0!==n)throw new AxiosError("Unknown option "+i,AxiosError.ERR_BAD_OPTION)}}validators$1.transitional=function(e,t,n){function r(e,t){return"[Axios v"+VERSION+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return function(n,a,i){if(!1===e)throw new AxiosError(r(a," has been removed"+(t?" in "+t:"")),AxiosError.ERR_DEPRECATED);return t&&!deprecatedWarnings[a]&&(deprecatedWarnings[a]=!0,console.warn(r(a," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,a,i)}};var validator$1={assertOptions:assertOptions,validators:validators$1},utils$1=utils$9,buildURL=buildURL$1,InterceptorManager=InterceptorManager_1,dispatchRequest=dispatchRequest$1,mergeConfig$1=mergeConfig$2,buildFullPath=buildFullPath$1,validator=validator$1,validators=validator.validators;function Axios$1(e){this.defaults=e,this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}Axios$1.prototype.request=function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},(t=mergeConfig$1(this.defaults,t)).method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var n=t.transitional;void 0!==n&&validator.assertOptions(n,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1);var r=[],a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,r.unshift(e.fulfilled,e.rejected))}));var i,o=[];if(this.interceptors.response.forEach((function(e){o.push(e.fulfilled,e.rejected)})),!a){var s=[dispatchRequest,void 0];for(Array.prototype.unshift.apply(s,r),s=s.concat(o),i=Promise.resolve(t);s.length;)i=i.then(s.shift(),s.shift());return i}for(var l=t;r.length;){var u=r.shift(),c=r.shift();try{l=u(l)}catch(e){c(e);break}}try{i=dispatchRequest(l)}catch(e){return Promise.reject(e)}for(;o.length;)i=i.then(o.shift(),o.shift());return i},Axios$1.prototype.getUri=function(e){e=mergeConfig$1(this.defaults,e);var t=buildFullPath(e.baseURL,e.url);return buildURL(t,e.params,e.paramsSerializer)},utils$1.forEach(["delete","get","head","options"],(function(e){Axios$1.prototype[e]=function(t,n){return this.request(mergeConfig$1(n||{},{method:e,url:t,data:(n||{}).data}))}})),utils$1.forEach(["post","put","patch"],(function(e){function t(t){return function(n,r,a){return this.request(mergeConfig$1(a||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:r}))}}Axios$1.prototype[e]=t(),Axios$1.prototype[e+"Form"]=t(!0)}));var Axios_1=Axios$1,CancelToken_1,hasRequiredCancelToken,spread,hasRequiredSpread,isAxiosError,hasRequiredIsAxiosError;function requireCancelToken(){if(hasRequiredCancelToken)return CancelToken_1;hasRequiredCancelToken=1;var e=requireCanceledError();function t(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var n;this.promise=new Promise((function(e){n=e}));var r=this;this.promise.then((function(e){if(r._listeners){var t,n=r._listeners.length;for(t=0;t{this.initializedPromiseResolves.forEach((e=>e(!0))),this.initialized=!0},this.getInitializedPromise=()=>this.initialized?Promise.resolve(!0):new Promise(((e,t)=>{this.initializedPromiseResolves.push(e)})),cidFromText(e).then((t=>expandDoenetMLsToFullSerializedComponents({cids:[t],doenetMLs:[e],componentInfoObjects:this.componentInfoObjects,flags:this.flags}))).then(this.finishCoreConstruction).catch((e=>{postMessage({messageType:"inErrorState",coreId:this.coreId,args:{errMsg:e.message}})}))}async finishCoreConstruction({cids:e,fullSerializedComponents:t}){this.cid=e[0];let n=t[0];addDocumentIfItsMissing(n),createComponentNames({serializedComponents:n,componentInfoObjects:this.componentInfoObjects}),this.componentIndexArray=extractComponentNamesAndIndices(n);let{rangePieces:r}=extractRangeIndexPieces({componentArray:this.componentIndexArray});this.componentRangePieces=r,postMessage({messageType:"componentRangePieces",coreId:this.coreId,args:{componentRangePieces:this.componentRangePieces}}),this.documentName=n[0].componentName,n[0].doenetAttributes.cid=this.cid,this._components={},this.componentsToRender={},this.componentsWithChangedChildrenToRender=new Set([]),this.stateVariableChangeTriggers={},this.actionsChangedToActions={},this.originsOfActionsChangedToActions={},this.essentialValuesSavedInDefinition={},this.saveStateToDBTimerId=null,this.rendererState={__componentNeedingUpdateValue:null},this.rendererVariablesByComponentType={};for(let e in this.componentInfoObjects.allComponentClasses)Object.defineProperty(this.rendererVariablesByComponentType,e,{get:function(){let t=this.componentInfoObjects.allComponentClasses[e].returnStateVariableInfo({onlyForRenderer:!0}).stateVariableDescriptions;return delete this.rendererVariablesByComponentType[e],this.rendererVariablesByComponentType[e]=t}.bind(this),configurable:!0});this.processQueue=[],this.stopProcessingRequests=!1,this.dependencies=new DependencyHandler({_components:this._components,componentInfoObjects:this.componentInfoObjects,core:this}),this.unmatchedChildren={};let a=getNumberOfVariants({serializedComponent:n[0],componentInfoObjects:this.componentInfoObjects}).numberOfVariants;if(!this.requestedVariant){if(this.requestedVariantIndex=((this.requestedVariantIndex-1)%a+a)%a+1,n[0].variants.uniqueVariants){let e=this.componentInfoObjects.allComponentClasses[n[0].componentType].getUniqueVariant({serializedComponent:n[0],variantIndex:this.requestedVariantIndex,componentInfoObjects:this.componentInfoObjects});e.success&&(this.requestedVariant=e.desiredVariant)}this.requestedVariant||(this.requestedVariant={index:this.requestedVariantIndex})}this.parameterStack.parameters.variant=this.requestedVariant,n[0].variants.desiredVariant=this.parameterStack.parameters.variant,await this.addComponents({serializedComponents:n,initialAdd:!0}),this.updateInfo.componentsToUpdateRenderers=[],await this.document.stateValues.itemCreditAchieved,this.canonicalGeneratedVariantString=JSON.stringify(await this.document.stateValues.generatedVariantInfo,serializedComponentsReplacer),this.canonicalItemVariantStrings=(await this.document.stateValues.itemVariantInfo).map((e=>JSON.stringify(e,serializedComponentsReplacer))),this.coreInfo={generatedVariantString:this.canonicalGeneratedVariantString,allPossibleVariants:deepClone(await this.document.sharedParameters.allPossibleVariants),rendererTypesInDocument:deepClone(this.rendererTypesInDocument),documentToRender:this.documentRendererInstructions},this.coreInfoString=JSON.stringify(this.coreInfo,serializedComponentsReplacer),this.messageViewerReady(),this.resolveInitialized()}async onDocumentFirstVisible(){this.requestRecordEvent({verb:"experienced",object:{componentName:this.document.componentName,componentType:"document"}});let e=function(t){let n=t.stateValues.scoredDescendants;if(Array.isArray(n))for(let t of n){if("answer"===t.componentType)return!0;if(e(t))return!0}return!1};await this.document.stateValues.scoredDescendants,e(this.document)||this.saveSubmissions({pageCreditAchieved:await this.document.stateValues.creditAchieved,suppressToast:!0}),setTimeout(this.sendVisibilityChangedEvents.bind(this),this.visibilityInfo.saveDelay)}async messageViewerReady(){postMessage({messageType:"initializeRenderers",coreId:this.coreId,args:{coreInfo:this.coreInfo}}),postMessage({messageType:"coreCreated",coreId:this.coreId})}async postUpdateRenderers(e,t=!1){postMessage({messageType:"updateRenderers",coreId:this.coreId,args:e,init:t})}async addComponents({serializedComponents:e,parentName:t,indexOfDefiningChildren:n,initialAdd:r=!1,assignNamesOffset:a}){let i;Array.isArray(e)||(e=[e]);let o=[],s="";if(!r){if(i=this._components[t],!i)return console.warn(`Cannot add children to parent ${t} as ${t} does not exist`),[];if(i.isShadow)return console.warn(`Cannot add children to parent ${t} as it is a shadow component.`),[];o=[{componentName:t,componentClass:i.constructor},...i.ancestors],this.parameterStack.push(i.sharedParameters,!1),this.nTimesAddedComponents?this.nTimesAddedComponents++:this.nTimesAddedComponents=1,s=`addComponents${this.nTimesAddedComponents}`}let l=await this.createIsolatedComponents({serializedComponents:e,ancestors:o,createNameContext:s});if(r||this.parameterStack.pop(),!0!==l.success)throw Error(l.message);const u=l.components;let c={},p={};if(u.forEach((e=>p[e.componentName]=e)),r){if(1!==u.length)throw Error("Initial components need to be an array of just one component.");if(this.document=u[0],await this.expandAllComposites(this.document),await this.expandAllComposites(this.document,!0),this.updateInfo.stateVariablesToEvaluate){let e=this.updateInfo.stateVariablesToEvaluate;this.updateInfo.stateVariablesToEvaluate=[];for(let{componentName:t,stateVariable:n}of e){let e=this._components[t];e&&e.state[n]&&await this.getStateVariableValue({component:e,stateVariable:n})}}await this.replacementChangesFromCompositesToUpdate();let e=await this.initializeRenderedComponentInstruction(this.document);if(this.updateInfo.compositesToUpdateReplacements.length>0){await this.replacementChangesFromCompositesToUpdate();let e=[...new Set(this.updateInfo.componentsToUpdateRenderers)];this.updateInfo.componentsToUpdateRenderers=[],await this.updateRendererInstructions({componentNamesToUpdate:e})}this.documentRendererInstructions=e.componentToRender;let t=[{instructionType:"updateRendererStates",rendererStatesToUpdate:e.rendererStatesToUpdate}];if(this.postUpdateRenderers({updateInstructions:t},!0),e.rendererStatesToForceUpdate.length>0){let t=[{instructionType:"updateRendererStates",rendererStatesToUpdate:e.rendererStatesToForceUpdate}];this.postUpdateRenderers({updateInstructions:t})}await this.processStateVariableTriggers()}else{if(void 0===i)throw Error("Must specify parent when adding components.");void 0===n&&(n=i.definingChildren.length);let e=await this.addChildrenAndRecurseToShadows({parent:i,indexOfDefiningChildren:n,newChildren:u,assignNamesOffset:a});if(!e.success)throw Error("Couldn't satisfy child logic result. Need informative error message");if(Object.assign(p,e.addedComponents),Object.assign(c,e.deletedComponents),await this.expandAllComposites(this.document),await this.expandAllComposites(this.document,!0),this.updateInfo.stateVariablesToEvaluate){let e=this.updateInfo.stateVariablesToEvaluate;this.updateInfo.stateVariablesToEvaluate=[];for(let{componentName:t,stateVariable:n}of e){let e=this._components[t];e&&e.state[n]&&await this.getStateVariableValue({component:e,stateVariable:n})}}if(await this.replacementChangesFromCompositesToUpdate(),await this.updateRendererInstructions({componentNamesToUpdate:await this.componentAndRenderedDescendants(i)}),this.updateInfo.compositesToUpdateReplacements.length>0){await this.replacementChangesFromCompositesToUpdate();let e=[...new Set(this.updateInfo.componentsToUpdateRenderers)];this.updateInfo.componentsToUpdateRenderers=[],await this.updateRendererInstructions({componentNamesToUpdate:e})}await this.processStateVariableTriggers()}return u}async updateRendererInstructions({componentNamesToUpdate:e,sourceOfUpdate:t={},actionId:n}){let r=[],a=[],i=[],o={},s=this.componentsWithChangedChildrenToRender;this.componentsWithChangedChildrenToRender=new Set([]);for(let t of s)if(t in this.componentsToRender){let n=[],a=this._components[t],l=[];if(a&&a.constructor.renderChildren){a.childrenMatched||await this.deriveChildResultsFromDefiningChildren({parent:a,expandComposites:!0,forceExpandComposites:!0}),l=await this.returnActiveChildrenIndicesToRender(a);let e=0;for(let[t,r]of a.activeChildren.entries())l.includes(t)&&(r.rendererType?(n.push(`nameType:${r.componentName};${r.componentType}`),e++):"string"==typeof r?(n.push(`string${e}:${r}`),e++):"number"==typeof r&&(n.push(`number${e}:${r.toString()}`),e++))}let u=this.componentsToRender[t].children,c=[];for(let[e,t]of u.entries())t.componentName?c.push(`nameType:${t.componentName};${t.componentType}`):"string"==typeof t?c.push(`string${e}:${t}`):"number"==typeof t&&c.push(`number${e}:${t.toString()}`);if(n.length!==c.length||n.some(((e,t)=>e!==c[t]))){for(let e of u)if(e.componentName){let t=this.deleteFromComponentsToRender({componentName:e.componentName,recurseToChildren:!0,componentsWithChangedChildrenToRenderInProgress:s});r.push(...t)}let n=[];if(l.length>0)for(let[e,t]of a.activeChildren.entries())if(l.includes(e))if(t.rendererType){let e=await this.initializeRenderedComponentInstruction(t,s);n.push(e.componentToRender),i.push(...e.rendererStatesToUpdate)}else"string"==typeof t?n.push(t):"number"==typeof t&&n.push(t.toString());this.componentsToRender[t].children=n,o[t]=n,s.delete(t),e.includes(t)||e.push(t)}}for(let t of e)if(t in this.componentsToRender){let e=this._components[t];if(e){let n={};for(let t in e.state)if(e.state[t].forRenderer){let r=removeFunctionsMathExpressionClass(await e.state[t].value);n[t]=r}let r={componentName:t,stateValues:n,rendererType:e.rendererType};this.rendererState[t]||(this.rendererState[t]={}),this.rendererState[t].stateValues=n,o[t]&&(r.childrenInstructions=o[t],this.rendererState[t].childrenInstructions=o[t]),i.push(r)}}if(i.length>0){let e={instructionType:"updateRendererStates",rendererStatesToUpdate:i,sourceOfUpdate:t};a.splice(0,0,e)}this.postUpdateRenderers({updateInstructions:a,actionId:n})}async initializeRenderedComponentInstruction(e,t=new Set([])){if(void 0===e.rendererType)return;e.childrenMatched||await this.deriveChildResultsFromDefiningChildren({parent:e,expandComposites:!0});let n=[],r=[],a={},i={},o=!1;for(let t in e.state)e.state[t].forRenderer&&(a[t]=removeFunctionsMathExpressionClass(await e.state[t].value),e.state[t].alwaysUpdateRenderer&&(o=!0));o&&(i=a);let s=e.componentName,l=[];if(e.constructor.renderChildren){let a=await this.returnActiveChildrenIndicesToRender(e);for(let[i,o]of e.activeChildren.entries())if(a.includes(i))if(o.rendererType){let e=await this.initializeRenderedComponentInstruction(o,t);l.push(e.componentToRender),n.push(...e.rendererStatesToUpdate),r.push(...e.rendererStatesToForceUpdate)}else"string"==typeof o?l.push(o):"number"==typeof o&&l.push(o.toString())}n.push({componentName:s,stateValues:a,childrenInstructions:l}),Object.keys(i).length>0&&r.push({componentName:s,stateValues:i}),this.rendererState[s]={stateValues:a,childrenInstructions:l},t.delete(s);let u={};for(let t in e.actions)u[t]={actionName:t,componentName:e.componentName};for(let t in e.externalActions){let n=await e.externalActions[t];n&&(u[t]={actionName:t,componentName:n.componentName})}let c={componentName:s,effectiveName:e.componentOrAdaptedName,componentType:e.componentType,rendererType:e.rendererType,actions:u};return this.componentsToRender[s]={children:l},{componentToRender:c,rendererStatesToUpdate:n,rendererStatesToForceUpdate:r}}deleteFromComponentsToRender({componentName:e,recurseToChildren:t=!0,componentsWithChangedChildrenToRenderInProgress:n}){let r=[e];if(t){let a=this.componentsToRender[e];if(a)for(let e of a.children){let a=this.deleteFromComponentsToRender({componentName:e.componentName,recurseToChildren:t,componentsWithChangedChildrenToRenderInProgress:n});r.push(...a)}}return delete this.componentsToRender[e],n.delete(e),r}async processStateVariableTriggers(){for(let e in this.stateVariableChangeTriggers){let t=this._components[e];for(let n in this.stateVariableChangeTriggers[e]){let r=this.stateVariableChangeTriggers[e][n],a=await t.state[n].value;if(a!==r.previousValue){let i=r.previousValue;r.previousValue=a,t.actions[r.action]&&await this.performAction({componentName:e,actionName:r.action,args:{stateValues:{[n]:a},previousValues:{[n]:i}}})}}}}async expandAllComposites(e,t=!1){let n=await this.expandCompositesOfDescendants(e,t),r=!0;for(;r;){r=!1;for(let e of n){let n=this._components[e],a=!1;for(let e of n.unexpandedCompositesNotReady){let n=this._components[e];if(n.state.readyToExpandWhenResolved.isResolved){a=!0;break}if((await this.dependencies.resolveItem({componentName:n.componentName,type:"stateVariable",stateVariable:"readyToExpandWhenResolved",force:t,recurseUpstream:!0})).success){a=!0;break}}if(a){let n=this._components[e];await this.deriveChildResultsFromDefiningChildren({parent:n,expandComposites:!0,forceExpandComposites:t}),r=!0}}}}async expandCompositesOfDescendants(e,t=!1){let n=[];e.childrenMatched||(await this.deriveChildResultsFromDefiningChildren({parent:e,expandComposites:!0,forceExpandComposites:t}),e.unexpandedCompositesNotReady.length>0?n.push(e.componentName):await this.dependencies.resolveBlockersFromChangedActiveChildren(e,t));for(let r in e.attributes){let a=e.attributes[r].component;if(a){let e=await this.expandCompositesOfDescendants(a,t);n.push(...e)}}for(let r in e.allChildren){let a=e.allChildren[r].component;if("object"!=typeof a)continue;let i=await this.expandCompositesOfDescendants(a,t);n.push(...i)}return n}async componentAndRenderedDescendants(e){if(!e?.componentName)return[];let t=[e.componentName];if(e.constructor.renderChildren){e.childrenMatched||await this.deriveChildResultsFromDefiningChildren({parent:e,expandComposites:!0});for(let n of e.activeChildren)t.push(...await this.componentAndRenderedDescendants(n))}return t}async createIsolatedComponents({serializedComponents:e,ancestors:t,shadow:n=!1,createNameContext:r=""}){let a="/";if(t.length>0){let e=t[0].componentName,n=this.components[e];a=n.attributes.newNamespace?.primitive?n.componentName+"/":getNamespaceFromName(n.componentName)}return{success:!0,components:(await this.createIsolatedComponentsSub({serializedComponents:e,ancestors:t,shadow:n,namespaceForUnamed:a,createNameContext:r})).components}}async createIsolatedComponentsSub({serializedComponents:e,ancestors:t,shadow:n=!1,createNameContext:r="",namespaceForUnamed:a="/",componentsReplacementOf:i}){let o=[];for(let[s,l]of e.entries()){if("object"!=typeof l){o.push(l);continue}if(!0===l.createdComponent){let e=this._components[l.componentName];o.push(e),this.setAncestors(e,t);continue}let e=this.componentInfoObjects.allComponentClasses[l.componentType];if(void 0===e)throw Error("Cannot create component of type "+l.componentType);l.doenetAttributes||(l.doenetAttributes={});let u=l.componentName;if(void 0===u){let e=t[0].componentName+"|"+r+"|";l.uniqueIdentifier?e+=l.uniqueIdentifier:e+=s,u=createUniqueName(l.componentType.toLowerCase(),e),u=a+u}let c=(await this.createChildrenThenComponent({serializedComponent:l,componentName:u,ancestors:t,componentClass:e,shadow:n,namespaceForUnamed:a,componentsReplacementOf:i})).newComponent;o.push(c)}return{components:o}}async createChildrenThenComponent({serializedComponent:e,componentName:t,ancestors:n,componentClass:r,shadow:a=!1,namespaceForUnamed:i="/",componentsReplacementOf:o}){let s=e.children,l=[],u=[],c=[{componentName:t,componentClass:r},...n],p=this.parameterStack.parameters;this.parameterStack.push();let d=this.parameterStack.parameters;if(r.descendantCompositesMustHaveAReplacement&&!a?(d.compositesMustHaveAReplacement=!0,d.compositesDefaultReplacementType=r.descendantCompositesDefaultReplacementType):(!1===r.descendantCompositesMustHaveAReplacement||a)&&(d.compositesMustHaveAReplacement=!1),r.modifySharedParameters&&r.modifySharedParameters({sharedParameters:d,serializedComponent:e}),e.doenetAttributes.pushSharedParameters)for(let t of e.doenetAttributes.pushSharedParameters){let e=t.parameterName;d[e]=e in d?[...d[e]]:[],d[e].push(t.value)}if(e.doenetAttributes.addToSharedParameters)for(let t of e.doenetAttributes.addToSharedParameters){let e=t.parameterName;d[e]=e in d?Object.assign({},d[e]):{},d[e][t.key]=t.value}if(void 0!==s){if(r.preprocessSerializedChildren&&r.preprocessSerializedChildren({serializedChildren:s,attributes:e.attributes,componentName:t}),r.setUpVariant){let t=gatherVariantComponents({serializedComponents:s,componentInfoObjects:this.componentInfoObjects});r.setUpVariant({serializedComponent:e,sharedParameters:d,descendantVariantComponents:t})}if(r.keepChildrenSerialized){let t=new Set([]),n=r.keepChildrenSerialized({serializedComponent:e,componentInfoObjects:this.componentInfoObjects});for(let e of n){if(t.has(Number(e)))throw Error("Invalid instructions to keep children serialized from "+r.componentType+": child repeated");t.add(Number(e)),u.push(s[e])}let o=[];for(let[e,n]of s.entries())t.has(e)||o.push(n);if(o.length>0){l=(await this.createIsolatedComponentsSub({serializedComponents:o,ancestors:c,shadow:a,namespaceForUnamed:i})).components}}else{l=(await this.createIsolatedComponentsSub({serializedComponents:s,ancestors:c,shadow:a,namespaceForUnamed:i})).components}}let m={};if(e.attributes)for(let t in e.attributes){if(e.attributes[t].component){let n=await this.createIsolatedComponentsSub({serializedComponents:[e.attributes[t].component],ancestors:c,shadow:a,namespaceForUnamed:i,createNameContext:`attribute|${t}`});m[t]={component:n.components[0]}}else m[t]=e.attributes[t]}let f={};e.downstreamDependencies&&Object.assign(f,e.downstreamDependencies);let h=await this.createStateVariableDefinitions({componentClass:r,prescribedDependencies:f,componentName:t});delete this.updateInfo.deletedComponents[t],delete this.updateInfo.deletedStateVariables[t];let y=new r({componentName:t,ancestors:n,definingChildren:l,stateVariableDefinitions:h,serializedChildren:u,serializedComponent:e,attributes:m,componentInfoObjects:this.componentInfoObjects,coreFunctions:this.coreFunctions,flags:this.flags,shadow:a,numerics:this.numerics,sharedParameters:d,parentSharedParameters:p});this.registerComponent(y),o&&(y.replacementOf=o),e.adaptedFrom&&(y.adaptedFrom=this._components[e.adaptedFrom],y.adaptedFrom.adapterUsed=y);for(let e in f){let t=f[e];for(let n of t)if("referenceShadow"===n.dependencyType){let t={componentName:e};Object.assign(t,n),delete t.dependencyType,y.shadows=t;let r=this._components[e];if(r.shadowedBy||(r.shadowedBy=[]),r.shadowedBy.push(y),n.isPrimaryShadow&&(r.primaryShadow=y.componentName,this.dependencies.updateTriggers.primaryShadowDependencies[e]))for(let t of this.dependencies.updateTriggers.primaryShadowDependencies[e])await t.recalculateDownstreamComponents();break}}e.unlinkedCopySource&&(y.unlinkedCopySource=e.unlinkedCopySource),await this.deriveChildResultsFromDefiningChildren({parent:y,expandComposites:!1}),await this.initializeComponentStateVariables(y),await this.dependencies.setUpComponentDependencies(y);let b=await this.dependencies.checkForDependenciesOnNewComponent(t);for(let e of b)await this.markStateVariableAndUpstreamDependentsStale({component:this._components[e.componentName],varName:e.varName});return await this.checkForStateVariablesUpdatesForNewComponent(t),await this.dependencies.resolveStateVariablesIfReady({component:y}),await this.checkForActionChaining({component:y}),this.parameterStack.pop(),{newComponent:y}}async checkForStateVariablesUpdatesForNewComponent(e){if(e in this.updateInfo.stateVariableUpdatesForMissingComponents){let t=await this.processNewStateVariableValues({[e]:this.updateInfo.stateVariableUpdatesForMissingComponents[e]}),n=this._components[e];if(n.constructor.processWhenJustUpdatedForNewComponent||t.foundIgnore)for(let r in this.updateInfo.stateVariableUpdatesForMissingComponents[e])n.state[r]&&(this.updateInfo.stateVariablesToEvaluate.push({componentName:e,stateVariable:r}),n.state[r].justUpdatedForNewComponent=!0,t.foundIgnore&&(n.reprocessAfterEvaluate=this.updateInfo.stateVariableUpdatesForMissingComponents[e]));delete this.updateInfo.stateVariableUpdatesForMissingComponents[e]}}async deriveChildResultsFromDefiningChildren({parent:e,expandComposites:t=!0,forceExpandComposites:n=!1}){if(this.derivingChildResults||(this.derivingChildResults=[]),this.derivingChildResults.includes(e.componentName))return{success:!1,skipping:!0};this.derivingChildResults.push(e.componentName);let r=await this.expandCompositeOfDefiningChildren(e,e.definingChildren,t,n);e.unexpandedCompositesReady=r.unexpandedCompositesReady,e.unexpandedCompositesNotReady=r.unexpandedCompositesNotReady,e.activeChildren=e.definingChildren.slice(),e.allChildren={},e.allChildrenOrdered=[];for(let t=0;te.componentType)).join(", ");this.unmatchedChildren[e.componentName]={message:`invalid children of type(s): ${t}`}}await this.dependencies.addBlockersFromChangedActiveChildren({parent:e});let i=this.derivingChildResults.indexOf(e.componentName);return this.derivingChildResults.splice(i,1),e.constructor.renderChildren&&this.componentsWithChangedChildrenToRender.add(e.componentName),a}async expandCompositeOfDefiningChildren(e,t,n,r){let a=[],i=[];for(let o=0;o=n)break;if(!r||r.includes(a))if("object"==typeof i)!i.constructor.sendToRendererEvenIfHidden&&await i.stateValues.hidden||t.push(a);else{let n=!1;if(e.compositeReplacementActiveRange)for(let t of e.compositeReplacementActiveRange){let e=this._components[t.compositeName];if(await e.stateValues.hidden&&t.firstInd<=a&&t.lastInd>=a){n=!0;break}}n||t.push(a)}}return t}async substituteAdapter({parent:e,childInd:t,adapterIndUsed:n}){let r,a=e.activeChildren[t];r=a.componentName?a.getAdapter(n):{componentType:this.componentInfoObjects.allComponentClasses[a.componentType].getAdapterComponentType(n,this.componentInfoObjects.publicStateVariableInfo),placeholderInd:a.placeholderInd+"adapt"};let i=a.adapterUsed;if(void 0===i||i.componentType!==r.componentType)if(a.componentName){let t;t=e.attributes.newNamespace?.primitive?e.componentName+"/":getNamespaceFromName(e.componentName),r.adaptedFrom=a.componentName,i=(await this.createIsolatedComponentsSub({serializedComponents:[r],shadow:!0,ancestors:a.ancestors,createNameContext:a.componentName+"|adapter",namespaceForUnamed:t})).components[0]}else r.adaptedFrom=a,i=r;if(e.activeChildren.splice(t,1,i),a.componentName&&(delete e.allChildren[a.componentName].activeChildrenIndex,e.allChildren[i.componentName]={activeChildrenIndex:t,component:i}),a.componentName){let t=e.allChildrenOrdered.indexOf(a.componentName);e.allChildrenOrdered.splice(t+1,0,i.componentName)}else{let t=e.allChildrenOrdered.indexOf(a.placeholderInd);e.allChildrenOrdered.splice(t+1,0,i.placeholderInd)}}async expandCompositeComponent(e){if(!("readyToExpandWhenResolved"in e.state))throw Error(`Could not find state variable readyToExpandWhenResolved of composite ${e.componentName}`);if(!e.state.readyToExpandWhenResolved.isResolved)return this.updateInfo.compositesToExpand.add(e.componentName),{success:!1};if(this.updateInfo.compositesToExpand.delete(e.componentName),this.updateInfo.compositesBeingExpanded.push(e.componentName),e.parent){if(e.parent.unexpandedCompositesReady){let t=e.parent.unexpandedCompositesReady.indexOf(e.componentName);-1!==t&&e.parent.unexpandedCompositesReady.splice(t,1)}if(e.parent.unexpandedCompositesNotReady){let t=e.parent.unexpandedCompositesNotReady.indexOf(e.componentName);-1!==t&&e.parent.unexpandedCompositesNotReady.splice(t,1)}}if(e.shadows)return await this.expandShadowingComposite(e);let t=await e.constructor.createSerializedReplacements({component:this.components[e.componentName],components:this.components,workspace:e.replacementsWorkspace,componentInfoObjects:this.componentInfoObjects,flags:this.flags,resolveItem:this.dependencies.resolveItem.bind(this.dependencies),publicCaseInsensitiveAliasSubstitutions:this.publicCaseInsensitiveAliasSubstitutions.bind(this)});if(e.constructor.stateVariableToEvaluateAfterReplacements&&await e.stateValues[e.constructor.stateVariableToEvaluateAfterReplacements],!t.replacements)throw Error(`Invalid createSerializedReplacements of ${e.componentName}`);{let n=t.replacements;await this.createAndSetReplacements({component:e,serializedReplacements:n}),t.withholdReplacements&&(e.replacementsToWithhold=e.replacements.length)}let n=this.updateInfo.compositesBeingExpanded.indexOf(e.componentName);if(-1===n)throw Error(`Something is wrong as we lost track that we were expanding ${e.componentName}`);return this.updateInfo.compositesBeingExpanded.splice(n,1),{success:!0,compositesExpanded:[e.componentName]}}async expandShadowingComposite(e){if(this.updateInfo.compositesBeingExpanded.includes(e.shadows.componentName)){let t=this._components[e.shadows.componentName];for(;t.shadows;)t=this._components[t.shadows.componentName];throw Error(`Circular reference involving ${t.componentName}`)}let t=this._components[e.shadows.componentName],n=[];if(!t.isExpanded){let r=await this.expandCompositeComponent(t);if(!r.success)throw Error(`expand result of ${e.componentName} was not a success even though ready to expand.`);n.push(...r.compositesExpanded)}let r=[],a=await e.stateValues.sourceAttributesToIgnore,i=await e.stateValues.sourceAttributesToIgnoreRecursively;for(let e of t.replacements)"object"==typeof e?r.push(await e.serialize({sourceAttributesToIgnore:a,sourceAttributesToIgnoreRecursively:i})):r.push(e);let o=e.replacementsWorkspace.uniqueIdentifiersUsed=[],s=e.shadows.compositeName;r=postProcessCopy({serializedComponents:r,componentName:s,uniqueIdentifiersUsed:o});let l=e.attributes.newNamespace?.primitive;if(e.attributes.isResponse){let t=e.constructor.createAttributesObject();for(let n of r){if("object"!=typeof n)continue;n.attributes||(n.attributes={});let r=convertAttributesForComponentType({attributes:{isResponse:e.attributes.isResponse},componentType:n.componentType,componentInfoObjects:this.componentInfoObjects,compositeAttributesObj:t,compositeCreatesNewNamespace:l});Object.assign(n.attributes,r)}}if(e.constructor.assignNamesToReplacements){let n,a=this.components[s],i=a.attributes.newNamespace?.primitive,o=a.doenetAttributes.assignNames,u=o?.some(Array.isArray),c=a.attributes.assignNewNamespaces?.primitive,p=this._components[a.doenetAttributes.targetComponentName];p&&(n=!this.componentInfoObjects.isCompositeComponent({componentType:p.componentType,includeNonStandard:!1})&&p.attributes.newNamespace?.primitive);let d=!u&&(l||n||i&&!o||c),m=e.doenetAttributes.assignNames;if(m&&await e.stateValues.addLevelToAssignNames&&(m=m.map((e=>[e]))),r=processAssignNames({assignNames:m,serializedComponents:r,parentName:e.componentName,parentCreatesNewNamespace:l,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:d,shadowingComposite:!0}).serializedComponents,p?.componentName===t.componentName&&a.doenetAttributes.fromCopyTarget){let t=deepClone(a.serializedChildren);this.componentInfoObjects.allComponentClasses[e.componentType].includeBlankStringChildren||(t=t.filter((e=>"string"!=typeof e||""!==e.trim())));let n=processAssignNames({assignNames:m,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:a.attributes.assignNewNamespaces?.primitive,indOffset:r.length,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:!0});r.push(...n.serializedComponents)}}else{let t=l;r=processAssignNames({serializedComponents:r,parentName:e.componentName,parentCreatesNewNamespace:l,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:t,shadowingComposite:!0}).serializedComponents}r=(await verifyReplacementsMatchSpecifiedType({component:e,replacements:r,assignNames:e.doenetAttributes.assignNames,componentInfoObjects:this.componentInfoObjects,compositeAttributesObj:e.constructor.createAttributesObject(),flags:this.flags})).replacements,await this.createAndSetReplacements({component:e,serializedReplacements:r});let u=this.updateInfo.compositesBeingExpanded.indexOf(e.componentName);if(-1===u)throw Error(`Something is wrong as we lost track that we were expanding ${e.componentName}`);return this.updateInfo.compositesBeingExpanded.splice(u,1),n.push(e.componentName),{success:!0,compositesExpanded:n}}async createAndSetReplacements({component:e,serializedReplacements:t}){let n;this.parameterStack.push(e.sharedParameters,!1),n=e.attributes.newNamespace?.primitive?e.componentName+"/":getNamespaceFromName(e.componentName);let r=await this.createIsolatedComponentsSub({serializedComponents:t,ancestors:e.ancestors,shadow:!0,createNameContext:e.componentName+"|replacements",namespaceForUnamed:n,componentsReplacementOf:e});this.parameterStack.pop(),e.replacements=r.components,await this.dependencies.addBlockersFromChangedReplacements(e),e.isExpanded=!0}async replaceCompositeChildren(e){delete e.placeholderActiveChildrenIndices,delete e.placeholderActiveChildrenIndicesByComposite,delete e.compositeReplacementActiveRange;let t=0;for(let n=0;ne+n));e.placeholderActiveChildrenIndices||(e.placeholderActiveChildrenIndices=[]),e.placeholderActiveChildrenIndices.push(...s),e.placeholderActiveChildrenIndicesByComposite||(e.placeholderActiveChildrenIndicesByComposite={}),e.placeholderActiveChildrenIndicesByComposite[r.componentName]=s}else await this.markWithheldReplacementsInactive(r),a=r.replacements,r.replacementsToWithhold>0&&(a=a.slice(0,-r.replacementsToWithhold)),e.constructor.includeBlankStringChildren&&!e.constructor.removeBlankStringChildrenPostSugar||(a=a.filter((e=>"string"!=typeof e||/\S/.test(e))));e.compositeReplacementActiveRange||(e.compositeReplacementActiveRange=[]);for(let t of e.compositeReplacementActiveRange)t.lastInd>=n&&(t.lastInd+=a.length-1);e.compositeReplacementActiveRange.push({compositeName:r.componentName,target:await r.stateValues.target,firstInd:n,lastInd:n+a.length-1}),e.activeChildren.splice(n,1,...a),delete e.allChildren[r.componentName].activeChildrenIndex;for(let t=0;t"object"==typeof e)).map((e=>e.componentName?e.componentName:e.placeholderInd))),1!==a.length){let t=a.length-1;for(let r=n+a.length;r0&&(t-=e.replacementsToWithhold);for(let n of e.replacements.slice(0,t))await this.changeInactiveComponentAndDescendants(n,!1);for(let n of e.replacements.slice(t))await this.changeInactiveComponentAndDescendants(n,!0);if(!await e.stateValues.isInactiveCompositeReplacement){let t=e.componentName;this.updateInfo.inactiveCompositesToUpdateReplacements.includes(t)&&(this.updateInfo.inactiveCompositesToUpdateReplacements=this.updateInfo.inactiveCompositesToUpdateReplacements.filter((e=>e!=t)),this.updateInfo.compositesToUpdateReplacements.push(t))}}async changeInactiveComponentAndDescendants(e,t){if("object"==typeof e&&await e.stateValues.isInactiveCompositeReplacement!==t){e.state.isInactiveCompositeReplacement.value=t,await this.markUpstreamDependentsStale({component:e,varName:"isInactiveCompositeReplacement"}),this.dependencies.recordActualChangeInUpstreamDependencies({component:e,varName:"isInactiveCompositeReplacement"});for(let n in e.allChildren)await this.changeInactiveComponentAndDescendants(this._components[n],t);for(let n in e.attributes){let r=e.attributes[n].component;r&&await this.changeInactiveComponentAndDescendants(this._components[r.componentName],t)}e.replacements&&await this.markWithheldReplacementsInactive(e)}}findShadowedChildInSerializedComponents({serializedComponents:e,shadowedComponentName:t}){for(let n of e){if(n.originalName===t)return n;if(n.children){let e=this.findShadowedChildInSerializedComponents({serializedComponents:n.children,shadowedComponentName:t});if(e)return e}}}async createStateVariableDefinitions({componentClass:e,prescribedDependencies:t,componentName:n}){let r;if(t)for(let e in t){let a=t[e];for(let t of a)if("referenceShadow"===t.dependencyType){if(e===n)throw Error(`circular reference involving ${n}`);r={linkSource:"referenceShadow",targetName:e,compositeName:t.compositeName,propVariable:t.propVariable,arrayStateVariable:t.arrayStateVariable,arrayKey:t.arrayKey,ignorePrimaryStateVariable:t.ignorePrimaryStateVariable,substituteForPrimaryStateVariable:t.substituteForPrimaryStateVariable,firstLevelReplacement:t.firstLevelReplacement,additionalStateVariableShadowing:t.additionalStateVariableShadowing}}else"adapter"===t.dependencyType&&(r={linkSource:"adapter",adapterTargetIdentity:t.adapterTargetIdentity,adapterVariable:t.adapterVariable,substituteForPrimaryStateVariable:t.substituteForPrimaryStateVariable,stateVariablesToShadow:t.stateVariablesToShadow})}let a={};r||this.createAttributeStateVariableDefinitions({stateVariableDefinitions:a,componentClass:e});let i=e.returnNormalizedStateVariableDefinitions({attributeNames:Object.keys(a),numerics:this.numerics});return Object.assign(a,i),r&&("adapter"===r.linkSource?this.createAdapterStateVariableDefinitions({redefineDependencies:r,stateVariableDefinitions:a,componentClass:e}):await this.createReferenceShadowStateVariableDefinitions({redefineDependencies:r,stateVariableDefinitions:a,componentClass:e})),a}createAttributeStateVariableDefinitions({componentClass:e,stateVariableDefinitions:t}){let n=e.createAttributesObject();for(let r in n){let a=n[r];if(!a.createStateVariable)continue;let i,o=a.createStateVariable,s=t[o]={isAttribute:!0,hasEssential:!0},l=!a.createComponentOfType;if(a.public&&(s.public=!0,s.shadowingInstructions={},l?(s.shadowingInstructions.createComponentOfType=a.createPrimitiveOfType,"string"===s.shadowingInstructions.createComponentOfType?s.shadowingInstructions.createComponentOfType="text":"stringArray"===s.shadowingInstructions.createComponentOfType?s.shadowingInstructions.createComponentOfType="textList":"numberArray"===s.shadowingInstructions.createComponentOfType&&(s.shadowingInstructions.createComponentOfType="numberList")):s.shadowingInstructions.createComponentOfType=a.createComponentOfType),!l){let t=this.componentInfoObjects.allComponentClasses[a.createComponentOfType];if(!t)throw Error(`Component type ${a.createComponentOfType} does not exist so cannot create state variable for attribute ${r} of componentType ${e.componentType}.`);i=a.componentStateVariableForAttributeValue,void 0===i&&(i=t.stateVariableForAttributeValue,void 0===i&&(i="value"))}s.returnDependencies=function(){let e={};return a.fallBackToParentStateVariable&&(e.parentValue={dependencyType:"parentStateVariable",variableName:a.fallBackToParentStateVariable}),l?e.attributePrimitive={dependencyType:"attributePrimitive",attributeName:r}:e.attributeComponent={dependencyType:"attributeComponent",attributeName:r,variableNames:[i]},e},s.definition=function({dependencyValues:e,usedDefault:t}){let n;if(e.attributeComponent)n=e.attributeComponent.stateValues[i];else{if(void 0===e.attributePrimitive||null===e.attributePrimitive){return void 0!==e.parentValue&&null!==e.parentValue&&!t.parentValue?{setValue:{[o]:e.parentValue},checkForActualChange:{[o]:!0}}:{useEssentialOrDefaultValue:{[o]:!0},checkForActualChange:{[o]:!0}}}n=e.attributePrimitive}return n=validateAttributeValue({value:n,attributeSpecification:a,attribute:r}),{setValue:{[o]:n},checkForActualChange:{[o]:!0}}},a.noInverse||(s.inverseDefinition=async function({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n}){if(!t.attributeComponent){if(void 0!==t.attributePrimitive&&null!==t.attributePrimitive)return{success:!1};if(void 0!==t.parentValue&&null!==t.parentValue&&!n.parentValue)return{success:!0,instructions:[{setDependency:"parentValue",desiredValue:e[o]}]};{let t=validateAttributeValue({value:e[o],attributeSpecification:a,attribute:r});return{success:!0,instructions:[{setEssentialValue:o,value:t}]}}}return{success:!0,instructions:[{setDependency:"attributeComponent",desiredValue:e[o],variableIndex:0}]}});let u=["forRenderer","defaultValue","propagateToProps","triggerActionOnChange"];for(let e of u)e in a&&(s[e]=a[e])}}createAdapterStateVariableDefinitions({redefineDependencies:e,stateVariableDefinitions:t,componentClass:n}){let r=this._components[e.adapterTargetIdentity.componentName],a=n.createAttributesObject();for(let n in a){let i=a[n];if(!i.createStateVariable)continue;let o=i.createStateVariable,s=t[o]={isAttribute:!0,hasEssential:!0},l=!i.createComponentOfType;i.public&&(s.public=!0,s.shadowingInstructions={},l?(s.shadowingInstructions.createComponentOfType=i.createPrimitiveOfType,"string"===s.shadowingInstructions.createComponentOfType?s.shadowingInstructions.createComponentOfType="text":"stringArray"===s.shadowingInstructions.createComponentOfType?s.shadowingInstructions.createComponentOfType="textList":"numberArray"===s.shadowingInstructions.createComponentOfType&&(s.shadowingInstructions.createComponentOfType="numberList")):s.shadowingInstructions.createComponentOfType=i.createComponentOfType),o in r.state?s.returnDependencies=()=>({adapterTargetVariable:{dependencyType:"stateVariable",componentName:e.adapterTargetIdentity.componentName,variableName:o}}):s.returnDependencies=()=>({}),s.definition=function({dependencyValues:e,usedDefault:t}){return void 0===e.adapterTargetVariable||t.adapterTargetVariable?{useEssentialOrDefaultValue:{[o]:!0},checkForActualChange:{[o]:!0}}:{setValue:{[o]:e.adapterTargetVariable},checkForActualChange:{[o]:!0}}},i.noInverse||(s.inverseDefinition=async function({desiredStateVariableValues:e,dependencyValues:t}){return void 0===t.adapterTargetVariable?{success:!0,instructions:[{setEssentialValue:o,value:e[o]}]}:{success:!0,instructions:[{setDependency:"adapterTargetVariable",desiredValue:e[o]}]}});let u=["forRenderer","defaultValue","propagateToProps"];for(let e of u)e in i&&(s[e]=i[e])}let i="value";e.substituteForPrimaryStateVariable?i=e.substituteForPrimaryStateVariable:n.primaryStateVariableForDefinition&&(i=n.primaryStateVariableForDefinition);let o=t[i];o.returnDependencies=()=>({adapterTargetVariable:{dependencyType:"stateVariable",componentName:e.adapterTargetIdentity.componentName,variableName:e.adapterVariable}}),o.set?o.definition=function({dependencyValues:e}){return{setValue:{[i]:o.set(e.adapterTargetVariable)}}}:o.definition=function({dependencyValues:e}){return{setValue:{[i]:e.adapterTargetVariable}}},o.inverseDefinition=function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"adapterTargetVariable",desiredValue:e[i]}]}},e.stateVariablesToShadow&&this.modifyStateDefsToBeShadows({stateVariablesToShadow:e.stateVariablesToShadow,stateVariableDefinitions:t,targetComponent:r})}async createReferenceShadowStateVariableDefinitions({redefineDependencies:e,stateVariableDefinitions:t,componentClass:n}){let r=this._components[e.targetName];e.propVariable&&!r.state[e.propVariable]&&this.checkIfArrayEntry({stateVariable:e.propVariable,component:r})&&await this.createFromArrayEntry({stateVariable:e.propVariable,component:r});let a=n.createAttributesObject();for(let e in a){let r=a[e],i=r.createStateVariable;if(!i)continue;let o,s=t[i]={isAttribute:!0,hasEssential:!0},l=!r.createComponentOfType;if(r.public&&(s.public=!0,s.shadowingInstructions={},l?(s.shadowingInstructions.createComponentOfType=r.createPrimitiveOfType,"string"===s.shadowingInstructions.createComponentOfType?s.shadowingInstructions.createComponentOfType="text":"stringArray"===s.shadowingInstructions.createComponentOfType?s.shadowingInstructions.createComponentOfType="textList":"numberArray"===s.shadowingInstructions.createComponentOfType&&(s.shadowingInstructions.createComponentOfType="numberList")):s.shadowingInstructions.createComponentOfType=r.createComponentOfType),!l){let t=this.componentInfoObjects.allComponentClasses[r.createComponentOfType];if(!t)throw Error(`Component type ${r.createComponentOfType} does not exist so cannot create state variable for attribute ${e} of componentType ${n.componentType}.`);o=r.componentStateVariableForAttributeValue,void 0===o&&(o=t.stateVariableForAttributeValue,void 0===o&&(o="value"))}let u={};l?u.attributePrimitive={dependencyType:"attributePrimitive",attributeName:e}:u.attributeComponent={dependencyType:"attributeComponent",attributeName:e,variableNames:[o]},r.fallBackToParentStateVariable&&(u.parentValue={dependencyType:"parentStateVariable",variableName:r.fallBackToParentStateVariable}),s.returnDependencies=()=>u,s.definition=function({dependencyValues:t,usedDefault:n}){let a;if(t.attributeComponent)a=t.attributeComponent.stateValues[o];else{if(void 0===t.attributePrimitive||null===t.attributePrimitive){return void 0!==t.parentValue&&null!==t.parentValue&&!n.parentValue?{setValue:{[i]:t.parentValue},checkForActualChange:{[i]:!0}}:{useEssentialOrDefaultValue:{[i]:!0},checkForActualChange:{[i]:!0}}}a=t.attributePrimitive}return a=validateAttributeValue({value:a,attributeSpecification:r,attribute:e}),{setValue:{[i]:a},checkForActualChange:{[i]:!0}}},r.noInverse||(s.inverseDefinition=async function({desiredStateVariableValues:t,dependencyValues:n,stateValues:a,workspace:o}){if(!n.attributeComponent){if(void 0!==n.attributePrimitive&&null!==n.attributePrimitive)return{success:!1};if(void 0!==n.parentValue&&null!==n.parentValue&&!usedDefault.parentValue)return{success:!0,instructions:[{setDependency:"parentValue",desiredValue:t[i]}]};{let n=validateAttributeValue({value:t[i],attributeSpecification:r,attribute:e});return{success:!0,instructions:[{setEssentialValue:i,value:n}]}}}return{success:!0,instructions:[{setDependency:"attributeComponent",desiredValue:t[i],variableIndex:0}]}});let c=["forRenderer","defaultValue","propagateToProps"];for(let e of c)e in r&&(s[e]=r[e])}if(e.propVariable){if(!e.ignorePrimaryStateVariable){let a="value";e.substituteForPrimaryStateVariable?a=e.substituteForPrimaryStateVariable:n.primaryStateVariableForDefinition&&(a=n.primaryStateVariableForDefinition);let i=t[a];if(!i)throw e.substituteForPrimaryStateVariable?Error(`Invalid public state variable of componentType ${n.componentType}: substituteForPrimaryStateVariable ${e.substituteForPrimaryStateVariable} does not exist`):Error(`Cannot have a public state variable with componentType ${n.componentType} as the class doesn't have a primary state variable for definition`);i.isShadow=!0,i.returnDependencies=()=>({targetVariable:{dependencyType:"stateVariable",componentName:r.componentName,variableName:e.propVariable}});let o=!1;void 0!==r.state[e.propVariable].defaultValue&&(i.defaultValue=r.state[e.propVariable].defaultValue,i.set&&(i.defaultValue=i.set(i.defaultValue)),i.hasEssential=!0,o=!0),i.set?i.definition=function({dependencyValues:e,usedDefault:t}){let n=i.set(e.targetVariable);return o&&t.targetVariable?{useEssentialOrDefaultValue:{[a]:{defaultValue:n}},alwaysShadow:[a]}:{setValue:{[a]:n},alwaysShadow:[a]}}:i.definition=function({dependencyValues:e,usedDefault:t}){return o&&t.targetVariable?{useEssentialOrDefaultValue:{[a]:{defaultValue:e.targetVariable}},alwaysShadow:[a]}:{setValue:{[a]:e.targetVariable},alwaysShadow:[a]}},i.inverseDefinition=function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"targetVariable",desiredValue:e[a]}]}}}if(e.additionalStateVariableShadowing){let n=[],a=[];for(let t in e.additionalStateVariableShadowing)n.push(t),a.push(e.additionalStateVariableShadowing[t].stateVariableToShadow);this.modifyStateDefsToBeShadows({stateVariablesToShadow:n,stateVariableDefinitions:t,targetComponent:r,differentStateVariablesInTarget:a})}return}let i=!1;if("readyToExpandWhenResolved"in t){i=!0;let e=t.readyToExpandWhenResolved,n=e.returnDependencies.bind(e),a=e.definition;e.returnDependencies=function(e){let t=n(e);return t.targetReadyToExpandWhenResolved={dependencyType:"stateVariable",componentName:r.componentName,variableName:"readyToExpandWhenResolved"},t},e.definition=function(e){let t=a(e);return t.setValue&&t.setValue.readyToExpandWhenResolved&&(e.dependencyValues.targetReadyToExpandWhenResolved||(t.setValue.readyToExpandWhenResolved=!1)),t}}let o=[];for(let e in r.state){let t=r.state[e];(t.shadowVariable||t.isShadow)&&o.push(e)}this.modifyStateDefsToBeShadows({stateVariablesToShadow:o,stateVariableDefinitions:t,foundReadyToExpandWhenResolved:i,targetComponent:r})}modifyStateDefsToBeShadows({stateVariablesToShadow:e,stateVariableDefinitions:t,foundReadyToExpandWhenResolved:n,targetComponent:r,differentStateVariablesInTarget:a=[]}){let i={};for(let[o,s]of e.entries()){let l=t[s];if(void 0===l){if("__array_"!==s.slice(0,8))continue;l=t[s]={}}if(l.isShadow=!0,l.additionalStateVariablesDefined)for(let t of l.additionalStateVariablesDefined)e.includes(t)||(i[t]||(i[t]=[]),i[t].push(s));delete l.additionalStateVariablesDefined,n||delete l.stateVariablesDeterminingDependencies;let u=l.public&&l.shadowingInstructions.hasVariableComponentType;if(l.isArray)l.returnArrayDependenciesByKey=function({arrayKeys:e}){let t={};for(let n of e)t[n]={targetVariable:{dependencyType:"stateVariable",componentName:r.componentName,variableName:this.arrayVarNameFromArrayKey(n)}};let n={};return u&&(n.targetVariableComponentType={dependencyType:"stateVariableComponentType",componentName:r.componentName,variableName:s}),l.inverseShadowToSetEntireArray&&(n.targetArray={dependencyType:"stateVariable",componentName:r.componentName,variableName:s}),{globalDependencies:n,dependenciesByKey:t}},l.arrayDefinitionByKey=function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let e of n)"targetVariable"in t[e]?r[e]=t[e].targetVariable:r[e]=l.defaultValueByArrayKey?.(e);let a={setValue:{[s]:r},alwaysShadow:[s]};return"targetVariableComponentType"in e&&(a.setCreateComponentOfType={[s]:e.targetVariableComponentType}),a},l.inverseArrayDefinitionByKey=function({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,arraySize:r,initialChange:a}){if(l.inverseShadowToSetEntireArray)return{success:!0,instructions:[{setDependency:"targetArray",desiredValue:e[s],treatAsInitialChange:a}]};let i=[];for(let r in e[s])t[r]&&i.push({setDependency:n[r].targetVariable,desiredValue:e[s][r],shadowedVariable:!0});return{success:!0,instructions:i}};else{let e=()=>({});n&&(e=l.returnDependencies.bind(l));let t=a[o];t||(t=s),l.returnDependencies=function(n){let a=Object.assign({},e(n));return a.targetVariable={dependencyType:"stateVariable",componentName:r.componentName,variableName:t},u&&(a.targetVariableComponentType={dependencyType:"stateVariableComponentType",componentName:r.componentName,variableName:t}),a},l.definition=function({dependencyValues:e,usedDefault:t}){let n={alwaysShadow:[s]};return"targetVariableComponentType"in e&&(n.setCreateComponentOfType={[s]:e.targetVariableComponentType}),t.targetVariable&&"defaultValue"in l&&l.hasEssential?n.useEssentialOrDefaultValue={[s]:{defaultValue:e.targetVariable}}:n.setValue={[s]:e.targetVariable},n},l.excludeDependencyValuesInInverseDefinition=!0,l.inverseDefinition=function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"targetVariable",desiredValue:e[s],shadowedVariable:!0}]}}}}for(let e in i)this.modifyStateDefToDeleteVariableReferences({varNamesToDelete:i[e],stateDef:t[e]})}modifyStateDefToDeleteVariableReferences({varNamesToDelete:e,stateDef:t}){for(let n of e){let e=t.additionalStateVariablesDefined.indexOf(n);t.additionalStateVariablesDefined.splice(e,1)}let n=t.definition;t.definition=function(t){let r=n(t);for(let t in r)if(Array.isArray(r[t]))for(let n of e){let e=r[t].indexOf(n);-1!==e&&r[t].splice(e,1)}else for(let n of e)delete r[t][n];return r}}async initializeComponentStateVariables(e){for(let t in e.state)e.state[t].isAlias?(e.stateVarAliases||(e.stateVarAliases={}),e.stateVarAliases[t]=e.state[t].targetVariableName,delete e.state[t]):await this.initializeStateVariable({component:e,stateVariable:t})}async initializeStateVariable({component:e,stateVariable:t,arrayStateVariable:n,arrayEntryPrefix:r}){let a=this.getStateVariableValue;e.state[t]||(e.state[t]={});let i=e.state[t];if(i.isResolved=!1,Object.defineProperty(i,"value",{get:()=>a({component:e,stateVariable:t}),configurable:!0}),void 0!==r?await this.initializeArrayEntryStateVariable({stateVarObj:i,arrayStateVariable:n,arrayEntryPrefix:r,component:e,stateVariable:t}):i.isArray&&await this.initializeArrayStateVariable({stateVarObj:i,component:e,stateVariable:t}),i.triggerActionOnChange){let n=this.stateVariableChangeTriggers[e.componentName];n||(n=this.stateVariableChangeTriggers[e.componentName]={}),n[t]={action:i.triggerActionOnChange}}}async checkForActionChaining({component:e,stateVariables:t}){if(e){t||(t=Object.keys(e.state));for(let n of t){let t=e.state[n];if(t.chainActionOnActionOfStateVariableTargets){let r,a=t.chainActionOnActionOfStateVariableTargets,i=await t.value,o=this.originsOfActionsChangedToActions[e.componentName];o&&(r=o[n]),r||(r=[]);let s=[];if(Array.isArray(i)){s=[...i];for(let t of s){let i=r.indexOf(t);if(-1===i){let r=this.actionsChangedToActions[t];r||(r=this.actionsChangedToActions[t]=[]),r.push({componentName:e.componentName,actionName:a.triggeredAction,stateVariableDefiningChain:n,args:{}})}else r.splice(i,1)}}for(let t of r){let r=this.actionsChangedToActions[t];if(r){let a=[];for(let t of r)t.componentName===e.componentName&&t.stateVariableDefiningChain===n||a.push(t);this.actionsChangedToActions[t]=a}}s.length>0?(o||(o=this.originsOfActionsChangedToActions[e.componentName]={}),o[n]=s):o&&(delete o[n],0===Object.keys(o).length&&delete this.originsOfActionsChangedToActions[e.componentName])}}}}async initializeArrayEntryStateVariable({stateVarObj:e,arrayStateVariable:t,arrayEntryPrefix:n,component:r,stateVariable:a}){e.isArrayEntry=!0,e.arrayStateVariable=t;let i=r.state[t];if(e.definition=i.definition,e.inverseDefinition=i.inverseDefinition,e.markStale=i.markStale,e.freshnessInfo=i.freshnessInfo,e.getPreviousDependencyValuesForMarkStale=i.getPreviousDependencyValuesForMarkStale,e.provideEssentialValuesInDefinition=i.provideEssentialValuesInDefinition,e.providePreviousValuesInDefinition=i.providePreviousValuesInDefinition,e.nDimensions=i.returnEntryDimensions(n),e.entryPrefix=n,e.varEnding=a.slice(n.length),i.createWorkspace&&(e.createWorkspace=!0,e.workspace=i.workspace),i.basedOnArrayKeyStateVariables&&(e.basedOnArrayKeyStateVariables=!0),i.additionalStateVariablesDefined){e.additionalStateVariablesDefined=[];let t=i.entryPrefixes.indexOf(n);for(let n of i.additionalStateVariablesDefined){let a=r.state[n];if(a.isArray){let n=a.entryPrefixes[t]+e.varEnding;e.additionalStateVariablesDefined.push(n)}else e.additionalStateVariablesDefined.push(n)}}if(i.shadowingInstructions&&(e.shadowingInstructions={},e.wrappingComponents=i.shadowingInstructions.returnWrappingComponents(n),i.shadowingInstructions.attributesToShadow&&(e.shadowingInstructions.attributesToShadow=i.shadowingInstructions.attributesToShadow),i.shadowingInstructions.createComponentOfType)){let t=i.entryPrefixes.indexOf(n);i.shadowingInstructions.createComponentOfType[t]&&(e.shadowingInstructions.createComponentOfType=[i.shadowingInstructions.createComponentOfType[t]])}if(i.getEntryValues?e.getValueFromArrayValues=async function(){return await i.getEntryValues({varName:a})}:e.getValueFromArrayValues=async function(){let t=await e.arrayKeys;if(0===t.length)return;let n=[];for(let e of t)n.push(i.getArrayValue({arrayKey:e}));return 1===n.length?n[0]:n},e.arraySizeStateVariable=i.arraySizeStateVariable,e._arrayKeys=[],e._unflattenedArrayKeys=[],Object.defineProperty(e,"arrayKeys",{get:function(){return(async()=>(await i.arraySize,e._arrayKeys))()}}),Object.defineProperty(e,"unflattenedArrayKeys",{get:function(){return(async()=>(await i.arraySize,e._unflattenedArrayKeys))()}}),r.state[e.arraySizeStateVariable].initiallyResolved){let t=await i.arraySize,n=i.getArrayKeysFromVarName({arrayEntryPrefix:e.entryPrefix,varEnding:e.varEnding,arraySize:t,nDimensions:i.nDimensions});e._unflattenedArrayKeys=n,e._arrayKeys=flattenDeep(n);let r=i.varNamesIncludingArrayKeys;for(let t of e._arrayKeys)r[t]||(r[t]=[]),r[t].push(a)}if(i.arrayEntryNames.push(a),Object.defineProperty(e,"arraySize",{get:()=>i.arraySize}),Object.defineProperty(e,"arrayEntrySize",{get:function(){return(async()=>{let t=[],n=[await e.unflattenedArrayKeys];for(let r=0;r1?(e.keyToIndex=e=>e.split(",").map((e=>Number(e))),e.setArrayValue=function({value:t,arrayKey:n,arraySize:r,arrayValues:a=e.arrayValues}){let i=e.keyToIndex(n),o=i.length;if(!o>e.nDimensions)return console.warn("Cannot set array value. Number of dimensions is too large."),{nFailures:1};let s=a,l=r;for(let c of i.slice(0,i.length-1)){if(!(c>=0&&ca&&(console.warn("ignoring array values of out bounds"),r+=e.length-a,e=e.slice(0,a)),1===n.length)for(let[n,r]of e.entries())t[n]=r;else for(let[a,i]of e.entries()){t[a]||(t=[]),r+=p(i,t[a],n[a]).nFailures}return{nFailures:r}}u+=p(t,s,l).nFailures}else s[i[i.length-1]]=t;return{nFailures:u}},e.getArrayValue=function({arrayKey:t,arrayValues:n=e.arrayValues}){let r=e.keyToIndex(t),a=n;for(let e of r.slice(0,r.length-1))if(a=a[e],!a)return;return a[r[r.length-1]]},e.getAllArrayKeys||(e.getAllArrayKeys=function(e,t=!0,n){function r(e,t){for(let[n,a]of e.entries())Array.isArray(a)?r(a,t):e[n]=t+","+a}function a(e){if(1===e.length)return Array.from(Array(e[0]),((e,t)=>String(t)));{let n=e[0],i=a(e.slice(1)),o=[];for(let e=0;ee+","+t)));else{let t=deepClone(i);r(t,e),o.push(t)}return o}}return n?0===n.length?[]:a(n):e&&0!==e.length?a(e):[]}),e.arrayVarNameFromArrayKey||(e.arrayVarNameFromArrayKey=function(e){return r[0]+e.split(",").map((e=>Number(e)+1)).join("_")}),e.arrayVarNameFromPropIndex||(e.arrayVarNameFromPropIndex=function(t,n){return r[0]+[...t.map((e=>Math.round(Number(e)))),...Array(e.nDimensions-t.length).fill(1)].join("_")}),e.adjustArrayToNewArraySize=async function(){let t=await e.arraySize;!function e(t,n){if(t.length=n[0],n.length>1){let r=n.slice(1);for(let[n,a]of t.entries())a||(a=t[n]=[]),e(a,r)}}(e.arrayValues,t)}):(e.keyToIndex=e=>Number(e),e.setArrayValue=function({value:t,arrayKey:r,arraySize:a,arrayValues:i=e.arrayValues}){let o=e.keyToIndex(r);return o>=0&&oString(t))):e&&0!==e.length?Array.from(Array(e[0]),((e,t)=>String(t))):[]}),e.arrayVarNameFromArrayKey||(e.arrayVarNameFromArrayKey=function(e){return r[0]+String(Number(e)+1)}),e.arrayVarNameFromPropIndex||(e.arrayVarNameFromPropIndex=function(e,t){return r[0]+e[0]}),e.adjustArrayToNewArraySize=async function(){let t=await e.arraySize;e.arrayValues.length=t[0]}),e.getArrayKeysFromVarName||(e.getArrayKeysFromVarName=returnDefaultGetArrayKeysFromVarName(e.nDimensions)),e.indexToKey=e=>String(e);let r=e.entryPrefixes;r||(r=e.entryPrefixes=[n]),t.arrayEntryPrefixes||(t.arrayEntryPrefixes={});for(let e of r)t.arrayEntryPrefixes[e]=n;e.returnEntryDimensions||(e.returnEntryDimensions=()=>1),e.shadowingInstructions&&(e.shadowingInstructions.returnWrappingComponents||(e.shadowingInstructions.returnWrappingComponents=e=>[]),e.wrappingComponents=e.shadowingInstructions.returnWrappingComponents()),e.usedDefaultByArrayKey={},e.arrayEntryNames=[],e.varNamesIncludingArrayKeys={};let a=[n];function i(t,n,r){let a={},i={};for(let n of e.dependencyNames.global)a[n]=t[n],i[n]=r[n];let o={},s={},l={};for(let a of n)if(o[a]={},s[a]={},a in e.dependencyNames.namesByKey){l[a]=!0;for(let n in e.dependencyNames.namesByKey[a]){let i=e.dependencyNames.namesByKey[a][n];i in t?(o[a][n]=t[i],s[a][n]=r[i]):l[a]=!1}}return{globalDependencyValues:a,globalUsedDefault:i,dependencyValuesByKey:o,usedDefaultByKey:s,foundAllDependencyValuesForKey:l}}if(e.additionalStateVariablesDefined&&a.push(...e.additionalStateVariablesDefined),e.returnDependencies=async function(n){n.arraySize=await e.arraySize;for(let e in n.stateValues)"__array_"===e.slice(0,8)&&delete n.stateValues[e];if(void 0===n.arrayKeys&&(n.arrayKeys=e.getAllArrayKeys(n.arraySize)),!e.dependencyNames&&(e.dependencyNames={namesByKey:{},keysByName:{},global:[]},e.additionalStateVariablesDefined))for(let n of e.additionalStateVariablesDefined)t.state[n].dependencyNames=e.dependencyNames;let r={};if(e.basedOnArrayKeyStateVariables&&n.arrayKeys.length>1)for(let e of n.arrayKeys)for(let n of a){let a=t.state[n];r[n+"_"+e]={dependencyType:"stateVariable",variableName:a.arrayVarNameFromArrayKey(e)}}else{let t=e.returnArrayDependenciesByKey(n);t.globalDependencies&&(e.dependencyNames.global=Object.keys(t.globalDependencies),Object.assign(r,t.globalDependencies)),t.dependenciesByKey||(t.dependenciesByKey={});for(let a of n.arrayKeys){a in e.dependencyNames.namesByKey||(n.changedDependency=!0),e.dependencyNames.namesByKey[a]={};for(let n in t.dependenciesByKey[a]){let i="__"+a+"_"+n;r[i]=t.dependenciesByKey[a][n],e.dependencyNames.namesByKey[a][n]=i,e.dependencyNames.keysByName[i]||(e.dependencyNames.keysByName[i]=[]),e.dependencyNames.keysByName[i].includes(a)||e.dependencyNames.keysByName[i].push(a)}}e.dependencyNames.global.push("__array_size")}return r.__array_size={dependencyType:"stateVariable",variableName:e.arraySizeStateVariable},r},e.getCurrentFreshness=function({freshnessInfo:t,arrayKeys:r,arraySize:a}){void 0===r&&(r=e.getAllArrayKeys(a));let i=t.freshByKey,o=t.freshArraySize?1:0;for(let e of r)i[e]&&(o+=1);return o>0?o===r.length+1?{fresh:{[n]:!0}}:{partiallyFresh:{[n]:o}}:{fresh:{[n]:!1}}},e.markStale=function({freshnessInfo:t,changes:r,arrayKeys:a,arraySize:i}){let o={};void 0===a&&(a=e.getAllArrayKeys(i)),e.markStaleByKey&&(o=e.markStaleByKey({arrayKeys:a,changes:r}));let s=t.freshByKey;if(r.__array_size)return t.freshArraySize=!1,t.freshByKey={},o.fresh={[n]:!1},o;if(0===Object.keys(s).length)return t.freshByKey={},t.freshArraySize?(o.partiallyFresh={[n]:1},o):(o.fresh={[n]:!1},o);for(let i in r){if(e.dependencyNames.global.includes(i))return t.freshByKey={},t.freshArraySize?(o.partiallyFresh={[n]:1},o):(o.fresh={[n]:!1},o);if(e.basedOnArrayKeyStateVariables&&a.length>1)delete s[i];else for(let t of e.dependencyNames.keysByName[i])delete s[t]}let l=t.freshArraySize?1:0;for(let e of a)s[e]&&(l+=1);return l>0?l===a.length+1?(o.fresh={[n]:!0},o):(o.partiallyFresh={[n]:l},o):(o.fresh={[n]:!1},o)},e.freshenOnNoChanges=function({arrayKeys:t,freshnessInfo:n,arraySize:r}){let a=n.freshByKey;void 0===t&&(t=e.getAllArrayKeys(r));for(let e of t)a[e]=!0},e.definition=function(r){if(void 0===r.arrayKeys&&(r.arrayKeys=e.getAllArrayKeys(r.arraySize)),e.basedOnArrayKeyStateVariables&&r.arrayKeys.length>1)return{};{let a=i(r.dependencyValues,r.arrayKeys,r.usedDefault),o=a.globalDependencyValues,s=a.globalUsedDefault,l=a.dependencyValuesByKey,u=a.usedDefaultByKey,c=a.foundAllDependencyValuesForKey;delete r.dependencyValues,r.globalDependencyValues=o,r.globalUsedDefault=s,r.dependencyValuesByKey=l,r.usedDefaultByKey=u;let p,d=[],m=r.freshnessInfo.freshByKey;for(let e of r.arrayKeys)!m[e]&&c[e]&&(m[e]=!0,d.push(e));if(0===d.length)p={};else{if(r.arrayKeys=d,!e.arrayDefinitionByKey)throw Error(`For ${n} of ${t.componentType}, arrayDefinitionByKey must be a function`);if(p=e.arrayDefinitionByKey(r),p.setValue&&p.setValue[n])for(let e in p.setValue[n])m[e]=!0;if(p.useEssentialOrDefaultValue&&p.useEssentialOrDefaultValue[n])for(let e in p.useEssentialOrDefaultValue[n])m[e]=!0}if(!r.freshnessInfo.freshArraySize){if(r.changes.__array_size&&(p.arraySizeChanged=[n],e.additionalStateVariablesDefined))for(let n of e.additionalStateVariablesDefined)t.state[n].isArray&&p.arraySizeChanged.push(n);r.freshnessInfo.freshArraySize=!0}return p}},e.inverseDefinition=function(t){if(!e.inverseArrayDefinitionByKey)return{success:!1};if(void 0===t.arrayKeys&&(t.arrayKeys=e.getAllArrayKeys(t.arraySize)),e.basedOnArrayKeyStateVariables&&t.arrayKeys.length>1){let e=[];for(let n of a)for(let r in t.desiredStateVariableValues[n]){let a=n+"_"+r;a in t.dependencyValues&&e.push({setDependency:a,desiredValue:t.desiredStateVariableValues[n][r],treatAsInitialChange:t.initialChange})}return{success:!0,instructions:e}}{let n=i(t.dependencyValues,t.arrayKeys,t.usedDefault),r=n.globalDependencyValues,a=n.globalUsedDefault,o=n.dependencyValuesByKey,s=n.usedDefaultByKey;return delete t.dependencyValues,t.globalDependencyValues=r,t.globalUsedDefault=a,t.dependencyValuesByKey=o,t.usedDefaultByKey=s,t.dependencyNamesByKey=e.dependencyNames.namesByKey,e.inverseArrayDefinitionByKey(t)}},await this.createArraySizeStateVariable({stateVarObj:e,component:t,stateVariable:n}),e.arraySizeStale=!0,e.previousArraySize=[],Object.defineProperty(e,"arraySize",{get:function(){return(async()=>t.state[e.arraySizeStateVariable].initiallyResolved?(e.arraySizeStale&&await e.recalculateArraySizeDependentQuantities(),await t.stateValues[e.arraySizeStateVariable]):[])()}}),e.recalculateArraySizeDependentQuantities=async function(){let n=await t.stateValues[e.arraySizeStateVariable];if(e.previousArraySize.length!==n.length||e.previousArraySize.some(((e,t)=>e!=n[t]))){e.previousArraySize=[...n];let r=e.varNamesIncludingArrayKeys={};for(let a of e.arrayEntryNames){let i=t.state[a],o=e.getArrayKeysFromVarName({arrayEntryPrefix:i.entryPrefix,varEnding:i.varEnding,arraySize:n,nDimensions:e.nDimensions});i._unflattenedArrayKeys=o,i._arrayKeys=flattenDeep(o);for(let e of i._arrayKeys)r[e]||(r[e]=[]),r[e].push(a)}}e.arraySizeStale=!1},!e.freshnessInfo&&(e.freshnessInfo={freshByKey:{}},e.additionalStateVariablesDefined))for(let n of e.additionalStateVariablesDefined)t.state[n]||(t.state[n]={}),t.state[n].freshnessInfo=e.freshnessInfo}async createArraySizeStateVariable({stateVarObj:e,component:t,stateVariable:n}){let r=[n];e.additionalStateVariablesDefined&&r.push(...e.additionalStateVariablesDefined),r.sort();let a="__array_size_"+r.join("_");if(e.arraySizeStateVariable=a,e.stateVariablesDeterminingDependencies?(e.stateVariablesDeterminingDependencies,e.stateVariablesDeterminingDependencies.push(a)):e.stateVariablesDeterminingDependencies=[a],t.state[a]){if(t.state[a].isShadow){t.state[a].markStale=function(){for(let e of r)t.state[e].arraySizeStale=!0;return{}}}}else t.state[a]={returnDependencies:e.returnArraySizeDependencies,definition({dependencyValues:t}){let n=e.returnArraySize({dependencyValues:t});for(let[e,t]of n.entries())Number.isInteger(t)&&t>=0||(n[e]=0);return{setValue:{[a]:n}}},markStale(){for(let e of r)t.state[e].arraySizeStale=!0;return{}}},e.stateVariablesDeterminingArraySizeDependencies&&(t.state[a].stateVariablesDeterminingDependencies=e.stateVariablesDeterminingArraySizeDependencies),await this.initializeStateVariable({component:t,stateVariable:a})}async arrayEntryNamesFromPropIndex({stateVariables:e,component:t,propIndex:n}){let r=[];for(let a of e){let e,i=t.state[a];if(!i){if(!this.checkIfArrayEntry({stateVariable:a,component:t})){r.push(a);continue}await this.createFromArrayEntry({stateVariable:a,component:t}),i=t.state[a]}if(i.isArray)e=i.arrayVarNameFromPropIndex(n,a);else if(i.isArrayEntry){e=t.state[i.arrayStateVariable].arrayVarNameFromPropIndex(n,a)}else console.warn(`Cannot get propIndex from ${a} of ${t.componentName} as it is not an array or array entry state variable`),e=a;e?r.push(e):(console.warn(`Cannot get propIndex from ${a} of ${t.componentName}`),r.push(a))}return r}recursivelyReplaceCompositesWithReplacements({replacements:e,recurseNonStandardComposites:t=!1,forceExpandComposites:n=!1,includeWithheldReplacements:r=!1}){let a=[],i=[],o=[],s=[];for(let l of e)if(this.componentInfoObjects.isCompositeComponent({componentType:l.componentType,includeNonStandard:t}))if(a.push(l.componentName),l.isExpanded||(l.state.readyToExpandWhenResolved.isResolved?o.push(l.componentName):s.push(l.componentName)),l.isExpanded){let e=l.replacements;!r&&l.replacementsToWithhold>0&&(e=e.slice(0,-l.replacementsToWithhold));let u=this.recursivelyReplaceCompositesWithReplacements({replacements:e,recurseNonStandardComposites:t,forceExpandComposites:n,includeWithheldReplacements:r});a.push(...u.compositesFound),i.push(...u.newReplacements),o.push(...u.unexpandedCompositesReady),s.push(...u.unexpandedCompositesNotReady)}else i.push(l);else i.push(l);return{compositesFound:a,newReplacements:i,unexpandedCompositesReady:o,unexpandedCompositesNotReady:s}}async getStateVariableValue({component:e,stateVariable:t}){let n=e.state[t];if(!n)throw Error(`Can't get value of ${t} of ${e.componentName} as it doesn't exist.`);if(e.reprocessAfterEvaluate){let t=e.reprocessAfterEvaluate;delete this._components[e.componentName].reprocessAfterEvaluate;for(let n in t)e.state[n]&&await this.getStateVariableValue({component:e,stateVariable:n});await this.processNewStateVariableValues({[e.componentName]:t})}let r=n.additionalStateVariablesDefined,a=[t];r&&a.push(...r);let i=!1;for(let n of a){if(!e.state[n].isResolved){if(!(await this.dependencies.resolveItem({componentName:e.componentName,type:"stateVariable",stateVariable:n,force:!0})).success)throw Error(`Can't get value of ${t} of ${e.componentName} as ${n} couldn't be resolved.`)}e.state[n].justUpdatedForNewComponent&&(delete this._components[e.componentName].state[n].justUpdatedForNewComponent,i=!0)}let o=await this.getStateVariableDefinitionArguments({component:e,stateVariable:t});o.componentInfoObjects=this.componentInfoObjects,o.justUpdatedForNewComponent=i,o.freshnessInfo=n.freshnessInfo;let s,l=o.arraySize;if(0!==Object.keys(o.changes).length||void 0===n._previousValue||n.forceRecalculation)delete n.forceRecalculation,s=n.definition(o);else{let e=[t];r&&e.push(...r),s={noChanges:e},n.freshenOnNoChanges&&n.freshenOnNoChanges(o)}let u={[t]:!1},c={};if(r)for(let e of r)u[e]=!1;for(let n in s.setValue){if(!(n in e.state))throw Error(`Definition of state variable ${t} of ${e.componentName} returned value of ${n}, which isn't a state variable.`);let r;if(n in u)u[n]=!0,e.state[n].isArray?c[n]||(c[n]={arrayKeysChanged:{}}):c[n]=!0;else{if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t,u[t]=!0,c[t]=!0;break}if(!r)throw Error(`Attempting to set value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}if(!(e.state[n].isResolved||r&&e.state[r].isResolved))throw Error(`Attempting to set value of stateVariable ${n} of ${e.componentName} while it is still unresolved!`);if(e.state[n].isArray){c[n]||(c[n]={arrayKeysChanged:{}});let t={};s.checkForActualChange&&s.checkForActualChange[n]&&(t=s.checkForActualChange[n]);for(let r in s.setValue[n])if(t[r]){e.state[n].getArrayValue({arrayKey:r})!==s.setValue[n][r]&&(e.state[n].setArrayValue({value:s.setValue[n][r],arrayKey:r,arraySize:l}),e.state[n].usedDefaultByArrayKey[r]=!1,c[n].arrayKeysChanged[r]=!0)}else e.state[n].setArrayValue({value:s.setValue[n][r],arrayKey:r,arraySize:l}),e.state[n].usedDefaultByArrayKey[r]=!1,c[n].arrayKeysChanged[r]=!0}else if(delete e.state[n].value,e.state[n].value=s.setValue[n],delete e.state[n].usedDefault,s.checkForActualChange?.[n]){let t=e.state[n].value,r=e.state[n]._previousValue;(t===r||Array.isArray(t)&&Array.isArray(r)&&t.length===r.length&&t.every(((e,t)=>e===r[t])))&&delete c[n]}}for(let n in s.useEssentialOrDefaultValue){if(!(n in e.state))throw Error(`Definition of state variable ${t} of ${e.componentName} requested essential or default value of ${n}, which isn't a state variable.`);if(!e.state[n].hasEssential)throw Error(`Definition of state variable ${t} of ${e.componentName} requested essential or default value of ${n}, but hasEssential is not set.`);let r;if(n in u)u[n]=!0,e.state[n].isArray?c[n]||(c[n]={arrayKeysChanged:{}}):c[n]=!0;else{if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t,u[t]=!0,c[t]=!0;break}if(!r)throw Error(`Attempting to set value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}if(!(e.state[n].isResolved||r&&e.state[r].isResolved))throw Error(`Attempting to set value of stateVariable ${n} of ${e.componentName} while it is still unresolved!`);let a=n;e.state[n].essentialVarName&&(a=e.state[n].essentialVarName);let i=e.essentialState[a];if(e.state[n].isArray){c[n]||(c[n]={arrayKeysChanged:{}});let t={};s.checkForActualChange&&s.checkForActualChange[n]&&(t=s.checkForActualChange[n]);for(let r in s.useEssentialOrDefaultValue[n]){let o,u;if(t[r]&&(o=e.state[n].getArrayValue({arrayKey:r})),Array.isArray(i)?u=e.state[n].getArrayValue({arrayKey:r,arrayValues:i}):i=e.essentialState[a]=[],void 0!==u)e.state[n].setArrayValue({value:u,arrayKey:r,arraySize:l});else{let t=s.useEssentialOrDefaultValue[n][r].defaultValue;if(void 0!==t)e.state[n].setArrayValue({value:t,arrayKey:r,arraySize:l}),e.state[n].usedDefaultByArrayKey[r]=!0;else{if(void 0===e.state[n].defaultValueByArrayKey?.(r))throw Error(`Neither value nor default value specified; state variable: ${n}, component: ${e.componentName}, arrayKey: ${r}.`);e.state[n].setArrayValue({value:e.state[n].defaultValueByArrayKey(r),arrayKey:r,arraySize:l}),e.state[n].usedDefaultByArrayKey[r]=!0}}if(t[r]){e.state[n].getArrayValue({arrayKey:r})!==o&&(c[n].arrayKeysChanged[r]=!0)}else c[n].arrayKeysChanged[r]=!0}}else{if(void 0!==i)delete e.state[n].value,e.state[n].value=i;else{let t=s.useEssentialOrDefaultValue[n].defaultValue;if(void 0!==t)delete e.state[n].value,e.state[n].value=t,e.state[n].usedDefault=!0;else{if(void 0===e.state[n].defaultValue)throw Error(`Neither value nor default value specified; state variable: ${n}, component: ${e.componentName}.`);delete e.state[n].value,e.state[n].value=e.state[n].defaultValue,e.state[n].usedDefault=!0}}if(s.checkForActualChange?.[n]){let t=e.state[n].value,r=e.state[n]._previousValue;(t===r||Array.isArray(t)&&Array.isArray(r)&&t.length===r.length&&t.every(((e,t)=>e===r[t])))&&delete c[n]}}}for(let n in s.markAsUsedDefault){if(!e.state[n].isResolved)throw Error(`Marking state variable as used default when it isn't yet resolved: ${n} of ${e.componentName}`);if(!(n in u)){let r;if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t;break}if(!r)throw Error(`Marking state variable ${n} as used default in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}if(Array.isArray())for(let t in s.markAsUsedDefault[n])s.markAsUsedDefault[n][t]&&(e.state[n].usedDefaultByArrayKey[t]=!0);else s.markAsUsedDefault[n]&&(e.state[n].usedDefault=!0)}if(s.noChanges)for(let n of s.noChanges){if(e.state[n].isResolved||(e.state[n].isResolved=!0),!(n in u)){let r;if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t;break}if(!r)throw Error(`Claiming stateVariable ${n} is unchanged in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}u[n]=!0,(Object.getOwnPropertyDescriptor(e.state[n],"value").get||e.state[n].immutable)&&(delete e.state[n].value,e.state[n].value=e.state[n]._previousValue)}for(let n in s.setEssentialValue){if(!(n in e.state))throw Error(`Definition of state variable ${t} of ${e.componentName} tried to make ${n} essential, which isn't a state variable.`);if(!(n in u)){let r;if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t;break}if(!r)throw Error(`Attempting to set essential value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}if(!e.state[n].hasEssential)throw Error(`Attempting to set the essential value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it does not have an essential value`);if(!e.state[n].shadowVariable&&!e.state[n].doNotShadowEssential)throw Error(`Attempting to set the essential value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it is not allowed unless the state variable is shadowed or the essential state is not shadowed.`);this.essentialValuesSavedInDefinition[e.componentName]||(this.essentialValuesSavedInDefinition[e.componentName]={});let r=n;if(e.state[n].essentialVarName&&(r=e.state[n].essentialVarName),e.state[n].isArray){let t=e.essentialState[r];Array.isArray(t)||(t=e.essentialState[r]=[]),this.essentialValuesSavedInDefinition[e.componentName][n]||(this.essentialValuesSavedInDefinition[e.componentName][n]={mergeObject:!0});for(let r in s.setEssentialValue[n])e.state[n].setArrayValue({value:s.setEssentialValue[n][r],arrayKey:r,arraySize:l,arrayValues:t}),this.essentialValuesSavedInDefinition[e.componentName][n][r]=s.setEssentialValue[n][r]}else e.essentialState[r]=s.setEssentialValue[n],this.essentialValuesSavedInDefinition[e.componentName][n]=s.setEssentialValue[n]}if(s.setCreateComponentOfType)for(let t in s.setCreateComponentOfType){if(!e.state[t].shadowingInstructions?.hasVariableComponentType)throw Error(`Cannot set type of ${t} of ${e.componentName} as it it does not have the hasVariableComponentType attribute.`);let n=!1,r=e.state[t].shadowingInstructions;r||(r=e.state[t].shadowingInstructions={});let a=r.createComponentOfType,i=s.setCreateComponentOfType[t];if(Array.isArray(a)?Array.isArray(i)?(a.length!==i.length||a.some(((e,t)=>e!=i[t])))&&(n=!0):n=!0:n=!!Array.isArray(i)||a!==i,n&&(c[t]=!0),r.createComponentOfType=s.setCreateComponentOfType[t],e.state[t].isArray&&e.state[t].arrayEntryNames){let n=s.setCreateComponentOfType[t],r=Array.isArray(n);for(let a of e.state[t].arrayEntryNames)if(r){let r=await e.state[a].arrayKeys,i=[];for(let a of r){let r=e.state[t].keyToIndex(a);i.push(n[r])}e.state[a].shadowingInstructions.createComponentOfType=i}else e.state[a].shadowingInstructions.createComponentOfType=n}}if(s.arraySizeChanged)for(let t of s.arraySizeChanged)await e.state[t].adjustArrayToNewArraySize(),void 0===c[t]?c[t]={arrayKeysChanged:{}}:!0===c[t]&&(c[t]={allArrayKeysChanged:!0,arrayKeysChanged:{}}),c[t].arraySizeChanged=!0;for(let n in u){if(!(u[n]||e.state[n].isArrayEntry||e.state[n].isArray))throw Error(`definition of ${t} of ${e.componentName} didn't return value of ${n}`);e.state[n].isArray?(delete e.state[n].value,e.state[n].value=e.state[n].arrayValues):e.state[n].isArrayEntry&&(delete e.state[n].value,e.state[n].value=await e.state[n].getValueFromArrayValues())}for(let t in c)if(this.dependencies.recordActualChangeInUpstreamDependencies({component:e,varName:t,changes:c[t]}),e.state[t].isArray){let n=[];if(!0===c[t]||c[t].allArrayKeysChanged||c.arraySizeChanged)e.state[t].arrayEntryNames&&(n=e.state[t].arrayEntryNames);else{let r=e.state[t].varNamesIncludingArrayKeys;for(let e in c[t].arrayKeysChanged){let t=r[e];t&&n.push(...t)}}n=[...new Set(n)];for(let t of n)this.dependencies.recordActualChangeInUpstreamDependencies({component:e,varName:t})}return await n.value}async getStateVariableDefinitionArguments({component:e,stateVariable:t,excludeDependencyValues:n}){let r;r=n?{}:await this.dependencies.getStateVariableDependencyValues({component:e,stateVariable:t}),r.componentName=e.componentName;let a=e.state[t];if(a.isArrayEntry?(r.arrayKeys=await a.arrayKeys,r.arraySize=await a.arraySize):a.isArray&&(r.arraySize=await a.arraySize),a.createWorkspace&&(r.workspace=a.workspace),a.providePreviousValuesInDefinition||a.provideEssentialValuesInDefinition){let n=[t];if(a.additionalStateVariablesDefined&&n.push(...a.additionalStateVariablesDefined),a.providePreviousValuesInDefinition){let t={};for(let r of n)e.state[r].isArrayEntry&&(r=e.state[r].arrayStateVariable),t[r]=e.state[r]._previousValue;r.previousValues=t}if(a.provideEssentialValuesInDefinition){let t={};for(let r of n){e.state[r].isArrayEntry&&(r=e.state[r].arrayStateVariable);let n=r;e.state[r].essentialVarName&&(n=e.state[r].essentialVarName),t[r]=e.essentialState[n]}r.essentialValues=t}}return r}async recordActualChangeInStateVariable({componentName:e,varName:t}){let n=this._components[e];await this.markStateVariableAndUpstreamDependentsStale({component:n,varName:t});let r=[t];n.state[t].additionalStateVariablesDefined&&r.push(...n.state[t].additionalStateVariablesDefined);for(let e of r)n.state[e].forceRecalculation=!0,this.dependencies.recordActualChangeInUpstreamDependencies({component:n,varName:e})}findCaseInsensitiveMatches({stateVariables:e,componentClass:t}){let n=this.componentInfoObjects.stateVariableInfo[t.componentType],r=[];for(let t of e){let e=!1,a=t.toLowerCase();for(let t in n.stateVariableDescriptions)if(a===t.toLowerCase()){e=!0,r.push(t);break}if(e)continue;let i=!1,o=a;"__array_size_"===a.substring(0,13)&&(i=!0,o=a.substring(13));for(let t in n.aliases)if(o===t.toLowerCase()){i&&(t="__array_size_"+t),r.push(t),e=!0;break}if(e)continue;let s=Object.keys(n.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let i of s)if(a.substring(0,i.length)===i.toLowerCase()){let o=n.arrayEntryPrefixes[i].arrayVariableName,s=n.stateVariableDescriptions[o];if(s.getArrayKeysFromVarName({arrayEntryPrefix:i,varEnding:t.substring(i.length),nDimensions:s.nDimensions}).length>0){let t=i+a.substring(i.length);e=!0,r.push(t);break}}e||r.push(t)}return r}matchPublicStateVariables({stateVariables:e,componentClass:t}){let n=this.componentInfoObjects.publicStateVariableInfo[t.componentType],r=[];for(let t of e){if(t in n.stateVariableDescriptions){r.push(t);continue}let e=t;if(e in n.aliases&&(e=n.aliases[e],e in n.stateVariableDescriptions)){r.push(e);continue}let a=!1,i=Object.keys(n.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let t of i)if(e.substring(0,t.length)===t){let r=n.arrayEntryPrefixes[t].arrayVariableName,i=n.stateVariableDescriptions[r];if(i.getArrayKeysFromVarName({arrayEntryPrefix:t,varEnding:e.substring(t.length),nDimensions:i.nDimensions}).length>0){a=!0;break}}a?r.push(t):r.push("__not_public_"+t)}return r}substituteAliases({stateVariables:e,componentClass:t}){let n=[],r=this.componentInfoObjects.stateVariableInfo[t.componentType];for(let t of e){let e=!1;"__array_size_"===t.substring(0,13)&&(e=!0,t=t.substring(13)),t=t in r.aliases?r.aliases[t]:t,e&&(t="__array_size_"+t),n.push(t)}return n}publicCaseInsensitiveAliasSubstitutions({stateVariables:e,componentClass:t}){let n=this.findCaseInsensitiveMatches({stateVariables:e,componentClass:t});return n=this.matchPublicStateVariables({stateVariables:n,componentClass:t}),n=this.substituteAliases({stateVariables:n,componentClass:t}),n}checkIfArrayEntry({stateVariable:e,component:t}){for(let n in t.arrayEntryPrefixes)if(e.substring(0,n.length)===n){let r=t.arrayEntryPrefixes[n],a=t.state[r];if(a.getArrayKeysFromVarName({arrayEntryPrefix:n,varEnding:e.substring(n.length),nDimensions:a.nDimensions}).length>0)return!0}return!1}async createFromArrayEntry({stateVariable:e,component:t,initializeOnly:n=!1}){if(!t.arrayEntryPrefixes)throw Error(`Unknown state variable ${e} of ${t.componentName}`);let r=Object.keys(t.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let a of r)if(e.substring(0,a.length)===a){let r=t.arrayEntryPrefixes[a],i=t.state[r];if(i.getArrayKeysFromVarName({arrayEntryPrefix:a,varEnding:e.substring(a.length),nDimensions:i.nDimensions}).length>0){let r=t.arrayEntryPrefixes[a];if(await this.initializeStateVariable({component:t,stateVariable:e,arrayStateVariable:r,arrayEntryPrefix:a}),n)return;let i=[e];if(t.state[e].additionalStateVariablesDefined){i.push(...t.state[e].additionalStateVariablesDefined);for(let n of t.state[e].additionalStateVariablesDefined)t.state[n]||await this.createFromArrayEntry({stateVariable:n,component:t,initializeOnly:!0})}await this.dependencies.setUpStateVariableDependencies({component:t,stateVariable:e,allStateVariablesAffected:i,core:this});let o=[];for(let e of i)this.dependencies.checkForCircularDependency({componentName:t.componentName,varName:e}),o.push(e),t.state[e].determineDependenciesStateVariable&&o.push(t.state[e].determineDependenciesStateVariable);return void await this.dependencies.resolveStateVariablesIfReady({component:t,stateVariables:o})}}throw Error(`Unknown state variable ${e} of ${t.componentName}`)}async markStateVariableAndUpstreamDependentsStale({component:e,varName:t}){t in this.rendererVariablesByComponentType[e.componentType]&&this.updateInfo.componentsToUpdateRenderers.push(e.componentName);let n={[t]:e.state[t]};e.state[t].additionalStateVariablesDefined&&e.state[t].additionalStateVariablesDefined.forEach((t=>n[t]=e.state[t]));let r=await this.lookUpCurrentFreshness({component:e,varName:t,allStateVariablesAffectedObj:n}),a=[],i=[],o=0;for(let e in n){let t=n[e];Object.getOwnPropertyDescriptor(t,"value").get||t.immutable?r&&(r.fresh&&r.fresh[e]?i.push(e):r.partiallyFresh&&r.partiallyFresh[e]&&(o+=r.partiallyFresh[e])):a.push(e)}i.push(...a);let s=i.length>0||o>0,l={};for(let e in n)l[e]=!0;let u=!1;if(s){let r=await this.processMarkStale({component:e,varName:t,allStateVariablesAffectedObj:n});if(r.fresh)for(let e in r.fresh)r.fresh[e]&&delete l[e];let a=0;for(let e in n){if(i.includes(e)&&(!r.fresh||!r.fresh[e])){u=!0;break}r.partiallyFresh&&r.partiallyFresh[e]&&(a+=r.partiallyFresh[e])}if(an({component:e,stateVariable:t}),configurable:!0})}}if(u)for(let t in l)await this.markUpstreamDependentsStale({component:e,varName:t})}async lookUpCurrentFreshness({component:e,varName:t,allStateVariablesAffectedObj:n}){let r=e.state[t];if(!r.getCurrentFreshness)return;let a,i,o=r.freshnessInfo;if(r.isArrayEntry&&(a=r._arrayKeys),r.isArrayEntry||r.isArray){let t=e.state[r.arraySizeStateVariable];i=t._previousValue,!(Object.getOwnPropertyDescriptor(t,"value").get||t.immutable)&&(i=await t.value),Array.isArray(i)||(i=[])}let s=r.getCurrentFreshness({freshnessInfo:o,arrayKeys:a,arraySize:i});if(s.partiallyFresh)for(let e in n)if(n[e].isArrayEntry){let t=n[e].arrayStateVariable;s.partiallyFresh[e]=s.partiallyFresh[t],delete s.partiallyFresh[t]}if(s.fresh)for(let e in n)if(n[e].isArrayEntry){let t=n[e].arrayStateVariable;t in s.fresh&&(s.fresh[e]=s.fresh[t],delete s.fresh[t])}return s}async processMarkStale({component:e,varName:t,allStateVariablesAffectedObj:n}){let r=e.state[t];if(!r.markStale||!r.initiallyResolved){let e={};return Object.keys(n).forEach((t=>e[t]=!1)),{fresh:e}}let a={},i=this.dependencies.downstreamDependencies[e.componentName][t];for(let e in i){let t=i[e],n={},r=!1;t.componentIdentityChanged&&(n.componentIdentityChanged=!0,r=!0),t.componentIdentitiesChanged&&(n.componentIdentitiesChanged=!0,r=!0),t.valuesChanged&&(n.valuesChanged=t.valuesChanged,r=!0),r&&(a[e]=n)}let o,s,l=r.freshnessInfo;if(r.isArrayEntry&&(o=r._arrayKeys),r.isArrayEntry||r.isArray){let t=e.state[r.arraySizeStateVariable];s=t._previousValue,!(Object.getOwnPropertyDescriptor(t,"value").get||t.immutable)&&(s=await t.value),Array.isArray(s)||(s=[])}let u=r.markStale({freshnessInfo:l,changes:a,arrayKeys:o,arraySize:s});if(u.partiallyFresh)for(let e in n)if(n[e].isArrayEntry){let t=n[e].arrayStateVariable;u.partiallyFresh[e]=u.partiallyFresh[t],delete u.partiallyFresh[t]}if(u.fresh)for(let e in n)if(n[e].isArrayEntry){let t=n[e].arrayStateVariable;t in u.fresh&&(u.fresh[e]=u.fresh[t],delete u.fresh[t])}return u}async markUpstreamDependentsStale({component:e,varName:t}){let n,r=e.componentName,a=this.getStateVariableValue,i=this.dependencies.upstreamDependencies[r][t];if(e.state[t]&&(n=e.state[t].freshnessInfo),i)for(let o of i){let i=!1;if(o.markStale&&await o.markStale(),o.downstreamComponentNames){let e=o.downstreamComponentNames.indexOf(r);if(-1===e)continue;if(o.mappedDownstreamVariableNamesByComponent){if(-1===o.mappedDownstreamVariableNamesByComponent[e].indexOf(t))throw Error(`something went wrong as ${t} not a downstreamVariable of ${o.dependencyName}`);"determineDependencies"===o.dependencyType&&(o.recalculateDependencies=!0),o.valuesChanged||(o.valuesChanged=[]),o.valuesChanged[e]||(o.valuesChanged[e]={}),o.valuesChanged[e][t]||(o.valuesChanged[e][t]={}),o.valuesChanged[e][t].potentialChange=!0,n&&(o.valuesChanged[e][t].freshnessInfo=n),i=!0}else t===o.downstreamVariableNameIfNoVariables&&(o.valuesChanged||(o.valuesChanged={[o.downstreamVariableNameIfNoVariables]:{}}),o.componentIdentityChanged=!0,o.valuesChanged[o.downstreamVariableNameIfNoVariables].potentialChange=!0,i=!0)}if(i){for(let e of o.upstreamVariableNames)if(e in this.rendererVariablesByComponentType[this.components[o.upstreamComponentName].componentType]){this.updateInfo.componentsToUpdateRenderers.push(o.upstreamComponentName);break}let t=o.upstreamVariableNames[0],n=this._components[o.upstreamComponentName],r={};o.upstreamVariableNames.forEach((e=>r[e]=n.state[e]));let i=await this.lookUpCurrentFreshness({component:n,varName:t,allStateVariablesAffectedObj:r}),s=[],l=[],u=0;for(let e in r){let t=r[e];Object.getOwnPropertyDescriptor(t,"value").get||t.immutable?i&&(i.fresh&&i.fresh[e]?l.push(e):i.partiallyFresh&&i.partiallyFresh[e]&&(u+=i.partiallyFresh[e])):s.push(e)}l.push(...s);let c=l.length>0||u>0,p={};for(let e in r)p[e]=!0;let d=!1;if(c){let a=await this.processMarkStale({component:n,varName:t,allStateVariablesAffectedObj:r});if(a.fresh)for(let e in a.fresh)a.fresh[e]&&delete p[e];let i=0;for(let e in r){if(l.includes(e)&&(!a.fresh||!a.fresh[e])){d=!0;break}a.partiallyFresh&&a.partiallyFresh[e]&&(i+=a.partiallyFresh[e])}if(ia({component:n,stateVariable:e}),configurable:!0}))}if(d)for(let e in p)await this.markUpstreamDependentsStale({component:n,varName:e})}}}registerComponent(e){if(e.componentName in this._components)throw Error(`Duplicate componentName: ${e.componentName}`);this._components[e.componentName]=e}deregisterComponent(e,t=!0){if(!0===t)for(let t in e.allChildren)this.deregisterComponent(e.allChildren[t].component);delete this._components[e.componentName]}setAncestors(e,t=[]){e.ancestors=t;let n=[{componentName:e.componentName,componentClass:e.constructor},...e.ancestors];for(let t in e.allChildren){let e=this._components[t];this.setAncestors(e,n)}for(let t in e.attributes){let r=e.attributes[t].component;r&&this.setAncestors(r,n)}}async addChildrenAndRecurseToShadows({parent:e,indexOfDefiningChildren:t,newChildren:n,assignNamesOffset:r}){this.spliceChildren(e,t,n);let a=await this.processNewDefiningChildren({parent:e}),i={};if(!a.success)return a;for(let e of n)"object"==typeof e&&(i[e.componentName]=e);if(e.shadowedBy)for(let a of e.shadowedBy){if(a.shadows.propVariable)continue;let e=this._components[a.shadows.compositeName],o=await e.stateValues.sourceAttributesToIgnore,s=await e.stateValues.sourceAttributesToIgnoreRecursively,l=[];for(let e of n)"object"==typeof e?l.push(await e.serialize({sourceAttributesToIgnore:o,sourceAttributesToIgnoreRecursively:s})):l.push(e);l=postProcessCopy({serializedComponents:l,componentName:a.shadows.compositeName});let u=a.attributes.newNamespace?.primitive,c=u;l=processAssignNames({indOffset:r,serializedComponents:l,parentName:a.componentName,parentCreatesNewNamespace:u,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:c}).serializedComponents;let p,d=this._components[a.componentName];this.parameterStack.push(d.sharedParameters,!1),p=u?a.componentName+"/":getNamespaceFromName(a.componentName);let m=await this.createIsolatedComponentsSub({serializedComponents:l,ancestors:a.ancestors,createNameContext:a.componentName+"|addChildren|"+r,namespaceForUnamed:p});this.parameterStack.pop();let f=await this.addChildrenAndRecurseToShadows({parent:d,indexOfDefiningChildren:t,newChildren:m.components,assignNamesOffset:r});if(!f.success)throw Error("was able to add components to parent but not shadows!");Object.assign(i,f.addedComponents)}return{success:!0,deletedComponents:{},addedComponents:i}}async processNewDefiningChildren({parent:e,expandComposites:t=!0}){this.parameterStack.push(e.sharedParameters,!1);let n=await this.deriveChildResultsFromDefiningChildren({parent:e,expandComposites:t});this.parameterStack.pop();let r=[{componentName:e.componentName,componentClass:e.constructor},...e.ancestors];for(let t in e.allChildren){let e=this._components[t];this.setAncestors(e,r)}return n}spliceChildren(e,t,n){let r=e.definingChildren.length;if(!Number.isInteger(t)||t>r||t<0)throw Error("Can't add children at index "+t+". Invalid index.");e.definingChildren.splice(t,0,...n)}async deleteComponents({components:e,deleteUpstreamDependencies:t=!0,skipProcessingChildrenOfParents:n=[]}){Array.isArray(e)||(e=[e]);const r={};this.determineComponentsToDelete({components:e,deleteUpstreamDependencies:t,componentsToDelete:r});const a={};for(let e in r){let t=r[e],n=this.components[t.parentName];if(void 0===n||n.componentName in r)continue;let i=a[t.parentName];void 0===i&&(i={parent:this._components[t.parentName],childNamesToBeDeleted:new Set},a[t.parentName]=i),i.childNamesToBeDeleted.add(e)}let i=[];for(let e in r){let t=this._components[e];if(t.replacementOf){let n=t.replacementOf,r=n.replacements.map((e=>e.componentName)),a=r.indexOf(e);-1!==a&&(n.replacements.splice(a,1),i.includes(n.componentName)||i.push(n.componentName))}}for(let e of i)e in r||await this.dependencies.addBlockersFromChangedReplacements(this._components[e]);let o=[];for(let e in a){let t=a[e],r=t.parent;o.push(r);for(let e=r.definingChildren.length-1;e>=0;e--){let n=r.definingChildren[e];t.childNamesToBeDeleted.has(n.componentName)&&r.definingChildren.splice(e,1)}n.includes(r.componentName)||await this.processNewDefiningChildren({parent:r,expandComposites:!1})}for(let e in r){let t=this._components[e];if(t.shadows){let e=this._components[t.shadows.componentName];1===e.shadowedBy.length?delete e.shadowedBy:e.shadowedBy.splice(e.shadowedBy.indexOf(t),1)}this.dependencies.deleteAllDownstreamDependencies({component:t});for(let e in this.dependencies.upstreamDependencies[t.componentName]){let n=this.dependencies.upstreamDependencies[t.componentName][e];for(let e of n)if(e.specifiedComponentName&&e.specifiedComponentName in r){let t=this.dependencies.updateTriggers.dependenciesMissingComponentBySpecifiedName[e.specifiedComponentName];t||(t=this.dependencies.updateTriggers.dependenciesMissingComponentBySpecifiedName[e.specifiedComponentName]=[]),t.includes(e)||t.push(e)}}await this.dependencies.deleteAllUpstreamDependencies({component:t}),this.updateInfo.deletedStateVariables[t.componentName]||(this.updateInfo.deletedStateVariables[t.componentName]=[]),this.updateInfo.deletedStateVariables[t.componentName].push(...Object.keys(t.state)),this.updateInfo.deletedComponents[t.componentName]=!0,delete this.unmatchedChildren[t.componentName],delete this.stateVariableChangeTriggers[t.componentName]}for(let e in r){let t=this._components[e];this.deregisterComponent(t,!1)}return this.updateInfo.componentsToUpdateRenderers=[...new Set(this.updateInfo.componentsToUpdateRenderers)].filter((e=>!(e in r))),this.updateInfo.compositesToUpdateReplacements=[...new Set(this.updateInfo.compositesToUpdateReplacements)].filter((e=>!(e in r))),{success:!0,deletedComponents:r,parentsOfDeleted:o}}determineComponentsToDelete({components:e,deleteUpstreamDependencies:t,componentsToDelete:n}){for(let r of e){if("object"!=typeof r)continue;if(r.componentName in n)continue;n[r.componentName]=this._components[r.componentName];let e=Object.values(r.allChildren).map((e=>e.component));for(let t in r.attributes){let n=r.attributes[t].component;n&&e.push(n)}void 0!==r.adaptedFrom&&e.push(r.adaptedFrom),!0===t&&(r.shadowedBy&&e.push(...r.shadowedBy),r.adapterUsed&&e.push(r.adapterUsed),r.replacements&&e.push(...r.replacements)),this.determineComponentsToDelete({components:e,deleteUpstreamDependencies:t,componentsToDelete:n})}}async updateCompositeReplacements({component:e,componentChanges:t,sourceOfUpdate:n}){let r={},a={},i=new Set;if(e.shadows){return{success:!0,deletedComponents:r,addedComponents:a,parentsOfDeleted:i}}let o=this.components[e.componentName];e.replacements||(e.replacements=[]),await e.stateValues.readyToExpandWhenResolved;const s=await e.constructor.calculateReplacementChanges({component:o,componentChanges:t,components:this.components,workspace:e.replacementsWorkspace,componentInfoObjects:this.componentInfoObjects,flags:this.flags,resolveItem:this.dependencies.resolveItem.bind(this.dependencies),publicCaseInsensitiveAliasSubstitutions:this.publicCaseInsensitiveAliasSubstitutions.bind(this)});e.constructor.stateVariableToEvaluateAfterReplacements&&await e.stateValues[e.constructor.stateVariableToEvaluateAfterReplacements];for(let o of s)if("add"===o.changeType){void 0!==o.replacementsToWithhold&&await this.adjustReplacementsToWithhold({component:e,change:o,componentChanges:t});let s,l=this._components[e.componentName];this.parameterStack.push(l.sharedParameters,!1);let u={[e.componentName]:calculateAllComponentsShadowing(e)},c=o.numberReplacementsToReplace,p=o.firstReplacementInd;if(c>0&&o.changeTopLevelReplacements&&await this.deleteReplacementsFromShadowsThenComposite({change:o,composite:e,componentChanges:t,sourceOfUpdate:n,parentsOfDeleted:i,deletedComponents:r,addedComponents:a,processNewChildren:!1}),!o.serializedReplacements)throw Error("Invalid replacement change.");{let t,n=o.serializedReplacements;t=e.attributes.newNamespace?.primitive?e.componentName+"/":getNamespaceFromName(e.componentName),s=(await this.createIsolatedComponentsSub({serializedComponents:n,ancestors:e.ancestors,createNameContext:e.componentName+"|replacements",namespaceForUnamed:t,componentsReplacementOf:e})).components}this.parameterStack.pop();let d={[e.componentName]:{newComponents:s,parent:o.parent}};if(l.shadowedBy&&u[l.componentName].length>0){let e=await this.createShadowedReplacements({replacementsToShadow:s,componentToShadow:l,parentToShadow:o.parent,currentShadowedBy:u,assignNamesOffset:o.assignNamesOffset,componentChanges:t,sourceOfUpdate:n,parentsOfDeleted:i,deletedComponents:r,addedComponents:a});Object.assign(d,e)}for(let e in d){let n=this._components[e];if(!n)continue;let r=d[e].newComponents;if(n.isExpanded){for(let e of r)"object"==typeof e&&(a[e.componentName]=e);if(!0===o.changeTopLevelReplacements){let e=this._components[n.parentName];n.replacements.splice(p,0,...r),await this.dependencies.addBlockersFromChangedReplacements(n);let a={changeType:"addedReplacements",composite:n,newReplacements:r,topLevel:!0,firstIndex:p,numberDeleted:c};t.push(a),await this.processNewDefiningChildren({parent:e,expandComposites:!1});let i=await this.componentAndRenderedDescendants(e);this.updateInfo.componentsToUpdateRenderers.push(...i)}else{let i=this._components[d[e].parent.componentName];this.spliceChildren(i,o.indexOfDefiningChildren,r),await this.processNewDefiningChildren({parent:i});for(let e of r)"object"==typeof e&&(a[e.componentName]=e);let s=await this.componentAndRenderedDescendants(i);this.updateInfo.componentsToUpdateRenderers.push(...s);let l={changeType:"addedReplacements",composite:n,newReplacements:r};t.push(l)}}else{await this.expandCompositeComponent(n);let e={changeType:"addedReplacements",composite:n,newReplacements:n.replacements,topLevel:!0,firstIndex:0,numberDeleted:0};t.push(e)}}}else if("delete"===o.changeType)void 0!==o.replacementsToWithhold&&await this.adjustReplacementsToWithhold({component:e,change:o,componentChanges:t}),await this.deleteReplacementsFromShadowsThenComposite({change:o,composite:e,componentsToDelete:o.components,componentChanges:t,sourceOfUpdate:n,parentsOfDeleted:i,deletedComponents:r,addedComponents:a});else{if("moveDependency"===o.changeType)throw Error("moveDependency not implemented");if("addDependency"===o.changeType)throw Error("addDependency not implemented");if("updateStateVariables"===o.changeType){let e={},t={};for(let n in o.stateChanges){let r={componentName:o.component.componentName,stateVariable:n,value:o.stateChanges[n],overrideFixed:!0};await this.requestComponentChanges({instruction:r,initialChange:!1,workspace:e,newStateVariableValues:t})}await this.processNewStateVariableValues(t)}else"changeReplacementsToWithhold"===o.changeType&&(void 0!==o.replacementsToWithhold&&await this.adjustReplacementsToWithhold({component:e,change:o,componentChanges:t}),await this.processChildChangesAndRecurseToShadows(e))}return{success:!0,deletedComponents:r,addedComponents:a,parentsOfDeleted:i}}async deleteReplacementsFromShadowsThenComposite({change:e,composite:t,componentsToDelete:n,componentChanges:r,sourceOfUpdate:a,parentsOfDeleted:i,deletedComponents:o,addedComponents:s,processNewChildren:l=!0}){let u=[];if(!t.isExpanded)return u;if(t.shadowedBy)for(let c of t.shadowedBy){if(c.shadows.propVariable)continue;let t;if(n){t=[];for(let e of n){let n;if(e.shadowedBy)for(let t of e.shadowedBy)if(!t.shadows.propVariable&&t.shadows.compositeName===c.shadows.compositeName){n=t;break}n?t.push(n):console.error(`could not find shadowing component of ${e.componentName}`)}}let p=await this.deleteReplacementsFromShadowsThenComposite({change:e,composite:c,componentsToDelete:t,componentChanges:r,sourceOfUpdate:a,parentsOfDeleted:i,deletedComponents:o,addedComponents:s,processNewChildren:l});u.push(...p)}if(e.changeTopLevelReplacements){let n=e.firstReplacementInd,s=e.numberReplacementsToDelete;"add"===e.changeType&&(s=e.numberReplacementsToReplace);let u=t.replacements.splice(n,s);await this.dependencies.addBlockersFromChangedReplacements(t);let c=await this.deleteComponents({components:u,componentChanges:r,sourceOfUpdate:a,skipProcessingChildrenOfParents:[t.parentName]});if(l&&await this.processNewDefiningChildren({parent:this._components[t.parentName],expandComposites:!1}),!1===c.success)throw Error("Couldn't delete components on composite update");for(let e of c.parentsOfDeleted){i.add(e.componentName);let t=await this.componentAndRenderedDescendants(e);this.updateInfo.componentsToUpdateRenderers.push(...t)}let p={};for(let e in c.deletedComponents){let t=c.deletedComponents[e].parentName;void 0===p[t]&&(p[t]=[]),p[t].push(e)}let d={changeType:"deletedReplacements",composite:t,topLevel:!0,firstIndex:n,numberDeleted:s,deletedNamesByParent:p,deletedComponents:c.deletedComponents};r.push(d),Object.assign(o,c.deletedComponents);let m=this._components[t.parentName],f=await this.componentAndRenderedDescendants(m);this.updateInfo.componentsToUpdateRenderers.push(...f)}else{let e=n.length,l=await this.deleteComponents({components:n,deleteUpstreamDependencies:!1,componentChanges:r,sourceOfUpdate:a});if(!1===l.success)throw Error("Couldn't delete components prescribed by composite");for(let e of l.parentsOfDeleted){i.add(e.componentName);let t=await this.componentAndRenderedDescendants(e);this.updateInfo.componentsToUpdateRenderers.push(...t)}let u={};for(let e in l.deletedComponents){let t=l.deletedComponents[e].parentName;void 0===u[t]&&(u[t]=[]),u[t].push(e)}let c={changeType:"deletedReplacements",composite:t,numberDeleted:e,deletedNamesByParent:u,deletedComponents:l.deletedComponents};r.push(c),Object.assign(o,l.deletedComponents),Object.assign(s,l.addedComponents)}return u}async processChildChangesAndRecurseToShadows(e){let t=this._components[e.parentName];await this.processNewDefiningChildren({parent:t,expandComposites:!1});let n=await this.componentAndRenderedDescendants(t);if(this.updateInfo.componentsToUpdateRenderers.push(...n),e.shadowedBy)for(let t of e.shadowedBy)t.shadows.propVariable||await this.processChildChangesAndRecurseToShadows(t)}async createShadowedReplacements({replacementsToShadow:e,componentToShadow:t,parentToShadow:n,currentShadowedBy:r,assignNamesOffset:a,componentChanges:i,sourceOfUpdate:o,parentsOfDeleted:s,deletedComponents:l,addedComponents:u}){let c=calculateAllComponentsShadowing(t);if(!r[t.componentName]||!c.every((e=>r[t.componentName].includes(e))))throw Error(`circular reference involving ${t.componentName}`);this.updateInfo.compositesBeingExpanded.push(t.componentName);let p={};for(let c of t.shadowedBy)if(!c.shadows.propVariable){if(this.updateInfo.compositesBeingExpanded.includes(c.componentName))throw Error(`circular dependence involving ${c.componentName}`);if(c.shadowedBy&&(r[c.componentName]=calculateAllComponentsShadowing(c)),c.isExpanded){let t=[],d=this._components[c.shadows.compositeName],m=await d.stateValues.sourceAttributesToIgnore,f=await d.stateValues.sourceAttributesToIgnoreRecursively;for(let n of e)"object"==typeof n?t.push(await n.serialize({sourceAttributesToIgnore:m,sourceAttributesToIgnoreRecursively:f})):t.push(n);t=postProcessCopy({serializedComponents:t,componentName:c.shadows.compositeName});let h,y=c.attributes.newNamespace?.primitive;if(c.attributes.isResponse){let e=c.constructor.createAttributesObject();for(let n of t){if("object"!=typeof n)continue;n.attributes||(n.attributes={});let t=convertAttributesForComponentType({attributes:{isResponse:c.attributes.isResponse},componentType:n.componentType,componentInfoObjects:this.componentInfoObjects,compositeAttributesObj:e,compositeCreatesNewNamespace:y});Object.assign(n.attributes,t)}}if(c.constructor.assignNamesToReplacements){let e=c.shadows.compositeName,n=this.components[e],r=n.attributes.newNamespace?.primitive,i=n.doenetAttributes.assignNames,o=y||r&&!i,s=c.doenetAttributes.assignNames;s&&await c.stateValues.addLevelToAssignNames&&(s=s.map((e=>[e]))),t=processAssignNames({assignNames:s,indOffset:a,serializedComponents:t,parentName:c.componentName,parentCreatesNewNamespace:y,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:o}).serializedComponents}else{let e=y;t=processAssignNames({indOffset:a,serializedComponents:t,parentName:c.componentName,parentCreatesNewNamespace:y,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:e}).serializedComponents}let b,g=this._components[c.componentName];this.parameterStack.push(g.sharedParameters,!1),b=y?c.componentName+"/":getNamespaceFromName(c.componentName);let v,T=await this.createIsolatedComponentsSub({serializedComponents:t,ancestors:c.ancestors,createNameContext:c.componentName+"|replacements",namespaceForUnamed:b,componentsReplacementOf:c});if(this.parameterStack.pop(),h=T.components,n){if(n.shadowedBy)for(let e of n.shadowedBy)if(!e.shadows.propVariable&&e.shadows.compositeName===c.shadows.compositeName){v=e;break}v||console.error(`could not find shadowing parent of ${n.componentName}`)}if(p[c.componentName]={newComponents:h,parent:v},c.shadowedBy&&r[c.componentName].length>0){let e=await this.createShadowedReplacements({replacementsToShadow:h,componentToShadow:c,parentToShadow:v,currentShadowedBy:r,assignNamesOffset:a,componentChanges:i,sourceOfUpdate:o,parentsOfDeleted:s,deletedComponents:l,addedComponents:u});Object.assign(p,e)}}}let d=this.updateInfo.compositesBeingExpanded.indexOf(t.componentName);if(-1===d)throw Error(`Something is wrong as we lost track that we were expanding ${component.componentName}`);return this.updateInfo.compositesBeingExpanded.splice(d,1),p}async adjustReplacementsToWithhold({component:e,change:t,componentChanges:n}){let r,a=[],i=t.replacementsToWithhold;if(r=void 0!==e.replacementsToWithhold?i-e.replacementsToWithhold:i,r<0){a.push(e.componentName);let t=e.replacements.length-i,o=e.replacements.length-i+r,s=e.replacements.slice(o,t),l={changeType:"addedReplacements",composite:e,topLevel:!0,newReplacements:s,firstIndex:o,numberDeleted:0};n.push(l)}else if(r>0){a.push(e.componentName);let t=e.replacements.length-i,o=t+r,s=e.replacements.slice(t,o),l={};for(let e of s){let t=e.parentName;void 0===l[t]&&(l[t]=[]),l[t].push(e.componentName)}let u={changeType:"deletedReplacements",composite:e,topLevel:!0,firstIndex:t,numberDeleted:r,deletedNamesByParent:l,deletedComponents:s};n.push(u)}if(e.replacementsToWithhold=i,await this.dependencies.addBlockersFromChangedReplacements(e),e.shadowedBy)for(let r of e.shadowedBy){if(r.shadows.propVariable)continue;let e=await this.adjustReplacementsToWithhold({component:r,change:t,componentChanges:n});a.push(...e)}return a}get rendererTypesInDocument(){return this.document.allPotentialRendererTypes}get components(){return this._components}set components(e){return null}async executeProcesses(){if(!this.stopProcessingRequests){for(;this.processQueue.length>0;){let e,t=this.processQueue.splice(0,1)[0];if("update"===t.type)(!t.skippable||this.processQueue.length<2)&&(e=await this.performUpdate(t));else if("action"===t.type)(!t.skippable||this.processQueue.length<2)&&(e=await this.performAction(t));else{if("recordEvent"!==t.type)throw Error(`Unrecognized process type: ${t.type}`);e=await this.performRecordEvent(t)}t.resolve(e)}this.processing=!1}}requestAction({componentName:e,actionName:t,args:n,event:r}){return new Promise(((a,i)=>{let o=n?.skippable;this.processQueue.push({type:"action",componentName:e,actionName:t,args:n,skippable:o,event:r,resolve:a,reject:i}),this.processing||(this.processing=!0,this.executeProcesses())}))}async performAction({componentName:e,actionName:t,args:n,event:r,caseInsensitiveMatch:a}){let i=this.components[e];if(i&&i.actions){let e=i.actions[t];if(!e&&a){let n=t.toLowerCase();for(let r in i.actions)if(r.toLowerCase()===n){e=i.actions[r],t=r;break}}if(e)return r&&this.requestRecordEvent(r),n||(n={}),await e(n)}if(!i&&"recordVisibilityChange"===t&&!1===n?.isVisible)return this.requestRecordEvent({verb:"visibilityChanged",object:{componentName:e},result:{isVisible:!1}}),this.resolveAction({actionId:n.actionId});i&&console.warn(`Cannot run action ${t} on component ${e}`)}resolveAction({actionId:e}){e&&postMessage({messageType:"resolveAction",coreId:this.coreId,args:{actionId:e}})}async triggerChainedActions({componentName:e,triggeringAction:t}){for(let e in this.updateInfo.componentsToUpdateActionChaining)await this.checkForActionChaining({component:this.components[e],stateVariables:this.updateInfo.componentsToUpdateActionChaining[e]});this.updateInfo.componentsToUpdateActionChaining={};let n=e;if(t&&(n+="|"+t),this.actionsChangedToActions[n])for(let e of this.actionsChangedToActions[n])await this.performAction(e)}async requestUpdate({updateInstructions:e,transient:t=!1,event:n,skippable:r=!1,overrideReadOnly:a=!1}){if(!this.flags.readOnly||a)return new Promise(((a,i)=>{this.processQueue.push({type:"update",updateInstructions:e,transient:t,event:n,skippable:r,resolve:a,reject:i}),this.processing||(this.processing=!0,this.executeProcesses())}));{let t={};for(let n of e){let e=t[n.componentName];e||(e=t[n.componentName]={}),n.sourceInformation&&Object.assign(e,n.sourceInformation)}await this.updateRendererInstructions({componentNamesToUpdate:e.map((e=>e.componentName)),sourceOfUpdate:{sourceInformation:t}})}}async performUpdate({updateInstructions:e,actionId:t,event:n,overrideReadOnly:r=!1,doNotSave:a=!1,canSkipUpdatingRenderer:i=!1,suppressToast:o=!1}){if(this.flags.readOnly&&!r){if(!i){let n={};for(let t of e){let e=n[t.componentName];e||(e=n[t.componentName]={}),t.sourceInformation&&Object.assign(e,t.sourceInformation)}await this.updateRendererInstructions({componentNamesToUpdate:e.map((e=>e.componentName)),sourceOfUpdate:{sourceInformation:n},actionId:t})}return}let s={},l=[],u={},c={},p=[];for(let t of e){if(t.componentName){let e=u[t.componentName];e||(e=u[t.componentName]={}),t.sourceInformation&&Object.assign(e,t.sourceInformation)}if("updateValue"===t.updateType)await this.requestComponentChanges({instruction:t,workspace:c,newStateVariableValues:s});else if("addComponents"===t.updateType)await this.addComponents({serializedComponents:t.serializedComponents,parentName:t.parentName,assignNamesOffset:t.assignNamesOffset});else if("deleteComponents"===t.updateType){if(t.componentNames.length>0){let e=[];for(let n of t.componentNames){let t=this._components[n];t?e.push(t):console.warn(`Cannot delete ${n} as it doesn't exist.`)}e.length>0&&await this.deleteComponents({components:e})}}else"executeUpdate"===t.updateType?(await this.executeUpdateStateVariables(s),l.push(s),s={}):"recordItemSubmission"===t.updateType?p.push(t):"setComponentNeedingUpdateValue"===t.updateType?this.rendererState.__componentNeedingUpdateValue=t.componentName:"unsetComponentNeedingUpdateValue"===t.updateType&&(this.rendererState.__componentNeedingUpdateValue=null)}await this.executeUpdateStateVariables(s),l.push(s),i||this.updateInfo.componentsToUpdateRenderers.push(...e.map((e=>e.componentName)));let d=[...new Set(this.updateInfo.componentsToUpdateRenderers)];if(this.updateInfo.componentsToUpdateRenderers=[],await this.updateRendererInstructions({componentNamesToUpdate:d,sourceOfUpdate:{sourceInformation:u,local:!0},actionId:t}),this.updateInfo.compositesToUpdateReplacements.length>0){await this.replacementChangesFromCompositesToUpdate();let e=[...new Set(this.updateInfo.componentsToUpdateRenderers)];this.updateInfo.componentsToUpdateRenderers=[],await this.updateRendererInstructions({componentNamesToUpdate:e,sourceOfUpdate:{sourceInformation:u,local:!0},actionId:t})}if(await this.processStateVariableTriggers(),this.updateInfo.componentsToUpdateRenderers=this.updateInfo.componentsToUpdateRenderers.filter((e=>!d.includes(e))),Object.keys(this.unmatchedChildren).length>0){let e="";for(let t in this.unmatchedChildren)this._components[t].isShadow||(e+=`Invalid children for ${t}: ${this.unmatchedChildren[t].message} `);e&&console.warn(e)}if(p.length>0){let e=[...new Set(p.map((e=>e.itemNumber)))],t=await this.document.stateValues.creditAchieved,r=await this.document.stateValues.itemCreditAchieved;if(n){if(n.context||(n.context={}),n.context.item=e[0],n.context.itemCreditAchieved=r[e[0]-1],e.length>1){n.context.additionalItemCreditAchieved={};for(let t of e)n.context.additionalItemCreditAchieved[t]=r[t-1]}n.context.pageCreditAchieved=await this.document.stateValues.creditAchieved}this.itemNumber>0&&this.saveSubmissions({pageCreditAchieved:t,suppressToast:o})}if(Object.keys(this.essentialValuesSavedInDefinition).length>0){for(let e in this.essentialValuesSavedInDefinition){let t=this._components[e]?.essentialState;if(t){this.cumulativeStateVariableChanges[e]||(this.cumulativeStateVariableChanges[e]={});for(let n in this.essentialValuesSavedInDefinition[e])if(void 0!==t[n]){let r=this.cumulativeStateVariableChanges[e][n];"object"==typeof r&&null!==r&&r.mergeObject?Object.assign(r,removeFunctionsMathExpressionClass(t[n])):this.cumulativeStateVariableChanges[e][n]=removeFunctionsMathExpressionClass(t[n])}}}this.essentialValuesSavedInDefinition={}}for(let e of l)for(let t in e){this.cumulativeStateVariableChanges[t]||(this.cumulativeStateVariableChanges[t]={});for(let n in e[t]){let r=this.cumulativeStateVariableChanges[t][n];"object"==typeof r&&null!==r&&r.mergeObject?Object.assign(r,removeFunctionsMathExpressionClass(e[t][n])):this.cumulativeStateVariableChanges[t][n]=removeFunctionsMathExpressionClass(e[t][n])}}a||(clearTimeout(this.savePageStateTimeoutID),this.savePageStateTimeoutID=setTimeout((()=>{this.saveState()}),1e3)),await this.document.stateValues.itemCreditAchieved,n&&this.requestRecordEvent(n)}requestRecordEvent(e){return this.resumeVisibilityMeasuring(),"visibilityChanged"===e.verb?this.processVisibilityChangedEvent(e):new Promise(((t,n)=>{this.processQueue.push({type:"recordEvent",event:e,resolve:t,reject:n}),this.processing||(this.processing=!0,this.executeProcesses())}))}async performRecordEvent({event:e}){if(!this.flags.allowSaveEvents)return;e.result||(e.result={}),e.context||(e.context={});const t={doenetId:this.doenetId,activityCid:this.activityCid,pageCid:this.cid,pageNumber:this.pageNumber,attemptNumber:this.attemptNumber,activityVariantIndex:this.activityVariantIndex,pageVariantIndex:this.requestedVariant.index,verb:e.verb,object:JSON.stringify(e.object,serializedComponentsReplacer),result:JSON.stringify(removeFunctionsMathExpressionClass(e.result),serializedComponentsReplacer),context:JSON.stringify(e.context,serializedComponentsReplacer),timestamp:(new Date).toISOString().slice(0,19).replace("T"," "),version:"0.1.1"};try{await axios.post("/api/recordEvent.php",t)}catch(e){console.error(`Error saving event: ${e.message}`)}}processVisibilityChangedEvent(e){let t=e.object.componentName;if(e.result.isVisible)this.visibilityInfo.componentsCurrentlyVisible[t]||(this.visibilityInfo.componentsCurrentlyVisible[t]=new Date),t===this.documentName&&(this.visibilityInfo.documentHasBeenVisible||(this.visibilityInfo.documentHasBeenVisible=!0,this.onDocumentFirstVisible()));else{let e=this.visibilityInfo.componentsCurrentlyVisible[t];if(e){delete this.visibilityInfo.componentsCurrentlyVisible[t];let n=(new Date-Math.max(e,this.visibilityInfo.timeLastSent))/1e3;this.visibilityInfo.infoToSend[t]?this.visibilityInfo.infoToSend[t]+=n:this.visibilityInfo.infoToSend[t]=n}}}sendVisibilityChangedEvents(){let e={...this.visibilityInfo.infoToSend};this.visibilityInfo.infoToSend={};let t=this.visibilityInfo.timeLastSent;this.visibilityInfo.timeLastSent=new Date;let n,r={...this.visibilityInfo.componentsCurrentlyVisible};for(let n in r){let a=(this.visibilityInfo.timeLastSent-Math.max(t,r[n]))/1e3;e[n]?e[n]+=a:e[n]=a}for(let t in e)e[t]=Math.round(e[t]),e[t]||delete e[t];if(Object.keys(e).length>0){let t={object:{componentName:this.documentName,componentType:"document"},verb:"isVisible",result:e};n=new Promise(((e,n)=>{this.processQueue.push({type:"recordEvent",event:t,resolve:e,reject:n}),this.processing||(this.processing=!0,this.executeProcesses())}))}return this.visibilityInfo.suspended||(clearTimeout(this.visibilityInfo.saveTimerId),this.visibilityInfo.saveTimerId=setTimeout(this.sendVisibilityChangedEvents.bind(this),this.visibilityInfo.saveDelay)),n}async suspendVisibilityMeasuring(){clearTimeout(this.visibilityInfo.saveTimerId),clearTimeout(this.visibilityInfo.suspendTimerId),this.visibilityInfo.suspended||(this.visibilityInfo.suspended=!0,await this.sendVisibilityChangedEvents())}resumeVisibilityMeasuring(){this.visibilityInfo.suspended&&(this.visibilityInfo.suspended=!1,this.visibilityInfo.timeLastSent=new Date,clearTimeout(this.visibilityInfo.saveTimerId),this.visibilityInfo.saveTimerId=setTimeout(this.sendVisibilityChangedEvents.bind(this),this.visibilityInfo.saveDelay)),clearTimeout(this.visibilityInfo.suspendTimerId),this.visibilityInfo.suspendTimerId=setTimeout(this.suspendVisibilityMeasuring.bind(this),this.visibilityInfo.suspendDelay)}async executeUpdateStateVariables(e){if(await this.processNewStateVariableValues(e),(await this.replacementChangesFromCompositesToUpdate()).updatedComposites&&(await this.expandAllComposites(this.document),await this.expandAllComposites(this.document,!0),this.updateInfo.stateVariablesToEvaluate)){let e=this.updateInfo.stateVariablesToEvaluate;this.updateInfo.stateVariablesToEvaluate=[];for(let{componentName:t,stateVariable:n}of e){let e=this._components[t];e&&e.state[n]&&await this.getStateVariableValue({component:e,stateVariable:n})}}await this.replacementChangesFromCompositesToUpdate()}async replacementChangesFromCompositesToUpdate(){let e=[...new Set(this.updateInfo.compositesToUpdateReplacements)];this.updateInfo.compositesToUpdateReplacements=[];let t=[],n=0,r=!1,a=[];for(;e.length>0;){for(let n of e){let e=this._components[n];if(e instanceof this.componentInfoObjects.allComponentClasses._composite&&e.isExpanded)if(e.state.readyToExpandWhenResolved.initiallyResolved)if(await e.stateValues.isInactiveCompositeReplacement)this.updateInfo.inactiveCompositesToUpdateReplacements.push(n);else{let t=await this.updateCompositeReplacements({component:e,componentChanges:a});Object.keys(t.addedComponents).length>0&&(r=!0),Object.keys(t.deletedComponents).length>0&&(r=!0)}else t.push(n)}if(e=[...new Set(this.updateInfo.compositesToUpdateReplacements)],this.updateInfo.compositesToUpdateReplacements=[],n++,n>100)throw Error("Seem to have an infinite loop while calculating replacement changes")}return this.updateInfo.compositesToUpdateReplacements=t,{updatedComposites:r}}async processNewStateVariableValues(e){let t=0,n=!1;for(let r in e){let a=this._components[r];if(void 0===a){let t=this.updateInfo.stateVariableUpdatesForMissingComponents[r];void 0===t&&(t=this.updateInfo.stateVariableUpdatesForMissingComponents[r]={}),Object.assign(t,e[r]);continue}let i=e[r];for(let e in i){let o=a.state[e];if(void 0===o){let t=e.match(/^__def_primitive_(\d+)$/);if(t){let n=Number(t[1]);a.definingChildren[n]=i[e],await this.processNewDefiningChildren({parent:a,expandComposites:!1});continue}if(t=e.match(/^__def_primitive_ignore_(\d+)$/),t){let r=Number(t[1]);a.definingChildren[r]=i[e],n=!0;continue}console.warn(`can't update state variable ${e} of component ${r}, as it doesn't exist.`);continue}if(!o.hasEssential){console.warn(`can't update state variable ${e} of component ${r}, as it does not have an essential state variable.`);continue}let s=e;if(a.state[e].essentialVarName&&(s=a.state[e].essentialVarName),e in this.rendererVariablesByComponentType[a.componentType]&&this.updateInfo.componentsToUpdateRenderers.push(a.componentName),o.isArray){let n=a.essentialState[s];Array.isArray(n)||(n=a.essentialState[s]=[]);let l=[];a.state[o.arraySizeStateVariable].initiallyResolved||await a.state[o.arraySizeStateVariable].value;let u=await o.arraySize;for(let r in i[e]){if("mergeObject"===r)continue;let a=e=>e;o.set&&(a=o.set);let s=o.setArrayValue({value:a(i[e][r]),arrayKey:r,arraySize:u,arrayValues:n});o.usedDefaultByArrayKey[r]=!1,t+=s.nFailures;let c=o.varNamesIncludingArrayKeys[r];c&&l.push(...c)}for(let e of l)await this.recordActualChangeInStateVariable({componentName:r,varName:e})}else{if(!o.hasEssential){console.warn(`can't update state variable ${e} of component ${r}, as it does not have an essential state variable.`);continue}o.set?a.essentialState[s]=o.set(i[e]):a.essentialState[s]=i[e],delete o.usedDefault}await this.recordActualChangeInStateVariable({componentName:r,varName:e})}}return{nFailures:t,foundIgnore:n}}async requestComponentChanges({instruction:e,initialChange:t=!0,workspace:n,newStateVariableValues:r}){let a=this._components[e.componentName],i=this.substituteAliases({stateVariables:[e.stateVariable],componentClass:a.constructor})[0];void 0===n[e.componentName]&&(n[e.componentName]={});let o=n[e.componentName],s=a.state[i],l=s.additionalStateVariablesDefined,u=[i];l&&u.push(...l);for(let e of u)if(!a.state[e].isResolved){if(!(await this.dependencies.resolveItem({componentName:a.componentName,type:"stateVariable",stateVariable:e,force:!0})).success)throw Error(`Can't get value of ${i} of ${a.componentName} as ${e} couldn't be resolved.`)}let c=await this.getStateVariableDefinitionArguments({component:a,stateVariable:i,excludeDependencyValues:s.excludeDependencyValuesInInverseDefinition});c.componentInfoObjects=this.componentInfoObjects,c.initialChange=t,c.stateValues=a.stateValues,c.overrideFixed=e.overrideFixed,c.shadowedVariable=e.shadowedVariable,c.sourceInformation=e.sourceInformation;let p=i;if(s.isArrayEntry){let t=s.arrayStateVariable;p=t;let n={};if(1===c.arrayKeys.length){if("value"in e)n[c.arrayKeys[0]]=e.value;else if("valueOfStateVariable"in e){let t=this.substituteAliases({stateVariables:[e.valueOfStateVariable],componentClass:a.constructor})[0],r=a.state[t];if(!r)throw Error(`Invalid instruction to change ${e.stateVariable} of ${e.componentName}, value of state variable ${e.valueOfStateVariable} not found.`);n[c.arrayKeys[0]]=await r.value}}else for(let[t,r]of c.arrayKeys.entries())if(Array.isArray(e.value))n[r]=e.value[t];else if(e.value instanceof me$3.class)try{n[r]=e.value.get_component(t)}catch(e){}c.desiredStateVariableValues={[t]:n}}else if("value"in e)c.desiredStateVariableValues={[i]:e.value};else if("valueOfStateVariable"in e){let t=this.substituteAliases({stateVariables:[e.valueOfStateVariable],componentClass:a.constructor})[0],n=a.state[t];if(!n)throw Error(`Invalid instruction to change ${e.stateVariable} of ${e.componentName}, value of state variable ${e.valueOfStateVariable} not found.`);c.desiredStateVariableValues={[i]:await n.value}}let d=o[p];if(void 0===d&&(d=o[p]={}),s.additionalStateVariablesDefined)for(let e of s.additionalStateVariablesDefined){let t=e;a.state[e].isArray&&(t=s.arrayStateVariable);let n=o[t];n&&(Object.assign(d,n),o[t]=d)}if(c.workspace=d,e.additionalStateVariableValues)for(let t in e.additionalStateVariableValues)s.additionalStateVariablesDefined.includes(t)?c.desiredStateVariableValues[t]=e.additionalStateVariableValues[t]:console.warn(`Can't invert ${t} at the same time as ${i}, as not an additional state variable defined`);if(!s.inverseDefinition)return void console.warn(`Cannot change state variable ${i} of ${a.componentName} as it doesn't have an inverse definition`);if(await a.stateValues.fixed&&!e.overrideFixed&&!s.ignoreFixed)return void console.log(`Changing ${i} of ${a.componentName} did not succeed because fixed is true.`);if(!t&&!1===await a.stateValues.modifyIndirectly)return void console.log(`Changing ${i} of ${a.componentName} did not succeed because modifyIndirectly is false.`);let m=await s.inverseDefinition(c);if(!m.success)return;let f,h=[];for(let e of m.instructions){let t=!1;if(e.setDependency){let n=e.setDependency,r=this.dependencies.downstreamDependencies[a.componentName][i][n];if(["stateVariable","parentStateVariable"].includes(r.dependencyType)&&1===r.downstreamComponentNames.length){let n=r.downstreamComponentNames[0],a=r.mappedDownstreamVariableNamesByComponent[0][0],i=this._components[n].state[a];if((i.isArrayEntry||i.isArray)&&!i.doNotCombineInverseArrayInstructions){let r=i.isArrayEntry?i.arrayStateVariable:a;if(!f||f.componentName===n&&f.stateVariable===r&&f.shadowedVariable===e.shadowedVariable&&f.treatAsInitialChange===e.treatAsInitialChange||(h.push(f),f=void 0),!e.additionalDependencyValues&&!i.basedOnArrayKeyStateVariables)if(t=!0,f||(f={combinedArray:!0,componentName:n,stateVariable:r,shadowedVariable:e.shadowedVariable,treatAsInitialChange:e.treatAsInitialChange,desiredValue:{}}),i.isArrayEntry){let t=await i.arrayKeys;if(1===t.length)f.desiredValue[t[0]]=e.desiredValue;else for(let[n,r]of t.entries())f.desiredValue[r]=e.desiredValue[n]}else Object.assign(f.desiredValue,e.desiredValue)}}}t||(f&&(h.push(f),f=void 0),h.push(e))}f&&(h.push(f),f=void 0);for(let t of h)if(t.setEssentialValue){if(!u.includes(t.setEssentialValue)){let e=!1;if(s.isArrayEntry){let n=[s.arrayStateVariable];if(s.additionalStateVariablesDefined)for(let e of s.additionalStateVariablesDefined){let t=a.state[e];t.isArrayEntry&&n.push(t.arrayStateVariable)}e=n.includes(t.setEssentialValue)}if(!e)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: specified changing value of ${t.setEssentialValue}, which is not a state variable defined with ${i}.`)}if(!a.state[t.setEssentialValue].hasEssential)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: can't set essential value of ${t.setEssentialValue} if it is does not have an essential value.`);if(!("value"in t))throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: setEssentialValue must specify a value`);let e=t.value;if(e instanceof me$3.class){e=(await preprocessMathInverseDefinition({desiredValue:e,stateValues:a.stateValues,variableName:t.setEssentialValue,workspace:d})).desiredValue}if(a.state[t.setEssentialValue].doNotShadowEssential||a.state[t.setEssentialValue].shadowVariable)this.calculateEssentialVariableChanges({component:a,varName:t.setEssentialValue,value:e,newStateVariableValues:r,recurseToShadows:!1});else{let n=a;for(;n.shadows&&void 0===n.shadows.propVariable;)n=this._components[n.shadows.componentName];this.calculateEssentialVariableChanges({component:n,varName:t.setEssentialValue,value:e,newStateVariableValues:r})}}else if(t.setDependency){let o=t.setDependency,s=this.dependencies.downstreamDependencies[a.componentName][i][o];if("child"===s.dependencyType){let l=t.childIndex;if(null!==s.downstreamPrimitives[l]){if(typeof t.desiredValue==typeof s.downstreamPrimitives[l]){let e=this._components[s.parentName],n=s.activeChildrenIndices[l];if(e.compositeReplacementActiveRange)for(let r of e.compositeReplacementActiveRange)if(r.firstInd<=n&&r.lastInd>=n)throw console.log(`parent: ${e.componentName}, activeChildInd: ${n}`),console.log(e.compositeReplacementActiveRange),console.log(t),Error("Need to implement changing primitive replacements from composite");let a=n;if(e.compositeReplacementActiveRange)for(let t of e.compositeReplacementActiveRange)t.lastInd!e)).length-1,c=s.downstreamComponentNames[u];if(!c)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: ${o} child of index ${t.childIndex} does not exist.`);let p=s.mappedDownstreamVariableNamesByComponent[t.childIndex][t.variableIndex];if(!p)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: ${o} variable of index ${t.variableIndex} does not exist.`);let d={componentName:c,stateVariable:p,value:t.desiredValue,overrideFixed:e.overrideFixed,arrayKey:t.arrayKey};await this.requestComponentChanges({instruction:d,initialChange:!0===t.treatAsInitialChange,workspace:n,newStateVariableValues:r})}}else if(["attributeComponent","shadowSource","adapterSource","targetComponent"].includes(s.dependencyType)){let l=s.downstreamComponentNames[0],u=s.mappedDownstreamVariableNamesByComponent[0][t.variableIndex];if(!u)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: ${o} variable of index ${t.variableIndex} does not exist.`);let c={componentName:l,stateVariable:u,value:t.desiredValue,overrideFixed:e.overrideFixed,arrayKey:t.arrayKey};await this.requestComponentChanges({instruction:c,initialChange:!0===t.treatAsInitialChange,workspace:n,newStateVariableValues:r})}else{if(!["stateVariable","parentStateVariable","adapterSourceStateVariable","sourceCompositeStateVariable"].includes(s.dependencyType)||1!==s.downstreamComponentNames.length)throw Error(`unimplemented dependency type ${s.dependencyType} in requestComponentChanges`);{let l=s.downstreamComponentNames[0],u=s.mappedDownstreamVariableNamesByComponent[0][0],c={componentName:l,stateVariable:u,value:t.desiredValue,overrideFixed:e.overrideFixed,shadowedVariable:t.shadowedVariable};if(t.additionalDependencyValues){let e=this.components[l].state[u];for(let n in t.additionalDependencyValues){let r=this.dependencies.downstreamDependencies[a.componentName][i][n];if(!["stateVariable","parentStateVariable"].includes(r.dependencyType)||1!==r.downstreamComponentNames.length){console.warn(`Can't simultaneously set additional dependency value ${n} if it isn't a state variable`);continue}let s=r.mappedDownstreamVariableNamesByComponent[0][0];r.downstreamComponentNames[0]===l&&e.additionalStateVariablesDefined.includes(s)?(c.additionalStateVariableValues||(c.additionalStateVariableValues={}),c.additionalStateVariableValues[s]=t.additionalDependencyValues[n]):console.warn(`Can't simultaneously set additional dependency value ${n} if it doesn't correspond to additional state variable defined of ${o}'s state variable`)}}await this.requestComponentChanges({instruction:c,initialChange:!0===t.treatAsInitialChange,workspace:n,newStateVariableValues:r})}}}else{if(!t.combinedArray)throw console.log(t),Error(`Unrecognized instruction in inverse definition of ${i} of ${a.componentName}`);{let a={componentName:t.componentName,stateVariable:t.stateVariable,value:t.desiredValue,overrideFixed:e.overrideFixed,shadowedVariable:t.shadowedVariable};await this.requestComponentChanges({instruction:a,initialChange:!0===t.treatAsInitialChange,workspace:n,newStateVariableValues:r})}}}calculateEssentialVariableChanges({component:e,varName:t,value:n,newStateVariableValues:r,recurseToShadows:a=!0}){if(r[e.componentName]||(r[e.componentName]={}),e.state[t].isArray?(r[e.componentName][t]||(r[e.componentName][t]={mergeObject:!0}),Object.assign(r[e.componentName][t],n)):r[e.componentName][t]=n,a&&e.shadowedBy)for(let a of e.shadowedBy)void 0===a.shadows.propVariable&&this.calculateEssentialVariableChanges({component:a,varName:t,value:n,newStateVariableValues:r})}calculatePrimitiveChildChanges({parent:e,definingInd:t,newValue:n,newStateVariableValues:r,markToIgnoreForParent:a}){if(r[e.componentName]||(r[e.componentName]={}),e.componentName===a?r[e.componentName][`__def_primitive_ignore_${t}`]=n:r[e.componentName][`__def_primitive_${t}`]=n,e.shadowedBy)for(let i of e.shadowedBy)void 0===i.shadows.propVariable&&this.calculatePrimitiveChildChanges({parent:i,definingInd:t,newValue:n,newStateVariableValues:r,markToIgnoreForParent:a})}async saveState(e=!1){if(this.savePageStateTimeoutID=null,!this.flags.allowSaveState&&!this.flags.allowLocalState)return;let t=nanoid();this.flags.allowLocalState&&await set(`${this.doenetId}|${this.pageNumber}|${this.attemptNumber}|${this.cid}`,{coreState:this.cumulativeStateVariableChanges,rendererState:this.rendererState,coreInfo:this.coreInfo,saveId:t}),postMessage({messageType:"savedState",coreId:this.coreId}),this.flags.allowSaveState&&(this.pageStateToBeSavedToDatabase={cid:this.cid,coreInfo:this.coreInfoString,coreState:JSON.stringify(this.cumulativeStateVariableChanges,serializedComponentsReplacer),rendererState:JSON.stringify(this.rendererState,serializedComponentsReplacer),pageNumber:this.pageNumber,attemptNumber:this.attemptNumber,doenetId:this.doenetId,saveId:t,serverSaveId:this.serverSaveId,updateDataOnContentChange:this.updateDataOnContentChange},this.changesToBeSaved=!0,await this.saveChangesToDatabase(e))}async saveChangesToDatabase(e){if(!this.changesToBeSaved)return;if(null!==this.saveStateToDBTimerId){if(!e)return;clearTimeout(this.saveStateToDBTimerId)}let t;this.changesToBeSaved=!1,this.saveStateToDBTimerId=setTimeout((()=>{this.saveStateToDBTimerId=null,this.saveChangesToDatabase()}),6e4);try{t=await axios.post("/api/savePageState.php",this.pageStateToBeSavedToDatabase)}catch(e){return void postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"Error synchronizing data. Changes not saved to the server.",toastType:toastType.ERROR}})}if(console.log("result from saving to database:",t.data),null===t.status)return void postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"Error synchronizing data. Changes not saved to the server. Are you connected to the internet?",toastType:toastType.ERROR}});let n=t.data;n.success?(this.serverSaveId=n.saveId,this.flags.allowLocalState&&await set(`${this.doenetId}|${this.pageNumber}|${this.attemptNumber}|${this.cid}|ServerSaveId`,n.saveId),n.stateOverwritten&&(this.attemptNumber!==Number(n.attemptNumber)||this.cid===n.cid?(this.flags.allowLocalState&&await set(`${this.doenetId}|${this.pageNumber}|${n.attemptNumber}|${n.cid}`,{coreState:JSON.parse(n.coreState,serializedComponentsReviver),rendererState:JSON.parse(n.rendererState,serializedComponentsReviver),coreInfo:JSON.parse(n.coreInfo,serializedComponentsReviver),saveId:n.saveId}),postMessage({messageType:"resetPage",coreId:this.coreId,args:{changedOnDevice:n.device,newCid:n.cid,newAttemptNumber:Number(n.attemptNumber)}})):postMessage({messageType:"inErrorState",coreId:this.coreId,args:{errMsg:"Content changed unexpectedly!"}}))):postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:n.message,toastType:toastType.ERROR}})}saveSubmissions({pageCreditAchieved:e,suppressToast:t=!1}){if(!this.flags.allowSaveSubmissions)return;const n={doenetId:this.doenetId,attemptNumber:this.attemptNumber,credit:e,itemNumber:this.itemNumber};console.log("payload for save credit for item",n),axios.post("/api/saveCreditForItem.php",n).then((e=>{if(null===e.status)postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"Credit not saved due to error. Are you connected to the internet?",toastType:toastType.ERROR}});else if(e.data.success){let n=e.data;postMessage({messageType:"updateCreditAchieved",coreId:this.coreId,args:{creditByItem:n.creditByItem.map(Number),creditForAssignment:Number(n.creditForAssignment),creditForAttempt:Number(n.creditForAttempt),showCorrectness:"1"===n.showCorrectness,totalPointsOrPercent:Number(n.totalPointsOrPercent)}}),n.viewedSolution&&(t||postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"No credit awarded since solution was viewed.",toastType:toastType.INFO}})),n.timeExpired&&(t||postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"No credit awarded since the time allowed has expired.",toastType:toastType.INFO}})),n.pastDueDate&&(t||postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"No credit awarded since the due date has passed.",toastType:toastType.INFO}})),n.exceededAttemptsAllowed&&(t||postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"No credit awarded since no more attempts are allowed.",toastType:toastType.INFO}})),n.databaseError&&postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"Credit not saved due to database error.",toastType:toastType.ERROR}})}else postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:`Credit not saved due to error: ${e.data.message}`,toastType:toastType.ERROR}})})).catch((e=>{postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:`Credit not saved due to error: ${e.message}`,toastType:toastType.ERROR}})}))}async recordSolutionView(){if(!this.flags.allowSaveSubmissions)return{allowView:!0,message:"",scoredComponent:this.documentName};try{const e=await axios.post("/api/reportSolutionViewed.php",{doenetId:this.doenetId,itemNumber:this.itemNumber,pageNumber:this.pageNumber,attemptNumber:this.attemptNumber});if(null===e.status){let e="Cannot show solution due to error. Are you connected to the internet?";return postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:e,toastType:toastType.ERROR}}),{allowView:!1,message:e,scoredComponent:this.documentName}}{let t=e.data;if(t.success)return{allowView:!0,message:"",scoredComponent:this.documentName};return{allowView:!1,message:`Cannot show solution due to error: ${t.message}`,scoredComponent:this.documentName}}}catch(e){let t="Cannot show solution due to error.";return postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:t,toastType:toastType.ERROR}}),{allowView:!1,message:t,scoredComponent:this.documentName}}}get scoredItemWeights(){return(async()=>(await this.document.stateValues.scoredDescendants).map((e=>e.stateValues.weight)))()}requestAnimationFrame(e){postMessage({messageType:"requestAnimationFrame",coreId:this.coreId,args:e})}cancelAnimationFrame(e){postMessage({messageType:"cancelAnimationFrame",coreId:this.coreId,args:e})}handleVisibilityChange({visible:e}){e?this.resumeVisibilityMeasuring():this.suspendVisibilityMeasuring()}handleNavigatingToComponent(e){let t=this._components[e];t?.actions?.revealSection&&this.requestAction({componentName:t.componentName,actionName:"revealSection"})}async terminate(){if(await this.suspendVisibilityMeasuring(),this.submitAnswersTimeout&&(clearTimeout(this.submitAnswersTimeout),await this.autoSubmitAnswers()),this.stopProcessingRequests=!0,this.processing)for(let e=0;e<10&&(await new Promise(((e,t)=>{setTimeout(e,100)})),this.processing);e++);this.savePageStateTimeoutID?(clearTimeout(this.savePageStateTimeoutID),await this.saveState(!0)):await this.saveChangesToDatabase(!0)}recordAnswerToAutoSubmit(e){this.answersToSubmit||(this.answersToSubmit=[]),this.answersToSubmit.includes(e)||this.answersToSubmit.push(e),clearTimeout(this.submitAnswersTimeout),this.submitAnswersTimeout=setTimeout((()=>{this.autoSubmitAnswers()}),1e3)}async autoSubmitAnswers(){let e=this.answersToSubmit;this.answersToSubmit=[];for(let t of e){this._components[t].actions.submitAnswer&&await this.requestAction({componentName:t,actionName:"submitAnswer"})}}}function validateAttributeValue({value:e,attributeSpecification:t,attribute:n}){return t.valueTransformations&&e in t.valueTransformations&&(e=t.valueTransformations[e]),void 0===t.transformNonFiniteTo||Number.isFinite(e)||(e=t.transformNonFiniteTo),t.toLowerCase&&(e=e.toLowerCase()),t.trim&&(e=e.trim()),t.validValues?t.validValues.includes(e)||(console.warn(`Invalid value ${e} for attribute ${n}, using value ${t.defaultValue}`),e=t.defaultValue):t.clamp&&(et.clamp[1]?e=t.clamp[1]:Number.isFinite(e)||(e=t.defaultValue)),e}function calculateAllComponentsShadowing(e){let t=[];if(e.shadowedBy)for(let n of e.shadowedBy)if(!n.shadows.propVariable){t.push(n.componentName);let e=calculateAllComponentsShadowing(n);t.push(...e)}if(e.replacementOf){let n=calculateAllComponentsShadowing(e.replacementOf);t.push(...n)}return t}return Core}(); + * Copyright (c) 2022 Handsoncode. All rights reserved. + */class HyperFormulaNS extends HyperFormula{}HyperFormulaNS.HyperFormula=HyperFormula,HyperFormulaNS.ErrorType=ErrorType,HyperFormulaNS.CellType=CellType,HyperFormulaNS.CellValueType=CellValueType,HyperFormulaNS.CellValueDetailedType=CellValueDetailedType,HyperFormulaNS.DetailedCellError=DetailedCellError,HyperFormulaNS.ExportedCellChange=ExportedCellChange,HyperFormulaNS.ExportedNamedExpressionChange=ExportedNamedExpressionChange,HyperFormulaNS.ConfigValueTooBigError=ConfigValueTooBigError,HyperFormulaNS.ConfigValueTooSmallError=ConfigValueTooSmallError,HyperFormulaNS.EvaluationSuspendedError=EvaluationSuspendedError,HyperFormulaNS.ExpectedOneOfValuesError=ExpectedOneOfValuesError,HyperFormulaNS.ExpectedValueOfTypeError=ExpectedValueOfTypeError,HyperFormulaNS.FunctionPlugin=FunctionPlugin,HyperFormulaNS.FunctionPluginValidationError=FunctionPluginValidationError,HyperFormulaNS.InvalidAddressError=InvalidAddressError,HyperFormulaNS.InvalidArgumentsError=InvalidArgumentsError,HyperFormulaNS.LanguageNotRegisteredError=LanguageNotRegisteredError,HyperFormulaNS.LanguageAlreadyRegisteredError=LanguageAlreadyRegisteredError,HyperFormulaNS.MissingTranslationError=MissingTranslationError,HyperFormulaNS.NamedExpressionDoesNotExistError=NamedExpressionDoesNotExistError,HyperFormulaNS.NamedExpressionNameIsAlreadyTakenError=NamedExpressionNameIsAlreadyTakenError,HyperFormulaNS.NamedExpressionNameIsInvalidError=NamedExpressionNameIsInvalidError,HyperFormulaNS.NoOperationToRedoError=NoOperationToRedoError,HyperFormulaNS.NoOperationToUndoError=NoOperationToUndoError,HyperFormulaNS.NoRelativeAddressesAllowedError=NoRelativeAddressesAllowedError,HyperFormulaNS.NoSheetWithIdError=NoSheetWithIdError,HyperFormulaNS.NoSheetWithNameError=NoSheetWithNameError,HyperFormulaNS.NotAFormulaError=NotAFormulaError,HyperFormulaNS.NothingToPasteError=NothingToPasteError,HyperFormulaNS.ProtectedFunctionTranslationError=ProtectedFunctionTranslationError,HyperFormulaNS.SheetNameAlreadyTakenError=SheetNameAlreadyTakenError,HyperFormulaNS.SheetSizeLimitExceededError=SheetSizeLimitExceededError,HyperFormulaNS.SourceLocationHasArrayError=SourceLocationHasArrayError,HyperFormulaNS.TargetLocationHasArrayError=TargetLocationHasArrayError,HyperFormulaNS.UnableToParseError=UnableToParseError;const defaultLanguage=Config.defaultConfig.language;HyperFormula.registerLanguage(defaultLanguage,dictionary),HyperFormula.languages[dictionary.langCode]=dictionary;for(const e of Object.getOwnPropertyNames(plugins))e.startsWith("_")||HyperFormula.registerFunctionPlugin(plugins[e]);class Spreadsheet extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{onChange:this.onChange.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="spreadsheet";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:100,isAbsolute:!1},public:!0,forRenderer:!0},e.minNumRows={createComponentOfType:"number",createStateVariable:"minNumRows",defaultValue:4,public:!0,forRenderer:!0},e.minNumColumns={createComponentOfType:"number",createStateVariable:"minNumColumns",defaultValue:4,public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize"},e.columnHeaders={createComponentOfType:"boolean",createStateVariable:"columnHeaders",defaultValue:!0,public:!0,forRenderer:!0},e.rowHeaders={createComponentOfType:"boolean",createStateVariable:"rowHeaders",defaultValue:!0,public:!0,forRenderer:!0},e.fixedRowsTop={createComponentOfType:"integer",createStateVariable:"fixedRowsTop",defaultValue:0,clamp:[0,1/0],public:!0,forRenderer:!0},e.fixedColumnsLeft={createComponentOfType:"integer",createStateVariable:"fixedColumnsLeft",defaultValue:0,clamp:[0,1/0],public:!0,forRenderer:!0},e.hiddenColumns={createComponentOfType:"numberList",createStateVariable:"hiddenColumns",defaultValue:[],public:!0,forRenderer:!0},e.hiddenRows={createComponentOfType:"numberList",createStateVariable:"hiddenRows",defaultValue:[],public:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"cells",componentTypes:["cell"]},{group:"rows",componentTypes:["row"]},{group:"columns",componentTypes:["column"]},{group:"cellBlocks",componentTypes:["cellBlock"]},{group:"dataFrames",componentTypes:["dataFrame"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.cellNameToRowCol={additionalStateVariablesDefined:["cellNamesByRowCol"],returnDependencies:()=>({cellRelatedChildren:{dependencyType:"child",childGroups:["cells","rows","columns","cellBlocks"],variableNames:["rowNum","colNum","prescribedCellsWithColNum","prescribedCellsWithRowNum","prescribedCellsRowsColumnsBlocks"],variablesOptional:!0}}),definition({dependencyValues:e,componentInfoObjects:t}){let n=determineCellMapping({cellRelatedChildren:e.cellRelatedChildren,componentInfoObjects:t});return{setValue:{cellNameToRowCol:n.cellNameToRowCol,cellNamesByRowCol:n.cellNamesByRowCol}}}},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({minNumRows:{dependencyType:"stateVariable",variableName:"minNumRows"},cellNamesByRowCol:{dependencyType:"stateVariable",variableName:"cellNamesByRowCol"},dataFrameChild:{dependencyType:"child",childGroups:["dataFrames"],variableNames:["numRows"]}}),definition({dependencyValues:e}){let t=e.minNumRows;return Number.isFinite(t)||(t=4),t=Math.max(t,e.cellNamesByRowCol.length),e.dataFrameChild.length>0&&(t=Math.max(t,e.dataFrameChild[0].stateValues.numRows)),{setValue:{numRows:t}}}},e.numColumns={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({minNumColumns:{dependencyType:"stateVariable",variableName:"minNumColumns"},cellNamesByRowCol:{dependencyType:"stateVariable",variableName:"cellNamesByRowCol"},dataFrameChild:{dependencyType:"child",childGroups:["dataFrames"],variableNames:["numColumns"]}}),definition({dependencyValues:e}){let t=e.minNumColumns;Number.isFinite(t)||(t=4);for(let n of e.cellNamesByRowCol)n&&(t=Math.max(t,n.length));return e.dataFrameChild.length>0&&(t=Math.max(t,e.dataFrameChild[0].stateValues.numColumns)),{setValue:{numColumns:t}}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},forRenderer:!0,returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]},numRows:{dependencyType:"stateVariable",variableName:"numRows"}}),definition({dependencyValues:e}){if(null===e.heightAttr){let t;return t=Number.isFinite(e.numRows)&&e.numRows>=0?40+23*e.numRows:132,{setValue:{height:{size:t,isAbsolute:!0}}}}return{setValue:{height:e.heightAttr.stateValues.componentSize}}}},e.cells={public:!0,shadowingInstructions:{createComponentOfType:"cell",returnWrappingComponents:e=>"cell"===e?[]:"row"===e?[["row"]]:"column"===e?[["column"]]:[["row"],["cellBlock"]]},forRenderer:!0,isArray:!0,entryPrefixes:["cell","row","column","range","rows","columns"],nDimensions:2,defaultValueByArrayKey:()=>"",hasEssential:!0,shadowVariable:!0,stateVariablesDeterminingDependencies:["cellNamesByRowCol"],returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnEntryDimensions:e=>["range","rows","columns"].includes(e)?2:1,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("cell"===e){let e,r,a=/^([a-zA-Z]+)([1-9]\d*)$/,i=t.match(a);if(i)r=i[1],e=i[2];else{let n=/^\(([a-zA-Z]+|\d+),([a-zA-Z]+|\d+)\)$/;if(i=t.match(n),!i)return[];e=i[1],r=i[2]}let s=normalizeIndex(e),o=normalizeIndex(r);return s>=0&&o>=0&&(!n||s=0))return[];if(!n)return[String(e)+",0"];if(!(e=0))return[];if(!n)return["0,"+String(e)];if(!(e=0&&a>=0&&r>=0&&i>=0))return[];if(!n)return[String(e)+","+String(r)];let l=Math.min(Math.min(e,a),n[0]-1),u=Math.min(Math.max(e,a),n[0]-1),c=Math.min(Math.min(r,i),n[1]-1),p=Math.min(Math.max(r,i),n[1]-1),d=[];for(let e=l;e<=u;e++){let t=[],n=String(e)+",";for(let e=c;e<=p;e++)t.push(n+e);d.push(t)}return d}{if(!n)return[String(0)+","+String(0)];let e=[];for(let t=0;t"cell("+e.split(",").map((e=>Number(e)+1)).join(",")+")",arrayVarNameFromPropIndex(e,t){if("cells"===t||"rows"===t)return 1===e.length?"row"+e[0]:`cell(${e[0]},${e[1]})`;if("columns"===t)return 1===e.length?"column"+e[0]:`cell(${e[1]},${e[0]})`;if("row"===t.slice(0,3)){return`cell(${t.slice(3)},${e[0]})`}if("column"===t.slice(0,6)){let n=t.slice(6);return`cell(${e[0]},${n})`}return null},returnArrayDependenciesByKey({stateValues:e,arrayKeys:t}){let n={},r=e.cellNamesByRowCol;for(let e of t){let[t,a]=e.split(",");r[t]&&r[t][a]&&(n[e]={cellText:{dependencyType:"stateVariable",componentName:r[t][a],variableName:"text",variablesOptional:!0}})}return{dependenciesByKey:n,globalDependencies:{dataFrameChild:{dependencyType:"child",childGroups:["dataFrames"],variableNames:["dataFrame","numRows","numColumns"]}}}},arrayDefinitionByKey({dependencyValuesByKey:e,globalDependencyValues:t,arrayKeys:n}){let r,a,i={},s={},o=null;t.dataFrameChild.length>0&&(o=t.dataFrameChild[0],r=o.stateValues.numRows,a=o.stateValues.numColumns);for(let t of n){let[n,l]=t.split(",");void 0!==e[t].cellText?i[t]=e[t].cellText:n0&&(l.setValue={cells:i}),Object.keys(s).length>0&&(l.useEssentialOrDefaultValue={cells:s}),l},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.cells)if(void 0!==t[r].cellText)n.push({setDependency:t[r].cellText,desiredValue:e.cells[r]});else{let t=e.cells[r];n.push({setEssentialValue:"cells",value:{[r]:null===t?"":String(t)}})}return{success:!0,instructions:n}}},e.evaluatedCells={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"cell",returnWrappingComponents:e=>"evaluatedCell"===e?[]:"evaluatedRow"===e?[["row"]]:"evaluatedColumn"===e?[["column"]]:[["row"],["cellBlock"]]},entryPrefixes:["evaluatedCell","evaluatedRow","evaluatedColumn","evaluatedRange","evaluatedRows","evaluatedColumns"],nDimensions:2,stateVariablesDeterminingDependencies:["cellNamesByRowCol"],returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnEntryDimensions:e=>["evaluatedRange","evaluatedRows","evaluatedColumns"].includes(e)?2:1,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("evaluatedCell"===e){let e,r,a=/^([a-zA-Z]+)([1-9]\d*)$/,i=t.match(a);if(i)r=i[1],e=i[2];else{let n=/^\(([a-zA-Z]+|\d+),([a-zA-Z]+|\d+)\)$/;if(i=t.match(n),!i)return[];e=i[1],r=i[2]}let s=normalizeIndex(e),o=normalizeIndex(r);return s>=0&&o>=0&&(!n||s=0))return[];if(!n)return[String(e)+",0"];if(!(e=0))return[];if(!n)return["0,"+String(e)];if(!(e=0&&a>=0&&r>=0&&i>=0))return[];if(!n)return[String(e)+","+String(r)];let l=Math.min(Math.min(e,a),n[0]-1),u=Math.min(Math.max(e,a),n[0]-1),c=Math.min(Math.min(r,i),n[1]-1),p=Math.min(Math.max(r,i),n[1]-1),d=[];for(let e=l;e<=u;e++){let t=[],n=String(e)+",";for(let e=c;e<=p;e++)t.push(n+e);d.push(t)}return d}{if(!n)return[String(0)+","+String(0)];let e=[];for(let t=0;t"evaluatedCell("+e.split(",").map((e=>Number(e)+1)).join(",")+")",arrayVarNameFromPropIndex(e,t){if("evaluatedCells"===t||"evaluatedRows"===t)return 1===e.length?"evaluatedRow"+e[0]:`evaluatedCell(${e[0]},${e[1]})`;if("evaluatedColumns"===t)return 1===e.length?"evaluatedColumn"+e[0]:`evaluatedCell(${e[1]},${e[0]})`;if("evaluatedRow"===t.slice(0,12)){return`evaluatedCell(${t.slice(12)},${e[0]})`}if("evaluatedColumn"===t.slice(0,15)){let n=t.slice(15);return`evaluatedCell(${e[0]},${n})`}return null},returnArrayDependenciesByKey:()=>({globalDependencies:{cells:{dependencyType:"stateVariable",variableName:"cells"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=HyperFormula.buildFromArray(e.cells,{licenseKey:"gpl-v3"}).getSheetValues(0),n={};for(let e in t){let r=t[e];for(let t in r)n[[e,t]]=r[t]}return{setValue:{evaluatedCells:n}}}},e.pointsInCells={isArray:!0,nDimensions:2,public:!0,shadowingInstructions:{createComponentOfType:"point"},entryPrefixes:["pointsInCell","pointsInRow","pointsInColumn","pointsInRange","pointsInRows","pointsInColumns"],returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnEntryDimensions:e=>["pointsInRange","pointsInRows","pointsInColumns"].includes(e)?2:1,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointsInCell"===e){let e,r,a=/^([a-zA-Z]+)([1-9]\d*)$/,i=t.match(a);if(i)r=i[1],e=i[2];else{let n=/^\(([a-zA-Z]+|\d+),([a-zA-Z]+|\d+)\)$/;if(i=t.match(n),!i)return[];e=i[1],r=i[2]}let s=normalizeIndex(e),o=normalizeIndex(r);return s>=0&&o>=0&&(!n||s=0))return[];if(!n)return[String(e),",0"];if(!(e>=0&&e=0))return[];if(!n)return["0,"+String(e)];if(!(e=0&&a>=0&&r>=0&&i>=0))return[];if(!n)return[String(e)+","+String(r)];let l=Math.min(Math.min(e,a),n[0]-1),u=Math.min(Math.max(e,a),n[0]-1),c=Math.min(Math.min(r,i),n[1]-1),p=Math.min(Math.max(r,i),n[1]-1),d=[];for(let e=l;e<=u;e++){let t=[],n=String(e)+",";for(let e=c;e<=p;e++)t.push(n+e);d.push(t)}return d}{if(!n)return[String(0)+","+String(0)];let e=[];for(let t=0;t"pointsInCell("+e.split(",").map((e=>Number(e)+1)).join(",")+")",arrayVarNameFromPropIndex(e,t){if("pointsInCells"===t||"pointsInRows"===t)return 1===e.length?"pointsInRow"+e[0]:`pointsInCell(${e[0]},${e[1]})`;if("pointsInColumns"===t)return 1===e.length?"pointsInColumn"+e[0]:`pointsInCell(${e[1]},${e[0]})`;if("pointsInRow"===t.slice(0,11)){return`pointsInCell(${t.slice(11)},${e[0]})`}if("pointsInColumn"===t.slice(0,14)){let n=t.slice(14);return`pointsInCell(${e[0]},${n})`}return null},returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e)+1)).join(",");t[n]={cellText:{dependencyType:"stateVariable",variableName:`evaluatedCell(${e})`,variablesOptional:!0}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t,a=e[r].cellText;if(a){try{t=me$3.fromAst(textToAst$1.convert(a))}catch(e){n[r]=null;continue}Array.isArray(t.tree)&&vectorOperators.includes(t.tree[0])?n[r]=t:n[r]=null}else n[r]=null}return{setValue:{pointsInCells:n}}}},e}async onChange({changes:e,source:t,actionId:n}){if(e){let t={};for(let n of e){let[e,r,a,i]=n;t[[e,r]]=null===i?"":i}return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"cells",value:t}],actionId:n,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:t}})}this.coreFunctions.resolveAction({actionId:n})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}function determineCellMapping({cellRelatedChildren:e,rowOffset:t=0,colOffset:n=0,cellNameToRowCol:r={},cellNamesByRowCol:a=[],componentInfoObjects:i}){var s=t,o=n,l=n,u=t,c=n,p=t,d=n;for(let m of e)if(i.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"cell"})){let e=m,i=normalizeIndex(e.stateValues.rowNum),u=normalizeIndex(e.stateValues.colNum);void 0===i?(i=s,void 0===u?u=l:u+=n):(i+=t,void 0===u?u=o:u+=n),addCellToMapping({cell:e,rowIndex:i,colIndex:u,cellNameToRowCol:r,cellNamesByRowCol:a}),p=Math.max(i,p),d=Math.max(u,d),s=i,o=u,l=u+1}else if(i.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"row"})){let e=m,i=normalizeIndex(e.stateValues.rowNum);void 0===i?i=u:i+=t;let c=e.stateValues.prescribedCellsWithColNum,h=n;for(let e of c){let t=normalizeIndex(e.stateValues.colNum);void 0===t?t=h:t+=n,addCellToMapping({cell:e,rowIndex:i,colIndex:t,cellNameToRowCol:r,cellNamesByRowCol:a}),h=t+1,p=Math.max(i,p),d=Math.max(t,d)}u=i+1,s=i+1,l=o=n}else if(i.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"column"})){let e=m,i=normalizeIndex(e.stateValues.colNum);void 0===i?i=c:i+=n;let u=e.stateValues.prescribedCellsWithRowNum,h=t;for(let e of u){let n=normalizeIndex(e.stateValues.rowNum);void 0===n?n=h:n+=t,addCellToMapping({cell:e,rowIndex:n,colIndex:i,cellNameToRowCol:r,cellNamesByRowCol:a}),h=n+1,p=Math.max(n,p),d=Math.max(i,d)}c=i+1,s=t,l=o=i+1}else if(i.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"cellBlock"})){let e=m,u=normalizeIndex(e.stateValues.rowNum),c=normalizeIndex(e.stateValues.colNum);void 0===u?(u=s,void 0===c?c=l:c+=n):(u+=t,void 0===c?c=o:c+=n);let h=determineCellMapping({cellRelatedChildren:e.stateValues.prescribedCellsRowsColumnsBlocks,rowOffset:u,colOffset:c,cellNameToRowCol:r,cellNamesByRowCol:a,componentInfoObjects:i});p=Math.max(h.maxRowIndex,p),d=Math.max(h.maxColIndex,d),s=u,o=c,l=h.maxColIndex+1}return{maxRowIndex:p,maxColIndex:d,cellNameToRowCol:r,cellNamesByRowCol:a}}function addCellToMapping({cell:e,rowIndex:t,colIndex:n,cellNameToRowCol:r,cellNamesByRowCol:a}){if(r[e.componentName]=[t,n],void 0===a[t]&&(a[t]=[]),void 0!==a[t][n]){console.warn(`Cell is overwriting previous cell at rowNum=${t+1}, colNum=${n+1}`),r[a[t][n]]=null}a[t][n]=e.componentName}class DiscreteSimulationResultList extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{onChange:this.onChange.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="DiscreteSimulationResultList";static rendererType="spreadsheet";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:100,isAbsolute:!1},public:!0,forRenderer:!0},e.minNumRows={createComponentOfType:"number",createStateVariable:"minNumRows",defaultValue:1,public:!0,forRenderer:!0},e.minNumColumns={createComponentOfType:"number",createStateVariable:"minNumColumns",defaultValue:1,public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize"},e.columnHeaders={createComponentOfType:"boolean",createStateVariable:"columnHeaders",defaultValue:!0,public:!0,forRenderer:!0},e.rowHeaders={createComponentOfType:"boolean",createStateVariable:"rowHeaders",defaultValue:!0,public:!0,forRenderer:!0},e.fixedRowsTop={createComponentOfType:"integer",createStateVariable:"fixedRowsTop",defaultValue:0,clamp:[0,1/0],public:!0,forRenderer:!0},e.fixedColumnsLeft={createComponentOfType:"integer",createStateVariable:"fixedColumnsLeft",defaultValue:0,clamp:[0,1/0],public:!0,forRenderer:!0},e.hiddenColumns={createComponentOfType:"numberList",createStateVariable:"hiddenColumns",defaultValue:[],public:!0,forRenderer:!0},e.hiddenRows={createComponentOfType:"numberList",createStateVariable:"hiddenRows",defaultValue:[],public:!0,forRenderer:!0},e.allIterates={createComponentOfType:"mathList",createStateVariable:"allIterates",defaultValue:[]},e.headerRow={createComponentOfType:"textList",createStateVariable:"headerRow",defaultValue:null},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({allIterates:{dependencyType:"stateVariable",variableName:"allIterates"},headerRow:{dependencyType:"stateVariable",variableName:"headerRow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition({dependencyValues:e,usedDefault:t}){let n=[],r=1,a=!1;if(e.allIterates.length>0&&Array.isArray(e.allIterates[0].tree)&&vectorOperators.includes(e.allIterates[0].tree[0])&&(r=e.allIterates[0].tree.length-1,a=!0),e.headerRow){let t=[],a=Math.min(e.headerRow.length,r+1);for(let n=0;n({minNumRows:{dependencyType:"stateVariable",variableName:"minNumRows"},cells:{dependencyType:"stateVariable",variableName:"cells"}}),definition({dependencyValues:e}){let t=e.minNumRows;return Number.isFinite(t)||(t=4),t=Math.max(t,e.cells.length),{setValue:{numRows:t}}}},e.numColumns={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({minNumColumns:{dependencyType:"stateVariable",variableName:"minNumColumns"},cells:{dependencyType:"stateVariable",variableName:"cells"}}),definition({dependencyValues:e}){let t=e.minNumColumns;Number.isFinite(t)||(t=4);for(let n of e.cells)n&&(t=Math.max(t,n.length));return{setValue:{numColumns:t}}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},forRenderer:!0,returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]},numRows:{dependencyType:"stateVariable",variableName:"numRows"}}),definition({dependencyValues:e}){if(null===e.heightAttr){let t;return t=Number.isFinite(e.numRows)&&e.numRows>=0?50+20*e.numRows:130,{setValue:{height:{size:t,isAbsolute:!0}}}}return{setValue:{height:e.heightAttr.stateValues.componentSize}}}},e}async onChange({changes:e,source:t,actionId:n}){if(e){let t={};for(let n of e){let[e,r,a,i]=n;t[[e,r]]=null===i?"":i}return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"cells",value:t}],actionId:n,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:t}})}this.coreFunctions.resolveAction({actionId:n})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class DiscreteSimulationResultPolyline extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{movePolyline:this.movePolyline.bind(this),finalizePolylinePosition:this.finalizePolylinePosition.bind(this)})}static componentType="discreteSimulationResultPolyline";static rendererType="polyline";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.allIterates={createComponentOfType:"mathList",createStateVariable:"allIteratesSub",defaultValue:[]},e.seriesNumber={createComponentOfType:"number",createStateVariable:"seriesNumber",defaultValue:null},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" polyline"}}}},e.allIterates={returnDependencies:()=>({allIteratesSub:{dependencyType:"stateVariable",variableName:"allIteratesSub"}}),definition:function({dependencyValues:e}){return{setValue:{allIterates:e.allIteratesSub.filter((e=>Number.isFinite(e.tree)||Array.isArray(e.tree)&&vectorOperators.includes(e.tree[0])&&e.tree.slice(1).every(Number.isFinite)))}}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({allIterates:{dependencyType:"stateVariable",variableName:"allIterates"}}),definition:function({dependencyValues:e}){return{setValue:{nVertices:e.allIterates.length}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:function({dependencyValues:e}){return{setValue:{nDimensions:2}}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},getAllArrayKeys(e,t=!0,n){function r(e){if(1===e.length)return Array.from(Array(e[0]),((e,t)=>String(t)));{let n=e[0],a=r(e.slice(1)),i=[];for(let e=0;ee+","+t))):i.push(a.map((t=>e+","+t)));return i}}if(n){if(0!==n.length&&e){let t=[...e];return t[0]=n[0],r(t)}return[]}return e&&0!==e.length?r(e):[]},returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices,2],returnArrayDependenciesByKey:()=>({globalDependencies:{seriesNumber:{dependencyType:"stateVariable",variableName:"seriesNumber"},allIterates:{dependencyType:"stateVariable",variableName:"allIterates"}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n={};for(let r=0;r({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={vertex:{dependencyType:"stateVariable",variableName:"vertex"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalVertices:n}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,s=[],o=i[0]?.[0],l=i[0]?.[1];for(let e=1;e=1?{x1:h,x2:f}:{x1:l+g*a*n,x2:u+g*y*o};let b=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/o,2);b0&&(p.x3=0),p}}}}},e}async movePolyline({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){let a={};for(let t in e)a[t+",0"]=me$3.fromAst(e[t][0]),a[t+",1"]=me$3.fromAst(e[t][1]);return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}async finalizePolylinePosition(){return await this.actions.movePolyline({pointCoords:await this.stateValues.numericalVertices,transient:!1})}}class Cell extends BaseComponent{static componentType="cell";static rendererType="cell";static renderChildren=!0;static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="text";static createAttributesObject(){let e=super.createAttributesObject();return e.rowNum={createComponentOfType:"text",createStateVariable:"rowNum",defaultValue:null,public:!0},e.colNum={createComponentOfType:"text",createStateVariable:"colNum",defaultValue:null,public:!0},e.colSpan={createComponentOfType:"integer",createStateVariable:"colSpan",defaultValue:1,public:!0,forRenderer:!0},e.halign={createComponentOfType:"text"},e.bottom={createComponentOfType:"text"},e.right={createComponentOfType:"text"},e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.halign={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,defaultValue:"left",returnDependencies:()=>({halignAttr:{dependencyType:"attributeComponent",attributeName:"halign",variableNames:["value"]},parentHalign:{dependencyType:"parentStateVariable",variableName:"halign"},tabularHalign:{dependencyType:"ancestor",componentType:"tabular",variableNames:["halign"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.halignAttr){let t=e.halignAttr.stateValues.value;return["left","center","right","justify"].includes(t)||(t="left"),{setValue:{halign:t}}}return!t.parentHalign&&e.parentHalign?{setValue:{halign:e.parentHalign}}:!t.tabularHalign&&e.tabularHalign?{setValue:{halign:e.tabularHalign.stateValues.halign}}:{useEssentialOrDefaultValue:{halign:!0}}}},e.bottom={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,defaultValue:"none",returnDependencies:()=>({bottomAttr:{dependencyType:"attributeComponent",attributeName:"bottom",variableNames:["value"]},parentBottom:{dependencyType:"parentStateVariable",variableName:"bottom"},tabularBottom:{dependencyType:"ancestor",componentType:"tabular",variableNames:["bottom"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.bottomAttr){let t=e.bottomAttr.stateValues.value;return["none","minor","medium","major"].includes(t)||(t="none"),{setValue:{bottom:t}}}return!t.parentBottom&&e.parentBottom?{setValue:{bottom:e.parentBottom}}:!t.tabularBottom&&e.tabularBottom?{setValue:{bottom:e.tabularBottom.stateValues.bottom}}:{useEssentialOrDefaultValue:{bottom:!0}}}},e.right={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,defaultValue:"none",returnDependencies:()=>({rightAttr:{dependencyType:"attributeComponent",attributeName:"right",variableNames:["value"]},tabularRight:{dependencyType:"ancestor",componentType:"tabular",variableNames:["right"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.rightAttr){let t=e.rightAttr.stateValues.value;return["none","minor","medium","major"].includes(t)||(t="none"),{setValue:{right:t}}}return!t.tabularRight&&e.tabularRight?{setValue:{right:e.tabularRight.stateValues.right}}:{useEssentialOrDefaultValue:{right:!0}}}},e.inHeader={public:!0,shadowingInstructions:{createComponentOfType:"booloean"},forRenderer:!0,defaultValue:!1,returnDependencies:()=>({parentHeader:{dependencyType:"parentStateVariable",variableName:"header"}}),definition:({dependencyValues:e})=>({setValue:{inHeader:!0===e.parentHeader}})},e.onlyMathChild={returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"]},otherChildren:{dependencyType:"child",childGroups:["anything"]}}),definition:({dependencyValues:e})=>({setValue:{onlyMathChild:1===e.mathChild.length&&0===e.otherChildren.length}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({children:{dependencyType:"child",childGroups:["maths","anything"],variableNames:["text"],variablesOptional:!0},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition({dependencyValues:e}){if(0===e.children.length)return{useEssentialOrDefaultValue:{text:{defaultValue:e.prefill}}};let t="";for(let n of e.children)"object"==typeof n?n.stateValues.text&&(t+=n.stateValues.text):t+=n.toString();return{setValue:{text:t}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>0===t.children.length?{success:!0,instructions:[{setEssentialValue:"text",value:null===e.text?"":String(e.text)}]}:1===t.children.length?"object"==typeof t.children[0]&&void 0===t.children[0].stateValues.text?{success:!1}:{success:!0,instructions:[{setDependency:"children",desiredValue:e.text,childIndex:0,variableIndex:0}]}:{success:!1}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},stateVariablesDeterminingDependencies:["onlyMathChild"],returnDependencies:({stateValues:e})=>e.onlyMathChild?{mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}:{text:{dependencyType:"stateVariable",variableName:"text"}},definition({dependencyValues:e}){if(e.mathChild)return{setValue:{math:e.mathChild[0].stateValues.value}};{let t;try{t=me$3.fromAst(textToAst$1.convert(e.text))}catch(e){t=me$3.fromAst("_")}return{setValue:{math:t}}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r}){if(t.mathChild)return{success:!0,instructions:[{setDependency:"mathChild",desiredValue:e.math,childIndex:0,variableIndex:0}]};return{success:!0,instructions:[{setDependency:"text",desiredValue:(await preprocessMathInverseDefinition({desiredValue:e.math,stateValues:n,variableName:"math",workspace:r})).desiredValue.toString()}]}}},e.number={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({math:{dependencyType:"stateVariable",variableName:"math"}}),definition({dependencyValues:e}){let t=e.math.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),{setValue:{number:t}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"math",desiredValue:me$3.fromAst(e.number)}]})},e}static adapters=["text","math","number"]}class Row extends BaseComponent{static componentType="row";static rendererType="row";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.rowNum={createComponentOfType:"text",createStateVariable:"rowNum",defaultValue:null,public:!0},e.header={createComponentOfType:"boolean",createStateVariable:"header",defaultValue:!1,public:!0,forRenderer:!0},e.halign={createComponentOfType:"text"},e.valign={createComponentOfType:"text"},e.left={createComponentOfType:"text"},e.bottom={createComponentOfType:"text"},e}static returnChildGroups(){return[{group:"cells",componentTypes:["cell"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.halign={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"left",hasEssential:!0,returnDependencies:()=>({halignAttr:{dependencyType:"attributeComponent",attributeName:"halign",variableNames:["value"]},parentHalign:{dependencyType:"parentStateVariable",variableName:"halign"}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.halignAttr){let t=e.halignAttr.stateValues.value;return["left","center","right","justify"].includes(t)||(t="left"),{setValue:{halign:t}}}return null===e.parentHalign||t.parentHalign?{useEssentialOrDefaultValue:{halign:!0}}:{setValue:{halign:e.parentHalign}}}},e.valign={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,defaultValue:"middle",hasEssential:!0,returnDependencies:()=>({valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},parentValign:{dependencyType:"parentStateVariable",variableName:"valign"}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.valignAttr){let t=e.valignAttr.stateValues.value;return["top","middle","bottom"].includes(t)||(t="middle"),{setValue:{valign:t}}}return null===e.parentValign||t.parentValign?{useEssentialOrDefaultValue:{valign:!0}}:{setValue:{valign:e.parentValign}}}},e.left={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,defaultValue:"none",hasEssential:!0,returnDependencies:()=>({leftAttr:{dependencyType:"attributeComponent",attributeName:"left",variableNames:["value"]},parentLeft:{dependencyType:"parentStateVariable",variableName:"left"}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.leftAttr){let t=e.leftAttr.stateValues.value;return["none","minor","medium","major"].includes(t)||(t="none"),{setValue:{left:t}}}return null===e.parentLeft||t.parentLeft?{useEssentialOrDefaultValue:{left:!0}}:{setValue:{left:e.parentLeft}}}},e.bottom={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"none",hasEssential:!0,returnDependencies:()=>({bottomAttr:{dependencyType:"attributeComponent",attributeName:"bottom",variableNames:["value"]},parentBottom:{dependencyType:"parentStateVariable",variableName:"bottom"}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.bottomAttr){let t=e.bottomAttr.stateValues.value;return["none","minor","medium","major"].includes(t)||(t="none"),{setValue:{bottom:t}}}return null===e.parentBottom||t.parentBottom?{useEssentialOrDefaultValue:{bottom:!0}}:{setValue:{bottom:e.parentBottom}}}},e.prescribedCellsWithColNum={returnDependencies:()=>({cellChildren:{dependencyType:"child",childGroups:["cells"],variableNames:["colNum"]}}),definition:({dependencyValues:e})=>({setValue:{prescribedCellsWithColNum:e.cellChildren}})},e}}class Column extends BaseComponent{static componentType="column";static rendererType="containerBlock";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.colNum={createComponentOfType:"text",createStateVariable:"colNum",defaultValue:null,public:!0},e}static returnChildGroups(){return[{group:"cells",componentTypes:["cell"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.prescribedCellsWithRowNum={returnDependencies:()=>({cellChildren:{dependencyType:"child",childGroups:["cells"],variableNames:["rowNum"]}}),definition:({dependencyValues:e})=>({setValue:{prescribedCellsWithRowNum:e.cellChildren}})},e}}class CellBlock extends BaseComponent{static componentType="cellBlock";static rendererType="containerBlock";static createAttributesObject(){let e=super.createAttributesObject();return e.rowNum={createComponentOfType:"text",createStateVariable:"rowNum",defaultValue:null,public:!0},e.colNum={createComponentOfType:"text",createStateVariable:"colNum",defaultValue:null,public:!0},e}static returnChildGroups(){return[{group:"children",componentTypes:["cell","row","column","cellblock"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.prescribedCellsRowsColumnsBlocks={returnDependencies:()=>({cellRelatedChildren:{dependencyType:"child",childGroups:["children"],variableNames:["rowNum","colNum","prescribedCellsWithColNum","prescribedCellsWithRowNum","prescribedCellsRowsColumnsBlocks"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{prescribedCellsRowsColumnsBlocks:e.cellRelatedChildren}})},e}}class Tabular extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="tabular";static rendererType="tabular";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:100,isAbsolute:!1},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:null,public:!0,forRenderer:!0},e.halign={createComponentOfType:"text",createStateVariable:"halign",defaultValue:"left",public:!0,validValues:["left","center","right","justify"]},e.valign={createComponentOfType:"text",createStateVariable:"valign",defaultValue:"middle",public:!0,validValues:["top","middle","bottom"]},e.top={createComponentOfType:"text",createStateVariable:"top",defaultValue:"none",public:!0,validValues:["none","minor","medium","major"],forRenderer:!0},e.left={createComponentOfType:"text",createStateVariable:"left",defaultValue:"none",public:!0,validValues:["none","minor","medium","major"]},e.bottom={createComponentOfType:"text",createStateVariable:"bottom",defaultValue:"none",public:!0,validValues:["none","minor","medium","major"]},e.right={createComponentOfType:"text",createStateVariable:"right",defaultValue:"none",public:!0,validValues:["none","minor","medium","major"]},e}static returnChildGroups(){return[{group:"rows",componentTypes:["row"]}]}static returnStateVariableDefinitions(){return super.returnStateVariableDefinitions()}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Table extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="table";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.suppressTableNameInTitle={createComponentOfType:"boolean",createStateVariable:"suppressTableNameInTitle",defaultValue:!1,forRenderer:!0},e.number={createComponentOfType:"boolean",createStateVariable:"number",defaultValue:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"titles",componentTypes:["title"]},{group:"inlinesBlocks",componentTypes:["_inline","_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.tableEnumeration={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["number"],additionalStateVariablesDefined:[{variableName:"tableName",public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0}],returnDependencies({stateValues:e}){let t={};return e.number&&(t.tableCounter={dependencyType:"counter",counterName:"table"}),t},definition({dependencyValues:e}){if(void 0===e.tableCounter)return{setValue:{tableEnumeration:null,tableName:"Table"}};let t=String(e.tableCounter);return{setValue:{tableEnumeration:t,tableName:"Table "+t}}}},e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[0].componentName),{setValue:{titleChildName:t}}}},e.title={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"],variableNames:["text"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[0].stateValues.text),{setValue:{title:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Figure extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="figure";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.suppressFigureNameInCaption={createComponentOfType:"boolean",createStateVariable:"suppressFigureNameInCaption",defaultValue:!1,forRenderer:!0},e.number={createComponentOfType:"boolean",createStateVariable:"number",defaultValue:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"captions",componentTypes:["caption"]},{group:"inlinesBlocks",componentTypes:["_inline","_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.figureEnumeration={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["number"],additionalStateVariablesDefined:[{variableName:"figureName",public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0}],returnDependencies({stateValues:e}){let t={};return e.number&&(t.figureCounter={dependencyType:"counter",counterName:"figure"}),t},definition({dependencyValues:e}){if(void 0===e.figureCounter)return{setValue:{figureEnumeration:null,figureName:"Figure"}};let t=String(e.figureCounter);return{setValue:{figureEnumeration:t,figureName:"Figure "+t}}}},e.captionChildName={forRenderer:!0,returnDependencies:()=>({captionChild:{dependencyType:"child",childGroups:["captions"]}}),definition({dependencyValues:e}){let t=null;return e.captionChild.length>0&&(t=e.captionChild[0].componentName),{setValue:{captionChildName:t}}}},e.caption={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({captionChild:{dependencyType:"child",childGroups:["captions"],variableNames:["text"]}}),definition({dependencyValues:e}){let t=null;return e.captionChild.length>0&&(t=e.captionChild[0].stateValues.text),{setValue:{caption:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class TextListFromString extends InlineComponent{static componentType="textListFromString";static rendererType="asList";static renderChildren=!0;static stateVariableForAttributeValue="texts";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.stringChildren.length}}}},e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={stringChild:{dependencyType:"child",childGroups:["strings"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)1===e[r].stringChild.length&&(n[r]=e[r].stringChild[0]);return{setValue:{texts:n}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"texts"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e}}class VariantControl extends BaseComponent{static componentType="variantControl";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.nVariants={createPrimitiveOfType:"integer"},e.uniqueVariants={createPrimitiveOfType:"boolean"},e.variantsToInclude={createComponentOfType:"textListFromString"},e.variantsToExclude={createComponentOfType:"textListFromString"},e.variantNames={createComponentOfType:"textListFromString"},e.seeds={createComponentOfType:"textListFromString"},e}}class SelectFromSequence extends Sequence{static componentType="selectFromSequence";static assignNamesToReplacements=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.numberToSelect={createComponentOfType:"integer",createStateVariable:"numberToSelect",defaultValue:1,public:!0},e.withReplacement={createComponentOfType:"boolean",createStateVariable:"withReplacement",defaultValue:!1,public:!0},e.sortResults={createComponentOfType:"boolean",createStateVariable:"sortResults",defaultValue:!1,public:!0},e.excludeCombinations={createComponentOfType:"_componentListOfListsWithSelectableType"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();e.excludedCombinations={returnDependencies:()=>({excludeCombinations:{dependencyType:"attributeComponent",attributeName:"excludeCombinations",variableNames:["lists"]},type:{dependencyType:"stateVariable",variableName:"type"},numberToSelect:{dependencyType:"stateVariable",variableName:"numberToSelect"}}),definition:function({dependencyValues:e}){if(null!==e.excludeCombinations){let t=e.excludeCombinations.stateValues.lists.map((t=>t.slice(0,e.numberToSelect))).filter((t=>t.length===e.numberToSelect));if("number"===e.type)for(;;){let e=mergeContainingCombinations(t);if(!e.merged)break;t=e.combinations}return{setValue:{excludedCombinations:t}}}return{setValue:{excludedCombinations:[]}}}},e.variants={returnDependencies:()=>({variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){return{setValue:{variants:e.variants}}}},e.selectedValues={immutable:!0,hasEssential:!0,shadowVariable:!0,additionalStateVariablesDefined:[{variableName:"selectedIndices",hasEssential:!0,shadowVariable:!0,immutable:!0}],returnDependencies:({sharedParameters:e})=>({numberToSelect:{dependencyType:"stateVariable",variableName:"numberToSelect"},withReplacement:{dependencyType:"stateVariable",variableName:"withReplacement"},length:{dependencyType:"stateVariable",variableName:"length"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"},exclude:{dependencyType:"stateVariable",variableName:"exclude"},excludedCombinations:{dependencyType:"stateVariable",variableName:"excludedCombinations"},type:{dependencyType:"stateVariable",variableName:"type"},lowercase:{dependencyType:"stateVariable",variableName:"lowercase"},sortResults:{dependencyType:"stateVariable",variableName:"sortResults"},variants:{dependencyType:"stateVariable",variableName:"variants"},variantRng:{dependencyType:"value",value:e.variantRng,doNotProxy:!0}}),definition:makeSelection},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:()=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{generatedVariantInfo:{indices:e.selectedIndices,meta:{createdBy:t}}}})};let t=e.readyToExpandWhenResolved.returnDependencies;return e.readyToExpandWhenResolved.returnDependencies=function(){let e=t();return e.selectedValues={dependencyType:"stateVariable",variableName:"selectedValues"},e},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n}){let r=await e.stateValues.type;"letters"===r&&(r="text");let a=e.attributes.newNamespace?.primitive,i={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(i[t]=e.attributes[t]);let s={};Object.keys(i).length>0&&(s=convertAttributesForComponentType({attributes:i,componentType:r,componentInfoObjects:t,compositeCreatesNewNamespace:a,flags:n}));let o=[];for(let t of await e.stateValues.selectedValues)o.push({componentType:r,attributes:s,state:{value:t,fixed:!0}});return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:o,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:t}).serializedComponents}}static calculateReplacementChanges(){return[]}static determineNumberOfUniqueVariants({serializedComponent:e}){let t=1,n=!1,r=e.attributes.type.primitive,a=e.attributes.numberToSelect?.component;if(a){if("integer"!==a.componentType||1!==a.children?.length||"string"!=typeof a.children[0])return console.log("cannot determine unique variants of selectFromSequence as numberToSelect isn't constant number."),{success:!1};if(t=Number(a.children[0]),!(Number.isInteger(t)&&t>=0))return console.log("cannot determine unique variants of selectFromSequence as numberToSelect isn't a non-negative integer."),{success:!1}}let i=e.attributes.withReplacement?.component;if(i){if("boolean"!==i.componentType)return console.log("cannot determine unique variants of selectFromSequence as withReplacement isn't constant boolean."),{success:!1};if(1===i.children?.length&&"string"==typeof i.children[0])n="true"===i.children[0].toLowerCase();else{if(void 0!==i.children&&0!==i.children.length||"boolean"!=typeof i.state?.value)return console.log("cannot determine unique variants of selectFromSequence as withReplacement isn't constant boolean."),{success:!1};n=i.state.value}}let s={from:null,to:null,step:null,length:null},o=e.attributes.from?.component;if(o){let e=o.children[0];if(1!==e.children?.length||"string"!=typeof e.children[0])return console.log("cannot determine unique variants of selectFromSequence as from isn't a constant."),{success:!1};{let t;if("number"===r){if(t=Number(e.children[0]),!Number.isFinite(t))return console.log("cannot determine unique variants of selectFromSequence of number type as from isn't a number."),{success:!1}}else if("letters"===r){if(t=lettersToNumber$1(e.children[0]),!Number.isFinite(t))return console.log("cannot determine unique variants of selectFromSequence of letters type as from isn't a combination of letters."),{success:!1}}else{let n=getFromText({functionSymbols:["f","g"]});try{t=n(e.children[0])}catch(e){return console.log("cannot determine unique variants of selectFromSequence of math type as from isn't a valid math expression."),{success:!1}}}s.from=t}}let l=e.attributes.to?.component;if(l){let e=l.children[0];if(1!==e.children?.length||"string"!=typeof e.children[0])return console.log("cannot determine unique variants of selectFromSequence as to isn't a constant."),{success:!1};{let t;if("number"===r){if(t=Number(e.children[0]),!Number.isFinite(t))return console.log("cannot determine unique variants of selectFromSequence of number type as to isn't a number."),{success:!1}}else if("letters"===r){if(t=lettersToNumber$1(e.children[0]),!Number.isFinite(t))return console.log("cannot determine unique variants of selectFromSequence of letters type as to isn't a combination of letters."),{success:!1}}else{let n=getFromText({functionSymbols:["f","g"]});try{t=n(e.children[0])}catch(e){return console.log("cannot determine unique variants of selectFromSequence of math type as to isn't a valid math expression."),{success:!1}}}s.to=t}}let u=e.attributes.step?.component;if(u){if(1!==u.children?.length||"string"!=typeof u.children[0])return console.log("cannot determine unique variants of selectFromSequence as step isn't a constant."),{success:!1};{let e;if("number"===r){if(e=Number(u.children[0]),!Number.isFinite(e))return console.log("cannot determine unique variants of selectFromSequence of number type as step isn't a number."),{success:!1}}else if("letters"===r){if(e=Number(u.children[0]),!Number.isInteger(e))return console.log("cannot determine unique variants of selectFromSequence of letters type as step isn't an integer."),{success:!1}}else{let t=getFromText({functionSymbols:["f","g"]});try{e=t(u.children[0])}catch(e){return console.log("cannot determine unique variants of selectFromSequence of math type as step isn't a valid math expression."),{success:!1}}}s.step=e}}let c=e.attributes.length?.component;if(c){if(1!==c.children?.length||"string"!=typeof c.children[0])return console.log("cannot determine unique variants of selectFromSequence as length isn't a constant."),{success:!1};{let e=Number(c.children[0]);if(!Number.isInteger(e))return console.log("cannot determine unique variants of selectFromSequence as length isn't an integer."),{success:!1};s.length=e}}if(e.attributes.excludeCombinations)return console.log("have not implemented unique variants of a selectFromSequence with excludeCombinations"),{success:!1};let p=[],d=e.attributes.exclude?.component;if(d){if("math"===r)return console.log("have not implemented unique variants of a selectFromSequence of type math with exclude"),{success:!1};if(!d.children.every((e=>1===e.children?.length&&"string"==typeof e.children[0])))return console.log("have not implemented unique variants of a selectFromSequence with non-constant exclude"),{success:!1};if(p="letters"===r?d.children.map((e=>lettersToNumber$1(e.children[0]))):d.children.map((e=>Number(e.children[0]))),!p.every(Number.isFinite))return console.log("have not implemented unique variants of a selectFromSequence with non-constant exclude"),{success:!1}}s=calculateSequenceParameters(s);let m=s.length,h=[];if(p.length>0&&"math"!==r){p.sort(((e,t)=>e-t)),p=p.filter(((e,t,n)=>e!=n[t-1]));for(let e of p){if(es.length-1+1e-10)break;Math.abs(t-Math.round(t))<1e-10&&(m--,h.push(t))}}if(m<=0)return{success:!1};let f,y={excludeIndices:h,nOptions:m,numberToSelect:t,withReplacement:n};if(e.variants.uniqueVariantData=y,n||1===t)f=Math.pow(m,t);else{f=m;for(let e=m-1;e>m-t;e--)f*=e}return e.variants.numberOfVariants=f,{success:!0,numberOfVariants:f}}static getUniqueVariant({serializedComponent:e,variantIndex:t}){let n=e.variants?.numberOfVariants;if(void 0===n)return{success:!1};if(!Number.isInteger(t)||t<1||t>n)return{success:!1};let r=e.variants.uniqueVariantData,a=r.excludeIndices,i=r.nOptions,s=r.numberToSelect,o=r.withReplacement,l=function(e){let t=e;for(let e of a)t>=e&&t++;return t};if(1===s)return{success:!0,desiredVariant:{indices:[l(t-1)+1]}};let u=enumerateSelectionCombinations({numberOfIndices:s,numberOfOptions:i,maxNumber:t,withReplacement:o})[t-1].map(l).map((e=>e+1));return{success:!0,desiredVariant:{indices:u}}}}function makeSelection({dependencyValues:e}){if(e.numberToSelect<1)return{setEssentialValue:{selectedValues:[],selectedIndices:[]},setValue:{selectedValues:[],selectedIndices:[]}};let t=1;if(e.withReplacement||(t=e.numberToSelect),t>e.length)throw Error("Cannot select "+t+" values from a sequence of length "+e.length);if(e.variants&&void 0!==e.variants.desiredVariant){let t=e.variants.desiredVariant.indices;if(void 0!==t){if(t.length!==e.numberToSelect)throw Error("Number of indices specified for select must match number to select");if(t=t.map(Number),!t.every(Number.isInteger))throw Error("All indices specified for select must be integers");let n=e.length;t=t.map((e=>((e-1)%n+n)%n+1));let r=[];for(let n of t){let t=returnSequenceValueForIndex({index:n-1,from:e.from,step:e.step,length:e.length,exclude:e.exclude,type:e.type,lowercase:e.lowercase});if(null===t)throw Error("Specified index of selectfromsequence that was excluded");r.push(t)}if(checkForExcludedCombination({type:e.type,excludedCombinations:e.excludedCombinations,values:r}))throw Error("Specified indices of selectfromsequence that was an excluded combination");return{setEssentialValue:{selectedValues:r,selectedIndices:t},setValue:{selectedValues:r,selectedIndices:t}}}}let n,r,a=e.excludedCombinations.length;if("number"===e.type){a=0;let t=e.length-e.exclude.length;for(let n of e.excludedCombinations){let r=n.reduce(((e,t)=>e+(Number.isNaN(t)?1:0)),0);if(r>0)if(e.withReplacement)a+=Math.pow(t,r);else{let n=t-e.numberToSelect+r,i=n;for(let e=1;e.7*i){let t=0;for(let n=0;n.7*t){if("number"!==e.type||!e.excludedCombinations.some((e=>e.some(Number.isNaN))))throw Error("Excluded over 70% of combinations in selectFromSequence");if(a-=estimateNumberOfDuplicateCombinations(e.excludedCombinations,e.length-e.exclude.length,e.withReplacement),a>.7*t)throw Error("Excluded over 70% of combinations in selectFromSequence")}}let s=!1;for(let a=0;a<200;a++){let a=selectValuesAndIndices({stateValues:e,numberUniqueRequired:t,numberToSelect:e.numberToSelect,withReplacement:e.withReplacement,rng:e.variantRng});if(n=a.selectedValues,r=a.selectedIndices,!checkForExcludedCombination({type:e.type,excludedCombinations:e.excludedCombinations,values:n})){s=!0;break}}if(!s)throw Error("By extremely unlikely fluke, couldn't select combination of random values")}if(e.sortResults){let t=[];for(let[e,a]of n.entries())t.push({value:a,index:r[e]});"number"===e.type?t.sort(((e,t)=>e.value-t.value)):"letters"===e.type&&t.sort(((e,t)=>lettersToNumber$1(e.value)-lettersToNumber$1(t.value))),n=t.map((e=>e.value)),r=t.map((e=>e.index))}return{setEssentialValue:{selectedValues:n,selectedIndices:r},setValue:{selectedValues:n,selectedIndices:r}}}function selectValuesAndIndices({stateValues:e,numberUniqueRequired:t=1,numberToSelect:n=1,withReplacement:r=!1,rng:a}){let i=[],s=[];if(e.exclude.length+t<.5*e.length){for(let t=0;tl)throw Error("Cannot select "+t+" unique values from sequence of length "+l);if(1===t){for(let e=0;e0;e--){const t=a(),n=Math.floor(t*(e+1));[o[e],o[n]]=[o[n],o[e]]}let u=o.slice(0,n);return i=u.map((e=>e.value)),s=u.map((e=>e.originalIndex+1)),{selectedValues:i,selectedIndices:s}}function checkForExcludedCombination({type:e,excludedCombinations:t,values:n}){return"math"===e?t.some((e=>e.every(((e,t)=>e.equals(n[t]))))):"number"===e?t.some((e=>e.every(((e,t)=>Number.isNaN(e)||Math.abs(e-n[t])<=1e-14*Math.max(Math.abs(e),Math.abs(n[t])))))):t.some((e=>e.every(((e,t)=>e===n[t]))))}function mergeContainingCombinations(e){if(0===e.length)return{merged:!1,combinations:[]};let t=[e[0]],n=!1;for(let r of e.slice(1)){let e=[],a=!1;for(let n of t){if(a){e.push(n);continue}let t=[];a=!0;let i=null;for(let e=0;e!Number.isNaN(e)));[...new Set(e)].length===e.length&&a.push(o)}}}for(;;){let e=mergeContainingCombinations(a);if(!e.merged)break;a=e.combinations}let i=0;if(a.length>0)for(let e of a){let r=e.reduce(((e,t)=>e+(Number.isNaN(t)?1:0)),0);if(r>0)if(n)i+=Math.pow(t,r);else{let n=t-e.length+r,a=n;for(let e=1;e"string"==typeof e||e.doenetAttributes&&e.doenetAttributes.createdFromMacro)))return{success:!1};let r;r=t.type?t.type:"math",["math","text","number","boolean"].includes(r)||(console.warn(`Invalid type ${r}`),r="math");let a=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:r,forceComponentType:!0})({matchedChildren:e,componentInfoObjects:n});if(a.success){return{success:!0,newChildren:a.newChildren.map((e=>({componentType:"option",children:[e]}))),newAttributes:{addLevelToAssignNames:{primitive:!0}}}}return{success:!1}}}),e}static returnChildGroups(){return[{group:"options",componentTypes:["option"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.variants={returnDependencies:()=>({variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){return{setValue:{variants:e.variants}}}},e.currentVariantName={returnDependencies:({sharedParameters:e})=>({variantName:{dependencyType:"value",value:e.variantName}}),definition:({dependencyValues:e})=>({setValue:{currentVariantName:e.variantName}})},e.allVariantNames={returnDependencies:({sharedParameters:e})=>({allVariantNames:{dependencyType:"value",value:e.allVariantNames}}),definition:({dependencyValues:e})=>({setValue:{allVariantNames:e.allVariantNames}})},e.nOptions={additionalStateVariablesDefined:["optionChildren"],returnDependencies:()=>({optionChildren:{dependencyType:"child",childGroups:["options"],variableNames:["selectForVariants","selectWeight"]}}),definition:({dependencyValues:e})=>({setValue:{optionChildren:e.optionChildren,nOptions:e.optionChildren.length}})},e.availableVariants={returnDependencies:()=>({optionChildren:{dependencyType:"stateVariable",variableName:"optionChildren"},numberToSelect:{dependencyType:"stateVariable",variableName:"numberToSelect"},allVariantNames:{dependencyType:"stateVariable",variableName:"allVariantNames"}}),definition:function({dependencyValues:e}){let t={};for(let[n,r]of e.optionChildren.entries())for(let e of r.stateValues.selectForVariants){let r=e.toLowerCase();void 0===t[r]&&(t[r]=[]),t[r].push(n+1)}for(let n in t)if(t[n].length!==e.numberToSelect)throw Error("Invalid variant name for select. Variant name "+n+" appears in "+t[n].length+" options but number to select is "+numberToSelect);if(Object.keys(t).length>0){for(let n of e.allVariantNames)if(!(n in t))throw Error("Some variants are specified for select but no options are specified for possible variant name: "+n);for(let n in t)if(!e.allVariantNames.includes(n))throw Error("Variant name "+n+" that is specified for select is not a possible variant name.")}return{setValue:{availableVariants:t}}}},e.selectedIndices={immutable:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:({sharedParameters:e})=>({numberToSelect:{dependencyType:"stateVariable",variableName:"numberToSelect"},withReplacement:{dependencyType:"stateVariable",variableName:"withReplacement"},optionChildren:{dependencyType:"stateVariable",variableName:"optionChildren"},nOptions:{dependencyType:"stateVariable",variableName:"nOptions"},currentVariantName:{dependencyType:"stateVariable",variableName:"currentVariantName"},variants:{dependencyType:"stateVariable",variableName:"variants"},availableVariants:{dependencyType:"stateVariable",variableName:"availableVariants"},variantRng:{dependencyType:"value",value:e.variantRng,doNotProxy:!0}}),definition:function({dependencyValues:e}){if(!(e.numberToSelect>=1)||0===e.nOptions)return{setEssentialValue:{selectedIndices:[]},setValue:{selectedIndices:[]}};if(e.variants&&void 0!==e.variants.desiredVariant){let t=e.variants.desiredVariant.indices;if(void 0!==t){if(t.length!==e.numberToSelect)throw Error("Number of indices specified for select must match number to select");if(t=t.map(Number),!t.every(Number.isInteger))throw Error("All indices specified for select must be integers");let n=e.nOptions;return t=t.map((e=>((e-1)%n+n)%n+1)),{setEssentialValue:{selectedIndices:t},setValue:{selectedIndices:t}}}}let t=e.availableVariants[e.currentVariantName];if(void 0!==t){if(e.numberToSelect>1){t=[...t];for(let n=e.numberToSelect-1;n>0;n--){const r=e.variantRng(),a=Math.floor(r*(n+1));[t[n],t[a]]=[t[a],t[n]]}}return{setEssentialValue:{selectedIndices:t},setValue:{selectedIndices:t}}}let n=[],r=1;if(e.withReplacement||(r=e.numberToSelect),r>e.nOptions)throw Error("Cannot select "+r+" components from only "+e.nOptions);let a=e.optionChildren.map((e=>e.stateValues.selectWeight)),i=a.reduce(((e,t)=>e+t));a=a.map((e=>e/i));let s=a.reduce(((e,t,n)=>[...e,t+(e[n-1]||0)]),[]),o=[...Array(s.length).keys()].map((e=>e+1));for(let t=0;tr?u=e:l=e}let c=o[u];n.push(c),!e.withReplacement&&te+t)),a=a.map((e=>e/i)),s=a.reduce(((e,t,n)=>[...e,t+(e[n-1]||0)]),[]))}return{setEssentialValue:{selectedIndices:n},setValue:{selectedIndices:n}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={providePreviousValuesInDefinition:!0,returnDependencies:({componentInfoObjects:e})=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(e.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t,previousValues:n}){let r={indices:e.selectedIndices,meta:{createdBy:t}},a=r.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?a.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&a.push(...t.stateValues.generatedVariantInfo.subvariants);for(let[e,t]of a.entries())if(!t.subvariants&&n.generatedVariantInfo){let t=n.generatedVariantInfo.subvariants;t[e].subvariants&&(a[e]=Object.assign({},a[e]),a[e].subvariants=t[e].subvariants)}return{setValue:{generatedVariantInfo:r}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n}){let r=[],a=await e.stateValues.optionChildren;for(let n of await e.stateValues.selectedIndices){let e=a[n-1].componentName,i=t[e],s=deepClone(await i.stateValues.serializedChildren),o={componentType:"option",state:{rendered:!0},doenetAttributes:Object.assign({},i.doenetAttributes),children:s,originalName:e};i.attributes.newNamespace&&(o.attributes={newNamespace:{primitive:!0}}),r.push(o)}let i=gatherVariantComponents({serializedComponents:r,componentInfoObjects:n});if(e.variants&&void 0!==e.variants.desiredVariant){let t=e.variants.desiredVariant;if(void 0!==t&&void 0!==t.subvariants)for(let e in t.subvariants){let n=t.subvariants[e],r=i[e];if(void 0===r)break;r.variants.desiredVariant=n}}let s=e.attributes.newNamespace?.primitive,o=e.doenetAttributes.assignNames;o&&await e.stateValues.addLevelToAssignNames&&(o=o.map((e=>[e])));for(let e of r)!e.attributes?.newNamespace?.primitive&&e.children&&markToCreateAllUniqueNames(e.children);let l=[];for(let[t,a]of r.entries()){let r=processAssignNames({assignNames:o,serializedComponents:[a],parentName:e.componentName,parentCreatesNewNamespace:s,componentInfoObjects:n,indOffset:t});l.push(r.serializedComponents[0])}return{replacements:l}}static calculateReplacementChanges(){return[]}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){let n=e.variants?.numberOfVariants;if(void 0!==n)return{success:!0,numberOfVariants:n};let r=1,a=!1,i=e.attributes.numberToSelect?.component;if(i){if("integer"!==i.componentType||1!==i.children?.length||"string"!=typeof i.children[0])return console.log("cannot determine unique variants of selectFromSequence as numberToSelect isn't constant number."),{success:!1};if(r=Number(i.children[0]),!(Number.isInteger(r)&&r>=0))return console.log("cannot determine unique variants of selectFromSequence as numberToSelect isn't a non-negative integer."),{success:!1}}let s=e.attributes.withReplacement?.component;if(s){if("boolean"!==s.componentType)return console.log("cannot determine unique variants of selectFromSequence as withReplacement isn't constant boolean."),{success:!1};if(1===s.children?.length&&"string"==typeof s.children[0])a="true"===s.children[0].toLowerCase();else{if(void 0!==s.children&&0!==s.children.length||"boolean"!=typeof s.state?.value)return console.log("cannot determine unique variants of selectFromSequence as withReplacement isn't constant boolean."),{success:!1};a=s.state.value}}for(let t of e.children)if(t.attributes?.selectWeight||t.attributes?.selectForVariants)return console.log("Unique variants for select disabled if have an option with selectWeight or selectForVariants specified"),{success:!1};void 0===e.variants&&(e.variants={});let o=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t});e.variants.descendantVariantComponents=o;let l=[];for(let e of o){let n=t.allComponentClasses[e.componentType].determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!n.success)return{success:!1};l.push(n.numberOfVariants)}let u={numberOfVariantsByChild:l,numberToSelect:r,withReplacement:a};if(0===l.length)n=1;else if(a||1===r){let e=l.reduce(((e,t)=>e+t));n=Math.pow(e,r)}else{let e=l.length;if(r>e)return{success:!1};let t=l[0],a=l.slice(1).every((e=>e===t));if(a){let a=e;for(let t=e-1;t>e-r;t--)a*=t;n=a*Math.pow(t,r)}else n=countOptions(l,r)}return e.variants.numberOfVariants=n,e.variants.uniqueVariants=!0,e.variants.uniqueVariantData=u,{success:!0,numberOfVariants:n}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};let a,i=e.variants.uniqueVariantData,s=i.numberOfVariantsByChild,o=i.numberToSelect,l=i.withReplacement,u=e.children.length,c=e.children;if(0===s.length)return{success:!0,desiredVariant:{indices:[]}};a=1===o?[...Array(u).keys()].map((e=>[e])):enumerateSelectionCombinations({numberOfIndices:o,numberOfOptions:u,withReplacement:l});let p,d,m=a.length,h=a.map((e=>({combination:e,numberOfPossibilities:e.reduce(((e,t)=>e*s[t]),1)}))),f=[...Array(m).keys()],y=0,g=f.length,b=t-1;for(;g>0;){let e=f.map((e=>h[e])).reduce(((e,t)=>Math.min(e,t.numberOfPossibilities)),1/0),t=e-y;if(bh[e].numberOfPossibilities>y)),g=f.length}let v=a[p],N=enumerateCombinations({numberOfOptionsByIndex:v.map((e=>s[e])),maxNumber:d})[d-1].map((e=>e+1)),T=[],C=!1;for(let[e,t]of v.entries())if(s[t]>1){let r=c[t],a=n.allComponentClasses[r.componentType].getUniqueVariant({serializedComponent:r,variantIndex:N[e],componentInfoObjects:n});if(!a.success)return{success:!1};T.push(a.desiredVariant),C=!0}else T.push({});let A={indices:v.map((e=>e+1))};return C&&(A.subvariants=T),{success:!0,desiredVariant:A}}}let countOptions=function(e,t){if(0===t)return 0;if(1===t)return e.reduce(((e,t)=>e+t));let n=0;for(let r in e){let a=e[r],i=[...e];i.splice(r,1),n+=a*countOptions(i,t-1)}return n};class AnimateFromSequence extends BaseComponent{constructor(e){super(e),Object.assign(this.actions,{changedAnimationOn:this.changedAnimationOn.bind(this),advanceAnimation:this.advanceAnimation.bind(this),startAnimation:this.startAnimation.bind(this),stopAnimation:this.stopAnimation.bind(this),toggleAnimation:this.toggleAnimation.bind(this)})}static componentType="animateFromSequence";static rendererType=void 0;static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject(),t=returnStandardSequenceAttributes();return Object.assign(e,t),e.prop={createPrimitiveOfType:"string"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.animationOn={createComponentOfType:"boolean",createStateVariable:"animationOn",defaultValue:!1,public:!0,triggerActionOnChange:"changedAnimationOn"},e.animationMode={createComponentOfType:"text",createStateVariable:"animationMode",defaultValue:"increase",validValues:["increase","decrease","increase once","decrease once","oscillate"],toLowerCase:!0,public:!0},e.animationInterval={createComponentOfType:"number",createStateVariable:"animationInterval",defaultValue:1e3,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStandardSequenceStateVariableDefinitions();return Object.assign(e,t),e.possibleValues={additionalStateVariablesDefined:["numberValues"],returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},length:{dependencyType:"stateVariable",variableName:"length"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"},exclude:{dependencyType:"stateVariable",variableName:"exclude"},lowercase:{dependencyType:"stateVariable",variableName:"lowercase"}}),definition({dependencyValues:e}){let t=returnSequenceValues(e);return{setValue:{possibleValues:t,numberValues:t.length}}}},e.selectedIndex={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{selectedIndex:!0}}),inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>({success:!0,instructions:[{setEssentialValue:"selectedIndex",value:me$3.math.mod(e.selectedIndex-1,await t.numberValues)+1}]})},e.value={public:!0,shadowingInstructions:{hasVariableComponentType:!0},returnDependencies:()=>({possibleValues:{dependencyType:"stateVariable",variableName:"possibleValues"},selectedIndex:{dependencyType:"stateVariable",variableName:"selectedIndex"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition:({dependencyValues:e})=>({setValue:{value:e.possibleValues[e.selectedIndex-1]},setCreateComponentOfType:{value:e.type}}),async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if("number"===t.type){let r=e.value;if(r instanceof me$3.class&&(r=r.evaluate_to_constant()),!Number.isFinite(r))return{success:!1};let a=-1,i=t.possibleValues.length-1;for(;a0?i=e:a=e}let s=i;return-1!==a&&Math.abs(r-t.possibleValues[a])({animationMode:{dependencyType:"stateVariable",variableName:"animationMode"}}),definition:({dependencyValues:e})=>({useEssentialOrDefaultValue:{currentAnimationDirection:{get defaultValue(){return"decrease"===e.animationMode.substring(0,8)?"decrease":"increase"}}}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.currentAnimationDirection.toLowerCase();return["increase","decrease"].includes(t)||(t="increase"),{success:!0,instructions:[{setEssentialValue:"currentAnimationDirection",value:t}]}}},e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){let t=null;return e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.propName={returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.targetIdentities={stateVariablesDeterminingDependencies:["targetComponent","componentIndex"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={};return null!==e.targetComponent&&(t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})?n.targets={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,componentIndex:e.componentIndex}:null!==e.componentIndex&&1!==e.componentIndex||(n.targets={dependencyType:"stateVariable",variableName:"targetComponent"})),n},definition({dependencyValues:e}){let t=null;return e.targets&&(t=e.targets,Array.isArray(t)||(t=[t])),{setValue:{targetIdentities:t}}}},e.targets={stateVariablesDeterminingDependencies:["targetIdentities","propName","propIndex"],returnDependencies:function({stateValues:e}){let t={targetIdentities:{dependencyType:"stateVariable",variableName:"targetIdentities"}};if(null!==e.targetIdentities)for(let[n,r]of e.targetIdentities.entries()){let a;if(e.propName){let t=e.propIndex;t&&(t=[...t]),a={dependencyType:"stateVariable",componentName:r.componentName,variableName:e.propName,returnAsComponentObject:!0,variablesOptional:!0,propIndex:t,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0}}else a={dependencyType:"stateVariable",componentName:r.componentName,variableName:"value",returnAsComponentObject:!0,variablesOptional:!0};t["target"+n]=a}return t},definition({dependencyValues:e}){let t=null;if(null!==e.targetIdentities){t=[];for(let n in e.targetIdentities)e["target"+n]&&t.push(e["target"+n])}return{setValue:{targets:t}}}},e.valueToIndex={returnDependencies:()=>({possibleValues:{dependencyType:"stateVariable",variableName:"possibleValues"}}),definition:function({dependencyValues:e}){let t={};for(let[n,r]of e.possibleValues.entries())t[r]=n;return{setValue:{valueToIndex:t}}}},e}async changedAnimationOn({stateValues:e,previousValues:t,actionId:n}){let r=[];if(e.animationOn)if(t.animationOn)this.coreFunctions.resolveAction({actionId:n});else{let e=await this.stateValues.currentAnimationDirection,t=await this.stateValues.animationMode,a=await this.stateValues.numberValues,i=await this.stateValues.selectedIndex,s=await this.findIndexFromTarget();"increase"===e?s===a&&("increase once"===t?s=1:"oscillate"===t&&(e="decrease",r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"currentAnimationDirection",value:e}))):"decrease"===e&&1===s&&("decrease once"===t?s=a:"oscillate"===t&&(e="increase",r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"currentAnimationDirection",value:e}))),s!==i&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedIndex",value:s});let o=await this.getUpdateInstructionsToSetTargetsToValue((await this.stateValues.possibleValues)[me$3.math.mod(s-1,a)]);r.push(...o),await this.coreFunctions.performUpdate({updateInstructions:r,actionId:n,event:{verb:"played",object:{componentName:this.componentName,componentType:this.componentType},context:{startIndex:s,animationDirection:e,animationMode:t}}}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName}),this.animationId=nanoid(),await this.coreFunctions.requestAnimationFrame({action:{actionName:"advanceAnimation",componentName:this.componentName},delay:await this.stateValues.animationInterval,animationId:this.animationId,actionArgs:{previousAnimationId:this.animationId}})}else t.animationOn?(await this.coreFunctions.cancelAnimationFrame(this.animationId),this.canceledAnimationId=this.animationId,await this.coreFunctions.triggerChainedActions({componentName:this.componentName}),this.coreFunctions.requestRecordEvent({verb:"paused",object:{componentName:this.componentName,componentType:this.componentType},context:{endIndex:await this.stateValues.selectedIndex}})):this.coreFunctions.resolveAction({actionId:n})}async findIndexFromTarget(){let e=await this.stateValues.targets,t=await this.stateValues.selectedIndex;if(null===e)return t;let n,r=e[0];if(r?.stateValues&&(n=Object.keys(r.stateValues)[0]),!n)return t;let a=r.stateValues[n],i=await this.stateValues.type;if("number"===i&&a instanceof me$3.class&&(a=a.evaluate_to_constant(),!Number.isFinite(a)))return t;let s=(await this.stateValues.valueToIndex)[a];if(void 0!==s)return s+1;if("number"!==i)return t;let o=await this.stateValues.possibleValues,l=function(e=0,t=o.length-1){if(t<=e+1)return a>o[e]?t:e;let n=Math.round((t+e)/2);return a>o[n]?l(n,t):l(e,n)},u=l();if(0!==u){let e=o[u-1],t=o[u];Math.abs(a-e)=await this.stateValues.numberValues&&("increase once"===s?i=!1:"oscillate"===s&&(a="decrease")));let l=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedIndex",value:n}],u=await this.getUpdateInstructionsToSetTargetsToValue((await this.stateValues.possibleValues)[me$3.math.mod(n-1,await this.stateValues.numberValues)]);l.push(...u),i||l.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"animationOn",value:!1}),a&&l.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"currentAnimationDirection",value:a}),await this.coreFunctions.performUpdate({updateInstructions:l,actionId:t}),i&&(this.animationId=nanoid(),await this.coreFunctions.requestAnimationFrame({action:{actionName:"advanceAnimation",componentName:this.componentName},delay:await this.stateValues.animationInterval,animationId:this.animationId,actionArgs:{previousAnimationId:this.animationId}}))}startAnimation({actionId:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"animationOn",value:!0}],actionId:e})}stopAnimation({actionId:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"animationOn",value:!1}],actionId:e})}async toggleAnimation({actionId:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"animationOn",value:!await this.stateValues.animationOn}],actionId:e})}async getUpdateInstructionsToSetTargetsToValue(e){let t=await this.stateValues.targets;if(null==t)return[];let n=[];for(let r of t){let t=Object.keys(r.stateValues)[0];void 0!==t?n.push({updateType:"updateValue",componentName:r.componentName,stateVariable:t,value:e}):await this.stateValues.propName?console.warn(`Cannot animate prop="${await this.stateValues.propName}" of ${await this.stateValues.target} as could not find prop ${await this.stateValues.propName} on a component of type ${r.componentType}`):console.warn(`Cannot animate ${await this.stateValues.target} as could not find a value state variable on a component of type ${r.componentType}`)}return n}}class Evaluate extends MathComponent{static componentType="evaluate";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.forceSymbolic={createComponentOfType:"boolean",createStateVariable:"forceSymbolic",defaultValue:!1,public:!0},e.forceNumeric={createComponentOfType:"boolean",createStateVariable:"forceNumeric",defaultValue:!1,public:!0},e.function={createComponentOfType:"function"},e.input={createComponentOfType:"mathList"},e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e}static returnChildGroups(){return[]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.codePre,delete e.expressionWithCodes,delete e.mathChildrenFunctionSymbols,delete e.codesAdjacentToStrings,delete e.mathChildrenByVectorComponent,delete e.mathChildrenWithCanBeModified,delete e.unordered,e.canBeModified={returnDependencies:()=>({}),definition:()=>({setValue:{canBeModified:!1}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:10,hasEssential:!0,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["displayDigits"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:e.functionAttr?t.functionAttr?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:e.functionAttr.stateValues.displayDecimals}}}:{setValue:{displayDecimals:e.functionAttr.stateValues.displayDecimals}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:e.functionAttr?t.functionAttr?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:e.functionAttr.stateValues.displaySmallAsZero}}}:{setValue:{displaySmallAsZero:e.functionAttr.stateValues.displaySmallAsZero}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:e.functionAttr?t.functionAttr?{useEssentialOrDefaultValue:{padZeros:{defaultValue:e.functionAttr.stateValues.padZeros}}}:{setValue:{padZeros:e.functionAttr.stateValues.padZeros}}:{useEssentialOrDefaultValue:{padZeros:!0}}},e.unnormalizedValue={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({inputAttr:{dependencyType:"attributeComponent",attributeName:"input",variableNames:["nComponents","maths"]},functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["symbolicfs","numericalfs","symbolic","nInputs","nOutputs"]},forceSymbolic:{dependencyType:"stateVariable",variableName:"forceSymbolic"},forceNumeric:{dependencyType:"stateVariable",variableName:"forceNumeric"}}),definition({dependencyValues:e}){if(!e.functionAttr||!e.inputAttr)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};let t=e.inputAttr.stateValues.maths;if(1===t.length){let e=t[0].tree;Array.isArray(e)&&vectorOperators.includes(e[0])&&(t=e.slice(1).map((e=>me$3.fromAst(e))))}if(t.length!==e.functionAttr.stateValues.nInputs)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};let n,r=[],a=e.functionAttr,i=a.stateValues.nOutputs;if(e.forceNumeric||!a.stateValues.symbolic&&!e.forceSymbolic){let e=t.map((e=>e.evaluate_to_constant())).map((e=>null===e?NaN:e));for(let t=0;t=0&&Number.isFinite(r))){let e="Invalid mean ("+r+") or standard deviation ("+n+") for a gaussian random variable.";return console.warn(e),Array(t).fill(NaN)}let e=[];for(let a=0;a0)for(let n=0;n({type:{dependencyType:"stateVariable",variableName:"type"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"}}),definition({dependencyValues:e}){let t;return t="discreteuniform"===e.type?e.specifiedStep:null,{setValue:{step:t}}}},e.from={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"to",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"nDiscreteValues"}],returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},step:{dependencyType:"stateVariable",variableName:"step"}}),definition({dependencyValues:e}){if(!["discreteuniform","uniform"].includes(e.type))return{setValue:{from:null,to:null,nDiscreteValues:null}};let t=e.step,n=e.specifiedFrom,r=e.specifiedTo,a=null;if(null===r)null===n&&(n=0),"uniform"===e.type?r=n+1:(r=n+t,a=2);else if(null===n)if("uniform"===e.type)n=0;else{let e=0;a=Math.floor((r-e)/t+1),a<1?(a=0,n=null):n=r-(a-1)*t}else"discreteuniform"===e.type&&(a=Math.floor((r-n)/t+1),a<1?a=0:r=n+(a-1)*t);return{setValue:{from:n,to:r,nDiscreteValues:a}}}},e.mean={stateVariablesDeterminingDependencies:["type"],public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies({stateValues:e}){let t={type:{dependencyType:"stateVariable",variableName:"type"}};return"gaussian"===e.type?t.specifiedMean={dependencyType:"stateVariable",variableName:"specifiedMean"}:(t.from={dependencyType:"stateVariable",variableName:"from"},t.to={dependencyType:"stateVariable",variableName:"to"}),t},definition({dependencyValues:e}){let t;return t="gaussian"===e.type?e.specifiedMean:(e.from+e.to)/2,{setValue:{mean:t}}}},e.variance={stateVariablesDeterminingDependencies:["type"],public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies({stateValues:e}){let t={type:{dependencyType:"stateVariable",variableName:"type"}};return"gaussian"===e.type?(t.specifiedVariance={dependencyType:"stateVariable",variableName:"specifiedVariance"},t.specifiedStandardDeviation={dependencyType:"stateVariable",variableName:"specifiedStandardDeviation"}):(t.from={dependencyType:"stateVariable",variableName:"from"},t.to={dependencyType:"stateVariable",variableName:"to"},"discreteuniform"===e.type&&(t.step={dependencyType:"stateVariable",variableName:"step"},t.nDiscreteValues={dependencyType:"stateVariable",variableName:"nDiscreteValues"})),t},definition({dependencyValues:e,usedDefault:t}){let n;return n="gaussian"===e.type?t.specifiedVariance&&!t.specifiedStandardDeviation?e.specifiedStandardDeviation**2:e.specifiedVariance:"discreteuniform"===e.type?(e.nDiscreteValues**2-1)*e.step**2/12:(e.to-e.from)**2/12,{setValue:{variance:n}}}},e.standardDeviation={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({variance:{dependencyType:"stateVariable",variableName:"variance"}}),definition:({dependencyValues:e})=>({setValue:{standardDeviation:Math.sqrt(e.variance)}})},e.sampledValues={shadowVariable:!0,hasEssential:!0,stateVariablesDeterminingDependencies:["variantDeterminesSeed"],returnDependencies({stateValues:e,sharedParameters:t}){let n={numberOfSamples:{dependencyType:"stateVariable",variableName:"numberOfSamples"},type:{dependencyType:"stateVariable",variableName:"type"},from:{dependencyType:"stateVariable",variableName:"from"},to:{dependencyType:"stateVariable",variableName:"to"},step:{dependencyType:"stateVariable",variableName:"step"},nDiscreteValues:{dependencyType:"stateVariable",variableName:"nDiscreteValues"},mean:{dependencyType:"stateVariable",variableName:"mean"},standardDeviation:{dependencyType:"stateVariable",variableName:"standardDeviation"}};return e.variantDeterminesSeed?n.rng={dependencyType:"value",value:t.variantRng,doNotProxy:!0}:n.rng={dependencyType:"value",value:t.rngWithDateSeed,doNotProxy:!0},n},definition({dependencyValues:e}){if(e.numberOfSamples<1)return{setEssentialValue:{sampledValues:[]},setValue:{sampledValues:[]}};let t=sampleFromRandomNumbers(e);return{setEssentialValue:{sampledValues:t},setValue:{sampledValues:t}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"sampledValues",value:e.sampledValues}]})},e.readyToExpandWhenResolved={returnDependencies:()=>({sampledValues:{dependencyType:"stateVariable",variableName:"sampledValues"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e})=>({variantSeed:{dependencyType:"value",value:e.variantSeed}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{generatedVariantInfo:{seed:e.variantSeed,meta:{createdBy:t}}}})},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,startNum:n=0,flags:r}){let a=e.attributes.newNamespace?.primitive,i={};for(let t of["displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(i[t]=e.attributes[t]);let s=[];for(let o of(await e.stateValues.sampledValues).slice(n)){let e={};Object.keys(i).length>0&&(e=convertAttributesForComponentType({attributes:i,componentType:"number",componentInfoObjects:t,compositeCreatesNewNamespace:a,flags:r})),s.push({componentType:"number",attributes:e,state:{value:o}})}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:a,indOffset:n,componentInfoObjects:t}).serializedComponents}}static async calculateReplacementChanges({component:e,componentInfoObjects:t,flags:n}){let r=[],a=await e.stateValues.sampledValues;if(a.length0){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};r.push(e)}if(a.length>e.replacements.length){let a=await this.createSerializedReplacements({component:e,componentInfoObjects:t,startNum:e.replacements.length,flags:n}),i={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:e.replacements.length,numberReplacementsToReplace:0,serializedReplacements:a.replacements,assignNamesOffset:e.replacements.length};r.push(i)}}let i=Math.min(e.replacements.length,a.length);for(let t=0;t({variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){return{setValue:{variants:e.variants}}}},e.step.immutable=!0,e.from.immutable=!0,e.from.additionalStateVariablesDefined[0].immutable=!0,e.from.additionalStateVariablesDefined[1].immutable=!0,e.mean.immutable=!0,e.variance.immutable=!0,e.standardDeviation.immutable=!0,delete e.sampledValues,e.selectedValues={immutable:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:({sharedParameters:e})=>({numberOfSamples:{dependencyType:"stateVariable",variableName:"numberToSelect"},type:{dependencyType:"stateVariable",variableName:"type"},from:{dependencyType:"stateVariable",variableName:"from"},to:{dependencyType:"stateVariable",variableName:"to"},step:{dependencyType:"stateVariable",variableName:"step"},nDiscreteValues:{dependencyType:"stateVariable",variableName:"nDiscreteValues"},mean:{dependencyType:"stateVariable",variableName:"mean"},standardDeviation:{dependencyType:"stateVariable",variableName:"standardDeviation"},variants:{dependencyType:"stateVariable",variableName:"variants"},rng:{dependencyType:"value",value:e.variantRng,doNotProxy:!0}}),definition({dependencyValues:e}){if(e.numberOfSamples<1)return{setEssentialValue:{selectedValues:[]},setValue:{selectedValues:[]}};if(e.variants&&e.variants.desiredVariant){let t=e.variants.desiredVariant.values;if(t){if(t.length!==e.numberOfSamples)throw Error("Number of values specified for selectRandomNumber must match number to select");return{setEssentialValue:{selectedValues:t},setValue:{selectedValues:t}}}}let t=sampleFromRandomNumbers(e);return{setEssentialValue:{selectedValues:t},setValue:{selectedValues:t}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:()=>({selectedValues:{dependencyType:"stateVariable",variableName:"selectedValues"}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{generatedVariantInfo:{values:e.selectedValues,meta:{createdBy:t}}}})},e.readyToExpandWhenResolved={returnDependencies:()=>({selectedValues:{dependencyType:"stateVariable",variableName:"selectedValues"}}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n}){let r=e.attributes.newNamespace?.primitive,a={};for(let t of["displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(a[t]=e.attributes[t]);let i=[];for(let s of await e.stateValues.selectedValues){let e={};Object.keys(a).length>0&&(e=convertAttributesForComponentType({attributes:a,componentType:"number",componentInfoObjects:t,compositeCreatesNewNamespace:r,flags:n})),i.push({componentType:"number",attributes:e,state:{value:s}})}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:i,parentName:e.componentName,parentCreatesNewNamespace:r,componentInfoObjects:t}).serializedComponents}}}delete SelectRandomNumbers.stateVariableToEvaluateAfterReplacements,delete SelectRandomNumbers.calculateReplacementChanges;class Substitute extends CompositeComponent{static componentType="substitute";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"math",toLowerCase:!0,validValues:["math","text"],public:!0},e.match={createComponentOfType:"_componentWithSelectableType",createStateVariable:"match",defaultValue:null},e.replacement={createComponentOfType:"_componentWithSelectableType",createStateVariable:"replacement",defaultValue:null},e.simplify={createComponentOfType:"text",createStateVariable:"simplify",defaultValue:"none",public:!0,toLowerCase:!0,valueTransformations:{true:"full"},validValues:["none","full","numbers","numberspreserveorder"]},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.matchWholeWord={createComponentOfType:"boolean",createStateVariable:"matchWholeWord",defaultValue:!1,public:!0},e.matchCase={createComponentOfType:"boolean",createStateVariable:"matchCase",defaultValue:!1,public:!0},e.preserveCase={createComponentOfType:"boolean",createStateVariable:"preserveCase",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){let n=t.type;return["math","text"].includes(n)||(n="math"),{success:!0,newChildren:[{componentType:n,children:e}]}}}),e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},child:{dependencyType:"child",childGroups:["anything"],variableNames:["displayDigits"],variablesOptional:!0}}),definition({dependencyValues:e,usedDefault:t}){if("math"!==e.type)return{setValue:{displayDigits:null}};if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({type:{dependencyType:"stateVariable",variableName:"type"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},child:{dependencyType:"child",childGroups:["anything"],variableNames:["displayDecimals"],variablesOptional:!0}}),definition:({dependencyValues:e,usedDefault:t})=>"math"!==e.type?{setValue:{displayDecimals:null}}:null===e.displayDecimalsAttr||t.displayDecimalsAttr?1!==e.child.length||t.child[0]&&t.child[0].displayDecimals?{useEssentialOrDefaultValue:{displayDecimals:!0}}:{setValue:{displayDecimals:e.child[0].stateValues.displayDecimals}}:{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},child:{dependencyType:"child",childGroups:["anything"],variableNames:["displaySmallAsZero"],variablesOptional:!0}}),definition:({dependencyValues:e,usedDefault:t})=>"math"!==e.type?{setValue:{displaySmallAsZero:null}}:null===e.displaySmallAsZeroAttr||t.displaySmallAsZeroAttr?1!==e.child.length||t.child[0]&&t.child[0].displaySmallAsZero?{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}:{setValue:{displaySmallAsZero:e.child[0].stateValues.displaySmallAsZero}}:{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},child:{dependencyType:"child",childGroups:["anything"],variableNames:["padZeros"],variablesOptional:!0}}),definition:({dependencyValues:e,usedDefault:t})=>"math"!==e.type?{setValue:{padZeros:null}}:null===e.padZerosAttr||t.padZerosAttr?1!==e.child.length||t.child[0]&&t.child[0].padZeros?{useEssentialOrDefaultValue:{padZeros:!0}}:{setValue:{padZeros:e.child[0].stateValues.padZeros}}:{setValue:{padZeros:e.padZerosAttr.stateValues.value}}},e.originalValue={returnDependencies:()=>({child:{dependencyType:"child",childGroups:["anything"],variableNames:["value"]}}),definition:({dependencyValues:e})=>e.child.length>0?{setValue:{originalValue:e.child[0].stateValues.value}}:{setValue:{originalValue:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.child.length>0?{success:!0,instructions:[{setDependency:"child",desiredValue:e.originalValue,childIndex:0,variableIndex:0}]}:{success:!1}},e.value={returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},originalValue:{dependencyType:"stateVariable",variableName:"originalValue"},match:{dependencyType:"stateVariable",variableName:"match"},replacement:{dependencyType:"stateVariable",variableName:"replacement"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},matchWholeWord:{dependencyType:"stateVariable",variableName:"matchWholeWord"},matchCase:{dependencyType:"stateVariable",variableName:"matchCase"},preserveCase:{dependencyType:"stateVariable",variableName:"preserveCase"}}),definition({dependencyValues:e}){if(null===e.originalValue)return{setValue:{value:null}};if(null===e.match||null===e.replacement)return{setValue:{value:e.originalValue}};if("text"===e.type){let t,n=e.originalValue,r="g";e.matchCase||(r="gi"),t=e.matchWholeWord?new RegExp("\\b"+escapeRegExp(e.match)+"\\b",r):new RegExp(escapeRegExp(e.match),r);let a=e.replacement;if(e.preserveCase){let e=returnPreserveCaseReplacer(a);n=n.replace(t,e)}else n=n.replace(t,a);return{setValue:{value:n}}}{let t=e.originalValue.subscripts_to_strings();return t=t.substitute({[e.match.subscripts_to_strings().tree]:e.replacement.subscripts_to_strings()}),t=t.strings_to_subscripts(),t=normalizeMathExpression({value:t,simplify:e.simplify}),{setValue:{value:t}}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("text"===t.type){let n,r,a=e.value,i="g";t.matchCase||(i="gi");let s=t.match,o=t.replacement;if(t.matchWholeWord)if(n=new RegExp("\\b"+escapeRegExp(s)+"\\b",i),t.matchCase&&t.preserveCase){let e=returnPreserveCaseReplacer(o);r=new RegExp("\\b"+escapeRegExp(e(s))+"\\b",i)}else r=new RegExp("\\b"+escapeRegExp(o)+"\\b",i);else if(n=new RegExp(escapeRegExp(s),i),t.matchCase&&t.preserveCase){let e=returnPreserveCaseReplacer(o);r=new RegExp(escapeRegExp(e(s)),i)}else r=new RegExp(escapeRegExp(o),i);return-1!==t.originalValue.search(r)||-1!==a.search(n)?{success:!1}:(a=a.replace(r,s),{success:!0,instructions:[{setDependency:"originalValue",desiredValue:a}]})}{let n=e.value.subscripts_to_strings(),r=t.match.subscripts_to_strings(),a=t.replacement.subscripts_to_strings();return"string"!=typeof r.tree||"string"!=typeof a.tree||(t.originalValue.variables(!0).includes(a.tree)||n.variables().includes(r.tree))?{success:!1}:(n=n.substitute({[a.tree]:r}),n=n.strings_to_subscripts(),{success:!0,instructions:[{setDependency:"originalValue",desiredValue:n}]})}}},e.readyToExpandWhenResolved={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n}){let r=e.attributes.newNamespace?.primitive,a=await e.stateValues.type,i={componentType:a,state:{value:await e.stateValues.value},downstreamDependencies:{[e.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:"value"}]}};if("math"===a){let t={},n={displayDigits:"integer",displayDecimals:"integer",displaySmallAsZero:"number",padZeros:"boolean"};for(let r in n){let a={componentType:n[r],downstreamDependencies:{[e.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:r}]}};t[r]={component:a}}i.attributes=t}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:[i],parentName:e.componentName,parentCreatesNewNamespace:r,componentInfoObjects:t}).serializedComponents}}}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function returnPreserveCaseReplacer(e){return function(t){return t.toUpperCase()===t?e.toUpperCase():t.toLowerCase()===t?e.toLowerCase():t[0].match(/[a-z]/)?e[0].toLowerCase()+e.substring(1):t[0].match(/[A-Z]/)?e[0].toUpperCase()+e.substring(1):e}}class PeriodicSet extends MathComponent{static componentType="periodicSet";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.minIndex={createComponentOfType:"integer",createStateVariable:"minIndex",defaultValue:-1/0,public:!0},e.maxIndex={createComponentOfType:"integer",createStateVariable:"maxIndex",defaultValue:1/0,public:!0},e.offsets={createComponentOfType:"mathList",createStateVariable:"offsets",defaultValue:null,public:!0},e.period={createComponentOfType:"math",createStateVariable:"period",defaultValue:null,public:!0},e.minIndexAsList={createComponentOfType:"integer",createStateVariable:"minIndexAsList",defaultValue:-1,public:!0},e.maxIndexAsList={createComponentOfType:"integer",createStateVariable:"maxIndexAsList",defaultValue:1,public:!0},e}static returnChildGroups(){return[]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.codePre,delete e.expressionWithCodes,delete e.mathChildrenFunctionSymbols,delete e.codesAdjacentToStrings,delete e.mathChildrenByVectorComponent,delete e.mathChildrenWithCanBeModified,delete e.unordered,e.canBeModified={returnDependencies:()=>({}),definition:()=>({setValue:{canBeModified:!1}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}if(!(null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals)&&null!==e.displayDigitsAttr){if(!t.displayDigitsAttr)return{setValue:{displayDigits:e.displayDigitsAttr.stateValues.value}};r=!0,n=e.displayDigitsAttr.stateValues.value}return r?{useEssentialOrDefaultValue:{displayDigits:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDigits:!0}}}},e.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:null,returnDependencies:()=>({mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.nOffsets={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({offsets:{dependencyType:"stateVariable",variableName:"offsets"}}),definition({dependencyValues:e}){let t=0;return null!==e.offsets&&(t=e.offsets.length),{setValue:{nOffsets:t}}}},e.unnormalizedValue={returnDependencies:()=>({offsets:{dependencyType:"stateVariable",variableName:"offsets"},period:{dependencyType:"stateVariable",variableName:"period"},minIndex:{dependencyType:"stateVariable",variableName:"minIndex"},maxIndex:{dependencyType:"stateVariable",variableName:"maxIndex"}}),definition({dependencyValues:e}){if(null===e.offsets||0===e.offsets.length||1===e.offsets.length&&"_"===e.offsets[0].tree||null===e.period||"_"===e.period.tree)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};let t=[],n=e.period.tree,r=e.minIndex,a=e.maxIndex;for(let i of e.offsets)t.push(["tuple",i.tree,n,r,a]);return{setValue:{unnormalizedValue:me$3.fromAst(["periodic_set",...t])}}}},e.redundantOffsets={additionalStateVariablesDefined:["uniqueOffsets"],public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({nOffsets:{dependencyType:"stateVariable",variableName:"nOffsets"},offsets:{dependencyType:"stateVariable",variableName:"offsets"},period:{dependencyType:"stateVariable",variableName:"period"}}),definition({dependencyValues:e}){let t=!1,n=[];if(null!==e.period){let r=e.period.evaluate_to_constant();if(null!==r)for(let a=0;a({uniqueOffsets:{dependencyType:"stateVariable",variableName:"uniqueOffsets"},period:{dependencyType:"stateVariable",variableName:"period"},minIndexAsList:{dependencyType:"stateVariable",variableName:"minIndexAsList"},maxIndexAsList:{dependencyType:"stateVariable",variableName:"maxIndexAsList"}}),definition({dependencyValues:e}){let t=[];if(null!==e.period){let n=e.period.evaluate_to_constant();if(null!==n){let r=e.period.simplify(),a=!0,i=[];for(let t of e.uniqueOffsets){let e=t.evaluate_to_constant();if(null===e){a=!1;break}{let a=t.subtract(r.multiply(Math.floor(e/n))).simplify(),s=a.evaluate_to_constant();i.push({num:s,offset:a})}}if(a){t.push(me$3.fromAst(["ldots"])),i.sort(((e,t)=>e.num-t.num));let n=-1,a=1;Number.isFinite(e.minIndexAsList)&&(n=e.minIndexAsList),Number.isFinite(e.maxIndexAsList)&&(a=e.maxIndexAsList);for(let e=n;e<=a;e++)for(let n of i)t.push(n.offset.add(r.multiply(e)).simplify());t.push(me$3.fromAst(["ldots"]))}}}return{setValue:{asList:t}}}},e}}class Image extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{moveImage:this.moveImage.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="image";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"specifiedWidth",defaultValue:null},e.size={createComponentOfType:"text",createStateVariable:"specifiedSize",defaultValue:"medium",toLowerCase:!0,validValues:sizePossibilities},e.aspectRatio={createComponentOfType:"number"},e.height={createComponentOfType:"_componentSize"},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",validValues:["block","inline"],defaultValue:"block",forRenderer:!0,public:!0},e.horizontalAlign={createComponentOfType:"text",createStateVariable:"horizontalAlign",toLowerCase:!0,validValues:["center","left","right"],defaultValue:"center",forRenderer:!0,public:!0},e.description={createComponentOfType:"text",createStateVariable:"description",defaultValue:"",public:!0,forRenderer:!0},e.source={createComponentOfType:"text",createStateVariable:"source",defaultValue:"",public:!0,forRenderer:!0},e.asFileName={createComponentOfType:"text",createStateVariable:"asFileName",defaultValue:null,public:!0,forRenderer:!0},e.mimeType={createComponentOfType:"text",createStateVariable:"mimeType",defaultValue:null,public:!0,forRenderer:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.rotate={createComponentOfType:"number",createStateVariable:"rotate",defaultValue:0,public:!0,forRenderer:!0},e.styleNumber.defaultValue=0,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.size={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({specifiedSize:{dependencyType:"stateVariable",variableName:"specifiedSize"},specifiedWidth:{dependencyType:"stateVariable",variableName:"specifiedWidth"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xscale"]}}),definition({dependencyValues:e,usedDefault:t}){const n="medium";if(t.specifiedSize){if(t.specifiedWidth)return{setValue:{size:n}};{let t=e.specifiedWidth;if(null===t)return{setValue:{size:n}};let r,{isAbsolute:a,size:i}=t;if(a){let t;if(e.graphAncestor){let n=e.graphAncestor.stateValues.xscale;t=orderedPercentWidthMidpoints.map((e=>e/100*n))}else t=orderedWidthMidpoints;for(let[e,n]of t.entries())if(i<=n){r=sizePossibilities[e];break}r||(r=n)}else{for(let[e,t]of orderedPercentWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=n)}return{setValue:{size:r}}}}return{setValue:{size:e.specifiedSize}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"specifiedSize",desiredValue:e.size}]})},e.width={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},returnDependencies:()=>({specifiedSize:{dependencyType:"stateVariable",variableName:"specifiedSize"},size:{dependencyType:"stateVariable",variableName:"size"},specifiedWidth:{dependencyType:"stateVariable",variableName:"specifiedWidth"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xscale"]}}),definition({dependencyValues:e,usedDefault:t}){if(e.graphAncestor){if(e.graphAncestor.stateValues.xscale,t.specifiedSize){if(t.specifiedWidth)return{setValue:{width:{isAbsolute:!1,size:percentWidthsBySize.medium}}};{let t,n=e.specifiedWidth;return t=n||{isAbsolute:!1,size:percentWidthsBySize.medium},{setValue:{width:t}}}}return{setValue:{width:{isAbsolute:!1,size:percentWidthsBySize[e.size]}}}}return{setValue:{width:{isAbsolute:!0,size:widthsBySize[e.size]}}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"specifiedWidth",desiredValue:e.width}]})},e.widthForGraph={forRenderer:!0,returnDependencies:()=>({width:{dependencyType:"stateVariable",variableName:"width"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xscale"]}}),definition({dependencyValues:e}){let t=e.width;return e.graphAncestor&&!t.isAbsolute&&(t={isAbsolute:!0,size:t.size/100*e.graphAncestor.stateValues.xscale}),{setValue:{widthForGraph:t}}}},e.aspectRatio={public:!0,forRenderer:!0,hasEssential:!0,defaultValue:null,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]}}),definition({dependencyValues:e}){if(null!==e.aspectRatioAttr){let t=e.aspectRatioAttr.stateValues.value;return Number.isFinite(t)||(t=null),{setValue:{aspectRatio:t}}}return{useEssentialOrDefaultValue:{aspectRatio:!0}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(null!==t.aspectRatioAttr)return{success:!0,instructions:[{setDependency:"aspectRatioAttr",desiredValue:e.aspectRatio,variableIndex:0}]};{let t=e.aspectRatio;return t>0||(t=null),{success:!0,instructions:[{setEssentialValue:"aspectRatio",value:t}]}}}},e.cid={forRenderer:!0,returnDependencies:()=>({source:{dependencyType:"stateVariable",variableName:"source"}}),definition:function({dependencyValues:e}){if(!e.source||"doenet:"!==e.source.substring(0,7).toLowerCase())return{setValue:{cid:null}};let t=null,n=e.source.match(/[:&]cid=([^&]+)/i);return n&&(t=n[1]),{setValue:{cid:t}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveImage({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Video extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVideoStarted:this.recordVideoStarted.bind(this),recordVideoWatched:this.recordVideoWatched.bind(this),recordVideoPaused:this.recordVideoPaused.bind(this),recordVideoSkipped:this.recordVideoSkipped.bind(this),recordVideoCompleted:this.recordVideoCompleted.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this),recordVideoReady:this.recordVideoReady.bind(this),playVideo:this.playVideo.bind(this),pauseVideo:this.pauseVideo.bind(this),setTime:this.setTime.bind(this)})}static componentType="video";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize"},e.size={createComponentOfType:"text"},e.aspectRatio={createComponentOfType:"number"},e.height={createComponentOfType:"_componentSize"},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",validValues:["block","inline"],defaultValue:"block",forRenderer:!0,public:!0},e.horizontalAlign={createComponentOfType:"text",createStateVariable:"horizontalAlign",validValues:["center","left","right"],defaultValue:"center",forRenderer:!0,public:!0},e.youtube={createComponentOfType:"text",createStateVariable:"youtube",defaultValue:null,public:!0,forRenderer:!0},e.source={createComponentOfType:"text",createStateVariable:"source",defaultValue:null,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.size={public:!0,defaultValue:"full",hasEssential:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({sizeAttr:{dependencyType:"attributeComponent",attributeName:"size",variableNames:["value"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]}}),definition({dependencyValues:e}){const t="full";if(e.sizeAttr){let n=e.sizeAttr.stateValues.value.toLowerCase();return sizePossibilities.includes(n)||(n=t),{setValue:{size:n}}}if(e.widthAttr){let n=e.widthAttr.stateValues.componentSize;if(null===n)return{setValue:{size:t}};let r,{isAbsolute:a,size:i}=n;if(a){for(let[e,t]of orderedWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}else{for(let[e,t]of orderedPercentWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}return{setValue:{size:r}}}return{useEssentialOrDefaultValue:{size:!0}}}},e.width={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},returnDependencies:()=>({size:{dependencyType:"stateVariable",variableName:"size"}}),definition:({dependencyValues:e})=>({setValue:{width:{isAbsolute:!0,size:widthsBySize[e.size]}}})},e.aspectRatio={public:!0,forRenderer:!0,defaultValue:"16 / 9",hasEssential:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},width:{dependencyType:"stateVariable",variableName:"width"}}),definition({dependencyValues:e}){if(null!==e.aspectRatioAttr){let t=e.aspectRatioAttr.stateValues.value;return Number.isFinite(t)||(t=1),{setValue:{aspectRatio:t}}}return{useEssentialOrDefaultValue:{aspectRatio:!0}}}},e.state={hasEssential:!0,defaultValue:"initializing",forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},ignoreFixed:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{state:!0}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.state.toLowerCase();return["stopped","playing"].includes(t)?{success:!0,instructions:[{setEssentialValue:"state",value:t}]}:{success:!1}}},e.time={hasEssential:!0,defaultValue:0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"number"},ignoreFixed:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{time:!0}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.time;return t>=0?{success:!0,instructions:[{setEssentialValue:"time",value:t}]}:{success:!1}}},e.duration={hasEssential:!0,defaultValue:null,public:!0,shadowingInstructions:{createComponentOfType:"number"},ignoreFixed:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{duration:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"duration",value:e.duration}]})},e.segmentsWatched={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{segmentsWatched:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"segmentsWatched",value:e.segmentsWatched}]})},e.secondsWatched={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({segmentsWatched:{dependencyType:"stateVariable",variableName:"segmentsWatched"}}),definition({dependencyValues:e}){let t=0;return e.segmentsWatched&&(t=e.segmentsWatched.reduce(((e,t)=>e+t[1]-t[0]),0)),{setValue:{secondsWatched:t}}}},e.fractionWatched={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({secondsWatched:{dependencyType:"stateVariable",variableName:"secondsWatched"},duration:{dependencyType:"stateVariable",variableName:"duration"}}),definition:({dependencyValues:e})=>({setValue:{fractionWatched:e.secondsWatched/e.duration}})},e}recordVideoStarted({beginTime:e,duration:t,rate:n}){this.coreFunctions.requestRecordEvent({verb:"played",object:{componentName:this.componentName,componentType:this.componentType,duration:t},context:{startingPoint:e,rate:n}}),this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"playing"}],overrideReadOnly:!0})}async recordVideoWatched({beginTime:e,endTime:t,duration:n,rates:r}){this.coreFunctions.requestRecordEvent({verb:"watched",object:{componentName:this.componentName,componentType:this.componentType,duration:n},context:{startingPoint:e,endingPoint:t,rates:r}});let a,i=await this.stateValues.segmentsWatched;if(e<1?e=0:t>n-2&&(t=n),i){a=[];let n=!1;for(let[r,s]of i.entries()){if(ts[1]+1?a.push(s):(e=Math.min(s[0],e),t=Math.max(s[1],t))}n||a.push([e,t])}else a=[[e,t]];return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"segmentsWatched",value:a}],canSkipUpdatingRenderer:!0}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}recordVideoPaused({endTime:e,duration:t}){this.coreFunctions.requestRecordEvent({verb:"paused",object:{componentName:this.componentName,componentType:this.componentType,duration:t},context:{endingPoint:e}}),this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"stopped"}],overrideReadOnly:!0})}recordVideoSkipped({beginTime:e,endTime:t,duration:n}){this.coreFunctions.requestRecordEvent({verb:"skipped",object:{componentName:this.componentName,componentType:this.componentType,duration:n},context:{startingPoint:e,endingPoint:t}})}recordVideoCompleted({duration:e}){this.coreFunctions.requestRecordEvent({verb:"completed",object:{componentName:this.componentName,componentType:this.componentType,duration:e}}),this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"stopped"}],overrideReadOnly:!0})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}recordVideoReady({duration:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"stopped"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"duration",value:e}],overrideReadOnly:!0,doNotSave:!0})}playVideo(){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"playing"}],overrideReadOnly:!0})}pauseVideo(){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"state",value:"stopped"}],overrideReadOnly:!0})}setTime({time:e}){this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"time",value:e}],overrideReadOnly:!0})}}class Embed extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="embed";static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:500,isAbsolute:!0},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:500,isAbsolute:!0},public:!0,forRenderer:!0},e.geogebra={createComponentOfType:"text",createStateVariable:"geogebra",defaultValue:null,public:!0,forRenderer:!0},e.encodedGeogebraContent={createComponentOfType:"text",createStateVariable:"encodedGeogebraContent",defaultValue:null,public:!0,forRenderer:!0},e.fromMathInsight={createComponentOfType:"text",createStateVariable:"fromMathInsight",defaultValue:null,public:!0,forRenderer:!0},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Hint extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{revealHint:this.revealHint.bind(this),closeHint:this.closeHint.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="hint";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"titles",componentTypes:["title"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.showHints={forRenderer:!0,returnDependencies:()=>({hide:{dependencyType:"stateVariable",variableName:"hide"},showHintsFlag:{dependencyType:"flag",flagName:"showHints"}}),definition:({dependencyValues:e})=>({setValue:{showHints:e.showHintsFlag&&!e.hide}})},e.open={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{open:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"open",value:e.open}]})},e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[e.titleChild.length-1].componentName),{setValue:{titleChildName:t}}}},e.childIndicesToRender={returnDependencies:()=>({titleChildren:{dependencyType:"child",childGroups:["titles"]},allChildren:{dependencyType:"child",childGroups:["anything","titles"]},titleChildName:{dependencyType:"stateVariable",variableName:"titleChildName"}}),definition({dependencyValues:e}){let t=[],n=e.titleChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())"object"==typeof a&&n.includes(a.componentName)&&a.componentName!==e.titleChildName||t.push(r);return{setValue:{childIndicesToRender:t}}}},e.title={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.titleChild.length?{setValue:{title:"Hint"}}:{setValue:{title:e.titleChild[e.titleChild.length-1].stateValues.text}}},e}async revealHint({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!0}],overrideReadOnly:!0,actionId:e,event:{verb:"viewed",object:{componentName:this.componentName,componentType:this.componentType}}})}async closeHint({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!1}],overrideReadOnly:!0,actionId:e,event:{verb:"closed",object:{componentName:this.componentName,componentType:this.componentType}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Solution extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{revealSolution:this.revealSolution.bind(this),closeSolution:this.closeSolution.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="solution";static renderChildren=!0;static sendToRendererEvenIfHidden=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.hide={createComponentOfType:"boolean"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){return{success:!0,newChildren:[{componentType:"_solutionContainer",children:e}]}}}),e}static returnChildGroups(){return[{group:"inlinesBlocks",componentTypes:["_inline","_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.hide={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,returnDependencies:()=>({hideAttr:{dependencyType:"attributeComponent",attributeName:"hide",variableNames:["value"]},displayMode:{dependencyType:"flag",flagName:"solutionDisplayMode"}}),definition:({dependencyValues:e})=>"none"===e.displayMode?{setValue:{hide:!0}}:null!==e.hideAttr?{setValue:{hide:e.hideAttr.stateValues.value}}:{useEssentialOrDefaultValue:{hide:!0}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>"none"===t.displayMode?{success:!1}:null!==t.hideAttr?{success:!0,instructions:[{setDependency:"hideAttr",desiredValue:e.hide,variableIndex:0}]}:{success:!0,instructions:[{setSetVariable:"hide",value:e.hide}]}},e.open={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,returnDependencies:()=>({displayMode:{dependencyType:"flag",flagName:"solutionDisplayMode"}}),definition:({dependencyValues:e})=>"displayed"===e.displayMode?{setValue:{open:!0}}:"none"===e.displayMode?{setValue:{open:!1}}:{useEssentialOrDefaultValue:{open:!0}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>"displayed"===t.displayMode||"none"===t.displayMode?{success:!1}:{success:!0,instructions:[{setEssentialValue:"open",value:e.open}]}},e.canBeClosed={forRenderer:!0,returnDependencies:()=>({displayMode:{dependencyType:"flag",flagName:"solutionDisplayMode"}}),definition:({dependencyValues:e})=>"button"===e.displayMode?{setValue:{canBeClosed:!0}}:{setValue:{canBeClosed:!1}}},e.message={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,defaultValue:"",hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{message:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"message",value:e.message}]})},e}async revealSolution({actionId:e}){let t,{allowView:n,message:r,scoredComponent:a}=await this.coreFunctions.recordSolutionView(),i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:n},{updateType:"updateValue",componentName:this.componentName,stateVariable:"message",value:r}];return n&&(i.push({updateType:"updateValue",componentName:a,stateVariable:"viewedSolution",value:!0}),t={verb:"viewed",object:{componentName:this.componentName,componentType:this.componentType}}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:t,overrideReadOnly:!0})}async closeSolution({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!1}],overrideReadOnly:!0,actionId:e,event:{verb:"closed",object:{componentName:this.componentName,componentType:this.componentType}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static includeBlankStringChildren=!0}class IntComma extends Text{static componentType="intcomma";static rendererType="text";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"originalValue"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType},returnDependencies:()=>({originalValue:{dependencyType:"stateVariable",variableName:"originalValue"}}),definition:function({dependencyValues:e}){let t=e.originalValue,n=/^(-?\d+)(\d{3})/,r=t.match(n);for(;null!==r;)t=t.replace(n,"$1,$2"),r=t.match(n);return{setValue:{value:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}}const e$1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split("");var t$1=function(e){let t=(e=e||"_")+"-";for(let e=0;e<7;e++)t+=e$1[Math.floor(Math.random()*e$1.length)];return t};let r$1={"!":"¡","?":"¿Ɂ",'"':'“”"❝❞',"'":"‘‛❛❜","-":"—–",a:"ªÀÁÂÃÄÅàáâãäåĀāĂ㥹ǍǎǞǟǠǡǺǻȀȁȂȃȦȧȺΆΑΔΛάαλАадѦѧӐӑӒӓƛɅæ",b:"ßþƀƁƂƃƄƅɃΒβϐϦБВЪЬвъьѢѣҌҍ",c:"¢©ÇçĆćĈĉĊċČčƆƇƈȻȼͻͼͽϲϹϽϾСсєҀҁҪҫ",d:"ÐĎďĐđƉƊȡƋƌǷ",e:"ÈÉÊËèéêëĒēĔĕĖėĘęĚěƎƏƐǝȄȅȆȇȨȩɆɇΈΕΞΣέεξϱϵ϶ЀЁЕЭеѐёҼҽҾҿӖӗӘәӚӛӬӭ",f:"ƑƒϜϝӺӻҒғſ",g:"ĜĝĞğĠġĢģƓǤǥǦǧǴǵ",h:"ĤĥĦħƕǶȞȟΉΗЂЊЋНнђћҢңҤҥҺһӉӊ",I:"ÌÍÎÏ",i:"ìíîïĨĩĪīĬĭĮįİıƖƗȈȉȊȋΊΐΪίιϊІЇії",j:"ĴĵǰȷɈɉϳЈј",k:"ĶķĸƘƙǨǩΚκЌЖКжкќҚқҜҝҞҟҠҡ",l:"ĹĺĻļĽľĿŀŁłƚƪǀǏǐȴȽΙӀӏ",m:"ΜϺϻМмӍӎ",n:"ÑñŃńŅņŇňʼnŊŋƝƞǸǹȠȵΝΠήηϞЍИЙЛПийлпѝҊҋӅӆӢӣӤӥπ",o:"ÒÓÔÕÖØðòóôõöøŌōŎŏŐőƟƠơǑǒǪǫǬǭǾǿȌȍȎȏȪȫȬȭȮȯȰȱΌΘΟθοσόϕϘϙϬϭϴОФоѲѳӦӧӨөӪӫ",p:"ƤƿΡρϷϸϼРрҎҏÞ",q:"Ɋɋ",r:"ŔŕŖŗŘřƦȐȑȒȓɌɍЃГЯгяѓҐґ",s:"ŚśŜŝŞşŠšƧƨȘșȿЅѕ",t:"ŢţŤťŦŧƫƬƭƮȚțȶȾΓΤτϮТт",u:"µÙÚÛÜùúûüŨũŪūŬŭŮůŰűŲųƯưƱƲǓǔǕǖǗǘǙǚǛǜȔȕȖȗɄΰμυϋύ",v:"νѴѵѶѷ",w:"ŴŵƜωώϖϢϣШЩшщѡѿ",x:"×ΧχϗϰХхҲҳӼӽӾӿ",y:"ÝýÿŶŷŸƳƴȲȳɎɏΎΥΫγψϒϓϔЎУучўѰѱҮүҰұӮӯӰӱӲӳ",z:"ŹźŻżŽžƩƵƶȤȥɀΖζ"},a$1={};Object.keys(r$1).forEach((function(e){r$1[e].split("").forEach((function(t){a$1[t]=e}))}));var n$1=e=>{let t=e.split("");return t.forEach(((e,n)=>{a$1[e]&&(t[n]=a$1[e])})),t.join("")};const i$1=/([A-Z]\.)+[A-Z]?,?$/,o$1=/^[A-Z]\.,?$/,s$1=/[A-Z]{2,}('s|,)?$/,l$1=/([a-z]\.)+[a-z]\.?$/;var u$1=function(e){return!0===i$1.test(e)||!0===l$1.test(e)||!0===o$1.test(e)||!0===s$1.test(e)};const c$2=n$1,h$1=u$1,d$1=/[a-z\u00C0-\u00FF] ?\/ ?[a-z\u00C0-\u00FF]/,g$1=function(e){let t=e=(e=(e=e||"").toLowerCase()).trim();return e=c$2(e),!0===d$1.test(e)&&(e=e.replace(/\/.*/,"")),e=(e=(e=(e=(e=(e=(e=e.replace(/^[#@]/,"")).replace(/[,;.!?]+$/,"")).replace(/[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]+/g,"'")).replace(/[\u0022\u00AB\u00BB\u201C\u201D\u201E\u201F\u2033\u2034\u2036\u2037\u2E42\u301D\u301E\u301F\uFF02]+/g,'"')).replace(/\u2026/g,"...")).replace(/\u2013/g,"-")).replace(/([aeiou][ktrp])in$/,"$1ing"),!0===/^(re|un)-?[^aeiou]./.test(e)&&(e=e.replace("-","")),h$1(e)&&(e=e.replace(/\./g,"")),!1===/^[:;]/.test(e)&&(e=(e=(e=e.replace(/\.{3,}$/g,"")).replace(/[",\.!:;\?\)]+$/g,"")).replace(/^['"\(]+/g,"")),""===(e=(e=e.replace(/[\u200B-\u200D\uFEFF]/g,"")).trim())&&(e=t),e.replace(/([0-9]),([0-9])/g,"$1$2")},p$1=function(e){return(e=e.replace(/['’]s$/,"")).replace(/s['’]$/,"s")},m$1=/^[ \n\t\.\[\](){}⟨⟩:,،、‒–—―…!‹›«»‐\-?‘’;\/⁄·&*•^†‡°¡¿※№÷׺ª%‰+−=‱¶′″‴§~\|‖¦©℗®℠™¤₳฿\u0022\uFF02\u0027\u201C\u201F\u201B\u201E\u2E42\u201A\u2035\u2036\u2037\u301D\u0060\u301F]+/,f$1=/[ \n\t\.'\[\](){}⟨⟩:,،、‒–—―…!‹›«»‐\-?‘’;\/⁄·&*@•^†‡°¡¿※#№÷׺ª‰+−=‱¶′″‴§~\|‖¦©℗®℠™¤₳฿\u0022\uFF02\u201D\u00B4\u301E]+$/,b$1=/\//,y$1=/['’]/,v$1=/^[a-z]\.([a-z]\.)+/i,w$1=/^[-+\.][0-9]/,k$1=/^'[0-9]{2}/;var A$1=e=>{let t=e,n="",r="";""===(e=(e=e.replace(m$1,(t=>(n=t,"-"!==n&&"+"!==n&&"."!==n||!w$1.test(e)?"'"===n&&k$1.test(e)?(n="",t):"":(n="",t))))).replace(f$1,(a=>(r=a,y$1.test(a)&&/[sn]['’]$/.test(t)&&!1===y$1.test(n)?(r=r.replace(y$1,""),"'"):!0===v$1.test(e)?(r=r.replace(/\./,""),"."):""))))&&(t=t.replace(/ *$/,(e=>(r=e||"",""))),e=t,n="");let a=g$1(e);const i={text:e,clean:a,reduced:p$1(a),pre:n,post:r};return b$1.test(e)&&e.split(b$1).forEach((e=>{i.alias=i.alias||{},i.alias[e.trim()]=!0})),i},D$1={};!function(e){const t=/^[A-Z][a-z'\u00C0-\u00FF]/,n=/^[A-Z]+s?$/;e.toUpperCase=function(){return this.text=this.text.toUpperCase(),this},e.toLowerCase=function(){return this.text=this.text.toLowerCase(),this},e.toTitleCase=function(){return this.text=this.text.replace(/^ *[a-z\u00C0-\u00FF]/,(e=>e.toUpperCase())),this},e.isUpperCase=function(){return n.test(this.text)},e.isTitleCase=function(){return t.test(this.text)},e.titleCase=e.isTitleCase}(D$1);var $$1={};!function(e){const t=/(\u0022|\uFF02|\u0027|\u201C|\u2018|\u201F|\u201B|\u201E|\u2E42|\u201A|\u00AB|\u2039|\u2035|\u2036|\u2037|\u301D|\u0060|\u301F)/,n=/(\u0022|\uFF02|\u0027|\u201D|\u2019|\u201D|\u2019|\u201D|\u201D|\u2019|\u00BB|\u203A|\u2032|\u2033|\u2034|\u301E|\u00B4|\u301E)/;e.hasPost=function(e){return-1!==this.post.indexOf(e)},e.hasPre=function(e){return-1!==this.pre.indexOf(e)},e.hasQuote=function(){return t.test(this.pre)||n.test(this.post)},e.hasQuotation=e.hasQuote,e.hasComma=function(){return this.hasPost(",")},e.hasPeriod=function(){return!0===this.hasPost(".")&&!1===this.hasPost("...")},e.hasExclamation=function(){return this.hasPost("!")},e.hasQuestionMark=function(){return this.hasPost("?")||this.hasPost("¿")},e.hasEllipses=function(){return this.hasPost("..")||this.hasPost("…")||this.hasPre("..")||this.hasPre("…")},e.hasSemicolon=function(){return this.hasPost(";")},e.hasSlash=function(){return/\//.test(this.text)},e.hasHyphen=function(){const e=/^(-|–|—)$/;return e.test(this.post)||e.test(this.pre)},e.hasDash=function(){const e=/ (-|–|—) /;return e.test(this.post)||e.test(this.pre)},e.hasContraction=function(){return Boolean(this.implicit)},e.addPunctuation=function(e){return","!==e&&";"!==e||(this.post=this.post.replace(e,"")),this.post=e+this.post,this}}($$1);var P$1={};const E$1=function(e,t,n=3){if(e===t)return 1;if(e.lengthn?r:n)+1;if(Math.abs(n-r)>(a||100))return a||100;let i,s,o,l,u,c,p=[];for(let e=0;e4)return n;o=t[i-1],l=s===o?0:1,u=p[a-1][i]+1,(c=p[a][i-1]+1)1&&i>1&&s===t[i-2]&&e[a-2]===o&&(c=p[a-2][i-2]+l)t.fuzzy)return!0;if(!0===t.soft&&(n=E$1(t.word,e.root),n>t.fuzzy))return!0}return t.word===e.clean||t.word===e.text||t.word===e.reduced}return void 0!==t.tag?!0===e.tags[t.tag]:void 0!==t.method?"function"==typeof e[t.method]&&!0===e[t.method]():void 0!==t.regex?t.regex.test(e.clean):void 0!==t.fastOr?!(!e.implicit||!0!==t.fastOr.hasOwnProperty(e.implicit))||t.fastOr.hasOwnProperty(e.reduced)||t.fastOr.hasOwnProperty(e.text):void 0!==t.choices&&("and"===t.operator?t.choices.every((t=>H$1(e,t,n,r))):t.choices.some((t=>H$1(e,t,n,r))))}(e,t,n,r);return!0===t.negative?!a:a};const j$1=H$1,N$1=u$1,x$1={};P$1.doesMatch=function(e,t,n){return j$1(this,e,t,n)},P$1.isAcronym=function(){return N$1(this.text)},P$1.isImplicit=function(){return""===this.text&&Boolean(this.implicit)},P$1.isKnown=function(){return Object.keys(this.tags).some((e=>!0!==x$1[e]))},P$1.setRoot=function(e){let t=e.transforms,n=this.implicit||this.clean;if(this.tags.Plural&&(n=t.toSingular(n,e)),this.tags.Verb&&!this.tags.Negative&&!this.tags.Infinitive){let r=null;this.tags.PastTense?r="PastTense":this.tags.Gerund?r="Gerund":this.tags.PresentTense?r="PresentTense":this.tags.Participle?r="Participle":this.tags.Actor&&(r="Actor"),n=t.toInfinitive(n,e,r)}this.root=n};var F$1={};const C$1=n$1,B$1=/[\s-]/,G$1=/^[A-Z-]+$/;F$1.textOut=function(e,t,n){e=e||{};let r=this.text,a=this.pre,i=this.post;return!0===e.reduced&&(r=this.reduced||""),!0===e.root&&(r=this.root||""),!0===e.implicit&&this.implicit&&(r=this.implicit||""),!0===e.normal&&(r=this.clean||this.text||""),!0===e.root&&(r=this.root||this.reduced||""),!0===e.unicode&&(r=C$1(r)),!0===e.titlecase&&(this.tags.ProperNoun&&!this.titleCase()||(this.tags.Acronym?r=r.toUpperCase():G$1.test(r)&&!this.tags.Acronym&&(r=r.toLowerCase()))),!0===e.lowercase&&(r=r.toLowerCase()),!0===e.acronyms&&this.tags.Acronym&&(r=r.replace(/\./g,"")),!0!==e.whitespace&&!0!==e.root||(a="",i=" ",!1!==B$1.test(this.post)&&!e.last||this.implicit||(i="")),!0!==e.punctuation||e.root||(!0===this.hasPost(".")?i="."+i:!0===this.hasPost("?")?i="?"+i:!0===this.hasPost("!")?i="!"+i:!0===this.hasPost(",")?i=","+i:!0===this.hasEllipses()&&(i="..."+i)),!0!==t&&(a=""),!0!==n&&(i=""),!0===e.abbreviations&&this.tags.Abbreviation&&(i=i.replace(/^\./,"")),a+r+i};var z$1={};const I$1={Auxiliary:1,Possessive:1},O$1=function(e,t){let n=Object.keys(e.tags);const r=t.tags;return n=n.sort(((e,t)=>I$1[t]||!r[t]?-1:r[t]?r[e]?r[e].lineage.length>r[t].lineage.length?1:r[e].isA.length>r[t].isA.length?-1:0:0:1)),n},T$2={text:!0,tags:!0,implicit:!0,whitespace:!0,clean:!1,id:!1,index:!1,offset:!1,bestTag:!1};z$1.json=function(e,t){e=e||{};let n={};return(e=Object.assign({},T$2,e)).text&&(n.text=this.text),e.normal&&(n.normal=this.clean),e.tags&&(n.tags=Object.keys(this.tags)),e.clean&&(n.clean=this.clean),(e.id||e.offset)&&(n.id=this.id),e.implicit&&null!==this.implicit&&(n.implicit=this.implicit),e.whitespace&&(n.pre=this.pre,n.post=this.post),e.bestTag&&(n.bestTag=O$1(this,t)[0]),n};var V$1=Object.assign({},D$1,$$1,P$1,F$1,z$1),M$1={},J$1={};function L$1(){return"undefined"!=typeof window&&window.document}const S$1=function(e,t){for(e=e.toString();e.lengthe.charAt(0).toUpperCase()+e.substr(1);const _$1=J$1,K$1=function(e,t,n,r){let a=r.tags;if(""===t||"."===t||"-"===t)return;if("#"===t[0]&&(t=t.replace(/^#/,"")),t=_$1.titleCase(t),!0===e.tags[t])return;const i=r.isVerbose();!0===i&&_$1.logTag(e,t,n),e.tags[t]=!0,!0===a.hasOwnProperty(t)&&(a[t].isA.forEach((t=>{e.tags[t]=!0,!0===i&&_$1.logTag(e,"→ "+t)})),e.unTag(a[t].notA,"←",r))},q$1=J$1,W$1=/^[a-z]/,R$1=function(e,t,n,r){const a=r.isVerbose();if("*"===t)return e.tags={},e;var i;t=t.replace(/^#/,""),!0===W$1.test(t)&&(t=(i=t).charAt(0).toUpperCase()+i.substr(1)),!0===e.tags[t]&&(delete e.tags[t],!0===a&&q$1.logUntag(e,t,n));const s=r.tags;if(s[t]){let n=s[t].lineage;for(let t=0;te.clone()));return t.forEach(((e,n)=>{this.pool.add(e),t[n+1]&&(e.next=t[n+1].id),t[n-1]&&(e.prev=t[n-1].id)})),this.buildFrom(t[0].id,t.length)},lastTerm:function(){let e=this.terms();return e[e.length-1]},hasId:function(e){if(0===this.length||!e)return!1;if(this.start===e)return!0;if(this.cache.terms){let t=this.cache.terms;for(let n=0;n""!==e.text)).length},fullSentence:function(){let e=this.terms(0);for(;e.prev;)e=this.pool.get(e.prev);let t=e.id,n=1;for(;e.next;)e=this.pool.get(e.next),n+=1;return this.buildFrom(t,n)}},oe$1={text:function(e={},t,n){"string"==typeof e&&(e="normal"===e?{whitespace:!0,unicode:!0,lowercase:!0,punctuation:!0,acronyms:!0,abbreviations:!0,implicit:!0,normal:!0}:"clean"===e?{titlecase:!1,lowercase:!0,punctuation:!0,whitespace:!0,unicode:!0,implicit:!0,normal:!0}:"reduced"===e?{punctuation:!1,titlecase:!1,lowercase:!0,whitespace:!0,unicode:!0,implicit:!0,reduced:!0}:"implicit"===e?{punctuation:!0,implicit:!0,whitespace:!0,trim:!0}:"root"===e?{titlecase:!1,lowercase:!0,punctuation:!0,whitespace:!0,unicode:!0,implicit:!0,root:!0}:{});let r=this.terms(),a=!1;r[0]&&null===r[0].prev&&null===r[r.length-1].next&&(a=!0);let i=r.reduce(((i,s,o)=>{if(0===o&&""===s.text&&null!==s.implicit&&!e.implicit)return i;e.last=n&&o===r.length-1;let l=!0,u=!0;return!1===a&&(0===o&&t&&(l=!1),o===r.length-1&&n&&(u=!1)),i+s.textOut(e,l,u)}),"");return!0===a&&n&&(i=i.replace(/ +$/,"")),!0===e.trim&&(i=i.trim()),i}},se$1={trim:function(){let e=this.terms();if(e.length>0){e[0].pre=e[0].pre.replace(/^\s+/,"");let t=e[e.length-1];t.post=t.post.replace(/\s+$/,"")}return this}},le$1={};const ue$1=/[.?!]\s*$/,ce$1=function(e,t){t[0].pre=e[0].pre;let n=e[e.length-1],r=t[t.length-1];r.post=function(e,t){return ue$1.test(t)?t+e.match(/\s*$/):e}(n.post,r.post),n.post="",""===n.post&&(n.post+=" ")},he$1=/ /,de$1=function(e,t,n){let r=e.terms(),a=t.terms();ce$1(r,a),function(e,t,n){let r=e[e.length-1],a=t[t.length-1],i=r.next;r.next=t[0].id,a.next=i,i&&(n.get(i).prev=a.id);let s=e[0].id;s&&(t[0].prev=s)}(r,a,e.pool);let i=[e],s=e.start,o=[n];return o=o.concat(n.parents()),o.forEach((e=>{let t=e.list.filter((e=>e.hasId(s)));i=i.concat(t)})),i=function(e){return e.filter(((t,n)=>e.indexOf(t)===n))}(i),i.forEach((e=>{e.length+=t.length})),e.cache={},e},ge$1=function(e,t,n){const r=e.start;let a=t.terms();!function(e){let t=e[e.length-1];!1===he$1.test(t.post)&&(t.post+=" ")}(a),function(e,t,n){let r=n[n.length-1];r.next=e.start;let a=e.pool,i=a.get(e.start);i.prev&&(a.get(i.prev).next=t.start),n[0].prev=e.terms(0).prev,e.terms(0).prev=r.id}(e,t,a);let i=[e],s=[n];return s=s.concat(n.parents()),s.forEach((e=>{let n=e.list.filter((e=>e.hasId(r)||e.hasId(t.start)));i=i.concat(n)})),i=function(e){return e.filter(((t,n)=>e.indexOf(t)===n))}(i),i.forEach((e=>{e.length+=t.length,e.start===r&&(e.start=t.start),e.cache={}})),e},pe$1=function(e,t){let n=t.pool(),r=e.terms(),a=n.get(r[0].prev)||{},i=n.get(r[r.length-1].next)||{};r[0].implicit&&a.implicit&&(a.set(a.implicit),a.post+=" "),function(e,t,n,r){let a=e.parents();a.push(e),a.forEach((e=>{let a=e.list.find((e=>e.hasId(t)));a&&(a.length-=n,a.start===t&&(a.start=r.id),a.cache={})})),e.list=e.list.filter((e=>!(!e.start||!e.length)))}(t,e.start,e.length,i),a&&(a.next=i.id),i&&(i.prev=a.id)};le$1.append=function(e,t){return de$1(this,e,t),this},le$1.prepend=function(e,t){return ge$1(this,e,t),this},le$1.delete=function(e){return pe$1(this,e),this},le$1.replace=function(e,t){let n=this.length;de$1(this,e,t);let r=this.buildFrom(this.start,this.length);r.length=n,pe$1(r,t)},le$1.splitOn=function(e){let t=this.terms(),n={before:null,match:null,after:null},r=t.findIndex((t=>t.id===e.start));if(-1===r)return n;let a=t.slice(0,r);a.length>0&&(n.before=this.buildFrom(a[0].id,a.length));let i=t.slice(r,r+e.length);i.length>0&&(n.match=this.buildFrom(i[0].id,i.length));let s=t.slice(r+e.length,t.length);return s.length>0&&(n.after=this.buildFrom(s[0].id,s.length,this.pool)),n};var me$2={json:function(e={},t){let n={};return e.text&&(n.text=this.text()),e.normal&&(n.normal=this.text("normal")),e.clean&&(n.clean=this.text("clean")),e.reduced&&(n.reduced=this.text("reduced")),e.implicit&&(n.implicit=this.text("implicit")),e.root&&(n.root=this.text("root")),e.trim&&(n.text&&(n.text=n.text.trim()),n.normal&&(n.normal=n.normal.trim()),n.reduced&&(n.reduced=n.reduced.trim())),e.terms&&(!0===e.terms&&(e.terms={}),n.terms=this.terms().map((n=>n.json(e.terms,t)))),n}},fe$1={lookAhead:function(e){e||(e=".*");let t=this.pool,n=[];const r=function(e){let a=t.get(e);a&&(n.push(a),a.prev&&r(a.next))};let a=this.terms(),i=a[a.length-1];return r(i.next),0===n.length?[]:this.buildFrom(n[0].id,n.length).match(e)},lookBehind:function(e){e||(e=".*");let t=this.pool,n=[];const r=function(e){let a=t.get(e);a&&(n.push(a),a.prev&&r(a.prev))};let a=t.get(this.start);return r(a.prev),0===n.length?[]:this.buildFrom(n[n.length-1].id,n.length).match(e)}},be$1=Object.assign({},ie$1,oe$1,se$1,le$1,me$2,fe$1),ye$1={},ve$1,we$1=function(e,t){if(0===t.length)return!0;for(let e=0;e0)return!0;if(!0===n.anything&&!0===n.negative)return!0}return!1},ke$1={};(ve$1=ke$1).getGreedy=function(e,t){let n=Object.assign({},e.regs[e.r],{start:!1,end:!1}),r=e.t;for(;e.t{let a=0,i=e.t+r+t+a;if(void 0===e.terms[i])return!1;let s=e.terms[i].doesMatch(n,i+e.start_i,e.phrase_length);if(!0===s&&!0===n.greedy)for(let t=1;t{let r=n.every(((t,n)=>{let r=e.t+n;return void 0!==e.terms[r]&&e.terms[r].doesMatch(t,r,e.phrase_length)}));return!0===r&&n.length>t&&(t=n.length),r}))&&t},ve$1.getGroup=function(e,t,n){if(e.groups[e.groupId])return e.groups[e.groupId];const r=e.terms[t].id;return e.groups[e.groupId]={group:String(n),start:r,length:0},e.groups[e.groupId]};const Ae$1=t$1,De=ke$1;var $e$1=function(e,t,n,r){let a={t:0,terms:e,r:0,regs:t,groups:{},start_i:n,phrase_length:r,hasGroup:!1,groupId:null,previousGroup:null};for(;a.r!e.optional)))break;return null}if(!0===e.anything&&!0===e.greedy){let n=De.greedyTo(a,t[a.r+1]);if(null===n||0===n)return null;if(void 0!==e.min&&n-a.te.max){a.t=a.t+e.max;continue}!0===a.hasGroup&&(De.getGroup(a,a.t,e.named).length=n-a.t),a.t=n;continue}if(void 0!==e.choices&&"or"===e.operator){let t=De.doOrBlock(a);if(t){if(!0===e.negative)return null;!0===a.hasGroup&&(De.getGroup(a,a.t,e.named).length+=t),a.t+=t;continue}if(!e.optional)return null}if(void 0!==e.choices&&"and"===e.operator){let t=De.doAndBlock(a);if(t){if(!0===e.negative)return null;!0===a.hasGroup&&(De.getGroup(a,a.t,e.named).length+=t),a.t+=t;continue}if(!e.optional)return null}let n=a.terms[a.t],i=n.doesMatch(e,a.start_i+a.t,a.phrase_length);if(!0===e.anything||!0===i||De.isEndGreedy(e,a)){let i=a.t;if(e.optional&&t[a.r+1]&&e.negative)continue;if(e.optional&&t[a.r+1]){let r=n.doesMatch(t[a.r+1],a.start_i+a.t,a.phrase_length);if(e.negative||r){let e=a.terms[a.t+1];e&&e.doesMatch(t[a.r+1],a.start_i+a.t,a.phrase_length)||(a.r+=1)}}if(a.t+=1,!0===e.end&&a.t!==a.terms.length&&!0!==e.greedy)return null;if(!0===e.greedy){if(a.t=De.getGreedy(a,t[a.r+1]),null===a.t)return null;if(e.min&&e.min>a.t)return null;if(!0===e.end&&a.start_i+a.t!==r)return null}if(!0===a.hasGroup){const t=De.getGroup(a,i,e.named);a.t>1&&e.greedy?t.length+=a.t-i:t.length++}}else{if(e.negative){let t=Object.assign({},e);if(t.negative=!1,!0===a.terms[a.t].doesMatch(t,a.start_i+a.t,a.phrase_length))return null}if(!0!==e.optional){if(a.terms[a.t].isImplicit()&&t[a.r-1]&&a.terms[a.t+1]){if(a.terms[a.t-1]&&a.terms[a.t-1].implicit===t[a.r-1].word)return null;if(a.terms[a.t+1].doesMatch(e,a.start_i+a.t,a.phrase_length)){a.t+=2;continue}}return null}}}return{match:a.terms.slice(0,a.t),groups:a.groups}},Pe$1=function(e,t,n){if(!n||0===n.length)return n;if(t.some((e=>e.end))){let t=e[e.length-1];n=n.filter((({match:e})=>-1!==e.indexOf(t)))}return n};const Ee$1=/(?:^|\s)([\!\[\^]*(?:<[^<]*>)?\/.*?[^\\\/]\/[\?\]\+\*\$~]*)(?:\s|$)/,He=/([\!\[\^]*(?:<[^<]*>)?\([^\)]+[^\\\)]\)[\?\]\+\*\$~]*)(?:\s|$)/,je$1=/ /g,Ne$1=e=>/^[\!\[\^]*(<[^<]*>)?\//.test(e)&&/\/[\?\]\+\*\$~]*$/.test(e),xe$1=function(e){return(e=e.map((e=>e.trim()))).filter((e=>e))};var Fe$1=function(e){let t=e.split(Ee$1),n=[];t.forEach((e=>{Ne$1(e)?n.push(e):n=n.concat(e.split(He))})),n=xe$1(n);let r=[];return n.forEach((e=>{(e=>/^[\!\[\^]*(<[^<]*>)?\(/.test(e)&&/\)[\?\]\+\*\$~]*$/.test(e))(e)||Ne$1(e)?r.push(e):r=r.concat(e.split(je$1))})),r=xe$1(r),r};const Ce$1=/\{([0-9]+,?[0-9]*)\}/,Be=/&&/,Ge=new RegExp(/^<\s*?(\S+)\s*?>/),ze$1=function(e){return e[e.length-1]},Ie=function(e){return e[0]},Oe$1=function(e){return e.substr(1)},Te=function(e){return e.substr(0,e.length-1)},Ve$1=function(e){return e=Oe$1(e),Te(e)},Me$1=function(e){let t={};for(let n=0;n<2;n+=1){if("$"===ze$1(e)&&(t.end=!0,e=Te(e)),"^"===Ie(e)&&(t.start=!0,e=Oe$1(e)),("["===Ie(e)||"]"===ze$1(e))&&(t.named=!0,"["===Ie(e)?t.groupType="]"===ze$1(e)?"single":"start":t.groupType="end",e=(e=e.replace(/^\[/,"")).replace(/\]$/,""),"<"===Ie(e))){const n=Ge.exec(e);n.length>=2&&(t.named=n[1],e=e.replace(n[0],""))}if("+"===ze$1(e)&&(t.greedy=!0,e=Te(e)),"*"!==e&&"*"===ze$1(e)&&"\\*"!==e&&(t.greedy=!0,e=Te(e)),"?"===ze$1(e)&&(t.optional=!0,e=Te(e)),"!"===Ie(e)&&(t.negative=!0,e=Oe$1(e)),"("===Ie(e)&&")"===ze$1(e)){Be.test(e)?(t.choices=e.split(Be),t.operator="and"):(t.choices=e.split("|"),t.operator="or"),t.choices[0]=Oe$1(t.choices[0]);let n=t.choices.length-1;t.choices[n]=Te(t.choices[n]),t.choices=t.choices.map((e=>e.trim())),t.choices=t.choices.filter((e=>e)),t.choices=t.choices.map((e=>e.split(/ /g).map(Me$1))),e=""}if("/"===Ie(e)&&"/"===ze$1(e))return e=Ve$1(e),t.regex=new RegExp(e),t;if("~"===Ie(e)&&"~"===ze$1(e))return e=Ve$1(e),t.soft=!0,t.word=e,t}return!0===Ce$1.test(e)&&(e=e.replace(Ce$1,((e,n)=>{let r=n.split(/,/g);return 1===r.length?(t.min=Number(r[0]),t.max=Number(r[0])):(t.min=Number(r[0]),t.max=Number(r[1]||999)),t.greedy=!0,t.optional=!0,""}))),"#"===Ie(e)?(t.tag=Oe$1(e),t.tag=(n=t.tag).charAt(0).toUpperCase()+n.substr(1),t):"@"===Ie(e)?(t.method=Oe$1(e),t):"."===e?(t.anything=!0,t):"*"===e?(t.anything=!0,t.greedy=!0,t.optional=!0,t):(e&&(e=(e=e.replace("\\*","*")).replace("\\.","."),t.word=e.toLowerCase()),t);var n},Je=Fe$1,Le=Me$1,Se=function(e,t={}){return e.filter((e=>e.groupType)).length>0&&(e=function(e){let t,n=!1,r=-1;for(let a=0;a{if(void 0!==e.choices&&!0===e.choices.every((e=>{if(1!==e.length)return!1;let t=e[0];return void 0!==t.word&&!0!==t.negative&&!0!==t.optional&&!0!==t.method}))){let t={};e.choices.forEach((e=>{t[e[0].word]=!0})),e.fastOr=t,delete e.choices}return e}))}(e)),e};var _e=function(e,t={}){if(null==e||""===e)return[];if("object"==typeof e){if(function(e){return"[object Array]"===Object.prototype.toString.call(e)}(e)){if(0===e.length||!e[0])return[];if("object"==typeof e[0])return e;if("string"==typeof e[0])return function(e){return[{choices:e.map((e=>[{word:e}])),operator:"or"}]}(e)}return e&&"Doc"===e.isA?function(e){if(!e||!e.list||!e.list[0])return[];let t=[];return e.list.forEach((e=>{let n=[];e.terms().forEach((e=>{n.push(e.id)})),t.push(n)})),[{idBlocks:t}]}(e):[]}"number"==typeof e&&(e=String(e));let n=Je(e);return n=n.map((e=>Le(e))),n=Se(n,t),n=function(e,t){return!0===t.fuzzy&&(t.fuzzy=.85),"number"==typeof t.fuzzy&&(e=e.map((e=>(t.fuzzy>0&&e.word&&(e.fuzzy=t.fuzzy),e.choices&&e.choices.forEach((e=>{e.forEach((e=>{e.fuzzy=t.fuzzy}))})),e)))),e}(n,t),n};const Ke=we$1,qe=$e$1,We=Pe$1,Re=_e,Ue=function(e,t){let n=[],r=t[0].idBlocks;for(let t=0;t{0!==r.length&&r.every(((n,r)=>e[t+r].id===n))&&(n.push({match:e.slice(t,t+r.length)}),t+=r.length-1)}));return n};var Qe=function(e,t,n=!1){if("string"==typeof t&&(t=Re(t)),!0===Ke(e,t))return[];const r=t.filter((e=>!0!==e.optional&&!0!==e.negative)).length;let a=e.terms(),i=[];if(t[0].idBlocks){let e=Ue(a,t);if(e&&e.length>0)return We(a,t,e)}if(!0===t[0].start){let e=qe(a,t,0,a.length);return e&&e.match&&e.match.length>0&&(e.match=e.match.filter((e=>e)),i.push(e)),We(a,t,i)}for(let e=0;ea.length);e+=1){let r=qe(a.slice(e),t,e,a.length);if(r&&r.match&&r.match.length>0&&(e+=r.match.length-1,r.match=r.match.filter((e=>e)),i.push(r),!0===n))return We(a,t,i)}return We(a,t,i)};const Ze=Qe,Xe=Qe,Ye=function(e,t){let n={};Ze(e,t).forEach((({match:e})=>{e.forEach((e=>{n[e.id]=!0}))}));let r=e.terms(),a=[],i=[];return r.forEach((e=>{!0!==n[e.id]?i.push(e):i.length>0&&(a.push(i),i=[])})),i.length>0&&a.push(i),a};ye$1.match=function(e,t=!1){let n=Xe(this,e,t);return n=n.map((({match:e,groups:t})=>{let n=this.buildFrom(e[0].id,e.length,t);return n.cache.terms=e,n})),n},ye$1.has=function(e){return Xe(this,e,!0).length>0},ye$1.not=function(e){let t=Ye(this,e);return t=t.map((e=>this.buildFrom(e[0].id,e.length))),t},ye$1.canBe=function(e,t){let n=[],r=this.terms(),a=!1;for(let i=0;ie.length>0)).map((e=>this.buildFrom(e[0].id,e.length))),n};const et=be$1,tt=ye$1;class rt{constructor(e,t,n){this.start=e,this.length=t,this.isA="Phrase",Object.defineProperty(this,"pool",{enumerable:!1,writable:!0,value:n}),Object.defineProperty(this,"cache",{enumerable:!1,writable:!0,value:{}}),Object.defineProperty(this,"groups",{enumerable:!1,writable:!0,value:{}})}}rt.prototype.buildFrom=function(e,t,n){let r=new rt(e,t,this.pool);return n&&Object.keys(n).length>0?r.groups=n:r.groups=this.groups,r},Object.assign(rt.prototype,tt),Object.assign(rt.prototype,et);const at={term:"terms"};Object.keys(at).forEach((e=>rt.prototype[e]=rt.prototype[at[e]]));var nt=rt;class it{constructor(e={}){Object.defineProperty(this,"words",{enumerable:!1,value:e})}add(e){return this.words[e.id]=e,this}get(e){return this.words[e]}remove(e){delete this.words[e]}merge(e){return Object.assign(this.words,e.words),this}stats(){return{words:Object.keys(this.words).length}}}it.prototype.clone=function(){let e=Object.keys(this.words).reduce(((e,t)=>{let n=this.words[t].clone();return e[n.id]=n,e}),{});return new it(e)};var ot=it,st=e=>{e.forEach(((t,n)=>{n>0&&(t.prev=e[n-1].id),e[n+1]&&(t.next=e[n+1].id)}))};const lt=/(\S.+?[.!?\u203D\u2E18\u203C\u2047-\u2049])(?=\s+|$)/g,ut=/\S/,ct=/[ .][A-Z]\.? *$/i,ht=/(?:\u2026|\.{2,}) *$/,dt=/((?:\r?\n|\r)+)/,gt=/[a-z0-9\u00C0-\u00FF\u00a9\u00ae\u2000-\u3300\ud000-\udfff]/i,pt=/^\s+/,mt=function(e,t,n,r){if(r.hasLetter=function(e,t){return t||gt.test(e)}(t,r.hasLetter),!r.hasLetter)return!1;if(function(e,t){return-1!==t.indexOf(".")&&ct.test(e)}(e,t))return!1;if(function(e,t){return-1!==t.indexOf(".")&&ht.test(e)}(e,t))return!1;let a=e.replace(/[.!?\u203D\u2E18\u203C\u2047-\u2049] *$/,"").split(" "),i=a[a.length-1].toLowerCase();return!n.hasOwnProperty(i)};var ft=function(e,t){let n=t.cache.abbreviations;e=e||"";let r=[],a=[];if(!(e=String(e))||"string"!=typeof e||!1===ut.test(e))return r;let i=function(e){let t=[],n=e.split(dt);for(let e=0;e0&&(r.push(t),s=a[e+1]||"",o.hasLetter=!1),a[e]=""}if(0===r.length)return[e];for(let e=1;e(e[t]=!0,e)),{});const At=function(e){return!0!==/^(re|un|micro|macro|trans|bi|mono|over)-?[^aeiou]./.test(e)&&(!0!==/^([a-z\u00C0-\u00FF/]+)(-|–|—)(like|ish|less|able)/i.test(e)&&(!0===/^([a-z\u00C0-\u00FF`"'/]+)(-|–|—)([a-z0-9\u00C0-\u00FF].*)/i.test(e)||!0===/^([0-9]{1,4})(-|–|—)([a-z\u00C0-\u00FF`"'/-]+$)/i.test(e)))},Dt=function(e){let t=[];const n=e.split(/[-–—]/);let r="-",a=e.match(/[-–—]/);a&&a[0]&&(r=a);for(let e=0;e0?(t[t.length-1]+=a,t.push(r)):t.push(a+r),a=""):a+=r}return a&&(0===t.length&&(t[0]=""),t[t.length-1]+=a),t=function(e){for(let t=1;te)),t};var xt=function(e="",t,n){let r=null;return"string"!=typeof e&&("number"==typeof e?e=String(e):function(e){return"[object Array]"===Object.prototype.toString.call(e)}(e)&&(r=e)),r=r||jt(e,t),r=r.map((e=>Nt(e))),n=n||new Et,r.map((e=>{e=e.map((e=>{let t=new $t(e);return n.add(t),t})),Ht(e);let t=new Pt(e[0].id,e.length,n);return t.cache.terms=e,t}))};const Ft=ne$1,Ct=nt,Bt=ot,Gt=st;var zt=function(e,t){let n=new Bt;return e.map(((e,r)=>{let a=e.terms.map(((a,i)=>{let s=new Ft(a.text);return s.pre=void 0!==a.pre?a.pre:"",void 0===a.post&&(a.post=" ",i>=e.terms.length-1&&(a.post=". ",r>=e.terms.length-1&&(a.post="."))),s.post=void 0!==a.post?a.post:" ",a.tags&&a.tags.forEach((e=>s.tag(e,"",t))),n.add(s),s}));return Gt(a),new Ct(a[0].id,a.length,n)}))};const It=["Person","Place","Organization"],Ot=["Noun","Verb","Adjective","Adverb","Value","QuestionWord"],Tt={Noun:"blue",Verb:"green",Negative:"green",Date:"red",Value:"red",Adjective:"magenta",Preposition:"cyan",Conjunction:"cyan",Determiner:"cyan",Adverb:"cyan"},Vt=function(e){return Object.keys(e).forEach((t=>{e[t].color?e[t].color=e[t].color:Tt[t]?e[t].color=Tt[t]:e[t].isA.some((n=>!!Tt[n]&&(e[t].color=Tt[n],!0)))})),e},Mt=function(e){return Object.keys(e).forEach((t=>{let n=e[t],r=n.isA.length;for(let t=0;tn.indexOf(e)===t))}(n.isA)})),e},Jt=function(e){let t=Object.keys(e);return t.forEach((n=>{let r=e[n];r.notA=r.notA||[],r.isA.forEach((t=>{if(e[t]&&e[t].notA){let n="string"==typeof e[t].notA?[e[t].isA]:e[t].notA||[];r.notA=r.notA.concat(n)}}));for(let a=0;an.indexOf(e)===t))}(r.notA)})),e},Lt=function(e){let t=Object.keys(e);return t.forEach((n=>{let r=e[n];r.lineage=[];for(let a=0;a{let n=e[t];n.isA=n.isA||[],"string"==typeof n.isA&&(n.isA=[n.isA]),n.notA=n.notA||[],"string"==typeof n.notA&&(n.notA=[n.notA])})),e}(e),e=Mt(e),e=Jt(e),e=Vt(e),Lt(e)};const _t={Noun:{notA:["Verb","Adjective","Adverb"]},Singular:{isA:"Noun",notA:"Plural"},ProperNoun:{isA:"Noun"},Person:{isA:["ProperNoun","Singular"],notA:["Place","Organization","Date"]},FirstName:{isA:"Person"},MaleName:{isA:"FirstName",notA:["FemaleName","LastName"]},FemaleName:{isA:"FirstName",notA:["MaleName","LastName"]},LastName:{isA:"Person",notA:["FirstName"]},NickName:{isA:"Person",notA:["FirstName","LastName"]},Honorific:{isA:"Noun",notA:["FirstName","LastName","Value"]},Place:{isA:"Singular",notA:["Person","Organization"]},Country:{isA:["Place","ProperNoun"],notA:["City"]},City:{isA:["Place","ProperNoun"],notA:["Country"]},Region:{isA:["Place","ProperNoun"]},Address:{isA:"Place"},Organization:{isA:["Singular","ProperNoun"],notA:["Person","Place"]},SportsTeam:{isA:"Organization"},School:{isA:"Organization"},Company:{isA:"Organization"},Plural:{isA:"Noun",notA:["Singular"]},Uncountable:{isA:"Noun"},Pronoun:{isA:"Noun",notA:It},Actor:{isA:"Noun",notA:It},Activity:{isA:"Noun",notA:["Person","Place"]},Unit:{isA:"Noun",notA:It},Demonym:{isA:["Noun","ProperNoun"],notA:It},Possessive:{isA:"Noun"}},Kt={Verb:{notA:["Noun","Adjective","Adverb","Value","Expression"]},PresentTense:{isA:"Verb",notA:["PastTense","FutureTense"]},Infinitive:{isA:"PresentTense",notA:["PastTense","Gerund"]},Imperative:{isA:"Infinitive"},Gerund:{isA:"PresentTense",notA:["PastTense","Copula","FutureTense"]},PastTense:{isA:"Verb",notA:["FutureTense"]},FutureTense:{isA:"Verb"},Copula:{isA:"Verb"},Modal:{isA:"Verb",notA:["Infinitive"]},PerfectTense:{isA:"Verb",notA:"Gerund"},Pluperfect:{isA:"Verb"},Participle:{isA:"PastTense"},PhrasalVerb:{isA:"Verb"},Particle:{isA:"PhrasalVerb"},Auxiliary:{notA:["Noun","Adjective","Value"]}},qt={Value:{notA:["Verb","Adjective","Adverb"]},Ordinal:{isA:"Value",notA:["Cardinal"]},Cardinal:{isA:"Value",notA:["Ordinal"]},Fraction:{isA:"Value",notA:["Noun"]},RomanNumeral:{isA:"Cardinal",notA:["Ordinal","TextValue"]},TextValue:{isA:"Value",notA:["NumericValue"]},NumericValue:{isA:"Value",notA:["TextValue"]},Money:{isA:"Cardinal"},Percent:{isA:"Value"}},Wt={Adjective:{notA:["Noun","Verb","Adverb","Value"]},Comparable:{isA:["Adjective"]},Comparative:{isA:["Adjective"]},Superlative:{isA:["Adjective"],notA:["Comparative"]},NumberRange:{},Adverb:{notA:["Noun","Verb","Adjective","Value"]},Date:{notA:["Verb","Adverb","Preposition","Adjective"]},Month:{isA:["Date","Singular"],notA:["Year","WeekDay","Time"]},WeekDay:{isA:["Date","Noun"]},Timezone:{isA:["Date","Noun"],notA:["Adjective","ProperNoun"]},Time:{isA:["Date"],notA:["AtMention"]},Determiner:{notA:Ot},Conjunction:{notA:Ot},Preposition:{notA:Ot},QuestionWord:{notA:["Determiner"]},Currency:{isA:["Noun"]},Expression:{notA:["Noun","Adjective","Verb","Adverb"]},Abbreviation:{},Url:{notA:["HashTag","PhoneNumber","Verb","Adjective","Value","AtMention","Email"]},PhoneNumber:{notA:["HashTag","Verb","Adjective","Value","AtMention","Email"]},HashTag:{},AtMention:{isA:["Noun"],notA:["HashTag","Verb","Adjective","Value","Email"]},Emoji:{notA:["HashTag","Verb","Adjective","Value","AtMention"]},Emoticon:{notA:["HashTag","Verb","Adjective","Value","AtMention"]},Email:{notA:["HashTag","Verb","Adjective","Value","AtMention"]},Acronym:{notA:["Plural","RomanNumeral"]},Negative:{notA:["Noun","Adjective","Value"]},Condition:{notA:["Verb","Adjective","Noun","Value"]}},Rt=St,Ut=function(e,t){Object.keys(e).forEach((n=>{t[n]=e[n]}))};var Qt=(()=>{let e={};return Ut(_t,e),Ut(Kt,e),Ut(qt,e),Ut(Wt,e),e=Rt(e),e})();const Zt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",Xt=Zt.split("").reduce((function(e,t,n){return e[t]=n,e}),{});var Yt=function(e){if(void 0!==Xt[e])return Xt[e];let t=0,n=1,r=36,a=1;for(;n=0;n--,a*=36){let r=e.charCodeAt(n)-48;r>10&&(r-=7),t+=r*a}return t};const er=function(e,t,n){const r=Yt(t);return r{let i=e.nodes[r];"!"===i[0]&&(t.push(a),i=i.slice(1));const s=i.split(/([A-Z0-9,]+)/g);for(let i=0;i{const n=t.split("¦");return e[n[0]]=n[1],e}),{}),n={};return Object.keys(t).forEach((function(e){const r=tr(t[e]);"true"===e&&(e=!0);for(let t=0;t{e[t]=["Abbreviation","Unit"]},Cardinal:(e,t)=>{e[t]=["TextValue","Cardinal"]},TextOrdinal:(e,t)=>{e[t]=["Ordinal","TextValue"],e[t+"s"]=["TextValue","Fraction"]},Singular:(e,t,n)=>{e[t]="Singular";let r=n.transforms.toPlural(t,n);e[r]=e[r]||"Plural"},Infinitive:(e,t,n)=>{e[t]="Infinitive";let r=n.transforms.conjugate(t,n),a=Object.keys(r);for(let t=0;t{e[t]="Comparable";let r=n.transforms.adjectives(t),a=Object.keys(r);for(let t=0;t{e[t]=["PhrasalVerb","Infinitive"];let r=t.split(" "),a=n.transforms.conjugate(r[0],n),i=Object.keys(a);for(let t=0;t{e[t]="Demonym";let r=n.transforms.toPlural(t,n);e[r]=e[r]||["Demonym","Plural"]}},or=function(e,t,n){Object.keys(e).forEach((r=>{let a=e[r];"Abbreviation"!==a&&"Unit"!==a||(n.cache.abbreviations[r]=!0);let i=r.split(" ");i.length>1&&(n.hasCompound[i[0]]=!0),void 0===ir[a]?void 0!==t[r]?("string"==typeof t[r]&&(t[r]=[t[r]]),"string"==typeof a?t[r].push(a):t[r]=t[r].concat(a)):t[r]=a:ir[a](t,r,n)}))};var sr={buildOut:function(e){let t=Object.assign({},nr);return Object.keys(rr).forEach((n=>{let r=ar(rr[n]);Object.keys(r).forEach((e=>{r[e]=n})),or(r,t,e)})),t},addWords:or},lr=function(e){let t=e.irregulars.nouns,n=Object.keys(t);for(let r=0;r{e.words[i[t]]=e.words[i[t]]||t,"Participle"===e.words[i[t]]&&(e.words[i[t]]=t)}))}};const ur={g:"Gerund",prt:"Participle",perf:"PerfectTense",pst:"PastTense",fut:"FuturePerfect",pres:"PresentTense",pluperf:"Pluperfect",a:"Actor"};let cr={act:{a:"_or"},ache:{pst:"ached",g:"aching"},age:{g:"ageing",pst:"aged",pres:"ages"},aim:{a:"_er",g:"_ing",pst:"_ed"},arise:{prt:"_n",pst:"arose"},babysit:{a:"_ter",pst:"babysat"},ban:{a:"",g:"_ning",pst:"_ned"},be:{a:"",g:"am",prt:"been",pst:"was",pres:"is"},beat:{a:"_er",g:"_ing",prt:"_en"},become:{prt:"_"},begin:{g:"_ning",prt:"begun",pst:"began"},being:{g:"are",pst:"were",pres:"are"},bend:{prt:"bent"},bet:{a:"_ter",prt:"_"},bind:{pst:"bound"},bite:{g:"biting",prt:"bitten",pst:"bit"},bleed:{pst:"bled",prt:"bled"},blow:{prt:"_n",pst:"blew"},boil:{a:"_er"},brake:{prt:"broken"},break:{pst:"broke"},breed:{pst:"bred"},bring:{pst:"brought",prt:"brought"},broadcast:{pst:"_"},budget:{pst:"_ed"},build:{pst:"built",prt:"built"},burn:{prt:"_ed"},burst:{prt:"_"},buy:{pst:"bought",prt:"bought"},can:{a:"",fut:"_",g:"",pst:"could",perf:"could",pluperf:"could",pres:"_"},catch:{pst:"caught"},choose:{g:"choosing",prt:"chosen",pst:"chose"},cling:{prt:"clung"},come:{prt:"_",pst:"came",g:"coming"},compete:{a:"competitor",g:"competing",pst:"_d"},cost:{pst:"_"},creep:{prt:"crept"},cut:{prt:"_"},deal:{pst:"_t",prt:"_t"},develop:{a:"_er",g:"_ing",pst:"_ed"},die:{g:"dying",pst:"_d"},dig:{g:"_ging",pst:"dug",prt:"dug"},dive:{prt:"_d"},do:{pst:"did",pres:"_es"},draw:{prt:"_n",pst:"drew"},dream:{prt:"_t"},drink:{prt:"drunk",pst:"drank"},drive:{g:"driving",prt:"_n",pst:"drove"},drop:{g:"_ping",pst:"_ped"},eat:{a:"_er",g:"_ing",prt:"_en",pst:"ate"},edit:{pst:"_ed",g:"_ing"},egg:{pst:"_ed"},fall:{prt:"_en",pst:"fell"},feed:{prt:"fed",pst:"fed"},feel:{a:"_er",pst:"felt"},fight:{pst:"fought",prt:"fought"},find:{pst:"found"},flee:{g:"_ing",prt:"fled"},fling:{prt:"flung"},fly:{prt:"flown",pst:"flew"},forbid:{pst:"forbade"},forget:{g:"_ing",prt:"forgotten",pst:"forgot"},forgive:{g:"forgiving",prt:"_n",pst:"forgave"},free:{a:"",g:"_ing"},freeze:{g:"freezing",prt:"frozen",pst:"froze"},get:{pst:"got",prt:"gotten"},give:{g:"giving",prt:"_n",pst:"gave"},go:{prt:"_ne",pst:"went",pres:"goes"},grow:{prt:"_n"},guide:{pst:"_d"},hang:{pst:"hung",prt:"hung"},have:{g:"having",pst:"had",prt:"had",pres:"has"},hear:{pst:"_d",prt:"_d"},hide:{prt:"hidden",pst:"hid"},hit:{prt:"_"},hold:{pst:"held",prt:"held"},hurt:{pst:"_",prt:"_"},ice:{g:"icing",pst:"_d"},imply:{pst:"implied",pres:"implies"},is:{a:"",g:"being",pst:"was",pres:"_"},keep:{prt:"kept"},kneel:{prt:"knelt"},know:{prt:"_n"},lay:{pst:"laid",prt:"laid"},lead:{pst:"led",prt:"led"},leap:{prt:"_t"},leave:{pst:"left",prt:"left"},lend:{prt:"lent"},lie:{g:"lying",pst:"lay"},light:{pst:"lit",prt:"lit"},log:{g:"_ging",pst:"_ged"},loose:{prt:"lost"},lose:{g:"losing",pst:"lost"},make:{pst:"made",prt:"made"},mean:{pst:"_t",prt:"_t"},meet:{a:"_er",g:"_ing",pst:"met",prt:"met"},miss:{pres:"_"},name:{g:"naming"},patrol:{g:"_ling",pst:"_led"},pay:{pst:"paid",prt:"paid"},prove:{prt:"_n"},puke:{g:"puking"},put:{prt:"_"},quit:{prt:"_"},read:{pst:"_",prt:"_"},ride:{prt:"ridden"},reside:{pst:"_d"},ring:{pst:"rang",prt:"rung"},rise:{fut:"will have _n",g:"rising",prt:"_n",pst:"rose",pluperf:"had _n"},rub:{g:"_bing",pst:"_bed"},run:{g:"_ning",prt:"_",pst:"ran"},say:{pst:"said",prt:"said",pres:"_s"},seat:{pst:"sat",prt:"sat"},see:{g:"_ing",prt:"_n",pst:"saw"},seek:{prt:"sought"},sell:{pst:"sold",prt:"sold"},send:{prt:"sent"},set:{prt:"_"},sew:{prt:"_n"},shake:{prt:"_n"},shave:{prt:"_d"},shed:{g:"_ding",pst:"_",pres:"_s"},shine:{pst:"shone",prt:"shone"},shoot:{pst:"shot",prt:"shot"},show:{pst:"_ed"},shut:{prt:"_"},sing:{prt:"sung",pst:"sang"},sink:{pst:"sank",pluperf:"had sunk"},sit:{pst:"sat"},ski:{pst:"_ied"},slay:{prt:"slain"},sleep:{prt:"slept"},slide:{pst:"slid",prt:"slid"},smash:{pres:"_es"},sneak:{prt:"snuck"},speak:{fut:"will have spoken",prt:"spoken",pst:"spoke",perf:"have spoken",pluperf:"had spoken"},speed:{prt:"sped"},spend:{prt:"spent"},spill:{prt:"_ed",pst:"spilt"},spin:{g:"_ning",pst:"spun",prt:"spun"},spit:{prt:"spat"},split:{prt:"_"},spread:{pst:"_"},spring:{prt:"sprung"},stand:{pst:"stood"},steal:{a:"_er",pst:"stole"},stick:{pst:"stuck"},sting:{pst:"stung"},stink:{pst:"stunk",prt:"stunk"},stream:{a:"_er"},strew:{prt:"_n"},strike:{g:"striking",pst:"struck"},suit:{a:"_er",g:"_ing",pst:"_ed"},sware:{prt:"sworn"},swear:{pst:"swore"},sweep:{prt:"swept"},swim:{g:"_ming",pst:"swam"},swing:{pst:"swung"},take:{fut:"will have _n",pst:"took",perf:"have _n",pluperf:"had _n"},teach:{pst:"taught",pres:"_es"},tear:{pst:"tore"},tell:{pst:"told"},think:{pst:"thought"},thrive:{prt:"_d"},tie:{g:"tying",pst:"_d"},undergo:{prt:"_ne"},understand:{pst:"understood"},upset:{prt:"_"},wait:{a:"_er",g:"_ing",pst:"_ed"},wake:{pst:"woke"},wear:{pst:"wore"},weave:{prt:"woven"},wed:{pst:"wed"},weep:{prt:"wept"},win:{g:"_ning",pst:"won"},wind:{prt:"wound"},withdraw:{pst:"withdrew"},wring:{prt:"wrung"},write:{g:"writing",prt:"written",pst:"wrote"}},hr=Object.keys(cr);for(let e=0;e{let r=cr[t][e];r=r.replace("_",t),n[ur[e]]=r})),cr[t]=n}var dr=cr;const gr={b:[{reg:/([^aeiou][aeiou])b$/i,repl:{pr:"$1bs",pa:"$1bbed",gr:"$1bbing"}}],d:[{reg:/(end)$/i,repl:{pr:"$1s",pa:"ent",gr:"$1ing",ar:"$1er"}},{reg:/(eed)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing",ar:"$1er"}},{reg:/(ed)$/i,repl:{pr:"$1s",pa:"$1ded",ar:"$1der",gr:"$1ding"}},{reg:/([^aeiou][ou])d$/i,repl:{pr:"$1ds",pa:"$1dded",gr:"$1dding"}}],e:[{reg:/(eave)$/i,repl:{pr:"$1s",pa:"$1d",gr:"eaving",ar:"$1r"}},{reg:/(ide)$/i,repl:{pr:"$1s",pa:"ode",gr:"iding",ar:"ider"}},{reg:/(t|sh?)(ake)$/i,repl:{pr:"$1$2s",pa:"$1ook",gr:"$1aking",ar:"$1$2r"}},{reg:/w(ake)$/i,repl:{pr:"w$1s",pa:"woke",gr:"waking",ar:"w$1r"}},{reg:/m(ake)$/i,repl:{pr:"m$1s",pa:"made",gr:"making",ar:"m$1r"}},{reg:/(a[tg]|i[zn]|ur|nc|gl|is)e$/i,repl:{pr:"$1es",pa:"$1ed",gr:"$1ing"}},{reg:/([bd]l)e$/i,repl:{pr:"$1es",pa:"$1ed",gr:"$1ing"}},{reg:/(om)e$/i,repl:{pr:"$1es",pa:"ame",gr:"$1ing"}}],g:[{reg:/([^aeiou][aou])g$/i,repl:{pr:"$1gs",pa:"$1gged",gr:"$1gging"}}],h:[{reg:/(..)([cs]h)$/i,repl:{pr:"$1$2es",pa:"$1$2ed",gr:"$1$2ing"}}],k:[{reg:/(ink)$/i,repl:{pr:"$1s",pa:"unk",gr:"$1ing",ar:"$1er"}}],m:[{reg:/([^aeiou][aeiou])m$/i,repl:{pr:"$1ms",pa:"$1mmed",gr:"$1mming"}}],n:[{reg:/(en)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}}],p:[{reg:/(e)(ep)$/i,repl:{pr:"$1$2s",pa:"$1pt",gr:"$1$2ing",ar:"$1$2er"}},{reg:/([^aeiou][aeiou])p$/i,repl:{pr:"$1ps",pa:"$1pped",gr:"$1pping"}},{reg:/([aeiu])p$/i,repl:{pr:"$1ps",pa:"$1p",gr:"$1pping"}}],r:[{reg:/([td]er)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}},{reg:/(er)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}}],s:[{reg:/(ish|tch|ess)$/i,repl:{pr:"$1es",pa:"$1ed",gr:"$1ing"}}],t:[{reg:/(ion|end|e[nc]t)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}},{reg:/(.eat)$/i,repl:{pr:"$1s",pa:"$1ed",gr:"$1ing"}},{reg:/([aeiu])t$/i,repl:{pr:"$1ts",pa:"$1t",gr:"$1tting"}},{reg:/([^aeiou][aeiou])t$/i,repl:{pr:"$1ts",pa:"$1tted",gr:"$1tting"}}],w:[{reg:/(.llow)$/i,repl:{pr:"$1s",pa:"$1ed"}},{reg:/(..)(ow)$/i,repl:{pr:"$1$2s",pa:"$1ew",gr:"$1$2ing",prt:"$1$2n"}}],y:[{reg:/(i|f|rr)y$/i,repl:{pr:"$1ies",pa:"$1ied",gr:"$1ying"}}],z:[{reg:/([aeiou]zz)$/i,repl:{pr:"$1es",pa:"$1ed",gr:"$1ing"}}]},pr={pr:"PresentTense",pa:"PastTense",gr:"Gerund",prt:"Participle",ar:"Actor"},mr=function(e,t){let n={},r=Object.keys(t.repl);for(let a=0;a"e"===e.charAt(e.length-1)?e.replace(/e$/,"ing"):e+"ing",PresentTense:e=>"s"===e.charAt(e.length-1)?e+"es":!0===fr.test(e)?e.slice(0,-1)+"ies":e+"s",PastTense:e=>"e"===e.charAt(e.length-1)?e+"d":"ed"===e.substr(-2)?e:!0===fr.test(e)?e.slice(0,-1)+"ied":e+"ed"};var vr=function(e="",t){let n={};return t&&t.irregulars&&!0===t.irregulars.verbs.hasOwnProperty(e)&&(n=Object.assign({},t.irregulars.verbs[e])),n=Object.assign({},br(e),n),void 0===n.Gerund&&(n.Gerund=yr.Gerund(e)),void 0===n.PastTense&&(n.PastTense=yr.PastTense(e)),void 0===n.PresentTense&&(n.PresentTense=yr.PresentTense(e)),n};const wr=[/ght$/,/nge$/,/ough$/,/ain$/,/uel$/,/[au]ll$/,/ow$/,/oud$/,/...p$/],kr=[/ary$/],Ar={nice:"nicest",late:"latest",hard:"hardest",inner:"innermost",outer:"outermost",far:"furthest",worse:"worst",bad:"worst",good:"best",big:"biggest",large:"largest"},Dr=[{reg:/y$/i,repl:"iest"},{reg:/([aeiou])t$/i,repl:"$1ttest"},{reg:/([aeou])de$/i,repl:"$1dest"},{reg:/nge$/i,repl:"ngest"},{reg:/([aeiou])te$/i,repl:"$1test"}],$r=[/ght$/,/nge$/,/ough$/,/ain$/,/uel$/,/[au]ll$/,/ow$/,/old$/,/oud$/,/e[ae]p$/],Pr=[/ary$/,/ous$/],Er={grey:"greyer",gray:"grayer",green:"greener",yellow:"yellower",red:"redder",good:"better",well:"better",bad:"worse",sad:"sadder",big:"bigger"},Hr=[{reg:/y$/i,repl:"ier"},{reg:/([aeiou])t$/i,repl:"$1tter"},{reg:/([aeou])de$/i,repl:"$1der"},{reg:/nge$/i,repl:"nger"}],jr={toSuperlative:function(e){if(Ar.hasOwnProperty(e))return Ar[e];for(let t=0;t(e[a[t]]=t,e)),{}));var a;if(r.hasOwnProperty(e))return r[e];for(let t=0;t(Ir[t].forEach((n=>e[n]=t)),e)),{});const Or=zr,Tr=Ir,Vr=Qt,Mr=sr,Jr=lr,Lr=St,Sr={nouns:{addendum:"addenda",alga:"algae",alumna:"alumnae",alumnus:"alumni",analysis:"analyses",antenna:"antennae",appendix:"appendices",avocado:"avocados",axis:"axes",bacillus:"bacilli",barracks:"barracks",beau:"beaux",bus:"buses",cactus:"cacti",chateau:"chateaux",child:"children",circus:"circuses",clothes:"clothes",corpus:"corpora",criterion:"criteria",curriculum:"curricula",database:"databases",deer:"deer",diagnosis:"diagnoses",echo:"echoes",embargo:"embargoes",epoch:"epochs",foot:"feet",formula:"formulae",fungus:"fungi",genus:"genera",goose:"geese",halo:"halos",hippopotamus:"hippopotami",index:"indices",larva:"larvae",leaf:"leaves",libretto:"libretti",loaf:"loaves",man:"men",matrix:"matrices",memorandum:"memoranda",modulus:"moduli",mosquito:"mosquitoes",mouse:"mice",nebula:"nebulae",nucleus:"nuclei",octopus:"octopi",opus:"opera",ovum:"ova",ox:"oxen",parenthesis:"parentheses",person:"people",phenomenon:"phenomena",prognosis:"prognoses",quiz:"quizzes",radius:"radii",referendum:"referenda",rodeo:"rodeos",sex:"sexes",shoe:"shoes",sombrero:"sombreros",stimulus:"stimuli",stomach:"stomachs",syllabus:"syllabi",synopsis:"synopses",tableau:"tableaux",thesis:"theses",thief:"thieves",tooth:"teeth",tornado:"tornados",tuxedo:"tuxedos",vertebra:"vertebrae"},verbs:dr},_r={conjugate:vr,adjectives:Nr,toPlural:Cr,toSingular:Gr,toInfinitive:function(e,t,n){if(!e)return"";if(!0===t.words.hasOwnProperty(e)){let n=t.irregulars.verbs,r=Object.keys(n);for(let t=0;t{let r=e[n];n=n.toLowerCase().trim(),t[n]=r})),Mr.addWords(t,this.words,this)}addConjugations(e){return Object.assign(this.irregulars.verbs,e),this}addPlurals(e){return Object.assign(this.irregulars.nouns,e),this}addTags(e){return e=Object.assign({},e),this.tags=Object.assign(this.tags,e),this.tags=Lr(this.tags),this}postProcess(e){return this.taggers.push(e),this}stats(){return{words:Object.keys(this.words).length,plurals:Object.keys(this.irregulars.nouns).length,conjugations:Object.keys(this.irregulars.verbs).length,compounds:Object.keys(this.hasCompound).length,postProcessors:this.taggers.length}}}const Wr=function(e){return JSON.parse(JSON.stringify(e))};qr.prototype.clone=function(){let e=new qr;return e.words=Object.assign({},this.words),e.hasCompound=Object.assign({},this.hasCompound),e.irregulars=Wr(this.irregulars),e.tags=Wr(this.tags),e.transforms=this.transforms,e.taggers=this.taggers,e};var Rr=qr,Ur={};!function(e){e.all=function(){return this.parents()[0]||this},e.parent=function(){return this.from?this.from:this},e.parents=function(e){let t=[];const n=function(e){e.from&&(t.push(e.from),n(e.from))};return n(this),t=t.reverse(),"number"==typeof e?t[e]:t},e.clone=function(e){let t=this.list.map((t=>t.clone(e)));return this.buildFrom(t)},e.wordCount=function(){return this.list.reduce(((e,t)=>e+t.wordCount()),0)},e.wordcount=e.wordCount}(Ur);var Qr={};!function(e){e.first=function(e){return void 0===e?this.get(0):this.slice(0,e)},e.last=function(e){if(void 0===e)return this.get(this.list.length-1);let t=this.list.length;return this.slice(t-e,t)},e.slice=function(e,t){let n=this.list.slice(e,t);return this.buildFrom(n)},e.eq=function(e){let t=this.list[e];return void 0===t?this.buildFrom([]):this.buildFrom([t])},e.get=e.eq,e.firstTerms=function(){return this.match("^.")},e.firstTerm=e.firstTerms,e.lastTerms=function(){return this.match(".$")},e.lastTerm=e.lastTerms,e.termList=function(e){let t=[];for(let n=0;nr.groups[e]));for(let e=0;ea.groups[e].group===t)),i.forEach((e=>{n.push(a.buildFrom(a.groups[e].start,a.groups[e].length))}))}return e.buildFrom(n)}(this,e)||this.buildFrom([]))},e.group=e.groups,e.sentences=function(e){let t=[];return this.list.forEach((e=>{t.push(e.fullSentence())})),"number"==typeof e?this.buildFrom([t[e]]):this.buildFrom(t)},e.sentence=e.sentences}(Qr);var Zr={},Xr=function(e,t){if(e._cache&&!0===e._cache.set){let{words:n,tags:r}=function(e){let t=[],n=[];return e.forEach((e=>{!0!==e.optional&&!0!==e.negative&&(void 0!==e.tag&&t.push(e.tag),void 0!==e.word&&n.push(e.word))})),{tags:t,words:n}}(t);for(let t=0;te.concat(t.match(a))),[]);return void 0!==r.group&&null!==r.group&&""!==r.group?this.buildFrom(i).groups(r.group):this.buildFrom(i)},e.not=function(e,r={}){let a=t(e,r);if(0===a.length||!1===n(this,a))return this;let i=this.list.reduce(((e,t)=>e.concat(t.not(a))),[]);return this.buildFrom(i)},e.matchOne=function(e,r={}){let a=t(e,r);if(!1===n(this,a))return this.buildFrom([]);for(let e=0;e!0===e.has(a)));return this.buildFrom(i)},e.ifNo=function(e,n={}){let r=t(e,n),a=this.list.filter((e=>!1===e.has(r)));return this.buildFrom(a)},e.has=function(e,r={}){let a=t(e,r);return!1!==n(this,a)&&this.list.some((e=>!0===e.has(a)))},e.lookAhead=function(e,n={}){e||(e=".*");let r=t(e,n),a=[];return this.list.forEach((e=>{a=a.concat(e.lookAhead(r))})),a=a.filter((e=>e)),this.buildFrom(a)},e.lookAfter=e.lookAhead,e.lookBehind=function(e,n={}){e||(e=".*");let r=t(e,n),a=[];return this.list.forEach((e=>{a=a.concat(e.lookBehind(r))})),a=a.filter((e=>e)),this.buildFrom(a)},e.lookBefore=e.lookBehind,e.before=function(e,n={}){let r=t(e,n),a=this.if(r).list.map((e=>{let t=e.terms().map((e=>e.id)),n=e.match(r)[0],a=t.indexOf(n.start);return 0===a||-1===a?null:e.buildFrom(e.start,a)}));return a=a.filter((e=>null!==e)),this.buildFrom(a)},e.after=function(e,n={}){let r=t(e,n),a=this.if(r).list.map((e=>{let t=e.terms(),n=t.map((e=>e.id)),a=e.match(r)[0],i=n.indexOf(a.start);if(-1===i||!t[i+a.length])return null;let s=t[i+a.length].id,o=e.length-i-a.length;return e.buildFrom(s,o)}));return a=a.filter((e=>null!==e)),this.buildFrom(a)},e.hasAfter=function(e,t={}){return this.filter((n=>n.lookAfter(e,t).found))},e.hasBefore=function(e,t={}){return this.filter((n=>n.lookBefore(e,t).found))}}(Zr);var Yr={};const ea=function(e,t,n,r){let a=[];"string"==typeof e&&(a=e.split(" ")),t.list.forEach((i=>{let s=i.terms();!0===n&&(s=s.filter((n=>n.canBe(e,t.world)))),s.forEach(((n,i)=>{a.length>1?a[i]&&"."!==a[i]&&n.tag(a[i],r,t.world):n.tag(e,r,t.world)}))}))};Yr.tag=function(e,t){return e?(ea(e,this,!1,t),this):this},Yr.tagSafe=function(e,t){return e?(ea(e,this,!0,t),this):this},Yr.unTag=function(e,t){return this.list.forEach((n=>{n.terms().forEach((n=>n.unTag(e,t,this.world)))})),this},Yr.canBe=function(e){if(!e)return this;let t=this.world,n=this.list.reduce(((n,r)=>n.concat(r.canBe(e,t))),[]);return this.buildFrom(n)};var ta={map:function(e){if(!e)return this;let t=this.list.map(((t,n)=>{let r=this.buildFrom([t]);r.from=null;let a=e(r,n);return a&&a.list&&a.list[0]?a.list[0]:a}));return t=t.filter((e=>e)),0===t.length?this.buildFrom(t):"object"!=typeof t[0]||"Phrase"!==t[0].isA?t:this.buildFrom(t)},forEach:function(e,t){return e?(this.list.forEach(((n,r)=>{let a=this.buildFrom([n]);!0===t&&(a.from=null),e(a,r)})),this):this},filter:function(e){if(!e)return this;let t=this.list.filter(((t,n)=>{let r=this.buildFrom([t]);return r.from=null,e(r,n)}));return this.buildFrom(t)},find:function(e){if(!e)return this;let t=this.list.find(((t,n)=>{let r=this.buildFrom([t]);return r.from=null,e(r,n)}));return t?this.buildFrom([t]):void 0},some:function(e){return e?this.list.some(((t,n)=>{let r=this.buildFrom([t]);return r.from=null,e(r,n)})):this},random:function(e){if(!this.found)return this;let t=Math.floor(Math.random()*this.list.length);if(void 0===e){let e=[this.list[t]];return this.buildFrom(e)}return t+e>this.length&&(t=this.length-e,t=t<0?0:t),this.slice(t,t+e)}},ra={},aa=function(e,t,n){let r=function(e,t=[]){let n={};return e.forEach(((e,r)=>{let a=!0;void 0!==t[r]&&(a=t[r]);let i=function(e){return e.split(/[ -]/g)}(e=(e=(e||"").toLowerCase()).replace(/[,;.!?]+$/,"")).map((e=>e.trim()));n[i[0]]=n[i[0]]||{},1===i.length?n[i[0]].value=a:(n[i[0]].more=n[i[0]].more||[],n[i[0]].more.push({rest:i.slice(1),value:a}))})),n}(e,t),a=[];for(let e=0;ee.reduced));for(let e=0;e{void 0!==i[e+n.rest.length]&&!0===n.rest.every(((t,n)=>t===i[e+n+1]))&&a.push({id:t.terms()[e].id,value:n.value,length:n.rest.length+1})})),void 0!==r[i[e]].value&&a.push({id:t.terms()[e].id,value:r[i[e]].value,length:1}))}return a};!function(e){const t=aa;e.lookup=function(e){let n=[],r=(a=e)&&"[object Object]"===Object.prototype.toString.call(a);var a;!0===r&&(e=Object.keys(e).map((t=>(n.push(e[t]),t)))),"string"==typeof e&&(e=[e]),!0!==this._cache.set&&this.cache();let i=t(e,n,this),s=this.list[0];if(!0===r){let e={};return i.forEach((t=>{e[t.value]=e[t.value]||[],e[t.value].push(s.buildFrom(t.id,t.length))})),Object.keys(e).forEach((t=>{e[t]=this.buildFrom(e[t])})),e}return i=i.map((e=>s.buildFrom(e.id,e.length))),this.buildFrom(i)},e.lookUp=e.lookup}(ra);var na={cache:function(e){e=e||{};let t={},n={};return this._cache.words=t,this._cache.tags=n,this._cache.set=!0,this.list.forEach(((r,a)=>{r.cache=r.cache||{},r.terms().forEach((r=>{t[r.reduced]&&!t.hasOwnProperty(r.reduced)||(t[r.reduced]=t[r.reduced]||[],t[r.reduced].push(a),Object.keys(r.tags).forEach((e=>{n[e]=n[e]||[],n[e].push(a)})),e.root&&(r.setRoot(this.world),t[r.root]=[a]))}))})),this},uncache:function(){return this._cache={},this.list.forEach((e=>{e.cache={}})),this.parents().forEach((e=>{e._cache={},e.list.forEach((e=>{e.cache={}}))})),this}},ia={};const oa=xt;ia.replaceWith=function(e,t={}){return e?(!0===t&&(t={keepTags:!0}),!1===t&&(t={keepTags:!1}),t=t||{},this.uncache(),this.list.forEach((n=>{let r,a=e;if("function"==typeof e&&(a=e(n)),a&&"object"==typeof a&&"Doc"===a.isA)r=a.list,this.pool().merge(a.pool());else{if("string"!=typeof a)return;{!1!==t.keepCase&&n.terms(0).isTitleCase()&&(a=(i=a).charAt(0).toUpperCase()+i.substr(1)),r=oa(a,this.world,this.pool());let e=this.buildFrom(r);e.tagger(),r=e.list}}var i;if(!0===t.keepTags){let e=n.json({terms:{tags:!0}}).terms;r[0].terms().forEach(((t,n)=>{e[n]&&t.tagSafe(e[n].tags,"keptTag",this.world)}))}n.replace(r[0],this)})),this):this.delete()},ia.replace=function(e,t,n){return void 0===t?this.replaceWith(e,n):(this.match(e).replaceWith(t,n),this)};var sa={};!function(e){const t=xt,n=function(e){return e&&"[object Object]"===Object.prototype.toString.call(e)},r=function(e,n){let r=t(e,n.world)[0],a=n.buildFrom([r]);return a.tagger(),n.list=a.list,n};e.append=function(e=""){return e?this.found?(this.uncache(),this.list.forEach((r=>{let a;n(e)&&"Doc"===e.isA?a=e.list[0].clone():"string"==typeof e&&(a=t(e,this.world,this.pool())[0]),this.buildFrom([a]).tagger(),r.append(a,this)})),this):r(e,this):this},e.insertAfter=e.append,e.insertAt=e.append,e.prepend=function(e){return e?this.found?(this.uncache(),this.list.forEach((r=>{let a;n(e)&&"Doc"===e.isA?a=e.list[0].clone():"string"==typeof e&&(a=t(e,this.world,this.pool())[0]),this.buildFrom([a]).tagger(),r.prepend(a,this)})),this):r(e,this):this},e.insertBefore=e.prepend,e.concat=function(){this.uncache();let e=this.list.slice(0);for(let n=0;ne.delete(this))),this},e.remove=e.delete}(sa);var la={};const ua={clean:!0,reduced:!0,root:!0};la.text=function(e){e=e||{};let t=!1;0===this.parents().length&&(t=!0),("root"===e||"object"==typeof e&&e.root)&&this.list.forEach((e=>{e.terms().forEach((e=>{null===e.root&&e.setRoot(this.world)}))}));let n=this.list.reduce(((n,r,a)=>{const i=!t&&0===a,s=!t&&a===this.list.length-1;return n+r.text(e,i,s)}),"");return!0!==ua[e]&&!0!==e.reduced&&!0!==e.clean&&!0!==e.root||(n=n.trim()),n};var ca={},ha=function(e,t,n){let r=function(e){let t=0,n=0,r={};return e.termList().forEach((e=>{r[e.id]={index:n,start:t+e.pre.length,length:e.text.length},t+=e.pre.length+e.text.length+e.post.length,n+=1})),r}(e.all());(n.terms.index||n.index)&&t.forEach((e=>{e.terms.forEach((e=>{e.index=r[e.id].index})),e.index=e.terms[0].index})),(n.terms.offset||n.offset)&&t.forEach((e=>{e.terms.forEach((e=>{e.offset=r[e.id]||{}})),e.offset={index:e.terms[0].offset.index,start:e.terms[0].offset.start-e.text.indexOf(e.terms[0].text),length:e.text.length}}))};!function(e){const t=ha,n={text:!0,terms:!0,trim:!0};e.json=function(e={}){if("number"==typeof e&&this.list[e])return this.list[e].json(n);!0===(e=function(e){return(e=Object.assign({},n,e)).unique&&(e.reduced=!0),e.offset&&(e.text=!0,e.terms&&!0!==e.terms||(e.terms={}),e.terms.offset=!0),(e.index||e.terms.index)&&(e.terms=!0===e.terms?{}:e.terms,e.terms.id=!0),e}(e)).root&&this.list.forEach((e=>{e.terms().forEach((e=>{null===e.root&&e.setRoot(this.world)}))}));let r=this.list.map((t=>t.json(e,this.world)));if((e.terms.offset||e.offset||e.terms.index||e.index)&&t(this,r,e),e.frequency||e.freq||e.count){let e={};this.list.forEach((t=>{let n=t.text("reduced");e[n]=e[n]||0,e[n]+=1})),this.list.forEach(((t,n)=>{r[n].count=e[t.text("reduced")]}))}if(e.unique){let e={};r=r.filter((t=>!0!==e[t.reduced]&&(e[t.reduced]=!0,!0)))}return r},e.data=e.json}(ca);var da={},ga={exports:{}};!function(e){const t="",n=function(e,t){for(e=e.toString();e.length{console.log('\n%c"'+e.text()+'"',"color: #e6d7b3;"),e.terms().forEach((e=>{let a=Object.keys(e.tags),i=e.text||"-";e.implicit&&(i="["+e.implicit+"]");let s="'"+i+"'";s=n(s,8);let o=a.find((e=>t[e]&&t[e].color)),l="steelblue";t[o]&&(l=t[o].color,l=r[l]),console.log(` ${s} - %c${a.join(", ")}`,`color: ${l||"steelblue"};`)}))}))}(e),e):(console.log(a.blue("=====")),e.list.forEach((t=>{console.log(a.blue(" -----")),t.terms().forEach((t=>{let r=Object.keys(t.tags),i=t.text||"-";t.implicit&&(i="["+t.implicit+"]"),i=a.yellow(i);let s="'"+i+"'";s=n(s,18);let o=a.blue(" | ")+s+" - "+function(e,t){return(e=e.map((e=>{if(!t.tags.hasOwnProperty(e))return e;const n=t.tags[e].color||"blue";return a[n](e)}))).join(", ")}(r,e.world);console.log(o)}))})),console.log(""),e)}}();const pa=ga.exports,ma=function(e){let t=e.json({text:!1,terms:!1,reduced:!0}),n={};t.forEach((e=>{n[e.reduced]||(e.count=0,n[e.reduced]=e),n[e.reduced].count+=1}));let r=Object.keys(n).map((e=>n[e]));return r.sort(((e,t)=>e.count>t.count?-1:e.counte.text)).filter((e=>e));if("freq"===e||"frequency"===e)return ma(this);if("terms"===e){let e=[];return this.json({text:!1,terms:{text:!0}}).forEach((t=>{let n=t.terms.map((e=>e.text));n=n.filter((e=>e)),e=e.concat(n)})),e}return"tags"===e?this.list.map((e=>e.terms().reduce(((e,t)=>(e[t.clean||t.implicit]=Object.keys(t.tags),e)),{}))):"debug"===e?(pa(this),this):this.text()};var fa={};const ba={alpha:(e,t)=>{let n=e.text("clean"),r=t.text("clean");return nr?1:0},length:(e,t)=>{let n=e.text().trim().length,r=t.text().trim().length;return nr?-1:0},wordCount:(e,t)=>{let n=e.wordCount(),r=t.wordCount();return nr?-1:0}};ba.alphabetical=ba.alpha,ba.wordcount=ba.wordCount;const ya={index:!0,sequence:!0,seq:!0,sequential:!0,chron:!0,chronological:!0};fa.sort=function(e){return"freq"===(e=e||"alpha")||"frequency"===e||"topk"===e?function(e){let t={};const n={case:!0,punctuation:!1,whitespace:!0,unicode:!0};return e.list.forEach((e=>{let r=e.text(n);t[r]=t[r]||0,t[r]+=1})),e.list.sort(((e,r)=>{let a=t[e.text(n)],i=t[r.text(n)];return ai?-1:0})),e}(this):ya.hasOwnProperty(e)?function(e){let t={};return e.json({terms:{offset:!0}}).forEach((e=>{t[e.terms[0].id]=e.terms[0].offset.start})),e.list=e.list.sort(((e,n)=>t[e.start]>t[n.start]?1:t[e.start]{let n=e.text("reduced").trim()||e.text("implicit").trim();return!0!==t.hasOwnProperty(n)&&(t[n]=!0,!0)})),this.buildFrom(e)};var va={};const wa=n$1,ka=/[\[\]{}⟨⟩:,،、‒–—―…‹›«»‐\-;\/⁄·*\•^†‡°¡¿※№÷׺ª%‰=‱¶§~|‖¦©℗®℠™¤₳฿]/g,Aa=/['‘’“”"′″‴]+/g,Da={whitespace:function(e){let t=e.list.map((e=>e.terms()));t.forEach(((e,n)=>{e.forEach(((r,a)=>{!0!==r.hasDash()?(r.pre=r.pre.replace(/\s/g,""),r.post=r.post.replace(/\s/g,""),(e.length-1!==a||t[n+1])&&(r.implicit&&!0===Boolean(r.text)||!0!==r.hasHyphen()&&(r.post+=" "))):r.post=" - "}))}))},punctuation:function(e){e.forEach((e=>{!0===e.hasHyphen()&&(e.post=" "),e.pre=e.pre.replace(ka,""),e.post=e.post.replace(ka,""),e.post=e.post.replace(/\.\.\./,""),!0===/!/.test(e.post)&&(e.post=e.post.replace(/!/g,""),e.post="!"+e.post),!0===/\?/.test(e.post)&&(e.post=e.post.replace(/[\?!]*/,""),e.post="?"+e.post)}))},unicode:function(e){e.forEach((e=>{!0!==e.isImplicit()&&(e.text=wa(e.text))}))},quotations:function(e){e.forEach((e=>{e.post=e.post.replace(Aa,""),e.pre=e.pre.replace(Aa,"")}))},adverbs:function(e){e.match("#Adverb").not("(not|nary|seldom|never|barely|almost|basically|so)").remove()},abbreviations:function(e){e.list.forEach((e=>{let t=e.terms();t.forEach(((e,n)=>{!0===e.tags.Abbreviation&&t[n+1]&&(e.post=e.post.replace(/^\./,""))}))}))}},$a={whitespace:!0,unicode:!0,punctuation:!0,emoji:!0,acronyms:!0,abbreviations:!0,case:!1,contractions:!1,parentheses:!1,quotations:!1,adverbs:!1,possessives:!1,verbs:!1,nouns:!1,honorifics:!1},Pa={light:{},medium:{case:!0,contractions:!0,parentheses:!0,quotations:!0,adverbs:!0}};Pa.heavy=Object.assign({},Pa.medium,{possessives:!0,verbs:!0,nouns:!0,honorifics:!0}),va.normalize=function(e){"string"==typeof(e=e||{})&&(e=Pa[e]||{}),e=Object.assign({},$a,e),this.uncache();let t=this.termList();return e.case&&this.toLowerCase(),e.whitespace&&Da.whitespace(this),e.unicode&&Da.unicode(t),e.punctuation&&Da.punctuation(t),e.emoji&&this.remove("(#Emoji|#Emoticon)"),e.acronyms&&this.acronyms().strip(),e.abbreviations&&Da.abbreviations(this),(e.contraction||e.contractions)&&this.contractions().expand(),e.parentheses&&this.parentheses().unwrap(),(e.quotations||e.quotes)&&Da.quotations(t),e.adverbs&&Da.adverbs(this),(e.possessive||e.possessives)&&this.possessives().strip(),e.verbs&&this.verbs().toInfinitive(),(e.nouns||e.plurals)&&this.nouns().toSingular(),e.honorifics&&this.remove("#Honorific"),this};var Ea={};!function(e){const t=_e;e.splitOn=function(e){if(!e)return this.parent().splitOn(this);let n=t(e),r=[];return this.list.forEach((e=>{let t=e.match(n);if(0===t.length)return void r.push(e);let a=e;t.forEach((e=>{let t=a.splitOn(e);t.before&&r.push(t.before),t.match&&r.push(t.match),a=t.after})),a&&r.push(a)})),this.buildFrom(r)},e.splitAfter=function(e){if(!e)return this.parent().splitAfter(this);let n=t(e),r=[];return this.list.forEach((e=>{let t=e.match(n);if(0===t.length)return void r.push(e);let a=e;t.forEach((e=>{let t=a.splitOn(e);t.before&&t.match?(t.before.length+=t.match.length,r.push(t.before)):t.match&&r.push(t.match),a=t.after})),a&&r.push(a)})),this.buildFrom(r)},e.split=e.splitAfter,e.splitBefore=function(e){if(!e)return this.parent().splitBefore(this);let n=t(e),r=[];return this.list.forEach((e=>{let t=e.match(n);if(0===t.length)return void r.push(e);let a=e;t.forEach((e=>{let t=a.splitOn(e);t.before&&r.push(t.before),t.match&&t.after&&(t.match.length+=t.after.length),a=t.match})),a&&r.push(a)})),this.buildFrom(r)},e.segment=function(e,t){e=e||{},t=t||{text:!0};let n=this,r=Object.keys(e);return r.forEach((e=>{n=n.splitOn(e)})),n.list.forEach((t=>{for(let n=0;n{let n=e.json(t);return n.segment=e.segment||null,n}))}}(Ea);var Ha={};const ja=function(e,t){let n=e.world;return e.list.forEach((e=>{e.terms().forEach((e=>e[t](n)))})),e};Ha.toLowerCase=function(){return ja(this,"toLowerCase")},Ha.toUpperCase=function(){return ja(this,"toUpperCase")},Ha.toTitleCase=function(){return ja(this,"toTitleCase")},Ha.toCamelCase=function(){return this.list.forEach((e=>{let t=e.terms();t.forEach(((e,n)=>{0!==n&&e.toTitleCase(),n!==t.length-1&&(e.post="")}))})),this};var Na={};!function(e){e.pre=function(e,t){return void 0===e?this.list[0].terms(0).pre:(this.list.forEach((n=>{let r=n.terms(0);!0===t?r.pre+=e:r.pre=e})),this)},e.post=function(e,t){return void 0===e?this.list.map((e=>{let t=e.terms();return t[t.length-1].post})):(this.list.forEach((n=>{let r=n.terms(),a=r[r.length-1];!0===t?a.post+=e:a.post=e})),this)},e.trim=function(){return this.list=this.list.map((e=>e.trim())),this},e.hyphenate=function(){return this.list.forEach((e=>{let t=e.terms();t.forEach(((e,n)=>{0!==n&&(e.pre=""),t[n+1]&&(e.post="-")}))})),this},e.dehyphenate=function(){const e=/(-|–|—)/;return this.list.forEach((t=>{t.terms().forEach((t=>{e.test(t.post)&&(t.post=" ")}))})),this},e.deHyphenate=e.dehyphenate,e.toQuotations=function(e,t){return e=e||'"',t=t||'"',this.list.forEach((n=>{let r=n.terms();r[0].pre=e+r[0].pre;let a=r[r.length-1];a.post=t+a.post})),this},e.toQuotation=e.toQuotations,e.toParentheses=function(e,t){return e=e||"(",t=t||")",this.list.forEach((n=>{let r=n.terms();r[0].pre=e+r[0].pre;let a=r[r.length-1];a.post=t+a.post})),this}}(Na);var xa={join:function(e){this.uncache();let t=this.list[0],n=t.length,r={};for(let n=1;n{e.list.forEach((e=>{let n=e.terms();for(let r=0;r!0!==r[e.start]))})),this.buildFrom([t])}},Fa={};const Ca=/[,\)"';:\-–—\.…]/,Ba=function(e,t){if(!e.found)return;let n=e.termList();for(let e=0;e{e.implicit=e.clean})),n[0].text+=t,n.slice(1).forEach((e=>{e.text=""}));for(let e=0;e{za[e[0]]=function(t){let n=this.match(e[1]);return"number"==typeof t&&(n=n.get(t)),n}})),za.emojis=za.emoji,za.atmentions=za.atMentions,za.words=za.terms,za.phoneNumbers=function(e){let t=this.splitAfter("@hasComma");return t=t.match("#PhoneNumber+"),"number"==typeof e&&(t=t.get(e)),t},za.money=function(e){let t=this.match("#Money #Currency?");return"number"==typeof e&&(t=t.get(e)),t},za.places=function(e){let t=this.match("(#City && @hasComma) (#Region|#Country)"),n=this.not(t).splitAfter("@hasComma");return n=n.concat(t),n.sort("index"),n=n.match("#Place+"),"number"==typeof e&&(n=n.get(e)),n},za.organizations=function(e){let t=this.clauses();return t=t.match("#Organization+"),"number"==typeof e&&(t=t.get(e)),t},za.entities=function(e){let t=this.clauses(),n=t.people();return n=n.concat(t.places()),n=n.concat(t.organizations()),n=n.not(["someone","man","woman","mother","brother","sister","father"]),n.sort("sequence"),"number"==typeof e&&(n=n.get(e)),n},za.things=za.entities,za.topics=za.entities;var Ia=za;const Oa=/^(under|over)-?.{3}/,Ta=function(e,t,n){let r=n.words,a=e[t].reduced+" "+e[t+1].reduced;return void 0!==r[a]&&!0===r.hasOwnProperty(a)?(e[t].tag(r[a],"lexicon-two",n),e[t+1].tag(r[a],"lexicon-two",n),1):t+20){a+=n;continue}}if(void 0===n[i]||!0!==n.hasOwnProperty(i))if(i===e[a].reduced||!0!==n.hasOwnProperty(e[a].reduced)){if(!0===Oa.test(i)){let r=i.replace(/^(under|over)-?/,"");!0===n.hasOwnProperty(r)&&e[a].tag(n[r],"noprefix-lexicon",t)}}else e[a].tag(n[e[a].reduced],"lexicon",t);else e[a].tag(n[i],"lexicon",t)}return e};const Ma=/[\'‘’‛‵′`´]$/,Ja=/^(m|k|cm|km|m)\/(s|h|hr)$/,La=[[/^[\w\.]+@[\w\.]+\.[a-z]{2,3}$/,"Email"],[/^#[a-z0-9_\u00C0-\u00FF]{2,}$/,"HashTag"],[/^@1?[0-9](am|pm)$/i,"Time"],[/^@1?[0-9]:[0-9]{2}(am|pm)?$/i,"Time"],[/^@\w{2,}$/,"AtMention"],[/^(https?:\/\/|www\.)+\w+\.[a-z]{2,3}/,"Url"],[/^[a-z0-9./].+\.(com|net|gov|org|ly|edu|info|biz|dev|ru|jp|de|in|uk|br|io|ai)/,"Url"],[/^'[0-9]{2}$/,"Year"],[/^[012]?[0-9](:[0-5][0-9])(:[0-5][0-9])$/,"Time"],[/^[012]?[0-9](:[0-5][0-9])?(:[0-5][0-9])? ?(am|pm)$/i,"Time"],[/^[012]?[0-9](:[0-5][0-9])(:[0-5][0-9])? ?(am|pm)?$/i,"Time"],[/^[PMCE]ST$/,"Time"],[/^utc ?[+-]?[0-9]+?$/,"Time"],[/^[a-z0-9]*? o\'?clock$/,"Time"],[/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}/i,"Date"],[/^[0-9]{1,4}-[0-9]{1,2}-[0-9]{1,4}$/,"Date"],[/^[0-9]{1,4}\/[0-9]{1,2}\/[0-9]{1,4}$/,"Date"],[/^[0-9]{1,4}-[a-z]{2,9}-[0-9]{1,4}$/i,"Date"],[/^gmt[+-][0-9][0-9]?$/i,"Timezone"],[/^utc[+-][0-9][0-9]?$/i,"Timezone"],[/^ma?c\'.*/,"LastName"],[/^o\'[drlkn].*/,"LastName"],[/^ma?cd[aeiou]/,"LastName"],[/^(lol)+[sz]$/,"Expression"],[/^woo+a*?h?$/,"Expression"],[/^(un|de|re)\\-[a-z\u00C0-\u00FF]{2}/,"Verb"],[/^[0-9]{1,4}\.[0-9]{1,2}\.[0-9]{1,4}$/,"Date"],[/^[0-9]{3}-[0-9]{4}$/,"PhoneNumber"],[/^(\+?[0-9][ -])?[0-9]{3}[ -]?[0-9]{3}-[0-9]{4}$/,"PhoneNumber"],[/^[-+]?[\$\xA2-\xA5\u058F\u060B\u09F2\u09F3\u09FB\u0AF1\u0BF9\u0E3F\u17DB\u20A0-\u20BD\uA838\uFDFC\uFE69\uFF04\uFFE0\uFFE1\uFFE5\uFFE6][-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?(k|m|b|bn)?\+?$/,["Money","Value"]],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?[\$\xA2-\xA5\u058F\u060B\u09F2\u09F3\u09FB\u0AF1\u0BF9\u0E3F\u17DB\u20A0-\u20BD\uA838\uFDFC\uFE69\uFF04\uFFE0\uFFE1\uFFE5\uFFE6]\+?$/,["Money","Value"]],[/^[-+]?[\$£]?[0-9]([0-9,.])+?(usd|eur|jpy|gbp|cad|aud|chf|cny|hkd|nzd|kr|rub)$/i,["Money","Value"]],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?\+?$/,["Cardinal","NumericValue"]],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?(st|nd|rd|r?th)$/,["Ordinal","NumericValue"]],[/^\.[0-9]+\+?$/,["Cardinal","NumericValue"]],[/^[-+]?[0-9]+(,[0-9]{3})*(\.[0-9]+)?%\+?$/,["Percent","Cardinal","NumericValue"]],[/^\.[0-9]+%$/,["Percent","Cardinal","NumericValue"]],[/^[0-9]{1,4}\/[0-9]{1,4}(st|nd|rd|th)?s?$/,["Fraction","NumericValue"]],[/^[0-9.]{1,3}[a-z]{0,2}[-–—][0-9]{1,3}[a-z]{0,2}$/,["Value","NumberRange"]],[/^[0-9][0-9]?(:[0-9][0-9])?(am|pm)? ?[-–—] ?[0-9][0-9]?(:[0-9][0-9])?(am|pm)?$/,["Time","NumberRange"]],[/^[0-9.]+([a-z]{1,4})$/,"Value"]],Sa=/^[IVXLCDM]{2,}$/,_a=/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,Ka="Adjective",qa="Infinitive",Wa="PresentTense",Ra="Singular",Ua="PastTense",Qa="Expression",Za="Adjective",Xa="Infinitive",Ya="PresentTense",en="Singular",tn="PastTense",rn="Adverb",an="Plural",nn="Verb",on="LastName",sn={a:[[/.[aeiou]na$/,"Noun"],[/.[oau][wvl]ska$/,"LastName"],[/.[^aeiou]ica$/,Ra],[/^([hyj]a)+$/,Qa]],c:[[/.[^aeiou]ic$/,Ka]],d:[[/[aeiou](pp|ll|ss|ff|gg|tt|rr|bb|nn|mm)ed$/,Ua],[/.[aeo]{2}[bdgmnprvz]ed$/,Ua],[/.[aeiou][sg]hed$/,Ua],[/.[aeiou]red$/,Ua],[/.[aeiou]r?ried$/,Ua],[/.[bcdgtr]led$/,Ua],[/.[aoui]f?led$/,Ua],[/.[iao]sed$/,Ua],[/[aeiou]n?[cs]ed$/,Ua],[/[aeiou][rl]?[mnf]ed$/,Ua],[/[aeiou][ns]?c?ked$/,Ua],[/[aeiou][nl]?ged$/,Ua],[/.[tdbwxz]ed$/,Ua],[/[^aeiou][aeiou][tvx]ed$/,Ua],[/.[cdlmnprstv]ied$/,Ua],[/[^aeiou]ard$/,Ra],[/[aeiou][^aeiou]id$/,Ka],[/.[vrl]id$/,Ka]],e:[[/.[lnr]ize$/,qa],[/.[^aeiou]ise$/,qa],[/.[aeiou]te$/,qa],[/.[^aeiou][ai]ble$/,Ka],[/.[^aeiou]eable$/,Ka],[/.[ts]ive$/,Ka],[/[a-z]-like$/,Ka]],h:[[/.[^aeiouf]ish$/,Ka],[/.v[iy]ch$/,"LastName"],[/^ug?h+$/,Qa],[/^uh[ -]?oh$/,Qa],[/[a-z]-ish$/,Ka]],i:[[/.[oau][wvl]ski$/,"LastName"]],k:[[/^(k){2}$/,Qa]],l:[[/.[gl]ial$/,Ka],[/.[^aeiou]ful$/,Ka],[/.[nrtumcd]al$/,Ka],[/.[^aeiou][ei]al$/,Ka]],m:[[/.[^aeiou]ium$/,Ra],[/[^aeiou]ism$/,Ra],[/^h*u*m+$/,Qa],[/^\d+ ?[ap]m$/,"Date"]],n:[[/.[lsrnpb]ian$/,Ka],[/[^aeiou]ician$/,"Actor"],[/[aeiou][ktrp]in$/,"Gerund"]],o:[[/^no+$/,Qa],[/^(yo)+$/,Qa],[/^woo+[pt]?$/,Qa]],r:[[/.[bdfklmst]ler$/,"Noun"],[/[aeiou][pns]er$/,Ra],[/[^i]fer$/,qa],[/.[^aeiou][ao]pher$/,"Actor"],[/.[lk]er$/,"Noun"],[/.ier$/,"Comparative"]],t:[[/.[di]est$/,"Superlative"],[/.[icldtgrv]ent$/,Ka],[/[aeiou].*ist$/,Ka],[/^[a-z]et$/,"Verb"]],s:[[/.[^aeiou]ises$/,Wa],[/.[rln]ates$/,Wa],[/.[^z]ens$/,"Verb"],[/.[lstrn]us$/,Ra],[/.[aeiou]sks$/,Wa],[/.[aeiou]kes$/,Wa],[/[aeiou][^aeiou]is$/,Ra],[/[a-z]\'s$/,"Noun"],[/^yes+$/,Qa]],v:[[/.[^aeiou][ai][kln]ov$/,"LastName"]],y:[[/.[cts]hy$/,Ka],[/.[st]ty$/,Ka],[/.[gk]y$/,Ka],[/.[tnl]ary$/,Ka],[/.[oe]ry$/,Ra],[/[rdntkbhs]ly$/,"Adverb"],[/...lly$/,"Adverb"],[/[bszmp]{2}y$/,Ka],[/.(gg|bb|zz)ly$/,Ka],[/.[ai]my$/,Ka],[/[ea]{2}zy$/,Ka],[/.[^aeiou]ity$/,Ra]]},ln=[null,null,{ea:en,ia:"Noun",ic:Za,ly:rn,"'n":nn,"'t":nn},{oed:tn,ued:tn,xed:tn," so":rn,"'ll":"Modal","'re":"Copula",azy:Za,eer:"Noun",end:nn,ped:tn,ffy:Za,ify:Xa,ing:"Gerund",ize:Xa,lar:Za,mum:Za,nes:Ya,nny:Za,oid:Za,ous:Za,que:Za,rol:en,sis:en,zes:Ya},{amed:tn,aped:tn,ched:tn,lked:tn,nded:tn,cted:tn,dged:tn,akis:on,cede:Xa,chuk:on,czyk:on,ects:Ya,ends:nn,enko:on,ette:en,fies:Ya,fore:rn,gate:Xa,gone:Za,ices:an,ints:an,ines:an,ions:an,less:rn,llen:Za,made:Za,nsen:on,oses:Ya,ould:"Modal",some:Za,sson:on,tage:Xa,teen:"Value",tion:en,tive:Za,tors:"Noun",vice:en},{tized:tn,urned:tn,eased:tn,ances:an,bound:Za,ettes:an,fully:rn,ishes:Ya,ities:an,marek:on,nssen:on,ology:"Noun",ports:an,rough:Za,tches:Ya,tieth:"Ordinal",tures:an,wards:rn,where:rn},{auskas:on,keeper:"Actor",logist:"Actor",teenth:"Value"},{opoulos:on,borough:"Place",sdottir:on}],un=/^(\u00a9|\u00ae|[\u2319-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])/,cn={":(":!0,":)":!0,":P":!0,":p":!0,":O":!0,":3":!0,":|":!0,":/":!0,":\\":!0,":$":!0,":*":!0,":@":!0,":-(":!0,":-)":!0,":-P":!0,":-p":!0,":-O":!0,":-3":!0,":-|":!0,":-/":!0,":-\\":!0,":-$":!0,":-*":!0,":-@":!0,":^(":!0,":^)":!0,":^P":!0,":^p":!0,":^O":!0,":^3":!0,":^|":!0,":^/":!0,":^\\":!0,":^$":!0,":^*":!0,":^@":!0,"):":!0,"(:":!0,"$:":!0,"*:":!0,")-:":!0,"(-:":!0,"$-:":!0,"*-:":!0,")^:":!0,"(^:":!0,"$^:":!0,"*^:":!0,"<3":!0,"2){let e=r.clean[r.clean.length-2];if("s"===e)return void r.tag(["Possessive","Noun"],"end-tick",n);"n"===e&&r.tag(["Gerund"],"chillin",n)}Ja.test(r.text)&&r.tag("Unit","per-sec",n)},regex:function(e,t){let n=e.text;for(let r=0;r=2&&Sa.test(n)&&_a.test(n)&&e.tag("RomanNumeral","xvii",t)},suffix:function(e,t){!function(e,t){const n=e.clean.length;let r=7;n<=r&&(r=n-1);for(let a=r;a>1;a-=1){let r=e.clean.substr(n-a,n);if(!0===ln[r.length].hasOwnProperty(r)){let n=ln[r.length][r];e.tagSafe(n,"suffix -"+r,t);break}}}(e,t),function(e,t){let n=e.clean,r=n[n.length-1];if(!0===sn.hasOwnProperty(r)){let a=sn[r];for(let i=0;i{let n=e.pre+e.text+e.post;var r;n=n.trim(),n=n.replace(/[.!?,]$/,""),!0===(e=>!(":"!==e.charAt(0)||null===e.match(/:.?$/)||e.match(" ")||e.length>35))(n)&&(e.tag("Emoji","comma-emoji",t),e.text=n,e.pre=e.pre.replace(":",""),e.post=e.post.replace(":","")),e.text.match(un)&&(e.tag("Emoji","unicode-emoji",t),e.text=n),!0===(r=(r=n).replace(/^[:;]/,":"),cn.hasOwnProperty(r))&&(e.tag("Emoticon","emoticon-emoji",t),e.text=n)}};var dn=function(e,t){let n=e.world;hn.lexicon(t,n);for(let e=0;ea.tags[e]));if(void 0!==e){let n=gn.afterThisPos[e];r.tag(n,"after-"+e,t);continue}}let i=e[n+1];if(i){if(!0===gn.beforeThisWord.hasOwnProperty(i.clean)){let e=gn.beforeThisWord[i.clean];r.tag(e,"before-"+i.clean,t);continue}let e=mn.find((e=>i.tags[e]));if(void 0!==e){let n=gn.beforeThisPos[e];r.tag(n,"before-"+e,t);continue}}}};const bn=/^[A-Z][a-z'\u00C0-\u00FF]/,yn=/[0-9]/;var vn=function(e){let t=e.world;e.list.forEach((e=>{let n=e.terms();for(let e=1;e{if(!0!==e.isKnown()&&!0===wn.test(e.clean)){let r=e.clean.replace(kn,"");r&&r.length>3&&void 0!==n[r]&&!0===n.hasOwnProperty(r)&&e.tag(n[r],"stem-"+r,t)}}))};const Dn=["Uncountable","Pronoun","Place","Value","Person","Month","WeekDay","Holiday"],$n={isSingular:[/(ax|test)is$/i,/(octop|vir|radi|nucle|fung|cact|stimul)us$/i,/(octop|vir)i$/i,/(rl)f$/i,/(alias|status)$/i,/(bu)s$/i,/(al|ad|at|er|et|ed|ad)o$/i,/(ti)um$/i,/(ti)a$/i,/sis$/i,/(?:(^f)fe|(lr)f)$/i,/hive$/i,/s[aeiou]+ns$/i,/(^aeiouy|qu)y$/i,/(x|ch|ss|sh|z)$/i,/(matr|vert|ind|cort)(ix|ex)$/i,/(m|l)ouse$/i,/(m|l)ice$/i,/(antenn|formul|nebul|vertebr|vit)a$/i,/.sis$/i,/^(?!talis|.*hu)(.*)man$/i],isPlural:[/(^v)ies$/i,/ises$/i,/ives$/i,/(antenn|formul|nebul|vertebr|vit)ae$/i,/(octop|vir|radi|nucle|fung|cact|stimul)i$/i,/(buffal|tomat|tornad)oes$/i,/(analy|ba|diagno|parenthe|progno|synop|the)ses$/i,/(vert|ind|cort)ices$/i,/(matr|append)ices$/i,/(x|ch|ss|sh|s|z|o)es$/i,/is$/i,/men$/i,/news$/i,/.tia$/i,/(^f)ves$/i,/(lr)ves$/i,/(^aeiouy|qu)ies$/i,/(m|l)ice$/i,/(cris|ax|test)es$/i,/(alias|status)es$/i,/ics$/i]},Pn=[/ss$/,/sis$/,/[^aeiou][uo]s$/,/'s$/],En=[/i$/,/ae$/];var Hn=function(e,t){if(e.tags.Noun&&!e.tags.Acronym){let n=e.clean;if(e.tags.Singular||e.tags.Plural)return;if(n.length<=3)return void e.tag("Singular","short-singular",t);if(Dn.find((t=>e.tags[t])))return;if($n.isPlural.find((e=>e.test(n))))return void e.tag("Plural","plural-rules",t);if($n.isSingular.find((e=>e.test(n))))return void e.tag("Singular","singular-rules",t);if(!0===/s$/.test(n)){if(Pn.find((e=>e.test(n))))return;return void e.tag("Plural","plural-fallback",t)}if(En.find((e=>e.test(n))))return;e.tag("Singular","singular-fallback",t)}};let jn=["academy","administration","agence","agences","agencies","agency","airlines","airways","army","assoc","associates","association","assurance","authority","autorite","aviation","bank","banque","board","boys","brands","brewery","brotherhood","brothers","building society","bureau","cafe","caisse","capital","care","cathedral","center","central bank","centre","chemicals","choir","chronicle","church","circus","clinic","clinique","club","co","coalition","coffee","collective","college","commission","committee","communications","community","company","comprehensive","computers","confederation","conference","conseil","consulting","containers","corporation","corps","corp","council","crew","daily news","data","departement","department","department store","departments","design","development","directorate","division","drilling","education","eglise","electric","electricity","energy","ensemble","enterprise","enterprises","entertainment","estate","etat","evening news","faculty","federation","financial","fm","foundation","fund","gas","gazette","girls","government","group","guild","health authority","herald","holdings","hospital","hotel","hotels","inc","industries","institut","institute","institute of technology","institutes","insurance","international","interstate","investment","investments","investors","journal","laboratory","labs","liberation army","limited","local authority","local health authority","machines","magazine","management","marine","marketing","markets","media","memorial","mercantile exchange","ministere","ministry","military","mobile","motor","motors","musee","museum","news","news service","observatory","office","oil","optical","orchestra","organization","partners","partnership","people's party","petrol","petroleum","pharmacare","pharmaceutical","pharmaceuticals","pizza","plc","police","polytechnic","post","power","press","productions","quartet","radio","regional authority","regional health authority","reserve","resources","restaurant","restaurants","savings","school","securities","service","services","social club","societe","society","sons","standard","state police","state university","stock exchange","subcommittee","syndicat","systems","telecommunications","telegraph","television","times","tribunal","tv","union","university","utilities","workers"].reduce((function(e,t){return e[t]="Noun",e}),{});const Nn=function(e){return!(!e.tags.Noun||e.tags.Pronoun||e.tags.Comma||e.tags.Possessive||!(e.tags.Organization||e.tags.Acronym||e.tags.Place||e.titleCase()))},xn=/^[A-Z]('s|,)?$/,Fn=/([A-Z]\.){2}[A-Z]?/i,Cn={I:!0,A:!0},Bn={neighbours:fn,case:vn,stem:An,plural:Hn,organizations:function(e,t){for(let n=0;n{!0!==e.tags.RomanNumeral&&(!0===Fn.test(e.text)&&e.tag("Acronym","period-acronym",t),e.isUpperCase()&&function(e,t){let n=e.reduced;return!!e.tags.Acronym||!t.words[n]&&!(n.length>5)&&e.isAcronym()}(e,t)?(e.tag("Acronym","acronym-step",t),e.tag("Noun","acronym-infer",t)):!Cn.hasOwnProperty(e.text)&&xn.test(e.text)&&(e.tag("Acronym","one-letter-acronym",t),e.tag("Noun","one-letter-infer",t)),e.tags.Organization&&e.text.length<=3&&e.tag("Acronym","acronym-org",t),e.tags.Organization&&e.isUpperCase()&&e.text.length<=6&&e.tag("Acronym","acronym-org-case",t))}))}};var Gn=function(e,t){let n=e.world;return Bn.neighbours(t,n),Bn.case(e),Bn.stem(t,n),t.forEach((t=>{!1===t.isKnown()&&t.tag("Noun","noun-fallback",e.world)})),Bn.organizations(t,n),Bn.acronyms(t,n),t.forEach((t=>{Bn.plural(t,e.world)})),e};const zn=/n't$/,In={"won't":["will","not"],wont:["will","not"],"can't":["can","not"],cant:["can","not"],cannot:["can","not"],"shan't":["should","not"],dont:["do","not"],dun:["do","not"]},On=/([a-z\u00C0-\u00FF]+)[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]([a-z]{1,2})$/i,Tn={ll:"will",ve:"have",re:"are",m:"am","n't":"not"},Vn={wanna:["want","to"],gonna:["going","to"],im:["i","am"],alot:["a","lot"],ive:["i","have"],imma:["I","will"],"where'd":["where","did"],whered:["where","did"],"when'd":["when","did"],whend:["when","did"],howd:["how","did"],whatd:["what","did"],dunno:["do","not","know"],brb:["be","right","back"],gtg:["got","to","go"],irl:["in","real","life"],tbh:["to","be","honest"],imo:["in","my","opinion"],til:["today","i","learned"],rn:["right","now"],twas:["it","was"],"@":["at"]},Mn=/([a-z\u00C0-\u00FF]+)[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]s$/i,Jn={that:!0,there:!0},Ln={here:!0,there:!0,everywhere:!0},Sn=/[a-z\u00C0-\u00FF]'d$/,_n={how:!0,what:!0},Kn=/^([0-9.]{1,3}[a-z]{0,2}) ?[-–—] ?([0-9]{1,3}[a-z]{0,2})$/i,qn=/^([0-9][0-9]?(:[0-9][0-9])?(am|pm)?) ?[-–—] ?([0-9][0-9]?(:[0-9][0-9])?(am|pm)?)$/i,Wn=/^(l|c|d|j|m|n|qu|s|t)[\u0027\u0060\u00B4\u2018\u2019\u201A\u201B\u2032\u2035\u2039\u203A]([a-z\u00C0-\u00FF]+)$/i,Rn={l:"le",c:"ce",d:"de",j:"je",m:"me",n:"ne",qu:"que",s:"se",t:"tu"},Un=Va,Qn=xt,Zn=function(e,t){return!0===In.hasOwnProperty(e.clean)?In[e.clean]:"ain't"===e.clean||"aint"===e.clean?function(e,t){let n=t.terms(),r=n.indexOf(e),a=n.slice(0,r).find((e=>e.tags.Noun));return a&&a.tags.Plural?["are","not"]:["is","not"]}(e,t):!0===zn.test(e.clean)?[e.clean.replace(zn,""),"not"]:null},Xn=function(e){let t=e.text.match(On);return null===t?null:Tn.hasOwnProperty(t[2])?[t[1],Tn[t[2]]]:null},Yn=function(e){return Vn.hasOwnProperty(e.clean)?Vn[e.clean]:null},ei=function(e,t,n){let r=e.text.match(Mn);if(null!==r){if(!0===((e,t)=>{if(e.tags.Possessive)return!0;if(e.tags.Pronoun||e.tags.QuestionWord)return!1;if(Jn.hasOwnProperty(e.reduced))return!1;let n=t.get(e.next);if(!n)return!0;if(n.tags.Verb)return!!n.tags.Infinitive||!!n.tags.PresentTense;if(n.tags.Noun)return!0!==Ln.hasOwnProperty(n.reduced);let r=t.get(n.next);return!(!r||!r.tags.Noun||r.tags.Pronoun)||(n.tags.Adjective||n.tags.Adverb||n.tags.Verb,!1)})(e,t.pool))return e.tag("#Possessive","isPossessive",n),null;if(null!==r)return((e,t)=>{let n=t.terms(),r=n.indexOf(e);return n.slice(r+1,r+3).find((e=>e.tags.PastTense))})(e,t)?[r[1],"has"]:[r[1],"is"]}return null},ti=function(e,t){if(Sn.test(e.clean)){let n=e.clean.replace(/'d$/,""),r=t.terms(),a=r.indexOf(e),i=r.slice(a+1,a+4);for(let e=0;e{e.implicit=e.text,e.text="",e.clean="",e.pre="",e.post="",0===Object.keys(e.tags).length&&(e.tags.Noun=!0)})),n};var li=function(e){let t=e.world;return e.list.forEach((n=>{let r=n.terms();for(let a=0;ae.list[t])),e.buildFrom(n)};var ci=function(e){let t=ui(e,"Infinitive");return t.found&&(t=t.ifNo("@hasQuestionMark"),t=t.ifNo("(i|we|they)"),t.not("will be").match("[#Infinitive] (#Determiner|#Possessive) #Noun").notIf("(our|their)").match("#Infinitive").tag("Imperative","shut-the"),t.match("^[#Infinitive] #Adverb?$",0).tag("Imperative","go-fast"),t.match("[(do && #Infinitive)] not? #Verb",0).tag("Imperative","do-not"),t.match("[#Infinitive] (it|some) (#Comparative|#Preposition|please|now|again)",0).tag("Imperative","do-it")),t=function(e,t){let n=e._cache.words.like||[];return n=n.map((t=>e.list[t])),e.buildFrom(n)}(e),t.match("#Adverb like").notIf("(really|generally|typically|usually|sometimes|often|just) [like]").tag("Adverb","adverb-like"),t=ui(e,"Adjective"),t.match("#Determiner #Adjective$").notIf("(#Comparative|#Superlative)").terms(1).tag("Noun","the-adj-1"),t=ui(e,"FirstName"),t.match("#FirstName (#Noun|@titleCase)").ifNo("^#Possessive").ifNo("(#Pronoun|#Plural)").ifNo("@hasComma .").lastTerm().tag("#LastName","firstname-noun"),t=ui(e,"Value"),t=t.match("#Value #PresentTense").ifNo("#Copula"),t.found&&(!0===t.has("(one|1)")?t.terms(1).tag("Singular","one-presentTense"):t.terms(1).tag("Plural","value-presentTense")),e.match("^(well|so|okay)").tag("Expression","well-"),e.match("#Value [of a second]",0).unTag("Value","of-a-second"),e.match("#Value [seconds]",0).unTag("Value","30-seconds").tag(["Unit","Plural"]),t=ui(e,"Gerund"),t.match("(be|been) (#Adverb|not)+? #Gerund").not("#Verb$").tag("Auxiliary","be-walking"),e.match("(try|use|attempt|build|make) #Verb").ifNo("(@hasComma|#Negative|#PhrasalVerb|#Copula|will|be)").lastTerm().tag("#Noun","do-verb"),t=ui(e,"Possessive"),t=t.match("#Possessive [#Infinitive]",0),t.lookBehind("(let|made|make|force|ask)").found||t.tag("Noun","her-match"),e},hi=function(e){let t={};for(let n=0;n{e.reg=ji(e.match);let t=function(e){let t=[];if(1===e.reg.filter((e=>void 0!==e.fastOr)).length){let n=e.reg.findIndex((e=>void 0!==e.fastOr));Object.keys(e.reg[n].fastOr).forEach((r=>{let a=Object.assign({},e);a.reg=a.reg.slice(0),a.reg[n]=Object.assign({},a.reg[n]),a.reg[n].word=r,delete a.reg[n].operator,delete a.reg[n].fastOr,t.push(a)}))}return t}(e);t.length>0?Fi=Fi.concat(t):Fi.push(e)})),Fi.forEach((e=>(e.required=function(e){let t=[],n=[];return e.forEach((e=>{!0!==e.optional&&!0!==e.negative&&(void 0!==e.tag&&t.push(e.tag),void 0!==e.word&&n.push(e.word))})),{tags:Ni(t),words:Ni(n)}}(e.reg),e)));const Ci=Fi,Bi=hi,Gi=ci,zi=function(e){Ci.forEach((t=>{let n=[];t.required.words.forEach((t=>{n.push(e._cache.words[t]||[])})),t.required.tags.forEach((t=>{n.push(e._cache.tags[t]||[])}));let r=function(e){if(0===e.length)return[];let t={};e.forEach((e=>{e=Bi(e);for(let n=0;nt[n]===e.length)),n=n.map((e=>Number(e))),n}(n);if(0===r.length)return;let a=r.map((t=>e.list[t])),i=e.buildFrom(a).match(t.reg,t.group);i.found&&(!0===t.safe?i.tagSafe(t.tag,t.reason):i.tag(t.tag,t.reason))}))},Ii=dn,Oi=Gn,Ti=li,Vi=function(e){return zi(e),Gi(e),e};var Mi=function(e){let t=e.termList();return e=Ii(e,t),e=Oi(e,t),(e=Ti(e)).cache(),(e=Vi(e)).uncache(),e.world.taggers.forEach((t=>{t(e)})),e},Ji=function(e){class t extends e{stripPeriods(){return this.termList().forEach((e=>{!0===e.tags.Abbreviation&&e.next&&(e.post=e.post.replace(/^\./,""));let t=e.text.replace(/\./,"");e.set(t)})),this}addPeriods(){return this.termList().forEach((e=>{e.post=e.post.replace(/^\./,""),e.post="."+e.post})),this}}return t.prototype.unwrap=t.prototype.stripPeriods,e.prototype.abbreviations=function(e){let n=this.match("#Abbreviation");return"number"==typeof e&&(n=n.get(e)),new t(n.list,this,this.world)},e};const Li=/\./;var Si=function(e){class t extends e{stripPeriods(){return this.termList().forEach((e=>{let t=e.text.replace(/\./g,"");e.set(t)})),this}addPeriods(){return this.termList().forEach((e=>{let t=e.text.replace(/\./g,"");t=t.split("").join("."),!1===Li.test(e.post)&&(t+="."),e.set(t)})),this}}return t.prototype.unwrap=t.prototype.stripPeriods,t.prototype.strip=t.prototype.stripPeriods,e.prototype.acronyms=function(e){let n=this.match("#Acronym");return"number"==typeof e&&(n=n.get(e)),new t(n.list,this,this.world)},e},_i=function(e){return e.prototype.clauses=function(t){let n=this.if("@hasComma").notIf("@hasComma @hasComma").notIf("@hasComma . .? (and|or) .").notIf("(#City && @hasComma) #Country").notIf("(#WeekDay && @hasComma) #Date").notIf("(#Date && @hasComma) #Year").notIf("@hasComma (too|also)$").match("@hasComma"),r=this.splitAfter(n),a=r.quotations();r=r.splitOn(a);let i=r.parentheses();r=r.splitOn(i);let s=r.if("#Copula #Adjective #Conjunction (#Pronoun|#Determiner) #Verb").match("#Conjunction");r=r.splitBefore(s);let o=r.if("if .{2,9} then .").match("then");r=r.splitBefore(o),r=r.splitBefore("as well as ."),r=r.splitBefore("such as ."),r=r.splitBefore("in addition to ."),r=r.splitAfter("@hasSemicolon"),r=r.splitAfter("@hasDash");let l=r.filter((e=>e.wordCount()>5&&e.match("#Verb+").length>=2));if(l.found){let e=l.splitAfter("#Noun .* #Verb .* #Noun+");r=r.splitOn(e.eq(0))}return"number"==typeof t&&(r=r.get(t)),new e(r.list,this,this.world)},e},Ki=function(e){class t extends e{constructor(e,t,n){super(e,t,n),this.contracted=null}expand(){return this.list.forEach((e=>{let t=e.terms(),n=t[0].isTitleCase();t.forEach(((e,n)=>{e.set(e.implicit||e.text),e.implicit=void 0,n{let r=t(n).beforeLast;r.append(e),r.termList(0).addPunctuation(",")})),this}remove(e){return this.items().if(e).remove()}hasOxfordComma(){return this.filter((e=>t(e).hasOxford))}addOxfordComma(){let e=this.items(),t=e.eq(e.length-2);return t.found&&!1===t.has("@hasComma")&&t.post(", "),this}removeOxfordComma(){let e=this.items(),t=e.eq(e.length-2);return t.found&&!0===t.has("@hasComma")&&t.post(" "),this}}return n.prototype.things=n.prototype.items,e.prototype.lists=function(e){let t=this.if("@hasComma+ .? (and|or) not? ."),r=t.match("(#Noun|#Adjective|#Determiner|#Article)+ #Conjunction not? (#Article|#Determiner)? #Adjective? #Noun+").if("#Noun"),a=t.match("(#Adjective|#Adverb)+ #Conjunction not? #Adverb? #Adjective+"),i=t.match("(#Verb|#Adverb)+ #Conjunction not? #Adverb? #Verb+"),s=r.concat(a);return s=s.concat(i),s=s.if("@hasComma"),"number"==typeof e&&(s=t.get(e)),new n(s.list,this,this.world)},e};const Wi={hour:"an",heir:"an",heirloom:"an",honest:"an",honour:"an",honor:"an",uber:"an"},Ri={a:!0,e:!0,f:!0,h:!0,i:!0,l:!0,m:!0,n:!0,o:!0,r:!0,s:!0,x:!0},Ui=[/^onc?e/i,/^u[bcfhjkqrstn][aeiou]/i,/^eul/i],Qi={isSingular:[/(ax|test)is$/i,/(octop|vir|radi|nucle|fung|cact|stimul)us$/i,/(octop|vir)i$/i,/(rl)f$/i,/(alias|status)$/i,/(bu)s$/i,/(al|ad|at|er|et|ed|ad)o$/i,/(ti)um$/i,/(ti)a$/i,/sis$/i,/(?:(^f)fe|(lr)f)$/i,/hive$/i,/(^aeiouy|qu)y$/i,/(x|ch|ss|sh|z)$/i,/(matr|vert|ind|cort)(ix|ex)$/i,/(m|l)ouse$/i,/(m|l)ice$/i,/(antenn|formul|nebul|vertebr|vit)a$/i,/.sis$/i,/^(?!talis|.*hu)(.*)man$/i],isPlural:[/(antenn|formul|nebul|vertebr|vit)ae$/i,/(octop|vir|radi|nucle|fung|cact|stimul)i$/i,/men$/i,/.tia$/i,/(m|l)ice$/i]},Zi=/s$/,Xi={he:"his",she:"hers",they:"theirs",we:"ours",i:"mine",you:"yours",her:"hers",their:"theirs",our:"ours",my:"mine",your:"yours"},Yi=function(e){return!0===e.has("#Plural")||!0!==e.has("(#Pronoun|#Place|#Value|#Person|#Uncountable|#Month|#WeekDay|#Holiday|#Possessive)")},eo=function(e){if(e.has("#Person")||e.has("#Place"))return"";if(e.has("#Plural"))return"the";let t=e.text("normal").trim();if(Wi.hasOwnProperty(t))return Wi[t];let n=t.substr(0,1);if(e.has("^@isAcronym")&&Ri.hasOwnProperty(n))return"an";for(let e=0;et.test(e)))&&(!0===Zi.test(e)||!!Qi.isPlural.find((t=>t.test(e)))||null)},ro=function(e){let t=e.text("text").trim();return Xi.hasOwnProperty(t)?(e.replaceWith(Xi[t],!0),void e.tag("Possessive","toPossessive")):/s$/.test(t)?(t+="'",e.replaceWith(t,!0),void e.tag("Possessive","toPossessive")):(t+="'s",e.replaceWith(t,!0),void e.tag("Possessive","toPossessive"))},ao=function(e){let t={main:e};if(e.has("#Noun (of|by|for) .")){let n=e.splitAfter("[#Noun+]",0);t.main=n.eq(0),t.post=n.eq(1)}return t},no={json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0];r.article=eo(t),n.push(r)})),null!==t?n[t]:n},adjectives:function(){let e=this.lookAhead("^(that|who|which)? (was|is|will)? be? #Adverb? #Adjective+");return e=e.concat(this.lookBehind("#Adjective+ #Adverb?$")),e=e.match("#Adjective"),e.sort("index")},isPlural:function(){return this.if("#Plural")},hasPlural:function(){return this.filter((e=>Yi(e)))},toPlural:function(e){let t=this.world.transforms.toPlural;return this.forEach((n=>{if(n.has("#Plural")||!1===Yi(n))return;let r=ao(n).main,a=r.text("reduced");if((r.has("#Singular")||!0!==to(a))&&(a=t(a,this.world),r.replace(a).tag("#Plural"),e)){let e=r.lookBefore("(an|a) #Adjective?$").not("#Adjective");!0===e.found&&e.remove()}})),this},toSingular:function(e){let t=this.world.transforms.toSingular;return this.forEach((n=>{if(n.has("^#Singular+$")||!1===Yi(n))return;let r=ao(n).main,a=r.text("reduced");if((r.has("#Plural")||!0===to(a))&&(a=t(a,this.world),r.replace(a).tag("#Singular"),e)){let e=n,t=n.lookBefore("#Adjective");t.found&&(e=t);let r=eo(e);e.insertBefore(r)}})),this},toPossessive:function(){return this.forEach((e=>{ro(e)})),this}};var io=function(e){class t extends e{}return Object.assign(t.prototype,no),e.prototype.nouns=function(e,n={}){let r=this.match("(#City && @hasComma) (#Region|#Country)"),a=this.not(r).splitAfter("@hasComma");a=a.concat(r);let i=a.quotations();return i.found&&(a=a.splitOn(i.eq(0))),a=a.match("#Noun+ (of|by)? the? #Noun+?"),!0!==n.keep_anaphora&&(a=a.not("#Pronoun"),a=a.not("(there|these)"),a=a.not("(#Month|#WeekDay)"),a=a.not("(my|our|your|their|her|his)")),a=a.not("(of|for|by|the)$"),"number"==typeof e&&(a=a.get(e)),new t(a.list,this,this.world)},e};const oo=/\(/,so=/\)/;var lo=function(e){class t extends e{unwrap(){return this.list.forEach((e=>{let t=e.terms(0);t.pre=t.pre.replace(oo,"");let n=e.lastTerm();n.post=n.post.replace(so,"")})),this}}return e.prototype.parentheses=function(e){let n=[];return this.list.forEach((e=>{let t=e.terms();for(let r=0;r{e.terms().forEach((e=>{let t=e.text.replace(/'s$/,"");e.set(t||e.text)}))})),this}}return e.prototype.possessives=function(e){let n=this.match("#Noun+? #Possessive");return"number"==typeof e&&(n=n.get(e)),new t(n.list,this,this.world)},e};const co={'"':'"',""":""","'":"'","“":"”","‘":"’","‟":"”","‛":"’","„":"”","⹂":"”","‚":"’","«":"»","‹":"›","‵":"′","‶":"″","‷":"‴","〝":"〞","`":"´","〟":"〞"},ho=RegExp("("+Object.keys(co).join("|")+")");var go=function(e){class t extends e{unwrap(){return this}}return e.prototype.quotations=function(e){let n=[];return this.list.forEach((e=>{let t=e.terms();for(let r=0;r{let t=!1,n=wo(e),r=e.negative.found;e.verb.lookBehind("i (#Adverb|#Verb)?$").found&&(t=!0);let a={PastTense:"was",PresentTense:"is",FutureTense:"will be",Infinitive:"is",Gerund:"being",Actor:"",PerfectTense:"been",Pluperfect:"been"};return n&&(a.PastTense="were",a.PresentTense="are",a.Infinitive="are"),!0===t&&(a.PastTense="was",a.PresentTense="am",a.Infinitive="am"),r&&(a.PastTense+=" not",a.PresentTense+=" not",a.FutureTense="will not be",a.Infinitive+=" not",a.PerfectTense="not "+a.PerfectTense,a.Pluperfect="not "+a.Pluperfect,a.Gerund="not "+a.Gerund),a},Do=function(e){let t=e.verb.text();return{PastTense:t+" have",PresentTense:t,FutureTense:t,Infinitive:t}},$o=mo;var Po=function(e,t){let n=e.verb;if(n.has("#Copula")||"be"===n.out("normal")&&e.auxiliary.has("will"))return Ao(e);if(e.auxiliary.has("are")&&n.has("#Gerund")){let n=e.original.clone(),r=n.clone().replace("are","were"),a=n.clone().replace("are","will be"),i=ko(e,t);return{PastTense:r.text(),PresentTense:n.text(),FutureTense:a.text(),Infinitive:i}}if(n.has("#Modal"))return Do(e);let r=ko(e,t);if(!r)return{};let a=t.transforms.conjugate(r,t);a.Infinitive=r;let i=$o(e);!0===i&&(a.PresentTense=a.Infinitive);let s=e.verb.termList(0).hasHyphen();if(e.particle.found){let t=e.particle.text(),n=!0===s?"-":" ";Object.keys(a).forEach((e=>a[e]+=n+t))}const o=e.negative.found;return a.FutureTense=a.FutureTense||"will "+a.Infinitive,o&&(a.PastTense="did not "+a.Infinitive,a.FutureTense="will not "+a.Infinitive,i?(a.PresentTense="do not "+a.Infinitive,a.Infinitive="do not "+a.Infinitive):(a.PresentTense="does not "+a.Infinitive,a.Infinitive="does not "+a.Infinitive),a.Gerund="not "+a.Gerund),a};const Eo=Po;var Ho={useParticiple:function(e){return!!e.auxiliary.has("(could|should|would|may|can|must)")||!!e.auxiliary.has("am .+? being")||!!e.auxiliary.has("had .+? been")},toParticiple:function(e,t){if(e.auxiliary.has("(have|had)")&&e.verb.has("#Participle"))return;let n=Eo(e,t),r=n.Participle||n.PastTense;r&&e.verb.replaceWith(r,!1),e.auxiliary.has("am .+? being")&&(e.auxiliary.remove("am"),e.auxiliary.replace("being","have been")),e.auxiliary.has("have")||e.auxiliary.append("have"),e.verb.tag("Participle","toParticiple"),e.auxiliary.replace("can","could"),e.auxiliary.replace("be have","have been"),e.auxiliary.replace("not have","have not"),e.auxiliary.tag("Auxiliary")}};const jo=function(e,t){let n=e.verb;if(!e.negative.found){if(e.auxiliary.found)return e.auxiliary.eq(0).append("not"),void(e.auxiliary.has("#Modal have not")&&e.auxiliary.replace("have not","not have"));if(n.has("(#Copula|will|has|had|do)"))n.append("not");else{if(n.has("#PastTense")){let r=fo(e,t);return n.replaceWith(r,!0),void n.prepend("did not")}if(n.has("#PresentTense")){let r=fo(e,t);return n.replaceWith(r,!0),void(bo(e)?n.prepend("do not"):n.prepend("does not"))}if(n.has("#Gerund")){let r=fo(e,t);return n.replaceWith(r,!0),void n.prepend("not")}bo(e)?n.prepend("does not"):n.prepend("do not")}}},No=function(e){let t={adverb:e.match("#Adverb+"),negative:e.match("#Negative"),auxiliary:e.match("#Auxiliary+").not("(#Negative|#Adverb)"),particle:e.match("#Particle"),verb:e.match("#Verb+").not("(#Adverb|#Negative|#Auxiliary|#Particle)"),original:e,subject:vo(e)};if(t.verb.has("(#PresentTense|#PastTense|#Infinitive) #Gerund$")&&(t.verb=t.verb.not("#Gerund$")),!t.verb.found)return Object.keys(t).forEach((e=>{t[e]=t[e].not(".")})),t.verb=e,t;if(t.adverb&&t.adverb.found){let n=t.adverb.text("reduced")+"$";e.has(n)&&(t.adverbAfter=!0)}return t},xo=mo,Fo=yo,Co=Po,{toParticiple:Bo,useParticiple:Go}=Ho,zo=function(e){return e.auxiliary.remove("(will|are|am|being)"),e.auxiliary.remove("(did|does)"),e.auxiliary.remove("(had|has|have)"),e.particle.remove(),e.negative.remove(),e},Io={json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=No(t);r.parts={},Object.keys(a).forEach((e=>{a[e]&&"Doc"===a[e].isA?r.parts[e]=a[e].text("normal"):r.parts[e]=a[e]})),r.isNegative=t.has("#Negative"),r.conjugations=Co(a,this.world),n.push(r)})),null!==t?n[t]:n},adverbs:function(){let e=[];this.forEach((t=>{let n=No(t).adverb;n.found&&(e=e.concat(n.list))}));let t=this.lookBehind("#Adverb+$");return t.found&&(e=t.list.concat(e)),t=this.lookAhead("^#Adverb+"),t.found&&(e=e.concat(t.list)),this.buildFrom(e)},isPlural:function(){let e=[];return this.forEach((t=>{let n=No(t);!0===xo(n,this.world)&&e.push(t.list[0])})),this.buildFrom(e)},isSingular:function(){let e=[];return this.forEach((t=>{let n=No(t);!1===xo(n,this.world)&&e.push(t.list[0])})),this.buildFrom(e)},conjugate:function(){let e=[];return this.forEach((t=>{let n=No(t),r=Co(n,this.world);e.push(r)})),e},toPastTense:function(){return this.forEach((e=>{let t=No(e);if(Go(t))return void Bo(t,this.world);if(e.has("#Imperative"))return;if(e.has("be")&&e.lookBehind("to$").found)return;if(t.verb.has("#Gerund")&&t.auxiliary.has("(is|will|was)"))return void e.replace("is","was");let n=Co(t,this.world).PastTense;n&&(t=zo(t),t.verb.replaceWith(n,!1),t.auxiliary.remove("(do|did|will)"))})),this},toPresentTense:function(){return this.forEach((e=>{if(e.has("#Imperative"))return;let t=No(e),n=Co(t,this.world),r=n.PresentTense;if(e.lookBehind("(i|we) (#Adverb|#Verb)?$").found&&(r=n.Infinitive),r){if(t.auxiliary.has("(have|had) been"))return t.auxiliary.replace("(have|had) been","am being"),void(n.Particle&&(r=n.Particle||n.PastTense));t.verb.replaceWith(r,!1),t.verb.tag("PresentTense"),t=zo(t),t.auxiliary.remove("#Modal"),t.auxiliary.remove("(do|did|will)")}})),this},toFutureTense:function(){return this.forEach((e=>{let t=No(e);if(Go(t))return;if(e.has("#Imperative"))return;let n=Co(t,this.world).FutureTense;n&&(t=zo(t),t.auxiliary.remove("#Modal"),t.verb.replaceWith(n,!1),t.verb.tag("FutureTense"),t.auxiliary.remove("(do|did|will)"))})),this},toInfinitive:function(){return this.forEach((e=>{let t=No(e),n=Co(t,this.world).Infinitive;n&&(e.replaceWith(n,!1),e.tag("Infinitive"))})),this},toGerund:function(){return this.forEach((e=>{let t=No(e),n=Co(t,this.world).Gerund;n&&(e.replaceWith(n,!1),e.tag("Gerund"))})),this},toParticiple:function(){return this.forEach((e=>{let t=No(e),n=!t.auxiliary.found;Bo(t,this.world),n&&(t.verb.prepend(t.auxiliary.text()),t.auxiliary.remove())})),this},isNegative:function(){return this.if("#Negative")},isPositive:function(){return this.ifNo("#Negative")},isImperative:function(){return this.if("#Imperative")},toNegative:function(){return this.list.forEach((e=>{let t=this.buildFrom([e]),n=No(t);jo(n,t.world)})),this},toPositive:function(){let e=this.match("do not #Verb");return e.found&&e.remove("do not"),this.remove("#Negative")},subject:function(){let e=[];return this.forEach((t=>{let n=Fo(t);n.list[0]&&e.push(n.list[0])})),this.buildFrom(e)}},Oo=Ia,To=[Ji,Si,_i,Ki,qi,io,lo,uo,go,function(e){class t extends e{}return Object.assign(t.prototype,Io),t.prototype.negate=t.prototype.toNegative,e.prototype.verbs=function(e){let n=this.match("(#Adverb|#Auxiliary|#Verb|#Negative|#Particle)+");n=n.not("^#Adverb+"),n=n.not("#Adverb+$");let r=n.match("(#Adverb && @hasComma) #Adverb"),a=n.not(r).splitAfter("@hasComma");return a=a.concat(r),a.sort("index"),a=a.if("#Verb"),a.has("(is|was)$")&&(a=a.splitBefore("(is|was)$")),a.has("#PresentTense #Adverb #PresentTense")&&(a=a.splitBefore("#Adverb #PresentTense")),"number"==typeof e&&(a=a.get(e)),new t(a.list,this,this.world)},e},function(e){class t extends e{}return e.prototype.people=function(e){let n=this.splitAfter("@hasComma");return n=n.match("#Person+"),"number"==typeof e&&(n=n.get(e)),new t(n.list,this,this.world)},e}],Vo={misc:Ga,selections:Ia},Mo=Mi,Jo=xt,Lo=function(e){return Object.keys(Oo).forEach((t=>e.prototype[t]=Oo[t])),To.forEach((t=>t(e))),e};class So{constructor(e,t,n){this.list=e,Object.defineProperty(this,"from",{enumerable:!1,value:t,writable:!0}),void 0===n&&void 0!==t&&(n=t.world),Object.defineProperty(this,"world",{enumerable:!1,value:n,writable:!0}),Object.defineProperty(this,"_cache",{enumerable:!1,writable:!0,value:{}}),Object.defineProperty(this,"found",{get:()=>this.list.length>0}),Object.defineProperty(this,"length",{get:()=>this.list.length}),Object.defineProperty(this,"isA",{get:()=>"Doc"})}tagger(){return Mo(this)}pool(){return this.list.length>0?this.list[0].pool:this.all().list[0].pool}}So.prototype.buildFrom=function(e){return e=e.map((e=>e.clone(!0))),new So(e,this,this.world)},So.prototype.fromText=function(e){let t=Jo(e,this.world,this.pool());return this.buildFrom(t)},Object.assign(So.prototype,Vo.misc),Object.assign(So.prototype,Vo.selections),Lo(So);const _o={untag:"unTag",and:"match",notIf:"ifNo",only:"if",onlyIf:"if"};Object.keys(_o).forEach((e=>So.prototype[e]=So.prototype[_o[e]]));const Ko=Va,qo=xt,Wo=zt,Ro=So,Uo=nt,Qo=ne$1,Zo=ot,Xo=function(e){let t=e.termList();return Ko(t,e.world),e.world.taggers.forEach((t=>{t(e)})),e},Yo=_e;var es=function e(t){let n=t;const r=function(e="",t){t&&n.addWords(t);let r=qo(e,n),a=new Ro(r,null,n);return a.tagger(),a};return r.tokenize=function(e="",t){let r=n;t&&(r=r.clone(),r.words={},r.addWords(t));let a=qo(e,r),i=new Ro(a,null,r);return(t||i.world.taggers.length>0)&&Xo(i),i},r.extend=function(e){return e(Ro,n,this,Uo,Qo,Zo),this},r.fromJSON=function(e){let t=Wo(e,n);return new Ro(t,null,n)},r.clone=function(){return e(n.clone())},r.verbose=function(e=!0){return n.verbose(e),this},r.world=function(){return n},r.parseMatch=function(e,t){return Yo(e,t)},r.version="13.11.4",r.import=r.load,r.plugin=r.extend,r}(new Rr),nlp=es,e=function(e,t){let n=e.match("#Value+? #Money+ #Currency+ (and #Money+ #Currency+)+?");return e.match("#Money").forEach((e=>{e.lookAfter("#Currency").found||(n=n.concat(e))})),"number"==typeof t&&(n=n.get(t)),n};const n="twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|fourty";var t=function(e,t){let r=e.match("#Value+");if(r.has("#NumericValue #NumericValue")&&(r.has("#Value @hasComma #Value")?r.splitAfter("@hasComma"):r.has("#NumericValue #Fraction")?r.splitAfter("#NumericValue #Fraction"):r=r.splitAfter("#NumericValue")),r.has("#Value #Value #Value")&&!r.has("#Multiple")&&r.has("("+n+") #Cardinal #Cardinal")&&(r=r.splitAfter("("+n+") #Cardinal")),r.has("#Value #Value")){r.has("#NumericValue #NumericValue")&&(r=r.splitOn("#Year")),r.has("("+n+") (eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen)")&&(r=r.splitAfter("("+n+")"));let e=r.match("#Cardinal #Cardinal");if(e.found&&!r.has("(point|decimal|#Fraction)")&&!e.has("#Cardinal (#Multiple|point|decimal)")){let t=r.has(`(one|two|three|four|five|six|seven|eight|nine) (${n})`),a=e.has("("+n+") #Cardinal"),i=e.has("#Multiple #Value");t||a||i||e.terms().forEach((e=>{r=r.splitOn(e)}))}r.match("#Ordinal #Ordinal").match("#TextValue").found&&!r.has("#Multiple")&&(r.has("("+n+") #Ordinal")||(r=r.splitAfter("#Ordinal"))),r.has("#Ordinal #Cardinal")&&(r=r.splitBefore("#Cardinal+")),r.has("#TextValue #NumericValue")&&!r.has("("+n+"|#Multiple)")&&(r=r.splitBefore("#NumericValue+"))}return r.has("#NumberRange")&&(r=r.splitAfter("#NumberRange")),"number"==typeof t&&(r=r.get(t)),r},r=function(e,t){let n=e.match("#Fraction+");return n=n.filter((e=>!e.lookBehind("#Value and$").found)),"number"==typeof t&&(n=n.eq(t)),n},a=function(e,t){let n=e.match("#Percent+");return n=n.concat(e.match("[#Cardinal] percent",0)),"number"==typeof t&&(n=n.eq(t)),n},i={ones:{zeroth:0,first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,zero:0,one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9},teens:{tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,ten:10,eleven:11,twelve:12,thirteen:13,fourteen:14,fifteen:15,sixteen:16,seventeen:17,eighteen:18,nineteen:19},tens:{twentieth:20,thirtieth:30,fortieth:40,fourtieth:40,fiftieth:50,sixtieth:60,seventieth:70,eightieth:80,ninetieth:90,twenty:20,thirty:30,forty:40,fourty:40,fifty:50,sixty:60,seventy:70,eighty:80,ninety:90},multiples:{hundredth:100,thousandth:1e3,millionth:1e6,billionth:1e9,trillionth:1e12,quadrillionth:1e15,quintillionth:1e18,sextillionth:1e21,septillionth:1e24,hundred:100,thousand:1e3,million:1e6,billion:1e9,trillion:1e12,quadrillion:1e15,quintillion:1e18,sextillion:1e21,septillion:1e24,grand:1e3}};const s=i,o=i,u=e=>{const t=[{reg:/^(minus|negative)[\s\-]/i,mult:-1},{reg:/^(a\s)?half[\s\-](of\s)?/i,mult:.5}];for(let n=0;n{if(s.ones.hasOwnProperty(e)){if(t.ones||t.teens)return!1}else if(s.teens.hasOwnProperty(e)){if(t.ones||t.teens||t.tens)return!1}else if(s.tens.hasOwnProperty(e)&&(t.ones||t.teens||t.tens))return!1;return!0},c$1=function(e){let t="0.";for(let n=0;n(e=(e=(e=(e=(e=(e=(e=e.replace(/1st$/,"1")).replace(/2nd$/,"2")).replace(/3rd$/,"3")).replace(/([4567890])r?th$/,"$1")).replace(/^[$€¥£¢]/,"")).replace(/[%$€¥£¢]$/,"")).replace(/,/g,"")).replace(/([0-9])([a-z\u00C0-\u00FF]{1,2})$/,"$1"),f=/^([0-9,\. ]+)\/([0-9,\. ]+)$/,d={"a few":3,"a couple":2,"a dozen":12,"two dozen":24,zero:0},y=e=>Object.keys(e).reduce(((t,n)=>t+e[n]),0);var p=function(e){if(!0===d.hasOwnProperty(e))return d[e];if("a"===e||"an"===e)return 1;const t=u(e);let n=null,r={},a=0,i=!1;const s=(e=t.str).split(/[ -]/);for(let e=0;e#Value+] out of every? [#Value+]");if(!0!==t.found)return null;let{num:n,den:r}=t.groups();return n&&r?(n=x(n),r=x(r),"number"==typeof n&&"number"==typeof r?{numerator:n,denominator:r}:null):null}(e)||function(e){let t=e.match("[(#Cardinal|a)+] [#Fraction+]");if(!0!==t.found)return null;let{num:n,dem:r}=t.groups();n=n.has("a")?1:x(n);let a=r.text("reduced");return b.test(a)&&(a=a.replace(b,""),r.replaceWith(a)),r=$.hasOwnProperty(a)?$[a]:x(r),"number"==typeof n&&"number"==typeof r?{numerator:n,denominator:r}:null}(e)||function(e){let t=e.match("^#Ordinal$");return!0!==t.found?null:e.lookAhead("^of .")?{numerator:1,denominator:x(t)}:null}(e)||null;return null!==t&&t.numerator&&t.denominator&&(t.decimal=t.numerator/t.denominator,t.decimal=(e=>{let t=Math.round(1e3*e)/1e3;return 0===t&&0!==e?e:t})(t.decimal)),t};const w=p,k=v;var C=function(e){let t=e.text("reduced"),n=/[0-9],[0-9]/.test(e.text("text")),r=function(e,t,n){let r=(e=e.replace(/,/g,"")).split(/^([^0-9]*)([0-9.,]*)([^0-9]*)$/);if(r&&r[2]&&t.terms().length<2){let t=parseFloat(r[2]||e);"number"!=typeof t&&(t=null);let n=r[3]||"";return"st"!==n&&"nd"!==n&&"rd"!==n&&"th"!==n||(n=""),"m"!==n&&"M"!==n||(t*=1e6,n=""),"k"!==n&&"k"!==n||(t*=1e3,n=""),{prefix:r[1]||"",num:t,suffix:n}}return null}(t,e);if(null!==r)return r.hasComma=n,r;let a=e.match("#Fraction #Fraction+$");a=!1===a.found?e.match("^#Fraction$"):a;let i=null;a.found&&(i=k(a),t=(e=(e=e.not(a)).not("and$")).text("reduced"));let s=0;return t&&(s=w(t)||0),i&&i.decimal&&(s+=i.decimal),{hasComma:n,prefix:"",num:s,suffix:""}},O=function(e){if(e<1e6)return String(e);let t;return t="number"==typeof e?e.toFixed(0):e,-1===t.indexOf("e+")?t:t.replace(".","").split("e+").reduce((function(e,t){return e+Array(t-e.length+2).join(0)}))};const V=O,F=[["ninety",90],["eighty",80],["seventy",70],["sixty",60],["fifty",50],["forty",40],["thirty",30],["twenty",20]],M=["","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],E=[[1e24,"septillion"],[1e20,"hundred sextillion"],[1e21,"sextillion"],[1e20,"hundred quintillion"],[1e18,"quintillion"],[1e17,"hundred quadrillion"],[1e15,"quadrillion"],[1e14,"hundred trillion"],[1e12,"trillion"],[1e11,"hundred billion"],[1e9,"billion"],[1e8,"hundred million"],[1e6,"million"],[1e5,"hundred thousand"],[1e3,"thousand"],[100,"hundred"],[1,"one"]],N=function(e){let t=[];if(e>100)return t;for(let n=0;n=F[n][1]&&(e-=F[n][1],t.push(F[n][0]));return M[e]&&t.push(M[e]),t};var P=function(e){if(0===e||"0"===e)return"zero";e>1e21&&(e=V(e));let t=[];e<0&&(t.push("minus"),e=Math.abs(e));let n=function(e){let t=e,n=[];return E.forEach((r=>{if(e>=r[0]){let e=Math.floor(t/r[0]);t-=e*r[0],e&&n.push({unit:r[1],count:e})}})),n}(e);for(let e=0;e1&&t.push("and")),t=t.concat(N(n[e].count)),t.push(r)}return t=t.concat((e=>{const t=["zero","one","two","three","four","five","six","seven","eight","nine"];let n=[],r=V(e).match(/\.([0-9]+)/);if(!r||!r[0])return n;n.push("point");let a=r[0].split("");for(let e=0;ee)),0===t.length&&(t[0]=""),t.join(" ")};const z=O,A=P,j={one:"first",two:"second",three:"third",five:"fifth",eight:"eighth",nine:"ninth",twelve:"twelfth",twenty:"twentieth",thirty:"thirtieth",forty:"fortieth",fourty:"fourtieth",fifty:"fiftieth",sixty:"sixtieth",seventy:"seventieth",eighty:"eightieth",ninety:"ninetieth"};var q=e=>{let t=A(e).split(" "),n=t[t.length-1];return j.hasOwnProperty(n)?t[t.length-1]=j[n]:t[t.length-1]=n.replace(/y$/,"i")+"th",t.join(" ")},S={prefixes:{"¢":"cents",$:"dollars","£":"pounds","¥":"yen","€":"euros","₡":"colón","฿":"baht","₭":"kip","₩":"won","₹":"rupees","₽":"ruble","₺":"liras"},suffixes:{"%":"percent",s:"seconds",cm:"centimetres",km:"kilometres"}};const T$1=O,R=P,L=function(e){if(!e&&0!==e)return null;let t=e%100;if(t>10&&t<20)return String(e)+"th";const n={0:"th",1:"st",2:"nd",3:"rd"};let r=z(e),a=r.slice(r.length-1,r.length);return r+=n[a]?n[a]:"th",r},W=q,B=S.prefixes,D=S.suffixes,U={usd:!0,eur:!0,jpy:!0,gbp:!0,cad:!0,aud:!0,chf:!0,cny:!0,hkd:!0,nzd:!0,kr:!0,rub:!0},K=function(e){return B.hasOwnProperty(e.prefix)&&(e.suffix+=B[e.prefix],e.prefix=""),D.hasOwnProperty(e.suffix)&&(e.suffix=D[e.suffix]),U.hasOwnProperty(e.suffix)&&(e.suffix=e.suffix.toUpperCase()),e.suffix&&(e.suffix=" "+e.suffix),e};var Y=function(e,t,n){let r=String(e.num);return t?(e=K(e),n?(r=W(r),`${e.prefix||""}${r}${e.suffix||""}`):(r=R(r),`${e.prefix||""}${r}${e.suffix||""}`)):n?(r=L(r),`${(e=K(e)).prefix||""}${r}${e.suffix||""}`):(!0===e.hasComma&&(r=e.num.toLocaleString()),r=T$1(r),`${e.prefix||""}${r}${e.suffix||""}`)};const G=C,H=function(e,t,n){if(!1===e)return;let r=t.lookAhead("^(#Unit|#Noun)");r.has("(#Address|#Money|#Percent)")||t.has("#Ordinal")||(1===n.num?r.nouns().toSingular():r.has("#Singular")&&r.nouns().toPlural())},I=Y,Q=p;let Z={json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=G(t);r.prefix=a.prefix,r.number=a.num,r.suffix=a.suffix,r.cardinal=I(a,!1,!1),r.ordinal=I(a,!1,!0),r.textCardinal=I(a,!0,!1),r.textOrdinal=I(a,!0,!0),n.push(r)})),null!==t?n[t]:n},units:function(){let e=this.lookAhead("(#Unit|#Noun)+");return e=e.splitAfter("@hasComma").first(),e=e.not("#Pronoun"),e.first()},isOrdinal:function(){return this.if("#Ordinal")},isCardinal:function(){return this.if("#Cardinal")},toNumber:function(){return this.forEach((e=>{let t=G(e);if(null===t.num)return;let n=I(t,!1,e.has("#Ordinal"));e.replaceWith(n,!0),e.tag("NumericValue")})),this},toLocaleString:function(){return this.forEach((e=>{let t=G(e);if(null===t.num)return;t.num=t.num.toLocaleString();let n=I(t,!1,e.has("#Ordinal"));e.replaceWith(n,!0)})),this},toText:function(){return this.forEach((e=>{let t=G(e);if(null===t.num)return;let n=I(t,!0,e.has("#Ordinal"));e.replaceWith(n,!0),e.tag("TextValue")})),this},toCardinal:function(e){return this.if("#Ordinal").forEach((t=>{let n=G(t);if(null===n.num)return;let r=I(n,t.has("#TextValue"),!1);if(t.has("#NumberRange")){let e=t.termList()[0];e.text&&""===e.post&&(e.post=" ")}t.replaceWith(r,!0),t.tag("Cardinal"),H(e,t,n)})),this},toOrdinal:function(){return this.if("#Cardinal").forEach((e=>{let t=G(e);if(null===t.num)return;let n=I(t,e.has("#TextValue"),!0);if(e.has("#NumberRange")){let t=e.termList()[0];t.text&&""===t.post&&(t.post=" ")}e.replaceWith(n,!0),e.tag("Ordinal");let r=this.lookAhead("^#Plural");r.found&&r.nouns().toSingular()})),this},isEqual:function(e){return this.filter((t=>G(t).num===e))},greaterThan:function(e){return this.filter((t=>G(t).num>e))},lessThan:function(e){return this.filter((t=>G(t).num{let r=G(n).num;return r>e&&r{let r=G(n);if(r.num=e,null===r.num)return;let a=I(r,n.has("#TextValue"),n.has("#Ordinal"));(n=n.not("#Currency")).replaceWith(a,!0),H(t,n,r)}))),this},add:function(e,t){return e?("string"==typeof e&&(e=Q(e)),this.forEach((n=>{let r=G(n);if(null===r.num)return;r.num+=e;let a=I(r,n.has("#TextValue"),n.has("#Ordinal"));(n=n.not("#Currency")).replaceWith(a,!0),H(t,n,r)})),this):this},subtract:function(e,t){return this.add(-1*e,t)},increment:function(e){return this.add(1,e),this},decrement:function(e){return this.add(-1,e),this},romanNumerals:function(e){let t=this.match("#RomanNumeral").numbers();return"number"==typeof e&&(t=t.get(e)),t},normalize:function(){const e={"%":!0};return this.forEach((t=>{let n=G(t);if(null!==n.num&&n.suffix&&!0!==e[n.suffix]){let e=n.prefix||"";t=t.replaceWith(e+n.num+" "+n.suffix)}})),this},get:function(e){let t=[];return this.forEach((e=>{t.push(G(e).num)})),void 0!==e?t[e]||null:t||null}};Z.toNice=Z.toLocaleString,Z.isBetween=Z.between,Z.minus=Z.subtract,Z.plus=Z.add,Z.equals=Z.isEqual;var J=Z;const X=C,_=function(e){let t=X(e).num;return"number"==typeof t?t/100:null};var ee={get:function(e){let t=[];return this.forEach((e=>{let n=_(e);null!==n&&t.push(n)})),void 0!==e?t[e]||null:t||null},json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=_(t);if(r.number=a,null!==a){let e=100*a;r.textNumber=`${e} percent`,r.cardinal=`${e}%`}n.push(r)})),null!==t?n[t]||{}:n},toFraction:function(){return this.forEach((e=>{let t=_(e);if(null!==t){t*=100,t=Math.round(100*t)/100;let n=`${t}/100`;this.replace(e,n)}})),this}},ne=[{dem:"american",name:"dollar",iso:"usd",sub:"cent",sym:["$","US$","U$"]},{name:"euro",iso:"eur",sub:"cent",sym:["€"]},{dem:"british",name:"pound",iso:"gbp",sub:"penny",alias:{sterling:!0},sym:["£"]},{name:"renminbi",iso:"cny",plural:"yuán",alias:{yuan:!0},sym:["元"]},{dem:"japanese",name:"yen",iso:"jpy",sub:"sen",sym:["¥","円","圓"]},{dem:"swedish",name:"krona",iso:"sek",sub:"öre",alias:{ore:!0,kronor:!0},sym:["kr"]},{dem:"estonian",name:"kroon",iso:"eek",sub:"sent",sym:["kr"]},{dem:"norwegian",name:"krone",iso:"nok",sub:"øre",sym:["kr"]},{dem:"icelandic",name:"króna",iso:"isk",sym:["kr"]},{dem:"danish",name:"krone",iso:"dkk",sub:"øre",sym:["kr."]},{dem:"zambian",name:"kwacha",iso:"zmw",sub:"ngwee",sym:["K"]},{dem:"malawian",name:"kwacha",iso:"mwk",sub:"tambala",sym:["K"]},{dem:"greek",name:"drachma",iso:"grd",sub:"leptοn",sym:["Δρχ.","Δρ.","₯"]},{dem:"eastern caribbean",name:"dollar",iso:"xcd",sub:"cent",sym:["$"]},{dem:"finnish",name:"markka",iso:"fim",sub:"penni",sym:["mk"]},{dem:"polish",name:"złoty",iso:"pln",sub:"grosz",sym:["zł"]},{dem:"slovenian",name:"tolar",iso:"sit",sub:"stotin",sym:[]},{dem:"australian",name:"dollar",iso:"aud",sub:"cent",sym:["$","A$","AU$"]},{dem:"deutsche",name:"mark",iso:"dem",sub:"pfennig",sym:["DM"]},{dem:"thai",name:"baht",iso:"thb",sub:"satang",sym:["฿"]},{dem:"canadian",name:"dollar",iso:"cad",sub:"cent",sym:["$","Can$","C$","CA$","CAD"]},{dem:"mexican",name:"peso",iso:"mxn",sub:"centavo",sym:["$","Mex$"]},{dem:"spanish",name:"peseta",iso:"esp",sub:"céntimo",sym:["Pta"]},{dem:"new zealand",name:"dollar",iso:"nzd",sub:"cent",sym:["$","NZ$"]},{dem:"chilean",name:"peso",iso:"clp",sub:"centavo",sym:["Cifrão","$"]},{dem:"nigerian",name:"naira",iso:"ngn",sub:"kobo",sym:["₦"]},{dem:"austrian",name:"schilling",iso:"ats",sub:"groschen",sym:["S","öS"]},{dem:"guatemalan",name:"quetzal",iso:"gtq",sub:"centavo",sym:["Q"]},{dem:"philippine",name:"peso",iso:"php",sub:"sentimo",sym:["₱"]},{dem:"hungarian",name:"forint",iso:"huf",sym:["Ft"]},{dem:"russian",name:"ruble",iso:"rub",sub:"kopeyka",sym:["₽","руб","р."]},{dem:"kuwaiti",name:"dinar",iso:"kwd",sub:"fils",sym:["د.ك","KD"]},{dem:"israeli",name:"new shekel",iso:"ils",sub:"agora",sym:["₪"]},{dem:"latvian",name:"lats",iso:"lvl",sub:"santīms",sym:["Ls"]},{dem:"kazakhstani",name:"tenge",iso:"kzt",sub:"tıyn",sym:["₸"]},{dem:"iraqi",name:"dinar",iso:"iqd",sub:"fils",sym:["د.ع"]},{dem:"bahamian",name:"dollar",iso:"bsd",sub:"cent",sym:["$","B$"]},{dem:"seychellois",name:"rupee",iso:"scr",sub:"cent",sym:["SCR","SR"]},{dem:"albanian",name:"lek",iso:"all",sub:"qindarkë",sym:["L"]},{dem:"bulgarian",name:"lev",iso:"bgn",sub:"stotinka",sym:["лв."]},{dem:"irish",name:"pound",iso:"iep",sym:["£","IR£"]},{name:"cfp franc",iso:"xpf",sym:["f"]},{dem:"south african",name:"rand",iso:"zar",sub:"cent",sym:["R"]},{dem:"south korean",name:"won",iso:"krw",sub:"jeon",plural:"won",sym:["₩"]},{dem:"north korean",name:"won",iso:"kpw",sub:"chon",plural:"won",sym:["₩"]},{dem:"portuguese",name:"escudo",iso:"pte",sub:"centavo",sym:[]},{dem:"ghanaian",name:"cedi",iso:"ghs",sub:"pesewa",sym:["GH₵"]},{dem:"hong kong",name:"dollar",iso:"hkd",sub:"毫",sym:["$"]},{dem:"new taiwan",name:"dollar",iso:"twd",sub:"dime",sym:["NT$"]},{dem:"east german",name:"mark",iso:"ddm",sub:"pfennig",sym:["M"]},{dem:"namibian",name:"dollar",iso:"nad",sub:"cent",sym:["$"]},{dem:"malaysian",name:"ringgit",iso:"myr",sub:"sen",sym:["RM"]},{dem:"swiss",name:"franc",iso:"chf",sym:["Rp."]},{dem:"panamanian",name:"balboa",iso:"pab",sub:"centésimo",sym:["B/."]},{dem:"indonesian",name:"rupiah",iso:"idr",sub:"sen",sym:["Rp"]},{dem:"brunei",name:"dollar",iso:"bnd",sub:"sen",sym:["$","B$"]},{dem:"venezuelan",name:"bolívar",iso:"vef",sub:"céntimo",sym:["Bs.F","Bs."]},{dem:"macedonian",name:"denar",iso:"mkd",sub:"deni",sym:["den"]},{dem:"mauritanian",name:"ouguiya",iso:"mru",sub:"khoums",sym:["UM"]},{dem:"argentine",name:"peso",iso:"ars",sub:"centavo",sym:["$"]},{dem:"libyan",name:"dinar",iso:"lyd",sub:"dirham",sym:["LD","ل.د"]},{dem:"jordanian",name:"dinar",iso:"jod",sub:"dirham",sym:["د.أ"]},{dem:"french",name:"franc",iso:"frf",sub:"centime",sym:["F","Fr","FF","₣"]},{dem:"syrian",name:"pound",iso:"syp",sub:"piastre",sym:["LS","£S"]},{dem:"belize",name:"dollar",iso:"bzd",sub:"cent",sym:["$"]},{dem:"saudi",name:"riyal",iso:"sar",sub:"halalah",sym:["SAR","ر.س"," ﷼"]},{dem:"surinamese",name:"dollar",iso:"srd",sub:"cent",sym:["$"]},{dem:"singapore",name:"dollar",iso:"sgd",sub:"cent",sym:["S$","$"]},{dem:"nepalese",name:"rupee",iso:"npr",sub:"paisa",sym:["रु ₨","Re"]},{dem:"nicaraguan",name:"córdoba",iso:"nio",sub:"centavo",sym:["C$"]},{dem:"bangladeshi",name:"taka",iso:"bdt",sub:"poysha",sym:["৳"]},{dem:"indian",name:"rupee",iso:"inr",sub:"paisa",sym:["₹"]},{dem:"maldivian",name:"rufiyaa",iso:"mvr",sub:"laari",sym:["Rf","MRf","MVR",".ރ "]},{dem:"sri lankan",name:"rupee",iso:"lkr",sub:"cents",sym:["Rs","රු","ரூ"]},{dem:"bhutanese",name:"ngultrum",iso:"btn",sub:"chhertum",sym:["Nu."]},{dem:"turkish",name:"lira",iso:"try",sub:"kuruş",sym:["YTL"]},{dem:"serbian",name:"dinar",iso:"rsd",sub:"para",sym:["din","дин"]},{dem:"bosnia and herzegovina",name:"convertible mark",iso:"bam",sub:"fening",sym:["KM"]},{dem:"botswana",name:"pula",iso:"bwp",sub:"thebe",sym:["p"]},{dem:"swazi",name:"lilangeni",iso:"szl",sub:"cent",sym:["L","E"]},{dem:"lithuanian",name:"litas",iso:"ltl",sub:"centas",sym:["Lt","ct"]},{dem:"mauritian",name:"rupee",iso:"mur",sub:"cent",sym:["₨"]},{dem:"pakistani",name:"rupee",iso:"pkr",sub:"paisa",sym:["₨"]},{dem:"maltese",name:"lira",iso:"mtl",sub:"cent",sym:["₤","Lm"]},{dem:"cypriot",name:"pound",iso:"cyp",sub:"cent",sym:["£"]},{dem:"moldovan",name:"leu",iso:"mdl",sym:["l"]},{dem:"croatian",name:"kuna",iso:"hrk",sub:"lipa",sym:["kn"]},{dem:"afghan",name:"afghani",iso:"afn",sub:"pul",sym:["؋","Af","Afs"]},{dem:"ecuadorian",name:"sucre",iso:"ecs",sub:"centavo",sym:["S/."]},{dem:"sierra leonean",name:"leone",iso:"sll",sub:"cent",sym:["Le"]}];const te=ne,re=C,ae={};let ie={};te.forEach((e=>{e.sym.forEach((t=>{ae[t]=ae[t]||e.iso})),ae[e.iso]=ae[e.iso]||e.iso,e.sub&&(ie[e.sub]=!0)}));let se=`(${Object.keys(ie).join("|")})`;const oe=Y,ue=function(e){let t=0,n=e.match(`and #Money+ ${se}`);if(n.found){e=e.not(n);let r=re(n.match("#Value+"));r&&r.num&&(t=r.num/100)}let r=re(e),a=r.num||0;a+=t;let i=((s=r).suffix&&ae.hasOwnProperty(s.suffix)?te.find((e=>e.iso===ae[s.suffix])):s.prefix&&ae.hasOwnProperty(s.prefix)?te.find((e=>e.iso===ae[s.prefix])):null)||function(e){let t=e.match("#Currency+");t.nouns().toSingular();let n=t.text("reduced");return te.find((e=>(n===`${e.dem} ${e.name}`||n===e.iso||n===e.sub||n===e.name||!(!e.alias||!0!==e.alias[n]))&&e))}(e)||{};var s;let o="";return i&&i.sym&&(o=i.sym[0],a&&e.has(`${se}`)&&(a/=100)),{num:a,iso:i.iso,demonym:i.dem,currency:i.name,plural:i.plural,symbol:o}},le=function(e=""){return e.replace(/\w\S*/g,(function(e){return e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()}))};var me$1={get:function(e){let t=[];return this.forEach((e=>{t.push(ue(e))})),void 0!==e?t[e]||null:t||null},currency:function(e){let t=[];return this.forEach((e=>{let n=ue(e);n&&t.push(n)})),"number"==typeof e?t[e]||null:t||null},json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=ue(t);if(r.number=a.num,a.iso&&(r.iso=a.iso.toUpperCase(),r.symbol=a.symbol,r.currency=le(a.demonym)+" "+le(a.currency)),r.textFmt=oe(a,!0,!1),a.currency){let e=a.currency;1!==a.num&&(e=a.plural||e+"s"),r.textFmt+=" "+e}n.push(r)})),null!==t?n[t]||{}:n}},ce={};const he=P,fe=q;ce.toText=function(e){if(!e.numerator||!e.denominator)return"";let t=he(e.numerator),n=fe(e.denominator);return 2===e.denominator&&(n="half"),t&&n?(1!==e.numerator&&(n+="s"),`${t} ${n}`):""},ce.textCardinal=function(e){return e.numerator&&e.denominator?`${he(e.numerator)} out of ${he(e.denominator)}`:""},ce.toDecimal=function(e){return e.decimal};const de=v,ye=ce,pe={get:function(e){let t=[];return this.forEach((e=>{t.push(de(e))})),void 0!==e?t[e]||null:t||null},toDecimal(){return this.forEach((e=>{let t=de(e);if(t){let n=ye.toDecimal(t);e.replaceWith(String(n),!0),e.tag("NumericValue"),e.unTag("Fraction")}})),this},json:function(e){let t=null;"number"==typeof e&&(t=e,e=null),e=e||{text:!0,normal:!0,trim:!0,terms:!0};let n=[];return this.forEach((t=>{let r=t.json(e)[0],a=de(t)||{},i=ye.toDecimal(a);r.numerator=a.numerator,r.denominator=a.denominator,r.number=i,r.textOrdinal=ye.toText(a),r.textCardinal=ye.textCardinal(a),n.push(r)})),null!==t?n[t]||{}:n},normalize:function(){return this.forEach((e=>{let t=de(e);if(t&&"number"==typeof t.numerator&&"number"==typeof t.denominator){let n=`${t.numerator}/${t.denominator}`;this.replace(e,n)}})),this},toText:function(e){let t=[];return this.forEach((e=>{let t=de(e)||{},n=ye.toText(t);e.replaceWith(n,!0),e.tag("Fraction")})),void 0!==e?t[e]:t},toPercentage:function(){return this.forEach((e=>{let t=de(e);if(t.decimal||0===t.decimal){let n=100*t.decimal;n=Math.round(100*n)/100,this.replace(e,`${n}%`)}})),this}};pe.toNumber=pe.toDecimal;var be=pe;const ge=function(e){return e.match("(hundred|thousand|million|billion|trillion|quadrillion|quintillion|sextillion|septillion)").tag("#Multiple","fraction-tagger"),e.match("[(half|quarter)] of? (a|an)",0).tag("Fraction","millionth"),e.match("#Adverb [half]",0).tag("Fraction","nearly-half"),e.match("[half] the",0).tag("Fraction","half-the"),e.match("#Value (halves|halfs|quarters)").tag("Fraction","two-halves"),e.match("a #Ordinal").tag("Fraction","a-quarter"),e.match("(#Fraction && /s$/)").lookBefore("#Cardinal+$").tag("Fraction"),e.match("[#Cardinal+ #Ordinal] of .",0).tag("Fraction","ordinal-of"),e.match("[(#NumericValue && #Ordinal)] of .",0).tag("Fraction","num-ordinal-of"),e.match("(a|one) #Cardinal?+ #Ordinal").tag("Fraction","a-ordinal"),e.match("#Cardinal+ out? of every? #Cardinal").tag("Fraction","fraction-tagger"),e},xe=function(e){const t="money-tagger";e.match("#Money and #Money #Currency?").tag("Money","money-and-money"),e.match("#Money").not("#TextValue").match("/\\.[0-9]{3}$/").unTag("#Money","three-decimal money"),e.ifNo("#Value").match("#Currency #Verb").unTag("Currency","no-currency"),e.match("#Value #Currency [and] #Value (cents|ore|centavos|sens)",0).tag("Money",t);let n=e.match("[#Value] [(mark|rand|won|rub|ore)]");return n.group("num").tag("Money",t),n.group("currency").tag("Currency",t),e};var $e=function(e){(e=xe(e)).match("the [/[0-9]+s$/]").tag("#Plural","number-tag"),e.match("half a? #Value").tag("Value","half-a-value"),e.match("#Value [and a (half|quarter)]",0).tag(["TextValue","#Fraction"],"value-and-a-half"),(e=ge(e)).match("#Cardinal and #Fraction #Fraction").tag("Value","number-tag")};const ve={mark:!0,sucre:!0,leone:!0,afghani:!0,rand:!0,try:!0,mop:!0,won:!0,all:!0,rub:!0,eek:!0,sit:!0,bam:!0,npr:!0,leu:!0};let we={kronor:"Currency"};ne.forEach((e=>{e.iso&&!ve[e.iso]&&(we[e.iso]=["Acronym","Currency"]);let t=e.name;if(t&&!ve[t]&&(we[t]="Currency",we[t+"s"]="Currency"),e.dem){let n=e.dem;we[`${n} ${t}`]="Currency",we[`${n} ${t}s`]="Currency"}e.sub&&(we[e.sub]="Currency")}));const ke=e,Ce=t,Oe=r,Ve=a,Fe=J,Me=ee,Ee=me$1,Ne=be,Pe=$e,ze={Fraction:{isA:["Value"]},Multiple:{isA:"Value"}},Ae=we;var je=function(e,t){t.addWords(Ae),t.addTags(ze),t.postProcess(Pe);class n extends e{}Object.assign(n.prototype,Fe);class r extends n{}Object.assign(r.prototype,Ee);class a extends n{}Object.assign(a.prototype,Ne);class i extends n{}Object.assign(i.prototype,Me);const s={numbers:function(e){let t=Ce(this,e);return new n(t.list,this,this.world)},percentages:function(e){let t=Ve(this,e);return new i(t.list,this,this.world)},fractions:function(e){let t=Oe(this,e);return new a(t.list,this,this.world)},money:function(e){let t=ke(this,e);return new r(t.list,this,this.world)}};return s.values=s.numbers,s.percents=s.percentages,Object.assign(e.prototype,s),e},compromise_numbers=je;nlp.extend(compromise_numbers);class Pluralize extends Text{static componentType="pluralize";static rendererType="text";static createAttributesObject(){let e=super.createAttributesObject();return e.pluralForm={createComponentOfType:"text",createStateVariable:"pluralForm",defaultValue:null,public:!0},e.basedOnNumber={createComponentOfType:"number",createStateVariable:"basedOnNumber",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePrePluralize"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valuePrePluralize:{dependencyType:"stateVariable",variableName:"valuePrePluralize"},pluralForm:{dependencyType:"stateVariable",variableName:"pluralForm"},basedOnNumber:{dependencyType:"stateVariable",variableName:"basedOnNumber"}}),definition:function({dependencyValues:e}){let t,n=nlp(e.valuePrePluralize),r=n.values().toNumber().all().terms().json();if(0===r.length)return{setValue:{value:e.valuePrePluralize}};if(null!==e.basedOnNumber&&(t=numberDesignatesPlural(e.basedOnNumber)),1===r.length)return void 0===t&&(t=!0),t?null!==e.pluralForm?{setValue:{value:e.pluralForm}}:{setValue:{value:n.nouns().toPlural().all().out("text")}}:{setValue:{value:e.valuePrePluralize}};if(void 0===t){let e=[],a=[],i=n.nouns().json();for(let[t,n]of r.entries()){let r=i[e.length];n.terms[0].tags.includes("Value")&&a.push(t),void 0!==r&&r.text===n.text&&e.push(t)}t=[];let s=n.values().numbers().json(),o=-1;for(let n of e){for(;Number(a[o+1])({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}}function numberDesignatesPlural(e){return 1!==e}class Feedback extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{updateHide:this.updateHide.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="feedback";static renderChildren=!0;static primaryStateVariableForDefinition="feedbackText";static createAttributesObject(){let e=super.createAttributesObject();return delete e.hide,e.condition={createComponentOfType:"boolean"},e.updateWith={createTargetComponentNames:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.updateWithComponentNames={chainActionOnActionOfStateVariableTargets:{triggeredAction:"updateHide"},returnDependencies:()=>({updateWith:{dependencyType:"attributeTargetComponentNames",attributeName:"updateWith"}}),definition:({dependencyValues:e})=>e.updateWith?{setValue:{updateWithComponentNames:e.updateWith.map((e=>e.absoluteName))}}:{setValue:{updateWithComponentNames:[]}}},e.hideWhenUpdated={returnDependencies:()=>({condition:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]},showFeedback:{dependencyType:"flag",flagName:"showFeedback"}}),definition:function({dependencyValues:e}){if(!e.showFeedback)return{setValue:{hideWhenUpdated:!0}};let t;return t=null!==e.condition&&!e.condition.stateValues.value,{setValue:{hideWhenUpdated:t}}}},e.hide={forRenderer:!0,defaultValue:!0,hasEssential:!0,returnDependencies:()=>({updateWith:{dependencyType:"attributeTargetComponentNames",attributeName:"updateWith"},condition:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]},showFeedback:{dependencyType:"flag",flagName:"showFeedback"}}),definition:function({dependencyValues:e}){if(e.updateWith)return{useEssentialOrDefaultValue:{hide:!0}};if(!e.showFeedback)return{setValue:{hide:!0}};let t;return t=null!==e.condition&&!e.condition.stateValues.value,{setValue:{hide:t}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.updateWith?{success:!0,instructions:[{setEssentialValue:"hide",value:e.hide}]}:{success:!1}},e.feedbackText={forRenderer:!0,defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{feedbackText:!0}})},e}async updateHide({actionId:e}){let t=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"hide",value:await this.stateValues.hideWhenUpdated}];return await this.coreFunctions.performUpdate({updateInstructions:t,actionId:e})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class CollaborateGroups extends BaseComponent{static componentType="collaborateGroups";static rendererType=void 0;static stateVariableForAttributeValue="collaborateGroups";static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"atLeastZeroPoints",componentType:"point",comparison:"atLeast",number:0}),r=breakStringsAndOthersIntoComponentsByStringCommas(),a=t.newLeaf({name:"exactlyOneString",componentType:"string",number:1,isSugar:!0,logicToWaitOnSugar:["atLeastZeroPoints"],replacementFunction:r});return t.newOperator({name:"pointsXorSugar",operator:"xor",propositions:[a,n],setAsBase:!0}),t}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.collaborateGroups={returnDependencies:()=>({pointChildren:{dependencyType:"child",childLogicName:"atLeastZeroPoints",variableNames:["xs","coords","nDimensions"]}}),definition:function({dependencyValues:e}){let t={};for(let n of e.pointChildren)if(2!==n.stateValues.nDimensions)console.warn(`invalid collaborate group: ${n.stateValues.coords.toString()}`);else{let e=n.stateValues.xs[0].evaluate_to_constant(),r=n.stateValues.xs[1].evaluate_to_constant();Number.isInteger(e)&&e>0&&Number.isInteger(r)&&r>0?(void 0===t[e]&&(t[e]=[]),t[e].push(r)):console.warn(`invalid collaborate group: ${n.stateValues.coords.toString()}`)}return{setValue:{collaborateGroups:{groups:t,matchGroup:function({groupNumber:e,numberOfGroups:n}={}){if(n>1){let r=t[n];return void 0!==r&&r.includes(e)}return!0}}}}}},e}}class CollaborateGroupSetup extends BaseComponent{static componentType="collaborateGroupSetup";static returnChildLogic(e){let t=super.returnChildLogic(e);return t.newLeaf({name:"atMostOnePossibleNumberOfGroups",componentType:"possibleNumberOfGroups",comparison:"atMost",number:1,setAsBase:!0}),t}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.possibleNumberOfGroups={returnDependencies:()=>({pngChild:{dependencyType:"child",childLogicName:"atMostOnePossibleNumberOfGroups",variableNames:["numbers"]}}),definition:function({dependencyValues:e}){return 0===e.pngChild.length?{setValue:{possibleNumberOfGroups:[1]}}:{setValue:{possibleNumberOfGroups:e.pngChild[0].stateValues.numbers}}}},e}}class ConsiderAsResponses extends BaseComponent{static componentType="considerAsResponses";static rendererType=void 0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.childrenWithNValues={returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"],variableNames:["nValues"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{childrenWithNValues:e.children}})},e.childrenAsResponses={returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"],variableNames:["value","values","componentType"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{childrenAsResponses:e.children}})},e}}class Case extends Template{static componentType="case";static createAttributesObject(){let e=super.createAttributesObject();return e.condition={createComponentOfType:"boolean"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.conditionSatisfied={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({condition:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t;return t=null===e.condition||e.condition.stateValues.value,{setValue:{conditionSatisfied:t}}}},e}static createSerializedReplacements({component:e,componentInfoObjects:t}){return e.stateValues.conditionSatisfied?super.createSerializedReplacements({component:e,componentInfoObjects:t}):{replacements:[]}}}var dist={},formats={};Object.defineProperty(formats,"__esModule",{value:!0}),formats.FORMAT_PLAIN=formats.FORMAT_HTML=formats.FORMATS=void 0;var FORMAT_HTML="html";formats.FORMAT_HTML=FORMAT_HTML;var FORMAT_PLAIN="plain";formats.FORMAT_PLAIN=FORMAT_PLAIN;var FORMATS=[FORMAT_HTML,FORMAT_PLAIN];formats.FORMATS=FORMATS;var units={};Object.defineProperty(units,"__esModule",{value:!0}),units.UNIT_WORDS=units.UNIT_WORD=units.UNIT_SENTENCES=units.UNIT_SENTENCE=units.UNIT_PARAGRAPHS=units.UNIT_PARAGRAPH=units.UNITS=void 0;var UNIT_WORDS="words";units.UNIT_WORDS=UNIT_WORDS;var UNIT_WORD="word";units.UNIT_WORD=UNIT_WORD;var UNIT_SENTENCES="sentences";units.UNIT_SENTENCES=UNIT_SENTENCES;var UNIT_SENTENCE="sentence";units.UNIT_SENTENCE=UNIT_SENTENCE;var UNIT_PARAGRAPHS="paragraphs";units.UNIT_PARAGRAPHS=UNIT_PARAGRAPHS;var UNIT_PARAGRAPH="paragraph";units.UNIT_PARAGRAPH=UNIT_PARAGRAPH;var UNITS=[UNIT_WORDS,UNIT_WORD,UNIT_SENTENCES,UNIT_SENTENCE,UNIT_PARAGRAPHS,UNIT_PARAGRAPH];units.UNITS=UNITS;var words={};Object.defineProperty(words,"__esModule",{value:!0}),words.WORDS=void 0;var WORDS=["ad","adipisicing","aliqua","aliquip","amet","anim","aute","cillum","commodo","consectetur","consequat","culpa","cupidatat","deserunt","do","dolor","dolore","duis","ea","eiusmod","elit","enim","esse","est","et","eu","ex","excepteur","exercitation","fugiat","id","in","incididunt","ipsum","irure","labore","laboris","laborum","Lorem","magna","minim","mollit","nisi","non","nostrud","nulla","occaecat","officia","pariatur","proident","qui","quis","reprehenderit","sint","sit","sunt","tempor","ullamco","ut","velit","veniam","voluptate"];words.WORDS=WORDS;var LoremIpsum={},lineEndings={};Object.defineProperty(lineEndings,"__esModule",{value:!0}),lineEndings.LINE_ENDINGS=void 0;var LINE_ENDINGS={POSIX:"\n",WIN32:"\r\n"};lineEndings.LINE_ENDINGS=LINE_ENDINGS;var generator={},util={},capitalize={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=function(e){var t=e.trim();return t.charAt(0).toUpperCase()+t.slice(1)};e.default=t}(capitalize);var isNode={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=function(){return!!e.exports};t.default=n}(isNode,isNode.exports);var isReactNative={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=function(){var e=!1;try{e="ReactNative"===navigator.product}catch(t){e=!1}return e};e.default=t}(isReactNative);var isWindows={},platforms={};Object.defineProperty(platforms,"__esModule",{value:!0}),platforms.SUPPORTED_PLATFORMS=void 0;var SUPPORTED_PLATFORMS={DARWIN:"darwin",LINUX:"linux",WIN32:"win32"};platforms.SUPPORTED_PLATFORMS=SUPPORTED_PLATFORMS,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=platforms,n=function(){var e=!1;try{e=browser$1.platform===t.SUPPORTED_PLATFORMS.WIN32}catch(t){e=!1}return e};e.default=n}(isWindows);var makeArrayOfLength={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return Array.apply(null,Array(e)).map((function(e,t){return t}))};e.default=t}(makeArrayOfLength);var makeArrayOfStrings={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t,n=(t=makeArrayOfLength)&&t.__esModule?t:{default:t};var r=function(e,t){return(0,n.default)(e).map((function(){return t()}))};e.default=r}(makeArrayOfStrings),function(e){Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"capitalize",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(e,"isNode",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(e,"isReactNative",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(e,"isWindows",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(e,"makeArrayOfLength",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(e,"makeArrayOfStrings",{enumerable:!0,get:function(){return s.default}});var t=o(capitalize),n=o(isNode.exports),r=o(isReactNative),a=o(isWindows),i=o(makeArrayOfLength),s=o(makeArrayOfStrings);function o(e){return e&&e.__esModule?e:{default:e}}}(util),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=words,n=util;function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},a=n.sentencesPerParagraph,s=void 0===a?{max:7,min:3}:a,o=n.wordsPerSentence,l=void 0===o?{max:15,min:5}:o,u=n.random;n.seed;var c=n.words,p=void 0===c?t.WORDS:c;if(r(this,e),i(this,"sentencesPerParagraph",void 0),i(this,"wordsPerSentence",void 0),i(this,"random",void 0),i(this,"words",void 0),s.min>s.max)throw new Error("Minimum number of sentences per paragraph (".concat(s.min,") cannot exceed maximum (").concat(s.max,")."));if(l.min>l.max)throw new Error("Minimum number of words per sentence (".concat(l.min,") cannot exceed maximum (").concat(l.max,")."));this.sentencesPerParagraph=s,this.words=p,this.wordsPerSentence=l,this.random=u||Math.random}var s,o,l;return s=e,(o=[{key:"generateRandomInteger",value:function(e,t){return Math.floor(this.random()*(t-e+1)+e)}},{key:"generateRandomWords",value:function(e){var t=this,r=this.wordsPerSentence,a=r.min,i=r.max,s=e||this.generateRandomInteger(a,i);return(0,n.makeArrayOfLength)(s).reduce((function(e,n){return"".concat(t.pluckRandomWord()," ").concat(e)}),"").trim()}},{key:"generateRandomSentence",value:function(e){return"".concat((0,n.capitalize)(this.generateRandomWords(e)),".")}},{key:"generateRandomParagraph",value:function(e){var t=this,r=this.sentencesPerParagraph,a=r.min,i=r.max,s=e||this.generateRandomInteger(a,i);return(0,n.makeArrayOfLength)(s).reduce((function(e,n){return"".concat(t.generateRandomSentence()," ").concat(e)}),"").trim()}},{key:"pluckRandomWord",value:function(){var e=this.words.length-1,t=this.generateRandomInteger(0,e);return this.words[t]}}])&&a(s.prototype,o),l&&a(s,l),Object.defineProperty(s,"prototype",{writable:!1}),e}(),o=s;e.default=o}(generator),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t,n=formats,r=lineEndings,a=(t=generator)&&t.__esModule?t:{default:t},i=util;function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.FORMAT_PLAIN,i=arguments.length>2?arguments[2]:void 0;if(s(this,e),this.format=r,this.suffix=i,l(this,"generator",void 0),-1===n.FORMATS.indexOf(r.toLowerCase()))throw new Error("".concat(r," is an invalid format. Please use ").concat(n.FORMATS.join(" or "),"."));this.generator=new a.default(t)}var t,u,c;return t=e,(u=[{key:"getLineEnding",value:function(){return this.suffix?this.suffix:!(0,i.isReactNative)()&&(0,i.isNode)()&&(0,i.isWindows)()?r.LINE_ENDINGS.WIN32:r.LINE_ENDINGS.POSIX}},{key:"formatString",value:function(e){return this.format===n.FORMAT_HTML?"

".concat(e,"

"):e}},{key:"formatStrings",value:function(e){var t=this;return e.map((function(e){return t.formatString(e)}))}},{key:"generateWords",value:function(e){return this.formatString(this.generator.generateRandomWords(e))}},{key:"generateSentences",value:function(e){return this.formatString(this.generator.generateRandomParagraph(e))}},{key:"generateParagraphs",value:function(e){var t=this.generator.generateRandomParagraph.bind(this.generator);return this.formatStrings((0,i.makeArrayOfStrings)(e,t)).join(this.getLineEnding())}}])&&o(t.prototype,u),c&&o(t,c),Object.defineProperty(t,"prototype",{writable:!1}),e}(),c=u;e.default=c}(LoremIpsum),function(e){Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"LoremIpsum",{enumerable:!0,get:function(){return i.default}}),e.loremIpsum=void 0;var t,n=formats,r=units,a=words,i=(t=LoremIpsum)&&t.__esModule?t:{default:t};e.loremIpsum=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.count,s=void 0===t?1:t,o=e.format,l=void 0===o?n.FORMAT_PLAIN:o,u=e.paragraphLowerBound,c=void 0===u?3:u,p=e.paragraphUpperBound,d=void 0===p?7:p,m=e.random,h=e.sentenceLowerBound,f=void 0===h?5:h,y=e.sentenceUpperBound,g=void 0===y?15:y,b=e.units,v=void 0===b?r.UNIT_SENTENCES:b,N=e.words,T=void 0===N?a.WORDS:N,C=e.suffix,A=void 0===C?"":C,V={random:m,sentencesPerParagraph:{max:d,min:c},words:T,wordsPerSentence:{max:g,min:f}},x=new i.default(V,l,A);switch(v){case r.UNIT_PARAGRAPHS:case r.UNIT_PARAGRAPH:return x.generateParagraphs(s);case r.UNIT_SENTENCES:case r.UNIT_SENTENCE:return x.generateSentences(s);case r.UNIT_WORDS:case r.UNIT_WORD:return x.generateWords(s);default:return""}}}(dist);class Lorem extends CompositeComponent{static componentType="lorem";static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.minSentencesPerParagraph={createComponentOfType:"number",createStateVariable:"minSentencesPerParagraph",defaultValue:4,public:!0},e.maxSentencesPerParagraph={createComponentOfType:"number",createStateVariable:"maxSentencesPerParagraph",defaultValue:8,public:!0},e.minWordsPerSentence={createComponentOfType:"number",createStateVariable:"minWordsPerSentence",defaultValue:4,public:!0},e.maxWordsPerSentence={createComponentOfType:"number",createStateVariable:"maxWordsPerSentence",defaultValue:8,public:!0},e.generateWords={createComponentOfType:"number",createStateVariable:"generateWords",defaultValue:null},e.generateSentences={createComponentOfType:"number",createStateVariable:"generateSentences",defaultValue:null},e.generateParagraphs={createComponentOfType:"number",createStateVariable:"generateParagraphs",defaultValue:null},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.readyToExpandWhenResolved={returnDependencies:()=>({minSentencesPerParagraph:{dependencyType:"stateVariable",variableName:"minSentencesPerParagraph"},maxSentencesPerParagraph:{dependencyType:"stateVariable",variableName:"maxSentencesPerParagraph"},minWordsPerSentence:{dependencyType:"stateVariable",variableName:"minWordsPerSentence"},maxWordsPerSentence:{dependencyType:"stateVariable",variableName:"maxWordsPerSentence"},generateWords:{dependencyType:"stateVariable",variableName:"generateWords"},generateSentences:{dependencyType:"stateVariable",variableName:"generateSentences"},generateParagraphs:{dependencyType:"stateVariable",variableName:"generateParagraphs"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{generatedVariantInfo:{seed:e.variantSeed,meta:{createdBy:t}}}})},e}static async createSerializedReplacements({component:e,componentInfoObjects:t}){const n=new dist.LoremIpsum({sentencesPerParagraph:{max:await e.stateValues.maxSentencesPerParagraph,min:await e.stateValues.minSentencesPerParagraph},wordsPerSentence:{max:await e.stateValues.maxWordsPerSentence,min:await e.stateValues.minWordsPerSentence},random:e.sharedParameters.variantRng});let r=[];if(null!==await e.stateValues.generateParagraphs){let t=await e.stateValues.generateParagraphs;if(Number.isInteger(t)&&t>0){r=n.generateParagraphs(t).split("\n").map((e=>({componentType:"p",children:[e]})))}}else if(null!==await e.stateValues.generateSentences){let t=await e.stateValues.generateSentences;if(Number.isInteger(t)&&t>0){let e=n.generateSentences(t).split(". ");for(let t of e.slice(0,e.length-1))r.push({componentType:"text",children:[t+"."]}),r.push(" ");r.push({componentType:"text",children:[e[e.length-1]]})}}else if(null!==await e.stateValues.generateWords){let t=await e.stateValues.generateWords;if(Number.isInteger(t)&&t>0){let e=n.generateWords(t).split(" ").map((e=>({componentType:"text",children:[e]})));r.push(e[0]);for(let t of e.slice(1))r.push(" "),r.push(t)}}let a=e.attributes.newNamespace?.primitive;return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:r,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:t}).serializedComponents}}static async calculateReplacementChanges({component:e,componentInfoObjects:t}){let n=await this.createSerializedReplacements({component:e,componentInfoObjects:t});return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:n.replacements}]}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n})}}function returnStandardTriggeringAttributes(e){return{triggerWhen:{createComponentOfType:"boolean",createStateVariable:"triggerWhen",defaultValue:!1,triggerActionOnChange:e},triggerWith:{createTargetComponentNames:!0},triggerWhenObjectsClicked:{createTargetComponentNames:!0},triggerWhenObjectsFocused:{createTargetComponentNames:!0}}}function addStandardTriggeringStateVariableDefinitions(e,t){e.insideTriggerSet={returnDependencies:()=>({parentTriggerSet:{dependencyType:"parentStateVariable",parentComponentType:"triggerSet",variableName:"updateValueAndActionsToTrigger"}}),definition:({dependencyValues:e})=>({setValue:{insideTriggerSet:null!==e.parentTriggerSet}})},e.triggerWith={returnDependencies:()=>({triggerWith:{dependencyType:"attributeTargetComponentNames",attributeName:"triggerWith"},triggerWhenObjectsClicked:{dependencyType:"attributeTargetComponentNames",attributeName:"triggerWhenObjectsClicked"},triggerWhenObjectsFocused:{dependencyType:"attributeTargetComponentNames",attributeName:"triggerWhenObjectsFocused"},triggerWhen:{dependencyType:"attributeComponent",attributeName:"triggerWhen"},insideTriggerSet:{dependencyType:"stateVariable",variableName:"insideTriggerSet"}}),definition({dependencyValues:e}){if(e.triggerWhen||e.insideTriggerSet)return{setValue:{triggerWith:null}};{let t=[];if(null!==e.triggerWith)for(let n of e.triggerWith)t.push({target:n.absoluteName});if(null!==e.triggerWhenObjectsClicked)for(let n of e.triggerWhenObjectsClicked)t.push({target:n.absoluteName,triggeringAction:"click"});if(null!==e.triggerWhenObjectsFocused)for(let n of e.triggerWhenObjectsFocused)t.push({target:n.absoluteName,triggeringAction:"down"});return 0===t.length&&(t=null),{setValue:{triggerWith:t}}}}},e.triggerWithTargetIds={chainActionOnActionOfStateVariableTargets:{triggeredAction:t},returnDependencies:()=>({triggerWith:{dependencyType:"stateVariable",variableName:"triggerWith"}}),definition({dependencyValues:e}){let t=[];if(e.triggerWith)for(let n of e.triggerWith){let e=n.target;n.triggeringAction&&(e+="|"+n.triggeringAction),t.includes(e)||t.push(e)}return{setValue:{triggerWithTargetIds:t}}},markStale:()=>({updateActionChaining:!0})};let n=e.hidden.returnDependencies,r=e.hidden.definition;e.hidden.returnDependencies=function(e){let t=n(e);return t.triggerWhen={dependencyType:"attributeComponent",attributeName:"triggerWhen"},t.triggerWith={dependencyType:"stateVariable",variableName:"triggerWith"},t.insideTriggerSet={dependencyType:"stateVariable",variableName:"insideTriggerSet"},t},e.hidden.definition=function(e){return e.dependencyValues.triggerWhen||e.dependencyValues.triggerWith||e.dependencyValues.insideTriggerSet?{setValue:{hidden:!0}}:r(e)}}class UpdateValue extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{updateValue:this.updateValue.bind(this),updateValueIfTriggerNewlyTrue:this.updateValueIfTriggerNewlyTrue.bind(this)})}static componentType="updateValue";static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject();e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"math",toLowerCase:!0,validValues:["math","number","boolean","text"]},e.prop={createPrimitiveOfType:"string"},e.newValue={createComponentOfType:"_componentWithSelectableType"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0};let t=returnStandardTriggeringAttributes("updateValueIfTriggerNewlyTrue");return Object.assign(e,t),e.simplify={createComponentOfType:"text",createStateVariable:"simplify",defaultValue:"none",public:!0,toLowerCase:!0,valueTransformations:{true:"full"},validValues:["none","full","numbers","numberspreserveorder"]},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();addStandardTriggeringStateVariableDefinitions(e,"updateValue");let t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){let t=null;return e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.propName={returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.targetIdentities={stateVariablesDeterminingDependencies:["targetComponent","componentIndex"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={};return null!==e.targetComponent&&(t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})?n.targets={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,componentIndex:e.componentIndex}:null!==e.componentIndex&&1!==e.componentIndex||(n.targets={dependencyType:"stateVariable",variableName:"targetComponent"})),n},definition({dependencyValues:e}){let t=null;return e.targets&&(t=e.targets,Array.isArray(t)||(t=[t])),{setValue:{targetIdentities:t}}}},e.targets={stateVariablesDeterminingDependencies:["targetIdentities","propName","propIndex"],returnDependencies:function({stateValues:e}){let t={targetIdentities:{dependencyType:"stateVariable",variableName:"targetIdentities"}};if(null!==e.targetIdentities)for(let[n,r]of e.targetIdentities.entries()){let a;if(e.propName){let t=e.propIndex;t&&(t=[...t]),a={dependencyType:"stateVariable",componentName:r.componentName,variableName:e.propName,returnAsComponentObject:!0,variablesOptional:!0,propIndex:t,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0}}else a={dependencyType:"componentIdentity",componentName:r.componentName};t["target"+n]=a}return t},definition({dependencyValues:e}){let t=null;if(null!==e.targetIdentities){t=[];for(let n in e.targetIdentities)e["target"+n]&&t.push(e["target"+n])}return{setValue:{targets:t}}}},e.newValue={returnDependencies:()=>({newValueAttr:{dependencyType:"attributeComponent",attributeName:"newValue",variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"},simplify:{dependencyType:"stateVariable",variableName:"simplify"}}),definition:function({dependencyValues:e}){if(null===e.newValueAttr)return{setValue:{newValue:null}};let t=e.newValueAttr.stateValues.value;return"math"===e.type&&(t=normalizeMathExpression({value:t,simplify:e.simplify})),{setValue:{newValue:t}}}},e}async updateValue({actionId:e}){let t=await this.stateValues.targets,n=await this.stateValues.newValue;if(null===t||null===n)return;let r=[];for(let e of t){let t="value";e.stateValues&&(t=Object.keys(e.stateValues)[0],void 0===t)?console.warn(`Cannot update prop="${await this.stateValues.propName}" of ${await this.stateValues.target} as could not find prop ${await this.stateValues.propName} on a component of type ${e.componentType}`):r.push({updateType:"updateValue",componentName:e.componentName,stateVariable:t,value:n})}return await this.coreFunctions.performUpdate({updateInstructions:r,actionId:e,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:n,responseText:n.toString()}}}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}async updateValueIfTriggerNewlyTrue({stateValues:e,previousValues:t,actionId:n}){if(await e.triggerWhen&&!1===t.triggerWhen&&!await this.stateValues.insideTriggerSet)return await this.updateValue({actionId:n});this.coreFunctions.resolveAction({actionId:n})}}class CallAction extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{callAction:this.callAction.bind(this),callActionIfTriggerNewlyTrue:this.callActionIfTriggerNewlyTrue.bind(this)})}static componentType="callAction";static acceptTarget=!0;static keepChildrenSerialized({serializedComponent:e,componentInfoObjects:t}){if(void 0===e.children)return[];{let n=[];for(let[r,a]of e.children.entries())t.componentIsSpecifiedType(a,"label")||n.push(r);return n}}static createAttributesObject(){let e=super.createAttributesObject();e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.actionName={createComponentOfType:"text",createStateVariable:"actionName",defaultValue:null,public:!0};let t=returnStandardTriggeringAttributes("callActionIfTriggerNewlyTrue");return Object.assign(e,t),e.numbers={createComponentOfType:"numberList"},e.number={createComponentOfType:"number"},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();addStandardTriggeringStateVariableDefinitions(e,"callAction");let t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){let t=null;return e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.targetName={returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"}}),definition({dependencyValues:e}){let t=null;return e.targetComponent&&(t=e.targetComponent.componentName),{setValue:{targetName:t}}}},e}async callAction({actionId:e}){let t=await this.stateValues.targetName,n=await this.stateValues.actionName;if(null!==t&&null!==n){let r={};this.serializedChildren.length>0&&(r.serializedComponents=deepClone(this.serializedChildren)),this.attributes.number&&(r.number=await this.attributes.number.component.stateValues.value),this.attributes.numbers&&(r.numbers=await this.attributes.numbers.component.stateValues.numbers),e&&(r.actionId=e),await this.coreFunctions.performAction({componentName:t,actionName:n,args:r,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType}},caseInsensitiveMatch:!0}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}else this.coreFunctions.resolveAction({actionId:e})}async callActionIfTriggerNewlyTrue({stateValues:e,previousValues:t,actionId:n}){if(e.triggerWhen&&!1===t.triggerWhen&&!await this.stateValues.insideTriggerSet)return await this.callAction({actionId:n});this.coreFunctions.resolveAction({actionId:n})}}class triggerSet extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{triggerActions:this.triggerActions.bind(this),triggerActionsIfTriggerNewlyTrue:this.triggerActionsIfTriggerNewlyTrue.bind(this)})}static componentType="triggerSet";static createAttributesObject(){let e=super.createAttributesObject();e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0};let t=returnStandardTriggeringAttributes("triggerActionsIfTriggerNewlyTrue");return Object.assign(e,t),e}static returnChildGroups(){return[{group:"updateValuesCallActions",componentTypes:["updateValue","callAction"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();addStandardTriggeringStateVariableDefinitions(e,"triggerActions");let t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.updateValueAndActionsToTrigger={returnDependencies:()=>({updateValueAndCallActionChildren:{dependencyType:"child",childGroups:["updateValuesCallActions"]}}),definition:({dependencyValues:e})=>({setValue:{updateValueAndActionsToTrigger:e.updateValueAndCallActionChildren}})},e}async triggerActions({actionId:e}){for(let e of await this.stateValues.updateValueAndActionsToTrigger)this.componentInfoObjects.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"updateValue"})?await this.coreFunctions.performAction({componentName:e.componentName,actionName:"updateValue"}):this.componentInfoObjects.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"callAction"})&&await this.coreFunctions.performAction({componentName:e.componentName,actionName:"callAction"});return this.coreFunctions.resolveAction({actionId:e}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}async triggerActionsIfTriggerNewlyTrue({stateValues:e,previousValues:t,actionId:n}){if(e.triggerWhen&&!1===t.triggerWhen)return await this.triggerActions({actionId:n});this.coreFunctions.resolveAction({actionId:n})}}class FunctionIterates extends InlineComponent{static componentType="functionIterates";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.nIterates={createComponentOfType:"integer",createStateVariable:"nIterates",defaultValue:0,public:!0},e.forceSymbolic={createComponentOfType:"boolean",createStateVariable:"forceSymbolic",defaultValue:!1,public:!0},e.forceNumeric={createComponentOfType:"boolean",createStateVariable:"forceNumeric",defaultValue:!1,public:!0},e.initialValue={createComponentOfType:"math",createStateVariable:"initialValue",defaultValue:me$3.fromAst("_")},e.function={createComponentOfType:"function"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["nInputs","nOutputs"]}}),definition:({dependencyValues:e})=>e.functionAttr?e.functionAttr.stateValues.nInputs!==e.functionAttr.stateValues.nOutputs?(console.warn("Function iterates are possible only if the number of inputs is equal to the number of outputs"),{setValue:{nDimensions:0}}):{setValue:{nDimensions:e.functionAttr.stateValues.nInputs}}:{setValue:{nDimensions:0}}},e.allIterates={public:!0,shadowingInstructions:{createComponentOfType:"mathList"},returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["symbolicfs","numericalfs","symbolic"]},forceSymbolic:{dependencyType:"stateVariable",variableName:"forceSymbolic"},forceNumeric:{dependencyType:"stateVariable",variableName:"forceNumeric"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},initialValue:{dependencyType:"stateVariable",variableName:"initialValue"},nIterates:{dependencyType:"stateVariable",variableName:"nIterates"}}),definition({dependencyValues:e}){let t=[],n=e.functionAttr,r=e.initialValue,a=!e.forceNumeric&&(n.stateValues.symbolic||e.forceSymbolic),i=e.nIterates;if(!n||0===e.nDimensions||!(1===e.nDimensions||Array.isArray(r.tree)&&vectorOperators.includes(r.tree[0])&&r.tree.length===e.nDimensions+1))return t=Array(i).fill(me$3.fromAst("_")),{setValue:{allIterates:t}};if(a)if(1===e.nDimensions){let e=n.stateValues.symbolicfs[0],a=r;for(let n=0;nme$3.fromAst(e).evaluate_to_constant())).map((e=>null==e?NaN:e));for(let n=0;n({initialValue:{dependencyType:"stateVariable",variableName:"initialValue"},allIterates:{dependencyType:"stateVariable",variableName:"allIterates"}}),definition:({dependencyValues:e})=>({setValue:{allIteratesWithInitial:[e.initialValue,...e.allIterates]}})},e.iterates={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["iterate"],returnArraySizeDependencies:()=>({nIterates:{dependencyType:"stateVariable",variableName:"nIterates"}}),returnArraySize:({dependencyValues:e})=>[e.nIterates],returnArrayDependenciesByKey:()=>({globalDependencies:{allIterates:{dependencyType:"stateVariable",variableName:"allIterates"}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n={};for(let r=0;r!Number.isFinite(e.nIterates)||e.nIterates<0?{}:e.nIterates>0?{finalIterate:{dependencyType:"stateVariable",variableName:`iterate${e.nIterates}`}}:{finalIterate:{dependencyType:"stateVariable",variableName:"initialValue"}},definition:({dependencyValues:e})=>({setValue:{finalIterate:e.finalIterate}})},e}}class Module extends Template{static componentType="module";static renderedDefault=!0;static acceptAnyAttribute=!0;static createAttributesObject(){let e=super.createAttributesObject();return delete e.styleNumber,e}}class CustomAttribute extends CompositeComponent{static componentType="customAttribute";static assignNamesToReplacements=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.componentType={createPrimitiveOfType:"string"},e.attribute={createPrimitiveOfType:"string"},e.defaultValue={leaveRaw:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.componentNameForAttributes={returnDependencies:()=>({parentVariableContainingName:{dependencyType:"parentStateVariable",variableName:"componentNameForAttributes"}}),definition:({dependencyValues:e})=>({setValue:{componentNameForAttributes:e.parentVariableContainingName}})},e.attributeName={returnDependencies:()=>({attribute:{dependencyType:"attributePrimitive",attributeName:"attribute"}}),definition:({dependencyValues:e})=>({setValue:{attributeName:e.attribute}})},e.readyToExpandWhenResolved={stateVariablesDeterminingDependencies:["componentNameForAttributes"],returnDependencies:({stateValues:e})=>({componentIdentity:{dependencyType:"componentIdentity",componentName:e.componentNameForAttributes}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a}){let i=e.attributes.newNamespace?.primitive,s=r.componentTypeLowerCaseMapping[e.attributes.componentType.primitive.toLowerCase()];if(!r.allComponentClasses[s])return console.warn(`Could not find component type ${s}`),{replacements:[]};let o=t[await e.stateValues.componentNameForAttributes],l={};for(let e in o.attributes)l[e.toLowerCase()]=e;let u=await e.stateValues.attributeName,c=l[u.toLowerCase()],p=o.attributes[c];if(void 0===p){if(void 0===e.attributes.defaultValue)return console.warn("Cannot create component from attribute if neither attribute nor default value specified"),{replacements:[]};p=e.attributes.defaultValue}let d=o.constructor,m=Object.keys(d.createAttributesObject()).map((e=>e.toLowerCase()));if(m.push("name","target","assignnames"),m.includes(u.toLowerCase()))return console.warn(`Cannot add attribute ${u} of a ${d.componentType} as it already exists in ${d.componentType} class`),{replacements:[]};let h=componentFromAttribute({attrObj:{createComponentOfType:s},value:p,componentInfoObjects:r}).component;if(h.children&&(applyMacros(h.children,r),i))for(let e of h.children)if("copy"===e.componentType){let t=e.doenetAttributes.target;/[a-zA-Z_]/.test(t[0])&&(e.doenetAttributes.target="../"+t)}return applySugar({serializedComponents:[h],isAttributeComponent:!0,componentInfoObjects:r}),setTNamesToAbsolute([h]),{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:[h],parentName:e.componentName,parentCreatesNewNamespace:i,componentInfoObjects:r}).serializedComponents}}}class Setup extends CompositeComponent{static componentType="setup";static returnChildGroups(){return[{group:"styleDefinitions",componentTypes:["styleDefinitions"]},{group:"feedbackDefinitions",componentTypes:["feedbackDefinitions"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.componentNameForAttributes={returnDependencies:()=>({sourceCompositeIdentity:{dependencyType:"sourceCompositeIdentity"}}),definition({dependencyValues:e}){let t=null;return e.sourceCompositeIdentity&&(t=e.sourceCompositeIdentity.componentName),{setValue:{componentNameForAttributes:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}}class Footnote extends InlineComponent{static componentType="footnote";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text?t+=n.stateValues.text:t+=" ";return{setValue:{text:t}}}},e.footnoteTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({footnoteCounter:{dependencyType:"counter",counterName:"footnote"}}),definition:({dependencyValues:e})=>({setValue:{footnoteTag:String(e.footnoteCounter)}})},e}}class Caption extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="caption";static rendererType="containerInline";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlinesBlocks",componentTypes:["_inline","_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlinesBlocks"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text?t+=n.stateValues.text:t+=" ";return{setValue:{text:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Endpoint extends Point{static componentType="endpoint";static rendererType="point";static createAttributesObject(){let e=super.createAttributesObject();return e.open={createComponentOfType:"boolean",createStateVariable:"open",defaultValue:!1,public:!0,forRenderer:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}async switchPoint({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!await this.stateValues.open}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{open:!await this.stateValues.open}}});this.coreFunctions.resolveAction({actionId:e})}}class Sort extends CompositeComponent{static componentType="sort";static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static assignNamesToReplacements=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.sortVectorsBy={createComponentOfType:"text",createStateVariable:"sortVectorsBy",defaultValue:"displacement",public:!0,toLowerCase:!0,validValues:["displacement","tail"]},e.sortByComponent={createComponentOfType:"integer",createStateVariable:"sortByComponent",defaultValue:"1",public:!0},e.sortByProp={createPrimitiveOfType:"string"},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.propName={returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"sortByProp"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.componentNamesForValues={returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"],variableNames:["componentNamesInList"],variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.children)n.stateValues.componentNamesInList?t.push(...n.stateValues.componentNamesInList):t.push(n.componentName);return{setValue:{componentNamesForValues:t}}}},e.sortedValues={stateVariablesDeterminingDependencies:["componentNamesForValues","sortByComponent","propName"],returnDependencies({stateValues:e}){let t={sortVectorsBy:{dependencyType:"stateVariable",variableName:"sortVectorsBy"},sortByComponent:{dependencyType:"stateVariable",variableName:"sortByComponent"},propName:{dependencyType:"stateVariable",variableName:"propName"}};if(e.propName)for(let[n,r]of e.componentNamesForValues.entries())t[`component${n}`]={dependencyType:"stateVariable",componentName:r,variableName:e.propName,variablesOptional:!0,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,returnAsComponentObject:!0};else for(let[n,r]of e.componentNamesForValues.entries())t[`component${n}`]={dependencyType:"multipleStateVariables",componentName:r,variableNames:["value",`x${e.sortByComponent}`,`tailX${e.sortByComponent}`],variablesOptional:!0};return t},definition({dependencyValues:e,componentInfoObjects:t}){let n=[],r=!0;for(let a in e){if("component"!==a.substring(0,9))continue;let i=e[a];if(e.propName){let e=Object.values(i.stateValues)[0];n.push({componentName:i.componentName,numericalValue:Number(e),textValue:String(e)}),Number.isFinite(e)||(r=!1)}else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"number"}))n.push({componentName:i.componentName,numericalValue:i.stateValues.value,textValue:String(i.stateValues.value)});else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"text"})){let e=NaN,t=i.stateValues.value;n.push({componentName:i.componentName,numericalValue:e,textValue:t}),r=!1}else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"math"})){let e=i.stateValues.value.evaluate_to_constant();null===e&&(e=NaN,r=!1),n.push({componentName:i.componentName,numericalValue:e,textValue:i.stateValues.value.toString()})}else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"point"})){let t=i.stateValues[`x${e.sortByComponent}`],a=NaN,s="";t&&(a=t.evaluate_to_constant(),null===a&&(a=NaN,r=!1),s=t.toString()),n.push({componentName:i.componentName,numericalValue:a,textValue:s})}else if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"vector"})){let t=NaN,a="",s=i.stateValues[`x${e.sortByComponent}`];s="displacement"===e.sortVectorsBy?i.stateValues[`x${e.sortByComponent}`]:i.stateValues[`tailX${e.sortByComponent}`],s&&(t=s.evaluate_to_constant(),null===t&&(t=NaN,r=!1),a=s.toString()),n.push({componentName:i.componentName,numericalValue:t,textValue:a})}}return r?n.sort(((e,t)=>e.numericalValue-t.numericalValue)):n.sort(((e,t)=>e.textValue>t.textValue?1:e.textValue({sortedValues:{dependencyType:"stateVariable",variableName:"sortedValues"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n,workspace:r}){let a=[],i=[];for(let n of await e.stateValues.sortedValues){let e;if(void 0===n.listInd)e=t[n.componentName];else{e=t[n.componentName].activeChildren[n.listInd]}e&&(i.push(e.componentName),a.push(await e.serialize({sourceAttributesToIgnoreRecursively:["isResponse"]})))}r.uniqueIdentifiersUsed=[],a=postProcessCopy({serializedComponents:a,componentName:e.componentName,uniqueIdentifiersUsed:r.uniqueIdentifiersUsed,addShadowDependencies:!0,markAsPrimaryShadow:!0});let s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:a,parentName:e.componentName,parentCreatesNewNamespace:await e.stateValues.newNamespace,componentInfoObjects:n});return r.componentsCopied=i,{replacements:s.serializedComponents}}static async calculateReplacementChanges({component:e,components:t,componentInfoObjects:n,workspace:r}){let a=[];for(let n of await e.stateValues.sortedValues){let e;if(void 0===n.listInd)e=t[n.componentName];else{e=t[n.componentName].activeChildren[n.listInd]}e&&a.push(e.componentName)}if(a.length==r.componentsCopied.length&&r.componentsCopied.every(((e,t)=>e===a[t])))return[];let i=(await this.createSerializedReplacements({component:e,components:t,componentInfoObjects:n,workspace:r})).replacements;return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:i}]}}class Shuffle extends CompositeComponent{static componentType="shuffle";static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static assignNamesToReplacements=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.originalComponentNames={additionalStateVariablesDefined:["nComponents"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"],variableNames:["componentNamesInList"],variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.children)n.stateValues.componentNamesInList?t.push(...n.stateValues.componentNamesInList):t.push(n.componentName);return{setValue:{originalComponentNames:t,nComponents:t.length}}}},e.componentOrder={returnDependencies:({sharedParameters:e})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},rngClass:{dependencyType:"value",value:e.rngClass,doNotProxy:!0},nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},variants:{dependencyType:"variants"}}),definition({dependencyValues:e}){let t=e.nComponents,n=e.variants?.desiredVariant?.indices;if(void 0!==n)if(n.length!==t)console.warn("Ignoring indices specified for shuffle as number of indices doesn't match number of components.");else{if(n=n.map(Number),!n.every(Number.isInteger))throw Error("All indices specified for shuffle must be integers");if(n.every((e=>e>=1&&e<=t)))return{setValue:{componentOrder:n}};console.warn("Ignoring indices specified for shuffle as some indices out of range.")}let r=e.rngClass(e.variantSeed+"co"),a=[...Array(t).keys()].map((e=>e+1));for(let e=t-1;e>0;e--){const t=r(),n=Math.floor(t*(e+1));[a[e],a[n]]=[a[n],a[e]]}return{setValue:{componentOrder:a}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({sortedValues:{dependencyType:"stateVariable",variableName:"componentOrder"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({componentInfoObjects:e,sharedParameters:t})=>({variantSeed:{dependencyType:"value",value:t.variantSeed},componentOrder:{dependencyType:"stateVariable",variableName:"componentOrder"},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(e.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t},indices:e.componentOrder},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n})}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n,workspace:r}){let a=[],i=[],s=await e.stateValues.originalComponentNames;for(let n of await e.stateValues.componentOrder){let e=t[s[n-1]];e&&(i.push(e.componentName),a.push(await e.serialize({sourceAttributesToIgnoreRecursively:["isResponse"]})))}r.uniqueIdentifiersUsed=[],a=postProcessCopy({serializedComponents:a,componentName:e.componentName,uniqueIdentifiersUsed:r.uniqueIdentifiersUsed,addShadowDependencies:!0,markAsPrimaryShadow:!0});let o=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:a,parentName:e.componentName,parentCreatesNewNamespace:await e.stateValues.newNamespace,componentInfoObjects:n});return r.componentsCopied=i,{replacements:o.serializedComponents}}static async calculateReplacementChanges({component:e,components:t,componentInfoObjects:n,workspace:r}){let a=[],i=await e.stateValues.originalComponentNames;for(let n of await e.stateValues.componentOrder){let e=t[i[n-1]];e&&a.push(e.componentName)}if(a.length==r.componentsCopied.length&&r.componentsCopied.every(((e,t)=>e===a[t])))return[];let s=(await this.createSerializedReplacements({component:e,components:t,componentInfoObjects:n,workspace:r})).replacements;return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:s}]}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){let n=0;for(let r of e.children)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})){if(!r.attributes.createComponentOfType?.primitive)return{success:!1};if(void 0!==r.attributes.nComponents?.primitive){let e=Number(r.attributes.nComponents?.primitive);if(!(Number.isInteger(e)&&e>=0))return{success:!1};n+=e}else n++}else n++;let r=1;for(let e=2;e<=n;e++)r*=e;let a=super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!a.success)return{success:!1};let i=a.numberOfVariants*r;return e.variants.numberOfVariants=i,e.variants.uniqueVariantData={numberOfVariantsByDescendant:e.variants.uniqueVariantData.numberOfVariantsByDescendant,numberOfPermutations:r,nComponents:n},{success:!0,numberOfVariants:i}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};let a=e.variants.uniqueVariantData.numberOfVariantsByDescendant,i=e.variants.descendantVariantComponents,s=e.variants.uniqueVariantData.numberOfPermutations,o=e.variants.uniqueVariantData.nComponents,l=[...a];l.push(s);let u=enumerateCombinations({numberOfOptionsByIndex:l,maxNumber:t})[t-1].map((e=>e+1)),c=u.pop(),p=u,d=[...Array(o).keys()].map((e=>e+1)),m=enumeratePermutations({values:d,maxNumber:c})[c-1],h=!1,f=[];for(let e=0;e1){let t=i[e],r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:p[e],componentInfoObjects:n});if(!r.success)return{success:!1};f.push(r.desiredVariant),h=!0}else f.push({});let y={indices:m};return h&&(y.subvariants=f),{success:!0,desiredVariant:y}}}class SolveEquations extends InlineComponent{static componentType="solveEquations";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.variables={createComponentOfType:"variables"},e.nDiscretizationPoints={createComponentOfType:"number",createStateVariable:"nDiscretizationPoints",defaultValue:100,public:!0},e.minVar={createComponentOfType:"number",createStateVariable:"minVar",defaultValue:null},e.maxVar={createComponentOfType:"number",createStateVariable:"maxVar",defaultValue:null},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){return e.every((e=>"string"==typeof e||e.doenetAttributes&&e.doenetAttributes.createdFromMacro))?1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}:{success:!1}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"strings",componentTypes:["string"]}]}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({}),returnArraySize:({dependencyValues:e})=>[1],returnArrayDependenciesByKey:({arrayKeys:e})=>({globalDependencies:{variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t,arrayKeys:n,usedDefault:r}){let a=[];return null!==e.variablesAttr&&(a=e.variablesAttr.stateValues.variables),{setValue:{variables:returnNVariables(t[0],a)}}}},t.variable={isAlias:!0,targetVariableName:"variable1"},t.allSolutions={returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},variables:{dependencyType:"stateVariable",variableName:"variables"},minVar:{dependencyType:"stateVariable",variableName:"minVar"},maxVar:{dependencyType:"stateVariable",variableName:"maxVar"},nDiscretizationPoints:{dependencyType:"stateVariable",variableName:"nDiscretizationPoints"}}),definition({dependencyValues:t}){if(0===t.mathChild.length)return{setValue:{allSolutions:[]}};let n=t.mathChild[0].stateValues.value;if(!Array.isArray(n.tree)||3!==n.tree.length||"="!==n.tree[0])return{setValue:{allSolutions:[]}};let r=t.minVar,a=t.maxVar,i=[],s=t.variables[0].subscripts_to_strings().tree,o=me$3.fromAst(["+",n.tree[1],["-",n.tree[2]]]).subscripts_to_strings(),l=o.f(),u=e=>l({[s]:e}),c=function(e){try{return u(e)}catch(e){return NaN}};if(Number.isFinite(r)||(r=-10),Number.isFinite(a)||(a=10),r>a)return{setValue:{allSolutions:[]}};let p=[r,a],d=[r];for(let e=0;enormalizeMathExpression({value:o.substitute({[s]:e}).strings_to_subscripts(),simplify:!0,expand:!0}).evaluate_to_constant())(e);return null!==n?n:NaN}})),y=d[0],g=f[0];for(let e=0;e0)for(let t=0;t<10;t++)if(y=.1*y+.9*n,s=.1*s+.9*n,g=c(y),o=c(s),g*o<0){g*u<0?(i.push(e.fzero(c,[l,y])),i.push(n)):(i.includes(n)||i.push(n),n=s,r=o),a=!0;break}}a||i.includes(n)||i.push(n)}else if(r*g<0)i.push(e.fzero(c,[y,n]));else if(0!==g&&t0&&(r>0&&g>r||r<0&&gr?c:e=>-c(e);let s=e.fminbr(t,[y,a],void 0,1e-10);if(s.success){let t=s.x,a=c(t);a*g<0?(i.push(e.fzero(c,[y,t])),n=t,r=a):0===a&&i.push(t)}}}y=n,g=r}i=i.filter((e=>e>=r&&e<=a));let b=i.map((e=>me$3.fromAst(e)));return{setValue:{allSolutions:b}}}},t.numberSolutions={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allSolutions:{dependencyType:"stateVariable",variableName:"allSolutions"}}),definition:({dependencyValues:e})=>({setValue:{numberSolutions:e.allSolutions.length}})},t.solutions={public:!0,shadowingInstructions:{createComponentOfType:"math"},isArray:!0,entryPrefixes:["solution"],returnArraySizeDependencies:()=>({numberSolutions:{dependencyType:"stateVariable",variableName:"numberSolutions"}}),returnArraySize:({dependencyValues:e})=>[e.numberSolutions],returnArrayDependenciesByKey:()=>({globalDependencies:{allSolutions:{dependencyType:"stateVariable",variableName:"allSolutions"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({parentOpen:{dependencyType:"parentStateVariable",variableName:"open"}}),markStale:()=>({updateReplacements:!0}),definition:({dependencyValues:e})=>({setValue:{rendered:Boolean(e.parentOpen)}})},e}static async calculateReplacementChanges({component:e,componentInfoObjects:t}){if(await e.stateValues.rendered&&0===e.replacements.length){let n=(await this.createSerializedReplacements({component:e,componentInfoObjects:t})).replacements;if(n.length>0){return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:0,serializedReplacements:n}]}return[]}return[]}}class SubsetOfRealsInput extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{addPoint:this.addPoint.bind(this),deletePoint:this.deletePoint.bind(this),movePoint:this.movePoint.bind(this),togglePoint:this.togglePoint.bind(this),toggleInterval:this.toggleInterval.bind(this),clear:this.clear.bind(this),setToR:this.setToR.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="subsetOfRealsInput";static variableForPlainMacro="subsetValue";static variableForPlainCopy="subsetValue";static createAttributesObject(){let e=super.createAttributesObject();return e.xmin={createComponentOfType:"number",createStateVariable:"xmin",defaultValue:-10,public:!0,forRenderer:!0},e.xmax={createComponentOfType:"number",createStateVariable:"xmax",defaultValue:10,public:!0,forRenderer:!0},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:800,public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:300,public:!0,forRenderer:!0},e.xlabel={createComponentOfType:"text",createStateVariable:"xlabel",defaultValue:"",public:!0,forRenderer:!0},e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:.5,public:!0},e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x"),public:!0},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e.bindValueTo={createComponentOfType:"subsetOfReals"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.subsetValue={public:!0,shadowingInstructions:{createComponentOfType:"subsetOfReals"},hasEssential:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["subsetValue"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"},variable:{dependencyType:"stateVariable",variableName:"variable"},format:{dependencyType:"stateVariable",variableName:"format"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{subsetValue:e.bindValueTo.stateValues.subsetValue}}:{useEssentialOrDefaultValue:{subsetValue:{get defaultValue(){return parseValueIntoSubset({inputString:e.prefill,format:e.format,variable:e.variable})}}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.subsetValue,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"subsetValue",value:e.subsetValue}]}},e.pointsFromSubset={additionalStateVariablesDefined:["intervalsFromSubset"],returnDependencies:()=>({subsetValue:{dependencyType:"stateVariable",variableName:"subsetValue"}}),definition({dependencyValues:e}){function t(e,t){let n=[],r=[];if(e.points&&(n=e.points),e.intervals&&(r=e.intervals),t.points){let e=n.map((e=>e.value));for(let r of t.points){let t=e.indexOf(r.value);-1===t?n.push(r):n[t].inSubset||=r.inSubset}}return t.intervals&&r.push(...t.intervals),{points:n,intervals:r}}let{points:n,intervals:r}=function e(n){if(null===n||n.isEmpty())return{};if(n instanceof theModule.Union){let r=[],a=[];for(let i of n.subsets){let n=e(i);({points:r,intervals:a}=t({points:r,intervals:a},n))}return{points:r,intervals:a}}if(n instanceof theModule.RealLine)return{intervals:[[-1/0,1/0]]};if(n instanceof theModule.Singleton)return{points:[{value:n.element,inSubset:!0}]};if(n instanceof theModule.OpenInterval){let e=[[n.left,n.right]],t=[];return Number.isFinite(n.left)&&t.push({value:n.left,inSubset:!1}),Number.isFinite(n.right)&&t.push({value:n.right,inSubset:!1}),{intervals:e,points:t}}return{}}(e.subsetValue),a=n||[],i=r||[];return a.sort(((e,t)=>e.value-t.value)),i.sort(((e,t)=>e[0]-t[0])),{setValue:{pointsFromSubset:a,intervalsFromSubset:i}}}},e.additionalPoints={defaultValue:[],hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{additionalPoints:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>e.additionalPoints.every(Number.isFinite)?{success:!0,instructions:[{setEssentialValue:"additionalPoints",value:[...e.additionalPoints].sort(((e,t)=>e-t))}]}:{success:!1}},e.points={additionalStateVariablesDefined:[{variableName:"intervals",forRenderer:!0}],forRenderer:!0,returnDependencies:()=>({pointsFromSubset:{dependencyType:"stateVariable",variableName:"pointsFromSubset"},intervalsFromSubset:{dependencyType:"stateVariable",variableName:"intervalsFromSubset"},additionalPoints:{dependencyType:"stateVariable",variableName:"additionalPoints"}}),definition({dependencyValues:e}){let t=[...e.pointsFromSubset],n=[...e.intervalsFromSubset],r=[...e.additionalPoints].sort(((e,t)=>e-t)),a=[],i=[],s=0,o=1/0,l=0;r.length>0&&(o=r[0]);let u=n[0],c=-1/0;t.push({value:1/0,inSubset:!1});for(let e of t){let t=!1;for(u&&u[0]e.value));if(!e.includes(r)){let e=!1;for(let t of i)if(t[0]r){e=!0;break}if(e)return s.push(r),await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:s}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{addedPoint:r,intervalsFromSubset:i,pointsFromSubset:a,additionalPoints:s}}});{a.push({value:r,inSubset:!0});let e=await this.createUpdateInstructions({intervalsFromSubset:i,pointsFromSubset:a,modifiedAdditionalPoints:!1,additionalPoints:s});return await this.coreFunctions.performUpdate({updateInstructions:e,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{addedPoint:r,intervalsFromSubset:i,pointsFromSubset:a,additionalPoints:s}}})}}}this.coreFunctions.resolveAction({actionId:t})}async deletePoint({pointInd:e,actionId:t}){let n=await this.stateValues.points[e],r=[...await this.stateValues.additionalPoints],a=[...await this.stateValues.pointsFromSubset],i=[...await this.stateValues.intervalsFromSubset];if(n.isAdditional)return r.splice(n.additionalPointInd,1),await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:r}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{deletedPoint:n.value,intervalsFromSubset:i,pointsFromSubset:a,additionalPoints:r}}});{let s=!1,o=a.map((e=>e.value)).indexOf(n.value),l=i.map((e=>e[1])).indexOf(n.value),u=i.map((e=>e[0])).indexOf(n.value);if(-1!==l)if(-1!==u)i[l]=[i[l][0],i[u][1]],i.splice(u,1),a.splice(o,1);else{let t=(await this.stateValues.points)[e-1];if(t&&t.isAdditional)i[l]=[i[l][0],t.value],r.splice(n.additionalPointInd,1),s=!0,a.splice(o,1,t);else if(i.splice(l,1),a.splice(o,1),t&&!t.inSubset){let e=i.map((e=>e[1])).indexOf(t.value);-1===e&&(r.push(t.value),s=!0)}}else if(-1!==u){let t=(await this.stateValues.points)[e+1];if(t&&t.isAdditional)i[u]=[t.value,i[u][1]],r.splice(n.additionalPointInd,1),s=!0,a.splice(o,1,t);else if(i.splice(u,1),a.splice(o,1),t&&!t.inSubset){let e=i.map((e=>e[0])).indexOf(t.value);-1===e&&(r.push(t.value),s=!0)}}else a.splice(o,1);let c=await this.createUpdateInstructions({intervalsFromSubset:i,pointsFromSubset:a,modifiedAdditionalPoints:s,additionalPoints:r});return await this.coreFunctions.performUpdate({updateInstructions:c,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{deletedPoint:n.value,intervalsFromSubset:i,pointsFromSubset:a,additionalPoints:r}}})}}async createUpdateInstructions({intervalsFromSubset:e,pointsFromSubset:t,modifiedAdditionalPoints:n,additionalPoints:r}){let a,i=await this.stateValues.dx,s=e=>Math.round(e/i)*i,o=[];for(let t of e)o.push(new theModule.OpenInterval(s(t[0]),s(t[1])));for(let e of t)e.inSubset&&o.push(new theModule.Singleton(s(e.value)));a=0===o.length?new theModule.EmptySet:1===o.length?o[0]:new theModule.Union(o);let l=[{componentName:this.componentName,updateType:"updateValue",stateVariable:"subsetValue",value:a}];return n&&l.push({componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:r.map(s)}),l}async movePoint({pointInd:e,value:t,transient:n,actionId:r}){let a=await this.stateValues.dx,i=Math.round(Math.max(await this.stateValues.xmin,Math.min(await this.stateValues.xmax,t))/a)*a,s=await this.stateValues.points,o=s[e],l=s[e-1];l&&(i=Math.max(i,l.value+a));let u=s[e+1];u&&(i=Math.min(i,u.value-a));let c=[...await this.stateValues.additionalPoints],p=[...await this.stateValues.pointsFromSubset],d=[...await this.stateValues.intervalsFromSubset];if(o.isAdditional)return c[o.additionalPointInd]=i,n?await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:c}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"additionalPoints",value:c}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{movedPoint:i,intervalsFromSubset:d,pointsFromSubset:p,additionalPoints:c}}});{let e=p.map((e=>e.value)).indexOf(o.value),t=d.map((e=>e[1])).indexOf(o.value),a=d.map((e=>e[0])).indexOf(o.value);p[e]={value:i,inSubset:p[e].inSubset},-1!==t&&(d[t]=[d[t][0],i]),-1!==a&&(d[a]=[i,d[a][1]]);let s=await this.createUpdateInstructions({intervalsFromSubset:d,pointsFromSubset:p,modifiedAdditionalPoints:!1});return n?await this.coreFunctions.performUpdate({updateInstructions:s,transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:s,actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{movedPoint:i,intervalsFromSubset:d,pointsFromSubset:p,additionalPoints:c}}})}}async togglePoint({pointInd:e,actionId:t}){let n=(await this.stateValues.points)[e],r=[...await this.stateValues.pointsFromSubset],a=[...await this.stateValues.intervalsFromSubset],i=[...await this.stateValues.additionalPoints],s=!1;if(n.isAdditional)if(i.splice(n.additionalPointInd,1),s=!0,n.inSubset){for(let[e,t]of a.entries())if(t[0]n.value){let r=[[t[0],n.value],[n.value,t[1]]];a.splice(e,1,...r);break}}else r.push({value:n.value,inSubset:!0});else{let e=r.map((e=>e.value)).indexOf(n.value),t=a.map((e=>e[1])).indexOf(n.value),o=a.map((e=>e[0])).indexOf(n.value);-1!==t?-1!==o?(a[t]=[a[t][0],a[o][1]],a.splice(o,1),r.splice(e,1),i.push(n.value),s=!0):r[e]={value:n.value,inSubset:!n.inSubset}:-1!==o?r[e]={value:n.value,inSubset:!n.inSubset}:(r.splice(e,1),i.push(n.value),s=!0)}let o=await this.createUpdateInstructions({intervalsFromSubset:a,pointsFromSubset:r,modifiedAdditionalPoints:s,additionalPoints:i});return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{toggledPoint:n.value,intervalsFromSubset:a,pointsFromSubset:r,additionalPoints:i}}})}async toggleInterval({intervalInd:e,actionId:t}){let n=(await this.stateValues.intervals)[e],r=await this.stateValues.points,a=r[e-1],i=r[e],s=[...await this.stateValues.pointsFromSubset],o=[...await this.stateValues.intervalsFromSubset],l=[...await this.stateValues.additionalPoints],u=!1;if(n.inSubset){let e,t;for(let[r,a]of o.entries())if(a[0]<=n.left&&a[1]>=n.right){t=a,e=r;break}if(n.left===t[0])if(n.right===t[1]){if(o.splice(e,1),a&&!a.inSubset){let e=o.map((e=>e[1])).indexOf(a.value);if(-1===e){let e=s.map((e=>e.value)).indexOf(a.value);s.splice(e,1),l.push(a.value),u=!0}}if(i&&!i.inSubset){let e=o.map((e=>e[0])).indexOf(i.value);if(-1===e){let e=s.map((e=>e.value)).indexOf(i.value);s.splice(e,1),l.push(i.value),u=!0}}}else{if(o[e]=[n.right,t[1]],a&&!a.inSubset){let e=o.map((e=>e[1])).indexOf(a.value);if(-1===e){let e=s.map((e=>e.value)).indexOf(a.value);s.splice(e,1),l.push(a.value),u=!0}}s.push({value:i.value,inSubset:!0}),l.splice(i.additionalPointInd,1),u=!0}else if(n.right===t[1]){if(o[e]=[t[0],n.left],i&&!i.inSubset){let e=o.map((e=>e[0])).indexOf(i.value);if(-1===e){let e=s.map((e=>e.value)).indexOf(i.value);s.splice(e,1),l.push(i.value),u=!0}}s.push({value:a.value,inSubset:!0}),l.splice(a.additionalPointInd,1),u=!0}else{let r=[[t[0],n.left],[n.right,t[1]]];o.splice(e,1,...r),s.push({value:a.value,inSubset:!0}),s.push({value:i.value,inSubset:!0}),l.splice(i.additionalPointInd,1),l.splice(a.additionalPointInd,1),u=!0}}else{let e=o.map((e=>e[1])).indexOf(n.left),t=o.map((e=>e[0])).indexOf(n.right);if(-1===e)-1===t?(o.push([n.left,n.right]),i&&i.isAdditional&&(l.splice(i.additionalPointInd,1),u=!0),a&&a.isAdditional&&(l.splice(a.additionalPointInd,1),u=!0)):(i.inSubset?(o[t]=[n.left,o[t][1]],l.push(i.value),u=!0):o.push([n.left,n.right]),a&&a.isAdditional&&(l.splice(a.additionalPointInd,1),u=!0));else if(-1===t)a.inSubset?(o[e]=[o[e][0],n.right],l.push(a.value),u=!0):o.push([n.left,n.right]),i&&i.isAdditional&&(l.splice(i.additionalPointInd,1),u=!0);else if(a.inSubset)if(i.inSubset){let n=[o[e][0],o[t][1]];o.splice(e,2,n),l.push(a.value),l.push(i.value),u=!0}else o[e]=[o[e][0],n.right],l.push(a.value),u=!0;else i.inSubset?(o[t]=[n.left,o[t][1]],l.push(i.value),u=!0):o.push([n.left,n.right])}let c=await this.createUpdateInstructions({intervalsFromSubset:o,pointsFromSubset:s,modifiedAdditionalPoints:u,additionalPoints:l});return await this.coreFunctions.performUpdate({updateInstructions:c,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{toggledInterval:[n.left,n.right],intervalsFromSubset:o,pointsFromSubset:s,additionalPoints:l}}})}async clear({actionId:e}){let t=await this.createUpdateInstructions({intervalsFromSubset:[],pointsFromSubset:[],modifiedAdditionalPoints:!0,additionalPoints:[]});return await this.coreFunctions.performUpdate({updateInstructions:t,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{cleared:!0,intervalsFromSubset:[],pointsFromSubset:[],additionalPoints:[]}}})}async setToR({actionId:e}){let t=await this.createUpdateInstructions({intervalsFromSubset:[[-1/0,1/0]],pointsFromSubset:[],modifiedAdditionalPoints:!0,additionalPoints:[]});return await this.coreFunctions.performUpdate({updateInstructions:t,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{setToR:!0,intervalsFromSubset:[[-1/0,1/0]],pointsFromSubset:[],additionalPoints:[]}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}function parseValueIntoSubset({inputString:e,format:t,variable:n}){if(!e)return new theModule.EmptySet;let r;if("latex"===t)try{r=me$3.fromLatex(e)}catch(t){return console.warn(`Invalid latex for subsetOfRealsInput: ${e}`),new theModule.EmptySet}else if("text"===t)try{r=me$3.fromText(e)}catch(t){return console.warn(`Invalid text for subsetOfRealsInput: ${e}`),new theModule.EmptySet}return buildSubsetFromMathExpression(r,n)}class SubsetOfReals extends MathComponent{static componentType="subsetOfReals";static rendererType="math";static primaryStateVariableForDefinition="subsetValue";static createAttributesObject(){let e=super.createAttributesObject();return e.createIntervals.defaultValue=!0,e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x")},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",defaultValue:"intervals",public:!0,toLowerCase:!0,validValues:["intervals","inequalities"]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"unnormalizedValue",newName:"unnormalizedValuePreliminary"}),e.value.shadowingInstructions.createComponentOfType="math",e.haveSingleSubsetChild={returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"]}}),definition:({dependencyValues:e,componentInfoObjects:t})=>({setValue:{haveSingleSubsetChild:1===e.mathChildren.length&&1===e.mathChildren.filter((e=>t.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"subsetOfReals"}))).length}})},e.subsetValue={stateVariablesDeterminingDependencies:["haveSingleSubsetChild"],returnDependencies({stateValues:e}){let t={haveSingleSubsetChild:{dependencyType:"stateVariable",variableName:"haveSingleSubsetChild"}};return e.haveSingleSubsetChild?t.subsetChild={dependencyType:"child",childGroups:["maths"],variableNames:["subsetValue"]}:(t.unnormalizedValuePreliminary={dependencyType:"stateVariable",variableName:"unnormalizedValuePreliminary"},t.variable={dependencyType:"stateVariable",variableName:"variable"}),t},definition({dependencyValues:e}){let t;return t=e.haveSingleSubsetChild?e.subsetChild[0].stateValues.subsetValue:buildSubsetFromMathExpression(e.unnormalizedValuePreliminary,e.variable),{setValue:{subsetValue:t}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(t.haveSingleSubsetChild)return{success:!0,instructions:[{setDependency:"subsetChild",desiredValue:e.subsetValue,childIndex:0,variableIndex:0}]};return{success:!0,instructions:[{setDependency:"unnormalizedValuePreliminary",desiredValue:mathExpressionFromSubsetValue({subsetValue:e.subsetValue,variable:t.variable,displayMode:await n.displayMode})}]}}},e.unnormalizedValue={returnDependencies:()=>({subsetValue:{dependencyType:"stateVariable",variableName:"subsetValue"},displayMode:{dependencyType:"stateVariable",variableName:"displayMode"},variable:{dependencyType:"stateVariable",variableName:"variable"}}),definition:({dependencyValues:e})=>({setValue:{unnormalizedValue:mathExpressionFromSubsetValue(e)}}),inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>({success:!0,instructions:[{setDependency:"subsetValue",desiredValue:buildSubsetFromMathExpression(e.unnormalizedValue,t.variable)}]})},e}}function mathExpressionFromSubsetValue({subsetValue:e,variable:t,displayMode:n="intervals"}){function r(e){return null===e?"_":"intervals"===n?e.closedInterval?["interval",["tuple",e.left,e.right],["tuple",!0,!0]]:e.openClosedInterval?["interval",["tuple",e.left,e.right],["tuple",!1,!0]]:e.closedOpenInterval?["interval",["tuple",e.left,e.right],["tuple",!0,!1]]:e.toMathExpression().tree:e.closedInterval?["lts",["tuple",e.left,t,e.right],["tuple",!1,!1]]:e.openClosedInterval?e.left===-1/0?["le",t,e.right]:["lts",["tuple",e.left,t,e.right],["tuple",!0,!1]]:e.closedOpenInterval?e.right===1/0?["ge",t,e.left]:["lts",["tuple",e.left,t,e.right],["tuple",!1,!0]]:e instanceof theModule.OpenInterval?e.left===-1/0?["<",t,e.right]:e.right===1/0?[">",t,e.left]:["lts",["tuple",e.left,t,e.right],["tuple",!0,!0]]:e instanceof theModule.Singleton?["=",t,e.element]:e.isEmpty()?["in",t,"∅"]:e instanceof theModule.RealLine?["in",t,"R"]:null}let a;if(e instanceof theModule.Union){let t=e.subsets.filter((e=>e instanceof theModule.Singleton)),i=e.subsets.filter((e=>e instanceof theModule.OpenInterval));for(let e=0;e(void 0===e.left?e.element:e.left)-(void 0===t.left?t.element:t.left))).map((e=>r(e)));a=s.length>1?"intervals"===n?me$3.fromAst(["union",...s]):me$3.fromAst(["or",...s]):me$3.fromAst(s[0])}else a=me$3.fromAst(r(e));return a}class Split extends CompositeComponent{static componentType="split";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"text",toLowerCase:!0,validValues:["text"]},e.splitBy={createComponentOfType:"text",createStateVariable:"splitBy",defaultValue:"letter",toLowerCase:!0,validValues:["letter","word","comma"]},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){let n=t.type;return["text"].includes(n)||(n="text"),{success:!0,newChildren:[{componentType:n,children:e}]}}}),e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.originalValue={returnDependencies:()=>({child:{dependencyType:"child",childGroups:["anything"],variableNames:["value"]}}),definition:({dependencyValues:e})=>e.child.length>0?{setValue:{originalValue:e.child[0].stateValues.value}}:{setValue:{originalValue:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.child.length>0?{success:!0,instructions:[{setDependency:"child",desiredValue:e.originalValue,childIndex:0,variableIndex:0}]}:{success:!1}},e.splitValues={returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},originalValue:{dependencyType:"stateVariable",variableName:"originalValue"},splitBy:{dependencyType:"stateVariable",variableName:"splitBy"}}),definition({dependencyValues:e}){if(null===e.originalValue)return{setValue:{splitValues:[]}};let t=[];return t="letter"===e.splitBy?[...e.originalValue]:"word"===e.splitBy?e.originalValue.split(/\s+/):"comma"===e.splitBy?e.originalValue.split(/\s*,\s*/):[e.originalValue],{setValue:{splitValues:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({splitValues:{dependencyType:"stateVariable",variableName:"splitValues"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t}){let n=e.attributes.newNamespace?.primitive,r={componentType:"textList",state:{textsShadow:await e.stateValues.splitValues},downstreamDependencies:{[e.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:"splitValues"}]}};return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:[r],parentName:e.componentName,parentCreatesNewNamespace:n,componentInfoObjects:t}).serializedComponents}}}class BestFitLine extends Line{static componentType="bestFitLine";static rendererType="line";static createAttributesObject(){let e=super.createAttributesObject();return delete e.draggable,delete e.equation,delete e.through,delete e.slope,e.points={createComponentOfType:"_pointListComponent"},e}static returnSugarInstructions(){return[]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.draggable={shadowingInstructions:{createComponentOfType:"boolean"},public:!0,forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{draggable:!1}})},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({}),definition:()=>({setValue:{nDimensions:2}})},delete e.nPointsPrescribed,delete e.basedOnSlope,delete e.dForSlope,delete e.essentialPoint1x,delete e.essentialPoint1y,delete e.equationIdentity,delete e.equation.stateVariablesDeterminingDependencies,e.equation.returnDependencies=()=>({points:{dependencyType:"attributeComponent",attributeName:"points",variableNames:["points","nDimensions"]},variables:{dependencyType:"stateVariable",variableName:"variables"}}),e.equation.definition=function({dependencyValues:e}){if(!e.points||e.points.stateValues.nDimensions<2||e.points.stateValues.points.length<1){let e=me$3.fromAst("_");return{setValue:{equation:e,coeff0:e,coeffvar1:e,coeffvar2:e}}}let t=[],n=[];for(let r of e.points.stateValues.points){let e=r.slice(0,2).map((e=>e&&e.evaluate_to_constant()));e.every(Number.isFinite)&&(t.push([1,e[0]]),n.push([e[1]]))}if(0===t.length){let e=me$3.fromAst("_");return{setValue:{equation:e,coeff0:e,coeffvar1:e,coeffvar2:e}}}t=me$3.math.matrix(t),n=me$3.math.matrix(n);let r=me$3.math.transpose(t),a=me$3.math.multiply(r,n),i=me$3.math.multiply(r,t),s=me$3.math.lusolve(i,a),o=me$3.fromAst(me$3.math.subset(s,me$3.math.index(0,0))),l=me$3.fromAst(me$3.math.subset(s,me$3.math.index(1,0))),u=me$3.fromAst(-1),c=e.variables,p=me$3.fromAst(["+",["*","a","x"],"c"]).substitute({a:l,c:o,x:c[0],y:c[1]}).simplify();return{setValue:{equation:me$3.fromAst(["=","y","r"]).substitute({r:p}),coeff0:o,coeffvar1:l,coeffvar2:u}}},delete e.equation.inverseDefinition,delete e.points.stateVariablesDeterminingDependencies,e.points.returnArrayDependenciesByKey=function(){return{globalDependencies:{coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"},variables:{dependencyType:"stateVariable",variableName:"variables"},lastPointsFromInverting:{dependencyType:"stateVariable",variableName:"lastPointsFromInverting"}}}},e}}class RegionBetweenCurveXAxis extends GraphicalComponent{static componentType="regionBetweenCurveXAxis";static createAttributesObject(){let e=super.createAttributesObject();return e.boundaryValues={createComponentOfType:"numberList",createStateVariable:"boundaryValues",defaultValue:[0,1],forRenderer:!0,public:!0},e.function={createComponentOfType:"function"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescription:e.selectedStyle.fillColorWord}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" region"}}}},e.function={additionalStateVariablesDefined:[{variableName:"haveFunction",forRenderer:!0},{variableName:"fDefinition",forRenderer:!0}],returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["numericalfs","nInputs","nOutputs","fDefinition"]}}),definition:({dependencyValues:e})=>null===e.functionAttr||1!==e.functionAttr.stateValues.nInputs||1!==e.functionAttr.stateValues.nOutputs?{setValue:{function:()=>NaN,haveFunction:!1,fDefinition:{}}}:{setValue:{function:e.functionAttr.stateValues.numericalfs[0],haveFunction:!0,fDefinition:e.functionAttr.stateValues.fDefinition}}},e}}class RegionHalfPlane extends GraphicalComponent{static componentType="regionHalfPlane";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.horizontal={createComponentOfType:"boolean",createStateVariable:"horizontal",defaultValue:!0,public:!0},e.boundaryValue={createComponentOfType:"number",createStateVariable:"boundaryValue",defaultValue:0,public:!0},e.greaterThan={createComponentOfType:"boolean",createStateVariable:"greaterThan",defaultValue:!0,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nearestPoint={returnDependencies:()=>({horizontal:{dependencyType:"stateVariable",variableName:"horizontal"},boundaryValue:{dependencyType:"stateVariable",variableName:"boundaryValue"},greaterThan:{dependencyType:"stateVariable",variableName:"greaterThan"}}),definition({dependencyValues:e}){let t=e.boundaryValue;return{setValue:{nearestPoint:function({variables:n,scales:r}){if(!Number.isFinite(t))return{};if(e.horizontal){if(e.greaterThan){if(n.x1t){let e=Object.assign({},n);return e.x1=t,e}return{}}if(e.greaterThan){if(n.x2t){let e=Object.assign({},n);return e.x2=t,e}return{}}}}}},e}}class CodeEditor extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{updateImmediateValue:this.updateImmediateValue.bind(this),updateValue:this.updateValue.bind(this),updateComponents:this.updateComponents.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="codeEditor";static variableForPlainMacro="value";static variableForPlainCopy="value";static renderChildren=!0;static processWhenJustUpdatedForNewComponent=!0;static get stateVariablesShadowedForReference(){return["value"]}static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e.bindValueTo={createComponentOfType:"text"},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:600,isAbsolute:!0},forRenderer:!0,public:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:400,isAbsolute:!0},forRenderer:!0,public:!0},e.viewerRatio={createComponentOfType:"number",createStateVariable:"viewerRatio",defaultValue:.5,forRenderer:!0,public:!0},e.showResults={createComponentOfType:"boolean",createStateVariable:"showResults",defaultValue:!1,forRenderer:!0,public:!0},e.renderedName={createPrimitiveOfType:"string"},e.staticName={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){if(e.length>0)return{success:!1};let n={componentType:"codeViewer",children:[{componentType:"renderDoenetML"}]},r=[n];if(t.renderedName&&(n.attributes={renderedName:{primitive:t.renderedName}},n.children[0].props={name:t.renderedName}),t.staticName){let e={componentType:"codeViewer",attributes:{hide:{component:{componentType:"boolean",state:{value:!0}}}},children:[{componentType:"renderDoenetML",props:{name:t.staticName}}]};r.push(e)}return{success:!0,newChildren:r}}}),e}static returnChildGroups(){return[{group:"codeViewers",componentTypes:["codeViewer"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.viewerHeight={returnDependencies:()=>({height:{dependencyType:"stateVariable",variableName:"height"},viewerRatio:{dependencyType:"stateVariable",variableName:"viewerRatio"}}),definition:function({dependencyValues:e}){if(!e.height.isAbsolute)throw Error("Codeeditor relative height not implemented");return{setValue:{viewerHeight:{size:e.height.size*e.viewerRatio,isAbsolute:!0}}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{variablesToCheck:"value",defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.value&&!n?{setValue:{immediateValue:e.value},makeEssential:{immediateValue:!0}}:{useEssentialOrDefaultValue:{immediateValue:{variablesToCheck:"immediateValue",defaultValue:e.value}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"text"}})},e.viewerChild={returnDependencies:()=>({viewerChild:{dependencyType:"child",childGroups:["codeViewers"]}}),definition:({dependencyValues:e})=>e.viewerChild.length>0?{setValue:{viewerChild:e.viewerChild}}:{setValue:{viewerChild:null}}},e}updateImmediateValue({text:e,actionId:t}){if(!this.stateValues.disabled)return this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}updateValue({actionId:e}){if(!this.stateValues.disabled&&this.stateValues.immediateValue!==this.stateValues.value){let t=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:this.stateValues.immediateValue},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}],n={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:this.stateValues.immediateValue,responseText:this.stateValues.immediateValue}};return this.stateValues.answerAncestor&&(n.context={answerAncestor:this.stateValues.answerAncestor.componentName}),this.coreFunctions.performUpdate({updateInstructions:t,actionId:e,event:n}).then((()=>{this.coreFunctions.triggerChainedActions({componentName:this.componentName}),this.attributes.staticName&&2===this.definingChildren.length&&"codeViewer"===this.definingChildren[1].componentType&&this.coreFunctions.performAction({componentName:this.definingChildren[1].componentName,actionName:"updateComponents"})}))}this.coreFunctions.resolveAction({actionId:e})}async updateComponents(){1===this.definingChildren.length&&"codeViewer"===this.definingChildren[0].componentType&&await this.coreFunctions.performAction({componentName:this.definingChildren[0].componentName,actionName:"updateComponents"})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class CodeViewer extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{updateComponents:this.updateComponents.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="codeViewer";static renderChildren=!0;static includeBlankStringChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.codeSource={createTargetComponentNames:!0},e.width={createComponentOfType:"_componentSize"},e.height={createComponentOfType:"_componentSize"},e.hasCodeEditorParent={createComponentOfType:"boolean"},e.renderedName={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){if(e.length>0)return{success:!1};let n={componentType:"renderDoenetML"};return t.codeSource&&(n.attributes={codeSource:{targetComponentNames:t.codeSource}}),t.renderedName&&(n.props={name:t.renderedName}),{success:!0,newChildren:[n]}}}),e}static returnChildGroups(){return[{group:"children",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.hasCodeEditorParent={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({codeEditorParent:{dependencyType:"parentIdentity",parentComponentType:"codeEditor"}}),definition:function({dependencyValues:e}){return e.codeEditorParent?{setValue:{hasCodeEditorParent:!0}}:{setValue:{hasCodeEditorParent:!1}}}},e.width={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},hasEssential:!0,forRenderer:!0,defaultValue:{size:600,isAbsolute:!0},returnDependencies:()=>({widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},parentWidth:{dependencyType:"parentStateVariable",variableName:"width",parentComponentType:"codeEditor"}}),definition:function({dependencyValues:e}){return e.widthAttr?{setValue:{width:e.widthAttr.stateValues.componentSize}}:e.parentWidth?{setValue:{width:e.parentWidth}}:{useEssentialOrDefaultValue:{width:!0}}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},hasEssential:!0,forRenderer:!0,defaultValue:{size:400,isAbsolute:!0},returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]},parentViewerHeight:{dependencyType:"parentStateVariable",variableName:"viewerHeight",parentComponentType:"codeEditor"}}),definition:function({dependencyValues:e}){return e.heightAttr?{setValue:{height:e.heightAttr.stateValues.componentSize}}:e.parentViewerHeight?{setValue:{height:e.parentViewerHeight}}:{useEssentialOrDefaultValue:{height:!0}}}},e.codeSourceComponentName={returnDependencies:()=>({codeSource:{dependencyType:"attributeTargetComponentNames",attributeName:"codeSource"}}),definition({dependencyValues:e}){let t;return t=1===e.codeSource?.length?e.codeSource[0].absoluteName:null,{setValue:{codeSourceComponentName:t}}}},e.codeSource={returnDependencies:()=>({codeSourceComponentName:{dependencyType:"stateVariable",variableName:"codeSourceComponentName"},codeEditorParent:{dependencyType:"parentIdentity",parentComponentType:"codeEditor"}}),definition:function({dependencyValues:e}){return e.codeSourceComponentName?{setValue:{codeSource:e.codeSourceComponentName}}:e.codeEditorParent?{setValue:{codeSource:e.codeEditorParent.componentName}}:{setValue:{codeSource:null}}}},e}async updateComponents(){1===this.definingChildren.length&&"renderDoenetML"===this.definingChildren[0].componentType&&await this.coreFunctions.performAction({componentName:this.definingChildren[0].componentName,actionName:"updateComponents"})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class RenderDoenetML extends CompositeComponent{constructor(e){super(e),Object.assign(this.actions,{updateComponents:this.updateComponents.bind(this)})}static componentType="renderDoenetML";static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="triggerUpdates";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.codeSource={createTargetComponentNames:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.codeSourceComponentName={returnDependencies:()=>({codeSource:{dependencyType:"attributeTargetComponentNames",attributeName:"codeSource"}}),definition({dependencyValues:e}){let t;return t=1===e.codeSource?.length?e.codeSource[0].absoluteName:null,{setValue:{codeSourceComponentName:t}}}},e.codeSource={returnDependencies:()=>({codeSourceComponentName:{dependencyType:"stateVariable",variableName:"codeSourceComponentName"},parentCodeSource:{dependencyType:"parentStateVariable",parentComponentType:"codeViewer",variableName:"codeSource"}}),definition:function({dependencyValues:e}){return e.codeSourceComponentName?{setValue:{codeSource:e.codeSourceComponentName}}:e.parentCodeSource?{setValue:{codeSource:e.parentCodeSource}}:{setValue:{codeSource:null}}}},e.doenetML={stateVariablesDeterminingDependencies:["codeSource"],returnDependencies:({stateValues:e})=>({doenetML:{dependencyType:"stateVariable",componentName:e.codeSource,variableName:"text",variablesOptional:!0}}),definition({dependencyValues:e}){let t="";return e.doenetML&&(t=e.doenetML,"string"!=typeof t&&(t="")),{setValue:{doenetML:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({doenetML:{dependencyType:"stateVariable",variableName:"doenetML"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.triggerUpdates={defaultValue:!0,hasEssential:!0,returnDependencies:()=>({}),markStale:()=>({updateReplacements:!0}),definition:()=>({useEssentialOrDefaultValue:{triggerUpdates:{}}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"triggerUpdates",value:e.triggerUpdates}]})},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=(await e.stateValues.doenetML).trim();r.previousDoenetML=i;try{a=(await expandDoenetMLsToFullSerializedComponents({cids:[],doenetMLs:[i],componentInfoObjects:t,flags:n})).fullSerializedComponents[0]}catch(e){return console.warn("error in user entered doenetML"),console.warn(e.message),{replacements:[]}}let s=e.componentName.split("/").map((e=>({namespace:e,componentCounts:{},namesUsed:{}})));return createComponentNames({serializedComponents:a,componentInfoObjects:t,namespaceStack:s}),restrictTNamesToNamespace({components:a,namespace:`${e.componentName}/`}),{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:a,parentName:e.componentName,parentCreatesNewNamespace:!0,componentInfoObjects:t,originalNamesAreConsistent:!0}).serializedComponents}}static async calculateReplacementChanges({component:e,componentChanges:t,componentInfoObjects:n,flags:r,workspace:a}){let i=(await e.stateValues.doenetML).trim();if(a.previousDoenetML===i)return[];a.previousDoenetML=i;let s=(await this.createSerializedReplacements({component:e,componentInfoObjects:n,flags:r,workspace:a})).replacements;return[{changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:s}]}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}async updateComponents({actionId:e}){let t=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"triggerUpdates",value:!0}];await this.coreFunctions.performUpdate({updateInstructions:t,actionId:e})}}class HasSameFactoring extends BooleanComponent{static componentType="hasSameFactoring";static rendererType="boolean";static createAttributesObject(){let e=super.createAttributesObject();return e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x")},e.restrictDivision={createComponentOfType:"boolean",createStateVariable:"restrictDivision",defaultValue:!1},e.monomialFactorMustMatch={createComponentOfType:"boolean",createStateVariable:"monomialFactorMustMatch",defaultValue:!1},e.allowOnlySignDifferences={createComponentOfType:"boolean",createStateVariable:"allowOnlySignDifferences",defaultValue:!1},e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.parsedExpression,delete e.mathChildrenByCode,e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},variable:{dependencyType:"stateVariable",variableName:"variable"},restrictDivision:{dependencyType:"stateVariable",variableName:"restrictDivision"},monomialFactorMustMatch:{dependencyType:"stateVariable",variableName:"monomialFactorMustMatch"},allowOnlySignDifferences:{dependencyType:"stateVariable",variableName:"allowOnlySignDifferences"}}),definition:function({dependencyValues:e}){if(2!==e.mathChildren.length)return{setValue:{value:!1}};let t=e.mathChildren[0].stateValues.value,n=e.mathChildren[1].stateValues.value;if(1!==checkEquality({object1:t,object2:n,isUnordered:!1,partialMatches:!1,symbolicEquality:!1,allowedErrorInNumbers:e.allowedErrorInNumbers,includeErrorInNumberExponents:e.includeErrorInNumberExponents,allowedErrorIsAbsolute:e.allowedErrorIsAbsolute,nSignErrorsMatched:e.nSignErrorsMatched}).fraction_equal)return{setValue:{value:!1}};if(Array.isArray(t.tree)&&"-"===t.tree[0]&&(t=me$3.fromAst(t.tree[1])),Array.isArray(n.tree)&&"-"===n.tree[0]&&(n=me$3.fromAst(n.tree[1])),e.restrictDivision||e.monomialFactorMustMatch||e.allowOnlySignDifferences||(Array.isArray(t.tree)&&"/"===t.tree[0]&&0===me$3.fromAst(t.tree[2]).variables().length&&(t=me$3.fromAst(t.tree[1]),Array.isArray(t.tree)&&"-"===t.tree[0]&&(t=me$3.fromAst(t.tree[1]))),Array.isArray(n.tree)&&"/"===n.tree[0]&&0===me$3.fromAst(n.tree[2]).variables().length&&(n=me$3.fromAst(n.tree[1]),Array.isArray(n.tree)&&"-"===n.tree[0]&&(n=me$3.fromAst(n.tree[1])))),t=me$3.fromAst(expandPositiveIntegerPowers(t.tree)),n=me$3.fromAst(expandPositiveIntegerPowers(n.tree)),!Array.isArray(t.tree)||"*"!==t.tree[0])return Array.isArray(n.tree)&&"*"===n.tree[0]?{setValue:{value:!1}}:{setValue:{value:!0}};if(!Array.isArray(n.tree)||"*"!==n.tree[0])return{setValue:{value:!1}};if(e.monomialFactorMustMatch||e.allowOnlySignDifferences){let e=findMonomialFromFactors(t.tree.slice(1)),r=findMonomialFromFactors(n.tree.slice(1));if(!e.equals(r)){let t=me$3.fromAst(["-",r.tree]);if(!e.equals(t))return{setValue:{value:!1}}}}if(e.allowOnlySignDifferences){let r=normalizeFactorSigns(t),a=normalizeFactorSigns(n);return{setValue:{value:r.equalsViaSyntax(a,{allowed_error_in_numbers:e.allowedErrorInNumbers,include_error_in_number_exponents:e.includeErrorInNumberExponents,allowed_error_is_absolute:e.allowedErrorIsAbsolute})}}}let r=t.tree.slice(1).filter((e=>me$3.fromAst(e).variables().length>0)),a=n.tree.slice(1).filter((e=>me$3.fromAst(e).variables().length>0));if(r.length!==a.length)return{setValue:{value:!1}};let i=0,s=0,o=0,l=0,u=e.variable.subscripts_to_strings().tree;for(let e of r){let t=me$3.fromAst(e).subscripts_to_strings().derivative(u).derivative(u).simplify();if(0===t.tree)s++;else{if(0!==t.variables().length)return{setValue:{value:!1}};i++}}for(let e of a){let t=me$3.fromAst(e).subscripts_to_strings().derivative(u).derivative(u).simplify();if(0===t.tree)l++;else{if(0!==t.variables().length)return{setValue:{value:!1}};o++}}return{setValue:{value:s===l&&i===o}}}},e}}function expandPositiveIntegerPowers(e){if(!Array.isArray(e))return e;if("^"===e[0]){let t=e[1],n=e[2];Number.isInteger(n)&&n>0&&(e=["*",...Array(n).fill(t)])}if("*"===e[0]){let t=e;e=["*"];for(let n of t.slice(1))if(Array.isArray(n)&&"^"===n[0]){let t=n[1],r=n[2];Number.isInteger(r)&&r>0?e.push(...Array(r).fill(t)):e.push(n)}else e.push(n)}return e}function findMonomialFromFactors(e){let t,n=[],r=!1;for(let t of e)if("string"==typeof t||0===me$3.fromAst(t).variables().length){if(!r){if(n.length>0)return me$3.fromAst("_");r=!0}n.push(t)}else r=!1;return t=0===n.length?1:1===n.length?n[0]:["*",...n],me$3.fromAst(t)}function normalizeFactorSigns(e){let t=e.simplify().tree;if("-"===t[0]&&(t=t[1]),"*"!==t[0])return me$3.fromAst(t).simplify();let n=["*"];for(let e of t.slice(1))if("number"==typeof e)e<0?n.push(-e):n.push(e);else if(Array.isArray(e))if("-"===e[0])n.push(e[1]);else if("+"===e[0]){let t=!1,r=e[1];if("number"==typeof r)r<0&&(t=!0);else if(Array.isArray(r))if("-"===r[0])t=!0;else if("*"===r[0]){let e=r[1];"number"==typeof e?e<0&&(t=!0):Array.isArray(e)&&"-"===e[0]&&(t=!0)}t?n.push(me$3.fromAst(["-",e]).simplify().tree):n.push(e)}else n.push(e);else n.push(e);return me$3.fromAst(n).simplify()}class DataFrame extends BaseComponent{static componentType="dataFrame";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.source={createComponentOfType:"text",createStateVariable:"source",required:!0,public:!0,forRenderer:!0},e.hasHeader={createComponentOfType:"boolean",createStateVariable:"hasHeader",defaultValue:!0,public:!0},e.columnTypes={createComponentOfType:"textList",createStateVariable:"columnTypesPrelim",defaultValue:[]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.cid={forRenderer:!0,returnDependencies:()=>({source:{dependencyType:"stateVariable",variableName:"source"}}),definition:function({dependencyValues:e}){if(!e.source||"doenet:"!==e.source.substring(0,7).toLowerCase())return{setValue:{cid:null}};let t=null,n=e.source.match(/[:&]cid=([^&]+)/i);return n&&(t=n[1]),{setValue:{cid:t}}}},e.dataFrame={stateVariablesDeterminingDependencies:["cid","source"],additionalStateVariablesDefined:[{variableName:"numRows",public:!0,shadowingInstructions:{createComponentOfType:"integer"}},{variableName:"numColumns",public:!0,shadowingInstructions:{createComponentOfType:"integer"}},{variableName:"columnTypes",public:!0,shadowingInstructions:{createComponentOfType:"textList"}},{variableName:"columnNames",public:!0,shadowingInstructions:{createComponentOfType:"textList"}}],returnDependencies:({stateValues:e})=>({fileContents:{dependencyType:"file",cid:e.cid,uri:e.source,fileType:"csv"},hasHeader:{dependencyType:"stateVariable",variableName:"hasHeader"},columnTypesPrelim:{dependencyType:"stateVariable",variableName:"columnTypesPrelim"}}),definition:function({dependencyValues:e,componentName:t}){let n=[],r=[],a=e.fileContents.trim().split("\n").map((e=>e.trim().split(",").map((e=>e.trim())))),i=a[0]?.length,s=!1;for(let e of a.slice(1))if(e.length!==i){s=!0;break}if(s)return console.warn(`Data has invalid shape. Rows has inconsistent lengths. Found in componentName :${t}`),{setValue:{dataFrame:null,numRows:u,numColumns:i,columnTypes:n,columnNames:r}};let o={},l=[];if(e.hasHeader?(o.columnNames=a[0].map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1)),e))),l=a.slice(1)):(o.columnNames=[...Array(i).keys()].map((e=>`col${e+1}`)),l=a),[...new Set(o.columnNames)].length({numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{dataFrame:{dependencyType:"stateVariable",variableName:"dataFrame"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},columnTypes:{dependencyType:"stateVariable",variableName:"columnTypes"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t){let t=0,a=0;if("number"===e.columnTypes[r]){for(let n=0;n({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({statisticsToDisplayPrelim:{dependencyType:"stateVariable",variableName:"statisticsToDisplayPrelim"}}),definition:function({dependencyValues:e}){let t=["mean","stdev","variance","stderr","count","minimum","quartile1","median","quartile3","maximum","range","sum"],n=[],r=e.statisticsToDisplayPrelim.map((e=>e.toLowerCase()));if(r.includes("default"))n=["mean","stdev","count","minimum","quartile1","median","quartile3","maximum"];else if(r.includes("all"))n=[...t];else for(let e of t)r.includes(e)&&n.push(e);return{setValue:{statisticsToDisplay:n}}}},e.sourceName={returnDependencies:()=>({source:{dependencyType:"attributeTargetComponentNames",attributeName:"source"}}),definition({dependencyValues:e}){let t;return t=1===e.source?.length?e.source[0].absoluteName:null,{setValue:{sourceName:t}}}},e.dataColumn={stateVariablesDeterminingDependencies:["sourceName"],additionalStateVariablesDefined:[{variableName:"columnName",public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0}],returnDependencies:({stateValues:e})=>({dataFrame:{dependencyType:"stateVariable",componentName:e.sourceName,variableName:"dataFrame",variableOptional:!0},desiredColumn:{dependencyType:"stateVariable",variableName:"desiredColumn"}}),definition({dependencyValues:e}){let t=null,n=null;if(e.dataFrame){let r=e.dataFrame,a=r.columnNames.indexOf(e.desiredColumn);if(-1!==a){n=e.desiredColumn,t=[];for(let e of r.data)null!==e[a]&&t.push(e[a])}}return{setValue:{dataColumn:t,columnName:n}}}},e.count={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=e.dataColumn.length),{setValue:{count:t}}}},e.sum={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=e.dataColumn.reduce(((e,t)=>e+t))),{setValue:{sum:t}}}},e.mean={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return null!==e.dataColumn&&(t=me$3.math.mean(e.dataColumn)),{setValue:{mean:t}}}},e.stdev={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.std(e.dataColumn)),{setValue:{stdev:t}}}},e.variance={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.variance(e.dataColumn)),{setValue:{variance:t}}}},e.stderr={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({stdev:{dependencyType:"stateVariable",variableName:"stdev"},count:{dependencyType:"stateVariable",variableName:"count"}}),definition({dependencyValues:e}){let t=null;return null!==e.stdev&&(t=e.stdev/Math.sqrt(e.count)),{setValue:{stderr:t}}}},e.minimum={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=Math.min(...e.dataColumn)),{setValue:{minimum:t}}}},e.maximum={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=Math.max(...e.dataColumn)),{setValue:{maximum:t}}}},e.median={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.median(e.dataColumn)),{setValue:{median:t}}}},e.quartile1={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.quantileSeq(e.dataColumn,.25)),{setValue:{quartile1:t}}}},e.quartile3={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({dataColumn:{dependencyType:"stateVariable",variableName:"dataColumn"}}),definition({dependencyValues:e}){let t=null;return e.dataColumn&&(t=me$3.math.quantileSeq(e.dataColumn,.75)),{setValue:{quartile3:t}}}},e.range={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({minimum:{dependencyType:"stateVariable",variableName:"minimum"},maximum:{dependencyType:"stateVariable",variableName:"maximum"}}),definition({dependencyValues:e}){let t=null;return null!==e.minimum&&(t=e.maximum-e.minimum),{setValue:{range:t}}}},e.summaryStatistics={forRenderer:!0,stateVariablesDeterminingDependencies:["statisticsToDisplay"],returnDependencies({stateValues:e}){let t={displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}};return e.statisticsToDisplay.includes("mean")&&(t.mean={dependencyType:"stateVariable",variableName:"mean"}),e.statisticsToDisplay.includes("stdev")&&(t.stdev={dependencyType:"stateVariable",variableName:"stdev"}),e.statisticsToDisplay.includes("variance")&&(t.variance={dependencyType:"stateVariable",variableName:"variance"}),e.statisticsToDisplay.includes("stderr")&&(t.stderr={dependencyType:"stateVariable",variableName:"stderr"}),e.statisticsToDisplay.includes("count")&&(t.count={dependencyType:"stateVariable",variableName:"count"}),e.statisticsToDisplay.includes("minimum")&&(t.minimum={dependencyType:"stateVariable",variableName:"minimum"}),e.statisticsToDisplay.includes("quartile1")&&(t.quartile1={dependencyType:"stateVariable",variableName:"quartile1"}),e.statisticsToDisplay.includes("median")&&(t.median={dependencyType:"stateVariable",variableName:"median"}),e.statisticsToDisplay.includes("quartile3")&&(t.quartile3={dependencyType:"stateVariable",variableName:"quartile3"}),e.statisticsToDisplay.includes("maximum")&&(t.maximum={dependencyType:"stateVariable",variableName:"maximum"}),e.statisticsToDisplay.includes("range")&&(t.range={dependencyType:"stateVariable",variableName:"range"}),e.statisticsToDisplay.includes("sum")&&(t.sum={dependencyType:"stateVariable",variableName:"sum"}),t},definition({dependencyValues:e,usedDefault:t}){let n={};return void 0!==e.mean&&(n.mean=roundForDisplay({value:e.mean,dependencyValues:e,usedDefault:t})),void 0!==e.stdev&&(n.stdev=roundForDisplay({value:e.stdev,dependencyValues:e,usedDefault:t})),void 0!==e.variance&&(n.variance=roundForDisplay({value:e.variance,dependencyValues:e,usedDefault:t})),void 0!==e.stderr&&(n.stderr=roundForDisplay({value:e.stderr,dependencyValues:e,usedDefault:t})),void 0!==e.count&&(n.count=roundForDisplay({value:e.count,dependencyValues:e,usedDefault:t})),void 0!==e.minimum&&(n.minimum=roundForDisplay({value:e.minimum,dependencyValues:e,usedDefault:t})),void 0!==e.quartile1&&(n.quartile1=roundForDisplay({value:e.quartile1,dependencyValues:e,usedDefault:t})),void 0!==e.median&&(n.median=roundForDisplay({value:e.median,dependencyValues:e,usedDefault:t})),void 0!==e.quartile3&&(n.quartile3=roundForDisplay({value:e.quartile3,dependencyValues:e,usedDefault:t})),void 0!==e.maximum&&(n.maximum=roundForDisplay({value:e.maximum,dependencyValues:e,usedDefault:t})),void 0!==e.range&&(n.range=roundForDisplay({value:e.range,dependencyValues:e,usedDefault:t})),void 0!==e.sum&&(n.sum=roundForDisplay({value:e.sum,dependencyValues:e,usedDefault:t})),{setValue:{summaryStatistics:n}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Chart extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{changeAxisLimits:this.changeAxisLimits.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="chart";static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createComponentOfType:"text",createStateVariable:"type",defaultValue:"histogram",toLowerCase:!0,validValues:["histogram","dotplot","frequencytable","box","bar"],forRenderer:!0},e.column={createComponentOfType:"text",createStateVariable:"desiredColumn",defaultValue:null},e.xmin={createComponentOfType:"number",createStateVariable:"xminPrelim",defaultValue:-10},e.xmax={createComponentOfType:"number",createStateVariable:"xmaxPrelim",defaultValue:10},e.ymin={createComponentOfType:"number",createStateVariable:"yminPrelim",defaultValue:-10},e.ymax={createComponentOfType:"number",createStateVariable:"ymaxPrelim",defaultValue:10},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:300,isAbsolute:!0},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:300,isAbsolute:!0},public:!0,forRenderer:!0},e.identicalAxisScales={createComponentOfType:"boolean",createStateVariable:"identicalAxisScales",defaultValue:!1,public:!0,forRenderer:!0},e.displayXAxis={createComponentOfType:"boolean",createStateVariable:"displayXAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxis={createComponentOfType:"boolean",createStateVariable:"displayYAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayXAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayXAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayYAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.xlabel={createComponentOfType:"text",createStateVariable:"xlabel",defaultValue:"",public:!0,forRenderer:!0},e.xlabelPosition={createComponentOfType:"text",createStateVariable:"xlabelPosition",defaultValue:"right",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["right","left"]},e.ylabel={createComponentOfType:"text",createStateVariable:"ylabel",defaultValue:"",public:!0,forRenderer:!0},e.ylabelPosition={createComponentOfType:"text",createStateVariable:"ylabelPosition",defaultValue:"top",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["top","bottom"]},e.ylabelAlignment={createComponentOfType:"text",createStateVariable:"ylabelAlignment",defaultValue:"left",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["left","right"]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.dataFrame={forRenderer:!0,returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent",variableNames:["dataFrame"],variablesOptional:!0}}),definition({dependencyValues:e}){console.log("definition of dataFrame",e);let t=null;return e.targetComponent?.stateValues.dataFrame&&(t=e.targetComponent.stateValues.dataFrame),{setValue:{dataFrame:t}}}},e.columnName={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"colInd",forRenderer:!0}],returnDependencies:()=>({desiredColumn:{dependencyType:"stateVariable",variableName:"desiredColumn"},dataFrame:{dependencyType:"stateVariable",variableName:"dataFrame"}}),definition({dependencyValues:e}){let t=null,n=null;return e.dataFrame&&(n=e.dataFrame.columnNames.indexOf(e.desiredColumn),-1!==n?t=e.desiredColumn:n=null),{setValue:{columnName:t,colInd:n}}}},e.xmin={stateVariablesDeterminingDependencies:["identicalAxisScales"],defaultValue:-10,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},xminPrelim:{dependencyType:"stateVariable",variableName:"xminPrelim"}};return e.identicalAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.width={dependencyType:"stateVariable",variableName:"width"},t.height={dependencyType:"stateVariable",variableName:"height"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales)return{setValue:{xmin:e.xminPrelim}};if(!t.xminPrelim)return{setValue:{xmin:e.xminPrelim}};let n=!t.xmaxPrelim,r=!t.yminPrelim,a=!t.ymaxPrelim;if(r&&a){let t=e.width.size/e.height.size,r=(e.ymaxPrelim-e.yminPrelim)*t;return n?{setValue:{xmin:e.xmaxPrelim-r}}:{setValue:{xmin:-r/2}}}return n?{setValue:{xmin:e.xmaxPrelim-20}}:{setValue:{xmin:-10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xminPrelim",desiredValue:e.xmin}]}},e.xmax={stateVariablesDeterminingDependencies:["identicalAxisScales"],defaultValue:-10,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},xmaxPrelim:{dependencyType:"stateVariable",variableName:"xmaxPrelim"}};return e.identicalAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.width={dependencyType:"stateVariable",variableName:"width"},t.height={dependencyType:"stateVariable",variableName:"height"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales)return{setValue:{xmax:e.xmaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.xminPrelim;if(s){let t=e.width.size/e.height.size,a=(e.ymaxPrelim-e.yminPrelim)*t;if(o){let t=e.xmaxPrelim-l;return{setValue:{xmax:l+Math.max(t,a)}}}return n?{setValue:{xmax:l+a}}:r?{setValue:{xmax:e.xmaxPrelim}}:{setValue:{xmax:a/2}}}return r?{setValue:{xmax:e.xmaxPrelim}}:n?{setValue:{xmax:l+20}}:{setValue:{xmax:10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xmaxPrelim",desiredValue:e.xmax}]}},e.ymin={stateVariablesDeterminingDependencies:["identicalAxisScales"],defaultValue:-10,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},yminPrelim:{dependencyType:"stateVariable",variableName:"yminPrelim"}};return e.identicalAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.width={dependencyType:"stateVariable",variableName:"width"},t.height={dependencyType:"stateVariable",variableName:"height"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales)return{setValue:{ymin:e.yminPrelim}};if(!t.yminPrelim)return{setValue:{ymin:e.yminPrelim}};let n=!t.ymaxPrelim,r=!t.xminPrelim,a=!t.xmaxPrelim,i=r&&a,s=e.width.size/e.height.size;if(i){let t=(e.xmaxPrelim-e.xminPrelim)/s;return n?{setValue:{ymin:e.ymaxPrelim-t}}:{setValue:{ymin:-t/2}}}return n?{setValue:{ymin:e.ymaxPrelim-20/s}}:{setValue:{ymin:-10/s}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"yminPrelim",desiredValue:e.ymin}]}},e.ymax={stateVariablesDeterminingDependencies:["identicalAxisScales"],defaultValue:-10,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},ymaxPrelim:{dependencyType:"stateVariable",variableName:"ymaxPrelim"}};return e.identicalAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.width={dependencyType:"stateVariable",variableName:"width"},t.height={dependencyType:"stateVariable",variableName:"height"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales)return{setValue:{ymax:e.ymaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.yminPrelim,u=e.width.size/e.height.size;if(o){let t=(e.xmaxPrelim-e.xminPrelim)/u;if(s){let n=e.ymaxPrelim-l;return{setValue:{ymax:l+Math.max(n,t)}}}return a?{setValue:{ymax:l+t}}:i?{setValue:{ymax:e.ymaxPrelim}}:{setValue:{ymax:t/2}}}return i?{setValue:{ymax:e.ymaxPrelim}}:a?{setValue:{ymax:l+20/u}}:{setValue:{ymax:10/u}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"ymaxPrelim",desiredValue:e.ymax}]}},e.xscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({xmin:{dependencyType:"stateVariable",variableName:"xmin"},xmax:{dependencyType:"stateVariable",variableName:"xmax"}}),definition:({dependencyValues:e})=>({setValue:{xscale:e.xmax-e.xmin}})},e.yscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({ymin:{dependencyType:"stateVariable",variableName:"ymin"},ymax:{dependencyType:"stateVariable",variableName:"ymax"}}),definition:({dependencyValues:e})=>({setValue:{yscale:e.ymax-e.ymin}})},e}async changeAxisLimits({xmin:e,xmax:t,ymin:n,ymax:r,actionId:a}){let i=[];return void 0!==e&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmin",value:e}),void 0!==t&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmax",value:t}),void 0!==n&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymin",value:n}),void 0!==r&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymax",value:r}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{xmin:e,xmax:t,ymin:n,ymax:r}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Legend extends GraphicalComponent{static componentType="legend";static createAttributesObject(){let e=super.createAttributesObject();return e.position={createComponentOfType:"text",createStateVariable:"position",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e.displayClosedSwatches={createComponentOfType:"boolean",createStateVariable:"displayClosedSwatches",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.graphicalElementNames={returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["graphicalDescendants"]}}),definition:({dependencyValues:e})=>e.graphAncestor?{setValue:{graphicalElementNames:e.graphAncestor.stateValues.graphicalDescendants.map((e=>e.componentName))}}:{setValue:{graphicalElementNames:null}}},e.legendElements={forRenderer:!0,stateVariablesDeterminingDependencies:["graphicalElementNames"],returnDependencies:({stateValues:e})=>{let t={labelChildren:{dependencyType:"child",childGroups:["labels"],variableNames:["value","hasLatex","forObjectComponentName"]},displayClosedSwatches:{dependencyType:"stateVariable",variableName:"displayClosedSwatches"}};if(e.graphicalElementNames){t.numGraphicalElements={dependencyType:"value",value:e.graphicalElementNames.length};for(let[n,r]of e.graphicalElementNames.entries())t[`graphicalElement${n}`]={dependencyType:"multipleStateVariables",componentName:r,variableNames:["selectedStyle","styleNumber","filled"],variablesOptional:!0},t[`graphicalElement${n}AdapterSource`]={dependencyType:"adapterSource",componentName:r},t[`graphicalElement${n}ShadowSource`]={dependencyType:"shadowSource",componentName:r}}return t},definition({dependencyValues:e,componentInfoObjects:t}){let n=[];if(e.numGraphicalElements>0){let r=[],a=[],i=[],s=[];for(let t=0;te.componentName)),l=[],u={};for(let n of e.labelChildren){let c={value:n.stateValues.value,hasLatex:n.stateValues.hasLatex};if(n.stateValues.forObjectComponentName){u[n.stateValues.forObjectComponentName]=c;let l=o.indexOf(n.stateValues.forObjectComponentName);if(-1!==l){let n=s[l];t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"point"})?r.push(n.stateValues.styleNumber):e.displayClosedSwatches&&t.allComponentClasses[n.componentType].representsClosedPath?a.push(n.stateValues.styleNumber):"legend"!==n.componentType&&i.push(n.stateValues.styleNumber)}}l.push({labelInfo:c,forObject:n.stateValues.forObjectComponentName})}for(let c of l){let l;if(c.forObject){let e=o.indexOf(c.forObject);-1!==e&&(l=s[e],s.splice(e,1),o.splice(e,1))}else for(let n=0;n({graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>e.graphAncestor?{setValue:{graphLimits:e.graphAncestor.stateValues}}:{setValue:{graphLimits:null}}},e}}class MatchesPattern extends BooleanComponent{static componentType="matchesPattern";static rendererType="boolean";static createAttributesObject(){let e=super.createAttributesObject();return e.pattern={createComponentOfType:"math"},e.allowImplicitIdentities={createComponentOfType:"boolean",createStateVariable:"allowImplicitIdentities",defaultValue:!1,public:!0},e.allowPermutations={createComponentOfType:"boolean",createStateVariable:"allowPermutations",defaultValue:!0,public:!0},e.requireNumericMatches={createComponentOfType:"boolean",createStateVariable:"requireNumericMatches",defaultValue:!1,public:!0},e.requireVariableMatches={createComponentOfType:"boolean",createStateVariable:"requireVariableMatches",defaultValue:!1,public:!0},e.excludeMatches={createComponentOfType:"mathList",createStateVariable:"excludeMatches",defaultValue:[],public:!0},e.matchExpressionWithBlanks={createComponentOfType:"boolean",createStateVariable:"matchExpressionWithBlanks",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){return 0===e.length||1===e.length&&t.componentIsSpecifiedType(e[0],"math")?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.parsedExpression,delete e.mathChildrenByCode,e.pattern={additionalStateVariablesDefined:["patternVariables"],returnDependencies:()=>({patternAttr:{dependencyType:"attributeComponent",attributeName:"pattern",variableNames:["value"]}}),definition({dependencyValues:e}){let t=[];if(!e.patternAttr)return{setValue:{pattern:"_",patternVariables:t}};let n=e.patternAttr.stateValues.value.variables(),r=703;let a=function e(a){if("_"===a){let e=numberToLetters(r);for(r++;n.includes(e);)e=numberToLetters(r),r++;return t.push(e),e}return Array.isArray(a)?[a[0],...a.slice(1).map(e)]:a}(e.patternAttr.stateValues.value.tree);return{setValue:{pattern:a,patternVariables:t}}}},e.value={additionalStateVariablesDefined:[{variableName:"allPatternMatches"}],public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({pattern:{dependencyType:"stateVariable",variableName:"pattern"},patternVariables:{dependencyType:"stateVariable",variableName:"patternVariables"},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},allowImplicitIdentities:{dependencyType:"stateVariable",variableName:"allowImplicitIdentities"},allowPermutations:{dependencyType:"stateVariable",variableName:"allowPermutations"},requireNumericMatches:{dependencyType:"stateVariable",variableName:"requireNumericMatches"},requireVariableMatches:{dependencyType:"stateVariable",variableName:"requireVariableMatches"},excludeMatches:{dependencyType:"stateVariable",variableName:"excludeMatches"},matchExpressionWithBlanks:{dependencyType:"stateVariable",variableName:"matchExpressionWithBlanks"}}),definition:function({dependencyValues:e}){if(0===e.mathChildren.length)return{setValue:{value:!1,allPatternMatches:[]}};let t=e.mathChildren[0].stateValues.value;if(t.variables().includes("_")&&!e.matchExpressionWithBlanks)return{setValue:{value:!1,allPatternMatches:[]}};let n={};if(e.requireNumericMatches){let t=e=>null!==me$3.fromAst(e).evaluate_to_constant();e.patternVariables.forEach((e=>n[e]=t))}else if(e.requireVariableMatches){let t=e=>"string"==typeof e;e.patternVariables.forEach((e=>n[e]=t))}else e.patternVariables.forEach((e=>n[e]=!0));let r={variables:n,allow_permutations:e.allowPermutations};e.allowImplicitIdentities&&(r.allow_implicit_identities=e.patternVariables);let a=t.match(e.pattern,r),i=!1,s=[];return a&&(Object.values(a).map((e=>me$3.fromAst(e))).some((t=>e.excludeMatches.some((e=>t.variables().some((t=>e.equalsViaSyntax(me$3.fromAst(t))))))))||(i=!0,s=e.patternVariables.map((e=>me$3.fromAst(a[e]))))),{setValue:{value:i,allPatternMatches:s}}}},e.nMatches={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allPatternMatches:{dependencyType:"stateVariable",variableName:"allPatternMatches"}}),definition:({dependencyValues:e})=>({setValue:{nMatches:e.allPatternMatches.length},checkForActualChange:{nMatches:!0}})},e.patternMatches={public:!0,shadowingInstructions:{createComponentOfType:"math"},isArray:!0,nDimensions:1,entryPrefixes:["patternMatch"],returnArraySizeDependencies:()=>({nMatches:{dependencyType:"stateVariable",variableName:"nMatches"}}),returnArraySize:({dependencyValues:e})=>[e.nMatches],returnArrayDependenciesByKey:()=>({globalDependencies:{allPatternMatches:{dependencyType:"stateVariable",variableName:"allPatternMatches"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({setValue:{unordered:!1}})},e.matrixSizePre={returnDependencies:()=>({rowChildren:{dependencyType:"child",childGroups:["rows"],variableNames:["nComponents"]},colChildren:{dependencyType:"child",childGroups:["columns"],variableNames:["nComponents"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["matrixSize"]},nRowsAttr:{dependencyType:"attributeComponent",attributeName:"nRows",variableNames:["value"]},nColumnsAttr:{dependencyType:"attributeComponent",attributeName:"nColumns",variableNames:["value"]}}),definition({dependencyValues:e}){let t=null,n=null;return e.nRowsAttr&&(t=e.nRowsAttr.stateValues.value,Number.isFinite(t)&&t>0||(t=null)),e.nColumnsAttr&&(n=e.nColumnsAttr.stateValues.value,Number.isFinite(n)&&n>0||(n=null)),e.rowChildren.length>0?(null===t&&(t=e.rowChildren.length),null===n&&(n=Math.max(1,...e.rowChildren.map((e=>e.stateValues.nComponents))))):e.colChildren.length>0?(null===n&&(n=e.colChildren.length),null===t&&(t=Math.max(1,...e.colChildren.map((e=>e.stateValues.nComponents))))):1===e.mathChildren.length?(null===t&&(t=e.mathChildren[0].stateValues.matrixSize[0]),null===n&&(n=e.mathChildren[0].stateValues.matrixSize[1])):null===t?null===n?(t=0,n=0):t=1:null===n&&(n=1),{setValue:{matrixSizePre:[t,n]}}}},e.matrixPre={isArray:!0,nDimensions:2,hasEssential:!0,returnArraySizeDependencies:()=>({matrixSizePre:{dependencyType:"stateVariable",variableName:"matrixSizePre"}}),returnArraySize:({dependencyValues:e})=>e.matrixSizePre,returnArrayDependenciesByKey:({arrayKeys:e})=>{let t={};for(let n of e){let[e,r]=n.split(",");t[n]={rowChild:{dependencyType:"child",childGroups:["rows"],childIndices:[e],variableNames:["math"+(Number(r)+1)]},colChild:{dependencyType:"child",childGroups:["columns"],childIndices:[r],variableNames:["math"+(Number(e)+1)]},mathChild:{dependencyType:"child",childGroups:["maths"],childIndices:[0],variableNames:["matrixEntry"+(Number(e)+1)+"_"+(Number(r)+1)]}}}return{globalDependencies:{defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"},rowChildIdentities:{dependencyType:"child",childGroups:["rows"]},colChildIdentities:{dependencyType:"child",childGroups:["columns"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a={},i={},s=e.rowChildIdentities.length>0,o=e.colChildIdentities.length>0;for(let r of n){let n,[l,u]=r.split(",");n=s?t[r].rowChild[0]?.stateValues["math"+(Number(u)+1)]:o?t[r].colChild[0]?.stateValues["math"+(Number(l)+1)]:t[r].mathChild[0]?.stateValues["matrixEntry"+(Number(l)+1)+"_"+(Number(u)+1)],void 0===n?i[r]={defaultValue:e.defaultEntry}:a[r]=n}return{setValue:{matrixPre:a},useEssentialOrDefaultValue:{matrixPre:i}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r}){let a=[],i={},s=t.rowChildIdentities.length>0,o=t.colChildIdentities.length>0;for(let t in e.matrixPre){let[l,u]=t.split(",");if(s){let s=n[t].rowChild[0]?.stateValues["math"+(Number(u)+1)];void 0===s?i[t]=e.matrixPre[t]:a.push({setDependency:r[t].rowChild,desiredValue:e.matrixPre[t],childIndex:0,variableIndex:0})}else if(o){let s=n[t].colChild[0]?.stateValues["math"+(Number(l)+1)];void 0===s?i[t]=e.matrixPre[t]:a.push({setDependency:r[t].colChild,desiredValue:e.matrixPre[t],childIndex:0,variableIndex:0})}else{let s=n[t].mathChild[0]?.stateValues["matrixEntry"+(Number(l)+1)+"_"+(Number(u)+1)];void 0===s?i[t]=e.matrixPre[t]:a.push({setDependency:r[t].mathChild,desiredValue:e.matrixPre[t],childIndex:0,variableIndex:0})}}return Object.keys(i).length>0&&a.push({setEssentialValue:"matrixPre",value:i}),{success:!0,instructions:a}}},e.unnormalizedValue={returnDependencies:()=>({matrixPre:{dependencyType:"stateVariable",variableName:"matrixPre"},matrixSizePre:{dependencyType:"stateVariable",variableName:"matrixSizePre"}}),definition({dependencyValues:e}){let t=["tuple"];for(let n=0;ne.tree))]);return{setValue:{unnormalizedValue:me$3.fromAst(["matrix",["tuple",...e.matrixSizePre],t])}}},inverseDefinition({dependencyValues:e,desiredStateVariableValues:t}){let n=t.unnormalizedValue.tree;if(!Array.isArray(n)||"matrix"!==n[0]||n[1]?.[1]!==e.matrixSizePre[0]||n[1]?.[2]!==e.matrixSizePre[1])return{success:!1};let r={};for(let t=0;t({modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"}}),definition:({dependencyValues:e})=>({setValue:{canBeModified:e.modifyIndirectly&&!e.fixed}})},e}}class EigenDecomposition extends BaseComponent{static componentType="eigenDecomposition";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:14,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.decomposition={returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition({dependencyValues:e}){if(0===e.mathChild.length)return{setValue:{decomposition:null}};let t=e.mathChild[0].stateValues.value.tree;if(!Array.isArray(t)||"matrix"!==t[0])return{setValue:{decomposition:null}};let n=t[1][1],r=t[1][2];if(!Number.isInteger(n)||r!==n)return{setValue:{decomposition:null}};let a,i=[];for(let e=0;e({decomposition:{dependencyType:"stateVariable",variableName:"decomposition"}}),returnArraySize({dependencyValues:e}){let t;return t=e.decomposition?e.decomposition.values.length:0,[t]},returnArrayDependenciesByKey:()=>({globalDependencies:{decomposition:{dependencyType:"stateVariable",variableName:"decomposition"}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n=[];for(let r=0;r"eigenvectorX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("eigenvectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("eigenvectors"===t)return 1===e.length?"eigenvector"+e[0]:`eigenvectorX${e[0]}_${e[1]}`;if("eigenvector"===t.slice(0,11)){let n=Number(t.slice(11));if(Number.isInteger(n)&&n>0)return`eigenvectorX${n}_${e[0]}`}return null},entryPrefixes:["eigenvectorX","eigenvector"],returnArraySizeDependencies:()=>({decomposition:{dependencyType:"stateVariable",variableName:"decomposition"}}),returnArraySize({dependencyValues:e}){let t;return t=e.decomposition?e.decomposition.values.length:0,[t,t]},returnArrayDependenciesByKey:()=>({globalDependencies:{decomposition:{dependencyType:"stateVariable",variableName:"decomposition"}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n={};for(let r=0;rme$3.math.divide(e,i)));for(let e=0;e({mathTextLikeChildren:{dependencyType:"child",childGroups:["mathTextLike"],variableNames:["text","latex"]}}),e.value.definition=function({dependencyValues:e}){if(0===e.mathTextLikeChildren.length)return{useEssentialOrDefaultValue:{value:!0}};let t="";for(let n of e.mathTextLikeChildren)"string"==typeof n?t+=n:void 0!==n.stateValues.latex?t+=n.stateValues.latex:t+=n.stateValues.text;return{setValue:{value:t}}},e.value.inverseDefinition=function({desiredStateVariableValues:e,dependencyValues:t}){let n=t.mathTextLikeChildren.length;return n>1?{success:!1}:1===n?{success:!0,instructions:[{setDependency:"textLikeChildren",desiredValue:e.value,childIndex:0,variableIndex:void 0===t.textLikeChildren[0].stateValues?.latex?0:1}]}:{success:!0,instructions:[{setEssentialValue:"value",value:null===e.value?"":String(e.value)}]}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.text}]})},e.latex={isAlias:!0,targetVariableName:"value"},e}}const unitConversions={"":1,px:1,pixel:1,pixels:1,"%":1,em:100,in:96,inch:96,inches:96,pt:1.333333333333,mm:3.7795296,millimeter:3.7795296,millimeters:3.7795296,cm:37.795296,centimeter:37.795296,centimeters:37.795296};class ComponentSize extends InlineComponent{static componentType="_componentSize";static rendererType="text";static primaryStateVariableForDefinition="componentSize";static stateVariableForAttributeValue="componentSize";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/..+/,replacementFunction:function({matchedChildren:e}){let t=e[e.length-1];if("string"==typeof t){let n=/([a-zA-z]+|%)$/,r=t.trim(),a=r.match(n);if(a){let t=a[1];if(t in unitConversions){let n=r.slice(0,a.index),i=e.slice(0,e.length-1);return n.length>0&&i.push(n),{success:!0,newChildren:[{componentType:"number",children:i},t]}}}}return{success:!0,newChildren:[{componentType:"number",children:e}]}}}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"numbers",componentTypes:["number"]},{group:"componentSizes",componentTypes:["_componentSize"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.componentSize={public:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},hasEssential:!0,returnDependencies:()=>({componentSizeChild:{dependencyType:"child",childGroups:["componentSizes"],variableNames:["componentSize"]},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},stringChild:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},parentDefaultAbsoluteSize:{dependencyType:"parentStateVariable",variableName:"defaultAbsoluteSize"}}),definition({dependencyValues:e}){let t=void 0!==e.parentDefaultAbsoluteSize&&e.parentDefaultAbsoluteSize;if(0===e.stringChild.length)return 0===e.numberChild.length?0===e.componentSizeChild.length?{useEssentialOrDefaultValue:{componentSize:{defaultValue:{size:100,isAbsolute:t}}}}:{setValue:{componentSize:e.componentSizeChild[0].stateValues.componentSize}}:{setValue:{componentSize:{size:e.numberChild[0].stateValues.value,isAbsolute:!0}}};{let t,n;if(e.numberChild.length>0)t=e.numberChild[0].stateValues.value,n=e.stringChild[0].trim();else{let r=e.stringChild[0].trim().match(/^(-?[\d.]+)\s*(.*)$/);if(null===r)return{setValue:{componentSize:null}};t=r[1],n=r[2].trim()}if(t=Number(t),!Number.isFinite(t))return{setValue:{componentSize:null}};let r=!("%"===n||"em"===n),a=unitConversions[n];return void 0===a&&(a=1),{setValue:{componentSize:{size:a*t,isAbsolute:r}}}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(0===t.stringChild.length)return 0===t.numberChild.length?0===t.componentSizeChild.length?{success:!0,instructions:[{setEssentialValue:"componentSize",value:e.componentSize}]}:{success:!0,instructions:[{setDependency:"componentSizeChild",desiredValue:e.componentSize,childIndex:0,variableIndex:0}]}:e.componentSize.isAbsolute?{success:!0,instructions:[{setDependency:"numberChild",desiredValue:e.componentSize.size,childIndex:0,variableIndex:0}]}:{success:!1};if(t.numberChild.length>0){let n=t.stringChild[0].trim(),r=!("%"===n||"em"===n);if(e.componentSize.isAbsolute!==r)return{success:!1};let a=unitConversions[n];return void 0===a&&(a=1),{success:!0,instructions:[{setDependency:"numberChild",desiredValue:e.componentSize.size/a,childIndex:0,variableIndex:0}]}}{let t=e.componentSize.size;return e.componentSize.isAbsolute?t+="px":t+="%",{success:!0,instructions:[{setDependency:"stringChild",desiredValue:t,childIndex:0,variableIndex:0}]}}}},e.number={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({componentSize:{dependencyType:"stateVariable",variableName:"componentSize"}}),definition({dependencyValues:e}){let t=null;return e.componentSize&&(t=e.componentSize.size),{setValue:{number:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(!t.componentSize)return{success:!1};return{success:!0,instructions:[{setDependency:"componentSize",desiredValue:{size:e.number,isAbsolute:t.componentSize.isAbsolute}}]}}},e.math=mathStateVariableFromNumberStateVariable({numberVariableName:"number",mathVariableName:"math",isPublic:!0}),e.isAbsolute={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({componentSize:{dependencyType:"stateVariable",variableName:"componentSize"}}),definition({dependencyValues:e}){let t=null;return e.componentSize&&(t=e.componentSize.isAbsolute),{setValue:{isAbsolute:t}}}},e.text={forRenderer:!0,returnDependencies:()=>({componentSize:{dependencyType:"stateVariable",variableName:"componentSize"}}),definition({dependencyValues:e}){let t="";return e.componentSize&&(t=e.componentSize.size,e.componentSize.isAbsolute?t+="px":t+="%"),{setValue:{text:t}}}},e}static adapters=["number","math"]}class ComponentSizeList extends BaseComponent{static componentType="_componentSizeList";static rendererType="asList";static renderChildren=!0;static stateVariableForAttributeValue="componentSizes";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=[],n=[],r=function(){n.length>0&&(t.push({componentType:"_componentSize",children:n}),n=[])};for(let t of e)if("string"==typeof t){let e=t.split(/\s+/);0===e[0].length&&(r(),e=e.slice(1));for(let[t,a]of e.entries())a.length>0?(n.push(a),t({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({componentSizeListChildren:{dependencyType:"child",childGroups:["componentSizeLists"],variableNames:["nComponents"]},componentSizeAndComponentSizeListChildren:{dependencyType:"child",childGroups:["componentSizes","componentSizeLists"],skipComponentNames:!0}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;for(let[i,s]of e.componentSizeAndComponentSizeListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"_componentSizeList"})){let t=e.componentSizeListChildren[a];a++;for(let e=0;e({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={componentSizeAndComponentSizeListChildren:{dependencyType:"child",childGroups:["componentSizes","componentSizeLists"],variableNames:["componentSize","componentSize"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentInfoObjects:r}){let a={};for(let i of n){let n=t[i].componentSizeAndComponentSizeListChildren[0];if(n)if(r.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"_componentSizeList"})){let t=e.childIndexByArrayKey[i][1]+1;a[i]=n.stateValues["componentSize"+t]}else a[i]=n.stateValues.componentSize}return{setValue:{componentSizes:a}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a,componentInfoObjects:i}){let s=[];for(let t in e.componentSizes){if(!n[t])continue;let a=n[t].componentSizeAndComponentSizeListChildren[0];a&&(i.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_componentSizeList"})?s.push({setDependency:r[t].componentSizeAndComponentSizeListChildren,desiredValue:e.componentSizes[t],childIndex:0,variableIndex:1}):s.push({setDependency:r[t].componentSizeAndComponentSizeListChildren,desiredValue:e.componentSizes[t],childIndex:0,variableIndex:0}))}return{success:!0,instructions:s}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"componentSizes"},e}}var ComponentSize$1=Object.freeze({__proto__:null,ComponentSize:ComponentSize,ComponentSizeList:ComponentSizeList});const componentTypeArray=[...Object.values(Aliases),...Object.values(MMeMen),...Object.values(MdMdnMrow),...Object.values(BooleanOperators),...Object.values(BooleanOperatorsOfMath),...Object.values(MathOperators),...Object.values(FunctionOperators),...Object.values(TextOperatorsOfMath),...Object.values(Extrema$1),...Object.values(ParagraphMarkup),...Object.values(SingleCharacterComponents),...Object.values(Sectioning),...Object.values(Lists),...Object.values(DynamicalSystems),...Object.values(Chemistry),...Object.values(FeedbackDefinitions$1),...Object.values(StyleDefinitions$1),...Object.values(SideBySide$1),...Object.values(ComponentWithSelectableType$1),...Object.values(Indexing),...Object.values(Divisions),...Object.values(Verbatim),...Object.values(Paginator$1),...Object.values(MatrixInput$1),Document,Text,TextList$1,TextList,P$2,BooleanComponent,BooleanList,MathComponent,MathList,TupleList,NumberList,NumberListFromString,Copy,Extract,Collect,Ref,Point,Coords,Line,LineSegment,Ray,Polyline,Polygon,Triangle,Rectangle,Circle,Parabola,Curve,BezierControls,ControlVectors,Vector,Angle,Answer,Award,When,MathInput,Textinput,BooleanInput,Choiceinput,Choice,NumberComponent,Integer,Graph$1,Variables,Variable,Function$1,Interval,Template,Option$1,Sequence,Slider,Spreadsheet,DiscreteSimulationResultList,DiscreteSimulationResultPolyline,Cell,Row,Column,CellBlock,Tabular,Table,Figure,Markers,Panel,Map$1,Sources,Constraints,ConstrainToGrid,ConstrainToGraph,AttractToGrid,ConstrainTo,AttractTo,ConstraintUnion,AttractToConstraint,Intersection,ConstrainToAngles,AttractToAngles,ConditionalContent,AsList,VariantControl,TextListFromString,SelectFromSequence,Select,Group,AnimateFromSequence,Evaluate,SelectRandomNumbers,SampleRandomNumbers,Substitute,PeriodicSet,Image,Video,Embed,Hint,Solution,IntComma,Pluralize,Feedback,CollaborateGroups,CollaborateGroupSetup,ConsiderAsResponses,Case,Lorem,UpdateValue,CallAction,triggerSet,FunctionIterates,Module,CustomAttribute,Setup,Footnote,Caption,Endpoint,Sort,Shuffle,SolveEquations,SolutionContainer,SubsetOfRealsInput,SubsetOfReals,Split,BestFitLine,RegionBetweenCurveXAxis,RegionHalfPlane,CodeEditor,CodeViewer,RenderDoenetML,HasSameFactoring,DataFrame,SummaryStatistics,Chart,Legend,Label,MatchesPattern,Matrix,EigenDecomposition,Latex,BaseComponent,InlineComponent,BlockComponent,GraphicalComponent,ConstraintComponent,Input,CompositeComponent,PointListComponent,IntervalListComponent,LineListComponent,VectorListComponent,AngleListComponent,BooleanOperator,BooleanBaseOperatorOfMath,MathOperator,MathOperatorOneInput,FunctionOperator,...Object.values(ComponentSize$1),SectioningComponent,InlineRenderInlineChildren,TextOrInline,SingleCharacter];function allComponentClasses(){const e={},t=new Set;for(let n of componentTypeArray){let r=n.componentType;if(void 0===r)throw Error("Cannot create component as componentType is undefined for class "+n);let a=r.toLowerCase();if(t.has(a))throw Error("component type "+r+" defined in two classes");e[r]=n,t.add(a)}return e}function componentTypesCreatingVariants(){const e={},t=new Set;for(let n of componentTypeArray)if(n.createsVariants){let r=n.componentType;if(void 0===r)throw Error("Cannot create component as componentType is undefined for class "+n);let a=r.toLowerCase();if(t.has(a))throw Error("component type "+r+" defined in two classes");e[r]=n,t.add(a)}return e}function createComponentInfoObjects(){let e=allComponentClasses(),t=componentTypesCreatingVariants(),n={};for(let t in e)n[t.toLowerCase()]=t;let r={};for(let t in e)Object.defineProperty(r,t,{get:function(){let n=e[t].returnStateVariableInfo();return delete r[t],r[t]=n}.bind(this),configurable:!0});let a={};for(let t in e)Object.defineProperty(a,t,{get:function(){let n=e[t].returnStateVariableInfo({onlyPublic:!0});return delete a[t],a[t]=n}.bind(this),configurable:!0});function i({inheritedComponentType:t,baseComponentType:n}){if(t===n)return!0;if("string"===t)return"_base"===n||"_inline"===n;if("string"===n)return!1;let r=e[n];return!!r&&r.isPrototypeOf(e[t])}let s=(e,t)=>i({inheritedComponentType:e,baseComponentType:t});return{allComponentClasses:e,componentTypesCreatingVariants:t,componentTypeLowerCaseMapping:n,isInheritedComponentType:i,isCompositeComponent:function({componentType:t,includeNonStandard:n=!0}){let r=e[t];return!!r&&(i({inheritedComponentType:t,baseComponentType:"_composite"})&&(n||!r.treatAsComponentForRecursiveReplacements))},stateVariableInfo:r,publicStateVariableInfo:a,componentIsSpecifiedType:(e,t)=>s(e.componentType,t)||s(e.attributes?.createComponentOfType?.primitive,t)}}function promisifyRequest(e){return new Promise(((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)}))}function createStore(e,t){const n=indexedDB.open(e);n.onupgradeneeded=()=>n.result.createObjectStore(t);const r=promisifyRequest(n);return(e,n)=>r.then((r=>n(r.transaction(t,e).objectStore(t))))}let defaultGetStoreFunc;function defaultGetStore(){return defaultGetStoreFunc||(defaultGetStoreFunc=createStore("keyval-store","keyval")),defaultGetStoreFunc}function set(e,t,n=defaultGetStore()){return n("readwrite",(n=>(n.put(t,e),promisifyRequest(n.transaction))))}const toastType=Object.freeze({ERROR:{timeout:-1,background:"rgba(193, 41, 46, 1)",gradientEnd:"rgba()"},ALERT:{timeout:-1,background:"rgba(255, 230, 0, 1)"},ACTION:{timeout:-1,background:"rgba()"},INFO:{timeout:3e3,background:"rgba(26, 90, 153,1)"},SUCCESS:{timeout:3e3,background:"rgba(41, 193, 67, 1)"},CONFIRMATION:{timeout:5e3,background:"rgba(26,90,153,1)"}});var axios$3={exports:{}},axios$2={exports:{}},bind$2=function(e,t){return function(){for(var n=new Array(arguments.length),r=0;r0;)s[i=r[a]]||(t[i]=e[i],s[i]=!0);e=Object.getPrototypeOf(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t}function endsWith(e,t,n){e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;var r=e.indexOf(t,n);return-1!==r&&r===n}function toArray(e){if(!e)return null;var t=e.length;if(isUndefined(t))return null;for(var n=new Array(t);t-- >0;)n[t]=e[t];return n}var isTypedArray=(TypedArray="undefined"!=typeof Uint8Array&&Object.getPrototypeOf(Uint8Array),function(e){return TypedArray&&e instanceof TypedArray}),TypedArray,utils$9={isArray:isArray$1,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer$1,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString,isNumber:isNumber,isObject:isObject,isPlainObject:isPlainObject,isUndefined:isUndefined,isDate:isDate,isFile:isFile,isBlob:isBlob,isFunction:isFunction,isStream:isStream,isURLSearchParams:isURLSearchParams,isStandardBrowserEnv:isStandardBrowserEnv,forEach:forEach,merge:merge,extend:extend,trim:trim,stripBOM:stripBOM,inherits:inherits,toFlatObject:toFlatObject,kindOf:kindOf,kindOfTest:kindOfTest,endsWith:endsWith,toArray:toArray,isTypedArray:isTypedArray,isFileList:isFileList},utils$8=utils$9;function encode(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var buildURL$1=function(e,t,n){if(!t)return e;var r;if(n)r=n(t);else if(utils$8.isURLSearchParams(t))r=t.toString();else{var a=[];utils$8.forEach(t,(function(e,t){null!=e&&(utils$8.isArray(e)?t+="[]":e=[e],utils$8.forEach(e,(function(e){utils$8.isDate(e)?e=e.toISOString():utils$8.isObject(e)&&(e=JSON.stringify(e)),a.push(encode(t)+"="+encode(e))})))})),r=a.join("&")}if(r){var i=e.indexOf("#");-1!==i&&(e=e.slice(0,i)),e+=(-1===e.indexOf("?")?"?":"&")+r}return e},utils$7=utils$9;function InterceptorManager$1(){this.handlers=[]}InterceptorManager$1.prototype.use=function(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1},InterceptorManager$1.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},InterceptorManager$1.prototype.forEach=function(e){utils$7.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var InterceptorManager_1=InterceptorManager$1,utils$6=utils$9,normalizeHeaderName$1=function(e,t){utils$6.forEach(e,(function(n,r){r!==t&&r.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[r])}))},AxiosError_1,hasRequiredAxiosError;function requireAxiosError(){if(hasRequiredAxiosError)return AxiosError_1;hasRequiredAxiosError=1;var e=utils$9;function t(e,t,n,r,a){Error.call(this),this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),a&&(this.response=a)}e.inherits(t,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var n=t.prototype,r={};return["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED"].forEach((function(e){r[e]={value:e}})),Object.defineProperties(t,r),Object.defineProperty(n,"isAxiosError",{value:!0}),t.from=function(r,a,i,s,o,l){var u=Object.create(n);return e.toFlatObject(r,u,(function(e){return e!==Error.prototype})),t.call(u,r.message,a,i,s,o),u.name=r.name,l&&Object.assign(u,l),u},AxiosError_1=t}var transitional={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,inited=!1;function init(){inited=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,n=e.length;t0)throw new Error("Invalid string. Length must be a multiple of 4");i="="===e[o-2]?2:"="===e[o-1]?1:0,s=new Arr(3*o/4-i),r=i>0?o-4:o;var l=0;for(t=0,n=0;t>16&255,s[l++]=a>>8&255,s[l++]=255&a;return 2===i?(a=revLookup[e.charCodeAt(t)]<<2|revLookup[e.charCodeAt(t+1)]>>4,s[l++]=255&a):1===i&&(a=revLookup[e.charCodeAt(t)]<<10|revLookup[e.charCodeAt(t+1)]<<4|revLookup[e.charCodeAt(t+2)]>>2,s[l++]=a>>8&255,s[l++]=255&a),s}function tripletToBase64(e){return lookup[e>>18&63]+lookup[e>>12&63]+lookup[e>>6&63]+lookup[63&e]}function encodeChunk(e,t,n){for(var r,a=[],i=t;il?l:o+s));return 1===r?(t=e[n-1],a+=lookup[t>>2],a+=lookup[t<<4&63],a+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],a+=lookup[t>>10],a+=lookup[t>>4&63],a+=lookup[t<<2&63],a+="="),i.push(a),i.join("")}function read(e,t,n,r,a){var i,s,o=8*a-r-1,l=(1<>1,c=-7,p=n?a-1:0,d=n?-1:1,m=e[t+p];for(p+=d,i=m&(1<<-c)-1,m>>=-c,c+=o;c>0;i=256*i+e[t+p],p+=d,c-=8);for(s=i&(1<<-c)-1,i>>=-c,c+=r;c>0;s=256*s+e[t+p],p+=d,c-=8);if(0===i)i=1-u;else{if(i===l)return s?NaN:1/0*(m?-1:1);s+=Math.pow(2,r),i-=u}return(m?-1:1)*s*Math.pow(2,i-r)}function write(e,t,n,r,a,i){var s,o,l,u=8*i-a-1,c=(1<>1,d=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,m=r?0:i-1,h=r?1:-1,f=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,s=c):(s=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-s))<1&&(s--,l*=2),(t+=s+p>=1?d/l:d*Math.pow(2,1-p))*l>=2&&(s++,l/=2),s+p>=c?(o=0,s=c):s+p>=1?(o=(t*l-1)*Math.pow(2,a),s+=p):(o=t*Math.pow(2,p-1)*Math.pow(2,a),s=0));a>=8;e[n+m]=255&o,m+=h,o/=256,a-=8);for(s=s<0;e[n+m]=255&s,m+=h,s/=256,u-=8);e[n+m-h]|=128*f}var toString={}.toString,isArray=Array.isArray||function(e){return"[object Array]"==toString.call(e)},INSPECT_MAX_BYTES=50;function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(e,t){if(kMaxLength()=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|e}function internalIsBuffer(e){return!(null==e||!e._isBuffer)}function byteLength(e,t){if(internalIsBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return utf8ToBytes(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return base64ToBytes(e).length;default:if(r)return utf8ToBytes(e).length;t=(""+t).toLowerCase(),r=!0}}function slowToString(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return hexSlice(this,t,n);case"utf8":case"utf-8":return utf8Slice(this,t,n);case"ascii":return asciiSlice(this,t,n);case"latin1":case"binary":return latin1Slice(this,t,n);case"base64":return base64Slice(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function swap(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function bidirectionalIndexOf(e,t,n,r,a){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)return-1;n=0}if("string"==typeof t&&(t=Buffer.from(t,r)),internalIsBuffer(t))return 0===t.length?-1:arrayIndexOf(e,t,n,r,a);if("number"==typeof t)return t&=255,Buffer.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):arrayIndexOf(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(e,t,n,r,a){var i,s=1,o=e.length,l=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,o/=2,l/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(a){var c=-1;for(i=n;io&&(n=o-l),i=n;i>=0;i--){for(var p=!0,d=0;da&&(r=a):r=a;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");r>i/2&&(r=i/2);for(var s=0;s239?4:u>223?3:u>191?2:1;if(a+p<=n)switch(p){case 1:u<128&&(c=u);break;case 2:128==(192&(i=e[a+1]))&&(l=(31&u)<<6|63&i)>127&&(c=l);break;case 3:i=e[a+1],s=e[a+2],128==(192&i)&&128==(192&s)&&(l=(15&u)<<12|(63&i)<<6|63&s)>2047&&(l<55296||l>57343)&&(c=l);break;case 4:i=e[a+1],s=e[a+2],o=e[a+3],128==(192&i)&&128==(192&s)&&128==(192&o)&&(l=(15&u)<<18|(63&i)<<12|(63&s)<<6|63&o)>65535&&l<1114112&&(c=l)}null===c?(c=65533,p=1):c>65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|1023&c),r.push(c),a+=p}return decodeCodePointsArray(r)}Buffer.TYPED_ARRAY_SUPPORT=void 0===global$1.TYPED_ARRAY_SUPPORT||global$1.TYPED_ARRAY_SUPPORT,kMaxLength(),Buffer.poolSize=8192,Buffer._augment=function(e){return e.__proto__=Buffer.prototype,e},Buffer.from=function(e,t,n){return from(null,e,t,n)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array),Buffer.alloc=function(e,t,n){return alloc(null,e,t,n)},Buffer.allocUnsafe=function(e){return allocUnsafe(null,e)},Buffer.allocUnsafeSlow=function(e){return allocUnsafe(null,e)},Buffer.isBuffer=isBuffer,Buffer.compare=function(e,t){if(!internalIsBuffer(e)||!internalIsBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,a=0,i=Math.min(n,r);a0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},Buffer.prototype.compare=function(e,t,n,r,a){if(!internalIsBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(a>>>=0)-(r>>>=0),s=(n>>>=0)-(t>>>=0),o=Math.min(i,s),l=this.slice(r,a),u=e.slice(t,n),c=0;ca)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return hexWrite(this,e,t,n);case"utf8":case"utf-8":return utf8Write(this,e,t,n);case"ascii":return asciiWrite(this,e,t,n);case"latin1":case"binary":return latin1Write(this,e,t,n);case"base64":return base64Write(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(e){var t=e.length;if(t<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,e);for(var n="",r=0;rr)&&(n=r);for(var a="",i=t;in)throw new RangeError("Trying to access beyond buffer length")}function checkInt(e,t,n,r,a,i){if(!internalIsBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||te.length)throw new RangeError("Index out of range")}function objectWriteUInt16(e,t,n,r){t<0&&(t=65535+t+1);for(var a=0,i=Math.min(e.length-n,2);a>>8*(r?a:1-a)}function objectWriteUInt32(e,t,n,r){t<0&&(t=4294967295+t+1);for(var a=0,i=Math.min(e.length-n,4);a>>8*(r?a:3-a)&255}function checkIEEE754(e,t,n,r,a,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function writeFloat(e,t,n,r,a){return a||checkIEEE754(e,t,n,4),write(e,t,n,r,23,4),n+4}function writeDouble(e,t,n,r,a){return a||checkIEEE754(e,t,n,8),write(e,t,n,r,52,8),n+8}Buffer.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t0&&(a*=256);)r+=this[e+--t]*a;return r},Buffer.prototype.readUInt8=function(e,t){return t||checkOffset(e,1,this.length),this[e]},Buffer.prototype.readUInt16LE=function(e,t){return t||checkOffset(e,2,this.length),this[e]|this[e+1]<<8},Buffer.prototype.readUInt16BE=function(e,t){return t||checkOffset(e,2,this.length),this[e]<<8|this[e+1]},Buffer.prototype.readUInt32LE=function(e,t){return t||checkOffset(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},Buffer.prototype.readUInt32BE=function(e,t){return t||checkOffset(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},Buffer.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||checkOffset(e,t,this.length);for(var r=this[e],a=1,i=0;++i=(a*=128)&&(r-=Math.pow(2,8*t)),r},Buffer.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||checkOffset(e,t,this.length);for(var r=t,a=1,i=this[e+--r];r>0&&(a*=256);)i+=this[e+--r]*a;return i>=(a*=128)&&(i-=Math.pow(2,8*t)),i},Buffer.prototype.readInt8=function(e,t){return t||checkOffset(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},Buffer.prototype.readInt16LE=function(e,t){t||checkOffset(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},Buffer.prototype.readInt16BE=function(e,t){t||checkOffset(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},Buffer.prototype.readInt32LE=function(e,t){return t||checkOffset(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},Buffer.prototype.readInt32BE=function(e,t){return t||checkOffset(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},Buffer.prototype.readFloatLE=function(e,t){return t||checkOffset(e,4,this.length),read(this,e,!0,23,4)},Buffer.prototype.readFloatBE=function(e,t){return t||checkOffset(e,4,this.length),read(this,e,!1,23,4)},Buffer.prototype.readDoubleLE=function(e,t){return t||checkOffset(e,8,this.length),read(this,e,!0,52,8)},Buffer.prototype.readDoubleBE=function(e,t){return t||checkOffset(e,8,this.length),read(this,e,!1,52,8)},Buffer.prototype.writeUIntLE=function(e,t,n,r){(e=+e,t|=0,n|=0,r)||checkInt(this,e,t,n,Math.pow(2,8*n)-1,0);var a=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+a]=e/i&255;return t+n},Buffer.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},Buffer.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):objectWriteUInt16(this,e,t,!0),t+2},Buffer.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):objectWriteUInt16(this,e,t,!1),t+2},Buffer.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):objectWriteUInt32(this,e,t,!0),t+4},Buffer.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):objectWriteUInt32(this,e,t,!1),t+4},Buffer.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);checkInt(this,e,t,n,a-1,-a)}var i=0,s=1,o=0;for(this[t]=255&e;++i>0)-o&255;return t+n},Buffer.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);checkInt(this,e,t,n,a-1,-a)}var i=n-1,s=1,o=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===o&&0!==this[t+i+1]&&(o=1),this[t+i]=(e/s>>0)-o&255;return t+n},Buffer.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},Buffer.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):objectWriteUInt16(this,e,t,!0),t+2},Buffer.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):objectWriteUInt16(this,e,t,!1),t+2},Buffer.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):objectWriteUInt32(this,e,t,!0),t+4},Buffer.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||checkInt(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):objectWriteUInt32(this,e,t,!1),t+4},Buffer.prototype.writeFloatLE=function(e,t,n){return writeFloat(this,e,t,!0,n)},Buffer.prototype.writeFloatBE=function(e,t,n){return writeFloat(this,e,t,!1,n)},Buffer.prototype.writeDoubleLE=function(e,t,n){return writeDouble(this,e,t,!0,n)},Buffer.prototype.writeDoubleBE=function(e,t,n){return writeDouble(this,e,t,!1,n)},Buffer.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--a)e[a+t]=this[a+n];else if(i<1e3||!Buffer.TYPED_ARRAY_SUPPORT)for(a=0;a>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&i.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function asciiToBytes(e){for(var t=[],n=0;n>8,a=n%256,i.push(a),i.push(r);return i}function base64ToBytes(e){return toByteArray(base64clean(e))}function blitBuffer(e,t,n,r){for(var a=0;a=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function isnan(e){return e!=e}function isBuffer(e){return null!=e&&(!!e._isBuffer||isFastBuffer(e)||isSlowBuffer(e))}function isFastBuffer(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function isSlowBuffer(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&isFastBuffer(e.slice(0,0))}function requireToFormData(){if(hasRequiredToFormData)return toFormData_1;hasRequiredToFormData=1;var e=utils$9;return toFormData_1=function(t,n){n=n||new FormData;var r=[];function a(t){return null===t?"":e.isDate(t)?t.toISOString():e.isArrayBuffer(t)||e.isTypedArray(t)?"function"==typeof Blob?new Blob([t]):Buffer.from(t):t}return function t(i,s){if(e.isPlainObject(i)||e.isArray(i)){if(-1!==r.indexOf(i))throw Error("Circular reference detected in "+s);r.push(i),e.forEach(i,(function(r,i){if(!e.isUndefined(r)){var o,l=s?s+"."+i:i;if(r&&!s&&"object"==typeof r)if(e.endsWith(i,"{}"))r=JSON.stringify(r);else if(e.endsWith(i,"[]")&&(o=e.toArray(r)))return void o.forEach((function(t){!e.isUndefined(t)&&n.append(l,a(t))}));t(r,l)}})),r.pop()}else n.append(s,a(i))}(t),n},toFormData_1}function requireSettle(){if(hasRequiredSettle)return settle;hasRequiredSettle=1;var e=requireAxiosError();return settle=function(t,n,r){var a=r.config.validateStatus;r.status&&a&&!a(r.status)?n(new e("Request failed with status code "+r.status,[e.ERR_BAD_REQUEST,e.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):t(r)},settle}function requireCookies(){if(hasRequiredCookies)return cookies;hasRequiredCookies=1;var e=utils$9;return cookies=e.isStandardBrowserEnv()?{write:function(t,n,r,a,i,s){var o=[];o.push(t+"="+encodeURIComponent(n)),e.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),e.isString(a)&&o.push("path="+a),e.isString(i)&&o.push("domain="+i),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}}var isAbsoluteURL$1=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)},combineURLs$1=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},isAbsoluteURL=isAbsoluteURL$1,combineURLs=combineURLs$1,buildFullPath$1=function(e,t){return e&&!isAbsoluteURL(t)?combineURLs(e,t):t},parseHeaders,hasRequiredParseHeaders,isURLSameOrigin,hasRequiredIsURLSameOrigin,CanceledError_1,hasRequiredCanceledError,parseProtocol,hasRequiredParseProtocol,xhr,hasRequiredXhr,_null,hasRequired_null;function requireParseHeaders(){if(hasRequiredParseHeaders)return parseHeaders;hasRequiredParseHeaders=1;var e=utils$9,t=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];return parseHeaders=function(n){var r,a,i,s={};return n?(e.forEach(n.split("\n"),(function(n){if(i=n.indexOf(":"),r=e.trim(n.substr(0,i)).toLowerCase(),a=e.trim(n.substr(i+1)),r){if(s[r]&&t.indexOf(r)>=0)return;s[r]="set-cookie"===r?(s[r]?s[r]:[]).concat([a]):s[r]?s[r]+", "+a:a}})),s):s},parseHeaders}function requireIsURLSameOrigin(){if(hasRequiredIsURLSameOrigin)return isURLSameOrigin;hasRequiredIsURLSameOrigin=1;var e=utils$9;return isURLSameOrigin=e.isStandardBrowserEnv()?function(){var t,n=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");function a(e){var t=e;return n&&(r.setAttribute("href",t),t=r.href),r.setAttribute("href",t),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:"/"===r.pathname.charAt(0)?r.pathname:"/"+r.pathname}}return t=a(window.location.href),function(n){var r=e.isString(n)?a(n):n;return r.protocol===t.protocol&&r.host===t.host}}():function(){return!0}}function requireCanceledError(){if(hasRequiredCanceledError)return CanceledError_1;hasRequiredCanceledError=1;var e=requireAxiosError();function t(t){e.call(this,null==t?"canceled":t,e.ERR_CANCELED),this.name="CanceledError"}return utils$9.inherits(t,e,{__CANCEL__:!0}),CanceledError_1=t}function requireParseProtocol(){return hasRequiredParseProtocol?parseProtocol:(hasRequiredParseProtocol=1,parseProtocol=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""})}function requireXhr(){if(hasRequiredXhr)return xhr;hasRequiredXhr=1;var e=utils$9,t=requireSettle(),n=requireCookies(),r=buildURL$1,a=buildFullPath$1,i=requireParseHeaders(),s=requireIsURLSameOrigin(),o=transitional,l=requireAxiosError(),u=requireCanceledError(),c=requireParseProtocol();return xhr=function(p){return new Promise((function(d,m){var h,f=p.data,y=p.headers,g=p.responseType;function b(){p.cancelToken&&p.cancelToken.unsubscribe(h),p.signal&&p.signal.removeEventListener("abort",h)}e.isFormData(f)&&e.isStandardBrowserEnv()&&delete y["Content-Type"];var v=new XMLHttpRequest;if(p.auth){var N=p.auth.username||"",T=p.auth.password?unescape(encodeURIComponent(p.auth.password)):"";y.Authorization="Basic "+btoa(N+":"+T)}var C=a(p.baseURL,p.url);function A(){if(v){var e="getAllResponseHeaders"in v?i(v.getAllResponseHeaders()):null,n={data:g&&"text"!==g&&"json"!==g?v.response:v.responseText,status:v.status,statusText:v.statusText,headers:e,config:p,request:v};t((function(e){d(e),b()}),(function(e){m(e),b()}),n),v=null}}if(v.open(p.method.toUpperCase(),r(C,p.params,p.paramsSerializer),!0),v.timeout=p.timeout,"onloadend"in v?v.onloadend=A:v.onreadystatechange=function(){v&&4===v.readyState&&(0!==v.status||v.responseURL&&0===v.responseURL.indexOf("file:"))&&setTimeout(A)},v.onabort=function(){v&&(m(new l("Request aborted",l.ECONNABORTED,p,v)),v=null)},v.onerror=function(){m(new l("Network Error",l.ERR_NETWORK,p,v,v)),v=null},v.ontimeout=function(){var e=p.timeout?"timeout of "+p.timeout+"ms exceeded":"timeout exceeded",t=p.transitional||o;p.timeoutErrorMessage&&(e=p.timeoutErrorMessage),m(new l(e,t.clarifyTimeoutError?l.ETIMEDOUT:l.ECONNABORTED,p,v)),v=null},e.isStandardBrowserEnv()){var V=(p.withCredentials||s(C))&&p.xsrfCookieName?n.read(p.xsrfCookieName):void 0;V&&(y[p.xsrfHeaderName]=V)}"setRequestHeader"in v&&e.forEach(y,(function(e,t){void 0===f&&"content-type"===t.toLowerCase()?delete y[t]:v.setRequestHeader(t,e)})),e.isUndefined(p.withCredentials)||(v.withCredentials=!!p.withCredentials),g&&"json"!==g&&(v.responseType=p.responseType),"function"==typeof p.onDownloadProgress&&v.addEventListener("progress",p.onDownloadProgress),"function"==typeof p.onUploadProgress&&v.upload&&v.upload.addEventListener("progress",p.onUploadProgress),(p.cancelToken||p.signal)&&(h=function(e){v&&(m(!e||e&&e.type?new u:e),v.abort(),v=null)},p.cancelToken&&p.cancelToken.subscribe(h),p.signal&&(p.signal.aborted?h():p.signal.addEventListener("abort",h))),f||(f=null);var x=c(C);x&&-1===["http","https","file"].indexOf(x)?m(new l("Unsupported protocol "+x+":",l.ERR_BAD_REQUEST,p)):v.send(f)}))},xhr}function require_null(){return hasRequired_null?_null:(hasRequired_null=1,_null=null)}var utils$5=utils$9,normalizeHeaderName=normalizeHeaderName$1,AxiosError$1=requireAxiosError(),transitionalDefaults=transitional,toFormData=requireToFormData(),DEFAULT_CONTENT_TYPE={"Content-Type":"application/x-www-form-urlencoded"};function setContentTypeIfUnset(e,t){!utils$5.isUndefined(e)&&utils$5.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}function getDefaultAdapter(){var e;return("undefined"!=typeof XMLHttpRequest||void 0!==browser$1&&"[object process]"===Object.prototype.toString.call(browser$1))&&(e=requireXhr()),e}function stringifySafely(e,t,n){if(utils$5.isString(e))try{return(t||JSON.parse)(e),utils$5.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(n||JSON.stringify)(e)}var defaults$3={transitional:transitionalDefaults,adapter:getDefaultAdapter(),transformRequest:[function(e,t){if(normalizeHeaderName(t,"Accept"),normalizeHeaderName(t,"Content-Type"),utils$5.isFormData(e)||utils$5.isArrayBuffer(e)||utils$5.isBuffer(e)||utils$5.isStream(e)||utils$5.isFile(e)||utils$5.isBlob(e))return e;if(utils$5.isArrayBufferView(e))return e.buffer;if(utils$5.isURLSearchParams(e))return setContentTypeIfUnset(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var n,r=utils$5.isObject(e),a=t&&t["Content-Type"];if((n=utils$5.isFileList(e))||r&&"multipart/form-data"===a){var i=this.env&&this.env.FormData;return toFormData(n?{"files[]":e}:e,i&&new i)}return r||"application/json"===a?(setContentTypeIfUnset(t,"application/json"),stringifySafely(e)):e}],transformResponse:[function(e){var t=this.transitional||defaults$3.transitional,n=t&&t.silentJSONParsing,r=t&&t.forcedJSONParsing,a=!n&&"json"===this.responseType;if(a||r&&utils$5.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(a){if("SyntaxError"===e.name)throw AxiosError$1.from(e,AxiosError$1.ERR_BAD_RESPONSE,this,null,this.response);throw e}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:require_null()},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};utils$5.forEach(["delete","get","head"],(function(e){defaults$3.headers[e]={}})),utils$5.forEach(["post","put","patch"],(function(e){defaults$3.headers[e]=utils$5.merge(DEFAULT_CONTENT_TYPE)}));var defaults_1=defaults$3,utils$4=utils$9,defaults$2=defaults_1,transformData$1=function(e,t,n){var r=this||defaults$2;return utils$4.forEach(n,(function(n){e=n.call(r,e,t)})),e},isCancel$1,hasRequiredIsCancel;function requireIsCancel(){return hasRequiredIsCancel?isCancel$1:(hasRequiredIsCancel=1,isCancel$1=function(e){return!(!e||!e.__CANCEL__)})}var utils$3=utils$9,transformData=transformData$1,isCancel=requireIsCancel(),defaults$1=defaults_1,CanceledError=requireCanceledError();function throwIfCancellationRequested(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new CanceledError}var dispatchRequest$1=function(e){return throwIfCancellationRequested(e),e.headers=e.headers||{},e.data=transformData.call(e,e.data,e.headers,e.transformRequest),e.headers=utils$3.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),utils$3.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||defaults$1.adapter)(e).then((function(t){return throwIfCancellationRequested(e),t.data=transformData.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return isCancel(t)||(throwIfCancellationRequested(e),t&&t.response&&(t.response.data=transformData.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},utils$2=utils$9,mergeConfig$2=function(e,t){t=t||{};var n={};function r(e,t){return utils$2.isPlainObject(e)&&utils$2.isPlainObject(t)?utils$2.merge(e,t):utils$2.isPlainObject(t)?utils$2.merge({},t):utils$2.isArray(t)?t.slice():t}function a(n){return utils$2.isUndefined(t[n])?utils$2.isUndefined(e[n])?void 0:r(void 0,e[n]):r(e[n],t[n])}function i(e){if(!utils$2.isUndefined(t[e]))return r(void 0,t[e])}function s(n){return utils$2.isUndefined(t[n])?utils$2.isUndefined(e[n])?void 0:r(void 0,e[n]):r(void 0,t[n])}function o(n){return n in t?r(e[n],t[n]):n in e?r(void 0,e[n]):void 0}var l={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:o};return utils$2.forEach(Object.keys(e).concat(Object.keys(t)),(function(e){var t=l[e]||a,r=t(e);utils$2.isUndefined(r)&&t!==o||(n[e]=r)})),n},data,hasRequiredData;function requireData(){return hasRequiredData?data:(hasRequiredData=1,data={version:"0.27.2"})}var VERSION=requireData().version,AxiosError=requireAxiosError(),validators$1={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){validators$1[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}}));var deprecatedWarnings={};function assertOptions(e,t,n){if("object"!=typeof e)throw new AxiosError("options must be an object",AxiosError.ERR_BAD_OPTION_VALUE);for(var r=Object.keys(e),a=r.length;a-- >0;){var i=r[a],s=t[i];if(s){var o=e[i],l=void 0===o||s(o,i,e);if(!0!==l)throw new AxiosError("option "+i+" must be "+l,AxiosError.ERR_BAD_OPTION_VALUE)}else if(!0!==n)throw new AxiosError("Unknown option "+i,AxiosError.ERR_BAD_OPTION)}}validators$1.transitional=function(e,t,n){function r(e,t){return"[Axios v"+VERSION+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return function(n,a,i){if(!1===e)throw new AxiosError(r(a," has been removed"+(t?" in "+t:"")),AxiosError.ERR_DEPRECATED);return t&&!deprecatedWarnings[a]&&(deprecatedWarnings[a]=!0,console.warn(r(a," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,a,i)}};var validator$1={assertOptions:assertOptions,validators:validators$1},utils$1=utils$9,buildURL=buildURL$1,InterceptorManager=InterceptorManager_1,dispatchRequest=dispatchRequest$1,mergeConfig$1=mergeConfig$2,buildFullPath=buildFullPath$1,validator=validator$1,validators=validator.validators;function Axios$1(e){this.defaults=e,this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}Axios$1.prototype.request=function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},(t=mergeConfig$1(this.defaults,t)).method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var n=t.transitional;void 0!==n&&validator.assertOptions(n,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1);var r=[],a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,r.unshift(e.fulfilled,e.rejected))}));var i,s=[];if(this.interceptors.response.forEach((function(e){s.push(e.fulfilled,e.rejected)})),!a){var o=[dispatchRequest,void 0];for(Array.prototype.unshift.apply(o,r),o=o.concat(s),i=Promise.resolve(t);o.length;)i=i.then(o.shift(),o.shift());return i}for(var l=t;r.length;){var u=r.shift(),c=r.shift();try{l=u(l)}catch(e){c(e);break}}try{i=dispatchRequest(l)}catch(e){return Promise.reject(e)}for(;s.length;)i=i.then(s.shift(),s.shift());return i},Axios$1.prototype.getUri=function(e){e=mergeConfig$1(this.defaults,e);var t=buildFullPath(e.baseURL,e.url);return buildURL(t,e.params,e.paramsSerializer)},utils$1.forEach(["delete","get","head","options"],(function(e){Axios$1.prototype[e]=function(t,n){return this.request(mergeConfig$1(n||{},{method:e,url:t,data:(n||{}).data}))}})),utils$1.forEach(["post","put","patch"],(function(e){function t(t){return function(n,r,a){return this.request(mergeConfig$1(a||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:r}))}}Axios$1.prototype[e]=t(),Axios$1.prototype[e+"Form"]=t(!0)}));var Axios_1=Axios$1,CancelToken_1,hasRequiredCancelToken,spread,hasRequiredSpread,isAxiosError,hasRequiredIsAxiosError;function requireCancelToken(){if(hasRequiredCancelToken)return CancelToken_1;hasRequiredCancelToken=1;var e=requireCanceledError();function t(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var n;this.promise=new Promise((function(e){n=e}));var r=this;this.promise.then((function(e){if(r._listeners){var t,n=r._listeners.length;for(t=0;t{this.initializedPromiseResolves.forEach((e=>e(!0))),this.initialized=!0},this.getInitializedPromise=()=>this.initialized?Promise.resolve(!0):new Promise(((e,t)=>{this.initializedPromiseResolves.push(e)})),cidFromText(e).then((t=>expandDoenetMLsToFullSerializedComponents({cids:[t],doenetMLs:[e],componentInfoObjects:this.componentInfoObjects,flags:this.flags}))).then(this.finishCoreConstruction).catch((e=>{postMessage({messageType:"inErrorState",coreId:this.coreId,args:{errMsg:e.message}})}))}async finishCoreConstruction({cids:e,fullSerializedComponents:t}){this.cid=e[0];let n=t[0];addDocumentIfItsMissing(n),createComponentNames({serializedComponents:n,componentInfoObjects:this.componentInfoObjects}),this.componentIndexArray=extractComponentNamesAndIndices(n);let{rangePieces:r}=extractRangeIndexPieces({componentArray:this.componentIndexArray});this.componentRangePieces=r,postMessage({messageType:"componentRangePieces",coreId:this.coreId,args:{componentRangePieces:this.componentRangePieces}}),this.documentName=n[0].componentName,n[0].doenetAttributes.cid=this.cid,this._components={},this.componentsToRender={},this.componentsWithChangedChildrenToRender=new Set([]),this.stateVariableChangeTriggers={},this.actionsChangedToActions={},this.originsOfActionsChangedToActions={},this.essentialValuesSavedInDefinition={},this.saveStateToDBTimerId=null,this.rendererState={__componentNeedingUpdateValue:null},this.rendererVariablesByComponentType={};for(let e in this.componentInfoObjects.allComponentClasses)Object.defineProperty(this.rendererVariablesByComponentType,e,{get:function(){let t=this.componentInfoObjects.allComponentClasses[e].returnStateVariableInfo({onlyForRenderer:!0}).stateVariableDescriptions;return delete this.rendererVariablesByComponentType[e],this.rendererVariablesByComponentType[e]=t}.bind(this),configurable:!0});this.processQueue=[],this.stopProcessingRequests=!1,this.dependencies=new DependencyHandler({_components:this._components,componentInfoObjects:this.componentInfoObjects,core:this}),this.unmatchedChildren={};let a=getNumberOfVariants({serializedComponent:n[0],componentInfoObjects:this.componentInfoObjects}).numberOfVariants;if(!this.requestedVariant){if(this.requestedVariantIndex=((this.requestedVariantIndex-1)%a+a)%a+1,n[0].variants.uniqueVariants){let e=this.componentInfoObjects.allComponentClasses[n[0].componentType].getUniqueVariant({serializedComponent:n[0],variantIndex:this.requestedVariantIndex,componentInfoObjects:this.componentInfoObjects});e.success&&(this.requestedVariant=e.desiredVariant)}this.requestedVariant||(this.requestedVariant={index:this.requestedVariantIndex})}this.parameterStack.parameters.variant=this.requestedVariant,n[0].variants.desiredVariant=this.parameterStack.parameters.variant,await this.addComponents({serializedComponents:n,initialAdd:!0}),this.updateInfo.componentsToUpdateRenderers.clear(),await this.document.stateValues.itemCreditAchieved,this.canonicalGeneratedVariantString=JSON.stringify(await this.document.stateValues.generatedVariantInfo,serializedComponentsReplacer),this.canonicalItemVariantStrings=(await this.document.stateValues.itemVariantInfo).map((e=>JSON.stringify(e,serializedComponentsReplacer))),this.coreInfo={generatedVariantString:this.canonicalGeneratedVariantString,allPossibleVariants:deepClone(await this.document.sharedParameters.allPossibleVariants),rendererTypesInDocument:deepClone(this.rendererTypesInDocument),documentToRender:this.documentRendererInstructions},this.coreInfoString=JSON.stringify(this.coreInfo,serializedComponentsReplacer),this.messageViewerReady(),this.resolveInitialized()}async onDocumentFirstVisible(){this.requestRecordEvent({verb:"experienced",object:{componentName:this.document.componentName,componentType:"document"}});let e=function(t){let n=t.stateValues.scoredDescendants;if(Array.isArray(n))for(let t of n){if("answer"===t.componentType)return!0;if(e(t))return!0}return!1};await this.document.stateValues.scoredDescendants,e(this.document)||this.saveSubmissions({pageCreditAchieved:await this.document.stateValues.creditAchieved,suppressToast:!0}),setTimeout(this.sendVisibilityChangedEvents.bind(this),this.visibilityInfo.saveDelay)}async messageViewerReady(){postMessage({messageType:"initializeRenderers",coreId:this.coreId,args:{coreInfo:this.coreInfo}}),postMessage({messageType:"coreCreated",coreId:this.coreId})}async postUpdateRenderers(e,t=!1){postMessage({messageType:"updateRenderers",coreId:this.coreId,args:e,init:t})}async addComponents({serializedComponents:e,parentName:t,indexOfDefiningChildren:n,initialAdd:r=!1,assignNamesOffset:a}){let i;Array.isArray(e)||(e=[e]);let s=[],o="";if(!r){if(i=this._components[t],!i)return console.warn(`Cannot add children to parent ${t} as ${t} does not exist`),[];s=[{componentName:t,componentClass:i.constructor},...i.ancestors],this.parameterStack.push(i.sharedParameters,!1),this.nTimesAddedComponents?this.nTimesAddedComponents++:this.nTimesAddedComponents=1,o=`addComponents${this.nTimesAddedComponents}`}let l=await this.createIsolatedComponents({serializedComponents:e,ancestors:s,createNameContext:o});if(r||this.parameterStack.pop(),!0!==l.success)throw Error(l.message);const u=l.components;let c={},p={};if(u.forEach((e=>p[e.componentName]=e)),r){if(1!==u.length)throw Error("Initial components need to be an array of just one component.");if(this.document=u[0],await this.expandAllComposites(this.document),await this.expandAllComposites(this.document,!0),this.updateInfo.stateVariablesToEvaluate){let e=this.updateInfo.stateVariablesToEvaluate;this.updateInfo.stateVariablesToEvaluate=[];for(let{componentName:t,stateVariable:n}of e){let e=this._components[t];e&&e.state[n]&&await this.getStateVariableValue({component:e,stateVariable:n})}}await this.replacementChangesFromCompositesToUpdate();let e=await this.initializeRenderedComponentInstruction(this.document);if(this.updateInfo.compositesToUpdateReplacements.size>0){await this.replacementChangesFromCompositesToUpdate();let e=[...this.updateInfo.componentsToUpdateRenderers];this.updateInfo.componentsToUpdateRenderers.clear(),await this.updateRendererInstructions({componentNamesToUpdate:e})}this.documentRendererInstructions=e.componentToRender;let t=[{instructionType:"updateRendererStates",rendererStatesToUpdate:e.rendererStatesToUpdate}];if(this.postUpdateRenderers({updateInstructions:t},!0),e.rendererStatesToForceUpdate.length>0){let t=[{instructionType:"updateRendererStates",rendererStatesToUpdate:e.rendererStatesToForceUpdate}];this.postUpdateRenderers({updateInstructions:t})}await this.processStateVariableTriggers()}else{if(void 0===i)throw Error("Must specify parent when adding components.");void 0===n&&(n=i.definingChildren.length);let e=await this.addChildrenAndRecurseToShadows({parent:i,indexOfDefiningChildren:n,newChildren:u,assignNamesOffset:a});if(!e.success)throw Error("Couldn't satisfy child logic result. Need informative error message");if(Object.assign(p,e.addedComponents),Object.assign(c,e.deletedComponents),await this.expandAllComposites(this.document),await this.expandAllComposites(this.document,!0),this.updateInfo.stateVariablesToEvaluate){let e=this.updateInfo.stateVariablesToEvaluate;this.updateInfo.stateVariablesToEvaluate=[];for(let{componentName:t,stateVariable:n}of e){let e=this._components[t];e&&e.state[n]&&await this.getStateVariableValue({component:e,stateVariable:n})}}if(await this.replacementChangesFromCompositesToUpdate(),await this.updateRendererInstructions({componentNamesToUpdate:await this.componentAndRenderedDescendants(i)}),this.updateInfo.compositesToUpdateReplacements.size>0){await this.replacementChangesFromCompositesToUpdate();let e=[...this.updateInfo.componentsToUpdateRenderers];this.updateInfo.componentsToUpdateRenderers.clear(),await this.updateRendererInstructions({componentNamesToUpdate:e})}await this.processStateVariableTriggers()}return u}async updateRendererInstructions({componentNamesToUpdate:e,sourceOfUpdate:t={},actionId:n}){let r=[],a=[],i=[],s={},o=this.componentsWithChangedChildrenToRender;this.componentsWithChangedChildrenToRender=new Set([]);for(let t of o)if(t in this.componentsToRender){let n=[],a=this._components[t],l=[];if(a&&a.constructor.renderChildren){a.childrenMatched||await this.deriveChildResultsFromDefiningChildren({parent:a,expandComposites:!0,forceExpandComposites:!0}),l=await this.returnActiveChildrenIndicesToRender(a);let e=0;for(let[t,r]of a.activeChildren.entries())l.includes(t)&&(r.rendererType?(n.push(`nameType:${r.componentName};${r.componentType}`),e++):"string"==typeof r?(n.push(`string${e}:${r}`),e++):"number"==typeof r&&(n.push(`number${e}:${r.toString()}`),e++))}let u=this.componentsToRender[t].children,c=[];for(let[e,t]of u.entries())t.componentName?c.push(`nameType:${t.componentName};${t.componentType}`):"string"==typeof t?c.push(`string${e}:${t}`):"number"==typeof t&&c.push(`number${e}:${t.toString()}`);if(n.length!==c.length||n.some(((e,t)=>e!==c[t]))){for(let e of u)if(e.componentName){let t=this.deleteFromComponentsToRender({componentName:e.componentName,recurseToChildren:!0,componentsWithChangedChildrenToRenderInProgress:o});r.push(...t)}let n=[];if(l.length>0)for(let[e,t]of a.activeChildren.entries())if(l.includes(e))if(t.rendererType){let e=await this.initializeRenderedComponentInstruction(t,o);n.push(e.componentToRender),i.push(...e.rendererStatesToUpdate)}else"string"==typeof t?n.push(t):"number"==typeof t&&n.push(t.toString());this.componentsToRender[t].children=n,s[t]=n,o.delete(t),e.includes(t)||e.push(t)}}for(let t of e)if(t in this.componentsToRender){let e=this._components[t];if(e){let n={};for(let t in e.state)if(e.state[t].forRenderer){let r=removeFunctionsMathExpressionClass(await e.state[t].value);n[t]=r}let r={componentName:t,stateValues:n,rendererType:e.rendererType};this.rendererState[t]||(this.rendererState[t]={}),this.rendererState[t].stateValues=n,s[t]&&(r.childrenInstructions=s[t],this.rendererState[t].childrenInstructions=s[t]),i.push(r)}}if(i.length>0){let e={instructionType:"updateRendererStates",rendererStatesToUpdate:i,sourceOfUpdate:t};a.splice(0,0,e)}this.postUpdateRenderers({updateInstructions:a,actionId:n})}async initializeRenderedComponentInstruction(e,t=new Set([])){if(void 0===e.rendererType)return;e.childrenMatched||await this.deriveChildResultsFromDefiningChildren({parent:e,expandComposites:!0});let n=[],r=[],a={},i={},s=!1;for(let t in e.state)e.state[t].forRenderer&&(a[t]=removeFunctionsMathExpressionClass(await e.state[t].value),e.state[t].alwaysUpdateRenderer&&(s=!0));s&&(i=a);let o=e.componentName,l=[];if(e.constructor.renderChildren){let a=await this.returnActiveChildrenIndicesToRender(e);for(let[i,s]of e.activeChildren.entries())if(a.includes(i))if(s.rendererType){let e=await this.initializeRenderedComponentInstruction(s,t);l.push(e.componentToRender),n.push(...e.rendererStatesToUpdate),r.push(...e.rendererStatesToForceUpdate)}else"string"==typeof s?l.push(s):"number"==typeof s&&l.push(s.toString())}n.push({componentName:o,stateValues:a,childrenInstructions:l}),Object.keys(i).length>0&&r.push({componentName:o,stateValues:i}),this.rendererState[o]={stateValues:a,childrenInstructions:l},t.delete(o);let u={};for(let t in e.actions)u[t]={actionName:t,componentName:e.componentName};for(let t in e.externalActions){let n=await e.externalActions[t];n&&(u[t]={actionName:t,componentName:n.componentName})}let c={componentName:o,effectiveName:e.componentOrAdaptedName,componentType:e.componentType,rendererType:e.rendererType,actions:u};return this.componentsToRender[o]={children:l},{componentToRender:c,rendererStatesToUpdate:n,rendererStatesToForceUpdate:r}}deleteFromComponentsToRender({componentName:e,recurseToChildren:t=!0,componentsWithChangedChildrenToRenderInProgress:n}){let r=[e];if(t){let a=this.componentsToRender[e];if(a)for(let e of a.children){let a=this.deleteFromComponentsToRender({componentName:e.componentName,recurseToChildren:t,componentsWithChangedChildrenToRenderInProgress:n});r.push(...a)}}return delete this.componentsToRender[e],n.delete(e),r}async processStateVariableTriggers(){for(let e in this.stateVariableChangeTriggers){let t=this._components[e];for(let n in this.stateVariableChangeTriggers[e]){let r=this.stateVariableChangeTriggers[e][n],a=await t.state[n].value;if(a!==r.previousValue){let i=r.previousValue;r.previousValue=a,t.actions[r.action]&&await this.performAction({componentName:e,actionName:r.action,args:{stateValues:{[n]:a},previousValues:{[n]:i}}})}}}}async expandAllComposites(e,t=!1){let n=await this.expandCompositesOfDescendants(e,t),r=!0;for(;r;){r=!1;for(let e of n){let n=this._components[e],a=!1;for(let e of n.unexpandedCompositesNotReady){let n=this._components[e];if(n.state.readyToExpandWhenResolved.isResolved){a=!0;break}if((await this.dependencies.resolveItem({componentName:n.componentName,type:"stateVariable",stateVariable:"readyToExpandWhenResolved",force:t,recurseUpstream:!0})).success){a=!0;break}}if(a){let n=this._components[e];await this.deriveChildResultsFromDefiningChildren({parent:n,expandComposites:!0,forceExpandComposites:t}),r=!0}}}}async expandCompositesOfDescendants(e,t=!1){let n=[];e.childrenMatched||(await this.deriveChildResultsFromDefiningChildren({parent:e,expandComposites:!0,forceExpandComposites:t}),e.unexpandedCompositesNotReady.length>0?n.push(e.componentName):await this.dependencies.resolveBlockersFromChangedActiveChildren(e,t));for(let r in e.attributes){let a=e.attributes[r].component;if(a){let e=await this.expandCompositesOfDescendants(a,t);n.push(...e)}}for(let r in e.allChildren){let a=e.allChildren[r].component;if("object"!=typeof a)continue;let i=await this.expandCompositesOfDescendants(a,t);n.push(...i)}return n}async componentAndRenderedDescendants(e){if(!e?.componentName)return[];let t=[e.componentName];if(e.constructor.renderChildren){e.childrenMatched||await this.deriveChildResultsFromDefiningChildren({parent:e,expandComposites:!0});for(let n of e.activeChildren)t.push(...await this.componentAndRenderedDescendants(n))}return t}async createIsolatedComponents({serializedComponents:e,ancestors:t,shadow:n=!1,createNameContext:r=""}){let a="/";if(t.length>0){let e=t[0].componentName,n=this.components[e];a=n.attributes.newNamespace?.primitive?n.componentName+"/":getNamespaceFromName(n.componentName)}return{success:!0,components:(await this.createIsolatedComponentsSub({serializedComponents:e,ancestors:t,shadow:n,namespaceForUnamed:a,createNameContext:r})).components}}async createIsolatedComponentsSub({serializedComponents:e,ancestors:t,shadow:n=!1,createNameContext:r="",namespaceForUnamed:a="/",componentsReplacementOf:i}){let s=[];for(let[o,l]of e.entries()){if("object"!=typeof l){s.push(l);continue}if(!0===l.createdComponent){let e=this._components[l.componentName];s.push(e),this.setAncestors(e,t);continue}let e=this.componentInfoObjects.allComponentClasses[l.componentType];if(void 0===e)throw Error("Cannot create component of type "+l.componentType);l.doenetAttributes||(l.doenetAttributes={});let u=l.componentName;if(void 0===u){let e=t[0].componentName+"|"+r+"|";l.uniqueIdentifier?e+=l.uniqueIdentifier:e+=o,u=createUniqueName(l.componentType.toLowerCase(),e),u=a+u}let c=(await this.createChildrenThenComponent({serializedComponent:l,componentName:u,ancestors:t,componentClass:e,shadow:n,namespaceForUnamed:a,componentsReplacementOf:i})).newComponent;s.push(c)}return{components:s}}async createChildrenThenComponent({serializedComponent:e,componentName:t,ancestors:n,componentClass:r,shadow:a=!1,namespaceForUnamed:i="/",componentsReplacementOf:s}){let o=e.children,l=[],u=[],c=[{componentName:t,componentClass:r},...n],p=this.parameterStack.parameters;this.parameterStack.push();let d=this.parameterStack.parameters;if(r.descendantCompositesMustHaveAReplacement&&!a?(d.compositesMustHaveAReplacement=!0,d.compositesDefaultReplacementType=r.descendantCompositesDefaultReplacementType):(!1===r.descendantCompositesMustHaveAReplacement||a)&&(d.compositesMustHaveAReplacement=!1),r.modifySharedParameters&&r.modifySharedParameters({sharedParameters:d,serializedComponent:e}),e.doenetAttributes.pushSharedParameters)for(let t of e.doenetAttributes.pushSharedParameters){let e=t.parameterName;d[e]=e in d?[...d[e]]:[],d[e].push(t.value)}if(e.doenetAttributes.addToSharedParameters)for(let t of e.doenetAttributes.addToSharedParameters){let e=t.parameterName;d[e]=e in d?Object.assign({},d[e]):{},d[e][t.key]=t.value}if(void 0!==o){if(r.preprocessSerializedChildren&&r.preprocessSerializedChildren({serializedChildren:o,attributes:e.attributes,componentName:t}),r.setUpVariant){let t=gatherVariantComponents({serializedComponents:o,componentInfoObjects:this.componentInfoObjects});r.setUpVariant({serializedComponent:e,sharedParameters:d,descendantVariantComponents:t})}if(r.keepChildrenSerialized){let t=new Set([]),n=r.keepChildrenSerialized({serializedComponent:e,componentInfoObjects:this.componentInfoObjects});for(let e of n){if(t.has(Number(e)))throw Error("Invalid instructions to keep children serialized from "+r.componentType+": child repeated");t.add(Number(e)),u.push(o[e])}let s=[];for(let[e,n]of o.entries())t.has(e)||s.push(n);if(s.length>0){l=(await this.createIsolatedComponentsSub({serializedComponents:s,ancestors:c,shadow:a,namespaceForUnamed:i})).components}}else{l=(await this.createIsolatedComponentsSub({serializedComponents:o,ancestors:c,shadow:a,namespaceForUnamed:i})).components}}let m={};if(e.attributes)for(let t in e.attributes){if(e.attributes[t].component){let n=await this.createIsolatedComponentsSub({serializedComponents:[e.attributes[t].component],ancestors:c,shadow:a,namespaceForUnamed:i,createNameContext:`attribute|${t}`});m[t]={component:n.components[0]}}else m[t]=e.attributes[t]}let h={};e.downstreamDependencies&&Object.assign(h,e.downstreamDependencies);let f=await this.createStateVariableDefinitions({componentClass:r,prescribedDependencies:h,componentName:t});delete this.updateInfo.deletedComponents[t],delete this.updateInfo.deletedStateVariables[t];let y=new r({componentName:t,ancestors:n,definingChildren:l,stateVariableDefinitions:f,serializedChildren:u,serializedComponent:e,attributes:m,componentInfoObjects:this.componentInfoObjects,coreFunctions:this.coreFunctions,flags:this.flags,shadow:a,numerics:this.numerics,sharedParameters:d,parentSharedParameters:p});this.registerComponent(y),s&&(y.replacementOf=s),e.adaptedFrom&&(y.adaptedFrom=this._components[e.adaptedFrom],y.adaptedFrom.adapterUsed=y);for(let e in h){let t=h[e];for(let n of t)if("referenceShadow"===n.dependencyType){let t={componentName:e};Object.assign(t,n),delete t.dependencyType,y.shadows=t;let r=this._components[e];if(r.shadowedBy||(r.shadowedBy=[]),r.shadowedBy.push(y),n.isPrimaryShadow&&(r.primaryShadow=y.componentName,this.dependencies.updateTriggers.primaryShadowDependencies[e]))for(let t of this.dependencies.updateTriggers.primaryShadowDependencies[e])await t.recalculateDownstreamComponents();break}}e.unlinkedCopySource&&(y.unlinkedCopySource=e.unlinkedCopySource),await this.deriveChildResultsFromDefiningChildren({parent:y,expandComposites:!1}),await this.initializeComponentStateVariables(y),await this.dependencies.setUpComponentDependencies(y);let g=await this.dependencies.checkForDependenciesOnNewComponent(t);for(let e of g)await this.markStateVariableAndUpstreamDependentsStale({component:this._components[e.componentName],varName:e.varName});return await this.checkForStateVariablesUpdatesForNewComponent(t),await this.dependencies.resolveStateVariablesIfReady({component:y}),await this.checkForActionChaining({component:y}),this.parameterStack.pop(),{newComponent:y}}async checkForStateVariablesUpdatesForNewComponent(e){if(e in this.updateInfo.stateVariableUpdatesForMissingComponents){let t=await this.processNewStateVariableValues({[e]:this.updateInfo.stateVariableUpdatesForMissingComponents[e]}),n=this._components[e];if(n.constructor.processWhenJustUpdatedForNewComponent||t.foundIgnore)for(let r in this.updateInfo.stateVariableUpdatesForMissingComponents[e])n.state[r]&&(this.updateInfo.stateVariablesToEvaluate.push({componentName:e,stateVariable:r}),n.state[r].justUpdatedForNewComponent=!0,t.foundIgnore&&(n.reprocessAfterEvaluate=this.updateInfo.stateVariableUpdatesForMissingComponents[e]));delete this.updateInfo.stateVariableUpdatesForMissingComponents[e]}}async deriveChildResultsFromDefiningChildren({parent:e,expandComposites:t=!0,forceExpandComposites:n=!1}){if(this.derivingChildResults||(this.derivingChildResults=[]),this.derivingChildResults.includes(e.componentName))return{success:!1,skipping:!0};this.derivingChildResults.push(e.componentName);let r,a=await this.expandCompositeOfDefiningChildren(e,e.definingChildren,t,n);e.unexpandedCompositesReady=a.unexpandedCompositesReady,e.unexpandedCompositesNotReady=a.unexpandedCompositesNotReady,e.activeChildren&&(r=e.activeChildren.map((e=>e.componentName?e.componentName:e))),e.activeChildren=e.definingChildren.slice(),e.allChildren={},e.allChildrenOrdered=[];for(let t=0;te.componentType)).join(", ");this.unmatchedChildren[e.componentName]={message:`invalid children of type(s): ${t}`}}await this.dependencies.addBlockersFromChangedActiveChildren({parent:e});let s=this.derivingChildResults.indexOf(e.componentName);if(this.derivingChildResults.splice(s,1),e.constructor.renderChildren){let t=r&&r.length==e.activeChildren.length&&e.activeChildren.every(((e,t)=>e.componentName?e.componentName===r[t]:e===r[t]));t||this.componentsWithChangedChildrenToRender.add(e.componentName)}return i}async expandCompositeOfDefiningChildren(e,t,n,r){let a=[],i=[];for(let s=0;s=n)break;if(!r||r.includes(a))if("object"==typeof i)!i.constructor.sendToRendererEvenIfHidden&&await i.stateValues.hidden||t.push(a);else{let n=!1;if(e.compositeReplacementActiveRange)for(let t of e.compositeReplacementActiveRange){let e=this._components[t.compositeName];if(await e.stateValues.hidden&&t.firstInd<=a&&t.lastInd>=a){n=!0;break}}n||t.push(a)}}return t}async substituteAdapter({parent:e,childInd:t,adapterIndUsed:n}){let r,a=e.activeChildren[t];r=a.componentName?a.getAdapter(n):{componentType:this.componentInfoObjects.allComponentClasses[a.componentType].getAdapterComponentType(n,this.componentInfoObjects.publicStateVariableInfo),placeholderInd:a.placeholderInd+"adapt"};let i=a.adapterUsed;if(void 0===i||i.componentType!==r.componentType)if(a.componentName){let t;t=e.attributes.newNamespace?.primitive?e.componentName+"/":getNamespaceFromName(e.componentName),r.adaptedFrom=a.componentName,i=(await this.createIsolatedComponentsSub({serializedComponents:[r],shadow:!0,ancestors:a.ancestors,createNameContext:a.componentName+"|adapter",namespaceForUnamed:t})).components[0]}else r.adaptedFrom=a,i=r;if(e.activeChildren.splice(t,1,i),a.componentName&&(delete e.allChildren[a.componentName].activeChildrenIndex,e.allChildren[i.componentName]={activeChildrenIndex:t,component:i}),a.componentName){let t=e.allChildrenOrdered.indexOf(a.componentName);e.allChildrenOrdered.splice(t+1,0,i.componentName)}else{let t=e.allChildrenOrdered.indexOf(a.placeholderInd);e.allChildrenOrdered.splice(t+1,0,i.placeholderInd)}}async expandCompositeComponent(e){if(!("readyToExpandWhenResolved"in e.state))throw Error(`Could not find state variable readyToExpandWhenResolved of composite ${e.componentName}`);if(!e.state.readyToExpandWhenResolved.isResolved)return this.updateInfo.compositesToExpand.add(e.componentName),{success:!1};if(this.updateInfo.compositesToExpand.delete(e.componentName),this.updateInfo.compositesBeingExpanded.push(e.componentName),e.parent){if(e.parent.unexpandedCompositesReady){let t=e.parent.unexpandedCompositesReady.indexOf(e.componentName);-1!==t&&e.parent.unexpandedCompositesReady.splice(t,1)}if(e.parent.unexpandedCompositesNotReady){let t=e.parent.unexpandedCompositesNotReady.indexOf(e.componentName);-1!==t&&e.parent.unexpandedCompositesNotReady.splice(t,1)}}if(e.shadows)return await this.expandShadowingComposite(e);let t=await e.constructor.createSerializedReplacements({component:this.components[e.componentName],components:this.components,workspace:e.replacementsWorkspace,componentInfoObjects:this.componentInfoObjects,flags:this.flags,resolveItem:this.dependencies.resolveItem.bind(this.dependencies),publicCaseInsensitiveAliasSubstitutions:this.publicCaseInsensitiveAliasSubstitutions.bind(this)});if(e.constructor.stateVariableToEvaluateAfterReplacements&&await e.stateValues[e.constructor.stateVariableToEvaluateAfterReplacements],!t.replacements)throw Error(`Invalid createSerializedReplacements of ${e.componentName}`);{let n=t.replacements;await this.createAndSetReplacements({component:e,serializedReplacements:n})}let n=this.updateInfo.compositesBeingExpanded.indexOf(e.componentName);if(-1===n)throw Error(`Something is wrong as we lost track that we were expanding ${e.componentName}`);return this.updateInfo.compositesBeingExpanded.splice(n,1),{success:!0,compositesExpanded:[e.componentName]}}async expandShadowingComposite(e){if(this.updateInfo.compositesBeingExpanded.includes(e.shadows.componentName)){let t=this._components[e.shadows.componentName];for(;t.shadows;)t=this._components[t.shadows.componentName];throw Error(`Circular reference involving ${t.componentName}`)}let t=this._components[e.shadows.componentName],n=[];if(!t.isExpanded){let r=await this.expandCompositeComponent(t);if(!r.success)throw Error(`expand result of ${e.componentName} was not a success even though ready to expand.`);n.push(...r.compositesExpanded)}let r=[],a=await e.stateValues.sourceAttributesToIgnore,i=await e.stateValues.sourceAttributesToIgnoreRecursively;for(let e of t.replacements)"object"==typeof e?r.push(await e.serialize({sourceAttributesToIgnore:a,sourceAttributesToIgnoreRecursively:i})):r.push(e);let s=e.replacementsWorkspace.uniqueIdentifiersUsed=[],o=e.shadows.compositeName;r=postProcessCopy({serializedComponents:r,componentName:o,uniqueIdentifiersUsed:s});let l=e.attributes.newNamespace?.primitive;if(e.attributes.isResponse){let t=e.constructor.createAttributesObject();for(let n of r){if("object"!=typeof n)continue;n.attributes||(n.attributes={});let r=convertAttributesForComponentType({attributes:{isResponse:e.attributes.isResponse},componentType:n.componentType,componentInfoObjects:this.componentInfoObjects,compositeAttributesObj:t,compositeCreatesNewNamespace:l});Object.assign(n.attributes,r)}}if(e.constructor.assignNamesToReplacements){let n,a=this.components[o],i=a.attributes.newNamespace?.primitive,s=a.doenetAttributes.assignNames,u=s?.some(Array.isArray),c=a.attributes.assignNewNamespaces?.primitive,p=this._components[a.doenetAttributes.targetComponentName];p&&(n=!this.componentInfoObjects.isCompositeComponent({componentType:p.componentType,includeNonStandard:!1})&&p.attributes.newNamespace?.primitive);let d=!u&&(l||n||i&&!s||c),m=e.doenetAttributes.assignNames;if(m&&await e.stateValues.addLevelToAssignNames&&(m=m.map((e=>[e]))),r=processAssignNames({assignNames:m,serializedComponents:r,parentName:e.componentName,parentCreatesNewNamespace:l,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:d,shadowingComposite:!0}).serializedComponents,p?.componentName===t.componentName&&a.doenetAttributes.fromCopyTarget){let t=deepClone(a.serializedChildren);this.componentInfoObjects.allComponentClasses[e.componentType].includeBlankStringChildren||(t=t.filter((e=>"string"!=typeof e||""!==e.trim())));let n=processAssignNames({assignNames:m,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:a.attributes.assignNewNamespaces?.primitive,indOffset:r.length,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:!0});r.push(...n.serializedComponents)}}else{let t=l;r=processAssignNames({serializedComponents:r,parentName:e.componentName,parentCreatesNewNamespace:l,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:t,shadowingComposite:!0}).serializedComponents}r=(await verifyReplacementsMatchSpecifiedType({component:e,replacements:r,assignNames:e.doenetAttributes.assignNames,componentInfoObjects:this.componentInfoObjects,compositeAttributesObj:e.constructor.createAttributesObject(),flags:this.flags})).replacements,await this.createAndSetReplacements({component:e,serializedReplacements:r}),t.replacementsToWithhold>0&&(e.replacementsToWithhold=t.replacementsToWithhold);let u=this.updateInfo.compositesBeingExpanded.indexOf(e.componentName);if(-1===u)throw Error(`Something is wrong as we lost track that we were expanding ${e.componentName}`);return this.updateInfo.compositesBeingExpanded.splice(u,1),n.push(e.componentName),{success:!0,compositesExpanded:n}}async createAndSetReplacements({component:e,serializedReplacements:t}){let n;this.parameterStack.push(e.sharedParameters,!1),n=e.attributes.newNamespace?.primitive?e.componentName+"/":getNamespaceFromName(e.componentName);let r=await this.createIsolatedComponentsSub({serializedComponents:t,ancestors:e.ancestors,shadow:!0,createNameContext:e.componentName+"|replacements",namespaceForUnamed:n,componentsReplacementOf:e});this.parameterStack.pop(),e.replacements=r.components,await this.dependencies.addBlockersFromChangedReplacements(e),e.isExpanded=!0}async replaceCompositeChildren(e){delete e.placeholderActiveChildrenIndices,delete e.placeholderActiveChildrenIndicesByComposite,delete e.compositeReplacementActiveRange;let t=0;for(let n=0;ne+n));e.placeholderActiveChildrenIndices||(e.placeholderActiveChildrenIndices=[]),e.placeholderActiveChildrenIndices.push(...o),e.placeholderActiveChildrenIndicesByComposite||(e.placeholderActiveChildrenIndicesByComposite={}),e.placeholderActiveChildrenIndicesByComposite[r.componentName]=o}else await this.markWithheldReplacementsInactive(r),a=r.replacements,r.replacementsToWithhold>0&&(a=a.slice(0,-r.replacementsToWithhold)),e.constructor.includeBlankStringChildren&&!e.constructor.removeBlankStringChildrenPostSugar||(a=a.filter((e=>"string"!=typeof e||/\S/.test(e))));e.compositeReplacementActiveRange||(e.compositeReplacementActiveRange=[]);for(let t of e.compositeReplacementActiveRange)t.lastInd>=n&&(t.lastInd+=a.length-1);e.compositeReplacementActiveRange.push({compositeName:r.componentName,target:await r.stateValues.target,firstInd:n,lastInd:n+a.length-1}),e.activeChildren.splice(n,1,...a),delete e.allChildren[r.componentName].activeChildrenIndex;for(let t=0;t"object"==typeof e)).map((e=>e.componentName?e.componentName:e.placeholderInd))),1!==a.length){let t=a.length-1;for(let r=n+a.length;r0&&(t-=e.replacementsToWithhold);for(let n of e.replacements.slice(0,t))await this.changeInactiveComponentAndDescendants(n,!1);for(let n of e.replacements.slice(t))await this.changeInactiveComponentAndDescendants(n,!0);if(!await e.stateValues.isInactiveCompositeReplacement){let t=e.componentName;this.updateInfo.inactiveCompositesToUpdateReplacements.has(t)&&(this.updateInfo.inactiveCompositesToUpdateReplacements.delete(t),this.updateInfo.compositesToUpdateReplacements.add(t))}}async changeInactiveComponentAndDescendants(e,t){if("object"==typeof e&&await e.stateValues.isInactiveCompositeReplacement!==t){e.state.isInactiveCompositeReplacement.value=t,await this.markUpstreamDependentsStale({component:e,varName:"isInactiveCompositeReplacement"}),this.dependencies.recordActualChangeInUpstreamDependencies({component:e,varName:"isInactiveCompositeReplacement"});for(let n in e.allChildren)await this.changeInactiveComponentAndDescendants(this._components[n],t);for(let n in e.attributes){let r=e.attributes[n].component;r&&await this.changeInactiveComponentAndDescendants(this._components[r.componentName],t)}e.replacements&&await this.markWithheldReplacementsInactive(e)}}findShadowedChildInSerializedComponents({serializedComponents:e,shadowedComponentName:t}){for(let n of e){if(n.originalName===t)return n;if(n.children){let e=this.findShadowedChildInSerializedComponents({serializedComponents:n.children,shadowedComponentName:t});if(e)return e}}}async createStateVariableDefinitions({componentClass:e,prescribedDependencies:t,componentName:n}){let r;if(t)for(let e in t){let a=t[e];for(let t of a)if("referenceShadow"===t.dependencyType){if(e===n)throw Error(`circular reference involving ${n}`);r={linkSource:"referenceShadow",targetName:e,compositeName:t.compositeName,propVariable:t.propVariable,arrayStateVariable:t.arrayStateVariable,arrayKey:t.arrayKey,ignorePrimaryStateVariable:t.ignorePrimaryStateVariable,substituteForPrimaryStateVariable:t.substituteForPrimaryStateVariable,firstLevelReplacement:t.firstLevelReplacement,additionalStateVariableShadowing:t.additionalStateVariableShadowing}}else"adapter"===t.dependencyType&&(r={linkSource:"adapter",adapterTargetIdentity:t.adapterTargetIdentity,adapterVariable:t.adapterVariable,substituteForPrimaryStateVariable:t.substituteForPrimaryStateVariable,stateVariablesToShadow:t.stateVariablesToShadow})}let a={};r||this.createAttributeStateVariableDefinitions({stateVariableDefinitions:a,componentClass:e});let i=e.returnNormalizedStateVariableDefinitions({attributeNames:Object.keys(a),numerics:this.numerics});return Object.assign(a,i),r&&("adapter"===r.linkSource?this.createAdapterStateVariableDefinitions({redefineDependencies:r,stateVariableDefinitions:a,componentClass:e}):await this.createReferenceShadowStateVariableDefinitions({redefineDependencies:r,stateVariableDefinitions:a,componentClass:e})),a}createAttributeStateVariableDefinitions({componentClass:e,stateVariableDefinitions:t}){let n=e.createAttributesObject();for(let r in n){let a=n[r];if(!a.createStateVariable)continue;let i,s=a.createStateVariable,o=t[s]={isAttribute:!0,hasEssential:!0};if(a.public)if(o.public=!0,o.shadowingInstructions={},a.createPrimitiveOfType)o.shadowingInstructions.createComponentOfType=a.createPrimitiveOfType,"string"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="text":"stringArray"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="textList":"numberArray"===o.shadowingInstructions.createComponentOfType&&(o.shadowingInstructions.createComponentOfType="numberList");else{if(a.createTargetComponentNames)throw Error("Cannot make a public state variable from an attribute with createTargetComponentNames");o.shadowingInstructions.createComponentOfType=a.createComponentOfType}if(a.createComponentOfType){let t=this.componentInfoObjects.allComponentClasses[a.createComponentOfType];if(!t)throw Error(`Component type ${a.createComponentOfType} does not exist so cannot create state variable for attribute ${r} of componentType ${e.componentType}.`);i=a.componentStateVariableForAttributeValue,void 0===i&&(i=t.stateVariableForAttributeValue,void 0===i&&(i="value"))}o.returnDependencies=function(){let e={};return a.fallBackToParentStateVariable&&(e.parentValue={dependencyType:"parentStateVariable",variableName:a.fallBackToParentStateVariable}),a.createPrimitiveOfType?e.attributePrimitive={dependencyType:"attributePrimitive",attributeName:r}:a.createTargetComponentNames?e.attributeTargetComponentNames={dependencyType:"attributeTargetComponentNames",attributeName:r}:e.attributeComponent={dependencyType:"attributeComponent",attributeName:r,variableNames:[i]},e},o.definition=function({dependencyValues:e,usedDefault:t}){let n;if(e.attributeComponent)n=e.attributeComponent.stateValues[i];else if(void 0!==e.attributePrimitive&&null!==e.attributePrimitive)n=e.attributePrimitive;else{if(void 0===e.attributeTargetComponentNames||null===e.attributeTargetComponentNames){return void 0!==e.parentValue&&null!==e.parentValue&&!t.parentValue?{setValue:{[s]:e.parentValue},checkForActualChange:{[s]:!0}}:{useEssentialOrDefaultValue:{[s]:!0},checkForActualChange:{[s]:!0}}}n=e.attributeTargetComponentNames}return n=validateAttributeValue({value:n,attributeSpecification:a,attribute:r}),{setValue:{[s]:n},checkForActualChange:{[s]:!0}}},a.noInverse||(o.inverseDefinition=async function({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n}){if(!t.attributeComponent){if(void 0!==t.attributePrimitive&&null!==t.attributePrimitive)return{success:!1};if(void 0!==t.attributeTargetComponentNames&&null!==t.attributeTargetComponentNames)return{success:!1};if(void 0!==t.parentValue&&null!==t.parentValue&&!n.parentValue)return{success:!0,instructions:[{setDependency:"parentValue",desiredValue:e[s]}]};{let t=validateAttributeValue({value:e[s],attributeSpecification:a,attribute:r});return{success:!0,instructions:[{setEssentialValue:s,value:t}]}}}return{success:!0,instructions:[{setDependency:"attributeComponent",desiredValue:e[s],variableIndex:0}]}});let l=["forRenderer","defaultValue","propagateToProps","triggerActionOnChange"];for(let e of l)e in a&&(o[e]=a[e])}}createAdapterStateVariableDefinitions({redefineDependencies:e,stateVariableDefinitions:t,componentClass:n}){let r=this._components[e.adapterTargetIdentity.componentName],a=n.createAttributesObject();for(let n in a){let i=a[n];if(!i.createStateVariable)continue;let s=i.createStateVariable,o=t[s]={isAttribute:!0,hasEssential:!0};if(i.public)if(o.public=!0,o.shadowingInstructions={},i.createPrimitiveOfType)o.shadowingInstructions.createComponentOfType=i.createPrimitiveOfType,"string"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="text":"stringArray"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="textList":"numberArray"===o.shadowingInstructions.createComponentOfType&&(o.shadowingInstructions.createComponentOfType="numberList");else{if(i.createTargetComponentNames)throw Error("Cannot make a public state variable from an attribute with createTargetComponentNames");o.shadowingInstructions.createComponentOfType=i.createComponentOfType}s in r.state?o.returnDependencies=()=>({adapterTargetVariable:{dependencyType:"stateVariable",componentName:e.adapterTargetIdentity.componentName,variableName:s}}):o.returnDependencies=()=>({}),o.definition=function({dependencyValues:e,usedDefault:t}){return void 0===e.adapterTargetVariable||t.adapterTargetVariable?{useEssentialOrDefaultValue:{[s]:!0},checkForActualChange:{[s]:!0}}:{setValue:{[s]:e.adapterTargetVariable},checkForActualChange:{[s]:!0}}},i.noInverse||(o.inverseDefinition=async function({desiredStateVariableValues:e,dependencyValues:t}){return void 0===t.adapterTargetVariable?{success:!0,instructions:[{setEssentialValue:s,value:e[s]}]}:{success:!0,instructions:[{setDependency:"adapterTargetVariable",desiredValue:e[s]}]}});let l=["forRenderer","defaultValue","propagateToProps"];for(let e of l)e in i&&(o[e]=i[e])}let i="value";e.substituteForPrimaryStateVariable?i=e.substituteForPrimaryStateVariable:n.primaryStateVariableForDefinition&&(i=n.primaryStateVariableForDefinition);let s=t[i];s.returnDependencies=()=>({adapterTargetVariable:{dependencyType:"stateVariable",componentName:e.adapterTargetIdentity.componentName,variableName:e.adapterVariable}}),s.set?s.definition=function({dependencyValues:e}){return{setValue:{[i]:s.set(e.adapterTargetVariable)}}}:s.definition=function({dependencyValues:e}){return{setValue:{[i]:e.adapterTargetVariable}}},s.inverseDefinition=function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"adapterTargetVariable",desiredValue:e[i]}]}},e.stateVariablesToShadow&&this.modifyStateDefsToBeShadows({stateVariablesToShadow:e.stateVariablesToShadow,stateVariableDefinitions:t,targetComponent:r})}async createReferenceShadowStateVariableDefinitions({redefineDependencies:e,stateVariableDefinitions:t,componentClass:n}){let r=this._components[e.targetName];e.propVariable&&!r.state[e.propVariable]&&this.checkIfArrayEntry({stateVariable:e.propVariable,component:r})&&await this.createFromArrayEntry({stateVariable:e.propVariable,component:r});let a=n.createAttributesObject();for(let e in a){let r=a[e],i=r.createStateVariable;if(!i)continue;let s,o=t[i]={isAttribute:!0,hasEssential:!0};if(r.createComponentOfType,r.public)if(o.public=!0,o.shadowingInstructions={},r.createPrimitiveOfType)o.shadowingInstructions.createComponentOfType=r.createPrimitiveOfType,"string"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="text":"stringArray"===o.shadowingInstructions.createComponentOfType?o.shadowingInstructions.createComponentOfType="textList":"numberArray"===o.shadowingInstructions.createComponentOfType&&(o.shadowingInstructions.createComponentOfType="numberList");else{if(r.createTargetComponentNames)throw Error("Cannot make a public state variable from an attribute with createTargetComponentNames");o.shadowingInstructions.createComponentOfType=r.createComponentOfType}if(r.createComponentOfType){let t=this.componentInfoObjects.allComponentClasses[r.createComponentOfType];if(!t)throw Error(`Component type ${r.createComponentOfType} does not exist so cannot create state variable for attribute ${e} of componentType ${n.componentType}.`);s=r.componentStateVariableForAttributeValue,void 0===s&&(s=t.stateVariableForAttributeValue,void 0===s&&(s="value"))}let l={};r.createPrimitiveOfType?l.attributePrimitive={dependencyType:"attributePrimitive",attributeName:e}:r.createTargetComponentNames?l.attributeTargetComponentNames={dependencyType:"attributeTargetComponentNames",attributeName:e}:l.attributeComponent={dependencyType:"attributeComponent",attributeName:e,variableNames:[s]},r.fallBackToParentStateVariable&&(l.parentValue={dependencyType:"parentStateVariable",variableName:r.fallBackToParentStateVariable}),o.returnDependencies=()=>l,o.definition=function({dependencyValues:t,usedDefault:n}){let a;if(t.attributeComponent)a=t.attributeComponent.stateValues[s];else if(void 0!==t.attributePrimitive&&null!==t.attributePrimitive)a=t.attributePrimitive;else{if(void 0===t.attributeTargetComponentNames||null===t.attributeTargetComponentNames){return void 0!==t.parentValue&&null!==t.parentValue&&!n.parentValue?{setValue:{[i]:t.parentValue},checkForActualChange:{[i]:!0}}:{useEssentialOrDefaultValue:{[i]:!0},checkForActualChange:{[i]:!0}}}a=t.attributeTargetComponentNames}return a=validateAttributeValue({value:a,attributeSpecification:r,attribute:e}),{setValue:{[i]:a},checkForActualChange:{[i]:!0}}},r.noInverse||(o.inverseDefinition=async function({desiredStateVariableValues:t,dependencyValues:n,stateValues:a,workspace:s}){if(!n.attributeComponent){if(void 0!==n.attributePrimitive&&null!==n.attributePrimitive)return{success:!1};if(void 0!==n.attributeTargetComponentNames&&null!==n.attributeTargetComponentNames)return{success:!1};if(void 0!==n.parentValue&&null!==n.parentValue&&!usedDefault.parentValue)return{success:!0,instructions:[{setDependency:"parentValue",desiredValue:t[i]}]};{let n=validateAttributeValue({value:t[i],attributeSpecification:r,attribute:e});return{success:!0,instructions:[{setEssentialValue:i,value:n}]}}}return{success:!0,instructions:[{setDependency:"attributeComponent",desiredValue:t[i],variableIndex:0}]}});let u=["forRenderer","defaultValue","propagateToProps"];for(let e of u)e in r&&(o[e]=r[e])}if(e.propVariable){if(!e.ignorePrimaryStateVariable){let a="value";e.substituteForPrimaryStateVariable?a=e.substituteForPrimaryStateVariable:n.primaryStateVariableForDefinition&&(a=n.primaryStateVariableForDefinition);let i=t[a];if(!i)throw e.substituteForPrimaryStateVariable?Error(`Invalid public state variable of componentType ${n.componentType}: substituteForPrimaryStateVariable ${e.substituteForPrimaryStateVariable} does not exist`):Error(`Cannot have a public state variable with componentType ${n.componentType} as the class doesn't have a primary state variable for definition`);i.isShadow=!0,i.returnDependencies=()=>({targetVariable:{dependencyType:"stateVariable",componentName:r.componentName,variableName:e.propVariable}});let s=!1;void 0!==r.state[e.propVariable].defaultValue&&(i.defaultValue=r.state[e.propVariable].defaultValue,i.set&&(i.defaultValue=i.set(i.defaultValue)),i.hasEssential=!0,s=!0),i.set?i.definition=function({dependencyValues:e,usedDefault:t}){let n=i.set(e.targetVariable);return s&&t.targetVariable?{useEssentialOrDefaultValue:{[a]:{defaultValue:n}},alwaysShadow:[a]}:{setValue:{[a]:n},alwaysShadow:[a]}}:i.definition=function({dependencyValues:e,usedDefault:t}){return s&&t.targetVariable?{useEssentialOrDefaultValue:{[a]:{defaultValue:e.targetVariable}},alwaysShadow:[a]}:{setValue:{[a]:e.targetVariable},alwaysShadow:[a]}},i.inverseDefinition=function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"targetVariable",desiredValue:e[a]}]}}}if(e.additionalStateVariableShadowing){let n=[],a=[];for(let t in e.additionalStateVariableShadowing)n.push(t),a.push(e.additionalStateVariableShadowing[t].stateVariableToShadow);this.modifyStateDefsToBeShadows({stateVariablesToShadow:n,stateVariableDefinitions:t,targetComponent:r,differentStateVariablesInTarget:a})}return}let i=!1;if("readyToExpandWhenResolved"in t){i=!0;let e=t.readyToExpandWhenResolved,n=e.returnDependencies.bind(e),a=e.definition;e.returnDependencies=function(e){let t=n(e);return t.targetReadyToExpandWhenResolved={dependencyType:"stateVariable",componentName:r.componentName,variableName:"readyToExpandWhenResolved"},t},e.definition=function(e){let t=a(e);return t.setValue&&t.setValue.readyToExpandWhenResolved&&(e.dependencyValues.targetReadyToExpandWhenResolved||(t.setValue.readyToExpandWhenResolved=!1)),t}}let s=[];for(let e in r.state){let t=r.state[e];(t.shadowVariable||t.isShadow)&&s.push(e)}this.modifyStateDefsToBeShadows({stateVariablesToShadow:s,stateVariableDefinitions:t,foundReadyToExpandWhenResolved:i,targetComponent:r})}modifyStateDefsToBeShadows({stateVariablesToShadow:e,stateVariableDefinitions:t,foundReadyToExpandWhenResolved:n,targetComponent:r,differentStateVariablesInTarget:a=[]}){let i={};for(let[s,o]of e.entries()){let l=t[o];if(void 0===l){if("__array_"!==o.slice(0,8))continue;l=t[o]={}}if(l.isShadow=!0,l.additionalStateVariablesDefined)for(let t of l.additionalStateVariablesDefined)e.includes(t)||(i[t]||(i[t]=[]),i[t].push(o));delete l.additionalStateVariablesDefined,n||delete l.stateVariablesDeterminingDependencies;let u=l.public&&l.shadowingInstructions.hasVariableComponentType;if(l.isArray)l.returnArrayDependenciesByKey=function({arrayKeys:e}){let t={};for(let n of e)t[n]={targetVariable:{dependencyType:"stateVariable",componentName:r.componentName,variableName:this.arrayVarNameFromArrayKey(n)}};let n={};return u&&(n.targetVariableComponentType={dependencyType:"stateVariableComponentType",componentName:r.componentName,variableName:o}),l.inverseShadowToSetEntireArray&&(n.targetArray={dependencyType:"stateVariable",componentName:r.componentName,variableName:o}),{globalDependencies:n,dependenciesByKey:t}},l.arrayDefinitionByKey=function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let e of n)"targetVariable"in t[e]?r[e]=t[e].targetVariable:r[e]=l.defaultValueByArrayKey?.(e);let a={setValue:{[o]:r},alwaysShadow:[o]};return"targetVariableComponentType"in e&&(a.setCreateComponentOfType={[o]:e.targetVariableComponentType}),a},l.inverseArrayDefinitionByKey=function({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,arraySize:r,initialChange:a}){if(l.inverseShadowToSetEntireArray)return{success:!0,instructions:[{setDependency:"targetArray",desiredValue:e[o],treatAsInitialChange:a}]};let i=[];for(let r in e[o])t[r]&&i.push({setDependency:n[r].targetVariable,desiredValue:e[o][r],shadowedVariable:!0});return{success:!0,instructions:i}};else{let e=()=>({});n&&(e=l.returnDependencies.bind(l));let t=a[s];t||(t=o),l.returnDependencies=function(n){let a=Object.assign({},e(n));return a.targetVariable={dependencyType:"stateVariable",componentName:r.componentName,variableName:t},u&&(a.targetVariableComponentType={dependencyType:"stateVariableComponentType",componentName:r.componentName,variableName:t}),a},l.definition=function({dependencyValues:e,usedDefault:t}){let n={alwaysShadow:[o]};return"targetVariableComponentType"in e&&(n.setCreateComponentOfType={[o]:e.targetVariableComponentType}),t.targetVariable&&"defaultValue"in l&&l.hasEssential?n.useEssentialOrDefaultValue={[o]:{defaultValue:e.targetVariable}}:n.setValue={[o]:e.targetVariable},n},l.excludeDependencyValuesInInverseDefinition=!0,l.inverseDefinition=function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"targetVariable",desiredValue:e[o],shadowedVariable:!0}]}}}}for(let e in i)this.modifyStateDefToDeleteVariableReferences({varNamesToDelete:i[e],stateDef:t[e]})}modifyStateDefToDeleteVariableReferences({varNamesToDelete:e,stateDef:t}){for(let n of e){let e=t.additionalStateVariablesDefined.indexOf(n);t.additionalStateVariablesDefined.splice(e,1)}let n=t.definition;t.definition=function(t){let r=n(t);for(let t in r)if(Array.isArray(r[t]))for(let n of e){let e=r[t].indexOf(n);-1!==e&&r[t].splice(e,1)}else for(let n of e)delete r[t][n];return r}}async initializeComponentStateVariables(e){for(let t in e.state)e.state[t].isAlias?(e.stateVarAliases||(e.stateVarAliases={}),e.stateVarAliases[t]=e.state[t].targetVariableName,delete e.state[t]):await this.initializeStateVariable({component:e,stateVariable:t})}async initializeStateVariable({component:e,stateVariable:t,arrayStateVariable:n,arrayEntryPrefix:r}){let a=this.getStateVariableValue;e.state[t]||(e.state[t]={});let i=e.state[t];if(i.isResolved=!1,Object.defineProperty(i,"value",{get:()=>a({component:e,stateVariable:t}),configurable:!0}),void 0!==r?await this.initializeArrayEntryStateVariable({stateVarObj:i,arrayStateVariable:n,arrayEntryPrefix:r,component:e,stateVariable:t}):i.isArray&&await this.initializeArrayStateVariable({stateVarObj:i,component:e,stateVariable:t}),i.triggerActionOnChange){let n=this.stateVariableChangeTriggers[e.componentName];n||(n=this.stateVariableChangeTriggers[e.componentName]={}),n[t]={action:i.triggerActionOnChange}}}async checkForActionChaining({component:e,stateVariables:t}){if(e){t||(t=Object.keys(e.state));for(let n of t){let t=e.state[n];if(t.chainActionOnActionOfStateVariableTargets){let r,a=t.chainActionOnActionOfStateVariableTargets,i=await t.value,s=this.originsOfActionsChangedToActions[e.componentName];s&&(r=s[n]),r||(r=[]);let o=[];if(Array.isArray(i)){o=[...i];for(let t of o){let i=r.indexOf(t);if(-1===i){let r=this.actionsChangedToActions[t];r||(r=this.actionsChangedToActions[t]=[]),r.push({componentName:e.componentName,actionName:a.triggeredAction,stateVariableDefiningChain:n,args:{}})}else r.splice(i,1)}}for(let t of r){let r=this.actionsChangedToActions[t];if(r){let a=[];for(let t of r)t.componentName===e.componentName&&t.stateVariableDefiningChain===n||a.push(t);this.actionsChangedToActions[t]=a}}o.length>0?(s||(s=this.originsOfActionsChangedToActions[e.componentName]={}),s[n]=o):s&&(delete s[n],0===Object.keys(s).length&&delete this.originsOfActionsChangedToActions[e.componentName])}}}}async initializeArrayEntryStateVariable({stateVarObj:e,arrayStateVariable:t,arrayEntryPrefix:n,component:r,stateVariable:a}){e.isArrayEntry=!0,e.arrayStateVariable=t;let i=r.state[t];if(e.definition=i.definition,e.inverseDefinition=i.inverseDefinition,e.markStale=i.markStale,e.freshnessInfo=i.freshnessInfo,e.getPreviousDependencyValuesForMarkStale=i.getPreviousDependencyValuesForMarkStale,e.provideEssentialValuesInDefinition=i.provideEssentialValuesInDefinition,e.providePreviousValuesInDefinition=i.providePreviousValuesInDefinition,e.nDimensions=i.returnEntryDimensions(n),e.entryPrefix=n,e.varEnding=a.slice(n.length),i.createWorkspace&&(e.createWorkspace=!0,e.workspace=i.workspace),i.basedOnArrayKeyStateVariables&&(e.basedOnArrayKeyStateVariables=!0),i.additionalStateVariablesDefined){e.additionalStateVariablesDefined=[];let t=i.entryPrefixes.indexOf(n);for(let n of i.additionalStateVariablesDefined){let a=r.state[n];if(a.isArray){let n=a.entryPrefixes[t]+e.varEnding;e.additionalStateVariablesDefined.push(n)}else e.additionalStateVariablesDefined.push(n)}}if(i.shadowingInstructions&&(e.shadowingInstructions={},e.wrappingComponents=i.shadowingInstructions.returnWrappingComponents(n),i.shadowingInstructions.attributesToShadow&&(e.shadowingInstructions.attributesToShadow=i.shadowingInstructions.attributesToShadow),i.shadowingInstructions.createComponentOfType)){let t=i.entryPrefixes.indexOf(n);i.shadowingInstructions.createComponentOfType[t]&&(e.shadowingInstructions.createComponentOfType=[i.shadowingInstructions.createComponentOfType[t]])}if(i.getEntryValues?e.getValueFromArrayValues=async function(){return await i.getEntryValues({varName:a})}:e.getValueFromArrayValues=async function(){let t=await e.arrayKeys;if(0===t.length)return;let n=[];for(let e of t)n.push(i.getArrayValue({arrayKey:e}));return 1===n.length?n[0]:n},e.arraySizeStateVariable=i.arraySizeStateVariable,e._arrayKeys=[],e._unflattenedArrayKeys=[],Object.defineProperty(e,"arrayKeys",{get:function(){return(async()=>(await i.arraySize,e._arrayKeys))()}}),Object.defineProperty(e,"unflattenedArrayKeys",{get:function(){return(async()=>(await i.arraySize,e._unflattenedArrayKeys))()}}),r.state[e.arraySizeStateVariable].initiallyResolved){let t=await i.arraySize,n=i.getArrayKeysFromVarName({arrayEntryPrefix:e.entryPrefix,varEnding:e.varEnding,arraySize:t,nDimensions:i.nDimensions});e._unflattenedArrayKeys=n,e._arrayKeys=flattenDeep(n);let r=i.varNamesIncludingArrayKeys;for(let t of e._arrayKeys)r[t]||(r[t]=[]),r[t].push(a)}if(i.arrayEntryNames.push(a),Object.defineProperty(e,"arraySize",{get:()=>i.arraySize}),Object.defineProperty(e,"arrayEntrySize",{get:function(){return(async()=>{let t=[],n=[await e.unflattenedArrayKeys];for(let r=0;r1?(e.keyToIndex=e=>e.split(",").map((e=>Number(e))),e.setArrayValue=function({value:t,arrayKey:n,arraySize:r,arrayValues:a=e.arrayValues}){let i=e.keyToIndex(n),s=i.length;if(!s>e.nDimensions)return console.warn("Cannot set array value. Number of dimensions is too large."),{nFailures:1};let o=a,l=r;for(let c of i.slice(0,i.length-1)){if(!(c>=0&&ca&&(console.warn("ignoring array values of out bounds"),r+=e.length-a,e=e.slice(0,a)),1===n.length)for(let[n,r]of e.entries())t[n]=r;else for(let[a,i]of e.entries()){t[a]||(t=[]),r+=p(i,t[a],n[a]).nFailures}return{nFailures:r}}u+=p(t,o,l).nFailures}else o[i[i.length-1]]=t;return{nFailures:u}},e.getArrayValue=function({arrayKey:t,arrayValues:n=e.arrayValues}){let r=e.keyToIndex(t),a=n;for(let e of r.slice(0,r.length-1))if(a=a[e],!a)return;return a[r[r.length-1]]},e.getAllArrayKeys||(e.getAllArrayKeys=function(e,t=!0,n){function r(e,t){for(let[n,a]of e.entries())Array.isArray(a)?r(a,t):e[n]=t+","+a}function a(e){if(1===e.length)return Array.from(Array(e[0]),((e,t)=>String(t)));{let n=e[0],i=a(e.slice(1)),s=[];for(let e=0;ee+","+t)));else{let t=deepClone(i);r(t,e),s.push(t)}return s}}return n?0===n.length?[]:a(n):e&&0!==e.length?a(e):[]}),e.arrayVarNameFromArrayKey||(e.arrayVarNameFromArrayKey=function(e){return r[0]+e.split(",").map((e=>Number(e)+1)).join("_")}),e.arrayVarNameFromPropIndex||(e.arrayVarNameFromPropIndex=function(t,n){return r[0]+[...t.map((e=>Math.round(Number(e)))),...Array(e.nDimensions-t.length).fill(1)].join("_")}),e.adjustArrayToNewArraySize=async function(){let t=await e.arraySize;!function e(t,n){if(t.length=n[0],n.length>1){let r=n.slice(1);for(let[n,a]of t.entries())a||(a=t[n]=[]),e(a,r)}}(e.arrayValues,t)}):(e.keyToIndex=e=>Number(e),e.setArrayValue=function({value:t,arrayKey:r,arraySize:a,arrayValues:i=e.arrayValues}){let s=e.keyToIndex(r);return s>=0&&sString(t))):e&&0!==e.length?Array.from(Array(e[0]),((e,t)=>String(t))):[]}),e.arrayVarNameFromArrayKey||(e.arrayVarNameFromArrayKey=function(e){return r[0]+String(Number(e)+1)}),e.arrayVarNameFromPropIndex||(e.arrayVarNameFromPropIndex=function(e,t){return r[0]+e[0]}),e.adjustArrayToNewArraySize=async function(){let t=await e.arraySize;e.arrayValues.length=t[0]}),e.getArrayKeysFromVarName||(e.getArrayKeysFromVarName=returnDefaultGetArrayKeysFromVarName(e.nDimensions)),e.indexToKey=e=>String(e);let r=e.entryPrefixes;r||(r=e.entryPrefixes=[n]),t.arrayEntryPrefixes||(t.arrayEntryPrefixes={});for(let e of r)t.arrayEntryPrefixes[e]=n;e.returnEntryDimensions||(e.returnEntryDimensions=()=>1),e.shadowingInstructions&&(e.shadowingInstructions.returnWrappingComponents||(e.shadowingInstructions.returnWrappingComponents=e=>[]),e.wrappingComponents=e.shadowingInstructions.returnWrappingComponents()),e.usedDefaultByArrayKey={},e.arrayEntryNames=[],e.varNamesIncludingArrayKeys={};let a=[n];function i(t,n,r){let a={},i={};for(let n of e.dependencyNames.global)a[n]=t[n],i[n]=r[n];let s={},o={},l={};for(let a of n)if(s[a]={},o[a]={},a in e.dependencyNames.namesByKey){l[a]=!0;for(let n in e.dependencyNames.namesByKey[a]){let i=e.dependencyNames.namesByKey[a][n];i in t?(s[a][n]=t[i],o[a][n]=r[i]):l[a]=!1}}return{globalDependencyValues:a,globalUsedDefault:i,dependencyValuesByKey:s,usedDefaultByKey:o,foundAllDependencyValuesForKey:l}}if(e.additionalStateVariablesDefined&&a.push(...e.additionalStateVariablesDefined),e.returnDependencies=async function(n){n.arraySize=await e.arraySize;for(let e in n.stateValues)"__array_"===e.slice(0,8)&&delete n.stateValues[e];if(void 0===n.arrayKeys&&(n.arrayKeys=e.getAllArrayKeys(n.arraySize)),!e.dependencyNames&&(e.dependencyNames={namesByKey:{},keysByName:{},global:[]},e.additionalStateVariablesDefined))for(let n of e.additionalStateVariablesDefined)t.state[n].dependencyNames=e.dependencyNames;let r={};if(e.basedOnArrayKeyStateVariables&&n.arrayKeys.length>1)for(let e of n.arrayKeys)for(let n of a){let a=t.state[n];r[n+"_"+e]={dependencyType:"stateVariable",variableName:a.arrayVarNameFromArrayKey(e)}}else{let t=e.returnArrayDependenciesByKey(n);t.globalDependencies&&(e.dependencyNames.global=Object.keys(t.globalDependencies),Object.assign(r,t.globalDependencies)),t.dependenciesByKey||(t.dependenciesByKey={});for(let a of n.arrayKeys){a in e.dependencyNames.namesByKey||(n.changedDependency=!0),e.dependencyNames.namesByKey[a]={};for(let n in t.dependenciesByKey[a]){let i="__"+a+"_"+n;r[i]=t.dependenciesByKey[a][n],e.dependencyNames.namesByKey[a][n]=i,e.dependencyNames.keysByName[i]||(e.dependencyNames.keysByName[i]=[]),e.dependencyNames.keysByName[i].includes(a)||e.dependencyNames.keysByName[i].push(a)}}e.dependencyNames.global.push("__array_size")}return r.__array_size={dependencyType:"stateVariable",variableName:e.arraySizeStateVariable},r},e.getCurrentFreshness=function({freshnessInfo:t,arrayKeys:r,arraySize:a}){void 0===r&&(r=e.getAllArrayKeys(a));let i=t.freshByKey,s=t.freshArraySize?1:0;for(let e of r)i[e]&&(s+=1);return s>0?s===r.length+1?{fresh:{[n]:!0}}:{partiallyFresh:{[n]:s}}:{fresh:{[n]:!1}}},e.markStale=function({freshnessInfo:t,changes:r,arrayKeys:a,arraySize:i}){let s={};void 0===a&&(a=e.getAllArrayKeys(i)),e.markStaleByKey&&(s=e.markStaleByKey({arrayKeys:a,changes:r}));let o=t.freshByKey;if(r.__array_size)return t.freshArraySize=!1,t.freshByKey={},s.fresh={[n]:!1},s;if(0===Object.keys(o).length)return t.freshByKey={},t.freshArraySize?(s.partiallyFresh={[n]:1},s):(s.fresh={[n]:!1},s);for(let i in r){if(e.dependencyNames.global.includes(i))return t.freshByKey={},t.freshArraySize?(s.partiallyFresh={[n]:1},s):(s.fresh={[n]:!1},s);if(e.basedOnArrayKeyStateVariables&&a.length>1)delete o[i];else for(let t of e.dependencyNames.keysByName[i])delete o[t]}let l=t.freshArraySize?1:0;for(let e of a)o[e]&&(l+=1);return l>0?l===a.length+1?(s.fresh={[n]:!0},s):(s.partiallyFresh={[n]:l},s):(s.fresh={[n]:!1},s)},e.freshenOnNoChanges=function({arrayKeys:t,freshnessInfo:n,arraySize:r}){let a=n.freshByKey;void 0===t&&(t=e.getAllArrayKeys(r));for(let e of t)a[e]=!0},e.definition=function(r){if(void 0===r.arrayKeys&&(r.arrayKeys=e.getAllArrayKeys(r.arraySize)),e.basedOnArrayKeyStateVariables&&r.arrayKeys.length>1)return{};{let a=i(r.dependencyValues,r.arrayKeys,r.usedDefault),s=a.globalDependencyValues,o=a.globalUsedDefault,l=a.dependencyValuesByKey,u=a.usedDefaultByKey,c=a.foundAllDependencyValuesForKey;delete r.dependencyValues,r.globalDependencyValues=s,r.globalUsedDefault=o,r.dependencyValuesByKey=l,r.usedDefaultByKey=u;let p,d=[],m=r.freshnessInfo.freshByKey;for(let e of r.arrayKeys)!m[e]&&c[e]&&(m[e]=!0,d.push(e));if(0===d.length)p={};else{if(r.arrayKeys=d,!e.arrayDefinitionByKey)throw Error(`For ${n} of ${t.componentType}, arrayDefinitionByKey must be a function`);if(p=e.arrayDefinitionByKey(r),p.setValue&&p.setValue[n])for(let e in p.setValue[n])m[e]=!0;if(p.useEssentialOrDefaultValue&&p.useEssentialOrDefaultValue[n])for(let e in p.useEssentialOrDefaultValue[n])m[e]=!0}if(!r.freshnessInfo.freshArraySize){if(r.changes.__array_size&&(p.arraySizeChanged=[n],e.additionalStateVariablesDefined))for(let n of e.additionalStateVariablesDefined)t.state[n].isArray&&p.arraySizeChanged.push(n);r.freshnessInfo.freshArraySize=!0}return p}},e.inverseDefinition=function(t){if(!e.inverseArrayDefinitionByKey)return{success:!1};if(void 0===t.arrayKeys&&(t.arrayKeys=e.getAllArrayKeys(t.arraySize)),e.basedOnArrayKeyStateVariables&&t.arrayKeys.length>1){let e=[];for(let n of a)for(let r in t.desiredStateVariableValues[n]){let a=n+"_"+r;a in t.dependencyValues&&e.push({setDependency:a,desiredValue:t.desiredStateVariableValues[n][r],treatAsInitialChange:t.initialChange})}return{success:!0,instructions:e}}{let n=i(t.dependencyValues,t.arrayKeys,t.usedDefault),r=n.globalDependencyValues,a=n.globalUsedDefault,s=n.dependencyValuesByKey,o=n.usedDefaultByKey;delete t.dependencyValues,t.globalDependencyValues=r,t.globalUsedDefault=a,t.dependencyValuesByKey=s,t.usedDefaultByKey=o,t.dependencyNamesByKey=e.dependencyNames.namesByKey;let l={};for(let e in t.desiredStateVariableValues)if(Array.isArray(t.desiredStateVariableValues[e]))l[e]=t.desiredStateVariableValues[e];else{l[e]={};for(let n in t.desiredStateVariableValues[e])t.arrayKeys.includes(n)&&(l[e][n]=t.desiredStateVariableValues[e][n])}return t.desiredStateVariableValues=l,e.inverseArrayDefinitionByKey(t)}},await this.createArraySizeStateVariable({stateVarObj:e,component:t,stateVariable:n}),e.arraySizeStale=!0,e.previousArraySize=[],Object.defineProperty(e,"arraySize",{get:function(){return(async()=>t.state[e.arraySizeStateVariable].initiallyResolved?(e.arraySizeStale&&await e.recalculateArraySizeDependentQuantities(),await t.stateValues[e.arraySizeStateVariable]):[])()}}),e.recalculateArraySizeDependentQuantities=async function(){let n=await t.stateValues[e.arraySizeStateVariable];if(e.previousArraySize.length!==n.length||e.previousArraySize.some(((e,t)=>e!=n[t]))){e.previousArraySize=[...n];let r=e.varNamesIncludingArrayKeys={};for(let a of e.arrayEntryNames){let i=t.state[a],s=e.getArrayKeysFromVarName({arrayEntryPrefix:i.entryPrefix,varEnding:i.varEnding,arraySize:n,nDimensions:e.nDimensions});i._unflattenedArrayKeys=s,i._arrayKeys=flattenDeep(s);for(let e of i._arrayKeys)r[e]||(r[e]=[]),r[e].push(a)}}e.arraySizeStale=!1},!e.freshnessInfo&&(e.freshnessInfo={freshByKey:{}},e.additionalStateVariablesDefined))for(let n of e.additionalStateVariablesDefined)t.state[n]||(t.state[n]={}),t.state[n].freshnessInfo=e.freshnessInfo}async createArraySizeStateVariable({stateVarObj:e,component:t,stateVariable:n}){let r=[n];e.additionalStateVariablesDefined&&r.push(...e.additionalStateVariablesDefined),r.sort();let a="__array_size_"+r.join("_");if(e.arraySizeStateVariable=a,e.stateVariablesDeterminingDependencies?(e.stateVariablesDeterminingDependencies,e.stateVariablesDeterminingDependencies.push(a)):e.stateVariablesDeterminingDependencies=[a],t.state[a]){if(t.state[a].isShadow){t.state[a].markStale=function(){for(let e of r)t.state[e].arraySizeStale=!0;return{}}}}else t.state[a]={returnDependencies:e.returnArraySizeDependencies,definition({dependencyValues:t}){let n=e.returnArraySize({dependencyValues:t});for(let[e,t]of n.entries())Number.isInteger(t)&&t>=0||(n[e]=0);return{setValue:{[a]:n}}},markStale(){for(let e of r)t.state[e].arraySizeStale=!0;return{}}},e.stateVariablesDeterminingArraySizeDependencies&&(t.state[a].stateVariablesDeterminingDependencies=e.stateVariablesDeterminingArraySizeDependencies),await this.initializeStateVariable({component:t,stateVariable:a})}async arrayEntryNamesFromPropIndex({stateVariables:e,component:t,propIndex:n}){let r=[];for(let a of e){let e,i=t.state[a];if(!i){if(!this.checkIfArrayEntry({stateVariable:a,component:t})){r.push(a);continue}await this.createFromArrayEntry({stateVariable:a,component:t}),i=t.state[a]}if(i.isArray)e=i.arrayVarNameFromPropIndex(n,a);else if(i.isArrayEntry){e=t.state[i.arrayStateVariable].arrayVarNameFromPropIndex(n,a)}else console.warn(`Cannot get propIndex from ${a} of ${t.componentName} as it is not an array or array entry state variable`),e=a;e?r.push(e):(console.warn(`Cannot get propIndex from ${a} of ${t.componentName}`),r.push(a))}return r}recursivelyReplaceCompositesWithReplacements({replacements:e,recurseNonStandardComposites:t=!1,forceExpandComposites:n=!1,includeWithheldReplacements:r=!1}){let a=[],i=[],s=[],o=[];for(let l of e)if(this.componentInfoObjects.isCompositeComponent({componentType:l.componentType,includeNonStandard:t}))if(a.push(l.componentName),l.isExpanded||(l.state.readyToExpandWhenResolved.isResolved?s.push(l.componentName):o.push(l.componentName)),l.isExpanded){let e=l.replacements;!r&&l.replacementsToWithhold>0&&(e=e.slice(0,-l.replacementsToWithhold));let u=this.recursivelyReplaceCompositesWithReplacements({replacements:e,recurseNonStandardComposites:t,forceExpandComposites:n,includeWithheldReplacements:r});a.push(...u.compositesFound),i.push(...u.newReplacements),s.push(...u.unexpandedCompositesReady),o.push(...u.unexpandedCompositesNotReady)}else i.push(l);else i.push(l);return{compositesFound:a,newReplacements:i,unexpandedCompositesReady:s,unexpandedCompositesNotReady:o}}async getStateVariableValue({component:e,stateVariable:t}){let n=e.state[t];if(!n)throw Error(`Can't get value of ${t} of ${e.componentName} as it doesn't exist.`);if(e.reprocessAfterEvaluate){let t=e.reprocessAfterEvaluate;delete this._components[e.componentName].reprocessAfterEvaluate;for(let n in t)e.state[n]&&await this.getStateVariableValue({component:e,stateVariable:n});await this.processNewStateVariableValues({[e.componentName]:t})}let r=n.additionalStateVariablesDefined,a=[t];r&&a.push(...r);let i=!1;for(let n of a){if(!e.state[n].isResolved){if(!(await this.dependencies.resolveItem({componentName:e.componentName,type:"stateVariable",stateVariable:n,force:!0})).success)throw Error(`Can't get value of ${t} of ${e.componentName} as ${n} couldn't be resolved.`)}e.state[n].justUpdatedForNewComponent&&(delete this._components[e.componentName].state[n].justUpdatedForNewComponent,i=!0)}let s=await this.getStateVariableDefinitionArguments({component:e,stateVariable:t});s.componentInfoObjects=this.componentInfoObjects,s.justUpdatedForNewComponent=i,s.freshnessInfo=n.freshnessInfo;let o,l=s.arraySize;if(0!==Object.keys(s.changes).length||void 0===n._previousValue||n.forceRecalculation)delete n.forceRecalculation,o=n.definition(s);else{let e=[t];r&&e.push(...r),o={noChanges:e},n.freshenOnNoChanges&&n.freshenOnNoChanges(s)}let u={[t]:!1},c={};if(r)for(let e of r)u[e]=!1;for(let n in o.setValue){if(!(n in e.state))throw Error(`Definition of state variable ${t} of ${e.componentName} returned value of ${n}, which isn't a state variable.`);let r;if(n in u)u[n]=!0,e.state[n].isArray?c[n]||(c[n]={arrayKeysChanged:{}}):c[n]=!0;else{if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t,u[t]=!0,c[t]=!0;break}if(!r)throw Error(`Attempting to set value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}if(!(e.state[n].isResolved||r&&e.state[r].isResolved))throw Error(`Attempting to set value of stateVariable ${n} of ${e.componentName} while it is still unresolved!`);if(e.state[n].isArray){c[n]||(c[n]={arrayKeysChanged:{}});let t={};o.checkForActualChange&&o.checkForActualChange[n]&&(t=o.checkForActualChange[n]);for(let r in o.setValue[n])if(t[r]){e.state[n].getArrayValue({arrayKey:r})!==o.setValue[n][r]&&(e.state[n].setArrayValue({value:o.setValue[n][r],arrayKey:r,arraySize:l}),e.state[n].usedDefaultByArrayKey[r]=!1,c[n].arrayKeysChanged[r]=!0)}else e.state[n].setArrayValue({value:o.setValue[n][r],arrayKey:r,arraySize:l}),e.state[n].usedDefaultByArrayKey[r]=!1,c[n].arrayKeysChanged[r]=!0}else if(delete e.state[n].value,e.state[n].value=o.setValue[n],delete e.state[n].usedDefault,o.checkForActualChange?.[n]){let t=e.state[n].value,r=e.state[n]._previousValue;(t===r||Array.isArray(t)&&Array.isArray(r)&&t.length===r.length&&t.every(((e,t)=>e===r[t])))&&delete c[n]}}for(let n in o.useEssentialOrDefaultValue){if(!(n in e.state))throw Error(`Definition of state variable ${t} of ${e.componentName} requested essential or default value of ${n}, which isn't a state variable.`);if(!e.state[n].hasEssential)throw Error(`Definition of state variable ${t} of ${e.componentName} requested essential or default value of ${n}, but hasEssential is not set.`);let r;if(n in u)u[n]=!0,e.state[n].isArray?c[n]||(c[n]={arrayKeysChanged:{}}):c[n]=!0;else{if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t,u[t]=!0,c[t]=!0;break}if(!r)throw Error(`Attempting to set value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}if(!(e.state[n].isResolved||r&&e.state[r].isResolved))throw Error(`Attempting to set value of stateVariable ${n} of ${e.componentName} while it is still unresolved!`);let a=n;e.state[n].essentialVarName&&(a=e.state[n].essentialVarName);let i=e.essentialState[a];if(e.state[n].isArray){c[n]||(c[n]={arrayKeysChanged:{}});let t={};o.checkForActualChange&&o.checkForActualChange[n]&&(t=o.checkForActualChange[n]);for(let r in o.useEssentialOrDefaultValue[n]){let s,u;if(t[r]&&(s=e.state[n].getArrayValue({arrayKey:r})),Array.isArray(i)?u=e.state[n].getArrayValue({arrayKey:r,arrayValues:i}):i=e.essentialState[a]=[],void 0!==u)e.state[n].setArrayValue({value:u,arrayKey:r,arraySize:l});else{let t=o.useEssentialOrDefaultValue[n][r].defaultValue;if(void 0!==t)e.state[n].setArrayValue({value:t,arrayKey:r,arraySize:l}),e.state[n].usedDefaultByArrayKey[r]=!0;else{if(void 0===e.state[n].defaultValueByArrayKey?.(r))throw Error(`Neither value nor default value specified; state variable: ${n}, component: ${e.componentName}, arrayKey: ${r}.`);e.state[n].setArrayValue({value:e.state[n].defaultValueByArrayKey(r),arrayKey:r,arraySize:l}),e.state[n].usedDefaultByArrayKey[r]=!0}}if(t[r]){e.state[n].getArrayValue({arrayKey:r})!==s&&(c[n].arrayKeysChanged[r]=!0)}else c[n].arrayKeysChanged[r]=!0}}else{if(void 0!==i)delete e.state[n].value,e.state[n].value=i;else{let t=o.useEssentialOrDefaultValue[n].defaultValue;if(void 0!==t)delete e.state[n].value,e.state[n].value=t,e.state[n].usedDefault=!0;else{if(void 0===e.state[n].defaultValue)throw Error(`Neither value nor default value specified; state variable: ${n}, component: ${e.componentName}.`);delete e.state[n].value,e.state[n].value=e.state[n].defaultValue,e.state[n].usedDefault=!0}}if(o.checkForActualChange?.[n]){let t=e.state[n].value,r=e.state[n]._previousValue;(t===r||Array.isArray(t)&&Array.isArray(r)&&t.length===r.length&&t.every(((e,t)=>e===r[t])))&&delete c[n]}}}for(let n in o.markAsUsedDefault){if(!e.state[n].isResolved)throw Error(`Marking state variable as used default when it isn't yet resolved: ${n} of ${e.componentName}`);if(!(n in u)){let r;if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t;break}if(!r)throw Error(`Marking state variable ${n} as used default in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}if(Array.isArray())for(let t in o.markAsUsedDefault[n])o.markAsUsedDefault[n][t]&&(e.state[n].usedDefaultByArrayKey[t]=!0);else o.markAsUsedDefault[n]&&(e.state[n].usedDefault=!0)}if(o.noChanges)for(let n of o.noChanges){if(e.state[n].isResolved||(e.state[n].isResolved=!0),!(n in u)){let r;if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t;break}if(!r)throw Error(`Claiming stateVariable ${n} is unchanged in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}u[n]=!0,(Object.getOwnPropertyDescriptor(e.state[n],"value").get||e.state[n].immutable)&&(delete e.state[n].value,e.state[n].value=e.state[n]._previousValue)}for(let n in o.setEssentialValue){if(!(n in e.state))throw Error(`Definition of state variable ${t} of ${e.componentName} tried to make ${n} essential, which isn't a state variable.`);if(!(n in u)){let r;if(e.state[n].isArray&&e.state[n].arrayEntryNames)for(let t of e.state[n].arrayEntryNames)if(t in u){r=t;break}if(!r)throw Error(`Attempting to set essential value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it's not listed as an additional state variable defined.`)}if(!e.state[n].hasEssential)throw Error(`Attempting to set the essential value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it does not have an essential value`);if(!e.state[n].shadowVariable&&!e.state[n].doNotShadowEssential)throw Error(`Attempting to set the essential value of stateVariable ${n} in definition of ${t} of ${e.componentName}, but it is not allowed unless the state variable is shadowed or the essential state is not shadowed.`);this.essentialValuesSavedInDefinition[e.componentName]||(this.essentialValuesSavedInDefinition[e.componentName]={});let r=n;if(e.state[n].essentialVarName&&(r=e.state[n].essentialVarName),e.state[n].isArray){let t=e.essentialState[r];Array.isArray(t)||(t=e.essentialState[r]=[]),this.essentialValuesSavedInDefinition[e.componentName][n]||(this.essentialValuesSavedInDefinition[e.componentName][n]={mergeObject:!0});for(let r in o.setEssentialValue[n])e.state[n].setArrayValue({value:o.setEssentialValue[n][r],arrayKey:r,arraySize:l,arrayValues:t}),this.essentialValuesSavedInDefinition[e.componentName][n][r]=o.setEssentialValue[n][r]}else e.essentialState[r]=o.setEssentialValue[n],this.essentialValuesSavedInDefinition[e.componentName][n]=o.setEssentialValue[n]}if(o.setCreateComponentOfType)for(let t in o.setCreateComponentOfType){if(!e.state[t].shadowingInstructions?.hasVariableComponentType)throw Error(`Cannot set type of ${t} of ${e.componentName} as it it does not have the hasVariableComponentType attribute.`);let n=!1,r=e.state[t].shadowingInstructions;r||(r=e.state[t].shadowingInstructions={});let a=r.createComponentOfType,i=o.setCreateComponentOfType[t];if(Array.isArray(a)?Array.isArray(i)?(a.length!==i.length||a.some(((e,t)=>e!=i[t])))&&(n=!0):n=!0:n=!!Array.isArray(i)||a!==i,n&&(c[t]=!0),r.createComponentOfType=o.setCreateComponentOfType[t],e.state[t].isArray&&e.state[t].arrayEntryNames){let n=o.setCreateComponentOfType[t],r=Array.isArray(n);for(let a of e.state[t].arrayEntryNames)if(r){let r=await e.state[a].arrayKeys,i=[];for(let a of r){let r=e.state[t].keyToIndex(a);i.push(n[r])}e.state[a].shadowingInstructions.createComponentOfType=i}else e.state[a].shadowingInstructions.createComponentOfType=n}}if(o.arraySizeChanged)for(let t of o.arraySizeChanged)await e.state[t].adjustArrayToNewArraySize(),void 0===c[t]?c[t]={arrayKeysChanged:{}}:!0===c[t]&&(c[t]={allArrayKeysChanged:!0,arrayKeysChanged:{}}),c[t].arraySizeChanged=!0;for(let n in u){if(!(u[n]||e.state[n].isArrayEntry||e.state[n].isArray))throw Error(`definition of ${t} of ${e.componentName} didn't return value of ${n}`);e.state[n].isArray?(delete e.state[n].value,e.state[n].value=e.state[n].arrayValues):e.state[n].isArrayEntry&&(delete e.state[n].value,e.state[n].value=await e.state[n].getValueFromArrayValues())}for(let t in c)if(this.dependencies.recordActualChangeInUpstreamDependencies({component:e,varName:t,changes:c[t]}),e.state[t].isArray){let n=[];if(!0===c[t]||c[t].allArrayKeysChanged||c.arraySizeChanged)e.state[t].arrayEntryNames&&(n=e.state[t].arrayEntryNames);else{let r=e.state[t].varNamesIncludingArrayKeys;for(let e in c[t].arrayKeysChanged){let t=r[e];t&&n.push(...t)}}n=[...new Set(n)];for(let t of n)this.dependencies.recordActualChangeInUpstreamDependencies({component:e,varName:t})}return await n.value}async getStateVariableDefinitionArguments({component:e,stateVariable:t,excludeDependencyValues:n}){let r;r=n?{}:await this.dependencies.getStateVariableDependencyValues({component:e,stateVariable:t}),r.componentName=e.componentName;let a=e.state[t];if(a.isArrayEntry?(r.arrayKeys=await a.arrayKeys,r.arraySize=await a.arraySize):a.isArray&&(r.arraySize=await a.arraySize),a.createWorkspace&&(r.workspace=a.workspace),a.providePreviousValuesInDefinition||a.provideEssentialValuesInDefinition){let n=[t];if(a.additionalStateVariablesDefined&&n.push(...a.additionalStateVariablesDefined),a.providePreviousValuesInDefinition){let t={};for(let r of n)e.state[r].isArrayEntry&&(r=e.state[r].arrayStateVariable),t[r]=e.state[r]._previousValue;r.previousValues=t}if(a.provideEssentialValuesInDefinition){let t={};for(let r of n){e.state[r].isArrayEntry&&(r=e.state[r].arrayStateVariable);let n=r;e.state[r].essentialVarName&&(n=e.state[r].essentialVarName),t[r]=e.essentialState[n]}r.essentialValues=t}}return r}async recordActualChangeInStateVariable({componentName:e,varName:t}){let n=this._components[e];await this.markStateVariableAndUpstreamDependentsStale({component:n,varName:t});let r=[t];n.state[t].additionalStateVariablesDefined&&r.push(...n.state[t].additionalStateVariablesDefined);for(let e of r)n.state[e].forceRecalculation=!0,this.dependencies.recordActualChangeInUpstreamDependencies({component:n,varName:e})}findCaseInsensitiveMatches({stateVariables:e,componentClass:t}){let n=this.componentInfoObjects.stateVariableInfo[t.componentType],r=[];for(let t of e){let e=!1,a=t.toLowerCase();for(let t in n.stateVariableDescriptions)if(a===t.toLowerCase()){e=!0,r.push(t);break}if(e)continue;let i=!1,s=a;"__array_size_"===a.substring(0,13)&&(i=!0,s=a.substring(13));for(let t in n.aliases)if(s===t.toLowerCase()){i&&(t="__array_size_"+t),r.push(t),e=!0;break}if(e)continue;let o=Object.keys(n.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let i of o)if(a.substring(0,i.length)===i.toLowerCase()){let s=n.arrayEntryPrefixes[i].arrayVariableName,o=n.stateVariableDescriptions[s];if(o.getArrayKeysFromVarName({arrayEntryPrefix:i,varEnding:t.substring(i.length),nDimensions:o.nDimensions}).length>0){let t=i+a.substring(i.length);e=!0,r.push(t);break}}e||r.push(t)}return r}matchPublicStateVariables({stateVariables:e,componentClass:t}){let n=this.componentInfoObjects.publicStateVariableInfo[t.componentType],r=[];for(let t of e){if(t in n.stateVariableDescriptions){r.push(t);continue}let e=t;if(e in n.aliases&&(e=n.aliases[e],e in n.stateVariableDescriptions)){r.push(e);continue}let a=!1,i=Object.keys(n.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let t of i)if(e.substring(0,t.length)===t){let r=n.arrayEntryPrefixes[t].arrayVariableName,i=n.stateVariableDescriptions[r];if(i.getArrayKeysFromVarName({arrayEntryPrefix:t,varEnding:e.substring(t.length),nDimensions:i.nDimensions}).length>0){a=!0;break}}a?r.push(t):r.push("__not_public_"+t)}return r}substituteAliases({stateVariables:e,componentClass:t}){let n=[],r=this.componentInfoObjects.stateVariableInfo[t.componentType];for(let t of e){let e=!1;"__array_size_"===t.substring(0,13)&&(e=!0,t=t.substring(13)),t=t in r.aliases?r.aliases[t]:t,e&&(t="__array_size_"+t),n.push(t)}return n}publicCaseInsensitiveAliasSubstitutions({stateVariables:e,componentClass:t}){let n=this.findCaseInsensitiveMatches({stateVariables:e,componentClass:t});return n=this.matchPublicStateVariables({stateVariables:n,componentClass:t}),n=this.substituteAliases({stateVariables:n,componentClass:t}),n}checkIfArrayEntry({stateVariable:e,component:t}){for(let n in t.arrayEntryPrefixes)if(e.substring(0,n.length)===n){let r=t.arrayEntryPrefixes[n],a=t.state[r];if(a.getArrayKeysFromVarName({arrayEntryPrefix:n,varEnding:e.substring(n.length),nDimensions:a.nDimensions}).length>0)return!0}return!1}async createFromArrayEntry({stateVariable:e,component:t,initializeOnly:n=!1}){if(!t.arrayEntryPrefixes)throw Error(`Unknown state variable ${e} of ${t.componentName}`);let r=Object.keys(t.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let a of r)if(e.substring(0,a.length)===a){let r=t.arrayEntryPrefixes[a],i=t.state[r];if(i.getArrayKeysFromVarName({arrayEntryPrefix:a,varEnding:e.substring(a.length),nDimensions:i.nDimensions}).length>0){let r=t.arrayEntryPrefixes[a];if(await this.initializeStateVariable({component:t,stateVariable:e,arrayStateVariable:r,arrayEntryPrefix:a}),n)return;let i=[e];if(t.state[e].additionalStateVariablesDefined){i.push(...t.state[e].additionalStateVariablesDefined);for(let n of t.state[e].additionalStateVariablesDefined)t.state[n]||await this.createFromArrayEntry({stateVariable:n,component:t,initializeOnly:!0})}await this.dependencies.setUpStateVariableDependencies({component:t,stateVariable:e,allStateVariablesAffected:i,core:this});let s=[];for(let e of i)this.dependencies.checkForCircularDependency({componentName:t.componentName,varName:e}),s.push(e),t.state[e].determineDependenciesStateVariable&&s.push(t.state[e].determineDependenciesStateVariable);return void await this.dependencies.resolveStateVariablesIfReady({component:t,stateVariables:s})}}throw Error(`Unknown state variable ${e} of ${t.componentName}`)}async markStateVariableAndUpstreamDependentsStale({component:e,varName:t}){t in this.rendererVariablesByComponentType[e.componentType]&&this.updateInfo.componentsToUpdateRenderers.add(e.componentName);let n={[t]:e.state[t]};e.state[t].additionalStateVariablesDefined&&e.state[t].additionalStateVariablesDefined.forEach((t=>n[t]=e.state[t]));let r=await this.lookUpCurrentFreshness({component:e,varName:t,allStateVariablesAffectedObj:n}),a=[],i=[],s=0;for(let e in n){let t=n[e];Object.getOwnPropertyDescriptor(t,"value").get||t.immutable?r&&(r.fresh&&r.fresh[e]?i.push(e):r.partiallyFresh&&r.partiallyFresh[e]&&(s+=r.partiallyFresh[e])):a.push(e)}i.push(...a);let o=i.length>0||s>0,l={};for(let e in n)l[e]=!0;let u=!1;if(o){let r=await this.processMarkStale({component:e,varName:t,allStateVariablesAffectedObj:n});if(r.fresh)for(let e in r.fresh)r.fresh[e]&&delete l[e];let a=0;for(let e in n){if(i.includes(e)&&(!r.fresh||!r.fresh[e])){u=!0;break}r.partiallyFresh&&r.partiallyFresh[e]&&(a+=r.partiallyFresh[e])}if(an({component:e,stateVariable:t}),configurable:!0})}}if(u)for(let t in l)await this.markUpstreamDependentsStale({component:e,varName:t})}async lookUpCurrentFreshness({component:e,varName:t,allStateVariablesAffectedObj:n}){let r=e.state[t];if(!r.getCurrentFreshness)return;let a,i,s=r.freshnessInfo;if(r.isArrayEntry&&(a=r._arrayKeys),r.isArrayEntry||r.isArray){let t=e.state[r.arraySizeStateVariable];i=t._previousValue,!(Object.getOwnPropertyDescriptor(t,"value").get||t.immutable)&&(i=await t.value),Array.isArray(i)||(i=[])}let o=r.getCurrentFreshness({freshnessInfo:s,arrayKeys:a,arraySize:i});if(o.partiallyFresh)for(let e in n)if(n[e].isArrayEntry){let t=n[e].arrayStateVariable;o.partiallyFresh[e]=o.partiallyFresh[t],delete o.partiallyFresh[t]}if(o.fresh)for(let e in n)if(n[e].isArrayEntry){let t=n[e].arrayStateVariable;t in o.fresh&&(o.fresh[e]=o.fresh[t],delete o.fresh[t])}return o}async processMarkStale({component:e,varName:t,allStateVariablesAffectedObj:n}){let r=e.state[t];if(!r.markStale||!r.initiallyResolved){let e={};return Object.keys(n).forEach((t=>e[t]=!1)),{fresh:e}}let a={},i=this.dependencies.downstreamDependencies[e.componentName][t];for(let e in i){let t=i[e],n={},r=!1;t.componentIdentityChanged&&(n.componentIdentityChanged=!0,r=!0),t.componentIdentitiesChanged&&(n.componentIdentitiesChanged=!0,r=!0),t.valuesChanged&&(n.valuesChanged=t.valuesChanged,r=!0),r&&(a[e]=n)}let s,o,l=r.freshnessInfo;if(r.isArrayEntry&&(s=r._arrayKeys),r.isArrayEntry||r.isArray){let t=e.state[r.arraySizeStateVariable];o=t._previousValue,!(Object.getOwnPropertyDescriptor(t,"value").get||t.immutable)&&(o=await t.value),Array.isArray(o)||(o=[])}let u=r.markStale({freshnessInfo:l,changes:a,arrayKeys:s,arraySize:o});if(u.partiallyFresh)for(let e in n)if(n[e].isArrayEntry){let t=n[e].arrayStateVariable;u.partiallyFresh[e]=u.partiallyFresh[t],delete u.partiallyFresh[t]}if(u.fresh)for(let e in n)if(n[e].isArrayEntry){let t=n[e].arrayStateVariable;t in u.fresh&&(u.fresh[e]=u.fresh[t],delete u.fresh[t])}return u}async markUpstreamDependentsStale({component:e,varName:t}){let n,r=e.componentName,a=this.getStateVariableValue,i=this.dependencies.upstreamDependencies[r][t];if(e.state[t]&&(n=e.state[t].freshnessInfo),i)for(let s of i){let i=!1;if(s.markStale&&await s.markStale(),s.downstreamComponentNames){let e=s.downstreamComponentNames.indexOf(r);if(-1===e)continue;if(s.mappedDownstreamVariableNamesByComponent){if(-1===s.mappedDownstreamVariableNamesByComponent[e].indexOf(t))throw Error(`something went wrong as ${t} not a downstreamVariable of ${s.dependencyName}`);"determineDependencies"===s.dependencyType&&(s.recalculateDependencies=!0),s.valuesChanged||(s.valuesChanged=[]),s.valuesChanged[e]||(s.valuesChanged[e]={}),s.valuesChanged[e][t]||(s.valuesChanged[e][t]={}),s.valuesChanged[e][t].potentialChange=!0,n&&(s.valuesChanged[e][t].freshnessInfo=n),i=!0}else t===s.downstreamVariableNameIfNoVariables&&(s.valuesChanged||(s.valuesChanged={[s.downstreamVariableNameIfNoVariables]:{}}),s.componentIdentityChanged=!0,s.valuesChanged[s.downstreamVariableNameIfNoVariables].potentialChange=!0,i=!0)}if(i){for(let e of s.upstreamVariableNames)if(e in this.rendererVariablesByComponentType[this.components[s.upstreamComponentName].componentType]){this.updateInfo.componentsToUpdateRenderers.add(s.upstreamComponentName);break}let t=s.upstreamVariableNames[0],n=this._components[s.upstreamComponentName],r={};s.upstreamVariableNames.forEach((e=>r[e]=n.state[e]));let i=await this.lookUpCurrentFreshness({component:n,varName:t,allStateVariablesAffectedObj:r}),o=[],l=[],u=0;for(let e in r){let t=r[e];Object.getOwnPropertyDescriptor(t,"value").get||t.immutable?i&&(i.fresh&&i.fresh[e]?l.push(e):i.partiallyFresh&&i.partiallyFresh[e]&&(u+=i.partiallyFresh[e])):o.push(e)}l.push(...o);let c=l.length>0||u>0,p={};for(let e in r)p[e]=!0;let d=!1;if(c){let a=await this.processMarkStale({component:n,varName:t,allStateVariablesAffectedObj:r});if(a.fresh)for(let e in a.fresh)a.fresh[e]&&delete p[e];let i=0;for(let e in r){if(l.includes(e)&&(!a.fresh||!a.fresh[e])){d=!0;break}a.partiallyFresh&&a.partiallyFresh[e]&&(i+=a.partiallyFresh[e])}if(ia({component:n,stateVariable:e}),configurable:!0}))}if(d)for(let e in p)await this.markUpstreamDependentsStale({component:n,varName:e})}}}registerComponent(e){if(e.componentName in this._components)throw Error(`Duplicate componentName: ${e.componentName}`);this._components[e.componentName]=e}deregisterComponent(e,t=!0){if(!0===t)for(let t in e.allChildren)this.deregisterComponent(e.allChildren[t].component);delete this._components[e.componentName]}setAncestors(e,t=[]){e.ancestors=t;let n=[{componentName:e.componentName,componentClass:e.constructor},...e.ancestors];for(let t in e.allChildren){let e=this._components[t];this.setAncestors(e,n)}for(let t in e.attributes){let r=e.attributes[t].component;r&&this.setAncestors(r,n)}}async addChildrenAndRecurseToShadows({parent:e,indexOfDefiningChildren:t,newChildren:n,assignNamesOffset:r}){this.spliceChildren(e,t,n);let a=await this.processNewDefiningChildren({parent:e}),i={};if(!a.success)return a;for(let e of n)"object"==typeof e&&(i[e.componentName]=e);if(e.shadowedBy)for(let a of e.shadowedBy){if(a.shadows.propVariable)continue;let e=this._components[a.shadows.compositeName],s=await e.stateValues.sourceAttributesToIgnore,o=await e.stateValues.sourceAttributesToIgnoreRecursively,l=[];for(let e of n)"object"==typeof e?l.push(await e.serialize({sourceAttributesToIgnore:s,sourceAttributesToIgnoreRecursively:o})):l.push(e);l=postProcessCopy({serializedComponents:l,componentName:a.shadows.compositeName});let u=a.attributes.newNamespace?.primitive,c=u;l=processAssignNames({indOffset:r,serializedComponents:l,parentName:a.componentName,parentCreatesNewNamespace:u,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:c}).serializedComponents;let p,d=this._components[a.componentName];this.parameterStack.push(d.sharedParameters,!1),p=u?a.componentName+"/":getNamespaceFromName(a.componentName);let m=await this.createIsolatedComponentsSub({serializedComponents:l,ancestors:a.ancestors,createNameContext:a.componentName+"|addChildren|"+r,namespaceForUnamed:p});this.parameterStack.pop();let h=await this.addChildrenAndRecurseToShadows({parent:d,indexOfDefiningChildren:t,newChildren:m.components,assignNamesOffset:r});if(!h.success)throw Error("was able to add components to parent but not shadows!");Object.assign(i,h.addedComponents)}return{success:!0,deletedComponents:{},addedComponents:i}}async processNewDefiningChildren({parent:e,expandComposites:t=!0}){this.parameterStack.push(e.sharedParameters,!1);let n=await this.deriveChildResultsFromDefiningChildren({parent:e,expandComposites:t});this.parameterStack.pop();let r=[{componentName:e.componentName,componentClass:e.constructor},...e.ancestors];for(let t in e.allChildren){let e=this._components[t];this.setAncestors(e,r)}return n}spliceChildren(e,t,n){let r=e.definingChildren.length;if(!Number.isInteger(t)||t>r||t<0)throw Error("Can't add children at index "+t+". Invalid index.");e.definingChildren.splice(t,0,...n)}async deleteComponents({components:e,deleteUpstreamDependencies:t=!0,skipProcessingChildrenOfParents:n=[]}){Array.isArray(e)||(e=[e]);const r={};this.determineComponentsToDelete({components:e,deleteUpstreamDependencies:t,componentsToDelete:r});const a={};for(let e in r){let t=r[e],n=this.components[t.parentName];if(void 0===n||n.componentName in r)continue;let i=a[t.parentName];void 0===i&&(i={parent:this._components[t.parentName],childNamesToBeDeleted:new Set},a[t.parentName]=i),i.childNamesToBeDeleted.add(e)}let i=[];for(let e in r){let t=this._components[e];if(t.replacementOf){let n=t.replacementOf,r=n.replacements.map((e=>e.componentName)),a=r.indexOf(e);-1!==a&&(n.replacements.splice(a,1),i.includes(n.componentName)||i.push(n.componentName))}}for(let e of i)e in r||await this.dependencies.addBlockersFromChangedReplacements(this._components[e]);let s=[];for(let e in a){let t=a[e],r=t.parent;s.push(r);for(let e=r.definingChildren.length-1;e>=0;e--){let n=r.definingChildren[e];t.childNamesToBeDeleted.has(n.componentName)&&r.definingChildren.splice(e,1)}n.includes(r.componentName)||await this.processNewDefiningChildren({parent:r,expandComposites:!1})}for(let e in r){let t=this._components[e];if(t.shadows){let e=this._components[t.shadows.componentName];1===e.shadowedBy.length?delete e.shadowedBy:e.shadowedBy.splice(e.shadowedBy.indexOf(t),1)}this.dependencies.deleteAllDownstreamDependencies({component:t});for(let e in this.dependencies.upstreamDependencies[t.componentName]){let n=this.dependencies.upstreamDependencies[t.componentName][e];for(let e of n)if(e.specifiedComponentName&&e.specifiedComponentName in r){let t=this.dependencies.updateTriggers.dependenciesMissingComponentBySpecifiedName[e.specifiedComponentName];t||(t=this.dependencies.updateTriggers.dependenciesMissingComponentBySpecifiedName[e.specifiedComponentName]=[]),t.includes(e)||t.push(e)}}await this.dependencies.deleteAllUpstreamDependencies({component:t}),this.updateInfo.deletedStateVariables[t.componentName]||(this.updateInfo.deletedStateVariables[t.componentName]=[]),this.updateInfo.deletedStateVariables[t.componentName].push(...Object.keys(t.state)),this.updateInfo.deletedComponents[t.componentName]=!0,delete this.unmatchedChildren[t.componentName],delete this.stateVariableChangeTriggers[t.componentName]}for(let e in r){let t=this._components[e];this.deregisterComponent(t,!1),this.updateInfo.componentsToUpdateRenderers.delete(e),this.updateInfo.compositesToUpdateReplacements.delete(e),this.updateInfo.inactiveCompositesToUpdateReplacements.delete(e)}return{success:!0,deletedComponents:r,parentsOfDeleted:s}}determineComponentsToDelete({components:e,deleteUpstreamDependencies:t,componentsToDelete:n}){for(let r of e){if("object"!=typeof r)continue;if(r.componentName in n)continue;n[r.componentName]=this._components[r.componentName];let e=Object.values(r.allChildren).map((e=>e.component));for(let t in r.attributes){let n=r.attributes[t].component;n&&e.push(n)}void 0!==r.adaptedFrom&&e.push(r.adaptedFrom),!0===t&&(r.shadowedBy&&e.push(...r.shadowedBy),r.adapterUsed&&e.push(r.adapterUsed),r.replacements&&e.push(...r.replacements)),this.determineComponentsToDelete({components:e,deleteUpstreamDependencies:t,componentsToDelete:n})}}async updateCompositeReplacements({component:e,componentChanges:t,sourceOfUpdate:n}){let r={},a={},i=new Set;if(e.shadows){return{success:!0,deletedComponents:r,addedComponents:a,parentsOfDeleted:i}}let s=this.components[e.componentName];e.replacements||(e.replacements=[]),await e.stateValues.readyToExpandWhenResolved;const o=await e.constructor.calculateReplacementChanges({component:s,componentChanges:t,components:this.components,workspace:e.replacementsWorkspace,componentInfoObjects:this.componentInfoObjects,flags:this.flags,resolveItem:this.dependencies.resolveItem.bind(this.dependencies),publicCaseInsensitiveAliasSubstitutions:this.publicCaseInsensitiveAliasSubstitutions.bind(this)});e.constructor.stateVariableToEvaluateAfterReplacements&&await e.stateValues[e.constructor.stateVariableToEvaluateAfterReplacements];for(let s of o)if("add"===s.changeType){void 0!==s.replacementsToWithhold&&await this.adjustReplacementsToWithhold({component:e,change:s,componentChanges:t});let o,l=this._components[e.componentName];this.parameterStack.push(l.sharedParameters,!1);let u={[e.componentName]:calculateAllComponentsShadowing(e)},c=s.numberReplacementsToReplace,p=s.firstReplacementInd;if(c>0&&s.changeTopLevelReplacements&&await this.deleteReplacementsFromShadowsThenComposite({change:s,composite:e,componentChanges:t,sourceOfUpdate:n,parentsOfDeleted:i,deletedComponents:r,addedComponents:a,processNewChildren:!1}),!s.serializedReplacements)throw Error("Invalid replacement change.");{let t,n=s.serializedReplacements;t=e.attributes.newNamespace?.primitive?e.componentName+"/":getNamespaceFromName(e.componentName),o=(await this.createIsolatedComponentsSub({serializedComponents:n,ancestors:e.ancestors,createNameContext:e.componentName+"|replacements",namespaceForUnamed:t,componentsReplacementOf:e})).components}this.parameterStack.pop();let d={[e.componentName]:{newComponents:o,parent:s.parent}};if(l.shadowedBy&&u[l.componentName].length>0){let e=await this.createShadowedReplacements({replacementsToShadow:o,componentToShadow:l,parentToShadow:s.parent,currentShadowedBy:u,assignNamesOffset:s.assignNamesOffset,componentChanges:t,sourceOfUpdate:n,parentsOfDeleted:i,deletedComponents:r,addedComponents:a});Object.assign(d,e)}for(let e in d){let n=this._components[e];if(!n)continue;let r=d[e].newComponents;if(n.isExpanded){for(let e of r)"object"==typeof e&&(a[e.componentName]=e);if(!0===s.changeTopLevelReplacements){let e=this._components[n.parentName];n.replacements.splice(p,0,...r),await this.dependencies.addBlockersFromChangedReplacements(n);let a={changeType:"addedReplacements",composite:n,newReplacements:r,topLevel:!0,firstIndex:p,numberDeleted:c};t.push(a),await this.processNewDefiningChildren({parent:e,expandComposites:!1}),(await this.componentAndRenderedDescendants(e)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e)))}else{let i=this._components[d[e].parent.componentName];this.spliceChildren(i,s.indexOfDefiningChildren,r),await this.processNewDefiningChildren({parent:i});for(let e of r)"object"==typeof e&&(a[e.componentName]=e);(await this.componentAndRenderedDescendants(i)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e)));let o={changeType:"addedReplacements",composite:n,newReplacements:r};t.push(o)}}else{await this.expandCompositeComponent(n);let e={changeType:"addedReplacements",composite:n,newReplacements:n.replacements,topLevel:!0,firstIndex:0,numberDeleted:0};t.push(e)}}}else if("delete"===s.changeType)void 0!==s.replacementsToWithhold&&await this.adjustReplacementsToWithhold({component:e,change:s,componentChanges:t}),await this.deleteReplacementsFromShadowsThenComposite({change:s,composite:e,componentsToDelete:s.components,componentChanges:t,sourceOfUpdate:n,parentsOfDeleted:i,deletedComponents:r,addedComponents:a});else if("updateStateVariables"===s.changeType){let e={},t={};for(let n in s.stateChanges){let r={componentName:s.component.componentName,stateVariable:n,value:s.stateChanges[n],overrideFixed:!0};await this.requestComponentChanges({instruction:r,initialChange:!1,workspace:e,newStateVariableValues:t})}await this.processNewStateVariableValues(t)}else"changeReplacementsToWithhold"===s.changeType&&(void 0!==s.replacementsToWithhold&&await this.adjustReplacementsToWithhold({component:e,change:s,componentChanges:t}),await this.processChildChangesAndRecurseToShadows(e));return{success:!0,deletedComponents:r,addedComponents:a,parentsOfDeleted:i}}async deleteReplacementsFromShadowsThenComposite({change:e,composite:t,componentsToDelete:n,componentChanges:r,sourceOfUpdate:a,parentsOfDeleted:i,deletedComponents:s,addedComponents:o,processNewChildren:l=!0}){let u=[];if(!t.isExpanded)return u;if(t.shadowedBy)for(let c of t.shadowedBy){if(c.shadows.propVariable)continue;let t;if(n){t=[];for(let e of n){let n;if(e.shadowedBy)for(let t of e.shadowedBy)if(!t.shadows.propVariable&&t.shadows.compositeName===c.shadows.compositeName){n=t;break}n?t.push(n):console.error(`could not find shadowing component of ${e.componentName}`)}}let p=await this.deleteReplacementsFromShadowsThenComposite({change:e,composite:c,componentsToDelete:t,componentChanges:r,sourceOfUpdate:a,parentsOfDeleted:i,deletedComponents:s,addedComponents:o,processNewChildren:l});u.push(...p)}if(e.changeTopLevelReplacements){let n=e.firstReplacementInd,o=e.numberReplacementsToDelete;"add"===e.changeType&&(o=e.numberReplacementsToReplace);let u=t.replacements.splice(n,o);await this.dependencies.addBlockersFromChangedReplacements(t);let c=await this.deleteComponents({components:u,componentChanges:r,sourceOfUpdate:a,skipProcessingChildrenOfParents:[t.parentName]});if(l&&await this.processNewDefiningChildren({parent:this._components[t.parentName],expandComposites:!1}),!1===c.success)throw Error("Couldn't delete components on composite update");for(let e of c.parentsOfDeleted){i.add(e.componentName),(await this.componentAndRenderedDescendants(e)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e)))}let p={};for(let e in c.deletedComponents){let t=c.deletedComponents[e].parentName;void 0===p[t]&&(p[t]=[]),p[t].push(e)}let d={changeType:"deletedReplacements",composite:t,topLevel:!0,firstIndex:n,numberDeleted:o,deletedNamesByParent:p,deletedComponents:c.deletedComponents};r.push(d),Object.assign(s,c.deletedComponents);let m=this._components[t.parentName];(await this.componentAndRenderedDescendants(m)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e)))}else{let e=n.length,l=await this.deleteComponents({components:n,deleteUpstreamDependencies:!1,componentChanges:r,sourceOfUpdate:a});if(!1===l.success)throw Error("Couldn't delete components prescribed by composite");for(let e of l.parentsOfDeleted){i.add(e.componentName),(await this.componentAndRenderedDescendants(e)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e)))}let u={};for(let e in l.deletedComponents){let t=l.deletedComponents[e].parentName;void 0===u[t]&&(u[t]=[]),u[t].push(e)}let c={changeType:"deletedReplacements",composite:t,numberDeleted:e,deletedNamesByParent:u,deletedComponents:l.deletedComponents};r.push(c),Object.assign(s,l.deletedComponents),Object.assign(o,l.addedComponents)}return u}async processChildChangesAndRecurseToShadows(e){let t=this._components[e.parentName];if(await this.processNewDefiningChildren({parent:t,expandComposites:!1}),(await this.componentAndRenderedDescendants(t)).forEach((e=>this.updateInfo.componentsToUpdateRenderers.add(e))),e.shadowedBy)for(let t of e.shadowedBy)t.shadows.propVariable||await this.processChildChangesAndRecurseToShadows(t)}async createShadowedReplacements({replacementsToShadow:e,componentToShadow:t,parentToShadow:n,currentShadowedBy:r,assignNamesOffset:a,componentChanges:i,sourceOfUpdate:s,parentsOfDeleted:o,deletedComponents:l,addedComponents:u}){let c=calculateAllComponentsShadowing(t);if(!r[t.componentName]||!c.every((e=>r[t.componentName].includes(e))))throw Error(`circular reference involving ${t.componentName}`);this.updateInfo.compositesBeingExpanded.push(t.componentName);let p={};for(let c of t.shadowedBy)if(!c.shadows.propVariable){if(this.updateInfo.compositesBeingExpanded.includes(c.componentName))throw Error(`circular dependence involving ${c.componentName}`);if(c.shadowedBy&&(r[c.componentName]=calculateAllComponentsShadowing(c)),c.isExpanded){let t=[],d=this._components[c.shadows.compositeName],m=await d.stateValues.sourceAttributesToIgnore,h=await d.stateValues.sourceAttributesToIgnoreRecursively;for(let n of e)"object"==typeof n?t.push(await n.serialize({sourceAttributesToIgnore:m,sourceAttributesToIgnoreRecursively:h})):t.push(n);t=postProcessCopy({serializedComponents:t,componentName:c.shadows.compositeName});let f,y=c.attributes.newNamespace?.primitive;if(c.attributes.isResponse){let e=c.constructor.createAttributesObject();for(let n of t){if("object"!=typeof n)continue;n.attributes||(n.attributes={});let t=convertAttributesForComponentType({attributes:{isResponse:c.attributes.isResponse},componentType:n.componentType,componentInfoObjects:this.componentInfoObjects,compositeAttributesObj:e,compositeCreatesNewNamespace:y});Object.assign(n.attributes,t)}}if(c.constructor.assignNamesToReplacements){let e=c.shadows.compositeName,n=this.components[e],r=n.attributes.newNamespace?.primitive,i=n.doenetAttributes.assignNames,s=y||r&&!i,o=c.doenetAttributes.assignNames;o&&await c.stateValues.addLevelToAssignNames&&(o=o.map((e=>[e]))),t=processAssignNames({assignNames:o,indOffset:a,serializedComponents:t,parentName:c.componentName,parentCreatesNewNamespace:y,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:s}).serializedComponents}else{let e=y;t=processAssignNames({indOffset:a,serializedComponents:t,parentName:c.componentName,parentCreatesNewNamespace:y,componentInfoObjects:this.componentInfoObjects,originalNamesAreConsistent:e}).serializedComponents}let g,b=this._components[c.componentName];this.parameterStack.push(b.sharedParameters,!1),g=y?c.componentName+"/":getNamespaceFromName(c.componentName);let v,N=await this.createIsolatedComponentsSub({serializedComponents:t,ancestors:c.ancestors,createNameContext:c.componentName+"|replacements",namespaceForUnamed:g,componentsReplacementOf:c});if(this.parameterStack.pop(),f=N.components,n){if(n.shadowedBy)for(let e of n.shadowedBy)if(!e.shadows.propVariable&&e.shadows.compositeName===c.shadows.compositeName){v=e;break}v||console.error(`could not find shadowing parent of ${n.componentName}`)}if(p[c.componentName]={newComponents:f,parent:v},c.shadowedBy&&r[c.componentName].length>0){let e=await this.createShadowedReplacements({replacementsToShadow:f,componentToShadow:c,parentToShadow:v,currentShadowedBy:r,assignNamesOffset:a,componentChanges:i,sourceOfUpdate:s,parentsOfDeleted:o,deletedComponents:l,addedComponents:u});Object.assign(p,e)}}}let d=this.updateInfo.compositesBeingExpanded.indexOf(t.componentName);if(-1===d)throw Error(`Something is wrong as we lost track that we were expanding ${component.componentName}`);return this.updateInfo.compositesBeingExpanded.splice(d,1),p}async adjustReplacementsToWithhold({component:e,change:t,componentChanges:n}){let r,a=[],i=t.replacementsToWithhold;if(r=void 0!==e.replacementsToWithhold?i-e.replacementsToWithhold:i,r<0){a.push(e.componentName);let t=e.replacements.length-i,s=e.replacements.length-i+r,o=e.replacements.slice(s,t),l={changeType:"addedReplacements",composite:e,topLevel:!0,newReplacements:o,firstIndex:s,numberDeleted:0};n.push(l)}else if(r>0){a.push(e.componentName);let t=e.replacements.length-i,s=t+r,o=e.replacements.slice(t,s),l={};for(let e of o){let t=e.parentName;void 0===l[t]&&(l[t]=[]),l[t].push(e.componentName)}let u={changeType:"deletedReplacements",composite:e,topLevel:!0,firstIndex:t,numberDeleted:r,deletedNamesByParent:l,deletedComponents:o};n.push(u)}if(e.replacementsToWithhold=i,await this.dependencies.addBlockersFromChangedReplacements(e),e.shadowedBy)for(let r of e.shadowedBy){if(r.shadows.propVariable)continue;let e=await this.adjustReplacementsToWithhold({component:r,change:t,componentChanges:n});a.push(...e)}return a}get rendererTypesInDocument(){return this.document.allPotentialRendererTypes}get components(){return this._components}set components(e){return null}async executeProcesses(){if(!this.stopProcessingRequests){for(;this.processQueue.length>0;){let e,t=this.processQueue.splice(0,1)[0];if("update"===t.type)(!t.skippable||this.processQueue.length<2)&&(e=await this.performUpdate(t));else if("action"===t.type)(!t.skippable||this.processQueue.length<2)&&(e=await this.performAction(t));else{if("recordEvent"!==t.type)throw Error(`Unrecognized process type: ${t.type}`);e=await this.performRecordEvent(t)}t.resolve(e)}this.processing=!1}}requestAction({componentName:e,actionName:t,args:n,event:r}){return new Promise(((a,i)=>{let s=n?.skippable;this.processQueue.push({type:"action",componentName:e,actionName:t,args:n,skippable:s,event:r,resolve:a,reject:i}),this.processing||(this.processing=!0,this.executeProcesses())}))}async performAction({componentName:e,actionName:t,args:n,event:r,caseInsensitiveMatch:a}){let i=this.components[e];if(i&&i.actions){let e=i.actions[t];if(!e&&a){let n=t.toLowerCase();for(let r in i.actions)if(r.toLowerCase()===n){e=i.actions[r],t=r;break}}if(e)return r&&this.requestRecordEvent(r),n||(n={}),await e(n)}if(!i&&"recordVisibilityChange"===t&&!1===n?.isVisible)return this.requestRecordEvent({verb:"visibilityChanged",object:{componentName:e},result:{isVisible:!1}}),this.resolveAction({actionId:n.actionId});i&&console.warn(`Cannot run action ${t} on component ${e}`)}resolveAction({actionId:e}){e&&postMessage({messageType:"resolveAction",coreId:this.coreId,args:{actionId:e}})}async triggerChainedActions({componentName:e,triggeringAction:t}){for(let e in this.updateInfo.componentsToUpdateActionChaining)await this.checkForActionChaining({component:this.components[e],stateVariables:this.updateInfo.componentsToUpdateActionChaining[e]});this.updateInfo.componentsToUpdateActionChaining={};let n=e;if(t&&(n+="|"+t),this.actionsChangedToActions[n])for(let e of this.actionsChangedToActions[n])await this.performAction(e)}async requestUpdate({updateInstructions:e,transient:t=!1,event:n,skippable:r=!1,overrideReadOnly:a=!1}){if(!this.flags.readOnly||a)return new Promise(((a,i)=>{this.processQueue.push({type:"update",updateInstructions:e,transient:t,event:n,skippable:r,resolve:a,reject:i}),this.processing||(this.processing=!0,this.executeProcesses())}));{let t={};for(let n of e){let e=t[n.componentName];e||(e=t[n.componentName]={}),n.sourceInformation&&Object.assign(e,n.sourceInformation)}await this.updateRendererInstructions({componentNamesToUpdate:e.map((e=>e.componentName)),sourceOfUpdate:{sourceInformation:t}})}}async performUpdate({updateInstructions:e,actionId:t,event:n,overrideReadOnly:r=!1,doNotSave:a=!1,canSkipUpdatingRenderer:i=!1,suppressToast:s=!1}){if(this.flags.readOnly&&!r){if(!i){let n={};for(let t of e){let e=n[t.componentName];e||(e=n[t.componentName]={}),t.sourceInformation&&Object.assign(e,t.sourceInformation)}await this.updateRendererInstructions({componentNamesToUpdate:e.map((e=>e.componentName)),sourceOfUpdate:{sourceInformation:n},actionId:t})}return}let o={},l=[],u={},c={},p=[];for(let t of e){if(t.componentName){let e=u[t.componentName];e||(e=u[t.componentName]={}),t.sourceInformation&&Object.assign(e,t.sourceInformation)}if("updateValue"===t.updateType)await this.requestComponentChanges({instruction:t,workspace:c,newStateVariableValues:o});else if("addComponents"===t.updateType)await this.addComponents({serializedComponents:t.serializedComponents,parentName:t.parentName,assignNamesOffset:t.assignNamesOffset});else if("deleteComponents"===t.updateType){if(t.componentNames.length>0){let e=[];for(let n of t.componentNames){let t=this._components[n];t?e.push(t):console.warn(`Cannot delete ${n} as it doesn't exist.`)}e.length>0&&await this.deleteComponents({components:e})}}else"executeUpdate"===t.updateType?(await this.executeUpdateStateVariables(o),l.push(o),o={}):"recordItemSubmission"===t.updateType?p.push(t):"setComponentNeedingUpdateValue"===t.updateType?this.rendererState.__componentNeedingUpdateValue=t.componentName:"unsetComponentNeedingUpdateValue"===t.updateType&&(this.rendererState.__componentNeedingUpdateValue=null)}await this.executeUpdateStateVariables(o),l.push(o),i||e.forEach((e=>{e.componentName&&this.updateInfo.componentsToUpdateRenderers.add(e.componentName)}));let d=[...this.updateInfo.componentsToUpdateRenderers];if(this.updateInfo.componentsToUpdateRenderers.clear(),await this.updateRendererInstructions({componentNamesToUpdate:d,sourceOfUpdate:{sourceInformation:u,local:!0},actionId:t}),this.updateInfo.compositesToUpdateReplacements.size>0){await this.replacementChangesFromCompositesToUpdate();let e=[...this.updateInfo.componentsToUpdateRenderers];this.updateInfo.componentsToUpdateRenderers.clear(),await this.updateRendererInstructions({componentNamesToUpdate:e,sourceOfUpdate:{sourceInformation:u,local:!0},actionId:t})}if(await this.processStateVariableTriggers(),Object.keys(this.unmatchedChildren).length>0){let e="";for(let t in this.unmatchedChildren)this._components[t].isShadow||(e+=`Invalid children for ${t}: ${this.unmatchedChildren[t].message} `);e&&console.warn(e)}if(p.length>0){let e=[...new Set(p.map((e=>e.itemNumber)))],t=await this.document.stateValues.creditAchieved,r=await this.document.stateValues.itemCreditAchieved;if(n){if(n.context||(n.context={}),n.context.item=e[0],n.context.itemCreditAchieved=r[e[0]-1],e.length>1){n.context.additionalItemCreditAchieved={};for(let t of e)n.context.additionalItemCreditAchieved[t]=r[t-1]}n.context.pageCreditAchieved=await this.document.stateValues.creditAchieved}this.itemNumber>0&&this.saveSubmissions({pageCreditAchieved:t,suppressToast:s})}if(Object.keys(this.essentialValuesSavedInDefinition).length>0){for(let e in this.essentialValuesSavedInDefinition){let t=this._components[e]?.essentialState;if(t){this.cumulativeStateVariableChanges[e]||(this.cumulativeStateVariableChanges[e]={});for(let n in this.essentialValuesSavedInDefinition[e])if(void 0!==t[n]){let r=this.cumulativeStateVariableChanges[e][n];"object"==typeof r&&null!==r&&r.mergeObject?Object.assign(r,removeFunctionsMathExpressionClass(t[n])):this.cumulativeStateVariableChanges[e][n]=removeFunctionsMathExpressionClass(t[n])}}}this.essentialValuesSavedInDefinition={}}for(let e of l)for(let t in e){this.cumulativeStateVariableChanges[t]||(this.cumulativeStateVariableChanges[t]={});for(let n in e[t]){let r=this.cumulativeStateVariableChanges[t][n];"object"==typeof r&&null!==r&&r.mergeObject?Object.assign(r,removeFunctionsMathExpressionClass(e[t][n])):this.cumulativeStateVariableChanges[t][n]=removeFunctionsMathExpressionClass(e[t][n])}}a||(clearTimeout(this.savePageStateTimeoutID),this.savePageStateTimeoutID=setTimeout((()=>{this.saveState()}),1e3)),await this.document.stateValues.itemCreditAchieved,n&&this.requestRecordEvent(n)}requestRecordEvent(e){return this.resumeVisibilityMeasuring(),"visibilityChanged"===e.verb?this.processVisibilityChangedEvent(e):new Promise(((t,n)=>{this.processQueue.push({type:"recordEvent",event:e,resolve:t,reject:n}),this.processing||(this.processing=!0,this.executeProcesses())}))}async performRecordEvent({event:e}){if(!this.flags.allowSaveEvents)return;e.result||(e.result={}),e.context||(e.context={});const t={doenetId:this.doenetId,activityCid:this.activityCid,pageCid:this.cid,pageNumber:this.pageNumber,attemptNumber:this.attemptNumber,activityVariantIndex:this.activityVariantIndex,pageVariantIndex:this.requestedVariant.index,verb:e.verb,object:JSON.stringify(e.object,serializedComponentsReplacer),result:JSON.stringify(removeFunctionsMathExpressionClass(e.result),serializedComponentsReplacer),context:JSON.stringify(e.context,serializedComponentsReplacer),timestamp:(new Date).toISOString().slice(0,19).replace("T"," "),version:"0.1.1"};try{await axios.post("/api/recordEvent.php",t)}catch(e){console.error(`Error saving event: ${e.message}`)}}processVisibilityChangedEvent(e){let t=e.object.componentName;if(e.result.isVisible)this.visibilityInfo.componentsCurrentlyVisible[t]||(this.visibilityInfo.componentsCurrentlyVisible[t]=new Date),t===this.documentName&&(this.visibilityInfo.documentHasBeenVisible||(this.visibilityInfo.documentHasBeenVisible=!0,this.onDocumentFirstVisible()));else{let e=this.visibilityInfo.componentsCurrentlyVisible[t];if(e){delete this.visibilityInfo.componentsCurrentlyVisible[t];let n=(new Date-Math.max(e,this.visibilityInfo.timeLastSent))/1e3;this.visibilityInfo.infoToSend[t]?this.visibilityInfo.infoToSend[t]+=n:this.visibilityInfo.infoToSend[t]=n}}}sendVisibilityChangedEvents(){let e={...this.visibilityInfo.infoToSend};this.visibilityInfo.infoToSend={};let t=this.visibilityInfo.timeLastSent;this.visibilityInfo.timeLastSent=new Date;let n,r={...this.visibilityInfo.componentsCurrentlyVisible};for(let n in r){let a=(this.visibilityInfo.timeLastSent-Math.max(t,r[n]))/1e3;e[n]?e[n]+=a:e[n]=a}for(let t in e)e[t]=Math.round(e[t]),e[t]||delete e[t];if(Object.keys(e).length>0){let t={object:{componentName:this.documentName,componentType:"document"},verb:"isVisible",result:e};n=new Promise(((e,n)=>{this.processQueue.push({type:"recordEvent",event:t,resolve:e,reject:n}),this.processing||(this.processing=!0,this.executeProcesses())}))}return this.visibilityInfo.suspended||(clearTimeout(this.visibilityInfo.saveTimerId),this.visibilityInfo.saveTimerId=setTimeout(this.sendVisibilityChangedEvents.bind(this),this.visibilityInfo.saveDelay)),n}async suspendVisibilityMeasuring(){clearTimeout(this.visibilityInfo.saveTimerId),clearTimeout(this.visibilityInfo.suspendTimerId),this.visibilityInfo.suspended||(this.visibilityInfo.suspended=!0,await this.sendVisibilityChangedEvents())}resumeVisibilityMeasuring(){this.visibilityInfo.suspended&&(this.visibilityInfo.suspended=!1,this.visibilityInfo.timeLastSent=new Date,clearTimeout(this.visibilityInfo.saveTimerId),this.visibilityInfo.saveTimerId=setTimeout(this.sendVisibilityChangedEvents.bind(this),this.visibilityInfo.saveDelay)),clearTimeout(this.visibilityInfo.suspendTimerId),this.visibilityInfo.suspendTimerId=setTimeout(this.suspendVisibilityMeasuring.bind(this),this.visibilityInfo.suspendDelay)}async executeUpdateStateVariables(e){if(await this.processNewStateVariableValues(e),(await this.replacementChangesFromCompositesToUpdate()).updatedComposites&&(await this.expandAllComposites(this.document),await this.expandAllComposites(this.document,!0),this.updateInfo.stateVariablesToEvaluate)){let e=this.updateInfo.stateVariablesToEvaluate;this.updateInfo.stateVariablesToEvaluate=[];for(let{componentName:t,stateVariable:n}of e){let e=this._components[t];e&&e.state[n]&&await this.getStateVariableValue({component:e,stateVariable:n})}}await this.replacementChangesFromCompositesToUpdate()}async replacementChangesFromCompositesToUpdate(){let e=[...this.updateInfo.compositesToUpdateReplacements];this.updateInfo.compositesToUpdateReplacements.clear();let t=new Set([]),n=0,r=!1,a=[];for(;e.length>0;){for(let n of e){let e=this._components[n];if(e instanceof this.componentInfoObjects.allComponentClasses._composite&&e.isExpanded)if(e.state.readyToExpandWhenResolved.initiallyResolved)if(await e.stateValues.isInactiveCompositeReplacement)this.updateInfo.inactiveCompositesToUpdateReplacements.add(n);else{let t=await this.updateCompositeReplacements({component:e,componentChanges:a});Object.keys(t.addedComponents).length>0&&(r=!0),Object.keys(t.deletedComponents).length>0&&(r=!0)}else t.add(n)}if(e=[...this.updateInfo.compositesToUpdateReplacements],this.updateInfo.compositesToUpdateReplacements.clear(),n++,n>100)throw Error("Seem to have an infinite loop while calculating replacement changes")}return this.updateInfo.compositesToUpdateReplacements=t,{updatedComposites:r}}async processNewStateVariableValues(e){let t=0,n=!1;for(let r in e){let a=this._components[r];if(void 0===a){let t=this.updateInfo.stateVariableUpdatesForMissingComponents[r];void 0===t&&(t=this.updateInfo.stateVariableUpdatesForMissingComponents[r]={}),Object.assign(t,e[r]);continue}let i=e[r];for(let e in i){let s=a.state[e];if(void 0===s){let t=e.match(/^__def_primitive_(\d+)$/);if(t){let n=Number(t[1]);a.definingChildren[n]=i[e],await this.processNewDefiningChildren({parent:a,expandComposites:!1});continue}if(t=e.match(/^__def_primitive_ignore_(\d+)$/),t){let r=Number(t[1]);a.definingChildren[r]=i[e],n=!0;continue}console.warn(`can't update state variable ${e} of component ${r}, as it doesn't exist.`);continue}if(!s.hasEssential){console.warn(`can't update state variable ${e} of component ${r}, as it does not have an essential state variable.`);continue}let o=e;if(a.state[e].essentialVarName&&(o=a.state[e].essentialVarName),e in this.rendererVariablesByComponentType[a.componentType]&&this.updateInfo.componentsToUpdateRenderers.add(a.componentName),s.isArray){let n=a.essentialState[o];Array.isArray(n)||(n=a.essentialState[o]=[]);let l=[];a.state[s.arraySizeStateVariable].initiallyResolved||await a.state[s.arraySizeStateVariable].value;let u=await s.arraySize;for(let r in i[e]){if("mergeObject"===r)continue;let a=e=>e;s.set&&(a=s.set);let o=s.setArrayValue({value:a(i[e][r]),arrayKey:r,arraySize:u,arrayValues:n});s.usedDefaultByArrayKey[r]=!1,t+=o.nFailures;let c=s.varNamesIncludingArrayKeys[r];c&&l.push(...c)}for(let e of l)await this.recordActualChangeInStateVariable({componentName:r,varName:e})}else{if(!s.hasEssential){console.warn(`can't update state variable ${e} of component ${r}, as it does not have an essential state variable.`);continue}s.set?a.essentialState[o]=s.set(i[e]):a.essentialState[o]=i[e],delete s.usedDefault}await this.recordActualChangeInStateVariable({componentName:r,varName:e})}}return{nFailures:t,foundIgnore:n}}async requestComponentChanges({instruction:e,initialChange:t=!0,workspace:n,newStateVariableValues:r}){let a=this._components[e.componentName],i=this.substituteAliases({stateVariables:[e.stateVariable],componentClass:a.constructor})[0];void 0===n[e.componentName]&&(n[e.componentName]={});let s=n[e.componentName],o=a.state[i],l=o.additionalStateVariablesDefined,u=[i];l&&u.push(...l);for(let e of u)if(!a.state[e].isResolved){if(!(await this.dependencies.resolveItem({componentName:a.componentName,type:"stateVariable",stateVariable:e,force:!0})).success)throw Error(`Can't get value of ${i} of ${a.componentName} as ${e} couldn't be resolved.`)}let c=await this.getStateVariableDefinitionArguments({component:a,stateVariable:i,excludeDependencyValues:o.excludeDependencyValuesInInverseDefinition});c.componentInfoObjects=this.componentInfoObjects,c.initialChange=t,c.stateValues=a.stateValues,c.overrideFixed=e.overrideFixed,c.shadowedVariable=e.shadowedVariable,c.sourceInformation=e.sourceInformation;let p=i;if(o.isArrayEntry){let t=o.arrayStateVariable;p=t;let n={};if(1===c.arrayKeys.length){if("value"in e)n[c.arrayKeys[0]]=e.value;else if("valueOfStateVariable"in e){let t=this.substituteAliases({stateVariables:[e.valueOfStateVariable],componentClass:a.constructor})[0],r=a.state[t];if(!r)throw Error(`Invalid instruction to change ${e.stateVariable} of ${e.componentName}, value of state variable ${e.valueOfStateVariable} not found.`);n[c.arrayKeys[0]]=await r.value}}else for(let[t,r]of c.arrayKeys.entries())if(Array.isArray(e.value))n[r]=e.value[t];else if(e.value instanceof me$3.class)try{n[r]=e.value.get_component(t)}catch(e){}c.desiredStateVariableValues={[t]:n}}else if("value"in e)c.desiredStateVariableValues={[i]:e.value};else if("valueOfStateVariable"in e){let t=this.substituteAliases({stateVariables:[e.valueOfStateVariable],componentClass:a.constructor})[0],n=a.state[t];if(!n)throw Error(`Invalid instruction to change ${e.stateVariable} of ${e.componentName}, value of state variable ${e.valueOfStateVariable} not found.`);c.desiredStateVariableValues={[i]:await n.value}}let d=s[p];if(void 0===d&&(d=s[p]={}),o.additionalStateVariablesDefined)for(let e of o.additionalStateVariablesDefined){let t=e;a.state[e].isArray&&(t=o.arrayStateVariable);let n=s[t];n&&(Object.assign(d,n),s[t]=d)}if(c.workspace=d,e.additionalStateVariableValues)for(let t in e.additionalStateVariableValues)o.additionalStateVariablesDefined.includes(t)?c.desiredStateVariableValues[t]=e.additionalStateVariableValues[t]:console.warn(`Can't invert ${t} at the same time as ${i}, as not an additional state variable defined`);if(!o.inverseDefinition)return void console.warn(`Cannot change state variable ${i} of ${a.componentName} as it doesn't have an inverse definition`);if(await a.stateValues.fixed&&!e.overrideFixed&&!o.ignoreFixed)return void console.log(`Changing ${i} of ${a.componentName} did not succeed because fixed is true.`);if(!t&&!1===await a.stateValues.modifyIndirectly)return void console.log(`Changing ${i} of ${a.componentName} did not succeed because modifyIndirectly is false.`);let m=await o.inverseDefinition(c);if(!m.success)return;let h,f=[];for(let e of m.instructions){let t=!1;if(e.setDependency){let n=e.setDependency,r=this.dependencies.downstreamDependencies[a.componentName][i][n];if(["stateVariable","parentStateVariable"].includes(r.dependencyType)&&1===r.downstreamComponentNames.length){let n=r.downstreamComponentNames[0],a=r.mappedDownstreamVariableNamesByComponent[0][0],i=this._components[n].state[a];if((i.isArrayEntry||i.isArray)&&!i.doNotCombineInverseArrayInstructions){let r=i.isArrayEntry?i.arrayStateVariable:a;if(!h||h.componentName===n&&h.stateVariable===r&&h.shadowedVariable===e.shadowedVariable&&h.treatAsInitialChange===e.treatAsInitialChange||(f.push(h),h=void 0),!e.additionalDependencyValues&&!i.basedOnArrayKeyStateVariables)if(t=!0,h||(h={combinedArray:!0,componentName:n,stateVariable:r,shadowedVariable:e.shadowedVariable,treatAsInitialChange:e.treatAsInitialChange,desiredValue:{}}),i.isArrayEntry){let t=await i.arrayKeys;if(1===t.length)h.desiredValue[t[0]]=e.desiredValue;else for(let[n,r]of t.entries())h.desiredValue[r]=e.desiredValue[n]}else if(1!==i.nDimensions&&Array.isArray(e.desiredValue)){let t=(e,n)=>{if(1===n)return Object.assign({},e);{let r={};for(let a in e){let i=t(e[a],n-1);for(let e in i)r[`${a},${e}`]=i[e]}return r}};Object.assign(h.desiredValue,t(e.desiredValue,i.nDimensions))}else Object.assign(h.desiredValue,e.desiredValue)}}}t||(h&&(f.push(h),h=void 0),f.push(e))}h&&(f.push(h),h=void 0);for(let t of f)if(t.setEssentialValue){if(!u.includes(t.setEssentialValue)){let e=!1;if(o.isArrayEntry){let n=[o.arrayStateVariable];if(o.additionalStateVariablesDefined)for(let e of o.additionalStateVariablesDefined){let t=a.state[e];t.isArrayEntry&&n.push(t.arrayStateVariable)}e=n.includes(t.setEssentialValue)}if(!e)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: specified changing value of ${t.setEssentialValue}, which is not a state variable defined with ${i}.`)}if(!a.state[t.setEssentialValue].hasEssential)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: can't set essential value of ${t.setEssentialValue} if it is does not have an essential value.`);if(!("value"in t))throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: setEssentialValue must specify a value`);let e=t.value;if(e instanceof me$3.class){e=(await preprocessMathInverseDefinition({desiredValue:e,stateValues:a.stateValues,variableName:t.setEssentialValue,workspace:d})).desiredValue}if(a.state[t.setEssentialValue].doNotShadowEssential||a.state[t.setEssentialValue].shadowVariable)this.calculateEssentialVariableChanges({component:a,varName:t.setEssentialValue,value:e,newStateVariableValues:r,recurseToShadows:!1});else{let n=a;for(;n.shadows&&void 0===n.shadows.propVariable;)n=this._components[n.shadows.componentName];this.calculateEssentialVariableChanges({component:n,varName:t.setEssentialValue,value:e,newStateVariableValues:r})}}else if(t.setDependency){let s=t.setDependency,o=this.dependencies.downstreamDependencies[a.componentName][i][s];if("child"===o.dependencyType){let l=t.childIndex;if(null!==o.downstreamPrimitives[l]){if(typeof t.desiredValue==typeof o.downstreamPrimitives[l]){let e=this._components[o.parentName],n=o.activeChildrenIndices[l];if(e.compositeReplacementActiveRange)for(let r of e.compositeReplacementActiveRange)if(r.firstInd<=n&&r.lastInd>=n)throw console.log(`parent: ${e.componentName}, activeChildInd: ${n}`),console.log(e.compositeReplacementActiveRange),console.log(t),Error("Need to implement changing primitive replacements from composite");let a=n;if(e.compositeReplacementActiveRange)for(let t of e.compositeReplacementActiveRange)t.lastInd!e)).length-1,c=o.downstreamComponentNames[u];if(!c)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: ${s} child of index ${t.childIndex} does not exist.`);let p=o.mappedDownstreamVariableNamesByComponent[t.childIndex][t.variableIndex];if(!p)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: ${s} variable of index ${t.variableIndex} does not exist.`);let d={componentName:c,stateVariable:p,value:t.desiredValue,overrideFixed:e.overrideFixed,arrayKey:t.arrayKey};await this.requestComponentChanges({instruction:d,initialChange:!0===t.treatAsInitialChange,workspace:n,newStateVariableValues:r})}}else if(["attributeComponent","shadowSource","adapterSource","targetComponent"].includes(o.dependencyType)){let l=o.downstreamComponentNames[0],u=o.mappedDownstreamVariableNamesByComponent[0][t.variableIndex];if(!u)throw Error(`Invalid inverse definition of ${i} of ${a.componentName}: ${s} variable of index ${t.variableIndex} does not exist.`);let c={componentName:l,stateVariable:u,value:t.desiredValue,overrideFixed:e.overrideFixed,arrayKey:t.arrayKey};await this.requestComponentChanges({instruction:c,initialChange:!0===t.treatAsInitialChange,workspace:n,newStateVariableValues:r})}else{if(!["stateVariable","parentStateVariable","adapterSourceStateVariable","sourceCompositeStateVariable"].includes(o.dependencyType)||1!==o.downstreamComponentNames.length)throw Error(`unimplemented dependency type ${o.dependencyType} in requestComponentChanges`);{let l=o.downstreamComponentNames[0],u=o.mappedDownstreamVariableNamesByComponent[0][0],c={componentName:l,stateVariable:u,value:t.desiredValue,overrideFixed:e.overrideFixed,shadowedVariable:t.shadowedVariable};if(t.additionalDependencyValues){let e=this.components[l].state[u];for(let n in t.additionalDependencyValues){let r=this.dependencies.downstreamDependencies[a.componentName][i][n];if(!["stateVariable","parentStateVariable"].includes(r.dependencyType)||1!==r.downstreamComponentNames.length){console.warn(`Can't simultaneously set additional dependency value ${n} if it isn't a state variable`);continue}let o=r.mappedDownstreamVariableNamesByComponent[0][0];r.downstreamComponentNames[0]===l&&e.additionalStateVariablesDefined.includes(o)?(c.additionalStateVariableValues||(c.additionalStateVariableValues={}),c.additionalStateVariableValues[o]=t.additionalDependencyValues[n]):console.warn(`Can't simultaneously set additional dependency value ${n} if it doesn't correspond to additional state variable defined of ${s}'s state variable`)}}await this.requestComponentChanges({instruction:c,initialChange:!0===t.treatAsInitialChange,workspace:n,newStateVariableValues:r})}}}else{if(!t.combinedArray)throw console.log(t),Error(`Unrecognized instruction in inverse definition of ${i} of ${a.componentName}`);{let a={componentName:t.componentName,stateVariable:t.stateVariable,value:t.desiredValue,overrideFixed:e.overrideFixed,shadowedVariable:t.shadowedVariable};await this.requestComponentChanges({instruction:a,initialChange:!0===t.treatAsInitialChange,workspace:n,newStateVariableValues:r})}}}calculateEssentialVariableChanges({component:e,varName:t,value:n,newStateVariableValues:r,recurseToShadows:a=!0}){if(r[e.componentName]||(r[e.componentName]={}),e.state[t].isArray?(r[e.componentName][t]||(r[e.componentName][t]={mergeObject:!0}),Object.assign(r[e.componentName][t],n)):r[e.componentName][t]=n,a&&e.shadowedBy)for(let a of e.shadowedBy)void 0===a.shadows.propVariable&&this.calculateEssentialVariableChanges({component:a,varName:t,value:n,newStateVariableValues:r})}calculatePrimitiveChildChanges({parent:e,definingInd:t,newValue:n,newStateVariableValues:r,markToIgnoreForParent:a}){if(r[e.componentName]||(r[e.componentName]={}),e.componentName===a?r[e.componentName][`__def_primitive_ignore_${t}`]=n:r[e.componentName][`__def_primitive_${t}`]=n,e.shadowedBy)for(let i of e.shadowedBy)void 0===i.shadows.propVariable&&this.calculatePrimitiveChildChanges({parent:i,definingInd:t,newValue:n,newStateVariableValues:r,markToIgnoreForParent:a})}async saveState(e=!1){if(this.savePageStateTimeoutID=null,!this.flags.allowSaveState&&!this.flags.allowLocalState)return;let t=nanoid();this.flags.allowLocalState&&await set(`${this.doenetId}|${this.pageNumber}|${this.attemptNumber}|${this.cid}`,{coreState:this.cumulativeStateVariableChanges,rendererState:this.rendererState,coreInfo:this.coreInfo,saveId:t}),postMessage({messageType:"savedState",coreId:this.coreId}),this.flags.allowSaveState&&(this.pageStateToBeSavedToDatabase={cid:this.cid,coreInfo:this.coreInfoString,coreState:JSON.stringify(this.cumulativeStateVariableChanges,serializedComponentsReplacer),rendererState:JSON.stringify(this.rendererState,serializedComponentsReplacer),pageNumber:this.pageNumber,attemptNumber:this.attemptNumber,doenetId:this.doenetId,saveId:t,serverSaveId:this.serverSaveId,updateDataOnContentChange:this.updateDataOnContentChange},this.changesToBeSaved=!0,await this.saveChangesToDatabase(e))}async saveChangesToDatabase(e){if(!this.changesToBeSaved)return;if(null!==this.saveStateToDBTimerId){if(!e)return;clearTimeout(this.saveStateToDBTimerId)}let t;this.changesToBeSaved=!1,this.saveStateToDBTimerId=setTimeout((()=>{this.saveStateToDBTimerId=null,this.saveChangesToDatabase()}),6e4);try{t=await axios.post("/api/savePageState.php",this.pageStateToBeSavedToDatabase)}catch(e){return void postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"Error synchronizing data. Changes not saved to the server.",toastType:toastType.ERROR}})}if(console.log("result from saving to database:",t.data),null===t.status)return void postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"Error synchronizing data. Changes not saved to the server. Are you connected to the internet?",toastType:toastType.ERROR}});let n=t.data;n.success?(this.serverSaveId=n.saveId,this.flags.allowLocalState&&await set(`${this.doenetId}|${this.pageNumber}|${this.attemptNumber}|${this.cid}|ServerSaveId`,n.saveId),n.stateOverwritten&&(this.attemptNumber!==Number(n.attemptNumber)||this.cid===n.cid?(this.flags.allowLocalState&&await set(`${this.doenetId}|${this.pageNumber}|${n.attemptNumber}|${n.cid}`,{coreState:JSON.parse(n.coreState,serializedComponentsReviver),rendererState:JSON.parse(n.rendererState,serializedComponentsReviver),coreInfo:JSON.parse(n.coreInfo,serializedComponentsReviver),saveId:n.saveId}),postMessage({messageType:"resetPage",coreId:this.coreId,args:{changedOnDevice:n.device,newCid:n.cid,newAttemptNumber:Number(n.attemptNumber)}})):postMessage({messageType:"inErrorState",coreId:this.coreId,args:{errMsg:"Content changed unexpectedly!"}}))):postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:n.message,toastType:toastType.ERROR}})}saveSubmissions({pageCreditAchieved:e,suppressToast:t=!1}){if(!this.flags.allowSaveSubmissions)return;const n={doenetId:this.doenetId,attemptNumber:this.attemptNumber,credit:e,itemNumber:this.itemNumber};console.log("payload for save credit for item",n),axios.post("/api/saveCreditForItem.php",n).then((e=>{if(null===e.status)postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"Credit not saved due to error. Are you connected to the internet?",toastType:toastType.ERROR}});else if(e.data.success){let n=e.data;postMessage({messageType:"updateCreditAchieved",coreId:this.coreId,args:{creditByItem:n.creditByItem.map(Number),creditForAssignment:Number(n.creditForAssignment),creditForAttempt:Number(n.creditForAttempt),showCorrectness:"1"===n.showCorrectness,totalPointsOrPercent:Number(n.totalPointsOrPercent)}}),n.viewedSolution&&(t||postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"No credit awarded since solution was viewed.",toastType:toastType.INFO}})),n.timeExpired&&(t||postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"No credit awarded since the time allowed has expired.",toastType:toastType.INFO}})),n.pastDueDate&&(t||postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"No credit awarded since the due date has passed.",toastType:toastType.INFO}})),n.exceededAttemptsAllowed&&(t||postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"No credit awarded since no more attempts are allowed.",toastType:toastType.INFO}})),n.databaseError&&postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:"Credit not saved due to database error.",toastType:toastType.ERROR}})}else postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:`Credit not saved due to error: ${e.data.message}`,toastType:toastType.ERROR}})})).catch((e=>{postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:`Credit not saved due to error: ${e.message}`,toastType:toastType.ERROR}})}))}async recordSolutionView(){if(!this.flags.allowSaveSubmissions)return{allowView:!0,message:"",scoredComponent:this.documentName};try{const e=await axios.post("/api/reportSolutionViewed.php",{doenetId:this.doenetId,itemNumber:this.itemNumber,pageNumber:this.pageNumber,attemptNumber:this.attemptNumber});if(null===e.status){let e="Cannot show solution due to error. Are you connected to the internet?";return postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:e,toastType:toastType.ERROR}}),{allowView:!1,message:e,scoredComponent:this.documentName}}{let t=e.data;if(t.success)return{allowView:!0,message:"",scoredComponent:this.documentName};return{allowView:!1,message:`Cannot show solution due to error: ${t.message}`,scoredComponent:this.documentName}}}catch(e){let t="Cannot show solution due to error.";return postMessage({messageType:"sendToast",coreId:this.coreId,args:{message:t,toastType:toastType.ERROR}}),{allowView:!1,message:t,scoredComponent:this.documentName}}}get scoredItemWeights(){return(async()=>(await this.document.stateValues.scoredDescendants).map((e=>e.stateValues.weight)))()}requestAnimationFrame(e){postMessage({messageType:"requestAnimationFrame",coreId:this.coreId,args:e})}cancelAnimationFrame(e){postMessage({messageType:"cancelAnimationFrame",coreId:this.coreId,args:e})}handleVisibilityChange({visible:e}){e?this.resumeVisibilityMeasuring():this.suspendVisibilityMeasuring()}handleNavigatingToComponent(e){let t=this._components[e];t?.actions?.revealSection&&this.requestAction({componentName:t.componentName,actionName:"revealSection"})}async terminate(){if(await this.suspendVisibilityMeasuring(),this.submitAnswersTimeout&&(clearTimeout(this.submitAnswersTimeout),await this.autoSubmitAnswers()),this.stopProcessingRequests=!0,this.processing)for(let e=0;e<10&&(await new Promise(((e,t)=>{setTimeout(e,100)})),this.processing);e++);this.savePageStateTimeoutID?(clearTimeout(this.savePageStateTimeoutID),await this.saveState(!0)):await this.saveChangesToDatabase(!0)}recordAnswerToAutoSubmit(e){this.answersToSubmit||(this.answersToSubmit=[]),this.answersToSubmit.includes(e)||this.answersToSubmit.push(e),clearTimeout(this.submitAnswersTimeout),this.submitAnswersTimeout=setTimeout((()=>{this.autoSubmitAnswers()}),1e3)}async autoSubmitAnswers(){let e=this.answersToSubmit;this.answersToSubmit=[];for(let t of e){this._components[t].actions.submitAnswer&&await this.requestAction({componentName:t,actionName:"submitAnswer"})}}requestComponentDoenetML(e){let t=this.components[e];if(!t)return null;let n=t.doenetMLrange;if(!n)return null;let r=void 0!==n.openBegin?n.openBegin:n.selfCloseBegin,a=void 0!==n.closeEnd?n.closeEnd:n.selfCloseEnd+1,i=this.doenetML.slice(r-1,a),s=i.split("\n"),o=s.slice(1).reduce(((e,t)=>Math.min(e,t.trim().length>1?t.search(/\S|$/):1/0)),1/0);return Number.isFinite(o)&&o>0&&(s=s.map((e=>{let t=Math.min(o,e.search(/\S|$/));return e.slice(t)})),i=s.join("\n")),i+="\n",i}copyToClipboard(e,t){"string"!=typeof e?this.resolveAction({actionId:t}):postMessage({messageType:"copyToClipboard",coreId:this.coreId,args:{text:e,actionId:t}})}}function validateAttributeValue({value:e,attributeSpecification:t,attribute:n}){return t.valueTransformations&&e in t.valueTransformations&&(e=t.valueTransformations[e]),void 0===t.transformNonFiniteTo||Number.isFinite(e)||(e=t.transformNonFiniteTo),t.toLowerCase&&(e=e.toLowerCase()),t.trim&&(e=e.trim()),t.validValues?t.validValues.includes(e)||(console.warn(`Invalid value ${e} for attribute ${n}, using value ${t.defaultValue}`),e=t.defaultValue):t.clamp&&(et.clamp[1]?e=t.clamp[1]:Number.isFinite(e)||(e=t.defaultValue)),e}function calculateAllComponentsShadowing(e){let t=[];if(e.shadowedBy)for(let n of e.shadowedBy)if(!n.shadows.propVariable){t.push(n.componentName);let e=calculateAllComponentsShadowing(n);t.push(...e)}if(e.replacementOf){let n=calculateAllComponentsShadowing(e.replacementOf);t.push(...n)}return t}return Core}(); diff --git a/src/Viewer/renderers/legend.jsx b/src/Viewer/renderers/legend.jsx index 1e6025877b..d2bc602582 100644 --- a/src/Viewer/renderers/legend.jsx +++ b/src/Viewer/renderers/legend.jsx @@ -1,6 +1,7 @@ import React, { useContext, useEffect, useRef } from 'react'; import useDoenetRender from './useDoenetRenderer'; import { BoardContext } from './graph'; +import { deepCompare } from '../../Core/utils/deepFunctions'; export default React.memo(function Legend(props) { let { name, id, SVs } = useDoenetRender(props); @@ -10,15 +11,16 @@ export default React.memo(function Legend(props) { let swatches = useRef([]); let labels = useRef([]) + let previousElements = useRef(null); + let previousPosition = useRef(null); + let previousLimits = useRef(null); + + useEffect(() => { //On unmount return () => { - // if line is defined - if (Object.keys(lineJXG.current).length !== 0) { - deleteLegend(); - } - + deleteLegend(); } }, []) @@ -209,13 +211,24 @@ export default React.memo(function Legend(props) { if (board) { - if (swatches.current.length > 0) { - deleteLegend(); + if (!deepCompare(previousElements.current, SVs.legendElements) + || !deepCompare(previousLimits.current, SVs.graphLimits) + || previousPosition.current !== SVs.position + ) { + + if (swatches.current.length > 0) { + deleteLegend(); + } + createLegend(); } - createLegend(); + previousElements.current = [...SVs.legendElements]; + previousLimits.current = Object.assign({}, SVs.graphLimits); + previousPosition.current = SVs.position; + + return <>
diff --git a/src/Viewer/renderers/polygon.jsx b/src/Viewer/renderers/polygon.jsx index ce00689e70..b3fa31d732 100644 --- a/src/Viewer/renderers/polygon.jsx +++ b/src/Viewer/renderers/polygon.jsx @@ -179,6 +179,10 @@ export default React.memo(function Polygon(props) { vertex.off('down'); } } + polygonJXG.current.off('drag'); + polygonJXG.current.off('up'); + polygonJXG.current.off('down'); + polygonJXG.current.off('hit'); board.removeObject(polygonJXG.current); polygonJXG.current = null; } diff --git a/src/Viewer/renderers/ref.jsx b/src/Viewer/renderers/ref.jsx index dde3ebaed8..c3b34abe10 100644 --- a/src/Viewer/renderers/ref.jsx +++ b/src/Viewer/renderers/ref.jsx @@ -87,7 +87,7 @@ export default React.memo(function Ref(props) { url = `tool=editor&${url}`; } url = `/public?${url}` - } else if(pageToolView.page === "placementexam") { + } else if (pageToolView.page === "placementexam") { url = `?tool=exam&${url}` } else { url = `?tool=assignment&${url}` @@ -146,7 +146,6 @@ export default React.memo(function Ref(props) { if (externalUri || url === "#") { // for some reason, if url = "#", the , below, causes a refresh // as it removes the # from the url. So we use a directly in this case. - console.log('first case'); return scrollableContainer?.[scrollAttribute], enumerable: true }); - console.log('second case'); return