@datagrok/compute 1.35.8 → 1.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/package.js CHANGED
@@ -1,2 +1,2 @@
1
- var compute;(()=>{var t={933:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".pipeline-view .d4-ribbon-name.selected {\n color: var(--grey-6)\n}\n\n.pipeline-view .d4-ribbon-name {\n color: var(--blue-1);\n margin: 12px 6px;\n font-weight: normal;\n place-content: center;\n}\n\n.pipeline-view .d4-ribbon-name + .d4-ribbon-name::before {\n color: var(--grey-3);\n}\n\n.pipeline-view .d4-ribbon-name.d4-disabled {\n cursor: default;\n pointer-events: none;\n color: var(--grey-3);\n}\n\n.ui-input-editor button.ui-btn-nav.ui-btn.d4-disabled {\n color: var(--grey-3)\n}","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/function-views/css/pipeline-view.css"],names:[],mappings:"AAAA;EACE;AACF;;AAEA;EACE,oBAAoB;EACpB,gBAAgB;EAChB,mBAAmB;EACnB,qBAAqB;AACvB;;AAEA;EACE,oBAAoB;AACtB;;AAEA;EACE,eAAe;EACf,oBAAoB;EACpB,oBAAoB;AACtB;;AAEA;EACE;AACF",sourcesContent:[".pipeline-view .d4-ribbon-name.selected {\n color: var(--grey-6)\n}\n\n.pipeline-view .d4-ribbon-name {\n color: var(--blue-1);\n margin: 12px 6px;\n font-weight: normal;\n place-content: center;\n}\n\n.pipeline-view .d4-ribbon-name + .d4-ribbon-name::before {\n color: var(--grey-3);\n}\n\n.pipeline-view .d4-ribbon-name.d4-disabled {\n cursor: default;\n pointer-events: none;\n color: var(--grey-3);\n}\n\n.ui-input-editor button.ui-btn-nav.ui-btn.d4-disabled {\n color: var(--grey-3)\n}"],sourceRoot:""}]);const a=r},362:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".ui-form .ui-input-buttons.rfv-buttons {\n margin-top: 0px;\n position: sticky;\n}\n\n.ui-form .ui-input-buttons.rfv-buttons .ui-input-editor {\n flex-wrap: wrap;\n}\n\n.ui-input-root.rfv-restricted-input.d4-disabled {\n pointer-events: all;\n cursor: pointer!important;\n}\n\n/* Hide all state icons by default */\n.ui-input-root > .ui-input-options .rfv-icon-lock,\n.ui-input-root > .ui-input-options .rfv-icon-unlock,\n.ui-input-root > .ui-input-options .rfv-icon-undo,\n.ui-input-root > .ui-input-options .rfv-icon-warning {\n display: none;\n}\n\n/* Show warning icon if input is on warning state */\n.ui-input-root.rfv-inconsistent-input > .ui-input-options .rfv-icon-warning {\n display: inherit;\n}\n\n/* Show undo icon if input is on inconstent state and hovered */\n.ui-input-root.rfv-restricted-unlocked-input:hover .rfv-icon-undo, .ui-input-root.rfv-inconsistent-input:hover .rfv-icon-undo {\n display: inherit;\n}\n\n/* Show/hide lock-unlock icons on input hover */\n.ui-input-root.rfv-restricted-input:hover .rfv-icon-lock {\n display: none;\n}\n.ui-input-root.rfv-restricted-input .rfv-icon-lock {\n display: inherit;\n}\n.ui-input-root.rfv-restricted-input .rfv-icon-unlock {\n display: none;\n}\n.ui-input-root.rfv-restricted-input:hover .rfv-icon-unlock {\n display: inherit;\n}\n\n.ui-form-condensed .rfv-buttons > .ui-label {\n margin-right: 0px!important;\n}\n\n.rfv-form .ui-form .rfv-buttons > .ui-input-editor {\n gap: 5px;\n justify-content: flex-end;\n}\n\ndiv.ui-box > div.ui-box.rfv-form > div.ui-div {\n overflow: visible!important;\n}\n\n.rfv-scalar-table {\n border-collapse: collapse;\n margin: 10px;\n}\n\n.rfv-scalar-table td {\n width: max-content;\n white-space: nowrap;\n}\n\n.rfv-scalar-table tr{\n min-height: 30px;\n border-bottom: 1pt solid var(--grey-12);\n}\n\n.rfv-scalar-table tr:nth-child(odd) {\n background-color: var(--grey-1);\n}\n\n.rfv-scalar-table td:last-child {\n width: 100%;\n}","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/function-views/css/rich-function-view.css"],names:[],mappings:"AAAA;IACI,eAAe;IACf,gBAAgB;AACpB;;AAEA;IACI,eAAe;AACnB;;AAEA;IACI,mBAAmB;IACnB,yBAAyB;AAC7B;;AAEA,oCAAoC;AACpC;;;;IAII,aAAa;AACjB;;AAEA,mDAAmD;AACnD;IACI,gBAAgB;AACpB;;AAEA,+DAA+D;AAC/D;IACI,gBAAgB;AACpB;;AAEA,+CAA+C;AAC/C;IACI,aAAa;AACjB;AACA;IACI,gBAAgB;AACpB;AACA;IACI,aAAa;AACjB;AACA;IACI,gBAAgB;AACpB;;AAEA;IACI,2BAA2B;AAC/B;;AAEA;IACI,QAAQ;IACR,yBAAyB;AAC7B;;AAEA;IACI,2BAA2B;AAC/B;;AAEA;IACI,yBAAyB;IACzB,YAAY;AAChB;;AAEA;IACI,kBAAkB;IAClB,mBAAmB;AACvB;;AAEA;IACI,gBAAgB;IAChB,uCAAuC;AAC3C;;AAEA;IACI,+BAA+B;AACnC;;AAEA;IACI,WAAW;AACf",sourcesContent:[".ui-form .ui-input-buttons.rfv-buttons {\n margin-top: 0px;\n position: sticky;\n}\n\n.ui-form .ui-input-buttons.rfv-buttons .ui-input-editor {\n flex-wrap: wrap;\n}\n\n.ui-input-root.rfv-restricted-input.d4-disabled {\n pointer-events: all;\n cursor: pointer!important;\n}\n\n/* Hide all state icons by default */\n.ui-input-root > .ui-input-options .rfv-icon-lock,\n.ui-input-root > .ui-input-options .rfv-icon-unlock,\n.ui-input-root > .ui-input-options .rfv-icon-undo,\n.ui-input-root > .ui-input-options .rfv-icon-warning {\n display: none;\n}\n\n/* Show warning icon if input is on warning state */\n.ui-input-root.rfv-inconsistent-input > .ui-input-options .rfv-icon-warning {\n display: inherit;\n}\n\n/* Show undo icon if input is on inconstent state and hovered */\n.ui-input-root.rfv-restricted-unlocked-input:hover .rfv-icon-undo, .ui-input-root.rfv-inconsistent-input:hover .rfv-icon-undo {\n display: inherit;\n}\n\n/* Show/hide lock-unlock icons on input hover */\n.ui-input-root.rfv-restricted-input:hover .rfv-icon-lock {\n display: none;\n}\n.ui-input-root.rfv-restricted-input .rfv-icon-lock {\n display: inherit;\n}\n.ui-input-root.rfv-restricted-input .rfv-icon-unlock {\n display: none;\n}\n.ui-input-root.rfv-restricted-input:hover .rfv-icon-unlock {\n display: inherit;\n}\n\n.ui-form-condensed .rfv-buttons > .ui-label {\n margin-right: 0px!important;\n}\n\n.rfv-form .ui-form .rfv-buttons > .ui-input-editor {\n gap: 5px;\n justify-content: flex-end;\n}\n\ndiv.ui-box > div.ui-box.rfv-form > div.ui-div {\n overflow: visible!important;\n}\n\n.rfv-scalar-table {\n border-collapse: collapse;\n margin: 10px;\n}\n\n.rfv-scalar-table td {\n width: max-content;\n white-space: nowrap;\n}\n\n.rfv-scalar-table tr{\n min-height: 30px;\n border-bottom: 1pt solid var(--grey-12);\n}\n\n.rfv-scalar-table tr:nth-child(odd) {\n background-color: var(--grey-1);\n}\n\n.rfv-scalar-table td:last-child {\n width: 100%;\n}"],sourceRoot:""}]);const a=r},993:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".ui-form .ui-input-root .sa-switch-input {\n max-width: 50px;\n min-width: 50px;\n}\n\n.ui-form.ui-form-condensed .ui-input-root .sa-switch-input {\n order: -3;\n top: -5px;\n position: relative;\n}\n\n.ui-form.ui-form-condensed .ui-input-root > .sa-switch-input + label.ui-input-label:not(:empty) {\n width: unset;\n}\n\n.ui-form.ui-form-condensed .ui-input-root > .sa-switch-input ~ .ui-input-editor {\n margin-left: 50px;\n}","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/function-views/css/sens-analysis.css"],names:[],mappings:"AAAA;IACI,eAAe;IACf,eAAe;AACnB;;AAEA;IACI,SAAS;IACT,SAAS;IACT,kBAAkB;AACtB;;AAEA;IACI,YAAY;AAChB;;AAEA;IACI,iBAAiB;AACrB",sourcesContent:[".ui-form .ui-input-root .sa-switch-input {\n max-width: 50px;\n min-width: 50px;\n}\n\n.ui-form.ui-form-condensed .ui-input-root .sa-switch-input {\n order: -3;\n top: -5px;\n position: relative;\n}\n\n.ui-form.ui-form-condensed .ui-input-root > .sa-switch-input + label.ui-input-label:not(:empty) {\n width: unset;\n}\n\n.ui-form.ui-form-condensed .ui-input-root > .sa-switch-input ~ .ui-input-editor {\n margin-left: 50px;\n}"],sourceRoot:""}]);const a=r},847:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,'.model-catalog-view .d4-gallery-card.entity-model i.grok-icon {\n height: 64px;\n width: 64px;\n position: initial;\n flex-shrink: 0;\n}\n\n.model-catalog-view .d4-gallery-card.entity-model .d4-link-label i.grok-icon + label {\n margin-left: 6px;\n align-items: center;\n display: inline-flex;\n white-space: normal;\n}\n\n.model-catalog-view .d4-gallery-card.entity-model {\n padding: 0 8px;\n align-items: center;\n display: flex;\n margin: 0;\n height: 94px;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .grok-gallery-grid {\n flex-direction: row!important;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .d4-link-label i.grok-icon {\n width: 32px;\n height: 32px;\n position: initial;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .d4-link-label label {\n margin-left: 8px;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .grok-gallery-grid .d4-link-label {\n min-width: 250px;\n margin-bottom: 9px;\n color: var(--grey-6);\n padding: 10px;\n width: initial;\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-node {\n font-size: 20px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-node {\n font-size: 16px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group .d4-tree-view-node {\n font-size: 14px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-video {\n width: 80%;\n height: 0;\n padding-bottom: 50%;\n margin: 10px 10px 0 0;\n border: 1px solid var(--grey-2);\n position: relative;\n background-size: cover;\n background-repeat: no-repeat;\n}\n\n.model-catalog-video i {\n position: absolute;\n right: 0;\n left: 0;\n bottom: 0;\n top: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n font-weight: 600;\n color: var(--grey-2);\n font-size: 42px;\n}\n\n.model-catalog-video i:hover {\n color: var(--grey-1);\n}\n\n.model-catalog-description {\n padding: 10px 0 0 0;\n}',"",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/model-catalog/css/model-card.css"],names:[],mappings:"AAAA;IACI,YAAY;IACZ,WAAW;IACX,iBAAiB;IACjB,cAAc;AAClB;;AAEA;IACI,gBAAgB;IAChB,mBAAmB;IACnB,oBAAoB;IACpB,mBAAmB;AACvB;;AAEA;IACI,cAAc;IACd,mBAAmB;IACnB,aAAa;IACb,SAAS;IACT,YAAY;AAChB;;AAEA;IACI,6BAA6B;AACjC;;AAEA;IACI,WAAW;IACX,YAAY;IACZ,iBAAiB;AACrB;;AAEA;IACI,gBAAgB;AACpB;;AAEA;IACI,gBAAgB;IAChB,kBAAkB;IAClB,oBAAoB;IACpB,aAAa;IACb,cAAc;AAClB;;AAEA;IACI,eAAe;IACf,cAAc;IACd,oBAAoB;AACxB;;AAEA;IACI,eAAe;IACf,cAAc;IACd,oBAAoB;AACxB;;AAEA;IACI,eAAe;IACf,cAAc;IACd,oBAAoB;AACxB;;AAEA;IACI,UAAU;IACV,SAAS;IACT,mBAAmB;IACnB,qBAAqB;IACrB,+BAA+B;IAC/B,kBAAkB;IAClB,sBAAsB;IACtB,4BAA4B;AAChC;;AAEA;IACI,kBAAkB;IAClB,QAAQ;IACR,OAAO;IACP,SAAS;IACT,MAAM;IACN,aAAa;IACb,mBAAmB;IACnB,uBAAuB;IACvB,gBAAgB;IAChB,oBAAoB;IACpB,eAAe;AACnB;;AAEA;IACI,oBAAoB;AACxB;;AAEA;IACI,mBAAmB;AACvB",sourcesContent:['.model-catalog-view .d4-gallery-card.entity-model i.grok-icon {\n height: 64px;\n width: 64px;\n position: initial;\n flex-shrink: 0;\n}\n\n.model-catalog-view .d4-gallery-card.entity-model .d4-link-label i.grok-icon + label {\n margin-left: 6px;\n align-items: center;\n display: inline-flex;\n white-space: normal;\n}\n\n.model-catalog-view .d4-gallery-card.entity-model {\n padding: 0 8px;\n align-items: center;\n display: flex;\n margin: 0;\n height: 94px;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .grok-gallery-grid {\n flex-direction: row!important;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .d4-link-label i.grok-icon {\n width: 32px;\n height: 32px;\n position: initial;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .d4-link-label label {\n margin-left: 8px;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .grok-gallery-grid .d4-link-label {\n min-width: 250px;\n margin-bottom: 9px;\n color: var(--grey-6);\n padding: 10px;\n width: initial;\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-node {\n font-size: 20px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-node {\n font-size: 16px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group .d4-tree-view-node {\n font-size: 14px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-video {\n width: 80%;\n height: 0;\n padding-bottom: 50%;\n margin: 10px 10px 0 0;\n border: 1px solid var(--grey-2);\n position: relative;\n background-size: cover;\n background-repeat: no-repeat;\n}\n\n.model-catalog-video i {\n position: absolute;\n right: 0;\n left: 0;\n bottom: 0;\n top: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n font-weight: 600;\n color: var(--grey-2);\n font-size: 42px;\n}\n\n.model-catalog-video i:hover {\n color: var(--grey-1);\n}\n\n.model-catalog-description {\n padding: 10px 0 0 0;\n}'],sourceRoot:""}]);const a=r},911:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".fi-drop-area {\n position: relative;\n}\n\n.fi-drop-area .default {\n color: var(--grey-2);\n}\n\n.fi-drop-area .drag-n-dropping {\n background-color: var(--steel-1);\n border: 1px dashed var(--blue-1);\n color: var(--grey-3);\n}\n\n.fi-drop-area .error {\n color: var(--red-3);\n}\n\n.fi-drop-area .success {\n color: var(--grey-6);\n}\n","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/shared-components/css/file-input.css"],names:[],mappings:"AAAA;EACE,kBAAkB;AACpB;;AAEA;EACE,oBAAoB;AACtB;;AAEA;EACE,gCAAgC;EAChC,gCAAgC;EAChC,oBAAoB;AACtB;;AAEA;EACE,mBAAmB;AACrB;;AAEA;EACE,oBAAoB;AACtB",sourcesContent:[".fi-drop-area {\n position: relative;\n}\n\n.fi-drop-area .default {\n color: var(--grey-2);\n}\n\n.fi-drop-area .drag-n-dropping {\n background-color: var(--steel-1);\n border: 1px dashed var(--blue-1);\n color: var(--grey-3);\n}\n\n.fi-drop-area .error {\n color: var(--red-3);\n}\n\n.fi-drop-area .success {\n color: var(--grey-6);\n}\n"],sourceRoot:""}]);const a=r},703:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,"","",{version:3,sources:[],names:[],mappings:"",sourceRoot:""}]);const a=r},565:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".hp-no-elements-label {\n margin: 12px;\n}\n\n.grok-icon.hp-disabled {\n pointer-events: none;\n opacity: 0.6;\n}\n\n.hp-funccall-card-hover-icon {\n display: none;\n}\n\n.hp-funccall-card:hover .hp-funccall-card-hover-icon {\n display: flex;\n margin: 0px 0px 0px 5px;\n}\n\n.hp-funccall-card {\n margin: 2px 1px;\n padding: 5px;\n justify-content: space-between;\n}\n\n.hp-funccall-card .hp-card-content {\n justify-content: space-around;\n margin-left: 5px;\n}\n\n.hp-funccall-card .hp-card-content * {\n margin-bottom: 3px;\n}\n\n.hp-funccall-card .description {\n margin-bottom: 2px;\n color: var(--grey-3);\n}\n\n.hp-funccall-card .date {\n color: var(--grey-3);\n margin-left: 5px;\n}\n","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/shared-components/css/history-panel.css"],names:[],mappings:"AAAA;IACI,YAAY;AAChB;;AAEA;IACI,oBAAoB;IACpB,YAAY;AAChB;;AAEA;IACI,aAAa;AACjB;;AAEA;IACI,aAAa;IACb,uBAAuB;AAC3B;;AAEA;IACI,eAAe;IACf,YAAY;IACZ,8BAA8B;AAClC;;AAEA;IACI,6BAA6B;IAC7B,gBAAgB;AACpB;;AAEA;IACI,kBAAkB;AACtB;;AAEA;IACI,kBAAkB;IAClB,oBAAoB;AACxB;;AAEA;IACI,oBAAoB;IACpB,gBAAgB;AACpB",sourcesContent:[".hp-no-elements-label {\n margin: 12px;\n}\n\n.grok-icon.hp-disabled {\n pointer-events: none;\n opacity: 0.6;\n}\n\n.hp-funccall-card-hover-icon {\n display: none;\n}\n\n.hp-funccall-card:hover .hp-funccall-card-hover-icon {\n display: flex;\n margin: 0px 0px 0px 5px;\n}\n\n.hp-funccall-card {\n margin: 2px 1px;\n padding: 5px;\n justify-content: space-between;\n}\n\n.hp-funccall-card .hp-card-content {\n justify-content: space-around;\n margin-left: 5px;\n}\n\n.hp-funccall-card .hp-card-content * {\n margin-bottom: 3px;\n}\n\n.hp-funccall-card .description {\n margin-bottom: 2px;\n color: var(--grey-3);\n}\n\n.hp-funccall-card .date {\n color: var(--grey-3);\n margin-left: 5px;\n}\n"],sourceRoot:""}]);const a=r},314:t=>{"use strict";t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var n="",i=void 0!==e[5];return e[4]&&(n+="@supports (".concat(e[4],") {")),e[2]&&(n+="@media ".concat(e[2]," {")),i&&(n+="@layer".concat(e[5].length>0?" ".concat(e[5]):""," {")),n+=t(e),i&&(n+="}"),e[2]&&(n+="}"),e[4]&&(n+="}"),n})).join("")},e.i=function(t,n,i,o,s){"string"==typeof t&&(t=[[null,t,void 0]]);var r={};if(i)for(var a=0;a<this.length;a++){var l=this[a][0];null!=l&&(r[l]=!0)}for(var u=0;u<t.length;u++){var c=[].concat(t[u]);i&&r[c[0]]||(void 0!==s&&(void 0===c[5]||(c[1]="@layer".concat(c[5].length>0?" ".concat(c[5]):""," {").concat(c[1],"}")),c[5]=s),n&&(c[2]?(c[1]="@media ".concat(c[2]," {").concat(c[1],"}"),c[2]=n):c[2]=n),o&&(c[4]?(c[1]="@supports (".concat(c[4],") {").concat(c[1],"}"),c[4]=o):c[4]="".concat(o)),e.push(c))}},e}},354:t=>{"use strict";t.exports=function(t){var e=t[1],n=t[3];if(!n)return e;if("function"==typeof btoa){var i=btoa(unescape(encodeURIComponent(JSON.stringify(n)))),o="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(i),s="/*# ".concat(o," */");return[e].concat([s]).join("\n")}return[e].join("\n")}},826:function(t){t.exports=function(){"use strict";var t="minute",e=/[+-]\d\d(?::?\d\d)?/g,n=/([+-]|\d\d)/g;return function(i,o,s){var r=o.prototype;s.utc=function(t){return new o({date:t,utc:!0,args:arguments})},r.utc=function(e){var n=s(this.toDate(),{locale:this.$L,utc:!0});return e?n.add(this.utcOffset(),t):n},r.local=function(){return s(this.toDate(),{locale:this.$L,utc:!1})};var a=r.parse;r.parse=function(t){t.utc&&(this.$u=!0),this.$utils().u(t.$offset)||(this.$offset=t.$offset),a.call(this,t)};var l=r.init;r.init=function(){if(this.$u){var t=this.$d;this.$y=t.getUTCFullYear(),this.$M=t.getUTCMonth(),this.$D=t.getUTCDate(),this.$W=t.getUTCDay(),this.$H=t.getUTCHours(),this.$m=t.getUTCMinutes(),this.$s=t.getUTCSeconds(),this.$ms=t.getUTCMilliseconds()}else l.call(this)};var u=r.utcOffset;r.utcOffset=function(i,o){var s=this.$utils().u;if(s(i))return this.$u?0:s(this.$offset)?u.call(this):this.$offset;if("string"==typeof i&&(i=function(t){void 0===t&&(t="");var i=t.match(e);if(!i)return null;var o=(""+i[0]).match(n)||["-",0,0],s=o[0],r=60*+o[1]+ +o[2];return 0===r?0:"+"===s?r:-r}(i),null===i))return this;var r=Math.abs(i)<=16?60*i:i,a=this;if(o)return a.$offset=r,a.$u=0===i,a;if(0!==i){var l=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(a=this.local().add(r+l,t)).$offset=r,a.$x.$localOffset=l}else a=this.utc();return a};var c=r.format;r.format=function(t){var e=t||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return c.call(this,e)},r.valueOf=function(){var t=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*t},r.isUTC=function(){return!!this.$u},r.toISOString=function(){return this.toDate().toISOString()},r.toString=function(){return this.toDate().toUTCString()};var d=r.toDate;r.toDate=function(t){return"s"===t&&this.$offset?s(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():d.call(this)};var p=r.diff;r.diff=function(t,e,n){if(t&&this.$u===t.$u)return p.call(this,t,e,n);var i=this.local(),o=s(t).local();return p.call(i,o,e,n)}}}()},693:(t,e,n)=>{t=n.nmd(t);var i="__lodash_hash_undefined__",o=9007199254740991,s="[object Arguments]",r="[object Boolean]",a="[object Date]",l="[object Function]",u="[object GeneratorFunction]",c="[object Map]",d="[object Number]",p="[object Object]",h="[object Promise]",f="[object RegExp]",m="[object Set]",v="[object String]",g="[object Symbol]",y="[object WeakMap]",b="[object ArrayBuffer]",w="[object DataView]",A="[object Float32Array]",C="[object Float64Array]",I="[object Int8Array]",S="[object Int16Array]",T="[object Int32Array]",E="[object Uint8Array]",x="[object Uint8ClampedArray]",R="[object Uint16Array]",O="[object Uint32Array]",P=/\w*$/,k=/^\[object .+?Constructor\]$/,F=/^(?:0|[1-9]\d*)$/,L={};L[s]=L["[object Array]"]=L[b]=L[w]=L[r]=L[a]=L[A]=L[C]=L[I]=L[S]=L[T]=L[c]=L[d]=L[p]=L[f]=L[m]=L[v]=L[g]=L[E]=L[x]=L[R]=L[O]=!0,L["[object Error]"]=L[l]=L[y]=!1;var N="object"==typeof n.g&&n.g&&n.g.Object===Object&&n.g,B="object"==typeof self&&self&&self.Object===Object&&self,M=N||B||Function("return this")(),_=e&&!e.nodeType&&e,D=_&&t&&!t.nodeType&&t,V=D&&D.exports===_;function j(t,e){return t.set(e[0],e[1]),t}function $(t,e){return t.add(e),t}function H(t,e,n,i){var o=-1,s=t?t.length:0;for(i&&s&&(n=t[++o]);++o<s;)n=e(n,t[o],o,t);return n}function U(t){var e=!1;if(null!=t&&"function"!=typeof t.toString)try{e=!!(t+"")}catch(t){}return e}function Y(t){var e=-1,n=Array(t.size);return t.forEach((function(t,i){n[++e]=[i,t]})),n}function W(t,e){return function(n){return t(e(n))}}function G(t){var e=-1,n=Array(t.size);return t.forEach((function(t){n[++e]=t})),n}var z,q=Array.prototype,J=Function.prototype,K=Object.prototype,Z=M["__core-js_shared__"],X=(z=/[^.]+$/.exec(Z&&Z.keys&&Z.keys.IE_PROTO||""))?"Symbol(src)_1."+z:"",Q=J.toString,tt=K.hasOwnProperty,et=K.toString,nt=RegExp("^"+Q.call(tt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),it=V?M.Buffer:void 0,ot=M.Symbol,st=M.Uint8Array,rt=W(Object.getPrototypeOf,Object),at=Object.create,lt=K.propertyIsEnumerable,ut=q.splice,ct=Object.getOwnPropertySymbols,dt=it?it.isBuffer:void 0,pt=W(Object.keys,Object),ht=Mt(M,"DataView"),ft=Mt(M,"Map"),mt=Mt(M,"Promise"),vt=Mt(M,"Set"),gt=Mt(M,"WeakMap"),yt=Mt(Object,"create"),bt=$t(ht),wt=$t(ft),At=$t(mt),Ct=$t(vt),It=$t(gt),St=ot?ot.prototype:void 0,Tt=St?St.valueOf:void 0;function Et(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}function xt(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}function Rt(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}function Ot(t){this.__data__=new xt(t)}function Pt(t,e,n){var i=t[e];tt.call(t,e)&&Ht(i,n)&&(void 0!==n||e in t)||(t[e]=n)}function kt(t,e){for(var n=t.length;n--;)if(Ht(t[n][0],e))return n;return-1}function Ft(t,e,n,i,o,h,y){var k;if(i&&(k=h?i(t,o,h,y):i(t)),void 0!==k)return k;if(!zt(t))return t;var F=Ut(t);if(F){if(k=function(t){var e=t.length,n=t.constructor(e);return e&&"string"==typeof t[0]&&tt.call(t,"index")&&(n.index=t.index,n.input=t.input),n}(t),!e)return function(t,e){var n=-1,i=t.length;for(e||(e=Array(i));++n<i;)e[n]=t[n];return e}(t,k)}else{var N=Dt(t),B=N==l||N==u;if(Wt(t))return function(t,e){if(e)return t.slice();var n=new t.constructor(t.length);return t.copy(n),n}(t,e);if(N==p||N==s||B&&!h){if(U(t))return h?t:{};if(k=function(t){return"function"!=typeof t.constructor||jt(t)?{}:zt(e=rt(t))?at(e):{};var e}(B?{}:t),!e)return function(t,e){return Nt(t,_t(t),e)}(t,function(t,e){return t&&Nt(e,qt(e),t)}(k,t))}else{if(!L[N])return h?t:{};k=function(t,e,n,i){var o,s=t.constructor;switch(e){case b:return Lt(t);case r:case a:return new s(+t);case w:return function(t,e){var n=e?Lt(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)}(t,i);case A:case C:case I:case S:case T:case E:case x:case R:case O:return function(t,e){var n=e?Lt(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}(t,i);case c:return function(t,e,n){return H(e?n(Y(t),!0):Y(t),j,new t.constructor)}(t,i,n);case d:case v:return new s(t);case f:return function(t){var e=new t.constructor(t.source,P.exec(t));return e.lastIndex=t.lastIndex,e}(t);case m:return function(t,e,n){return H(e?n(G(t),!0):G(t),$,new t.constructor)}(t,i,n);case g:return o=t,Tt?Object(Tt.call(o)):{}}}(t,N,Ft,e)}}y||(y=new Ot);var M=y.get(t);if(M)return M;if(y.set(t,k),!F)var _=n?function(t){return function(t,e,n){var i=e(t);return Ut(t)?i:function(t,e){for(var n=-1,i=e.length,o=t.length;++n<i;)t[o+n]=e[n];return t}(i,n(t))}(t,qt,_t)}(t):qt(t);return function(t,e){for(var n=-1,i=t?t.length:0;++n<i&&!1!==e(t[n],n););}(_||t,(function(o,s){_&&(o=t[s=o]),Pt(k,s,Ft(o,e,n,i,s,t,y))})),k}function Lt(t){var e=new t.constructor(t.byteLength);return new st(e).set(new st(t)),e}function Nt(t,e,n,i){n||(n={});for(var o=-1,s=e.length;++o<s;){var r=e[o],a=i?i(n[r],t[r],r,n,t):void 0;Pt(n,r,void 0===a?t[r]:a)}return n}function Bt(t,e){var n,i,o=t.__data__;return("string"==(i=typeof(n=e))||"number"==i||"symbol"==i||"boolean"==i?"__proto__"!==n:null===n)?o["string"==typeof e?"string":"hash"]:o.map}function Mt(t,e){var n=function(t,e){return null==t?void 0:t[e]}(t,e);return function(t){return!(!zt(t)||(e=t,X&&X in e))&&(Gt(t)||U(t)?nt:k).test($t(t));var e}(n)?n:void 0}Et.prototype.clear=function(){this.__data__=yt?yt(null):{}},Et.prototype.delete=function(t){return this.has(t)&&delete this.__data__[t]},Et.prototype.get=function(t){var e=this.__data__;if(yt){var n=e[t];return n===i?void 0:n}return tt.call(e,t)?e[t]:void 0},Et.prototype.has=function(t){var e=this.__data__;return yt?void 0!==e[t]:tt.call(e,t)},Et.prototype.set=function(t,e){return this.__data__[t]=yt&&void 0===e?i:e,this},xt.prototype.clear=function(){this.__data__=[]},xt.prototype.delete=function(t){var e=this.__data__,n=kt(e,t);return!(n<0||(n==e.length-1?e.pop():ut.call(e,n,1),0))},xt.prototype.get=function(t){var e=this.__data__,n=kt(e,t);return n<0?void 0:e[n][1]},xt.prototype.has=function(t){return kt(this.__data__,t)>-1},xt.prototype.set=function(t,e){var n=this.__data__,i=kt(n,t);return i<0?n.push([t,e]):n[i][1]=e,this},Rt.prototype.clear=function(){this.__data__={hash:new Et,map:new(ft||xt),string:new Et}},Rt.prototype.delete=function(t){return Bt(this,t).delete(t)},Rt.prototype.get=function(t){return Bt(this,t).get(t)},Rt.prototype.has=function(t){return Bt(this,t).has(t)},Rt.prototype.set=function(t,e){return Bt(this,t).set(t,e),this},Ot.prototype.clear=function(){this.__data__=new xt},Ot.prototype.delete=function(t){return this.__data__.delete(t)},Ot.prototype.get=function(t){return this.__data__.get(t)},Ot.prototype.has=function(t){return this.__data__.has(t)},Ot.prototype.set=function(t,e){var n=this.__data__;if(n instanceof xt){var i=n.__data__;if(!ft||i.length<199)return i.push([t,e]),this;n=this.__data__=new Rt(i)}return n.set(t,e),this};var _t=ct?W(ct,Object):function(){return[]},Dt=function(t){return et.call(t)};function Vt(t,e){return!!(e=null==e?o:e)&&("number"==typeof t||F.test(t))&&t>-1&&t%1==0&&t<e}function jt(t){var e=t&&t.constructor;return t===("function"==typeof e&&e.prototype||K)}function $t(t){if(null!=t){try{return Q.call(t)}catch(t){}try{return t+""}catch(t){}}return""}function Ht(t,e){return t===e||t!=t&&e!=e}(ht&&Dt(new ht(new ArrayBuffer(1)))!=w||ft&&Dt(new ft)!=c||mt&&Dt(mt.resolve())!=h||vt&&Dt(new vt)!=m||gt&&Dt(new gt)!=y)&&(Dt=function(t){var e=et.call(t),n=e==p?t.constructor:void 0,i=n?$t(n):void 0;if(i)switch(i){case bt:return w;case wt:return c;case At:return h;case Ct:return m;case It:return y}return e});var Ut=Array.isArray;function Yt(t){return null!=t&&function(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=o}(t.length)&&!Gt(t)}var Wt=dt||function(){return!1};function Gt(t){var e=zt(t)?et.call(t):"";return e==l||e==u}function zt(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function qt(t){return Yt(t)?function(t,e){var n=Ut(t)||function(t){return function(t){return function(t){return!!t&&"object"==typeof t}(t)&&Yt(t)}(t)&&tt.call(t,"callee")&&(!lt.call(t,"callee")||et.call(t)==s)}(t)?function(t,e){for(var n=-1,i=Array(t);++n<t;)i[n]=e(n);return i}(t.length,String):[],i=n.length,o=!!i;for(var r in t)!e&&!tt.call(t,r)||o&&("length"==r||Vt(r,i))||n.push(r);return n}(t):function(t){if(!jt(t))return pt(t);var e=[];for(var n in Object(t))tt.call(t,n)&&"constructor"!=n&&e.push(n);return e}(t)}t.exports=function(t,e){return Ft(t,!0,!0,e)}},72:t=>{"use strict";var e=[];function n(t){for(var n=-1,i=0;i<e.length;i++)if(e[i].identifier===t){n=i;break}return n}function i(t,i){for(var s={},r=[],a=0;a<t.length;a++){var l=t[a],u=i.base?l[0]+i.base:l[0],c=s[u]||0,d="".concat(u," ").concat(c);s[u]=c+1;var p=n(d),h={css:l[1],media:l[2],sourceMap:l[3],supports:l[4],layer:l[5]};if(-1!==p)e[p].references++,e[p].updater(h);else{var f=o(h,i);i.byIndex=a,e.splice(a,0,{identifier:d,updater:f,references:1})}r.push(d)}return r}function o(t,e){var n=e.domAPI(e);return n.update(t),function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap&&e.supports===t.supports&&e.layer===t.layer)return;n.update(t=e)}else n.remove()}}t.exports=function(t,o){var s=i(t=t||[],o=o||{});return function(t){t=t||[];for(var r=0;r<s.length;r++){var a=n(s[r]);e[a].references--}for(var l=i(t,o),u=0;u<s.length;u++){var c=n(s[u]);0===e[c].references&&(e[c].updater(),e.splice(c,1))}s=l}}},659:t=>{"use strict";var e={};t.exports=function(t,n){var i=function(t){if(void 0===e[t]){var n=document.querySelector(t);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(t){n=null}e[t]=n}return e[t]}(t);if(!i)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");i.appendChild(n)}},540:t=>{"use strict";t.exports=function(t){var e=document.createElement("style");return t.setAttributes(e,t.attributes),t.insert(e,t.options),e}},56:(t,e,n)=>{"use strict";t.exports=function(t){var e=n.nc;e&&t.setAttribute("nonce",e)}},825:t=>{"use strict";t.exports=function(t){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var e=t.insertStyleElement(t);return{update:function(n){!function(t,e,n){var i="";n.supports&&(i+="@supports (".concat(n.supports,") {")),n.media&&(i+="@media ".concat(n.media," {"));var o=void 0!==n.layer;o&&(i+="@layer".concat(n.layer.length>0?" ".concat(n.layer):""," {")),i+=n.css,o&&(i+="}"),n.media&&(i+="}"),n.supports&&(i+="}");var s=n.sourceMap;s&&"undefined"!=typeof btoa&&(i+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(s))))," */")),e.styleTagTransform(i,t,e.options)}(e,t,n)},remove:function(){!function(t){if(null===t.parentNode)return!1;t.parentNode.removeChild(t)}(e)}}}},113:t=>{"use strict";t.exports=function(t,e){if(e.styleSheet)e.styleSheet.cssText=t;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(t))}}}},e={};function n(i){var o=e[i];if(void 0!==o)return o.exports;var s=e[i]={id:i,loaded:!1,exports:{}};return t[i].call(s.exports,s,s.exports,n),s.loaded=!0,s.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var i in e)n.o(e,i)&&!n.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.nmd=t=>(t.paths=[],t.children||(t.children=[]),t),n.nc=void 0;var i={};(()=>{"use strict";n.r(i),n.d(i,{AmbTempValidator:()=>xo,CompView:()=>Fo,CompositionPipeline:()=>Bo,CustomCustomizer:()=>wo,CustomDataUploader:()=>yo,CustomStringInput:()=>Oo,CustomUploader:()=>bo,DesiredTempValidator:()=>To,HeatCapValidator:()=>Ro,InitialTempValidator:()=>Eo,ObjectCoolingSelector:()=>Po,OutliersSelection:()=>ho,Pipeline:()=>No,PipelineStepEditor:()=>mo,RFV:()=>Lo,RichFunctionViewEditor:()=>fo,SimTimeValidator:()=>So,_package:()=>co,fileInput:()=>jo,historyInput:()=>$o,historyInputJSON:()=>Ho,historyPanel:()=>Uo,init:()=>Ao,makeAdvice:()=>_o,makeRevalidation:()=>Do,makeValidationResult:()=>Mo,mergeValidationResults:()=>Vo,modelCatalog:()=>Io,openModelFromFuncall:()=>po,renderRestPanel:()=>vo,testPipeline:()=>ko});const t=grok,e=ui,o=DG,s=rxjs.operators,r=$;var a=n.n(r);const l=()=>document.querySelector(".d4-balloon-container");class u extends o.JsViewer{constructor(){super()}onFrameAttached(t){this.render()}onTableAttached(){this.render()}render(){if(!this.dataFrame||this.dataFrame.rowCount<=0)return void(this.root.innerHTML="");const n=this.dataFrame,i="isOutlier",s="Rationale",r="Count",u="isConfirmed";n.columns.byName(i)||n.columns.add(o.Column.fromBitSet(i,o.BitSet.create(n.rowCount,(()=>!1)))),n.columns.byName(s)||n.columns.add(o.Column.fromStrings(s,Array.from({length:n.rowCount},(()=>""))));const c=()=>o.DataFrame.fromColumns([o.Column.fromStrings(s,[]),o.Column.fromInt32Array(r,new Int32Array([])),o.Column.fromStrings("Actions",[]),o.Column.fromBitSet(u,o.BitSet.create(0,(()=>!1)))]),d=o.Viewer.grid(c());d.root.style.width="100%",d.root.style.minWidth="230px",d.columns.setVisible([s,r,"Actions"]),this.root.append(e.divV([e.divV([d.root],{style:{height:"75%"}})],{style:{height:"100%"}}));const p=()=>{var t,e;if(!d.dataFrame)return;null===(t=n.col(i))||void 0===t||t.markers.assign("true",o.MARKER_TYPE.OUTLIER);const r=null===(e=d.dataFrame)||void 0===e?void 0:e.cell(d.dataFrame.rowCount-1,s).value;n.selection.getSelectedIndexes().forEach((t=>{n.col(i).set(t,!0,!1),n.col(s).set(t,r,!1)})),n.selection.setAll(!1),n.fireValuesChanged(),a()(l()).empty()},h=()=>{d.dataFrame&&(d.dataFrame.rows.removeAt(d.dataFrame.rowCount-1),n.selection.setAll(!1),a()(l()).empty())};d.onCellPrepare((t=>{var o,r,a;t.isTableCell&&("Actions"===t.gridColumn.name&&(t.gridColumn.cellType="html",t.style.element=e.divH([...(null===(o=t.grid.dataFrame)||void 0===o?void 0:o.get(u,t.gridRow))?[(a=null===(r=t.grid.dataFrame)||void 0===r?void 0:r.get(s,t.gridRow),e.div(e.icons.delete((()=>{for(let t=0;t<n.rowCount;t++)n.columns.byName(s).get(t)===a&&(n.columns.byName(s).set(t,"",!1),n.columns.byName(i).set(t,!1,!1));n.fireValuesChanged()}),"Remove the outliers group"),{style:{"text-align":"center",margin:"6px"}}))]:[e.div(e.iconFA("check",p,"Confirm the outliers"),{style:{"text-align":"center",margin:"6px"}}),e.div(e.iconFA("times",h,"Cancel the outliers"),{style:{"text-align":"center",margin:"6px"}})]])))})),d.onCellValueEdited.subscribe((t=>{var e,i;if(!d.dataFrame||t.gridColumn.name!==s)return;if(!d.dataFrame.columns.byName(u).get(t.gridRow))return;const o=new Set;for(let t=0;t<(null===(e=d.dataFrame)||void 0===e?void 0:e.rowCount);t++){const e=null===(i=d.dataFrame)||void 0===i?void 0:i.columns.byName(s).get(t);o.add(e)}for(let e=0;e<n.rowCount;e++){const i=n.columns.byName(s).get(e);""==i||o.has(i)||n.columns.byName(s).set(e,t.cell.value)}}));const f=()=>{if(n.columns.byName(s))for(let t=0;t<n.rowCount;t++)n.columns.byName(i).get(t)?""===n.columns.byName(s).get(t)&&n.columns.byName(s).set(t,"Manual",!1):""!==n.columns.byName(s).get(t)&&n.columns.byName(s).set(t,"",!1);const t={};if(n.columns.byName(s))for(let e=0;e<n.rowCount;e++){const i=n.columns.byName(s).get(e),o=t[i];""!=i&&(o?t[i]++:t[i]=1)}d.dataFrame=c(),d.columns.setVisible([s,r,"Actions"]),Object.keys(t).map((e=>{var n;null===(n=d.dataFrame)||void 0===n||n.rows.addNew([e,t[e],"",!0])}))};n.onDataChanged.subscribe(f),n.onSelectionChanged.subscribe((()=>{if(!d.dataFrame||!n.selection.trueCount)return;const i=l();if(i&&!a()(i).is(":empty")||t.shell.info(e.div([e.divText("Confirm selected points as outliers?"),e.divH([e.bigButton("Confirm",p),e.button("Cancel",h)])])),d.dataFrame.columns.byName(u).toList().some((t=>!1===t)))d.dataFrame.set(r,d.dataFrame.rowCount-1,n.selection.trueCount);else{const t=d.dataFrame.rows.addNew(["Manual",n.selection.trueCount,"",!1]);d.dataFrame.currentCell=d.dataFrame.cell(t.idx,s)}})),n.selection.setAll(!1),f()}}const c=rxjs,d=dayjs;var p=n.n(d);const h=wu;var f=n.n(h);const m={barchart:o.VIEWER.BAR_CHART,boxplot:o.VIEWER.BOX_PLOT,calendar:o.VIEWER.CALENDAR,corrplot:o.VIEWER.CORR_PLOT,densityplot:o.VIEWER.DENSITY_PLOT,filters:o.VIEWER.FILTERS,form:o.VIEWER.FORM,globe:o.VIEWER.GLOBE,googlemap:o.VIEWER.GOOGLE_MAP,grid:o.VIEWER.GRID,heatmap:o.VIEWER.HEAT_MAP,histogram:o.VIEWER.HISTOGRAM,linechart:o.VIEWER.LINE_CHART,markup:o.VIEWER.MARKUP,matrixplot:o.VIEWER.MATRIX_PLOT,networkdiagram:o.VIEWER.NETWORK_DIAGRAM,pcplot:o.VIEWER.PC_PLOT,piechart:o.VIEWER.PIE_CHART,scatterplot:o.VIEWER.SCATTER_PLOT,"3dscatterplot":o.VIEWER.SCATTER_PLOT_3D,shapemap:o.VIEWER.SHAPE_MAP,statistics:o.VIEWER.STATISTICS,tileviewer:o.VIEWER.TILE_VIEWER,timelines:o.VIEWER.TIMELINES,treemap:o.VIEWER.TREE_MAP,trellisplot:o.VIEWER.TRELLIS_PLOT,wordcloud:o.VIEWER.WORD_CLOUD},v="JsCardView",g="viewer",y="restrictedValues",b="editState";var w;!function(t){t.INPUT="Input",t.OUTPUT="Output"}(w||(w={}));const A="experimental",C="Run name",I="RunId";var S,T;!function(t){t.HIDDEN="hidden",t.VISIBLE="visible"}(S||(S={})),function(t){t.ENABLED="enabled",t.DISABLED="disabled"}(T||(T={}));const E="ModelStorage",x="Source",R="Is favorite",O="Is complete",P="Delete",k="Author",F="Date",L="Title",N="Desc.",B="Tags";function M(t){return t&&t.root&&t.onInput}function _(t){return(null==t?void 0:t.setValidation)&&M(t)}function D(t){return(null==t?void 0:t.setDisabled)&&(null==t?void 0:t.setRestricted)&&(null==t?void 0:t.setRestrictedUnlocked)&&(null==t?void 0:t.setInconsistent)&&(null==t?void 0:t.setUserInput)&&M(t)}function V(t){var e;return!(null===(e=null==t?void 0:t.errors)||void 0===e?void 0:e.length)&&!(null==t?void 0:t.pending)}function j(t,e){return{description:t,actions:e}}function H(t){if(null==t?void 0:t.errors)return t.errors.map((t=>t.description)).join("; ")}function U(t){var e,n,i;const o=t=>"string"==typeof t?j(t):t;return{errors:null===(e=null==t?void 0:t.errors)||void 0===e?void 0:e.map((t=>o(t))),warnings:null===(n=null==t?void 0:t.warnings)||void 0===n?void 0:n.map((t=>o(t))),notifications:null===(i=null==t?void 0:t.notifications)||void 0===i?void 0:i.map((t=>o(t)))}}function Y(...t){var e,n,i,o,s;const r=[],a=[],l=[],u=[];let c={};for(const d of t)d&&(r.push(...null!==(e=d.errors)&&void 0!==e?e:[]),a.push(...null!==(n=d.warnings)&&void 0!==n?n:[]),l.push(...null!==(i=d.notifications)&&void 0!==i?i:[]),u.push(...null!==(o=d.revalidate)&&void 0!==o?o:[]),c=Object.assign(Object.assign({},c),null!==(s=d.context)&&void 0!==s?s:{}));return{errors:r,warnings:a,notifications:l,revalidate:u,context:c}}function W(t,n,i){if(i&&n){for(function(t,e){const n=t.getBoundingClientRect().toJSON();e.style.inset="unset",e.style.top=n.y+"px",e.style.left=n.x+20+"px"}(n,i);i.firstChild&&i.removeChild(i.firstChild););const o=function(t){var n;const i=e.divV([],{style:{gap:"10px"}});for(const o of["errors","warnings","notifications"]){const s=t[o];if(null==s?void 0:s.length)for(const t of s){const s=G(o);s.style.marginRight="4px",i.appendChild(e.divV([e.divH([s,e.span([t.description])]),...(null!==(n=t.actions)&&void 0!==n?n:[]).map((t=>e.link(t.actionName,t.action,void 0,{style:{paddingLeft:"20px"}})))]))}}return i}(t);i.appendChild(o),i.showPopover()}}function G(t){let n;return"errors"===t?(n=e.iconFA("exclamation-circle"),n.style.color="var(--red-3)"):"warnings"===t?(n=e.iconFA("exclamation-circle"),n.style.color="var(--orange-2)"):"notifications"===t&&(n=e.iconFA("info-circle"),n.style.color="var(--blue-1)"),n&&(n.classList.remove("fal"),n.classList.add("far")),n}var z=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const q=e=>z(void 0,void 0,void 0,(function*(){const n=(yield t.functions.eval(e.func.nqName)).prepare([...e.inputs].reduce(((t,[e,n])=>(t[e]=n,t)),{}));return e.options.forEach((t=>n.options[t]=e.options[t])),n})),J=t=>!K(t)||!t.id,K=t=>{try{return t.started}catch(t){return null}},Z=(e,n)=>{var i,o,s,r,a,l,u;if(n===k)return null!==(o=null===(i=e.author)||void 0===i?void 0:i.friendlyName)&&void 0!==o?o:t.shell.user.friendlyName;const c=null!==(l=null!==(a=null!==(r=null!==(s=e[n])&&void 0!==s?s:e.inputs[n])&&void 0!==r?r:e.outputs[n])&&void 0!==a?a:e.options[n])&&void 0!==l?l:null;return null!==(u=null==c?void 0:c.toString())&&void 0!==u?u:""},X=t=>t.options.mainParams?JSON.parse(t.options.mainParams):null;function Q(t){const e=t;return e.dart&&o.toJs(e.dart)instanceof o.InputBase}const tt=t=>{const e=t.clone();t.options.forEach((n=>e.options[n]=t.options[n]));const n=f()(t.outputParams.values()).filter((e=>e.property.propertyType===o.TYPE.DATA_FRAME&&!!t.outputs[e.name]));for(const i of n)e.outputs[i.name]=t.outputs[i.name].clone();const i=f()(t.inputParams.values()).filter((e=>e.property.propertyType===o.TYPE.DATA_FRAME&&!!t.inputs[e.name]));for(const n of i)e.inputs[n.name]=t.inputs[n.name].clone();return e},et=t=>{const e=t.options[g];return void 0!==e?{name:t.name,config:JSON.parse(e,((t,e)=>{if("true"===e)return!0;if("false"===e)return!1;if("type"===t)return m[e]||e;if(!t.toLowerCase().includes("color")){const t=Number.parseFloat(e);if(!Number.isNaN(t))return t}return e}))}:{name:t.name,config:[]}},nt=(t,e)=>{t.addRow(["Parameter","Value","Units"]).font={bold:!0},e.forEach((e=>{t.addRow([e.caption,e.value,e.units])})),t.getColumn(1).width=1.2*Math.max(...e.map((t=>t.caption.toString().length)),9),t.getColumn(2).width=1.2*Math.max(...e.map((t=>t.value.toString().length)),5),t.getColumn(3).width=1.2*Math.max(...e.map((t=>t.units.toString().length)),5)};let it=0;const ot=(t,e,n,i)=>{const o=t.getColumn(null!=n?n:1).letter,s={name:`ID_${it.toString()}`,ref:`${o}${null!=i?i:1}`,columns:e.columns.toList().map((t=>({name:t.name,filterButton:!1}))),rows:new Array(e.rowCount).fill(0).map(((t,n)=>[...e.row(n).cells].map((t=>t.value))))};t.addTable(s),t.columns.forEach((t=>{t.width=25,t.alignment={wrapText:!0}})),it++},st=(t,e,n,i,...s)=>z(void 0,[t,e,n,i,...s],void 0,(function*(t,e,n,i,s=0){yield o.Utils.loadJsCss(["/js/common/html2canvas.min.js"]);const r=window.html2canvas,a=yield r(n,{logging:!1}),l=a.toDataURL("image/png"),u=t.addImage({base64:l,extension:"png"});e.addImage(u,{tl:{col:i,row:s},ext:{width:a.width,height:a.height}})}));function rt(t,e){return z(this,void 0,void 0,(function*(){const n={};for(const[i,o]of Object.entries(t.inputs)){const{property:t}=e.funcCall.inputParams[i];n[i]=yield at(t,o,e)}return{inputs:n,outputs:t.outputs}}))}function at(t,e,n){return z(this,void 0,void 0,(function*(){return"file"===t.propertyType&&n.getInput?n.getInput(t.name).value.arrayBuffer():e}))}function lt(t,e){return z(this,void 0,void 0,(function*(){return"file"===t?new File([e],""):e}))}var ut=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const ct=t=>{switch(t){case"Today":return"started > -1d";case"Yesterday":return"started > -2d and started < -1d";case"Any time":return"";case"Last year":return"started > -2y and started < -1y";case"This year":return"started > -1y";case"Last month":return"started > -2m and started < -1m";case"This month":return"started > -1m";case"Last week":return"started > -2w and started < -1w";case"This week":return"started > -1w"}};var dt;!function(e){const n={},i=new o.LruCache;function s(e){return ut(this,arguments,void 0,(function*(e,i=!0){var o;const s=e.func.id,r=t.dapi.functions.include("package").allPackageVersions().find(s),a=i&&null!==(o=n[s])&&void 0!==o?o:yield r;n[s]||(n[s]=a),e.func=a}))}function r(e){return ut(this,arguments,void 0,(function*(e,n=!1){const i=yield t.dapi.functions.calls.allPackageVersions().include("session.user, inputs, outputs").find(e);if(yield s(i),!n){const e=f()(i.outputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!i.outputs[t.name]));yield Promise.all(e.map((e=>ut(this,void 0,void 0,(function*(){return i.outputs[e.name]=yield t.dapi.tables.getTable(i.outputs[e.name]),Promise.resolve()})))));const n=f()(i.inputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!i.inputs[t.name]));yield Promise.all(n.map((e=>ut(this,void 0,void 0,(function*(){return i.inputs[e.name]=yield t.dapi.tables.getTable(i.inputs[e.name]),Promise.resolve()})))))}return i}))}e.augmentCallWithFunc=s,e.loadChildRuns=function(e){return ut(this,void 0,void 0,(function*(){const n=yield r(e);yield s(n);const i=yield t.dapi.functions.calls.allPackageVersions().include("func").filter(`options.parentCallId="${e}"`).list();return yield Promise.all(i.map((t=>ut(this,void 0,void 0,(function*(){return s(t)}))))),{parentRun:n,childRuns:i}}))},e.loadRun=r,e.saveRun=function(e){return ut(this,void 0,void 0,(function*(){let n=i.get("All users");n||(n=yield t.dapi.groups.find(o.Group.defaultGroupsIds["All users"]),i.set("All users",n));const s=tt(e);J(s)&&(s.options.createdOn=p()().unix());const r=f()(s.outputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!s.outputs[t.name]));yield Promise.all(r.map((e=>ut(this,void 0,void 0,(function*(){yield t.dapi.tables.uploadDataFrame(s.outputs[e.name]),yield t.dapi.permissions.grant(s.outputs[e.name].getTableInfo(),n,!1)})))));const a=f()(s.inputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!s.inputs[t.name]));return yield Promise.all(a.map((e=>ut(this,void 0,void 0,(function*(){yield t.dapi.tables.uploadDataFrame(s.inputs[e.name]),yield t.dapi.permissions.grant(s.inputs[e.name].getTableInfo(),n,!1)}))))),yield t.dapi.functions.calls.allPackageVersions().save(s)}))},e.deleteRun=function(e){return ut(this,void 0,void 0,(function*(){e.options.isDeleted=!0,yield t.dapi.functions.calls.allPackageVersions().save(e)}))},e.pullRuns=function(e){return ut(this,arguments,void 0,(function*(e,n={},i={}){let o=`func.id="${e}"`;return o+=n.author?` and session.user.id="${n.author.id}"`:"",o+=n.date?ct(n.date):"",t.dapi.functions.calls.allPackageVersions().filter(o).include("session.user, options").list(i)}))},e.pullRunsByName=function(e){return ut(this,arguments,void 0,(function*(e,n=[],i={},r=[],a=!1){let l="";for(const t of n){const e=[];t.author&&e.push(`session.user.id="${t.author.id}"`),t.date&&e.push(ct(t.date)),t.text&&e.push(`((options.title like "${t.text}") or (options.annotation like "${t.text}"))`),t.includeDeleted||e.push('((options.isDeleted != "true") or (options.isDeleted = null))');const n=e.join(" and ");""!==n&&(l+=""===l?`(${n})`:` or (${n})`)}""!==l&&(l=` and (${l})`);const u=yield t.dapi.functions.calls.allPackageVersions().filter(`func.name="${e}"${l}`).include(`${r.join(",")}`).list(i);for(const t of u)yield s(t);if((r.includes("inputs")||r.includes("func.params"))&&!a)for(const e of u){const n=f()(e.inputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!e.inputs[t.name]));for(const i of n)e.inputs[i.name]=yield t.dapi.tables.getTable(e.inputs[i.name])}if((r.includes("outputs")||r.includes("func.params"))&&!a)for(const e of u){const n=f()(e.outputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!e.outputs[t.name]));for(const i of n)e.outputs[i.name]=yield t.dapi.tables.getTable(e.outputs[i.name])}return u}))}}(dt||(dt={}));var pt=n(72),ht=n.n(pt),ft=n(825),mt=n.n(ft),vt=n(659),gt=n.n(vt),yt=n(56),bt=n.n(yt),wt=n(540),At=n.n(wt),Ct=n(113),It=n.n(Ct),St=n(911),Tt={};Tt.styleTagTransform=It(),Tt.setAttributes=bt(),Tt.insert=gt().bind(null,"head"),Tt.domAPI=mt(),Tt.insertStyleElement=At(),ht()(St.A,Tt),St.A&&St.A.locals&&St.A.locals;var Et=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const xt="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";class Rt extends o.InputBase{get value(){return this.fileValue}set value(t){this.stringValue=(null==t?void 0:t.name)||"Drag-n-drop your file",this.fileValue=t,this.notify&&this.fireInput()}constructor(t="Drag-n-drop here",n=null,i=null,o=xt){super(e.input.string("Input file",{value:""}).dart),this.initialText=t,this.initialValue=n,this.onValueChanged=i,this.fileType=o,this.uploadedFile$=new c.Subject,this.onFileUploaded=this.uploadedFile$,this.fileValue=null,this.isValid=new c.BehaviorSubject(!0),this.hiddenInput=document.createElement("input"),this.icon=e.iconFA("cloud-upload",(()=>this.hiddenInput.click())),this.subscribeOnEvents(),this.root.style.display="flex",this.isValid.subscribe((t=>{if(t){this.input.classList.remove("error"),this.input.classList.add("success");const t=e.iconFA("times",(()=>this.reset()),"Reset uploaded file");this.icon.replaceWith(t),this.icon=t}else{this.input.classList.remove("success"),this.input.classList.add("error");const t=e.iconFA("redo",(()=>this.hiddenInput.click()),"Re-upload a file");this.icon.replaceWith(t),this.icon=t}})),this.uploadedFile$.subscribe((t=>{if(this.onValueChanged&&this.onValueChanged(t),!t){const t=e.iconFA("cloud-upload",(()=>this.hiddenInput.click()),"Choose a file to upload");this.icon.replaceWith(t),this.icon=t}this.value=t})),this.reset()}subscribeOnEvents(){this.input.readOnly=!0,this.input.classList.add("default");const t=t=>Et(this,void 0,void 0,(function*(){if(t&&t.length&&this.enabled){if(t.length>1)throw this.isValid.next(!1),new Error("Please specify single input file");if(this.fileType&&t[0].type!==this.fileType)throw this.isValid.next(!1),new Error("File type is not supported");this.isValid.value?this.uploadedFile$.next(t[0]):this.uploadedFile$.next(null)}}));this.root.classList.add("fi-drop-area"),this.root.style.width="100%",this.hiddenInput.type="file",this.hiddenInput.addEventListener("change",(()=>Et(this,void 0,void 0,(function*(){return yield t(this.hiddenInput.files)}))),!1),["dragenter","dragover","dragleave","drop"].forEach((t=>{this.input.addEventListener(t,(t=>{t.preventDefault(),t.stopPropagation()}),!1)})),["dragenter","dragover"].forEach((t=>{this.input.addEventListener(t,(()=>{this.input.classList.add("drag-n-dropping")}),!1)})),["dragleave","drop"].forEach((t=>{this.input.addEventListener(t,(()=>{this.input.classList.remove("drag-n-dropping")}),!1)})),this.input.addEventListener("drop",(e=>Et(this,void 0,void 0,(function*(){const n=e.dataTransfer.files;t(n)}))),!1),this.input.addEventListener("click",(()=>this.hiddenInput.click()),!1),this.addOptions(this.icon),["drag","dragenter"].forEach((t=>{document.getElementsByClassName("layout-workarea")[0].addEventListener(t,(t=>{t.stopPropagation()}),!1)}))}reset(){this.input.classList.value="ui-input-editor default",this.hiddenInput.value="",this.uploadedFile$.next(null)}}var Ot=n(703),Pt={};Pt.styleTagTransform=It(),Pt.setAttributes=bt(),Pt.insert=gt().bind(null,"head"),Pt.domAPI=mt(),Pt.insertStyleElement=At(),ht()(Ot.A,Pt),Ot.A&&Ot.A.locals&&Ot.A.locals;var kt=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};class Ft extends o.Dialog{constructor(n,i){var s,r,a;super(e.dialog({title:"Edit run metadata"}).dart),this._onMetadataEdit=new c.Subject,this.onMetadataEdit=this._onMetadataEdit.asObservable();let l=null!==(s=n.options.title)&&void 0!==s?s:"",u=null!==(r=n.options.description)&&void 0!==r?r:"",d=i;const p=e.input.string("Title",{value:l,onValueChanged:()=>l=p.value}),h=e.input.string(" ",{value:""}),f=o.TagEditor.create();(null!==(a=n.options.tags)&&void 0!==a?a:[]).forEach((t=>{f.addTag(t)})),h.input.replaceWith(f.root);const m=()=>{""===v.value||f.tags.includes(v.value)||(f.addTag(v.value),v.value="")},v=e.input.string("Tag",{value:""}).addOptions(e.iconFA("plus",m,"Add this tag")),g=(0,c.fromEvent)(v.input,"onkeydown").subscribe((t=>{"Enter"==t.key&&(t.stopPropagation(),m())}));this.sub(g);const y=e.input.string("Description",{value:u,onValueChanged:()=>u=y.value}),b=e.input.bool("Favorites",{value:d,onValueChanged:()=>d=b.value});this.add(e.form([p,y,b,v,h])),this.addButton("Save",(()=>kt(this,void 0,void 0,(function*(){if(""!==v.value)return void t.shell.info(`Dialog has unsaved tags: ${v.value}`);let e="same";d&&!i&&(e="favorited"),!d&&i&&(e="unfavorited");const n={title:""!==l?l:null,description:""!==u?u:null,tags:f.tags.map((t=>t)),favorite:e};this._onMetadataEdit.next(n),this.close()}))))}}class Lt extends o.Dialog{constructor(t){super(e.dialog({title:`Delete ${t.size>1?t.size:""} ${t.size>1?"runs":"run"}`}).dart),this._onFuncCallDelete=new c.Subject,this.onFuncCallDelete=this._onFuncCallDelete.asObservable(),this.add(e.divText(`Deleted ${t.size>1?t.size:""} ${t.size>1?"runs":"run"} ${t.size>1?"are":"is"} impossible to restore. Are you sure?`)),this.onOK((()=>kt(this,void 0,void 0,(function*(){return this._onFuncCallDelete.next(t)}))))}}var Nt=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const Bt=t=>{var e,n;if(null===(e=t.options)||void 0===e?void 0:e.default)return JSON.parse(null===(n=t.options)||void 0===n?void 0:n.default);const i=t.defaultValue;return t.propertyType===o.TYPE.STRING&&i?i.substring(1,i.length-1):i};function Mt(t,n){n?(a()(t).addClass("ui-box").css({width:"auto",height:"auto"}),e.setUpdateIndicator(t,!0)):(e.setUpdateIndicator(t,!1),a()(t).removeClass("ui-box"))}const _t=t=>{const e=t.clone(),n=f()(t.outputParams.values()).filter((e=>e.property.propertyType===o.TYPE.DATA_FRAME&&!!t.outputs[e.name]));for(const i of n)e.outputs[i.name]=t.outputs[i.name].clone();const i=f()(t.inputParams.values()).filter((e=>e.property.propertyType===o.TYPE.DATA_FRAME&&!!t.inputs[e.name]));for(const n of i)e.inputs[n.name]=t.inputs[n.name].clone();return e},Dt=t=>{const e=t.options[g];return void 0!==e?{name:t.name,config:JSON.parse(e,((t,e)=>{if("true"===e)return!0;if("false"===e)return!1;if("type"===t)return m[e]||e;if(!t.toLowerCase().includes("color")){const t=Number.parseFloat(e);if(!Number.isNaN(t))return t}return e}))}:{name:t.name,config:[]}},Vt=t=>{try{return t.started.toDate().toLocaleString("en-us",{month:"short",day:"numeric",hour:"numeric",minute:"numeric"})}catch(t){return"Not completed"}};var jt=n(826),$t=n.n(jt),Ht=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};p().extend($t());const Ut=Object.values(o.COLUMN_TYPE).filter((t=>t!==o.TYPE.DATA_FRAME)),Yt=t=>t.replace(/([A-Z])/g,(t=>` ${t.toLowerCase()}`)).trim().replace(/^./,(t=>t.toUpperCase())),Wt=new o.LruCache;class Gt extends o.Widget{storageName(t){return`${E}_${[...t.values()][0].func.name}_Fav`}get onRunsDfChanged(){return this._onRunsDfChanged.asObservable()}get onChosen(){return this._onChosen.asObservable()}get chosen(){return this._onChosen.value}set chosen(t){var e;this.chosenById=null!==(e=null==t?void 0:t.id)&&void 0!==e?e:null}set chosenById(t){if(t){for(let e=0;e<this.currentDf.rowCount;e++)if(this.currentDf.getCol(Jt).get(e)===t){this.currentDf.currentRowIdx=e;break}}else this.currentDf.currentRowIdx=-1}get selected(){return this._onSelectedChanged.value}get runs(){return this.onRunsChanged.value}get onSelectedChanged(){return this._onSelectedChanged.asObservable()}saveIsFavorite(e,n){return Ht(this,void 0,void 0,(function*(){const i=`${E}_${e.func.name}_Fav`;return n?t.dapi.userDataStorage.postValue(i,e.id,""):t.dapi.userDataStorage.remove(i,e.id)}))}getRunByIdx(t){return this.runs.get(this.currentDf.get(Jt,t))}showEditDialog(e,n){const i=new Ft(e,n),o=i.onMetadataEdit.subscribe((n=>Ht(this,void 0,void 0,(function*(){var i;if(null===(i=this.options)||void 0===i?void 0:i.isHistory)return("same"!==n.favorite?this.saveIsFavorite(e,"favorited"===n.favorite):Promise.resolve()).then((()=>dt.loadRun(e.id,!1))).then((t=>(n.title&&(t.options.title=n.title),n.description&&(t.options.description=n.description),n.tags&&(t.options.tags=n.tags),[dt.saveRun(t),t]))).then((([,t])=>{this.updateRun(t),this.onMetadataEdit.next(t),o.unsubscribe()})).catch((e=>{t.shell.error(e)}));this.updateRun(e)}))));i.show({center:!0,width:500})}visibleProps(t){var e,n,i;return null!==(i=null!==(n=null===(e=this.options)||void 0===e?void 0:e.visibleProps)&&void 0!==n?n:X(t))&&void 0!==i?i:t.inputs.filter((t=>Ut.includes(t.propertyType))).map((t=>t.name))}constructor(n,i){var r,l,u,d,h,m,v;super(e.div([],{style:{height:"100%",width:"100%"}})),this.initialRuns=n,this.options=i,this.onRunsChanged=new c.BehaviorSubject(this.initialRuns.reduce(((t,e)=>(t.set(e.id,e),t)),new Map)),this._onRunsDfChanged=new c.BehaviorSubject(o.DataFrame.fromColumns([o.Column.bool(x,0),...(null===(r=this.options)||void 0===r?void 0:r.isHistory)?[o.Column.bool(R,0)]:[],...(null===(l=this.options)||void 0===l?void 0:l.showActions)?[o.Column.string(P,0)]:[],o.Column.bool(O,0),o.Column.dateTime(F,0),o.Column.string(k,0),o.Column.string(B,0),o.Column.string(L,0),o.Column.string(N,0),o.Column.fromStrings(Jt,[])])),this._historyFilters=o.Viewer.filters(this._onRunsDfChanged.value,{title:"Filters",columnNames:[]}),this._historyGrid=o.Viewer.grid(this._onRunsDfChanged.value,{showRowHeader:!1,showColumnGridlines:!1,allowEdit:!1}),this.onComparisonCalled=new c.Subject,this.onMetadataEdit=new c.Subject,this._onChosen=new c.BehaviorSubject(null),this.onDelete=new c.Subject,this._onSelectedChanged=new c.BehaviorSubject(new Set([])),this.layout=e.splitH([],null,!0),this.defaultGridText=e.divText(null!==(d=null===(u=this.options)||void 0===u?void 0:u.fallbackText)&&void 0!==d?d:"No historical runs found","hp-no-elements-label"),this.defaultFiltersText=e.divText("No filters to show","hp-no-elements-label"),this.filterWithText=e.divH([this.defaultFiltersText,this._historyFilters.root],"ui-box"),this.trashIcon=e.div(e.iconFA("trash-alt",(()=>{const n=this.currentDf.selection.getSelectedIndexes(),i=new Set;n.forEach((t=>i.add(this.getRunByIdx(t))));const o=new Lt(i);o.onFuncCallDelete.pipe((0,s.take)(1)).subscribe((n=>Ht(this,void 0,void 0,(function*(){e.setUpdateIndicator(this.root,!0);try{yield Promise.all(f()(n.values()).map((t=>Ht(this,void 0,void 0,(function*(){return yield this.deleteRun(t.id),Promise.resolve()})))))}catch(e){t.shell.error(e)}finally{e.setUpdateIndicator(this.root,!1)}})))),o.show({center:!0,width:500,modal:!0})}),"Delete selected runs"),{style:{"padding-top":"5px"}}),this.compareIcon=e.div(e.iconFA("exchange",(()=>Ht(this,void 0,void 0,(function*(){const t=this.currentDf.selection.getSelectedIndexes(),e=[];t.forEach((t=>{e.push(this.currentDf.getCol(Jt).get(t))})),this.onComparisonCalled.next(e)}))),"Compare selected runs"),{style:{"padding-top":"5px"}}),this._isFilterHidden=new c.BehaviorSubject(!1),this.showFiltersIcon=e.div(e.iconFA("filter",(()=>{this._isFilterHidden.next(!this._isFilterHidden.value)}),"Toggle filters"),{style:{"padding-top":"4px"}}),this._compactMode=new c.BehaviorSubject(null!==(m=null===(h=this.options)||void 0===h?void 0:h.isHistory)&&void 0!==m&&m),this.toggleCompactMode=e.div(e.iconFA("expand-alt",(()=>{this.compactMode=!this.compactMode}),"Toggle compact mode"),{style:{"padding-top":"4px"}}),this.showMetadataIcon=e.input.toggle("Metadata",{value:!0,onValueChanged:()=>{this.styleHistoryGrid(),this.styleHistoryFilters()}}),this.showInputsIcon=e.input.toggle("Params",{value:!1,onValueChanged:()=>Ht(this,void 0,void 0,(function*(){var t;const e=this.showInputsIcon.value;0!==this.runs.size&&(e&&(null===(t=this.options)||void 0===t?void 0:t.isHistory)?((yield Promise.all([...this.runs.values()].map((t=>Ht(this,void 0,void 0,(function*(){if(Wt.has(t.id))return Wt.get(t.id);{const e=yield dt.loadRun(t.id,!0);return Wt.set(e.id,e),e}})))))).forEach((t=>{this.runs.set(t.id,t)})),this.onRunsChanged.next(this.runs)):(this.styleHistoryGrid(),this.styleHistoryFilters()))}))});const g=e.divH([e.divH([...(null==i?void 0:i.isHistory)?[this.toggleCompactMode]:[],this.showFiltersIcon,this.showMetadataIcon.root,this.showInputsIcon.root],{style:{gap:"5px",padding:"5px"}}),e.divH((null===(v=this.options)||void 0===v?void 0:v.showBatchActions)?[this.trashIcon,this.compareIcon]:[],{style:{gap:"5px",padding:"5px"}})],{style:{"justify-content":"space-between",padding:"0px 5px"}});g.style.setProperty("overflow-y","hidden","important");const y=e.divV([this.defaultGridText,g,this._historyGrid.root],"ui-box");a()(y).removeClass("ui-div"),a()(y).css("width","100%"),this.root.appendChild(this.layout),e.setDisplayAll([this._historyGrid.root,this._historyFilters.root,this.toggleCompactMode,this.trashIcon,this.compareIcon,this.showFiltersIcon],!1),this.setGridCellRendering();const b=this.onRunsChanged.subscribe((n=>Ht(this,void 0,void 0,(function*(){var i,s,r;const a=[...n.values()],l=t=>{var e,n;return t.propertyType===o.TYPE.DATE_TIME?o.Column.dateTime(null!==(e=t.caption)&&void 0!==e?e:Yt(t.name),a.length).init((e=>window.grok_DayJs_To_DateTime(a[e].inputs[t.name]))):o.Column.fromType(t.propertyType,null!==(n=t.caption)&&void 0!==n?n:Yt(t.name),a.length).init((e=>{var n,i,o,s;return null!==(s=null===(o=null===(i=null===(n=this.options)||void 0===n?void 0:n.propFuncs)||void 0===i?void 0:i[t.name])||void 0===o?void 0:o.call(i,a[e]))&&void 0!==s?s:Z(a[e],t.name)}))},u=t=>t===F?o.Column.dateTime(Yt(t),a.length).init((t=>window.grok_DayJs_To_DateTime(K(a[t])?a[t].started.utc(!0):p().unix(a[t].options.createdOn)))):t===O?o.Column.bool(Yt(t),a.length).init((t=>K(a[t]))):o.Column.fromStrings(Yt(t),a.map((e=>{var n,i,o,s;return null!==(s=null===(o=null===(i=null===(n=this.options)||void 0===n?void 0:n.propFuncs)||void 0===i?void 0:i[t])||void 0===o?void 0:o.call(i,e))&&void 0!==s?s:Z(e,t)})));if(console.log(a),a.length>0){const c=null!==(i=yield t.dapi.userDataStorage.get(this.storageName(n)))&&void 0!==i?i:{},d=Object.keys(c),p=a[0].func,h=t=>{var e;const n=null!==(e=p.inputs.find((e=>e.name===t)))&&void 0!==e?e:p.outputs.find((e=>e.name===t));return n?l(n):u(t)},f=o.DataFrame.fromColumns([o.Column.string(x,a.length).init((t=>{const e=a[t].options.immutable_tags;return e&&e.includes(A)?"Experimental":"Simulated"})),...(null===(s=this.options)||void 0===s?void 0:s.isHistory)?[o.Column.bool(R,a.length).init((t=>d.includes(a[t].id)))]:[],...(null===(r=this.options)||void 0===r?void 0:r.showActions)?[o.Column.string(P,a.length).init("")]:[],u(F),u(O),u(k),o.Column.string(B,a.length).init((t=>a[t].options.tags?a[t].options.tags.join(","):"")),o.Column.string(L,a.length).init((t=>a[t].options.title)),o.Column.string(N,a.length).init((t=>a[t].options.description))]);this.visibleProps(p).map((t=>h(t))).forEach((t=>{t.name=f.columns.getUnusedName(t.name),f.columns.add(t,!1)})),f.columns.add(o.Column.fromStrings(Jt,a.map((t=>t.id)))),e.setDisplayAll([this.defaultGridText,this.defaultFiltersText],!1),e.setDisplayAll([this._historyGrid.root,this._historyFilters.root,this.toggleCompactMode,this.showMetadataIcon.root,this.trashIcon,this.compareIcon,this.showFiltersIcon],!0),e.setDisplay(this.showInputsIcon.root,this.visibleProps(p).length>0),this._onRunsDfChanged.next(f)}else e.setDisplayAll([this.defaultGridText,this.defaultFiltersText],!0),e.setDisplayAll([this._historyGrid.root,this._historyFilters.root,this.showMetadataIcon.root,this.showInputsIcon.root,this.toggleCompactMode,this.trashIcon,this.compareIcon,this.showFiltersIcon],!1)})))),w=this._onRunsDfChanged.subscribe((t=>{this._historyFilters.dataFrame=t,this._historyGrid.dataFrame=t,this.currentDf.getCol(B).setTag(o.TAGS.MULTI_VALUE_SEPARATOR,","),this.styleHistoryGrid(),this.styleHistoryFilters();const e=t.onCurrentRowChanged.subscribe((()=>{var t;this.currentDf.rows.select((()=>!1)),this._onChosen.next(null!==(t=this.getRunByIdx(this.currentDf.currentRowIdx))&&void 0!==t?t:null)})),n=t.onSelectionChanged.subscribe((()=>{const e=[...t.selection.getSelectedIndexes()].map((t=>this.getRunByIdx(t)));this._onSelectedChanged.next(new Set(e)),this.redrawSelectionState()}));this.redrawSelectionState(),this.subs.push(e,n)})),C=this._isFilterHidden.subscribe((t=>{t?(a()(this.showFiltersIcon.firstChild).addClass("fal"),a()(this.showFiltersIcon.firstChild).removeClass("fad"),e.setDisplay(this.filterWithText,!1)):(a()(this.showFiltersIcon.firstChild).addClass("fad"),a()(this.showFiltersIcon.firstChild).removeClass("fal"),a()(this.filterWithText).css(this.compactMode?"height":"width","320px"),a()(this.filterWithText).css(this.compactMode?"width":"height","100%"),e.setDisplay(this.filterWithText,!0))})),I=this._compactMode.subscribe((t=>{const n=[y,this.filterWithText];a()(this.filterWithText).removeClass("ui-div");const i={style:{width:"100%",height:"100%"}};a()(this.toggleCompactMode.firstChild).addClass(t?"fa-expand-alt":"fa-compress-alt"),a()(this.toggleCompactMode.firstChild).removeClass(t?"fa-compress-alt":"fa-expand-alt");const o=t?e.splitV(n,i,!0):e.splitH(n,i,!0);this.layout.replaceWith(o),this.layout=o,e.tools.waitForElementInDom(this.layout).then((t=>{a()(t).css(this.compactMode?"height":"width","100%"),a()(this._historyFilters.root).css(Object.assign({},this.compactMode?{width:"100%"}:{height:"100%"})),a()(this.filterWithText).css(Object.assign({},this.compactMode?{height:"310px",width:"100%"}:{width:"310px",height:"100%"})),a()(y).css(Object.assign({},this.compactMode?{width:"100%"}:{height:"100%"})),setTimeout((()=>{this.styleHistoryGrid(),this.styleHistoryFilters()}),100)}))}));this.subs.push(b,I,w,C)}setGridColumnsRendering(){const t=this._historyGrid.columns.byName(P);t&&(t.cellType="html",t.width=35);const e=this._historyGrid.columns.byName(R);e&&(e.cellType="html",e.width=20);const n=this._historyGrid.columns.byName(x);n.cellType="html",n.width=20;const i=this._historyGrid.columns.byName(B);i.cellType="html",i.width=90,this._historyGrid.columns.byName(F).width=110,this._historyGrid.columns.byName(Jt).cellType="html"}isFavoriteByIndex(t){return this.currentDf.get(R,t)}setGridCellRendering(){this._historyGrid.onCellPrepare((n=>{var i,o,r,l,u,c,d,p,h,m,v;if(n.isColHeader&&(null===(i=n.tableColumn)||void 0===i?void 0:i.name)&&[P,x,R].includes(n.tableColumn.name)&&(n.customText=""),!n.isColHeader){if((null===(o=n.tableColumn)||void 0===o?void 0:o.name)===P){n.customText="";const i=this.getRunByIdx(n.tableRowIndex);n.element=e.divH([e.iconFA("trash",(()=>{const i=new Set([this.getRunByIdx(n.tableRowIndex)]),o=new Lt(i);o.onFuncCallDelete.pipe((0,s.take)(1)).subscribe((()=>Ht(this,void 0,void 0,(function*(){e.setUpdateIndicator(this.root,!0);try{yield Promise.all(f()(i.values()).map((t=>Ht(this,void 0,void 0,(function*(){return yield this.deleteRun(t.id),Promise.resolve()})))))}catch(e){t.shell.error(e)}finally{e.setUpdateIndicator(this.root,!1)}})))),o.show({center:!0,width:500})}),"Remove run from history"),e.iconFA("edit",(()=>this.showEditDialog(i,this.isFavoriteByIndex(n.tableRowIndex))),"Edit run metadata")],{style:{padding:"6px 0px",gap:"6px","justify-content":"space-between"}})}if((null===(r=n.tableColumn)||void 0===r?void 0:r.name)===R){n.customText="";const t=this.getRunByIdx(n.tableRowIndex),i=e.iconFA("star",(()=>this.saveIsFavorite(t,!1).then((()=>this.updateRun(t)))),"Unfavorite");a()(i).addClass("fas"),n.element=e.div(n.cell.value?i:e.iconFA("star",(()=>this.saveIsFavorite(t,!0).then((()=>this.updateRun(t)))),"Favorite"),{style:{padding:"5px 0px"}})}if((null===(l=n.tableColumn)||void 0===l?void 0:l.name)===x){n.customText="";const t=e.iconFA("flask",null,"Experimental run");a()(t).addClass("fad fa-sm"),a()(t).removeClass("fal"),n.element=n.cell.value&&"Experimental"===n.cell.value?e.div(t,{style:{padding:"5px"}}):e.div()}if((null===(u=n.tableColumn)||void 0===u?void 0:u.name)===B){n.customText="";const t=n.cell.value.length>0?e.div(null===(c=n.cell.value)||void 0===c?void 0:c.split(",").map((t=>e.span([t],"d4-tag"))),"d4-tag-editor"):e.div();a()(t).css({padding:"3px","background-color":"transparent"}),n.element=t}if((null===(d=n.tableColumn)||void 0===d?void 0:d.name)===Jt){n.customText="";const i=this.getRunByIdx(n.tableRowIndex);if(!i)return;const o=i.author.picture;a()(o).css({width:"25px",height:"25px",fontSize:"20px"}),e.bind(i.author,o);const r=e.iconFA("flask",null,"Experimental run");r.classList.add("fad","fa-sm"),r.classList.remove("fal"),r.style.marginLeft="3px";const l=i.options.immutable_tags,u=e.span([e.label(null!==(m=null!==(p=i.options.title)&&void 0!==p?p:null===(h=i.author)||void 0===h?void 0:h.friendlyName)&&void 0!==m?m:t.shell.user.friendlyName,{style:{color:"var(--blue-1)"}}),...l&&l.includes(A)?[r]:[]]),c=e.iconFA("edit",(t=>{t.stopPropagation(),this.showEditDialog(i,this.isFavoriteByIndex(n.tableRowIndex))}),"Edit run metadata");c.classList.add("hp-funccall-card-icon","hp-funccall-card-hover-icon");const d=e.iconFA("trash-alt",(i=>Ht(this,void 0,void 0,(function*(){i.stopPropagation();const o=new Set([this.getRunByIdx(n.tableRowIndex)]),r=new Lt(o);r.onFuncCallDelete.pipe((0,s.take)(1)).subscribe((()=>Ht(this,void 0,void 0,(function*(){e.setUpdateIndicator(this.root,!0);try{yield Promise.all(f()(o.values()).map((t=>Ht(this,void 0,void 0,(function*(){return yield this.deleteRun(t.id),Promise.resolve()})))))}catch(e){t.shell.error(e)}finally{e.setUpdateIndicator(this.root,!1)}})))),r.show({center:!0,width:500})}))),"Delete run");d.classList.add("hp-funccall-card-icon","hp-funccall-card-hover-icon");const g=e.iconFA("star",(t=>{t.stopPropagation(),this.saveIsFavorite(i,!1).then((()=>this.updateRun(i)))}),"Unfavorite");g.classList.add("fas","hp-funccall-card-icon");const y=e.iconFA("star",(t=>{t.stopPropagation(),this.saveIsFavorite(i,!0).then((()=>this.updateRun(i)))}),"Favorite");y.classList.add("hp-funccall-card-icon","hp-funccall-card-hover-icon"),this.isFavoriteByIndex(n.tableRowIndex)?(e.setDisplay(y,!1),e.setDisplay(g,!0)):(e.setDisplay(g,!1),e.setDisplay(y,!0));const b=Vt(i),w=e.divH([e.divH([o,e.divV([u,e.span([b]),...i.options.tags&&i.options.tags.length>0?[e.div(i.options.tags.map((t=>e.span([t],"d4-tag"))))]:[]],"hp-card-content")]),e.divH([...(null===(v=this.options)||void 0===v?void 0:v.showActions)?[g,y,c,d]:[]])],"hp-funccall-card"),C=n.tableRowIndex;w.addEventListener("mouseover",(()=>{n.grid.dataFrame.mouseOverRowIdx=C})),w.addEventListener("click",(t=>{t.shiftKey?n.grid.dataFrame.selection.set(C,!0):t.ctrlKey?n.grid.dataFrame.selection.set(C,!1):n.grid.dataFrame.currentRowIdx=C})),n.element=w}}}))}deleteRun(e){return Ht(this,void 0,void 0,(function*(){return dt.loadRun(e,!0).then((t=>Ht(this,void 0,void 0,(function*(){var e;return[yield(null===(e=this.options)||void 0===e?void 0:e.isHistory)?dt.deleteRun(t):Promise.resolve(),t]})))).then((([,t])=>{var n;return this.runs.delete(e),this.onRunsChanged.next(this.runs),(null===(n=this.options)||void 0===n?void 0:n.isHistory)&&this.onDelete.next(t),t})).then((t=>{this.saveIsFavorite(t,!1)})).catch((e=>{t.shell.error(e)}))}))}editRun(t){this.showEditDialog(t,!1)}updateRun(t){this.runs.set(t.id,t),this.onRunsChanged.next(this.onRunsChanged.value)}addRun(t){this.runs.set(t.id,t),this.onRunsChanged.next(this.onRunsChanged.value)}updateRuns(t){this.onRunsChanged.next(t.reduce(((t,e)=>(t.set(e.id,e),t)),new Map))}get isFilterHidden(){return this._isFilterHidden.value}set isFilterHidden(t){this._isFilterHidden.next(t)}get compactMode(){return this._compactMode.value}set compactMode(t){this._compactMode.next(t)}get onCompactModeChanged(){return this._compactMode.asObservable()}styleHistoryGrid(){var t;this._historyGrid.setOptions({showCurrentRowIndicator:!0,showCurrentCellOutline:!1,allowEdit:!1,allowBlockSelection:!1,showRowHeader:!1,showColumnLabels:!this.compactMode,extendLastColumn:this.compactMode}),this._historyGrid.sort([F],[!1]);for(let e=0;e<this._historyGrid.columns.length;e++){const n=this._historyGrid.columns.byIndex(e);n&&(null===(t=n.column)||void 0===t?void 0:t.type)===o.TYPE.DATE_TIME&&(n.format="MMM d, h:mm tt")}if(this.setGridColumnsRendering(),0!==this.runs.size)if(this.compactMode)this._historyGrid.columns.setVisible([Jt]),this._historyGrid.props.rowHeight=70,this._historyGrid.invalidate();else{this._historyGrid.props.rowHeight=28;const t=[...this.runs.values()][0].func,e=this.showMetadataIcon.value,n=this.currentDf.getCol(B);this._historyGrid.columns.setVisible([x,R,P,...e?[F]:[],...e?[k]:[],...e&&n.stats.missingValueCount<n.length?[B]:[],...e?[L]:[],...e?[N]:[],...this.showInputsIcon.value?this.visibleProps(t).map((e=>{var n,i;const o=null!==(n=t.inputs.find((t=>t.name===e)))&&void 0!==n?n:t.outputs.find((t=>t.name===e));return o?null!==(i=o.caption)&&void 0!==i?i:Yt(o.name):Yt(e)})):[]])}}get currentDf(){return this._onRunsDfChanged.value}styleHistoryFilters(){var t,n;if(this.runs.size>0){const i=[...this.runs.values()][0].func,o=this.currentDf.getCol(B),s=this.showMetadataIcon.value,r=[...s&&this.currentDf.getCol(x).categories.length>1?[x]:[],...s&&(null!==(n=null===(t=this.currentDf.col(R))||void 0===t?void 0:t.categories.length)&&void 0!==n?n:0)>1?[R]:[],...s?[F,O]:[],...s&&this.currentDf.getCol(k).categories.length>1?[k]:[],...s&&o.stats.missingValueCount<o.length?[B]:[],...s&&this.currentDf.getCol(L).categories.length>1?[L]:[],...s&&this.currentDf.getCol(N).categories.length>1?[N]:[],...this.showInputsIcon.value?this.visibleProps(i).map((t=>{var e,n;const o=null!==(e=i.inputs.find((e=>e.name===t)))&&void 0!==e?e:i.outputs.find((e=>e.name===t));return o?null!==(n=o.caption)&&void 0!==n?n:Yt(o.name):Yt(t)})).filter((t=>{var e;return!(null===(e=this.options)||void 0===e?void 0:e.isHistory)||this.currentDf.getCol(t).categories.length>1})).map((t=>t)):[]];r.length>0?(a()(this.filterWithText).css({paddingTop:"10px"}),e.setDisplay(this.defaultFiltersText,!1),e.setDisplay(this._historyFilters.root,!0),this._historyFilters.setOptions({columnNames:r,showHeader:!1,showBoolCombinedFitler:!1})):(e.setDisplay(this.defaultFiltersText,!0),e.setDisplay(this._historyFilters.root,!1))}}redrawSelectionState(){const t=this.currentDf.selection.trueCount;t<2?this.compareIcon.firstChild.classList.add("hp-disabled"):this.compareIcon.firstChild.classList.remove("hp-disabled"),0===t?this.trashIcon.firstChild.classList.add("hp-disabled"):this.trashIcon.firstChild.classList.remove("hp-disabled")}}var zt=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};class qt{static getHistoryRuns(e,n=!0){return(0,c.from)((()=>zt(this,void 0,void 0,(function*(){return yield dt.pullRunsByName(e,[{author:t.shell.user}],{order:"started"},["func.params","session.user","options"],n)})))())}}const Jt="ID";class Kt extends o.InputBase{constructor(t,n,i){var o,r;const a=e.input.string(t,{value:""});super(a.dart),this.label=t,this._funcName=n,this.options=i,this.onHistoricalRunChosen=new c.BehaviorSubject(null),this.experimentRunsUpdate=new c.Subject,this.store={experimentRuns:new c.Observable,isExperimentRunsLoading:new c.Subject,experimentRunData:new c.BehaviorSubject("")},this._historyList=new Gt([],{fallbackText:"No runs are found in history",showActions:!1,showBatchActions:!1,isHistory:!1,visibleProps:null===(o=this.options)||void 0===o?void 0:o.mainProps,propFuncs:null===(r=this.options)||void 0===r?void 0:r.propFuncs}),this._historyDialog=this.getHistoryDialog(),this._visibleInput=e.input.string(this.label,{value:""}),this._visibleIcon=e.iconFA("search",(()=>this.showSelectionDialog())),this._chosenRun=null,this._chosenRunId=null,this._visibleInput=a,this._visibleInput.readOnly=!0,this._visibleInput.input.addEventListener("click",(()=>this.showSelectionDialog())),this._visibleInput.addOptions(this._visibleIcon),this.store.experimentRuns=this.experimentRunsUpdate.pipe((0,s.tap)((()=>this.toggleLoaderExpRuns(!0))),(0,s.switchMap)((()=>{var t,e;return qt.getHistoryRuns(this._funcName,null===(e=null===(t=this.options)||void 0===t?void 0:t.skipDfsOnInit)||void 0===e||e).pipe((0,s.catchError)((t=>(console.error(t),c.EMPTY))),(0,s.finalize)((()=>this.toggleLoaderExpRuns(!1))))})),(0,s.shareReplay)(1)),this.store.experimentRuns.subscribe((t=>{this._historyList.updateRuns(t.filter((t=>!J(t))))})),this.store.isExperimentRunsLoading.subscribe((t=>{e.setUpdateIndicator(this._visibleInput.root,t),e.setUpdateIndicator(this._historyList.root,t)})),this.experimentRunsUpdate.next()}setCurrentRow(){this.getValue()?this._historyList.chosen=this.getValue():this.chosenRunId&&(this._historyList.chosenById=this.chosenRunId)}showSelectionDialog(){this.renderGridAndFilters(),this._historyDialog.getButton("OK").disabled=1!==this._historyList.selected.size,this._historyDialog.show({modal:!0,fullScreen:!0,center:!0,width:window.innerWidth-50,height:window.innerHeight-50})}renderGridAndFilters(){var t,e;const n=new Gt([...this._historyList.runs.values()],Object.assign(Object.assign({},this.options),{visibleProps:null===(t=this.options)||void 0===t?void 0:t.mainProps,propFuncs:null===(e=this.options)||void 0===e?void 0:e.propFuncs}));this._historyList.root.replaceWith(n.root),this._historyList=n,this._historyList.onChosen.subscribe((t=>{this._historyDialog.getButton("OK").disabled=!t})),this._historyList.onRunsDfChanged.pipe((0,s.filter)((t=>t.rowCount>0)),(0,s.take)(1)).subscribe((t=>{this.setCurrentRow()}))}getHistoryDialog(){const t=e.dialog();return a()(t.root.querySelector(".d4-dialog-contents")).removeClass("ui-form"),t.onOK((()=>zt(this,void 0,void 0,(function*(){var t,e;let n=this._historyList.chosen;n&&((null===(e=null===(t=this.options)||void 0===t?void 0:t.skipDfsOnInit)||void 0===e||e)&&(n=yield dt.loadRun(n.id,!1)),this.setValue(n)),this.fireInput()})))),t.addButton("Refresh",(()=>{this.experimentRunsUpdate.next()}),2,"Reload list of runs"),t.addButton("Discard",(()=>{this.setValue(null),this.fireInput(),t.close()}),1,"Discard the previous choice"),a()(t.getButton("CANCEL")).hide(),t.add(this._historyList.root),t}setValue(t){var e,n,i,o,s,r,a;this._chosenRun=t,this._chosenRunId=null!==(n=null===(e=this._chosenRun)||void 0===e?void 0:e.id)&&void 0!==n?n:null,this.onHistoricalRunChosen.next(t),this.stringValue=t?(null===(i=this.options)||void 0===i?void 0:i.stringValueFunc)?null===(o=this.options)||void 0===o?void 0:o.stringValueFunc(t):[`${Vt(t)} \\ ${t.author.name}`,(null!==(a=null!==(r=null===(s=this.options)||void 0===s?void 0:s.mainProps)&&void 0!==r?r:X(t.func))&&void 0!==a?a:[]).map((e=>Z(t,e))).join(" \\ ")].join(" \\ "):"No run chosen",this.notify&&this.fireChanged()}getValue(){return this._chosenRun}get chosenRun(){return this._chosenRun}get chosenRunId(){return this._chosenRunId}set chosenRunId(t){this._chosenRunId=t}get root(){return this._visibleInput.root}set stringValue(t){this._visibleInput.value=t,this._visibleInput.setTooltip(this._visibleInput.value)}get stringValue(){return this._visibleInput.value}get iconRoot(){return this._visibleIcon}toggleLoaderExpRuns(t){this.store.isExperimentRunsLoading.next(t)}}class Zt extends Kt{set value(t){this.setValue(t)}get value(){return this.getValue()}}class Xt extends Kt{get value(){const t=this.getValue();return t?JSON.stringify({visualValue:this.stringValue,id:t.id.split("-")}):null}set value(t){this.setValue(null),this.stringValue=t?JSON.parse(t).visualValue:"No run is chosen",this.chosenRunId=t?JSON.parse(t).id.join("-"):""}}var Qt=n(565),te={};te.styleTagTransform=It(),te.setAttributes=bt(),te.insert=gt().bind(null,"head"),te.domAPI=mt(),te.insertStyleElement=At(),ht()(Qt.A,te),Qt.A&&Qt.A.locals&&Qt.A.locals;var ee;class ne extends o.Widget{updateHistoryPane(t){this.historyList.updateRuns(t)}showEditDialog(t){this.historyList.editRun(t)}addRun(t){this.historyList.addRun(t)}get history(){return this.historyList.runs}get onCompactModeChanged(){return this.historyList.onCompactModeChanged}get compactMode(){return this.historyList.compactMode}constructor(n){super(e.box(e.divText("No historical runs loaded","hp-no-elements-label"),{style:{width:"100%",height:"100%"}})),this.func=n,this.onRunChosen=new c.Subject,this.onComparison=new c.Subject,this.afterRunEdited=new c.Subject,this.afterRunDeleted=new c.Subject,this.allRunsFetch=new c.Subject,this.historyList=new Gt([],{fallbackText:"No runs are found in history",showActions:!0,showBatchActions:!0,isHistory:!0}),this.panel=this.historyList.root;const i=this.historyList.onChosen.pipe((0,s.filter)((t=>!!t))).subscribe((t=>this.onRunChosen.next(t.id))),o=this.historyList.onComparisonCalled.subscribe((t=>this.onComparison.next(t))),r=this.allRunsFetch.subscribe((()=>{return n=this,i=void 0,s=function*(){e.setUpdateIndicator(this.root,!0),dt.pullRunsByName(this.func.name,[{author:t.shell.user}],{},["session.user","options"]).then((t=>{e.empty(this.root),this.root.appendChild(this.panel),this.updateHistoryPane(t)})).catch((e=>t.shell.error(e))).finally((()=>e.setUpdateIndicator(this.root,!1)))},new((o=void 0)||(o=Promise))((function(t,e){function r(t){try{l(s.next(t))}catch(t){e(t)}}function a(t){try{l(s.throw(t))}catch(t){e(t)}}function l(e){var n;e.done?t(e.value):(n=e.value,n instanceof o?n:new o((function(t){t(n)}))).then(r,a)}l((s=s.apply(n,i||[])).next())}));var n,i,o,s})),a=this.historyList.onMetadataEdit.subscribe((t=>{this.afterRunEdited.next(t)})),l=this.historyList.onDelete.subscribe((t=>{this.afterRunDeleted.next(t)}));this.subs.push(i,r,a,o,l),this.allRunsFetch.next()}}!function(t){t.fileInput=function(t="Drag-n-drop here",e=null,n=null,i=xt){return new Rt(t,e,n,i)},t.historyInput=function(t,e,n){return new Zt(t,e,n)},t.historyInputJSON=function(t,e,n){return new Xt(t,e,n)},t.historyPanel=function(t){return new ne(t)}}(ee||(ee={}));var ie=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const oe=window;class se extends o.TableView{static fromComparedRuns(n,i){return ie(this,arguments,void 0,(function*(n,i,s={parentView:void 0,parentCall:void 0}){const r=((n,i,s={parentView:void 0,parentCall:void 0})=>{var r,l;const u=i,c=[...u.inputs,...u.outputs].map((t=>Dt(t))).reduce(((t,e)=>(t[e.name]?t[e.name].push(...e.config):t[e.name]=e.config,t)),{}),d=t=>{var e;if(t.propertyType===o.TYPE.DATA_FRAME){const e=c[t.name].map((e=>{var i;let s=null!==(i=t.caption)&&void 0!==i?i:t.name;const r=o.Column.fromType(o.TYPE.DATA_FRAME,s,n.length);r.init((e=>{var i;return null!==(i=n[e].inputs[t.name])&&void 0!==i?i:n[e].outputs[t.name]}));const a=p.columns.getUnusedName(`${r.name} (${e.type})`);return r.name=a,s=a,r.temp[g]=e,p.columns.add(r),r}));return e}{let i=null!==(e=t.caption)&&void 0!==e?e:t.name;const s=o.Column.fromType(t.propertyType,i,n.length);s.init((e=>{var i;return null!==(i=n[e].inputs[t.name])&&void 0!==i?i:n[e].outputs[t.name]}));const r=p.columns.getUnusedName(s.name);return s.name=r,i=r,p.columns.add(s),[s]}},p=o.DataFrame.create(n.length),h=[];return n.forEach((t=>{var e;let n=null!==(e=t.options.title)&&void 0!==e?e:`${t.func.name} - ${Vt(t)}`,i=2;for(;h.includes(n);)n=`${t.func.name} - ${Vt(t)})\n .toLocaleString('en-us', {month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric'})} - ${i}`,i++;h.push(n)})),p.columns.add(o.Column.fromStrings(C,h)),p.name=(null===(r=s.parentCall)||void 0===r?void 0:r.func.name)?`${null===(l=s.parentCall)||void 0===l?void 0:l.func.name} - comparison`:`${i.name} - comparison`,u.inputs.forEach((t=>d(t))),u.outputs.forEach((t=>d(t))),t.events.onCurrentObjectChanged.subscribe((({sender:n})=>{if(n instanceof o.Column&&n.type===o.TYPE.DATA_FRAME&&t.shell.tv&&t.shell.tv.temp.isComparison&&[o.VIEWER.LINE_CHART,o.VIEWER.SCATTER_PLOT,o.VIEWER.HISTOGRAM,o.VIEWER.BOX_PLOT].includes(n.temp[g].type)){t.shell.windows.showProperties=!0;const i=t=>{const e=t.get(0).clone();e.columns.addNew(I,o.TYPE.STRING).init(t.dataFrame.get(C,0));for(let n=1;n<t.length;n++){const i=t.get(n).clone();i.columns.addNew(I,o.TYPE.STRING).init(t.dataFrame.get(C,n));const s=[o.COLUMN_TYPE.INT,o.COLUMN_TYPE.FLOAT];for(let t=0;t<i.columns.length;t++){const n=i.columns.byIndex(t),r=e.columns.byIndex(t);n.type!==r.type&&s.includes(n.type)&&s.includes(r.type)&&(n.type!==o.COLUMN_TYPE.FLOAT&&i.columns.replace(n,n.convertTo(o.COLUMN_TYPE.FLOAT)),r.type!==o.COLUMN_TYPE.FLOAT&&e.columns.replace(r,r.convertTo(o.COLUMN_TYPE.FLOAT)))}e.append(i,!0)}return e},s=n.temp[g].look;setTimeout((()=>{switch(n.temp[g].type){case o.VIEWER.LINE_CHART:const r=e.waitBox((()=>Nt(void 0,void 0,void 0,(function*(){var t;const e=null!==(t=n.temp.unitedDf)&&void 0!==t?t:i(n);return n.temp.unitedDf=e,e.plot.line(Object.assign(Object.assign({},s),{split:I})).root}))));a()(r).css({width:"100%"}),t.shell.o=r;break;case o.VIEWER.SCATTER_PLOT:const l=e.waitBox((()=>Nt(void 0,void 0,void 0,(function*(){var t;const e=null!==(t=n.temp.unitedDf)&&void 0!==t?t:i(n);return n.temp.unitedDf=e,e.plot.scatter(Object.assign(Object.assign({},s),{color:I})).root}))));t.shell.o=l,a()(l).css({width:"100%"});break;case o.VIEWER.HISTOGRAM:const u=e.waitBox((()=>Nt(void 0,void 0,void 0,(function*(){var t;const e=null!==(t=n.temp.unitedDf)&&void 0!==t?t:i(n);return n.temp.unitedDf=e,e.plot.histogram(Object.assign(Object.assign({},s),{split:I})).root}))));t.shell.o=u,a()(u).css({width:"100%"});break;case o.VIEWER.BOX_PLOT:const c=e.waitBox((()=>Nt(void 0,void 0,void 0,(function*(){var t;const e=null!==(t=n.temp.unitedDf)&&void 0!==t?t:i(n);return n.temp.unitedDf=e,e.plot.box(Object.assign(Object.assign({},s),{category:I})).root}))));t.shell.o=c,a()(c).css({width:"100%"})}}))}})),p})(n,i,s),l=[...t.shell.views].find((t=>t.type===v||"scripts"===t.type||"functions"===t.type));return l&&(t.shell.v=l),new this(r,s)}))}constructor(e,n={}){super(oe.grok_TableView(e.dart,!1)),n.parentView&&(this.parentView=n.parentView),this.parentCall=n.parentCall||t.functions.getCurrentCall()}showAllColumns(){const t=this.dataFrame.columns.names();this.grid.columns.setVisible(t)}showChangingColumns(){const t=this.dataFrame.columns.names().filter((t=>o.TYPES_SCALAR.has(this.dataFrame.getCol(t).type)&&this.dataFrame.getCol(t).categories.length>1||!o.TYPES_SCALAR.has(this.dataFrame.getCol(t).type)));this.grid.columns.setVisible(t)}defaultCustomize(){var n;const i=e.iconFA("compress-alt",(()=>{this.showChangingColumns(),a()(s).show(),a()(i).hide()}),"Hide constant parameters"),s=e.iconFA("expand-arrows-alt",(()=>{this.showAllColumns(),a()(s).hide(),a()(i).show()}),"Show all parameters");a()(i).hide(),this.setRibbonPanels([...this.getRibbonPanels(),[i,s]]),this.showChangingColumns(),this.root.style.removeProperty("width"),this.root.firstChild.style.removeProperty("width"),this.root.firstChild.firstChild.style.removeProperty("width"),this.grid.props.rowHeight=180,this.grid.props.showAddNewRowIcon=!1,this.grid.props.allowEdit=!1,this.grid.columns.byName(C).width=70;for(let t=0;t<this.grid.columns.length;t++){const e=this.grid.columns.byIndex(t);(null===(n=e.column)||void 0===n?void 0:n.temp[g])&&(e.width=350,e.cellType="html")}const r=new o.LruCache;this.grid.onCellPrepare((t=>ie(this,void 0,void 0,(function*(){if(!t.isColHeader&&!t.isRowHeader){if(t.tableColumn.name===C){t.customText="";const n=t.cell.value.split(" - "),i=n.length>1?[n[0],e.element("br"),n[1]]:n;return t.element=e.div(i,{style:{"writing-mode":"vertical-rl","text-orientation":"mixed",margin:"auto"}}),void(t.element.parentElement.style.display="flex")}if(t.tableColumn&&t.tableColumn.temp[g]){const e=t.cell.value,n=t.tableColumn.temp[g],i=n.type,s=()=>ie(this,void 0,void 0,(function*(){const s=Object.values(m).includes(i)?o.Viewer.fromType(i,e):yield e.plot.fromType(i);return t.tableColumn.temp[g].look?s.setOptions(t.tableColumn.temp[g].look):(s.setOptions(n),t.tableColumn.temp[g]=s.getOptions()),s.root})),a=`${e.id}_${i}`;if(r.get(a))t.element=r.get(a);else{const e=yield s();r.set(a,e),t.element=e}t.element.style.width="100%",t.element.style.height="100%"}}}))));const l=e.box(e.div([],{style:{"min-height":"100px"}})),u=t.events.onCurrentViewChanged.subscribe((()=>{t.shell.v.id===this.id?t.shell.dockManager.dock(l,"down",null,"Comparison chart",.25):t.shell.dockManager.close(l)})),c=this.grid.onCellClick.subscribe((n=>{var i;if(t.shell.v.id===this.id&&n.isColHeader&&(null===(i=n.tableColumn)||void 0===i?void 0:i.type)===o.TYPE.DATA_FRAME&&[o.VIEWER.LINE_CHART,o.VIEWER.SCATTER_PLOT,o.VIEWER.HISTOGRAM,o.VIEWER.BOX_PLOT].includes(n.tableColumn.temp[g].type)){t.shell.dockManager.findNode(l)||t.shell.dockManager.dock(l,"down",null,"Comparison chart",.25);const i=t=>{const e=o.toJs(t.get(0)).clone();e.columns.addNew(I,o.TYPE.STRING).init(t.dataFrame.get(C,0));for(let n=1;n<t.length;n++){const i=o.toJs(t.get(n)).clone();i.columns.addNew(I,o.TYPE.STRING).init(t.dataFrame.get(C,n));const s=[o.COLUMN_TYPE.INT,o.COLUMN_TYPE.FLOAT];for(let t=0;t<i.columns.length;t++){const n=i.columns.byIndex(t),r=e.columns.byIndex(t);n.type!==r.type&&s.includes(n.type)&&s.includes(r.type)&&(n.type!==o.COLUMN_TYPE.FLOAT&&i.columns.replace(n,n.convertTo(o.COLUMN_TYPE.FLOAT)),r.type!==o.COLUMN_TYPE.FLOAT&&e.columns.replace(r,r.convertTo(o.COLUMN_TYPE.FLOAT)))}e.append(i,!0)}return e},s=(t,e,i)=>{var s;switch(null===(s=n.tableColumn)||void 0===s?void 0:s.temp[g].type){case o.VIEWER.LINE_CHART:return i.plot.line(Object.assign(Object.assign({},e),{split:I})).root;case o.VIEWER.SCATTER_PLOT:return i.plot.scatter(Object.assign(Object.assign({},e),{color:I})).root;case o.VIEWER.HISTOGRAM:return i.plot.histogram(Object.assign(Object.assign({},e),{split:I})).root;case o.VIEWER.BOX_PLOT:return i.plot.box(Object.assign(Object.assign({},e),{category:I})).root}};e.setUpdateIndicator(l,!0),setTimeout((()=>{var t;if(!n.tableColumn.temp.unitedPlot){const o=n.tableColumn.temp[g].look,r=i(n.tableColumn);n.tableColumn.temp.unitedPlot=s(null===(t=n.tableColumn)||void 0===t?void 0:t.temp[g].type,o,r),e.setUpdateIndicator(l,!1)}e.empty(l),l.appendChild(n.tableColumn.temp.unitedPlot)}),10)}else t.shell.dockManager.close(l)}));this.subs.push(c,u)}}const re="_DG_CUSTOM_SERIALIZED_TOKEN_";function ae(t,e=2){return JSON.stringify(t,((t,e)=>e instanceof o.DataFrame?{[re]:"DataFrame",value:Array.from(e.toByteArray())}:e instanceof ArrayBuffer?{[re]:"ArrayBuffer",value:Array.from(new Uint8Array(e))}:e instanceof Map?{[re]:"Map",value:Array.from(e)}:e instanceof Set?{[re]:"Set",value:Array.from(e)}:e),e)}function le(t,e){if(e&&e[re]&&e.value)switch(e[re]){case"DataFrame":return o.DataFrame.fromByteArray(new Uint8Array(e.value));case"ArrayBuffer":return new Uint8Array(e.value).buffer;case"Map":return new Map(e.value);case"Set":return new Set(e.value)}return e}const ue=[{name:"Null",predicate:function(t,e){return null==t&&null==e},checker:function(){}},{name:"Boolean",predicate:function(t,e){return"boolean"==typeof t&&"boolean"==typeof e},checker:de},{name:"String",predicate:function(t,e){return"string"==typeof t&&"string"==typeof e},checker:de},{name:"Integer",predicate:function(t,e){return Number.isInteger(t)&&Number.isInteger(e)},checker:de},{name:"Float",predicate:function(t,e){return"number"==typeof t&&"number"==typeof e},checker:function(t,e,n){if(!(t===Number.POSITIVE_INFINITY&&e===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY&&e===Number.NEGATIVE_INFINITY||isNaN(t)&&isNaN(e)))return Math.abs(t-e)<n.options.floatTolerance?void 0:[{msg:`Expected ${e}, got ${t} (tolerance = ${n.options.floatTolerance})`}]}},{name:"Map",predicate:function(t,e){return t instanceof Map&&e instanceof Map},checker:function(t,e,n,i){const o=[];if(t.size!==e.size){const n={msg:`Maps are of different size: actual map size is ${t.size} and expected map size is ${e.size}`};o.push(n)}for(const n of e.keys()){const o=t.get(n),s=e.get(n);i([String(n)],o,s)}return o}},{name:"Set",predicate:function(t,e){return t instanceof Set&&e instanceof Set},checker:function(t,e,n,i){const o=[];if(t.size!==e.size){const n={msg:`Sets are of different size: actual set size is ${t.size} and expected set size is ${e.size}`};o.push(n)}for(const n of e.values()){const e=t.has(n);i([String(n)],e,!0)}return o}},{name:"ArrayBuffer",predicate:function(t,e){return t instanceof ArrayBuffer&&e instanceof ArrayBuffer},checker:function(t,e,n,i){return pe(Array.from(new Uint8Array(t)),Array.from(new Uint8Array(e)),0,i)}},{name:"Array",predicate:function(t,e){return t instanceof Array&&e instanceof Array},checker:pe},{name:"DataFrame",predicate:function(t,e){return t instanceof o.DataFrame&&e instanceof o.DataFrame},checker:function(t,e,n,i){const o=[];if(t.rowCount!==e.rowCount){const n={msg:`Dataframes has different row count: actual row count is ${t.rowCount} and expected row count is ${e.rowCount}`};o.push(n)}for(const n of e.columns){const s=t.columns.byName(n.name);if(s)if(s.type===n.type)for(let t=0;t<e.rowCount;t++){const e=s.get(t),o=n.get(t);i([n.name,String(t)],e,o)}else{const t={msg:`Column ${n.name} type expected ${n.type} got ${s.type}`};o.push(t)}else{const t={msg:`Column ${n.name} not found`};o.push(t)}}return o}},{name:"Object",predicate:function(t,e){return"object"==typeof t&&"object"==typeof e},checker:function(t,e,n,i){for(const[n,o]of Object.entries(e))i([n],t[n],o);return[]}}];class ce extends Error{}function de(t,e){if(t!==e)return[{msg:`Expected ${e}, got ${t}`}]}function pe(t,e,n,i){const o=[];if(t.length!==e.length){const n={msg:`Arrays are of different length: actual array length is ${t.length} and expected array length is ${e.length}`};o.push(n)}for(let n=0;n<t.length;n++)i([String(n)],t[n],e[n]);return o}const he={floatTolerance:.001,maxErrorsReport:5,maxDepth:128,checkersSeq:ue,prefix:""};class fe{constructor(t={}){this.options=Object.assign(Object.assign({},he),t),this.state={errors:[],currentPath:[],options:this.options}}run(t,e){this.matchChecker(t,e),this.checkErrorsLimit(0)}checkDeep(t,e,n){const i=t.length;if(this.state.currentPath.push(...t),this.state.currentPath.length>this.options.maxDepth)throw new ce(`Max depth ${this.options.maxDepth} is exceeded, potentially a circular structure`);this.matchChecker(e,n),this.state.currentPath.splice(-i)}matchChecker(t,e){let n=!1;for(const{predicate:i,checker:o}of this.options.checkersSeq)if(i(t,e)){n=!0;const i=o(t,e,this.state,this.checkDeep.bind(this));i&&i.map((t=>this.addError(t)));break}if(!n){const n={msg:`Type mismatch or no checker defined: expected ${e}, got ${t}`};this.addError(n)}}addError(t){var e,n;const i={path:[...null!==(e=this.state.currentPath)&&void 0!==e?e:[],...null!==(n=t.path)&&void 0!==n?n:[]],msg:t.msg};this.state.errors.push(i),this.checkErrorsLimit()}checkErrorsLimit(t=this.options.maxErrorsReport){if(this.state.errors.length>t){const t=this.makeReport();throw new ce(t)}}makeReport(){const t=this.state.errors.map((t=>{var e;const n=(null!==(e=t.path)&&void 0!==e?e:[]).map((t=>`['${String(t)}']`)).join("."),i=n?`${n}: ${t.msg}`:t.msg;return this.options.prefix?`${this.options.prefix}: ${i}`:i})).slice(0,this.options.maxErrorsReport).join("\n");return t}}var me=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const ve=2e4,ge=5e3,ye=5e3;function be(e,n){return me(this,arguments,void 0,(function*(e,n,i={}){var o,s,r;yield Ae(n,null!==(o=i.initWaitTimeout)&&void 0!==o?o:ve),n.disableSetters(!0);try{for(const[t,o]of Object.entries(n.steps)){const a=e[t];if(!a)continue;const l=null!==(r=null===(s=i.stepOptions)||void 0===s?void 0:s[t])&&void 0!==r?r:{},u=l.prefix?`${l.prefix}: ${t}`:t,{updateMode:c}=i,d={validatorsWaitTimeout:ge,initWaitTimeout:ve,parent:n,interactive:i.interactive,updateMode:c};yield we(a,o.view,Object.assign(Object.assign(Object.assign({},d),l),{prefix:u}))}}finally{n.disableSetters(!1)}i.interactive&&t.shell.info(`${n.name} test passed`)}))}function we(e,n){return me(this,arguments,void 0,(function*(e,n,i={}){var o;yield Ae(n,null!==(o=i.initWaitTimeout)&&void 0!==o?o:ve);const r=()=>me(this,void 0,void 0,(function*(){var e;if(i.parent){const n=null!==(e=i.parentWaitTimeout)&&void 0!==e?e:ye,o=yield i.parent.isUpdating.pipe((0,s.map)((()=>i.parent.getRunningUpdates())),(0,s.debounceTime)(100),(0,s.takeUntil)((0,c.of)(null).pipe((0,s.delay)(n))),(0,s.takeWhile)((t=>0!==t.length),!0),(0,s.last)()).toPromise();if(null==o?void 0:o.length){const e=`{options.prefix}: parent updates failed to complete in ${n}ms, updates: ${o.join(",")}`,s=new Error(e);throw i.interactive&&t.shell.error(String(s)),s}}}));yield r();for(const[t,o]of Object.entries(e.inputs)){const e=n.funcCall.inputParams[t].property.propertyType;i.updateMode?null==n.funcCall.inputs[t]&&(n.funcCall.inputs[t]=yield lt(e,o)):n.funcCall.inputs[t]=yield lt(e,o)}if(yield r(),yield(()=>me(this,void 0,void 0,(function*(){var e;if(n instanceof Oi){const o=null!==(e=i.validatorsWaitTimeout)&&void 0!==e?e:ge,r=yield n.pendingValidations.pipe((0,s.map)((t=>Object.keys(t))),(0,s.debounceTime)(100),(0,s.takeUntil)((0,c.of)(null).pipe((0,s.delay)(o))),(0,s.takeWhile)((()=>!n.isValid()),!0),(0,s.last)()).toPromise();if(null==r?void 0:r.length){const e=`{options.prefix}: validators failed to accept input in ${o}ms, inputs: ${r.join(",")}`,n=new Error(e);throw i.interactive&&t.shell.error(String(n)),n}}})))(),console.log(`running ${n.func.nqName}`),yield n.run(),!i.updateMode){console.log(`checking ${n.func.nqName} results`);try{!function(t,e,n){new fe(n).run(t,e)}(n.funcCall.outputs,e.outputs,i),!i.parent&&i.interactive&&t.shell.info(`${n.name} test passed`)}catch(e){throw i.interactive&&t.shell.error(String(e)),e}console.log(`${n.func.nqName} ok`)}}))}function Ae(t,e){return me(this,void 0,void 0,(function*(){if(!(yield t.isReady.pipe((0,s.takeUntil)((0,c.of)(null).pipe((0,s.delay)(e))),(0,s.takeWhile)((t=>!t),!0),(0,s.last)()).toPromise()))throw new Error(`Waiting for view ${t.name} timeout`)}))}var Ce=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const Ie=new URL(t.shell.startUri),Se="Run Data JSON",Te=()=>Ce(void 0,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,selfBrowserSurface:"include"}),e=new MediaRecorder(t),n=[];e.ondataavailable=t=>n.push(t.data),e.onstop=()=>{const e=new Blob(n,{type:n[0].type});t.getVideoTracks()[0].stop(),o.Utils.download(`Recording ${(new Date).toLocaleString("en-us",{month:"short",day:"numeric",hour:"numeric",minute:"numeric"})}.mkv`,e,n[0].type)},e.start()}));class Ee extends o.ViewBase{constructor(n,i={historyEnabled:!0,isTabbed:!1,skipInit:!1}){var s,r,a,l,u;super(),this.initValue=n,this.options=i,this._type="function",this.funcCallReplaced=new c.Subject,this.isReady=new c.BehaviorSubject(!1),this.exportConfig=null,this.getMocks=null,this.getTemplates=null,this.getHelp=null,this.reportBug=null,this.requestFeature=null,this.getAbout=null,this.historyBlock=null,this.isHistorical=new c.BehaviorSubject(!1),this.historyRoot=e.div(),this.consistencyState=new c.BehaviorSubject("consistent"),this.defaultExportFilename=(t,e)=>`${this.name} - ${(new Date).toLocaleString("en-US").replaceAll(/:|\//g,"-")}.${null!=e?e:this.exportConfig.supportedExtensions[t]}`,this.defaultSupportedExportExtensions=()=>({Excel:"xlsx"}),this.defaultSupportedExportFormats=()=>["Excel"],this.helpCache=null,this.box=!0,this.parentCall=t.functions.getCurrentCall(),n instanceof o.FuncCall&&(this.parentCall=n),this.parentView=null===(a=null===(r=null===(s=this.parentCall)||void 0===s?void 0:s.parentCall)||void 0===r?void 0:r.aux)||void 0===a?void 0:a.view,(null===(u=null===(l=this.parentCall)||void 0===l?void 0:l.func)||void 0===u?void 0:u.name)&&(this.basePath=`/${this.parentCall.func.name}`),i.skipInit||this.init()}onFuncCallReady(){return Ce(this,void 0,void 0,(function*(){if(yield dt.augmentCallWithFunc(this.funcCall,!1),!this.options.isTabbed){this.name&&"New view"!==this.name||(this.name=this.funcCall.func.friendlyName);try{this.func.package&&(yield this.getPackageData())}catch(t){console.log(t)}}this.build();const t=this.getStartId();if(t&&!this.options.isTabbed&&(e.setUpdateIndicator(this.root,!0),this.loadRun(t),e.setUpdateIndicator(this.root,!1),this.setAsLoaded()),this.isHistoryEnabled&&this.func){const t=this.options.isTabbed?this.isHistorical.subscribe((t=>{t||(this.funcCall.id=null)})):this.isHistorical.subscribe((t=>{var e,n;if(t){this.path=`?id=${this.funcCall.id}`;const t=Vt(this.funcCall);this.name.indexOf(" — ")<0?this.name=`${this.name} — ${null!==(e=this.funcCall.options.title)&&void 0!==e?e:t}`:this.name=`${this.name.substring(0,this.name.indexOf(" — "))} — ${null!==(n=this.funcCall.options.title)&&void 0!==n?n:t}`}else this.path="",this.funcCall.id=null,this.name=`${this.name.substring(0,this.name.indexOf(" — ")>0?this.name.indexOf(" — "):void 0)}`}));this.subs.push(t)}}))}getStartId(){return t.shell.getVar("isLoaded")?void 0:Ie.searchParams.get("id")}setAsLoaded(){return t.shell.setVar("isLoaded",!0)}get funcCall(){return this._funcCall}get func(){var t;return null===(t=this.funcCall)||void 0===t?void 0:t.func}get lastCall(){return this._lastCall}set lastCall(t){this._lastCall=t}get type(){return this._type}getPackageData(){return Ce(this,void 0,void 0,(function*(){var t,e;const n=this.func.package;if(!n)return;const i=null===(t=yield null==n?void 0:n.getProperties())||void 0===t?void 0:t.REPORT_BUG_URL;i&&!this.reportBug&&(this.reportBug=()=>Ce(this,void 0,void 0,(function*(){window.open(i,"_blank")})));const o=null===(e=yield null==n?void 0:n.getProperties())||void 0===e?void 0:e.REQUEST_FEATURE_URL;o&&!this.requestFeature&&(this.requestFeature=()=>Ce(this,void 0,void 0,(function*(){window.open(o,"_blank")})));const s=`${n.friendlyName}.\nLast updated on ${p()(n.updatedOn).format("YYYY MMM D, HH:mm")}`;this.getAbout||(this.getAbout=()=>Ce(this,void 0,void 0,(function*(){return s})))}))}linkFunccall(t){this._funcCall=t,this.funcCallReplaced.next(!0)}loadFuncCallById(){return Ce(this,void 0,void 0,(function*(){if(this.initValue instanceof o.FuncCall)return yield new Promise((t=>setTimeout(t,0))),void this.linkFunccall(this.initValue);e.setUpdateIndicator(this.root,!0);const n=this.getStartId();if(n&&!this.options.isTabbed)this.linkFunccall(yield dt.loadRun(n));else{const e=yield t.functions.eval(this.initValue);this.linkFunccall(e.prepare({}))}e.setUpdateIndicator(this.root,!1)}))}init(){return Ce(this,void 0,void 0,(function*(){yield this.loadFuncCallById(),yield this.onFuncCallReady(),this.isReady.next(!0)}))}build(){e.empty(this.root),this.root.appendChild(this.buildIO()),this.options.historyEnabled&&this.isHistoryEnabled&&this.buildHistoryBlock(),this.buildRibbonMenu(),this.buildRibbonPanels()}onComparisonLaunch(e){return Ce(this,void 0,void 0,(function*(){const n=this.comparatorFunc;if(n){const i=yield t.functions.eval(n),o=(yield i.prepare({params:{comparedRuns:e}}).call()).outputs.comparisonView;return void t.shell.addView(o)}const i=t.shell.v.parentCall,o=[...t.shell.views].find((t=>t.type===v)),s=yield se.fromComparedRuns(e,this.func,{parentView:o,parentCall:i});t.shell.addView(s),s.defaultCustomize();const r=this.compareCustomizer;if(r){const e=yield t.functions.eval(r);yield e.prepare({params:{defaultView:s}}).call()}}))}onSaveClick(){return Ce(this,void 0,void 0,(function*(){yield this.saveRun(this.funcCall)}))}buildHistoryBlock(){const n=ee.historyPanel(this.func);let i=!1;return this.subs.push(n.onCompactModeChanged.subscribe((e=>{const n=t.shell.dockManager.findNode(this.historyRoot);n&&(t.shell.dockManager.close(n),e?t.shell.dockManager.dock(this.historyRoot,"right",null,"History",.3):t.shell.dockManager.dock(this.historyRoot,"down",null,"History",.3))})),n.onRunChosen.subscribe((t=>Ce(this,void 0,void 0,(function*(){e.setUpdateIndicator(this.root,!0),yield this.loadRun(t),e.setUpdateIndicator(this.root,!1)})))),n.onComparison.subscribe((t=>Ce(this,void 0,void 0,(function*(){Mt(n.root,!0);const e=yield Promise.all(t.map((t=>dt.loadRun(t))));yield this.onComparisonLaunch(e),Mt(n.root,!1)})))),n.afterRunEdited.subscribe((t=>{var e,n;if(t.id===this.funcCall.id&&t.options.title){this.path=`?id=${this.funcCall.id}`;const i=Vt(t);this.name.indexOf(" — ")<0?this.name=`${this.name} — ${null!==(e=t.options.title)&&void 0!==e?e:i}`:this.name=`${this.name.substring(0,this.name.indexOf(" — "))} — ${null!==(n=t.options.title)&&void 0!==n?n:i}`}})),t.events.onViewRemoving.subscribe((e=>{if(e.args.view==this){const e=t.shell.dockManager.findNode(this.historyRoot);e?(t.shell.dockManager.close(e),i=!0):i=!1}})),t.events.onCurrentViewChanged.subscribe((()=>{var e;if(t.shell.v==this)i&&((null===(e=this.historyBlock)||void 0===e?void 0:e.compactMode)?t.shell.dockManager.dock(this.historyRoot,"right",null,"History",.3):t.shell.dockManager.dock(this.historyRoot,"down",null,"History",.3));else{const e=t.shell.dockManager.findNode(this.historyRoot);e?(t.shell.dockManager.close(e),i=!0):i=!1}}))),e.empty(this.historyRoot),this.historyRoot.style.removeProperty("justify-content"),this.historyRoot.append(n.root),this.historyBlock=n,n.root}buildRibbonPanels(){const n=e.iconFA("history",(()=>{var e;t.shell.dockManager.findNode(this.historyRoot)||((null===(e=this.historyBlock)||void 0===e?void 0:e.compactMode)?t.shell.dockManager.dock(this.historyRoot,"right",null,"History",.3):t.shell.dockManager.dock(this.historyRoot,"down",null,"History",.3),this.historyRoot.parentElement.classList.add("ui-box"),this.historyRoot.classList.add("ui-box"))})),i=e.iconFA("save",(()=>Ce(this,void 0,void 0,(function*(){yield this.onSaveClick()}))),"Save current state"),o=e.comboPopup(e.iconFA("arrow-to-bottom"),this.getFormats(),this.exportRun.bind(this)),r=e.iconFA("edit",(()=>{this.historyBlock&&this.lastCall&&this.historyBlock.showEditDialog(this.historyBlock.history.get(this.funcCall.id))}),"Edit this run metadata"),l=this.isHistorical.subscribe((t=>{t?(e.setDisplay(o,!J(this.funcCall)),e.setDisplay(r,!0)):(a()(o).hide(),a()(r).hide())}));if(this.subs.push(l),e.tooltip.bind(o,(()=>"inconsistent"===this.consistencyState.value&&this.mandatoryConsistent?"Current run is inconsistent. Export feature is disabled.":null)),!this.options.isTabbed&&this.mandatoryConsistent){const t=this.consistencyState.pipe((0,s.distinctUntilChanged)()).subscribe((t=>{"inconsistent"===t?(a()(o).addClass("d4-disabled"),a()(o.lastChild).css("color","unset")):(a()(o).removeClass("d4-disabled"),a()(o.lastChild).removeProp("color"))}));this.subs.push(t)}const u=[[...!this.options.isTabbed&&this.isHistoryEnabled&&this.options.historyEnabled?[n]:[],...!this.options.isTabbed&&this.isHistoryEnabled?[i]:[],...!this.options.isTabbed&&this.isExportEnabled&&this.exportConfig&&this.exportConfig.supportedFormats.length>0?[o]:[],...this.options.isTabbed?[]:[r]]];return this.setRibbonPanels(u),u}buildRibbonMenu(){if(this.ribbonMenu.clear(),!(this.exportConfig||this.reportBug||this.requestFeature||this.getHelp||this.getMocks||this.getTemplates))return;const t=this.ribbonMenu.group("Model");if(this.getMocks&&this.getMocks.length>0)if(1===this.getMocks.length)t.item("Input data mock",this.getMocks[0].action);else{const e=t.group("Input data mocks");this.getMocks.forEach((t=>{e.item(t.mockName,t.action)})),t.endGroup()}if(this.getTemplates&&this.getTemplates.length>0)if(1===this.getTemplates.length)t.item("Input data template",this.getTemplates[0].action);else{const e=t.group("Input data templates");this.getTemplates.forEach((t=>{e.item(t.name,t.action)})),t.endGroup()}this.isExportEnabled&&this.exportConfig&&this.exportConfig.supportedFormats.length>0&&t.group("Export").items(this.getFormats(),this.exportRun.bind(this)).endGroup(),this.reportBug&&t.item("Report a bug",(()=>this.reportBug())),this.requestFeature&&t.item("Request a feature",(()=>this.requestFeature())),this.getHelp&&t.item("Help",(()=>this.getHelp()));const n=t.group("Test runner");n.item("Execute Test JSON",(()=>this.importRunJsonDialog())),n.item("Update Test JSON",(()=>this.importRunJsonDialog(!0))),t.endGroup(),t.item("Record the screen",Te),this.getAbout&&t.item("About",(()=>Ce(this,void 0,void 0,(function*(){const t=yield this.getAbout();if(t){const n=e.dialog("Current version");t.split("\n").forEach((t=>n.add(e.label(t)))),n.onOK((()=>{})),n.getButton("CANCEL").style.display="none",n.show({center:!0})}}))))}exportRun(t){return Ce(this,void 0,void 0,(function*(){if(t!==Se)o.Utils.download(this.exportConfig.filename(t),yield this.exportConfig.export(t));else{const t=yield this.exportRunJson();t&&o.Utils.download(this.defaultExportFilename("","json"),t)}}))}getFormats(){var t,e;return[...null!==(e=null===(t=this.exportConfig)||void 0===t?void 0:t.supportedFormats)&&void 0!==e?e:[],Se]}onBeforeSaveRun(t){return Ce(this,void 0,void 0,(function*(){}))}onAfterSaveRun(t){return Ce(this,void 0,void 0,(function*(){}))}saveRun(t){return Ce(this,void 0,void 0,(function*(){let e=tt(t);yield this.onBeforeSaveRun(e),J(t)&&(e=yield q(t)),e.id&&e.newId();const n=yield dt.saveRun(e),i=yield dt.loadRun(n.id);return this.options.historyEnabled&&this.isHistoryEnabled&&this.historyBlock&&this.historyBlock.addRun(i),this.linkFunccall(i),this.isHistorical.next(!0),yield this.onAfterSaveRun(n),n}))}onBeforeDeleteRun(t){return Ce(this,void 0,void 0,(function*(){}))}onAfterDeleteRun(t){return Ce(this,void 0,void 0,(function*(){}))}deleteRun(t){return Ce(this,void 0,void 0,(function*(){return yield this.onBeforeDeleteRun(t),yield dt.deleteRun(t),yield this.onAfterDeleteRun(t),t.id}))}onBeforeLoadRun(){return Ce(this,void 0,void 0,(function*(){}))}onAfterLoadRun(t){return Ce(this,void 0,void 0,(function*(){}))}loadRun(t){return Ce(this,void 0,void 0,(function*(){yield this.onBeforeLoadRun();const e=yield dt.loadRun(t);return this.lastCall=tt(e),this.linkFunccall(e),this.isHistorical.next(!0),yield this.onAfterLoadRun(e),e}))}onBeforeRun(t){return Ce(this,void 0,void 0,(function*(){}))}onAfterRun(t){return Ce(this,void 0,void 0,(function*(){}))}run(){return Ce(this,void 0,void 0,(function*(){if(!this.funcCall)throw new Error("The correspoding function is not specified");yield this.onBeforeRun(this.funcCall);const e=o.TaskBarProgressIndicator.create("Calculating...");try{this.funcCall.newId(),yield this.funcCall.call(),yield this.onAfterRun(this.funcCall),this.lastCall=tt(this.funcCall),this.options.isTabbed||this.runningOnInput||!this.isHistoryEnabled||(yield this.saveRun(this.funcCall))}catch(e){t.shell.error(e.toString())}finally{e.close()}}))}exportRunJson(){return Ce(this,void 0,void 0,(function*(){if(this._lastCall)return ae(yield rt(this._lastCall,this),0)}))}importRunJsonDialog(){return Ce(this,arguments,void 0,(function*(t=!1){const n=new Rt("JSON file",null,null,"application/json"),i={modal:!0,fullScreen:!0,width:500,height:200,center:!0};if(!(yield new Promise(((t,o)=>{e.dialog({title:"Import Run JSON"}).add(e.div([e.inputs([n])])).onOK((()=>t(!0))).onCancel((()=>t(!1))).show(i)})))||!n.value)return;const o=(r=yield n.value.text(),JSON.parse(r,le));var r;t?(yield this.executeTest(o,!0),yield this.isHistorical.pipe((0,s.filter)((t=>t)),(0,s.take)(1),(0,s.delay)(0)).toPromise(),yield this.exportRun(Se)):yield this.executeTest(o)}))}executeTest(t){return Ce(this,arguments,void 0,(function*(t,e=!1){yield we(t,this,{updateMode:e,interactive:!0})}))}get compareCustomizer(){var t;return null!==(t=this.func.options.compareCustomizer)&&void 0!==t?t:null}get comparatorFunc(){var t;return null!==(t=this.func.options.comparatorFunc)&&void 0!==t?t:null}get uploadFunc(){var t;return null!==(t=this.func.options.uploadFunc)&&void 0!==t?t:null}get runningOnInput(){return"true"===this.func.options.runOnInput}get runningOnStart(){return"true"===this.func.options.runOnOpen}get mainParams(){return this.func.options.mainParams?JSON.parse(this.func.options.mainParams):null}get mandatoryConsistent(){var t;return"true"===(null===(t=this.parentCall)||void 0===t?void 0:t.func.options.mandatoryConsistent)}get hasContextHelp(){return!!this.func.options.help}getContextHelp(){return Ce(this,void 0,void 0,(function*(){const e=this.func.options.help;if(!e)return null;if(this.helpCache)return this.helpCache;const n=`System:AppData/${e}`;if(yield t.dapi.files.exists(n)){const e=yield t.dapi.files.readAsText(n);return this.helpCache=e,e}const i=`${t.shell.user.name}.home/${e}`;if(yield t.dapi.files.exists(i)){const e=yield t.dapi.files.readAsText(i);return this.helpCache=e,e}return null}))}get features(){var t;return JSON.parse(null!==(t=this.func.options.features)&&void 0!==t?t:"{}")}getFeature(t,e){var n;return this.features instanceof Array?this.features.includes(t):this.features instanceof Object&&null!==(n=this.features[t])&&void 0!==n?n:e}get isExportEnabled(){return this.getFeature("export",!0)}get isHistoryEnabled(){return this.getFeature("history",!0)}get isSaEnabled(){return this.getFeature("sens-analysis",!1)}get hasUploadMode(){return this.getFeature("upload",!1)}get isFittingEnabled(){return this.getFeature("fitting",!1)}}var xe=Uint8Array,Re=Uint16Array,Oe=Uint32Array,Pe=new xe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ke=new xe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Fe=new xe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Le=function(t,e){for(var n=new Re(31),i=0;i<31;++i)n[i]=e+=1<<t[i-1];var o=new Oe(n[30]);for(i=1;i<30;++i)for(var s=n[i];s<n[i+1];++s)o[s]=s-n[i]<<5|i;return[n,o]},Ne=Le(Pe,2),Be=Ne[0],Me=Ne[1];Be[28]=258,Me[258]=28;for(var _e=Le(ke,0),De=(_e[0],_e[1]),Ve=new Re(32768),je=0;je<32768;++je){var $e=(43690&je)>>>1|(21845&je)<<1;$e=(61680&($e=(52428&$e)>>>2|(13107&$e)<<2))>>>4|(3855&$e)<<4,Ve[je]=((65280&$e)>>>8|(255&$e)<<8)>>>1}var He=function(t,e,n){for(var i=t.length,o=0,s=new Re(e);o<i;++o)t[o]&&++s[t[o]-1];var r,a=new Re(e);for(o=0;o<e;++o)a[o]=a[o-1]+s[o-1]<<1;if(n){r=new Re(1<<e);var l=15-e;for(o=0;o<i;++o)if(t[o])for(var u=o<<4|t[o],c=e-t[o],d=a[t[o]-1]++<<c,p=d|(1<<c)-1;d<=p;++d)r[Ve[d]>>>l]=u}else for(r=new Re(i),o=0;o<i;++o)t[o]&&(r[o]=Ve[a[t[o]-1]++]>>>15-t[o]);return r},Ue=new xe(288);for(je=0;je<144;++je)Ue[je]=8;for(je=144;je<256;++je)Ue[je]=9;for(je=256;je<280;++je)Ue[je]=7;for(je=280;je<288;++je)Ue[je]=8;var Ye=new xe(32);for(je=0;je<32;++je)Ye[je]=5;var We=He(Ue,9,0),Ge=He(Ye,5,0),ze=function(t){return(t+7)/8|0},qe=function(t,e,n){(null==e||e<0)&&(e=0),(null==n||n>t.length)&&(n=t.length);var i=new(2==t.BYTES_PER_ELEMENT?Re:4==t.BYTES_PER_ELEMENT?Oe:xe)(n-e);return i.set(t.subarray(e,n)),i},Je=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Ke=function(t,e,n){var i=new Error(e||Je[t]);if(i.code=t,Error.captureStackTrace&&Error.captureStackTrace(i,Ke),!n)throw i;return i},Ze=function(t,e,n){n<<=7&e;var i=e/8|0;t[i]|=n,t[i+1]|=n>>>8},Xe=function(t,e,n){n<<=7&e;var i=e/8|0;t[i]|=n,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Qe=function(t,e){for(var n=[],i=0;i<t.length;++i)t[i]&&n.push({s:i,f:t[i]});var o=n.length,s=n.slice();if(!o)return[an,0];if(1==o){var r=new xe(n[0].s+1);return r[n[0].s]=1,[r,1]}n.sort((function(t,e){return t.f-e.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=o-1;)a=n[n[u].f<n[d].f?u++:d++],l=n[u!=c&&n[u].f<n[d].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var p=s[0].s;for(i=1;i<o;++i)s[i].s>p&&(p=s[i].s);var h=new Re(p+1),f=tn(n[c-1],h,0);if(f>e){i=0;var m=0,v=f-e,g=1<<v;for(s.sort((function(t,e){return h[e.s]-h[t.s]||t.f-e.f}));i<o;++i){var y=s[i].s;if(!(h[y]>e))break;m+=g-(1<<f-h[y]),h[y]=e}for(m>>>=v;m>0;){var b=s[i].s;h[b]<e?m-=1<<e-h[b]++-1:++i}for(;i>=0&&m;--i){var w=s[i].s;h[w]==e&&(--h[w],++m)}f=e}return[new xe(h),f]},tn=function(t,e,n){return-1==t.s?Math.max(tn(t.l,e,n+1),tn(t.r,e,n+1)):e[t.s]=n},en=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Re(++e),i=0,o=t[0],s=1,r=function(t){n[i++]=t},a=1;a<=e;++a)if(t[a]==o&&a!=e)++s;else{if(!o&&s>2){for(;s>138;s-=138)r(32754);s>2&&(r(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(r(o),--s;s>6;s-=6)r(8304);s>2&&(r(s-3<<5|8208),s=0)}for(;s--;)r(o);s=1,o=t[a]}return[n.subarray(0,i),e]},nn=function(t,e){for(var n=0,i=0;i<e.length;++i)n+=t[i]*e[i];return n},on=function(t,e,n){var i=n.length,o=ze(e+2);t[o]=255&i,t[o+1]=i>>>8,t[o+2]=255^t[o],t[o+3]=255^t[o+1];for(var s=0;s<i;++s)t[o+s+4]=n[s];return 8*(o+4+i)},sn=function(t,e,n,i,o,s,r,a,l,u,c){Ze(e,c++,n),++o[256];for(var d=Qe(o,15),p=d[0],h=d[1],f=Qe(s,15),m=f[0],v=f[1],g=en(p),y=g[0],b=g[1],w=en(m),A=w[0],C=w[1],I=new Re(19),S=0;S<y.length;++S)I[31&y[S]]++;for(S=0;S<A.length;++S)I[31&A[S]]++;for(var T=Qe(I,7),E=T[0],x=T[1],R=19;R>4&&!E[Fe[R-1]];--R);var O,P,k,F,L=u+5<<3,N=nn(o,Ue)+nn(s,Ye)+r,B=nn(o,p)+nn(s,m)+r+14+3*R+nn(I,E)+(2*I[16]+3*I[17]+7*I[18]);if(L<=N&&L<=B)return on(e,c,t.subarray(l,l+u));if(Ze(e,c,1+(B<N)),c+=2,B<N){O=He(p,h,0),P=p,k=He(m,v,0),F=m;var M=He(E,x,0);for(Ze(e,c,b-257),Ze(e,c+5,C-1),Ze(e,c+10,R-4),c+=14,S=0;S<R;++S)Ze(e,c+3*S,E[Fe[S]]);c+=3*R;for(var _=[y,A],D=0;D<2;++D){var V=_[D];for(S=0;S<V.length;++S){var j=31&V[S];Ze(e,c,M[j]),c+=E[j],j>15&&(Ze(e,c,V[S]>>>5&127),c+=V[S]>>>12)}}}else O=We,P=Ue,k=Ge,F=Ye;for(S=0;S<a;++S)if(i[S]>255){j=i[S]>>>18&31,Xe(e,c,O[j+257]),c+=P[j+257],j>7&&(Ze(e,c,i[S]>>>23&31),c+=Pe[j]);var $=31&i[S];Xe(e,c,k[$]),c+=F[$],$>3&&(Xe(e,c,i[S]>>>5&8191),c+=ke[$])}else Xe(e,c,O[i[S]]),c+=P[i[S]];return Xe(e,c,O[256]),c+P[256]},rn=new Oe([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),an=new xe(0),ln=function(){for(var t=new Int32Array(256),e=0;e<256;++e){for(var n=e,i=9;--i;)n=(1&n&&-306674912)^n>>>1;t[e]=n}return t}(),un=function(){var t=-1;return{p:function(e){for(var n=t,i=0;i<e.length;++i)n=ln[255&n^e[i]]^n>>>8;t=n},d:function(){return~t}}},cn=function(t,e,n,i,o){return function(t,e,n,i,o,s){var r=t.length,a=new xe(i+r+5*(1+Math.ceil(r/7e3))+o),l=a.subarray(i,a.length-o),u=0;if(!e||r<8)for(var c=0;c<=r;c+=65535){var d=c+65535;d>=r&&(l[u>>3]=s),u=on(l,u+1,t.subarray(c,d))}else{for(var p=rn[e-1],h=p>>>13,f=8191&p,m=(1<<n)-1,v=new Re(32768),g=new Re(m+1),y=Math.ceil(n/3),b=2*y,w=function(e){return(t[e]^t[e+1]<<y^t[e+2]<<b)&m},A=new Oe(25e3),C=new Re(288),I=new Re(32),S=0,T=0,E=(c=0,0),x=0,R=0;c<r;++c){var O=w(c),P=32767&c,k=g[O];if(v[P]=k,g[O]=P,x<=c){var F=r-c;if((S>7e3||E>24576)&&F>423){u=sn(t,l,0,A,C,I,T,E,R,c-R,u),E=S=T=0,R=c;for(var L=0;L<286;++L)C[L]=0;for(L=0;L<30;++L)I[L]=0}var N=2,B=0,M=f,_=P-k&32767;if(F>2&&O==w(c-_))for(var D=Math.min(h,F)-1,V=Math.min(32767,c),j=Math.min(258,F);_<=V&&--M&&P!=k;){if(t[c+N]==t[c+N-_]){for(var $=0;$<j&&t[c+$]==t[c+$-_];++$);if($>N){if(N=$,B=_,$>D)break;var H=Math.min(_,$-2),U=0;for(L=0;L<H;++L){var Y=c-_+L+32768&32767,W=Y-v[Y]+32768&32767;W>U&&(U=W,k=Y)}}}_+=(P=k)-(k=v[P])+32768&32767}if(B){A[E++]=268435456|Me[N]<<18|De[B];var G=31&Me[N],z=31&De[B];T+=Pe[G]+ke[z],++C[257+G],++I[z],x=c+N,++S}else A[E++]=t[c],++C[t[c]]}}u=sn(t,l,s,A,C,I,T,E,R,c-R,u),!s&&7&u&&(u=on(l,u+1,an))}return qe(a,0,i+ze(u)+o)}(t,null==e.level?6:e.level,null==e.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(t.length)))):12+e.mem,n,i,!o)},dn=function(t,e){var n={};for(var i in t)n[i]=t[i];for(var i in e)n[i]=e[i];return n},pn=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function hn(t,e){return cn(t,e||{},0,0)}var fn=function(t,e,n,i){for(var o in t){var s=t[o],r=e+o,a=i;Array.isArray(s)&&(a=dn(i,s[1]),s=s[0]),s instanceof xe?n[r]=[s,a]:(n[r+="/"]=[new xe(0),a],fn(s,r,n,i))}},mn="undefined"!=typeof TextEncoder&&new TextEncoder,vn="undefined"!=typeof TextDecoder&&new TextDecoder;try{vn.decode(an,{stream:!0})}catch(t){}function gn(t,e){if(e){for(var n=new xe(t.length),i=0;i<t.length;++i)n[i]=t.charCodeAt(i);return n}if(mn)return mn.encode(t);var o=t.length,s=new xe(t.length+(t.length>>1)),r=0,a=function(t){s[r++]=t};for(i=0;i<o;++i){if(r+5>s.length){var l=new xe(r+8+(o-i<<1));l.set(s),s=l}var u=t.charCodeAt(i);u<128||e?a(u):u<2048?(a(192|u>>6),a(128|63&u)):u>55295&&u<57344?(a(240|(u=65536+(1047552&u)|1023&t.charCodeAt(++i))>>18),a(128|u>>12&63),a(128|u>>6&63),a(128|63&u)):(a(224|u>>12),a(128|u>>6&63),a(128|63&u))}return qe(s,0,r)}var yn=function(t){var e=0;if(t)for(var n in t){var i=t[n].length;i>65535&&Ke(9),e+=i+4}return e},bn=function(t,e,n,i,o,s,r,a){var l=i.length,u=n.extra,c=a&&a.length,d=yn(u);pn(t,e,null!=r?33639248:67324752),e+=4,null!=r&&(t[e++]=20,t[e++]=n.os),t[e]=20,e+=2,t[e++]=n.flag<<1|(s<0&&8),t[e++]=o&&8,t[e++]=255&n.compression,t[e++]=n.compression>>8;var p=new Date(null==n.mtime?Date.now():n.mtime),h=p.getFullYear()-1980;if((h<0||h>119)&&Ke(10),pn(t,e,h<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>>1),e+=4,-1!=s&&(pn(t,e,n.crc),pn(t,e+4,s<0?-s-2:s),pn(t,e+8,n.size)),pn(t,e+12,l),pn(t,e+14,d),e+=16,null!=r&&(pn(t,e,c),pn(t,e+6,n.attrs),pn(t,e+10,r),e+=14),t.set(i,e),e+=l,d)for(var f in u){var m=u[f],v=m.length;pn(t,e,+f),pn(t,e+2,v),t.set(m,e+4),e+=4+v}return c&&(t.set(a,e),e+=c),e};function wn(t,e){e||(e={});var n={},i=[];fn(t,"",n,e);var o=0,s=0;for(var r in n){var a=n[r],l=a[0],u=a[1],c=0==u.level?0:8,d=(I=gn(r)).length,p=u.comment,h=p&&gn(p),f=h&&h.length,m=yn(u.extra);d>65535&&Ke(11);var v=c?hn(l,u):l,g=v.length,y=un();y.p(l),i.push(dn(u,{size:l.length,crc:y.d(),c:v,f:I,m:h,u:d!=r.length||h&&p.length!=f,o,compression:c})),o+=30+d+m+g,s+=76+2*(d+m)+(f||0)+g}for(var b=new xe(s+22),w=o,A=s-o,C=0;C<i.length;++C){var I=i[C];bn(b,I.o,I,I.f,I.u,I.c.length);var S=30+I.f.length+yn(I.extra);b.set(I.c,I.o+S),bn(b,o,I,I.f,I.u,I.c.length,I.o,I.m),o+=16+S+(I.m?I.m.length:0)}return function(t,e,n,i,o){pn(t,e,101010256),pn(t,e+8,n),pn(t,e+10,n),pn(t,e+12,i),pn(t,e+16,o)}(b,o,i.length,A,w),b}"function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout&&setTimeout;var An=n(933),Cn={};Cn.styleTagTransform=It(),Cn.setAttributes=bt(),Cn.insert=gt().bind(null,"head"),Cn.domAPI=mt(),Cn.insertStyleElement=At(),ht()(An.A,Cn),An.A&&An.A.locals&&An.A.locals;var In=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const Sn=t=>{var e,n;return null!==(n=null===(e=t.options)||void 0===e?void 0:e.friendlyName)&&void 0!==n?n:t.func.name},Tn=t=>{var e;return null!==(e=t.customId)&&void 0!==e?e:t.funcName};class En extends Ee{set currentTabName(t){this.stepTabs.getPane(t)&&(this.stepTabs.currentPane=this.stepTabs.getPane(t))}getStepView(t){var e;return null===(e=this.steps[t])||void 0===e?void 0:e.view}getRunningUpdates(){return[]}disableSetters(t){}constructor(t,e,n={historyEnabled:!0,isTabbed:!1,skipInit:!1}){super(t,n),this.initialConfig=e,this.steps={},this.onStepCompleted=new c.Subject,this.isUpdating=new c.BehaviorSubject(!1),this.pipelineViewExportExtensions=()=>({Archive:"zip","Single Excel":"xlsx"}),this.pipelineViewExportFormats=()=>["Archive","Single Excel"],this.pipelineViewExport=t=>In(this,void 0,void 0,(function*(){if(!this.stepTabs)throw new Error("Set step tabs please for export");if("Archive"===t){const t={};for(const e of Object.values(this.steps).filter((t=>t.visibility.value===S.VISIBLE))){this.stepTabs.currentPane=this.stepTabs.getPane(Sn(e)),yield new Promise((t=>setTimeout(t,100)));const n=yield e.view.exportConfig.export("Excel");t[e.view.exportConfig.filename("Excel")]=[new Uint8Array(yield n.arrayBuffer()),{level:0}]}return new Blob([wn(t)])}if("Single Excel"===t){yield o.Utils.loadJsCss(["/js/common/exceljs.min.js"]);const t=window.ExcelJS,e="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",n=new t.Workbook,i=(t,e,n)=>{let i=`${Sn(n)}>${e}`;i.length>31&&(i=`${i.slice(0,31)}`);let o=1;for(;t.worksheets.some((t=>t.name===i));){let t=`${Sn(n)}>${e}`;t.length>31-`-${o}`.length&&(t=`${e.slice(0,31-`-${o}`.length)}`),i=`${t}-${o}`,o++}return i};for(const e of Object.values(this.steps).filter((t=>t.visibility.value===S.VISIBLE))){const o=new t.Workbook;this.stepTabs.currentPane=this.stepTabs.getPane(Sn(e)),yield new Promise((t=>setTimeout(t,100))),yield o.xlsx.load(yield(yield e.view.exportConfig.export("Excel")).arrayBuffer()),o.eachSheet((t=>{const s=i(n,t.name,e),r=n.addWorksheet("New sheet");r.model=t.model,r.name=s,t.getImages().forEach((t=>{const e=n.addImage(o.getImage(t.imageId));r.addImage(e,t.range)}))}))}return new Blob([yield n.xlsx.writeBuffer()],{type:e})}throw new Error("This format is not supported")})),this.exportConfig={supportedExtensions:this.pipelineViewExportExtensions(),supportedFormats:this.pipelineViewExportFormats(),export:this.pipelineViewExport,filename:this.defaultExportFilename},this.helpFiles={}}init(){return In(this,void 0,void 0,(function*(){yield this.loadFuncCallById(),this.initialConfig.forEach(((t,e)=>{var n;this.steps[Tn(t)]={idx:e,visibility:new c.BehaviorSubject(null!==(n=t.hiddenOnInit)&&void 0!==n?n:S.VISIBLE),ability:new c.BehaviorSubject(this.isHistorical.value||0===e?T.ENABLED:T.DISABLED),options:{friendlyName:t.friendlyName,helpUrl:t.helpUrl,customId:t.customId}}})),this.subs.push(t.functions.onAfterRunAction.pipe((0,s.filter)((t=>Object.values(this.steps).some((({view:e})=>{var n;return(null===(n=null==e?void 0:e.funcCall)||void 0===n?void 0:n.id)===(null==t?void 0:t.id)&&!!t}))))).subscribe((t=>{this.onStepCompleted.next(t),"true"!==t.func.options.isMain&&t.func.nqName!==this.initialConfig[this.initialConfig.length-1].funcName||this.run()})));const n=this.initialConfig.map((e=>In(this,void 0,void 0,(function*(){return{stepScript:yield t.functions.eval(e.funcName),stepId:Tn(e)}})))),i=yield Promise.all(n);i.forEach((t=>{this.steps[t.stepId].func=t.stepScript})),this.root.classList.remove("ui-panel");const r={},l="Compute:PipelineStepEditor",u=i.map((e=>In(this,void 0,void 0,(function*(){const n=e.stepScript.script?(t=>{const e=t.script,n=e.indexOf("editor:");if(n<0)return l;const i=e.indexOf("\n",n);return e.substring(n+7,i).trim()})(e.stepScript):l;return r[n]||(r[n]=yield t.functions.eval(n.split(" ").join(""))),this.steps[e.stepId].editor=n,Promise.resolve()}))));yield Promise.all(u);const d=i.map((n=>In(this,void 0,void 0,(function*(){const i=this.steps[n.stepId],l=n.stepScript.prepare(),u=r[i.editor];yield this.onBeforeStepFuncCallApply(n.stepScript.nqName,l,u);const d=yield u.apply({call:l}),p=e.button("Back",(()=>{}),"Go to the previous step");a()(p).addClass("ui-btn-nav");const h=e.button("Next",(()=>{}),"Go to the next step");a()(h).addClass("ui-btn-nav"),this.syncNavButtons(i,p,h),d.setNavigationButtons([p,h]),this.steps[n.stepId].view=d;const f=this.steps[n.stepId],m=()=>{Object.values(this.steps).forEach((t=>{t.idx>f.idx&&t.visibility.value===S.VISIBLE&&t.ability.value===T.ENABLED&&t.ability.next(T.DISABLED)}))},v=f.view.funcCallReplaced.pipe((0,s.switchMap)((()=>{const t=[...f.view.funcCall.inputParams.values()].map((t=>t.onChanged.pipe((0,s.mapTo)(t))));return(0,c.merge)(...t)}))),g=v.subscribe(m);this.subs.push(g);const y=v.pipe((0,s.filter)((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&t.value)),(0,s.switchMap)((t=>t.value.onDataChanged))).subscribe(m);this.subs.push(y);const b=t.functions.onAfterRunAction.pipe((0,s.filter)((t=>f.view.funcCall&&t&&!!t.id&&f.view.funcCall.id===t.id)),(0,s.withLatestFrom)(f.visibility,f.ability),(0,s.filter)((([,t,e])=>!(t===S.HIDDEN||e===T.DISABLED)))).subscribe((()=>{const t=(()=>Object.values(this.steps).find((t=>t.idx>f.idx&&t.visibility.value===S.VISIBLE&&t.ability.value===T.ENABLED))?null:Object.values(this.steps).find((t=>t.idx>f.idx&&t.visibility.value===S.VISIBLE&&t.ability.value===T.DISABLED)))();null==t||t.ability.next(T.ENABLED)}));return this.subs.push(b),yield this.onAfterStepFuncCallApply(n.stepScript.nqName,l,d),d})))),p=yield Promise.all(d),h=(0,c.combineLatest)(p.map((t=>t.isHistorical))).subscribe((t=>{t.some(((t,e)=>{var n;return!t&&(null===(n=Object.values(this.steps).find((t=>t.idx===e)))||void 0===n?void 0:n.visibility.value)===S.VISIBLE}))&&this.isHistorical.value&&this.isHistorical.next(!1)}));this.subs.push(h);const f=this.isUpdating.subscribe((t=>{for(const e of Object.values(this.steps)){const n=e.view;(null==n?void 0:n.blockRuns)&&n.blockRuns.next(t)}}));this.subs.push(f),yield this.onFuncCallReady(),this.isReady.next(!0),this.loadHelp().then((()=>{this.buildRibbonPanels();const e=()=>{const t=this.findCurrentStep();t&&this.helpFiles[t.func.nqName]&&this.getHelpState().then((e=>{"opened"===e&&this.showHelpWithDelay(t)}))},n=t.events.onCurrentViewChanged.pipe((0,s.filter)((()=>t.shell.v==this))).subscribe(e);e(),this.subs.push(n)}))}))}loadHelp(){return In(this,void 0,void 0,(function*(){return Promise.all(Object.values(this.steps).map((e=>In(this,void 0,void 0,(function*(){var n,i,o,s;const r=null!==(i=null===(n=e.options)||void 0===n?void 0:n.helpUrl)&&void 0!==i?i:e.func.options.help;if(r){const n=`System:AppData/${this.func.package.name}/${r}`,i=(yield t.dapi.files.exists(n))?yield t.dapi.files.readAsText(n):yield e.view.getContextHelp();i&&(this.helpFiles[null!==(s=null===(o=e.options)||void 0===o?void 0:o.customId)&&void 0!==s?s:e.func.nqName]=i)}})))))}))}syncNavButtons(t,e,n){let i,o;n.addEventListener("click",(()=>{i&&(this.currentTabName=Sn(i))})),e.addEventListener("click",(()=>{o&&(this.currentTabName=Sn(o))}));const r=this.getPipelineStateChanges().pipe((0,s.startWith)(!0),(0,s.debounceTime)(0)).subscribe((()=>{i=this.getNextStep(t),o=this.getPreviousStep(t),i?(a()(n).show(),i.ability.value===T.DISABLED&&a()(n).addClass("d4-disabled"),i.ability.value===T.ENABLED&&a()(n).removeClass("d4-disabled")):a()(n).hide(),o?(a()(e).show(),o.ability.value===T.DISABLED&&a()(e).addClass("d4-disabled"),o.ability.value===T.ENABLED&&a()(e).removeClass("d4-disabled")):a()(e).hide()}));this.subs.push(r)}getPreviousStep(t){return Object.values(this.steps).slice().reverse().find((e=>e.idx<t.idx&&e.visibility.value===S.VISIBLE))}getNextStep(t){return Object.values(this.steps).find((e=>e.idx>t.idx&&e.visibility.value===S.VISIBLE))}getPipelineStateChanges(){const t=Object.values(this.steps).flatMap((t=>[t.ability,t.visibility]));return(0,c.merge)(...t).pipe((0,s.mapTo)(!0))}onComparisonLaunch(e){return In(this,void 0,void 0,(function*(){const n=t.shell.v.parentCall,i=yield Promise.all(e.map((t=>dt.loadChildRuns(t.id)))),o=yield Promise.all(i.map((t=>{var e;return null!==(e=t.childRuns.find((t=>"true"===t.func.options.isMain)))&&void 0!==e?e:t.childRuns.find((t=>t.func.nqName===this.initialConfig[this.initialConfig.length-1].funcName))})).map((t=>dt.loadRun(t.id)))),s=[...t.shell.views].find((t=>t.type===v)),r=yield se.fromComparedRuns(o,o[0].func,{parentView:s,parentCall:n});t.shell.addView(r)}))}onBeforeStepFuncCallApply(t,e,n){return In(this,void 0,void 0,(function*(){}))}onAfterStepFuncCallApply(t,e,n){return In(this,void 0,void 0,(function*(){}))}buildIO(){const t=Object.values(this.steps).reduce(((t,e)=>Object.assign(Object.assign({},t),{[Sn(e)]:e.view.root})),{}),n=e.tabControl(t),i=Object.values(this.steps).map((t=>{const i=e.iconFA("exclamation-circle",null,"This step has inconsistent inputs");return a()(i).css({color:"var(--orange-2)","margin-left":"3px","padding-top":"1px"}),n.getPane(Sn(t)).header.appendChild(i),t.view.consistencyState.subscribe((t=>{"consistent"===t&&a()(i).hide(),"inconsistent"===t&&a()(i).show()}))}));this.subs.push(...i);const o=Object.values(this.steps).map((t=>t.view.consistencyState)),s=(0,c.merge)(...o).subscribe((()=>{o.map((t=>t.value)).some((t=>"inconsistent"===t))?this.consistencyState.next("inconsistent"):this.consistencyState.next("consistent")}));this.subs.push(s);const r=n.panes[0].header.parentElement;r.classList.add("d4-ribbon","pipeline-view"),r.classList.remove("d4-tab-header-stripe"),r.firstChild.remove();for(let t=0;t<n.panes.length;t++)n.panes[t].header.classList.add("d4-ribbon-name"),n.panes[t].header.classList.remove("d4-tab-header");return n.panes[0].header.style.marginLeft="12px",n.root.style.height="100%",n.root.style.width="100%",this.stepTabs=n,this.initialConfig.forEach((t=>{const e=Tn(t);this.subs.push(this.steps[e].visibility.subscribe((t=>{t===S.VISIBLE&&a()(this.stepTabs.getPane(Sn(this.steps[e])).header).css("display","inherit"),t===S.HIDDEN&&a()(this.stepTabs.getPane(Sn(this.steps[e])).header).hide()})))})),Object.values(this.steps).forEach((t=>{this.subs.push(t.ability.subscribe((e=>{e===T.ENABLED&&a()(this.stepTabs.getPane(Sn(t)).header).removeClass("d4-disabled"),e===T.DISABLED&&a()(this.stepTabs.getPane(Sn(t)).header).addClass("d4-disabled")})))})),this.hideSteps(...this.initialConfig.filter((t=>t.hiddenOnInit===S.HIDDEN)).map((t=>t.funcName))),n.root}showHelpWithDelay(n){return In(this,void 0,void 0,(function*(){t.shell.windows.help.visible=!0,yield new Promise((t=>setTimeout(t,100))),t.shell.windows.help.showHelp(e.markdown(this.helpFiles[n.func.nqName]))}))}findCurrentStep(){return Object.values(this.steps).find((t=>Sn(t)===this.stepTabs.currentPane.name))}buildHistoryBlock(){const e=super.buildHistoryBlock(),n=this.historyBlock.afterRunDeleted.subscribe((e=>In(this,void 0,void 0,(function*(){(yield t.dapi.functions.calls.allPackageVersions().filter(`options.parentCallId="${e.id}"`).list()).map((t=>In(this,void 0,void 0,(function*(){return dt.deleteRun(t)}))))}))));return this.subs.push(n),e}getHelpState(){return In(this,void 0,void 0,(function*(){return"closed"===(yield t.dapi.userDataStorage.getValue(E,`${this.func.name}_help_state`))?"closed":"opened"}))}saveHelpState(e){return In(this,void 0,void 0,(function*(){return t.dapi.userDataStorage.postValue(E,`${this.func.name}_help_state`,e)}))}buildRibbonPanels(){const n=e.iconFA("info",(()=>In(this,void 0,void 0,(function*(){const t=this.findCurrentStep();t&&this.helpFiles[t.func.nqName]&&(yield this.showHelpWithDelay(t),this.saveHelpState("opened"))})))),i=()=>{var e,i,o;const s=this.findCurrentStep(),r=[[...super.buildRibbonPanels().flat(),...s&&(null===(o=this.steps[null!==(i=null===(e=s.options)||void 0===e?void 0:e.customId)&&void 0!==i?i:s.func.nqName].options)||void 0===o?void 0:o.helpUrl)?[n]:[]],...s?s.view.buildRibbonPanels():[]];return this.setRibbonPanels(r),s&&this.helpFiles[s.func.nqName]&&t.shell.windows.help.visible&&this.showHelpWithDelay(s),r};if(!this.isReady.value){const n=this.stepTabs.onTabChanged.subscribe(i),o=t.events.onEvent("grok-panels-changed").pipe((0,s.filter)((()=>t.shell.v===this))).subscribe((()=>In(this,void 0,void 0,(function*(){const n=yield this.getHelpState();if(t.shell.windows.help.visible&&"closed"===n)this.saveHelpState("opened");else if(!t.shell.windows.help.visible&&"opened"===n){const n=e.iconFA("info");return a()(n).css("margin","0px 3px"),t.shell.info(e.span(["You can open help panel by clicking the",n,"button on the ribbon menu"])),void this.saveHelpState("closed")}}))));this.subs.push(n,o)}return i()}saveRun(t){return In(this,void 0,void 0,(function*(){let e=_t(t);yield this.onBeforeSaveRun(e),J(t)&&(e=yield q(t)),e.id&&e.newId();const n=Object.values(this.steps).filter((t=>t.visibility.value===S.VISIBLE)).map((t=>In(this,void 0,void 0,(function*(){var n,i;const o=t.view.funcCall;return o.options.parentCallId=e.id,(null===(n=t.options)||void 0===n?void 0:n.customId)&&(o.options.customId=null===(i=t.options)||void 0===i?void 0:i.customId),yield t.view.saveRun(o),Promise.resolve()}))));yield Promise.all(n),e.options.title&&(e.options.title=`${e.options.title} (copy)`);const i=yield dt.saveRun(e),o=yield dt.loadRun(i.id);return this.options.historyEnabled&&this.isHistoryEnabled&&this.historyBlock&&this.historyBlock.addRun(yield dt.loadRun(i.id)),this.linkFunccall(o),this.isHistorical.next(!0),yield this.onAfterSaveRun(e),i}))}loadRun(t){return In(this,void 0,void 0,(function*(){const{parentRun:e,childRuns:n}=yield dt.loadChildRuns(t),i=Object.values(this.steps).filter((t=>t.visibility.value===S.VISIBLE)).findIndex((t=>Sn(t)===this.stepTabs.currentPane.name));yield this.onBeforeLoadRun();for(const t of Object.values(this.steps)){const e=n.filter((e=>e.func.nqName===t.func.nqName));if(0===e.length&&(t.visibility.next(S.HIDDEN),t.ability.next(T.DISABLED)),1===e.length&&(yield t.view.loadRun(e[0].id),t.visibility.next(S.VISIBLE),J(e[0])?t.ability.next(T.DISABLED):t.ability.next(T.ENABLED)),e.length>1){const n=e.find((e=>{var n;return e.options.customId===(null===(n=t.options)||void 0===n?void 0:n.customId)}));yield t.view.loadRun(n.id),t.visibility.next(S.VISIBLE),J(n)?t.ability.next(T.DISABLED):t.ability.next(T.ENABLED)}}const o=Object.values(this.steps).find((t=>t.ability.value===T.DISABLED&&t.visibility.value===S.VISIBLE)),s=null!=o?o:Object.values(this.steps)[0];if(s.ability.next(T.ENABLED),o){let t=this.getNextStep(o);for(;t;)t.ability.next(T.DISABLED),t=this.getNextStep(t)}this.lastCall=e,this.linkFunccall(e),this.isHistorical.next(!0);const r=Object.values(this.steps).filter((t=>t.visibility.value==S.VISIBLE)).at(i);return r&&r.ability.value===T.ENABLED?this.currentTabName=Sn(r):this.currentTabName=Sn(s),yield this.onAfterLoadRun(e),e}))}hideSteps(...t){return In(this,void 0,void 0,(function*(){t.forEach((t=>{this.steps[t].visibility.next(S.HIDDEN)}))}))}showSteps(...t){return In(this,void 0,void 0,(function*(){t.forEach((t=>{this.steps[t].visibility.next(S.VISIBLE)}))}))}exportRunJson(){return In(this,void 0,void 0,(function*(){if(this._lastCall){const t={isPipeline:!0};for(const[e,n]of Object.entries(this.steps)){const i=n.view.lastCall;i&&(t[e]=yield rt(i,n.view))}return ae(t,0)}}))}executeTest(t){return In(this,arguments,void 0,(function*(t,e=!1){yield be(t,this,{updateMode:e,interactive:!0})}))}getStepViewRuns(t){return this.onStepCompleted.pipe((0,s.filter)((e=>e.func.nqName===t)),(0,s.map)((()=>this.getStepView(t))))}}var xn=n(362),Rn={};Rn.styleTagTransform=It(),Rn.setAttributes=bt(),Rn.insert=gt().bind(null,"head"),Rn.domAPI=mt(),Rn.insertStyleElement=At(),ht()(xn.A,Rn),xn.A&&xn.A.locals&&xn.A.locals;var On,Pn;!function(t){t.INCORRECT_SIZE_TYPE="Size must be an integer.",t.SIZE_MUST_BE_POSITIVE="Size must be positive."}(On||(On={})),function(t){t[t.BATCH_SIZE=100]="BATCH_SIZE",t[t.MS_TO_SLEEP=10]="MS_TO_SLEEP"}(Pn||(Pn={}));const kn=t=>new Promise(((e,n)=>setTimeout(e,t)));function Fn(t){if(!Number.isInteger(t))throw new Error(On.INCORRECT_SIZE_TYPE);if(t<1)throw new Error(On.SIZE_MUST_BE_POSITIVE)}function Ln(t){return e=this,n=void 0,s=function*(){const e=[],n=o.TaskBarProgressIndicator.create("Running sensitivity analysis...");n.cancelable=!0;let i=0;const s=t.length;for(let o=0;o<s&&(e.push(yield t[o].call()),1===o&&(n.update(100*o/s,"Running sensitivity analysis..."),yield kn(10*Pn.MS_TO_SLEEP)),++i,!n.canceled);++o)i>=Pn.BATCH_SIZE&&(n.update(100*o/s,"Running sensitivity analysis..."),yield kn(Pn.MS_TO_SLEEP),i=0);return n.close(),e},new((i=void 0)||(i=Promise))((function(t,o){function r(t){try{l(s.next(t))}catch(t){o(t)}}function a(t){try{l(s.throw(t))}catch(t){o(t)}}function l(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i((function(t){t(n)}))).then(r,a)}l((s=s.apply(e,n||[])).next())}));var e,n,i,s}class Nn{constructor(t=1,e=1){Fn(t),Fn(e),this.N=t,this.d=e,this.A=this.generateMatrix(t,e),this.B=this.generateMatrix(t,e),this.AB=this.createMixMatrax(this.A,this.B)}generateMatrix(t,e){const n=new Array(e);for(let i=0;i<e;++i){n[i]=new Float32Array(t);for(let e=0;e<t;++e)n[i][e]=Math.random()}return n}createMixMatrax(t,e){const n=this.d,i=new Array(n);for(let o=0;o<n;++o){i[o]=new Array(0);for(let s=0;s<n;++s)o!==s?i[o].push(t[s]):i[o].push(e[s])}return i}getRow(t,e){const n=new Float32Array(this.d);for(let i=0;i<this.d;++i)n[i]=t[i][e];return n}getRowOfMatrixA(t){return this.getRow(this.A,t)}getRowOfMatrixB(t){return this.getRow(this.B,t)}getRowOfMatrixAB(t,e){return this.getRow(this.AB[t],e)}getConcatenatedColumns(){const t=new Array(0),e=this.N,n=this.d;for(let i=0;i<n;++i){const o=new Float32Array(e*(n+2));o.set(this.A[i]),o.set(this.B[i],e);for(let t=0;t<n;++t)o.set(this.AB[t][i],2*e+e*t);t.push(o)}return t}}const Bn="Unsupported output type.";function Mn(e,n){const i=e.rowCount,s=n.value.row;if(null!==s)return e.columns.names().map((t=>({idx:s,columnName:t})));const r=e.col(n.value.colName);if(null===r)return t.shell.warning(`Output dataframe "${e.name}" doesn't contain the "${n.value.colName}" column. The last row is analyzed.`),e.columns.names().map((t=>({idx:i-1,columnName:t})));if(r.type!==o.COLUMN_TYPE.INT&&r.type!==o.COLUMN_TYPE.FLOAT)return t.shell.warning(`Non-supported type of the "${n.value.colName}" column: ${r.type}. Last row of the output dataframe "${e.name}" is analyzed.`),e.columns.names().map((t=>({idx:i-1,columnName:t})));const a=r.getRawData(),l=n.value.colValue;let u,c=0,d=Math.abs(a[0]-l);for(let t=1;t<i;++t)u=Math.abs(a[t]-l),u<d&&(d=u,c=t);return e.columns.names().map((t=>({idx:c,columnName:t})))}function _n(t,e){var n,i,s;if(t.length<1)throw new Error("Funccall array is empty.");const r=t.length,a=function(t,e){const n=[];for(const i of e)i.prop.propertyType==o.TYPE.DATA_FRAME?n.push({prop:i.prop,elements:Mn(t.outputs[i.prop.name],i)}):n.push({prop:i.prop,elements:[]});return n}(t[0],e),l=function(t,e,n){var i;const s=[];for(const r of e){const e=r.prop,a=e.name;switch(e.propertyType){case o.TYPE.BIG_INT:case o.TYPE.INT:case o.TYPE.FLOAT:s.push(o.Column.fromType(e.propertyType,a,n));break;case o.TYPE.DATA_FRAME:const l=t.outputs[a];if(r.elements)for(const t of r.elements)s.push(o.Column.fromType(null===(i=l.col(t.columnName))||void 0===i?void 0:i.type,t.columnName,n));break;default:throw new Error(Bn)}}return o.DataFrame.fromColumns(s)}(t[0],a,r);for(let e=0;e<r;++e)for(const r of a){const a=r.prop,u=a.name,c=t[e];switch(a.propertyType){case o.TYPE.BIG_INT:case o.TYPE.INT:case o.TYPE.FLOAT:null===(n=l.col(u))||void 0===n||n.set(e,c.outputs[u]);break;case o.TYPE.DATA_FRAME:const t=c.outputs[u],a=t.rowCount-1;if(r.elements)for(const n of r.elements)null===(i=l.col(n.columnName))||void 0===i||i.set(e,null===(s=t.col(n.columnName))||void 0===s?void 0:s.get(-1!==n.idx?n.idx:a));break;default:throw new Error(Bn)}}return l}function Dn(t,e){const n=function(t,e){return e.forEach((e=>{t.forEach((t=>{t.name===e.name&&(t.name=`${t.name} (input)`,e.name=`${e.name} (output)`)}))})),t.concat(e)}(t,e),i=n.length;if(0===i)return o.DataFrame.create();const s=o.DataFrame.fromColumns([n[0]]);for(let t=1;t<i;++t)n[t].name=s.columns.getUnusedName(n[t].name),s.columns.add(n[t]);return s}class Vn{constructor(t,e,n,i,s){Fn(s),this.samplesCount=s,this.fixedInputs=e,this.func=t;const r=function(t,e){const n=e.length,i=function(t,e){return new Nn(t,e).getConcatenatedColumns()}(t,n);return[...Array(n).keys()].map((t=>function(t,e){var n;const i=e.length,s=o.Column.fromType(t.prop.propertyType,null!==(n=t.prop.caption)&&void 0!==n?n:t.prop.name,i),r=s.getRawData(),a=t.max-t.min;for(let n=0;n<i;++n)r[n]=t.min+a*e[n];return s}(e[t],i[t])))}(s,n);this.dimension=n.length,this.variedInputs=[...Array(this.dimension).keys()].map((t=>({prop:n[t].prop,min:n[t].min,max:n[t].max,column:r[t]}))),this.runsCount=s*(this.dimension+2),this.funcCalls=[];for(let n=0;n<this.runsCount;++n){const i={};for(const t of e)i[t.name]=t.value;for(const t of this.variedInputs)i[t.prop.name]=t.column.get(n);this.funcCalls.push(t.prepare(i))}this.outputsOfInterest=i}getSobolIndeces(t){const e=this.dimension,n=this.samplesCount,i=new Float32Array(e),s=new Float32Array(e),r=t.getRawData(),a=2*n;let l=0,u=0;for(let t=0;t<a;++t)l+=r[t],u+=r[t]*r[t];const c=l/a,d=u/a-c*c;if(0===d)i.fill(0),s.fill(0);else for(let t=0;t<e;++t){let e=0,o=0,a=0;for(let i=0;i<n;++i)a=r[(2+t)*n+i]-r[i],e+=r[n+i]*a,o+=a*a;i[t]=e/(n*d),s[t]=o/(2*n*d)}return{firstOrder:o.Column.fromFloat32Array(t.name,i),totalOrder:o.Column.fromFloat32Array(t.name,s)}}perform(){return t=this,e=void 0,i=function*(){this.funcCalls=yield Ln(this.funcCalls);const t=this.variedInputs.map((t=>t.column)),e=_n(this.funcCalls,this.outputsOfInterest).columns.toList(),n=Dn(t,e);n.name=`Sensitivity Analysis of ${this.func.friendlyName}`;const i=e.map((t=>this.getSobolIndeces(t))),s=o.Column.fromStrings("input",t.map((t=>t.name))),r=[s],a=[s];for(const t of i)r.push(t.firstOrder),a.push(t.totalOrder);const l=o.DataFrame.fromColumns(r);l.name="First order Sobol' indices";const u=o.DataFrame.fromColumns(a);return u.name="Total order Sobol' indices",{funcEvalResults:n,funcCalls:this.funcCalls,firstOrderSobolIndices:l,totalOrderSobolIndices:u}},new((n=void 0)||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}));var t,e,n,i}}class jn{constructor(t,e,n,i,s){Fn(s),this.func=t;const r=function(t,e){var n;const i=[];for(const s of e){const e=o.Column.fromType(s.prop.propertyType,null!==(n=s.prop.caption)&&void 0!==n?n:s.prop.name,t),r=e.getRawData(),a=s.max-s.min;for(let e=0;e<t;++e)r[e]=s.min+a*Math.random();i.push(e)}return i}(s,n);this.dimension=n.length,this.variedInputs=[...Array(this.dimension).keys()].map((t=>({prop:n[t].prop,min:n[t].min,max:n[t].max,column:r[t]}))),this.funcCalls=[];for(let n=0;n<s;++n){const i={};for(const t of e)i[t.name]=t.value;for(const t of this.variedInputs)i[t.prop.name]=t.column.get(n);this.funcCalls.push(t.prepare(i))}this.outputsOfInterest=i}perform(){return t=this,e=void 0,i=function*(){this.funcCalls=yield Ln(this.funcCalls);const t=Dn(this.variedInputs.map((t=>t.column)),_n(this.funcCalls,this.outputsOfInterest).columns.toList());return t.name=`Sensitivity Analysis of ${this.func.friendlyName}`,{funcEvalResults:t,funcCalls:this.funcCalls}},new((n=void 0)||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}));var t,e,n,i}}var $n,Hn,Un=n(993),Yn={};Yn.styleTagTransform=It(),Yn.setAttributes=bt(),Yn.insert=gt().bind(null,"head"),Yn.domAPI=mt(),Yn.insertStyleElement=At(),ht()(Un.A,Yn),Un.A&&Un.A.locals&&Un.A.locals,function(t){t[t.COR_PLOT=.5]="COR_PLOT",t[t.PC_PLOT=.6]="PC_PLOT",t[t.GRAPH=.6]="GRAPH",t[t.BAR_CHART=.2]="BAR_CHART"}($n||($n={})),function(t){t.METHOD="`Method`",t.SAMPLES="`Samples`"}(Hn||(Hn={}));const Wn=`# Sensitivity Analysis\n\nSensitivity Analysis runs the computation multiple times with varying inputs, \nand analyzes the relationship between inputs and outputs.\n\nUse one of the following methods:\n\n* [Monte Carlo](https://en.wikipedia.org/wiki/Monte_Carlo_method) explores a function \nat randomly taken points\n\n* [Sobol](https://en.wikipedia.org/wiki/Variance-based_sensitivity_analysis)\ndecomposes output variance into fractions, which can be attributed to inputs\n\n* **Grid** studies a function at the points of a grid with the specified step\n\n## Monte Carlo\n\nOnce you've chosen it in ${Hn.METHOD}\n\n* Set in ${Hn.SAMPLES} the number of random points \n\n* Use switchers to specify varied inputs and outputs to be analyzed\n\n* Press **Run** or <i class="fas fa-play"></i> on the top panel. You will get \n\n * [Correlation plot](https://datagrok.ai/help/visualize/viewers/correlation-plot) for exploring\ncorrelations between varied inputs and the specified outputs\n\n * [PC plot](https://datagrok.ai/help/visualize/viewers/pc-plot) visualizing multivariate data\nand providing variations of the selected inputs & outputs\n\n * [Line chart](https://datagrok.ai/help/visualize/viewers/line-chart) or \n[Scatterplot](https://datagrok.ai/help/visualize/viewers/scatter-plot) (dependently on the varied\ninputs count) showing a behavior of each output separately\n\n * [Grid](https://datagrok.ai/help/visualize/viewers/grid) containing inputs and outputs values \nof each function evaluation\n\n* Press <i class="grok-icon fal fa-question"></i> on the top panel to learn more about \n[Sensitivity Analysis](https://datagrok.ai/help/compute/#sensitivity-analysis)\n\n## Sobol\n\nThis method performs \n[variance-based sensitivity analysis](https://en.wikipedia.org/wiki/Variance-based_sensitivity_analysis). \nIt provides the same visualizations \nas **Monte Carlo** and [bar charts](https://datagrok.ai/help/visualize/viewers/bar-chart) showing \nSobol' indices:\n\n* First-order indices indicate the contribution to the output variance of varying each input alone\n\n* Total-order indices measure the contribution to the output variance of each input,\n including all variance caused by its interactions with any other inputs\n \n ## Grid\n \n This method provides the same visualization as the previous ones. Unlike them, it evaluates a function \n at the points of uniform grid within the specified ranges.`;var Gn=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const zn=[o.TYPE.INT,o.TYPE.BIG_INT,o.TYPE.FLOAT,o.TYPE.BOOL,o.TYPE.DATA_FRAME],qn=[o.TYPE.INT,o.TYPE.BIG_INT,o.TYPE.FLOAT,o.TYPE.BOOL,o.TYPE.DATA_FRAME];var Jn,Kn;!function(t){t.GRID_ANALYSIS="Grid",t.RANDOM_ANALYSIS="Monte Carlo",t.SOBOL_ANALYSIS="Sobol"}(Jn||(Jn={})),function(t){t.LAST_ROW="Last row",t.FIRST_ROW="First row",t.ALL_COLUMNS="",t.BY_COL_VAL="By value in column"}(Kn||(Kn={}));const Zn=()=>e.div([],"sa-switch-input");class Xn{static fromEmpty(e){return Gn(this,arguments,void 0,(function*(e,n={parentView:void 0,parentCall:void 0}){const i=[...t.shell.views].find((t=>t.type===v)),o=yield se.fromComparedRuns([],e,{parentView:i,parentCall:n.parentCall});t.shell.addView(o),new this(e,o,n)}))}constructor(t,n,i={parentView:void 0,parentCall:void 0,configFunc:void 0}){this.func=t,this.options=i,this.generateInputFields=t=>{const n={analysisType:{input:e.input.choice("Method",{value:Jn.RANDOM_ANALYSIS,items:[Jn.RANDOM_ANALYSIS,Jn.SOBOL_ANALYSIS,Jn.GRID_ANALYSIS],onValueChanged:()=>{const t=n.analysisType.input.value;n.analysisType.value.next(t),this.updateRunWidgetsState(),this.setAnalysisInputTooltip(),this.store.analysisInputs.samplesCount.input.setTooltip(this.samplesCountTooltip())}}),value:new c.BehaviorSubject(Jn.RANDOM_ANALYSIS)},samplesCount:{input:e.input.int("Samples",{value:10,onValueChanged:()=>{n.samplesCount.value=n.samplesCount.input.value,this.updateRunWidgetsState()}}),value:10}};n.analysisType.input.root.insertBefore(Zn(),n.analysisType.input.captionLabel),n.samplesCount.input.root.insertBefore(Zn(),n.samplesCount.input.captionLabel);const i=(t,e)=>void 0===t.options[e]?Bt(t):Number(t.options[e]),s=(t,n,i=!0)=>{const o=e.input.toggle(" ",{value:t,onValueChanged:()=>n(o.value)});return a()(o.root).addClass("sa-switch-input"),a()(o.captionLabel).hide(),e.tooltip.bind(o.root,(()=>i?o.value?"Switch to mark input as immutable":"Switch to mark input as mutable":o.value?"Switch to mark output as not requiring analysis":"Switch to mark output as requiring analysis")),o},r=t.inputs.reduce(((t,r)=>{const l=i(r,"default");switch(r.propertyType){case o.TYPE.INT:case o.TYPE.BIG_INT:case o.TYPE.FLOAT:const u=s(!1,(t=>{f.isChanging.next(t),this.updateRunWidgetsState()})),d=s(!1,(t=>{f.isChanging.next(t),this.updateRunWidgetsState()})),p={type:r.propertyType,prop:r,const:{input:(()=>{var t;const n=e.input.float(null!==(t=r.caption)&&void 0!==t?t:r.name,{value:Bt(r),onValueChanged:()=>f.const.value=n.value});return n.root.insertBefore(d.root,n.captionLabel),n.addPostfix(r.options.units),n})(),value:Bt(r)},min:{input:(()=>{var t;const n=e.input.float(`${null!==(t=r.caption)&&void 0!==t?t:r.name} min`,{value:i(r,"min"),onValueChanged:()=>f.min.value=n.value});return n.root.insertBefore(u.root,n.captionLabel),n.addPostfix(r.options.units),n})(),value:i(r,"min")},max:{input:(()=>{var t;const n=e.input.float(`${null!==(t=r.caption)&&void 0!==t?t:r.name} max`,{value:i(r,"max"),onValueChanged:()=>f.max.value=n.value});return n.addPostfix(r.options.units),n})(),value:i(r,"max")},lvl:{input:e.input.int("Samples",{value:3,onValueChanged:()=>{const t=p.lvl.input.value;f.lvl.value=t,this.updateRunWidgetsState()}}),value:3},isChanging:new c.BehaviorSubject(!1)};[p.max.input,p.lvl.input].forEach((t=>{t.root.insertBefore(Zn(),t.captionLabel),a()(t.root).removeProp("display")}));const h=[p.lvl.input];t[r.name]=Object.assign(Object.assign({},p),{constForm:[p.const.input],saForm:[p.min.input,p.max.input,...h]});const f=t[r.name];f.isChanging.subscribe((t=>{u.notify=!1,u.value=t,u.notify=!0,d.notify=!1,d.value=t,d.notify=!0})),(0,c.combineLatest)([p.isChanging,n.analysisType.value]).subscribe((([t,e])=>{t?(f.constForm.forEach((t=>a()(t.root).hide())),f.saForm.forEach((t=>a()(t.root).css("display","flex"))),h.forEach((t=>e===Jn.GRID_ANALYSIS?a()(t.root).css("display","flex"):a()(t.root).hide()))):(f.constForm.forEach((t=>a()(t.root).css("display","flex"))),f.saForm.forEach((t=>a()(t.root).hide())))}));break;case o.TYPE.BOOL:const m=s(!1,(t=>{g.isChanging.next(t),this.updateRunWidgetsState()})),v={type:r.propertyType,prop:r,const:{input:(()=>{var t,n;const i=e.input.bool(`${null!==(t=r.caption)&&void 0!==t?t:r.name}`,{value:null!==(n=Bt(r))&&void 0!==n&&n,onValueChanged:()=>g.const.value=v.const.input.value});return i.root.insertBefore(m.root,i.captionLabel),i})(),value:l},isChanging:new c.BehaviorSubject(!1),lvl:1};t[r.name]=Object.assign(Object.assign({},v),{constForm:[v.const.input],saForm:[]});const g=t[r.name];g.isChanging.subscribe((t=>{g.lvl=t?2:1}));break;default:const y=Zn(),b={input:(()=>{const t=e.input.forProperty(r,void 0,{onValueChanged:t=>b.value=t.value});return t.root.insertBefore(y,t.captionLabel),t.addPostfix(r.options.units),t})(),value:Bt(r)};t[r.name]={const:b,constForm:[b.input],saForm:[],type:r.propertyType,prop:r,isChanging:new c.BehaviorSubject(!1)}}return t}),{}),l=t.outputs.reduce(((t,n)=>{const i={prop:n,input:(()=>{var t;const r=null!==(t=n.caption)&&void 0!==t?t:n.name;let a;n.propertyType===o.TYPE.DATA_FRAME?(a=e.input.choice(r,{value:Kn.LAST_ROW,items:[Kn.LAST_ROW,Kn.FIRST_ROW,Kn.BY_COL_VAL],onValueChanged:()=>{const t=a.value;i.value.returning=t,i.analysisInputs.forEach((e=>{e.root.hidden=t!==Kn.BY_COL_VAL})),a.setTooltip(this.getOutputTooltip(r,t))}}),a.setTooltip(this.getOutputTooltip(r,Kn.LAST_ROW))):(a=e.input.forProperty(n),a.setTooltip("Scalar")),a.addCaption(r);const l=qn.includes(n.propertyType)?s(!0,(t=>{i.isInterest.next(t),i.analysisInputs.forEach((t=>{t.root.hidden=i.value.returning!==Kn.BY_COL_VAL})),this.updateRunWidgetsState(),n.propertyType===o.TYPE.DATA_FRAME&&a.setTooltip(t?this.getOutputTooltip(r,Kn.LAST_ROW):"Dataframe")}),!1).root:Zn();return a.root.insertBefore(l,a.captionLabel),a})(),analysisInputs:n.propertyType===o.TYPE.DATA_FRAME?[(()=>{var t;const o=e.input.string("Column",{value:Kn.ALL_COLUMNS,onValueChanged:()=>{i.value.colName=o.value}});return o.root.insertBefore(Zn(),o.captionLabel),o.root.hidden=!0,o.setTooltip(`Name of column of the '${null!==(t=n.caption)&&void 0!==t?t:n.name}' dataframe`),o})(),(()=>{var t;const o=e.input.float("Value",{value:0,onValueChanged:()=>{i.value.colValue=o.value}});return o.root.insertBefore(Zn(),o.captionLabel),o.root.hidden=!0,o.setTooltip(`Value specifying the '${null!==(t=n.caption)&&void 0!==t?t:n.name}' dataframe row`),o})()]:[],value:{returning:Kn.LAST_ROW,colName:Kn.ALL_COLUMNS,colValue:0},isInterest:new c.BehaviorSubject(!0)};return a()(i.input.input).css("visibility","hidden"),i.prop.propertyType===o.TYPE.DATA_FRAME&&i.isInterest.subscribe((t=>{i.analysisInputs.forEach((e=>t?a()(e.root).show():a()(e.root).hide())),a()(i.input.input).css("visibility",t?"visible":"hidden")})),t[n.name]=i,t}),{});return{analysisInputs:n,inputs:r,outputs:l}},this.openedViewers=[],this.gridSubscription=null,this.store=this.generateInputFields(this.func),this.runButton=e.bigButton("Run",(()=>Gn(this,void 0,void 0,(function*(){return yield this.runAnalysis()})))),this.runIcon=e.iconFA("play",(()=>Gn(this,void 0,void 0,(function*(){return yield this.runAnalysis()})))),this.runIcon.style.color="var(--green-2)",this.runIcon.classList.add("fas"),this.helpIcon=e.iconFA("question",(()=>{window.open("https://datagrok.ai/help/compute.md#sensitivity-analysis","_blank")}),"Open help in a new tab");const s=this.buildFormWithBtn();this.runButton.disabled=!this.canEvaluationBeRun(),this.runIcon.hidden=this.runButton.disabled,this.addTooltips(),this.comparisonView=n,this.comparisonView.dockManager.dock(s,o.DOCK_TYPE.LEFT,null,`${this.func.name} - Sensitivity Analysis`,.25),this.comparisonView.grid.columns.byName("Run name").visible=!1;const r=this.comparisonView.getRibbonPanels();r.push([this.helpIcon,this.runIcon]),this.comparisonView.setRibbonPanels(r),this.comparisonView.helpUrl="https://datagrok.ai/help/compute.md#sensitivity-analysis",this.tableDockNode=this.comparisonView.dockManager.findNode(this.comparisonView.grid.root);const l=e.markdown(Wn);l.style.padding="10px",l.style.overflow="auto",this.helpMdNode=this.comparisonView.dockManager.dock(l,o.DOCK_TYPE.FILL,this.tableDockNode,"About")}closeOpenedViewers(){for(const t of this.openedViewers)t.close();this.openedViewers.splice(0),this.helpMdNode&&(this.helpMdNode.detachFromParent(),this.helpMdNode.container.destroy(),this.helpMdNode=void 0),this.gridSubscription&&(this.gridSubscription.unsubscribe(),this.gridSubscription=null)}getFuncCallCount(t,e){let n=0;switch(t.analysisType.value.value){case Jn.GRID_ANALYSIS:let i=1;const s=t=>t.type===o.TYPE.INT||t.type===o.TYPE.BIG_INT||t.type===o.TYPE.FLOAT;for(const t of Object.values(e))t.isChanging.value&&(i*=s(t)?t.lvl.value:t.lvl,++n);return 0===n?0:i;case Jn.RANDOM_ANALYSIS:return t.samplesCount.value;case Jn.SOBOL_ANALYSIS:for(const t of Object.keys(e))e[t].isChanging.value&&++n;return 0===n?0:(n+2)*t.samplesCount.value;default:return 0}}getFuncCallCountAsString(){if(!this.canEvaluationBeRun())return"0";const t=this.getFuncCallCount(this.store.analysisInputs,this.store.inputs);return t<1e3?String(t):t<1e6?String(Math.ceil(t/10)/100)+"k":t<1e9?String(Math.ceil(t/1e4)/100)+"m":String(Math.ceil(t/1e7)/100)+"b"}updateRunWidgetsState(){this.runButton.textContent=`Run (${this.getFuncCallCountAsString()})`,this.runButton.disabled=!this.canEvaluationBeRun(),this.runIcon.hidden=this.runButton.disabled}buildFormWithBtn(){let t="Misc";const n=Object.values(this.store.inputs).reduce(((n,i)=>{const o=i.prop;return o.category!==t&&(n.append(e.h2(o.category)),t=o.category),n.append(...i.constForm.map((t=>t.root)),...i.saForm.map((t=>t.root))),n}),e.div([this.store.analysisInputs.analysisType.input,this.store.analysisInputs.samplesCount.input],{style:{"overflow-y":"scroll",width:"100%"}}));a()(n).addClass("ui-form");const i=e.h2("Outputs");n.appendChild(i),t="Misc";const o=Object.values(this.store.outputs).reduce(((n,i)=>{const o=i.prop;return o.category!==t&&(n.append(e.h2(o.category)),t=o.category),n.append(i.input.root,...i.analysisInputs.map((t=>t.root))),n}),n);this.store.analysisInputs.analysisType.value.subscribe((t=>{t===Jn.GRID_ANALYSIS?a()(this.store.analysisInputs.samplesCount.input.root).hide():(a()(i).show(),a()(o).show(),a()(this.store.analysisInputs.samplesCount.input.root).show())}));let s=!1;for(const t of Object.keys(this.store.outputs))if(this.store.outputs[t].isInterest.value){s=!0;break}s||this.store.outputs[Object.keys(this.store.outputs)[0]].isInterest.next(!0),this.updateRunWidgetsState();const r=e.buttonsInput([this.runButton]);return n.appendChild(r),a()(n).css({"padding-left":"12px","overflow-y":"scroll","padding-right":"4px"}),n}setAnalysisInputTooltip(){let t;switch(this.store.analysisInputs.analysisType.value.value){case Jn.GRID_ANALYSIS:t="Grid analysis: the function is evaluated with respect to the selected inputs varying within the specified ranges";break;case Jn.RANDOM_ANALYSIS:t="Monte Carlo simulation: the function is evaluated with respect to random variation of the selected inputs within the specified ranges";break;case Jn.SOBOL_ANALYSIS:t="Variance-based sensitivity analysis: the Sobol' indices are computed";break;default:t="Unknown method!"}this.store.analysisInputs.analysisType.input.setTooltip(t)}getOutputTooltip(t,e){switch(e){case Kn.FIRST_ROW:return`To analyze first row of the '${t}' dataframe`;case Kn.LAST_ROW:return`To analyze last row of the '${t}' dataframe`;case Kn.BY_COL_VAL:return`To analyze "${t}"'s row defined by custom value in column`;default:return""}}samplesCountTooltip(){switch(this.store.analysisInputs.analysisType.value.value){case Jn.RANDOM_ANALYSIS:return"Input sets count";case Jn.SOBOL_ANALYSIS:return"Sample size for the Sobol' indices computation";default:return"Unknown method!"}}addTooltips(){var t;this.setAnalysisInputTooltip(),e.tooltip.bind(this.runButton,(()=>`Run sensitivity analysis: the function is evaluated ${this.getFuncCallCount(this.store.analysisInputs,this.store.inputs)} times`)),e.tooltip.bind(this.runIcon,(()=>`Run sensitivity analysis: the function is evaluated ${this.getFuncCallCount(this.store.analysisInputs,this.store.inputs)} times`)),this.store.analysisInputs.samplesCount.input.setTooltip(this.samplesCountTooltip());for(const e of Object.keys(this.store.inputs)){const n=this.store.inputs[e].prop.propertyType;if(n===o.TYPE.BOOL||n===o.TYPE.STRING)continue;const i=this.store.inputs[e],s=null!==(t=i.prop.caption)&&void 0!==t?t:i.prop.name;i.const.input.setTooltip(`'${s}' value`),i.min.input.setTooltip(`Min value of '${s}'`),i.max.input.setTooltip(`Max value of '${s}'`),i.lvl.input.setTooltip(`Number of samples along the axis '${s}'`)}}isAnyInputSelected(){for(const t of Object.keys(this.store.inputs))if(this.store.inputs[t].isChanging.value)return!0;return!1}isAnyOutputSelected(){for(const t of Object.keys(this.store.outputs))if(this.store.outputs[t].isInterest.value)return!0;return!1}canEvaluationBeRun(){return this.isAnyInputSelected()&&this.isAnyOutputSelected()}runAnalysis(){return Gn(this,void 0,void 0,(function*(){if(this.canEvaluationBeRun())switch(this.store.analysisInputs.analysisType.value.value){case Jn.GRID_ANALYSIS:yield this.runGridAnalysis();break;case Jn.RANDOM_ANALYSIS:yield this.runRandomAnalysis();break;case Jn.SOBOL_ANALYSIS:yield this.runSobolAnalysis()}}))}getFixedInputColumns(t){return Object.values(this.store.inputs).filter((t=>!zn.includes(t.type)||!t.isChanging.value)).map((e=>{var n;return o.Column.fromList(e.type,null!==(n=e.prop.caption)&&void 0!==n?n:e.prop.name,Array(t).fill(e.const.value))}))}runSobolAnalysis(){return Gn(this,void 0,void 0,(function*(){const n={func:this.func,fixedInputs:this.getFixedInputs().map((t=>({name:t,value:this.store.inputs[t].const.value}))),variedInputs:this.getVariedInputs().map((t=>{const e=this.store.inputs[t];return{prop:e.prop,min:e.min.value,max:e.max.value}})),samplesCount:this.store.analysisInputs.samplesCount.value||1},i=this.getOutputsOfInterest(),s=new Vn(n.func,n.fixedInputs,n.variedInputs,i,n.samplesCount),r=yield s.perform();this.closeOpenedViewers();const l=r.funcEvalResults,u=r.funcCalls,c=r.firstOrderSobolIndices,d=r.totalOrderSobolIndices,p=c.columns.names();this.comparisonView.dataFrame=l;const h=l.columns.names(),f=this.getFixedInputColumns(l.rowCount);for(const t of f)t.name=l.columns.getUnusedName(`${t.name} (fixed)`),l.columns.add(t);this.comparisonView.grid.columns.setVisible([h[0]]),this.comparisonView.grid.columns.setVisible(h),this.comparisonView.grid.props.rowHeight=25;const m=o.Viewer.correlationPlot(l,{xColumnNames:h,yColumnNames:h}),v=this.comparisonView.dockManager.dock(m,o.DOCK_TYPE.LEFT,this.tableDockNode,"",$n.COR_PLOT);this.openedViewers.push(m);const g=o.Viewer.pcPlot(l,{columnNames:h});this.comparisonView.dockManager.dock(g,o.DOCK_TYPE.DOWN,v,"",$n.PC_PLOT),this.openedViewers.push(g);const y=this.getOutputNameForScatterPlot(h,l,n.variedInputs.length),b=1===n.variedInputs.length?o.Viewer.lineChart(l,this.getLineChartOpt(h)):o.Viewer.scatterPlot(l,this.getScatterOpt(h,y));this.openedViewers.push(b),this.comparisonView.dockManager.dock(b,o.DOCK_TYPE.DOWN,this.tableDockNode,"",$n.GRAPH);const w=o.Viewer.barChart(c,this.getBarChartOpt(c.name,p[0],y)),A=this.comparisonView.dockManager.dock(w,o.DOCK_TYPE.RIGHT,void 0,"",$n.BAR_CHART),C=o.Viewer.barChart(d,this.getBarChartOpt(d.name,p[0],y));this.comparisonView.dockManager.dock(C,o.DOCK_TYPE.DOWN,A),this.openedViewers=this.openedViewers.concat([w,C]),this.gridSubscription=this.comparisonView.grid.onCellClick.subscribe((n=>{var i;const s=u[null!==(i=n.tableRowIndex)&&void 0!==i?i:0],r=[...s.outputParams.values()].filter((t=>o.TYPES_SCALAR.has(t.property.propertyType))),l=o.HtmlTable.create(r,(t=>{var e;return[null!==(e=t.property.caption)&&void 0!==e?e:t.property.name,s.outputs[t.property.name],t.property.options.units]})).root,c=[...s.outputParams.values()].filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME)).reduce(((t,e)=>{var n;const i=Dt(e.property).config,r=s.outputs[e.name],l=null!==(n=e.property.caption)&&void 0!==n?n:e.property.name;return i.map((e=>{const n=e.type,i=o.Viewer.fromType(n,r);i.setOptions(e),a()(i.root).css({width:"100%"}),t[l]?t[l].push(i.root):t[l]=[i.root]})),t}),{});let d,p;r.length>0?(p=1,d=Object.assign({"Output scalars":[l]},c)):(p=0,d=Object.assign({},c));const h=e.accordion();a()(h.root).css({width:"100%"}),Object.entries(d).map((t=>{h.addPane(t[0],(()=>e.divV(t[1])))})),h.panes[p].expanded=!0,t.shell.o=h.root}))}))}getFixedInputs(){return Object.keys(this.store.inputs).filter((t=>!zn.includes(this.store.inputs[t].type)||!this.store.inputs[t].isChanging.value))}getVariedInputs(){return Object.keys(this.store.inputs).filter((t=>!!zn.includes(this.store.inputs[t].type)&&this.store.inputs[t].isChanging.value))}runRandomAnalysis(){return Gn(this,void 0,void 0,(function*(){const n={func:this.func,fixedInputs:this.getFixedInputs().map((t=>({name:t,value:this.store.inputs[t].const.value}))),variedInputs:this.getVariedInputs().map((t=>{const e=this.store.inputs[t];return{prop:e.prop,min:e.min.value,max:e.max.value}})),samplesCount:this.store.analysisInputs.samplesCount.value||1},i=this.getOutputsOfInterest(),s=new jn(n.func,n.fixedInputs,n.variedInputs,i,n.samplesCount),r=yield s.perform(),l=r.funcEvalResults,u=r.funcCalls;this.closeOpenedViewers(),this.comparisonView.dataFrame=l;const c=l.columns.names(),d=this.getFixedInputColumns(l.rowCount);for(const t of d)t.name=l.columns.getUnusedName(`${t.name} (fixed)`),l.columns.add(t);this.comparisonView.grid.columns.setVisible([c[0]]),this.comparisonView.grid.columns.setVisible(c),this.comparisonView.grid.props.rowHeight=25;const p=o.Viewer.correlationPlot(l,{xColumnNames:c,yColumnNames:c}),h=this.comparisonView.dockManager.dock(p,o.DOCK_TYPE.LEFT,this.tableDockNode,"",$n.COR_PLOT);this.openedViewers.push(p);const f=o.Viewer.pcPlot(l,{columnNames:c});this.comparisonView.dockManager.dock(f,o.DOCK_TYPE.DOWN,h,"",$n.PC_PLOT),this.openedViewers.push(f);const m=this.getOutputNameForScatterPlot(c,l,n.variedInputs.length),v=1===n.variedInputs.length?o.Viewer.lineChart(l,this.getLineChartOpt(c)):o.Viewer.scatterPlot(l,this.getScatterOpt(c,m));this.openedViewers.push(v),this.comparisonView.dockManager.dock(v,o.DOCK_TYPE.DOWN,this.tableDockNode,"",$n.GRAPH),this.gridSubscription=this.comparisonView.grid.onCellClick.subscribe((n=>{var i;const s=u[null!==(i=n.tableRowIndex)&&void 0!==i?i:0],r=[...s.outputParams.values()].filter((t=>o.TYPES_SCALAR.has(t.property.propertyType))),l=o.HtmlTable.create(r,(t=>{var e;return[null!==(e=t.property.caption)&&void 0!==e?e:t.property.name,s.outputs[t.property.name],t.property.options.units]})).root,c=[...s.outputParams.values()].filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME)).reduce(((t,e)=>{var n;const i=Dt(e.property).config,r=s.outputs[e.name],l=null!==(n=e.property.caption)&&void 0!==n?n:e.property.name;return i.map((e=>{const n=e.type,i=o.Viewer.fromType(n,r);i.setOptions(e),a()(i.root).css({width:"100%"}),t[l]?t[l].push(i.root):t[l]=[i.root]})),t}),{});let d,p;r.length>0?(p=1,d=Object.assign({"Output scalars":[l]},c)):(p=0,d=Object.assign({},c));const h=e.accordion();a()(h.root).css({width:"100%"}),Object.entries(d).map((t=>{h.addPane(t[0],(()=>e.divV(t[1])))})),h.panes[p].expanded=!0,t.shell.o=h.root}))}))}runGridAnalysis(){return Gn(this,void 0,void 0,(function*(){var n,i;const s=Object.keys(this.store.inputs).reduce(((t,e)=>{switch(this.store.inputs[e].type){case o.TYPE.INT:case o.TYPE.BIG_INT:const n=this.store.inputs[e],i=(n.max.value-n.min.value)/(n.lvl.value-1);t[e]=n.isChanging.value?Array.from({length:n.lvl.value},((t,e)=>Math.round(n.min.value+e*i))):[n.const.value];break;case o.TYPE.FLOAT:const s=this.store.inputs[e],r=(s.max.value-s.min.value)/(s.lvl.value-1);t[e]=s.isChanging.value?Array.from({length:s.lvl.value},((t,e)=>s.min.value+e*r)):[s.const.value];break;case o.TYPE.BOOL:const a=this.store.inputs[e];t[e]=a.isChanging.value?[a.const.value,!a.const.value]:[a.const.value];break;default:const l=this.store.inputs[e];t[e]=[l.const.value]}return t}),{});let r=Object.values(s)[0].map((t=>[t]));for(let t=1;t<Object.values(s).length;t++){const e=Object.values(s)[t],n=[];for(const t of r)for(const i of e)n.push([...t,i]);r=n}const l=r.map((t=>this.func.prepare(this.func.inputs.map(((t,e)=>({name:t.name,idx:e}))).reduce(((e,{name:n,idx:i})=>(e[n]=t[i],e)),{})))),u=yield Ln(l);this.closeOpenedViewers();const c=[],d=u.length,p=this.getFixedInputColumns(d);for(const t of Object.keys(this.store.inputs)){const e=this.store.inputs[t],i=e.prop;e.isChanging.value&&c.push(o.Column.fromType(i.propertyType,null!==(n=i.caption)&&void 0!==n?n:i.name,d))}const h=[...c],f=h.length,m=o.DataFrame.fromColumns([h[0]]);for(let t=1;t<f;++t)h[t].name=m.columns.getUnusedName(h[t].name),m.columns.add(h[t]);for(let t=0;t<d;++t)for(const e of Object.keys(this.store.inputs)){const n=this.store.inputs[e],o=n.prop;n.isChanging.value&&m.set(null!==(i=o.caption)&&void 0!==i?i:o.name,t,u[t].inputs[e])}const v=this.getOutputsOfInterest(),g=_n(u,v).columns;for(const t of g)h.forEach((e=>{e.name===t.name&&(e.name=`${e.name} (input)`,t.name=`${t.name} (output)`)})),t.name=m.columns.getUnusedName(t.name),m.columns.add(t);const y=m.columns.names();for(const t of p)t.name=m.columns.getUnusedName(`${t.name} (fixed)`),m.columns.add(t);this.comparisonView.dataFrame=m,this.gridSubscription=this.comparisonView.grid.onCellClick.subscribe((n=>{var i;const s=u[null!==(i=n.tableRowIndex)&&void 0!==i?i:0],r=[...s.outputParams.values()].filter((t=>o.TYPES_SCALAR.has(t.property.propertyType))),l=o.HtmlTable.create(r,(t=>{var e;return[null!==(e=t.property.caption)&&void 0!==e?e:t.property.name,s.outputs[t.property.name],t.property.options.units]})).root,c=[...s.outputParams.values()].filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME)).reduce(((t,e)=>{var n;const i=Dt(e.property).config,r=s.outputs[e.name],l=null!==(n=e.property.caption)&&void 0!==n?n:e.property.name;return i.map((e=>{const n=e.type,i=o.Viewer.fromType(n,r);i.setOptions(e),a()(i.root).css({width:"100%"}),t[l]?t[l].push(i.root):t[l]=[i.root]})),t}),{});let d,p;r.length>0?(p=1,d=Object.assign({"Output scalars":[l]},c)):(p=0,d=Object.assign({},c));const h=e.accordion();a()(h.root).css({width:"100%"}),Object.entries(d).map((t=>{h.addPane(t[0],(()=>e.divV(t[1])))})),h.panes[p].expanded=!0,t.shell.o=h.root})),this.comparisonView.grid.columns.setVisible([y[0]]),this.comparisonView.grid.columns.setVisible(y),this.comparisonView.grid.props.rowHeight=25;const b=o.Viewer.correlationPlot(m,{xColumnNames:y,yColumnNames:y}),w=this.comparisonView.dockManager.dock(b,o.DOCK_TYPE.LEFT,this.tableDockNode,"",$n.COR_PLOT);this.openedViewers.push(b);const A=o.Viewer.pcPlot(m,{columnNames:y});this.comparisonView.dockManager.dock(A,o.DOCK_TYPE.DOWN,w,"",$n.PC_PLOT),this.openedViewers.push(A);const C=this.getOutputNameForScatterPlot(y,m,c.length),I=1===c.length?o.Viewer.lineChart(m,this.getLineChartOpt(y)):o.Viewer.scatterPlot(m,this.getScatterOpt(y,C));this.openedViewers.push(I),this.comparisonView.dockManager.dock(I,o.DOCK_TYPE.DOWN,this.tableDockNode,"",$n.GRAPH)}))}getOutputNameForScatterPlot(t,e,n){var i,o,s,r;for(let a=n;a<t.length;++a)if((null!==(o=null===(i=e.col(t[a]))||void 0===i?void 0:i.min)&&void 0!==o?o:0)<(null!==(r=null===(s=e.col(t[a]))||void 0===s?void 0:s.max)&&void 0!==r?r:0))return t[a];return t[n]}getOutputsOfInterest(){const t=[];for(const e of Object.keys(this.store.outputs)){const n=this.store.outputs[e];if(n.isInterest.value){let e;switch(n.value.returning){case Kn.LAST_ROW:e=-1;break;case Kn.FIRST_ROW:e=0;break;default:e=null}t.push({prop:n.prop,value:{row:e,colName:n.value.colName,colValue:n.value.colValue}})}}return t}getScatterOpt(t,e){return{xColumnName:t[0],yColumnName:t[1],colorColumnName:e,sizeColumnName:e,markerMaxSize:12,jitterSize:5}}getLineChartOpt(t){return{xColumnName:t[0],yColumnNames:t.slice(1,Math.min(t.length,8)),markerSize:1,markerType:o.MARKER_TYPE.GRADIENT,multiAxis:!0}}getBarChartOpt(t,e,n){return{description:t,splitColumnName:e,valueColumnName:n,valueAggrType:o.AGG.AVG,showTitle:!1,showCategorySelector:!1,showStackSelector:!1,showValueAxis:!1}}}var Qn;!function(t){t.NELDER_MEAD="Nelder-Mead",t.GRAD_DESC="Gradient descent"}(Qn||(Qn={}));const ti=new Map([[Qn.NELDER_MEAD,"The Nelder-Mead method"],[Qn.GRAD_DESC,"The gradient descent method"]]);var ei;!function(t){t.MAD="MAD",t.RMSE="RMSE"}(ei||(ei={}));const ni=new Map([[ei.MAD,"Maximum absolute deviation"],[ei.RMSE,"Root mean square error"]]);var ii,oi,si,ri;!function(t){t[t.LOSS_COL_WIDTH=60]="LOSS_COL_WIDTH",t[t.ROW_HEIGHT=180]="ROW_HEIGHT",t[t.LOSS_GRAPH_WIDTH=360]="LOSS_GRAPH_WIDTH",t[t.GOF_VIEWER_WIDTH=240]="GOF_VIEWER_WIDTH"}(ii||(ii={})),function(t){t.ITER="Iteration",t.LOSS="Loss",t.LOSS_GRAPH="Fitting profile",t.TARGET="Target",t.FIT="Fit",t.METHOD="method",t.VALUE="Value",t.OBJECTIVE="Target",t.SAMPLES="samples",t.ID="id",t.OBTAINED="Simulation",t.LOSS_LOW="loss",t.SIMILARITY="similarity"}(oi||(oi={})),function(t){t.GOAL="`Goal`",t.FIT="`Fit`",t.MIN="`min`",t.MAX="`max`",t.TARGET="`Target`",t.METHOD="`method`",t.CONTEXT="`Context Panel (F4)`",t.SAMPLES="`samples`",t.LOSS="`loss`",t.SIMILARITY="`similarity`"}(si||(si={})),function(t){t[t.SIMILARITY_MIN=0]="SIMILARITY_MIN",t[t.SIMILARITY_DEFAULT=.01]="SIMILARITY_DEFAULT",t[t.SAMPLES=10]="SAMPLES"}(ri||(ri={}));const ai=`# Fitting\n\nUse fitting to solve an inverse problem: find input conditions leading to specified output constraints. \nIt computes inputs minimizing deviation measured by [loss function](https://en.wikipedia.org/wiki/Loss_function).\n\n1. In the ${si.FIT} block, use switchers to specify inputs to be found:\n * Set ${si.MIN} and ${si.MAX} values for each selected item. They define the variation range\n * Set values of all other inputs\n\n2. Set output constraints in the ${si.TARGET} block:\n * Use switchers to specify target outputs\n * Set target value for each selected item\n\n3. Choose ${si.METHOD}. Press <i class="grok-icon fal fa-cog"></i> to specify its settings.\n\n4. Specify the loss function type (in the ${si.LOSS} field).\n\n5. Enter the number of points to be found (in the ${si.SAMPLES} field).\n\n6. Set the maximum scaled deviation between similar fitted points (in the ${si.SIMILARITY} field).\n\n7. Press the "Run" icon <i class="fas fa-play"></i> on the top panel to perform fitting. You will get a\n[grid](https://datagrok.ai/help/visualize/viewers/grid) containing \n\n * loss function values\n * fitted inputs\n * viewers visualizing the goodness of fit:\n * [line chart](https://datagrok.ai/help/visualize/viewers/line-chart) showing the loss function minimization\n\n8. Open ${si.CONTEXT}. You will get the function run corresponding to the selected grid row.\n\n9. Press <i class="grok-icon fal fa-question"></i> on the top panel to learn more about \n[parameters optimization](https://datagrok.ai/help/compute/#input-parameter-optimization).\n\n# Learn more\n\n* [Parameters optimization](https://datagrok.ai/help/compute/#input-parameter-optimization)\n* [Nelder-Mead method](https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method)`;class li extends Error{constructor(t){super(t)}}function ci(t){return new Promise(((e,n)=>setTimeout(e,t)))}function di(t,e){const n=t.getRawData(),i=e.getRawData(),o=e.length,s=Math.min(t.length,o),r=new Uint32Array(s);let a=0,l=0,u=0;for(let t=0;t<s;++t){for(;;){if(l=Math.abs(i[a]-n[t]),++a,!(a<o)){--a;break}if(u=Math.abs(i[a]-n[t]),u>l){--a;break}l=u}r[t]=a}return r}function pi(t,e,n,i){const o=e.col(t),s=n.col(t);if(null===o)throw new li(`no "${t}" column in the target dataframe "${e.name}"`);if(null===s)throw new li(`no "${t}" column in the output dataframe "${n.name}"`);const r=di(o,s),a=e.columns,l=a.length,u=new Float32Array((l-1)*r.length);let c=0;for(const e of a)if(e.name!==t){const t=n.col(e.name);if(null===t)throw new li(`no "${e.name}" column in the output dataframe "${n.name}"`);const o=t.getRawData(),s=e.getRawData();if(i){const t=e.stats.max-e.stats.min,n=t>0?t:1;r.forEach(((t,e)=>{u[c]=(o[t]-s[e])/n,++c}))}else r.forEach(((t,e)=>{u[c]=o[t]-s[e],++c}))}return u}var hi=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const fi=new Map([["tolerance",{default:1e-6,min:1e-20,max:.1}],["maxIter",{default:50,min:1,max:1e4}],["nonZeroParam",{default:1e-4,min:1e-20,max:.1}],["initialScale",{default:.02,min:1e-20,max:.1}],["scaleReflaction",{default:1,min:1,max:2}],["scaleExpansion",{default:2,min:1,max:2}],["scaleContraction",{default:-.5,min:-.5,max:0}]]),mi=new Map([["tolerance","tolerance"],["maxIter","max iterations"],["nonZeroParam","non-zero param"],["initialScale","initial scale"],["scaleReflaction","scale reflection"],["scaleExpansion","scale expansion"],["scaleContraction","scale contraction"]]);function vi(t,e,n,i){for(let o=0;o<e;o++){let s=0;for(let t=0;t<e+1;t++)t!=n&&(s+=i[t][o]);t[o]=s/e}}function gi(t,e,n,i,o,s,r,a){for(let l=0;l<s;l++)e[l]=t[l],e[l]+=o*(t[l]-i[n][l]),e[l]<r[l]?e[l]=r[l]:e[l]>a[l]&&(e[l]=a[l])}const yi=function(t,e,n,i,o){return hi(this,void 0,void 0,(function*(){const s=n.get("tolerance"),r=n.get("maxIter"),a=n.get("scaleReflaction"),l=n.get("scaleExpansion"),u=n.get("scaleContraction"),c=e.length+1,d=e.length,[p,h]=yield function(t,e,n,i,o){return hi(this,void 0,void 0,(function*(){const s=n.length+1,r=n.length,a=e.get("nonZeroParam"),l=e.get("initialScale"),u=new Array(s),c=new Array(s);for(let e=0;e<s;e++){u[e]=new Float32Array(r);for(let t=0;t<r;t++)u[e][t]=n[t],0!=e&&e-1===t&&(0==n[t]?u[e][t]=a:u[e][t]+=l*n[e-1],u[e][t]<i[t]?u[e][t]=i[t]:u[e][t]>o[t]&&(u[e][t]=o[t]));c[e]=yield t(u[e])}return[u,c]}))}(t,n,e,i,o),f=new Array(c);for(let t=0;t<c;t++)f[t]=t;const m=f.length-1;let v=0,g=0,y=0,b=0;const w=new Float32Array(d),A=new Float32Array(d),C=new Float32Array(d),I=new Float32Array(d),S=new Array(r);if(c>1){for(;f.sort(((t,e)=>h[t]-h[e])),!(v>r);){if(0==v&&(g=h[0],y=2*h[f[0]]),S[v]=g,++v,g=h[f[0]],y-g>s)b=0;else if(++b,b>2*c)break;y=g,vi(w,d,f[m],p),gi(w,A,f[m],p,a,d,i,o);const e=yield t(A);if(e<h[f[m]]){gi(w,C,f[m],p,l,d,i,o);const n=yield t(C);if(n<e){h[f[m]]=n;for(let t=0;t<d;t++)p[f[m]][t]=C[t];continue}h[f[m]]=e;for(let t=0;t<d;t++)p[f[m]][t]=A[t];continue}gi(w,I,f[m],p,u,d,i,o);const n=yield t(I);if(!(n<h[f[m]]))break;h[f[m]]=n;for(let t=0;t<d;t++)p[f[m]][t]=I[t]}for(let t=v;t<r;t++)S[t]=h[f[0]]}return{point:p[f[0]],cost:h[f[0]],iterCosts:S,iterCount:v-1}}))};function bi(t,e,n){const i=e-n,o=new Array(t);for(let e=0;e<t;e++){const t=Math.random();o[e]=n+t*i}return o}function wi(t,e,n,i){return s=this,r=arguments,l=function*(t,e,n,i,s=1){const r=function(t,e,n){const i=e.length,o=new Array(t);for(let e=0;e<t;e++)o[e]=new Float32Array(i);for(let s=0;s<i;s++)if(e[s]===n[s])for(let n=0;n<t;n++)o[n][s]=e[s];else{const i=bi(t,e[s],n[s]);for(let e=0;e<t;e++)o[e][s]=i[e]}return o}(s,n,e),a=[],l=[],u=[];let c=0,d=null;const p=o.TaskBarProgressIndicator.create("Fitting...");let h;for(h=0;h<s;++h)try{if(a.push(yield yi(t,r[h],i,e,n)),p.update(100*(h+1)/s,"Fitting..."),yield ci(10),p.canceled)break}catch(t){if(p.close(),t instanceof li)throw new Error(`Inconsistent dataframes: ${t.message}`);++c,l.push(t instanceof Error?t.message:"Platform issue"),u.push(r[h])}if(p.close(),c>0){const t=n.length,e=new Array(t);for(let n=0;n<t;++n)e[n]=new Float32Array(c);u.forEach(((t,n)=>t.forEach(((t,i)=>e[i][n]=t)))),d=o.DataFrame.fromColumns(e.map(((t,e)=>o.Column.fromFloat32Array(`arg${e}`,t)))),d.columns.add(o.Column.fromStrings("Issue",l))}return{extremums:a,fails:d}},new((a=void 0)||(a=Promise))((function(t,e){function n(t){try{o(l.next(t))}catch(t){e(t)}}function i(t){try{o(l.throw(t))}catch(t){e(t)}}function o(e){var o;e.done?t(e.value):(o=e.value,o instanceof a?o:new a((function(t){t(o)}))).then(n,i)}o((l=l.apply(s,r||[])).next())}));var s,r,a,l}var Ai=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const Ci=[o.TYPE.INT,o.TYPE.BIG_INT,o.TYPE.FLOAT,o.TYPE.DATA_FRAME],Ii=()=>e.div([],"sa-switch-input");class Si{static fromEmpty(e){return Ai(this,arguments,void 0,(function*(e,n={parentView:void 0,parentCall:void 0}){const i=[...t.shell.views].find((t=>t.type===v)),o=yield se.fromComparedRuns([],e,{parentView:i,parentCall:n.parentCall});t.shell.addView(o),new this(e,o,n)}))}constructor(n,i,s={parentView:void 0,parentCall:void 0,configFunc:void 0}){if(this.func=n,this.options=s,this.generateInputFields=t=>{const n=(t,e)=>void 0===t.options[e]?t.defaultValue:Number(t.options[e]),i=(t,n,i=!0)=>{const o=e.input.toggle(" ",{value:t,onValueChanged:()=>n(o.value)});return a()(o.root).addClass("sa-switch-input"),a()(o.captionLabel).hide(),e.tooltip.bind(o.root,(()=>i?o.value?"Switch OFF fitting the input":"Switch ON fitting the input":o.value?"Mark the output as not a target":"Mark the output as a target")),o},s=t.inputs.reduce(((t,s)=>{var r;const l=n(s,"default");if(s.propertyType===o.TYPE.FLOAT){const o=i(!1,(t=>{h.isChanging.next(t),this.updateApplicabilityState()})),u=i(!1,(t=>{h.isChanging.next(t),this.updateApplicabilityState()})),d=null!==(r=s.caption)&&void 0!==r?r:s.name,p={type:s.propertyType,prop:s,const:{input:(()=>{const t=e.input.float(d,{value:l,onValueChanged:()=>{h.const.value=t.value,this.updateApplicabilityState()}});return t.root.insertBefore(u.root,t.captionLabel),t.addPostfix(s.options.units),t.setTooltip(`Value of '${d}'`),t.nullable=!1,t})(),value:l},min:{input:(()=>{const t=e.input.float(`${d} (min)`,{value:n(s,"min"),onValueChanged:()=>{h.min.value=t.value,this.updateApplicabilityState()}});return t.addValidator((t=>Number(t)>p.max.value?"Greater than max":null)),t.root.insertBefore(o.root,t.captionLabel),t.addPostfix(s.options.units),t.setTooltip(`Min value '${d}'`),t.nullable=!1,t})(),value:n(s,"min")},max:{input:(()=>{const t=e.input.float(`${d} (max)`,{value:n(s,"max"),onValueChanged:()=>{h.max.value=t.value,this.updateApplicabilityState()}});return t.addValidator((t=>Number(t)<p.min.value?"Smaller than min":null)),t.addPostfix(s.options.units),t.setTooltip(`Max value of '${d}'`),t.nullable=!1,t})(),value:n(s,"max")},isChanging:new c.BehaviorSubject(!1)};[p.max.input].forEach((t=>{t.root.insertBefore(Ii(),t.captionLabel),a()(t.root).removeProp("display")})),t[s.name]=Object.assign(Object.assign({},p),{constForm:[p.const.input],saForm:[p.min.input,p.max.input]});const h=t[s.name];h.isChanging.subscribe((t=>{o.notify=!1,o.value=t,o.notify=!0,u.notify=!1,u.value=t,u.notify=!0})),(0,c.combineLatest)([p.isChanging]).subscribe((([t])=>{t?(h.constForm.forEach((t=>a()(t.root).hide())),h.saForm.forEach((t=>a()(t.root).css("display","flex")))):(h.constForm.forEach((t=>a()(t.root).css("display","flex"))),h.saForm.forEach((t=>a()(t.root).hide())))}))}else{const n=Ii(),i={input:(()=>{var t;const o=e.input.forProperty(s);return o.caption=null!==(t=s.caption)&&void 0!==t?t:s.name,o.onInput((()=>{i.value=o.value,this.updateApplicabilityState()})),o.root.insertBefore(n,o.captionLabel),o.addPostfix(s.options.units),o.nullable=!1,o})(),value:l};i.input.value=l,t[s.name]={const:i,constForm:[i.input],saForm:[],type:s.propertyType,prop:s,isChanging:new c.BehaviorSubject(!1)}}return t}),{}),r=t.outputs.filter((t=>Ci.includes(t.propertyType))).reduce(((t,n)=>{const s={prop:n,input:(()=>{var t;const r=null!==(t=n.caption)&&void 0!==t?t:n.name,a=e.input.forProperty(n);a.addCaption(r),a.value=0,a.setTooltip(this.toSetSwitched?"Target value":n.propertyType===o.TYPE.DATA_FRAME?"Output dataframe":"Output scalar"),a.input.hidden=!this.toSetSwitched,a.nullable=!1,e.tooltip.bind(a.captionLabel,n.propertyType===o.TYPE.DATA_FRAME?"Output dataframe":"Output scalar"),a.onChanged((()=>{if(s.target=a.value,n.propertyType===o.TYPE.DATA_FRAME)if(s.target){const t=[];for(const e of a.value.columns)e.type!==o.COLUMN_TYPE.FLOAT&&e.type!==o.COLUMN_TYPE.INT||t.push(e.name);s.colNameInput.items=t,s.colNameInput.value=t[0]}else s.colNameInput.items=[null],s.colNameInput.value=null;this.updateApplicabilityState()})),n.propertyType===o.TYPE.DATA_FRAME&&(a.root.lastElementChild.hidden=!this.toSetSwitched);const l=i(this.toSetSwitched,(t=>{s.isInterest.next(t),this.updateApplicabilityState(),a.input.hidden=!t,a.setTooltip(t?"Target value":n.propertyType===o.TYPE.DATA_FRAME?"Output dataframe":"Output scalar"),n.propertyType===o.TYPE.DATA_FRAME&&(a.root.lastElementChild.hidden=!t,s.colNameInput.root.hidden=!t)}),!1).root;return a.root.insertBefore(l,a.captionLabel),a})(),colNameInput:(()=>{const t=e.input.choice("argument",{value:null,items:[null],onValueChanged:()=>{s.colName=t.value}});return t.setTooltip("Column with argument values"),t.root.insertBefore(Ii(),t.captionLabel),t.root.hidden=n.propertyType!==o.TYPE.DATA_FRAME||!this.toSetSwitched,this.toSetSwitched=!1,t.nullable=!1,t})(),isInterest:new c.BehaviorSubject(this.toSetSwitched),target:n.propertyType!==o.TYPE.DATA_FRAME?0:null,colName:""};return t[n.name]=s,t}),{});return{inputs:s,outputs:r}},this.readyToRun=!1,this.runIcon=e.iconFA("play",(()=>Ai(this,void 0,void 0,(function*(){this.readyToRun&&(yield this.runOptimization())})))),this.helpIcon=e.iconFA("question",(()=>{window.open("https://datagrok.ai/help/compute/#input-parameter-optimization","_blank")}),"Open help in a new tab"),this.showFailsBtn=e.button("Issues",(()=>{if(this.method!==Qn.NELDER_MEAD)throw new Error(`Not implemented the '${this.method}' method`);this.showNelderMeadFails()}),"Show issues"),this.gridClickSubscription=null,this.gridCellChangeSubscription=null,this.failsDF=null,this.toSetSwitched=!0,this.samplesCount=ri.SAMPLES,this.samplesCountInput=e.input.forProperty(o.Property.fromOptions({name:oi.SAMPLES,inputType:"Int",defaultValue:this.samplesCount,min:1,max:1e3})),this.loss=ei.RMSE,this.lossInput=e.input.choice(oi.LOSS_LOW,{value:this.loss,items:[ei.MAD,ei.RMSE],onValueChanged:()=>{this.loss=this.lossInput.value,this.lossInput.setTooltip(ni.get(this.loss))}}),this.similarity=ri.SIMILARITY_DEFAULT,this.similarityInput=e.input.forProperty(o.Property.fromOptions({name:oi.SIMILARITY,inputType:"Float",defaultValue:this.similarity,min:0})),this.helpDN=void 0,this.method=Qn.NELDER_MEAD,this.methodInput=e.input.choice(oi.METHOD,{value:this.method,items:[Qn.NELDER_MEAD],onValueChanged:()=>{this.method=this.methodInput.value,this.showHideSettingInputs(),this.methodInput.setTooltip(ti.get(this.method))}}),this.nelderMeadSettings=new Map,this.gradDescentSettings={iterCount:10,learningRate:1e-4},this.settingsInputs=new Map,this.store=this.generateInputFields(this.func),this.fittingSettingsIcon=e.iconFA("cog",(()=>{const t=this.fittingSettingsDiv.hidden;this.fittingSettingsDiv.hidden=!t}),"Modify fitting settings"),this.fittingSettingsDiv=e.divV([]),!this.isOptimizationApplicable(n))return t.shell.warning("Fitting is not applicable: the function has no scalar outputs."),void i.close();const r=this.buildForm();this.comparisonView=i,this.comparisonView.dockManager.dock(r,o.DOCK_TYPE.LEFT,null,`${this.func.name} - Fitting`,.25),this.comparisonView.grid.columns.byName("Run name").visible=!1,fi.forEach(((t,e)=>this.nelderMeadSettings.set(e,t.default)));const l=this.comparisonView.getRibbonPanels();l.push([this.helpIcon,this.runIcon]),this.comparisonView.setRibbonPanels(l),this.fittingSettingsDiv.hidden=!0,this.comparisonView.name=this.comparisonView.name.replace("comparison","fitting"),this.comparisonView.helpUrl="https://datagrok.ai/help/compute/#input-parameter-optimization";const u=e.markdown(ai);u.style.padding="10px",u.style.overflow="auto",this.helpDN=this.comparisonView.dockManager.dock(u,o.DOCK_TYPE.FILL,this.comparisonView.dockManager.findNode(this.comparisonView.grid.root),"About"),this.methodInput.setTooltip(ti.get(this.method)),e.tooltip.bind(this.methodInput.captionLabel,"Method for minimizing the loss function"),this.lossInput.setTooltip(ni.get(this.loss)),e.tooltip.bind(this.lossInput.captionLabel,"Loss function type"),this.showFailsBtn.style.padding="0px",this.samplesCountInput.addCaption(oi.SAMPLES),this.samplesCountInput.onChanged((()=>{this.samplesCount=this.samplesCountInput.value,this.updateApplicabilityState()})),this.samplesCountInput.setTooltip("Number of points to be found"),this.similarityInput.onChanged((()=>{this.similarity=this.similarityInput.value,this.updateApplicabilityState()})),this.similarityInput.addCaption(oi.SIMILARITY),this.similarityInput.setTooltip("The higher the value, the fewer points will be found"),e.tooltip.bind(this.similarityInput.captionLabel,"Max scaled deviation between similar fitted points"),this.updateRunIconStyle(),this.updateRunIconDisabledTooltip("Select inputs for fitting"),this.runIcon.classList.add("fas")}isOptimizationApplicable(t){for(const n of t.outputs)if((e=n).propertyType===o.TYPE.INT||e.propertyType===o.TYPE.FLOAT||e.propertyType===o.TYPE.DATA_FRAME)return!0;var e;return!1}generateNelderMeadSettingsInputs(){const t=[];fi.forEach(((n,i)=>{const s=e.input.forProperty(o.Property.fromOptions({name:mi.get(i),inputType:"maxIter"!==i?"Float":"Int",defaultValue:n.default,min:n.min,max:n.max}));s.addCaption(mi.get(i)),s.nullable=!1,s.onChanged((()=>{this.nelderMeadSettings.set(i,s.value),this.updateApplicabilityState()})),t.push(s)})),this.settingsInputs.set(Qn.NELDER_MEAD,t)}areNelderMeadSettingsCorrect(){for(const[t,e]of this.nelderMeadSettings)if(null==e||e>fi.get(t).max||e<fi.get(t).min)return this.updateRunIconDisabledTooltip(`Invalid "${t}": check method settings`),!1;return!0}generateGradDescentSettingsInputs(){const t=e.input.forProperty(o.Property.fromOptions({name:"iterations",inputType:"Int",defaultValue:this.gradDescentSettings.iterCount,min:1,max:1e4}));t.onChanged((()=>this.gradDescentSettings.iterCount=t.value));const n=e.input.forProperty(o.Property.fromOptions({name:"Learning rate",inputType:"Float",defaultValue:this.gradDescentSettings.learningRate,min:1e-6,max:1e3}));n.onChanged((()=>this.gradDescentSettings.learningRate=n.value)),this.settingsInputs.set(Qn.GRAD_DESC,[t,n])}areGradDescentSettingsCorrect(){return!1}areMethodSettingsCorrect(){switch(this.method){case Qn.NELDER_MEAD:return this.areNelderMeadSettingsCorrect();case Qn.GRAD_DESC:return this.areGradDescentSettingsCorrect();default:return!0}}generateSettingInputs(){this.generateNelderMeadSettingsInputs(),this.generateGradDescentSettingsInputs()}showHideSettingInputs(){this.settingsInputs.forEach(((t,e)=>t.forEach((t=>t.root.hidden=e!==this.method))))}buildForm(){const t=e.h1(oi.FIT);e.tooltip.bind(t,"Select inputs to be fitted");const n=new Map([["Misc",[]]]);Object.values(this.store.inputs).forEach((t=>{const e=t.prop.category,i=[...t.constForm.map((t=>t.root)),...t.saForm.map((t=>t.root))];n.has(e)?n.get(e).push(...i):n.set(e,i)}));const i=e.div([t],{style:{"overflow-y":"scroll",width:"100%"}});n.size>1?(n.forEach(((t,n)=>{"Misc"!==n&&(i.append(e.h3(n)),i.append(...t))})),n.get("Misc").length>0&&(i.append(e.h3("Misc")),i.append(...n.get("Misc")))):i.append(...n.get("Misc"));const o=e.h1(oi.TARGET);e.tooltip.bind(o,"Select target outputs"),i.appendChild(o);let s="Misc";Object.values(this.store.outputs).reduce(((t,n)=>{const i=n.prop;return i.category!==s&&(t.append(e.h3(i.category)),s=i.category),t.append(n.input.root),t.append(n.colNameInput.root),t}),i);let r=!1;for(const t of Object.keys(this.store.outputs))if(!0===this.store.outputs[t].isInterest.value){r=!0;break}r||this.store.outputs[Object.keys(this.store.outputs)[0]].isInterest.next(!0);const l=e.h1("Using");e.tooltip.bind(l,"Specify fitting method"),i.appendChild(l),this.methodInput.root.insertBefore(this.fittingSettingsIcon,this.methodInput.captionLabel),this.fittingSettingsIcon.style.minWidth="50px",i.appendChild(this.methodInput.root);const u=e.h2("with settings");return e.tooltip.bind(u,(()=>`Settings of the ${this.method} method`)),this.fittingSettingsDiv.appendChild(u),this.generateSettingInputs(),this.showHideSettingInputs(),i.appendChild(this.fittingSettingsDiv),this.settingsInputs.forEach((t=>t.forEach((t=>{t.root.insertBefore(Ii(),t.captionLabel),this.fittingSettingsDiv.append(t.root)})))),[this.lossInput,this.samplesCountInput,this.similarityInput].forEach((t=>{t.root.insertBefore(Ii(),t.captionLabel),t.nullable=!1,i.appendChild(t.root)})),a()(i).addClass("ui-form"),this.updateApplicabilityState(),a()(i).css({"padding-left":"12px","overflow-y":"scroll","padding-right":"4px"}),i}updateRunIconDisabledTooltip(t){e.tooltip.bind(this.runIcon,(()=>{const n=e.label(t);return n.style.color="#FF0000",n}))}updateApplicabilityState(){this.readyToRun=this.canFittingBeRun(),this.updateRunIconStyle()}updateRunIconStyle(){this.readyToRun?(this.runIcon.style.color="var(--green-2)",e.tooltip.bind(this.runIcon,"Run fitting")):this.runIcon.style.color="var(--grey-3)"}areInputsReady(){var t;let e,n=!1,i=!0;for(const o of Object.keys(this.store.inputs)){const s=this.store.inputs[o],r=null!==(t=s.prop.caption)&&void 0!==t?t:s.prop.name;if(!0===s.isChanging.value){n=!0;const t=s.min.input,o=s.max.input,a=t.value,l=o.value;e=null!=a&&void 0!==l&&void 0!==l,e?a>l?(e=!1,this.updateRunIconDisabledTooltip(`Invalid min & max of "${r}"`),t.input.classList.add("d4-invalid"),o.input.classList.add("d4-invalid")):(t.input.classList.remove("d4-invalid"),o.input.classList.remove("d4-invalid")):this.updateRunIconDisabledTooltip(`Incomplete "${r}"`),i=i&&e}else{e=null!=s.const.input.value,e||this.updateRunIconDisabledTooltip(`Incomplete "${r}"`),i=i&&e}}return n||this.updateRunIconDisabledTooltip("No parameters for fitting selected"),n&&i}areOutputsReady(){let t,e=!1,n=!0;for(const i of Object.keys(this.store.outputs)){const s=this.store.outputs[i];if(!0===s.isInterest.value){e=!0;t=null!=s.input.value,s.prop.propertyType===o.TYPE.DATA_FRAME&&(t=t&&null!==s.colNameInput.value&&""!==s.colName),t||this.updateRunIconDisabledTooltip(`Incomplete the "${s.input.caption}" target`),n=n&&t}}return e||this.updateRunIconDisabledTooltip("No targets selected"),e&&n}isSamplesCountValid(){return this.samplesCount>0||(this.updateRunIconDisabledTooltip(`Invalid "${oi.SAMPLES}"`),!1)}isSimilarityValid(){return this.similarity>=ri.SIMILARITY_MIN||(this.updateRunIconDisabledTooltip(`Invalid "${oi.SIMILARITY}"`),!1)}canFittingBeRun(){return this.areInputsReady()&&this.areOutputsReady()&&this.isSamplesCountValid()&&this.areMethodSettingsCorrect()&&this.isSimilarityValid()}getFixedInputs(){return Object.keys(this.store.inputs).filter((t=>!this.store.inputs[t].isChanging.value))}getFittedInputs(){return Object.keys(this.store.inputs).filter((t=>this.store.inputs[t].type===o.TYPE.FLOAT&&this.store.inputs[t].isChanging.value))}runOptimization(){return Ai(this,void 0,void 0,(function*(){try{if(!this.canFittingBeRun())return;if(this.samplesCount<1)return;if(this.similarity<ri.SIMILARITY_MIN)return;this.failsDF=null;const n={},i=this.getFixedInputs();i.forEach((t=>n[t]=this.store.inputs[t].const.value));const s=this.getFittedInputs(),r=s.length,l=[],u=new Float32Array(r),c=new Float32Array(r),d=new Array(r);s.forEach(((t,e)=>{var n;const i=this.store.inputs[t];u[e]=i.min.value,c[e]=i.max.value,l.push(t),d[e]=null!==(n=i.prop.caption)&&void 0!==n?n:i.prop.name}));const p=this.getOutputsOfInterest();if(p.length<1)return void t.shell.error("No output is selected for optimization.");const h=p.map((t=>t.prop.propertyType)).filter((t=>t===o.TYPE.DATA_FRAME)).length>1,f=t=>Ai(this,void 0,void 0,(function*(){t.forEach(((t,e)=>n[l[e]]=t));const e=this.func.prepare(n);return yield e.call()})),m=t=>Ai(this,void 0,void 0,(function*(){t.forEach(((t,e)=>n[l[e]]=t));const e=this.func.prepare(n),i=yield e.call();let s=0,r=0,a=0;return p.forEach((t=>{t.prop.propertyType!==o.TYPE.DATA_FRAME?(a=t.target,s+=Math.pow((a-i.getParamValue(t.prop.name))/(0!==a?a:1),2),++r):pi(t.colName,t.target,i.getParamValue(t.prop.name),!0).forEach((t=>{s+=Math.pow(t,2),++r}))})),Math.sqrt(s/r)})),v=t=>Ai(this,void 0,void 0,(function*(){t.forEach(((t,e)=>n[l[e]]=t));const e=this.func.prepare(n),i=yield e.call();let s=0;return p.forEach((t=>{t.prop.propertyType!==o.TYPE.DATA_FRAME?s=Math.max(s,Math.abs(t.target-i.getParamValue(t.prop.name))):pi(t.colName,t.target,i.getParamValue(t.prop.name),!1).forEach((t=>s=Math.max(s,Math.abs(t))))})),s}));let g,y,b;if(this.loss===ei.MAD?(g=v,y="maximum absolute devation"):(g=m,y="root mean square error"),this.method!==Qn.NELDER_MEAD)throw new Error(`Not implemented the '${this.method}' method`);b=yield wi(g,u,c,this.nelderMeadSettings,this.samplesCount);const w=b.extremums,A=w.length;if(A<this.samplesCount){this.failsDF=b.fails;const t=this.failsDF.columns;d.forEach(((e,n)=>t.byIndex(n).name=t.getUnusedName(e))),i.forEach((e=>{var n,i;const s=this.store.inputs[e];s.prop.propertyType!==o.TYPE.DATA_FRAME&&t.add(o.Column.fromList(s.prop.propertyType,t.getUnusedName(null!==(n=s.prop.caption)&&void 0!==n?n:s.prop.name),new Array(null===(i=this.failsDF)||void 0===i?void 0:i.rowCount).fill(s.const.value)))}))}const C=[],I=this.similarity;w.forEach((t=>{let e=!0;C.forEach((n=>e&&(e=function(t,e,n,i){const o=t.length;if(o!==e.length||o!==n.length||o!==i.length)throw new Error("Inconsistent found points");return t.reduce(((t,o,s)=>{const r=i[s]-n[s];return r>0?Math.max(t,Math.abs(o-e[s])/r):t}),0)}(n.point,t.point,u,c)>I))),e&&C.push(t)}));const S=C.length;if(A<this.samplesCount){if(A<1)return void t.shell.warning(e.divV([e.label(`Failed to find ${this.samplesCount} point${this.samplesCount>1?"s":""}`),e.div([this.showFailsBtn])]));t.shell.info(e.divV([e.label(`Found ${S} point${S>1?"s":""}`),e.div([this.showFailsBtn])]))}else t.shell.info(`Found ${S} point${S>1?"s":""}`);this.clearPrev(),C.sort(((t,e)=>t.cost-e.cost));const T=new Float32Array(S),E=this.comparisonView.grid,x=new Array(S),R=new Array(S),O=new Array(S),P=new Map([[oi.LOSS,`The final loss obtained: ${y}`]]);let k=!0;const F=[];C.forEach(((t,e)=>Ai(this,void 0,void 0,(function*(){T[e]=t.cost;const n=this.getLossGraph(t);O[e]=n;const i=new Map,s=yield f(t.point);R[e]=s,p.forEach((t=>{this.getOutputGof(t.prop,t.target,s,t.colName,h).forEach((t=>i.set(t.caption,t.root)))})),x[e]=i,k&&(i.forEach(((t,e)=>{var n;P.set(e,"Goodness of fit"),null===(n=this.comparisonView.table)||void 0===n||n.columns.addNew(e,o.COLUMN_TYPE.STRING);const i=this.comparisonView.grid.columns.byName(e);i.cellType="html",i.width=ii.GOF_VIEWER_WIDTH,F.push(e)})),k=!1)}))));const L=o.DataFrame.fromColumns([o.Column.fromFloat32Array(oi.LOSS,T)]);this.comparisonView.dataFrame=L;const N=L.columns;d.forEach(((t,e,n)=>{t=N.getUnusedName(t),n[e]=t;const i=new Float32Array(S);for(let t=0;t<S;++t)i[t]=C[t].point[e];N.add(o.Column.fromFloat32Array(t,i)),P.set(t,`Obtained values of '${t}'`)})),E.props.rowHeight=ii.ROW_HEIGHT,E.props.showAddNewRowIcon=!1,E.props.allowEdit=!1;const B=N.getUnusedName(`${this.loss} by iterations`);P.set(B,`Minimizing ${y}`),N.addNew(B,o.COLUMN_TYPE.STRING);const M=E.columns.byName(B);M.cellType="html",M.width=ii.LOSS_GRAPH_WIDTH;let _=!0;E.onCellPrepare((t=>Ai(this,void 0,void 0,(function*(){_&&(E.columns.setOrder(N.names().filter((t=>t!==B)).concat([B])),_=!1),t.isColHeader||t.isRowHeader||(t.isTableCell&&t.gridColumn.name===B&&null!==t.cell.value&&(t.style.element=O[t.gridRow]),F.forEach((n=>{var i;t.isTableCell&&t.gridColumn.name===n&&null!==t.cell.value&&void 0!==x[t.gridRow]&&(t.style.element=null!==(i=x[t.gridRow].get(n))&&void 0!==i?i:e.label(""))})))})))),E.columns.byName(oi.LOSS).format="scientific",E.columns.byName(oi.LOSS).width=ii.LOSS_COL_WIDTH,E.onCellTooltip((function(t,n,i){if(t.isColHeader&&t.tableColumn){const o=t.tableColumn.name,s=P.get(o);return e.tooltip.show(null!=s?s:"",n,i),!0}})),L.currentCell=L.cell(0,oi.LOSS);const D=n=>Ai(this,void 0,void 0,(function*(){var i;if(null==n)return;const s=null!==(i=n.tableRowIndex)&&void 0!==i?i:0,r=R[s],l=[...r.outputParams.values()].filter((t=>o.TYPES_SCALAR.has(t.property.propertyType))),u=o.HtmlTable.create(l,(t=>{var e;return[null!==(e=t.property.caption)&&void 0!==e?e:t.property.name,r.outputs[t.property.name],t.property.options.units]})).root,c=[...r.outputParams.values()].filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME)).reduce(((t,e)=>{var n;const i=Dt(e.property).config,s=r.outputs[e.name],l=null!==(n=e.property.caption)&&void 0!==n?n:e.property.name;return i.map((e=>{const n=e.type,i=o.Viewer.fromType(n,s);i.setOptions(e),a()(i.root).css({width:"100%"}),t[l]?t[l].push(i.root):t[l]=[i.root]})),t}),{});let d;d=l.length>0?Object.assign({"Output scalars":[u]},c):Object.assign({},c);const p=e.accordion();if(a()(p.root).css({width:"100%"}),Object.entries(d).map((t=>{p.addPane(t[0],(()=>e.divV(t[1])))})),p.panes.length-1<0)throw new Error("Function has no outputs");p.panes[p.panes.length-1].expanded=!0,t.shell.o=p.root}));this.gridClickSubscription=E.onCellClick.subscribe(D),this.gridCellChangeSubscription=E.onCurrentCellChanged.subscribe(D)}catch(e){t.shell.error(e instanceof Error?e.message:"The platform issue")}}))}getOutputsOfInterest(){const t=[];for(const e of Object.keys(this.store.outputs)){const n=this.store.outputs[e];n.isInterest.value&&t.push(n)}return t}getLossGraph(t){return o.Viewer.lineChart(o.DataFrame.fromColumns([o.Column.fromList(o.COLUMN_TYPE.INT,oi.ITER,[...Array(t.iterCount).keys()].map((t=>t+1))),o.Column.fromList(o.COLUMN_TYPE.FLOAT,oi.LOSS,t.iterCosts.slice(0,t.iterCount))]),{showYAxis:!0,showXAxis:!0,showXSelector:!0,showYSelectors:!0,lineColoringType:"custom",lineColor:15274e3,markerColor:15274e3}).root}getOutputGof(t,e,n,i,s){var r;const a=t.propertyType,l=t.name,u=null!==(r=t.caption)&&void 0!==r?r:l;switch(a){case o.TYPE.FLOAT:case o.TYPE.INT:case o.TYPE.BIG_INT:return[{caption:u,root:o.Viewer.barChart(o.DataFrame.fromColumns([o.Column.fromStrings(u,["obtained","target"]),o.Column.fromList(a,oi.VALUE,[n.getParamValue(l),e])]),{valueColumnName:oi.VALUE,splitColumnName:u,valueAggrType:o.AGG.AVG,showValueSelector:!1,showCategorySelector:!1,showStackSelector:!1,showEmptyBars:!0}).root}];case o.TYPE.DATA_FRAME:const r=[],c=n.getParamValue(l),d=e,p=c.col(i),h=d.col(i),f=Dt(t).config;if(null===p||null===h)throw new Error("Creating viewer fails: incorrect argument column name");const m=p.getRawData(),v=di(h,p),g=v.length,y=Array(g);v.forEach(((t,e)=>y[e]=m[t]));let b,w,A=null;return f.filter((t=>t.type===o.VIEWER.LINE_CHART)).forEach((t=>{const e=t.segmentColumnName;if(e){const t=Array(g);v.forEach(((n,i)=>t[i]=c.col(e).get(n))),A=o.Column.fromStrings(e,t)}})),d.columns.names().forEach((t=>{if(t!==i){if(w=c.col(t),null===w)throw new Error(`Creating viewer fails: no '${t}' column in the output dataframe`);b=w.getRawData();const e=Array(g);if(v.forEach(((t,n)=>e[n]=b[t])),w=d.col(t),null===w)throw new Error(`Creating viewer fails: no '${t}' column in the target dataframe`);b=w.getRawData();const n=Array(g);v.forEach(((t,e)=>n[e]=b[e]));const i={multiAxis:!0,yGlobalScale:!0},a=o.DataFrame.fromColumns([h,o.Column.fromList(w.type,oi.OBTAINED,e),o.Column.fromList(w.type,oi.TARGET,n)]);A&&(a.columns.add(A),i.segmentColumnName=A.name),r.push({caption:s?`${u}: [${t}]`:`[${t}]`,root:o.Viewer.lineChart(a,i).root})}})),r;default:throw new Error("Unsupported output type")}}clearPrev(){void 0!==this.helpDN&&(this.comparisonView.dockManager.close(this.helpDN),this.helpDN=void 0),this.gridClickSubscription&&(this.gridClickSubscription.unsubscribe(),this.gridClickSubscription=null),this.gridCellChangeSubscription&&(this.gridCellChangeSubscription.unsubscribe(),this.gridCellChangeSubscription=null)}showNelderMeadFails(){if(null===this.failsDF)return;const n=t.shell.addTableView(this.failsDF);n.addViewer(o.Viewer.form(o.DataFrame.fromColumns(Object.entries(this.nelderMeadSettings).map((t=>{var e;return o.Column.fromFloat32Array(null!==(e=mi.get(t[0]))&&void 0!==e?e:t[0],new Float32Array([t[1]]))})))),{description:"The Nelder-Mead method settings",showNavigation:!1});const i=this.getFittedInputs().length,s=new Map;this.failsDF.columns.names().forEach(((t,e)=>{e<i?s.set(t,`Initial value of "${t}" used in the Nelder-Mead method`):e>i?s.set(t,`Value of "${t}" (fixed input)`):s.set(t,"Error message raised")})),n.grid.onCellTooltip((function(t,n,i){if(t.isColHeader&&t.tableColumn){const o=t.tableColumn.name,r=s.get(o);return e.tooltip.show(null!=r?r:"",n,i),!0}}))}}var Ti,Ei=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};!function(t){t.INPUTS="inputs",t.OUTPUTS="outputs"}(Ti||(Ti={}));const xi={[Ti.INPUTS]:"inputParams",[Ti.OUTPUTS]:"outputParams"},Ri=()=>e.divText("[No data to display]",{style:{"text-align":"center","align-content":"center",width:"100%",height:"100%"}});class Oi extends Ee{static fromFuncCall(t,e={historyEnabled:!0,isTabbed:!1}){return new this(t,e)}constructor(t,n={historyEnabled:!0,isTabbed:!1}){super(t,n),this.options=n,this.validationRequests=new c.Subject,this.validationUpdates=new c.Subject,this.runRequests=new c.Subject,this.isRunning=new c.BehaviorSubject(!1),this.isUploadMode=new c.BehaviorSubject(!1),this.inputsOverride={},this.inputsMap={},this.validators={},this.validationState={},this.externalValidatorsUpdates=new c.Subject,this.externalValidatorsState={},this.pendingValidations=this.validationUpdates.pipe((0,s.startWith)(null),(0,s.map)((()=>this.validationState))),this._isOutputOutdated=new c.BehaviorSubject(!0),this.isOutputOutdated=this._isOutputOutdated.pipe((0,s.distinctUntilChanged)()),this.blockRuns=new c.BehaviorSubject(!1),this.prevOpenedTab=null,this.beforeInputPropertyRender=new c.Subject,this.afterInputPropertyRender=new c.Subject,this.afterOutputPropertyRender=new c.Subject,this.afterOutputSacalarTableRender=new c.Subject,this.formButtons=e.div(),this.additionalBtns=[],this.navBtns=[],this.tabsElem=e.tabControl(),this.dfToViewerMapping={},this.focusedInput=null,this.foldedCategoryInputs={},this.sheetNamesCache={},this.richFunctionExport=t=>Ei(this,void 0,void 0,(function*(){if("Excel"===t)try{const e=this.lastCall;if(!e)throw new Error("Function was not called");if(!this.exportConfig.supportedFormats.includes(t))throw new Error(`Format "${t}" is not supported.`);if(!this.func)throw new Error("The correspoding function is not specified");yield o.Utils.loadJsCss(["/js/common/exceljs.min.js"]);const n=window.ExcelJS,i="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",s=new n.Workbook,r=t=>o.TYPES_SCALAR.has(t),a=t=>t.propertyType===o.TYPE.DATA_FRAME,l=this.func.inputs.filter((t=>a(t))),u=this.func.inputs.filter((t=>r(t.propertyType))),c=this.func.outputs.filter((t=>a(t))),d=this.func.outputs.filter((t=>r(t.propertyType)));if(l.forEach((t=>{var n;const i=t.options.caption||t.name,o=null!==(n=s.worksheets.find((t=>t.name===this.getSheetName(i,s))))&&void 0!==n?n:s.addWorksheet(this.getSheetName(i,s)),r=e.inputs[t.name];ot(o,r)})),u.length){const t=s.addWorksheet("Input scalars");nt(t,u.map((t=>{var n,i,o;return{caption:null!==(n=t.options.caption)&&void 0!==n?n:t.name,value:null!==(i=e.inputs[t.name])&&void 0!==i?i:"",units:null!==(o=t.options.units)&&void 0!==o?o:""}})))}if(c.forEach((t=>{var n;const i=t.options.caption||t.name,o=null!==(n=s.worksheets.find((t=>t.name===this.getSheetName(i,s))))&&void 0!==n?n:s.addWorksheet(this.getSheetName(i,s)),r=e.outputs[t.name];ot(o,r)})),d.length){const t=s.addWorksheet("Output scalars");nt(t,d.map((t=>{var n,i,o;return{caption:null!==(n=t.options.caption)&&void 0!==n?n:t.name,value:null!==(i=e.outputs[t.name])&&void 0!==i?i:"",units:null!==(o=t.options.units)&&void 0!==o?o:""}})))}const p=this.tabsElem;for(const t of this.inputTabsLabels)for(const n of this.categoryToDfParamMap.inputs[t].filter((t=>a(t)))){const i=this.dfToViewerMapping[n.name].filter((t=>t.type!==o.VIEWER.GRID)).filter((t=>Object.values(m).includes(t.type)));if(0===i.length)continue;p.currentPane=p.getPane(t),yield new Promise((t=>setTimeout(t,100)));const r=n.options.caption||n.name,a=e.inputs[n.name];for(const[t,e]of i.entries())yield st(s,s.getWorksheet(this.getSheetName(r,s)),e.root,a.columns.length+2,t>0?Math.ceil(i[t-1].root.clientHeight/20)+1:0)}for(const t of this.outputTabsLabels)for(const n of this.categoryToDfParamMap.outputs[t].filter((t=>a(t)))){const i=this.dfToViewerMapping[n.name].filter((t=>t.type!==o.VIEWER.GRID)).filter((t=>Object.values(m).includes(t.type)));if(0===i.length)continue;p.currentPane=p.getPane(t),yield new Promise((t=>setTimeout(t,100)));const r=n.options.caption||n.name,a=e.outputs[n.name];for(const[t,e]of i.entries())if(e.type===o.VIEWER.STATISTICS){const e=a.columns.length,n=o.DataFrame.fromColumns([o.Column.string("Name",e).init((t=>a.columns.byIndex(t).name)),o.Column.int("Values",e).init((t=>a.columns.byIndex(t).stats.valueCount)),o.Column.int("Nulls",e).init((t=>a.columns.byIndex(t).stats.missingValueCount)),o.Column.float("Min",e).init((t=>a.columns.byIndex(t).stats.min)),o.Column.float("Max",e).init((t=>a.columns.byIndex(t).stats.max)),o.Column.float("Avg",e).init((t=>a.columns.byIndex(t).stats.avg)),o.Column.float("Stdev",e).init((t=>a.columns.byIndex(t).stats.stdev))]);ot(s.getWorksheet(this.getSheetName(r,s)),n,a.columns.length+2,t>0?Math.ceil(i[t-1].root.clientHeight/20)+1:0)}else yield st(s,s.getWorksheet(this.getSheetName(r,s)),e.root,a.columns.length+2,t>0?Math.ceil(i[t-1].root.clientHeight/20)+1:0)}const h=yield s.xlsx.writeBuffer();return new Blob([h],{type:i})}catch(t){console.log(t)}if("DataUrl images"===t){const t={},e=t=>t.propertyType===o.TYPE.DATA_FRAME,n=this.tabsElem;yield o.Utils.loadJsCss(["/js/common/html2canvas.min.js"]);const i=window.html2canvas;for(const s of this.tabsLabels.filter((t=>this.inputTabsLabels.includes(t))))for(const r of this.categoryToDfParamMap.inputs[s].filter((t=>e(t)))){const e=this.dfToViewerMapping[r.name].filter((t=>t.type!==o.VIEWER.GRID&&t.type!==o.VIEWER.STATISTICS)).filter((t=>Object.values(m).includes(t.type)));if(0!==e.length){n.currentPane=n.getPane(s),yield new Promise((t=>setTimeout(t,100)));for(const[n,o]of e.entries()){const e=(yield i(o.root,{logging:!1})).toDataURL();t[r.name]||(t[r.name]={}),t[r.name][n]={dataUrl:e,width:o.root.clientWidth,height:o.root.clientHeight}}}}for(const s of this.tabsLabels.filter((t=>this.outputTabsLabels.includes(t))))for(const r of this.categoryToDfParamMap.outputs[s].filter((t=>e(t)))){const e=this.dfToViewerMapping[r.name].filter((t=>t.type!==o.VIEWER.GRID&&t.type!==o.VIEWER.STATISTICS)).filter((t=>Object.values(m).includes(t.type)));if(0!==e.length){n.currentPane=n.getPane(s),yield new Promise((t=>setTimeout(t,100)));for(const[n,o]of e.entries()){const e=(yield i(o.root,{logging:!1})).toDataURL();t[r.name]||(t[r.name]={}),t[r.name][n]={dataUrl:e,width:o.root.clientWidth,height:o.root.clientHeight}}}}return new Blob([JSON.stringify(t)],{type:"text/plain"})}throw new Error("Format is not supported")})),this.exportConfig={supportedExtensions:this.richFunctionViewExportExtensions(),supportedFormats:this.richFunctionViewSupportedFormats(),export:this.richFunctionExport,filename:this.defaultExportFilename}}onFuncCallReady(){const n=Object.create(null,{onFuncCallReady:{get:()=>super.onFuncCallReady}});return Ei(this,void 0,void 0,(function*(){yield this.loadInputsOverrides(),yield this.loadInputsValidators(),yield n.onFuncCallReady.call(this);const i=this.funcCallReplaced.subscribe((()=>this.validationRequests.next({isRevalidation:!1})));this.subs.push(i);const o=this.validationRequests.pipe((0,s.groupBy)((t=>t.field)),(0,s.mergeMap)((t=>t.pipe((0,s.tap)((t=>this.setValidationPending(t.field))),(0,s.switchMap)((t=>{const e=new AbortController,n=e.signal;let i=!1;return new c.Observable((o=>{const s=(0,c.from)(this.runValidation(Object.assign({},t),n)).subscribe((t=>{i=!0,o.next(t)}));return()=>{i||e.abort(),s.unsubscribe()}})).pipe((0,s.tap)((e=>{this.setValidationResults(e),this.runRevalidations(t,e),this.validationUpdates.next(null)})),(0,s.mapTo)(t))})))))).subscribe((t=>{t.field&&this.runningOnInput&&this.isRunnable()&&this.doRun()}));this.subs.push(o);const r=this.externalValidatorsUpdates.subscribe((t=>{this.updateInputValidationReuslts(t)}));this.subs.push(r);const a=(0,c.combineLatest)([this.runRequests.pipe((0,s.switchMap)((()=>(0,c.of)(!1).pipe((0,s.delay)(500),(0,s.startWith)(!0))))),this.validationUpdates.pipe((0,s.debounceTime)(0))]).pipe((0,s.filter)((([t])=>t&&this.isRunnable()))).subscribe((()=>this.doRun()));this.subs.push(a);const l=this.options.isTabbed?null:yield this.loadLastInputs();if(l)t.shell.info(e.div([e.divText("Do you want to load last inputs?"),e.divH([e.bigButton("Load",(()=>{for(const[t,e]of Object.entries(l)){const n=this.getInput(t);n.notify=!1,n.value=e,n.notify=!0}t.shell.info(e.divText("Change the loaded inputs to run computations"))}))])]));else{const t=new AbortController,e=yield this.runValidation({isRevalidation:!1},t.signal);this.setValidationResults(e),this.runRevalidations({isRevalidation:!1},e),this.validationUpdates.next(null),this.runningOnStart&&this.isRunnable()&&(yield this.doRun())}}))}onBeforeRun(){return this.tabsElem.currentPane&&(this.prevOpenedTab=this.inputTabsLabels.includes(this.tabsElem.currentPane.name)?null:this.tabsElem.currentPane),Promise.resolve()}onAfterRun(){if(this.showOutput(),this.tabsElem.panes.forEach((t=>{a()(t.header).show()})),this.prevOpenedTab)return this.tabsElem.currentPane=this.prevOpenedTab,Promise.resolve();const t=this.tabsElem.panes.find((t=>this.outputTabsLabels.includes(t.name)));return t&&(this.tabsElem.currentPane=t),Promise.resolve()}getRunButton(t="Run"){var n;const i=e.bigButton(null!==(n=this.func.options.runLabel)&&void 0!==n?n:t,(()=>Ei(this,void 0,void 0,(function*(){return yield this.doRun()})))),o=(0,c.merge)(this.validationUpdates,this.externalValidatorsUpdates,this.isRunning,this.blockRuns).subscribe((()=>{const t=this.isRunnable();i.disabled=!t}));return this.subs.push(o),i}loadInputsOverrides(){return Ei(this,void 0,void 0,(function*(){const e=[...this.funcCall.inputParams.values()];yield Promise.all(e.map((e=>Ei(this,void 0,void 0,(function*(){if(e.property.options.input){const n=(yield t.functions.eval(e.property.options.input)).prepare({params:JSON.parse(e.property.options.inputOptions||"{}")});yield n.call(),this.inputsOverride[e.name]=n.outputs.input}})))))}))}loadInputsValidators(){return Ei(this,void 0,void 0,(function*(){const e=[...this.funcCall.inputParams.values()];yield Promise.all(e.map((e=>Ei(this,void 0,void 0,(function*(){if(e.property.options.validatorFunc){const n=(yield t.functions.eval(e.property.options.validatorFunc)).prepare({params:JSON.parse(e.property.options.validatorFuncOptions||"{}")});yield n.call(),this.validators[e.name]=n.outputs.validator}})))))}))}keepOutput(){var t;return"true"===(null===(t=this.func)||void 0===t?void 0:t.options.keepOutput)}getSaveButton(t="Save"){const n=e.bigButton(t,(()=>Ei(this,void 0,void 0,(function*(){return yield this.saveExperimentalRun(this.funcCall)}))),"Save uploaded data"),i=this.isUploadMode.subscribe((t=>{this.buildRibbonPanels(),t?a()(n).show():a()(n).hide()}));return this.subs.push(i),n}getStandardButtons(){const t=this.getRunButton(),n=e.div([t]);e.tooltip.bind(n,(()=>t.disabled?this.isRunning.value?"Computations are in progress":this.getValidationMessage():""));const i=this.getSaveButton();return[...this.isHistoryEnabled&&!this.options.isTabbed?[i]:[],...this.runningOnInput?[]:[n]]}buildFormButtons(){var t;const n=this.getStandardButtons(),i=e.buttonsInput();return a()(i.firstChild).css({display:"none"}),null===(t=i.lastChild)||void 0===t||t.replaceWith(e.div([...this.navBtns,...this.additionalBtns,...n],"ui-input-editor")),a()(i).addClass("rfv-buttons"),a()(i).css({"max-width":"100%"}),this.formButtons.replaceWith(i),this.formButtons=i,i}setAdditionalButtons(t){this.additionalBtns=t,this.buildFormButtons()}setNavigationButtons(t){this.navBtns=t}buildIO(){const{inputBlock:t,inputForm:n,outputForm:i,controlsWrapper:o}=this.buildInputBlock(),s=[...Array.from(n.childNodes),...this.isUploadMode.value?[Array.from(i.childNodes)]:[]];e.tools.handleResize(t,(()=>{a()(t).width()<300?(a()(n).addClass("ui-form-condensed"),a()(i).addClass("ui-form-condensed"),a()(o).addClass("ui-form-condensed"),s.forEach((t=>a()(t).css("min-width","100px")))):(a()(n).removeClass("ui-form-condensed"),a()(i).removeClass("ui-form-condensed"),a()(o).removeClass("ui-form-condensed"),s.forEach((t=>a()(t).css("min-width","100%"))))}));const r=this.buildOutputBlock();r.style.height="100%",r.style.width="100%",this.hideOutput();const l=e.splitH([t,e.panel([r],{style:{"padding-top":"0px"}})],null,!0);return l.style.padding="0 12px",t.style.maxWidth="360px",l}buildInputBlock(){const t=this.renderInputForm(),n=this.renderOutputForm();this.buildFormButtons();const i=e.div(this.formButtons,"ui-form ui-form-wide");a()(i).css({"padding-left":"0px","padding-bottom":"0px","padding-right":"6px","max-width":"100%","min-height":"50px"});const o=e.input.toggle("",{value:this.isUploadMode.value,onValueChanged:()=>this.isUploadMode.next(o.value)}),s=this.isUploadMode.subscribe((t=>{o.notify=!1,o.value=t,o.notify=!0,t?a()(n).show():a()(n).hide()}));return this.subs.push(s),{inputBlock:e.divV([t,...this.hasUploadMode&&!this.uploadFunc?[e.divH([e.h2("Experimental data"),o.root],{style:{"flex-grow":"0"}}),n]:[],i],"ui-box rfv-form"),inputForm:t,outputForm:n,controlsWrapper:i}}processCustomDataUpload(){return Ei(this,void 0,void 0,(function*(){const n=()=>{const t=o.Dialog.create({title:"Select to compare"}),n=new Gt(p.length>0?p:[...this.historyBlock.history.values()],{fallbackText:"No historical runs found",showActions:!(p.length>0),showBatchActions:!(p.length>0)}),i=new Gt(d,{fallbackText:"No runs uploaded",showActions:!1,showBatchActions:!1});t.add(e.divV([e.divV([e.label("Uploaded runs"),e.element("div","splitbar-horizontal"),i.root],{style:{height:"50%","overflow-y":"hidden"}}),e.divV([e.label(p.length>0?"Simulated":"History",{style:{padding:"0px 10px 0px 9px"}}),e.element("div","splitbar-horizontal"),n.root],{style:{height:"50%","overflow-y":"hidden"}})],{style:{"justify-content":"space-between",gap:"10px","overflow-y":"scroll",height:"100%"}})),a()(t.root.querySelector(".d4-dialog-contents")).removeClass("ui-form");const s="Compare selected";return 0===p.length?t.addButton(s,(()=>Ei(this,void 0,void 0,(function*(){const e=yield Promise.all([...n.selected].map((t=>dt.loadRun(t.id))));this.onComparisonLaunch([...e,...i.selected.values()]),t.close()})))):t.addButton(s,(()=>Ei(this,void 0,void 0,(function*(){this.onComparisonLaunch([...n.selected.values(),...i.selected.values()]),t.close()})))),t.getButton(s).disabled=!0,this.subs.push((0,c.merge)(n.onSelectedChanged,i.onSelectedChanged).subscribe((()=>{n.selected.size+i.selected.size>1?t.getButton(s).disabled=!1:t.getButton(s).disabled=!0}))),this.isHistorical.value&&t.addButton(v,(()=>Ei(this,void 0,void 0,(function*(){this.onComparisonLaunch([this.funcCall,...i.selected.values()]),t.close()})))),a()(t.getButton("CANCEL")).hide(),t},i=yield t.functions.eval(this.uploadFunc),r=yield i.prepare({params:{func:this.func}}).call(),l=r.outputs.uploadWidget,u=r.outputs.uploadFuncCall;let d=[],p=[];const h=o.Dialog.create({title:"Upload"});a()(h.root.querySelector(".d4-dialog-contents")).removeClass("ui-form");const f=o.Dialog.create({title:"Review uploaded runs"});a()(f.root.querySelector(".d4-dialog-contents")).removeClass("ui-form");const m="Save to history",v="Compare w/ current";h.add(l.root),h.addButton(m,(()=>Ei(this,void 0,void 0,(function*(){return Mt(h.root,!0),d.forEach((t=>{t.options.immutable_tags?t.options.immutable_tags.push(A):t.options.immutable_tags=[A]})),Promise.all(d.map((t=>Ei(this,void 0,void 0,(function*(){const e=yield this.getValidExpRun(t);return dt.saveRun(e)}))))).then((t=>Promise.all(t.map((t=>dt.loadRun(t.id)))))).then((t=>{t.forEach((t=>this.historyBlock.addRun(t)))})).catch((e=>{t.shell.error(e)})).finally((()=>{Mt(h.root,!1),h.close();const t=new Gt(d,{fallbackText:"No runs uploaded",showActions:!0,showBatchActions:!0});f.add(t),f.show({modal:!0,fullScreen:!0})}))})))),h.addButton("Next",(()=>{h.close(),d.forEach((t=>{t.options.immutable_tags?t.options.immutable_tags.push(A):t.options.immutable_tags=[A]}));const t=new Gt(d,{fallbackText:"No runs uploaded",showActions:!0,showBatchActions:!0});f.add(t.root),f.show({modal:!0,fullScreen:!0})})),a()(h.getButton("CANCEL")).hide(),h.getButton(m).disabled=!0,h.getButton("Next").disabled=!0,a()(f.getButton("CANCEL")).hide(),f.addButton("Simulate w/ same inputs",(()=>{Mt(h.root,!0),Promise.all(d.map((t=>this.func.prepare(_t(t).inputs).call()))).then((t=>{p=t,f.close(),n().show({modal:!0,fullScreen:!0})})).catch((e=>{t.shell.error(e)})).finally((()=>{Mt(h.root,!1)}))})),f.addButton("Compare w/ history",(()=>{f.close(),n().show({modal:!0,fullScreen:!0})}));const g=t.functions.onAfterRunAction.pipe((0,s.filter)((t=>t.id===u.id))).subscribe((()=>{d=u.outputs.uploadedCalls,h.getButton(m).disabled=!1,h.getButton("Next").disabled=!1})),y=h.onClose.subscribe((()=>{this.isUploadMode.next(!1)}));h.subs.push(y,g),h.show({modal:!0,center:!0,resizable:!0})}))}onSaveClick(){return Ei(this,void 0,void 0,(function*(){this.isUploadMode.value?yield this.saveExperimentalRun(this.funcCall):yield this.saveRun(this.funcCall)}))}buildRibbonPanels(){super.buildRibbonPanels();const n=e.iconFA("play",(()=>Ei(this,void 0,void 0,(function*(){return yield this.doRun()}))),"Run computations");n.classList.add("fas");const i=e.iconFA("arrow-to-top",(()=>Ei(this,void 0,void 0,(function*(){this.uploadFunc?yield this.processCustomDataUpload():(this.isUploadMode.next(!this.isUploadMode.value),i.classList.toggle("d4-current"))}))),"Upload experimental data");i.classList.add("d4-toggle-button",...this.isUploadMode.value?["d4-current"]:[]);const o=e.iconFA("analytics",(()=>Ei(this,void 0,void 0,(function*(){return yield this.onSALaunch()}))),"Run sensitivity analysis"),s=e.iconFA("chart-line",(()=>Ei(this,void 0,void 0,(function*(){return yield this.onFittingLaunch()}))),"Fit inputs"),r=e.iconFA("info",(()=>Ei(this,void 0,void 0,(function*(){this.hasContextHelp&&(t.shell.windows.help.visible=!0,yield new Promise((t=>setTimeout(t,100))),t.shell.windows.help.showHelp(e.markdown(yield this.getContextHelp())))})))),a=[[...super.buildRibbonPanels().flat(),...this.runningOnInput||this.options.isTabbed?[]:[n],...this.hasUploadMode?[i]:[],...this.isSaEnabled?[o]:[],...this.isFittingEnabled?[s]:[],...this.hasContextHelp?[r]:[]]];return this.setRibbonPanels(a),a}showOutput(){e.setDisplay(this.tabsElem.root,!0),this._isOutputOutdated.next(!1)}getViewers(t){return this.dfToViewerMapping[t]}buildOutputBlock(){this.tabsElem.root.style.width="100%",this.tabsLabels.forEach((n=>{const[i,r]=this.categoryToDfParamMap.outputs[n]?[this.categoryToDfParamMap.outputs[n],!1]:[this.categoryToDfParamMap.inputs[n],!0],l=i.filter((t=>t.propertyType===o.TYPE.DATA_FRAME||t.propertyType===o.TYPE.GRAPHICS)),u=i.filter((t=>t.propertyType!==o.TYPE.DATA_FRAME&&t.propertyType!==o.TYPE.GRAPHICS)),d=l.map((t=>et(t).config));let p="";const h=l.reduce(((n,i,l)=>{var u,c;this.dfToViewerMapping[i.name]=[];const h=d[l].map(((n,s)=>Ei(this,void 0,void 0,(function*(){var s,r,a,l;const u=null!==(l=null!==(r=null===(s=this.funcCall.outputs[i.name])||void 0===s?void 0:s.value)&&void 0!==r?r:null===(a=this.funcCall.inputParams[i.name])||void 0===a?void 0:a.value)&&void 0!==l?l:t.data.demo.demog(0),c=n.type,d=Object.values(m).includes(c)?o.Viewer.fromType(c,u):yield u.plot.fromType(c);d.setOptions(n),this.dfToViewerMapping[i.name].push(d),this.afterOutputPropertyRender.next({prop:i,output:d});const p=Ri();return 0===u.rowCount&&"demog 0"===u.name&&(e.setDisplay(d.root,!1),e.setDisplay(p,!0)),{viewer:d,stub:p}})))),f=h.map(((t,n)=>t.then((({viewer:t,stub:o})=>{const r=this.funcCallReplaced.pipe((0,s.startWith)(null),(0,s.switchMap)((()=>{var t;return(null!==(t=this.funcCall.outputParams[i.name])&&void 0!==t?t:this.funcCall.inputParams[i.name]).onChanged.pipe((0,s.startWith)(null))})),(0,s.skip)(1)).subscribe((()=>Ei(this,void 0,void 0,(function*(){var s;const r=null!==(s=this.funcCall.outputParams[i.name])&&void 0!==s?s:this.funcCall.inputParams[i.name];if(r.value){if(e.setDisplay(t.root,!0),e.setDisplay(o,!1),Object.values(m).includes(t.type))t.dataFrame=r.value;else{const e=yield r.value.plot.fromType(t.type);t.root.replaceWith(e.root),t=e}Object.keys(d[l][n]).includes("color")&&t.setOptions({color:d[l][n].color}),this.afterOutputPropertyRender.next({prop:i,output:t})}else e.setDisplay(t.root,!1),e.setDisplay(o,!0)}))));return this.subs.push(r),{loadedViewer:t,stub:o}})))),v=p!==(null!==(u=i.options.caption)&&void 0!==u?u:i.name)?null!==(c=i.options.caption)&&void 0!==c?c:i.name:" ";if(p=v,r){const t=this.funcCallReplaced.pipe((0,s.switchMap)((()=>{var t;return(null!==(t=this.funcCall.outputParams[i.name])&&void 0!==t?t:this.funcCall.inputParams[i.name]).onChanged}))).subscribe((()=>{this.showOutput(),this.inputTabsLabels.forEach((t=>{a()(this.tabsElem.getPane(t).header).show()}))}));this.subs.push(t)}const g=f.map(((t,n)=>{const i=d[l][n].block,o=e.wait((()=>Ei(this,void 0,void 0,(function*(){const n=yield t;return a()(n.loadedViewer.root).css({height:"100%",width:"100%"}),e.divV([n.loadedViewer.root,n.stub],{style:{width:"100%"}})}))));return a()(o).css({"min-height":"300px","flex-grow":"1"}),e.divV([e.h2(0===n?v:" ",{style:{"white-space":"pre"}}),o],{style:Object.assign({},i?{width:`${i}%`,"max-width":`${i}%`,"max-height":"100%"}:{"flex-grow":"1"})})}));if(i.propertyType===o.TYPE.GRAPHICS){const t=i.options.block,o=Ri();o.classList.add("grok-scripting-image-container");const r=e.divV([e.h2(v,{style:{"white-space":"pre"}}),o],{style:Object.assign({},t?{width:`${t}%`,"max-width":`${t}%`,"max-height":"100%"}:{"flex-grow":"1"})}),a=()=>{var t;const e=null!==(t=this.funcCall.outputParams[i.name])&&void 0!==t?t:this.funcCall.inputParams[i.name];e.value?(o.style.backgroundImage=`url("data:image/png;base64,${e.value}")`,o.textContent=""):(o.style.removeProperty("background-image"),o.textContent="[No data to display]")},l=this.funcCallReplaced.pipe((0,s.startWith)(null),(0,s.switchMap)((()=>{var t;return(null!==(t=this.funcCall.outputParams[i.name])&&void 0!==t?t:this.funcCall.inputParams[i.name]).onChanged.pipe((0,s.startWith)(null))})),(0,s.skip)(1)).subscribe(a);this.subs.push(l),n.append(r)}return n.append(...g),n}),e.divH([],{style:{"flex-wrap":"wrap","flex-grow":"1","max-height":"100%"}})),f=()=>{const t=o.HtmlTable.create(u,(t=>{var e;const n=t.options.precision,i=n&&t.propertyType===o.TYPE.FLOAT&&this.funcCall.outputs[t.name]?this.funcCall.outputs[t.name].toPrecision(n):this.funcCall.outputs[t.name],s=t.options.units?` [${t.options.units}]`:"";return[`${null!==(e=t.caption)&&void 0!==e?e:t.name}${s}`,null!=i?i:"[No value]"]})).root;return a()(t).addClass("rfv-scalar-table"),this.afterOutputSacalarTableRender.next(t),t};let v=f();const g=(0,c.merge)(this.funcCallReplaced,this.isRunning.pipe((0,s.filter)((t=>!1===t)),(0,s.skip)(1))).subscribe((()=>{const t=f();v.replaceWith(t),v=t,a()(this.tabsElem.getPane(n).header).show()}));this.subs.push(g),this.tabsElem.addPane(n,(()=>e.divV([...l.length?[h]:[],...u.length?[v]:[]])))}));const n=e.box();return n.append(this.tabsElem.root),n}onAfterLoadRun(t){return Ei(this,void 0,void 0,(function*(){this.showOutput()}))}get tabsLabels(){return[...this.inputTabsLabels,...this.outputTabsLabels]}get outputTabsLabels(){return Object.keys(this.categoryToDfParamMap.outputs)}get inputTabsLabels(){return Object.keys(this.categoryToDfParamMap.inputs)}get categoryToDfParamMap(){const t={inputs:{},outputs:{}};return this.func.inputs.filter((t=>t.propertyType===o.TYPE.DATA_FRAME&&0!==et(t).config.length)).forEach((e=>{const n="Misc"===e.category?"Input":e.category;t.inputs[n]?t.inputs[n].push(e):t.inputs[n]=[e]})),this.func.outputs.forEach((e=>{const n="Misc"===e.category?"Output":e.category;e.propertyType===o.TYPE.DATA_FRAME&&0===et(e).config.length||(t.outputs[n]?t.outputs[n].push(e):t.outputs[n]=[e])})),t}get inputsStorage(){return`RFV_LastInputs_${this.funcCall.func.name}`}saveLastInputs(){return Ei(this,void 0,void 0,(function*(){try{const e=yield f()(this.funcCall.inputParams.values()).reduce(((e,n)=>Ei(this,void 0,void 0,(function*(){const i=n.property.propertyType!==o.TYPE.DATA_FRAME?this.funcCall.inputs[n.name]:yield t.dapi.tables.uploadDataFrame(this.funcCall.inputs[n.name]);return Object.assign(Object.assign({},yield e),{[n.name]:JSON.stringify(i)})}))),Promise.resolve({}));return yield t.dapi.userDataStorage.put(this.inputsStorage,e)}catch(e){t.shell.error(e.toString())}}))}loadLastInputs(){return Ei(this,void 0,void 0,(function*(){try{const e=yield t.dapi.userDataStorage.get(this.inputsStorage);return 0===Object.keys(e).length?null:yield f()(this.funcCall.inputParams.values()).reduce(((n,i)=>Ei(this,void 0,void 0,(function*(){const s=i.property.propertyType!==o.TYPE.DATA_FRAME?JSON.parse(e[i.name]):yield t.dapi.tables.getTable(JSON.parse(e[i.name]));return Object.assign(Object.assign({},yield n),{[i.name]:s})}))),Promise.resolve({}))}catch(e){t.shell.error(e.toString())}}))}deleteLastInputs(){return Ei(this,void 0,void 0,(function*(){try{return yield t.dapi.userDataStorage.put(this.inputsStorage,{})}catch(e){t.shell.error(e.toString())}}))}doRun(){return Ei(this,void 0,void 0,(function*(){this.isRunning.next(!0);try{this.options.isTabbed||(yield this.saveLastInputs()),yield this.run(),this.options.isTabbed||(yield this.deleteLastInputs())}catch(e){t.shell.error(e.toString()),console.log(e)}finally{this.isRunning.next(!1),this.validationRequests.next({isRevalidation:!1,isNewOutput:!0})}}))}setExternalValidationResults(t,e){this.externalValidatorsState[t]=e,this.externalValidatorsUpdates.next(t)}saveInputLockState(t,e,n){"restricted"===n&&(this.funcCall.options[y]=Object.assign(Object.assign({},this.funcCall.options[y]),{[t]:e})),n&&(this.funcCall.options[b]=Object.assign(Object.assign({},this.funcCall.options[b]),{[t]:n})),this.updateConsistencyState()}getInputLockState(t){var e;return null===(e=this.funcCall.options[b])||void 0===e?void 0:e[t]}updateConsistencyState(){const t=Object.values(this.funcCall.options[b]).some((t=>"inconsistent"===t));this.consistencyState.next(t?"inconsistent":"consistent")}getInput(t){return this.inputsMap[t]}setInput(t,e,n){const i=this.getInput(t);if(!i)throw new Error(`No input named ${t}`);if(this.funcCall.inputParams[t].property.propertyType===o.TYPE.DATA_FRAME&&"restricted"===n)throw new Error(`Param ${t} is dataframe. Restricted state is not supported for them.`);n||(n=this.funcCall.inputParams[t].property.propertyType===o.TYPE.DATA_FRAME?"disabled":"restricted"),this.funcCall.inputs[t]=e,this.setInputLockState(i,t,e,n)}getParamChanges(t){return this.funcCallReplaced.pipe((0,s.startWith)(null),(0,s.filter)((()=>!!this.funcCall)),(0,s.map)((()=>this.funcCall.inputParams[t]?"inputParams":"outputParams")),(0,s.switchMap)((e=>this.funcCall[e][t].onChanged.pipe((0,s.startWith)(null),(0,s.map)((()=>this.funcCall[e][t].value))))))}getParamValue(t){var e,n;const i=(null===(e=this.funcCall)||void 0===e?void 0:e.inputParams[t])?"inputParams":"outputParams";return null===(n=this.funcCall)||void 0===n?void 0:n[i][t].value}setInputLockState(t,e,n,i){i&&this.saveInputLockState(e,n,i),D(t)&&("disabled"===i&&t.setDisabled(),"restricted"===i&&t.setRestricted(),"restricted unlocked"===i&&t.setRestrictedUnlocked(),"inconsistent"===i&&t.setInconsistent(),"user input"===i&&t.setUserInput())}getRestrictedValue(t){var e;return null===(e=this.funcCall.options[y])||void 0===e?void 0:e[t]}renderOutputForm(){return this.renderIOForm(Ti.OUTPUTS)}onSALaunch(){return Ei(this,void 0,void 0,(function*(){yield Xn.fromEmpty(this.func)}))}onFittingLaunch(){return Ei(this,void 0,void 0,(function*(){yield Si.fromEmpty(this.func)}))}renderInputForm(){return this.renderIOForm(Ti.INPUTS)}renderIOForm(t){const n=e.divH([],"ui-form ui-form-wide");a()(n).css({"flex-wrap":"wrap","flex-grow":"0","padding-right":"12px","padding-top":"0px","padding-left":"0px","max-width":"100%",gap:"4px"});let i="Misc";const o=this.funcCall[xi[t]].values();return f()(o).filter((t=>!!t)).forEach((e=>{const o=e.property;this.beforeInputPropertyRender.next(o);const s=this.getInputForVal(e);s?(this.inputsMap[e.property.name]=s,t===Ti.INPUTS&&(this.syncInput(e,s,t),this.checkForMapping(e,s),this.runningOnInput||this.disableInputsOnRun(e.property.name,s),this.bindOnHotkey(s)),this.renderCategory(n,e.property.category,i),this.renderInput(n,e,s),this.afterInputPropertyRender.next({prop:o,input:s}),i=o.category):i=o.category})),Object.keys(this.foldedCategoryInputs).forEach((t=>this.foldedCategoryInputs[t].forEach((t=>a()(t.input.root).hide())))),n.classList.remove("ui-panel"),n}saveFocusedElement(t){this.focusedInput=t}restoreFocusedElement(){var t;null===(t=this.focusedInput)||void 0===t||t.focus()}disableInputsOnRun(t,e){const n=this.isRunning.subscribe((n=>{"user input"!==this.getInputLockState(t)&&this.getInputLockState(t)||(n?(Q(e)&&a()(e.input).is(":focus")&&this.saveFocusedElement(e.input),e.enabled=!1):(e.enabled=!0,Q(e)&&this.restoreFocusedElement()))}));this.subs.push(n)}checkForMapping(t,e){if(!e.hasOwnProperty("_chosenRun"))return;const n=t.property.options.funccallMapping;if(!n)return;const i=JSON.parse(n),o=this.funcCallReplaced.pipe((0,s.startWith)(!0),(0,s.switchMap)((()=>this.funcCall.inputParams[t.property.name].onChanged))).subscribe((()=>{Object.entries(i).forEach((([t,n])=>this.setInput(t,e.chosenRun?(t=>{var n,i,o,s,r,a;return null!==(a=null!==(s=null!==(i=null===(n=e.chosenRun)||void 0===n?void 0:n.inputs[t])&&void 0!==i?i:null===(o=e.chosenRun)||void 0===o?void 0:o.outputs[t])&&void 0!==s?s:null===(r=e.chosenRun)||void 0===r?void 0:r.options[t])&&void 0!==a?a:null})(n):Bt(this.funcCall.inputParams[t].property),e.chosenRun?"restricted":"user input")))}));this.subs.push(o)}getInputForVal(t){var n,i;const s=t.property;if(this.inputsOverride[t.property.name])return this.inputsOverride[t.property.name];if(s.propertyType===o.TYPE.STRING&&s.options.choices&&!s.options.propagateChoice)return e.input.choice(null!==(n=s.caption)&&void 0!==n?n:s.name,{value:Bt(s),items:JSON.parse(s.options.choices),nullable:s.nullable});switch(s.propertyType){case"file":return ee.fileInput(null!==(i=s.caption)&&void 0!==i?i:s.name,null,null,null);case o.TYPE.FLOAT:const t=e.input.forProperty(s),n=s.options.format;return n&&(t.format=n),t;default:return e.input.forProperty(s)}}bindOnHotkey(t){Q(t)&&(t.input.onkeydown=t=>Ei(this,void 0,void 0,(function*(){"Enter"==t.key&&this.runRequests.next()})))}get foldedCategories(){var t;return JSON.parse(null!==(t=this.func.options.foldedCategories)&&void 0!==t?t:"[]")}getCategoryWarningIcon(t){const n=e.iconFA("exclamation-circle",null,"This category has inconsistent inputs");a()(n).css({color:"var(--orange-2)","padding-left":"5px"}).hide();const i=this.funcCallReplaced.subscribe((()=>{this.foldedCategoryInputs[t].some((t=>"inconsistent"===this.getInputLockState(t.paramName)&&t.input.value!==this.getRestrictedValue(t.paramName)))?a()(n).show():a()(n).hide()}));return this.subs.push(i),n}renderCategory(t,n,i){if(n!==i)if(this.foldedCategories.includes(n)){const i=this.getCategoryWarningIcon(n),o=e.iconFA("chevron-right",(()=>{var t;a()(s).show(),a()(o).hide(),a()(i).hide(),(null!==(t=this.foldedCategoryInputs[n])&&void 0!==t?t:[]).forEach((t=>a()(t.input.root).css({display:""})))}),"Open category");a()(o).css("padding-right","5px");const s=e.iconFA("chevron-down",(()=>{var t;a()(s).hide(),a()(o).show(),this.foldedCategoryInputs[n].some((t=>"inconsistent"===this.getInputLockState(t.paramName)))?a()(i).show():a()(i).hide(),(null!==(t=this.foldedCategoryInputs[n])&&void 0!==t?t:[]).forEach((t=>a()(t.input.root).hide()))}),"Close category");a()(s).css("padding-right","5px"),t.append(e.h2([o,s,e.h2(n,{style:{display:"inline"}}),i],{style:{width:"100%"}})),a()(s).hide()}else t.append(e.h2(n,{style:{width:"100%"}}))}renderInput(t,n,i){var o;const s=n.property;this.foldedCategories.includes(s.category)&&(this.foldedCategoryInputs[s.category]=[...null!==(o=this.foldedCategoryInputs[s.category])&&void 0!==o?o:[],{paramName:n.property.name,input:i}]),this.injectLockIcons(n,i),(t=>{if(D(t))return;const e=t;e.setDisabled=function(){t.enabled=!1,a()(t.root).removeClass("rfv-restricted-unlocked-input"),a()(t.root).removeClass("rfv-inconsistent-input"),a()(t.root).removeClass("rfv-restricted-input")},e.setRestricted=function(){t.enabled=!1,Q(t)&&(t.input.disabled=!1),a()(t.root).addClass("rfv-restricted-input"),a()(t.root).removeClass("rfv-restricted-unlocked-input"),a()(t.root).removeClass("rfv-inconsistent-input")},e.setRestrictedUnlocked=function(){t.enabled=!0,a()(t.root).addClass("rfv-restricted-unlocked-input"),a()(t.root).removeClass("rfv-restricted-input"),a()(t.root).removeClass("rfv-inconsistent-input")},e.setInconsistent=function(){t.enabled=!0,a()(t.root).addClass("rfv-inconsistent-input"),a()(t.root).removeClass("rfv-restricted-input"),a()(t.root).removeClass("rfv-restricted-unlocked-input")},e.setUserInput=function(){t.enabled=!0,a()(t.root).removeClass("rfv-inconsistent-input"),a()(t.root).removeClass("rfv-restricted-input"),a()(t.root).removeClass("rfv-restricted-unlocked-input")}})(i),Q(i)&&(((t,e)=>{var n;const i=t.property;a()(e.root).css({width:`calc(${null!==(n=i.options.block)&&void 0!==n?n:"100"}% - ${i.options.block?"2":"0"}px)`,"box-sizing":"border-box"})})(n,i),this.bindTooltips(n,i),(t=>{const n=e.element("i");t.addOptions(n),t.setValidation=function(i){for(;n.firstChild&&n.removeChild(n.firstChild););const[o,s]=function(t){let n,i;return(null==t?void 0:t.pending)&&(i=e.iconFA("spinner",(()=>{W(t,i,n)}))),(null==t?void 0:t.errors)&&t.errors.length?(i=e.iconFA("exclamation-circle",(()=>{W(t,i,n)})),i.style.color="var(--red-3)"):(null==t?void 0:t.warnings)&&t.warnings.length?(i=e.iconFA("exclamation-circle",(()=>{W(t,i,n)})),i.style.color="var(--orange-2)"):(null==t?void 0:t.notifications)&&t.notifications.length&&(i=e.iconFA("info-circle",(()=>{W(t,i,n)})),i.style.color="var(--blue-1)"),i&&(i.classList.remove("fal"),i.classList.add("far"),n=function(t){const n=e.div([],"d4-tooltip");return function(t){t.popover="auto",t.style.fontStyle="normal",t.style.pointerEvents="all"}(n),t.appendChild(n),n}(i)),[i,n]}(i);o&&s&&(n.appendChild(o),n.appendChild(s)),t.input.classList.remove("d4-invalid"),t.input.classList.remove("d4-partially-invalid"),(null==i?void 0:i.errors)&&i.errors.length||(null==i?void 0:i.warnings)&&i.warnings.length||(null==i?void 0:i.notifications)&&i.notifications.length||(null==i?void 0:i.pending)?a()(n).css("display","flex"):a()(n).hide(),(null==i?void 0:i.errors)&&i.errors.length?t.input.classList.add("d4-invalid"):(null==i?void 0:i.warnings)&&i.warnings.length&&t.input.classList.add("d4-partially-invalid")}})(i)),t.append(i.root)}bindTooltips(t,n){const i=t.property.name,o=()=>{var n,o;const s=`${null!==(o=null!==(n=t.property.description)&&void 0!==n?n:t.property.caption)&&void 0!==o?o:t.property.name}.`,r=(()=>"disabled"===this.getInputLockState(i)?"Input is disabled to prevent inconsistency.":"inconsistent"===this.getInputLockState(i)?"The entered value is inconsistent to the computed value.":"restricted"===this.getInputLockState(i)?"The value is dependent and computed automatically. Click to edit":null)();return s||r?e.divV([...s?[e.divText(s)]:[],...r?[e.divText(r)]:[]],{style:{"max-width":"300px"}}):null};e.tooltip.bind(n.captionLabel,o),e.tooltip.bind(n.input,o)}injectLockIcons(t,n){const i=t.property.name;n.root.addEventListener("click",(()=>{"restricted"===this.getInputLockState(i)&&this.setInputLockState(n,t.name,t.value,"restricted unlocked")}));const s=e.iconFA("lock");a()(s).addClass("rfv-icon-lock"),a()(s).css({color:"var(--grey-2)"});const r=e.iconFA("lock-open");a()(r).addClass("rfv-icon-unlock"),a()(r).css({color:"var(--grey-2)"});const l=e.iconFA("undo",(e=>{this.setInput(t.name,this.getRestrictedValue(i),"restricted"),e.stopPropagation()}),"Reset value to computed value");a()(l).addClass("rfv-icon-undo"),a()(l).css({color:"var(--blue-2)"});const u=e.iconFA("exclamation-circle",null);e.tooltip.bind(u,(()=>`Current value is incosistent. Computed value was ${o.TYPES_SCALAR.has(t.property.propertyType)?this.getRestrictedValue(i):"different"}`)),a()(u).addClass("rfv-icon-warning"),a()(u).css({color:"var(--orange-2)"});const c=n;c.placeLockStateIcons||(c.placeLockStateIcons=function(t,e,i,o){Q(n)&&(n.addOptions(t),n.addOptions(e),n.addOptions(i),n.addOptions(o))}),c.placeLockStateIcons(s,r,l,u)}syncInput(t,e,n){const i=t.name;let r=!1;const a=this.funcCallReplaced.pipe((0,s.startWith)(!0)).subscribe((()=>{var t,o;const s=this.funcCall[xi[n]][i],r=null!==(o=null!==(t=this.funcCall[n][i])&&void 0!==t?t:Bt(s.property))&&void 0!==o?o:null;e.notify=!1,e.value=r,e.notify=!0,this.funcCall[n][i]=r,this.setInputLockState(e,i,r,this.getInputLockState(i))}));this.subs.push(a);const l=this.funcCallReplaced.pipe((0,s.startWith)(!0),(0,s.switchMap)((()=>{const t=this.funcCall[xi[n]][i];return t.onChanged.pipe((0,s.mapTo)(t))}))).subscribe((t=>{const i=this.funcCall[n][t.name];if(r||(e.notify=!1,e.value=i,e.notify=!0),n===Ti.INPUTS){this.isHistorical.next(!1),this.hideOutput(),this.validationRequests.next({field:t.name,isRevalidation:!1});const n=this.getInputLockState(t.name);"restricted unlocked"!==n&&"inconsistent"!==n||this.setInputLockState(e,t.name,i,i===this.getRestrictedValue(t.name)?"restricted unlocked":"inconsistent")}}));this.subs.push(l);const u=this.funcCallReplaced.pipe((0,s.startWith)(!0),(0,s.switchMap)((()=>{const t=this.funcCall[xi[n]][i];return t.onChanged.pipe((0,s.mapTo)(t),(0,s.startWith)(t))})),(0,s.filter)((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&t.value)),(0,s.switchMap)((t=>t.value.onDataChanged.pipe((0,s.mapTo)(t))))).subscribe((t=>{this.validationRequests.next({field:t.name,isRevalidation:!1})}));this.subs.push(u);const d=(p=e.onInput.bind(e),new c.Observable((t=>{const e=p((e=>{t.next(e)}));return()=>e.unsubscribe()}))).pipe((0,s.debounceTime)(250)).subscribe((()=>{try{r=!0,this.funcCall[n][t.name]=e.value}finally{r=!1}}));var p;this.subs.push(d)}isRunnable(){return!this.isRunning.value&&!this.blockRuns.value&&this.isValid()}isValid(){for(const[t,e]of Object.entries(this.validationState))if(!V(e))return!1;for(const[t,e]of Object.entries(this.externalValidatorsState))if(!V(e))return!1;return!0}getValidationState(){return this.validationState}getValidationMessage(){const t=[];for(const[e,n]of Object.entries(this.validationState))V(n)||t.push(`${e}: ${H(n)}`);return t.join("\n")}runValidation(t,e){return Ei(this,void 0,void 0,(function*(){const n=t.field,i=this.getValidatedNames(n),o=yield Promise.all(i.map((n=>Ei(this,void 0,void 0,(function*(){const i=this.funcCall.inputs[n],o=yield(u=i,this._funcCall,this.lastCall,t.isNewOutput,t.isRevalidation,s=void 0,r=void 0,a=void 0,l=function*(){if(null==u)return U({errors:["Missing value"]})},new(a||(a=Promise))((function(t,e){function n(t){try{o(l.next(t))}catch(t){e(t)}}function i(t){try{o(l.throw(t))}catch(t){e(t)}}function o(e){var o;e.done?t(e.value):(o=e.value,o instanceof a?o:new a((function(t){t(o)}))).then(n,i)}o((l=l.apply(s,r||[])).next())})));var s,r,a,l,u;let c;const d=this.validators[n];return d&&(c=yield d(i,{param:n,funcCall:this._funcCall,lastCall:this.lastCall,signal:e,isNewOutput:!!t.isNewOutput,isRevalidation:t.isRevalidation,context:t.context,view:this})),[n,Y(...this.funcCall.inputParams[n].property.options.nullable?[]:[o],c)]})))));return Object.fromEntries(o)}))}setValidationPending(t){const e=this.getValidatedNames(t);for(const t of e){this.validationState[t]={pending:!0};const e=this.inputsMap[t];_(e)&&e.setValidation({pending:!0})}this.validationUpdates.next(null)}setValidationResults(t){for(const[e,n]of Object.entries(t))this.validationState[e]=n,this.updateInputValidationReuslts(e)}updateInputValidationReuslts(t){const e=Y(this.validationState[t],this.externalValidatorsState[t]),n=this.inputsMap[t];_(n)&&n.setValidation(e)}runRevalidations(t,e){if(!t.isRevalidation)for(const[,t]of Object.entries(e))if(null==t?void 0:t.revalidate)for(const e of t.revalidate)this.validationRequests.next({field:e,context:t.context,isRevalidation:!0})}getValidatedNames(t){return t?[t]:[...this.funcCall.inputs.keys()]}getValidExpRun(e){return Ei(this,void 0,void 0,(function*(){const n=yield(yield t.functions.eval("Sin")).prepare({x:1}).call();e.dart.r2=n.dart.r2;const i=e.options.immutable_tags||[];return e.options.immutable_tags=i.includes(A)?i:[...i,A],e.newId(),e}))}saveExperimentalRun(t){return Ei(this,void 0,void 0,(function*(){const e=yield this.getValidExpRun(t);yield this.saveRun(e)}))}hideOutput(){if(this._isOutputOutdated.next(!0),this.keepOutput())return;this.outputTabsLabels.forEach((t=>{var e;return a()(null===(e=this.tabsElem.getPane(t))||void 0===e?void 0:e.header).hide()}));const t=this.tabsElem.panes.find((t=>this.inputTabsLabels.includes(t.name)));t?this.tabsElem.currentPane=t:a()(this.tabsElem.root).hide()}getSheetName(t,e){if(this.sheetNamesCache[t])return this.sheetNamesCache[t];let n=`${t}`;n.length>31&&(n=`${n.slice(0,31)}`);let i=1;for(;e.worksheets.some((t=>t.name===n));){let e=`${t}`;e.length>31-`-${i}`.length&&(e=`${t.slice(0,31-`-${i}`.length)}`),n=`${e}-${i}`,i++}return this.sheetNamesCache[t]=n,n}richFunctionViewSupportedFormats(){return["Excel","DataUrl images"]}richFunctionViewExportExtensions(){return{Excel:"xlsx","DataUrl images":"txt"}}}var Pi=n(693),ki=n.n(Pi);function Fi(t){return null==t?void 0:t.nestedPipelines}function Li(t){return ki()(t,(t=>{if("function"==typeof t)return t}))}function Ni(t,...e){return t.concat(...e)}function Bi(t){return t.filter((t=>t)).join("/")}function Mi(t){return t.split("/").filter((t=>t))}function _i(t){const e=Mi(t);return Bi(e.slice(0,e.length-1))}function Di(t,e){if(t.startsWith(e))return t.substring(e.length)}function Vi(t){return Array.isArray(t[0])?t:[t]}function ji(t,e,n){var i;const o=[{node:t,path:[]}],s=new Set;for(;o.length;){const{node:t,path:a}=o.pop();if(Fi(t))if(s.has(t))n=e(n,t,a);else{o.push({node:t,path:a});for(const e of Object.values(null!==(i=t.nestedPipelines)&&void 0!==i?i:{}))o.push({node:e,path:[...a,t.id]});s.add(t)}else(null==(r=t)?void 0:r.nestedPipelines)||(n=e(n,t,a))}var r;return n}function $i(e,n){return i=this,o=void 0,r=function*(){if("string"==typeof e){const i=(yield t.functions.eval(e)).prepare({params:n});return yield i.call(),i.outputs}return yield e(n)},new((s=void 0)||(s=Promise))((function(t,e){function n(t){try{l(r.next(t))}catch(t){e(t)}}function a(t){try{l(r.throw(t))}catch(t){e(t)}}function l(e){var i;e.done?t(e.value):(i=e.value,i instanceof s?i:new s((function(t){t(i)}))).then(n,a)}l((r=r.apply(i,o||[])).next())}));var i,o,s,r}function Hi(...t){console.log(...t)}class Ui{constructor(t,e,n,i){this.conf=t,this.pipelineState=e,this.parentId=n,this.notifier=i,this.currentSource=new c.BehaviorSubject((0,c.of)()),this.valueChanges=this.currentSource.pipe((0,s.switchMap)((t=>t))),this.value=new c.BehaviorSubject(void 0),this.setter=(t,e)=>{this.currentSource.next((0,c.of)(t))},this.valueChanges.pipe((0,s.takeUntil)(this.pipelineState.closed)).subscribe((t=>{Hi(`state updated: ${this.parentId}/${this.conf.id}, new value ${t}`),this.value.next(t)}))}linkState(t,e){this.currentSource.next(t),e&&(this.setter=e)}getValue(){return this.value.value}setValue(t,e){this.setter(t,e)}}class Yi{constructor(t,e,n){this.pipelinePath=t,this.from=[],this.to=[],this.fromKeys=new Set,this.toKeys=new Set,e&&(this.from=Vi(e),this.fromKeys=new Set(this.from.map((t=>Bi(t))))),n&&(this.to=Vi(n),this.toKeys=new Set(this.to.map((t=>Bi(t)))))}}class Wi{constructor(t,e,n,i){if(this.conf=t,this.type=e,this.pipelinePath=n,this.pipelineState=i,this.states=new Map,this.notifier=new c.Subject,"pipeline"===e){const e=t.states;for(const n of null!=e?e:[])this.states.set(n.id,new Ui(n,this.pipelineState,t.id))}if("step"===e){const e=t.states;for(const n of null!=e?e:[])this.states.set(n.id,new Ui(n,this.pipelineState,t.id))}if("popup"===e){const e=t.states;for(const n of null!=e?e:[])this.states.set(n.id,new Ui(n,this.pipelineState,t.id,this.notifier))}if("action"===e){const e=t;this.controllerConfig=new Yi(n,e.from,e.to)}}}class Gi{constructor(t,e,n){this.conf=t,this.pipelinePath=e,this.pipelineState=n,this.enabled=new c.BehaviorSubject(!0),this.currentSource=new c.BehaviorSubject((0,c.of)()),this.externalTrigger=new c.Subject,this.valueChanges=this.currentSource.pipe((0,s.switchMap)((t=>t))),this.controllerConfig=new Yi(e,t.from,t.to)}setSources(t){this.currentSource.next((0,c.merge)(...t,this.externalTrigger))}trigger(){this.externalTrigger.next(!0)}getValuesChanges(){return this.valueChanges.pipe((0,s.withLatestFrom)(this.enabled),(0,s.filter)((([,t])=>!!t)),(0,s.mapTo)(!0))}}class zi extends Error{}class qi{constructor(t,e,n,i){this.handlerId=t,this.config=e,this.rt=n,this.signal=i}enableLink(t){this.checkAborted();const e=Ni(this.config.pipelinePath,t);return this.rt.setLinkState(e,!0)}disableLink(t){this.checkAborted();const e=Ni(this.config.pipelinePath,t);return this.rt.setLinkState(e,!1)}isLinkEnabled(t){this.checkAborted();const e=Ni(this.config.pipelinePath,t);return this.rt.setLinkState(e,!1)}enableStep(t){this.checkAborted();const e=Ni(this.config.pipelinePath,t);if(this.checkOutput(e))return Hi(`handler: ${this.handlerId}, try enable step: ${Bi(e)}`),this.rt.setStepState(e,!0)}disableStep(t){this.checkAborted();const e=Ni(this.config.pipelinePath,t);if(this.checkOutput(e))return Hi(`handler: ${this.handlerId}, try enable step: ${Bi(e)}`),this.rt.setStepState(e,!1)}isStepEnabled(t){this.checkAborted();const e=Ni(this.config.pipelinePath,t);return this.rt.getStepState(e)}enablePipeline(t){this.checkAborted();const e=Ni(this.config.pipelinePath,t);if(this.checkOutput(e))return Hi(`handler: ${this.handlerId}, try enable pipeline: ${Bi(e)}`),this.rt.setPipelineState(e,!0)}disablePipeline(t){this.checkAborted();const e=Ni(this.config.pipelinePath,t);if(this.checkOutput(e))return Hi(`handler: ${this.handlerId}, try disable pipeline: ${Bi(e)}`),this.rt.setPipelineState(e,!1)}triggerLink(t){this.checkAborted();const e=Ni(this.config.pipelinePath,t);if(this.checkOutput(e))return this.rt.triggerLink(e)}getState(t){this.checkAborted();const e=Ni(this.config.pipelinePath,t);if(this.checkInput(e))return this.rt.getState(e)}setState(t,e,n){this.checkAborted();const i=Ni(this.config.pipelinePath,t);if(this.checkOutput(i))return Hi(`handler: ${this.handlerId}, try update state: ${Bi(i)}, value: ${e}`),this.rt.setState(i,e,n)}updateStateInputState(t,e){this.checkAborted();const n=Ni(this.config.pipelinePath,t);this.checkOutput(n)&&this.rt.setState(n,this.rt.getState(n),e)}getView(t){this.checkAborted();const e=Ni(this.config.pipelinePath,t);return this.rt.getView(e)}goToStep(t){this.checkAborted();const e=Ni(this.config.pipelinePath,t);return this.rt.goToStep(e)}setValidation(t,e){this.checkAborted();const n=Ni(this.config.pipelinePath,t),i=Mi(this.handlerId);this.checkValidation(n)&&(Hi(`handler: ${this.handlerId}: update validation: ${n}, value: ${e}`),this.rt.setValidation(n,i,e))}getValidationAction(t,e){this.checkAborted();const n=Ni(this.config.pipelinePath,t);return this.rt.getAction(n,e)}loadNestedPipeline(t,e){this.checkAborted();const n=Ni(this.config.pipelinePath,t);this.rt.loadNestedPipeline(n,e)}getCloseNotifier(){return this.rt.pipelineState.closed}checkAborted(){var t;if(null===(t=this.signal)||void 0===t?void 0:t.aborted)throw new zi}checkInput(e){const n=Bi(e);return this.config.fromKeys.has(n)||t.shell.warning(`Handler ${this.handlerId} has not declared access to input ${n}`),!0}checkOutput(e){const n=Bi(e);return this.config.toKeys.has(n)||t.shell.warning(`Handler ${this.handlerId} has not declared access to output ${n}`),!this.config.fromKeys.has(n)||(t.shell.error(`Handler ${this.handlerId} trying to set output value which is input ${n}`),!1)}checkValidation(e){const n=Bi(e);return this.config.toKeys.has(n)&&this.config.fromKeys.has(n)||t.shell.warning(`Handler ${this.handlerId} should declare both input and output access to set validation ${n}`),!0}}var Ji=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};class Ki{constructor(t,e,n,i){this.nodes=t,this.links=e,this.view=n,this.pipelineState=i,this.runningLinks=new Set,this.disabledSettersPrefixes=new Set,this.validationState=new Map,this.pipelineLoads=new c.Subject,this.isUpdating=new c.BehaviorSubject(!1),this.pipelineLoads.pipe((0,s.concatMap)((({path:t,runId:e})=>(0,c.from)(this.pipelineLoader(t,e)))),(0,s.takeUntil)(this.pipelineState.closed)).subscribe()}setLinkState(t,e){const n=Bi(t),i=this.links.get(n);i&&i.enabled.next(e)}getLinkState(t){const e=Bi(t),n=this.links.get(e);return!!(null==n?void 0:n.enabled.value)}setStepState(t,e){const n=Bi(t);this.isSetterDisabled(t,"step")||(Hi(`step visibility updated: ${n}, new value: ${e}`),e?this.view.showSteps(n):this.view.hideSteps(n))}getStepState(t){const e=Bi(t);return this.view.getStepState(e)===S.VISIBLE}setPipelineState(t,e){const n=this.getNestedSteps(t);for(const t of n)this.setStepState(Mi(t.pathKey),e)}loadNestedPipeline(t,e){this.pipelineLoads.next({path:t,runId:e})}triggerLink(t){const e=Bi(t),n=this.links.get(e);n&&n.trigger()}getState(t){const{state:e}=this.getNodeState(t);return null==e?void 0:e.getValue()}setState(t,e,n){const{state:i,node:o}=this.getNodeState(t);i&&!this.isSetterDisabled(t,o.type)&&i.setValue(e,n)}getView(t){const e=Bi(t);return this.view.getStepView(e)}setValidation(t,e,n){var i;const o=Bi(t),s=Bi(e),r=null!==(i=this.validationState.get(o))&&void 0!==i?i:new Map;r.set(s,n),this.validationState.set(o,r),this.updateViewValidation(t)}getAction(n,i){const o=Bi(n),s=this.nodes.get(o);if("action"!==(null==s?void 0:s.type)&&"popup"!==(null==s?void 0:s.type)){const e=`Node ${n.join(",")} is not an action/popup`;throw t.shell.error(e),new Error(e)}if("action"===s.type){const e=s.conf,n=e.handler,o=s.controllerConfig;return{actionName:null!=i?i:e.friendlyName,action:()=>Ji(this,void 0,void 0,(function*(){try{const t=new qi(s.conf.id,o,this);yield $i(n,{controller:t})}catch(e){throw t.shell.error(String(e)),e}}))}}{const n=s.conf,o=this.view.getStepView(n.id);if(!o){const e=`Popup view ${n.id} not found`;throw t.shell.error(e),new Error(e)}return{actionName:null!=i?i:n.friendlyName,action:()=>Ji(this,void 0,void 0,(function*(){try{yield new Promise(((t,i)=>{e.dialog(n.friendlyName).add(o.root).onOK((()=>{s.notifier.next(!0),t(!0)})).onCancel((()=>{t(!1)})).showModal(!0)}))}catch(e){throw t.shell.error(String(e)),e}}))}}}wireViews(){for(const[,t]of this.nodes)for(const[,e]of t.states)if(!("popup"!==t.type&&"step"!==t.type||"input"!==e.conf.stateType&&"output"!==e.conf.stateType)){const n=e.conf.id,{changes:i,setter:o}=this.view.getStateBindings(t.conf.id,n);e.linkState(i,o)}}wireLinks(){var t;for(const[,e]of this.links){const n=e.controllerConfig.from.map((t=>this.getValueChanges(t,e))),i=null!==(t=e.conf.handler)&&void 0!==t?t:this.getDefaultHandler(e);e.getValuesChanges().pipe((0,s.debounceTime)(0),(0,s.switchMap)((()=>this.getHandlerObservable(e,i))),(0,s.takeUntil)(this.pipelineState.closed)).subscribe(),e.setSources(n)}}getHandlerObservable(e,n){return new c.Observable((i=>{this.addRunningHandler(e.conf.id);const o=new AbortController,r=o.signal,a=new qi(e.conf.id,e.controllerConfig,this,r);let l=!1;const u=(0,c.from)($i(n,{controller:a})).pipe((0,s.finalize)((()=>this.removeRunningHandler(e.conf.id)))).subscribe((t=>{l=!0,i.next(t)}),(e=>{e instanceof zi||(t.shell.error(e),console.error(e))}));return()=>{l||o.abort(),u.unsubscribe()}}))}getValueChanges(t,e){const{state:n}=this.getNodeState(t),i=e.conf.includeDataFrameMutations?n.value.pipe((0,s.switchMap)((t=>{var e;return(null==t?void 0:t.onDataChanged)&&(null===(e=null==t?void 0:t.onDataChanged)||void 0===e?void 0:e.pipe)?t.onDataChanged.pipe((0,s.startWith)(null),(0,s.mapTo)(t)):(0,c.of)(t)}))):n.value,o=n.notifier;return e.conf.ignoreNotifier||!o?i:i.pipe((0,s.sample)(o))}getDefaultHandler(t){return()=>Ji(this,void 0,void 0,(function*(){const e=Math.min(t.controllerConfig.from.length,t.controllerConfig.to.length);for(let n=0;n<e;n++){let e=this.getState(t.controllerConfig.from[n]);e instanceof o.DataFrame&&(e=e.clone()),this.setState(t.controllerConfig.to[n],e,t.conf.inputState)}}))}getRunningUpdates(){return[...this.runningLinks]}goToStep(t){console.log("TODO: not implemented")}disableSubStepsIOSetters(t){const e=Bi(t);Hi(`disable substeps setters: ${e}`),this.disabledSettersPrefixes.add(e)}enableSubStepsIOSetters(t){const e=Bi(t);Hi(`enable substeps setters: ${e}`),this.disabledSettersPrefixes.delete(e)}awaitForAllUpdatesDone(){return Ji(this,void 0,void 0,(function*(){yield this.isUpdating.pipe((0,s.debounceTime)(1),(0,s.filter)((t=>!t)),(0,s.take)(1)).toPromise()}))}pipelineLoader(t,e){return Ji(this,void 0,void 0,(function*(){this.setPipelineState(t,!1),this.disableSubStepsIOSetters(t);try{const n=yield this.loadPipelineFuncCalls(e),i=this.getNestedSteps(t);yield this.loadNestedSteps(n,i),yield this.awaitForAllUpdatesDone()}finally{this.enableSubStepsIOSetters(t)}}))}loadNestedSteps(t,e){return Ji(this,void 0,void 0,(function*(){const n=new Map;for(const t of e)n.set(t.nestedStepId,t);for(const e of t){const t=e.options.customId,i=n.get(t);if(i){const t=this.view.getStepView(i.pathKey);if(t){Hi(`loaded step: ${i.pathKey}, nqName: ${i.nqName}, id: ${e.id}`);const n=yield t.loadRun(e.id);this.view.showSteps(i.pathKey),J(n)||this.view.enableStep(i.pathKey)}}}const i=this.view.getFollowingStep();i&&i.ability.next(T.ENABLED)}))}getNestedSteps(t){const e=Bi(t),n=t[t.length-1];return[...this.nodes.entries()].filter((([t,n])=>"step"===n.type&&Di(t,e))).map((([t,i])=>{const o=t,s=Di(t,e);return{pathKey:o,nestedStepId:Bi(Ni([n],Mi(s))),nqName:i.conf.nqName}}))}loadPipelineFuncCalls(t){return Ji(this,void 0,void 0,(function*(){return(yield dt.loadChildRuns(t)).childRuns}))}addRunningHandler(t){this.runningLinks.add(t),this.isUpdating.next(!0)}removeRunningHandler(t){this.runningLinks.delete(t),this.isUpdating.next(0!==this.runningLinks.size)}isSetterDisabled(t,e){if("step"===e){const e=Bi(t);for(const t of this.disabledSettersPrefixes)if(Di(e,t))return!0}return!1}getNodeState(t){const e=t.slice(0,t.length-1),n=t[t.length-1],i=Bi(e),o=this.nodes.get(i);if(o&&o.states){const t=o.states.get(n);if(t)return{node:o,state:t}}}updateViewValidation(t){const e=Bi(t),n=this.validationState.get(e),i=[...n.keys()].sort().map((t=>n.get(t))),{state:o,node:s}=this.getNodeState(t);this.view.setExternalValidationResults(s.conf.id,o.conf.id,Y(...i))}}class Zi{constructor(){this.closed=new c.Subject}}var Xi=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};class Qi extends En{constructor(t){super(t,[],{historyEnabled:!0,isTabbed:!1,skipInit:!0}),this.hooks=[],this.customViews=new Map}injectConfiguration(t,e,n,i){i&&(this.exportConfig=Object.assign(Object.assign({},this.exportConfig),i)),this.initialConfig=t.map((t=>Object.assign(Object.assign({},t),{customId:t.id}))),this.hooks=e,this.rt=n,this.rt.isUpdating.pipe((0,s.takeUntil)(this.rt.pipelineState.closed)).subscribe((t=>this.isUpdating.next(t)))}getStateBindings(t,e){const n=this.getStepView(t);return{changes:n.getParamChanges(e),setter:(t,i)=>{n.setInput(e,t,i)}}}setExternalValidationResults(t,e,n){const i=this.getStepView(t);i&&i.setExternalValidationResults(e,n)}addMenuItem(t,e){var n;null===(n=this.actionsMenu)||void 0===n||n.item(t,e)}enableStep(t){this.steps[t].ability.next(T.ENABLED)}getStepState(t){return this.steps[t].visibility.value}getFollowingStep(){return Object.values(this.steps).filter((t=>t.visibility.value===S.VISIBLE&&t.ability.value===T.DISABLED))[0]}getRunningUpdates(){return this.rt.getRunningUpdates()}buildRibbonMenu(){super.buildRibbonMenu(),this.actionsMenu=this.ribbonMenu.group("Actions")}getStepView(t){return super.getStepView(t)||this.customViews.get(t)}init(){const t=Object.create(null,{init:{get:()=>super.init}});return Xi(this,void 0,void 0,(function*(){this.rt.disableSubStepsIOSetters([]),yield this.execHooks("beforeInit"),yield t.init.call(this),yield this.execHooks("afterInit")}))}onBeforeStepFuncCallApply(t,e,n){return Xi(this,void 0,void 0,(function*(){yield this.execHooks("beforeFuncCallReady",{nqName:t,scriptCall:e,editorFunc:n})}))}onAfterStepFuncCallApply(t,e,n){return Xi(this,void 0,void 0,(function*(){yield this.execHooks("afterFuncCallReady",{nqName:t,scriptCall:e,view:n})}))}onBeforeLoadRun(){const t=Object.create(null,{onBeforeLoadRun:{get:()=>super.onBeforeLoadRun}});return Xi(this,void 0,void 0,(function*(){this.rt.disableSubStepsIOSetters([]),yield t.onBeforeLoadRun.call(this),yield this.execHooks("beforeLoadRun")}))}onAfterLoadRun(t){const e=Object.create(null,{onAfterLoadRun:{get:()=>super.onAfterLoadRun}});return Xi(this,void 0,void 0,(function*(){yield e.onAfterLoadRun.call(this,t),yield this.rt.awaitForAllUpdatesDone(),this.rt.enableSubStepsIOSetters([]),yield this.execHooks("afterLoadRun",{run:t})}))}onBeforeSaveRun(){const t=Object.create(null,{onBeforeLoadRun:{get:()=>super.onBeforeLoadRun}});return Xi(this,void 0,void 0,(function*(){this.rt.disableSubStepsIOSetters([]),yield t.onBeforeLoadRun.call(this),yield this.execHooks("beforeSaveRun")}))}onAfterSaveRun(t){const e=Object.create(null,{onAfterLoadRun:{get:()=>super.onAfterLoadRun}});return Xi(this,void 0,void 0,(function*(){yield e.onAfterLoadRun.call(this,t),yield this.rt.awaitForAllUpdatesDone(),this.rt.enableSubStepsIOSetters([]),yield this.execHooks("afterSaveRun",{run:t})}))}build(){super.build(),this.rt.wireViews(),this.rt.wireLinks(),this.rt.enableSubStepsIOSetters([]),this.execHooks("onViewReady",{view:this})}close(){this.rt.pipelineState.closed.next(!0);for(const t of this.customViews.values())t.customClose();super.close()}execHooks(t){return Xi(this,arguments,void 0,(function*(t,e={}){for(const{hooks:n,pipelinePath:i}of this.hooks){const o=n[t];for(const t of null!=o?o:[]){const n=t.handler,o=new Yi(i,t.from,t.to),s=new qi(t.id,o,this.rt),r=Object.assign(Object.assign({},e),{controller:s});yield $i(n,r)}}}))}}class to extends Oi{detach(){}customClose(){super.detach(),super.close()}}var eo=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))},no=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};function io(e){return()=>no(this,void 0,void 0,(function*(){try{const n=yield t.dapi.groups.filter(`friendlyName="${e}"`).list();if(0===n.length)throw new Error("group with specified name is not found");if(n.length>1)throw new Error("found more than one group with specified name");const i=n[0];fetch(`${window.location.origin}/api/groups/${i.id}/requests/${t.shell.user.group.id}`,{method:"POST"})}catch(e){t.shell.error(e.toString())}}))}class oo extends o.ObjectHandler{get type(){return"Model"}getById(e){return no(this,void 0,void 0,(function*(){return yield t.dapi.functions.find(e)}))}refresh(t){return no(this,void 0,void 0,(function*(){return yield this.getById(t.id)}))}static openHelp(n){return no(this,void 0,void 0,(function*(){if(null!=n.options.readme){t.shell.windows.showHelp=!0,yield new Promise((t=>setTimeout(t,100)));const i=`System:AppData/${n.package.name}/${n.options.readme}`;t.dapi.files.readAsText(i).then((n=>{t.shell.windows.help.showHelp(e.markdown(n))}))}}))}static openModel(t){t.prepare().edit()}static openModelFromFunccall(t){t.edit()}isApplicable(t){const e=o.toJs(t);return e instanceof o.Func&&e.hasTag("model")}constructor(){super(),this.userGroups=new c.BehaviorSubject(void 0)}getLanguageIcon(t){return"grok"==t?e.iconSvg("project"):e.iconImage("script",`/images/entities/${t}.png`)}renderMarkup(n){const i=e.divH([],{style:{"justify-content":"space-between",width:"100%"}});return setTimeout((()=>no(this,void 0,void 0,(function*(){const o=yield this.awaitUserGroups(),s=JSON.parse(n.options.mandatoryUserGroups?`${n.options.mandatoryUserGroups}`:"[]").filter((t=>!o.map((t=>t.friendlyName)).includes(t.name))),r=s.length>0,a=e.iconFA("exclamation-triangle",null);a.classList.remove("grok-icon");const l=()=>{const t=e.iconFA("times");return t.style.marginRight="6px",t.classList.remove("grok-icon"),t},u=e.div(e.divV([e.label("You should be a member of the following group(s):",{style:{marginLeft:"0px"}}),...s.map((t=>e.divV([e.span([l(),t.name],{style:{"font-weight":600}}),...t.help?[e.span([t.help],{style:{marginLeft:"16px"}})]:[],e.link("Request group membership",io(t.name),void 0,{style:{marginLeft:"16px"}})])))],{style:{gap:"10px"}})),c=e.span([this.renderIcon(n),e.label(n.friendlyName)]);var d;i.onclick=()=>{t.shell.windows.help.visible&&oo.openHelp(n)},r?c.classList.add("d4-disabled"):i.ondblclick=()=>{oo.openModel(n)},r&&(function(t){t.popover="auto",t.style.cursor="default",t.style.padding="10px",t.style.background="#fdffe5",t.style.border="1px solid #E4E6CE",t.style.borderRadius="2px",t.style.boxShadow="0 0 5px #E4E6CE",t.style.maxWidth="500px",t.style.color="var(--gray-6)"}(d=u),document.body.append(d),i.addEventListener("click",(()=>{!function(t,e){!function(t,e){const n=t.getBoundingClientRect().toJSON();e.style.inset="unset",e.style.top=n.y+"px",e.style.left=n.x+20+"px"}(t,e),e.showPopover()}(a,u)}))),i.append(c),r&&i.append(e.span([a]))})))),i}renderIcon(t){if(null!=t.options.icon&&(t.options.icon.startsWith("http://")||t.options.icon.startsWith("https://")))return e.iconImage("model-icon",t.options.icon);if(t instanceof o.Script)return this.getLanguageIcon(t.language);let n=(t=o.Func.find({package:t.package.name,name:t.name})[0]).package.getIconUrl();if(null!=t.options.icon){const e=n.split("/");e.pop(),e.push(t.options.icon),n=e.join("/")}return e.iconImage(t.package.name,n)}renderPreview(e){const n=Object.create(null,{renderPreview:{get:()=>super.renderPreview}});return no(this,void 0,void 0,(function*(){var i;const s=null!==(i=e.options.editor)&&void 0!==i?i:"Compute:RichFunctionViewEditor",r=yield t.functions.find(s);if(null!==r&&r instanceof o.Func){const t=r.prepare({call:e.prepare()});yield t.call(!1,void 0,{processed:!0});const n=t.getOutputParamValue();if(n instanceof o.View)return n}return n.renderPreview.call(this,e)}))}renderProperties(t){const n=e.accordion("ComputeModel");n.context=t;const i=e.div([e.span([this.renderIcon(t),e.label(t.friendlyName),e.contextActions(t),e.star(t.id)])]);return n.addTitle(i),null!=t.description&&i.appendChild(e.div([e.markdown(t.description)],"model-catalog-description")),i.appendChild(e.tags(t)),null!=t.options["dev.status"]&&i.appendChild(e.tableFromMap({Status:t.options["dev.status"]})),n.end(),n.root}renderTooltip(t){const n=e.span([this.renderIcon(t),e.label(t.friendlyName)]);return n.classList.add("d4-link-label"),e.bind(t,e.divV([e.h2(n),e.divV([e.divText(t.description,"ui-description")],{style:{lineHeight:"150%"}})]))}renderCard(t){const n=this.renderMarkup(t);return n.classList.add("d4-link-label"),e.bind(t,e.h2(n))}init(){this.registerParamFunc("Help",(t=>{oo.openHelp(o.toJs(t))})),setTimeout((()=>no(this,void 0,void 0,(function*(){const t=yield(yield fetch(`${window.location.origin}/api/groups/all_parents`)).json();this.userGroups.next(t)}))))}awaitUserGroups(){return no(this,void 0,void 0,(function*(){return this.userGroups.pipe((0,s.filter)((t=>!!t)),(0,s.map)((t=>t)),(0,s.take)(1)).toPromise()}))}}var so=n(847),ro={};ro.styleTagTransform=It(),ro.setAttributes=bt(),ro.insert=gt().bind(null,"head"),ro.domAPI=mt(),ro.insertStyleElement=At(),ht()(so.A,ro),so.A&&so.A.locals&&so.A.locals;class ao extends o.CustomCardView{static findOrCreateCatalogView(t,e,n){var i;return null!==(i=this.findModelCatalogView(e))&&void 0!==i?i:this.createModelCatalogView(t,e,n)}static createModelCatalogView(t,e,n){const i=o.Func.find({package:n.name,name:e})[0].prepare(),s=new this(t,e);return s.parentCall=i,s}static findModelCatalogView(e){return f()(t.shell.views).find((t=>{var n;return(null===(n=t.parentCall)||void 0===n?void 0:n.func.name)==e}))}bindModel(t){var e;t.aux.showOnTaskBar=!1;const n=this.parentCall;null!=n&&(n.aux.view=null!==(e=ao.findModelCatalogView(this.funcName))&&void 0!==e?e:this,t.parentCall=n)}constructor(e,n){if(super({dataSource:t.dapi.functions,permanentFilter:"#model"}),this.funcName=n,this.isHelpOpen=!1,this.root.classList.add("model-catalog-view"),this.meta=new oo,this.name=e,this.permanentFilter="#model",this.renderMode=o.RENDER_MODE.BRIEF,this.objectType="Func",this.categoryFilters={"options.department":"Department","options.HL_process":"HL_process","options.process":"Process",tag:"Tags"},this.filters={All:"",Favorites:"starredBy = @current","Used by me":"usedBy = @current"},this.hierarchy=["options.department","options.HL_process","options.process"],this.hierarchyProperties={"options.department":"Department","options.HL_process":"HL_process","options.process":"Process"},this.showTree=!0,this.initRibbon(),this.initMenu(),t.shell.windows.showProperties=!1,t.shell.windows.showHelp=this.isHelpOpen,!ao.findModelCatalogView(this.funcName)){const e=t.functions.onBeforeRunAction.subscribe((t=>{var e,n;t.func.hasTag("model")?this.bindModel(t):(null===(n=null===(e=t.inputs)||void 0===e?void 0:e.call)||void 0===n?void 0:n.func)instanceof o.Func&&t.inputs.call.func.hasTag("model")&&this.bindModel(t.inputs.call)})),n=t.events.onCurrentViewChanged.subscribe((()=>{return e=this,n=void 0,o=function*(){t.shell.v===this&&(t.shell.windows.showHelp=this.isHelpOpen)},new((i=void 0)||(i=Promise))((function(t,s){function r(t){try{l(o.next(t))}catch(t){s(t)}}function a(t){try{l(o.throw(t))}catch(t){s(t)}}function l(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i((function(t){t(n)}))).then(r,a)}l((o=o.apply(e,n||[])).next())}));var e,n,i,o}));this.subs.push(e,n)}}initRibbon(){}initMenu(){this.ribbonMenu.group("Help").item("Compute Engine",(()=>window.open("https://github.com/datagrok-ai/public/tree/master/packages/Compute","_blank"))).item("Developing Models",(()=>window.open("https://datagrok.ai/help/compute/scripting","_blank"))).endGroup()}}var lo=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};let uo=!1;const co=new o.Package;function po(t){oo.openModelFromFunccall(t)}function ho(){return new u}function fo(t){return Oi.fromFuncCall(t,{historyEnabled:!0,isTabbed:!1})}function mo(t){return Oi.fromFuncCall(t,{historyEnabled:!1,isTabbed:!0})}function vo(n){return lo(this,void 0,void 0,(function*(){let i={};n.inputs.forEach((t=>i[t.name]=null));let s=`\ncurl --location --request POST '${t.settings.apiUrl}/v1/func/${n.nqName}/run' \\\n--header 'Authorization: ${go("auth")}' \\\n--header 'Content-Type: application/json' \\\n--data-raw '${JSON.stringify(i)}'`,r=`\nvar myHeaders = new Headers();\nmyHeaders.append("Authorization", "${go("auth")}");\nmyHeaders.append("Content-Type", "application/json");\n\nvar raw = JSON.stringify(${JSON.stringify(i)});\n\nvar requestOptions = {\n method: 'POST',\n headers: myHeaders,\n body: raw,\n redirect: 'follow'\n};\n\nfetch("${t.settings.apiUrl}/v1/func/${n.nqName}/run", requestOptions)\n .then(response => response.text())\n .then(result => console.log(result))\n .catch(error => console.log('error', error));`,a=e.tabControl({CURL:e.div([e.divText(s)]),JS:e.div([e.divText(r)])});return o.Widget.fromRoot(a.root)}))}function go(t){let e=document.cookie.match(new RegExp("(?:^|; )"+t.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,"\\$1")+"=([^;]*)"));return e?decodeURIComponent(e[1]):void 0}function yo(t){return lo(this,void 0,void 0,(function*(){return yield new Promise((t=>setTimeout(t,1e3))),[yield t.prepare({ambTemp:22,initTemp:100,desiredTemp:30,area:.06,heatCap:4200,heatTransferCoeff:8.3,simTime:21600}).call()]}))}function bo(n){return lo(this,void 0,void 0,(function*(){const i=(yield t.functions.eval("Compute:CustomDataUploader")).prepare({func:n.func}),r=e.bigButton("Click me to get mock calls",(()=>i.call())),a=o.Widget.fromRoot(e.panel([e.divV([e.label("This part of dialog comes from my custom data uploader"),e.divH([r],{style:{"justify-content":"center"}})])])),l=t.functions.onBeforeRunAction.pipe((0,s.filter)((t=>t.id===i.id))).subscribe((()=>{e.setUpdateIndicator(r,!0)})),u=t.functions.onAfterRunAction.pipe((0,s.filter)((t=>t.id===i.id))).subscribe((()=>{e.setUpdateIndicator(r,!1)}));return a.subs.push(l,u),{uploadWidget:a,uploadFuncCall:i}}))}function wo(t){t.defaultView.scatterPlot({xColumnName:"Initial temperature",yColumnName:"Time to cool"})}function Ao(){uo||(o.ObjectHandler.list().find((t=>"Model"===t.type))||o.ObjectHandler.register(new oo),t.events.onAccordionConstructed.subscribe((t=>{const n=t.context;null!=n&&"script"==n.type&&(t.getPane("REST")||t.addPane("REST",(()=>e.wait((()=>lo(this,void 0,void 0,(function*(){return(yield vo(n)).root})))))))})),uo=!0)}let Co=!1;function Io(){const e=t.shell.startUri.indexOf("?"),n=t.shell.startUri.substring(8,e>0?e:void 0).split("/");if(!Co&&n.includes("Compute")){const e=ao.findOrCreateCatalogView("Model Catalog","modelCatalog",co);return t.shell.addView(e),Co=!0,void(n.length>3&&t.dapi.functions.filter(`shortName = "${n[3]}" and #model`).list().then((t=>{1==t.length&&oo.openModel(t[0])})))}const i=window.location.href.indexOf("?"),o=window.location.href.substring(8,i>0?i:void 0).split("/");if(o.includes("browse")){const e=ao.findModelCatalogView("modelCatalog");return e&&(t.shell.v=e),ao.createModelCatalogView("Model Catalog","modelCatalog",co)}if(o.includes("apps")){const e=ao.findModelCatalogView("modelCatalog");if(e)t.shell.v=e;else{const e=ao.createModelCatalogView("Model Catalog","modelCatalog",co);t.shell.addView(e)}}}function So(t){const{reasonableMin:e,reasonableMax:n}=t;return t=>U({warnings:t<e||t>n?[`Minimum reasonable time is ${e}. Maximum reasonable time is ${n}`]:void 0,errors:t<0?["Time should be strictly positive"]:void 0})}function To(t){return(t,e)=>{const n=e.funcCall.inputs.ambTemp,i=e.funcCall.inputs.initTemp;return U({errors:[...t<n?[j(`Desired temperature cannot be less than ambient temperature (${n}). \n`,[{actionName:"Set desired equal to ambient",action:()=>e.funcCall.inputs.desiredTemp=n}])]:[],...t>i?[`Desired temperature cannot be higher than initial temperature (${i})`]:[]]})}}function Eo(t){return(t,e)=>{const n=e.funcCall.inputs.ambTemp;return U({errors:[...t<n?[`Initial temperature cannot be less than ambient temperature (${n}).`]:[]]})}}function xo(t){return(t,e)=>{const n=e.funcCall.inputs.initTemp;return U({errors:[...t>n?[`Ambient temperature cannot be higher than initial temperature (${n})`]:[]]})}}function Ro(t){return(t,e)=>U({errors:[...t<=0?["Heat capacity must be greater than zero."]:[]],notifications:[j("Heat capacity is only dependent on the object material.",[{actionName:"Google it",action:()=>{window.open("http://google.com")}}])]})}function Oo(t){const n=e.input.string("Custom input",{value:""});return n.root.style.backgroundColor="aqua",n.input.style.backgroundColor="aqua",n}function Po(t){return ee.historyInputJSON("Previous run","ObjectCooling")}const ko=be,Fo=class extends Ee{},Lo=Oi,No=En,Bo=class{static compose(t,e){const n={};for(const t of e){const{id:e}=t;n[e]=Li(t)}return Object.assign(Object.assign({},t),{nestedPipelines:n})}constructor(t){this.pipelineState=new Zi,this.ioInfo=new Map,this.nodes=new Map,this.links=new Map,this.nestedPipelineConfig=new Map,this.hooks=[],this.steps=[],this.isInit=!1,t&&this.setConfig(t)}setConfig(t){if(this.config)throw new Error("Pipeline already has config");if(this.config=Li(t),this.id=this.config.id,this.nqName&&this.nqName!==this.config.nqName)throw new Error(`Config different wrapper nqName ${this.config.nqName}, already set to ${this.nqName}`);this.nqName=this.config.nqName,this.exportConfig=this.config.exportConfig}makePipelineView(t=this.nqName){if(this.viewInst)throw new Error(`View has been already created for pipeline ${t}`);if(!t)throw new Error("No nqName for pipeline");if(this.nqName&&this.nqName!==t)throw new Error(`View different wrapper nqName ${t}, already set to ${this.nqName}`);return this.viewInst=new Qi(t),this.nqName=t,this.viewInst}init(){return eo(this,void 0,void 0,(function*(){if(this.isInit)throw new Error(`Double init for pipeline ${this.nqName} ${this.id}`);if(this.isInit=!0,!this.viewInst)throw new Error(`No view for pipeline ${this.nqName} ${this.id}`);yield this.loadFuncCallsIO(),this.addScriptStatesToConfig(),this.processConfig(),this.addSystemHooks(),this.rt=new Ki(this.nodes,this.links,this.viewInst,this.pipelineState),this.viewInst.injectConfiguration(this.steps,this.hooks,this.rt,this.exportConfig),this.isInit=!0,yield this.viewInst.init()}))}loadFuncCallsIO(){return eo(this,void 0,void 0,(function*(){const t=yield this.gatherIONqNames();for(const e of t){const t=yield this.getFuncIOSpec(e);this.ioInfo.set(e,t)}}))}addSystemHooks(){var t,n;const i=new Map,o=new Map,r=this.viewInst.customViews,a=new Map;for(const e of this.nodes.values())if("popup"===e.type||"action"===e.type){if("popup"===e.type){const t=e.conf;o.set(t.id,t.nqName)}const s=e.conf;if("none"===s.position)continue;const r=_i(e.conf.id);if("buttons"===s.position){const n=null!==(t=i.get(r))&&void 0!==t?t:[];n.push(e),i.set(r,n)}if("menu"===s.position){const t=this.nestedPipelineConfig.get(Bi(e.pipelinePath)),i=null!==(n=null==t?void 0:t.friendlyPrefix)&&void 0!==n?n:"",o=s.friendlyName,r=i?`${i}: ${o}`:o;a.set(r,e)}}const l=[{id:"_SystemViewsAdd_",handler:()=>eo(this,void 0,void 0,(function*(){for(const[t,e]of o.entries()){const n=new to(e,{historyEnabled:!1,isTabbed:!0});yield n.isReady.pipe((0,s.filter)((t=>t)),(0,s.take)(1)).toPromise(),n.root.style.width="100%",n.root.style.height="100%",n.root.style.overflow="hidden",r.set(t,n)}}))}],u=[{id:"_SystemButtonsAdd_",handler:t=>eo(this,[t],void 0,(function*({controller:t}){for(const[n,o]of i.entries()){const i=o.map((t=>{const n=t.conf,i=this.rt.getAction(Mi(n.id));return e.button(i.actionName,i.action)}));t.getView(Mi(n)).setAdditionalButtons(i)}}))},{id:"_SystemMenuAdd_",handler:()=>eo(this,void 0,void 0,(function*(){for(const[t,e]of a){const n=e.conf,i=this.rt.getAction(Mi(n.id));this.viewInst.addMenuItem(t,i.action)}}))}],c={beforeInit:l,onViewReady:u};this.hooks.unshift({pipelinePath:[],hooks:c})}processConfig(){if(!this.config)throw new Error("No pipeline config");const{toRemove:t,toAdd:e,nestedPipelineConfig:n}=ji(this.config,((t,e,n)=>(Fi(e)&&this.processMergeConfig(e,n,t.toRemove,t.toAdd,t.nestedPipelineConfig),t)),{toRemove:new Set,toAdd:new Map,nestedPipelineConfig:new Map});this.nestedPipelineConfig=n,this.hooks=ji(this.config,((e,n,i)=>{const o=this.getPipelineHooks(n,t,i);return e.unshift({hooks:o,pipelinePath:Ni(i,[n.id])}),e}),[]),ji(this.config,((n,i,o)=>(this.processPipelineConfig(i,o,t,e),n)),void 0);const{pipelineSteps:i,pipelineSeq:o}=ji(this.config,((t,e)=>{const n=e.id,i=e.steps.map((t=>({id:t.id,funcName:t.nqName,friendlyName:t.friendlyName,helpUrl:t.helpUrl})));return t.pipelineSteps.set(n,i),t.pipelineSeq.unshift(n),t}),{pipelineSteps:new Map,pipelineSeq:[]});this.steps=o.reduce(((t,e)=>{var o,s;const r=i.get(e),a=null===(o=n.get(e))||void 0===o?void 0:o.insertBeforeStep,l=null===(s=n.get(e))||void 0===s?void 0:s.friendlyPrefix;if(a){const e=t.findIndex((t=>t.id===a));if(e>0){const n=l?r.map((t=>Object.assign(Object.assign({},t),{friendlyName:`${l}: ${t.friendlyName}`}))):r;t.splice(e,0,...n)}return t}return[...t,...null!=r?r:[]]}),[])}getPipelineHooks(t,e,n){var i,o;t.hooks=null!==(i=t.hooks)&&void 0!==i?i:{};for(const[i,s]of Object.entries(null!==(o=t.hooks)&&void 0!==o?o:{})){const o=[];for(const i of null!=s?s:[]){const s=Bi(this.updateFullPathLink(i,Ni(n,[t.id])));e.has(s)||o.push(i)}t.hooks[i]=o}return t.hooks}processPipelineConfig(t,e,n,i){var o,s,r,a,l;const u=this.proccessPipelineNodeConfig(t,e),c=[];for(const e of t.steps){const t=this.processNodeConfig(e,u,u,new Set,"step");if(!t)continue;const a=t.id,l=[];for(const e of this.getAllItems(null!==(o=t.popups)&&void 0!==o?o:[],a,i,"popup")){const t=this.processNodeConfig(e,Mi(a),u,n,"popup");if(!t)continue;const o=[];for(const r of this.getAllItems(null!==(s=e.actions)&&void 0!==s?s:[],t.id,i,"action")){const e=this.processActionNodeConfig(r,Mi(t.id),u,n);e&&o.push(e)}e.actions=o,l.push(e)}const d=[];for(const e of this.getAllItems(null!==(r=t.actions)&&void 0!==r?r:[],a,i,"action")){const t=this.processActionNodeConfig(e,Mi(a),u,n);t&&d.push(t)}t.popups=l,t.actions=d,c.push(t)}const d=[];for(const e of null!==(a=t.links)&&void 0!==a?a:[]){const t=this.processLinkConfig(e,u,n);t&&d.push(t)}const p=[];for(const e of this.getAllItems(null!==(l=t.actions)&&void 0!==l?l:[],t.id,i,"action")){const t=this.processActionNodeConfig(e,u,u,n);t&&p.push(t)}t.steps=c,t.links=d,t.actions=p}getAllItems(t,e,n,i){var o,s;return[...t,...null!==(s=null===(o=n.get(e))||void 0===o?void 0:o[i])&&void 0!==s?s:[]]}proccessPipelineNodeConfig(t,e){const n=this.updateFullPathNode(t,e),i=Bi(n);return this.nodes.set(i,new Wi(t,"pipeline",e,this.pipelineState)),n}processActionNodeConfig(t,e,n,i){this.updateFullPathLink(t,n,!1);const o=Bi(this.updateFullPathNode(t,e));if(!i.has(o))return this.nodes.set(o,new Wi(t,"action",n,this.pipelineState)),t}processNodeConfig(t,e,n,i,o){const s=Bi(this.updateFullPathNode(t,e));if(!i.has(s))return this.nodes.set(s,new Wi(t,o,n,this.pipelineState)),t}processLinkConfig(t,e,n){const i=Bi(this.updateFullPathLink(t,e));if(!n.has(i))return this.links.set(i,new Gi(t,e,this.pipelineState)),t}updateFullPathLink(t,e,n=!0){return t.from&&(Array.isArray(t.from[0])?t.from=t.from.map((t=>[...e,...t])):t.from=[...e,...t.from]),t.to&&(Array.isArray(t.to[0])?t.to=t.to.map((t=>[...e,...t])):t.to=[...e,...t.to]),n?this.updateFullPathNode(t,e):[t.id]}updateFullPathNode(t,e){const n=Ni(e,[t.id]);return t.id=Bi(n),n}processMergeConfig(t,e,n,i,o){var s,r;const a=Ni(e,[t.id]);for(const e of null!==(s=t.itemsToRemove)&&void 0!==s?s:[]){const t=Bi(Ni(a,e));n.add(t)}delete t.itemsToRemove;for(const[e,n]of Object.entries(null!==(r=t.nestedPipelinesConfig)&&void 0!==r?r:{})){const t=Bi(Ni(a,[e]));if(n.insertBeforeStep){const e=Bi(Ni(a,[n.insertBeforeStep]));o.set(t,Object.assign(Object.assign({},n),{insertBeforeStep:e}))}else o.set(t,Object.assign({},n))}delete t.nestedPipelinesConfig;const{popupsToAdd:l,actionsToAdd:u}=t;this.processMergeNodeList(null!=l?l:[],a,i,"popup"),this.processMergeNodeList(null!=u?u:[],a,i,"action"),delete t.popupsToAdd,delete t.actionsToAdd}processMergeNodeList(t,e,n,i){var o,s;for(const[r,a]of t){const t=Bi(Ni(e,null!=a?a:[])),l=null!==(o=n.get(t))&&void 0!==o?o:{},u=null!==(s=l[i])&&void 0!==s?s:[];u.unshift(r),l[i]=u,n.set(t,l)}}addScriptStatesToConfig(){if(!this.config)throw new Error("No pipeline config");ji(this.config,((t,e)=>{var n,i;for(const t of e.steps){this.addNodeIOInfo(t);for(const e of null!==(n=t.popups)&&void 0!==n?n:[])this.addNodeIOInfo(e)}if(Fi(e))for(const[t]of null!==(i=e.popupsToAdd)&&void 0!==i?i:[])this.addNodeIOInfo(t);return t}),void 0)}addNodeIOInfo(t){var e;const n=null!==(e=Li(this.ioInfo.get(t.nqName)))&&void 0!==e?e:[];t.states?t.states.push(...n):t.states=n}getFuncIOSpec(e){return eo(this,void 0,void 0,(function*(){const n=yield t.functions.eval(e);return[...n.inputs.map((t=>({id:t.name,type:t.propertyType,stateType:"input"}))),...n.outputs.map((t=>({id:t.name,type:t.propertyType,stateType:"output"})))]}))}gatherIONqNames(){return eo(this,void 0,void 0,(function*(){if(!this.config)throw new Error("No pipeline config");const t=new Set;return ji(this.config,((e,n)=>{var i,o;for(const e of n.steps){t.add(e.nqName);for(const n of null!==(i=e.popups)&&void 0!==i?i:[])t.add(n.nqName)}if(Fi(n))for(const[e]of null!==(o=n.popupsToAdd)&&void 0!==o?o:[])t.add(e.nqName);return e}),t),t}))}},Mo=U,_o=j,Do=function(t,e,n){return Object.assign({revalidate:t,context:e},n)},Vo=Y,jo=ee.fileInput,$o=ee.historyInput,Ho=ee.historyInputJSON,Uo=ee.historyPanel})(),compute=i})();
1
+ var compute;(()=>{var t={933:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".pipeline-view .d4-ribbon-name.selected {\n color: var(--grey-6)\n}\n\n.pipeline-view .d4-ribbon-name {\n color: var(--blue-1);\n margin: 12px 6px;\n font-weight: normal;\n place-content: center;\n}\n\n.pipeline-view .d4-ribbon-name + .d4-ribbon-name::before {\n color: var(--grey-3);\n}\n\n.pipeline-view .d4-ribbon-name.d4-disabled {\n cursor: default;\n pointer-events: none;\n color: var(--grey-3);\n}\n\n.ui-input-editor button.ui-btn-nav.ui-btn.d4-disabled {\n color: var(--grey-3)\n}","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/function-views/css/pipeline-view.css"],names:[],mappings:"AAAA;EACE;AACF;;AAEA;EACE,oBAAoB;EACpB,gBAAgB;EAChB,mBAAmB;EACnB,qBAAqB;AACvB;;AAEA;EACE,oBAAoB;AACtB;;AAEA;EACE,eAAe;EACf,oBAAoB;EACpB,oBAAoB;AACtB;;AAEA;EACE;AACF",sourcesContent:[".pipeline-view .d4-ribbon-name.selected {\n color: var(--grey-6)\n}\n\n.pipeline-view .d4-ribbon-name {\n color: var(--blue-1);\n margin: 12px 6px;\n font-weight: normal;\n place-content: center;\n}\n\n.pipeline-view .d4-ribbon-name + .d4-ribbon-name::before {\n color: var(--grey-3);\n}\n\n.pipeline-view .d4-ribbon-name.d4-disabled {\n cursor: default;\n pointer-events: none;\n color: var(--grey-3);\n}\n\n.ui-input-editor button.ui-btn-nav.ui-btn.d4-disabled {\n color: var(--grey-3)\n}"],sourceRoot:""}]);const a=r},362:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".ui-form .ui-input-buttons.rfv-buttons {\n margin-top: 0px;\n position: sticky;\n}\n\n.ui-form .ui-input-buttons.rfv-buttons .ui-input-editor {\n flex-wrap: wrap;\n}\n\n.ui-input-root.rfv-restricted-input.d4-disabled {\n pointer-events: all;\n cursor: pointer!important;\n}\n\n/* Hide all state icons by default */\n.ui-input-root > .ui-input-options .rfv-icon-lock,\n.ui-input-root > .ui-input-options .rfv-icon-unlock,\n.ui-input-root > .ui-input-options .rfv-icon-undo,\n.ui-input-root > .ui-input-options .rfv-icon-warning {\n display: none;\n}\n\n/* Show warning icon if input is on warning state */\n.ui-input-root.rfv-inconsistent-input > .ui-input-options .rfv-icon-warning {\n display: inherit;\n}\n\n/* Show undo icon if input is on inconstent state and hovered */\n.ui-input-root.rfv-restricted-unlocked-input:hover .rfv-icon-undo, .ui-input-root.rfv-inconsistent-input:hover .rfv-icon-undo {\n display: inherit;\n}\n\n/* Show/hide lock-unlock icons on input hover */\n.ui-input-root.rfv-restricted-input:hover .rfv-icon-lock {\n display: none;\n}\n.ui-input-root.rfv-restricted-input .rfv-icon-lock {\n display: inherit;\n}\n.ui-input-root.rfv-restricted-input .rfv-icon-unlock {\n display: none;\n}\n.ui-input-root.rfv-restricted-input:hover .rfv-icon-unlock {\n display: inherit;\n}\n\n.ui-form-condensed .rfv-buttons > .ui-label {\n margin-right: 0px!important;\n}\n\n.rfv-form .ui-form .rfv-buttons > .ui-input-editor {\n gap: 5px;\n justify-content: flex-end;\n}\n\ndiv.ui-box > div.ui-box.rfv-form > div.ui-div {\n overflow: visible!important;\n}\n\n.rfv-scalar-table {\n border-collapse: collapse;\n margin: 10px;\n}\n\n.rfv-scalar-table td {\n width: max-content;\n white-space: nowrap;\n}\n\n.rfv-scalar-table tr{\n min-height: 30px;\n border-bottom: 1pt solid var(--grey-12);\n}\n\n.rfv-scalar-table tr:nth-child(odd) {\n background-color: var(--grey-1);\n}\n\n.rfv-scalar-table td:last-child {\n width: 100%;\n}","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/function-views/css/rich-function-view.css"],names:[],mappings:"AAAA;IACI,eAAe;IACf,gBAAgB;AACpB;;AAEA;IACI,eAAe;AACnB;;AAEA;IACI,mBAAmB;IACnB,yBAAyB;AAC7B;;AAEA,oCAAoC;AACpC;;;;IAII,aAAa;AACjB;;AAEA,mDAAmD;AACnD;IACI,gBAAgB;AACpB;;AAEA,+DAA+D;AAC/D;IACI,gBAAgB;AACpB;;AAEA,+CAA+C;AAC/C;IACI,aAAa;AACjB;AACA;IACI,gBAAgB;AACpB;AACA;IACI,aAAa;AACjB;AACA;IACI,gBAAgB;AACpB;;AAEA;IACI,2BAA2B;AAC/B;;AAEA;IACI,QAAQ;IACR,yBAAyB;AAC7B;;AAEA;IACI,2BAA2B;AAC/B;;AAEA;IACI,yBAAyB;IACzB,YAAY;AAChB;;AAEA;IACI,kBAAkB;IAClB,mBAAmB;AACvB;;AAEA;IACI,gBAAgB;IAChB,uCAAuC;AAC3C;;AAEA;IACI,+BAA+B;AACnC;;AAEA;IACI,WAAW;AACf",sourcesContent:[".ui-form .ui-input-buttons.rfv-buttons {\n margin-top: 0px;\n position: sticky;\n}\n\n.ui-form .ui-input-buttons.rfv-buttons .ui-input-editor {\n flex-wrap: wrap;\n}\n\n.ui-input-root.rfv-restricted-input.d4-disabled {\n pointer-events: all;\n cursor: pointer!important;\n}\n\n/* Hide all state icons by default */\n.ui-input-root > .ui-input-options .rfv-icon-lock,\n.ui-input-root > .ui-input-options .rfv-icon-unlock,\n.ui-input-root > .ui-input-options .rfv-icon-undo,\n.ui-input-root > .ui-input-options .rfv-icon-warning {\n display: none;\n}\n\n/* Show warning icon if input is on warning state */\n.ui-input-root.rfv-inconsistent-input > .ui-input-options .rfv-icon-warning {\n display: inherit;\n}\n\n/* Show undo icon if input is on inconstent state and hovered */\n.ui-input-root.rfv-restricted-unlocked-input:hover .rfv-icon-undo, .ui-input-root.rfv-inconsistent-input:hover .rfv-icon-undo {\n display: inherit;\n}\n\n/* Show/hide lock-unlock icons on input hover */\n.ui-input-root.rfv-restricted-input:hover .rfv-icon-lock {\n display: none;\n}\n.ui-input-root.rfv-restricted-input .rfv-icon-lock {\n display: inherit;\n}\n.ui-input-root.rfv-restricted-input .rfv-icon-unlock {\n display: none;\n}\n.ui-input-root.rfv-restricted-input:hover .rfv-icon-unlock {\n display: inherit;\n}\n\n.ui-form-condensed .rfv-buttons > .ui-label {\n margin-right: 0px!important;\n}\n\n.rfv-form .ui-form .rfv-buttons > .ui-input-editor {\n gap: 5px;\n justify-content: flex-end;\n}\n\ndiv.ui-box > div.ui-box.rfv-form > div.ui-div {\n overflow: visible!important;\n}\n\n.rfv-scalar-table {\n border-collapse: collapse;\n margin: 10px;\n}\n\n.rfv-scalar-table td {\n width: max-content;\n white-space: nowrap;\n}\n\n.rfv-scalar-table tr{\n min-height: 30px;\n border-bottom: 1pt solid var(--grey-12);\n}\n\n.rfv-scalar-table tr:nth-child(odd) {\n background-color: var(--grey-1);\n}\n\n.rfv-scalar-table td:last-child {\n width: 100%;\n}"],sourceRoot:""}]);const a=r},993:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".ui-form .ui-input-root .sa-switch-input {\n max-width: 50px;\n min-width: 50px;\n}\n\n.ui-form.ui-form-condensed .ui-input-root .sa-switch-input {\n order: -3;\n top: -5px;\n position: relative;\n}\n\n.ui-form.ui-form-condensed .ui-input-root > .sa-switch-input + label.ui-input-label:not(:empty) {\n width: unset;\n}\n\n.ui-form.ui-form-condensed .ui-input-root > .sa-switch-input ~ .ui-input-editor {\n margin-left: 50px;\n}","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/function-views/css/sens-analysis.css"],names:[],mappings:"AAAA;IACI,eAAe;IACf,eAAe;AACnB;;AAEA;IACI,SAAS;IACT,SAAS;IACT,kBAAkB;AACtB;;AAEA;IACI,YAAY;AAChB;;AAEA;IACI,iBAAiB;AACrB",sourcesContent:[".ui-form .ui-input-root .sa-switch-input {\n max-width: 50px;\n min-width: 50px;\n}\n\n.ui-form.ui-form-condensed .ui-input-root .sa-switch-input {\n order: -3;\n top: -5px;\n position: relative;\n}\n\n.ui-form.ui-form-condensed .ui-input-root > .sa-switch-input + label.ui-input-label:not(:empty) {\n width: unset;\n}\n\n.ui-form.ui-form-condensed .ui-input-root > .sa-switch-input ~ .ui-input-editor {\n margin-left: 50px;\n}"],sourceRoot:""}]);const a=r},847:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,'.model-catalog-view .d4-gallery-card.entity-model i.grok-icon {\n height: 64px;\n width: 64px;\n position: initial;\n flex-shrink: 0;\n}\n\n.model-catalog-view .d4-gallery-card.entity-model .d4-link-label i.grok-icon + label {\n margin-left: 6px;\n align-items: center;\n display: inline-flex;\n white-space: normal;\n}\n\n.model-catalog-view .d4-gallery-card.entity-model {\n padding: 0 8px;\n align-items: center;\n display: flex;\n margin: 0;\n height: 94px;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .grok-gallery-grid {\n flex-direction: row!important;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .d4-link-label i.grok-icon {\n width: 32px;\n height: 32px;\n position: initial;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .d4-link-label label {\n margin-left: 8px;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .grok-gallery-grid .d4-link-label {\n min-width: 250px;\n margin-bottom: 9px;\n color: var(--grey-6);\n padding: 10px;\n width: initial;\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-node {\n font-size: 20px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-node {\n font-size: 16px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group .d4-tree-view-node {\n font-size: 14px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-video {\n width: 80%;\n height: 0;\n padding-bottom: 50%;\n margin: 10px 10px 0 0;\n border: 1px solid var(--grey-2);\n position: relative;\n background-size: cover;\n background-repeat: no-repeat;\n}\n\n.model-catalog-video i {\n position: absolute;\n right: 0;\n left: 0;\n bottom: 0;\n top: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n font-weight: 600;\n color: var(--grey-2);\n font-size: 42px;\n}\n\n.model-catalog-video i:hover {\n color: var(--grey-1);\n}\n\n.model-catalog-description {\n padding: 10px 0 0 0;\n}',"",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/model-catalog/css/model-card.css"],names:[],mappings:"AAAA;IACI,YAAY;IACZ,WAAW;IACX,iBAAiB;IACjB,cAAc;AAClB;;AAEA;IACI,gBAAgB;IAChB,mBAAmB;IACnB,oBAAoB;IACpB,mBAAmB;AACvB;;AAEA;IACI,cAAc;IACd,mBAAmB;IACnB,aAAa;IACb,SAAS;IACT,YAAY;AAChB;;AAEA;IACI,6BAA6B;AACjC;;AAEA;IACI,WAAW;IACX,YAAY;IACZ,iBAAiB;AACrB;;AAEA;IACI,gBAAgB;AACpB;;AAEA;IACI,gBAAgB;IAChB,kBAAkB;IAClB,oBAAoB;IACpB,aAAa;IACb,cAAc;AAClB;;AAEA;IACI,eAAe;IACf,cAAc;IACd,oBAAoB;AACxB;;AAEA;IACI,eAAe;IACf,cAAc;IACd,oBAAoB;AACxB;;AAEA;IACI,eAAe;IACf,cAAc;IACd,oBAAoB;AACxB;;AAEA;IACI,UAAU;IACV,SAAS;IACT,mBAAmB;IACnB,qBAAqB;IACrB,+BAA+B;IAC/B,kBAAkB;IAClB,sBAAsB;IACtB,4BAA4B;AAChC;;AAEA;IACI,kBAAkB;IAClB,QAAQ;IACR,OAAO;IACP,SAAS;IACT,MAAM;IACN,aAAa;IACb,mBAAmB;IACnB,uBAAuB;IACvB,gBAAgB;IAChB,oBAAoB;IACpB,eAAe;AACnB;;AAEA;IACI,oBAAoB;AACxB;;AAEA;IACI,mBAAmB;AACvB",sourcesContent:['.model-catalog-view .d4-gallery-card.entity-model i.grok-icon {\n height: 64px;\n width: 64px;\n position: initial;\n flex-shrink: 0;\n}\n\n.model-catalog-view .d4-gallery-card.entity-model .d4-link-label i.grok-icon + label {\n margin-left: 6px;\n align-items: center;\n display: inline-flex;\n white-space: normal;\n}\n\n.model-catalog-view .d4-gallery-card.entity-model {\n padding: 0 8px;\n align-items: center;\n display: flex;\n margin: 0;\n height: 94px;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .grok-gallery-grid {\n flex-direction: row!important;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .d4-link-label i.grok-icon {\n width: 32px;\n height: 32px;\n position: initial;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .d4-link-label label {\n margin-left: 8px;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .grok-gallery-grid .d4-link-label {\n min-width: 250px;\n margin-bottom: 9px;\n color: var(--grey-6);\n padding: 10px;\n width: initial;\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-node {\n font-size: 20px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-node {\n font-size: 16px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group .d4-tree-view-node {\n font-size: 14px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-video {\n width: 80%;\n height: 0;\n padding-bottom: 50%;\n margin: 10px 10px 0 0;\n border: 1px solid var(--grey-2);\n position: relative;\n background-size: cover;\n background-repeat: no-repeat;\n}\n\n.model-catalog-video i {\n position: absolute;\n right: 0;\n left: 0;\n bottom: 0;\n top: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n font-weight: 600;\n color: var(--grey-2);\n font-size: 42px;\n}\n\n.model-catalog-video i:hover {\n color: var(--grey-1);\n}\n\n.model-catalog-description {\n padding: 10px 0 0 0;\n}'],sourceRoot:""}]);const a=r},911:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".fi-drop-area {\n position: relative;\n}\n\n.fi-drop-area .default {\n color: var(--grey-2);\n}\n\n.fi-drop-area .drag-n-dropping {\n background-color: var(--steel-1);\n border: 1px dashed var(--blue-1);\n color: var(--grey-3);\n}\n\n.fi-drop-area .error {\n color: var(--red-3);\n}\n\n.fi-drop-area .success {\n color: var(--grey-6);\n}\n","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/shared-components/css/file-input.css"],names:[],mappings:"AAAA;EACE,kBAAkB;AACpB;;AAEA;EACE,oBAAoB;AACtB;;AAEA;EACE,gCAAgC;EAChC,gCAAgC;EAChC,oBAAoB;AACtB;;AAEA;EACE,mBAAmB;AACrB;;AAEA;EACE,oBAAoB;AACtB",sourcesContent:[".fi-drop-area {\n position: relative;\n}\n\n.fi-drop-area .default {\n color: var(--grey-2);\n}\n\n.fi-drop-area .drag-n-dropping {\n background-color: var(--steel-1);\n border: 1px dashed var(--blue-1);\n color: var(--grey-3);\n}\n\n.fi-drop-area .error {\n color: var(--red-3);\n}\n\n.fi-drop-area .success {\n color: var(--grey-6);\n}\n"],sourceRoot:""}]);const a=r},703:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,"","",{version:3,sources:[],names:[],mappings:"",sourceRoot:""}]);const a=r},565:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".hp-no-elements-label {\n margin: 12px;\n}\n\n.grok-icon.hp-disabled {\n pointer-events: none;\n opacity: 0.6;\n}\n\n.hp-funccall-card-hover-icon {\n display: none;\n}\n\n.hp-funccall-card:hover .hp-funccall-card-hover-icon {\n display: flex;\n margin: 0px 0px 0px 5px;\n}\n\n.hp-funccall-card {\n margin: 2px 1px;\n padding: 5px;\n justify-content: space-between;\n}\n\n.hp-funccall-card .hp-card-content {\n justify-content: space-around;\n margin-left: 5px;\n}\n\n.hp-funccall-card .hp-card-content * {\n margin-bottom: 3px;\n}\n\n.hp-funccall-card .description {\n margin-bottom: 2px;\n color: var(--grey-3);\n}\n\n.hp-funccall-card .date {\n color: var(--grey-3);\n margin-left: 5px;\n}\n","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/shared-components/css/history-panel.css"],names:[],mappings:"AAAA;IACI,YAAY;AAChB;;AAEA;IACI,oBAAoB;IACpB,YAAY;AAChB;;AAEA;IACI,aAAa;AACjB;;AAEA;IACI,aAAa;IACb,uBAAuB;AAC3B;;AAEA;IACI,eAAe;IACf,YAAY;IACZ,8BAA8B;AAClC;;AAEA;IACI,6BAA6B;IAC7B,gBAAgB;AACpB;;AAEA;IACI,kBAAkB;AACtB;;AAEA;IACI,kBAAkB;IAClB,oBAAoB;AACxB;;AAEA;IACI,oBAAoB;IACpB,gBAAgB;AACpB",sourcesContent:[".hp-no-elements-label {\n margin: 12px;\n}\n\n.grok-icon.hp-disabled {\n pointer-events: none;\n opacity: 0.6;\n}\n\n.hp-funccall-card-hover-icon {\n display: none;\n}\n\n.hp-funccall-card:hover .hp-funccall-card-hover-icon {\n display: flex;\n margin: 0px 0px 0px 5px;\n}\n\n.hp-funccall-card {\n margin: 2px 1px;\n padding: 5px;\n justify-content: space-between;\n}\n\n.hp-funccall-card .hp-card-content {\n justify-content: space-around;\n margin-left: 5px;\n}\n\n.hp-funccall-card .hp-card-content * {\n margin-bottom: 3px;\n}\n\n.hp-funccall-card .description {\n margin-bottom: 2px;\n color: var(--grey-3);\n}\n\n.hp-funccall-card .date {\n color: var(--grey-3);\n margin-left: 5px;\n}\n"],sourceRoot:""}]);const a=r},314:t=>{"use strict";t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var n="",i=void 0!==e[5];return e[4]&&(n+="@supports (".concat(e[4],") {")),e[2]&&(n+="@media ".concat(e[2]," {")),i&&(n+="@layer".concat(e[5].length>0?" ".concat(e[5]):""," {")),n+=t(e),i&&(n+="}"),e[2]&&(n+="}"),e[4]&&(n+="}"),n})).join("")},e.i=function(t,n,i,o,s){"string"==typeof t&&(t=[[null,t,void 0]]);var r={};if(i)for(var a=0;a<this.length;a++){var l=this[a][0];null!=l&&(r[l]=!0)}for(var u=0;u<t.length;u++){var c=[].concat(t[u]);i&&r[c[0]]||(void 0!==s&&(void 0===c[5]||(c[1]="@layer".concat(c[5].length>0?" ".concat(c[5]):""," {").concat(c[1],"}")),c[5]=s),n&&(c[2]?(c[1]="@media ".concat(c[2]," {").concat(c[1],"}"),c[2]=n):c[2]=n),o&&(c[4]?(c[1]="@supports (".concat(c[4],") {").concat(c[1],"}"),c[4]=o):c[4]="".concat(o)),e.push(c))}},e}},354:t=>{"use strict";t.exports=function(t){var e=t[1],n=t[3];if(!n)return e;if("function"==typeof btoa){var i=btoa(unescape(encodeURIComponent(JSON.stringify(n)))),o="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(i),s="/*# ".concat(o," */");return[e].concat([s]).join("\n")}return[e].join("\n")}},826:function(t){t.exports=function(){"use strict";var t="minute",e=/[+-]\d\d(?::?\d\d)?/g,n=/([+-]|\d\d)/g;return function(i,o,s){var r=o.prototype;s.utc=function(t){return new o({date:t,utc:!0,args:arguments})},r.utc=function(e){var n=s(this.toDate(),{locale:this.$L,utc:!0});return e?n.add(this.utcOffset(),t):n},r.local=function(){return s(this.toDate(),{locale:this.$L,utc:!1})};var a=r.parse;r.parse=function(t){t.utc&&(this.$u=!0),this.$utils().u(t.$offset)||(this.$offset=t.$offset),a.call(this,t)};var l=r.init;r.init=function(){if(this.$u){var t=this.$d;this.$y=t.getUTCFullYear(),this.$M=t.getUTCMonth(),this.$D=t.getUTCDate(),this.$W=t.getUTCDay(),this.$H=t.getUTCHours(),this.$m=t.getUTCMinutes(),this.$s=t.getUTCSeconds(),this.$ms=t.getUTCMilliseconds()}else l.call(this)};var u=r.utcOffset;r.utcOffset=function(i,o){var s=this.$utils().u;if(s(i))return this.$u?0:s(this.$offset)?u.call(this):this.$offset;if("string"==typeof i&&(i=function(t){void 0===t&&(t="");var i=t.match(e);if(!i)return null;var o=(""+i[0]).match(n)||["-",0,0],s=o[0],r=60*+o[1]+ +o[2];return 0===r?0:"+"===s?r:-r}(i),null===i))return this;var r=Math.abs(i)<=16?60*i:i,a=this;if(o)return a.$offset=r,a.$u=0===i,a;if(0!==i){var l=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(a=this.local().add(r+l,t)).$offset=r,a.$x.$localOffset=l}else a=this.utc();return a};var c=r.format;r.format=function(t){var e=t||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return c.call(this,e)},r.valueOf=function(){var t=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*t},r.isUTC=function(){return!!this.$u},r.toISOString=function(){return this.toDate().toISOString()},r.toString=function(){return this.toDate().toUTCString()};var d=r.toDate;r.toDate=function(t){return"s"===t&&this.$offset?s(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():d.call(this)};var p=r.diff;r.diff=function(t,e,n){if(t&&this.$u===t.$u)return p.call(this,t,e,n);var i=this.local(),o=s(t).local();return p.call(i,o,e,n)}}}()},693:(t,e,n)=>{t=n.nmd(t);var i="__lodash_hash_undefined__",o=9007199254740991,s="[object Arguments]",r="[object Boolean]",a="[object Date]",l="[object Function]",u="[object GeneratorFunction]",c="[object Map]",d="[object Number]",p="[object Object]",h="[object Promise]",f="[object RegExp]",m="[object Set]",v="[object String]",g="[object Symbol]",y="[object WeakMap]",b="[object ArrayBuffer]",w="[object DataView]",A="[object Float32Array]",C="[object Float64Array]",I="[object Int8Array]",S="[object Int16Array]",T="[object Int32Array]",E="[object Uint8Array]",x="[object Uint8ClampedArray]",R="[object Uint16Array]",O="[object Uint32Array]",P=/\w*$/,k=/^\[object .+?Constructor\]$/,F=/^(?:0|[1-9]\d*)$/,N={};N[s]=N["[object Array]"]=N[b]=N[w]=N[r]=N[a]=N[A]=N[C]=N[I]=N[S]=N[T]=N[c]=N[d]=N[p]=N[f]=N[m]=N[v]=N[g]=N[E]=N[x]=N[R]=N[O]=!0,N["[object Error]"]=N[l]=N[y]=!1;var L="object"==typeof n.g&&n.g&&n.g.Object===Object&&n.g,B="object"==typeof self&&self&&self.Object===Object&&self,V=L||B||Function("return this")(),M=e&&!e.nodeType&&e,_=M&&t&&!t.nodeType&&t,D=_&&_.exports===M;function j(t,e){return t.set(e[0],e[1]),t}function $(t,e){return t.add(e),t}function H(t,e,n,i){var o=-1,s=t?t.length:0;for(i&&s&&(n=t[++o]);++o<s;)n=e(n,t[o],o,t);return n}function U(t){var e=!1;if(null!=t&&"function"!=typeof t.toString)try{e=!!(t+"")}catch(t){}return e}function Y(t){var e=-1,n=Array(t.size);return t.forEach((function(t,i){n[++e]=[i,t]})),n}function W(t,e){return function(n){return t(e(n))}}function G(t){var e=-1,n=Array(t.size);return t.forEach((function(t){n[++e]=t})),n}var q,z=Array.prototype,J=Function.prototype,K=Object.prototype,Z=V["__core-js_shared__"],X=(q=/[^.]+$/.exec(Z&&Z.keys&&Z.keys.IE_PROTO||""))?"Symbol(src)_1."+q:"",Q=J.toString,tt=K.hasOwnProperty,et=K.toString,nt=RegExp("^"+Q.call(tt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),it=D?V.Buffer:void 0,ot=V.Symbol,st=V.Uint8Array,rt=W(Object.getPrototypeOf,Object),at=Object.create,lt=K.propertyIsEnumerable,ut=z.splice,ct=Object.getOwnPropertySymbols,dt=it?it.isBuffer:void 0,pt=W(Object.keys,Object),ht=Vt(V,"DataView"),ft=Vt(V,"Map"),mt=Vt(V,"Promise"),vt=Vt(V,"Set"),gt=Vt(V,"WeakMap"),yt=Vt(Object,"create"),bt=$t(ht),wt=$t(ft),At=$t(mt),Ct=$t(vt),It=$t(gt),St=ot?ot.prototype:void 0,Tt=St?St.valueOf:void 0;function Et(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}function xt(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}function Rt(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}function Ot(t){this.__data__=new xt(t)}function Pt(t,e,n){var i=t[e];tt.call(t,e)&&Ht(i,n)&&(void 0!==n||e in t)||(t[e]=n)}function kt(t,e){for(var n=t.length;n--;)if(Ht(t[n][0],e))return n;return-1}function Ft(t,e,n,i,o,h,y){var k;if(i&&(k=h?i(t,o,h,y):i(t)),void 0!==k)return k;if(!qt(t))return t;var F=Ut(t);if(F){if(k=function(t){var e=t.length,n=t.constructor(e);return e&&"string"==typeof t[0]&&tt.call(t,"index")&&(n.index=t.index,n.input=t.input),n}(t),!e)return function(t,e){var n=-1,i=t.length;for(e||(e=Array(i));++n<i;)e[n]=t[n];return e}(t,k)}else{var L=_t(t),B=L==l||L==u;if(Wt(t))return function(t,e){if(e)return t.slice();var n=new t.constructor(t.length);return t.copy(n),n}(t,e);if(L==p||L==s||B&&!h){if(U(t))return h?t:{};if(k=function(t){return"function"!=typeof t.constructor||jt(t)?{}:qt(e=rt(t))?at(e):{};var e}(B?{}:t),!e)return function(t,e){return Lt(t,Mt(t),e)}(t,function(t,e){return t&&Lt(e,zt(e),t)}(k,t))}else{if(!N[L])return h?t:{};k=function(t,e,n,i){var o,s=t.constructor;switch(e){case b:return Nt(t);case r:case a:return new s(+t);case w:return function(t,e){var n=e?Nt(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)}(t,i);case A:case C:case I:case S:case T:case E:case x:case R:case O:return function(t,e){var n=e?Nt(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}(t,i);case c:return function(t,e,n){return H(e?n(Y(t),!0):Y(t),j,new t.constructor)}(t,i,n);case d:case v:return new s(t);case f:return function(t){var e=new t.constructor(t.source,P.exec(t));return e.lastIndex=t.lastIndex,e}(t);case m:return function(t,e,n){return H(e?n(G(t),!0):G(t),$,new t.constructor)}(t,i,n);case g:return o=t,Tt?Object(Tt.call(o)):{}}}(t,L,Ft,e)}}y||(y=new Ot);var V=y.get(t);if(V)return V;if(y.set(t,k),!F)var M=n?function(t){return function(t,e,n){var i=e(t);return Ut(t)?i:function(t,e){for(var n=-1,i=e.length,o=t.length;++n<i;)t[o+n]=e[n];return t}(i,n(t))}(t,zt,Mt)}(t):zt(t);return function(t,e){for(var n=-1,i=t?t.length:0;++n<i&&!1!==e(t[n],n););}(M||t,(function(o,s){M&&(o=t[s=o]),Pt(k,s,Ft(o,e,n,i,s,t,y))})),k}function Nt(t){var e=new t.constructor(t.byteLength);return new st(e).set(new st(t)),e}function Lt(t,e,n,i){n||(n={});for(var o=-1,s=e.length;++o<s;){var r=e[o],a=i?i(n[r],t[r],r,n,t):void 0;Pt(n,r,void 0===a?t[r]:a)}return n}function Bt(t,e){var n,i,o=t.__data__;return("string"==(i=typeof(n=e))||"number"==i||"symbol"==i||"boolean"==i?"__proto__"!==n:null===n)?o["string"==typeof e?"string":"hash"]:o.map}function Vt(t,e){var n=function(t,e){return null==t?void 0:t[e]}(t,e);return function(t){return!(!qt(t)||(e=t,X&&X in e))&&(Gt(t)||U(t)?nt:k).test($t(t));var e}(n)?n:void 0}Et.prototype.clear=function(){this.__data__=yt?yt(null):{}},Et.prototype.delete=function(t){return this.has(t)&&delete this.__data__[t]},Et.prototype.get=function(t){var e=this.__data__;if(yt){var n=e[t];return n===i?void 0:n}return tt.call(e,t)?e[t]:void 0},Et.prototype.has=function(t){var e=this.__data__;return yt?void 0!==e[t]:tt.call(e,t)},Et.prototype.set=function(t,e){return this.__data__[t]=yt&&void 0===e?i:e,this},xt.prototype.clear=function(){this.__data__=[]},xt.prototype.delete=function(t){var e=this.__data__,n=kt(e,t);return!(n<0||(n==e.length-1?e.pop():ut.call(e,n,1),0))},xt.prototype.get=function(t){var e=this.__data__,n=kt(e,t);return n<0?void 0:e[n][1]},xt.prototype.has=function(t){return kt(this.__data__,t)>-1},xt.prototype.set=function(t,e){var n=this.__data__,i=kt(n,t);return i<0?n.push([t,e]):n[i][1]=e,this},Rt.prototype.clear=function(){this.__data__={hash:new Et,map:new(ft||xt),string:new Et}},Rt.prototype.delete=function(t){return Bt(this,t).delete(t)},Rt.prototype.get=function(t){return Bt(this,t).get(t)},Rt.prototype.has=function(t){return Bt(this,t).has(t)},Rt.prototype.set=function(t,e){return Bt(this,t).set(t,e),this},Ot.prototype.clear=function(){this.__data__=new xt},Ot.prototype.delete=function(t){return this.__data__.delete(t)},Ot.prototype.get=function(t){return this.__data__.get(t)},Ot.prototype.has=function(t){return this.__data__.has(t)},Ot.prototype.set=function(t,e){var n=this.__data__;if(n instanceof xt){var i=n.__data__;if(!ft||i.length<199)return i.push([t,e]),this;n=this.__data__=new Rt(i)}return n.set(t,e),this};var Mt=ct?W(ct,Object):function(){return[]},_t=function(t){return et.call(t)};function Dt(t,e){return!!(e=null==e?o:e)&&("number"==typeof t||F.test(t))&&t>-1&&t%1==0&&t<e}function jt(t){var e=t&&t.constructor;return t===("function"==typeof e&&e.prototype||K)}function $t(t){if(null!=t){try{return Q.call(t)}catch(t){}try{return t+""}catch(t){}}return""}function Ht(t,e){return t===e||t!=t&&e!=e}(ht&&_t(new ht(new ArrayBuffer(1)))!=w||ft&&_t(new ft)!=c||mt&&_t(mt.resolve())!=h||vt&&_t(new vt)!=m||gt&&_t(new gt)!=y)&&(_t=function(t){var e=et.call(t),n=e==p?t.constructor:void 0,i=n?$t(n):void 0;if(i)switch(i){case bt:return w;case wt:return c;case At:return h;case Ct:return m;case It:return y}return e});var Ut=Array.isArray;function Yt(t){return null!=t&&function(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=o}(t.length)&&!Gt(t)}var Wt=dt||function(){return!1};function Gt(t){var e=qt(t)?et.call(t):"";return e==l||e==u}function qt(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function zt(t){return Yt(t)?function(t,e){var n=Ut(t)||function(t){return function(t){return function(t){return!!t&&"object"==typeof t}(t)&&Yt(t)}(t)&&tt.call(t,"callee")&&(!lt.call(t,"callee")||et.call(t)==s)}(t)?function(t,e){for(var n=-1,i=Array(t);++n<t;)i[n]=e(n);return i}(t.length,String):[],i=n.length,o=!!i;for(var r in t)!e&&!tt.call(t,r)||o&&("length"==r||Dt(r,i))||n.push(r);return n}(t):function(t){if(!jt(t))return pt(t);var e=[];for(var n in Object(t))tt.call(t,n)&&"constructor"!=n&&e.push(n);return e}(t)}t.exports=function(t,e){return Ft(t,!0,!0,e)}},72:t=>{"use strict";var e=[];function n(t){for(var n=-1,i=0;i<e.length;i++)if(e[i].identifier===t){n=i;break}return n}function i(t,i){for(var s={},r=[],a=0;a<t.length;a++){var l=t[a],u=i.base?l[0]+i.base:l[0],c=s[u]||0,d="".concat(u," ").concat(c);s[u]=c+1;var p=n(d),h={css:l[1],media:l[2],sourceMap:l[3],supports:l[4],layer:l[5]};if(-1!==p)e[p].references++,e[p].updater(h);else{var f=o(h,i);i.byIndex=a,e.splice(a,0,{identifier:d,updater:f,references:1})}r.push(d)}return r}function o(t,e){var n=e.domAPI(e);return n.update(t),function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap&&e.supports===t.supports&&e.layer===t.layer)return;n.update(t=e)}else n.remove()}}t.exports=function(t,o){var s=i(t=t||[],o=o||{});return function(t){t=t||[];for(var r=0;r<s.length;r++){var a=n(s[r]);e[a].references--}for(var l=i(t,o),u=0;u<s.length;u++){var c=n(s[u]);0===e[c].references&&(e[c].updater(),e.splice(c,1))}s=l}}},659:t=>{"use strict";var e={};t.exports=function(t,n){var i=function(t){if(void 0===e[t]){var n=document.querySelector(t);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(t){n=null}e[t]=n}return e[t]}(t);if(!i)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");i.appendChild(n)}},540:t=>{"use strict";t.exports=function(t){var e=document.createElement("style");return t.setAttributes(e,t.attributes),t.insert(e,t.options),e}},56:(t,e,n)=>{"use strict";t.exports=function(t){var e=n.nc;e&&t.setAttribute("nonce",e)}},825:t=>{"use strict";t.exports=function(t){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var e=t.insertStyleElement(t);return{update:function(n){!function(t,e,n){var i="";n.supports&&(i+="@supports (".concat(n.supports,") {")),n.media&&(i+="@media ".concat(n.media," {"));var o=void 0!==n.layer;o&&(i+="@layer".concat(n.layer.length>0?" ".concat(n.layer):""," {")),i+=n.css,o&&(i+="}"),n.media&&(i+="}"),n.supports&&(i+="}");var s=n.sourceMap;s&&"undefined"!=typeof btoa&&(i+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(s))))," */")),e.styleTagTransform(i,t,e.options)}(e,t,n)},remove:function(){!function(t){if(null===t.parentNode)return!1;t.parentNode.removeChild(t)}(e)}}}},113:t=>{"use strict";t.exports=function(t,e){if(e.styleSheet)e.styleSheet.cssText=t;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(t))}}}},e={};function n(i){var o=e[i];if(void 0!==o)return o.exports;var s=e[i]={id:i,loaded:!1,exports:{}};return t[i].call(s.exports,s,s.exports,n),s.loaded=!0,s.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var i in e)n.o(e,i)&&!n.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.nmd=t=>(t.paths=[],t.children||(t.children=[]),t),n.nc=void 0;var i={};(()=>{"use strict";n.r(i),n.d(i,{AmbTempValidator:()=>Ro,CompView:()=>No,CompositionPipeline:()=>Vo,CustomCustomizer:()=>Ao,CustomDataUploader:()=>bo,CustomStringInput:()=>Po,CustomUploader:()=>wo,DesiredTempValidator:()=>Eo,HeatCapValidator:()=>Oo,InitialTempValidator:()=>xo,ObjectCoolingSelector:()=>ko,OutliersSelection:()=>fo,Pipeline:()=>Bo,PipelineStepEditor:()=>vo,RFV:()=>Lo,RichFunctionViewEditor:()=>mo,SimTimeValidator:()=>To,_package:()=>po,fileInput:()=>$o,historyInput:()=>Ho,historyInputJSON:()=>Uo,historyPanel:()=>Yo,init:()=>Co,makeAdvice:()=>_o,makeRevalidation:()=>Do,makeValidationResult:()=>Mo,mergeValidationResults:()=>jo,modelCatalog:()=>So,openModelFromFuncall:()=>ho,renderRestPanel:()=>go,testPipeline:()=>Fo});const t=grok,e=ui,o=DG,s=rxjs.operators,r=$;var a=n.n(r);const l=()=>document.querySelector(".d4-balloon-container");class u extends o.JsViewer{constructor(){super()}onFrameAttached(t){this.render()}onTableAttached(){this.render()}render(){if(!this.dataFrame||this.dataFrame.rowCount<=0)return void(this.root.innerHTML="");const n=this.dataFrame,i="isOutlier",s="Rationale",r="Count",u="isConfirmed";n.columns.byName(i)||n.columns.add(o.Column.fromBitSet(i,o.BitSet.create(n.rowCount,(()=>!1)))),n.columns.byName(s)||n.columns.add(o.Column.fromStrings(s,Array.from({length:n.rowCount},(()=>""))));const c=()=>o.DataFrame.fromColumns([o.Column.fromStrings(s,[]),o.Column.fromInt32Array(r,new Int32Array([])),o.Column.fromStrings("Actions",[]),o.Column.fromBitSet(u,o.BitSet.create(0,(()=>!1)))]),d=o.Viewer.grid(c());d.root.style.width="100%",d.root.style.minWidth="230px",d.columns.setVisible([s,r,"Actions"]),this.root.append(e.divV([e.divV([d.root],{style:{height:"75%"}})],{style:{height:"100%"}}));const p=()=>{var t,e;if(!d.dataFrame)return;null===(t=n.col(i))||void 0===t||t.meta.markers.assign("true",o.MARKER_TYPE.OUTLIER);const r=null===(e=d.dataFrame)||void 0===e?void 0:e.cell(d.dataFrame.rowCount-1,s).value;n.selection.getSelectedIndexes().forEach((t=>{n.col(i).set(t,!0,!1),n.col(s).set(t,r,!1)})),n.selection.setAll(!1),n.fireValuesChanged(),a()(l()).empty()},h=()=>{d.dataFrame&&(d.dataFrame.rows.removeAt(d.dataFrame.rowCount-1),n.selection.setAll(!1),a()(l()).empty())};d.onCellPrepare((t=>{var o,r,a;t.isTableCell&&("Actions"===t.gridColumn.name&&(t.gridColumn.cellType="html",t.style.element=e.divH([...(null===(o=t.grid.dataFrame)||void 0===o?void 0:o.get(u,t.gridRow))?[(a=null===(r=t.grid.dataFrame)||void 0===r?void 0:r.get(s,t.gridRow),e.div(e.icons.delete((()=>{for(let t=0;t<n.rowCount;t++)n.columns.byName(s).get(t)===a&&(n.columns.byName(s).set(t,"",!1),n.columns.byName(i).set(t,!1,!1));n.fireValuesChanged()}),"Remove the outliers group"),{style:{"text-align":"center",margin:"6px"}}))]:[e.div(e.iconFA("check",p,"Confirm the outliers"),{style:{"text-align":"center",margin:"6px"}}),e.div(e.iconFA("times",h,"Cancel the outliers"),{style:{"text-align":"center",margin:"6px"}})]])))})),d.onCellValueEdited.subscribe((t=>{var e,i;if(!d.dataFrame||t.gridColumn.name!==s)return;if(!d.dataFrame.columns.byName(u).get(t.gridRow))return;const o=new Set;for(let t=0;t<(null===(e=d.dataFrame)||void 0===e?void 0:e.rowCount);t++){const e=null===(i=d.dataFrame)||void 0===i?void 0:i.columns.byName(s).get(t);o.add(e)}for(let e=0;e<n.rowCount;e++){const i=n.columns.byName(s).get(e);""==i||o.has(i)||n.columns.byName(s).set(e,t.cell.value)}}));const f=()=>{if(n.columns.byName(s))for(let t=0;t<n.rowCount;t++)n.columns.byName(i).get(t)?""===n.columns.byName(s).get(t)&&n.columns.byName(s).set(t,"Manual",!1):""!==n.columns.byName(s).get(t)&&n.columns.byName(s).set(t,"",!1);const t={};if(n.columns.byName(s))for(let e=0;e<n.rowCount;e++){const i=n.columns.byName(s).get(e),o=t[i];""!=i&&(o?t[i]++:t[i]=1)}d.dataFrame=c(),d.columns.setVisible([s,r,"Actions"]),Object.keys(t).map((e=>{var n;null===(n=d.dataFrame)||void 0===n||n.rows.addNew([e,t[e],"",!0])}))};n.onDataChanged.subscribe(f),n.onSelectionChanged.subscribe((()=>{if(!d.dataFrame||!n.selection.trueCount)return;const i=l();if(i&&!a()(i).is(":empty")||t.shell.info(e.div([e.divText("Confirm selected points as outliers?"),e.divH([e.bigButton("Confirm",p),e.button("Cancel",h)])])),d.dataFrame.columns.byName(u).toList().some((t=>!1===t)))d.dataFrame.set(r,d.dataFrame.rowCount-1,n.selection.trueCount);else{const t=d.dataFrame.rows.addNew(["Manual",n.selection.trueCount,"",!1]);d.dataFrame.currentCell=d.dataFrame.cell(t.idx,s)}})),n.selection.setAll(!1),f()}}const c=rxjs,d=dayjs;var p=n.n(d);const h=wu;var f=n.n(h);const m={barchart:o.VIEWER.BAR_CHART,boxplot:o.VIEWER.BOX_PLOT,calendar:o.VIEWER.CALENDAR,corrplot:o.VIEWER.CORR_PLOT,densityplot:o.VIEWER.DENSITY_PLOT,filters:o.VIEWER.FILTERS,form:o.VIEWER.FORM,globe:o.VIEWER.GLOBE,googlemap:o.VIEWER.GOOGLE_MAP,grid:o.VIEWER.GRID,heatmap:o.VIEWER.HEAT_MAP,histogram:o.VIEWER.HISTOGRAM,linechart:o.VIEWER.LINE_CHART,markup:o.VIEWER.MARKUP,matrixplot:o.VIEWER.MATRIX_PLOT,networkdiagram:o.VIEWER.NETWORK_DIAGRAM,pcplot:o.VIEWER.PC_PLOT,piechart:o.VIEWER.PIE_CHART,scatterplot:o.VIEWER.SCATTER_PLOT,"3dscatterplot":o.VIEWER.SCATTER_PLOT_3D,shapemap:o.VIEWER.SHAPE_MAP,statistics:o.VIEWER.STATISTICS,tileviewer:o.VIEWER.TILE_VIEWER,timelines:o.VIEWER.TIMELINES,treemap:o.VIEWER.TREE_MAP,trellisplot:o.VIEWER.TRELLIS_PLOT,wordcloud:o.VIEWER.WORD_CLOUD},v="JsCardView",g="viewer",y="restrictedValues",b="editState";var w;!function(t){t.INPUT="Input",t.OUTPUT="Output"}(w||(w={}));const A="experimental",C="Run name",I="RunId";var S,T;!function(t){t.HIDDEN="hidden",t.VISIBLE="visible"}(S||(S={})),function(t){t.ENABLED="enabled",t.DISABLED="disabled"}(T||(T={}));const E="ModelStorage",x="Source",R="Is favorite",O="Is complete",P="Delete",k="Author",F="Date",N="Title",L="Desc.",B="Tags";function V(t){return t&&t.root&&t.onInput}function M(t){return(null==t?void 0:t.setValidation)&&V(t)}function _(t){return(null==t?void 0:t.setDisabled)&&(null==t?void 0:t.setRestricted)&&(null==t?void 0:t.setRestrictedUnlocked)&&(null==t?void 0:t.setInconsistent)&&(null==t?void 0:t.setUserInput)&&V(t)}function D(t){var e;return!(null===(e=null==t?void 0:t.errors)||void 0===e?void 0:e.length)&&!(null==t?void 0:t.pending)}function j(t,e){return{description:t,actions:e}}function H(t){if(null==t?void 0:t.errors)return t.errors.map((t=>t.description)).join("; ")}function U(t){var e,n,i;const o=t=>"string"==typeof t?j(t):t;return{errors:null===(e=null==t?void 0:t.errors)||void 0===e?void 0:e.map((t=>o(t))),warnings:null===(n=null==t?void 0:t.warnings)||void 0===n?void 0:n.map((t=>o(t))),notifications:null===(i=null==t?void 0:t.notifications)||void 0===i?void 0:i.map((t=>o(t)))}}function Y(...t){var e,n,i,o,s;const r=[],a=[],l=[],u=[];let c={};for(const d of t)d&&(r.push(...null!==(e=d.errors)&&void 0!==e?e:[]),a.push(...null!==(n=d.warnings)&&void 0!==n?n:[]),l.push(...null!==(i=d.notifications)&&void 0!==i?i:[]),u.push(...null!==(o=d.revalidate)&&void 0!==o?o:[]),c=Object.assign(Object.assign({},c),null!==(s=d.context)&&void 0!==s?s:{}));return{errors:r,warnings:a,notifications:l,revalidate:u,context:c}}function W(t){let n,i;return(null==t?void 0:t.pending)&&(i=e.iconFA("spinner",(()=>{G(t,i,n)}))),(null==t?void 0:t.errors)&&t.errors.length?(i=e.iconFA("exclamation-circle",(()=>{G(t,i,n)})),i.style.color="var(--red-3)"):(null==t?void 0:t.warnings)&&t.warnings.length?(i=e.iconFA("exclamation-circle",(()=>{G(t,i,n)})),i.style.color="var(--orange-2)"):(null==t?void 0:t.notifications)&&t.notifications.length&&(i=e.iconFA("info-circle",(()=>{G(t,i,n)})),i.style.color="var(--blue-1)"),i&&(i.classList.remove("fal"),i.classList.add("far"),n=function(t){const n=e.div([],"d4-tooltip");return function(t){t.popover="auto",t.style.fontStyle="normal",t.style.pointerEvents="all"}(n),t.appendChild(n),n}(i)),[null!=i?i:e.div(),null!=n?n:e.div()]}function G(t,n,i){if(i&&n){for(function(t,e){const n=t.getBoundingClientRect().toJSON();e.style.inset="unset",e.style.top=n.y+"px",e.style.left=n.x+20+"px"}(n,i);i.firstChild&&i.removeChild(i.firstChild););const o=function(t){var n;const i=e.divV([],{style:{gap:"10px"}});for(const o of["errors","warnings","notifications"]){const s=t[o];if(null==s?void 0:s.length)for(const t of s){const s=q(o);s.style.marginRight="4px",i.appendChild(e.divV([e.divH([s,e.span([t.description])]),...(null!==(n=t.actions)&&void 0!==n?n:[]).map((t=>e.link(t.actionName,t.action,void 0,{style:{paddingLeft:"20px"}})))]))}}return i}(t);i.appendChild(o),i.showPopover()}}function q(t){let n;return"errors"===t?(n=e.iconFA("exclamation-circle"),n.style.color="var(--red-3)"):"warnings"===t?(n=e.iconFA("exclamation-circle"),n.style.color="var(--orange-2)"):"notifications"===t&&(n=e.iconFA("info-circle"),n.style.color="var(--blue-1)"),n&&(n.classList.remove("fal"),n.classList.add("far")),n}var z=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const J=e=>z(void 0,void 0,void 0,(function*(){const n=(yield t.functions.eval(e.func.nqName)).prepare([...e.inputs].reduce(((t,[e,n])=>(t[e]=n,t)),{}));return e.options.forEach((t=>n.options[t]=e.options[t])),n})),K=t=>!Z(t)||!t.id,Z=t=>{try{return t.started}catch(t){return null}},X=(e,n)=>{var i,o,s,r,a,l,u;if(n===k)return null!==(o=null===(i=e.author)||void 0===i?void 0:i.friendlyName)&&void 0!==o?o:t.shell.user.friendlyName;const c=null!==(l=null!==(a=null!==(r=null!==(s=e[n])&&void 0!==s?s:e.inputs[n])&&void 0!==r?r:e.outputs[n])&&void 0!==a?a:e.options[n])&&void 0!==l?l:null;return null!==(u=null==c?void 0:c.toString())&&void 0!==u?u:""},Q=t=>t.options.mainParams?JSON.parse(t.options.mainParams):null;function tt(t){const e=t;return e.dart&&o.toJs(e.dart)instanceof o.InputBase}const et=t=>{const e=t.clone();t.options.forEach((n=>e.options[n]=t.options[n]));const n=f()(t.outputParams.values()).filter((e=>e.property.propertyType===o.TYPE.DATA_FRAME&&!!t.outputs[e.name]));for(const i of n)e.outputs[i.name]=t.outputs[i.name].clone();const i=f()(t.inputParams.values()).filter((e=>e.property.propertyType===o.TYPE.DATA_FRAME&&!!t.inputs[e.name]));for(const n of i)e.inputs[n.name]=t.inputs[n.name].clone();return e},nt=t=>{const e=t.options[g];return void 0!==e?{name:t.name,config:JSON.parse(e,((t,e)=>{if("true"===e)return!0;if("false"===e)return!1;if("type"===t)return m[e]||e;if(!t.toLowerCase().includes("color")){const t=Number.parseFloat(e);if(!Number.isNaN(t))return t}return e}))}:{name:t.name,config:[]}},it=(t,e)=>{t.addRow(["Parameter","Value","Units"]).font={bold:!0},e.forEach((e=>{t.addRow([e.caption,e.value,e.units])})),t.getColumn(1).width=1.2*Math.max(...e.map((t=>t.caption.toString().length)),9),t.getColumn(2).width=1.2*Math.max(...e.map((t=>t.value.toString().length)),5),t.getColumn(3).width=1.2*Math.max(...e.map((t=>t.units.toString().length)),5)};let ot=0;const st=(t,e,n,i)=>{const o=t.getColumn(null!=n?n:1).letter,s={name:`ID_${ot.toString()}`,ref:`${o}${null!=i?i:1}`,columns:e.columns.toList().map((t=>({name:t.name,filterButton:!1}))),rows:new Array(e.rowCount).fill(0).map(((t,n)=>[...e.row(n).cells].map((t=>t.value))))};t.addTable(s),t.columns.forEach((t=>{t.width=25,t.alignment={wrapText:!0}})),ot++},rt=(t,e,n,i,...s)=>z(void 0,[t,e,n,i,...s],void 0,(function*(t,e,n,i,s=0){yield o.Utils.loadJsCss(["/js/common/html2canvas.min.js"]);const r=window.html2canvas,a=yield r(n,{logging:!1}),l=a.toDataURL("image/png"),u=t.addImage({base64:l,extension:"png"});e.addImage(u,{tl:{col:i,row:s},ext:{width:a.width,height:a.height}})}));function at(t,e){return z(this,void 0,void 0,(function*(){const n={};for(const[i,o]of Object.entries(t.inputs)){const{property:t}=e.funcCall.inputParams[i];n[i]=yield lt(t,o,e)}return{inputs:n,outputs:t.outputs}}))}function lt(t,e,n){return z(this,void 0,void 0,(function*(){return"file"===t.propertyType&&n.getInput?n.getInput(t.name).value.arrayBuffer():e}))}function ut(t,e){return z(this,void 0,void 0,(function*(){return"file"===t?new File([e],""):e}))}var ct=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const dt=t=>{switch(t){case"Today":return"started > -1d";case"Yesterday":return"started > -2d and started < -1d";case"Any time":return"";case"Last year":return"started > -2y and started < -1y";case"This year":return"started > -1y";case"Last month":return"started > -2m and started < -1m";case"This month":return"started > -1m";case"Last week":return"started > -2w and started < -1w";case"This week":return"started > -1w"}};var pt;!function(e){const n={},i=new o.LruCache;function s(e){return ct(this,arguments,void 0,(function*(e,i=!0){var o;const s=e.func.id,r=t.dapi.functions.include("package").allPackageVersions().find(s),a=i&&null!==(o=n[s])&&void 0!==o?o:yield r;n[s]||(n[s]=a),e.func=a}))}function r(e){return ct(this,arguments,void 0,(function*(e,n=!1){const i=yield t.dapi.functions.calls.allPackageVersions().include("session.user, inputs, outputs").find(e);if(yield s(i),!n){const e=f()(i.outputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!i.outputs[t.name]));yield Promise.all(e.map((e=>ct(this,void 0,void 0,(function*(){return i.outputs[e.name]=yield t.dapi.tables.getTable(i.outputs[e.name]),Promise.resolve()})))));const n=f()(i.inputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!i.inputs[t.name]));yield Promise.all(n.map((e=>ct(this,void 0,void 0,(function*(){return i.inputs[e.name]=yield t.dapi.tables.getTable(i.inputs[e.name]),Promise.resolve()})))))}return i}))}e.augmentCallWithFunc=s,e.loadChildRuns=function(e){return ct(this,void 0,void 0,(function*(){const n=yield r(e);yield s(n);const i=yield t.dapi.functions.calls.allPackageVersions().include("func").filter(`options.parentCallId="${e}"`).list();return yield Promise.all(i.map((t=>ct(this,void 0,void 0,(function*(){return s(t)}))))),{parentRun:n,childRuns:i}}))},e.loadRun=r,e.saveRun=function(e){return ct(this,void 0,void 0,(function*(){let n=i.get("All users");n||(n=yield t.dapi.groups.find(o.Group.defaultGroupsIds["All users"]),i.set("All users",n));const s=et(e);K(s)&&(s.options.createdOn=p()().unix());const r=f()(s.outputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!s.outputs[t.name]));yield Promise.all(r.map((e=>ct(this,void 0,void 0,(function*(){yield t.dapi.tables.uploadDataFrame(s.outputs[e.name]),yield t.dapi.permissions.grant(s.outputs[e.name].getTableInfo(),n,!1)})))));const a=f()(s.inputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!s.inputs[t.name]));return yield Promise.all(a.map((e=>ct(this,void 0,void 0,(function*(){yield t.dapi.tables.uploadDataFrame(s.inputs[e.name]),yield t.dapi.permissions.grant(s.inputs[e.name].getTableInfo(),n,!1)}))))),yield t.dapi.functions.calls.allPackageVersions().save(s)}))},e.deleteRun=function(e){return ct(this,void 0,void 0,(function*(){e.options.isDeleted=!0,yield t.dapi.functions.calls.allPackageVersions().save(e)}))},e.pullRuns=function(e){return ct(this,arguments,void 0,(function*(e,n={},i={}){let o=`func.id="${e}"`;return o+=n.author?` and session.user.id="${n.author.id}"`:"",o+=n.date?dt(n.date):"",t.dapi.functions.calls.allPackageVersions().filter(o).include("session.user, options").list(i)}))},e.pullRunsByName=function(e){return ct(this,arguments,void 0,(function*(e,n=[],i={},r=[],a=!1){let l="";for(const t of n){const e=[];t.author&&e.push(`session.user.id="${t.author.id}"`),t.date&&e.push(dt(t.date)),t.text&&e.push(`((options.title like "${t.text}") or (options.annotation like "${t.text}"))`),t.includeDeleted||e.push('((options.isDeleted != "true") or (options.isDeleted = null))');const n=e.join(" and ");""!==n&&(l+=""===l?`(${n})`:` or (${n})`)}""!==l&&(l=` and (${l})`);const u=yield t.dapi.functions.calls.allPackageVersions().filter(`func.name="${e}"${l}`).include(`${r.join(",")}`).list(i);for(const t of u)yield s(t);if((r.includes("inputs")||r.includes("func.params"))&&!a)for(const e of u){const n=f()(e.inputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!e.inputs[t.name]));for(const i of n)e.inputs[i.name]=yield t.dapi.tables.getTable(e.inputs[i.name])}if((r.includes("outputs")||r.includes("func.params"))&&!a)for(const e of u){const n=f()(e.outputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!e.outputs[t.name]));for(const i of n)e.outputs[i.name]=yield t.dapi.tables.getTable(e.outputs[i.name])}return u}))}}(pt||(pt={}));var ht=n(72),ft=n.n(ht),mt=n(825),vt=n.n(mt),gt=n(659),yt=n.n(gt),bt=n(56),wt=n.n(bt),At=n(540),Ct=n.n(At),It=n(113),St=n.n(It),Tt=n(911),Et={};Et.styleTagTransform=St(),Et.setAttributes=wt(),Et.insert=yt().bind(null,"head"),Et.domAPI=vt(),Et.insertStyleElement=Ct(),ft()(Tt.A,Et),Tt.A&&Tt.A.locals&&Tt.A.locals;var xt=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const Rt="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";class Ot extends o.InputBase{get value(){return this.fileValue}set value(t){this.stringValue=(null==t?void 0:t.name)||"Drag-n-drop your file",this.fileValue=t,this.notify&&this.fireInput()}constructor(t="Drag-n-drop here",n=null,i=null,o=Rt){super(e.input.string("Input file",{value:""}).dart),this.initialText=t,this.initialValue=n,this.onValueChanged=i,this.fileType=o,this.uploadedFile$=new c.Subject,this.onFileUploaded=this.uploadedFile$,this.fileValue=null,this.isValid=new c.BehaviorSubject(!0),this.hiddenInput=document.createElement("input"),this.icon=e.iconFA("cloud-upload",(()=>this.hiddenInput.click())),this.subscribeOnEvents(),this.root.style.display="flex",this.isValid.subscribe((t=>{if(t){this.input.classList.remove("error"),this.input.classList.add("success");const t=e.iconFA("times",(()=>this.reset()),"Reset uploaded file");this.icon.replaceWith(t),this.icon=t}else{this.input.classList.remove("success"),this.input.classList.add("error");const t=e.iconFA("redo",(()=>this.hiddenInput.click()),"Re-upload a file");this.icon.replaceWith(t),this.icon=t}})),this.uploadedFile$.subscribe((t=>{if(this.onValueChanged&&this.onValueChanged(t),!t){const t=e.iconFA("cloud-upload",(()=>this.hiddenInput.click()),"Choose a file to upload");this.icon.replaceWith(t),this.icon=t}this.value=t})),this.reset()}subscribeOnEvents(){this.input.readOnly=!0,this.input.classList.add("default");const t=t=>xt(this,void 0,void 0,(function*(){if(t&&t.length&&this.enabled){if(t.length>1)throw this.isValid.next(!1),new Error("Please specify single input file");if(this.fileType&&t[0].type!==this.fileType)throw this.isValid.next(!1),new Error("File type is not supported");this.isValid.value?this.uploadedFile$.next(t[0]):this.uploadedFile$.next(null)}}));this.root.classList.add("fi-drop-area"),this.root.style.width="100%",this.hiddenInput.type="file",this.hiddenInput.addEventListener("change",(()=>xt(this,void 0,void 0,(function*(){return yield t(this.hiddenInput.files)}))),!1),["dragenter","dragover","dragleave","drop"].forEach((t=>{this.input.addEventListener(t,(t=>{t.preventDefault(),t.stopPropagation()}),!1)})),["dragenter","dragover"].forEach((t=>{this.input.addEventListener(t,(()=>{this.input.classList.add("drag-n-dropping")}),!1)})),["dragleave","drop"].forEach((t=>{this.input.addEventListener(t,(()=>{this.input.classList.remove("drag-n-dropping")}),!1)})),this.input.addEventListener("drop",(e=>xt(this,void 0,void 0,(function*(){const n=e.dataTransfer.files;t(n)}))),!1),this.input.addEventListener("click",(()=>this.hiddenInput.click()),!1),this.addOptions(this.icon),["drag","dragenter"].forEach((t=>{document.getElementsByClassName("layout-workarea")[0].addEventListener(t,(t=>{t.stopPropagation()}),!1)}))}reset(){this.input.classList.value="ui-input-editor default",this.hiddenInput.value="",this.uploadedFile$.next(null)}}var Pt=n(703),kt={};kt.styleTagTransform=St(),kt.setAttributes=wt(),kt.insert=yt().bind(null,"head"),kt.domAPI=vt(),kt.insertStyleElement=Ct(),ft()(Pt.A,kt),Pt.A&&Pt.A.locals&&Pt.A.locals;var Ft=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};class Nt extends o.Dialog{constructor(n,i){var s,r,a;super(e.dialog({title:"Edit run metadata"}).dart),this._onMetadataEdit=new c.Subject,this.onMetadataEdit=this._onMetadataEdit.asObservable();let l=null!==(s=n.options.title)&&void 0!==s?s:"",u=null!==(r=n.options.description)&&void 0!==r?r:"",d=i;const p=e.input.string("Title",{value:l,onValueChanged:()=>l=p.value}),h=e.input.string(" ",{value:""}),f=o.TagEditor.create();(null!==(a=n.options.tags)&&void 0!==a?a:[]).forEach((t=>{f.addTag(t)})),h.input.replaceWith(f.root);const m=()=>{""===v.value||f.tags.includes(v.value)||(f.addTag(v.value),v.value="")},v=e.input.string("Tag",{value:""}).addOptions(e.iconFA("plus",m,"Add this tag")),g=(0,c.fromEvent)(v.input,"onkeydown").subscribe((t=>{"Enter"==t.key&&(t.stopPropagation(),m())}));this.sub(g);const y=e.input.string("Description",{value:u,onValueChanged:()=>u=y.value}),b=e.input.bool("Favorites",{value:d,onValueChanged:()=>d=b.value});this.add(e.form([p,y,b,v,h])),this.addButton("Save",(()=>Ft(this,void 0,void 0,(function*(){if(""!==v.value)return void t.shell.info(`Dialog has unsaved tags: ${v.value}`);let e="same";d&&!i&&(e="favorited"),!d&&i&&(e="unfavorited");const n={title:""!==l?l:null,description:""!==u?u:null,tags:f.tags.map((t=>t)),favorite:e};this._onMetadataEdit.next(n),this.close()}))))}}class Lt extends o.Dialog{constructor(t){super(e.dialog({title:`Delete ${t.size>1?t.size:""} ${t.size>1?"runs":"run"}`}).dart),this._onFuncCallDelete=new c.Subject,this.onFuncCallDelete=this._onFuncCallDelete.asObservable(),this.add(e.divText(`Deleted ${t.size>1?t.size:""} ${t.size>1?"runs":"run"} ${t.size>1?"are":"is"} impossible to restore. Are you sure?`)),this.onOK((()=>Ft(this,void 0,void 0,(function*(){return this._onFuncCallDelete.next(t)}))))}}var Bt=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const Vt=t=>{var e,n;if(null===(e=t.options)||void 0===e?void 0:e.default)return JSON.parse(null===(n=t.options)||void 0===n?void 0:n.default);const i=t.defaultValue;return t.propertyType===o.TYPE.STRING&&i?i.substring(1,i.length-1):i};function Mt(t,n){n?(a()(t).addClass("ui-box").css({width:"auto",height:"auto"}),e.setUpdateIndicator(t,!0)):(e.setUpdateIndicator(t,!1),a()(t).removeClass("ui-box"))}const _t=t=>{const e=t.clone(),n=f()(t.outputParams.values()).filter((e=>e.property.propertyType===o.TYPE.DATA_FRAME&&!!t.outputs[e.name]));for(const i of n)e.outputs[i.name]=t.outputs[i.name].clone();const i=f()(t.inputParams.values()).filter((e=>e.property.propertyType===o.TYPE.DATA_FRAME&&!!t.inputs[e.name]));for(const n of i)e.inputs[n.name]=t.inputs[n.name].clone();return e},Dt=t=>{const e=t.options[g];return void 0!==e?{name:t.name,config:JSON.parse(e,((t,e)=>{if("true"===e)return!0;if("false"===e)return!1;if("type"===t)return m[e]||e;if(!t.toLowerCase().includes("color")){const t=Number.parseFloat(e);if(!Number.isNaN(t))return t}return e}))}:{name:t.name,config:[]}},jt=t=>{try{return t.started.toDate().toLocaleString("en-us",{month:"short",day:"numeric",hour:"numeric",minute:"numeric"})}catch(t){return"Not completed"}};var $t=n(826),Ht=n.n($t),Ut=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};p().extend(Ht());const Yt=Object.values(o.COLUMN_TYPE).filter((t=>t!==o.TYPE.DATA_FRAME)),Wt=t=>t.replace(/([A-Z])/g,(t=>` ${t.toLowerCase()}`)).trim().replace(/^./,(t=>t.toUpperCase())),Gt=new o.LruCache;class qt extends o.Widget{storageName(t){return`${E}_${[...t.values()][0].func.name}_Fav`}get onRunsDfChanged(){return this._onRunsDfChanged.asObservable()}get onChosen(){return this._onChosen.asObservable()}get chosen(){return this._onChosen.value}set chosen(t){var e;this.chosenById=null!==(e=null==t?void 0:t.id)&&void 0!==e?e:null}set chosenById(t){if(t){for(let e=0;e<this.currentDf.rowCount;e++)if(this.currentDf.getCol(Kt).get(e)===t){this.currentDf.currentRowIdx=e;break}}else this.currentDf.currentRowIdx=-1}get selected(){return this._onSelectedChanged.value}get runs(){return this.onRunsChanged.value}get onSelectedChanged(){return this._onSelectedChanged.asObservable()}saveIsFavorite(e,n){return Ut(this,void 0,void 0,(function*(){const i=`${E}_${e.func.name}_Fav`;return n?t.dapi.userDataStorage.postValue(i,e.id,""):t.dapi.userDataStorage.remove(i,e.id)}))}getRunByIdx(t){return this.runs.get(this.currentDf.get(Kt,t))}showEditDialog(e,n){const i=new Nt(e,n),o=i.onMetadataEdit.subscribe((n=>Ut(this,void 0,void 0,(function*(){var i;if(null===(i=this.options)||void 0===i?void 0:i.isHistory)return("same"!==n.favorite?this.saveIsFavorite(e,"favorited"===n.favorite):Promise.resolve()).then((()=>pt.loadRun(e.id,!1))).then((t=>(n.title&&(t.options.title=n.title),n.description&&(t.options.description=n.description),n.tags&&(t.options.tags=n.tags),[pt.saveRun(t),t]))).then((([,t])=>{this.updateRun(t),this.onMetadataEdit.next(t),o.unsubscribe()})).catch((e=>{t.shell.error(e)}));this.updateRun(e)}))));i.show({center:!0,width:500})}visibleProps(t){var e,n,i;return null!==(i=null!==(n=null===(e=this.options)||void 0===e?void 0:e.visibleProps)&&void 0!==n?n:Q(t))&&void 0!==i?i:t.inputs.filter((t=>Yt.includes(t.propertyType))).map((t=>t.name))}constructor(n,i){var r,l,u,d,h,m,v;super(e.div([],{style:{height:"100%",width:"100%"}})),this.initialRuns=n,this.options=i,this.onRunsChanged=new c.BehaviorSubject(this.initialRuns.reduce(((t,e)=>(t.set(e.id,e),t)),new Map)),this._onRunsDfChanged=new c.BehaviorSubject(o.DataFrame.fromColumns([o.Column.bool(x,0),...(null===(r=this.options)||void 0===r?void 0:r.isHistory)?[o.Column.bool(R,0)]:[],...(null===(l=this.options)||void 0===l?void 0:l.showActions)?[o.Column.string(P,0)]:[],o.Column.bool(O,0),o.Column.dateTime(F,0),o.Column.string(k,0),o.Column.string(B,0),o.Column.string(N,0),o.Column.string(L,0),o.Column.fromStrings(Kt,[])])),this._historyFilters=o.Viewer.filters(this._onRunsDfChanged.value,{title:"Filters",columnNames:[]}),this._historyGrid=o.Viewer.grid(this._onRunsDfChanged.value,{showRowHeader:!1,showColumnGridlines:!1,allowEdit:!1}),this.onComparisonCalled=new c.Subject,this.onMetadataEdit=new c.Subject,this._onChosen=new c.BehaviorSubject(null),this.onDelete=new c.Subject,this._onSelectedChanged=new c.BehaviorSubject(new Set([])),this.layout=e.splitH([],null,!0),this.defaultGridText=e.divText(null!==(d=null===(u=this.options)||void 0===u?void 0:u.fallbackText)&&void 0!==d?d:"No historical runs found","hp-no-elements-label"),this.defaultFiltersText=e.divText("No filters to show","hp-no-elements-label"),this.filterWithText=e.divH([this.defaultFiltersText,this._historyFilters.root],"ui-box"),this.trashIcon=e.div(e.iconFA("trash-alt",(()=>{const n=this.currentDf.selection.getSelectedIndexes(),i=new Set;n.forEach((t=>i.add(this.getRunByIdx(t))));const o=new Lt(i);o.onFuncCallDelete.pipe((0,s.take)(1)).subscribe((n=>Ut(this,void 0,void 0,(function*(){e.setUpdateIndicator(this.root,!0);try{yield Promise.all(f()(n.values()).map((t=>Ut(this,void 0,void 0,(function*(){return yield this.deleteRun(t.id),Promise.resolve()})))))}catch(e){t.shell.error(e)}finally{e.setUpdateIndicator(this.root,!1)}})))),o.show({center:!0,width:500,modal:!0})}),"Delete selected runs"),{style:{"padding-top":"5px"}}),this.compareIcon=e.div(e.iconFA("exchange",(()=>Ut(this,void 0,void 0,(function*(){const t=this.currentDf.selection.getSelectedIndexes(),e=[];t.forEach((t=>{e.push(this.currentDf.getCol(Kt).get(t))})),this.onComparisonCalled.next(e)}))),"Compare selected runs"),{style:{"padding-top":"5px"}}),this._isFilterHidden=new c.BehaviorSubject(!1),this.showFiltersIcon=e.div(e.iconFA("filter",(()=>{this._isFilterHidden.next(!this._isFilterHidden.value)}),"Toggle filters"),{style:{"padding-top":"4px"}}),this._compactMode=new c.BehaviorSubject(null!==(m=null===(h=this.options)||void 0===h?void 0:h.isHistory)&&void 0!==m&&m),this.toggleCompactMode=e.div(e.iconFA("expand-alt",(()=>{this.compactMode=!this.compactMode}),"Toggle compact mode"),{style:{"padding-top":"4px"}}),this.showMetadataIcon=e.input.toggle("Metadata",{value:!0,onValueChanged:()=>{this.styleHistoryGrid(),this.styleHistoryFilters()}}),this.showInputsIcon=e.input.toggle("Params",{value:!1,onValueChanged:()=>Ut(this,void 0,void 0,(function*(){var t;const e=this.showInputsIcon.value;0!==this.runs.size&&(e&&(null===(t=this.options)||void 0===t?void 0:t.isHistory)?((yield Promise.all([...this.runs.values()].map((t=>Ut(this,void 0,void 0,(function*(){if(Gt.has(t.id))return Gt.get(t.id);{const e=yield pt.loadRun(t.id,!0);return Gt.set(e.id,e),e}})))))).forEach((t=>{this.runs.set(t.id,t)})),this.onRunsChanged.next(this.runs)):(this.styleHistoryGrid(),this.styleHistoryFilters()))}))});const g=e.divH([e.divH([...(null==i?void 0:i.isHistory)?[this.toggleCompactMode]:[],this.showFiltersIcon,this.showMetadataIcon.root,this.showInputsIcon.root],{style:{gap:"5px",padding:"5px"}}),e.divH((null===(v=this.options)||void 0===v?void 0:v.showBatchActions)?[this.trashIcon,this.compareIcon]:[],{style:{gap:"5px",padding:"5px"}})],{style:{"justify-content":"space-between",padding:"0px 5px"}});g.style.setProperty("overflow-y","hidden","important");const y=e.divV([this.defaultGridText,g,this._historyGrid.root],"ui-box");a()(y).removeClass("ui-div"),a()(y).css("width","100%"),this.root.appendChild(this.layout),e.setDisplayAll([this._historyGrid.root,this._historyFilters.root,this.toggleCompactMode,this.trashIcon,this.compareIcon,this.showFiltersIcon],!1),this.setGridCellRendering();const b=this.onRunsChanged.subscribe((n=>Ut(this,void 0,void 0,(function*(){var i,s,r;const a=[...n.values()],l=t=>{var e,n;return t.propertyType===o.TYPE.DATE_TIME?o.Column.dateTime(null!==(e=t.caption)&&void 0!==e?e:Wt(t.name),a.length).init((e=>window.grok_DayJs_To_DateTime(a[e].inputs[t.name]))):o.Column.fromType(t.propertyType,null!==(n=t.caption)&&void 0!==n?n:Wt(t.name),a.length).init((e=>{var n,i,o,s;return null!==(s=null===(o=null===(i=null===(n=this.options)||void 0===n?void 0:n.propFuncs)||void 0===i?void 0:i[t.name])||void 0===o?void 0:o.call(i,a[e]))&&void 0!==s?s:X(a[e],t.name)}))},u=t=>t===F?o.Column.dateTime(Wt(t),a.length).init((t=>window.grok_DayJs_To_DateTime(Z(a[t])?a[t].started.utc(!0):p().unix(a[t].options.createdOn)))):t===O?o.Column.bool(Wt(t),a.length).init((t=>Z(a[t]))):o.Column.fromStrings(Wt(t),a.map((e=>{var n,i,o,s;return null!==(s=null===(o=null===(i=null===(n=this.options)||void 0===n?void 0:n.propFuncs)||void 0===i?void 0:i[t])||void 0===o?void 0:o.call(i,e))&&void 0!==s?s:X(e,t)})));if(a.length>0){const c=null!==(i=yield t.dapi.userDataStorage.get(this.storageName(n)))&&void 0!==i?i:{},d=Object.keys(c),p=a[0].func,h=t=>{var e;const n=null!==(e=p.inputs.find((e=>e.name===t)))&&void 0!==e?e:p.outputs.find((e=>e.name===t));return n?l(n):u(t)},f=o.DataFrame.fromColumns([o.Column.string(x,a.length).init((t=>{const e=a[t].options.immutable_tags;return e&&e.includes(A)?"Experimental":"Simulated"})),...(null===(s=this.options)||void 0===s?void 0:s.isHistory)?[o.Column.bool(R,a.length).init((t=>d.includes(a[t].id)))]:[],...(null===(r=this.options)||void 0===r?void 0:r.showActions)?[o.Column.string(P,a.length).init("")]:[],u(F),u(O),u(k),o.Column.string(B,a.length).init((t=>a[t].options.tags?a[t].options.tags.join(","):"")),o.Column.string(N,a.length).init((t=>a[t].options.title)),o.Column.string(L,a.length).init((t=>a[t].options.description))]);this.visibleProps(p).map((t=>h(t))).forEach((t=>{t.name=f.columns.getUnusedName(t.name),f.columns.add(t,!1)})),f.columns.add(o.Column.fromStrings(Kt,a.map((t=>t.id)))),e.setDisplayAll([this.defaultGridText,this.defaultFiltersText],!1),e.setDisplayAll([this._historyGrid.root,this._historyFilters.root,this.toggleCompactMode,this.showMetadataIcon.root,this.trashIcon,this.compareIcon,this.showFiltersIcon],!0),e.setDisplay(this.showInputsIcon.root,this.visibleProps(p).length>0),this._onRunsDfChanged.next(f)}else e.setDisplayAll([this.defaultGridText,this.defaultFiltersText],!0),e.setDisplayAll([this._historyGrid.root,this._historyFilters.root,this.showMetadataIcon.root,this.showInputsIcon.root,this.toggleCompactMode,this.trashIcon,this.compareIcon,this.showFiltersIcon],!1)})))),w=this._onRunsDfChanged.subscribe((t=>{this._historyFilters.dataFrame=t,this._historyGrid.dataFrame=t,this.currentDf.getCol(B).setTag(o.TAGS.MULTI_VALUE_SEPARATOR,","),this.styleHistoryGrid(),this.styleHistoryFilters();const e=t.onCurrentRowChanged.subscribe((()=>{var t;this.currentDf.rows.select((()=>!1)),this._onChosen.next(null!==(t=this.getRunByIdx(this.currentDf.currentRowIdx))&&void 0!==t?t:null)})),n=t.onSelectionChanged.subscribe((()=>{const e=[...t.selection.getSelectedIndexes()].map((t=>this.getRunByIdx(t)));this._onSelectedChanged.next(new Set(e)),this.redrawSelectionState()}));this.redrawSelectionState(),this.subs.push(e,n)})),C=this._isFilterHidden.subscribe((t=>{t?(a()(this.showFiltersIcon.firstChild).addClass("fal"),a()(this.showFiltersIcon.firstChild).removeClass("fad"),e.setDisplay(this.filterWithText,!1)):(a()(this.showFiltersIcon.firstChild).addClass("fad"),a()(this.showFiltersIcon.firstChild).removeClass("fal"),a()(this.filterWithText).css(this.compactMode?"height":"width","320px"),a()(this.filterWithText).css(this.compactMode?"width":"height","100%"),e.setDisplay(this.filterWithText,!0))})),I=this._compactMode.subscribe((t=>{const n=[y,this.filterWithText];a()(this.filterWithText).removeClass("ui-div");const i={style:{width:"100%",height:"100%"}};a()(this.toggleCompactMode.firstChild).addClass(t?"fa-expand-alt":"fa-compress-alt"),a()(this.toggleCompactMode.firstChild).removeClass(t?"fa-compress-alt":"fa-expand-alt");const o=t?e.splitV(n,i,!0):e.splitH(n,i,!0);this.layout.replaceWith(o),this.layout=o,e.tools.waitForElementInDom(this.layout).then((t=>{a()(t).css(this.compactMode?"height":"width","100%"),a()(this._historyFilters.root).css(Object.assign({},this.compactMode?{width:"100%"}:{height:"100%"})),a()(this.filterWithText).css(Object.assign({},this.compactMode?{height:"310px",width:"100%"}:{width:"310px",height:"100%"})),a()(y).css(Object.assign({},this.compactMode?{width:"100%"}:{height:"100%"})),setTimeout((()=>{this.styleHistoryGrid(),this.styleHistoryFilters()}),100)}))}));this.subs.push(b,I,w,C)}setGridColumnsRendering(){const t=this._historyGrid.columns.byName(P);t&&(t.cellType="html",t.width=35);const e=this._historyGrid.columns.byName(R);e&&(e.cellType="html",e.width=20);const n=this._historyGrid.columns.byName(x);n.cellType="html",n.width=20;const i=this._historyGrid.columns.byName(B);i.cellType="html",i.width=90,this._historyGrid.columns.byName(F).width=110,this._historyGrid.columns.byName(Kt).cellType="html"}isFavoriteByIndex(t){return this.currentDf.get(R,t)}setGridCellRendering(){this._historyGrid.onCellPrepare((n=>{var i,o,r,l,u,c,d,p,h,m,v;if(n.isColHeader&&(null===(i=n.tableColumn)||void 0===i?void 0:i.name)&&[P,x,R].includes(n.tableColumn.name)&&(n.customText=""),!n.isColHeader){if((null===(o=n.tableColumn)||void 0===o?void 0:o.name)===P){n.customText="";const i=this.getRunByIdx(n.tableRowIndex);n.element=e.divH([e.iconFA("trash",(()=>{const i=new Set([this.getRunByIdx(n.tableRowIndex)]),o=new Lt(i);o.onFuncCallDelete.pipe((0,s.take)(1)).subscribe((()=>Ut(this,void 0,void 0,(function*(){e.setUpdateIndicator(this.root,!0);try{yield Promise.all(f()(i.values()).map((t=>Ut(this,void 0,void 0,(function*(){return yield this.deleteRun(t.id),Promise.resolve()})))))}catch(e){t.shell.error(e)}finally{e.setUpdateIndicator(this.root,!1)}})))),o.show({center:!0,width:500})}),"Remove run from history"),e.iconFA("edit",(()=>this.showEditDialog(i,this.isFavoriteByIndex(n.tableRowIndex))),"Edit run metadata")],{style:{padding:"6px 0px",gap:"6px","justify-content":"space-between"}})}if((null===(r=n.tableColumn)||void 0===r?void 0:r.name)===R){n.customText="";const t=this.getRunByIdx(n.tableRowIndex),i=e.iconFA("star",(()=>this.saveIsFavorite(t,!1).then((()=>this.updateRun(t)))),"Unfavorite");a()(i).addClass("fas"),n.element=e.div(n.cell.value?i:e.iconFA("star",(()=>this.saveIsFavorite(t,!0).then((()=>this.updateRun(t)))),"Favorite"),{style:{padding:"5px 0px"}})}if((null===(l=n.tableColumn)||void 0===l?void 0:l.name)===x){n.customText="";const t=e.iconFA("flask",null,"Experimental run");a()(t).addClass("fad fa-sm"),a()(t).removeClass("fal"),n.element=n.cell.value&&"Experimental"===n.cell.value?e.div(t,{style:{padding:"5px"}}):e.div()}if((null===(u=n.tableColumn)||void 0===u?void 0:u.name)===B){n.customText="";const t=n.cell.value.length>0?e.div(null===(c=n.cell.value)||void 0===c?void 0:c.split(",").map((t=>e.span([t],"d4-tag"))),"d4-tag-editor"):e.div();a()(t).css({padding:"3px","background-color":"transparent"}),n.element=t}if((null===(d=n.tableColumn)||void 0===d?void 0:d.name)===Kt){n.customText="";const i=this.getRunByIdx(n.tableRowIndex);if(!i)return;const o=i.author.picture;a()(o).css({width:"25px",height:"25px",fontSize:"20px"}),e.bind(i.author,o);const r=e.iconFA("flask",null,"Experimental run");r.classList.add("fad","fa-sm"),r.classList.remove("fal"),r.style.marginLeft="3px";const l=i.options.immutable_tags,u=e.span([e.label(null!==(m=null!==(p=i.options.title)&&void 0!==p?p:null===(h=i.author)||void 0===h?void 0:h.friendlyName)&&void 0!==m?m:t.shell.user.friendlyName,{style:{color:"var(--blue-1)"}}),...l&&l.includes(A)?[r]:[]]),c=e.iconFA("edit",(t=>{t.stopPropagation(),this.showEditDialog(i,this.isFavoriteByIndex(n.tableRowIndex))}),"Edit run metadata");c.classList.add("hp-funccall-card-icon","hp-funccall-card-hover-icon");const d=e.iconFA("trash-alt",(i=>Ut(this,void 0,void 0,(function*(){i.stopPropagation();const o=new Set([this.getRunByIdx(n.tableRowIndex)]),r=new Lt(o);r.onFuncCallDelete.pipe((0,s.take)(1)).subscribe((()=>Ut(this,void 0,void 0,(function*(){e.setUpdateIndicator(this.root,!0);try{yield Promise.all(f()(o.values()).map((t=>Ut(this,void 0,void 0,(function*(){return yield this.deleteRun(t.id),Promise.resolve()})))))}catch(e){t.shell.error(e)}finally{e.setUpdateIndicator(this.root,!1)}})))),r.show({center:!0,width:500})}))),"Delete run");d.classList.add("hp-funccall-card-icon","hp-funccall-card-hover-icon");const g=e.iconFA("star",(t=>{t.stopPropagation(),this.saveIsFavorite(i,!1).then((()=>this.updateRun(i)))}),"Unfavorite");g.classList.add("fas","hp-funccall-card-icon");const y=e.iconFA("star",(t=>{t.stopPropagation(),this.saveIsFavorite(i,!0).then((()=>this.updateRun(i)))}),"Favorite");y.classList.add("hp-funccall-card-icon","hp-funccall-card-hover-icon"),this.isFavoriteByIndex(n.tableRowIndex)?(e.setDisplay(y,!1),e.setDisplay(g,!0)):(e.setDisplay(g,!1),e.setDisplay(y,!0));const b=jt(i),w=e.divH([e.divH([o,e.divV([u,e.span([b]),...i.options.tags&&i.options.tags.length>0?[e.div(i.options.tags.map((t=>e.span([t],"d4-tag"))))]:[]],"hp-card-content")]),e.divH([...(null===(v=this.options)||void 0===v?void 0:v.showActions)?[g,y,c,d]:[]])],"hp-funccall-card"),C=n.tableRowIndex;w.addEventListener("mouseover",(()=>{n.grid.dataFrame.mouseOverRowIdx=C})),w.addEventListener("click",(t=>{t.shiftKey?n.grid.dataFrame.selection.set(C,!0):t.ctrlKey?n.grid.dataFrame.selection.set(C,!1):n.grid.dataFrame.currentRowIdx=C})),n.element=w}}}))}deleteRun(e){return Ut(this,void 0,void 0,(function*(){return pt.loadRun(e,!0).then((t=>Ut(this,void 0,void 0,(function*(){var e;return[yield(null===(e=this.options)||void 0===e?void 0:e.isHistory)?pt.deleteRun(t):Promise.resolve(),t]})))).then((([,t])=>{var n;return this.runs.delete(e),this.onRunsChanged.next(this.runs),(null===(n=this.options)||void 0===n?void 0:n.isHistory)&&this.onDelete.next(t),t})).then((t=>{this.saveIsFavorite(t,!1)})).catch((e=>{t.shell.error(e)}))}))}editRun(t){this.showEditDialog(t,!1)}updateRun(t){this.runs.set(t.id,t),this.onRunsChanged.next(this.onRunsChanged.value)}addRun(t){this.runs.set(t.id,t),this.onRunsChanged.next(this.onRunsChanged.value)}updateRuns(t){this.onRunsChanged.next(t.reduce(((t,e)=>(t.set(e.id,e),t)),new Map))}get isFilterHidden(){return this._isFilterHidden.value}set isFilterHidden(t){this._isFilterHidden.next(t)}get compactMode(){return this._compactMode.value}set compactMode(t){this._compactMode.next(t)}get onCompactModeChanged(){return this._compactMode.asObservable()}styleHistoryGrid(){var t;this._historyGrid.setOptions({showCurrentRowIndicator:!0,showCurrentCellOutline:!1,allowEdit:!1,allowBlockSelection:!1,showRowHeader:!1,showColumnLabels:!this.compactMode,extendLastColumn:this.compactMode}),this._historyGrid.sort([F],[!1]);for(let e=0;e<this._historyGrid.columns.length;e++){const n=this._historyGrid.columns.byIndex(e);n&&(null===(t=n.column)||void 0===t?void 0:t.type)===o.TYPE.DATE_TIME&&(n.format="MMM d, h:mm tt")}if(this.setGridColumnsRendering(),0!==this.runs.size)if(this.compactMode)this._historyGrid.columns.setVisible([Kt]),this._historyGrid.props.rowHeight=70,this._historyGrid.invalidate();else{this._historyGrid.props.rowHeight=28;const t=[...this.runs.values()][0].func,e=this.showMetadataIcon.value,n=this.currentDf.getCol(B);this._historyGrid.columns.setVisible([x,R,P,...e?[F]:[],...e?[k]:[],...e&&n.stats.missingValueCount<n.length?[B]:[],...e?[N]:[],...e?[L]:[],...this.showInputsIcon.value?this.visibleProps(t).map((e=>{var n,i;const o=null!==(n=t.inputs.find((t=>t.name===e)))&&void 0!==n?n:t.outputs.find((t=>t.name===e));return o?null!==(i=o.caption)&&void 0!==i?i:Wt(o.name):Wt(e)})):[]])}}get currentDf(){return this._onRunsDfChanged.value}styleHistoryFilters(){var t,n;if(this.runs.size>0){const i=[...this.runs.values()][0].func,o=this.currentDf.getCol(B),s=this.showMetadataIcon.value,r=[...s&&this.currentDf.getCol(x).categories.length>1?[x]:[],...s&&(null!==(n=null===(t=this.currentDf.col(R))||void 0===t?void 0:t.categories.length)&&void 0!==n?n:0)>1?[R]:[],...s?[F,O]:[],...s&&this.currentDf.getCol(k).categories.length>1?[k]:[],...s&&o.stats.missingValueCount<o.length?[B]:[],...s&&this.currentDf.getCol(N).categories.length>1?[N]:[],...s&&this.currentDf.getCol(L).categories.length>1?[L]:[],...this.showInputsIcon.value?this.visibleProps(i).map((t=>{var e,n;const o=null!==(e=i.inputs.find((e=>e.name===t)))&&void 0!==e?e:i.outputs.find((e=>e.name===t));return o?null!==(n=o.caption)&&void 0!==n?n:Wt(o.name):Wt(t)})).filter((t=>{var e;return!(null===(e=this.options)||void 0===e?void 0:e.isHistory)||this.currentDf.getCol(t).categories.length>1})).map((t=>t)):[]];r.length>0?(a()(this.filterWithText).css({paddingTop:"10px"}),e.setDisplay(this.defaultFiltersText,!1),e.setDisplay(this._historyFilters.root,!0),this._historyFilters.setOptions({columnNames:r,showHeader:!1,showBoolCombinedFitler:!1})):(e.setDisplay(this.defaultFiltersText,!0),e.setDisplay(this._historyFilters.root,!1))}}redrawSelectionState(){const t=this.currentDf.selection.trueCount;t<2?this.compareIcon.firstChild.classList.add("hp-disabled"):this.compareIcon.firstChild.classList.remove("hp-disabled"),0===t?this.trashIcon.firstChild.classList.add("hp-disabled"):this.trashIcon.firstChild.classList.remove("hp-disabled")}}var zt=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};class Jt{static getHistoryRuns(e,n=!0){return(0,c.from)((()=>zt(this,void 0,void 0,(function*(){return yield pt.pullRunsByName(e,[{author:t.shell.user}],{order:"started"},["func.params","session.user","options"],n)})))())}}const Kt="ID";class Zt extends o.InputBase{constructor(t,n,i){var o,r;const a=e.input.string(t,{value:""});super(a.dart),this.label=t,this._funcName=n,this.options=i,this.onHistoricalRunChosen=new c.BehaviorSubject(null),this.experimentRunsUpdate=new c.Subject,this.store={experimentRuns:new c.Observable,isExperimentRunsLoading:new c.Subject,experimentRunData:new c.BehaviorSubject("")},this._historyList=new qt([],{fallbackText:"No runs are found in history",showActions:!1,showBatchActions:!1,isHistory:!1,visibleProps:null===(o=this.options)||void 0===o?void 0:o.mainProps,propFuncs:null===(r=this.options)||void 0===r?void 0:r.propFuncs}),this._historyDialog=this.getHistoryDialog(),this._visibleInput=e.input.string(this.label,{value:""}),this._visibleIcon=e.iconFA("search",(()=>this.showSelectionDialog())),this._chosenRun=null,this._chosenRunId=null,this._visibleInput=a,this._visibleInput.readOnly=!0,this._visibleInput.input.addEventListener("click",(()=>this.showSelectionDialog())),this._visibleInput.addOptions(this._visibleIcon),this.store.experimentRuns=this.experimentRunsUpdate.pipe((0,s.tap)((()=>this.toggleLoaderExpRuns(!0))),(0,s.switchMap)((()=>{var t,e;return Jt.getHistoryRuns(this._funcName,null===(e=null===(t=this.options)||void 0===t?void 0:t.skipDfsOnInit)||void 0===e||e).pipe((0,s.catchError)((t=>(console.error(t),c.EMPTY))),(0,s.finalize)((()=>this.toggleLoaderExpRuns(!1))))})),(0,s.shareReplay)(1)),this.store.experimentRuns.subscribe((t=>{this._historyList.updateRuns(t.filter((t=>!K(t))))})),this.store.isExperimentRunsLoading.subscribe((t=>{e.setUpdateIndicator(this._visibleInput.root,t),e.setUpdateIndicator(this._historyList.root,t)})),this.experimentRunsUpdate.next()}setCurrentRow(){this.getValue()?this._historyList.chosen=this.getValue():this.chosenRunId&&(this._historyList.chosenById=this.chosenRunId)}showSelectionDialog(){this.renderGridAndFilters(),this._historyDialog.getButton("OK").disabled=1!==this._historyList.selected.size,this._historyDialog.show({modal:!0,fullScreen:!0,center:!0,width:window.innerWidth-50,height:window.innerHeight-50})}renderGridAndFilters(){var t,e;const n=new qt([...this._historyList.runs.values()],Object.assign(Object.assign({},this.options),{visibleProps:null===(t=this.options)||void 0===t?void 0:t.mainProps,propFuncs:null===(e=this.options)||void 0===e?void 0:e.propFuncs}));this._historyList.root.replaceWith(n.root),this._historyList=n,this._historyList.onChosen.subscribe((t=>{this._historyDialog.getButton("OK").disabled=!t})),this._historyList.onRunsDfChanged.pipe((0,s.filter)((t=>t.rowCount>0)),(0,s.take)(1)).subscribe((t=>{this.setCurrentRow()}))}getHistoryDialog(){const t=e.dialog();return a()(t.root.querySelector(".d4-dialog-contents")).removeClass("ui-form"),t.onOK((()=>zt(this,void 0,void 0,(function*(){var t,e;let n=this._historyList.chosen;n&&((null===(e=null===(t=this.options)||void 0===t?void 0:t.skipDfsOnInit)||void 0===e||e)&&(n=yield pt.loadRun(n.id,!1)),this.setValue(n)),this.fireInput()})))),t.addButton("Refresh",(()=>{this.experimentRunsUpdate.next()}),2,"Reload list of runs"),t.addButton("Discard",(()=>{this.setValue(null),this.fireInput(),t.close()}),1,"Discard the previous choice"),a()(t.getButton("CANCEL")).hide(),t.add(this._historyList.root),t}setValue(t){var e,n,i,o,s,r,a;this._chosenRun=t,this._chosenRunId=null!==(n=null===(e=this._chosenRun)||void 0===e?void 0:e.id)&&void 0!==n?n:null,this.onHistoricalRunChosen.next(t),this.stringValue=t?(null===(i=this.options)||void 0===i?void 0:i.stringValueFunc)?null===(o=this.options)||void 0===o?void 0:o.stringValueFunc(t):[`${jt(t)} \\ ${t.author.name}`,(null!==(a=null!==(r=null===(s=this.options)||void 0===s?void 0:s.mainProps)&&void 0!==r?r:Q(t.func))&&void 0!==a?a:[]).map((e=>X(t,e))).join(" \\ ")].join(" \\ "):"No run chosen",this.notify&&this.fireChanged()}getValue(){return this._chosenRun}get chosenRun(){return this._chosenRun}get chosenRunId(){return this._chosenRunId}set chosenRunId(t){this._chosenRunId=t}get root(){return this._visibleInput.root}set stringValue(t){this._visibleInput.value=t,this._visibleInput.setTooltip(this._visibleInput.value)}get stringValue(){return this._visibleInput.value}get iconRoot(){return this._visibleIcon}toggleLoaderExpRuns(t){this.store.isExperimentRunsLoading.next(t)}}class Xt extends Zt{set value(t){this.setValue(t)}get value(){return this.getValue()}}class Qt extends Zt{get value(){const t=this.getValue();return t?JSON.stringify({visualValue:this.stringValue,id:t.id.split("-")}):null}set value(t){this.setValue(null),this.stringValue=t?JSON.parse(t).visualValue:"No run is chosen",this.chosenRunId=t?JSON.parse(t).id.join("-"):""}}var te=n(565),ee={};ee.styleTagTransform=St(),ee.setAttributes=wt(),ee.insert=yt().bind(null,"head"),ee.domAPI=vt(),ee.insertStyleElement=Ct(),ft()(te.A,ee),te.A&&te.A.locals&&te.A.locals;var ne;class ie extends o.Widget{updateHistoryPane(t){this.historyList.updateRuns(t)}showEditDialog(t){this.historyList.editRun(t)}addRun(t){this.historyList.addRun(t)}get history(){return this.historyList.runs}get onCompactModeChanged(){return this.historyList.onCompactModeChanged}get compactMode(){return this.historyList.compactMode}constructor(n){super(e.box(e.divText("No historical runs loaded","hp-no-elements-label"),{style:{width:"100%",height:"100%"}})),this.func=n,this.onRunChosen=new c.Subject,this.onComparison=new c.Subject,this.afterRunEdited=new c.Subject,this.afterRunDeleted=new c.Subject,this.allRunsFetch=new c.Subject,this.historyList=new qt([],{fallbackText:"No runs are found in history",showActions:!0,showBatchActions:!0,isHistory:!0}),this.panel=this.historyList.root;const i=this.historyList.onChosen.pipe((0,s.filter)((t=>!!t))).subscribe((t=>this.onRunChosen.next(t.id))),o=this.historyList.onComparisonCalled.subscribe((t=>this.onComparison.next(t))),r=this.allRunsFetch.subscribe((()=>{return n=this,i=void 0,s=function*(){e.setUpdateIndicator(this.root,!0),pt.pullRunsByName(this.func.name,[{author:t.shell.user}],{},["session.user","options"]).then((t=>{e.empty(this.root),this.root.appendChild(this.panel),this.updateHistoryPane(t)})).catch((e=>t.shell.error(e))).finally((()=>e.setUpdateIndicator(this.root,!1)))},new((o=void 0)||(o=Promise))((function(t,e){function r(t){try{l(s.next(t))}catch(t){e(t)}}function a(t){try{l(s.throw(t))}catch(t){e(t)}}function l(e){var n;e.done?t(e.value):(n=e.value,n instanceof o?n:new o((function(t){t(n)}))).then(r,a)}l((s=s.apply(n,i||[])).next())}));var n,i,o,s})),a=this.historyList.onMetadataEdit.subscribe((t=>{this.afterRunEdited.next(t)})),l=this.historyList.onDelete.subscribe((t=>{this.afterRunDeleted.next(t)}));this.subs.push(i,r,a,o,l),this.allRunsFetch.next()}}!function(t){t.fileInput=function(t="Drag-n-drop here",e=null,n=null,i=Rt){return new Ot(t,e,n,i)},t.historyInput=function(t,e,n){return new Xt(t,e,n)},t.historyInputJSON=function(t,e,n){return new Qt(t,e,n)},t.historyPanel=function(t){return new ie(t)}}(ne||(ne={}));var oe=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const se=window;class re extends o.TableView{static fromComparedRuns(n,i){return oe(this,arguments,void 0,(function*(n,i,s={parentView:void 0,parentCall:void 0}){const r=((n,i,s={parentView:void 0,parentCall:void 0})=>{var r,l;const u=i,c=[...u.inputs,...u.outputs].map((t=>Dt(t))).reduce(((t,e)=>(t[e.name]?t[e.name].push(...e.config):t[e.name]=e.config,t)),{}),d=t=>{var e;if(t.propertyType===o.TYPE.DATA_FRAME){const e=c[t.name].map((e=>{var i;let s=null!==(i=t.caption)&&void 0!==i?i:t.name;const r=o.Column.fromType(o.TYPE.DATA_FRAME,s,n.length);r.init((e=>{var i;return null!==(i=n[e].inputs[t.name])&&void 0!==i?i:n[e].outputs[t.name]}));const a=p.columns.getUnusedName(`${r.name} (${e.type})`);return r.name=a,s=a,r.temp[g]=e,p.columns.add(r),r}));return e}{let i=null!==(e=t.caption)&&void 0!==e?e:t.name;const s=o.Column.fromType(t.propertyType,i,n.length);s.init((e=>{var i;return null!==(i=n[e].inputs[t.name])&&void 0!==i?i:n[e].outputs[t.name]}));const r=p.columns.getUnusedName(s.name);return s.name=r,i=r,p.columns.add(s),[s]}},p=o.DataFrame.create(n.length),h=[];return n.forEach((t=>{var e;let n=null!==(e=t.options.title)&&void 0!==e?e:`${t.func.name} - ${jt(t)}`,i=2;for(;h.includes(n);)n=`${t.func.name} - ${jt(t)})\n .toLocaleString('en-us', {month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric'})} - ${i}`,i++;h.push(n)})),p.columns.add(o.Column.fromStrings(C,h)),p.name=(null===(r=s.parentCall)||void 0===r?void 0:r.func.name)?`${null===(l=s.parentCall)||void 0===l?void 0:l.func.name} - comparison`:`${i.name} - comparison`,u.inputs.forEach((t=>d(t))),u.outputs.forEach((t=>d(t))),t.events.onCurrentObjectChanged.subscribe((({sender:n})=>{if(n instanceof o.Column&&n.type===o.TYPE.DATA_FRAME&&t.shell.tv&&t.shell.tv.temp.isComparison&&[o.VIEWER.LINE_CHART,o.VIEWER.SCATTER_PLOT,o.VIEWER.HISTOGRAM,o.VIEWER.BOX_PLOT].includes(n.temp[g].type)){t.shell.windows.showProperties=!0;const i=t=>{const e=t.get(0).clone();e.columns.addNew(I,o.TYPE.STRING).init(t.dataFrame.get(C,0));for(let n=1;n<t.length;n++){const i=t.get(n).clone();i.columns.addNew(I,o.TYPE.STRING).init(t.dataFrame.get(C,n));const s=[o.COLUMN_TYPE.INT,o.COLUMN_TYPE.FLOAT];for(let t=0;t<i.columns.length;t++){const n=i.columns.byIndex(t),r=e.columns.byIndex(t);n.type!==r.type&&s.includes(n.type)&&s.includes(r.type)&&(n.type!==o.COLUMN_TYPE.FLOAT&&i.columns.replace(n,n.convertTo(o.COLUMN_TYPE.FLOAT)),r.type!==o.COLUMN_TYPE.FLOAT&&e.columns.replace(r,r.convertTo(o.COLUMN_TYPE.FLOAT)))}e.append(i,!0)}return e},s=n.temp[g].look;setTimeout((()=>{switch(n.temp[g].type){case o.VIEWER.LINE_CHART:const r=e.waitBox((()=>Bt(void 0,void 0,void 0,(function*(){var t;const e=null!==(t=n.temp.unitedDf)&&void 0!==t?t:i(n);return n.temp.unitedDf=e,e.plot.line(Object.assign(Object.assign({},s),{split:I})).root}))));a()(r).css({width:"100%"}),t.shell.o=r;break;case o.VIEWER.SCATTER_PLOT:const l=e.waitBox((()=>Bt(void 0,void 0,void 0,(function*(){var t;const e=null!==(t=n.temp.unitedDf)&&void 0!==t?t:i(n);return n.temp.unitedDf=e,e.plot.scatter(Object.assign(Object.assign({},s),{color:I})).root}))));t.shell.o=l,a()(l).css({width:"100%"});break;case o.VIEWER.HISTOGRAM:const u=e.waitBox((()=>Bt(void 0,void 0,void 0,(function*(){var t;const e=null!==(t=n.temp.unitedDf)&&void 0!==t?t:i(n);return n.temp.unitedDf=e,e.plot.histogram(Object.assign(Object.assign({},s),{split:I})).root}))));t.shell.o=u,a()(u).css({width:"100%"});break;case o.VIEWER.BOX_PLOT:const c=e.waitBox((()=>Bt(void 0,void 0,void 0,(function*(){var t;const e=null!==(t=n.temp.unitedDf)&&void 0!==t?t:i(n);return n.temp.unitedDf=e,e.plot.box(Object.assign(Object.assign({},s),{category:I})).root}))));t.shell.o=c,a()(c).css({width:"100%"})}}))}})),p})(n,i,s),l=[...t.shell.views].find((t=>t.type===v||"scripts"===t.type||"functions"===t.type));return l&&(t.shell.v=l),new this(r,s)}))}constructor(e,n={}){super(se.grok_TableView(e.dart,!1)),n.parentView&&(this.parentView=n.parentView),this.parentCall=n.parentCall||t.functions.getCurrentCall()}showAllColumns(){const t=this.dataFrame.columns.names();this.grid.columns.setVisible(t)}showChangingColumns(){const t=this.dataFrame.columns.names().filter((t=>o.TYPES_SCALAR.has(this.dataFrame.getCol(t).type)&&this.dataFrame.getCol(t).categories.length>1||!o.TYPES_SCALAR.has(this.dataFrame.getCol(t).type)));this.grid.columns.setVisible(t)}defaultCustomize(){var n;const i=e.iconFA("compress-alt",(()=>{this.showChangingColumns(),a()(s).show(),a()(i).hide()}),"Hide constant parameters"),s=e.iconFA("expand-arrows-alt",(()=>{this.showAllColumns(),a()(s).hide(),a()(i).show()}),"Show all parameters");a()(i).hide(),this.setRibbonPanels([...this.getRibbonPanels(),[i,s]]),this.showChangingColumns(),this.root.style.removeProperty("width"),this.root.firstChild.style.removeProperty("width"),this.root.firstChild.firstChild.style.removeProperty("width"),this.grid.props.rowHeight=180,this.grid.props.showAddNewRowIcon=!1,this.grid.props.allowEdit=!1,this.grid.columns.byName(C).width=70;for(let t=0;t<this.grid.columns.length;t++){const e=this.grid.columns.byIndex(t);(null===(n=e.column)||void 0===n?void 0:n.temp[g])&&(e.width=350,e.cellType="html")}const r=new o.LruCache;this.grid.onCellPrepare((t=>oe(this,void 0,void 0,(function*(){if(!t.isColHeader&&!t.isRowHeader){if(t.tableColumn.name===C){t.customText="";const n=t.cell.value.split(" - "),i=n.length>1?[n[0],e.element("br"),n[1]]:n;return t.element=e.div(i,{style:{"writing-mode":"vertical-rl","text-orientation":"mixed",margin:"auto"}}),void(t.element.parentElement.style.display="flex")}if(t.tableColumn&&t.tableColumn.temp[g]){const e=t.cell.value,n=t.tableColumn.temp[g],i=n.type,s=()=>oe(this,void 0,void 0,(function*(){const s=Object.values(m).includes(i)?o.Viewer.fromType(i,e):yield e.plot.fromType(i);return t.tableColumn.temp[g].look?s.setOptions(t.tableColumn.temp[g].look):(s.setOptions(n),t.tableColumn.temp[g]=s.getOptions()),s.root})),a=`${e.id}_${i}`;if(r.get(a))t.element=r.get(a);else{const e=yield s();r.set(a,e),t.element=e}t.element.style.width="100%",t.element.style.height="100%"}}}))));const l=e.box(e.div([],{style:{"min-height":"100px"}})),u=t.events.onCurrentViewChanged.subscribe((()=>{t.shell.v.id===this.id?t.shell.dockManager.dock(l,"down",null,"Comparison chart",.25):t.shell.dockManager.close(l)})),c=this.grid.onCellClick.subscribe((n=>{var i;if(t.shell.v.id===this.id&&n.isColHeader&&(null===(i=n.tableColumn)||void 0===i?void 0:i.type)===o.TYPE.DATA_FRAME&&[o.VIEWER.LINE_CHART,o.VIEWER.SCATTER_PLOT,o.VIEWER.HISTOGRAM,o.VIEWER.BOX_PLOT].includes(n.tableColumn.temp[g].type)){t.shell.dockManager.findNode(l)||t.shell.dockManager.dock(l,"down",null,"Comparison chart",.25);const i=t=>{const e=o.toJs(t.get(0)).clone();e.columns.addNew(I,o.TYPE.STRING).init(t.dataFrame.get(C,0));for(let n=1;n<t.length;n++){const i=o.toJs(t.get(n)).clone();i.columns.addNew(I,o.TYPE.STRING).init(t.dataFrame.get(C,n));const s=[o.COLUMN_TYPE.INT,o.COLUMN_TYPE.FLOAT];for(let t=0;t<i.columns.length;t++){const n=i.columns.byIndex(t),r=e.columns.byIndex(t);n.type!==r.type&&s.includes(n.type)&&s.includes(r.type)&&(n.type!==o.COLUMN_TYPE.FLOAT&&i.columns.replace(n,n.convertTo(o.COLUMN_TYPE.FLOAT)),r.type!==o.COLUMN_TYPE.FLOAT&&e.columns.replace(r,r.convertTo(o.COLUMN_TYPE.FLOAT)))}e.append(i,!0)}return e},s=(t,e,i)=>{var s;switch(null===(s=n.tableColumn)||void 0===s?void 0:s.temp[g].type){case o.VIEWER.LINE_CHART:return i.plot.line(Object.assign(Object.assign({},e),{split:I})).root;case o.VIEWER.SCATTER_PLOT:return i.plot.scatter(Object.assign(Object.assign({},e),{color:I})).root;case o.VIEWER.HISTOGRAM:return i.plot.histogram(Object.assign(Object.assign({},e),{split:I})).root;case o.VIEWER.BOX_PLOT:return i.plot.box(Object.assign(Object.assign({},e),{category:I})).root}};e.setUpdateIndicator(l,!0),setTimeout((()=>{var t;if(!n.tableColumn.temp.unitedPlot){const o=n.tableColumn.temp[g].look,r=i(n.tableColumn);n.tableColumn.temp.unitedPlot=s(null===(t=n.tableColumn)||void 0===t?void 0:t.temp[g].type,o,r),e.setUpdateIndicator(l,!1)}e.empty(l),l.appendChild(n.tableColumn.temp.unitedPlot)}),10)}else t.shell.dockManager.close(l)}));this.subs.push(c,u)}}const ae="_DG_CUSTOM_SERIALIZED_TOKEN_";function le(t,e=2){return JSON.stringify(t,((t,e)=>e instanceof o.DataFrame?{[ae]:"DataFrame",value:Array.from(e.toByteArray())}:e instanceof ArrayBuffer?{[ae]:"ArrayBuffer",value:Array.from(new Uint8Array(e))}:e instanceof Map?{[ae]:"Map",value:Array.from(e)}:e instanceof Set?{[ae]:"Set",value:Array.from(e)}:e),e)}function ue(t,e){if(e&&e[ae]&&e.value)switch(e[ae]){case"DataFrame":return o.DataFrame.fromByteArray(new Uint8Array(e.value));case"ArrayBuffer":return new Uint8Array(e.value).buffer;case"Map":return new Map(e.value);case"Set":return new Set(e.value)}return e}const ce=[{name:"Null",predicate:function(t,e){return null==t&&null==e},checker:function(){}},{name:"Boolean",predicate:function(t,e){return"boolean"==typeof t&&"boolean"==typeof e},checker:pe},{name:"String",predicate:function(t,e){return"string"==typeof t&&"string"==typeof e},checker:pe},{name:"Integer",predicate:function(t,e){return Number.isInteger(t)&&Number.isInteger(e)},checker:pe},{name:"Float",predicate:function(t,e){return"number"==typeof t&&"number"==typeof e},checker:function(t,e,n){if(!(t===Number.POSITIVE_INFINITY&&e===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY&&e===Number.NEGATIVE_INFINITY||isNaN(t)&&isNaN(e)))return Math.abs(t-e)<n.options.floatTolerance?void 0:[{msg:`Expected ${e}, got ${t} (tolerance = ${n.options.floatTolerance})`}]}},{name:"Map",predicate:function(t,e){return t instanceof Map&&e instanceof Map},checker:function(t,e,n,i){const o=[];if(t.size!==e.size){const n={msg:`Maps are of different size: actual map size is ${t.size} and expected map size is ${e.size}`};o.push(n)}for(const n of e.keys()){const o=t.get(n),s=e.get(n);i([String(n)],o,s)}return o}},{name:"Set",predicate:function(t,e){return t instanceof Set&&e instanceof Set},checker:function(t,e,n,i){const o=[];if(t.size!==e.size){const n={msg:`Sets are of different size: actual set size is ${t.size} and expected set size is ${e.size}`};o.push(n)}for(const n of e.values()){const e=t.has(n);i([String(n)],e,!0)}return o}},{name:"ArrayBuffer",predicate:function(t,e){return t instanceof ArrayBuffer&&e instanceof ArrayBuffer},checker:function(t,e,n,i){return he(Array.from(new Uint8Array(t)),Array.from(new Uint8Array(e)),0,i)}},{name:"Array",predicate:function(t,e){return t instanceof Array&&e instanceof Array},checker:he},{name:"DataFrame",predicate:function(t,e){return t instanceof o.DataFrame&&e instanceof o.DataFrame},checker:function(t,e,n,i){const o=[];if(t.rowCount!==e.rowCount){const n={msg:`Dataframes has different row count: actual row count is ${t.rowCount} and expected row count is ${e.rowCount}`};o.push(n)}for(const n of e.columns){const s=t.columns.byName(n.name);if(s)if(s.type===n.type)for(let t=0;t<e.rowCount;t++){const e=s.get(t),o=n.get(t);i([n.name,String(t)],e,o)}else{const t={msg:`Column ${n.name} type expected ${n.type} got ${s.type}`};o.push(t)}else{const t={msg:`Column ${n.name} not found`};o.push(t)}}return o}},{name:"Object",predicate:function(t,e){return"object"==typeof t&&"object"==typeof e},checker:function(t,e,n,i){for(const[n,o]of Object.entries(e))i([n],t[n],o);return[]}}];class de extends Error{}function pe(t,e){if(t!==e)return[{msg:`Expected ${e}, got ${t}`}]}function he(t,e,n,i){const o=[];if(t.length!==e.length){const n={msg:`Arrays are of different length: actual array length is ${t.length} and expected array length is ${e.length}`};o.push(n)}for(let n=0;n<t.length;n++)i([String(n)],t[n],e[n]);return o}const fe={floatTolerance:.001,maxErrorsReport:5,maxDepth:128,checkersSeq:ce,prefix:""};class me{constructor(t={}){this.options=Object.assign(Object.assign({},fe),t),this.state={errors:[],currentPath:[],options:this.options}}run(t,e){this.matchChecker(t,e),this.checkErrorsLimit(0)}checkDeep(t,e,n){const i=t.length;if(this.state.currentPath.push(...t),this.state.currentPath.length>this.options.maxDepth)throw new de(`Max depth ${this.options.maxDepth} is exceeded, potentially a circular structure`);this.matchChecker(e,n),this.state.currentPath.splice(-i)}matchChecker(t,e){let n=!1;for(const{predicate:i,checker:o}of this.options.checkersSeq)if(i(t,e)){n=!0;const i=o(t,e,this.state,this.checkDeep.bind(this));i&&i.map((t=>this.addError(t)));break}if(!n){const n={msg:`Type mismatch or no checker defined: expected ${e}, got ${t}`};this.addError(n)}}addError(t){var e,n;const i={path:[...null!==(e=this.state.currentPath)&&void 0!==e?e:[],...null!==(n=t.path)&&void 0!==n?n:[]],msg:t.msg};this.state.errors.push(i),this.checkErrorsLimit()}checkErrorsLimit(t=this.options.maxErrorsReport){if(this.state.errors.length>t){const t=this.makeReport();throw new de(t)}}makeReport(){const t=this.state.errors.map((t=>{var e;const n=(null!==(e=t.path)&&void 0!==e?e:[]).map((t=>`['${String(t)}']`)).join("."),i=n?`${n}: ${t.msg}`:t.msg;return this.options.prefix?`${this.options.prefix}: ${i}`:i})).slice(0,this.options.maxErrorsReport).join("\n");return t}}var ve=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const ge=2e4,ye=5e3,be=5e3;function we(e,n){return ve(this,arguments,void 0,(function*(e,n,i={}){var o,s,r;yield Ce(n,null!==(o=i.initWaitTimeout)&&void 0!==o?o:ge),n.disableSetters(!0);try{for(const[t,o]of Object.entries(n.steps)){const a=e[t];if(!a)continue;const l=null!==(r=null===(s=i.stepOptions)||void 0===s?void 0:s[t])&&void 0!==r?r:{},u=l.prefix?`${l.prefix}: ${t}`:t,{updateMode:c}=i,d={validatorsWaitTimeout:ye,initWaitTimeout:ge,parent:n,interactive:i.interactive,updateMode:c};yield Ae(a,o.view,Object.assign(Object.assign(Object.assign({},d),l),{prefix:u}))}}finally{n.disableSetters(!1)}i.interactive&&t.shell.info(`${n.name} test passed`)}))}function Ae(e,n){return ve(this,arguments,void 0,(function*(e,n,i={}){var o;yield Ce(n,null!==(o=i.initWaitTimeout)&&void 0!==o?o:ge);const r=()=>ve(this,void 0,void 0,(function*(){var e;if(i.parent){const n=null!==(e=i.parentWaitTimeout)&&void 0!==e?e:be,o=yield i.parent.isUpdating.pipe((0,s.map)((()=>i.parent.getRunningUpdates())),(0,s.debounceTime)(100),(0,s.takeUntil)((0,c.of)(null).pipe((0,s.delay)(n))),(0,s.takeWhile)((t=>0!==t.length),!0),(0,s.last)()).toPromise();if(null==o?void 0:o.length){const e=`{options.prefix}: parent updates failed to complete in ${n}ms, updates: ${o.join(",")}`,s=new Error(e);throw i.interactive&&t.shell.error(String(s)),s}}}));yield r();for(const[t,o]of Object.entries(e.inputs)){const e=n.funcCall.inputParams[t].property.propertyType;i.updateMode?null==n.funcCall.inputs[t]&&(n.funcCall.inputs[t]=yield ut(e,o)):n.funcCall.inputs[t]=yield ut(e,o)}if(yield r(),yield(()=>ve(this,void 0,void 0,(function*(){var e;if(n instanceof Pi){const o=null!==(e=i.validatorsWaitTimeout)&&void 0!==e?e:ye,r=yield n.pendingInputValidations.pipe((0,s.map)((t=>Object.keys(t))),(0,s.debounceTime)(100),(0,s.takeUntil)((0,c.of)(null).pipe((0,s.delay)(o))),(0,s.takeWhile)((()=>!n.isValid()),!0),(0,s.last)()).toPromise();if(null==r?void 0:r.length){const e=`{options.prefix}: validators failed to accept input in ${o}ms, inputs: ${r.join(",")}`,n=new Error(e);throw i.interactive&&t.shell.error(String(n)),n}}})))(),console.log(`running ${n.func.nqName}`),yield n.run(),!i.updateMode){console.log(`checking ${n.func.nqName} results`);try{!function(t,e,n){new me(n).run(t,e)}(n.funcCall.outputs,e.outputs,i),!i.parent&&i.interactive&&t.shell.info(`${n.name} test passed`)}catch(e){throw i.interactive&&t.shell.error(String(e)),e}console.log(`${n.func.nqName} ok`)}}))}function Ce(t,e){return ve(this,void 0,void 0,(function*(){if(!(yield t.isReady.pipe((0,s.takeUntil)((0,c.of)(null).pipe((0,s.delay)(e))),(0,s.takeWhile)((t=>!t),!0),(0,s.last)()).toPromise()))throw new Error(`Waiting for view ${t.name} timeout`)}))}var Ie=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const Se=new URL(t.shell.startUri),Te="Run Data JSON",Ee=()=>Ie(void 0,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,selfBrowserSurface:"include"}),e=new MediaRecorder(t),n=[];e.ondataavailable=t=>n.push(t.data),e.onstop=()=>{const e=new Blob(n,{type:n[0].type});t.getVideoTracks()[0].stop(),o.Utils.download(`Recording ${(new Date).toLocaleString("en-us",{month:"short",day:"numeric",hour:"numeric",minute:"numeric"})}.mkv`,e,n[0].type)},e.start()}));class xe extends o.ViewBase{constructor(n,i={historyEnabled:!0,isTabbed:!1,skipInit:!1}){var s,r,a,l,u;super(),this.initValue=n,this.options=i,this._type="function",this.funcCallReplaced=new c.Subject,this.isReady=new c.BehaviorSubject(!1),this.exportConfig=null,this.getMocks=null,this.getTemplates=null,this.getHelp=null,this.reportBug=null,this.requestFeature=null,this.getAbout=null,this.historyBlock=null,this.isHistorical=new c.BehaviorSubject(!1),this.historyRoot=e.div(),this.consistencyState=new c.BehaviorSubject("consistent"),this.defaultExportFilename=(t,e)=>`${this.name} - ${(new Date).toLocaleString("en-US").replaceAll(/:|\//g,"-")}.${null!=e?e:this.exportConfig.supportedExtensions[t]}`,this.defaultSupportedExportExtensions=()=>({Excel:"xlsx"}),this.defaultSupportedExportFormats=()=>["Excel"],this.helpCache=null,this.box=!0,this.parentCall=t.functions.getCurrentCall(),n instanceof o.FuncCall&&(this.parentCall=n),this.parentView=null===(a=null===(r=null===(s=this.parentCall)||void 0===s?void 0:s.parentCall)||void 0===r?void 0:r.aux)||void 0===a?void 0:a.view,(null===(u=null===(l=this.parentCall)||void 0===l?void 0:l.func)||void 0===u?void 0:u.name)&&(this.basePath=`/${this.parentCall.func.name}`),i.skipInit||this.init()}onFuncCallReady(){return Ie(this,void 0,void 0,(function*(){if(yield pt.augmentCallWithFunc(this.funcCall,!1),!this.options.isTabbed){this.name&&"New view"!==this.name||(this.name=this.funcCall.func.friendlyName);try{this.func.package&&(yield this.getPackageData())}catch(t){console.log(t)}}this.build();const t=this.getStartId();if(t&&!this.options.isTabbed&&(e.setUpdateIndicator(this.root,!0),this.loadRun(t),e.setUpdateIndicator(this.root,!1),this.setAsLoaded()),this.isHistoryEnabled&&this.func){const t=this.options.isTabbed?this.isHistorical.subscribe((t=>{t||(this.funcCall.id=null)})):this.isHistorical.subscribe((t=>{var e,n;if(t){this.path=`?id=${this.funcCall.id}`;const t=jt(this.funcCall);this.name.indexOf(" — ")<0?this.name=`${this.name} — ${null!==(e=this.funcCall.options.title)&&void 0!==e?e:t}`:this.name=`${this.name.substring(0,this.name.indexOf(" — "))} — ${null!==(n=this.funcCall.options.title)&&void 0!==n?n:t}`}else this.path="",this.funcCall.id=null,this.name=`${this.name.substring(0,this.name.indexOf(" — ")>0?this.name.indexOf(" — "):void 0)}`}));this.subs.push(t)}}))}getStartId(){return t.shell.getVar("isLoaded")?void 0:Se.searchParams.get("id")}setAsLoaded(){return t.shell.setVar("isLoaded",!0)}get funcCall(){return this._funcCall}get func(){var t;return null===(t=this.funcCall)||void 0===t?void 0:t.func}get lastCall(){return this._lastCall}set lastCall(t){this._lastCall=t}get type(){return this._type}getPackageData(){return Ie(this,void 0,void 0,(function*(){var t,e;const n=this.func.package;if(!n)return;const i=null===(t=yield null==n?void 0:n.getProperties())||void 0===t?void 0:t.REPORT_BUG_URL;i&&!this.reportBug&&(this.reportBug=()=>Ie(this,void 0,void 0,(function*(){window.open(i,"_blank")})));const o=null===(e=yield null==n?void 0:n.getProperties())||void 0===e?void 0:e.REQUEST_FEATURE_URL;o&&!this.requestFeature&&(this.requestFeature=()=>Ie(this,void 0,void 0,(function*(){window.open(o,"_blank")})));const s=`${n.friendlyName}.\nLast updated on ${p()(n.updatedOn).format("YYYY MMM D, HH:mm")}`;this.getAbout||(this.getAbout=()=>Ie(this,void 0,void 0,(function*(){return s})))}))}linkFunccall(t){this._funcCall=t,this.funcCallReplaced.next(!0)}loadFuncCallById(){return Ie(this,void 0,void 0,(function*(){if(this.initValue instanceof o.FuncCall)return yield new Promise((t=>setTimeout(t,0))),void this.linkFunccall(this.initValue);e.setUpdateIndicator(this.root,!0);const n=this.getStartId();if(n&&!this.options.isTabbed)this.linkFunccall(yield pt.loadRun(n));else{const e=yield t.functions.eval(this.initValue);this.linkFunccall(e.prepare({}))}e.setUpdateIndicator(this.root,!1)}))}init(){return Ie(this,void 0,void 0,(function*(){yield this.loadFuncCallById(),yield this.onFuncCallReady(),this.isReady.next(!0)}))}build(){e.empty(this.root),this.root.appendChild(this.buildIO()),this.options.historyEnabled&&this.isHistoryEnabled&&this.buildHistoryBlock(),this.buildRibbonMenu(),this.buildRibbonPanels()}onComparisonLaunch(e){return Ie(this,void 0,void 0,(function*(){const n=this.comparatorFunc;if(n){const i=yield t.functions.eval(n),o=(yield i.prepare({params:{comparedRuns:e}}).call()).outputs.comparisonView;return void t.shell.addView(o)}const i=t.shell.v.parentCall,o=[...t.shell.views].find((t=>t.type===v)),s=yield re.fromComparedRuns(e,this.func,{parentView:o,parentCall:i});t.shell.addView(s),s.defaultCustomize();const r=this.compareCustomizer;if(r){const e=yield t.functions.eval(r);yield e.prepare({params:{defaultView:s}}).call()}}))}onSaveClick(){return Ie(this,void 0,void 0,(function*(){yield this.saveRun(this.funcCall)}))}buildHistoryBlock(){const n=ne.historyPanel(this.func);let i=!1;return this.subs.push(n.onCompactModeChanged.subscribe((e=>{const n=t.shell.dockManager.findNode(this.historyRoot);n&&(t.shell.dockManager.close(n),e?t.shell.dockManager.dock(this.historyRoot,"right",null,"History",.3):t.shell.dockManager.dock(this.historyRoot,"down",null,"History",.3))})),n.onRunChosen.subscribe((t=>Ie(this,void 0,void 0,(function*(){e.setUpdateIndicator(this.root,!0),yield this.loadRun(t),e.setUpdateIndicator(this.root,!1)})))),n.onComparison.subscribe((t=>Ie(this,void 0,void 0,(function*(){Mt(n.root,!0);const e=yield Promise.all(t.map((t=>pt.loadRun(t))));yield this.onComparisonLaunch(e),Mt(n.root,!1)})))),n.afterRunEdited.subscribe((t=>{var e,n;if(t.id===this.funcCall.id&&t.options.title){this.path=`?id=${this.funcCall.id}`;const i=jt(t);this.name.indexOf(" — ")<0?this.name=`${this.name} — ${null!==(e=t.options.title)&&void 0!==e?e:i}`:this.name=`${this.name.substring(0,this.name.indexOf(" — "))} — ${null!==(n=t.options.title)&&void 0!==n?n:i}`}})),t.events.onViewRemoving.subscribe((e=>{if(e.args.view==this){const e=t.shell.dockManager.findNode(this.historyRoot);e?(t.shell.dockManager.close(e),i=!0):i=!1}})),t.events.onCurrentViewChanged.subscribe((()=>{var e;if(t.shell.v==this)i&&((null===(e=this.historyBlock)||void 0===e?void 0:e.compactMode)?t.shell.dockManager.dock(this.historyRoot,"right",null,"History",.3):t.shell.dockManager.dock(this.historyRoot,"down",null,"History",.3));else{const e=t.shell.dockManager.findNode(this.historyRoot);e?(t.shell.dockManager.close(e),i=!0):i=!1}}))),e.empty(this.historyRoot),this.historyRoot.style.removeProperty("justify-content"),this.historyRoot.append(n.root),this.historyBlock=n,n.root}buildRibbonPanels(){const n=e.iconFA("history",(()=>{var e;t.shell.dockManager.findNode(this.historyRoot)||((null===(e=this.historyBlock)||void 0===e?void 0:e.compactMode)?t.shell.dockManager.dock(this.historyRoot,"right",null,"History",.3):t.shell.dockManager.dock(this.historyRoot,"down",null,"History",.3),this.historyRoot.parentElement.classList.add("ui-box"),this.historyRoot.classList.add("ui-box"))})),i=e.iconFA("save",(()=>Ie(this,void 0,void 0,(function*(){yield this.onSaveClick()}))),"Save current state"),o=e.comboPopup(e.iconFA("arrow-to-bottom"),this.getFormats(),this.exportRun.bind(this)),r=e.iconFA("edit",(()=>{this.historyBlock&&this.lastCall&&this.historyBlock.showEditDialog(this.historyBlock.history.get(this.funcCall.id))}),"Edit this run metadata"),l=this.isHistorical.subscribe((t=>{t?(e.setDisplay(o,!K(this.funcCall)),e.setDisplay(r,!0)):(a()(o).hide(),a()(r).hide())}));if(this.subs.push(l),e.tooltip.bind(o,(()=>"inconsistent"===this.consistencyState.value&&this.mandatoryConsistent?"Current run is inconsistent. Export feature is disabled.":null)),!this.options.isTabbed&&this.mandatoryConsistent){const t=this.consistencyState.pipe((0,s.distinctUntilChanged)()).subscribe((t=>{"inconsistent"===t?(a()(o).addClass("d4-disabled"),a()(o.lastChild).css("color","unset")):(a()(o).removeClass("d4-disabled"),a()(o.lastChild).removeProp("color"))}));this.subs.push(t)}const u=[[...!this.options.isTabbed&&this.isHistoryEnabled&&this.options.historyEnabled?[n]:[],...!this.options.isTabbed&&this.isHistoryEnabled?[i]:[],...!this.options.isTabbed&&this.isExportEnabled&&this.exportConfig&&this.exportConfig.supportedFormats.length>0?[o]:[],...this.options.isTabbed?[]:[r]]];return this.setRibbonPanels(u),u}buildRibbonMenu(){if(this.ribbonMenu.clear(),!(this.exportConfig||this.reportBug||this.requestFeature||this.getHelp||this.getMocks||this.getTemplates))return;const t=this.ribbonMenu.group("Model");if(this.getMocks&&this.getMocks.length>0)if(1===this.getMocks.length)t.item("Input data mock",this.getMocks[0].action);else{const e=t.group("Input data mocks");this.getMocks.forEach((t=>{e.item(t.mockName,t.action)})),t.endGroup()}if(this.getTemplates&&this.getTemplates.length>0)if(1===this.getTemplates.length)t.item("Input data template",this.getTemplates[0].action);else{const e=t.group("Input data templates");this.getTemplates.forEach((t=>{e.item(t.name,t.action)})),t.endGroup()}this.isExportEnabled&&this.exportConfig&&this.exportConfig.supportedFormats.length>0&&t.group("Export").items(this.getFormats(),this.exportRun.bind(this)).endGroup(),this.reportBug&&t.item("Report a bug",(()=>this.reportBug())),this.requestFeature&&t.item("Request a feature",(()=>this.requestFeature())),this.getHelp&&t.item("Help",(()=>this.getHelp()));const n=t.group("Test runner");n.item("Execute Test JSON",(()=>this.importRunJsonDialog())),n.item("Update Test JSON",(()=>this.importRunJsonDialog(!0))),t.endGroup(),t.item("Record the screen",Ee),this.getAbout&&t.item("About",(()=>Ie(this,void 0,void 0,(function*(){const t=yield this.getAbout();if(t){const n=e.dialog("Current version");t.split("\n").forEach((t=>n.add(e.label(t)))),n.onOK((()=>{})),n.getButton("CANCEL").style.display="none",n.show({center:!0})}}))))}exportRun(t){return Ie(this,void 0,void 0,(function*(){if(t!==Te)o.Utils.download(this.exportConfig.filename(t),yield this.exportConfig.export(t));else{const t=yield this.exportRunJson();t&&o.Utils.download(this.defaultExportFilename("","json"),t)}}))}getFormats(){var t,e;return[...null!==(e=null===(t=this.exportConfig)||void 0===t?void 0:t.supportedFormats)&&void 0!==e?e:[],Te]}onBeforeSaveRun(t){return Ie(this,void 0,void 0,(function*(){}))}onAfterSaveRun(t){return Ie(this,void 0,void 0,(function*(){}))}saveRun(t){return Ie(this,void 0,void 0,(function*(){let e=et(t);yield this.onBeforeSaveRun(e),K(t)&&(e=yield J(t)),e.id&&e.newId();const n=yield pt.saveRun(e),i=yield pt.loadRun(n.id);return this.options.historyEnabled&&this.isHistoryEnabled&&this.historyBlock&&this.historyBlock.addRun(i),this.linkFunccall(i),this.isHistorical.next(!0),yield this.onAfterSaveRun(n),n}))}onBeforeDeleteRun(t){return Ie(this,void 0,void 0,(function*(){}))}onAfterDeleteRun(t){return Ie(this,void 0,void 0,(function*(){}))}deleteRun(t){return Ie(this,void 0,void 0,(function*(){return yield this.onBeforeDeleteRun(t),yield pt.deleteRun(t),yield this.onAfterDeleteRun(t),t.id}))}onBeforeLoadRun(){return Ie(this,void 0,void 0,(function*(){}))}onAfterLoadRun(t){return Ie(this,void 0,void 0,(function*(){}))}loadRun(t){return Ie(this,void 0,void 0,(function*(){yield this.onBeforeLoadRun();const e=yield pt.loadRun(t);return this.lastCall=et(e),this.linkFunccall(e),this.isHistorical.next(!0),yield this.onAfterLoadRun(e),e}))}onBeforeRun(t){return Ie(this,void 0,void 0,(function*(){}))}onAfterRun(t){return Ie(this,void 0,void 0,(function*(){}))}run(){return Ie(this,void 0,void 0,(function*(){if(!this.funcCall)throw new Error("The correspoding function is not specified");yield this.onBeforeRun(this.funcCall);const e=o.TaskBarProgressIndicator.create("Calculating...");try{this.funcCall.newId(),yield this.funcCall.call(),yield this.onAfterRun(this.funcCall),this.lastCall=et(this.funcCall),this.options.isTabbed||this.runningOnInput||!this.isHistoryEnabled||(yield this.saveRun(this.funcCall))}catch(e){t.shell.error(e.toString())}finally{e.close()}}))}exportRunJson(){return Ie(this,void 0,void 0,(function*(){if(this._lastCall)return le(yield at(this._lastCall,this),0)}))}importRunJsonDialog(){return Ie(this,arguments,void 0,(function*(t=!1){const n=new Ot("JSON file",null,null,"application/json"),i={modal:!0,fullScreen:!0,width:500,height:200,center:!0};if(!(yield new Promise(((t,o)=>{e.dialog({title:"Import Run JSON"}).add(e.div([e.inputs([n])])).onOK((()=>t(!0))).onCancel((()=>t(!1))).show(i)})))||!n.value)return;const o=(r=yield n.value.text(),JSON.parse(r,ue));var r;t?(yield this.executeTest(o,!0),yield this.isHistorical.pipe((0,s.filter)((t=>t)),(0,s.take)(1),(0,s.delay)(0)).toPromise(),yield this.exportRun(Te)):yield this.executeTest(o)}))}executeTest(t){return Ie(this,arguments,void 0,(function*(t,e=!1){yield Ae(t,this,{updateMode:e,interactive:!0})}))}get compareCustomizer(){var t;return null!==(t=this.func.options.compareCustomizer)&&void 0!==t?t:null}get comparatorFunc(){var t;return null!==(t=this.func.options.comparatorFunc)&&void 0!==t?t:null}get uploadFunc(){var t;return null!==(t=this.func.options.uploadFunc)&&void 0!==t?t:null}get runningOnInput(){return"true"===this.func.options.runOnInput}get runningOnStart(){return"true"===this.func.options.runOnOpen}get mainParams(){return this.func.options.mainParams?JSON.parse(this.func.options.mainParams):null}get mandatoryConsistent(){var t;return"true"===(null===(t=this.parentCall)||void 0===t?void 0:t.func.options.mandatoryConsistent)}get hasContextHelp(){return!!this.func.options.help}getContextHelp(){return Ie(this,void 0,void 0,(function*(){const e=this.func.options.help;if(!e)return null;if(this.helpCache)return this.helpCache;const n=`System:AppData/${e}`;if(yield t.dapi.files.exists(n)){const e=yield t.dapi.files.readAsText(n);return this.helpCache=e,e}const i=`${t.shell.user.name}.home/${e}`;if(yield t.dapi.files.exists(i)){const e=yield t.dapi.files.readAsText(i);return this.helpCache=e,e}return null}))}get features(){var t;return JSON.parse(null!==(t=this.func.options.features)&&void 0!==t?t:"{}")}getFeature(t,e){var n;return this.features instanceof Array?this.features.includes(t):this.features instanceof Object&&null!==(n=this.features[t])&&void 0!==n?n:e}get isExportEnabled(){return this.getFeature("export",!0)}get isHistoryEnabled(){return this.getFeature("history",!0)}get isSaEnabled(){return this.getFeature("sens-analysis",!1)}get hasUploadMode(){return this.getFeature("upload",!1)}get isFittingEnabled(){return this.getFeature("fitting",!1)}}var Re=Uint8Array,Oe=Uint16Array,Pe=Uint32Array,ke=new Re([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Fe=new Re([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ne=new Re([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Le=function(t,e){for(var n=new Oe(31),i=0;i<31;++i)n[i]=e+=1<<t[i-1];var o=new Pe(n[30]);for(i=1;i<30;++i)for(var s=n[i];s<n[i+1];++s)o[s]=s-n[i]<<5|i;return[n,o]},Be=Le(ke,2),Ve=Be[0],Me=Be[1];Ve[28]=258,Me[258]=28;for(var _e=Le(Fe,0),De=(_e[0],_e[1]),je=new Oe(32768),$e=0;$e<32768;++$e){var He=(43690&$e)>>>1|(21845&$e)<<1;He=(61680&(He=(52428&He)>>>2|(13107&He)<<2))>>>4|(3855&He)<<4,je[$e]=((65280&He)>>>8|(255&He)<<8)>>>1}var Ue=function(t,e,n){for(var i=t.length,o=0,s=new Oe(e);o<i;++o)t[o]&&++s[t[o]-1];var r,a=new Oe(e);for(o=0;o<e;++o)a[o]=a[o-1]+s[o-1]<<1;if(n){r=new Oe(1<<e);var l=15-e;for(o=0;o<i;++o)if(t[o])for(var u=o<<4|t[o],c=e-t[o],d=a[t[o]-1]++<<c,p=d|(1<<c)-1;d<=p;++d)r[je[d]>>>l]=u}else for(r=new Oe(i),o=0;o<i;++o)t[o]&&(r[o]=je[a[t[o]-1]++]>>>15-t[o]);return r},Ye=new Re(288);for($e=0;$e<144;++$e)Ye[$e]=8;for($e=144;$e<256;++$e)Ye[$e]=9;for($e=256;$e<280;++$e)Ye[$e]=7;for($e=280;$e<288;++$e)Ye[$e]=8;var We=new Re(32);for($e=0;$e<32;++$e)We[$e]=5;var Ge=Ue(Ye,9,0),qe=Ue(We,5,0),ze=function(t){return(t+7)/8|0},Je=function(t,e,n){(null==e||e<0)&&(e=0),(null==n||n>t.length)&&(n=t.length);var i=new(2==t.BYTES_PER_ELEMENT?Oe:4==t.BYTES_PER_ELEMENT?Pe:Re)(n-e);return i.set(t.subarray(e,n)),i},Ke=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Ze=function(t,e,n){var i=new Error(e||Ke[t]);if(i.code=t,Error.captureStackTrace&&Error.captureStackTrace(i,Ze),!n)throw i;return i},Xe=function(t,e,n){n<<=7&e;var i=e/8|0;t[i]|=n,t[i+1]|=n>>>8},Qe=function(t,e,n){n<<=7&e;var i=e/8|0;t[i]|=n,t[i+1]|=n>>>8,t[i+2]|=n>>>16},tn=function(t,e){for(var n=[],i=0;i<t.length;++i)t[i]&&n.push({s:i,f:t[i]});var o=n.length,s=n.slice();if(!o)return[ln,0];if(1==o){var r=new Re(n[0].s+1);return r[n[0].s]=1,[r,1]}n.sort((function(t,e){return t.f-e.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=o-1;)a=n[n[u].f<n[d].f?u++:d++],l=n[u!=c&&n[u].f<n[d].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var p=s[0].s;for(i=1;i<o;++i)s[i].s>p&&(p=s[i].s);var h=new Oe(p+1),f=en(n[c-1],h,0);if(f>e){i=0;var m=0,v=f-e,g=1<<v;for(s.sort((function(t,e){return h[e.s]-h[t.s]||t.f-e.f}));i<o;++i){var y=s[i].s;if(!(h[y]>e))break;m+=g-(1<<f-h[y]),h[y]=e}for(m>>>=v;m>0;){var b=s[i].s;h[b]<e?m-=1<<e-h[b]++-1:++i}for(;i>=0&&m;--i){var w=s[i].s;h[w]==e&&(--h[w],++m)}f=e}return[new Re(h),f]},en=function(t,e,n){return-1==t.s?Math.max(en(t.l,e,n+1),en(t.r,e,n+1)):e[t.s]=n},nn=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Oe(++e),i=0,o=t[0],s=1,r=function(t){n[i++]=t},a=1;a<=e;++a)if(t[a]==o&&a!=e)++s;else{if(!o&&s>2){for(;s>138;s-=138)r(32754);s>2&&(r(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(r(o),--s;s>6;s-=6)r(8304);s>2&&(r(s-3<<5|8208),s=0)}for(;s--;)r(o);s=1,o=t[a]}return[n.subarray(0,i),e]},on=function(t,e){for(var n=0,i=0;i<e.length;++i)n+=t[i]*e[i];return n},sn=function(t,e,n){var i=n.length,o=ze(e+2);t[o]=255&i,t[o+1]=i>>>8,t[o+2]=255^t[o],t[o+3]=255^t[o+1];for(var s=0;s<i;++s)t[o+s+4]=n[s];return 8*(o+4+i)},rn=function(t,e,n,i,o,s,r,a,l,u,c){Xe(e,c++,n),++o[256];for(var d=tn(o,15),p=d[0],h=d[1],f=tn(s,15),m=f[0],v=f[1],g=nn(p),y=g[0],b=g[1],w=nn(m),A=w[0],C=w[1],I=new Oe(19),S=0;S<y.length;++S)I[31&y[S]]++;for(S=0;S<A.length;++S)I[31&A[S]]++;for(var T=tn(I,7),E=T[0],x=T[1],R=19;R>4&&!E[Ne[R-1]];--R);var O,P,k,F,N=u+5<<3,L=on(o,Ye)+on(s,We)+r,B=on(o,p)+on(s,m)+r+14+3*R+on(I,E)+(2*I[16]+3*I[17]+7*I[18]);if(N<=L&&N<=B)return sn(e,c,t.subarray(l,l+u));if(Xe(e,c,1+(B<L)),c+=2,B<L){O=Ue(p,h,0),P=p,k=Ue(m,v,0),F=m;var V=Ue(E,x,0);for(Xe(e,c,b-257),Xe(e,c+5,C-1),Xe(e,c+10,R-4),c+=14,S=0;S<R;++S)Xe(e,c+3*S,E[Ne[S]]);c+=3*R;for(var M=[y,A],_=0;_<2;++_){var D=M[_];for(S=0;S<D.length;++S){var j=31&D[S];Xe(e,c,V[j]),c+=E[j],j>15&&(Xe(e,c,D[S]>>>5&127),c+=D[S]>>>12)}}}else O=Ge,P=Ye,k=qe,F=We;for(S=0;S<a;++S)if(i[S]>255){j=i[S]>>>18&31,Qe(e,c,O[j+257]),c+=P[j+257],j>7&&(Xe(e,c,i[S]>>>23&31),c+=ke[j]);var $=31&i[S];Qe(e,c,k[$]),c+=F[$],$>3&&(Qe(e,c,i[S]>>>5&8191),c+=Fe[$])}else Qe(e,c,O[i[S]]),c+=P[i[S]];return Qe(e,c,O[256]),c+P[256]},an=new Pe([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ln=new Re(0),un=function(){for(var t=new Int32Array(256),e=0;e<256;++e){for(var n=e,i=9;--i;)n=(1&n&&-306674912)^n>>>1;t[e]=n}return t}(),cn=function(){var t=-1;return{p:function(e){for(var n=t,i=0;i<e.length;++i)n=un[255&n^e[i]]^n>>>8;t=n},d:function(){return~t}}},dn=function(t,e,n,i,o){return function(t,e,n,i,o,s){var r=t.length,a=new Re(i+r+5*(1+Math.ceil(r/7e3))+o),l=a.subarray(i,a.length-o),u=0;if(!e||r<8)for(var c=0;c<=r;c+=65535){var d=c+65535;d>=r&&(l[u>>3]=s),u=sn(l,u+1,t.subarray(c,d))}else{for(var p=an[e-1],h=p>>>13,f=8191&p,m=(1<<n)-1,v=new Oe(32768),g=new Oe(m+1),y=Math.ceil(n/3),b=2*y,w=function(e){return(t[e]^t[e+1]<<y^t[e+2]<<b)&m},A=new Pe(25e3),C=new Oe(288),I=new Oe(32),S=0,T=0,E=(c=0,0),x=0,R=0;c<r;++c){var O=w(c),P=32767&c,k=g[O];if(v[P]=k,g[O]=P,x<=c){var F=r-c;if((S>7e3||E>24576)&&F>423){u=rn(t,l,0,A,C,I,T,E,R,c-R,u),E=S=T=0,R=c;for(var N=0;N<286;++N)C[N]=0;for(N=0;N<30;++N)I[N]=0}var L=2,B=0,V=f,M=P-k&32767;if(F>2&&O==w(c-M))for(var _=Math.min(h,F)-1,D=Math.min(32767,c),j=Math.min(258,F);M<=D&&--V&&P!=k;){if(t[c+L]==t[c+L-M]){for(var $=0;$<j&&t[c+$]==t[c+$-M];++$);if($>L){if(L=$,B=M,$>_)break;var H=Math.min(M,$-2),U=0;for(N=0;N<H;++N){var Y=c-M+N+32768&32767,W=Y-v[Y]+32768&32767;W>U&&(U=W,k=Y)}}}M+=(P=k)-(k=v[P])+32768&32767}if(B){A[E++]=268435456|Me[L]<<18|De[B];var G=31&Me[L],q=31&De[B];T+=ke[G]+Fe[q],++C[257+G],++I[q],x=c+L,++S}else A[E++]=t[c],++C[t[c]]}}u=rn(t,l,s,A,C,I,T,E,R,c-R,u),!s&&7&u&&(u=sn(l,u+1,ln))}return Je(a,0,i+ze(u)+o)}(t,null==e.level?6:e.level,null==e.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(t.length)))):12+e.mem,n,i,!o)},pn=function(t,e){var n={};for(var i in t)n[i]=t[i];for(var i in e)n[i]=e[i];return n},hn=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function fn(t,e){return dn(t,e||{},0,0)}var mn=function(t,e,n,i){for(var o in t){var s=t[o],r=e+o,a=i;Array.isArray(s)&&(a=pn(i,s[1]),s=s[0]),s instanceof Re?n[r]=[s,a]:(n[r+="/"]=[new Re(0),a],mn(s,r,n,i))}},vn="undefined"!=typeof TextEncoder&&new TextEncoder,gn="undefined"!=typeof TextDecoder&&new TextDecoder;try{gn.decode(ln,{stream:!0})}catch(t){}function yn(t,e){if(e){for(var n=new Re(t.length),i=0;i<t.length;++i)n[i]=t.charCodeAt(i);return n}if(vn)return vn.encode(t);var o=t.length,s=new Re(t.length+(t.length>>1)),r=0,a=function(t){s[r++]=t};for(i=0;i<o;++i){if(r+5>s.length){var l=new Re(r+8+(o-i<<1));l.set(s),s=l}var u=t.charCodeAt(i);u<128||e?a(u):u<2048?(a(192|u>>6),a(128|63&u)):u>55295&&u<57344?(a(240|(u=65536+(1047552&u)|1023&t.charCodeAt(++i))>>18),a(128|u>>12&63),a(128|u>>6&63),a(128|63&u)):(a(224|u>>12),a(128|u>>6&63),a(128|63&u))}return Je(s,0,r)}var bn=function(t){var e=0;if(t)for(var n in t){var i=t[n].length;i>65535&&Ze(9),e+=i+4}return e},wn=function(t,e,n,i,o,s,r,a){var l=i.length,u=n.extra,c=a&&a.length,d=bn(u);hn(t,e,null!=r?33639248:67324752),e+=4,null!=r&&(t[e++]=20,t[e++]=n.os),t[e]=20,e+=2,t[e++]=n.flag<<1|(s<0&&8),t[e++]=o&&8,t[e++]=255&n.compression,t[e++]=n.compression>>8;var p=new Date(null==n.mtime?Date.now():n.mtime),h=p.getFullYear()-1980;if((h<0||h>119)&&Ze(10),hn(t,e,h<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>>1),e+=4,-1!=s&&(hn(t,e,n.crc),hn(t,e+4,s<0?-s-2:s),hn(t,e+8,n.size)),hn(t,e+12,l),hn(t,e+14,d),e+=16,null!=r&&(hn(t,e,c),hn(t,e+6,n.attrs),hn(t,e+10,r),e+=14),t.set(i,e),e+=l,d)for(var f in u){var m=u[f],v=m.length;hn(t,e,+f),hn(t,e+2,v),t.set(m,e+4),e+=4+v}return c&&(t.set(a,e),e+=c),e};function An(t,e){e||(e={});var n={},i=[];mn(t,"",n,e);var o=0,s=0;for(var r in n){var a=n[r],l=a[0],u=a[1],c=0==u.level?0:8,d=(I=yn(r)).length,p=u.comment,h=p&&yn(p),f=h&&h.length,m=bn(u.extra);d>65535&&Ze(11);var v=c?fn(l,u):l,g=v.length,y=cn();y.p(l),i.push(pn(u,{size:l.length,crc:y.d(),c:v,f:I,m:h,u:d!=r.length||h&&p.length!=f,o,compression:c})),o+=30+d+m+g,s+=76+2*(d+m)+(f||0)+g}for(var b=new Re(s+22),w=o,A=s-o,C=0;C<i.length;++C){var I=i[C];wn(b,I.o,I,I.f,I.u,I.c.length);var S=30+I.f.length+bn(I.extra);b.set(I.c,I.o+S),wn(b,o,I,I.f,I.u,I.c.length,I.o,I.m),o+=16+S+(I.m?I.m.length:0)}return function(t,e,n,i,o){hn(t,e,101010256),hn(t,e+8,n),hn(t,e+10,n),hn(t,e+12,i),hn(t,e+16,o)}(b,o,i.length,A,w),b}"function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout&&setTimeout;var Cn=n(933),In={};In.styleTagTransform=St(),In.setAttributes=wt(),In.insert=yt().bind(null,"head"),In.domAPI=vt(),In.insertStyleElement=Ct(),ft()(Cn.A,In),Cn.A&&Cn.A.locals&&Cn.A.locals;var Sn=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const Tn=t=>{var e,n;return null!==(n=null===(e=t.options)||void 0===e?void 0:e.friendlyName)&&void 0!==n?n:t.func.name},En=t=>{var e;return null!==(e=t.customId)&&void 0!==e?e:t.funcName};class xn extends xe{set currentTabName(t){this.stepTabs.getPane(t)&&(this.stepTabs.currentPane=this.stepTabs.getPane(t))}getStepView(t){var e;return null===(e=this.steps[t])||void 0===e?void 0:e.view}getRunningUpdates(){return[]}disableSetters(t){}constructor(t,e,n={historyEnabled:!0,isTabbed:!1,skipInit:!1}){super(t,n),this.initialConfig=e,this.steps={},this.onStepCompleted=new c.Subject,this.isUpdating=new c.BehaviorSubject(!1),this.pipelineViewExportExtensions=()=>({Archive:"zip","Single Excel":"xlsx"}),this.pipelineViewExportFormats=()=>["Archive","Single Excel"],this.pipelineViewExport=t=>Sn(this,void 0,void 0,(function*(){if(!this.stepTabs)throw new Error("Set step tabs please for export");if("Archive"===t){const t={};for(const e of Object.values(this.steps).filter((t=>t.visibility.value===S.VISIBLE))){this.stepTabs.currentPane=this.stepTabs.getPane(Tn(e)),yield new Promise((t=>setTimeout(t,100)));const n=yield e.view.exportConfig.export("Excel");t[e.view.exportConfig.filename("Excel")]=[new Uint8Array(yield n.arrayBuffer()),{level:0}]}return new Blob([An(t)])}if("Single Excel"===t){yield o.Utils.loadJsCss(["/js/common/exceljs.min.js"]);const t=window.ExcelJS,e="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",n=new t.Workbook,i=(t,e,n)=>{let i=`${Tn(n)}>${e}`;i.length>31&&(i=`${i.slice(0,31)}`);let o=2;for(;t.worksheets.some((t=>t.name.toLowerCase()===i.toLowerCase()));){let t=`${Tn(n)}>${e}`;t.length>31-`-${o}`.length&&(t=`${t.slice(0,31-`-${o}`.length)}`),i=`${t}-${o}`,o++}return i};for(const e of Object.values(this.steps).filter((t=>t.visibility.value===S.VISIBLE))){const o=new t.Workbook;this.stepTabs.currentPane=this.stepTabs.getPane(Tn(e)),yield new Promise((t=>setTimeout(t,100))),yield o.xlsx.load(yield(yield e.view.exportConfig.export("Excel")).arrayBuffer()),o.eachSheet((t=>{const s=i(n,t.name,e),r=n.addWorksheet("New sheet");r.model=t.model,r.name=s,t.getImages().forEach((t=>{const e=n.addImage(o.getImage(t.imageId));r.addImage(e,t.range)}))}))}return new Blob([yield n.xlsx.writeBuffer()],{type:e})}throw new Error("This format is not supported")})),this.exportConfig={supportedExtensions:this.pipelineViewExportExtensions(),supportedFormats:this.pipelineViewExportFormats(),export:this.pipelineViewExport,filename:this.defaultExportFilename},this.helpFiles={}}init(){return Sn(this,void 0,void 0,(function*(){yield this.loadFuncCallById(),this.initialConfig.forEach(((t,e)=>{var n;this.steps[En(t)]={idx:e,visibility:new c.BehaviorSubject(null!==(n=t.hiddenOnInit)&&void 0!==n?n:S.VISIBLE),ability:new c.BehaviorSubject(this.isHistorical.value||0===e?T.ENABLED:T.DISABLED),options:{friendlyName:t.friendlyName,helpUrl:t.helpUrl,customId:t.customId}}})),this.subs.push(t.functions.onAfterRunAction.pipe((0,s.filter)((t=>Object.values(this.steps).some((({view:e})=>{var n;return(null===(n=null==e?void 0:e.funcCall)||void 0===n?void 0:n.id)===(null==t?void 0:t.id)&&!!t}))))).subscribe((t=>{this.onStepCompleted.next(t),"true"!==t.func.options.isMain&&t.func.nqName!==this.initialConfig[this.initialConfig.length-1].funcName||this.run()})));const n=this.initialConfig.map((e=>Sn(this,void 0,void 0,(function*(){return{stepScript:yield t.functions.eval(e.funcName),stepId:En(e)}})))),i=yield Promise.all(n);i.forEach((t=>{this.steps[t.stepId].func=t.stepScript})),this.root.classList.remove("ui-panel");const r={},l="Compute:PipelineStepEditor",u=i.map((e=>Sn(this,void 0,void 0,(function*(){const n=e.stepScript.script?(t=>{const e=t.script,n=e.indexOf("editor:");if(n<0)return l;const i=e.indexOf("\n",n);return e.substring(n+7,i).trim()})(e.stepScript):l;return r[n]||(r[n]=yield t.functions.eval(n.split(" ").join(""))),this.steps[e.stepId].editor=n,Promise.resolve()}))));yield Promise.all(u);const d=i.map((n=>Sn(this,void 0,void 0,(function*(){const i=this.steps[n.stepId],l=n.stepScript.prepare(),u=r[i.editor];yield this.onBeforeStepFuncCallApply(n.stepScript.nqName,l,u);const d=yield u.apply({call:l}),p=e.button("Back",(()=>{}),"Go to the previous step");a()(p).addClass("ui-btn-nav");const h=e.button("Next",(()=>{}),"Go to the next step");a()(h).addClass("ui-btn-nav"),this.syncNavButtons(i,p,h),d.setNavigationButtons([p,h]),this.steps[n.stepId].view=d;const f=this.steps[n.stepId],m=()=>{Object.values(this.steps).forEach((t=>{t.idx>f.idx&&t.visibility.value===S.VISIBLE&&t.ability.value===T.ENABLED&&t.ability.next(T.DISABLED)}))},v=f.view.funcCallReplaced.pipe((0,s.switchMap)((()=>{const t=[...f.view.funcCall.inputParams.values()].map((t=>t.onChanged.pipe((0,s.mapTo)(t))));return(0,c.merge)(...t)}))),g=v.subscribe(m);this.subs.push(g);const y=v.pipe((0,s.filter)((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&t.value)),(0,s.switchMap)((t=>t.value.onDataChanged))).subscribe(m);this.subs.push(y);const b=t.functions.onAfterRunAction.pipe((0,s.filter)((t=>f.view.funcCall&&t&&!!t.id&&f.view.funcCall.id===t.id)),(0,s.withLatestFrom)(f.visibility,f.ability),(0,s.filter)((([,t,e])=>!(t===S.HIDDEN||e===T.DISABLED)))).subscribe((()=>{const t=(()=>Object.values(this.steps).find((t=>t.idx>f.idx&&t.visibility.value===S.VISIBLE&&t.ability.value===T.ENABLED))?null:Object.values(this.steps).find((t=>t.idx>f.idx&&t.visibility.value===S.VISIBLE&&t.ability.value===T.DISABLED)))();null==t||t.ability.next(T.ENABLED)}));return this.subs.push(b),yield this.onAfterStepFuncCallApply(n.stepScript.nqName,l,d),d})))),p=yield Promise.all(d),h=(0,c.combineLatest)(p.map((t=>t.isHistorical))).subscribe((t=>{t.some(((t,e)=>{var n;return!t&&(null===(n=Object.values(this.steps).find((t=>t.idx===e)))||void 0===n?void 0:n.visibility.value)===S.VISIBLE}))&&this.isHistorical.value&&this.isHistorical.next(!1)}));this.subs.push(h);const f=this.isUpdating.subscribe((t=>{for(const e of Object.values(this.steps)){const n=e.view;(null==n?void 0:n.blockRuns)&&n.blockRuns.next(t)}}));this.subs.push(f),yield this.onFuncCallReady(),this.isReady.next(!0),this.loadHelp().then((()=>{this.buildRibbonPanels();const e=()=>{const t=this.findCurrentStep();t&&this.helpFiles[t.func.nqName]&&this.getHelpState().then((e=>{"opened"===e&&this.showHelpWithDelay(t)}))},n=t.events.onCurrentViewChanged.pipe((0,s.filter)((()=>t.shell.v==this))).subscribe(e);e(),this.subs.push(n)}))}))}loadHelp(){return Sn(this,void 0,void 0,(function*(){return Promise.all(Object.values(this.steps).map((e=>Sn(this,void 0,void 0,(function*(){var n,i,o,s;const r=null!==(i=null===(n=e.options)||void 0===n?void 0:n.helpUrl)&&void 0!==i?i:e.func.options.help;if(r){const n=`System:AppData/${this.func.package.name}/${r}`,i=(yield t.dapi.files.exists(n))?yield t.dapi.files.readAsText(n):yield e.view.getContextHelp();i&&(this.helpFiles[null!==(s=null===(o=e.options)||void 0===o?void 0:o.customId)&&void 0!==s?s:e.func.nqName]=i)}})))))}))}syncNavButtons(t,e,n){let i,o;n.addEventListener("click",(()=>{i&&(this.currentTabName=Tn(i))})),e.addEventListener("click",(()=>{o&&(this.currentTabName=Tn(o))}));const r=this.getPipelineStateChanges().pipe((0,s.startWith)(!0),(0,s.debounceTime)(0)).subscribe((()=>{i=this.getNextStep(t),o=this.getPreviousStep(t),i?(a()(n).show(),i.ability.value===T.DISABLED&&a()(n).addClass("d4-disabled"),i.ability.value===T.ENABLED&&a()(n).removeClass("d4-disabled")):a()(n).hide(),o?(a()(e).show(),o.ability.value===T.DISABLED&&a()(e).addClass("d4-disabled"),o.ability.value===T.ENABLED&&a()(e).removeClass("d4-disabled")):a()(e).hide()}));this.subs.push(r)}getPreviousStep(t){return Object.values(this.steps).slice().reverse().find((e=>e.idx<t.idx&&e.visibility.value===S.VISIBLE))}getNextStep(t){return Object.values(this.steps).find((e=>e.idx>t.idx&&e.visibility.value===S.VISIBLE))}getPipelineStateChanges(){const t=Object.values(this.steps).flatMap((t=>[t.ability,t.visibility]));return(0,c.merge)(...t).pipe((0,s.mapTo)(!0))}onComparisonLaunch(e){return Sn(this,void 0,void 0,(function*(){const n=t.shell.v.parentCall,i=yield Promise.all(e.map((t=>pt.loadChildRuns(t.id)))),o=yield Promise.all(i.map((t=>{var e;return null!==(e=t.childRuns.find((t=>"true"===t.func.options.isMain)))&&void 0!==e?e:t.childRuns.find((t=>t.func.nqName===this.initialConfig[this.initialConfig.length-1].funcName))})).map((t=>pt.loadRun(t.id)))),s=[...t.shell.views].find((t=>t.type===v)),r=yield re.fromComparedRuns(o,o[0].func,{parentView:s,parentCall:n});t.shell.addView(r)}))}onBeforeStepFuncCallApply(t,e,n){return Sn(this,void 0,void 0,(function*(){}))}onAfterStepFuncCallApply(t,e,n){return Sn(this,void 0,void 0,(function*(){}))}buildIO(){const t=Object.values(this.steps).reduce(((t,e)=>Object.assign(Object.assign({},t),{[Tn(e)]:e.view.root})),{}),n=e.tabControl(t),i=Object.values(this.steps).map((t=>{const i=e.iconFA("exclamation-circle",null,"This step has inconsistent inputs");return a()(i).css({color:"var(--orange-2)","margin-left":"3px","padding-top":"1px"}),n.getPane(Tn(t)).header.appendChild(i),t.view.consistencyState.subscribe((t=>{"consistent"===t&&a()(i).hide(),"inconsistent"===t&&a()(i).show()}))}));this.subs.push(...i);const o=Object.values(this.steps).map((t=>t.view.consistencyState)),s=(0,c.merge)(...o).subscribe((()=>{o.map((t=>t.value)).some((t=>"inconsistent"===t))?this.consistencyState.next("inconsistent"):this.consistencyState.next("consistent")}));this.subs.push(s);const r=n.panes[0].header.parentElement;r.classList.add("d4-ribbon","pipeline-view"),r.classList.remove("d4-tab-header-stripe"),r.firstChild.remove();for(let t=0;t<n.panes.length;t++)n.panes[t].header.classList.add("d4-ribbon-name"),n.panes[t].header.classList.remove("d4-tab-header");return n.panes[0].header.style.marginLeft="12px",n.root.style.height="100%",n.root.style.width="100%",this.stepTabs=n,this.initialConfig.forEach((t=>{const e=En(t);this.subs.push(this.steps[e].visibility.subscribe((t=>{t===S.VISIBLE&&a()(this.stepTabs.getPane(Tn(this.steps[e])).header).css("display","inherit"),t===S.HIDDEN&&a()(this.stepTabs.getPane(Tn(this.steps[e])).header).hide()})))})),Object.values(this.steps).forEach((t=>{this.subs.push(t.ability.subscribe((e=>{e===T.ENABLED&&a()(this.stepTabs.getPane(Tn(t)).header).removeClass("d4-disabled"),e===T.DISABLED&&a()(this.stepTabs.getPane(Tn(t)).header).addClass("d4-disabled")})))})),this.hideSteps(...this.initialConfig.filter((t=>t.hiddenOnInit===S.HIDDEN)).map((t=>t.funcName))),n.root}showHelpWithDelay(n){return Sn(this,void 0,void 0,(function*(){t.shell.windows.help.visible=!0,yield new Promise((t=>setTimeout(t,100))),t.shell.windows.help.showHelp(e.markdown(this.helpFiles[n.func.nqName]))}))}findCurrentStep(){return Object.values(this.steps).find((t=>Tn(t)===this.stepTabs.currentPane.name))}buildHistoryBlock(){const e=super.buildHistoryBlock(),n=this.historyBlock.afterRunDeleted.subscribe((e=>Sn(this,void 0,void 0,(function*(){(yield t.dapi.functions.calls.allPackageVersions().filter(`options.parentCallId="${e.id}"`).list()).map((t=>Sn(this,void 0,void 0,(function*(){return pt.deleteRun(t)}))))}))));return this.subs.push(n),e}getHelpState(){return Sn(this,void 0,void 0,(function*(){return"closed"===(yield t.dapi.userDataStorage.getValue(E,`${this.func.name}_help_state`))?"closed":"opened"}))}saveHelpState(e){return Sn(this,void 0,void 0,(function*(){return t.dapi.userDataStorage.postValue(E,`${this.func.name}_help_state`,e)}))}buildRibbonPanels(){const n=e.iconFA("info",(()=>Sn(this,void 0,void 0,(function*(){const t=this.findCurrentStep();t&&this.helpFiles[t.func.nqName]&&(yield this.showHelpWithDelay(t),this.saveHelpState("opened"))})))),i=()=>{var e,i,o;const s=this.findCurrentStep(),r=[[...super.buildRibbonPanels().flat(),...s&&(null===(o=this.steps[null!==(i=null===(e=s.options)||void 0===e?void 0:e.customId)&&void 0!==i?i:s.func.nqName].options)||void 0===o?void 0:o.helpUrl)?[n]:[]],...s?s.view.buildRibbonPanels():[]];return this.setRibbonPanels(r),s&&this.helpFiles[s.func.nqName]&&t.shell.windows.help.visible&&this.showHelpWithDelay(s),r};if(!this.isReady.value){const n=this.stepTabs.onTabChanged.subscribe(i),o=t.events.onEvent("grok-panels-changed").pipe((0,s.filter)((()=>t.shell.v===this))).subscribe((()=>Sn(this,void 0,void 0,(function*(){const n=yield this.getHelpState();if(t.shell.windows.help.visible&&"closed"===n)this.saveHelpState("opened");else if(!t.shell.windows.help.visible&&"opened"===n){const n=e.iconFA("info");return a()(n).css("margin","0px 3px"),t.shell.info(e.span(["You can open help panel by clicking the",n,"button on the ribbon menu"])),void this.saveHelpState("closed")}}))));this.subs.push(n,o)}return i()}saveRun(t){return Sn(this,void 0,void 0,(function*(){let e=_t(t);yield this.onBeforeSaveRun(e),K(t)&&(e=yield J(t)),e.id&&e.newId();const n=Object.values(this.steps).filter((t=>t.visibility.value===S.VISIBLE)).map((t=>Sn(this,void 0,void 0,(function*(){var n,i;const o=t.view.funcCall;return o.options.parentCallId=e.id,(null===(n=t.options)||void 0===n?void 0:n.customId)&&(o.options.customId=null===(i=t.options)||void 0===i?void 0:i.customId),yield t.view.saveRun(o),Promise.resolve()}))));yield Promise.all(n),e.options.title&&(e.options.title=`${e.options.title} (copy)`);const i=yield pt.saveRun(e),o=yield pt.loadRun(i.id);return this.options.historyEnabled&&this.isHistoryEnabled&&this.historyBlock&&this.historyBlock.addRun(yield pt.loadRun(i.id)),this.linkFunccall(o),this.isHistorical.next(!0),yield this.onAfterSaveRun(e),i}))}loadRun(t){return Sn(this,void 0,void 0,(function*(){const{parentRun:e,childRuns:n}=yield pt.loadChildRuns(t),i=Object.values(this.steps).filter((t=>t.visibility.value===S.VISIBLE)).findIndex((t=>Tn(t)===this.stepTabs.currentPane.name));yield this.onBeforeLoadRun();for(const t of Object.values(this.steps)){const e=n.filter((e=>e.func.nqName===t.func.nqName));if(0===e.length&&(t.visibility.next(S.HIDDEN),t.ability.next(T.DISABLED)),1===e.length&&(yield t.view.loadRun(e[0].id),t.visibility.next(S.VISIBLE),K(e[0])?t.ability.next(T.DISABLED):t.ability.next(T.ENABLED)),e.length>1){const n=e.find((e=>{var n;return e.options.customId===(null===(n=t.options)||void 0===n?void 0:n.customId)}));yield t.view.loadRun(n.id),t.visibility.next(S.VISIBLE),K(n)?t.ability.next(T.DISABLED):t.ability.next(T.ENABLED)}}const o=Object.values(this.steps).find((t=>t.ability.value===T.DISABLED&&t.visibility.value===S.VISIBLE)),s=null!=o?o:Object.values(this.steps)[0];if(s.ability.next(T.ENABLED),o){let t=this.getNextStep(o);for(;t;)t.ability.next(T.DISABLED),t=this.getNextStep(t)}this.lastCall=e,this.linkFunccall(e),this.isHistorical.next(!0);const r=Object.values(this.steps).filter((t=>t.visibility.value==S.VISIBLE)).at(i);return r&&r.ability.value===T.ENABLED?this.currentTabName=Tn(r):this.currentTabName=Tn(s),yield this.onAfterLoadRun(e),e}))}hideSteps(...t){return Sn(this,void 0,void 0,(function*(){t.forEach((t=>{this.steps[t].visibility.next(S.HIDDEN)}))}))}showSteps(...t){return Sn(this,void 0,void 0,(function*(){t.forEach((t=>{this.steps[t].visibility.next(S.VISIBLE)}))}))}exportRunJson(){return Sn(this,void 0,void 0,(function*(){if(this._lastCall){const t={isPipeline:!0};for(const[e,n]of Object.entries(this.steps)){const i=n.view.lastCall;i&&(t[e]=yield at(i,n.view))}return le(t,0)}}))}executeTest(t){return Sn(this,arguments,void 0,(function*(t,e=!1){yield we(t,this,{updateMode:e,interactive:!0})}))}getStepViewRuns(t){return this.onStepCompleted.pipe((0,s.filter)((e=>e.func.nqName===t)),(0,s.map)((()=>this.getStepView(t))))}}var Rn=n(362),On={};On.styleTagTransform=St(),On.setAttributes=wt(),On.insert=yt().bind(null,"head"),On.domAPI=vt(),On.insertStyleElement=Ct(),ft()(Rn.A,On),Rn.A&&Rn.A.locals&&Rn.A.locals;var Pn,kn;!function(t){t.INCORRECT_SIZE_TYPE="Size must be an integer.",t.SIZE_MUST_BE_POSITIVE="Size must be positive."}(Pn||(Pn={})),function(t){t[t.BATCH_SIZE=100]="BATCH_SIZE",t[t.MS_TO_SLEEP=10]="MS_TO_SLEEP"}(kn||(kn={}));const Fn=t=>new Promise(((e,n)=>setTimeout(e,t)));function Nn(t){if(!Number.isInteger(t))throw new Error(Pn.INCORRECT_SIZE_TYPE);if(t<1)throw new Error(Pn.SIZE_MUST_BE_POSITIVE)}function Ln(t){return e=this,n=void 0,s=function*(){const e=[],n=o.TaskBarProgressIndicator.create("Running sensitivity analysis...");n.cancelable=!0;let i=0;const s=t.length;for(let o=0;o<s&&(e.push(yield t[o].call()),1===o&&(n.update(100*o/s,"Running sensitivity analysis..."),yield Fn(10*kn.MS_TO_SLEEP)),++i,!n.canceled);++o)i>=kn.BATCH_SIZE&&(n.update(100*o/s,"Running sensitivity analysis..."),yield Fn(kn.MS_TO_SLEEP),i=0);return n.close(),e},new((i=void 0)||(i=Promise))((function(t,o){function r(t){try{l(s.next(t))}catch(t){o(t)}}function a(t){try{l(s.throw(t))}catch(t){o(t)}}function l(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i((function(t){t(n)}))).then(r,a)}l((s=s.apply(e,n||[])).next())}));var e,n,i,s}class Bn{constructor(t=1,e=1){Nn(t),Nn(e),this.N=t,this.d=e,this.A=this.generateMatrix(t,e),this.B=this.generateMatrix(t,e),this.AB=this.createMixMatrax(this.A,this.B)}generateMatrix(t,e){const n=new Array(e);for(let i=0;i<e;++i){n[i]=new Float32Array(t);for(let e=0;e<t;++e)n[i][e]=Math.random()}return n}createMixMatrax(t,e){const n=this.d,i=new Array(n);for(let o=0;o<n;++o){i[o]=new Array(0);for(let s=0;s<n;++s)o!==s?i[o].push(t[s]):i[o].push(e[s])}return i}getRow(t,e){const n=new Float32Array(this.d);for(let i=0;i<this.d;++i)n[i]=t[i][e];return n}getRowOfMatrixA(t){return this.getRow(this.A,t)}getRowOfMatrixB(t){return this.getRow(this.B,t)}getRowOfMatrixAB(t,e){return this.getRow(this.AB[t],e)}getConcatenatedColumns(){const t=new Array(0),e=this.N,n=this.d;for(let i=0;i<n;++i){const o=new Float32Array(e*(n+2));o.set(this.A[i]),o.set(this.B[i],e);for(let t=0;t<n;++t)o.set(this.AB[t][i],2*e+e*t);t.push(o)}return t}}const Vn="Unsupported output type.";function Mn(e,n){const i=e.rowCount,s=n.value.row;if(null!==s)return e.columns.names().map((t=>({idx:s,columnName:t})));const r=e.col(n.value.colName);if(null===r)return t.shell.warning(`Output dataframe "${e.name}" doesn't contain the "${n.value.colName}" column. The last row is analyzed.`),e.columns.names().map((t=>({idx:i-1,columnName:t})));if(r.type!==o.COLUMN_TYPE.INT&&r.type!==o.COLUMN_TYPE.FLOAT)return t.shell.warning(`Non-supported type of the "${n.value.colName}" column: ${r.type}. Last row of the output dataframe "${e.name}" is analyzed.`),e.columns.names().map((t=>({idx:i-1,columnName:t})));const a=r.getRawData(),l=n.value.colValue;let u,c=0,d=Math.abs(a[0]-l);for(let t=1;t<i;++t)u=Math.abs(a[t]-l),u<d&&(d=u,c=t);return e.columns.names().map((t=>({idx:c,columnName:t})))}function _n(t,e){var n,i,s;if(t.length<1)throw new Error("Funccall array is empty.");const r=t.length,a=function(t,e){const n=[];for(const i of e)i.prop.propertyType==o.TYPE.DATA_FRAME?n.push({prop:i.prop,elements:Mn(t.outputs[i.prop.name],i)}):n.push({prop:i.prop,elements:[]});return n}(t[0],e),l=function(t,e,n){var i;const s=[];for(const r of e){const e=r.prop,a=e.name;switch(e.propertyType){case o.TYPE.BIG_INT:case o.TYPE.INT:case o.TYPE.FLOAT:s.push(o.Column.fromType(e.propertyType,a,n));break;case o.TYPE.DATA_FRAME:const l=t.outputs[a];if(r.elements)for(const t of r.elements)s.push(o.Column.fromType(null===(i=l.col(t.columnName))||void 0===i?void 0:i.type,t.columnName,n));break;default:throw new Error(Vn)}}return o.DataFrame.fromColumns(s)}(t[0],a,r);for(let e=0;e<r;++e)for(const r of a){const a=r.prop,u=a.name,c=t[e];switch(a.propertyType){case o.TYPE.BIG_INT:case o.TYPE.INT:case o.TYPE.FLOAT:null===(n=l.col(u))||void 0===n||n.set(e,c.outputs[u]);break;case o.TYPE.DATA_FRAME:const t=c.outputs[u],a=t.rowCount-1;if(r.elements)for(const n of r.elements)null===(i=l.col(n.columnName))||void 0===i||i.set(e,null===(s=t.col(n.columnName))||void 0===s?void 0:s.get(-1!==n.idx?n.idx:a));break;default:throw new Error(Vn)}}return l}function Dn(t,e){const n=function(t,e){return e.forEach((e=>{t.forEach((t=>{t.name===e.name&&(t.name=`${t.name} (input)`,e.name=`${e.name} (output)`)}))})),t.concat(e)}(t,e),i=n.length;if(0===i)return o.DataFrame.create();const s=o.DataFrame.fromColumns([n[0]]);for(let t=1;t<i;++t)n[t].name=s.columns.getUnusedName(n[t].name),s.columns.add(n[t]);return s}class jn{constructor(t,e,n,i,s){Nn(s),this.samplesCount=s,this.fixedInputs=e,this.func=t;const r=function(t,e){const n=e.length,i=function(t,e){return new Bn(t,e).getConcatenatedColumns()}(t,n);return[...Array(n).keys()].map((t=>function(t,e){var n;const i=e.length,s=o.Column.fromType(t.prop.propertyType,null!==(n=t.prop.caption)&&void 0!==n?n:t.prop.name,i),r=s.getRawData(),a=t.max-t.min;for(let n=0;n<i;++n)r[n]=t.min+a*e[n];return s}(e[t],i[t])))}(s,n);this.dimension=n.length,this.variedInputs=[...Array(this.dimension).keys()].map((t=>({prop:n[t].prop,min:n[t].min,max:n[t].max,column:r[t]}))),this.runsCount=s*(this.dimension+2),this.funcCalls=[];for(let n=0;n<this.runsCount;++n){const i={};for(const t of e)i[t.name]=t.value;for(const t of this.variedInputs)i[t.prop.name]=t.column.get(n);this.funcCalls.push(t.prepare(i))}this.outputsOfInterest=i}getSobolIndeces(t){const e=this.dimension,n=this.samplesCount,i=new Float32Array(e),s=new Float32Array(e),r=t.getRawData(),a=2*n;let l=0,u=0;for(let t=0;t<a;++t)l+=r[t],u+=r[t]*r[t];const c=l/a,d=u/a-c*c;if(0===d)i.fill(0),s.fill(0);else for(let t=0;t<e;++t){let e=0,o=0,a=0;for(let i=0;i<n;++i)a=r[(2+t)*n+i]-r[i],e+=r[n+i]*a,o+=a*a;i[t]=e/(n*d),s[t]=o/(2*n*d)}return{firstOrder:o.Column.fromFloat32Array(t.name,i),totalOrder:o.Column.fromFloat32Array(t.name,s)}}perform(){return t=this,e=void 0,i=function*(){this.funcCalls=yield Ln(this.funcCalls);const t=this.variedInputs.map((t=>t.column)),e=_n(this.funcCalls,this.outputsOfInterest).columns.toList(),n=Dn(t,e);n.name=`Sensitivity Analysis of ${this.func.friendlyName}`;const i=e.map((t=>this.getSobolIndeces(t))),s=o.Column.fromStrings("input",t.map((t=>t.name))),r=[s],a=[s];for(const t of i)r.push(t.firstOrder),a.push(t.totalOrder);const l=o.DataFrame.fromColumns(r);l.name="First order Sobol' indices";const u=o.DataFrame.fromColumns(a);return u.name="Total order Sobol' indices",{funcEvalResults:n,funcCalls:this.funcCalls,firstOrderSobolIndices:l,totalOrderSobolIndices:u}},new((n=void 0)||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}));var t,e,n,i}}class $n{constructor(t,e,n,i,s){Nn(s),this.func=t;const r=function(t,e){var n;const i=[];for(const s of e){const e=o.Column.fromType(s.prop.propertyType,null!==(n=s.prop.caption)&&void 0!==n?n:s.prop.name,t),r=e.getRawData(),a=s.max-s.min;for(let e=0;e<t;++e)r[e]=s.min+a*Math.random();i.push(e)}return i}(s,n);this.dimension=n.length,this.variedInputs=[...Array(this.dimension).keys()].map((t=>({prop:n[t].prop,min:n[t].min,max:n[t].max,column:r[t]}))),this.funcCalls=[];for(let n=0;n<s;++n){const i={};for(const t of e)i[t.name]=t.value;for(const t of this.variedInputs)i[t.prop.name]=t.column.get(n);this.funcCalls.push(t.prepare(i))}this.outputsOfInterest=i}perform(){return t=this,e=void 0,i=function*(){this.funcCalls=yield Ln(this.funcCalls);const t=Dn(this.variedInputs.map((t=>t.column)),_n(this.funcCalls,this.outputsOfInterest).columns.toList());return t.name=`Sensitivity Analysis of ${this.func.friendlyName}`,{funcEvalResults:t,funcCalls:this.funcCalls}},new((n=void 0)||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}));var t,e,n,i}}var Hn,Un,Yn=n(993),Wn={};Wn.styleTagTransform=St(),Wn.setAttributes=wt(),Wn.insert=yt().bind(null,"head"),Wn.domAPI=vt(),Wn.insertStyleElement=Ct(),ft()(Yn.A,Wn),Yn.A&&Yn.A.locals&&Yn.A.locals,function(t){t[t.COR_PLOT=.5]="COR_PLOT",t[t.PC_PLOT=.6]="PC_PLOT",t[t.GRAPH=.6]="GRAPH",t[t.BAR_CHART=.2]="BAR_CHART"}(Hn||(Hn={})),function(t){t.METHOD="`Method`",t.SAMPLES="`Samples`"}(Un||(Un={}));const Gn=`# Sensitivity Analysis\n\nSensitivity Analysis runs the computation multiple times with varying inputs, \nand analyzes the relationship between inputs and outputs.\n\nUse one of the following methods:\n\n* [Monte Carlo](https://en.wikipedia.org/wiki/Monte_Carlo_method) explores a function \nat randomly taken points\n\n* [Sobol](https://en.wikipedia.org/wiki/Variance-based_sensitivity_analysis)\ndecomposes output variance into fractions, which can be attributed to inputs\n\n* **Grid** studies a function at the points of a grid with the specified step\n\n## Monte Carlo\n\nOnce you've chosen it in ${Un.METHOD}\n\n* Set in ${Un.SAMPLES} the number of random points \n\n* Use switchers to specify varied inputs and outputs to be analyzed\n\n* Press **Run** or <i class="fas fa-play"></i> on the top panel. You will get \n\n * [Correlation plot](https://datagrok.ai/help/visualize/viewers/correlation-plot) for exploring\ncorrelations between varied inputs and the specified outputs\n\n * [PC plot](https://datagrok.ai/help/visualize/viewers/pc-plot) visualizing multivariate data\nand providing variations of the selected inputs & outputs\n\n * [Line chart](https://datagrok.ai/help/visualize/viewers/line-chart) or \n[Scatterplot](https://datagrok.ai/help/visualize/viewers/scatter-plot) (dependently on the varied\ninputs count) showing a behavior of each output separately\n\n * [Grid](https://datagrok.ai/help/visualize/viewers/grid) containing inputs and outputs values \nof each function evaluation\n\n* Press <i class="grok-icon fal fa-question"></i> on the top panel to learn more about \n[Sensitivity Analysis](https://datagrok.ai/help/compute/#sensitivity-analysis)\n\n## Sobol\n\nThis method performs \n[variance-based sensitivity analysis](https://en.wikipedia.org/wiki/Variance-based_sensitivity_analysis). \nIt provides the same visualizations \nas **Monte Carlo** and [bar charts](https://datagrok.ai/help/visualize/viewers/bar-chart) showing \nSobol' indices:\n\n* First-order indices indicate the contribution to the output variance of varying each input alone\n\n* Total-order indices measure the contribution to the output variance of each input,\n including all variance caused by its interactions with any other inputs\n \n ## Grid\n \n This method provides the same visualization as the previous ones. Unlike them, it evaluates a function \n at the points of uniform grid within the specified ranges.`;var qn=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const zn=[o.TYPE.INT,o.TYPE.BIG_INT,o.TYPE.FLOAT,o.TYPE.BOOL,o.TYPE.DATA_FRAME],Jn=[o.TYPE.INT,o.TYPE.BIG_INT,o.TYPE.FLOAT,o.TYPE.BOOL,o.TYPE.DATA_FRAME];var Kn,Zn;!function(t){t.GRID_ANALYSIS="Grid",t.RANDOM_ANALYSIS="Monte Carlo",t.SOBOL_ANALYSIS="Sobol"}(Kn||(Kn={})),function(t){t.LAST_ROW="Last row",t.FIRST_ROW="First row",t.ALL_COLUMNS="",t.BY_COL_VAL="By value in column"}(Zn||(Zn={}));const Xn=()=>e.div([],"sa-switch-input");class Qn{static fromEmpty(e){return qn(this,arguments,void 0,(function*(e,n={parentView:void 0,parentCall:void 0}){const i=[...t.shell.views].find((t=>t.type===v)),o=yield re.fromComparedRuns([],e,{parentView:i,parentCall:n.parentCall});t.shell.addView(o),new this(e,o,n)}))}constructor(t,n,i={parentView:void 0,parentCall:void 0,configFunc:void 0}){this.func=t,this.options=i,this.generateInputFields=t=>{const n={analysisType:{input:e.input.choice("Method",{value:Kn.RANDOM_ANALYSIS,items:[Kn.RANDOM_ANALYSIS,Kn.SOBOL_ANALYSIS,Kn.GRID_ANALYSIS],onValueChanged:()=>{const t=n.analysisType.input.value;n.analysisType.value.next(t),this.updateRunWidgetsState(),this.setAnalysisInputTooltip(),this.store.analysisInputs.samplesCount.input.setTooltip(this.samplesCountTooltip())}}),value:new c.BehaviorSubject(Kn.RANDOM_ANALYSIS)},samplesCount:{input:e.input.int("Samples",{value:10,onValueChanged:()=>{n.samplesCount.value=n.samplesCount.input.value,this.updateRunWidgetsState()}}),value:10}};n.analysisType.input.root.insertBefore(Xn(),n.analysisType.input.captionLabel),n.samplesCount.input.root.insertBefore(Xn(),n.samplesCount.input.captionLabel);const i=(t,e)=>void 0===t.options[e]?Vt(t):Number(t.options[e]),s=(t,n,i=!0)=>{const o=e.input.toggle(" ",{value:t,onValueChanged:()=>n(o.value)});return a()(o.root).addClass("sa-switch-input"),a()(o.captionLabel).hide(),e.tooltip.bind(o.root,(()=>i?o.value?"Switch to mark input as immutable":"Switch to mark input as mutable":o.value?"Switch to mark output as not requiring analysis":"Switch to mark output as requiring analysis")),o},r=t.inputs.reduce(((t,r)=>{const l=i(r,"default");switch(r.propertyType){case o.TYPE.INT:case o.TYPE.BIG_INT:case o.TYPE.FLOAT:const u=s(!1,(t=>{f.isChanging.next(t),this.updateRunWidgetsState()})),d=s(!1,(t=>{f.isChanging.next(t),this.updateRunWidgetsState()})),p={type:r.propertyType,prop:r,const:{input:(()=>{var t;const n=e.input.float(null!==(t=r.caption)&&void 0!==t?t:r.name,{value:Vt(r),onValueChanged:()=>f.const.value=n.value});return n.root.insertBefore(d.root,n.captionLabel),n.addPostfix(r.options.units),n})(),value:Vt(r)},min:{input:(()=>{var t;const n=e.input.float(`${null!==(t=r.caption)&&void 0!==t?t:r.name} min`,{value:i(r,"min"),onValueChanged:()=>f.min.value=n.value});return n.root.insertBefore(u.root,n.captionLabel),n.addPostfix(r.options.units),n})(),value:i(r,"min")},max:{input:(()=>{var t;const n=e.input.float(`${null!==(t=r.caption)&&void 0!==t?t:r.name} max`,{value:i(r,"max"),onValueChanged:()=>f.max.value=n.value});return n.addPostfix(r.options.units),n})(),value:i(r,"max")},lvl:{input:e.input.int("Samples",{value:3,onValueChanged:()=>{const t=p.lvl.input.value;f.lvl.value=t,this.updateRunWidgetsState()}}),value:3},isChanging:new c.BehaviorSubject(!1)};[p.max.input,p.lvl.input].forEach((t=>{t.root.insertBefore(Xn(),t.captionLabel),a()(t.root).removeProp("display")}));const h=[p.lvl.input];t[r.name]=Object.assign(Object.assign({},p),{constForm:[p.const.input],saForm:[p.min.input,p.max.input,...h]});const f=t[r.name];f.isChanging.subscribe((t=>{u.notify=!1,u.value=t,u.notify=!0,d.notify=!1,d.value=t,d.notify=!0})),(0,c.combineLatest)([p.isChanging,n.analysisType.value]).subscribe((([t,e])=>{t?(f.constForm.forEach((t=>a()(t.root).hide())),f.saForm.forEach((t=>a()(t.root).css("display","flex"))),h.forEach((t=>e===Kn.GRID_ANALYSIS?a()(t.root).css("display","flex"):a()(t.root).hide()))):(f.constForm.forEach((t=>a()(t.root).css("display","flex"))),f.saForm.forEach((t=>a()(t.root).hide())))}));break;case o.TYPE.BOOL:const m=s(!1,(t=>{g.isChanging.next(t),this.updateRunWidgetsState()})),v={type:r.propertyType,prop:r,const:{input:(()=>{var t,n;const i=e.input.bool(`${null!==(t=r.caption)&&void 0!==t?t:r.name}`,{value:null!==(n=Vt(r))&&void 0!==n&&n,onValueChanged:()=>g.const.value=v.const.input.value});return i.root.insertBefore(m.root,i.captionLabel),i})(),value:l},isChanging:new c.BehaviorSubject(!1),lvl:1};t[r.name]=Object.assign(Object.assign({},v),{constForm:[v.const.input],saForm:[]});const g=t[r.name];g.isChanging.subscribe((t=>{g.lvl=t?2:1}));break;default:const y=Xn(),b={input:(()=>{const t=e.input.forProperty(r,void 0,{onValueChanged:t=>b.value=t.value});return t.root.insertBefore(y,t.captionLabel),t.addPostfix(r.options.units),t})(),value:Vt(r)};t[r.name]={const:b,constForm:[b.input],saForm:[],type:r.propertyType,prop:r,isChanging:new c.BehaviorSubject(!1)}}return t}),{}),l=t.outputs.reduce(((t,n)=>{const i={prop:n,input:(()=>{var t;const r=null!==(t=n.caption)&&void 0!==t?t:n.name;let a;n.propertyType===o.TYPE.DATA_FRAME?(a=e.input.choice(r,{value:Zn.LAST_ROW,items:[Zn.LAST_ROW,Zn.FIRST_ROW,Zn.BY_COL_VAL],onValueChanged:()=>{const t=a.value;i.value.returning=t,i.analysisInputs.forEach((e=>{e.root.hidden=t!==Zn.BY_COL_VAL})),a.setTooltip(this.getOutputTooltip(r,t))}}),a.setTooltip(this.getOutputTooltip(r,Zn.LAST_ROW))):(a=e.input.forProperty(n),a.setTooltip("Scalar")),a.addCaption(r);const l=Jn.includes(n.propertyType)?s(!0,(t=>{i.isInterest.next(t),i.analysisInputs.forEach((t=>{t.root.hidden=i.value.returning!==Zn.BY_COL_VAL})),this.updateRunWidgetsState(),n.propertyType===o.TYPE.DATA_FRAME&&a.setTooltip(t?this.getOutputTooltip(r,Zn.LAST_ROW):"Dataframe")}),!1).root:Xn();return a.root.insertBefore(l,a.captionLabel),a})(),analysisInputs:n.propertyType===o.TYPE.DATA_FRAME?[(()=>{var t;const o=e.input.string("Column",{value:Zn.ALL_COLUMNS,onValueChanged:()=>{i.value.colName=o.value}});return o.root.insertBefore(Xn(),o.captionLabel),o.root.hidden=!0,o.setTooltip(`Name of column of the '${null!==(t=n.caption)&&void 0!==t?t:n.name}' dataframe`),o})(),(()=>{var t;const o=e.input.float("Value",{value:0,onValueChanged:()=>{i.value.colValue=o.value}});return o.root.insertBefore(Xn(),o.captionLabel),o.root.hidden=!0,o.setTooltip(`Value specifying the '${null!==(t=n.caption)&&void 0!==t?t:n.name}' dataframe row`),o})()]:[],value:{returning:Zn.LAST_ROW,colName:Zn.ALL_COLUMNS,colValue:0},isInterest:new c.BehaviorSubject(!0)};return a()(i.input.input).css("visibility","hidden"),i.prop.propertyType===o.TYPE.DATA_FRAME&&i.isInterest.subscribe((t=>{i.analysisInputs.forEach((e=>t?a()(e.root).show():a()(e.root).hide())),a()(i.input.input).css("visibility",t?"visible":"hidden")})),t[n.name]=i,t}),{});return{analysisInputs:n,inputs:r,outputs:l}},this.openedViewers=[],this.gridSubscription=null,this.store=this.generateInputFields(this.func),this.runButton=e.bigButton("Run",(()=>qn(this,void 0,void 0,(function*(){return yield this.runAnalysis()})))),this.runIcon=e.iconFA("play",(()=>qn(this,void 0,void 0,(function*(){return yield this.runAnalysis()})))),this.runIcon.style.color="var(--green-2)",this.runIcon.classList.add("fas"),this.helpIcon=e.iconFA("question",(()=>{window.open("https://datagrok.ai/help/compute.md#sensitivity-analysis","_blank")}),"Open help in a new tab");const s=this.buildFormWithBtn();this.runButton.disabled=!this.canEvaluationBeRun(),this.runIcon.hidden=this.runButton.disabled,this.addTooltips(),this.comparisonView=n,this.comparisonView.dockManager.dock(s,o.DOCK_TYPE.LEFT,null,`${this.func.name} - Sensitivity Analysis`,.25),this.comparisonView.grid.columns.byName("Run name").visible=!1;const r=this.comparisonView.getRibbonPanels();r.push([this.helpIcon,this.runIcon]),this.comparisonView.setRibbonPanels(r),this.comparisonView.helpUrl="https://datagrok.ai/help/compute.md#sensitivity-analysis",this.tableDockNode=this.comparisonView.dockManager.findNode(this.comparisonView.grid.root);const l=e.markdown(Gn);l.style.padding="10px",l.style.overflow="auto",this.helpMdNode=this.comparisonView.dockManager.dock(l,o.DOCK_TYPE.FILL,this.tableDockNode,"About")}closeOpenedViewers(){for(const t of this.openedViewers)t.close();this.openedViewers.splice(0),this.helpMdNode&&(this.helpMdNode.detachFromParent(),this.helpMdNode.container.destroy(),this.helpMdNode=void 0),this.gridSubscription&&(this.gridSubscription.unsubscribe(),this.gridSubscription=null)}getFuncCallCount(t,e){let n=0;switch(t.analysisType.value.value){case Kn.GRID_ANALYSIS:let i=1;const s=t=>t.type===o.TYPE.INT||t.type===o.TYPE.BIG_INT||t.type===o.TYPE.FLOAT;for(const t of Object.values(e))t.isChanging.value&&(i*=s(t)?t.lvl.value:t.lvl,++n);return 0===n?0:i;case Kn.RANDOM_ANALYSIS:return t.samplesCount.value;case Kn.SOBOL_ANALYSIS:for(const t of Object.keys(e))e[t].isChanging.value&&++n;return 0===n?0:(n+2)*t.samplesCount.value;default:return 0}}getFuncCallCountAsString(){if(!this.canEvaluationBeRun())return"0";const t=this.getFuncCallCount(this.store.analysisInputs,this.store.inputs);return t<1e3?String(t):t<1e6?String(Math.ceil(t/10)/100)+"k":t<1e9?String(Math.ceil(t/1e4)/100)+"m":String(Math.ceil(t/1e7)/100)+"b"}updateRunWidgetsState(){this.runButton.textContent=`Run (${this.getFuncCallCountAsString()})`,this.runButton.disabled=!this.canEvaluationBeRun(),this.runIcon.hidden=this.runButton.disabled}buildFormWithBtn(){let t="Misc";const n=Object.values(this.store.inputs).reduce(((n,i)=>{const o=i.prop;return o.category!==t&&(n.append(e.h2(o.category)),t=o.category),n.append(...i.constForm.map((t=>t.root)),...i.saForm.map((t=>t.root))),n}),e.div([this.store.analysisInputs.analysisType.input,this.store.analysisInputs.samplesCount.input],{style:{"overflow-y":"scroll",width:"100%"}}));a()(n).addClass("ui-form");const i=e.h2("Outputs");n.appendChild(i),t="Misc";const o=Object.values(this.store.outputs).reduce(((n,i)=>{const o=i.prop;return o.category!==t&&(n.append(e.h2(o.category)),t=o.category),n.append(i.input.root,...i.analysisInputs.map((t=>t.root))),n}),n);this.store.analysisInputs.analysisType.value.subscribe((t=>{t===Kn.GRID_ANALYSIS?a()(this.store.analysisInputs.samplesCount.input.root).hide():(a()(i).show(),a()(o).show(),a()(this.store.analysisInputs.samplesCount.input.root).show())}));let s=!1;for(const t of Object.keys(this.store.outputs))if(this.store.outputs[t].isInterest.value){s=!0;break}s||this.store.outputs[Object.keys(this.store.outputs)[0]].isInterest.next(!0),this.updateRunWidgetsState();const r=e.buttonsInput([this.runButton]);return n.appendChild(r),a()(n).css({"padding-left":"12px","overflow-y":"scroll","padding-right":"4px"}),n}setAnalysisInputTooltip(){let t;switch(this.store.analysisInputs.analysisType.value.value){case Kn.GRID_ANALYSIS:t="Grid analysis: the function is evaluated with respect to the selected inputs varying within the specified ranges";break;case Kn.RANDOM_ANALYSIS:t="Monte Carlo simulation: the function is evaluated with respect to random variation of the selected inputs within the specified ranges";break;case Kn.SOBOL_ANALYSIS:t="Variance-based sensitivity analysis: the Sobol' indices are computed";break;default:t="Unknown method!"}this.store.analysisInputs.analysisType.input.setTooltip(t)}getOutputTooltip(t,e){switch(e){case Zn.FIRST_ROW:return`To analyze first row of the '${t}' dataframe`;case Zn.LAST_ROW:return`To analyze last row of the '${t}' dataframe`;case Zn.BY_COL_VAL:return`To analyze "${t}"'s row defined by custom value in column`;default:return""}}samplesCountTooltip(){switch(this.store.analysisInputs.analysisType.value.value){case Kn.RANDOM_ANALYSIS:return"Input sets count";case Kn.SOBOL_ANALYSIS:return"Sample size for the Sobol' indices computation";default:return"Unknown method!"}}addTooltips(){var t;this.setAnalysisInputTooltip(),e.tooltip.bind(this.runButton,(()=>`Run sensitivity analysis: the function is evaluated ${this.getFuncCallCount(this.store.analysisInputs,this.store.inputs)} times`)),e.tooltip.bind(this.runIcon,(()=>`Run sensitivity analysis: the function is evaluated ${this.getFuncCallCount(this.store.analysisInputs,this.store.inputs)} times`)),this.store.analysisInputs.samplesCount.input.setTooltip(this.samplesCountTooltip());for(const e of Object.keys(this.store.inputs)){const n=this.store.inputs[e].prop.propertyType;if(n===o.TYPE.BOOL||n===o.TYPE.STRING)continue;const i=this.store.inputs[e],s=null!==(t=i.prop.caption)&&void 0!==t?t:i.prop.name;i.const.input.setTooltip(`'${s}' value`),i.min.input.setTooltip(`Min value of '${s}'`),i.max.input.setTooltip(`Max value of '${s}'`),i.lvl.input.setTooltip(`Number of samples along the axis '${s}'`)}}isAnyInputSelected(){for(const t of Object.keys(this.store.inputs))if(this.store.inputs[t].isChanging.value)return!0;return!1}isAnyOutputSelected(){for(const t of Object.keys(this.store.outputs))if(this.store.outputs[t].isInterest.value)return!0;return!1}canEvaluationBeRun(){return this.isAnyInputSelected()&&this.isAnyOutputSelected()}runAnalysis(){return qn(this,void 0,void 0,(function*(){if(this.canEvaluationBeRun())switch(this.store.analysisInputs.analysisType.value.value){case Kn.GRID_ANALYSIS:yield this.runGridAnalysis();break;case Kn.RANDOM_ANALYSIS:yield this.runRandomAnalysis();break;case Kn.SOBOL_ANALYSIS:yield this.runSobolAnalysis()}}))}getFixedInputColumns(t){return Object.values(this.store.inputs).filter((t=>!zn.includes(t.type)||!t.isChanging.value)).map((e=>{var n;return o.Column.fromList(e.type,null!==(n=e.prop.caption)&&void 0!==n?n:e.prop.name,Array(t).fill(e.const.value))}))}runSobolAnalysis(){return qn(this,void 0,void 0,(function*(){const n={func:this.func,fixedInputs:this.getFixedInputs().map((t=>({name:t,value:this.store.inputs[t].const.value}))),variedInputs:this.getVariedInputs().map((t=>{const e=this.store.inputs[t];return{prop:e.prop,min:e.min.value,max:e.max.value}})),samplesCount:this.store.analysisInputs.samplesCount.value||1},i=this.getOutputsOfInterest(),s=new jn(n.func,n.fixedInputs,n.variedInputs,i,n.samplesCount),r=yield s.perform();this.closeOpenedViewers();const l=r.funcEvalResults,u=r.funcCalls,c=r.firstOrderSobolIndices,d=r.totalOrderSobolIndices,p=c.columns.names();this.comparisonView.dataFrame=l;const h=l.columns.names(),f=this.getFixedInputColumns(l.rowCount);for(const t of f)t.name=l.columns.getUnusedName(`${t.name} (fixed)`),l.columns.add(t);this.comparisonView.grid.columns.setVisible([h[0]]),this.comparisonView.grid.columns.setVisible(h),this.comparisonView.grid.props.rowHeight=25;const m=o.Viewer.correlationPlot(l,{xColumnNames:h,yColumnNames:h}),v=this.comparisonView.dockManager.dock(m,o.DOCK_TYPE.LEFT,this.tableDockNode,"",Hn.COR_PLOT);this.openedViewers.push(m);const g=o.Viewer.pcPlot(l,{columnNames:h});this.comparisonView.dockManager.dock(g,o.DOCK_TYPE.DOWN,v,"",Hn.PC_PLOT),this.openedViewers.push(g);const y=this.getOutputNameForScatterPlot(h,l,n.variedInputs.length),b=1===n.variedInputs.length?o.Viewer.lineChart(l,this.getLineChartOpt(h)):o.Viewer.scatterPlot(l,this.getScatterOpt(h,y));this.openedViewers.push(b),this.comparisonView.dockManager.dock(b,o.DOCK_TYPE.DOWN,this.tableDockNode,"",Hn.GRAPH);const w=o.Viewer.barChart(c,this.getBarChartOpt(c.name,p[0],y)),A=this.comparisonView.dockManager.dock(w,o.DOCK_TYPE.RIGHT,void 0,"",Hn.BAR_CHART),C=o.Viewer.barChart(d,this.getBarChartOpt(d.name,p[0],y));this.comparisonView.dockManager.dock(C,o.DOCK_TYPE.DOWN,A),this.openedViewers=this.openedViewers.concat([w,C]),this.gridSubscription=this.comparisonView.grid.onCellClick.subscribe((n=>{var i;const s=u[null!==(i=n.tableRowIndex)&&void 0!==i?i:0],r=[...s.outputParams.values()].filter((t=>o.TYPES_SCALAR.has(t.property.propertyType))),l=o.HtmlTable.create(r,(t=>{var e;return[null!==(e=t.property.caption)&&void 0!==e?e:t.property.name,s.outputs[t.property.name],t.property.options.units]})).root,c=[...s.outputParams.values()].filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME)).reduce(((t,e)=>{var n;const i=Dt(e.property).config,r=s.outputs[e.name],l=null!==(n=e.property.caption)&&void 0!==n?n:e.property.name;return i.map((e=>{const n=e.type,i=o.Viewer.fromType(n,r);i.setOptions(e),a()(i.root).css({width:"100%"}),t[l]?t[l].push(i.root):t[l]=[i.root]})),t}),{});let d,p;r.length>0?(p=1,d=Object.assign({"Output scalars":[l]},c)):(p=0,d=Object.assign({},c));const h=e.accordion();a()(h.root).css({width:"100%"}),Object.entries(d).map((t=>{h.addPane(t[0],(()=>e.divV(t[1])))})),h.panes[p].expanded=!0,t.shell.o=h.root}))}))}getFixedInputs(){return Object.keys(this.store.inputs).filter((t=>!zn.includes(this.store.inputs[t].type)||!this.store.inputs[t].isChanging.value))}getVariedInputs(){return Object.keys(this.store.inputs).filter((t=>!!zn.includes(this.store.inputs[t].type)&&this.store.inputs[t].isChanging.value))}runRandomAnalysis(){return qn(this,void 0,void 0,(function*(){const n={func:this.func,fixedInputs:this.getFixedInputs().map((t=>({name:t,value:this.store.inputs[t].const.value}))),variedInputs:this.getVariedInputs().map((t=>{const e=this.store.inputs[t];return{prop:e.prop,min:e.min.value,max:e.max.value}})),samplesCount:this.store.analysisInputs.samplesCount.value||1},i=this.getOutputsOfInterest(),s=new $n(n.func,n.fixedInputs,n.variedInputs,i,n.samplesCount),r=yield s.perform(),l=r.funcEvalResults,u=r.funcCalls;this.closeOpenedViewers(),this.comparisonView.dataFrame=l;const c=l.columns.names(),d=this.getFixedInputColumns(l.rowCount);for(const t of d)t.name=l.columns.getUnusedName(`${t.name} (fixed)`),l.columns.add(t);this.comparisonView.grid.columns.setVisible([c[0]]),this.comparisonView.grid.columns.setVisible(c),this.comparisonView.grid.props.rowHeight=25;const p=o.Viewer.correlationPlot(l,{xColumnNames:c,yColumnNames:c}),h=this.comparisonView.dockManager.dock(p,o.DOCK_TYPE.LEFT,this.tableDockNode,"",Hn.COR_PLOT);this.openedViewers.push(p);const f=o.Viewer.pcPlot(l,{columnNames:c});this.comparisonView.dockManager.dock(f,o.DOCK_TYPE.DOWN,h,"",Hn.PC_PLOT),this.openedViewers.push(f);const m=this.getOutputNameForScatterPlot(c,l,n.variedInputs.length),v=1===n.variedInputs.length?o.Viewer.lineChart(l,this.getLineChartOpt(c)):o.Viewer.scatterPlot(l,this.getScatterOpt(c,m));this.openedViewers.push(v),this.comparisonView.dockManager.dock(v,o.DOCK_TYPE.DOWN,this.tableDockNode,"",Hn.GRAPH),this.gridSubscription=this.comparisonView.grid.onCellClick.subscribe((n=>{var i;const s=u[null!==(i=n.tableRowIndex)&&void 0!==i?i:0],r=[...s.outputParams.values()].filter((t=>o.TYPES_SCALAR.has(t.property.propertyType))),l=o.HtmlTable.create(r,(t=>{var e;return[null!==(e=t.property.caption)&&void 0!==e?e:t.property.name,s.outputs[t.property.name],t.property.options.units]})).root,c=[...s.outputParams.values()].filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME)).reduce(((t,e)=>{var n;const i=Dt(e.property).config,r=s.outputs[e.name],l=null!==(n=e.property.caption)&&void 0!==n?n:e.property.name;return i.map((e=>{const n=e.type,i=o.Viewer.fromType(n,r);i.setOptions(e),a()(i.root).css({width:"100%"}),t[l]?t[l].push(i.root):t[l]=[i.root]})),t}),{});let d,p;r.length>0?(p=1,d=Object.assign({"Output scalars":[l]},c)):(p=0,d=Object.assign({},c));const h=e.accordion();a()(h.root).css({width:"100%"}),Object.entries(d).map((t=>{h.addPane(t[0],(()=>e.divV(t[1])))})),h.panes[p].expanded=!0,t.shell.o=h.root}))}))}runGridAnalysis(){return qn(this,void 0,void 0,(function*(){var n,i;const s=Object.keys(this.store.inputs).reduce(((t,e)=>{switch(this.store.inputs[e].type){case o.TYPE.INT:case o.TYPE.BIG_INT:const n=this.store.inputs[e],i=(n.max.value-n.min.value)/(n.lvl.value-1);t[e]=n.isChanging.value?Array.from({length:n.lvl.value},((t,e)=>Math.round(n.min.value+e*i))):[n.const.value];break;case o.TYPE.FLOAT:const s=this.store.inputs[e],r=(s.max.value-s.min.value)/(s.lvl.value-1);t[e]=s.isChanging.value?Array.from({length:s.lvl.value},((t,e)=>s.min.value+e*r)):[s.const.value];break;case o.TYPE.BOOL:const a=this.store.inputs[e];t[e]=a.isChanging.value?[a.const.value,!a.const.value]:[a.const.value];break;default:const l=this.store.inputs[e];t[e]=[l.const.value]}return t}),{});let r=Object.values(s)[0].map((t=>[t]));for(let t=1;t<Object.values(s).length;t++){const e=Object.values(s)[t],n=[];for(const t of r)for(const i of e)n.push([...t,i]);r=n}const l=r.map((t=>this.func.prepare(this.func.inputs.map(((t,e)=>({name:t.name,idx:e}))).reduce(((e,{name:n,idx:i})=>(e[n]=t[i],e)),{})))),u=yield Ln(l);this.closeOpenedViewers();const c=[],d=u.length,p=this.getFixedInputColumns(d);for(const t of Object.keys(this.store.inputs)){const e=this.store.inputs[t],i=e.prop;e.isChanging.value&&c.push(o.Column.fromType(i.propertyType,null!==(n=i.caption)&&void 0!==n?n:i.name,d))}const h=[...c],f=h.length,m=o.DataFrame.fromColumns([h[0]]);for(let t=1;t<f;++t)h[t].name=m.columns.getUnusedName(h[t].name),m.columns.add(h[t]);for(let t=0;t<d;++t)for(const e of Object.keys(this.store.inputs)){const n=this.store.inputs[e],o=n.prop;n.isChanging.value&&m.set(null!==(i=o.caption)&&void 0!==i?i:o.name,t,u[t].inputs[e])}const v=this.getOutputsOfInterest(),g=_n(u,v).columns;for(const t of g)h.forEach((e=>{e.name===t.name&&(e.name=`${e.name} (input)`,t.name=`${t.name} (output)`)})),t.name=m.columns.getUnusedName(t.name),m.columns.add(t);const y=m.columns.names();for(const t of p)t.name=m.columns.getUnusedName(`${t.name} (fixed)`),m.columns.add(t);this.comparisonView.dataFrame=m,this.gridSubscription=this.comparisonView.grid.onCellClick.subscribe((n=>{var i;const s=u[null!==(i=n.tableRowIndex)&&void 0!==i?i:0],r=[...s.outputParams.values()].filter((t=>o.TYPES_SCALAR.has(t.property.propertyType))),l=o.HtmlTable.create(r,(t=>{var e;return[null!==(e=t.property.caption)&&void 0!==e?e:t.property.name,s.outputs[t.property.name],t.property.options.units]})).root,c=[...s.outputParams.values()].filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME)).reduce(((t,e)=>{var n;const i=Dt(e.property).config,r=s.outputs[e.name],l=null!==(n=e.property.caption)&&void 0!==n?n:e.property.name;return i.map((e=>{const n=e.type,i=o.Viewer.fromType(n,r);i.setOptions(e),a()(i.root).css({width:"100%"}),t[l]?t[l].push(i.root):t[l]=[i.root]})),t}),{});let d,p;r.length>0?(p=1,d=Object.assign({"Output scalars":[l]},c)):(p=0,d=Object.assign({},c));const h=e.accordion();a()(h.root).css({width:"100%"}),Object.entries(d).map((t=>{h.addPane(t[0],(()=>e.divV(t[1])))})),h.panes[p].expanded=!0,t.shell.o=h.root})),this.comparisonView.grid.columns.setVisible([y[0]]),this.comparisonView.grid.columns.setVisible(y),this.comparisonView.grid.props.rowHeight=25;const b=o.Viewer.correlationPlot(m,{xColumnNames:y,yColumnNames:y}),w=this.comparisonView.dockManager.dock(b,o.DOCK_TYPE.LEFT,this.tableDockNode,"",Hn.COR_PLOT);this.openedViewers.push(b);const A=o.Viewer.pcPlot(m,{columnNames:y});this.comparisonView.dockManager.dock(A,o.DOCK_TYPE.DOWN,w,"",Hn.PC_PLOT),this.openedViewers.push(A);const C=this.getOutputNameForScatterPlot(y,m,c.length),I=1===c.length?o.Viewer.lineChart(m,this.getLineChartOpt(y)):o.Viewer.scatterPlot(m,this.getScatterOpt(y,C));this.openedViewers.push(I),this.comparisonView.dockManager.dock(I,o.DOCK_TYPE.DOWN,this.tableDockNode,"",Hn.GRAPH)}))}getOutputNameForScatterPlot(t,e,n){var i,o,s,r;for(let a=n;a<t.length;++a)if((null!==(o=null===(i=e.col(t[a]))||void 0===i?void 0:i.min)&&void 0!==o?o:0)<(null!==(r=null===(s=e.col(t[a]))||void 0===s?void 0:s.max)&&void 0!==r?r:0))return t[a];return t[n]}getOutputsOfInterest(){const t=[];for(const e of Object.keys(this.store.outputs)){const n=this.store.outputs[e];if(n.isInterest.value){let e;switch(n.value.returning){case Zn.LAST_ROW:e=-1;break;case Zn.FIRST_ROW:e=0;break;default:e=null}t.push({prop:n.prop,value:{row:e,colName:n.value.colName,colValue:n.value.colValue}})}}return t}getScatterOpt(t,e){return{xColumnName:t[0],yColumnName:t[1],colorColumnName:e,sizeColumnName:e,markerMaxSize:12,jitterSize:5}}getLineChartOpt(t){return{xColumnName:t[0],yColumnNames:t.slice(1,Math.min(t.length,8)),markerSize:1,markerType:o.MARKER_TYPE.GRADIENT,multiAxis:!0}}getBarChartOpt(t,e,n){return{description:t,splitColumnName:e,valueColumnName:n,valueAggrType:o.AGG.AVG,showTitle:!1,showCategorySelector:!1,showStackSelector:!1,showValueAxis:!1}}}var ti;!function(t){t.NELDER_MEAD="Nelder-Mead",t.GRAD_DESC="Gradient descent"}(ti||(ti={}));const ei=new Map([[ti.NELDER_MEAD,"The Nelder-Mead method"],[ti.GRAD_DESC,"The gradient descent method"]]);var ni;!function(t){t.MAD="MAD",t.RMSE="RMSE"}(ni||(ni={}));const ii=new Map([[ni.MAD,"Maximum absolute deviation"],[ni.RMSE,"Root mean square error"]]);var oi,si,ri,ai;!function(t){t[t.LOSS_COL_WIDTH=60]="LOSS_COL_WIDTH",t[t.ROW_HEIGHT=180]="ROW_HEIGHT",t[t.LOSS_GRAPH_WIDTH=360]="LOSS_GRAPH_WIDTH",t[t.GOF_VIEWER_WIDTH=240]="GOF_VIEWER_WIDTH"}(oi||(oi={})),function(t){t.ITER="Iteration",t.LOSS="Loss",t.LOSS_GRAPH="Fitting profile",t.TARGET="Target",t.FIT="Fit",t.METHOD="method",t.VALUE="Value",t.OBJECTIVE="Target",t.SAMPLES="samples",t.ID="id",t.OBTAINED="Simulation",t.LOSS_LOW="loss",t.SIMILARITY="similarity"}(si||(si={})),function(t){t.GOAL="`Goal`",t.FIT="`Fit`",t.MIN="`min`",t.MAX="`max`",t.TARGET="`Target`",t.METHOD="`method`",t.CONTEXT="`Context Panel (F4)`",t.SAMPLES="`samples`",t.LOSS="`loss`",t.SIMILARITY="`similarity`"}(ri||(ri={})),function(t){t[t.SIMILARITY_MIN=0]="SIMILARITY_MIN",t[t.SIMILARITY_DEFAULT=.01]="SIMILARITY_DEFAULT",t[t.SAMPLES=10]="SAMPLES"}(ai||(ai={}));const li=`# Fitting\n\nUse fitting to solve an inverse problem: find input conditions leading to specified output constraints. \nIt computes inputs minimizing deviation measured by [loss function](https://en.wikipedia.org/wiki/Loss_function).\n\n1. In the ${ri.FIT} block, use switchers to specify inputs to be found:\n * Set ${ri.MIN} and ${ri.MAX} values for each selected item. They define the variation range\n * Set values of all other inputs\n\n2. Set output constraints in the ${ri.TARGET} block:\n * Use switchers to specify target outputs\n * Set target value for each selected item\n\n3. Choose ${ri.METHOD}. Press <i class="grok-icon fal fa-cog"></i> to specify its settings.\n\n4. Specify the loss function type (in the ${ri.LOSS} field).\n\n5. Enter the number of points to be found (in the ${ri.SAMPLES} field).\n\n6. Set the maximum scaled deviation between similar fitted points (in the ${ri.SIMILARITY} field).\n\n7. Press the "Run" icon <i class="fas fa-play"></i> on the top panel to perform fitting. You will get a\n[grid](https://datagrok.ai/help/visualize/viewers/grid) containing \n\n * loss function values\n * fitted inputs\n * viewers visualizing the goodness of fit:\n * [line chart](https://datagrok.ai/help/visualize/viewers/line-chart) showing the loss function minimization\n\n8. Open ${ri.CONTEXT}. You will get the function run corresponding to the selected grid row.\n\n9. Press <i class="grok-icon fal fa-question"></i> on the top panel to learn more about \n[parameters optimization](https://datagrok.ai/help/compute/#input-parameter-optimization).\n\n# Learn more\n\n* [Parameters optimization](https://datagrok.ai/help/compute/#input-parameter-optimization)\n* [Nelder-Mead method](https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method)`;class ci extends Error{constructor(t){super(t)}}function di(t){return new Promise(((e,n)=>setTimeout(e,t)))}function pi(t,e){const n=t.getRawData(),i=e.getRawData(),o=e.length,s=Math.min(t.length,o),r=new Uint32Array(s);let a=0,l=0,u=0;for(let t=0;t<s;++t){for(;;){if(l=Math.abs(i[a]-n[t]),++a,!(a<o)){--a;break}if(u=Math.abs(i[a]-n[t]),u>l){--a;break}l=u}r[t]=a}return r}function hi(t,e,n,i){const o=e.col(t),s=n.col(t);if(null===o)throw new ci(`no "${t}" column in the target dataframe "${e.name}"`);if(null===s)throw new ci(`no "${t}" column in the output dataframe "${n.name}"`);const r=pi(o,s),a=e.columns,l=a.length,u=new Float32Array((l-1)*r.length);let c=0;for(const e of a)if(e.name!==t){const t=n.col(e.name);if(null===t)throw new ci(`no "${e.name}" column in the output dataframe "${n.name}"`);const o=t.getRawData(),s=e.getRawData();if(i){const t=e.stats.max-e.stats.min,n=t>0?t:1;r.forEach(((t,e)=>{u[c]=(o[t]-s[e])/n,++c}))}else r.forEach(((t,e)=>{u[c]=o[t]-s[e],++c}))}return u}var fi=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const mi=new Map([["tolerance",{default:1e-6,min:1e-20,max:.1}],["maxIter",{default:50,min:1,max:1e4}],["nonZeroParam",{default:1e-4,min:1e-20,max:.1}],["initialScale",{default:.02,min:1e-20,max:.1}],["scaleReflaction",{default:1,min:1,max:2}],["scaleExpansion",{default:2,min:1,max:2}],["scaleContraction",{default:-.5,min:-.5,max:0}]]),vi=new Map([["tolerance","tolerance"],["maxIter","max iterations"],["nonZeroParam","non-zero param"],["initialScale","initial scale"],["scaleReflaction","scale reflection"],["scaleExpansion","scale expansion"],["scaleContraction","scale contraction"]]);function gi(t,e,n,i){for(let o=0;o<e;o++){let s=0;for(let t=0;t<e+1;t++)t!=n&&(s+=i[t][o]);t[o]=s/e}}function yi(t,e,n,i,o,s,r,a){for(let l=0;l<s;l++)e[l]=t[l],e[l]+=o*(t[l]-i[n][l]),e[l]<r[l]?e[l]=r[l]:e[l]>a[l]&&(e[l]=a[l])}const bi=function(t,e,n,i,o){return fi(this,void 0,void 0,(function*(){const s=n.get("tolerance"),r=n.get("maxIter"),a=n.get("scaleReflaction"),l=n.get("scaleExpansion"),u=n.get("scaleContraction"),c=e.length+1,d=e.length,[p,h]=yield function(t,e,n,i,o){return fi(this,void 0,void 0,(function*(){const s=n.length+1,r=n.length,a=e.get("nonZeroParam"),l=e.get("initialScale"),u=new Array(s),c=new Array(s);for(let e=0;e<s;e++){u[e]=new Float32Array(r);for(let t=0;t<r;t++)u[e][t]=n[t],0!=e&&e-1===t&&(0==n[t]?u[e][t]=a:u[e][t]+=l*n[e-1],u[e][t]<i[t]?u[e][t]=i[t]:u[e][t]>o[t]&&(u[e][t]=o[t]));c[e]=yield t(u[e])}return[u,c]}))}(t,n,e,i,o),f=new Array(c);for(let t=0;t<c;t++)f[t]=t;const m=f.length-1;let v=0,g=0,y=0,b=0;const w=new Float32Array(d),A=new Float32Array(d),C=new Float32Array(d),I=new Float32Array(d),S=new Array(r);if(c>1){for(;f.sort(((t,e)=>h[t]-h[e])),!(v>r);){if(0==v&&(g=h[0],y=2*h[f[0]]),S[v]=g,++v,g=h[f[0]],y-g>s)b=0;else if(++b,b>2*c)break;y=g,gi(w,d,f[m],p),yi(w,A,f[m],p,a,d,i,o);const e=yield t(A);if(e<h[f[m]]){yi(w,C,f[m],p,l,d,i,o);const n=yield t(C);if(n<e){h[f[m]]=n;for(let t=0;t<d;t++)p[f[m]][t]=C[t];continue}h[f[m]]=e;for(let t=0;t<d;t++)p[f[m]][t]=A[t];continue}yi(w,I,f[m],p,u,d,i,o);const n=yield t(I);if(!(n<h[f[m]]))break;h[f[m]]=n;for(let t=0;t<d;t++)p[f[m]][t]=I[t]}for(let t=v;t<r;t++)S[t]=h[f[0]]}return{point:p[f[0]],cost:h[f[0]],iterCosts:S,iterCount:v-1}}))};function wi(t,e,n){const i=e-n,o=new Array(t);for(let e=0;e<t;e++){const t=Math.random();o[e]=n+t*i}return o}function Ai(t,e,n,i){return s=this,r=arguments,l=function*(t,e,n,i,s=1){const r=function(t,e,n){const i=e.length,o=new Array(t);for(let e=0;e<t;e++)o[e]=new Float32Array(i);for(let s=0;s<i;s++)if(e[s]===n[s])for(let n=0;n<t;n++)o[n][s]=e[s];else{const i=wi(t,e[s],n[s]);for(let e=0;e<t;e++)o[e][s]=i[e]}return o}(s,n,e),a=[],l=[],u=[];let c=0,d=null;const p=o.TaskBarProgressIndicator.create("Fitting...");let h;for(h=0;h<s;++h)try{if(a.push(yield bi(t,r[h],i,e,n)),p.update(100*(h+1)/s,"Fitting..."),yield di(10),p.canceled)break}catch(t){if(p.close(),t instanceof ci)throw new Error(`Inconsistent dataframes: ${t.message}`);++c,l.push(t instanceof Error?t.message:"Platform issue"),u.push(r[h])}if(p.close(),c>0){const t=n.length,e=new Array(t);for(let n=0;n<t;++n)e[n]=new Float32Array(c);u.forEach(((t,n)=>t.forEach(((t,i)=>e[i][n]=t)))),d=o.DataFrame.fromColumns(e.map(((t,e)=>o.Column.fromFloat32Array(`arg${e}`,t)))),d.columns.add(o.Column.fromStrings("Issue",l))}return{extremums:a,fails:d}},new((a=void 0)||(a=Promise))((function(t,e){function n(t){try{o(l.next(t))}catch(t){e(t)}}function i(t){try{o(l.throw(t))}catch(t){e(t)}}function o(e){var o;e.done?t(e.value):(o=e.value,o instanceof a?o:new a((function(t){t(o)}))).then(n,i)}o((l=l.apply(s,r||[])).next())}));var s,r,a,l}var Ci=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const Ii=[o.TYPE.INT,o.TYPE.BIG_INT,o.TYPE.FLOAT,o.TYPE.DATA_FRAME],Si=()=>e.div([],"sa-switch-input");class Ti{static fromEmpty(e){return Ci(this,arguments,void 0,(function*(e,n={parentView:void 0,parentCall:void 0}){const i=[...t.shell.views].find((t=>t.type===v)),o=yield re.fromComparedRuns([],e,{parentView:i,parentCall:n.parentCall});t.shell.addView(o),new this(e,o,n)}))}constructor(n,i,s={parentView:void 0,parentCall:void 0,configFunc:void 0}){if(this.func=n,this.options=s,this.generateInputFields=t=>{const n=(t,e)=>void 0===t.options[e]?t.defaultValue:Number(t.options[e]),i=(t,n,i=!0)=>{const o=e.input.toggle(" ",{value:t,onValueChanged:()=>n(o.value)});return a()(o.root).addClass("sa-switch-input"),a()(o.captionLabel).hide(),e.tooltip.bind(o.root,(()=>i?o.value?"Switch OFF fitting the input":"Switch ON fitting the input":o.value?"Mark the output as not a target":"Mark the output as a target")),o},s=t.inputs.reduce(((t,s)=>{var r;const l=n(s,"default");if(s.propertyType===o.TYPE.FLOAT){const o=i(!1,(t=>{h.isChanging.next(t),this.updateApplicabilityState()})),u=i(!1,(t=>{h.isChanging.next(t),this.updateApplicabilityState()})),d=null!==(r=s.caption)&&void 0!==r?r:s.name,p={type:s.propertyType,prop:s,const:{input:(()=>{const t=e.input.float(d,{value:l,onValueChanged:()=>{h.const.value=t.value,this.updateApplicabilityState()}});return t.root.insertBefore(u.root,t.captionLabel),t.addPostfix(s.options.units),t.setTooltip(`Value of '${d}'`),t.nullable=!1,t})(),value:l},min:{input:(()=>{const t=e.input.float(`${d} (min)`,{value:n(s,"min"),onValueChanged:()=>{h.min.value=t.value,this.updateApplicabilityState()}});return t.addValidator((t=>Number(t)>p.max.value?"Greater than max":null)),t.root.insertBefore(o.root,t.captionLabel),t.addPostfix(s.options.units),t.setTooltip(`Min value '${d}'`),t.nullable=!1,t})(),value:n(s,"min")},max:{input:(()=>{const t=e.input.float(`${d} (max)`,{value:n(s,"max"),onValueChanged:()=>{h.max.value=t.value,this.updateApplicabilityState()}});return t.addValidator((t=>Number(t)<p.min.value?"Smaller than min":null)),t.addPostfix(s.options.units),t.setTooltip(`Max value of '${d}'`),t.nullable=!1,t})(),value:n(s,"max")},isChanging:new c.BehaviorSubject(!1)};[p.max.input].forEach((t=>{t.root.insertBefore(Si(),t.captionLabel),a()(t.root).removeProp("display")})),t[s.name]=Object.assign(Object.assign({},p),{constForm:[p.const.input],saForm:[p.min.input,p.max.input]});const h=t[s.name];h.isChanging.subscribe((t=>{o.notify=!1,o.value=t,o.notify=!0,u.notify=!1,u.value=t,u.notify=!0})),(0,c.combineLatest)([p.isChanging]).subscribe((([t])=>{t?(h.constForm.forEach((t=>a()(t.root).hide())),h.saForm.forEach((t=>a()(t.root).css("display","flex")))):(h.constForm.forEach((t=>a()(t.root).css("display","flex"))),h.saForm.forEach((t=>a()(t.root).hide())))}))}else{const n=Si(),i={input:(()=>{var t;const o=e.input.forProperty(s);return o.caption=null!==(t=s.caption)&&void 0!==t?t:s.name,o.onInput((()=>{i.value=o.value,this.updateApplicabilityState()})),o.root.insertBefore(n,o.captionLabel),o.addPostfix(s.options.units),o.nullable=!1,o})(),value:l};i.input.value=l,t[s.name]={const:i,constForm:[i.input],saForm:[],type:s.propertyType,prop:s,isChanging:new c.BehaviorSubject(!1)}}return t}),{}),r=t.outputs.filter((t=>Ii.includes(t.propertyType))).reduce(((t,n)=>{const s={prop:n,input:(()=>{var t;const r=null!==(t=n.caption)&&void 0!==t?t:n.name,a=e.input.forProperty(n);a.addCaption(r),a.value=0,a.setTooltip(this.toSetSwitched?"Target value":n.propertyType===o.TYPE.DATA_FRAME?"Output dataframe":"Output scalar"),a.input.hidden=!this.toSetSwitched,a.nullable=!1,e.tooltip.bind(a.captionLabel,n.propertyType===o.TYPE.DATA_FRAME?"Output dataframe":"Output scalar"),a.onChanged((()=>{if(s.target=a.value,n.propertyType===o.TYPE.DATA_FRAME)if(s.target){const t=[];for(const e of a.value.columns)e.type!==o.COLUMN_TYPE.FLOAT&&e.type!==o.COLUMN_TYPE.INT||t.push(e.name);s.colNameInput.items=t,s.colNameInput.value=t[0]}else s.colNameInput.items=[null],s.colNameInput.value=null;this.updateApplicabilityState()})),n.propertyType===o.TYPE.DATA_FRAME&&(a.root.lastElementChild.hidden=!this.toSetSwitched);const l=i(this.toSetSwitched,(t=>{s.isInterest.next(t),this.updateApplicabilityState(),a.input.hidden=!t,a.setTooltip(t?"Target value":n.propertyType===o.TYPE.DATA_FRAME?"Output dataframe":"Output scalar"),n.propertyType===o.TYPE.DATA_FRAME&&(a.root.lastElementChild.hidden=!t,s.colNameInput.root.hidden=!t)}),!1).root;return a.root.insertBefore(l,a.captionLabel),a})(),colNameInput:(()=>{const t=e.input.choice("argument",{value:null,items:[null],onValueChanged:()=>{s.colName=t.value}});return t.setTooltip("Column with argument values"),t.root.insertBefore(Si(),t.captionLabel),t.root.hidden=n.propertyType!==o.TYPE.DATA_FRAME||!this.toSetSwitched,this.toSetSwitched=!1,t.nullable=!1,t})(),isInterest:new c.BehaviorSubject(this.toSetSwitched),target:n.propertyType!==o.TYPE.DATA_FRAME?0:null,colName:""};return t[n.name]=s,t}),{});return{inputs:s,outputs:r}},this.readyToRun=!1,this.runIcon=e.iconFA("play",(()=>Ci(this,void 0,void 0,(function*(){this.readyToRun&&(yield this.runOptimization())})))),this.helpIcon=e.iconFA("question",(()=>{window.open("https://datagrok.ai/help/compute/#input-parameter-optimization","_blank")}),"Open help in a new tab"),this.showFailsBtn=e.button("Issues",(()=>{if(this.method!==ti.NELDER_MEAD)throw new Error(`Not implemented the '${this.method}' method`);this.showNelderMeadFails()}),"Show issues"),this.gridClickSubscription=null,this.gridCellChangeSubscription=null,this.failsDF=null,this.toSetSwitched=!0,this.samplesCount=ai.SAMPLES,this.samplesCountInput=e.input.forProperty(o.Property.fromOptions({name:si.SAMPLES,inputType:"Int",defaultValue:this.samplesCount,min:1,max:1e3})),this.loss=ni.RMSE,this.lossInput=e.input.choice(si.LOSS_LOW,{value:this.loss,items:[ni.MAD,ni.RMSE],onValueChanged:()=>{this.loss=this.lossInput.value,this.lossInput.setTooltip(ii.get(this.loss))}}),this.similarity=ai.SIMILARITY_DEFAULT,this.similarityInput=e.input.forProperty(o.Property.fromOptions({name:si.SIMILARITY,inputType:"Float",defaultValue:this.similarity,min:0})),this.helpDN=void 0,this.method=ti.NELDER_MEAD,this.methodInput=e.input.choice(si.METHOD,{value:this.method,items:[ti.NELDER_MEAD],onValueChanged:()=>{this.method=this.methodInput.value,this.showHideSettingInputs(),this.methodInput.setTooltip(ei.get(this.method))}}),this.nelderMeadSettings=new Map,this.gradDescentSettings={iterCount:10,learningRate:1e-4},this.settingsInputs=new Map,this.store=this.generateInputFields(this.func),this.fittingSettingsIcon=e.iconFA("cog",(()=>{const t=this.fittingSettingsDiv.hidden;this.fittingSettingsDiv.hidden=!t}),"Modify fitting settings"),this.fittingSettingsDiv=e.divV([]),!this.isOptimizationApplicable(n))return t.shell.warning("Fitting is not applicable: the function has no scalar outputs."),void i.close();const r=this.buildForm();this.comparisonView=i,this.comparisonView.dockManager.dock(r,o.DOCK_TYPE.LEFT,null,`${this.func.name} - Fitting`,.25),this.comparisonView.grid.columns.byName("Run name").visible=!1,mi.forEach(((t,e)=>this.nelderMeadSettings.set(e,t.default)));const l=this.comparisonView.getRibbonPanels();l.push([this.helpIcon,this.runIcon]),this.comparisonView.setRibbonPanels(l),this.fittingSettingsDiv.hidden=!0,this.comparisonView.name=this.comparisonView.name.replace("comparison","fitting"),this.comparisonView.helpUrl="https://datagrok.ai/help/compute/#input-parameter-optimization";const u=e.markdown(li);u.style.padding="10px",u.style.overflow="auto",this.helpDN=this.comparisonView.dockManager.dock(u,o.DOCK_TYPE.FILL,this.comparisonView.dockManager.findNode(this.comparisonView.grid.root),"About"),this.methodInput.setTooltip(ei.get(this.method)),e.tooltip.bind(this.methodInput.captionLabel,"Method for minimizing the loss function"),this.lossInput.setTooltip(ii.get(this.loss)),e.tooltip.bind(this.lossInput.captionLabel,"Loss function type"),this.showFailsBtn.style.padding="0px",this.samplesCountInput.addCaption(si.SAMPLES),this.samplesCountInput.onChanged((()=>{this.samplesCount=this.samplesCountInput.value,this.updateApplicabilityState()})),this.samplesCountInput.setTooltip("Number of points to be found"),this.similarityInput.onChanged((()=>{this.similarity=this.similarityInput.value,this.updateApplicabilityState()})),this.similarityInput.addCaption(si.SIMILARITY),this.similarityInput.setTooltip("The higher the value, the fewer points will be found"),e.tooltip.bind(this.similarityInput.captionLabel,"Max scaled deviation between similar fitted points"),this.updateRunIconStyle(),this.updateRunIconDisabledTooltip("Select inputs for fitting"),this.runIcon.classList.add("fas")}isOptimizationApplicable(t){for(const n of t.outputs)if((e=n).propertyType===o.TYPE.INT||e.propertyType===o.TYPE.FLOAT||e.propertyType===o.TYPE.DATA_FRAME)return!0;var e;return!1}generateNelderMeadSettingsInputs(){const t=[];mi.forEach(((n,i)=>{const s=e.input.forProperty(o.Property.fromOptions({name:vi.get(i),inputType:"maxIter"!==i?"Float":"Int",defaultValue:n.default,min:n.min,max:n.max}));s.addCaption(vi.get(i)),s.nullable=!1,s.onChanged((()=>{this.nelderMeadSettings.set(i,s.value),this.updateApplicabilityState()})),t.push(s)})),this.settingsInputs.set(ti.NELDER_MEAD,t)}areNelderMeadSettingsCorrect(){for(const[t,e]of this.nelderMeadSettings)if(null==e||e>mi.get(t).max||e<mi.get(t).min)return this.updateRunIconDisabledTooltip(`Invalid "${t}": check method settings`),!1;return!0}generateGradDescentSettingsInputs(){const t=e.input.forProperty(o.Property.fromOptions({name:"iterations",inputType:"Int",defaultValue:this.gradDescentSettings.iterCount,min:1,max:1e4}));t.onChanged((()=>this.gradDescentSettings.iterCount=t.value));const n=e.input.forProperty(o.Property.fromOptions({name:"Learning rate",inputType:"Float",defaultValue:this.gradDescentSettings.learningRate,min:1e-6,max:1e3}));n.onChanged((()=>this.gradDescentSettings.learningRate=n.value)),this.settingsInputs.set(ti.GRAD_DESC,[t,n])}areGradDescentSettingsCorrect(){return!1}areMethodSettingsCorrect(){switch(this.method){case ti.NELDER_MEAD:return this.areNelderMeadSettingsCorrect();case ti.GRAD_DESC:return this.areGradDescentSettingsCorrect();default:return!0}}generateSettingInputs(){this.generateNelderMeadSettingsInputs(),this.generateGradDescentSettingsInputs()}showHideSettingInputs(){this.settingsInputs.forEach(((t,e)=>t.forEach((t=>t.root.hidden=e!==this.method))))}buildForm(){const t=e.h1(si.FIT);e.tooltip.bind(t,"Select inputs to be fitted");const n=new Map([["Misc",[]]]);Object.values(this.store.inputs).forEach((t=>{const e=t.prop.category,i=[...t.constForm.map((t=>t.root)),...t.saForm.map((t=>t.root))];n.has(e)?n.get(e).push(...i):n.set(e,i)}));const i=e.div([t],{style:{"overflow-y":"scroll",width:"100%"}});n.size>1?(n.forEach(((t,n)=>{"Misc"!==n&&(i.append(e.h3(n)),i.append(...t))})),n.get("Misc").length>0&&(i.append(e.h3("Misc")),i.append(...n.get("Misc")))):i.append(...n.get("Misc"));const o=e.h1(si.TARGET);e.tooltip.bind(o,"Select target outputs"),i.appendChild(o);let s="Misc";Object.values(this.store.outputs).reduce(((t,n)=>{const i=n.prop;return i.category!==s&&(t.append(e.h3(i.category)),s=i.category),t.append(n.input.root),t.append(n.colNameInput.root),t}),i);let r=!1;for(const t of Object.keys(this.store.outputs))if(!0===this.store.outputs[t].isInterest.value){r=!0;break}r||this.store.outputs[Object.keys(this.store.outputs)[0]].isInterest.next(!0);const l=e.h1("Using");e.tooltip.bind(l,"Specify fitting method"),i.appendChild(l),this.methodInput.root.insertBefore(this.fittingSettingsIcon,this.methodInput.captionLabel),this.fittingSettingsIcon.style.minWidth="50px",i.appendChild(this.methodInput.root);const u=e.h2("with settings");return e.tooltip.bind(u,(()=>`Settings of the ${this.method} method`)),this.fittingSettingsDiv.appendChild(u),this.generateSettingInputs(),this.showHideSettingInputs(),i.appendChild(this.fittingSettingsDiv),this.settingsInputs.forEach((t=>t.forEach((t=>{t.root.insertBefore(Si(),t.captionLabel),this.fittingSettingsDiv.append(t.root)})))),[this.lossInput,this.samplesCountInput,this.similarityInput].forEach((t=>{t.root.insertBefore(Si(),t.captionLabel),t.nullable=!1,i.appendChild(t.root)})),a()(i).addClass("ui-form"),this.updateApplicabilityState(),a()(i).css({"padding-left":"12px","overflow-y":"scroll","padding-right":"4px"}),i}updateRunIconDisabledTooltip(t){e.tooltip.bind(this.runIcon,(()=>{const n=e.label(t);return n.style.color="#FF0000",n}))}updateApplicabilityState(){this.readyToRun=this.canFittingBeRun(),this.updateRunIconStyle()}updateRunIconStyle(){this.readyToRun?(this.runIcon.style.color="var(--green-2)",e.tooltip.bind(this.runIcon,"Run fitting")):this.runIcon.style.color="var(--grey-3)"}areInputsReady(){var t;let e,n=!1,i=!0;for(const o of Object.keys(this.store.inputs)){const s=this.store.inputs[o],r=null!==(t=s.prop.caption)&&void 0!==t?t:s.prop.name;if(!0===s.isChanging.value){n=!0;const t=s.min.input,o=s.max.input,a=t.value,l=o.value;e=null!=a&&void 0!==l&&void 0!==l,e?a>l?(e=!1,this.updateRunIconDisabledTooltip(`Invalid min & max of "${r}"`),t.input.classList.add("d4-invalid"),o.input.classList.add("d4-invalid")):(t.input.classList.remove("d4-invalid"),o.input.classList.remove("d4-invalid")):this.updateRunIconDisabledTooltip(`Incomplete "${r}"`),i=i&&e}else{e=null!=s.const.input.value,e||this.updateRunIconDisabledTooltip(`Incomplete "${r}"`),i=i&&e}}return n||this.updateRunIconDisabledTooltip("No parameters for fitting selected"),n&&i}areOutputsReady(){let t,e=!1,n=!0;for(const i of Object.keys(this.store.outputs)){const s=this.store.outputs[i];if(!0===s.isInterest.value){e=!0;t=null!=s.input.value,s.prop.propertyType===o.TYPE.DATA_FRAME&&(t=t&&null!==s.colNameInput.value&&""!==s.colName),t||this.updateRunIconDisabledTooltip(`Incomplete the "${s.input.caption}" target`),n=n&&t}}return e||this.updateRunIconDisabledTooltip("No targets selected"),e&&n}isSamplesCountValid(){return this.samplesCount>0||(this.updateRunIconDisabledTooltip(`Invalid "${si.SAMPLES}"`),!1)}isSimilarityValid(){return this.similarity>=ai.SIMILARITY_MIN||(this.updateRunIconDisabledTooltip(`Invalid "${si.SIMILARITY}"`),!1)}canFittingBeRun(){return this.areInputsReady()&&this.areOutputsReady()&&this.isSamplesCountValid()&&this.areMethodSettingsCorrect()&&this.isSimilarityValid()}getFixedInputs(){return Object.keys(this.store.inputs).filter((t=>!this.store.inputs[t].isChanging.value))}getFittedInputs(){return Object.keys(this.store.inputs).filter((t=>this.store.inputs[t].type===o.TYPE.FLOAT&&this.store.inputs[t].isChanging.value))}runOptimization(){return Ci(this,void 0,void 0,(function*(){try{if(!this.canFittingBeRun())return;if(this.samplesCount<1)return;if(this.similarity<ai.SIMILARITY_MIN)return;this.failsDF=null;const n={},i=this.getFixedInputs();i.forEach((t=>n[t]=this.store.inputs[t].const.value));const s=this.getFittedInputs(),r=s.length,l=[],u=new Float32Array(r),c=new Float32Array(r),d=new Array(r);s.forEach(((t,e)=>{var n,i,o;const s=this.store.inputs[t];u[e]=null!==(n=s.min.value)&&void 0!==n?n:0,c[e]=null!==(i=s.max.value)&&void 0!==i?i:0,l.push(t),d[e]=null!==(o=s.prop.caption)&&void 0!==o?o:s.prop.name}));const p=this.getOutputsOfInterest();if(p.length<1)return void t.shell.error("No output is selected for optimization.");const h=p.map((t=>t.prop.propertyType)).filter((t=>t===o.TYPE.DATA_FRAME)).length>1,f=t=>Ci(this,void 0,void 0,(function*(){t.forEach(((t,e)=>n[l[e]]=t));const e=this.func.prepare(n);return yield e.call()})),m=t=>Ci(this,void 0,void 0,(function*(){t.forEach(((t,e)=>n[l[e]]=t));const e=this.func.prepare(n),i=yield e.call();let s=0,r=0,a=0;return p.forEach((t=>{t.prop.propertyType!==o.TYPE.DATA_FRAME?(a=t.target,s+=Math.pow((a-i.getParamValue(t.prop.name))/(0!==a?a:1),2),++r):hi(t.colName,t.target,i.getParamValue(t.prop.name),!0).forEach((t=>{s+=Math.pow(t,2),++r}))})),Math.sqrt(s/r)})),v=t=>Ci(this,void 0,void 0,(function*(){t.forEach(((t,e)=>n[l[e]]=t));const e=this.func.prepare(n),i=yield e.call();let s=0;return p.forEach((t=>{t.prop.propertyType!==o.TYPE.DATA_FRAME?s=Math.max(s,Math.abs(t.target-i.getParamValue(t.prop.name))):hi(t.colName,t.target,i.getParamValue(t.prop.name),!1).forEach((t=>s=Math.max(s,Math.abs(t))))})),s}));let g,y,b;if(this.loss===ni.MAD?(g=v,y="maximum absolute devation"):(g=m,y="root mean square error"),this.method!==ti.NELDER_MEAD)throw new Error(`Not implemented the '${this.method}' method`);b=yield Ai(g,u,c,this.nelderMeadSettings,this.samplesCount);const w=b.extremums,A=w.length;if(A<this.samplesCount){this.failsDF=b.fails;const t=this.failsDF.columns;d.forEach(((e,n)=>t.byIndex(n).name=t.getUnusedName(e))),i.forEach((e=>{var n,i;const s=this.store.inputs[e];s.prop.propertyType!==o.TYPE.DATA_FRAME&&t.add(o.Column.fromList(s.prop.propertyType,t.getUnusedName(null!==(n=s.prop.caption)&&void 0!==n?n:s.prop.name),new Array(null===(i=this.failsDF)||void 0===i?void 0:i.rowCount).fill(s.const.value)))}))}const C=[],I=this.similarity;w.forEach((t=>{let e=!0;C.forEach((n=>e&&(e=function(t,e,n,i){const o=t.length;if(o!==e.length||o!==n.length||o!==i.length)throw new Error("Inconsistent found points");return t.reduce(((t,o,s)=>{const r=i[s]-n[s];return r>0?Math.max(t,Math.abs(o-e[s])/r):t}),0)}(n.point,t.point,u,c)>I))),e&&C.push(t)}));const S=C.length;if(A<this.samplesCount){if(A<1)return void t.shell.warning(e.divV([e.label(`Failed to find ${this.samplesCount} point${this.samplesCount>1?"s":""}`),e.div([this.showFailsBtn])]));t.shell.info(e.divV([e.label(`Found ${S} point${S>1?"s":""}`),e.div([this.showFailsBtn])]))}else t.shell.info(`Found ${S} point${S>1?"s":""}`);this.clearPrev(),C.sort(((t,e)=>t.cost-e.cost));const T=new Float32Array(S),E=this.comparisonView.grid,x=new Array(S),R=new Array(S),O=new Array(S),P=new Map([[si.LOSS,`The final loss obtained: ${y}`]]);let k=!0;const F=[];C.forEach(((t,e)=>Ci(this,void 0,void 0,(function*(){T[e]=t.cost;const n=this.getLossGraph(t);O[e]=n;const i=new Map,s=yield f(t.point);R[e]=s,p.forEach((t=>{this.getOutputGof(t.prop,t.target,s,t.colName,h).forEach((t=>i.set(t.caption,t.root)))})),x[e]=i,k&&(i.forEach(((t,e)=>{var n;P.set(e,"Goodness of fit"),null===(n=this.comparisonView.table)||void 0===n||n.columns.addNew(e,o.COLUMN_TYPE.STRING);const i=this.comparisonView.grid.columns.byName(e);i.cellType="html",i.width=oi.GOF_VIEWER_WIDTH,F.push(e)})),k=!1)}))));const N=o.DataFrame.fromColumns([o.Column.fromFloat32Array(si.LOSS,T)]);this.comparisonView.dataFrame=N;const L=N.columns;d.forEach(((t,e,n)=>{t=L.getUnusedName(t),n[e]=t;const i=new Float32Array(S);for(let t=0;t<S;++t)i[t]=C[t].point[e];L.add(o.Column.fromFloat32Array(t,i)),P.set(t,`Obtained values of '${t}'`)})),E.props.rowHeight=oi.ROW_HEIGHT,E.props.showAddNewRowIcon=!1,E.props.allowEdit=!1;const B=L.getUnusedName(`${this.loss} by iterations`);P.set(B,`Minimizing ${y}`),L.addNew(B,o.COLUMN_TYPE.STRING);const V=E.columns.byName(B);V.cellType="html",V.width=oi.LOSS_GRAPH_WIDTH;let M=!0;E.onCellPrepare((t=>Ci(this,void 0,void 0,(function*(){M&&(E.columns.setOrder(L.names().filter((t=>t!==B)).concat([B])),M=!1),t.isColHeader||t.isRowHeader||(t.isTableCell&&t.gridColumn.name===B&&null!==t.cell.value&&(t.style.element=O[t.gridRow]),F.forEach((n=>{var i;t.isTableCell&&t.gridColumn.name===n&&null!==t.cell.value&&void 0!==x[t.gridRow]&&(t.style.element=null!==(i=x[t.gridRow].get(n))&&void 0!==i?i:e.label(""))})))})))),E.columns.byName(si.LOSS).format="scientific",E.columns.byName(si.LOSS).width=oi.LOSS_COL_WIDTH,E.onCellTooltip((function(t,n,i){if(t.isColHeader&&t.tableColumn){const o=t.tableColumn.name,s=P.get(o);return e.tooltip.show(null!=s?s:"",n,i),!0}})),N.currentCell=N.cell(0,si.LOSS);const _=n=>Ci(this,void 0,void 0,(function*(){var i;if(null==n)return;const s=null!==(i=n.tableRowIndex)&&void 0!==i?i:0,r=R[s],l=[...r.outputParams.values()].filter((t=>o.TYPES_SCALAR.has(t.property.propertyType))),u=o.HtmlTable.create(l,(t=>{var e;return[null!==(e=t.property.caption)&&void 0!==e?e:t.property.name,r.outputs[t.property.name],t.property.options.units]})).root,c=[...r.outputParams.values()].filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME)).reduce(((t,e)=>{var n;const i=Dt(e.property).config,s=r.outputs[e.name],l=null!==(n=e.property.caption)&&void 0!==n?n:e.property.name;return i.map((e=>{const n=e.type,i=o.Viewer.fromType(n,s);i.setOptions(e),a()(i.root).css({width:"100%"}),t[l]?t[l].push(i.root):t[l]=[i.root]})),t}),{});let d;d=l.length>0?Object.assign({"Output scalars":[u]},c):Object.assign({},c);const p=e.accordion();if(a()(p.root).css({width:"100%"}),Object.entries(d).map((t=>{p.addPane(t[0],(()=>e.divV(t[1])))})),p.panes.length-1<0)throw new Error("Function has no outputs");p.panes[p.panes.length-1].expanded=!0,t.shell.o=p.root}));this.gridClickSubscription=E.onCellClick.subscribe(_),this.gridCellChangeSubscription=E.onCurrentCellChanged.subscribe(_)}catch(e){t.shell.error(e instanceof Error?e.message:"The platform issue")}}))}getOutputsOfInterest(){const t=[];for(const e of Object.keys(this.store.outputs)){const n=this.store.outputs[e];n.isInterest.value&&t.push(n)}return t}getLossGraph(t){return o.Viewer.lineChart(o.DataFrame.fromColumns([o.Column.fromList(o.COLUMN_TYPE.INT,si.ITER,[...Array(t.iterCount).keys()].map((t=>t+1))),o.Column.fromList(o.COLUMN_TYPE.FLOAT,si.LOSS,t.iterCosts.slice(0,t.iterCount))]),{showYAxis:!0,showXAxis:!0,showXSelector:!0,showYSelectors:!0,lineColoringType:"custom",lineColor:15274e3,markerColor:15274e3}).root}getOutputGof(t,e,n,i,s){var r;const a=t.propertyType,l=t.name,u=null!==(r=t.caption)&&void 0!==r?r:l;switch(a){case o.TYPE.FLOAT:case o.TYPE.INT:case o.TYPE.BIG_INT:return[{caption:u,root:o.Viewer.barChart(o.DataFrame.fromColumns([o.Column.fromStrings(u,["obtained","target"]),o.Column.fromList(a,si.VALUE,[n.getParamValue(l),e])]),{valueColumnName:si.VALUE,splitColumnName:u,valueAggrType:o.AGG.AVG,showValueSelector:!1,showCategorySelector:!1,showStackSelector:!1,showEmptyBars:!0}).root}];case o.TYPE.DATA_FRAME:const r=[],c=n.getParamValue(l),d=e,p=c.col(i),h=d.col(i),f=Dt(t).config;if(null===p||null===h)throw new Error("Creating viewer fails: incorrect argument column name");const m=p.getRawData(),v=pi(h,p),g=v.length,y=Array(g);v.forEach(((t,e)=>y[e]=m[t]));let b,w,A=null;return f.filter((t=>t.type===o.VIEWER.LINE_CHART)).forEach((t=>{const e=t.segmentColumnName;if(e){const t=Array(g);v.forEach(((n,i)=>t[i]=c.col(e).get(n))),A=o.Column.fromStrings(e,t)}})),d.columns.names().forEach((t=>{if(t!==i){if(w=c.col(t),null===w)throw new Error(`Creating viewer fails: no '${t}' column in the output dataframe`);b=w.getRawData();const e=Array(g);if(v.forEach(((t,n)=>e[n]=b[t])),w=d.col(t),null===w)throw new Error(`Creating viewer fails: no '${t}' column in the target dataframe`);b=w.getRawData();const n=Array(g);v.forEach(((t,e)=>n[e]=b[e]));const i={multiAxis:!0,yGlobalScale:!0},a=o.DataFrame.fromColumns([h,o.Column.fromList(w.type,si.OBTAINED,e),o.Column.fromList(w.type,si.TARGET,n)]);A&&(a.columns.add(A),i.segmentColumnName=A.name),r.push({caption:s?`${u}: [${t}]`:`[${t}]`,root:o.Viewer.lineChart(a,i).root})}})),r;default:throw new Error("Unsupported output type")}}clearPrev(){void 0!==this.helpDN&&(this.comparisonView.dockManager.close(this.helpDN),this.helpDN=void 0),this.gridClickSubscription&&(this.gridClickSubscription.unsubscribe(),this.gridClickSubscription=null),this.gridCellChangeSubscription&&(this.gridCellChangeSubscription.unsubscribe(),this.gridCellChangeSubscription=null)}showNelderMeadFails(){if(null===this.failsDF)return;const n=t.shell.addTableView(this.failsDF);n.addViewer(o.Viewer.form(o.DataFrame.fromColumns(Object.entries(this.nelderMeadSettings).map((t=>{var e;return o.Column.fromFloat32Array(null!==(e=vi.get(t[0]))&&void 0!==e?e:t[0],new Float32Array([t[1]]))})))),{description:"The Nelder-Mead method settings",showNavigation:!1});const i=this.getFittedInputs().length,s=new Map;this.failsDF.columns.names().forEach(((t,e)=>{e<i?s.set(t,`Initial value of "${t}" used in the Nelder-Mead method`):e>i?s.set(t,`Value of "${t}" (fixed input)`):s.set(t,"Error message raised")})),n.grid.onCellTooltip((function(t,n,i){if(t.isColHeader&&t.tableColumn){const o=t.tableColumn.name,r=s.get(o);return e.tooltip.show(null!=r?r:"",n,i),!0}}))}}var Ei,xi=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};!function(t){t.INPUTS="inputs",t.OUTPUTS="outputs"}(Ei||(Ei={}));const Ri={[Ei.INPUTS]:"inputParams",[Ei.OUTPUTS]:"outputParams"},Oi=()=>e.divText("[No data to display]",{style:{"text-align":"center","align-content":"center",width:"100%",height:"100%"}});class Pi extends xe{static fromFuncCall(t,e={historyEnabled:!0,isTabbed:!1}){return new this(t,e)}constructor(t,n={historyEnabled:!0,isTabbed:!1}){super(t,n),this.options=n,this.inputValidationRequests=new c.Subject,this.outputValidationRequests=new c.Subject,this.inputValidationUpdates=new c.Subject,this.outputValidationUpdates=new c.Subject,this.runRequests=new c.Subject,this.isRunning=new c.BehaviorSubject(!1),this.isUploadMode=new c.BehaviorSubject(!1),this.inputsOverride={},this.inputsMap={},this.outputValidationSigns={},this.inputValidators={},this.outputValidators={},this.inputValidationState={},this.outputValidationState={},this.externalValidatorsUpdates=new c.Subject,this.externalValidatorsState={},this.pendingInputValidations=this.inputValidationUpdates.pipe((0,s.startWith)(null),(0,s.map)((()=>this.inputValidationState))),this._isOutputOutdated=new c.BehaviorSubject(!0),this.isOutputOutdated=this._isOutputOutdated.pipe((0,s.distinctUntilChanged)()),this.blockRuns=new c.BehaviorSubject(!1),this.prevOpenedTab=null,this.beforeInputPropertyRender=new c.Subject,this.afterInputPropertyRender=new c.Subject,this.afterOutputPropertyRender=new c.Subject,this.afterOutputSacalarTableRender=new c.Subject,this.formButtons=e.div(),this.additionalBtns=[],this.navBtns=[],this.tabsElem=e.tabControl(),this.dfToViewerMapping={},this.focusedInput=null,this.foldedCategoryInputs={},this.sheetNamesCache={},this.richFunctionExport=t=>xi(this,void 0,void 0,(function*(){if("Excel"===t)try{const e=this.lastCall;if(!e)throw new Error("Function was not called");if(!this.exportConfig.supportedFormats.includes(t))throw new Error(`Format "${t}" is not supported.`);if(!this.func)throw new Error("The correspoding function is not specified");yield o.Utils.loadJsCss(["/js/common/exceljs.min.js"]);const n=window.ExcelJS,i="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",s=new n.Workbook,r=t=>o.TYPES_SCALAR.has(t),a=t=>t.propertyType===o.TYPE.DATA_FRAME,l=this.func.inputs.filter((t=>a(t))),u=this.func.inputs.filter((t=>r(t.propertyType))),c=this.func.outputs.filter((t=>a(t))),d=this.func.outputs.filter((t=>r(t.propertyType)));if(l.forEach((t=>{var n;const i=t.options.caption||t.name,o=null!==(n=s.worksheets.find((t=>t.name===this.getSheetName(i,s))))&&void 0!==n?n:s.addWorksheet(this.getSheetName(i,s)),r=e.inputs[t.name];st(o,r)})),u.length){const t=s.addWorksheet("Input scalars");it(t,u.map((t=>{var n,i,o;return{caption:null!==(n=t.options.caption)&&void 0!==n?n:t.name,value:null!==(i=e.inputs[t.name])&&void 0!==i?i:"",units:null!==(o=t.options.units)&&void 0!==o?o:""}})))}if(c.forEach((t=>{var n;const i=t.options.caption||t.name,o=null!==(n=s.worksheets.find((t=>t.name===this.getSheetName(i,s))))&&void 0!==n?n:s.addWorksheet(this.getSheetName(i,s)),r=e.outputs[t.name];st(o,r)})),d.length){const t=s.addWorksheet("Output scalars");it(t,d.map((t=>{var n,i,o;return{caption:null!==(n=t.options.caption)&&void 0!==n?n:t.name,value:null!==(i=e.outputs[t.name])&&void 0!==i?i:"",units:null!==(o=t.options.units)&&void 0!==o?o:""}})))}const p=this.tabsElem;for(const t of this.inputTabsLabels)for(const n of this.categoryToDfParamMap.inputs[t].filter((t=>a(t)))){const i=this.dfToViewerMapping[n.name].filter((t=>t.type!==o.VIEWER.GRID)).filter((t=>Object.values(m).includes(t.type)));if(0===i.length)continue;p.currentPane=p.getPane(t),yield new Promise((t=>setTimeout(t,100)));const r=n.options.caption||n.name,a=e.inputs[n.name];for(const[t,e]of i.entries())yield rt(s,s.getWorksheet(this.getSheetName(r,s)),e.root,a.columns.length+2,t>0?Math.ceil(i[t-1].root.clientHeight/20)+1:0)}for(const t of this.outputTabsLabels)for(const n of this.categoryToDfParamMap.outputs[t].filter((t=>a(t)))){const i=this.dfToViewerMapping[n.name].filter((t=>t.type!==o.VIEWER.GRID)).filter((t=>Object.values(m).includes(t.type)));if(0===i.length)continue;p.currentPane=p.getPane(t),yield new Promise((t=>setTimeout(t,100)));const r=n.options.caption||n.name,a=e.outputs[n.name];for(const[t,e]of i.entries())if(e.type===o.VIEWER.STATISTICS){const e=a.columns.length,n=o.DataFrame.fromColumns([o.Column.string("Name",e).init((t=>a.columns.byIndex(t).name)),o.Column.int("Values",e).init((t=>a.columns.byIndex(t).stats.valueCount)),o.Column.int("Nulls",e).init((t=>a.columns.byIndex(t).stats.missingValueCount)),o.Column.float("Min",e).init((t=>a.columns.byIndex(t).stats.min)),o.Column.float("Max",e).init((t=>a.columns.byIndex(t).stats.max)),o.Column.float("Avg",e).init((t=>a.columns.byIndex(t).stats.avg)),o.Column.float("Stdev",e).init((t=>a.columns.byIndex(t).stats.stdev))]);st(s.getWorksheet(this.getSheetName(r,s)),n,a.columns.length+2,t>0?Math.ceil(i[t-1].root.clientHeight/20)+1:0)}else yield rt(s,s.getWorksheet(this.getSheetName(r,s)),e.root,a.columns.length+2,t>0?Math.ceil(i[t-1].root.clientHeight/20)+1:0)}const h=yield s.xlsx.writeBuffer();return new Blob([h],{type:i})}catch(t){console.log(t)}if("DataUrl images"===t){const t={},e=t=>t.propertyType===o.TYPE.DATA_FRAME,n=this.tabsElem;yield o.Utils.loadJsCss(["/js/common/html2canvas.min.js"]);const i=window.html2canvas;for(const s of this.tabsLabels.filter((t=>this.inputTabsLabels.includes(t))))for(const r of this.categoryToDfParamMap.inputs[s].filter((t=>e(t)))){const e=this.dfToViewerMapping[r.name].filter((t=>t.type!==o.VIEWER.GRID&&t.type!==o.VIEWER.STATISTICS)).filter((t=>Object.values(m).includes(t.type)));if(0!==e.length){n.currentPane=n.getPane(s),yield new Promise((t=>setTimeout(t,100)));for(const[n,o]of e.entries()){const e=(yield i(o.root,{logging:!1})).toDataURL();t[r.name]||(t[r.name]={}),t[r.name][n]={dataUrl:e,width:o.root.clientWidth,height:o.root.clientHeight}}}}for(const s of this.tabsLabels.filter((t=>this.outputTabsLabels.includes(t))))for(const r of this.categoryToDfParamMap.outputs[s].filter((t=>e(t)))){const e=this.dfToViewerMapping[r.name].filter((t=>t.type!==o.VIEWER.GRID&&t.type!==o.VIEWER.STATISTICS)).filter((t=>Object.values(m).includes(t.type)));if(0!==e.length){n.currentPane=n.getPane(s),yield new Promise((t=>setTimeout(t,100)));for(const[n,o]of e.entries()){const e=(yield i(o.root,{logging:!1})).toDataURL();t[r.name]||(t[r.name]={}),t[r.name][n]={dataUrl:e,width:o.root.clientWidth,height:o.root.clientHeight}}}}return new Blob([JSON.stringify(t)],{type:"text/plain"})}throw new Error("Format is not supported")})),this.exportConfig={supportedExtensions:this.richFunctionViewExportExtensions(),supportedFormats:this.richFunctionViewSupportedFormats(),export:this.richFunctionExport,filename:this.defaultExportFilename}}onFuncCallReady(){const n=Object.create(null,{onFuncCallReady:{get:()=>super.onFuncCallReady}});return xi(this,void 0,void 0,(function*(){yield this.loadInputsOverrides(),yield this.loadValidators(Ei.INPUTS),yield this.loadValidators(Ei.OUTPUTS),yield n.onFuncCallReady.call(this);const i=this.funcCallReplaced.subscribe((()=>{this.inputValidationRequests.next({isRevalidation:!1}),this.outputValidationRequests.next({isRevalidation:!1})}));this.subs.push(i);const o=t=>(0,s.mergeMap)((e=>e.pipe((0,s.tap)((e=>{t===Ei.INPUTS?this.setInputValidationPending(e.field):this.setOutputValidationPending(e.field)})),(0,s.switchMap)((e=>{const n=new AbortController,i=n.signal;let o=!1;return new c.Observable((s=>{const r=(0,c.from)(this.runValidation(Object.assign({},e),i,t)).subscribe((t=>{o=!0,s.next(t)}));return()=>{o||n.abort(),r.unsubscribe()}})).pipe((0,s.tap)((n=>{t===Ei.INPUTS?this.setInputValidationResults(n):this.setOutputValidationResults(n),this.runRevalidations(e,n,t),t===Ei.INPUTS?this.inputValidationUpdates.next(null):this.outputValidationUpdates.next(null)})),(0,s.mapTo)(e))}))))),r=this.inputValidationRequests.pipe((0,s.groupBy)((t=>t.field)),o(Ei.INPUTS)).subscribe((t=>{t.field&&this.runningOnInput&&this.isRunnable()&&this.doRun()}));this.subs.push(r);const a=this.outputValidationRequests.pipe((0,s.groupBy)((t=>t.field)),o(Ei.OUTPUTS)).subscribe();this.subs.push(a);const l=this.externalValidatorsUpdates.subscribe((t=>{this.updateInputValidationResults(t)}));this.subs.push(l);const u=(0,c.combineLatest)([this.runRequests.pipe((0,s.switchMap)((()=>(0,c.of)(!1).pipe((0,s.delay)(500),(0,s.startWith)(!0))))),this.inputValidationUpdates.pipe((0,s.debounceTime)(0))]).pipe((0,s.filter)((([t])=>t&&this.isRunnable()))).subscribe((()=>this.doRun()));this.subs.push(u);const d=this.options.isTabbed?null:yield this.loadLastInputs();if(d)t.shell.info(e.div([e.divText("Do you want to load last inputs?"),e.divH([e.bigButton("Load",(()=>{for(const[t,e]of Object.entries(d)){const n=this.getInput(t);n.notify=!1,n.value=e,n.notify=!0}t.shell.info(e.divText("Change the loaded inputs to run computations"))}))])]));else{const t=new AbortController,e=yield this.runValidation({isRevalidation:!1},t.signal);this.setInputValidationResults(e),this.runRevalidations({isRevalidation:!1},e),this.inputValidationUpdates.next(null),this.runningOnStart&&this.isRunnable()&&(yield this.doRun())}}))}onBeforeRun(){return this.tabsElem.currentPane&&(this.prevOpenedTab=this.inputTabsLabels.includes(this.tabsElem.currentPane.name)?null:this.tabsElem.currentPane),Promise.resolve()}onAfterRun(){if(this.showOutput(),this.tabsElem.panes.forEach((t=>{a()(t.header).show()})),this.prevOpenedTab)return this.tabsElem.currentPane=this.prevOpenedTab,Promise.resolve();const t=this.tabsElem.panes.find((t=>this.outputTabsLabels.includes(t.name)));return t&&(this.tabsElem.currentPane=t),Promise.resolve()}getRunButton(t="Run"){var n;const i=e.bigButton(null!==(n=this.func.options.runLabel)&&void 0!==n?n:t,(()=>xi(this,void 0,void 0,(function*(){return yield this.doRun()})))),o=(0,c.merge)(this.inputValidationUpdates,this.externalValidatorsUpdates,this.isRunning,this.blockRuns).subscribe((()=>{const t=this.isRunnable();i.disabled=!t}));return this.subs.push(o),i}loadInputsOverrides(){return xi(this,void 0,void 0,(function*(){const e=[...this.funcCall.inputParams.values()];yield Promise.all(e.map((e=>xi(this,void 0,void 0,(function*(){if(e.property.options.input){const n=(yield t.functions.eval(e.property.options.input)).prepare({params:JSON.parse(e.property.options.inputOptions||"{}")});yield n.call(),this.inputsOverride[e.name]=n.outputs.input}})))))}))}loadValidators(){return xi(this,arguments,void 0,(function*(e=Ei.INPUTS){const n=[...this.funcCall[Ri[e]].values()];yield Promise.all(n.map((n=>xi(this,void 0,void 0,(function*(){if(n.property.options.validatorFunc){const i=(yield t.functions.eval(n.property.options.validatorFunc)).prepare({params:JSON.parse(n.property.options.validatorFuncOptions||"{}")});yield i.call(),e===Ei.INPUTS?this.inputValidators[n.name]=i.outputs.validator:this.outputValidators[n.name]=i.outputs.validator}})))))}))}keepOutput(){var t;return"true"===(null===(t=this.func)||void 0===t?void 0:t.options.keepOutput)}getSaveButton(t="Save"){const n=e.bigButton(t,(()=>xi(this,void 0,void 0,(function*(){return yield this.saveExperimentalRun(this.funcCall)}))),"Save uploaded data"),i=this.isUploadMode.subscribe((t=>{this.buildRibbonPanels(),t?a()(n).show():a()(n).hide()}));return this.subs.push(i),n}getStandardButtons(){const t=this.getRunButton(),n=e.div([t]);e.tooltip.bind(n,(()=>t.disabled?this.isRunning.value?"Computations are in progress":this.getValidationMessage():""));const i=this.getSaveButton();return[...this.isHistoryEnabled&&!this.options.isTabbed?[i]:[],...this.runningOnInput?[]:[n]]}buildFormButtons(){var t;const n=this.getStandardButtons(),i=e.buttonsInput();return a()(i.firstChild).css({display:"none"}),null===(t=i.lastChild)||void 0===t||t.replaceWith(e.div([...this.navBtns,...this.additionalBtns,...n],"ui-input-editor")),a()(i).addClass("rfv-buttons"),a()(i).css({"max-width":"100%"}),this.formButtons.replaceWith(i),this.formButtons=i,i}setAdditionalButtons(t){this.additionalBtns=t,this.buildFormButtons()}setNavigationButtons(t){this.navBtns=t}buildIO(){const{inputBlock:t,inputForm:n,outputForm:i,controlsWrapper:o}=this.buildInputBlock(),s=[...Array.from(n.childNodes),...this.isUploadMode.value?[Array.from(i.childNodes)]:[]];e.tools.handleResize(t,(()=>{a()(t).width()<300?(a()(n).addClass("ui-form-condensed"),a()(i).addClass("ui-form-condensed"),a()(o).addClass("ui-form-condensed"),s.forEach((t=>a()(t).css("min-width","100px")))):(a()(n).removeClass("ui-form-condensed"),a()(i).removeClass("ui-form-condensed"),a()(o).removeClass("ui-form-condensed"),s.forEach((t=>a()(t).css("min-width","100%"))))}));const r=this.buildOutputBlock();r.style.height="100%",r.style.width="100%",this.hideOutput();const l=e.splitH([t,e.panel([r],{style:{"padding-top":"0px"}})],null,!0);return l.style.padding="0 12px",t.style.maxWidth="360px",l}buildInputBlock(){const t=this.renderInputForm(),n=this.renderOutputForm();this.buildFormButtons();const i=e.div(this.formButtons,"ui-form ui-form-wide");a()(i).css({"padding-left":"0px","padding-bottom":"0px","padding-right":"6px","max-width":"100%","min-height":"50px"});const o=e.input.toggle("",{value:this.isUploadMode.value,onValueChanged:()=>this.isUploadMode.next(o.value)}),s=this.isUploadMode.subscribe((t=>{o.notify=!1,o.value=t,o.notify=!0,t?a()(n).show():a()(n).hide()}));return this.subs.push(s),{inputBlock:e.divV([t,...this.hasUploadMode&&!this.uploadFunc?[e.divH([e.h2("Experimental data"),o.root],{style:{"flex-grow":"0"}}),n]:[],i],"ui-box rfv-form"),inputForm:t,outputForm:n,controlsWrapper:i}}processCustomDataUpload(){return xi(this,void 0,void 0,(function*(){const n=()=>{const t=o.Dialog.create({title:"Select to compare"}),n=new qt(p.length>0?p:[...this.historyBlock.history.values()],{fallbackText:"No historical runs found",showActions:!(p.length>0),showBatchActions:!(p.length>0)}),i=new qt(d,{fallbackText:"No runs uploaded",showActions:!1,showBatchActions:!1});t.add(e.divV([e.divV([e.label("Uploaded runs"),e.element("div","splitbar-horizontal"),i.root],{style:{height:"50%","overflow-y":"hidden"}}),e.divV([e.label(p.length>0?"Simulated":"History",{style:{padding:"0px 10px 0px 9px"}}),e.element("div","splitbar-horizontal"),n.root],{style:{height:"50%","overflow-y":"hidden"}})],{style:{"justify-content":"space-between",gap:"10px","overflow-y":"scroll",height:"100%"}})),a()(t.root.querySelector(".d4-dialog-contents")).removeClass("ui-form");const s="Compare selected";return 0===p.length?t.addButton(s,(()=>xi(this,void 0,void 0,(function*(){const e=yield Promise.all([...n.selected].map((t=>pt.loadRun(t.id))));this.onComparisonLaunch([...e,...i.selected.values()]),t.close()})))):t.addButton(s,(()=>xi(this,void 0,void 0,(function*(){this.onComparisonLaunch([...n.selected.values(),...i.selected.values()]),t.close()})))),t.getButton(s).disabled=!0,this.subs.push((0,c.merge)(n.onSelectedChanged,i.onSelectedChanged).subscribe((()=>{n.selected.size+i.selected.size>1?t.getButton(s).disabled=!1:t.getButton(s).disabled=!0}))),this.isHistorical.value&&t.addButton(v,(()=>xi(this,void 0,void 0,(function*(){this.onComparisonLaunch([this.funcCall,...i.selected.values()]),t.close()})))),a()(t.getButton("CANCEL")).hide(),t},i=yield t.functions.eval(this.uploadFunc),r=yield i.prepare({params:{func:this.func}}).call(),l=r.outputs.uploadWidget,u=r.outputs.uploadFuncCall;let d=[],p=[];const h=o.Dialog.create({title:"Upload"});a()(h.root.querySelector(".d4-dialog-contents")).removeClass("ui-form");const f=o.Dialog.create({title:"Review uploaded runs"});a()(f.root.querySelector(".d4-dialog-contents")).removeClass("ui-form");const m="Save to history",v="Compare w/ current";h.add(l.root),h.addButton(m,(()=>xi(this,void 0,void 0,(function*(){return Mt(h.root,!0),d.forEach((t=>{t.options.immutable_tags?t.options.immutable_tags.push(A):t.options.immutable_tags=[A]})),Promise.all(d.map((t=>xi(this,void 0,void 0,(function*(){const e=yield this.getValidExpRun(t);return pt.saveRun(e)}))))).then((t=>Promise.all(t.map((t=>pt.loadRun(t.id)))))).then((t=>{t.forEach((t=>this.historyBlock.addRun(t)))})).catch((e=>{t.shell.error(e)})).finally((()=>{Mt(h.root,!1),h.close();const t=new qt(d,{fallbackText:"No runs uploaded",showActions:!0,showBatchActions:!0});f.add(t),f.show({modal:!0,fullScreen:!0})}))})))),h.addButton("Next",(()=>{h.close(),d.forEach((t=>{t.options.immutable_tags?t.options.immutable_tags.push(A):t.options.immutable_tags=[A]}));const t=new qt(d,{fallbackText:"No runs uploaded",showActions:!0,showBatchActions:!0});f.add(t.root),f.show({modal:!0,fullScreen:!0})})),a()(h.getButton("CANCEL")).hide(),h.getButton(m).disabled=!0,h.getButton("Next").disabled=!0,a()(f.getButton("CANCEL")).hide(),f.addButton("Simulate w/ same inputs",(()=>{Mt(h.root,!0),Promise.all(d.map((t=>this.func.prepare(_t(t).inputs).call()))).then((t=>{p=t,f.close(),n().show({modal:!0,fullScreen:!0})})).catch((e=>{t.shell.error(e)})).finally((()=>{Mt(h.root,!1)}))})),f.addButton("Compare w/ history",(()=>{f.close(),n().show({modal:!0,fullScreen:!0})}));const g=t.functions.onAfterRunAction.pipe((0,s.filter)((t=>t.id===u.id))).subscribe((()=>{d=u.outputs.uploadedCalls,h.getButton(m).disabled=!1,h.getButton("Next").disabled=!1})),y=h.onClose.subscribe((()=>{this.isUploadMode.next(!1)}));h.subs.push(y,g),h.show({modal:!0,center:!0,resizable:!0})}))}onSaveClick(){return xi(this,void 0,void 0,(function*(){this.isUploadMode.value?yield this.saveExperimentalRun(this.funcCall):yield this.saveRun(this.funcCall)}))}buildRibbonPanels(){super.buildRibbonPanels();const n=e.iconFA("play",(()=>xi(this,void 0,void 0,(function*(){return yield this.doRun()}))),"Run computations");n.classList.add("fas");const i=e.iconFA("arrow-to-top",(()=>xi(this,void 0,void 0,(function*(){this.uploadFunc?yield this.processCustomDataUpload():(this.isUploadMode.next(!this.isUploadMode.value),i.classList.toggle("d4-current"))}))),"Upload experimental data");i.classList.add("d4-toggle-button",...this.isUploadMode.value?["d4-current"]:[]);const o=e.iconFA("analytics",(()=>xi(this,void 0,void 0,(function*(){return yield this.onSALaunch()}))),"Run sensitivity analysis"),s=e.iconFA("chart-line",(()=>xi(this,void 0,void 0,(function*(){return yield this.onFittingLaunch()}))),"Fit inputs"),r=e.iconFA("info",(()=>xi(this,void 0,void 0,(function*(){this.hasContextHelp&&(t.shell.windows.help.visible=!0,yield new Promise((t=>setTimeout(t,100))),t.shell.windows.help.showHelp(e.markdown(yield this.getContextHelp())))})))),a=[[...super.buildRibbonPanels().flat(),...this.runningOnInput||this.options.isTabbed?[]:[n],...this.hasUploadMode?[i]:[],...this.isSaEnabled?[o]:[],...this.isFittingEnabled?[s]:[],...this.hasContextHelp?[r]:[]]];return this.setRibbonPanels(a),a}showOutput(){e.setDisplay(this.tabsElem.root,!0),this._isOutputOutdated.next(!1)}getViewers(t){return this.dfToViewerMapping[t]}buildOutputBlock(){this.tabsElem.root.style.width="100%",this.tabsLabels.forEach((n=>{const[i,r]=this.categoryToDfParamMap.outputs[n]?[this.categoryToDfParamMap.outputs[n],!1]:[this.categoryToDfParamMap.inputs[n],!0],l=i.filter((t=>t.propertyType===o.TYPE.DATA_FRAME||t.propertyType===o.TYPE.GRAPHICS)),u=i.filter((t=>t.propertyType!==o.TYPE.DATA_FRAME&&t.propertyType!==o.TYPE.GRAPHICS)),d=l.map((t=>nt(t).config));let p="";const h=l.reduce(((n,i,l)=>{var u,c;this.dfToViewerMapping[i.name]=[];const h=d[l].map(((n,s)=>xi(this,void 0,void 0,(function*(){var s,r,a,l;const u=null!==(l=null!==(r=null===(s=this.funcCall.outputs[i.name])||void 0===s?void 0:s.value)&&void 0!==r?r:null===(a=this.funcCall.inputParams[i.name])||void 0===a?void 0:a.value)&&void 0!==l?l:t.data.demo.demog(0),c=n.type,d=Object.values(m).includes(c)?o.Viewer.fromType(c,u):yield u.plot.fromType(c);d.setOptions(n),this.dfToViewerMapping[i.name].push(d),this.afterOutputPropertyRender.next({prop:i,output:d});const p=Oi();return 0===u.rowCount&&"demog 0"===u.name&&(e.setDisplay(d.root,!1),e.setDisplay(p,!0)),{viewer:d,stub:p}})))),f=h.map(((t,n)=>t.then((({viewer:t,stub:o})=>{const r=this.funcCallReplaced.pipe((0,s.startWith)(null),(0,s.switchMap)((()=>{var t;return(null!==(t=this.funcCall.outputParams[i.name])&&void 0!==t?t:this.funcCall.inputParams[i.name]).onChanged.pipe((0,s.startWith)(null))})),(0,s.skip)(1)).subscribe((()=>xi(this,void 0,void 0,(function*(){var s;const r=null!==(s=this.funcCall.outputParams[i.name])&&void 0!==s?s:this.funcCall.inputParams[i.name];if(r.value){if(e.setDisplay(t.root,!0),e.setDisplay(o,!1),Object.values(m).includes(t.type))t.dataFrame=r.value;else{const e=yield r.value.plot.fromType(t.type);t.root.replaceWith(e.root),t=e}Object.keys(d[l][n]).includes("color")&&t.setOptions({color:d[l][n].color}),this.afterOutputPropertyRender.next({prop:i,output:t})}else e.setDisplay(t.root,!1),e.setDisplay(o,!0)}))));return this.subs.push(r),{loadedViewer:t,stub:o}})))),v=p!==(null!==(u=i.options.caption)&&void 0!==u?u:i.name)?null!==(c=i.options.caption)&&void 0!==c?c:i.name:" ";if(p=v,r){const t=this.funcCallReplaced.pipe((0,s.switchMap)((()=>{var t;return(null!==(t=this.funcCall.outputParams[i.name])&&void 0!==t?t:this.funcCall.inputParams[i.name]).onChanged}))).subscribe((()=>{this.showOutput(),this.inputTabsLabels.forEach((t=>{a()(this.tabsElem.getPane(t).header).show()}))}));this.subs.push(t)}const g=f.map(((t,n)=>{const o=d[l][n].block,s=e.wait((()=>xi(this,void 0,void 0,(function*(){const n=yield t;return a()(n.loadedViewer.root).css({height:"100%",width:"100%"}),e.divV([n.loadedViewer.root,n.stub],{style:{width:"100%"}})}))));a()(s).css({"min-height":"300px","flex-grow":"1"});const r=W();return this.outputValidationSigns[i.name]=r,e.divV([e.divH([e.h2(0===n?v:" ",{style:{"white-space":"pre"}}),...0===n?[e.div([this.outputValidationSigns[i.name][0],this.outputValidationSigns[i.name][1]],{style:{margin:"10.79px"}})]:[]]),s],{style:Object.assign({},o?{width:`${o}%`,"max-width":`${o}%`,"max-height":"100%"}:{"flex-grow":"1"})})}));if(i.propertyType===o.TYPE.GRAPHICS){const t=i.options.block,o=Oi();o.classList.add("grok-scripting-image-container");const r=e.divV([e.h2(v,{style:{"white-space":"pre"}}),o],{style:Object.assign({},t?{width:`${t}%`,"max-width":`${t}%`,"max-height":"100%"}:{"flex-grow":"1"})}),a=()=>{var t;const e=null!==(t=this.funcCall.outputParams[i.name])&&void 0!==t?t:this.funcCall.inputParams[i.name];e.value?(o.style.backgroundImage=`url("data:image/png;base64,${e.value}")`,o.textContent=""):(o.style.removeProperty("background-image"),o.textContent="[No data to display]")},l=this.funcCallReplaced.pipe((0,s.startWith)(null),(0,s.switchMap)((()=>{var t;return(null!==(t=this.funcCall.outputParams[i.name])&&void 0!==t?t:this.funcCall.inputParams[i.name]).onChanged.pipe((0,s.startWith)(null))})),(0,s.skip)(1)).subscribe(a);this.subs.push(l),n.append(r)}return n.append(...g),n}),e.divH([],{style:{"flex-wrap":"wrap","flex-grow":"1","max-height":"100%"}}));u.forEach((t=>{const e=W();this.outputValidationSigns[t.name]=e}));const f=()=>{const t=o.HtmlTable.create(u,(t=>{var n;const i=t.options.precision,s=i&&t.propertyType===o.TYPE.FLOAT&&this.funcCall.outputs[t.name]?this.funcCall.outputs[t.name].toPrecision(i):this.funcCall.outputs[t.name],r=t.options.units?` [${t.options.units}]`:"";return[`${null!==(n=t.caption)&&void 0!==n?n:t.name}${r}`,null!=s?s:"[No value]",e.div([this.outputValidationSigns[t.name][0],this.outputValidationSigns[t.name][1]])]})).root;return a()(t).addClass("rfv-scalar-table"),this.afterOutputSacalarTableRender.next(t),t};let v=f();const g=(0,c.merge)(this.funcCallReplaced,this.isRunning.pipe((0,s.filter)((t=>!1===t)),(0,s.skip)(1))).subscribe((()=>{const t=f();v.replaceWith(t),v=t,a()(this.tabsElem.getPane(n).header).show()}));this.subs.push(g),this.tabsElem.addPane(n,(()=>e.divV([...l.length?[h]:[],...u.length?[v]:[]])))}));const n=e.box();return n.append(this.tabsElem.root),n}onAfterLoadRun(t){return xi(this,void 0,void 0,(function*(){this.showOutput()}))}get tabsLabels(){return[...this.inputTabsLabels,...this.outputTabsLabels]}get outputTabsLabels(){return Object.keys(this.categoryToDfParamMap.outputs)}get inputTabsLabels(){return Object.keys(this.categoryToDfParamMap.inputs)}get categoryToDfParamMap(){const t={inputs:{},outputs:{}};return this.func.inputs.filter((t=>t.propertyType===o.TYPE.DATA_FRAME&&0!==nt(t).config.length)).forEach((e=>{const n="Misc"===e.category?"Input":e.category;t.inputs[n]?t.inputs[n].push(e):t.inputs[n]=[e]})),this.func.outputs.forEach((e=>{const n="Misc"===e.category?"Output":e.category;e.propertyType===o.TYPE.DATA_FRAME&&0===nt(e).config.length||(t.outputs[n]?t.outputs[n].push(e):t.outputs[n]=[e])})),t}get inputsStorage(){return`RFV_LastInputs_${this.funcCall.func.name}`}saveLastInputs(){return xi(this,void 0,void 0,(function*(){try{const e=yield f()(this.funcCall.inputParams.values()).reduce(((e,n)=>xi(this,void 0,void 0,(function*(){const i=n.property.propertyType!==o.TYPE.DATA_FRAME?this.funcCall.inputs[n.name]:yield t.dapi.tables.uploadDataFrame(this.funcCall.inputs[n.name]);return Object.assign(Object.assign({},yield e),{[n.name]:JSON.stringify(i)})}))),Promise.resolve({}));return yield t.dapi.userDataStorage.put(this.inputsStorage,e)}catch(e){t.shell.error(e.toString())}}))}loadLastInputs(){return xi(this,void 0,void 0,(function*(){try{const e=yield t.dapi.userDataStorage.get(this.inputsStorage);return 0===Object.keys(e).length?null:yield f()(this.funcCall.inputParams.values()).reduce(((n,i)=>xi(this,void 0,void 0,(function*(){const s=i.property.propertyType!==o.TYPE.DATA_FRAME?JSON.parse(e[i.name]):yield t.dapi.tables.getTable(JSON.parse(e[i.name]));return Object.assign(Object.assign({},yield n),{[i.name]:s})}))),Promise.resolve({}))}catch(e){t.shell.error(e.toString())}}))}deleteLastInputs(){return xi(this,void 0,void 0,(function*(){try{return yield t.dapi.userDataStorage.put(this.inputsStorage,{})}catch(e){t.shell.error(e.toString())}}))}doRun(){return xi(this,void 0,void 0,(function*(){this.isRunning.next(!0);try{this.options.isTabbed||(yield this.saveLastInputs()),yield this.run(),this.options.isTabbed||(yield this.deleteLastInputs())}catch(e){t.shell.error(e.toString()),console.log(e)}finally{this.isRunning.next(!1),this.inputValidationRequests.next({isRevalidation:!1,isNewOutput:!0}),this.outputValidationRequests.next({isRevalidation:!1})}}))}setExternalValidationResults(t,e){this.externalValidatorsState[t]=e,this.externalValidatorsUpdates.next(t)}saveInputLockState(t,e,n){"restricted"===n&&(this.funcCall.options[y]=Object.assign(Object.assign({},this.funcCall.options[y]),{[t]:e})),n&&(this.funcCall.options[b]=Object.assign(Object.assign({},this.funcCall.options[b]),{[t]:n})),this.updateConsistencyState()}getInputLockState(t){var e;return null===(e=this.funcCall.options[b])||void 0===e?void 0:e[t]}updateConsistencyState(){const t=Object.values(this.funcCall.options[b]).some((t=>"inconsistent"===t));this.consistencyState.next(t?"inconsistent":"consistent")}getInput(t){return this.inputsMap[t]}setInput(t,e,n){const i=this.getInput(t);if(!i)throw new Error(`No input named ${t}`);if(this.funcCall.inputParams[t].property.propertyType===o.TYPE.DATA_FRAME&&"restricted"===n)throw new Error(`Param ${t} is dataframe. Restricted state is not supported for them.`);n||(n=this.funcCall.inputParams[t].property.propertyType===o.TYPE.DATA_FRAME?"disabled":"restricted"),this.funcCall.inputs[t]=e,this.setInputLockState(i,t,e,n)}getParamChanges(t){return this.funcCallReplaced.pipe((0,s.startWith)(null),(0,s.filter)((()=>!!this.funcCall)),(0,s.map)((()=>this.funcCall.inputParams[t]?"inputParams":"outputParams")),(0,s.switchMap)((e=>this.funcCall[e][t].onChanged.pipe((0,s.startWith)(null),(0,s.map)((()=>this.funcCall[e][t].value))))))}getParamValue(t){var e,n;const i=(null===(e=this.funcCall)||void 0===e?void 0:e.inputParams[t])?"inputParams":"outputParams";return null===(n=this.funcCall)||void 0===n?void 0:n[i][t].value}setInputLockState(t,e,n,i){i&&this.saveInputLockState(e,n,i),_(t)&&("disabled"===i&&t.setDisabled(),"restricted"===i&&t.setRestricted(),"restricted unlocked"===i&&t.setRestrictedUnlocked(),"inconsistent"===i&&t.setInconsistent(),"user input"===i&&t.setUserInput())}getRestrictedValue(t){var e;return null===(e=this.funcCall.options[y])||void 0===e?void 0:e[t]}renderOutputForm(){return this.renderIOForm(Ei.OUTPUTS)}onSALaunch(){return xi(this,void 0,void 0,(function*(){yield Qn.fromEmpty(this.func)}))}onFittingLaunch(){return xi(this,void 0,void 0,(function*(){yield Ti.fromEmpty(this.func)}))}renderInputForm(){return this.renderIOForm(Ei.INPUTS)}renderIOForm(t){const n=e.divH([],"ui-form ui-form-wide");a()(n).css({"flex-wrap":"wrap","flex-grow":"0","padding-right":"12px","padding-top":"0px","padding-left":"0px","max-width":"100%",gap:"4px"});let i="Misc";const o=this.funcCall[Ri[t]].values();return f()(o).filter((t=>!!t)).forEach((e=>{const o=e.property;this.beforeInputPropertyRender.next(o);const s=this.getInputForVal(e);s?(this.inputsMap[e.property.name]=s,t===Ei.INPUTS&&(this.syncInput(e,s,t),this.checkForMapping(e,s),this.runningOnInput||this.disableInputsOnRun(e.property.name,s),this.bindOnHotkey(s)),this.renderCategory(n,e.property.category,i),this.renderInput(n,e,s),this.afterInputPropertyRender.next({prop:o,input:s}),i=o.category):i=o.category})),Object.keys(this.foldedCategoryInputs).forEach((t=>this.foldedCategoryInputs[t].forEach((t=>a()(t.input.root).hide())))),n.classList.remove("ui-panel"),n}saveFocusedElement(t){this.focusedInput=t}restoreFocusedElement(){var t;null===(t=this.focusedInput)||void 0===t||t.focus()}disableInputsOnRun(t,e){const n=this.isRunning.subscribe((n=>{"user input"!==this.getInputLockState(t)&&this.getInputLockState(t)||(n?(tt(e)&&a()(e.input).is(":focus")&&this.saveFocusedElement(e.input),e.enabled=!1):(e.enabled=!0,tt(e)&&this.restoreFocusedElement()))}));this.subs.push(n)}checkForMapping(t,e){if(!e.hasOwnProperty("_chosenRun"))return;const n=t.property.options.funccallMapping;if(!n)return;const i=JSON.parse(n),o=this.funcCallReplaced.pipe((0,s.startWith)(!0),(0,s.switchMap)((()=>this.funcCall.inputParams[t.property.name].onChanged))).subscribe((()=>{Object.entries(i).forEach((([t,n])=>this.setInput(t,e.chosenRun?(t=>{var n,i,o,s,r,a;return null!==(a=null!==(s=null!==(i=null===(n=e.chosenRun)||void 0===n?void 0:n.inputs[t])&&void 0!==i?i:null===(o=e.chosenRun)||void 0===o?void 0:o.outputs[t])&&void 0!==s?s:null===(r=e.chosenRun)||void 0===r?void 0:r.options[t])&&void 0!==a?a:null})(n):Vt(this.funcCall.inputParams[t].property),e.chosenRun?"restricted":"user input")))}));this.subs.push(o)}getInputForVal(t){var n,i;const s=t.property;if(this.inputsOverride[t.property.name])return this.inputsOverride[t.property.name];if(s.propertyType===o.TYPE.STRING&&s.options.choices&&!s.options.propagateChoice)return e.input.choice(null!==(n=s.caption)&&void 0!==n?n:s.name,{value:Vt(s),items:JSON.parse(s.options.choices),nullable:s.nullable});switch(s.propertyType){case"file":return ne.fileInput(null!==(i=s.caption)&&void 0!==i?i:s.name,null,null,null);case o.TYPE.FLOAT:const t=e.input.forProperty(s),n=s.options.format;return n&&(t.format=n),t;default:return e.input.forProperty(s)}}bindOnHotkey(t){tt(t)&&(t.input.onkeydown=t=>xi(this,void 0,void 0,(function*(){"Enter"==t.key&&this.runRequests.next()})))}get foldedCategories(){var t;return JSON.parse(null!==(t=this.func.options.foldedCategories)&&void 0!==t?t:"[]")}getCategoryWarningIcon(t){const n=e.iconFA("exclamation-circle",null,"This category has inconsistent inputs");a()(n).css({color:"var(--orange-2)","padding-left":"5px"}).hide();const i=this.funcCallReplaced.subscribe((()=>{this.foldedCategoryInputs[t].some((t=>"inconsistent"===this.getInputLockState(t.paramName)&&t.input.value!==this.getRestrictedValue(t.paramName)))?a()(n).show():a()(n).hide()}));return this.subs.push(i),n}renderCategory(t,n,i){if(n!==i)if(this.foldedCategories.includes(n)){const i=this.getCategoryWarningIcon(n),o=e.iconFA("chevron-right",(()=>{var t;a()(s).show(),a()(o).hide(),a()(i).hide(),(null!==(t=this.foldedCategoryInputs[n])&&void 0!==t?t:[]).forEach((t=>a()(t.input.root).css({display:""})))}),"Open category");a()(o).css("padding-right","5px");const s=e.iconFA("chevron-down",(()=>{var t;a()(s).hide(),a()(o).show(),this.foldedCategoryInputs[n].some((t=>"inconsistent"===this.getInputLockState(t.paramName)))?a()(i).show():a()(i).hide(),(null!==(t=this.foldedCategoryInputs[n])&&void 0!==t?t:[]).forEach((t=>a()(t.input.root).hide()))}),"Close category");a()(s).css("padding-right","5px"),t.append(e.h2([o,s,e.h2(n,{style:{display:"inline"}}),i],{style:{width:"100%"}})),a()(s).hide()}else t.append(e.h2(n,{style:{width:"100%"}}))}renderInput(t,n,i){var o;const s=n.property;this.foldedCategories.includes(s.category)&&(this.foldedCategoryInputs[s.category]=[...null!==(o=this.foldedCategoryInputs[s.category])&&void 0!==o?o:[],{paramName:n.property.name,input:i}]),this.injectLockIcons(n,i),(t=>{if(_(t))return;const e=t;e.setDisabled=function(){t.enabled=!1,a()(t.root).removeClass("rfv-restricted-unlocked-input"),a()(t.root).removeClass("rfv-inconsistent-input"),a()(t.root).removeClass("rfv-restricted-input")},e.setRestricted=function(){t.enabled=!1,tt(t)&&(t.input.disabled=!1),a()(t.root).addClass("rfv-restricted-input"),a()(t.root).removeClass("rfv-restricted-unlocked-input"),a()(t.root).removeClass("rfv-inconsistent-input")},e.setRestrictedUnlocked=function(){t.enabled=!0,a()(t.root).addClass("rfv-restricted-unlocked-input"),a()(t.root).removeClass("rfv-restricted-input"),a()(t.root).removeClass("rfv-inconsistent-input")},e.setInconsistent=function(){t.enabled=!0,a()(t.root).addClass("rfv-inconsistent-input"),a()(t.root).removeClass("rfv-restricted-input"),a()(t.root).removeClass("rfv-restricted-unlocked-input")},e.setUserInput=function(){t.enabled=!0,a()(t.root).removeClass("rfv-inconsistent-input"),a()(t.root).removeClass("rfv-restricted-input"),a()(t.root).removeClass("rfv-restricted-unlocked-input")}})(i),tt(i)&&(((t,e)=>{var n;const i=t.property;a()(e.root).css({width:`calc(${null!==(n=i.options.block)&&void 0!==n?n:"100"}% - ${i.options.block?"2":"0"}px)`,"box-sizing":"border-box"})})(n,i),this.bindTooltips(n,i),(t=>{const n=e.element("i");t.addOptions(n),t.setValidation=function(e){for(;n.firstChild&&n.removeChild(n.firstChild););const[i,o]=W(e);i&&o&&(n.appendChild(i),n.appendChild(o)),t.input.classList.remove("d4-invalid"),t.input.classList.remove("d4-partially-invalid"),(null==e?void 0:e.errors)&&e.errors.length||(null==e?void 0:e.warnings)&&e.warnings.length||(null==e?void 0:e.notifications)&&e.notifications.length||(null==e?void 0:e.pending)?a()(n).css("display","flex"):a()(n).hide(),(null==e?void 0:e.errors)&&e.errors.length?t.input.classList.add("d4-invalid"):(null==e?void 0:e.warnings)&&e.warnings.length&&t.input.classList.add("d4-partially-invalid")}})(i)),t.append(i.root)}bindTooltips(t,n){const i=t.property.name,o=()=>{var n,o;const s=`${null!==(o=null!==(n=t.property.description)&&void 0!==n?n:t.property.caption)&&void 0!==o?o:t.property.name}.`,r=(()=>"disabled"===this.getInputLockState(i)?"Input is disabled to prevent inconsistency.":"inconsistent"===this.getInputLockState(i)?"The entered value is inconsistent to the computed value.":"restricted"===this.getInputLockState(i)?"The value is dependent and computed automatically. Click to edit":null)();return s||r?e.divV([...s?[e.divText(s)]:[],...r?[e.divText(r)]:[]],{style:{"max-width":"300px"}}):null};e.tooltip.bind(n.captionLabel,o),e.tooltip.bind(n.input,o)}injectLockIcons(t,n){const i=t.property.name;n.root.addEventListener("click",(()=>{"restricted"===this.getInputLockState(i)&&this.setInputLockState(n,t.name,t.value,"restricted unlocked")}));const s=e.iconFA("lock");a()(s).addClass("rfv-icon-lock"),a()(s).css({color:"var(--grey-2)"});const r=e.iconFA("lock-open");a()(r).addClass("rfv-icon-unlock"),a()(r).css({color:"var(--grey-2)"});const l=e.iconFA("undo",(e=>{this.setInput(t.name,this.getRestrictedValue(i),"restricted"),e.stopPropagation()}),"Reset value to computed value");a()(l).addClass("rfv-icon-undo"),a()(l).css({color:"var(--blue-2)"});const u=e.iconFA("exclamation-circle",null);e.tooltip.bind(u,(()=>`Current value is incosistent. Computed value was ${o.TYPES_SCALAR.has(t.property.propertyType)?this.getRestrictedValue(i):"different"}`)),a()(u).addClass("rfv-icon-warning"),a()(u).css({color:"var(--orange-2)"});const c=n;c.placeLockStateIcons||(c.placeLockStateIcons=function(t,e,i,o){tt(n)&&(n.addOptions(t),n.addOptions(e),n.addOptions(i),n.addOptions(o))}),c.placeLockStateIcons(s,r,l,u)}syncInput(t,e,n){const i=t.name;let r=!1;const a=this.funcCallReplaced.pipe((0,s.startWith)(!0)).subscribe((()=>{var t,o;const s=this.funcCall[Ri[n]][i],r=null!==(o=null!==(t=this.funcCall[n][i])&&void 0!==t?t:Vt(s.property))&&void 0!==o?o:null;e.notify=!1,e.value=r,e.notify=!0,this.funcCall[n][i]=r,this.setInputLockState(e,i,r,this.getInputLockState(i))}));this.subs.push(a);const l=this.funcCallReplaced.pipe((0,s.startWith)(!0),(0,s.switchMap)((()=>{const t=this.funcCall[Ri[n]][i];return t.onChanged.pipe((0,s.mapTo)(t))}))).subscribe((t=>{const i=this.funcCall[n][t.name];if(r||(e.notify=!1,e.value=i,e.notify=!0),n===Ei.INPUTS){this.isHistorical.next(!1),this.hideOutput(),this.inputValidationRequests.next({field:t.name,isRevalidation:!1});const n=this.getInputLockState(t.name);"restricted unlocked"!==n&&"inconsistent"!==n||this.setInputLockState(e,t.name,i,i===this.getRestrictedValue(t.name)?"restricted unlocked":"inconsistent")}}));this.subs.push(l);const u=this.funcCallReplaced.pipe((0,s.startWith)(!0),(0,s.switchMap)((()=>{const t=this.funcCall[Ri[n]][i];return t.onChanged.pipe((0,s.mapTo)(t),(0,s.startWith)(t))})),(0,s.filter)((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&t.value)),(0,s.switchMap)((t=>t.value.onDataChanged.pipe((0,s.mapTo)(t))))).subscribe((t=>{n===Ei.INPUTS?this.inputValidationRequests.next({field:t.name,isRevalidation:!1}):this.outputValidationRequests.next({field:t.name,isRevalidation:!1})}));this.subs.push(u);const d=(p=e.onInput.bind(e),new c.Observable((t=>{const e=p((e=>{t.next(e)}));return()=>e.unsubscribe()}))).pipe((0,s.debounceTime)(250)).subscribe((()=>{try{r=!0,this.funcCall[n][t.name]=e.value}finally{r=!1}}));var p;this.subs.push(d)}isRunnable(){return!this.isRunning.value&&!this.blockRuns.value&&this.isValid()}isValid(){for(const[t,e]of Object.entries(this.inputValidationState))if(!D(e))return!1;for(const[t,e]of Object.entries(this.externalValidatorsState))if(!D(e))return!1;return!0}getValidationState(){return this.inputValidationState}getValidationMessage(){const t=[];for(const[e,n]of Object.entries(this.inputValidationState))D(n)||t.push(`${e}: ${H(n)}`);return t.join("\n")}runValidation(t,e){return xi(this,arguments,void 0,(function*(t,e,n=Ei.INPUTS){const i=t.field,o=this.getValidatedNames(i,n),s=yield Promise.all(o.map((i=>xi(this,void 0,void 0,(function*(){const o=n===Ei.INPUTS?this.funcCall.inputs[i]:this.funcCall.outputs[i],s=yield(c=o,this._funcCall,this.lastCall,t.isNewOutput,t.isRevalidation,r=void 0,a=void 0,l=void 0,u=function*(){if(null==c)return U({errors:["Missing value"]})},new(l||(l=Promise))((function(t,e){function n(t){try{o(u.next(t))}catch(t){e(t)}}function i(t){try{o(u.throw(t))}catch(t){e(t)}}function o(e){var o;e.done?t(e.value):(o=e.value,o instanceof l?o:new l((function(t){t(o)}))).then(n,i)}o((u=u.apply(r,a||[])).next())})));var r,a,l,u,c;let d;const p=n===Ei.INPUTS?this.inputValidators[i]:this.outputValidators[i];p&&(d=yield p(o,{param:i,funcCall:this._funcCall,lastCall:this.lastCall,signal:e,isNewOutput:!!t.isNewOutput,isRevalidation:t.isRevalidation,context:t.context,view:this}));const h=n===Ei.INPUTS&&this.funcCall.inputParams[i].property.options.nullable;return[i,Y(...h?[]:[s],d)]})))));return Object.fromEntries(s)}))}setInputValidationPending(t){const e=this.getValidatedNames(t);for(const t of e){this.inputValidationState[t]={pending:!0};const e=this.inputsMap[t];M(e)&&e.setValidation({pending:!0})}this.inputValidationUpdates.next(null)}setOutputValidationPending(t){const e=this.getValidatedNames(t,Ei.OUTPUTS);for(const t of e){this.outputValidationState[t]={pending:!0};const e=this.outputValidationSigns[t];if(e){const n=W({pending:!0});e[0].replaceWith(n[0]),e[1].replaceWith(n[1]),this.outputValidationSigns[t]=n}}this.outputValidationUpdates.next(null)}setInputValidationResults(t){for(const[e,n]of Object.entries(t))this.inputValidationState[e]=n,this.updateInputValidationResults(e)}setOutputValidationResults(t){for(const[e,n]of Object.entries(t))this.outputValidationState[e]=n,this.updateOutputValidationResults(e)}updateOutputValidationResults(t){const e=this.outputValidationState[t],n=this.outputValidationSigns[t];n&&(this.outputValidationSigns[t]=((t,e)=>{const n=W(e);return t[0].replaceWith(n[0]),t[1].replaceWith(n[1]),n})(n,e))}updateInputValidationResults(t){const e=Y(this.inputValidationState[t],this.externalValidatorsState[t]),n=this.inputsMap[t];M(n)&&n.setValidation(e)}runRevalidations(t,e,n=Ei.INPUTS){if(!t.isRevalidation)for(const[,t]of Object.entries(e))if(null==t?void 0:t.revalidate)for(const e of t.revalidate)n===Ei.INPUTS?this.inputValidationRequests.next({field:e,context:t.context,isRevalidation:!0}):this.outputValidationRequests.next({field:e,context:t.context,isRevalidation:!0})}getValidatedNames(t,e=Ei.INPUTS){return t?[t]:[...e===Ei.INPUTS?this.funcCall.inputs.keys():this.funcCall.outputs.keys()]}getValidExpRun(e){return xi(this,void 0,void 0,(function*(){const n=yield(yield t.functions.eval("Sin")).prepare({x:1}).call();e.dart.r2=n.dart.r2;const i=e.options.immutable_tags||[];return e.options.immutable_tags=i.includes(A)?i:[...i,A],e.newId(),e}))}saveExperimentalRun(t){return xi(this,void 0,void 0,(function*(){const e=yield this.getValidExpRun(t);yield this.saveRun(e)}))}hideOutput(){if(this._isOutputOutdated.next(!0),this.keepOutput())return;this.outputTabsLabels.forEach((t=>{var e;return a()(null===(e=this.tabsElem.getPane(t))||void 0===e?void 0:e.header).hide()}));const t=this.tabsElem.panes.find((t=>this.inputTabsLabels.includes(t.name)));t?this.tabsElem.currentPane=t:a()(this.tabsElem.root).hide()}getSheetName(t,e){if(this.sheetNamesCache[t])return this.sheetNamesCache[t];let n=`${t}`;n.length>31&&(n=`${n.slice(0,31)}`);let i=1;for(;e.worksheets.some((t=>t.name.toLowerCase()===n.toLowerCase()));){let e=`${t}`;e.length>31-`-${i}`.length&&(e=`${t.slice(0,31-`-${i}`.length)}`),n=`${e}-${i}`,i++}return this.sheetNamesCache[t]=n,n}richFunctionViewSupportedFormats(){return["Excel","DataUrl images"]}richFunctionViewExportExtensions(){return{Excel:"xlsx","DataUrl images":"txt"}}}var ki=n(693),Fi=n.n(ki);function Ni(t){return null==t?void 0:t.nestedPipelines}function Li(t){return Fi()(t,(t=>{if("function"==typeof t)return t}))}function Bi(t,...e){return t.concat(...e)}function Vi(t){return t.filter((t=>t)).join("/")}function Mi(t){return t.split("/").filter((t=>t))}function _i(t){const e=Mi(t);return Vi(e.slice(0,e.length-1))}function Di(t,e){if(t.startsWith(e))return t.substring(e.length)}function ji(t){return Array.isArray(t[0])?t:[t]}function $i(t,e,n){var i;const o=[{node:t,path:[]}],s=new Set;for(;o.length;){const{node:t,path:a}=o.pop();if(Ni(t))if(s.has(t))n=e(n,t,a);else{o.push({node:t,path:a});for(const e of Object.values(null!==(i=t.nestedPipelines)&&void 0!==i?i:{}))o.push({node:e,path:[...a,t.id]});s.add(t)}else(null==(r=t)?void 0:r.nestedPipelines)||(n=e(n,t,a))}var r;return n}function Hi(e,n){return i=this,o=void 0,r=function*(){if("string"==typeof e){const i=(yield t.functions.eval(e)).prepare({params:n});return yield i.call(),i.outputs}return yield e(n)},new((s=void 0)||(s=Promise))((function(t,e){function n(t){try{l(r.next(t))}catch(t){e(t)}}function a(t){try{l(r.throw(t))}catch(t){e(t)}}function l(e){var i;e.done?t(e.value):(i=e.value,i instanceof s?i:new s((function(t){t(i)}))).then(n,a)}l((r=r.apply(i,o||[])).next())}));var i,o,s,r}function Ui(...t){console.log(...t)}class Yi{constructor(t,e,n,i){this.conf=t,this.pipelineState=e,this.parentId=n,this.notifier=i,this.currentSource=new c.BehaviorSubject((0,c.of)()),this.valueChanges=this.currentSource.pipe((0,s.switchMap)((t=>t))),this.value=new c.BehaviorSubject(void 0),this.setter=(t,e)=>{this.currentSource.next((0,c.of)(t))},this.valueChanges.pipe((0,s.takeUntil)(this.pipelineState.closed)).subscribe((t=>{Ui(`state updated: ${this.parentId}/${this.conf.id}, new value ${t}`),this.value.next(t)}))}linkState(t,e){this.currentSource.next(t),e&&(this.setter=e)}getValue(){return this.value.value}setValue(t,e){this.setter(t,e)}}class Wi{constructor(t,e,n){this.pipelinePath=t,this.from=[],this.to=[],this.fromKeys=new Set,this.toKeys=new Set,e&&(this.from=ji(e),this.fromKeys=new Set(this.from.map((t=>Vi(t))))),n&&(this.to=ji(n),this.toKeys=new Set(this.to.map((t=>Vi(t)))))}}class Gi{constructor(t,e,n,i){if(this.conf=t,this.type=e,this.pipelinePath=n,this.pipelineState=i,this.states=new Map,this.notifier=new c.Subject,"pipeline"===e){const e=t.states;for(const n of null!=e?e:[])this.states.set(n.id,new Yi(n,this.pipelineState,t.id))}if("step"===e){const e=t.states;for(const n of null!=e?e:[])this.states.set(n.id,new Yi(n,this.pipelineState,t.id))}if("popup"===e){const e=t.states;for(const n of null!=e?e:[])this.states.set(n.id,new Yi(n,this.pipelineState,t.id,this.notifier))}if("action"===e){const e=t;this.controllerConfig=new Wi(n,e.from,e.to)}}}class qi{constructor(t,e,n){this.conf=t,this.pipelinePath=e,this.pipelineState=n,this.enabled=new c.BehaviorSubject(!0),this.currentSource=new c.BehaviorSubject((0,c.of)()),this.externalTrigger=new c.Subject,this.valueChanges=this.currentSource.pipe((0,s.switchMap)((t=>t))),this.controllerConfig=new Wi(e,t.from,t.to)}setSources(t){this.currentSource.next((0,c.merge)(...t,this.externalTrigger))}trigger(){this.externalTrigger.next(!0)}getValuesChanges(){return this.valueChanges.pipe((0,s.withLatestFrom)(this.enabled),(0,s.filter)((([,t])=>!!t)),(0,s.mapTo)(!0))}}class zi extends Error{}class Ji{constructor(t,e,n,i){this.handlerId=t,this.config=e,this.rt=n,this.signal=i}enableLink(t){this.checkAborted();const e=Bi(this.config.pipelinePath,t);return this.rt.setLinkState(e,!0)}disableLink(t){this.checkAborted();const e=Bi(this.config.pipelinePath,t);return this.rt.setLinkState(e,!1)}isLinkEnabled(t){this.checkAborted();const e=Bi(this.config.pipelinePath,t);return this.rt.setLinkState(e,!1)}enableStep(t){this.checkAborted();const e=Bi(this.config.pipelinePath,t);if(this.checkOutput(e))return Ui(`handler: ${this.handlerId}, try enable step: ${Vi(e)}`),this.rt.setStepState(e,!0)}disableStep(t){this.checkAborted();const e=Bi(this.config.pipelinePath,t);if(this.checkOutput(e))return Ui(`handler: ${this.handlerId}, try enable step: ${Vi(e)}`),this.rt.setStepState(e,!1)}isStepEnabled(t){this.checkAborted();const e=Bi(this.config.pipelinePath,t);return this.rt.getStepState(e)}enablePipeline(t){this.checkAborted();const e=Bi(this.config.pipelinePath,t);if(this.checkOutput(e))return Ui(`handler: ${this.handlerId}, try enable pipeline: ${Vi(e)}`),this.rt.setPipelineState(e,!0)}disablePipeline(t){this.checkAborted();const e=Bi(this.config.pipelinePath,t);if(this.checkOutput(e))return Ui(`handler: ${this.handlerId}, try disable pipeline: ${Vi(e)}`),this.rt.setPipelineState(e,!1)}triggerLink(t){this.checkAborted();const e=Bi(this.config.pipelinePath,t);if(this.checkOutput(e))return this.rt.triggerLink(e)}getState(t){this.checkAborted();const e=Bi(this.config.pipelinePath,t);if(this.checkInput(e))return this.rt.getState(e)}setState(t,e,n){this.checkAborted();const i=Bi(this.config.pipelinePath,t);if(this.checkOutput(i))return Ui(`handler: ${this.handlerId}, try update state: ${Vi(i)}, value: ${e}`),this.rt.setState(i,e,n)}updateStateInputState(t,e){this.checkAborted();const n=Bi(this.config.pipelinePath,t);this.checkOutput(n)&&this.rt.setState(n,this.rt.getState(n),e)}getView(t){this.checkAborted();const e=Bi(this.config.pipelinePath,t);return this.rt.getView(e)}goToStep(t){this.checkAborted();const e=Bi(this.config.pipelinePath,t);return this.rt.goToStep(e)}setValidation(t,e){this.checkAborted();const n=Bi(this.config.pipelinePath,t),i=Mi(this.handlerId);this.checkValidation(n)&&(Ui(`handler: ${this.handlerId}: update validation: ${n}, value: ${e}`),this.rt.setValidation(n,i,e))}getValidationAction(t,e){this.checkAborted();const n=Bi(this.config.pipelinePath,t);return this.rt.getAction(n,e)}loadNestedPipeline(t,e){this.checkAborted();const n=Bi(this.config.pipelinePath,t);this.rt.loadNestedPipeline(n,e)}getCloseNotifier(){return this.rt.pipelineState.closed}checkAborted(){var t;if(null===(t=this.signal)||void 0===t?void 0:t.aborted)throw new zi}checkInput(e){const n=Vi(e);return this.config.fromKeys.has(n)||t.shell.warning(`Handler ${this.handlerId} has not declared access to input ${n}`),!0}checkOutput(e){const n=Vi(e);return this.config.toKeys.has(n)||t.shell.warning(`Handler ${this.handlerId} has not declared access to output ${n}`),!this.config.fromKeys.has(n)||(t.shell.error(`Handler ${this.handlerId} trying to set output value which is input ${n}`),!1)}checkValidation(e){const n=Vi(e);return this.config.toKeys.has(n)&&this.config.fromKeys.has(n)||t.shell.warning(`Handler ${this.handlerId} should declare both input and output access to set validation ${n}`),!0}}var Ki=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};class Zi{constructor(t,e,n,i){this.nodes=t,this.links=e,this.view=n,this.pipelineState=i,this.runningLinks=new Set,this.disabledSettersPrefixes=new Set,this.validationState=new Map,this.pipelineLoads=new c.Subject,this.isUpdating=new c.BehaviorSubject(!1),this.pipelineLoads.pipe((0,s.concatMap)((({path:t,runId:e})=>(0,c.from)(this.pipelineLoader(t,e)))),(0,s.takeUntil)(this.pipelineState.closed)).subscribe()}setLinkState(t,e){const n=Vi(t),i=this.links.get(n);i&&i.enabled.next(e)}getLinkState(t){const e=Vi(t),n=this.links.get(e);return!!(null==n?void 0:n.enabled.value)}setStepState(t,e){const n=Vi(t);this.isSetterDisabled(t,"step")||(Ui(`step visibility updated: ${n}, new value: ${e}`),e?this.view.showSteps(n):this.view.hideSteps(n))}getStepState(t){const e=Vi(t);return this.view.getStepState(e)===S.VISIBLE}setPipelineState(t,e){const n=this.getNestedSteps(t);for(const t of n)this.setStepState(Mi(t.pathKey),e)}loadNestedPipeline(t,e){this.pipelineLoads.next({path:t,runId:e})}triggerLink(t){const e=Vi(t),n=this.links.get(e);n&&n.trigger()}getState(t){const{state:e}=this.getNodeState(t);return null==e?void 0:e.getValue()}setState(t,e,n){const{state:i,node:o}=this.getNodeState(t);i&&!this.isSetterDisabled(t,o.type)&&i.setValue(e,n)}getView(t){const e=Vi(t);return this.view.getStepView(e)}setValidation(t,e,n){var i;const o=Vi(t),s=Vi(e),r=null!==(i=this.validationState.get(o))&&void 0!==i?i:new Map;r.set(s,n),this.validationState.set(o,r),this.updateViewValidation(t)}getAction(n,i){const o=Vi(n),s=this.nodes.get(o);if("action"!==(null==s?void 0:s.type)&&"popup"!==(null==s?void 0:s.type)){const e=`Node ${n.join(",")} is not an action/popup`;throw t.shell.error(e),new Error(e)}if("action"===s.type){const e=s.conf,n=e.handler,o=s.controllerConfig;return{actionName:null!=i?i:e.friendlyName,action:()=>Ki(this,void 0,void 0,(function*(){try{const t=new Ji(s.conf.id,o,this);yield Hi(n,{controller:t})}catch(e){throw t.shell.error(String(e)),e}}))}}{const n=s.conf,o=this.view.getStepView(n.id);if(!o){const e=`Popup view ${n.id} not found`;throw t.shell.error(e),new Error(e)}return{actionName:null!=i?i:n.friendlyName,action:()=>Ki(this,void 0,void 0,(function*(){try{yield new Promise(((t,i)=>{e.dialog(n.friendlyName).add(o.root).onOK((()=>{s.notifier.next(!0),t(!0)})).onCancel((()=>{t(!1)})).showModal(!0)}))}catch(e){throw t.shell.error(String(e)),e}}))}}}wireViews(){for(const[,t]of this.nodes)for(const[,e]of t.states)if(!("popup"!==t.type&&"step"!==t.type||"input"!==e.conf.stateType&&"output"!==e.conf.stateType)){const n=e.conf.id,{changes:i,setter:o}=this.view.getStateBindings(t.conf.id,n);e.linkState(i,o)}}wireLinks(){var t;for(const[,e]of this.links){const n=e.controllerConfig.from.map((t=>this.getValueChanges(t,e))),i=null!==(t=e.conf.handler)&&void 0!==t?t:this.getDefaultHandler(e);e.getValuesChanges().pipe((0,s.debounceTime)(0),(0,s.switchMap)((()=>this.getHandlerObservable(e,i))),(0,s.takeUntil)(this.pipelineState.closed)).subscribe(),e.setSources(n)}}getHandlerObservable(e,n){return new c.Observable((i=>{this.addRunningHandler(e.conf.id);const o=new AbortController,r=o.signal,a=new Ji(e.conf.id,e.controllerConfig,this,r);let l=!1;const u=(0,c.from)(Hi(n,{controller:a})).pipe((0,s.finalize)((()=>this.removeRunningHandler(e.conf.id)))).subscribe((t=>{l=!0,i.next(t)}),(e=>{e instanceof zi||(t.shell.error(e),console.error(e))}));return()=>{l||o.abort(),u.unsubscribe()}}))}getValueChanges(t,e){const{state:n}=this.getNodeState(t),i=e.conf.includeDataFrameMutations?n.value.pipe((0,s.switchMap)((t=>{var e;return(null==t?void 0:t.onDataChanged)&&(null===(e=null==t?void 0:t.onDataChanged)||void 0===e?void 0:e.pipe)?t.onDataChanged.pipe((0,s.startWith)(null),(0,s.mapTo)(t)):(0,c.of)(t)}))):n.value,o=n.notifier;return e.conf.ignoreNotifier||!o?i:i.pipe((0,s.sample)(o))}getDefaultHandler(t){return()=>Ki(this,void 0,void 0,(function*(){const e=Math.min(t.controllerConfig.from.length,t.controllerConfig.to.length);for(let n=0;n<e;n++){let e=this.getState(t.controllerConfig.from[n]);e instanceof o.DataFrame&&(e=e.clone()),this.setState(t.controllerConfig.to[n],e,t.conf.inputState)}}))}getRunningUpdates(){return[...this.runningLinks]}goToStep(t){console.log("TODO: not implemented")}disableSubStepsIOSetters(t){const e=Vi(t);Ui(`disable substeps setters: ${e}`),this.disabledSettersPrefixes.add(e)}enableSubStepsIOSetters(t){const e=Vi(t);Ui(`enable substeps setters: ${e}`),this.disabledSettersPrefixes.delete(e)}awaitForAllUpdatesDone(){return Ki(this,void 0,void 0,(function*(){yield this.isUpdating.pipe((0,s.debounceTime)(1),(0,s.filter)((t=>!t)),(0,s.take)(1)).toPromise()}))}pipelineLoader(t,e){return Ki(this,void 0,void 0,(function*(){this.setPipelineState(t,!1),this.disableSubStepsIOSetters(t);try{const n=yield this.loadPipelineFuncCalls(e),i=this.getNestedSteps(t);yield this.loadNestedSteps(n,i),yield this.awaitForAllUpdatesDone()}finally{this.enableSubStepsIOSetters(t)}}))}loadNestedSteps(t,e){return Ki(this,void 0,void 0,(function*(){const n=new Map;for(const t of e)n.set(t.nestedStepId,t);for(const e of t){const t=e.options.customId,i=n.get(t);if(i){const t=this.view.getStepView(i.pathKey);if(t){Ui(`loaded step: ${i.pathKey}, nqName: ${i.nqName}, id: ${e.id}`);const n=yield t.loadRun(e.id);this.view.showSteps(i.pathKey),K(n)||this.view.enableStep(i.pathKey)}}}const i=this.view.getFollowingStep();i&&i.ability.next(T.ENABLED)}))}getNestedSteps(t){const e=Vi(t),n=t[t.length-1];return[...this.nodes.entries()].filter((([t,n])=>"step"===n.type&&Di(t,e))).map((([t,i])=>{const o=t,s=Di(t,e);return{pathKey:o,nestedStepId:Vi(Bi([n],Mi(s))),nqName:i.conf.nqName}}))}loadPipelineFuncCalls(t){return Ki(this,void 0,void 0,(function*(){return(yield pt.loadChildRuns(t)).childRuns}))}addRunningHandler(t){this.runningLinks.add(t),this.isUpdating.next(!0)}removeRunningHandler(t){this.runningLinks.delete(t),this.isUpdating.next(0!==this.runningLinks.size)}isSetterDisabled(t,e){if("step"===e){const e=Vi(t);for(const t of this.disabledSettersPrefixes)if(Di(e,t))return!0}return!1}getNodeState(t){const e=t.slice(0,t.length-1),n=t[t.length-1],i=Vi(e),o=this.nodes.get(i);if(o&&o.states){const t=o.states.get(n);if(t)return{node:o,state:t}}}updateViewValidation(t){const e=Vi(t),n=this.validationState.get(e),i=[...n.keys()].sort().map((t=>n.get(t))),{state:o,node:s}=this.getNodeState(t);this.view.setExternalValidationResults(s.conf.id,o.conf.id,Y(...i))}}class Xi{constructor(){this.closed=new c.Subject}}var Qi=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};class to extends xn{constructor(t,e={historyEnabled:!0,isTabbed:!1,skipInit:!0}){super(t,[],e),this.hooks=[],this.customViews=new Map}injectConfiguration(t,e,n,i){i&&(this.exportConfig=Object.assign(Object.assign({},this.exportConfig),i)),this.initialConfig=t.map((t=>Object.assign(Object.assign({},t),{customId:t.id}))),this.hooks=e,this.rt=n,this.rt.isUpdating.pipe((0,s.takeUntil)(this.rt.pipelineState.closed)).subscribe((t=>this.isUpdating.next(t)))}getStateBindings(t,e){const n=this.getStepView(t);return{changes:n.getParamChanges(e),setter:(t,i)=>{n.setInput(e,t,i)}}}setExternalValidationResults(t,e,n){const i=this.getStepView(t);i&&i.setExternalValidationResults(e,n)}addMenuItem(t,e){var n;null===(n=this.actionsMenu)||void 0===n||n.item(t,e)}enableStep(t){this.steps[t].ability.next(T.ENABLED)}getStepState(t){return this.steps[t].visibility.value}getFollowingStep(){return Object.values(this.steps).filter((t=>t.visibility.value===S.VISIBLE&&t.ability.value===T.DISABLED))[0]}getRunningUpdates(){return this.rt.getRunningUpdates()}buildRibbonMenu(){super.buildRibbonMenu(),this.actionsMenu=this.ribbonMenu.group("Actions")}getStepView(t){return super.getStepView(t)||this.customViews.get(t)}init(){const t=Object.create(null,{init:{get:()=>super.init}});return Qi(this,void 0,void 0,(function*(){this.rt.disableSubStepsIOSetters([]),yield this.execHooks("beforeInit"),yield t.init.call(this),yield this.execHooks("afterInit")}))}onBeforeStepFuncCallApply(t,e,n){return Qi(this,void 0,void 0,(function*(){yield this.execHooks("beforeFuncCallReady",{nqName:t,scriptCall:e,editorFunc:n})}))}onAfterStepFuncCallApply(t,e,n){return Qi(this,void 0,void 0,(function*(){yield this.execHooks("afterFuncCallReady",{nqName:t,scriptCall:e,view:n})}))}onBeforeLoadRun(){const t=Object.create(null,{onBeforeLoadRun:{get:()=>super.onBeforeLoadRun}});return Qi(this,void 0,void 0,(function*(){this.rt.disableSubStepsIOSetters([]),yield t.onBeforeLoadRun.call(this),yield this.execHooks("beforeLoadRun")}))}onAfterLoadRun(t){const e=Object.create(null,{onAfterLoadRun:{get:()=>super.onAfterLoadRun}});return Qi(this,void 0,void 0,(function*(){yield e.onAfterLoadRun.call(this,t),yield this.rt.awaitForAllUpdatesDone(),this.rt.enableSubStepsIOSetters([]),yield this.execHooks("afterLoadRun",{run:t})}))}onBeforeSaveRun(){const t=Object.create(null,{onBeforeLoadRun:{get:()=>super.onBeforeLoadRun}});return Qi(this,void 0,void 0,(function*(){this.rt.disableSubStepsIOSetters([]),yield t.onBeforeLoadRun.call(this),yield this.execHooks("beforeSaveRun")}))}onAfterSaveRun(t){const e=Object.create(null,{onAfterLoadRun:{get:()=>super.onAfterLoadRun}});return Qi(this,void 0,void 0,(function*(){yield e.onAfterLoadRun.call(this,t),yield this.rt.awaitForAllUpdatesDone(),this.rt.enableSubStepsIOSetters([]),yield this.execHooks("afterSaveRun",{run:t})}))}build(){super.build(),this.rt.wireViews(),this.rt.wireLinks(),this.rt.enableSubStepsIOSetters([]),this.execHooks("onViewReady",{view:this})}close(){this.rt.pipelineState.closed.next(!0);for(const t of this.customViews.values())t.customClose();super.close()}execHooks(t){return Qi(this,arguments,void 0,(function*(t,e={}){for(const{hooks:n,pipelinePath:i}of this.hooks){const o=n[t];for(const t of null!=o?o:[]){const n=t.handler,o=new Wi(i,t.from,t.to),s=new Ji(t.id,o,this.rt),r=Object.assign(Object.assign({},e),{controller:s});yield Hi(n,r)}}}))}}class eo extends Pi{detach(){}customClose(){super.detach(),super.close()}}var no=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))},io=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};function oo(e){return()=>io(this,void 0,void 0,(function*(){try{const n=yield t.dapi.groups.filter(`friendlyName="${e}"`).list();if(0===n.length)throw new Error("group with specified name is not found");if(n.length>1)throw new Error("found more than one group with specified name");const i=n[0];fetch(`${window.location.origin}/api/groups/${i.id}/requests/${t.shell.user.group.id}`,{method:"POST"})}catch(e){t.shell.error(e.toString())}}))}class so extends o.ObjectHandler{get type(){return"Model"}getById(e){return io(this,void 0,void 0,(function*(){return yield t.dapi.functions.find(e)}))}refresh(t){return io(this,void 0,void 0,(function*(){return yield this.getById(t.id)}))}static openHelp(n){return io(this,void 0,void 0,(function*(){if(null!=n.options.readme){t.shell.windows.showHelp=!0,yield new Promise((t=>setTimeout(t,100)));const i=`System:AppData/${n.package.name}/${n.options.readme}`;t.dapi.files.readAsText(i).then((n=>{t.shell.windows.help.showHelp(e.markdown(n))}))}}))}static openModel(t){t.prepare().edit()}static openModelFromFunccall(t){t.edit()}isApplicable(t){const e=o.toJs(t);return e instanceof o.Func&&e.hasTag("model")}constructor(){super(),this.userGroups=new c.BehaviorSubject(void 0)}getLanguageIcon(t){return"grok"==t?e.iconSvg("project"):e.iconImage("script",`/images/entities/${t}.png`)}renderMarkup(n){const i=e.divH([],{style:{"justify-content":"space-between",width:"100%"}});return setTimeout((()=>io(this,void 0,void 0,(function*(){const o=yield this.awaitUserGroups(),s=JSON.parse(n.options.mandatoryUserGroups?`${n.options.mandatoryUserGroups}`:"[]").filter((t=>!o.map((t=>t.friendlyName)).includes(t.name))),r=s.length>0,a=e.iconFA("exclamation-triangle",null);a.classList.remove("grok-icon");const l=()=>{const t=e.iconFA("times");return t.style.marginRight="6px",t.classList.remove("grok-icon"),t},u=e.div(e.divV([e.label("You should be a member of the following group(s):",{style:{marginLeft:"0px"}}),...s.map((t=>e.divV([e.span([l(),t.name],{style:{"font-weight":600}}),...t.help?[e.span([t.help],{style:{marginLeft:"16px"}})]:[],e.link("Request group membership",oo(t.name),void 0,{style:{marginLeft:"16px"}})])))],{style:{gap:"10px"}})),c=e.span([this.renderIcon(n),e.label(n.friendlyName)]);var d;i.onclick=()=>{t.shell.windows.help.visible&&so.openHelp(n)},r?c.classList.add("d4-disabled"):i.ondblclick=()=>{so.openModel(n)},r&&(function(t){t.popover="auto",t.style.cursor="default",t.style.padding="10px",t.style.background="#fdffe5",t.style.border="1px solid #E4E6CE",t.style.borderRadius="2px",t.style.boxShadow="0 0 5px #E4E6CE",t.style.maxWidth="500px",t.style.color="var(--gray-6)"}(d=u),document.body.append(d),i.addEventListener("click",(()=>{!function(t,e){!function(t,e){const n=t.getBoundingClientRect().toJSON();e.style.inset="unset",e.style.top=n.y+"px",e.style.left=n.x+20+"px"}(t,e),e.showPopover()}(a,u)}))),i.append(c),r&&i.append(e.span([a]))})))),i}renderIcon(t){if(null!=t.options.icon&&(t.options.icon.startsWith("http://")||t.options.icon.startsWith("https://")))return e.iconImage("model-icon",t.options.icon);if(t instanceof o.Script)return this.getLanguageIcon(t.language);let n=(t=o.Func.find({package:t.package.name,name:t.name})[0]).package.getIconUrl();if(null!=t.options.icon){const e=n.split("/");e.pop(),e.push(t.options.icon),n=e.join("/")}return e.iconImage(t.package.name,n)}renderPreview(e){const n=Object.create(null,{renderPreview:{get:()=>super.renderPreview}});return io(this,void 0,void 0,(function*(){var i;const s=null!==(i=e.options.editor)&&void 0!==i?i:"Compute:RichFunctionViewEditor",r=yield t.functions.find(s);if(null!==r&&r instanceof o.Func){const t=r.prepare({call:e.prepare()});yield t.call(!1,void 0,{processed:!0});const n=t.getOutputParamValue();if(n instanceof o.View)return n}return n.renderPreview.call(this,e)}))}renderProperties(t){const n=e.accordion("ComputeModel");n.context=t;const i=e.div([e.span([this.renderIcon(t),e.label(t.friendlyName),e.contextActions(t),e.star(t.id)])]);return n.addTitle(i),null!=t.description&&i.appendChild(e.div([e.markdown(t.description)],"model-catalog-description")),i.appendChild(e.tags(t)),null!=t.options["dev.status"]&&i.appendChild(e.tableFromMap({Status:t.options["dev.status"]})),n.end(),n.root}renderTooltip(t){const n=e.span([this.renderIcon(t),e.label(t.friendlyName)]);return n.classList.add("d4-link-label"),e.bind(t,e.divV([e.h2(n),e.divV([e.divText(t.description,"ui-description")],{style:{lineHeight:"150%"}})]))}renderCard(t){const n=this.renderMarkup(t);return n.classList.add("d4-link-label"),e.bind(t,e.h2(n))}init(){this.registerParamFunc("Help",(t=>{so.openHelp(o.toJs(t))})),setTimeout((()=>io(this,void 0,void 0,(function*(){const t=yield(yield fetch(`${window.location.origin}/api/groups/all_parents`)).json();this.userGroups.next(t)}))))}awaitUserGroups(){return io(this,void 0,void 0,(function*(){return this.userGroups.pipe((0,s.filter)((t=>!!t)),(0,s.map)((t=>t)),(0,s.take)(1)).toPromise()}))}}var ro=n(847),ao={};ao.styleTagTransform=St(),ao.setAttributes=wt(),ao.insert=yt().bind(null,"head"),ao.domAPI=vt(),ao.insertStyleElement=Ct(),ft()(ro.A,ao),ro.A&&ro.A.locals&&ro.A.locals;class lo extends o.CustomCardView{static findOrCreateCatalogView(t,e,n){var i;return null!==(i=this.findModelCatalogView(e))&&void 0!==i?i:this.createModelCatalogView(t,e,n)}static createModelCatalogView(t,e,n){const i=o.Func.find({package:n.name,name:e})[0].prepare(),s=new this(t,e);return s.parentCall=i,s}static findModelCatalogView(e){return f()(t.shell.views).find((t=>{var n;return(null===(n=t.parentCall)||void 0===n?void 0:n.func.name)==e}))}bindModel(t){var e;t.aux.showOnTaskBar=!1;const n=this.parentCall;null!=n&&(n.aux.view=null!==(e=lo.findModelCatalogView(this.funcName))&&void 0!==e?e:this,t.parentCall=n)}constructor(e,n){if(super({dataSource:t.dapi.functions,permanentFilter:"#model"}),this.funcName=n,this.isHelpOpen=!1,this.root.classList.add("model-catalog-view"),this.meta=new so,this.name=e,this.permanentFilter="#model",this.renderMode=o.RENDER_MODE.BRIEF,this.objectType="Func",this.categoryFilters={"options.department":"Department","options.HL_process":"HL_process","options.process":"Process",tag:"Tags"},this.filters={All:"",Favorites:"starredBy = @current","Used by me":"usedBy = @current"},this.hierarchy=["options.department","options.HL_process","options.process"],this.hierarchyProperties={"options.department":"Department","options.HL_process":"HL_process","options.process":"Process"},this.showTree=!0,this.initRibbon(),this.initMenu(),t.shell.windows.showProperties=!1,t.shell.windows.showHelp=this.isHelpOpen,!lo.findModelCatalogView(this.funcName)){const e=t.functions.onBeforeRunAction.subscribe((t=>{var e,n;t.func.hasTag("model")?this.bindModel(t):(null===(n=null===(e=t.inputs)||void 0===e?void 0:e.call)||void 0===n?void 0:n.func)instanceof o.Func&&t.inputs.call.func.hasTag("model")&&this.bindModel(t.inputs.call)})),n=t.events.onCurrentViewChanged.subscribe((()=>{return e=this,n=void 0,o=function*(){t.shell.v===this&&(t.shell.windows.showHelp=this.isHelpOpen)},new((i=void 0)||(i=Promise))((function(t,s){function r(t){try{l(o.next(t))}catch(t){s(t)}}function a(t){try{l(o.throw(t))}catch(t){s(t)}}function l(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i((function(t){t(n)}))).then(r,a)}l((o=o.apply(e,n||[])).next())}));var e,n,i,o}));this.subs.push(e,n)}}initRibbon(){}initMenu(){this.ribbonMenu.group("Help").item("Compute Engine",(()=>window.open("https://github.com/datagrok-ai/public/tree/master/packages/Compute","_blank"))).item("Developing Models",(()=>window.open("https://datagrok.ai/help/compute/scripting","_blank"))).endGroup()}}var uo=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};let co=!1;const po=new o.Package;function ho(t){so.openModelFromFunccall(t)}function fo(){return new u}function mo(t){return Pi.fromFuncCall(t,{historyEnabled:!0,isTabbed:!1})}function vo(t){return Pi.fromFuncCall(t,{historyEnabled:!1,isTabbed:!0})}function go(n){return uo(this,void 0,void 0,(function*(){let i={};n.inputs.forEach((t=>i[t.name]=null));let s=`\ncurl --location --request POST '${t.settings.apiUrl}/v1/func/${n.nqName}/run' \\\n--header 'Authorization: ${yo("auth")}' \\\n--header 'Content-Type: application/json' \\\n--data-raw '${JSON.stringify(i)}'`,r=`\nvar myHeaders = new Headers();\nmyHeaders.append("Authorization", "${yo("auth")}");\nmyHeaders.append("Content-Type", "application/json");\n\nvar raw = JSON.stringify(${JSON.stringify(i)});\n\nvar requestOptions = {\n method: 'POST',\n headers: myHeaders,\n body: raw,\n redirect: 'follow'\n};\n\nfetch("${t.settings.apiUrl}/v1/func/${n.nqName}/run", requestOptions)\n .then(response => response.text())\n .then(result => console.log(result))\n .catch(error => console.log('error', error));`,a=e.tabControl({CURL:e.div([e.divText(s)]),JS:e.div([e.divText(r)])});return o.Widget.fromRoot(a.root)}))}function yo(t){let e=document.cookie.match(new RegExp("(?:^|; )"+t.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,"\\$1")+"=([^;]*)"));return e?decodeURIComponent(e[1]):void 0}function bo(t){return uo(this,void 0,void 0,(function*(){return yield new Promise((t=>setTimeout(t,1e3))),[yield t.prepare({ambTemp:22,initTemp:100,desiredTemp:30,area:.06,heatCap:4200,heatTransferCoeff:8.3,simTime:21600}).call()]}))}function wo(n){return uo(this,void 0,void 0,(function*(){const i=(yield t.functions.eval("Compute:CustomDataUploader")).prepare({func:n.func}),r=e.bigButton("Click me to get mock calls",(()=>i.call())),a=o.Widget.fromRoot(e.panel([e.divV([e.label("This part of dialog comes from my custom data uploader"),e.divH([r],{style:{"justify-content":"center"}})])])),l=t.functions.onBeforeRunAction.pipe((0,s.filter)((t=>t.id===i.id))).subscribe((()=>{e.setUpdateIndicator(r,!0)})),u=t.functions.onAfterRunAction.pipe((0,s.filter)((t=>t.id===i.id))).subscribe((()=>{e.setUpdateIndicator(r,!1)}));return a.subs.push(l,u),{uploadWidget:a,uploadFuncCall:i}}))}function Ao(t){t.defaultView.scatterPlot({xColumnName:"Initial temperature",yColumnName:"Time to cool"})}function Co(){co||(o.ObjectHandler.list().find((t=>"Model"===t.type))||o.ObjectHandler.register(new so),t.events.onAccordionConstructed.subscribe((t=>{const n=t.context;null!=n&&"script"==n.type&&(t.getPane("REST")||t.addPane("REST",(()=>e.wait((()=>uo(this,void 0,void 0,(function*(){return(yield go(n)).root})))))))})),co=!0)}let Io=!1;function So(){const e=t.shell.startUri.indexOf("?"),n=t.shell.startUri.substring(8,e>0?e:void 0).split("/");if(!Io&&n.includes("Compute")){const e=lo.findOrCreateCatalogView("Model Catalog","modelCatalog",po);return t.shell.addView(e),Io=!0,void(n.length>3&&t.dapi.functions.filter(`shortName = "${n[3]}" and #model`).list().then((t=>{1==t.length&&so.openModel(t[0])})))}const i=window.location.href.indexOf("?"),o=window.location.href.substring(8,i>0?i:void 0).split("/");if(o.includes("browse")){const e=lo.findModelCatalogView("modelCatalog");return e&&(t.shell.v=e),lo.createModelCatalogView("Model Catalog","modelCatalog",po)}if(o.includes("apps")){const e=lo.findModelCatalogView("modelCatalog");if(e)t.shell.v=e;else{const e=lo.createModelCatalogView("Model Catalog","modelCatalog",po);t.shell.addView(e)}}}function To(t){const{reasonableMin:e,reasonableMax:n}=t;return t=>U({warnings:t<e||t>n?[`Minimum reasonable time is ${e}. Maximum reasonable time is ${n}`]:void 0,errors:t<0?["Time should be strictly positive"]:void 0})}function Eo(t){return(t,e)=>{const n=e.funcCall.inputs.ambTemp,i=e.funcCall.inputs.initTemp;return U({errors:[...t<n?[j(`Desired temperature cannot be less than ambient temperature (${n}). \n`,[{actionName:"Set desired equal to ambient",action:()=>e.funcCall.inputs.desiredTemp=n}])]:[],...t>i?[`Desired temperature cannot be higher than initial temperature (${i})`]:[]]})}}function xo(t){return(t,e)=>{const n=e.funcCall.inputs.ambTemp;return U({errors:[...t<n?[`Initial temperature cannot be less than ambient temperature (${n}).`]:[]]})}}function Ro(t){return(t,e)=>{const n=e.funcCall.inputs.initTemp;return U({errors:[...t>n?[`Ambient temperature cannot be higher than initial temperature (${n})`]:[]]})}}function Oo(t){return(t,e)=>U({errors:[...t<=0?["Heat capacity must be greater than zero."]:[]],notifications:[j("Heat capacity is only dependent on the object material.",[{actionName:"Google it",action:()=>{window.open("http://google.com")}}])]})}function Po(t){const n=e.input.string("Custom input",{value:""});return n.root.style.backgroundColor="aqua",n.input.style.backgroundColor="aqua",n}function ko(t){return ne.historyInputJSON("Previous run","ObjectCooling")}const Fo=we,No=class extends xe{},Lo=Pi,Bo=xn,Vo=class{static compose(t,e){const n={};for(const t of e){const{id:e}=t;n[e]=Li(t)}return Object.assign(Object.assign({},t),{nestedPipelines:n})}constructor(t){this.pipelineState=new Xi,this.ioInfo=new Map,this.nodes=new Map,this.links=new Map,this.nestedPipelineConfig=new Map,this.hooks=[],this.steps=[],this.isInit=!1,t&&this.setConfig(t)}setConfig(t){if(this.config)throw new Error("Pipeline already has config");if(this.config=Li(t),this.id=this.config.id,this.nqName&&this.nqName!==this.config.nqName)throw new Error(`Config different wrapper nqName ${this.config.nqName}, already set to ${this.nqName}`);this.nqName=this.config.nqName,this.exportConfig=this.config.exportConfig}makePipelineView(t=this.nqName,e){if(this.viewInst)throw new Error(`View has been already created for pipeline ${t}`);if(!t)throw new Error("No nqName for pipeline");if(this.nqName&&this.nqName!==t)throw new Error(`View different wrapper nqName ${t}, already set to ${this.nqName}`);return this.viewInst=new to(t,e),this.nqName=t,this.viewInst}init(){return no(this,void 0,void 0,(function*(){if(this.isInit)throw new Error(`Double init for pipeline ${this.nqName} ${this.id}`);if(this.isInit=!0,!this.viewInst)throw new Error(`No view for pipeline ${this.nqName} ${this.id}`);yield this.loadFuncCallsIO(),this.addScriptStatesToConfig(),this.processConfig(),this.addSystemHooks(),this.rt=new Zi(this.nodes,this.links,this.viewInst,this.pipelineState),this.viewInst.injectConfiguration(this.steps,this.hooks,this.rt,this.exportConfig),this.isInit=!0,yield this.viewInst.init()}))}loadFuncCallsIO(){return no(this,void 0,void 0,(function*(){const t=yield this.gatherIONqNames();for(const e of t){const t=yield this.getFuncIOSpec(e);this.ioInfo.set(e,t)}}))}addSystemHooks(){var t,n;const i=new Map,o=new Map,r=this.viewInst.customViews,a=new Map;for(const e of this.nodes.values())if("popup"===e.type||"action"===e.type){if("popup"===e.type){const t=e.conf;o.set(t.id,t.nqName)}const s=e.conf;if("none"===s.position)continue;const r=_i(e.conf.id);if("buttons"===s.position){const n=null!==(t=i.get(r))&&void 0!==t?t:[];n.push(e),i.set(r,n)}if("menu"===s.position){const t=this.nestedPipelineConfig.get(Vi(e.pipelinePath)),i=null!==(n=null==t?void 0:t.friendlyPrefix)&&void 0!==n?n:"",o=s.friendlyName,r=i?`${i}: ${o}`:o;a.set(r,e)}}const l=[{id:"_SystemViewsAdd_",handler:()=>no(this,void 0,void 0,(function*(){for(const[t,e]of o.entries()){const n=new eo(e,{historyEnabled:!1,isTabbed:!0});yield n.isReady.pipe((0,s.filter)((t=>t)),(0,s.take)(1)).toPromise(),n.root.style.width="100%",n.root.style.height="100%",n.root.style.overflow="hidden",r.set(t,n)}}))}],u=[{id:"_SystemButtonsAdd_",handler:t=>no(this,[t],void 0,(function*({controller:t}){for(const[n,o]of i.entries()){const i=o.map((t=>{const n=t.conf,i=this.rt.getAction(Mi(n.id));return e.button(i.actionName,i.action)}));t.getView(Mi(n)).setAdditionalButtons(i)}}))},{id:"_SystemMenuAdd_",handler:()=>no(this,void 0,void 0,(function*(){for(const[t,e]of a){const n=e.conf,i=this.rt.getAction(Mi(n.id));this.viewInst.addMenuItem(t,i.action)}}))}],c={beforeInit:l,onViewReady:u};this.hooks.unshift({pipelinePath:[],hooks:c})}processConfig(){if(!this.config)throw new Error("No pipeline config");const{toRemove:t,toAdd:e,nestedPipelineConfig:n}=$i(this.config,((t,e,n)=>(Ni(e)&&this.processMergeConfig(e,n,t.toRemove,t.toAdd,t.nestedPipelineConfig),t)),{toRemove:new Set,toAdd:new Map,nestedPipelineConfig:new Map});this.nestedPipelineConfig=n,this.hooks=$i(this.config,((e,n,i)=>{const o=this.getPipelineHooks(n,t,i);return e.unshift({hooks:o,pipelinePath:Bi(i,[n.id])}),e}),[]),$i(this.config,((n,i,o)=>(this.processPipelineConfig(i,o,t,e),n)),void 0);const{pipelineSteps:i,pipelineSeq:o}=$i(this.config,((t,e)=>{const n=e.id,i=e.steps.map((t=>({id:t.id,funcName:t.nqName,friendlyName:t.friendlyName,helpUrl:t.helpUrl})));return t.pipelineSteps.set(n,i),t.pipelineSeq.unshift(n),t}),{pipelineSteps:new Map,pipelineSeq:[]});this.steps=o.reduce(((t,e)=>{var o,s;const r=i.get(e),a=null===(o=n.get(e))||void 0===o?void 0:o.insertBeforeStep,l=null===(s=n.get(e))||void 0===s?void 0:s.friendlyPrefix;if(a){const e=t.findIndex((t=>t.id===a));if(e>0){const n=l?r.map((t=>Object.assign(Object.assign({},t),{friendlyName:`${l}: ${t.friendlyName}`}))):r;t.splice(e,0,...n)}return t}return[...t,...null!=r?r:[]]}),[])}getPipelineHooks(t,e,n){var i,o;t.hooks=null!==(i=t.hooks)&&void 0!==i?i:{};for(const[i,s]of Object.entries(null!==(o=t.hooks)&&void 0!==o?o:{})){const o=[];for(const i of null!=s?s:[]){const s=Vi(this.updateFullPathLink(i,Bi(n,[t.id])));e.has(s)||o.push(i)}t.hooks[i]=o}return t.hooks}processPipelineConfig(t,e,n,i){var o,s,r,a,l;const u=this.proccessPipelineNodeConfig(t,e),c=[];for(const e of t.steps){const t=this.processNodeConfig(e,u,u,new Set,"step");if(!t)continue;const a=t.id,l=[];for(const e of this.getAllItems(null!==(o=t.popups)&&void 0!==o?o:[],a,i,"popup")){const t=this.processNodeConfig(e,Mi(a),u,n,"popup");if(!t)continue;const o=[];for(const r of this.getAllItems(null!==(s=e.actions)&&void 0!==s?s:[],t.id,i,"action")){const e=this.processActionNodeConfig(r,Mi(t.id),u,n);e&&o.push(e)}e.actions=o,l.push(e)}const d=[];for(const e of this.getAllItems(null!==(r=t.actions)&&void 0!==r?r:[],a,i,"action")){const t=this.processActionNodeConfig(e,Mi(a),u,n);t&&d.push(t)}t.popups=l,t.actions=d,c.push(t)}const d=[];for(const e of null!==(a=t.links)&&void 0!==a?a:[]){const t=this.processLinkConfig(e,u,n);t&&d.push(t)}const p=[];for(const e of this.getAllItems(null!==(l=t.actions)&&void 0!==l?l:[],t.id,i,"action")){const t=this.processActionNodeConfig(e,u,u,n);t&&p.push(t)}t.steps=c,t.links=d,t.actions=p}getAllItems(t,e,n,i){var o,s;return[...t,...null!==(s=null===(o=n.get(e))||void 0===o?void 0:o[i])&&void 0!==s?s:[]]}proccessPipelineNodeConfig(t,e){const n=this.updateFullPathNode(t,e),i=Vi(n);return this.nodes.set(i,new Gi(t,"pipeline",e,this.pipelineState)),n}processActionNodeConfig(t,e,n,i){this.updateFullPathLink(t,n,!1);const o=Vi(this.updateFullPathNode(t,e));if(!i.has(o))return this.nodes.set(o,new Gi(t,"action",n,this.pipelineState)),t}processNodeConfig(t,e,n,i,o){const s=Vi(this.updateFullPathNode(t,e));if(!i.has(s))return this.nodes.set(s,new Gi(t,o,n,this.pipelineState)),t}processLinkConfig(t,e,n){const i=Vi(this.updateFullPathLink(t,e));if(!n.has(i))return this.links.set(i,new qi(t,e,this.pipelineState)),t}updateFullPathLink(t,e,n=!0){return t.from&&(Array.isArray(t.from[0])?t.from=t.from.map((t=>[...e,...t])):t.from=[...e,...t.from]),t.to&&(Array.isArray(t.to[0])?t.to=t.to.map((t=>[...e,...t])):t.to=[...e,...t.to]),n?this.updateFullPathNode(t,e):[t.id]}updateFullPathNode(t,e){const n=Bi(e,[t.id]);return t.id=Vi(n),n}processMergeConfig(t,e,n,i,o){var s,r;const a=Bi(e,[t.id]);for(const e of null!==(s=t.itemsToRemove)&&void 0!==s?s:[]){const t=Vi(Bi(a,e));n.add(t)}delete t.itemsToRemove;for(const[e,n]of Object.entries(null!==(r=t.nestedPipelinesConfig)&&void 0!==r?r:{})){const t=Vi(Bi(a,[e]));if(n.insertBeforeStep){const e=Vi(Bi(a,[n.insertBeforeStep]));o.set(t,Object.assign(Object.assign({},n),{insertBeforeStep:e}))}else o.set(t,Object.assign({},n))}delete t.nestedPipelinesConfig;const{popupsToAdd:l,actionsToAdd:u}=t;this.processMergeNodeList(null!=l?l:[],a,i,"popup"),this.processMergeNodeList(null!=u?u:[],a,i,"action"),delete t.popupsToAdd,delete t.actionsToAdd}processMergeNodeList(t,e,n,i){var o,s;for(const[r,a]of t){const t=Vi(Bi(e,null!=a?a:[])),l=null!==(o=n.get(t))&&void 0!==o?o:{},u=null!==(s=l[i])&&void 0!==s?s:[];u.unshift(r),l[i]=u,n.set(t,l)}}addScriptStatesToConfig(){if(!this.config)throw new Error("No pipeline config");$i(this.config,((t,e)=>{var n,i;for(const t of e.steps){this.addNodeIOInfo(t);for(const e of null!==(n=t.popups)&&void 0!==n?n:[])this.addNodeIOInfo(e)}if(Ni(e))for(const[t]of null!==(i=e.popupsToAdd)&&void 0!==i?i:[])this.addNodeIOInfo(t);return t}),void 0)}addNodeIOInfo(t){var e;const n=null!==(e=Li(this.ioInfo.get(t.nqName)))&&void 0!==e?e:[];t.states?t.states.push(...n):t.states=n}getFuncIOSpec(e){return no(this,void 0,void 0,(function*(){const n=yield t.functions.eval(e);return[...n.inputs.map((t=>({id:t.name,type:t.propertyType,stateType:"input"}))),...n.outputs.map((t=>({id:t.name,type:t.propertyType,stateType:"output"})))]}))}gatherIONqNames(){return no(this,void 0,void 0,(function*(){if(!this.config)throw new Error("No pipeline config");const t=new Set;return $i(this.config,((e,n)=>{var i,o;for(const e of n.steps){t.add(e.nqName);for(const n of null!==(i=e.popups)&&void 0!==i?i:[])t.add(n.nqName)}if(Ni(n))for(const[e]of null!==(o=n.popupsToAdd)&&void 0!==o?o:[])t.add(e.nqName);return e}),t),t}))}},Mo=U,_o=j,Do=function(t,e,n){return Object.assign({revalidate:t,context:e},n)},jo=Y,$o=ne.fileInput,Ho=ne.historyInput,Uo=ne.historyInputJSON,Yo=ne.historyPanel})(),compute=i})();
2
2
  //# sourceMappingURL=package.js.map