@datagrok/bio 2.12.13 → 2.12.15
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/CHANGELOG.md +8 -0
- package/dist/package-test.js +1 -1
- package/dist/package-test.js.map +1 -1
- package/dist/package.js +1 -1
- package/dist/package.js.map +1 -1
- package/package.json +1 -1
- package/src/utils/helm-to-molfile/converter/converter.ts +6 -5
- package/src/utils/helm-to-molfile/converter/mol-atoms-v3k.ts +4 -4
- package/src/utils/helm-to-molfile/converter/monomer-wrapper.ts +13 -4
- package/src/utils/helm-to-molfile/converter/polymer.ts +1 -1
package/dist/package.js
CHANGED
|
@@ -5,5 +5,5 @@ var bio;(()=>{var e={2012:(e,t,n)=>{"use strict";n.d(t,{f:()=>r});var s=n(9976);
|
|
|
5
5
|
|| ${a} === "boolean" || ${r} === null`).assign(l,o._`[${r}]`)}}s.else(),p(e),s.endIf(),s.if(o._`${l} !== undefined`,(()=>{s.assign(r,l),function({gen:e,parentData:t,parentDataProperty:n},s){e.if(o._`${t} !== undefined`,(()=>e.assign(o._`${t}[${n}]`,s)))}(e,l)}))}(e,t,a):p(e)}))}return c};const u=new Set(["string","number","integer","boolean","null"]);function h(e,t,n,s=l.Correct){const r=s===l.Correct?o.operators.EQ:o.operators.NEQ;let i;switch(e){case"null":return o._`${t} ${r} null`;case"array":i=o._`Array.isArray(${t})`;break;case"object":i=o._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=a(o._`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=a();break;default:return o._`typeof ${t} ${r} ${e}`}return s===l.Correct?i:(0,o.not)(i);function a(e=o.nil){return(0,o.and)(o._`typeof ${t} == "number"`,e,n?o._`isFinite(${t})`:o.nil)}}function d(e,t,n,s){if(1===e.length)return h(e[0],t,n,s);let r;const i=(0,a.toHash)(e);if(i.array&&i.object){const e=o._`typeof ${t} != "object"`;r=i.null?e:o._`!${t} || ${e}`,delete i.null,delete i.array,delete i.object}else r=o.nil;i.number&&delete i.integer;for(const e in i)r=(0,o.and)(r,h(e,t,n,s));return r}t.checkDataType=h,t.checkDataTypes=d;const m={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?o._`{type: ${e}}`:o._`{type: ${t}}`};function p(e){const t=function(e){const{gen:t,data:n,schema:s}=e,r=(0,a.schemaRefOrVal)(e,s,"type");return{gen:t,keyword:"type",data:n,schema:s.type,schemaCode:r,schemaValue:r,parentSchema:s,params:{},it:e}}(e);(0,i.reportError)(t,m)}t.reportTypeError=p},313:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assignDefaults=void 0;const s=n(3487),r=n(6776);function i(e,t,n){const{gen:i,compositeRule:o,data:a,opts:l}=e;if(void 0===n)return;const c=s._`${a}${(0,s.getProperty)(t)}`;if(o)return void(0,r.checkStrictMode)(e,`default is ignored for: ${c}`);let u=s._`${c} === undefined`;"empty"===l.useDefaults&&(u=s._`${u} || ${c} === null || ${c} === ""`),i.if(u,s._`${c} = ${(0,s.stringify)(n)}`)}t.assignDefaults=function(e,t){const{properties:n,items:s}=e.schema;if("object"===t&&n)for(const t in n)i(e,t,n[t].default);else"array"===t&&Array.isArray(s)&&s.forEach(((t,n)=>i(e,n,t.default)))}},4815:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getData=t.KeywordCxt=t.validateFunctionCode=void 0;const s=n(5667),r=n(453),i=n(8876),o=n(453),a=n(313),l=n(5005),c=n(3099),u=n(3487),h=n(2141),d=n(2531),m=n(6776),p=n(4181);function f({gen:e,validateName:t,schema:n,schemaEnv:s,opts:r},i){r.code.es5?e.func(t,u._`${h.default.data}, ${h.default.valCxt}`,s.$async,(()=>{e.code(u._`"use strict"; ${g(n,r)}`),function(e,t){e.if(h.default.valCxt,(()=>{e.var(h.default.instancePath,u._`${h.default.valCxt}.${h.default.instancePath}`),e.var(h.default.parentData,u._`${h.default.valCxt}.${h.default.parentData}`),e.var(h.default.parentDataProperty,u._`${h.default.valCxt}.${h.default.parentDataProperty}`),e.var(h.default.rootData,u._`${h.default.valCxt}.${h.default.rootData}`),t.dynamicRef&&e.var(h.default.dynamicAnchors,u._`${h.default.valCxt}.${h.default.dynamicAnchors}`)}),(()=>{e.var(h.default.instancePath,u._`""`),e.var(h.default.parentData,u._`undefined`),e.var(h.default.parentDataProperty,u._`undefined`),e.var(h.default.rootData,h.default.data),t.dynamicRef&&e.var(h.default.dynamicAnchors,u._`{}`)}))}(e,r),e.code(i)})):e.func(t,u._`${h.default.data}, ${function(e){return u._`{${h.default.instancePath}="", ${h.default.parentData}, ${h.default.parentDataProperty}, ${h.default.rootData}=${h.default.data}${e.dynamicRef?u._`, ${h.default.dynamicAnchors}={}`:u.nil}}={}`}(r)}`,s.$async,(()=>e.code(g(n,r)).code(i)))}function g(e,t){const n="object"==typeof e&&e[t.schemaId];return n&&(t.code.source||t.code.process)?u._`/*# sourceURL=${n} */`:u.nil}function y({schema:e,self:t}){if("boolean"==typeof e)return!e;for(const n in e)if(t.RULES.all[n])return!0;return!1}function b(e){return"boolean"!=typeof e.schema}function v(e){(0,m.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:n,opts:s,self:r}=e;t.$ref&&s.ignoreKeywordsWithRef&&(0,m.schemaHasRulesButRef)(t,r.RULES)&&r.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}(e)}function w(e,t){if(e.opts.jtd)return S(e,[],!1,t);const n=(0,r.getSchemaTypes)(e.schema);S(e,n,!(0,r.coerceAndCheckDataType)(e,n),t)}function C({gen:e,schemaEnv:t,schema:n,errSchemaPath:s,opts:r}){const i=n.$comment;if(!0===r.$comment)e.code(u._`${h.default.self}.logger.log(${i})`);else if("function"==typeof r.$comment){const n=u.str`${s}/$comment`,r=e.scopeValue("root",{ref:t.root});e.code(u._`${h.default.self}.opts.$comment(${i}, ${n}, ${r}.schema)`)}}function S(e,t,n,s){const{gen:r,schema:a,data:l,allErrors:c,opts:d,self:p}=e,{RULES:f}=p;function g(m){(0,i.shouldUseGroup)(a,m)&&(m.type?(r.if((0,o.checkDataType)(m.type,l,d.strictNumbers)),A(e,m),1===t.length&&t[0]===m.type&&n&&(r.else(),(0,o.reportTypeError)(e)),r.endIf()):A(e,m),c||r.if(u._`${h.default.errors} === ${s||0}`))}!a.$ref||!d.ignoreKeywordsWithRef&&(0,m.schemaHasRulesButRef)(a,f)?(d.jtd||function(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(function(e,t){t.length&&(e.dataTypes.length?(t.forEach((t=>{x(e.dataTypes,t)||E(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)})),function(e,t){const n=[];for(const s of e.dataTypes)x(t,s)?n.push(s):t.includes("integer")&&"number"===s&&n.push("integer");e.dataTypes=n}(e,t)):e.dataTypes=t)}(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&E(e,"use allowUnionTypes to allow union type keyword")}(e,t),function(e,t){const n=e.self.RULES.all;for(const s in n){const r=n[s];if("object"==typeof r&&(0,i.shouldUseRule)(e.schema,r)){const{type:n}=r.definition;n.length&&!n.some((e=>{return s=e,(n=t).includes(s)||"number"===s&&n.includes("integer");var n,s}))&&E(e,`missing type "${n.join(",")}" for keyword "${s}"`)}}}(e,e.dataTypes))}(e,t),r.block((()=>{for(const e of f.rules)g(e);g(f.post)}))):r.block((()=>T(e,"$ref",f.all.$ref.definition)))}function A(e,t){const{gen:n,schema:s,opts:{useDefaults:r}}=e;r&&(0,a.assignDefaults)(e,t.type),n.block((()=>{for(const n of t.rules)(0,i.shouldUseRule)(s,n)&&T(e,n.keyword,n.definition,t.type)}))}function x(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function E(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,m.checkStrictMode)(e,t,e.opts.strictTypes)}t.validateFunctionCode=function(e){b(e)&&(v(e),y(e))?function(e){const{schema:t,opts:n,gen:s}=e;f(e,(()=>{n.$comment&&t.$comment&&C(e),function(e){const{schema:t,opts:n}=e;void 0!==t.default&&n.useDefaults&&n.strictSchema&&(0,m.checkStrictMode)(e,"default is ignored in the schema root")}(e),s.let(h.default.vErrors,null),s.let(h.default.errors,0),n.unevaluated&&function(e){const{gen:t,validateName:n}=e;e.evaluated=t.const("evaluated",u._`${n}.evaluated`),t.if(u._`${e.evaluated}.dynamicProps`,(()=>t.assign(u._`${e.evaluated}.props`,u._`undefined`))),t.if(u._`${e.evaluated}.dynamicItems`,(()=>t.assign(u._`${e.evaluated}.items`,u._`undefined`)))}(e),w(e),function(e){const{gen:t,schemaEnv:n,validateName:s,ValidationError:r,opts:i}=e;n.$async?t.if(u._`${h.default.errors} === 0`,(()=>t.return(h.default.data)),(()=>t.throw(u._`new ${r}(${h.default.vErrors})`))):(t.assign(u._`${s}.errors`,h.default.vErrors),i.unevaluated&&function({gen:e,evaluated:t,props:n,items:s}){n instanceof u.Name&&e.assign(u._`${t}.props`,n),s instanceof u.Name&&e.assign(u._`${t}.items`,s)}(e),t.return(u._`${h.default.errors} === 0`))}(e)}))}(e):f(e,(()=>(0,s.topBoolOrEmptySchema)(e)))};class I{constructor(e,t,n){if((0,l.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,m.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",$(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,l.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",h.default.errors))}result(e,t,n){this.failResult((0,u.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,u.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(u._`${t} !== undefined && (${(0,u.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t)return this.setParams(t),this._error(e,n),void this.setParams({});this._error(e,n)}_error(e,t){(e?p.reportExtraError:p.reportError)(this,this.def.error,t)}$dataError(){(0,p.reportError)(this,this.def.$dataError||p.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,p.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=u.nil){this.gen.block((()=>{this.check$data(e,n),t()}))}check$data(e=u.nil,t=u.nil){if(!this.$data)return;const{gen:n,schemaCode:s,schemaType:r,def:i}=this;n.if((0,u.or)(u._`${s} === undefined`,t)),e!==u.nil&&n.assign(e,!0),(r.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==u.nil&&n.assign(e,!1)),n.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:n,def:s,it:r}=this;return(0,u.or)(function(){if(n.length){if(!(t instanceof u.Name))throw new Error("ajv implementation error");const e=Array.isArray(n)?n:[n];return u._`${(0,o.checkDataTypes)(e,t,r.opts.strictNumbers,o.DataType.Wrong)}`}return u.nil}(),function(){if(s.validateSchema){const n=e.scopeValue("validate$data",{ref:s.validateSchema});return u._`!${n}(${t})`}return u.nil}())}subschema(e,t){const n=(0,c.getSubschema)(this.it,e);(0,c.extendSubschemaData)(n,this.it,e),(0,c.extendSubschemaMode)(n,e);const r={...this.it,...n,items:void 0,props:void 0};return function(e,t){b(e)&&(v(e),y(e))?function(e,t){const{schema:n,gen:s,opts:r}=e;r.$comment&&n.$comment&&C(e),function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,d.resolveUrl)(e.opts.uriResolver,e.baseId,t))}(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const i=s.const("_errs",h.default.errors);w(e,i),s.var(t,u._`${i} === ${h.default.errors}`)}(e,t):(0,s.boolOrEmptySchema)(e,t)}(r,t),r}mergeEvaluated(e,t){const{it:n,gen:s}=this;n.opts.unevaluated&&(!0!==n.props&&void 0!==e.props&&(n.props=m.mergeEvaluated.props(s,e.props,n.props,t)),!0!==n.items&&void 0!==e.items&&(n.items=m.mergeEvaluated.items(s,e.items,n.items,t)))}mergeValidEvaluated(e,t){const{it:n,gen:s}=this;if(n.opts.unevaluated&&(!0!==n.props||!0!==n.items))return s.if(t,(()=>this.mergeEvaluated(e,u.Name))),!0}}function T(e,t,n,s){const r=new I(e,n,t);"code"in n?n.code(r,s):r.$data&&n.validate?(0,l.funcKeywordCode)(r,n):"macro"in n?(0,l.macroKeywordCode)(r,n):(n.compile||n.validate)&&(0,l.funcKeywordCode)(r,n)}t.KeywordCxt=I;const _=/^\/(?:[^~]|~0|~1)*$/,M=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function $(e,{dataLevel:t,dataNames:n,dataPathArr:s}){let r,i;if(""===e)return h.default.rootData;if("/"===e[0]){if(!_.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);r=e,i=h.default.rootData}else{const o=M.exec(e);if(!o)throw new Error(`Invalid JSON-pointer: ${e}`);const a=+o[1];if(r=o[2],"#"===r){if(a>=t)throw new Error(l("property/index",a));return s[t-a]}if(a>t)throw new Error(l("data",a));if(i=n[t-a],!r)return i}let o=i;const a=r.split("/");for(const e of a)e&&(i=u._`${i}${(0,u.getProperty)((0,m.unescapeJsonPointer)(e))}`,o=u._`${o} && ${i}`);return o;function l(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}t.getData=$},5005:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateKeywordUsage=t.validSchemaType=t.funcKeywordCode=t.macroKeywordCode=void 0;const s=n(3487),r=n(2141),i=n(412),o=n(4181);function a(e){const{gen:t,data:n,it:r}=e;t.if(r.parentData,(()=>t.assign(n,s._`${r.parentData}[${r.parentDataProperty}]`)))}function l(e,t,n){if(void 0===n)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword","function"==typeof n?{ref:n}:{ref:n,code:(0,s.stringify)(n)})}t.macroKeywordCode=function(e,t){const{gen:n,keyword:r,schema:i,parentSchema:o,it:a}=e,c=t.macro.call(a.self,i,o,a),u=l(n,r,c);!1!==a.opts.validateSchema&&a.self.validateSchema(c,!0);const h=n.name("valid");e.subschema({schema:c,schemaPath:s.nil,errSchemaPath:`${a.errSchemaPath}/${r}`,topSchemaRef:u,compositeRule:!0},h),e.pass(h,(()=>e.error(!0)))},t.funcKeywordCode=function(e,t){var n;const{gen:c,keyword:u,schema:h,parentSchema:d,$data:m,it:p}=e;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(p,t);const f=!m&&t.compile?t.compile.call(p.self,h,d,p):t.validate,g=l(c,u,f),y=c.let("valid");function b(n=(t.async?s._`await `:s.nil)){const o=p.opts.passContext?r.default.this:r.default.self,a=!("compile"in t&&!m||!1===t.schema);c.assign(y,s._`${n}${(0,i.callValidateCode)(e,g,o,a)}`,t.modifying)}function v(e){var n;c.if((0,s.not)(null!==(n=t.valid)&&void 0!==n?n:y),e)}e.block$data(y,(function(){if(!1===t.errors)b(),t.modifying&&a(e),v((()=>e.error()));else{const n=t.async?function(){const e=c.let("ruleErrs",null);return c.try((()=>b(s._`await `)),(t=>c.assign(y,!1).if(s._`${t} instanceof ${p.ValidationError}`,(()=>c.assign(e,s._`${t}.errors`)),(()=>c.throw(t))))),e}():function(){const e=s._`${g}.errors`;return c.assign(e,null),b(s.nil),e}();t.modifying&&a(e),v((()=>function(e,t){const{gen:n}=e;n.if(s._`Array.isArray(${t})`,(()=>{n.assign(r.default.vErrors,s._`${r.default.vErrors} === null ? ${t} : ${r.default.vErrors}.concat(${t})`).assign(r.default.errors,s._`${r.default.vErrors}.length`),(0,o.extendErrors)(e)}),(()=>e.error()))}(e,n)))}})),e.ok(null!==(n=t.valid)&&void 0!==n?n:y)},t.validSchemaType=function(e,t,n=!1){return!t.length||t.some((t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||n&&void 0===e))},t.validateKeywordUsage=function({schema:e,opts:t,self:n,errSchemaPath:s},r,i){if(Array.isArray(r.keyword)?!r.keyword.includes(i):r.keyword!==i)throw new Error("ajv implementation error");const o=r.dependencies;if(null==o?void 0:o.some((t=>!Object.prototype.hasOwnProperty.call(e,t))))throw new Error(`parent schema must have dependencies of ${i}: ${o.join(",")}`);if(r.validateSchema&&!r.validateSchema(e[i])){const e=`keyword "${i}" value is invalid at path "${s}": `+n.errorsText(r.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);n.logger.error(e)}}},3099:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extendSubschemaMode=t.extendSubschemaData=t.getSubschema=void 0;const s=n(3487),r=n(6776);t.getSubschema=function(e,{keyword:t,schemaProp:n,schema:i,schemaPath:o,errSchemaPath:a,topSchemaRef:l}){if(void 0!==t&&void 0!==i)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==t){const i=e.schema[t];return void 0===n?{schema:i,schemaPath:s._`${e.schemaPath}${(0,s.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:i[n],schemaPath:s._`${e.schemaPath}${(0,s.getProperty)(t)}${(0,s.getProperty)(n)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,r.escapeFragment)(n)}`}}if(void 0!==i){if(void 0===o||void 0===a||void 0===l)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:i,schemaPath:o,topSchemaRef:l,errSchemaPath:a}}throw new Error('either "keyword" or "schema" must be passed')},t.extendSubschemaData=function(e,t,{dataProp:n,dataPropType:i,data:o,dataTypes:a,propertyName:l}){if(void 0!==o&&void 0!==n)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:c}=t;if(void 0!==n){const{errorPath:o,dataPathArr:a,opts:l}=t;u(c.let("data",s._`${t.data}${(0,s.getProperty)(n)}`,!0)),e.errorPath=s.str`${o}${(0,r.getErrorPath)(n,i,l.jsPropertySyntax)}`,e.parentDataProperty=s._`${n}`,e.dataPathArr=[...a,e.parentDataProperty]}function u(n){e.data=n,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,n]}void 0!==o&&(u(o instanceof s.Name?o:c.let("data",o,!0)),void 0!==l&&(e.propertyName=l)),a&&(e.dataTypes=a)},t.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:s,createErrors:r,allErrors:i}){void 0!==s&&(e.compositeRule=s),void 0!==r&&(e.createErrors=r),void 0!==i&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=n}},7159:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var s=n(4815);Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return s.KeywordCxt}});var r=n(3487);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const i=n(7426),o=n(6646),a=n(3141),l=n(5173),c=n(3487),u=n(2531),h=n(453),d=n(6776),m=n(4775),p=n(3589),f=(e,t)=>new RegExp(e,t);f.code="new RegExp";const g=["removeAdditional","useDefaults","coerceTypes"],y=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),b={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},v={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},w=200;function C(e){var t,n,s,r,i,o,a,l,c,u,h,d,m,g,y,b,v,C,S,A,x,E,I,T,_;const M=e.strict,$=null===(t=e.code)||void 0===t?void 0:t.optimize,N=!0===$||void 0===$?1:$||0,L=null!==(s=null===(n=e.code)||void 0===n?void 0:n.regExp)&&void 0!==s?s:f,P=null!==(r=e.uriResolver)&&void 0!==r?r:p.default;return{strictSchema:null===(o=null!==(i=e.strictSchema)&&void 0!==i?i:M)||void 0===o||o,strictNumbers:null===(l=null!==(a=e.strictNumbers)&&void 0!==a?a:M)||void 0===l||l,strictTypes:null!==(u=null!==(c=e.strictTypes)&&void 0!==c?c:M)&&void 0!==u?u:"log",strictTuples:null!==(d=null!==(h=e.strictTuples)&&void 0!==h?h:M)&&void 0!==d?d:"log",strictRequired:null!==(g=null!==(m=e.strictRequired)&&void 0!==m?m:M)&&void 0!==g&&g,code:e.code?{...e.code,optimize:N,regExp:L}:{optimize:N,regExp:L},loopRequired:null!==(y=e.loopRequired)&&void 0!==y?y:w,loopEnum:null!==(b=e.loopEnum)&&void 0!==b?b:w,meta:null===(v=e.meta)||void 0===v||v,messages:null===(C=e.messages)||void 0===C||C,inlineRefs:null===(S=e.inlineRefs)||void 0===S||S,schemaId:null!==(A=e.schemaId)&&void 0!==A?A:"$id",addUsedSchema:null===(x=e.addUsedSchema)||void 0===x||x,validateSchema:null===(E=e.validateSchema)||void 0===E||E,validateFormats:null===(I=e.validateFormats)||void 0===I||I,unicodeRegExp:null===(T=e.unicodeRegExp)||void 0===T||T,int32range:null===(_=e.int32range)||void 0===_||_,uriResolver:P}}class S{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...C(e)};const{es5:t,lines:n}=this.opts.code;this.scope=new c.ValueScope({scope:{},prefixes:y,es5:t,lines:n}),this.logger=function(e){if(!1===e)return M;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),A.call(this,b,e,"NOT SUPPORTED"),A.call(this,v,e,"DEPRECATED","warn"),this._metaOpts=_.call(this),e.formats&&I.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&T.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),E.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:n}=this.opts;let s=m;"id"===n&&(s={...m},s.id=s.$id,delete s.$id),t&&e&&this.addMetaSchema(s,s[n],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let n;if("string"==typeof e){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);const s=n(t);return"$async"in n||(this.errors=n.errors),s}compile(e,t){const n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:n}=this.opts;return s.call(this,e,t);async function s(e,t){await r.call(this,e.$schema);const n=this._addSchema(e,t);return n.validate||i.call(this,n)}async function r(e){e&&!this.getSchema(e)&&await s.call(this,{$ref:e},!0)}async function i(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof o.default))throw t;return a.call(this,t),await l.call(this,t.missingSchema),i.call(this,e)}}function a({missingSchema:e,missingRef:t}){if(this.refs[e])throw new Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function l(e){const n=await c.call(this,e);this.refs[e]||await r.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function c(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,n,s);return this}let r;if("object"==typeof e){const{schemaId:t}=this.opts;if(r=e[t],void 0!==r&&"string"!=typeof r)throw new Error(`schema ${t} must be string`)}return t=(0,u.normalizeId)(t||r),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,s,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let n;if(n=e.$schema,void 0!==n&&"string"!=typeof n)throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const s=this.validate(n,e);if(!s&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return s}getSchema(e){let t;for(;"string"==typeof(t=x.call(this,e));)e=t;if(void 0===t){const{schemaId:n}=this.opts,s=new l.SchemaEnv({schema:{},schemaId:n});if(t=l.resolveSchema.call(this,s,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const t=x.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,u.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if("string"==typeof e)n=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(n=(t=e).keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(N.call(this,n,t),!t)return(0,d.eachItem)(n,(e=>L.call(this,e))),this;R.call(this,t);const s={...t,type:(0,h.getJSONTypes)(t.type),schemaType:(0,h.getJSONTypes)(t.schemaType)};return(0,d.eachItem)(n,0===s.type.length?e=>L.call(this,e,s):e=>s.type.forEach((t=>L.call(this,e,s,t)))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const n of t.rules){const t=n.rules.findIndex((t=>t.keyword===e));t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:n="data"}={}){return e&&0!==e.length?e.map((e=>`${n}${e.instancePath} ${e.message}`)).reduce(((e,n)=>e+t+n)):"No errors"}$dataMetaSchema(e,t){const n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const s of t){const t=s.split("/").slice(1);let r=e;for(const e of t)r=r[e];for(const e in n){const t=n[e];if("object"!=typeof t)continue;const{$data:s}=t.definition,i=r[e];s&&i&&(r[e]=k(i))}}return e}_removeAllSchemas(e,t){for(const n in e){const s=e[n];t&&!t.test(n)||("string"==typeof s?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,t,n,s=this.opts.validateSchema,r=this.opts.addUsedSchema){let i;const{schemaId:o}=this.opts;if("object"==typeof e)i=e[o];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let a=this._cache.get(e);if(void 0!==a)return a;n=(0,u.normalizeId)(i||n);const c=u.getSchemaRefs.call(this,e,n);return a=new l.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:n,localRefs:c}),this._cache.set(a.schema,a),r&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=a),s&&this.validateSchema(e,!0),a}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):l.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{l.compileSchema.call(this,e)}finally{this.opts=t}}}function A(e,t,n,s="error"){for(const r in e){const i=r;i in t&&this.logger[s](`${n}: option ${r}. ${e[i]}`)}}function x(e){return e=(0,u.normalizeId)(e),this.schemas[e]||this.refs[e]}function E(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function I(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function T(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const n=e[t];n.keyword||(n.keyword=t),this.addKeyword(n)}}}function _(){const e={...this.opts};for(const t of g)delete e[t];return e}t.default=S,S.ValidationError=i.default,S.MissingRefError=o.default;const M={log(){},warn(){},error(){}},$=/^[a-z_$][a-z0-9_$:-]*$/i;function N(e,t){const{RULES:n}=this;if((0,d.eachItem)(e,(e=>{if(n.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!$.test(e))throw new Error(`Keyword ${e} has invalid name`)})),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function L(e,t,n){var s;const r=null==t?void 0:t.post;if(n&&r)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:i}=this;let o=r?i.post:i.rules.find((({type:e})=>e===n));if(o||(o={type:n,rules:[]},i.rules.push(o)),i.keywords[e]=!0,!t)return;const a={keyword:e,definition:{...t,type:(0,h.getJSONTypes)(t.type),schemaType:(0,h.getJSONTypes)(t.schemaType)}};t.before?P.call(this,o,a,t.before):o.rules.push(a),i.all[e]=a,null===(s=t.implements)||void 0===s||s.forEach((e=>this.addKeyword(e)))}function P(e,t,n){const s=e.rules.findIndex((e=>e.keyword===n));s>=0?e.rules.splice(s,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function R(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=k(t)),e.validateSchema=this.compile(t,!0))}const O={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function k(e){return{anyOf:[e,O]}}},4087:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(2577),r=n(996),i=n(5568),o=n(6795),a=n(235),l=n(2567),c=n(1233),u=n(1968),h=["/properties"];t.default=function(e){return[s,r,i,o,a,t(this,l),c,t(this,u)].forEach((e=>this.addMetaSchema(e,void 0,!1))),this;function t(t,n){return e?t.$dataMetaSchema(n,h):n}}},3510:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(4063);s.code='require("ajv/dist/runtime/equal").default',t.default=s},4499:(e,t)=>{"use strict";function n(e){const t=e.length;let n,s=0,r=0;for(;r<t;)s++,n=e.charCodeAt(r++),n>=55296&&n<=56319&&r<t&&(n=e.charCodeAt(r),56320==(64512&n)&&r++);return s}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n,n.code='require("ajv/dist/runtime/ucs2length").default'},3589:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(540);s.code='require("ajv/dist/runtime/uri").default',t.default=s},7426:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class n extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}t.default=n},4783:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateAdditionalItems=void 0;const s=n(3487),r=n(6776),i={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>s.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>s._`{limit: ${e}}`},code(e){const{parentSchema:t,it:n}=e,{items:s}=t;Array.isArray(s)?o(e,s):(0,r.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas')}};function o(e,t){const{gen:n,schema:i,data:o,keyword:a,it:l}=e;l.items=!0;const c=n.const("len",s._`${o}.length`);if(!1===i)e.setParams({len:t.length}),e.pass(s._`${c} <= ${t.length}`);else if("object"==typeof i&&!(0,r.alwaysValidSchema)(l,i)){const i=n.var("valid",s._`${c} <= ${t.length}`);n.if((0,s.not)(i),(()=>function(i){n.forRange("i",t.length,c,(t=>{e.subschema({keyword:a,dataProp:t,dataPropType:r.Type.Num},i),l.allErrors||n.if((0,s.not)(i),(()=>n.break()))}))}(i))),e.ok(i)}}t.validateAdditionalItems=o,t.default=i},9351:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(412),r=n(3487),i=n(2141),o=n(6776),a={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:e})=>r._`{additionalProperty: ${e.additionalProperty}}`},code(e){const{gen:t,schema:n,parentSchema:a,data:l,errsCount:c,it:u}=e;if(!c)throw new Error("ajv implementation error");const{allErrors:h,opts:d}=u;if(u.props=!0,"all"!==d.removeAdditional&&(0,o.alwaysValidSchema)(u,n))return;const m=(0,s.allSchemaProperties)(a.properties),p=(0,s.allSchemaProperties)(a.patternProperties);function f(e){t.code(r._`delete ${l}[${e}]`)}function g(s){if("all"===d.removeAdditional||d.removeAdditional&&!1===n)f(s);else{if(!1===n)return e.setParams({additionalProperty:s}),e.error(),void(h||t.break());if("object"==typeof n&&!(0,o.alwaysValidSchema)(u,n)){const n=t.name("valid");"failing"===d.removeAdditional?(y(s,n,!1),t.if((0,r.not)(n),(()=>{e.reset(),f(s)}))):(y(s,n),h||t.if((0,r.not)(n),(()=>t.break())))}}}function y(t,n,s){const r={keyword:"additionalProperties",dataProp:t,dataPropType:o.Type.Str};!1===s&&Object.assign(r,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(r,n)}t.forIn("key",l,(n=>{m.length||p.length?t.if(function(n){let i;if(m.length>8){const e=(0,o.schemaRefOrVal)(u,a.properties,"properties");i=(0,s.isOwnProperty)(t,e,n)}else i=m.length?(0,r.or)(...m.map((e=>r._`${n} === ${e}`))):r.nil;return p.length&&(i=(0,r.or)(i,...p.map((t=>r._`${(0,s.usePattern)(e,t)}.test(${n})`)))),(0,r.not)(i)}(n),(()=>g(n))):g(n)})),e.ok(r._`${c} === ${i.default.errors}`)}};t.default=a},1125:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(6776),r={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:n,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");const i=t.name("valid");n.forEach(((t,n)=>{if((0,s.alwaysValidSchema)(r,t))return;const o=e.subschema({keyword:"allOf",schemaProp:n},i);e.ok(i),e.mergeEvaluated(o)}))}};t.default=r},19:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:n(412).validateUnion,error:{message:"must match a schema in anyOf"}};t.default=s},9864:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>void 0===t?s.str`must contain at least ${e} valid item(s)`:s.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>void 0===t?s._`{minContains: ${e}}`:s._`{minContains: ${e}, maxContains: ${t}}`},code(e){const{gen:t,schema:n,parentSchema:i,data:o,it:a}=e;let l,c;const{minContains:u,maxContains:h}=i;a.opts.next?(l=void 0===u?1:u,c=h):l=1;const d=t.const("len",s._`${o}.length`);if(e.setParams({min:l,max:c}),void 0===c&&0===l)return void(0,r.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==c&&l>c)return(0,r.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,r.alwaysValidSchema)(a,n)){let t=s._`${d} >= ${l}`;return void 0!==c&&(t=s._`${t} && ${d} <= ${c}`),void e.pass(t)}a.items=!0;const m=t.name("valid");function p(){const e=t.name("_valid"),n=t.let("count",0);f(e,(()=>t.if(e,(()=>function(e){t.code(s._`${e}++`),void 0===c?t.if(s._`${e} >= ${l}`,(()=>t.assign(m,!0).break())):(t.if(s._`${e} > ${c}`,(()=>t.assign(m,!1).break())),1===l?t.assign(m,!0):t.if(s._`${e} >= ${l}`,(()=>t.assign(m,!0))))}(n)))))}function f(n,s){t.forRange("i",0,d,(t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:r.Type.Num,compositeRule:!0},n),s()}))}void 0===c&&1===l?f(m,(()=>t.if(m,(()=>t.break())))):0===l?(t.let(m,!0),void 0!==c&&t.if(s._`${o}.length > 0`,p)):(t.let(m,!1),p()),e.result(m,(()=>e.reset()))}};t.default=i},7772:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const s=n(3487),r=n(6776),i=n(412);t.error={message:({params:{property:e,depsCount:t,deps:n}})=>{const r=1===t?"property":"properties";return s.str`must have ${r} ${n} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:n,missingProperty:r}})=>s._`{property: ${e},
|
|
6
6
|
missingProperty: ${r},
|
|
7
7
|
depsCount: ${t},
|
|
8
|
-
deps: ${n}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(e){const[t,n]=function({schema:e}){const t={},n={};for(const s in e)"__proto__"!==s&&((Array.isArray(e[s])?t:n)[s]=e[s]);return[t,n]}(e);a(e,t),l(e,n)}};function a(e,t=e.schema){const{gen:n,data:r,it:o}=e;if(0===Object.keys(t).length)return;const a=n.let("missing");for(const l in t){const c=t[l];if(0===c.length)continue;const u=(0,i.propertyInData)(n,r,l,o.opts.ownProperties);e.setParams({property:l,depsCount:c.length,deps:c.join(", ")}),o.allErrors?n.if(u,(()=>{for(const t of c)(0,i.checkReportMissingProp)(e,t)})):(n.if(s._`${u} && (${(0,i.checkMissingProp)(e,c,a)})`),(0,i.reportMissingProp)(e,a),n.else())}}function l(e,t=e.schema){const{gen:n,data:s,keyword:o,it:a}=e,l=n.name("valid");for(const c in t)(0,r.alwaysValidSchema)(a,t[c])||(n.if((0,i.propertyInData)(n,s,c,a.opts.ownProperties),(()=>{const t=e.subschema({keyword:o,schemaProp:c},l);e.mergeValidEvaluated(t,l)}),(()=>n.var(l,!0))),e.ok(l))}t.validatePropertyDeps=a,t.validateSchemaDeps=l,t.default=o},7274:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(7772),r={keyword:"dependentSchemas",type:"object",schemaType:"object",code:e=>(0,s.validateSchemaDeps)(e)};t.default=r},9434:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:e})=>s.str`must match "${e.ifClause}" schema`,params:({params:e})=>s._`{failingKeyword: ${e.ifClause}}`},code(e){const{gen:t,parentSchema:n,it:i}=e;void 0===n.then&&void 0===n.else&&(0,r.checkStrictMode)(i,'"if" without "then" and "else" is ignored');const a=o(i,"then"),l=o(i,"else");if(!a&&!l)return;const c=t.let("valid",!0),u=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}(),e.reset(),a&&l){const n=t.let("ifClause");e.setParams({ifClause:n}),t.if(u,h("then",n),h("else",n))}else a?t.if(u,h("then")):t.if((0,s.not)(u),h("else"));function h(n,r){return()=>{const i=e.subschema({keyword:n},u);t.assign(c,u),e.mergeValidEvaluated(i,c),r?t.assign(r,s._`${n}`):e.setParams({ifClause:n})}}e.pass(c,(()=>e.error(!0)))}};function o(e,t){const n=e.schema[t];return void 0!==n&&!(0,r.alwaysValidSchema)(e,n)}t.default=i},8200:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(4783),r=n(2924),i=n(4665),o=n(1119),a=n(9864),l=n(7772),c=n(3708),u=n(9351),h=n(6239),d=n(2296),m=n(2182),p=n(19),f=n(4200),g=n(1125),y=n(9434),b=n(6552);t.default=function(e=!1){const t=[m.default,p.default,f.default,g.default,y.default,b.default,c.default,u.default,l.default,h.default,d.default];return e?t.push(r.default,o.default):t.push(s.default,i.default),t.push(a.default),t}},4665:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;const s=n(3487),r=n(6776),i=n(412),o={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:n}=e;if(Array.isArray(t))return a(e,"additionalItems",t);n.items=!0,(0,r.alwaysValidSchema)(n,t)||e.ok((0,i.validateArray)(e))}};function a(e,t,n=e.schema){const{gen:i,parentSchema:o,data:a,keyword:l,it:c}=e;!function(e){const{opts:s,errSchemaPath:i}=c,o=n.length,a=o===e.minItems&&(o===e.maxItems||!1===e[t]);if(s.strictTuples&&!a){const e=`"${l}" is ${o}-tuple, but minItems or maxItems/${t} are not specified or different at path "${i}"`;(0,r.checkStrictMode)(c,e,s.strictTuples)}}(o),c.opts.unevaluated&&n.length&&!0!==c.items&&(c.items=r.mergeEvaluated.items(i,n.length,c.items));const u=i.name("valid"),h=i.const("len",s._`${a}.length`);n.forEach(((t,n)=>{(0,r.alwaysValidSchema)(c,t)||(i.if(s._`${h} > ${n}`,(()=>e.subschema({keyword:l,schemaProp:n,dataProp:n},u))),e.ok(u))}))}t.validateTuple=a,t.default=o},1119:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i=n(412),o=n(4783),a={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>s.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>s._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:n,it:s}=e,{prefixItems:a}=n;s.items=!0,(0,r.alwaysValidSchema)(s,t)||(a?(0,o.validateAdditionalItems)(e,a):e.ok((0,i.validateArray)(e)))}};t.default=a},2182:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(6776),r={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:n,it:r}=e;if((0,s.alwaysValidSchema)(r,n))return void e.fail();const i=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),e.failResult(i,(()=>e.reset()),(()=>e.error()))},error:{message:"must NOT be valid"}};t.default=r},4200:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:e})=>s._`{passingSchemas: ${e.passing}}`},code(e){const{gen:t,schema:n,parentSchema:i,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&i.discriminator)return;const a=n,l=t.let("valid",!1),c=t.let("passing",null),u=t.name("_valid");e.setParams({passing:c}),t.block((function(){a.forEach(((n,i)=>{let a;(0,r.alwaysValidSchema)(o,n)?t.var(u,!0):a=e.subschema({keyword:"oneOf",schemaProp:i,compositeRule:!0},u),i>0&&t.if(s._`${u} && ${l}`).assign(l,!1).assign(c,s._`[${c}, ${i}]`).else(),t.if(u,(()=>{t.assign(l,!0),t.assign(c,i),a&&e.mergeEvaluated(a,s.Name)}))}))})),e.result(l,(()=>e.reset()),(()=>e.error(!0)))}};t.default=i},2296:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(412),r=n(3487),i=n(6776),o=n(6776),a={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,data:a,parentSchema:l,it:c}=e,{opts:u}=c,h=(0,s.allSchemaProperties)(n),d=h.filter((e=>(0,i.alwaysValidSchema)(c,n[e])));if(0===h.length||d.length===h.length&&(!c.opts.unevaluated||!0===c.props))return;const m=u.strictSchema&&!u.allowMatchingProperties&&l.properties,p=t.name("valid");!0===c.props||c.props instanceof r.Name||(c.props=(0,o.evaluatedPropsToName)(t,c.props));const{props:f}=c;function g(e){for(const t in m)new RegExp(e).test(t)&&(0,i.checkStrictMode)(c,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function y(n){t.forIn("key",a,(i=>{t.if(r._`${(0,s.usePattern)(e,n)}.test(${i})`,(()=>{const s=d.includes(n);s||e.subschema({keyword:"patternProperties",schemaProp:n,dataProp:i,dataPropType:o.Type.Str},p),c.opts.unevaluated&&!0!==f?t.assign(r._`${f}[${i}]`,!0):s||c.allErrors||t.if((0,r.not)(p),(()=>t.break()))}))}))}!function(){for(const e of h)m&&g(e),c.allErrors?y(e):(t.var(p,!0),y(e),t.if(p))}()}};t.default=a},2924:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(4665),r={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,s.validateTuple)(e,"items")};t.default=r},6239:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(4815),r=n(412),i=n(6776),o=n(9351),a={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,parentSchema:a,data:l,it:c}=e;"all"===c.opts.removeAdditional&&void 0===a.additionalProperties&&o.default.code(new s.KeywordCxt(c,o.default,"additionalProperties"));const u=(0,r.allSchemaProperties)(n);for(const e of u)c.definedProperties.add(e);c.opts.unevaluated&&u.length&&!0!==c.props&&(c.props=i.mergeEvaluated.props(t,(0,i.toHash)(u),c.props));const h=u.filter((e=>!(0,i.alwaysValidSchema)(c,n[e])));if(0===h.length)return;const d=t.name("valid");for(const n of h)m(n)?p(n):(t.if((0,r.propertyInData)(t,l,n,c.opts.ownProperties)),p(n),c.allErrors||t.else().var(d,!0),t.endIf()),e.it.definedProperties.add(n),e.ok(d);function m(e){return c.opts.useDefaults&&!c.compositeRule&&void 0!==n[e].default}function p(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},d)}}};t.default=a},3708:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:e})=>s._`{propertyName: ${e.propertyName}}`},code(e){const{gen:t,schema:n,data:i,it:o}=e;if((0,r.alwaysValidSchema)(o,n))return;const a=t.name("valid");t.forIn("key",i,(n=>{e.setParams({propertyName:n}),e.subschema({keyword:"propertyNames",data:n,dataTypes:["string"],propertyName:n,compositeRule:!0},a),t.if((0,s.not)(a),(()=>{e.error(!0),o.allErrors||t.break()}))})),e.ok(a)}};t.default=i},6552:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(6776),r={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){void 0===t.if&&(0,s.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};t.default=r},412:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateUnion=t.validateArray=t.usePattern=t.callValidateCode=t.schemaProperties=t.allSchemaProperties=t.noPropertyInData=t.propertyInData=t.isOwnProperty=t.hasPropFunc=t.reportMissingProp=t.checkMissingProp=t.checkReportMissingProp=void 0;const s=n(3487),r=n(6776),i=n(2141),o=n(6776);function a(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:s._`Object.prototype.hasOwnProperty`})}function l(e,t,n){return s._`${a(e)}.call(${t}, ${n})`}function c(e,t,n,r){const i=s._`${t}${(0,s.getProperty)(n)} === undefined`;return r?(0,s.or)(i,(0,s.not)(l(e,t,n))):i}function u(e){return e?Object.keys(e).filter((e=>"__proto__"!==e)):[]}t.checkReportMissingProp=function(e,t){const{gen:n,data:r,it:i}=e;n.if(c(n,r,t,i.opts.ownProperties),(()=>{e.setParams({missingProperty:s._`${t}`},!0),e.error()}))},t.checkMissingProp=function({gen:e,data:t,it:{opts:n}},r,i){return(0,s.or)(...r.map((r=>(0,s.and)(c(e,t,r,n.ownProperties),s._`${i} = ${r}`))))},t.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},t.hasPropFunc=a,t.isOwnProperty=l,t.propertyInData=function(e,t,n,r){const i=s._`${t}${(0,s.getProperty)(n)} !== undefined`;return r?s._`${i} && ${l(e,t,n)}`:i},t.noPropertyInData=c,t.allSchemaProperties=u,t.schemaProperties=function(e,t){return u(t).filter((n=>!(0,r.alwaysValidSchema)(e,t[n])))},t.callValidateCode=function({schemaCode:e,data:t,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:a},it:l},c,u,h){const d=h?s._`${e}, ${t}, ${r}${o}`:t,m=[[i.default.instancePath,(0,s.strConcat)(i.default.instancePath,a)],[i.default.parentData,l.parentData],[i.default.parentDataProperty,l.parentDataProperty],[i.default.rootData,i.default.rootData]];l.opts.dynamicRef&&m.push([i.default.dynamicAnchors,i.default.dynamicAnchors]);const p=s._`${d}, ${n.object(...m)}`;return u!==s.nil?s._`${c}.call(${u}, ${p})`:s._`${c}(${p})`};const h=s._`new RegExp`;t.usePattern=function({gen:e,it:{opts:t}},n){const r=t.unicodeRegExp?"u":"",{regExp:i}=t.code,a=i(n,r);return e.scopeValue("pattern",{key:a.toString(),ref:a,code:s._`${"new RegExp"===i.code?h:(0,o.useFunc)(e,i)}(${n}, ${r})`})},t.validateArray=function(e){const{gen:t,data:n,keyword:i,it:o}=e,a=t.name("valid");if(o.allErrors){const e=t.let("valid",!0);return l((()=>t.assign(e,!1))),e}return t.var(a,!0),l((()=>t.break())),a;function l(o){const l=t.const("len",s._`${n}.length`);t.forRange("i",0,l,(n=>{e.subschema({keyword:i,dataProp:n,dataPropType:r.Type.Num},a),t.if((0,s.not)(a),o)}))}},t.validateUnion=function(e){const{gen:t,schema:n,keyword:i,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some((e=>(0,r.alwaysValidSchema)(o,e)))&&!o.opts.unevaluated)return;const a=t.let("valid",!1),l=t.name("_valid");t.block((()=>n.forEach(((n,r)=>{const o=e.subschema({keyword:i,schemaProp:r,compositeRule:!0},l);t.assign(a,s._`${a} || ${l}`),e.mergeValidEvaluated(o,l)||t.if((0,s.not)(a))})))),e.result(a,(()=>e.reset()),(()=>e.error(!0)))}},8386:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};t.default=n},5684:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(8386),r=n(8280),i=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",s.default,r.default];t.default=i},8280:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;const s=n(6646),r=n(412),i=n(3487),o=n(2141),a=n(5173),l=n(6776),c={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:n,it:r}=e,{baseId:o,schemaEnv:l,validateName:c,opts:d,self:m}=r,{root:p}=l;if(("#"===n||"#/"===n)&&o===p.baseId)return function(){if(l===p)return h(e,c,l,l.$async);const n=t.scopeValue("root",{ref:p});return h(e,i._`${n}.validate`,p,p.$async)}();const f=a.resolveRef.call(m,p,o,n);if(void 0===f)throw new s.default(r.opts.uriResolver,o,n);return f instanceof a.SchemaEnv?function(t){const n=u(e,t);h(e,n,t,t.$async)}(f):function(s){const r=t.scopeValue("schema",!0===d.code.source?{ref:s,code:(0,i.stringify)(s)}:{ref:s}),o=t.name("valid"),a=e.subschema({schema:s,dataTypes:[],schemaPath:i.nil,topSchemaRef:r,errSchemaPath:n},o);e.mergeEvaluated(a),e.ok(o)}(f)}};function u(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):i._`${n.scopeValue("wrapper",{ref:t})}.validate`}function h(e,t,n,s){const{gen:a,it:c}=e,{allErrors:u,schemaEnv:h,opts:d}=c,m=d.passContext?o.default.this:i.nil;function p(e){const t=i._`${e}.errors`;a.assign(o.default.vErrors,i._`${o.default.vErrors} === null ? ${t} : ${o.default.vErrors}.concat(${t})`),a.assign(o.default.errors,i._`${o.default.vErrors}.length`)}function f(e){var t;if(!c.opts.unevaluated)return;const s=null===(t=null==n?void 0:n.validate)||void 0===t?void 0:t.evaluated;if(!0!==c.props)if(s&&!s.dynamicProps)void 0!==s.props&&(c.props=l.mergeEvaluated.props(a,s.props,c.props));else{const t=a.var("props",i._`${e}.evaluated.props`);c.props=l.mergeEvaluated.props(a,t,c.props,i.Name)}if(!0!==c.items)if(s&&!s.dynamicItems)void 0!==s.items&&(c.items=l.mergeEvaluated.items(a,s.items,c.items));else{const t=a.var("items",i._`${e}.evaluated.items`);c.items=l.mergeEvaluated.items(a,t,c.items,i.Name)}}s?function(){if(!h.$async)throw new Error("async schema referenced by sync schema");const n=a.let("valid");a.try((()=>{a.code(i._`await ${(0,r.callValidateCode)(e,t,m)}`),f(t),u||a.assign(n,!0)}),(e=>{a.if(i._`!(${e} instanceof ${c.ValidationError})`,(()=>a.throw(e))),p(e),u||a.assign(n,!1)})),e.ok(n)}():e.result((0,r.callValidateCode)(e,t,m),(()=>f(t)),(()=>p(t)))}t.getValidate=u,t.callRef=h,t.default=c},1240:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(9306),i=n(5173),o=n(6776),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===r.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>s._`{error: ${e}, tag: ${n}, tagValue: ${t}}`},code(e){const{gen:t,data:n,schema:a,parentSchema:l,it:c}=e,{oneOf:u}=l;if(!c.opts.discriminator)throw new Error("discriminator: requires discriminator option");const h=a.propertyName;if("string"!=typeof h)throw new Error("discriminator: requires propertyName");if(a.mapping)throw new Error("discriminator: mapping is not supported");if(!u)throw new Error("discriminator: requires oneOf keyword");const d=t.let("valid",!1),m=t.const("tag",s._`${n}${(0,s.getProperty)(h)}`);function p(n){const r=t.name("valid"),i=e.subschema({keyword:"oneOf",schemaProp:n},r);return e.mergeEvaluated(i,s.Name),r}t.if(s._`typeof ${m} == "string"`,(()=>function(){const n=function(){var e;const t={},n=r(l);let s=!0;for(let t=0;t<u.length;t++){let l=u[t];(null==l?void 0:l.$ref)&&!(0,o.schemaHasRulesButRef)(l,c.self.RULES)&&(l=i.resolveRef.call(c.self,c.schemaEnv.root,c.baseId,null==l?void 0:l.$ref),l instanceof i.SchemaEnv&&(l=l.schema));const d=null===(e=null==l?void 0:l.properties)||void 0===e?void 0:e[h];if("object"!=typeof d)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${h}"`);s=s&&(n||r(l)),a(d,t)}if(!s)throw new Error(`discriminator: "${h}" must be required`);return t;function r({required:e}){return Array.isArray(e)&&e.includes(h)}function a(e,t){if(e.const)d(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${h}" must have "const" or "enum"`);for(const n of e.enum)d(n,t)}}function d(e,n){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${h}" values must be unique strings`);t[e]=n}}();t.if(!1);for(const e in n)t.elseIf(s._`${m} === ${e}`),t.assign(d,p(n[e]));t.else(),e.error(!1,{discrError:r.DiscrError.Mapping,tag:m,tagName:h}),t.endIf()}()),(()=>e.error(!1,{discrError:r.DiscrError.Tag,tag:m,tagName:h}))),e.ok(d)}};t.default=a},9306:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.DiscrError=void 0,(n=t.DiscrError||(t.DiscrError={})).Tag="tag",n.Mapping="mapping"},7299:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(5684),r=n(2649),i=n(8200),o=n(6121),a=n(1448),l=n(808),c=n(9502),u=n(6167),h=[o.default,s.default,r.default,(0,i.default)(!0),c.default,u.metadataVocabulary,u.contentVocabulary,a.default,l.default];t.default=h},3924:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(5684),r=n(2649),i=n(8200),o=n(9502),a=n(6167),l=[s.default,r.default,(0,i.default)(),o.default,a.metadataVocabulary,a.contentVocabulary];t.default=l},6215:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dynamicAnchor=void 0;const s=n(3487),r=n(2141),i=n(5173),o=n(8280),a={keyword:"$dynamicAnchor",schemaType:"string",code:e=>l(e,e.schema)};function l(e,t){const{gen:n,it:a}=e;a.schemaEnv.root.dynamicAnchors[t]=!0;const l=s._`${r.default.dynamicAnchors}${(0,s.getProperty)(t)}`,c="#"===a.errSchemaPath?a.validateName:function(e){const{schemaEnv:t,schema:n,self:s}=e.it,{root:r,baseId:a,localRefs:l,meta:c}=t.root,{schemaId:u}=s.opts,h=new i.SchemaEnv({schema:n,schemaId:u,root:r,baseId:a,localRefs:l,meta:c});return i.compileSchema.call(s,h),(0,o.getValidate)(e,h)}(e);n.if(s._`!${l}`,(()=>n.assign(l,c)))}t.dynamicAnchor=l,t.default=a},1919:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dynamicRef=void 0;const s=n(3487),r=n(2141),i=n(8280),o={keyword:"$dynamicRef",schemaType:"string",code:e=>a(e,e.schema)};function a(e,t){const{gen:n,keyword:o,it:a}=e;if("#"!==t[0])throw new Error(`"${o}" only supports hash fragment reference`);const l=t.slice(1);if(a.allErrors)c();else{const t=n.let("valid",!1);c(t),e.ok(t)}function c(e){if(a.schemaEnv.root.dynamicAnchors[l]){const t=n.let("_v",s._`${r.default.dynamicAnchors}${(0,s.getProperty)(l)}`);n.if(t,u(t,e),u(a.validateName,e))}else u(a.validateName,e)()}function u(t,s){return s?()=>n.block((()=>{(0,i.callRef)(e,t),n.let(s,!0)})):()=>(0,i.callRef)(e,t)}}t.dynamicRef=a,t.default=o},6121:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(6215),r=n(1919),i=n(4094),o=n(3944),a=[s.default,r.default,i.default,o.default];t.default=a},4094:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(6215),r=n(6776),i={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){e.schema?(0,s.dynamicAnchor)(e,""):(0,r.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};t.default=i},3944:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(1919),r={keyword:"$recursiveRef",schemaType:"string",code:e=>(0,s.dynamicRef)(e,e.schema)};t.default=r},9651:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>s.str`must match format "${e}"`,params:({schemaCode:e})=>s._`{format: ${e}}`},code(e,t){const{gen:n,data:r,$data:i,schema:o,schemaCode:a,it:l}=e,{opts:c,errSchemaPath:u,schemaEnv:h,self:d}=l;c.validateFormats&&(i?function(){const i=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),o=n.const("fDef",s._`${i}[${a}]`),l=n.let("fType"),u=n.let("format");n.if(s._`typeof ${o} == "object" && !(${o} instanceof RegExp)`,(()=>n.assign(l,s._`${o}.type || "string"`).assign(u,s._`${o}.validate`)),(()=>n.assign(l,s._`"string"`).assign(u,o))),e.fail$data((0,s.or)(!1===c.strictSchema?s.nil:s._`${a} && !${u}`,function(){const e=h.$async?s._`(${o}.async ? await ${u}(${r}) : ${u}(${r}))`:s._`${u}(${r})`,n=s._`(typeof ${u} == "function" ? ${e} : ${u}.test(${r}))`;return s._`${u} && ${u} !== true && ${l} === ${t} && !${n}`}()))}():function(){const i=d.formats[o];if(!i)return void function(){if(!1!==c.strictSchema)throw new Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}d.logger.warn(e())}();if(!0===i)return;const[a,l,m]=function(e){const t=e instanceof RegExp?(0,s.regexpCode)(e):c.code.formats?s._`${c.code.formats}${(0,s.getProperty)(o)}`:void 0,r=n.scopeValue("formats",{key:o,ref:e,code:t});return"object"!=typeof e||e instanceof RegExp?["string",e,r]:[e.type||"string",e.validate,s._`${r}.validate`]}(i);a===t&&e.pass(function(){if("object"==typeof i&&!(i instanceof RegExp)&&i.async){if(!h.$async)throw new Error("async format in sync schema");return s._`await ${m}(${r})`}return"function"==typeof l?s._`${m}(${r})`:s._`${m}.test(${r})`}())}())}};t.default=r},9502:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=[n(9651).default];t.default=s},6167:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.contentVocabulary=t.metadataVocabulary=void 0,t.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],t.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]},1448:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(8921),r=n(7274),i=n(3633),o=[s.default,r.default,i.default];t.default=o},808:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(1782),r=n(4641),i=[s.default,r.default];t.default=i},4641:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:{message:({params:{len:e}})=>s.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>s._`{limit: ${e}}`},code(e){const{gen:t,schema:n,data:i,it:o}=e,a=o.items||0;if(!0===a)return;const l=t.const("len",s._`${i}.length`);if(!1===n)e.setParams({len:a}),e.fail(s._`${l} > ${a}`);else if("object"==typeof n&&!(0,r.alwaysValidSchema)(o,n)){const n=t.var("valid",s._`${l} <= ${a}`);t.if((0,s.not)(n),(()=>function(n,i){t.forRange("i",i,l,(i=>{e.subschema({keyword:"unevaluatedItems",dataProp:i,dataPropType:r.Type.Num},n),o.allErrors||t.if((0,s.not)(n),(()=>t.break()))}))}(n,a))),e.ok(n)}o.items=!0}};t.default=i},1782:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i=n(2141),o={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:{message:"must NOT have unevaluated properties",params:({params:e})=>s._`{unevaluatedProperty: ${e.unevaluatedProperty}}`},code(e){const{gen:t,schema:n,data:o,errsCount:a,it:l}=e;if(!a)throw new Error("ajv implementation error");const{allErrors:c,props:u}=l;function h(i){if(!1===n)return e.setParams({unevaluatedProperty:i}),e.error(),void(c||t.break());if(!(0,r.alwaysValidSchema)(l,n)){const n=t.name("valid");e.subschema({keyword:"unevaluatedProperties",dataProp:i,dataPropType:r.Type.Str},n),c||t.if((0,s.not)(n),(()=>t.break()))}}u instanceof s.Name?t.if(s._`${u} !== true`,(()=>t.forIn("key",o,(e=>t.if(function(e,t){return s._`!${e} || !${e}[${t}]`}(u,e),(()=>h(e))))))):!0!==u&&t.forIn("key",o,(e=>void 0===u?h(e):t.if(function(e,t){const n=[];for(const r in e)!0===e[r]&&n.push(s._`${t} !== ${r}`);return(0,s.and)(...n)}(u,e),(()=>h(e))))),l.props=!0,e.ok(s._`${a} === ${i.default.errors}`)}};t.default=o},4693:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i=n(3510),o={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>s._`{allowedValue: ${e}}`},code(e){const{gen:t,data:n,$data:o,schemaCode:a,schema:l}=e;o||l&&"object"==typeof l?e.fail$data(s._`!${(0,r.useFunc)(t,i.default)}(${n}, ${a})`):e.fail(s._`${l} !== ${n}`)}};t.default=o},8921:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(7772),r={keyword:"dependentRequired",type:"object",schemaType:"object",error:s.error,code:e=>(0,s.validatePropertyDeps)(e)};t.default=r},966:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i=n(3510),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>s._`{allowedValues: ${e}}`},code(e){const{gen:t,data:n,$data:o,schema:a,schemaCode:l,it:c}=e;if(!o&&0===a.length)throw new Error("enum must have non-empty array");const u=a.length>=c.opts.loopEnum;let h;const d=()=>null!=h?h:h=(0,r.useFunc)(t,i.default);let m;if(u||o)m=t.let("valid"),e.block$data(m,(function(){t.assign(m,!1),t.forOf("v",l,(e=>t.if(s._`${d()}(${n}, ${e})`,(()=>t.assign(m,!0).break()))))}));else{if(!Array.isArray(a))throw new Error("ajv implementation error");const e=t.const("vSchema",l);m=(0,s.or)(...a.map(((t,r)=>function(e,t){const r=a[t];return"object"==typeof r&&null!==r?s._`${d()}(${n}, ${e}[${t}])`:s._`${n} === ${r}`}(e,r))))}e.pass(m)}};t.default=o},2649:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3983),r=n(430),i=n(3229),o=n(4336),a=n(498),l=n(3301),c=n(1687),u=n(2958),h=n(4693),d=n(966),m=[s.default,r.default,i.default,o.default,a.default,l.default,c.default,u.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},h.default,d.default];t.default=m},3633:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(6776),r={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:n}){void 0===t.contains&&(0,s.checkStrictMode)(n,`"${e}" without "contains" is ignored`)}};t.default=r},1687:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n="maxItems"===e?"more":"fewer";return s.str`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>s._`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:r}=e,i="maxItems"===t?s.operators.GT:s.operators.LT;e.fail$data(s._`${n}.length ${i} ${r}`)}};t.default=r},3229:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i=n(4499),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n="maxLength"===e?"more":"fewer";return s.str`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>s._`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:o,it:a}=e,l="maxLength"===t?s.operators.GT:s.operators.LT,c=!1===a.opts.unicode?s._`${n}.length`:s._`${(0,r.useFunc)(e.gen,i.default)}(${n})`;e.fail$data(s._`${c} ${l} ${o}`)}};t.default=o},3983:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=s.operators,i={maximum:{okStr:"<=",ok:r.LTE,fail:r.GT},minimum:{okStr:">=",ok:r.GTE,fail:r.LT},exclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},exclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}},o={message:({keyword:e,schemaCode:t})=>s.str`must be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>s._`{comparison: ${i[e].okStr}, limit: ${t}}`},a={keyword:Object.keys(i),type:"number",schemaType:"number",$data:!0,error:o,code(e){const{keyword:t,data:n,schemaCode:r}=e;e.fail$data(s._`${n} ${i[t].fail} ${r} || isNaN(${n})`)}};t.default=a},498:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n="maxProperties"===e?"more":"fewer";return s.str`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>s._`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:r}=e,i="maxProperties"===t?s.operators.GT:s.operators.LT;e.fail$data(s._`Object.keys(${n}).length ${i} ${r}`)}};t.default=r},430:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>s.str`must be multiple of ${e}`,params:({schemaCode:e})=>s._`{multipleOf: ${e}}`},code(e){const{gen:t,data:n,schemaCode:r,it:i}=e,o=i.opts.multipleOfPrecision,a=t.let("res"),l=o?s._`Math.abs(Math.round(${a}) - ${a}) > 1e-${o}`:s._`${a} !== parseInt(${a})`;e.fail$data(s._`(${r} === 0 || (${a} = ${n}/${r}, ${l}))`)}};t.default=r},4336:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(412),r=n(3487),i={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>r.str`must match pattern "${e}"`,params:({schemaCode:e})=>r._`{pattern: ${e}}`},code(e){const{data:t,$data:n,schema:i,schemaCode:o,it:a}=e,l=a.opts.unicodeRegExp?"u":"",c=n?r._`(new RegExp(${o}, ${l}))`:(0,s.usePattern)(e,i);e.fail$data(r._`!${c}.test(${t})`)}};t.default=i},3301:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(412),r=n(3487),i=n(6776),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>r.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>r._`{missingProperty: ${e}}`},code(e){const{gen:t,schema:n,schemaCode:o,data:a,$data:l,it:c}=e,{opts:u}=c;if(!l&&0===n.length)return;const h=n.length>=u.loopRequired;if(c.allErrors?function(){if(h||l)e.block$data(r.nil,d);else for(const t of n)(0,s.checkReportMissingProp)(e,t)}():function(){const i=t.let("missing");if(h||l){const n=t.let("valid",!0);e.block$data(n,(()=>function(n,i){e.setParams({missingProperty:n}),t.forOf(n,o,(()=>{t.assign(i,(0,s.propertyInData)(t,a,n,u.ownProperties)),t.if((0,r.not)(i),(()=>{e.error(),t.break()}))}),r.nil)}(i,n))),e.ok(n)}else t.if((0,s.checkMissingProp)(e,n,i)),(0,s.reportMissingProp)(e,i),t.else()}(),u.strictRequired){const t=e.parentSchema.properties,{definedProperties:s}=e.it;for(const e of n)if(void 0===(null==t?void 0:t[e])&&!s.has(e)){const t=`required property "${e}" is not defined at "${c.schemaEnv.baseId+c.errSchemaPath}" (strictRequired)`;(0,i.checkStrictMode)(c,t,c.opts.strictRequired)}}function d(){t.forOf("prop",o,(n=>{e.setParams({missingProperty:n}),t.if((0,s.noPropertyInData)(t,a,n,u.ownProperties),(()=>e.error()))}))}}};t.default=o},2958:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(453),r=n(3487),i=n(6776),o=n(3510),a={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>r.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>r._`{i: ${e}, j: ${t}}`},code(e){const{gen:t,data:n,$data:a,schema:l,parentSchema:c,schemaCode:u,it:h}=e;if(!a&&!l)return;const d=t.let("valid"),m=c.items?(0,s.getSchemaTypes)(c.items):[];function p(i,o){const a=t.name("item"),l=(0,s.checkDataTypes)(m,a,h.opts.strictNumbers,s.DataType.Wrong),c=t.const("indices",r._`{}`);t.for(r._`;${i}--;`,(()=>{t.let(a,r._`${n}[${i}]`),t.if(l,r._`continue`),m.length>1&&t.if(r._`typeof ${a} == "string"`,r._`${a} += "_"`),t.if(r._`typeof ${c}[${a}] == "number"`,(()=>{t.assign(o,r._`${c}[${a}]`),e.error(),t.assign(d,!1).break()})).code(r._`${c}[${a}] = ${i}`)}))}function f(s,a){const l=(0,i.useFunc)(t,o.default),c=t.name("outer");t.label(c).for(r._`;${s}--;`,(()=>t.for(r._`${a} = ${s}; ${a}--;`,(()=>t.if(r._`${l}(${n}[${s}], ${n}[${a}])`,(()=>{e.error(),t.assign(d,!1).break(c)}))))))}e.block$data(d,(function(){const s=t.let("i",r._`${n}.length`),i=t.let("j");e.setParams({i:s,j:i}),t.assign(d,!0),t.if(r._`${s} > 1`,(()=>(m.length>0&&!m.some((e=>"object"===e||"array"===e))?p:f)(s,i)))}),r._`${u} === false`),e.ok(d)}};t.default=a},8277:(e,t,n)=>{"use strict";n.d(t,{Z:()=>a});var s=n(7537),r=n.n(s),i=n(3645),o=n.n(i)()(r());o.push([e.id,"\n.ui-form.ui-tooltip .ui-input-root > label.ui-input-label:not(:empty) {\n /* min-width: 30px; /* Breaks right margin /**/\n}\n\n.ui-form.ui-tooltip .ui-input-root > div.ui-input-text:not(:empty) {\n margin-top: 6px;\n}","",{version:3,sources:["webpack://./css/cell-renderer.css"],names:[],mappings:";AACA;IACI,8CAA8C;AAClD;;AAEA;IACI,eAAe;AACnB",sourcesContent:["\n.ui-form.ui-tooltip .ui-input-root > label.ui-input-label:not(:empty) {\n /* min-width: 30px; /* Breaks right margin /**/\n}\n\n.ui-form.ui-tooltip .ui-input-root > div.ui-input-text:not(:empty) {\n margin-top: 6px;\n}"],sourceRoot:""}]);const a=o},5362:(e,t,n)=>{"use strict";n.d(t,{Z:()=>a});var s=n(7537),r=n.n(s),i=n(3645),o=n.n(i)()(r());o.push([e.id,".macromolecule-cell-comp-analysis-host{\n max-height: 250px;\n overflow-y: scroll;\n}\n\n.macromolecule-cell-comp-analysis-bar{\n height: inherit;\n display: block;\n margin-top: 1.5px;\n margin-bottom: 1.5px;\n margin-right: 3px;\n}\n\n.macromolecule-cell-comp-analysis-value{\n display: flex;\n}","",{version:3,sources:["webpack://./css/composition-analysis.css"],names:[],mappings:"AAAA;IACI,iBAAiB;IACjB,kBAAkB;AACtB;;AAEA;IACI,eAAe;IACf,cAAc;IACd,iBAAiB;IACjB,oBAAoB;IACpB,iBAAiB;AACrB;;AAEA;IACI,aAAa;AACjB",sourcesContent:[".macromolecule-cell-comp-analysis-host{\n max-height: 250px;\n overflow-y: scroll;\n}\n\n.macromolecule-cell-comp-analysis-bar{\n height: inherit;\n display: block;\n margin-top: 1.5px;\n margin-bottom: 1.5px;\n margin-right: 3px;\n}\n\n.macromolecule-cell-comp-analysis-value{\n display: flex;\n}"],sourceRoot:""}]);const a=o},9564:(e,t,n)=>{"use strict";n.d(t,{Z:()=>a});var s=n(7537),r=n.n(s),i=n(3645),o=n.n(i)()(r());o.push([e.id,".kalign-version {\n margin-bottom: 0;\n text-align: end;\n font-size: 12px;\n opacity: 0.8;\n}\nbutton.msa-params-button.ui-btn {\n justify-content: end;\n}","",{version:3,sources:["webpack://./css/msa.css"],names:[],mappings:"AAAA;IACI,gBAAgB;IAChB,eAAe;IACf,eAAe;IACf,YAAY;AAChB;AACA;IACI,oBAAoB;AACxB",sourcesContent:[".kalign-version {\n margin-bottom: 0;\n text-align: end;\n font-size: 12px;\n opacity: 0.8;\n}\nbutton.msa-params-button.ui-btn {\n justify-content: end;\n}"],sourceRoot:""}]);const a=o},9414:(e,t,n)=>{"use strict";n.d(t,{Z:()=>a});var s=n(7537),r=n.n(s),i=n(3645),o=n.n(i)()(r());o.push([e.id,".scatter_plot_link {\n position: absolute!important;\n right: 10px;\n}\n\n.cliffs_grid {\n top: 10px;\n}\n\n.show_only_cliffs {\n top: 30px;\n}\n\n.ml-dim-reduction-settings-input i.grok-icon.grok-font-icon-settings {\n font-size: 18px;\n position: absolute;\n height: 28px;\n}\n","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/ml/css/styles.css"],names:[],mappings:"AAAA;IACI,4BAA4B;IAC5B,WAAW;AACf;;AAEA;IACI,SAAS;AACb;;AAEA;IACI,SAAS;AACb;;AAEA;IACI,eAAe;IACf,kBAAkB;IAClB,YAAY;AAChB",sourcesContent:[".scatter_plot_link {\n position: absolute!important;\n right: 10px;\n}\n\n.cliffs_grid {\n top: 10px;\n}\n\n.show_only_cliffs {\n top: 30px;\n}\n\n.ml-dim-reduction-settings-input i.grok-icon.grok-font-icon-settings {\n font-size: 18px;\n position: absolute;\n height: 28px;\n}\n"],sourceRoot:""}]);const a=o},8710:(e,t,n)=>{"use strict";n.d(t,{Z:()=>a});var s=n(7537),r=n.n(s),i=n(3645),o=n.n(i)()(r());o.push([e.id,".monomer-lib-controls-form {\n margin-left: auto;\n margin-right: auto;\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n}\n","",{version:3,sources:["webpack://./src/utils/monomer-lib/library-file-manager/style.css"],names:[],mappings:"AAAA;EACE,iBAAiB;EACjB,kBAAkB;EAClB,aAAa;EACb,sBAAsB;EACtB,mBAAmB;EACnB,WAAW;AACb",sourcesContent:[".monomer-lib-controls-form {\n margin-left: auto;\n margin-right: auto;\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n}\n"],sourceRoot:""}]);const a=o},3645:e=>{"use strict";e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var n="",s=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),s&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),s&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n})).join("")},t.i=function(e,n,s,r,i){"string"==typeof e&&(e=[[null,e,void 0]]);var o={};if(s)for(var a=0;a<this.length;a++){var l=this[a][0];null!=l&&(o[l]=!0)}for(var c=0;c<e.length;c++){var u=[].concat(e[c]);s&&o[u[0]]||(void 0!==i&&(void 0===u[5]||(u[1]="@layer".concat(u[5].length>0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=i),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),r&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=r):u[4]="".concat(r)),t.push(u))}},t}},7537:e=>{"use strict";e.exports=function(e){var t=e[1],n=e[3];if(!n)return t;if("function"==typeof btoa){var s=btoa(unescape(encodeURIComponent(JSON.stringify(n)))),r="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(s),i="/*# ".concat(r," */");return[t].concat([i]).join("\n")}return[t].join("\n")}},4063:e=>{"use strict";e.exports=function e(t,n){if(t===n)return!0;if(t&&n&&"object"==typeof t&&"object"==typeof n){if(t.constructor!==n.constructor)return!1;var s,r,i;if(Array.isArray(t)){if((s=t.length)!=n.length)return!1;for(r=s;0!=r--;)if(!e(t[r],n[r]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if((s=(i=Object.keys(t)).length)!==Object.keys(n).length)return!1;for(r=s;0!=r--;)if(!Object.prototype.hasOwnProperty.call(n,i[r]))return!1;for(r=s;0!=r--;){var o=i[r];if(!e(t[o],n[o]))return!1}return!0}return t!=t&&n!=n}},9133:function(e,t,n){var s;!function(t,r){var i={};!function(e){"use strict";e.__esModule=!0,e.digestLength=32,e.blockSize=64;var t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function n(e,n,s,r,i){for(var o,a,l,c,u,h,d,m,p,f,g,y,b;i>=64;){for(o=n[0],a=n[1],l=n[2],c=n[3],u=n[4],h=n[5],d=n[6],m=n[7],f=0;f<16;f++)g=r+4*f,e[f]=(255&s[g])<<24|(255&s[g+1])<<16|(255&s[g+2])<<8|255&s[g+3];for(f=16;f<64;f++)y=((p=e[f-2])>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,b=((p=e[f-15])>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,e[f]=(y+e[f-7]|0)+(b+e[f-16]|0);for(f=0;f<64;f++)y=(((u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7))+(u&h^~u&d)|0)+(m+(t[f]+e[f]|0)|0)|0,b=((o>>>2|o<<30)^(o>>>13|o<<19)^(o>>>22|o<<10))+(o&a^o&l^a&l)|0,m=d,d=h,h=u,u=c+y|0,c=l,l=a,a=o,o=y+b|0;n[0]+=o,n[1]+=a,n[2]+=l,n[3]+=c,n[4]+=u,n[5]+=h,n[6]+=d,n[7]+=m,r+=64,i-=64}return r}var s=function(){function t(){this.digestLength=e.digestLength,this.blockSize=e.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return t.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},t.prototype.clean=function(){for(var e=0;e<this.buffer.length;e++)this.buffer[e]=0;for(e=0;e<this.temp.length;e++)this.temp[e]=0;this.reset()},t.prototype.update=function(e,t){if(void 0===t&&(t=e.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var s=0;if(this.bytesHashed+=t,this.bufferLength>0){for(;this.bufferLength<64&&t>0;)this.buffer[this.bufferLength++]=e[s++],t--;64===this.bufferLength&&(n(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(t>=64&&(s=n(this.temp,this.state,e,s,t),t%=64);t>0;)this.buffer[this.bufferLength++]=e[s++],t--;return this},t.prototype.finish=function(e){if(!this.finished){var t=this.bytesHashed,s=this.bufferLength,r=t/536870912|0,i=t<<3,o=t%64<56?64:128;this.buffer[s]=128;for(var a=s+1;a<o-8;a++)this.buffer[a]=0;this.buffer[o-8]=r>>>24&255,this.buffer[o-7]=r>>>16&255,this.buffer[o-6]=r>>>8&255,this.buffer[o-5]=r>>>0&255,this.buffer[o-4]=i>>>24&255,this.buffer[o-3]=i>>>16&255,this.buffer[o-2]=i>>>8&255,this.buffer[o-1]=i>>>0&255,n(this.temp,this.state,this.buffer,0,o),this.finished=!0}for(a=0;a<8;a++)e[4*a+0]=this.state[a]>>>24&255,e[4*a+1]=this.state[a]>>>16&255,e[4*a+2]=this.state[a]>>>8&255,e[4*a+3]=this.state[a]>>>0&255;return this},t.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},t.prototype._saveState=function(e){for(var t=0;t<this.state.length;t++)e[t]=this.state[t]},t.prototype._restoreState=function(e,t){for(var n=0;n<this.state.length;n++)this.state[n]=e[n];this.bytesHashed=t,this.finished=!1,this.bufferLength=0},t}();e.Hash=s;var r=function(){function e(e){this.inner=new s,this.outer=new s,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var t=new Uint8Array(this.blockSize);if(e.length>this.blockSize)(new s).update(e).finish(t).clean();else for(var n=0;n<e.length;n++)t[n]=e[n];for(n=0;n<t.length;n++)t[n]^=54;for(this.inner.update(t),n=0;n<t.length;n++)t[n]^=106;for(this.outer.update(t),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate),n=0;n<t.length;n++)t[n]=0}return e.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},e.prototype.clean=function(){for(var e=0;e<this.istate.length;e++)this.ostate[e]=this.istate[e]=0;this.inner.clean(),this.outer.clean()},e.prototype.update=function(e){return this.inner.update(e),this},e.prototype.finish=function(e){return this.outer.finished?this.outer.finish(e):(this.inner.finish(e),this.outer.update(e,this.digestLength).finish(e)),this},e.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},e}();function i(e){var t=(new s).update(e),n=t.digest();return t.clean(),n}function o(e,t){var n=new r(e).update(t),s=n.digest();return n.clean(),s}function a(e,t,n,s){var r=s[0];if(0===r)throw new Error("hkdf: cannot expand more");t.reset(),r>1&&t.update(e),n&&t.update(n),t.update(s),t.finish(e),s[0]++}e.HMAC=r,e.hash=i,e.default=i,e.hmac=o;var l=new Uint8Array(e.digestLength);e.hkdf=function(e,t,n,s){void 0===t&&(t=l),void 0===s&&(s=32);for(var i=new Uint8Array([1]),c=o(t,e),u=new r(c),h=new Uint8Array(u.digestLength),d=h.length,m=new Uint8Array(s),p=0;p<s;p++)d===h.length&&(a(h,u,n,i),d=0),m[p]=h[d++];return u.clean(),h.fill(0),i.fill(0),m},e.pbkdf2=function(e,t,n,s){for(var i=new r(e),o=i.digestLength,a=new Uint8Array(4),l=new Uint8Array(o),c=new Uint8Array(o),u=new Uint8Array(s),h=0;h*o<s;h++){var d=h+1;a[0]=d>>>24&255,a[1]=d>>>16&255,a[2]=d>>>8&255,a[3]=d>>>0&255,i.reset(),i.update(t),i.update(a),i.finish(c);for(var m=0;m<o;m++)l[m]=c[m];for(m=2;m<=n;m++){i.reset(),i.update(c).finish(c);for(var p=0;p<o;p++)l[p]^=c[p]}for(m=0;m<o&&h*o+m<s;m++)u[h*o+m]=l[m]}for(h=0;h<o;h++)l[h]=c[h]=0;for(h=0;h<4;h++)a[h]=0;return i.clean(),u}}(i);var o=i.default;for(var a in i)o[a]=i[a];"object"==typeof e.exports?e.exports=o:void 0===(s=function(){return o}.call(i,n,i,e))||(e.exports=s)}()},1811:(e,t,n)=>{"use strict";n.d(t,{T:()=>r});const s=new Uint32Array(65536),r=(e,t)=>{if(e.length<t.length){const n=t;t=e,e=n}return 0===t.length?e.length:e.length<=32?((e,t)=>{const n=e.length,r=t.length,i=1<<n-1;let o=-1,a=0,l=n,c=n;for(;c--;)s[e.charCodeAt(c)]|=1<<c;for(c=0;c<r;c++){let e=s[t.charCodeAt(c)];const n=e|a;e|=(e&o)+o^o,a|=~(e|o),o&=e,a&i&&l++,o&i&&l--,a=a<<1|1,o=o<<1|~(n|a),a&=n}for(c=n;c--;)s[e.charCodeAt(c)]=0;return l})(e,t):((e,t)=>{const n=t.length,r=e.length,i=[],o=[],a=Math.ceil(n/32),l=Math.ceil(r/32);for(let e=0;e<a;e++)o[e]=-1,i[e]=0;let c=0;for(;c<l-1;c++){let a=0,l=-1;const u=32*c,h=Math.min(32,r)+u;for(let t=u;t<h;t++)s[e.charCodeAt(t)]|=1<<t;for(let e=0;e<n;e++){const n=s[t.charCodeAt(e)],r=o[e/32|0]>>>e&1,c=i[e/32|0]>>>e&1,u=n|a,h=((n|c)&l)+l^l|n|c;let d=a|~(h|l),m=l&h;d>>>31^r&&(o[e/32|0]^=1<<e),m>>>31^c&&(i[e/32|0]^=1<<e),d=d<<1|r,m=m<<1|c,l=m|~(u|d),a=d&u}for(let t=u;t<h;t++)s[e.charCodeAt(t)]=0}let u=0,h=-1;const d=32*c,m=Math.min(32,r-d)+d;for(let t=d;t<m;t++)s[e.charCodeAt(t)]|=1<<t;let p=r;for(let e=0;e<n;e++){const n=s[t.charCodeAt(e)],a=o[e/32|0]>>>e&1,l=i[e/32|0]>>>e&1,c=n|u,d=((n|l)&h)+h^h|n|l;let m=u|~(d|h),f=h&d;p+=m>>>r-1&1,p-=f>>>r-1&1,m>>>31^a&&(o[e/32|0]^=1<<e),f>>>31^l&&(i[e/32|0]^=1<<e),m=m<<1|a,f=f<<1|l,h=f|~(c|m),u=m&c}for(let t=d;t<m;t++)s[e.charCodeAt(t)]=0;return p})(e,t)}},3979:(e,t)=>{"use strict";t.H$=void 0,t.H$=function(e,t,n){var s=function(e,t,n){if(0===e.length||0===t.length)return 0;if(n&&!n.caseSensitive&&(e=e.toUpperCase(),t=t.toUpperCase()),e===t)return 1;for(var s=0,r=e.length,i=t.length,o=Math.floor(Math.max(r,i)/2)-1,a=new Array(r),l=new Array(i),c=0;c<r;c++)for(var u=Math.max(0,c-o);u<=Math.min(i,c+o+1);u++)if(!a[c]&&!l[u]&&e[c]===t[u]){++s,a[c]=l[u]=!0;break}if(0===s)return 0;var h=0,d=0;for(c=0;c<r;c++)if(a[c]){for(;!l[d];)d++;e.charAt(c)!==t.charAt(d++)&&h++}return(s/r+s/i+(s-(h/=2))/s)/3}(e,t,n),r=0;if(s>.7){for(var i=Math.min(e.length,t.length),o=0;e[o]===t[o]&&o<4&&o<i;)++r,o++;s+=.1*r*(1-s)}return s}},9461:e=>{"use strict";var t=e.exports=function(e,t,s){"function"==typeof t&&(s=t,t={}),n(t,"function"==typeof(s=t.cb||s)?s:s.pre||function(){},s.post||function(){},e,"",e)};function n(e,s,r,i,o,a,l,c,u,h){if(i&&"object"==typeof i&&!Array.isArray(i)){for(var d in s(i,o,a,l,c,u,h),i){var m=i[d];if(Array.isArray(m)){if(d in t.arrayKeywords)for(var p=0;p<m.length;p++)n(e,s,r,m[p],o+"/"+d+"/"+p,a,o,d,i,p)}else if(d in t.propsKeywords){if(m&&"object"==typeof m)for(var f in m)n(e,s,r,m[f],o+"/"+d+"/"+f.replace(/~/g,"~0").replace(/\//g,"~1"),a,o,d,i,f)}else(d in t.keywords||e.allKeys&&!(d in t.skipKeywords))&&n(e,s,r,m,o+"/"+d,a,o,d,i)}r(i,o,a,l,c,u,h)}}t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0}},3379:e=>{"use strict";var t=[];function n(e){for(var n=-1,s=0;s<t.length;s++)if(t[s].identifier===e){n=s;break}return n}function s(e,s){for(var i={},o=[],a=0;a<e.length;a++){var l=e[a],c=s.base?l[0]+s.base:l[0],u=i[c]||0,h="".concat(c," ").concat(u);i[c]=u+1;var d=n(h),m={css:l[1],media:l[2],sourceMap:l[3],supports:l[4],layer:l[5]};if(-1!==d)t[d].references++,t[d].updater(m);else{var p=r(m,s);s.byIndex=a,t.splice(a,0,{identifier:h,updater:p,references:1})}o.push(h)}return o}function r(e,t){var n=t.domAPI(t);return n.update(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap&&t.supports===e.supports&&t.layer===e.layer)return;n.update(e=t)}else n.remove()}}e.exports=function(e,r){var i=s(e=e||[],r=r||{});return function(e){e=e||[];for(var o=0;o<i.length;o++){var a=n(i[o]);t[a].references--}for(var l=s(e,r),c=0;c<i.length;c++){var u=n(i[c]);0===t[u].references&&(t[u].updater(),t.splice(u,1))}i=l}}},569:e=>{"use strict";var t={};e.exports=function(e,n){var s=function(e){if(void 0===t[e]){var n=document.querySelector(e);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(e){n=null}t[e]=n}return t[e]}(e);if(!s)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");s.appendChild(n)}},9216:e=>{"use strict";e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}},3565:(e,t,n)=>{"use strict";e.exports=function(e){var t=n.nc;t&&e.setAttribute("nonce",t)}},7795:e=>{"use strict";e.exports=function(e){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var t=e.insertStyleElement(e);return{update:function(n){!function(e,t,n){var s="";n.supports&&(s+="@supports (".concat(n.supports,") {")),n.media&&(s+="@media ".concat(n.media," {"));var r=void 0!==n.layer;r&&(s+="@layer".concat(n.layer.length>0?" ".concat(n.layer):""," {")),s+=n.css,r&&(s+="}"),n.media&&(s+="}"),n.supports&&(s+="}");var i=n.sourceMap;i&&"undefined"!=typeof btoa&&(s+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(i))))," */")),t.styleTagTransform(s,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}},4589:e=>{"use strict";e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}},7241:(e,t,n)=>{"use strict";n.d(t,{D:()=>c});var s=n(4469),r=n(976),i=n(3649),o=n(8260),a=n(6286);const l=31;async function c(e,t=!1,n){const a=o.g.forColumn(e);let c;n??(n=new Map);const h=a.isHelm()?(0,i.getHelmMonomers)(e):Object.keys(a.stats.freq).filter((e=>""!==e));for(let e=0;e<h.length;e++)n.has(h[e])||n.set(h[e],`${n.size+1}`);if(a.isHelm())c=await s.functions.call("HELM:getMolFiles",{col:e}),c=function(e,t,n=!1){const s=new Array(e.length);for(let r=0;r<e.length;r++){let i=0,o=0,a="\n Datagrok macromolecule handler\n\n 0 0 0 0 0 0 999 V3000\nM V30 BEGIN CTAB\n";const c=e.get(r);i=c.indexOf("\n",i)+1,i=c.indexOf("\n",i)+1,i=c.indexOf("\n",i)+1;const u=parseInt(c.substring(i,i+3)),h=parseInt(c.substring(i+3,i+6));a+=`M V30 COUNTS ${u} ${h} 0 0 0\n`,a+="M V30 BEGIN ATOM\n";for(let e=0;e<u;e++){i=c.indexOf("\n",i)+1+l,o=c.indexOf(" ",i);const s=c.substring(i,o);a+=n?`M V30 ${e+1} R${t.get(s)} 0.000 0.000 0 0\n`:`M V30 ${e+1} At 0.000 0.000 0 0 MASS=${t.get(s)}\n`}a+="M V30 END ATOM\n",a+="M V30 BEGIN BOND\n";for(let e=0;e<h;e++){i=c.indexOf("\n",i)+1;const t=parseInt(c.substring(i,i+3).trim()),n=parseInt(c.substring(i+3,i+6).trim());a+=`M V30 ${e+1} ${parseInt(c.substring(i+6,i+9).trim())} ${t} ${n}\n`}a+="M V30 END BOND\n",a+="M V30 END CTAB\n",a+="M END",s[r]=a}return s}(c,n,t);else{c=new Array(e.length);for(let s=0;s<e.length;s++){const e=u(a.getSplitted(s),n,t);c[s]=e}}return r.Column.fromStrings("monomericMols",c)}function u(e,t,n=!1){let s="\n Datagrok macromolecule handler\n\n 0 0 0 0 0 0 999 V3000\nM V30 BEGIN CTAB\n";s+=`M V30 COUNTS ${e.length} ${e.length?e.length-1:0} 0 0 0\n`,s+="M V30 BEGIN ATOM\n";for(let r=0;r<e.length;r++){const i=e.getCanonical(r);i!==a.G2&&(s+=n?`M V30 ${r+1} R${t.get(i)} 0.000 0.000 0 0\n`:`M V30 ${r+1} At 0.000 0.000 0 0 MASS=${t.get(i)}\n`)}s+="M V30 END ATOM\n",s+="M V30 BEGIN BOND\n";for(let t=0;t<e.length-1;t++)s+=`M V30 ${t+1} 1 ${t+1} ${t+2}\n`;return s+="M V30 END BOND\n",s+="M V30 END CTAB\n",s+="M END",s}},3649:(e,t,n)=>{"use strict";n.r(t),n.d(t,{GetRegionEditor:()=>bs,SeqActivityCliffsEditor:()=>Cs,SeqPaletteCustom:()=>hs,SequenceSpaceEditor:()=>ws,SplitToMonomersEditor:()=>vs,SubsequenceSearchTopMenu:()=>Qs,_package:()=>ls,activityCliffs:()=>Ls,addCopyMenu:()=>cr,alignSequences:()=>Gs,applyNotationProviderForCyclized:()=>vr,bioSubstructureFilter:()=>rr,compositionAnalysis:()=>Ds,compositionAnalysisWidget:()=>xs,convertDialog:()=>Us,createMonomerLibraryForPolyTool:()=>gr,demoBioActivityCliffs:()=>dr,demoBioAtomicLevel:()=>mr,demoBioHelmMsaSequenceSpace:()=>pr,demoBioSequenceSpace:()=>hr,demoBioSimilarityDiversity:()=>ur,detectMacromoleculeProbe:()=>br,diversitySearchTopMenu:()=>Xs,diversitySearchViewer:()=>zs,fastaSequenceCellRenderer:()=>Ss,getBioLib:()=>ps,getHelmMonomers:()=>Zs,getMonomerLibHelper:()=>cs,getRegion:()=>$s,getRegionApp:()=>ar,getRegionHelmApp:()=>lr,getRegionPanel:()=>gs,getRegionTopMenu:()=>Ns,getSeqHandler:()=>fs,helmPreprocessingFunction:()=>Rs,hydrophobPalette:()=>us,importBam:()=>Vs,importFasta:()=>Bs,initBio:()=>ds,libraryPanel:()=>ys,macroMolColumnPropertyPanel:()=>As,macromoleculeDifferenceCellRenderer:()=>Is,macromoleculePreprocessingFunction:()=>Ps,manageMonomerLibraries:()=>nr,monomerCellRenderer:()=>js,multipleSequenceAlignmentDialog:()=>Fs,polyTool:()=>Hs,polyToolColumnChoice:()=>fr,saveAsFasta:()=>sr,sdfToJsonLib:()=>yr,searchSubsequenceEditor:()=>Js,separatorSequenceCellRenderer:()=>Es,sequenceAlignment:()=>Ts,sequenceIdentityScoring:()=>er,sequenceSimilarityScoring:()=>tr,sequenceSpaceTopMenu:()=>Os,sequenceTooltip:()=>ms,similaritySearchTopMenu:()=>Ks,similaritySearchViewer:()=>qs,splitToMonomersTopMenu:()=>Ys,testDetectMacromolecule:()=>Ws,toAtomicLevel:()=>ks,vdRegionsViewer:()=>Ms,webLogoAggApp:()=>or,webLogoLargeApp:()=>ir,webLogoViewer:()=>_s});var s,r,i=n(4469),o=n(3870),a=n(976),l=n(3277),c=n(4628);(r=s||(s={})).EUCLIDEAN="EUCLIDEAN",r.MANHATTAN="MANHATTAN";class u{constructor(){this.learningRate={uiName:"Learninig rate",value:1,tooltip:"The initial learning rate for the embedding optimization"},this.nEpochs={uiName:"Epochs",value:0,tooltip:"The number of epochs to optimize embeddings via SGD. Computed automatically if set to 0"},this.nNeighbors={uiName:"Neighbors",value:15,tooltip:"The number of nearest neighbors to construct the fuzzy manifold"},this.spread={uiName:"Spread",value:1,tooltip:"The effective scale of embedded points, used with min distance to control \n the clumped/dispersed nature of the embedding"},this.minDist={uiName:"Min distance",value:.1,tooltip:"The effective minimum distance between embedded points, \n used with spread to control the clumped/dispersed nature of the embedding"},this.randomSeed={uiName:"Random seed",value:null,tooltip:"Random seed",type:"string"},this.useWebGPU={uiName:"Use WebGPU",value:!1,tooltip:"Use WebGPU for KNN computations (EXPERIMENTAL)",type:"boolean"}}}class h{constructor(){this.epsilon={uiName:"Epsilon",value:10,tooltip:"Epsilon is learning rate"},this.perplexity={uiName:"Perplexity",value:30,tooltip:"Roughly how many neighbors each point influences"}}}const d="MCL";a.SEMTYPE.MOLECULE,a.SEMTYPE.MACROMOLECULE;class m{constructor(){this.epsilon={uiName:"Epsilon",value:.01,tooltip:"Minimum distance between cluster points",min:0,max:2,step:.005},this.minPts={uiName:"Minimum points",value:4,tooltip:"Minimum number of points in cluster",min:1,max:1e3,step:1}}}class p{get algorithmOptions(){const e=this.methodsParams[this.methodInput.value],t={};return Object.keys(e).forEach((n=>{null!=e[n].value&&(t[n]=e[n].value)})),t}get dbScanOptions(){return{dbScanEpsilon:this.dbScanParams.epsilon.value??.01,dbScanMinPts:this.dbScanParams.minPts.value??4}}constructor(e={}){this.editorSettings={},this.plotEmbeddingsInput=o.boolInput("Plot embeddings",!0),this.clusterEmbeddingsInput=o.boolInput("Cluster embeddings",!0),this.preprocessingFunctionInputRoot=null,this.methods=[c.A.UMAP,c.A.T_SNE],this.columnFunctionsMap={},this.supportedFunctions={},this.availableMetrics=[],this.methodSettingsDiv=o.inputs([]),this.dbScanSettingsDiv=o.inputs([]),this.preprocessingFuncSettingsDiv=o.inputs([]),this.preprocessingFunctionSettings={},this.methodsParams={[c.A.UMAP]:new u,[c.A.T_SNE]:new h},this.dbScanParams=new m,this.editorSettings=e,this.editorSettings.enableMCL&&this.methods.push(d),a.Func.find({tags:[l.n3]}).forEach((e=>{const t=e.options.get(l.vO)??"",n=e.friendlyName??e.name,s=e.options.get(l.ts)??"",r=e.options.get(l.q6)??"",i=e.options.get(l.dB)??"";this.editorSettings.semtype&&!t.includes(this.editorSettings.semtype)||this.editorSettings.type&&!s.includes(this.editorSettings.type)||this.editorSettings.units&&!r.includes(this.editorSettings.units)||(this.supportedFunctions[n]={func:e,semTypes:t?t.split(","):[],types:s?s.split(","):[],units:r?r.split(","):[],distanceFunctions:i?i.split(","):[]})})),this.tableInput=o.tableInput("Table",i.shell.tv.dataFrame,i.shell.tables,(()=>{this.onTableInputChanged()})),this.onTableInputChanged(),this.regenerateColInput(),this.onColumnInputChanged();let t=!1,n=!1;this.methodInput=o.choiceInput("Method",c.A.UMAP,this.methods,(()=>{t&&this.createAlgorithmSettingsDiv(this.methodSettingsDiv,this.methodsParams[this.methodInput.value])})),this.methodSettingsIcon=o.icons.settings((()=>{t=!t,t?this.createAlgorithmSettingsDiv(this.methodSettingsDiv,this.methodsParams[this.methodInput.value]):o.empty(this.methodSettingsDiv)}),"Modify methods parameters"),this.dbScanSettingsIcon=o.icons.settings((()=>{n=!n,n?this.createAlgorithmSettingsDiv(this.dbScanSettingsDiv,this.dbScanParams):o.empty(this.dbScanSettingsDiv)}),"Modify clustering parameters"),this.clusterEmbeddingsInput.classList.add("ml-dim-reduction-settings-input"),this.clusterEmbeddingsInput.root.prepend(this.dbScanSettingsIcon),this.methodInput.root.classList.add("ml-dim-reduction-settings-input"),this.methodInput.root.prepend(this.methodSettingsIcon),this.methodSettingsDiv=o.inputs([]);const s=this.columnFunctionsMap[this.colInput.value.name];this.preprocessingFunctionInput=o.choiceInput("Encoding function",s[0],s,(()=>{this.onPreprocessingFunctionChanged()}));let r=!1;this.preprocessingFunctionInputRoot||(this.preprocessingFunctionInputRoot=this.preprocessingFunctionInput.root,r=!0),r||(o.empty(this.preprocessingFunctionInputRoot),Array.from(this.preprocessingFunctionInput.root.children).forEach((e=>this.preprocessingFunctionInputRoot.append(e)))),this.preprocessingFunctionInputRoot.classList.add("ml-dim-reduction-settings-input");let p=!1;this.preprocessingFuncSettingsIcon=o.icons.settings((async()=>{p?o.empty(this.preprocessingFuncSettingsDiv):await this.createPreprocessingFuncParamsDiv(this.preprocessingFuncSettingsDiv,this.supportedFunctions[this.preprocessingFunctionInput.value].func),p=!p}),"Modify encoding function parameters"),this.preprocessingFunctionInputRoot.prepend(this.preprocessingFuncSettingsIcon),this.similarityMetricInput=o.choiceInput("Similarity","",[],null),this.similarityMetricInput.nullable=!1,this.similarityMetricInputRoot||(this.similarityMetricInputRoot=this.similarityMetricInput.root),this.onPreprocessingFunctionChanged()}getColInput(){const e=this.tableInput.value?.columns.toList().find((e=>!!this.columnFunctionsMap[e.name]))??null,t=o.columnInput("Column",this.tableInput.value,e,(()=>this.onColumnInputChanged()),{filter:e=>!!this.columnFunctionsMap[e.name]});return this.colInputRoot||(this.colInputRoot=t.root),t}regenerateColInput(){let e=!1;this.colInputRoot&&(e=!0,o.empty(this.colInputRoot)),this.colInput=this.getColInput(),e&&Array.from(this.colInput.root.children).forEach((e=>this.colInputRoot.append(e))),this.onColumnInputChanged()}onTableInputChanged(){const e=this.tableInput.value;e&&(this.columnFunctionsMap={},e.columns.toList().forEach((e=>{Object.keys(this.supportedFunctions).forEach((t=>{const n=this.supportedFunctions[t].semTypes,s=this.supportedFunctions[t].types,r=this.supportedFunctions[t].units,i=!n.length||e.semType&&n.includes(e.semType),o=!s.length||s.includes(e.type),l=!r.length||e.getTag(a.TAGS.UNITS)&&r.includes(e.getTag(a.TAGS.UNITS));i&&o&&l&&(this.columnFunctionsMap[e.name]||(this.columnFunctionsMap[e.name]=[]),this.columnFunctionsMap[e.name].push(t))}))})),this.regenerateColInput())}onColumnInputChanged(){const e=this.colInput.value;if(!e)return;const t=this.columnFunctionsMap[e.name];this.preprocessingFunctionInput=o.choiceInput("Preprocessing function",t[0],t,(()=>{this.onPreprocessingFunctionChanged()}));let n=!1;this.preprocessingFunctionInputRoot||(this.preprocessingFunctionInputRoot=this.preprocessingFunctionInput.root,n=!0),n||(o.empty(this.preprocessingFunctionInputRoot),Array.from(this.preprocessingFunctionInput.root.children).forEach((e=>this.preprocessingFunctionInputRoot.append(e)))),this.onPreprocessingFunctionChanged()}onPreprocessingFunctionChanged(){o.empty(this.preprocessingFuncSettingsDiv),this.preprocessingFunctionSettings={};const e=this.preprocessingFunctionInput.value,t=this.supportedFunctions[e].distanceFunctions;this.availableMetrics=[...t],this.similarityMetricInput=o.choiceInput("Similarity",this.availableMetrics[0],this.availableMetrics,null),this.similarityMetricInput.nullable=!1,this.similarityMetricInputRoot||(this.similarityMetricInputRoot=this.similarityMetricInput.root),o.empty(this.similarityMetricInputRoot),Array.from(this.similarityMetricInput.root.children).forEach((e=>this.similarityMetricInputRoot.append(e))),this.preprocessingFuncSettingsIcon&&(this.supportedFunctions[e].func.inputs.length<3?this.preprocessingFuncSettingsIcon.style.display="none":this.preprocessingFuncSettingsIcon.style.display="flex")}createAlgorithmSettingsDiv(e,t){return o.empty(e),Object.keys(t).forEach((n=>{const s=t[n],r="string"===s.type?o.stringInput(s.uiName,s.value??"",(()=>{s.value=r.value})):"boolean"===s.type?o.boolInput(s.uiName,s.value??!1,(()=>{s.value=r.value})):o.floatInput(s.uiName,s.value,(()=>{s.value=r.value}));o.tooltip.bind(r.input??r.root,s.tooltip),e.append(r.root)})),e}async createPreprocessingFuncParamsDiv(e,t){if(o.empty(e),t.inputs.length<3)return o.div();const n=t.prepare(),s=await n.buildEditor(o.div());for(let r=2;r<t.inputs.length;r++){const i=t.inputs[r];(this.preprocessingFunctionSettings[i.name]||n.inputParams[t.inputs[r].name].value||i.defaultValue)&&(this.preprocessingFunctionSettings[i.name]=this.preprocessingFunctionSettings[i.name]??n.inputParams[i.name].value??i.defaultValue);const o=s.find((e=>e.property.name===i.name));o&&(null!==this.preprocessingFunctionSettings[i.name]&&void 0!==this.preprocessingFunctionSettings[i.name]&&(o.value=this.preprocessingFunctionSettings[i.name]),o.onChanged((()=>{this.preprocessingFunctionSettings[i.name]=o.value})),e.append(o.root))}return e}getEditor(){return o.div([this.tableInput,this.colInputRoot,this.preprocessingFunctionInputRoot,this.preprocessingFuncSettingsDiv,this.methodInput,this.methodSettingsDiv,this.similarityMetricInputRoot,this.plotEmbeddingsInput,this.clusterEmbeddingsInput,this.dbScanSettingsDiv],{style:{minWidth:"320px"},classes:"ui-form"})}getParams(){return{table:this.tableInput.value,col:this.colInput.value,methodName:this.methodInput.value,preprocessingFunction:this.supportedFunctions[this.preprocessingFunctionInput.value].func,similarityMetric:this.similarityMetricInput.value,plotEmbeddings:this.plotEmbeddingsInput.value,clusterEmbeddings:this.clusterEmbeddingsInput.value,options:{...this.algorithmOptions,...this.dbScanOptions,preprocessingFuncArgs:this.preprocessingFunctionSettings??{}}}}}var f=n(442),g=n(5697),y=n(701),b=n(3379),v=n.n(b),w=n(7795),C=n.n(w),S=n(569),A=n.n(S),x=n(3565),E=n.n(x),I=n(9216),T=n.n(I),_=n(4589),M=n.n(_),$=n(9414),N={};N.styleTagTransform=M(),N.setAttributes=E(),N.insert=A().bind(null,"head"),N.domAPI=C(),N.insertStyleElement=T(),v()($.Z,N),$.Z&&$.Z.locals&&$.Z.locals;const L=e=>null==e;function P(e,t,n,s){if(n>e[e.length-1])return;const r=e.findIndex((e=>n<e));e.pop(),e.splice(r,0,n),t.pop(),t.splice(r,0,s)}var R=n(6254);class O{constructor(e=!0,t=!0){const s=navigator.hardwareConcurrency;this._workerCount=e?Math.max(s-2,1):1,this._workers=new Array(this._workerCount).fill(null).map((()=>new Worker(new URL(n.p+n.u(65),n.b)))),this._terminateOnComplete=t}async calc(e,t,n=!0,r){return await this.calcMulti([e],[t],n,[r??{}],[1],s.MANHATTAN)}async calcMulti(e,t,n=!0,r=[{}],i=[1],o=s.MANHATTAN){if(e.length<1)throw new Error("values must contain at least one array");if(t.length!==e.length||r.length!==e.length||i.length!==e.length)throw new Error("values, fnNames, weights and opts must have the same length");return new Promise((async(s,a)=>{try{const a=e[0].length,l=new Array(this._workerCount),c=a*(a-1)/2;this._workerCount=Math.min(this._workerCount,c);const u=c/this._workerCount,h=new Float32Array(c);let d=0,m=1,p=0,f=Number.MIN_VALUE;for(let n=0;n<this._workerCount;n++){const s=Math.floor(n*u),g=n===this._workerCount-1?c:Math.floor((n+1)*u),y=d,b=m;n!==this._workerCount-1&&(d=a-2-Math.floor(Math.sqrt(-8*g+4*a*(a-1)-7)/2-.5),m=g-a*d+Math.floor((d+1)*(d+2)/2)),this._workers[n].postMessage({values:e,fnNames:t,startRow:y,startCol:b,chunckSize:g-s,opts:r,weights:i,aggregationMethod:o}),l[n]=new Promise(((e,t)=>{this._workers[n].onmessage=({data:{error:r,distanceMatrixData:i,min:o,max:a}})=>{this._terminateOnComplete&&setTimeout((()=>this._workers[n].terminate())),r?t(r):(h.set(i,s),o<p&&(p=o),a>f&&(f=a),e())}}))}await Promise.all(l),n&&h.forEach(((e,t)=>{h[t]=(e-p)/(f-p)})),s(h)}catch(e){a(e)}}))}terminate(){this._workers.forEach((e=>e.terminate()))}}class k{constructor(){this._workerCount=Math.max(navigator.hardwareConcurrency-2,1)}async calcMultiColumn(e,t,r,i=[{}],o=[1],a=s.EUCLIDEAN){const l=e[0].length*(e[0].length-1)/2,c=Math.floor(l/this._workerCount),u=e[0].length>2e4?await this.getMinimalThreshold(e,t,i,o,a):0;r<u&&(console.log(`using threshold ${u}`),r=u),i.forEach(((e,t)=>i[t].threshold=r));const h=new Array(this._workerCount),d=new Array(this._workerCount).fill(null).map((()=>new Worker(new URL(n.p+n.u(23),n.b))));for(let n=0;n<this._workerCount;n++)h[n]=new Promise(((s,u)=>{const h=n*c,m=n===this._workerCount-1?l:(n+1)*c;m<=h&&s({i:new Int32Array(0),j:new Int32Array(0),distance:new Float32Array(0),idx:n}),d[n].postMessage({values:e,startIdx:h,endIdx:m,threshold:r,fnNames:t,opts:i,weights:o,aggregationMethod:a}),d[n].onmessage=({data:{error:e,i:t,j:r,distance:i}})=>{e?(d[n].terminate(),u(e)):(d[n].terminate(),s({i:t,j:r,distance:i,idx:n}))}}));const m=await Promise.all(h),p=m.reduce(((e,t)=>e+t.i.length),0),f=new Int32Array(p),g=new Int32Array(p),y=new Float32Array(p);let b=0;for(const e of m)f.set(e.i,b),g.set(e.j,b),y.set(e.distance,b),b+=e.i.length;return{i:f,j:g,distance:y}}async calc(e,t,n,s={}){return await this.calcMultiColumn([e],[t],n,[s],[1])}async getKNN(e,t,n=15,s={}){return await this.multiColumnKNN([e],[t],n,[s],[1])}async getThresholdKNN(e,t,n=.8,s={}){return await this.multiColumnThresholdKnn([e],[t],n,[s],[1])}async multiColumnThresholdKnn(e,t,r=.8,i,o,a=s.EUCLIDEAN){if(e.length!==t.length||e.length!==i.length||e.length!==o.length)throw new Error("values, distance functions, options and weights arrays should have the same length");if(e.some((t=>t.length!==e[0].length)))throw new Error("all values arrays should have the same length");const l=e[0].length*(e[0].length-1)/2,c=Math.floor(l/this._workerCount),u=new Array(this._workerCount),h=new Array(this._workerCount).fill(null).map((()=>new Worker(new URL(n.p+n.u(427),n.b))));for(let n=0;n<this._workerCount;n++)u[n]=new Promise(((s,u)=>{const d=n*c,m=n===this._workerCount-1?l:(n+1)*c;m<=d&&s({knnDistances:new Array(0),knnIndexes:new Array(0)}),h[n].postMessage({values:e,startIdx:d,endIdx:m,fnNames:t,opts:i,threshold:r,weights:o,aggregationMethod:a}),h[n].onmessage=({data:{error:e,knnDistances:t,knnIndexes:r}})=>{e?(h[n].terminate(),u(e)):(h[n].terminate(),s({knnDistances:t,knnIndexes:r}))}}));const d=await Promise.all(u),m=new Int32Array(e[0].length);for(const t of d)for(let n=0;n<e[0].length;++n)m[n]+=t.knnIndexes[n]?.length??0;const p={knnDistances:new Array(e[0].length).fill(null).map(((e,t)=>new Array(m[t]))),knnIndexes:new Array(e[0].length).fill(null).map(((e,t)=>new Array(m[t])))};for(const t of d)for(let n=0;n<e[0].length;++n)for(let e=0;e<t.knnDistances[n]?.length;++e)p.knnDistances[n][m[n]-1]=t.knnDistances[n][e],p.knnIndexes[n][m[n]-1]=t.knnIndexes[n][e],m[n]-=1;return p}async multiColumnKNN(e,t,r=15,i,o,a=s.EUCLIDEAN){if(e.length!==t.length||e.length!==i.length||e.length!==o.length)throw new Error("values, distance functions, options and weights arrays should have the same length");if(e.some((t=>t.length!==e[0].length)))throw new Error("all values arrays should have the same length");const l=e[0].length*(e[0].length-1)/2,c=Math.floor(l/this._workerCount),u=new Array(this._workerCount),h=new Array(this._workerCount).fill(null).map((()=>new Worker(new URL(n.p+n.u(282),n.b))));for(let n=0;n<this._workerCount;n++)u[n]=new Promise(((s,u)=>{const d=n*c,m=n===this._workerCount-1?l:(n+1)*c;m<=d&&s({knnDistances:new Array(0),knnIndexes:new Array(0)}),h[n].postMessage({values:e,startIdx:d,endIdx:m,fnNames:t,opts:i,nNeighbours:r,weights:o,aggregationMethod:a}),h[n].onmessage=({data:{error:e,knnDistances:t,knnIndexes:r}})=>{e?(h[n].terminate(),u(e)):(h[n].terminate(),s({knnDistances:t,knnIndexes:r}))}}));const d=await Promise.all(u),m={knnDistances:new Array(e[0].length).fill(null).map((()=>new Array(r).fill(99999))),knnIndexes:new Array(e[0].length).fill(null).map((()=>new Array(r).fill(-1)))};for(const t of d)for(let n=0;n<e[0].length;++n)for(let e=0;e<t.knnDistances[n]?.length;++e)P(m.knnDistances[n],m.knnIndexes[n],t.knnDistances[n][e],t.knnIndexes[n][e]);return m}async getSampleDistances(e,t,r=[],i,o=s.EUCLIDEAN){const a=new Array(this._workerCount).fill(null).map((()=>new Worker(new URL(n.p+n.u(40),n.b))));try{const n=e[0].length*(e[0].length-1)/2,s=Math.floor(n/this._workerCount),l=1e6,c=Math.max(Math.min(n/1e3,l),Math.min(n,l)),u=Math.floor(c/this._workerCount),h=new Array(this._workerCount);for(let l=0;l<this._workerCount;l++)h[l]=new Promise(((c,h)=>{const d=l*s,m=l===this._workerCount-1?n:(l+1)*s;a[l].postMessage({values:e,startIdx:d,endIdx:m,sampleLength:u,fnNames:t,opts:r,weights:i,aggregationMethod:o}),a[l].onmessage=({data:{error:e,distance:t}})=>{a[l].terminate(),e?h(e):c({distance:t})}}));const d=await Promise.all(h),m=d.reduce(((e,t)=>e+t.distance.length),0),p=new Float32Array(m);let f=0;for(const e of d)p.set(e.distance,f),f+=e.distance.length;return p.sort(),p}catch(e){return a?.forEach((e=>e?.terminate())),console.error(e),new Float32Array(1).fill(.5)}}async getMinimalThreshold(e,t,n=[],r,i=s.EUCLIDEAN){try{const s=e.length*(e.length-1)/2,o=await this.getSampleDistances(e,t,n,r,i);return 1-o[Math.floor(7e7/s*o.length)]}catch(e){return console.error(e),.5}}static calcSync(e,t,n,s){const r=[],i=[],o=[];let a=0,l=0,c=0;const u=e.length*(e.length-1)/2;for(;a<u;){const t=L(e[l])||L(e[c])?1:n(e[l],e[c]);1-t>=s&&(r.push(l),i.push(c),o.push(t)),a++,c++,c===e.length&&(l++,c=l+1)}return{i:new Int32Array(r),j:new Int32Array(i),distance:new Float32Array(o)}}}var F,G=n(9657);!function(e){e.none="none",e.bold="bold",e.dashed="dashed"}(F||(F={}));class D{get currentLineId(){return this._currentLineIdx}set currentLineId(e){e!==this._currentLineIdx&&(this._currentLineIdx=e,this.sp.render(this.ctx))}set linesToRender(e){this.updateLines(e),this.sp.render(this.ctx)}set linesVisibility(e){this.visibility=e,this.sp.render(this.ctx)}constructor(e,t,n,s,r=F.none){var i;this._currentLineIdx=-1,this.lineClicked=new y.Subject,this.lineHover=new y.Subject,this.mouseOverLineId=-1,this.arrowWidth=15,this.sp=e,this.xAxisCol=this.sp.dataFrame.columns.byName(t),this.yAxisCol=this.sp.dataFrame.columns.byName(n),this.canvas=this.sp.getInfo().canvas,this.ctx=this.canvas.getContext("2d"),this.currentLineStyle=r,this.updateLines(s),this.visibility=null!==(i=s.visibility)&&void 0!==i?i:new G.Z(this.lines.from.length),s.visibility||this.visibility.setAll(!0,!1),s.arrowSize&&(this.arrowWidth=s.arrowSize),this.canvas.onmousedown=e=>{-1!==this.mouseOverLineId&&this.lineClicked.next({x:e.clientX,y:e.clientY,id:this.mouseOverLineId,event:e})},this.canvas.onmousemove=e=>{this.mouseOverLineId=this.checkCoordsOnLine(e.offsetX,e.offsetY),-1!==this.mouseOverLineId&&this.lineHover.next({x:e.clientX,y:e.clientY,id:this.mouseOverLineId,event:e})},e.onEvent("d4-before-draw-scene").subscribe((e=>{this.renderLines()}))}updateLines(e){this.lines=e,this.multipleLinesCounts=new Uint8Array(this.lines.from.length),e.skipMultiLineCalculation?this.multipleLinesCounts.fill(0):this.createMultiLinesIndices()}renderLines(){var e,t,n,s,r,i,o,a,l,c,u,h,d;const m=this.sp.getOptions().look,p=this.lines.colors||this.lines.width||this.lines.opacities||this.lines.drawArrowsArr;p||(this.ctx.lineWidth=null!==(e=this.lines.width)&&void 0!==e?e:1,this.ctx.strokeStyle=`rgba(${null!==(t=this.lines.color)&&void 0!==t?t:"0,128,0"},${null!==(n=this.lines.opacity)&&void 0!==n?n:1})`);const f=m.sizeColumnName?this.sp.dataFrame.col(m.sizeColumnName):null,g=this.sp.dataFrame.filter;for(let e=0;e<this.lines.from.length;e++)if(g.get(this.lines.from[e])&&g.get(this.lines.to[e])&&this.visibility.getBit(e)){let t=0;const{sizeFrom:n,sizeTo:g}=this.getMarkersSizes(m,f,e),y=this.sp.worldToScreen(this.xAxisCol.get(this.lines.from[e]),this.yAxisCol.get(this.lines.from[e]));let b=null==y?void 0:y.x,v=null==y?void 0:y.y;const w=this.sp.worldToScreen(this.xAxisCol.get(this.lines.to[e]),this.yAxisCol.get(this.lines.to[e]));let C=null==w?void 0:w.x,S=null==w?void 0:w.y;const A=Math.min(this.sp.viewBox.width,this.sp.viewBox.height);if(this.ctx.beginPath(),b&&v&&C&&S&&Math.hypot(C-b,S-v)/A>.01){if(p){const t=(null===(s=this.lines.colors)||void 0===s?void 0:s[e])?null===(r=this.lines.colors)||void 0===r?void 0:r[e]:"0,128,0",n=(null===(i=this.lines.opacities)||void 0===i?void 0:i[e])?null===(o=this.lines.opacities)||void 0===o?void 0:o[e]:1;this.ctx.strokeStyle=`rgba(${t},${n})`,this.ctx.lineWidth=(null===(a=this.lines.widths)||void 0===a?void 0:a[e])?null===(l=this.lines.widths)||void 0===l?void 0:l[e]:1}e===this._currentLineIdx&&this.toggleCurrentLineStyle(!0);const m=this.multipleLinesCounts[e];let f=null;if(m){t=this.getLineLength(b,v,C,S);const s=this.getPointOnDistance(b,v,C,S,g,t),r=this.getPointOnDistance(C,S,b,v,n,t);b=s.x,v=s.y,C=r.x,S=r.y,f=this.lines.from[e]>this.lines.to[e]?this.findControlPoint(m,b,v,C,S,e):this.findControlPoint(m,C,S,b,v,e),this.ctx.moveTo(b,v),this.ctx.quadraticCurveTo(f.x,f.y,C,S)}else this.ctx.moveTo(b,v),this.ctx.lineTo(C,S);if((null!==(c=this.lines.drawArrows)&&void 0!==c?c:null===(u=this.lines.drawArrowsArr)||void 0===u?void 0:u.getBit(e))&&(t||(t=this.getLineLength(b,v,C,S)),t>this.arrowWidth)){const e=m?null:this.getPointOnDistance(b,v,C,S,g,t),n=m?f.x:b,s=m?f.y:v;this.canvasArrow(this.ctx,null!==(h=null==e?void 0:e.x)&&void 0!==h?h:b,null!==(d=null==e?void 0:e.y)&&void 0!==d?d:v,n,s)}this.ctx.stroke(),this.ctx.closePath(),e===this._currentLineIdx&&this.toggleCurrentLineStyle(!1)}}this.fillLeftBottomRect()}toggleCurrentLineStyle(e){switch(this.currentLineStyle){case F.bold:e?this.ctx.lineWidth+=2:this.ctx.lineWidth-=2;break;case F.dashed:e?this.ctx.setLineDash([5,5]):this.ctx.setLineDash([]);break;default:return}}getMarkersSizes(e,t,n){let s=3,r=3;return t?(s=(e.markerMinSize+(e.markerMaxSize-e.markerMinSize)*t.scale(this.lines.from[n]))/2,r=(e.markerMinSize+(e.markerMaxSize-e.markerMinSize)*t.scale(this.lines.to[n]))/2):e.markerDefaultSize&&(s=e.markerDefaultSize/2,r=e.markerDefaultSize/2),{sizeFrom:s,sizeTo:r}}fillLeftBottomRect(){const e=new Path2D;e.rect(this.sp.yAxisBox.minX,this.sp.yAxisBox.maxY,this.sp.yAxisBox.width,this.sp.xAxisBox.height),this.ctx.fillStyle="white",this.ctx.beginPath(),this.ctx.fill(e),this.ctx.closePath()}createMultiLinesIndices(){const e=new G.Z(this.lines.from.length);e.setAll(!0);for(let t=-1;-1!==(t=e.findNext(t));){const n=t,s=this.lines.from[n],r=this.lines.to[n];let i=1;for(let n=t;-1!==(n=e.findNext(n));){const t=this.lines.from[n],o=this.lines.to[n];(t===s&&o===r||o===s&&t===r)&&(this.multipleLinesCounts[n]=++i,e.setBit(n,!1,!1))}i>1&&(this.multipleLinesCounts[n]=1),e.setBit(t,!1,!1)}}checkCoordsOnLine(e,t){let n=-1,s=null,r=null;const i=this.sp.getOptions().look,o=i.sizeColumnName?this.sp.dataFrame.col(i.sizeColumnName):null,a=this.sp.dataFrame.filter;for(let l=0;l<this.lines.from.length;l++)if(a.get(this.lines.from[l])&&a.get(this.lines.to[l])&&this.visibility.getBit(l)){const{sizeFrom:a,sizeTo:c}=this.getMarkersSizes(i,o,l),u=this.sp.worldToScreen(this.xAxisCol.get(this.lines.from[l]),this.yAxisCol.get(this.lines.from[l])),h=this.sp.worldToScreen(this.xAxisCol.get(this.lines.to[l]),this.yAxisCol.get(this.lines.to[l]));if(this.multipleLinesCounts[l]){const n=this.getLineLength(u.x,u.y,h.x,h.y),s=this.getPointOnDistance(u.x,u.y,h.x,h.y,c,n),i=this.getPointOnDistance(h.x,h.y,null==u?void 0:u.x,null==u?void 0:u.y,a,n),o=this.lines.from[l]>this.lines.to[l]?this.findControlPoint(this.multipleLinesCounts[l],s.x,s.y,i.x,i.y,l):this.findControlPoint(this.multipleLinesCounts[l],i.x,i.y,s.x,s.y,l);r=this.calculateDistToCurveLine(l,e,t,s,i,o)}else r=this.calculateDistToStraightLine(e,t,u,h);(!s&&null!==r&&r<5||s&&null!==r&&r<s)&&(s=r,n=l)}return n}calculateDistToStraightLine(e,t,n,s){const r=Math.min(n.x,s.x),i=Math.max(n.x,s.x),o=Math.min(n.y,s.y),a=Math.max(n.y,s.y);return e>=r-2&&e<=i+2&&t>=o-2&&t<=a+2?this.distToStraightLineSegment(e,t,n,s):null}distToStraightLineSegment(e,t,n,s){const r=(e,t,n,s)=>Math.pow(e-n,2)+Math.pow(t-s,2),i=r(n.x,n.y,s.x,s.y);if(0==i)return r(e,t,n.x,n.y);let o=((e-n.x)*(s.x-n.x)+(t-n.y)*(s.y-n.y))/i;return o=Math.max(0,Math.min(1,o)),r(e,t,n.x+o*(s.x-n.x),n.y+o*(s.y-n.y))}calculateDistToCurveLine(e,t,n,s,r,i){const o=Math.min(s.x,r.x,i.x),a=Math.max(s.x,r.x,i.x),l=Math.min(s.y,r.y,i.y),c=Math.max(s.y,r.y,i.y);if(t>=o-2&&t<=a+2&&n>=l-2&&n<=c+2){const e=a-o,u=c-l;return this.calculateDistToCurveInRect(t,n,s,i,r,e,u)}return null}calculateDistToCurveInRect(e,t,n,s,r,i,o){const a=Math.floor((i+o)/3),l=1/a,c=new Uint32Array(a),u=new Uint32Array(a),h=new Uint32Array(a);let d=null;const m=new G.Z(a);for(let i=0;i<c.length;i++){const o=i*l,a=Math.pow(1-o,2)*n.x+2*o*(1-o)*s.x+Math.pow(o,2)*r.x,m=Math.pow(1-o,2)*n.y+2*o*(1-o)*s.y+Math.pow(o,2)*r.y,p=Math.abs(e-a),f=Math.abs(t-m),g=p+f;(!d||d>g)&&(d=g),h[i]=Math.max(p,f),c[i]=a,u[i]=m}for(let e=0;e<c.length;e++)h[e]<d&&m.setBit(e,!0,!1);let p=null;for(let n=-1;-1!==(n=m.findNext(n));){const s=Math.hypot(c[n]-e,u[n]-t);(!p||p>s)&&(p=s)}return p}getLineLength(e,t,n,s){return Math.sqrt(Math.pow(n-e,2)+Math.pow(s-t,2))}getPointOnDistance(e,t,n,s,r,i){const o=n-r*((n-e)/i),l=s-r*((s-t)/i);return new a.Point(o,l)}findControlPoint(e,t,n,s,r,i){const o=t+(s-t)/2,l=n+(r-n)/2;let c=o-t,u=l-n;const h=Math.sqrt(c*c+u*u);c/=h,u/=h;const d=50*Math.ceil(e/2);return e%2==0?new a.Point(o+d/2*u,l-d/2*c):new a.Point(o-d/2*u,l+d/2*c)}canvasArrow(e,t,n,s,r){const i=Math.atan2(s-t,r-n)+Math.PI;e.moveTo(t-this.arrowWidth*Math.sin(i-Math.PI/10),n-this.arrowWidth*Math.cos(i-Math.PI/10)),e.lineTo(t,n),e.lineTo(t-this.arrowWidth*Math.sin(i+Math.PI/10),n-this.arrowWidth*Math.cos(i+Math.PI/10))}}const B="dimensionality-reducer-terminate-event";var V,U,H=n(850);async function j(e,t,s,r,o,a,l){let c=await async function(e,t,s,r,o,a,l){if(!a.distanceFnArgs)throw new Error("options.distanceFnArgs must be defined");if(e.length!==t.length||e.length!==a.distanceFnArgs.length||e.length!==r.length)throw new Error("data, metrics and options and weights must have the same length");return new Promise((function(c,u){const h=new Worker(new URL(n.p+n.u(42),n.b));h.postMessage({columnsData:e,distanceMetrics:t,method:s,options:a,weights:r,aggregationMethod:o});const d=i.events.onCustomEvent(B).subscribe((()=>{try{h?.terminate()}finally{d.unsubscribe()}}));h.onmessage=({data:{error:e,embedding:t,epochNum:n,epochsLength:s}})=>{L(n)||L(s)?(d.unsubscribe(),e?u(e):c(t),setTimeout((()=>h.terminate()),100)):l&&l(n,s,t)}}))}(e,s,t,r,o,a,l);return c=c.map((e=>(0,H.Fv)(e))),c}(U=V||(V={})).EUCLIDEAN="EUCLIDEAN",U.MANHATTAN="MANHATTAN";const W={[V.EUCLIDEAN]:function(e){return`\n var sum = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n sum = sum + distances[i] * distances[i] * computeInfo.weights[i] * computeInfo.weights[i];\n }\n return sqrt(sum);\n `},[V.MANHATTAN]:function(e){return`\n var sum = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n sum = sum + abs(distances[i]) * computeInfo.weights[i];\n }\n return sum;\n `}};var Y,Z;(Z=Y||(Y={})).HAMMING="Hamming",Z.EUCLIDEAN="Euclidean",Z.MANHATTAN="Manhattan",Z.TANIMOTO="Tanimoto",Z.LEVENSTEIN="Levenshtein",Z.NEEDLEMAN_WUNSCH="Needlemann-Wunsch",Z.MONOMER_CHEMICAL_DISTANCE="Monomer chemical distance",Z.SOKAL="Sokal",Z.COSINE="Cosine",Z.ASYMMETRIC="Asymmetric",Z.Difference="Difference",Z.OneHot="One-Hot";const q={[Y.HAMMING]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n let maxLength: u32 = max(aLength, bLength);\n let minLength: u32 = min(aLength, bLength);\n let sizeDiff: u32 = maxLength - minLength;\n \n let maxIntDistance = ceil(maxDistance * f32(maxLength)) - f32(sizeDiff);\n\n var diff: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n diff = diff + f32(a[i] != b[i]);\n if (diff > maxIntDistance) {\n return 1.0;\n }\n }\n diff += f32(sizeDiff);\n return diff / ${e};\n `},[Y.EUCLIDEAN]:function(e,t){return`\n var dist: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n dist = dist + f32(a[i] - b[i]) * f32(a[i] - b[i]);\n }\n return sqrt(dist);\n `},[Y.MANHATTAN]:function(e,t){return`\n var dist: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n dist = dist + abs(f32(a[i] - b[i]));\n }\n return dist;\n `},[Y.TANIMOTO]:function(e,t){return`\n var onBitsa: u32 = 0u;\n var onBitsb: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n onBitsa = onBitsa + countOneBits(a[i]);\n onBitsb = onBitsb + countOneBits(b[i]);\n }\n\n if (onBitsa == 0u && onBitsb == 0u) {\n return 0.0;\n }\n\n let totalOnBits = onBitsa + onBitsb;\n var commonBits: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n commonBits = commonBits + countOneBits(a[i] & b[i]);\n }\n\n return 1.0 - f32(commonBits) / f32(totalOnBits - commonBits);\n `},[Y.LEVENSTEIN]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n let maxLength: u32 = max(aLength, bLength);\n let minLength: u32 = min(aLength, bLength);\n\n let maxIntDistance = ceil(maxDistance * f32(maxLength));\n\n // we will store two arrays as matrix and swap the working indices per pass.\n // this way we can reduce memory usage per computation to just O(aLength)\n // the grid will have aLength + 1 columns and bLength + 1 rows\n // this will be guaranteed by iteration, but the array sizes must be known at compile time, so we will use a fixed size of maxArraySize\n var dynamicPassMat: array<array<f32, ${e+1}u>, 2>; // initialize to 0\n \n var prevIndex: u32 = 0;\n var curIndex: u32 = 1; // we will swap these indices per pass\n\n // initialize the first row\n for (var i = 0u; i <= aLength; i = i + 1u) {\n dynamicPassMat[prevIndex][i] = f32(i);\n }\n\n // iterate over the rows\n for (var i = 1u; i <= bLength; i = i + 1u) {\n dynamicPassMat[curIndex][0] = f32(i);\n var minEntry: f32 = f32(maxLength);\n let prevRow = &dynamicPassMat[prevIndex];\n let curRow = &dynamicPassMat[curIndex];\n let bMon = u32(b[i - 1]);\n for (var j = 1u; j <= aLength; j = j + 1u) {\n var cost: f32 = f32(a[j - 1] != bMon);\n var res: f32 = min(\n min(\n (*prevRow)[j] + 1.0, // deletion\n (*curRow)[j - 1] + 1.0, // insertion\n ),\n (*prevRow)[j - 1] + cost // substitution\n );\n (*curRow)[j] = res;\n if (res < minEntry) {\n minEntry = res;\n }\n }\n // swap the indices\n let temp: u32 = prevIndex;\n prevIndex = curIndex;\n curIndex = temp;\n if (minEntry > maxIntDistance) {\n return 1.0;\n }\n }\n\n return dynamicPassMat[prevIndex][aLength] / f32(maxLength);\n `},[Y.NEEDLEMAN_WUNSCH]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n let maxLength: u32 = max(aLength, bLength);\n let minLength: u32 = min(aLength, bLength);\n \n let maxIntDistance = ceil(maxDistance * f32(maxLength));\n // we will store two arrays as matrix and swap the working indices per pass.\n // this way we can reduce memory usage per computation to just O(aLength)\n // the grid will have aLength + 1 columns and bLength + 1 rows\n // this will be guaranteed by iteration, but the array sizes must be known at compile time, so we will use a fixed size of maxArraySize\n var dynamicPassMat: array<array<f32, ${e+1}u>, 2>; // initialize to 0\n \n // we need to keep track of which operation led to the current cell\n // i.e. whether we came from the left, top or diagonal to assign gap open/gap extend penalty\n var verticalGaps: array<u32, ${e+1}u>;\n var horizontalGaps: array<u32, ${e+1}u>;\n\n let gapOpenPenalty: f32 = suppInfo.gapOpenPenalty${t};\n let gapExtensionPenalty: f32 = suppInfo.gapExtensionPenalty${t};\n var prevIndex: u32 = 0;\n var curIndex: u32 = 1; // we will swap these indices per pass\n // initialize the first row\n for (var i = 0u; i <= aLength; i = i + 1u) {\n dynamicPassMat[prevIndex][i] = gapOpenPenalty + f32(i - 1) * gapExtensionPenalty;\n dynamicPassMat[curIndex][i] = 0.0;\n }\n dynamicPassMat[0][0] = 0.0;\n\n let simMatrix = &suppInfo.similarityMatrix${t}; // using pointers make things faster\n // iterate over the rows\n for (var i = 1u; i <= bLength; i = i + 1u) {\n let prevRow = &dynamicPassMat[prevIndex];\n let curRow = &dynamicPassMat[curIndex];\n (*curRow)[0] = gapOpenPenalty + f32(i - 1) * gapExtensionPenalty;\n var minEntry: f32 = f32(maxLength);\n let monB = u32(b[i - 1]);\n for (var j = 1u; j <= aLength; j = j + 1u) {\n let monA = u32(a[j - 1]);\n \n let cost: f32 = (*prevRow)[j - 1] + 1f - (*simMatrix)[monA][monB];\n var top = (*prevRow)[j]; // deletion\n if (verticalGaps[j] > 0) {\n top = top + gapExtensionPenalty;\n } else {\n top = top + gapOpenPenalty;\n }\n var left = (*curRow)[j - 1]; // insertion\n if (horizontalGaps[j - 1] > 0) {\n left = left + gapExtensionPenalty;\n } else {\n left = left + gapOpenPenalty;\n }\n var res: f32 = min(\n min(\n top, // deletion\n left, // insertion\n ),\n cost // substitution\n );\n (*curRow)[j] = res;\n if (res < minEntry) {\n minEntry = res;\n }\n // update the horizontal and vertical gaps\n if (res == cost) {\n verticalGaps[j] = 0;\n horizontalGaps[j] = 0;\n } else if (res == left) {\n verticalGaps[j] = 0;\n horizontalGaps[j] = 1;\n } else {\n verticalGaps[j] = 1;\n horizontalGaps[j] = 0;\n }\n }\n // swap the indices\n let temp: u32 = prevIndex;\n prevIndex = curIndex;\n curIndex = temp;\n if (minEntry > maxIntDistance) {\n return 1.0;\n }\n }\n return dynamicPassMat[prevIndex][aLength] / f32(maxLength);\n \n `},[Y.MONOMER_CHEMICAL_DISTANCE]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n let maxLength: u32 = max(aLength, bLength);\n let minLength: u32 = min(aLength, bLength);\n let sizeDiff: u32 = maxLength - minLength;\n \n let maxIntDistance = ceil(maxDistance * f32(maxLength)) - f32(sizeDiff);\n\n let simMatrix = &(suppInfo.similarityMatrix${t}); // using pointers make things faster\n var diff: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n diff = diff + 1.0 - (*simMatrix)[u32(a[i])][u32(b[i])];\n if (diff > maxIntDistance) {\n return 1.0;\n }\n }\n diff += f32(sizeDiff);\n return diff / ${e};\n `},[Y.SOKAL]:function(e,t){return`\n var onBitsa: u32 = 0u;\n var onBitsb: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n onBitsa = onBitsa + countOneBits(a[i]);\n onBitsb = onBitsb + countOneBits(b[i]);\n }\n let total = onBitsa + onBitsb;\n if (total == 0u) {\n return 1.0;\n }\n var commonBits: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n commonBits = commonBits + countOneBits(a[i] & b[i]);\n }\n return 1.0 - f32(commonBits) / f32(total * 2 - commonBits * 3);\n `},[Y.COSINE]:function(e,t){return`\n var onBitsa: u32 = 0u;\n var onBitsb: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n onBitsa = onBitsa + countOneBits(a[i]);\n onBitsb = onBitsb + countOneBits(b[i]);\n }\n let total = onBitsa * onBitsb; // p.s. here total is taken by multiplying\n if (total == 0u) {\n return 1.0;\n }\n var commonBits: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n commonBits = commonBits + countOneBits(a[i] & b[i]);\n }\n return 1.0 - f32(commonBits) / sqrt(f32(total));\n `},[Y.ASYMMETRIC]:function(e,t){return`\n var onBitsa: u32 = 0u;\n var onBitsb: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n onBitsa = onBitsa + countOneBits(a[i]);\n onBitsb = onBitsb + countOneBits(b[i]);\n }\n let min = min(onBitsa, onBitsb);\n if (min == 0u) {\n return 1.0;\n }\n var commonBits: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n commonBits = commonBits + countOneBits(a[i] & b[i]);\n }\n return 1.0 - f32(commonBits) / f32(min);\n `},[Y.Difference]:function(e,t){return`\n let range = suppInfo.range${t};\n return f32(abs(f32(a[0]) - f32(b[0])) / range);\n `},[Y.OneHot]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n if (aLength != bLength) {\n return 1.0;\n }\n for (var i = 0u; i < aLength; i = i + 1u) {\n if(a[i] != b[i]) {\n return 1.0;\n }\n }\n return 0.0;\n `}},K={[Y.HAMMING]:e=>Math.ceil(e/30),[Y.EUCLIDEAN]:e=>Math.ceil(e/30),[Y.MANHATTAN]:e=>Math.ceil(e/30),[Y.TANIMOTO]:e=>Math.ceil(e/60),[Y.SOKAL]:e=>Math.ceil(e/60),[Y.COSINE]:e=>Math.ceil(e/60),[Y.ASYMMETRIC]:e=>Math.ceil(e/60),[Y.LEVENSTEIN]:e=>Math.ceil(e*e/60),[Y.NEEDLEMAN_WUNSCH]:e=>Math.ceil(e*e/60),[Y.MONOMER_CHEMICAL_DISTANCE]:e=>Math.ceil(e/25),[Y.Difference]:e=>1,[Y.OneHot]:e=>Math.ceil(e/40)},z={STRING:new Set([Y.HAMMING,Y.LEVENSTEIN,Y.NEEDLEMAN_WUNSCH,Y.MONOMER_CHEMICAL_DISTANCE,Y.OneHot]),UINT32ARRAY:new Set([Y.HAMMING,Y.EUCLIDEAN,Y.MANHATTAN,Y.MONOMER_CHEMICAL_DISTANCE,Y.LEVENSTEIN,Y.NEEDLEMAN_WUNSCH,Y.TANIMOTO,Y.COSINE,Y.SOKAL,Y.ASYMMETRIC,Y.OneHot,Y.Difference]),INT32ARRAY:new Set([Y.EUCLIDEAN,Y.MANHATTAN,Y.OneHot,Y.Difference]),FLOAT32ARRAY:new Set([Y.EUCLIDEAN,Y.MANHATTAN,Y.Difference]),NUMBER:new Set([Y.EUCLIDEAN,Y.MANHATTAN,Y.Difference]),BITARRAY:new Set([Y.TANIMOTO,Y.COSINE,Y.SOKAL,Y.ASYMMETRIC])};var X=function(e,t,n,s){return new(n||(n=Promise))((function(r,i){function o(e){try{l(s.next(e))}catch(e){i(e)}}function a(e){try{l(s.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))},J=function(e,t,n,s){return new(n||(n=Promise))((function(r,i){function o(e){try{l(s.next(e))}catch(e){i(e)}}function a(e){try{l(s.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};function Q(e,t,n,s){return e.map(((e,s)=>`\n fn distanceScript${s}(aIndex: u32, bIndex: u32) -> f32 {\n let a = computeInfo.data${s}[aIndex];\n let b = computeInfo.data${s}[bIndex];\n let maxDistance: f32 = ${n};\n ${q[e](t[s],s)}\n }\n `)).join("\n")+"\n"+`\n fn combinedDistance(aIndex: u32, bIndex: u32) -> f32 {\n var distances: array<f32, ${e.length}>;\n ${e.map(((e,t)=>`distances[${t}] = distanceScript${t}(aIndex, bIndex);`)).join("\n")}\n ${W[s](e.length)}\n }\n \n `}let ee=0;const te="cliffsDf",ne=new y.Subject,se="activity_difference",re="SALI_index",ie="similarity",oe="line_index",ae=["1_molecule","2_molecule"],le="filterCliffs";async function ce(e,t,s,r,l,c,u,h,m,p,g,y,b,v,w,C){ee++;const S=c/100;let A,x=!1;const E=y.inputs,I=await y.apply({[E[0].name]:t,[E[1].name]:u,...m.preprocessingFuncArgs??{}});let T=[];if(h===d){const t=await function(e,t,s,r,i,o,a=10,l=!1){const c=new Worker(new URL(n.p+n.u(246),n.b));let u;return c.postMessage({data:e,threshold:t,weights:s,aggregationMethod:r,distanceFns:i,distanceFnArgs:o,maxIterations:a,useWebGPU:l}),{promise:new Promise(((e,t)=>{u=e,c.onmessage=t=>{setTimeout((()=>c.terminate()),100),e(t.data.res)},c.onerror=e=>{setTimeout((()=>c.terminate()),100),t(e)}})),terminate:()=>{try{u(null),c.terminate()}catch(e){console.error(e)}}}}([I.entries],c,[1],"MANHATTAN",[u],[I.options??{}],m?.maxIterations??5,m.useWebGPU??!1).promise;e.columns.addNewInt(e.columns.getUnusedName("MCL Cluster")).init((e=>t.clusters[e])),T=[t.embedX,t.embedY]}else T=await j([I.entries],h,[u],[1],"MANHATTAN",{...m,distanceFnArgs:[I.options??{}]});if(T.length!==s.length)throw new Error("Number of axes names should be equal to number of embedding dimensions");for(let t=0;t<T.length;++t)e.columns.addNewFloat(s[t]).init((e=>T[t][e]));let _=null;if(m.useWebGPU)try{_=await function(e,t=.8,n,s,r,i){return J(this,void 0,void 0,(function*(){const o=yield function(){return X(this,void 0,void 0,(function*(){const e=yield navigator.gpu.requestAdapter({powerPreference:"high-performance"});if(null==e)return null;const t=1e9,n=e.limits,s=n.maxBufferSize,r=n.maxStorageBufferBindingSize;try{return yield e.requestDevice({requiredLimits:{maxBufferSize:Math.min(s,t),maxStorageBufferBindingSize:Math.min(r,t)}})}catch(t){return console.error("Failed to create device with required limits",t),yield e.requestDevice()}}))}();if(!o)return null;const a=Object.values(Y);if(n.some((e=>!a.includes(e))))throw new Error("Invalid distance metrics provided: "+n.join(", "));if(!Object.values(V).includes(s))throw new Error("Invalid aggregation function provided: "+s);const l=1-t;if(i.length!==e.length||i.length!==n.length||i.length!==r.length)throw new Error("Options, weigths and distance functions must be provided for each column");if(e.some((t=>t.length!==e[0].length)))throw new Error("All entry lists must be the same length");const c=e.length,u=e[0].length,h=e.map(((e,t)=>function(e,t=Y.HAMMING,n,s={gapOpenPenalty:1,gapExtensionPenalty:.6}){var r,i;let o=null;const a=e.some((e=>"string"==typeof e))?(o="STRING",e.map((e=>new Uint32Array(e.split("").map((e=>e.charCodeAt(0))))))):e.some((e=>"number"==typeof e))?(o="NUMBER",e.map((e=>new Float32Array([e])))):"object"==typeof e[0]&&e.some((e=>"_data"in e&&"_length"in e))?(o="BITARRAY",e.map((e=>e._data))):e.some((e=>e instanceof Float32Array))?(o="FLOAT32ARRAY",e):e.some((e=>e instanceof Uint32Array))?(o="UINT32ARRAY",e):e.some((e=>e instanceof Int32Array))?(o="INT32ARRAY",e):void 0;if(!a||!o)throw new Error("Invalid entry type, could not determine entry type from input list");const l=a[0]instanceof Int32Array?"INT32ARRAY":a[0]instanceof Float32Array?"FLOAT32ARRAY":"UINT32ARRAY",c=new Uint32Array(a.map((e=>e.length)));if(!z[o]||!z[o].has(t))throw new Error(`Distance metric '${t}' not supported for entry type '${o}'`);const u=c.reduce(((e,t)=>Math.max(e,t)),0),h=K[t](u),d="INT32ARRAY"===l?Int32Array:"FLOAT32ARRAY"===l?Float32Array:Uint32Array,m=new d(a.length*u);a.forEach(((e,t)=>{m.set(e,t*u)}));let p="",f=0,g="FLOAT32ARRAY",y=null;if(t===Y.NEEDLEMAN_WUNSCH||t===Y.MONOMER_CHEMICAL_DISTANCE){let e=s.scoringMatrix&&s.alphabetIndexes?Object.keys(s.alphabetIndexes).reduce(((e,t)=>Math.max(e,t.charCodeAt(0))),0):-1;if(!s.alphabetIndexes||!s.scoringMatrix){for(let t=0;t<m.length;t++)m[t]>e&&(e=m[t]);s.scoringMatrix=new Array(e+1).fill(null).map((()=>new Array(e+1).fill(0))),s.alphabetIndexes={};for(let e=0;e<s.scoringMatrix.length;e++)s.scoringMatrix[e][e]=1,s.alphabetIndexes[String.fromCharCode(e)]=e}const t=(e+1)*(e+1),o=new Array(e+1).fill(null).map((()=>new Float32Array(e+1)));for(let t=0;t<e+1;t++)o[t][t]=1;const a=s.alphabetIndexes;for(const e of Object.keys(a))for(const t of Object.keys(a))e!==t&&(o[e.charCodeAt(0)][t.charCodeAt(0)]=s.scoringMatrix[a[e]][a[t]]);f=2+t,g="FLOAT32ARRAY",y=new Float32Array(f),y[0]=null!==(r=s.gapOpenPenalty)&&void 0!==r?r:1,y[1]=null!==(i=s.gapExtensionPenalty)&&void 0!==i?i:.6;let l=2;for(let e=0;e<o.length;e++)y.set(o[e],l),l+=o[e].length;p=`\n gapOpenPenalty${n}: f32,\n gapExtensionPenalty${n}: f32,\n similarityMatrix${n}: array<array<f32, ${e+1}>, ${e+1}>`}else if(t===Y.Difference){if(!s.range||"number"!=typeof s.range||s.range<=0){const e=m.reduce(((e,t)=>Math.min(e,t)),m[0]),t=m.reduce(((e,t)=>Math.max(e,t)),m[0]);s.range=t-e}if(s.range<=0)throw new Error("Invalid range for difference distance metric: "+s.range);f=1,g="FLOAT32ARRAY",y=new Float32Array([s.range]),p=`\n range${n}: f32`}const b=m instanceof Int32Array?"i32":m instanceof Float32Array?"f32":"u32",v=`data${n}: array<array<${b}, ${u}>, ${a.length}>`;return{flatSourceArray:m,sourceArraySize:m.length,maxEntryLen:u,arraySizes:c,complexity:h,suppInfoBuffer:y,suppInfoSize:f,suppInfoType:g,suppInfoStructWgsl:p,entryType:o,dataTypeWGSL:b,dataStructWgsl:v,EncodedArrayConstructor:d}}(e,n[t],t,i[t])));if(0===c)throw new Error("No columns provided. Please provide at least one column of data.");1===c&&(s=V.MANHATTAN);let d=h.map((e=>e.suppInfoStructWgsl)).filter((e=>!!e&&""!=e)).join(",\n"),m=!1;d&&""!=d.trim()||(m=!0,d="\ndummy: f32\n");const p=h.map((e=>e.dataStructWgsl)).filter((e=>!!e&&""!=e)).join(",\n"),f=new Uint32Array(c*u);h.forEach(((e,t)=>{f.set(e.arraySizes,t*u)}));const g=1e4,y=100,b=h.reduce(((e,t)=>e+t.complexity),0),v=Math.ceil(1e4/b),w=Math.ceil(Math.sqrt(Math.ceil(100))),C=10*w,S=u*(u-1)/2,A=Math.ceil(S/g),x=o.createShaderModule({label:"Sparse matrix compute shader",code:`\n // each thread will perform 100 iterations at one time, comparing 100 pairs of entries.\n // in total, each thread will perform at most ${A} comparisons.\n // first is the result struct, containing is, js, and distances. each array with length of 100,\n // and also integer for how many pairs were found to be below threshold.\n struct SparseResult {\n i: array<array<u32, 100>, 10000>,\n j: array<array<u32, 100>, 10000>,\n distances: array<array<f32, 100>, 10000>,\n found: array<u32, 10000>,\n done: array<u32, 10000>\n }\n // struct for the data\n struct ComputeInfo {\n // start at cols and rows, and end at cols and rows for each thread, these will be calculated on cpu and passed to gpu.\n startAtCols: array<u32, 10000>,\n startAtRows: array<u32, 10000>,\n endAtCols: array<u32, 10000>,\n endAtRows: array<u32, 10000>,\n\n // the ACTUALLY sizes of each entry\n entrySizes: array<array<u32, ${u}>, ${c}>,\n // the weights for each entry\n weights: array<f32, ${c}>,\n // the data for each entry\n ${p} // an example of the dataWgsl would be:\n //data0: array<array<u32,20>,100>,\n //data1: array<array<u32,20>,100>\n }\n\n // struct for the supplementary information\n struct SuppInfo {\n // struct containing all the supplementary info, like scoring matrix, alphabet indexes, range, etc.\n ${d}\n };\n\n @group(0) @binding(0) var<storage, read_write> computeInfo: ComputeInfo;\n @group(0) @binding(1) var<storage, read_write> suppInfo: SuppInfo;\n @group(0) @binding(2) var<storage, read_write> results: SparseResult;\n @compute @workgroup_size(10, 10) fn calcSparseMatrix(\n @builtin(global_invocation_id) id: vec3<u32>\n ) {\n ${m?"let otherDummy = suppInfo.dummy * 2;":""} // just to make sure that the suppInfo is not optimized out\n let threadCol = id.x;\n let threadRow = id.y;\n let linearIndex = threadRow * ${C} + threadCol;\n if (linearIndex >= 10000) {\n return; // if we are out of bounds, return\n } \n var startAtCol: u32 = computeInfo.startAtCols[linearIndex];\n var startAtRow: u32 = computeInfo.startAtRows[linearIndex];\n let endAtCol: u32 = min(computeInfo.endAtCols[linearIndex], ${u}u);\n let endAtRow: u32 = min(computeInfo.endAtRows[linearIndex], ${u}u);\n let is = &results.i[linearIndex];\n let js = &results.j[linearIndex];\n let distances = &results.distances[linearIndex];\n results.found[linearIndex] = 0; // initialize the found counter\n var found: u32 = 0;\n if (results.done[linearIndex] > 0) {\n return; // if we are done, return\n }\n for (var i = 0; i < ${v}; i++) {\n if (startAtCol >= endAtCol && startAtRow >= endAtRow) {\n results.done[linearIndex] = 1;\n break;\n }\n if (found >= 100) {\n break;\n }\n let dist = combinedDistance(startAtCol, startAtRow);\n if (dist <= ${l}) {\n (*is)[found] = startAtCol;\n (*js)[found] = startAtRow;\n (*distances)[found] = dist;\n found = found + 1;\n }\n startAtCol = startAtCol + 1;\n if (startAtCol >= ${u}u) {\n startAtRow += 1;\n startAtCol = startAtRow + 1;\n }\n }\n results.found[linearIndex] = found;\n // update the startAtCols and startAtRows\n computeInfo.startAtCols[linearIndex] = startAtCol;\n computeInfo.startAtRows[linearIndex] = startAtRow;\n\n }\n\n // this will generate the distance script for each distance metric and then combine them into one\n ${Q(n,h.map((e=>e.maxEntryLen)),l,s)}\n\n\n `}),E=o.createComputePipeline({label:"sparse matrix compute pipeline",layout:"auto",compute:{module:x,entryPoint:"calcSparseMatrix"}}),I=new Uint32Array(g),T=new Uint32Array(g),_=new Uint32Array(g),M=new Uint32Array(g),$=Math.floor(S/g);let N=0,L=1;console.time("GPUthreadStarts");for(let e=0;e<g;e++){const t=9999===e?S-1:(e+1)*$,n=u-2-Math.floor(Math.sqrt(-8*t+4*u*(u-1)-7)/2-.5),s=t-u*n+Math.floor((n+1)*(n+2)/2);I[e]=L,T[e]=N,_[e]=s,M[e]=n,N=n,L=s}console.timeEnd("GPUthreadStarts");const P=4e4+u*c+c+h.reduce(((e,t)=>e+t.sourceArraySize),0),R=h.reduce(((e,t)=>e+t.suppInfoSize),0),O=1e6,k=P*Uint32Array.BYTES_PER_ELEMENT;let F=k;const G=15&k;0!==G&&(F+=16-G);const D=o.createBuffer({label:"compute info buffer",size:F,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST,mappedAtCreation:!0}),B=D.getMappedRange();let U=0;new Uint32Array(B,U,g).set(I),U+=g*Uint32Array.BYTES_PER_ELEMENT,new Uint32Array(B,U,g).set(T),U+=g*Uint32Array.BYTES_PER_ELEMENT,new Uint32Array(B,U,g).set(_),U+=g*Uint32Array.BYTES_PER_ELEMENT,new Uint32Array(B,U,g).set(M),U+=g*Uint32Array.BYTES_PER_ELEMENT,new Uint32Array(B,U,f.length).set(f),U+=f.length*Uint32Array.BYTES_PER_ELEMENT,new Float32Array(B,U,c).set(r),U+=c*Float32Array.BYTES_PER_ELEMENT;for(const e of h){const t=e.EncodedArrayConstructor,n=e.sourceArraySize;new t(B,U,n).set(e.flatSourceArray),U+=n*t.BYTES_PER_ELEMENT}D.unmap();const H=R*Uint32Array.BYTES_PER_ELEMENT;let j=H;const W=15&H;0!==W&&(j+=16-W),j=Math.max(j,16);const Z=o.createBuffer({label:"supp info buffer",size:j,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST,mappedAtCreation:!0}),q=Z.getMappedRange();let J=0;for(const e of h)e.suppInfoBuffer&&e.suppInfoBuffer.byteLength>0&&e.suppInfoSize>0&&(new("UINT32ARRAY"===e.suppInfoType?Uint32Array:Float32Array)(q,J,e.suppInfoBuffer.length).set(e.suppInfoBuffer),J+=e.suppInfoBuffer.byteLength);0===J&&new Uint32Array(q,0,4).set([1,1,1,1]),Z.unmap();const ee=302e4*Uint32Array.BYTES_PER_ELEMENT;let te=ee;const ne=15ⅇ0!==ne&&(te+=16-ne);const se=o.createBuffer({label:"results buffer",size:te,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),re=o.createBindGroup({label:"bindGroup for sparse matrix buffer",layout:E.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:D}},{binding:1,resource:{buffer:Z}},{binding:2,resource:{buffer:se}}]}),ie=o.createBuffer({label:"results out buffer",size:se.size,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),oe=[],ae=[],le=[];let ce=!1;for(;!ce;){const e=o.createCommandEncoder({label:"distance encoder"}),t=e.beginComputePass({label:"distance compute pass"});t.setPipeline(E),t.setBindGroup(0,re),t.dispatchWorkgroups(w,w),t.end(),e.copyBufferToBuffer(se,0,ie,0,ie.size);const n=e.finish();o.queue.submit([n]),yield o.queue.onSubmittedWorkDone(),yield ie.mapAsync(GPUMapMode.READ);const s=ie.getMappedRange();let r=0;const i=new Uint32Array(s,r,O);r+=O*Uint32Array.BYTES_PER_ELEMENT;const a=new Uint32Array(s,r,O);r+=O*Uint32Array.BYTES_PER_ELEMENT;const l=new Float32Array(s,r,O);r+=O*Float32Array.BYTES_PER_ELEMENT;const c=new Uint32Array(s,r,g);r+=g*Uint32Array.BYTES_PER_ELEMENT,ce=new Uint32Array(s,r,g).every((e=>1===e));const u=c.reduce(((e,t)=>e+t),0),h=new Uint32Array(u),d=new Uint32Array(u),m=new Float32Array(u);let p=0;for(let e=0;e<c.length;e++){const t=c[e];0!==t&&(h.set(i.subarray(e*y,e*y+t),p),d.set(a.subarray(e*y,e*y+t),p),m.set(l.subarray(e*y,e*y+t),p),p+=t)}oe.push(h),ae.push(d),le.push(m),ie.unmap()}const ue=oe.reduce(((e,t)=>e+t.length),0),he=new Uint32Array(ue),de=new Uint32Array(ue),me=new Float32Array(ue);let pe=0;for(let e=0;e<oe.length;e++)he.set(oe[e],pe),de.set(ae[e],pe),me.set(le[e],pe),pe+=oe[e].length;return o.destroy(),{i:he,j:de,distance:me}}))}([I.entries],S,[u],V.MANHATTAN,[1],[I.options??{}])}catch(e){console.error(e)}_||(m.useWebGPU&&console.error("WebGPU sparse matrix calculation failed, falling back to CPU implementation"),_=await(new k).calc(I.entries,u,S,I.options));const M=await async function(e,t){const n=e.distance.map(((n,s)=>{const r=Math.abs(t.get(e.i[s])-t.get(e.j[s]));return 0!=n?r/n:1/0})),s=e.distance.map((e=>1-e)),r=e.i,i=e.j,o=new Set;return e.distance.forEach(((t,n)=>{o.add(e.i[n]),o.add(e.j[n])})),{simVals:s,saliVals:n,n1:r,n2:i,cliffsMolIds:o}}(_,l),$=function(e,t,n,s,r,i){const o=new Array(e).fill(0);for(let e=0;e!=n.length;++e)t[e]!=1/0&&(i.get(n[e])>i.get(s[e])?o[n[e]]+=t[e]:o[s[e]]+=t[e]);return a.Column.fromList("double",`sali_${r[0].substring(r[0].lastIndexOf("_"))}`,o)}(t.length,M.saliVals,M.n1,M.n2,s,l);e.columns.add($);const N=function(e,t){const n=a.BitSet.create(e.rowCount);for(let s=0;s<e.rowCount;s++)n.set(s,t.has(s));return n}(e,M.cliffsMolIds),L=function(e){const t=e.filter((e=>e!==1/0)),n=t.reduce(((e,t)=>Math.min(e,t)),Number.MAX_VALUE),s=t.reduce(((e,t)=>Math.max(e,t)),n);return{max:s,min:n}}(M.saliVals),P=.8/(L.max-L.min),R=i.shell.getTableView(e.name),O=R.addViewer(a.VIEWER.SCATTER_PLOT,{xColumnName:s[0],yColumnName:s[1],size:$.name,color:l.name,showXSelector:!1,showYSelector:!1,showSizeSelector:!1,showColorSelector:!1,markerMinSize:5,markerMaxSize:25,title:r}),G=function(e,t,n,s,r,i,o,l){const c={from:new Uint32Array(t.n1.length),to:new Uint32Array(t.n1.length),opacities:new Float32Array(t.n1.length),colors:new Array(t.n1.length),widths:new Float32Array(t.n1.length)};for(let n=0;n<t.n1.length;n++)c.from[n]=t.n1[n],c.to[n]=t.n2[n],c.opacities[n]=t.saliVals[n]===1/0?1:.2+(t.saliVals[n]-o.min)*l,c.colors[n]=e.selection.get(c.from[n])&&e.selection.get(c.to[n])?"255,255,0":"0,128,0",c.widths[n]=1;const u=a.DataFrame.create(c.from.length);return ae.forEach(((e,t)=>{u.columns.addNewString(e).init((e=>n.get(0===t?c.from[e]:c.to[e]))),function(e,t){Object.keys(t).forEach((n=>{e.tags[n]=t[n]}))}(u.col(e),i),u.col(e).semType=r})),u.columns.addNewFloat(se).init((e=>Math.abs(s.get(c.from[e])-s.get(c.to[e])))),u.columns.addNewInt(oe).init((e=>e)),u.columns.addNewFloat(re).init((e=>t.saliVals[e])),u.columns.addNewFloat(ie).init((e=>t.simVals[e])),u.name=`${te}${ee}`,{lines:c,linesDf:u}}(e,M,t,l,p,g,L,P);G.lines.skipMultiLineCalculation=!0,G.linesDf.col(re).setTag("description","Structure−Activity Landscape Index (activity difference divided by 1 minus similarity)");const B=new D(O,s[0],s[1],G.lines,F.none),U=w?w(G.linesDf,ae).sort([re],[!1]):G.linesDf.plot.grid().sort([re],[!1]);U.col(oe)&&(U.col(oe).visible=!1),e.temp[".cliffsDfGrid"]=U;const H=o.button(`${G.linesDf.rowCount} cliffs`,(()=>{R.dockManager.dock(U,"down",null,"Activity cliffs",C??.2)}));H.classList.add("scatter_plot_link","cliffs_grid"),O.root.append(H);const W=o.switchInput("Show only cliffs",!1,(()=>{W.value?(O.dataFrame.setTag(le,s[0]),e.filter.and(N),ne.next(s[0])):(O.dataFrame.setTag(le,""),e.filter.setAll(!0),ne.next(""))}));W.root.classList.add("scatter_plot_link","show_only_cliffs"),O.root.append(W.root),ne.subscribe((e=>{W.enabled=""===e||e===s[0]}));let Z=!1;O.onEvent("d4-before-draw-scene").subscribe((t=>{Z?Z=!1:W.value&&(setTimeout((()=>{e.filter.and(N)}),100),Z=!0)}));const q=i.events.onViewerClosed.subscribe((e=>{e.args.viewer===O&&(R.dockManager.close(U.root),q.unsubscribe(),R.subs=R.subs.filter((e=>e!==q)))}));return R.subs.push(q),G.linesDf.onCurrentCellChanged.subscribe((()=>{for(let e=0;e<G.linesDf.rowCount;e++)G.lines.widths[e]=e===G.linesDf.currentRowIdx?3:1;B.linesToRender=G.lines;const n=G.linesDf.currentCol&&G.linesDf.currentCol.name===ae[1]?G.lines.to:G.lines.from,r=-1!==G.linesDf.currentRowIdx?G.linesDf.currentRowIdx:null;if(O.dataFrame.currentRowIdx=r?n[r]:-1,null!==r){const n=G.linesDf.currentRowIdx;B.currentLineId=n;const{zoomLeft:a,zoomRight:c,zoomTop:u,zoomBottom:h}=function(e,t,n,s,r,i){const o=Math.abs(n-r),a=Math.abs(s-i),l=e/o,c=t/a,u=Math.min(l,c),h=e/u*5,d=t/u*5,m=(n<r?n:r)+o/2-h/2,p=(s>i?s:i)-a/2+d/2;return{zoomLeft:m,zoomRight:m+h,zoomTop:p,zoomBottom:p-d}}(O.viewport.width,O.viewport.height,O.dataFrame.get(s[0],G.lines.from[n]),O.dataFrame.get(s[1],G.lines.from[n]),O.dataFrame.get(s[0],G.lines.to[n]),O.dataFrame.get(s[1],G.lines.to[n]));O.zoom(a,u,c,h),W.value?e.filter.and(N):!0===W.enabled&&e.filter.setAll(!0),setTimeout((()=>{!function(e,t,n,s,r,a,l,c,u){const h=t.getPane("Cliff Details");o.empty(h.root);const d=u({points:[n,s],lineId:r,df:e,seqCol:a,activityCol:l,sali:c});h.root.append(d),setTimeout((()=>{i.shell.o=t.root}),500)}(e,A,G.lines.from[r],G.lines.to[r],r,t,l,G.linesDf.get(re,r),v);const n=O.dataFrame.getSortedOrder(R.grid.sortByColumns,R.grid.sortTypes);R.grid.scrollToCell(t.name,n.indexOf(O.dataFrame.currentRowIdx))}),1e3)}})),G.linesDf.onSelectionChanged.subscribe((t=>{setTimeout((()=>(()=>{const t=a.BitSet.create(e.rowCount);for(let e=0;e<G.linesDf.rowCount;e++){const n=G.linesDf.selection.get(e);n&&(t.set(G.lines.from[e],!0),t.set(G.lines.to[e],!0)),G.lines.colors[e]=n?"255,255,0":"0,128,0"}e.selection.copyFrom(t),B.linesToRender=G.lines})()),100)})),e.onSelectionChanged.subscribe((t=>{!1===e.selection.anyTrue&&"number"==typeof t&&(x?x=!1:(e=>{e.selection.setAll(!1);for(let e=0;e<G.lines.colors.length;e++)G.lines.colors[e]="0,128,0";B.linesToRender=G.lines})(U.dataFrame))})),B.lineClicked.subscribe((t=>{if(x=!0,B.currentLineId=t.id,-1!==t.id){const n=G.linesDf.selection.clone();setTimeout((()=>{t.event.ctrlKey?(n.set(t.id,!n.get(t.id)),G.linesDf.selection.copyFrom(n)):(G.linesDf.currentRowIdx!==t.id&&(G.linesDf.currentRowIdx=t.id,e.currentRowIdx=G.lines.from[t.id]),G.linesDf.selection.copyFrom(n));const s=G.linesDf.getSortedOrder(U.sortByColumns,U.sortTypes);U.scrollToCell(ae[0],s.indexOf(t.id))}),500)}})),B.lineHover.pipe((0,f.debounceTime)(500)).subscribe((n=>{-1!==n.id&&-1===e.mouseOverRowIdx&&o.tooltip.show(b({lineId:n.id,points:[G.lines.from[n.id],G.lines.to[n.id]],df:e,seqCol:t,activityCol:l}),n.x,n.y)})),O.addProperty("similarityLimit","double",S),A=function(){const e=o.accordion(),t=o.element("i");return t.className="grok-icon svg-icon svg-view-layout",e.addTitle(o.span([t,o.label("Activity cliffs")])),e.addPane("Cliff Details",(()=>o.divText("Cliff has not been selected")),!0),i.shell.o=e.root,e}(),O}var ue,he=n(8260),de=n(5226),me=n(7228),pe=n(8457);async function fe(e,t,n,s){const r=(0,pe.O)(t),i=he.g.forColumn(t).getNewColumnFromList("ref",[n]),o=he.g.forColumn(i).getSplitted(0),l=s===ue.IDENTITY?function(e,t){const n=t.columns.length,s=new Array(n),r=new Array(n),i=new Array(n);for(let o=0;o<n;++o){const n=t.columns.byIndex(o);s[o]=n.getRawData(),r[o]=n.categories.indexOf(""),i[o]=n.categories.indexOf(e.getOriginal(o)??"")}const o=a.Column.float("Identity",t.rowCount),l=o.getRawData();for(let n=0;n<t.rowCount;++n){l[n]=0;for(let t=0;t<e.length;++t)s[t][n]===i[t]&&++l[n];l[n]/=e.length}return o}(o,r):s===ue.SIMILARITY?await async function(e,t){const n=t.columns.toList();return await(0,me.Qx)(n,e)}(o,r):null;if(null===l)throw new Error(`In bio library: Unkown sequence scoring method: ${s}`);return l.name=e.columns.getUnusedName(l.name),e.columns.add(l),l}!function(e){e.IDENTITY="identity",e.SIMILARITY="similarity"}(ue||(ue={}));var ge=n(7945),ye=n(4293),be=n(6414),ve=n.n(be),we=n(2583);const Ce="rgb(100,100,100)",Se="#808080",Ae="rgb(0,0,0)",xe=we.GU;var Ee,Ie;function Te(e,t,n,s,r,i,o=Ce,a=0,l=!1,c=1,u="",h=!1,d=Ie.classic,m=[],p=0,f=null,g=null,y=null,b={}){r.textAlign="start";let v=i.substring(0),w=h?"":u;d===Ie.MSA&&(w="");let C=!0,S=!0,A="difference";if(null!=f&&null!=f.cell.column&&(C=f.cell.column.temp["color-code"]??!0,S=f.cell.column.temp["compare-with-current"]??!0,A=f.cell.column.temp["highlight-difference"]??"difference"),g){const e=g[p];S&&g.length>0&&"difference"===A&&(c=v==e?.3:c),S&&g.length>0&&"equal"===A&&(c=v!=e?.3:c)}null!=y&&(v=xe(v,y));const x=v+w;b[x]??(b[x]=r.measureText(x));let E=b[x];b[v]??(b[v]=r.measureText(v));let I=b[v].width;b[w]??(b[w]=r.measureText(w));const T=b[w].width,_=s/2-(E.fontBoundingBoxAscent+E.fontBoundingBoxDescent)/2+1;function M(n,s){const i=C?o:Ae;r.fillStyle=i,r.globalAlpha=c,d===Ie.classic&&(r.fillText(v,e+n,t+_),r.fillStyle=Se,r.fillText(w,e+s,t+_)),d===Ie.MSA&&r.fillText(v,e+n,t+_)}E=E.width,d===Ie.MSA&&(I=m[p],E=m[p]);const $=(m[p]??0)-(m[0]??0);if(l||E>n)return M($,$+I),e+$+I+T;{const t=(n-E)/2;return M(t,t+I),e+$+t+I}}!function(e){e.maxMonomerLength=".mm.cellRenderer.maxMonomerLength"}(Ee||(Ee={})),function(e){e.MSA="MSA",e.classic="classic"}(Ie||(Ie={}));var _e=n(9611),Me=n(8447),$e=n(7331);const Ne={DNA:"RNA",RNA:"RNA",PT:"PEPTIDE",UN:"PEPTIDE"};var Le;!function(e){e.long="long",e.short="short"}(Le||(Le={}));const Pe={true:"1",false:"0"};var Re=n(3553);const Oe="rgb(100,100,100)",ke=Me.GU;function Fe(e,t,n,s,r){return e?Math.max(Math.min(e.canvas.width/r-n,s)):Math.max(t.canvas.width/r-n,0)}function Ge(e){const t=!ve().enumerate(e).some((([t,n])=>t.length>1&&0!=n&&n!=e.length-1)),n=[],s=t?"":" ";for(const[t,r]of ve().enumerate(e)){let i=t;r<e.length&&(i+=`${t?"":"-"}${s}`),n.push(i)}return[n,t]}function De(e){let t=null,n=null;try{n=e.gridColumn}catch{n=null}if(t=n&&n.dart?n.temp:null,!t){let n=null;try{n=e.cell.column}catch{n=null}t=n?n.temp:null}if(null===t)throw new Error("Monomer placer store (GridColumn or Column) not found.");return t}class Be extends a.GridCellRenderer{constructor(){super(...arguments),this.padding=5}get name(){return"sequence"}get cellType(){return"sequence"}get defaultHeight(){return 30}get defaultWidth(){return 230}onClick(e,t){e.cell.column.temp["current-word"]=e.cell.value,e.grid.invalidate()}onMouseMove(e,t){const n=e.cell.column,s=De(e)[".mm.cellRenderer.monomerPlacer"];if(!s)return;const r=e.bounds,i=t.offsetX-e.gridColumn.left+(e.gridColumn.left-r.x),a=s.getPosition(e.tableRowIndex,i),l=he.g.forColumn(s.col).getSplitted(e.tableRowIndex).canonicals;if(null!==a&&a<l.length){const e=l[a],r=[o.div(e)];let i=s._monomerStructureMap[e];i=s._monomerStructureMap[e]=(()=>{const t=he.g.forColumn(n).alphabet??"UN",r=Ne[t];return s.props.monomerLib.getTooltip(r,e)})(),r.push(i),o.tooltip.show(o.divV(r),t.x+16,t.y+16)}else o.tooltip.hide()}render(e,t,n,s,r,i,o){let l,c=0,u=50;try{l=i.grid}catch(e){l=void 0;const[t,n]=(0,ge.yf)(e);ls.logger.error(t,void 0,n)}const h=i.cell.column;if(!l||!h)return;const d=h.temp,m=d["monomer-width"];if("short"===(null!=m?m:"short")){const e=parseInt(h.getTag(Ee.maxMonomerLength));u=(isNaN(e)?ls.properties?.MaxMonomerLength:e)??4}let p=De(i)[".mm.cellRenderer.monomerPlacer"];p||(p=new _e.A(l,h,(()=>{const e=he.g.forColumn(h);return{seqHandler:e,monomerCharWidth:7,separatorWidth:e.isMsa()?8:c,monomerToShort:ke,monomerLengthLimit:u,monomerLib:ps()}}))),h.tags[".mm.cellRenderer.settingsChanged"]===Pe.true&&(c=d[".mm.cellRenderer.gapLength"]??c,p.setMonomerLengthLimit(u),p.setSeparatorWidth(p.isMsa()?8:c),h.setTag(".mm.cellRenderer.settingsChanged",Pe.false));const[f,g]=p.getCellMonomerLengths(i.tableRowIndex);f.length,p.updated&&(De(i)[".mm.cellRenderer.monomerPlacer"]=p),e.save();try{const o=window.devicePixelRatio,l=-1!==i.gridRow?i.grid:null,c=(i.cell.value,i.cell.rowIndex),m=h.getTag("alphabet"),f=50;s=Fe(l,e,t,s,o),e.beginPath(),e.rect(t+this.padding,n+this.padding,s-this.padding-1,r-2*this.padding),e.clip(),e.font="12px monospace",e.textBaseline="top";const y=h.getTag(a.TAGS.UNITS),b=h.getTag("aligned"),v=(0,Me.py)(m),w=h.getTag("separator")??"",C=s/5,S=he.g.forColumn(h),A=d["reference-sequence"],x=d["current-word"];x&&-1===h?.dataFrame?.currentRowIdx&&(d["current-word"]=null);const E=(()=>{const e=S.getSplitter(C);return ve()(e(null!=A&&""!=A?A:x??"").originals).toArray()})(),I=S.getSplitted(c);let T=Oe,_=Ie.classic;b&&b.includes("MSA")&&y==Me.r2.SEPARATOR&&(_=Ie.MSA);for(let o=0;o<I.length;++o){const a=I.getOriginal(o);T=v.get(a),e.fillStyle=Oe;const l=o===I.length-1;if(Te(t+this.padding,n,s,r,e,a,T,0,!0,1,w,l,_,g,o,i,E,u,p._monomerLengthMap),f>s)break}}catch(e){const t=e instanceof Error?e.message:e?e.toString():"Error 'undefined'";ls.logger.error(`Bio: MacromoleculeSequenceCellRenderer.render() error: ${t}`)}finally{e.restore()}}}class Ve extends a.GridCellRenderer{get name(){return"MacromoleculeDifferenceCR"}get cellType(){return Re.Of.MACROMOLECULE_DIFFERENCE}get defaultHeight(){return 30}get defaultWidth(){return 230}render(e,t,n,s,r,i,o){const l=window.devicePixelRatio,c=i.grid,u=i.cell,h=i.tableColumn,d=u.value??"",m=h.tags.separator,p=h.tags[a.TAGS.UNITS];s=Fe(c,e,t,s,l);const[f,g]=d.split("#"),y=(0,we.vU)(p,m);Ue(e,t,n,s,r,ve()(y(f).canonicals).toArray(),ve()(y(g).canonicals).toArray(),p)}}function Ue(e,t,n,s,r,i,o,a,l,c){if(i.length!==o.length){const e=function(e,t){let n=0,s=0;const r=e.length>t.length?e:t,i=e.length>t.length?t:e;for(let e=0;e<i.length;e++)r[e]===i[e]&&n++;const o=r.length-i.length;for(let e=r.length-1;e>o;e--)r[e]===i[e-o]&&s++;const a=new Array(Math.abs(e.length-t.length)).fill(he.lh[Me.r2.FASTA]);function l(e){return n>s?e.concat(a):a.concat(e)}return e.length>t.length?t=l(ve()(t).toArray()):e=l(ve()(e).toArray()),{subParts1:e,subParts2:t}}(i,o);i=e.subParts1,o=e.subParts2}const u=e.measureText(Ge(i).join("")),h=e.measureText(Ge(o).join("")),d=Math.max(u.width,h.width);l&&(s=d+4*i.length,e.canvas.width=d+4*i.length);let m=Math.max(t,t+(s-(d+4*i.length))/2)+5;const p=Math.max(n,n+(r-28)/2);e.save(),e.beginPath(),e.rect(t,n,l?d+4*i.length:s,r),e.clip(),e.font="12px monospace",e.textBaseline="top";let f=$e.UE.Color;"HELM"!=a&&(f=(0,Me.py)(a.substring(a.length-2)));for(let t=0;t<i.length;t++){const n=i[t],a=o[t],l=f.get(n);if(n!=a){const i=f.get(a),o=Te(m,p-7,s,r,e,n,l,0,!0),u=Te(m,p+7,s,r,e,a,i,0,!0);m=Math.max(u,o),c&&(c[t]=He(n,a,l,i,p,7,r))}else m=Te(m,p,s,r,e,n,l,0,!0,.5);m+=4}e.restore()}function He(e,t,n,s,r,i,o){const a=document.createElement("canvas"),l=a.getContext("2d");l.font="12px monospace";const c=l.measureText(Ge([e]).join("")).width,u=l.measureText(Ge([t]).join("")).width,h=Math.max(c,u);return a.height=o,a.width=h+4,l.font="12px monospace",l.textBaseline="top",Te(0,r-i,h,o,l,e,n,0,!0),Te(0,r+i,h,o,l,t,s,0,!0),a}var je,We=n(8467),Ye=n(9298);!function(e){e.Unknown="unknown",e.FR="framework",e.CDR="cdr"}(je||(je={}));const Ze=new class{constructor(){this.regionTypes=[je.CDR],this.chains=["Heavy","Light"],this.skipEmptyPositions=!1,this.fitWidth=!1,this.positionWidth=16,this.positionHeight=Ye.ES.Entropy,this.filterSource=Ye.vS.filterSource}};var qe=n(172),Ke=n(8415);const ze=je;var Xe,Je;!function(e){e.STYLE="Style",e.BEHAVIOR="Behavior",e.LAYOUT="Layout",e.DATA="Data"}(Xe||(Xe={})),function(e){e.skipEmptyPositions="skipEmptyPositions",e.regionTypes="regionTypes",e.chains="chains",e.fitWidth="fitWidth",e.positionWidth="positionWidth",e.positionHeight="positionHeight",e.filterSource="filterSource"}(Je||(Je={}));const Qe=Ze;class et extends a.JsViewer{constructor(){super(),this.viewed=!1,this.regionsFg=null,this.regionsRoot=null,this.isOpened=!1,this.panelNode=null,this.regions=[],this.viewerId=++et.viewerCounter,this.setDataInProgress=!1,this.host=null,this.mainLayout=null,this.logos=[],this.viewSubs=[],this.calcSizeRequested=!1,this._onRendered=new y.Subject,this.skipEmptyPositions=this.bool(Je.skipEmptyPositions,Qe.skipEmptyPositions,{category:Xe.DATA}),this.regionTypes=this.stringList(Je.regionTypes,Qe.regionTypes,{category:Xe.DATA,choices:Object.values(ze).filter((e=>e!=ze.Unknown))}),this.chains=this.stringList(Je.chains,Qe.chains,{category:Xe.DATA,choices:["Heavy","Light"]}),this.fitWidth=this.bool(Je.fitWidth,Qe.fitWidth,{category:Xe.LAYOUT}),this.positionWidth=this.float(Je.positionWidth,Qe.positionWidth,{category:Xe.LAYOUT,editor:"slider",min:0,max:64,description:"Internal WebLogo viewers property width of position."}),this.positionHeight=this.string(Je.positionHeight,Qe.positionHeight,{category:Xe.LAYOUT,choices:Object.keys(Ye.ES)}),this.filterSource=this.string(Je.filterSource,Qe.filterSource,{category:Xe.BEHAVIOR,choices:Object.values(Ye.Ct)}),this.viewSyncer=new qe.c(ls.logger)}viewerToLog(){return`VdRegionsViewer<${this.viewerId}>`}async init(){this.subs.push((0,y.fromEvent)(this.root,"mousemove").subscribe(this.rootOnMouseMove.bind(this)))}detach(){const e=`${this.viewerToLog()}.detach()`,t=super.detach.bind(this);this.viewSyncer.sync(`${e}`,(async()=>{this.setDataInProgress||(this.viewed&&(await this.destroyView("detach"),this.viewed=!1),t())}))}onTableAttached(){super.onTableAttached(),this.setData(this.regions)}onPropertyChanged(e){if(super.onPropertyChanged(e),e){switch(e.name){case Je.regionTypes:case Je.chains:this.setData(this.regions)}switch(e.name){case Je.skipEmptyPositions:for(let e=0;e<this.logos.length;++e)for(const t of this.chains)this.logos[e][t].setOptions({[Ke.bo.skipEmptyPositions]:this.skipEmptyPositions});this.calcSize();break;case Je.fitWidth:case Je.positionWidth:this.calcSize();break;case Je.positionHeight:for(let e=0;e<this.logos.length;++e)for(const t of this.chains)this.logos[e][t].setOptions({[Ke.bo.positionHeight]:this.positionHeight});this.calcSize();break;case Je.filterSource:this.filterSourceInput.value=this.filterSource;break;default:this.setData(this.regions)}}else console.warn("Bio: VdRegionsViewer.onPropertyChanged() property is null")}setData(e){const t=`${this.viewerToLog()}.setData()`;ls.logger.debug(`${t}, in, regions.length = ${e.length}`),this.viewSyncer.sync(`${t}`,(async()=>{if(!this.setDataInProgress){this.setDataInProgress=!0;try{this.viewed&&(await this.destroyView("setData"),this.viewed=!1),this.regions=e,this.viewed||(await this.buildView("setData"),this.viewed=!0)}finally{this.setDataInProgress=!1}}}))}async destroyView(e){ls.logger.debug(`Bio: VdRegionsViewer.destroyView( mainLayout = ${this.mainLayout?"value":"none"} ), purpose = '${e}', this.regions.length = ${this.regions.length}`),this.filterSourceInput&&o.empty(this.filterSourceInput.root),null!=this.mainLayout&&(this.mainLayout.remove(),this.host.remove(),this.host=null,this.mainLayout=null);for(const e of this.viewSubs)e.unsubscribe()}async buildView(e){ls.logger.debug(`Bio: VdRegionsViewer.buildView() begin, purpose = '${e}', this.regions.length = ${this.regions.length}`);const t=this.regions.filter((e=>this.regionTypes.includes(e.type))),n=Array.from(new Set(t.map((e=>e.order)))).sort(),s=[];for(let e=0;e<n.length;e++)for(const r of this.chains){const i=t.find((t=>t.order==n[e]&&t.chain==r));s.push((async()=>{const t=await this.dataFrame.plot.fromType("WebLogo",{sequenceColumnName:i.sequenceColumnName,startPositionName:i.positionStartName,endPositionName:i.positionEndName,fixWidth:!0,skipEmptyPositions:this.skipEmptyPositions,positionWidth:this.positionWidth,positionHeight:this.positionHeight,filterSource:this.filterSource});return t.onSizeChanged.subscribe((()=>{this.calcSize()})),[e,r,t]})())}const r=await Promise.all(s);this.logos=new Array(n.length);for(let e=0;e<n.length;++e)this.logos[e]={};for(const[e,t,n]of r)this.logos[e][t]=n,this.viewSubs.push(n.onFreqsCalculated.subscribe((()=>{this.calcSize()})));this.mainLayout=o.table(this.chains,(e=>[...n.length>0?[o.div(e,{style:{transform:"rotate(-90deg)",font:"12px Roboto, Roboto Local, sans-serif",textAlign:"center",width:"16px",marginTop:"24px",marginLeft:"6px"}})]:[],...[...Array(n.length).keys()].map((t=>{const n=this.logos[t][e];return n.root.style.height="100%",o.div([n.root],{style:{marginTop:"4px",marginBottom:"4px"}})}))]),["",...[...Array(n.length).keys()].map((e=>t.find((t=>t.order==n[e]&&t.chain==this.chains[0])).name||"Name"))]),this.mainLayout.className="mlb-vd-regions-viewer-table2",this.filterSourceInput=o.choiceInput("Data source",this.filterSource,Object.values(Ye.Ct),this.filterSourceInputOnValueChanged.bind(this)),this.filterSourceInput.root.style.position="absolute",this.filterSourceInput.root.style.right="9px",this.filterSourceInput.root.style.top="-4px",Math.ceil(255*Math.random()).toString(16),this.host=o.div([this.mainLayout,this.filterSourceInput.root],{}),this.root.appendChild(this.host),this.root.style.overflowX="auto",this.calcSize(),this.viewSubs.push(o.onSizeChanged(this.root).subscribe(this.rootOnSizeChanged.bind(this))),ls.logger.debug("Bio: VdRegionsViewer.buildView() end")}calcSize(){ls.logger.debug("Bio: VdRegionsViewer.calcSize(), start");const e=()=>{if(!this.host)return;const e=(this.root.clientHeight-54)/this.chains.length;let t=0;for(let n=0;n<this.logos.length;n++){for(const t of this.chains)this.logos[n][t].root.style.height=`${e}px`;t+=Math.max(...this.chains.map((e=>this.logos[n][e].Length)))}if(this.fitWidth){if(this.logos.length>0&&t>0){const e=22,n=13,s=9,r=(this.root.clientWidth-e-(this.logos.length-1)*s-n)/t;for(let e=0;e<this.logos.length;e++)for(const t of this.chains){const n=this.logos[e][t];n.setOptions({[Ke.bo.positionWidth]:r-n.positionMarginValue}),n.root.style.width=r*n.Length+"px"}}this.host.style.setProperty("overflow","hidden","important")}else{for(let e=0;e<this.logos.length;e++)for(const t of this.chains)this.logos[e][t].setOptions({[Ke.bo.positionWidth]:this.positionWidth});this.host.style.removeProperty("overflow")}0===this.positionWidth?this.host.style.setProperty("overflow-x","hidden","important"):this.host.style.removeProperty("overflow-x")};this.calcSizeRequested||(this.calcSizeRequested=!0,window.setTimeout((()=>{e(),this.calcSizeRequested=!1}),0))}rootOnSizeChanged(e){this.calcSize()}rootOnMouseMove(e){}filterSourceInputOnValueChanged(){const e=`${this.viewerToLog()}.filterSourceInputOnValueChanged()`,t=this.filterSourceInput.value;this.viewSyncer.sync(`${e}`,(async()=>{if(this.filterSource!==t){this.props.getProperty(Je.filterSource).set(this,t);for(let e=0;e<this.logos.length;e++)for(let t=0;t<this.chains.length;t++){const n=this.chains[t];this.logos[e][n].setOptions({[Ke.bo.filterSource]:this.filterSource})}}}))}get onRendered(){return this._onRendered}invalidate(e){const t=`${this.viewerToLog()}.invalidate(${e?` <- ${e} `:""})`;this.viewSyncer.sync(`${t}`,(async()=>{this._onRendered.next()}))}async awaitRendered(e=5e3){await(0,We.zg)(this.onRendered,(()=>{}),(()=>{this.invalidate()}),e);const t=this.viewSyncer.resetErrors();if(t.length>0)throw t[0]}}et.viewerCounter=-1;var tt=n(9017),nt=n(708);async function st(e,t,n="Morgan"){const s=e.length,r=he.g.forColumn(e),i=Array(s);let o=1;const a=new Map,l=e.categories,c=e.getRawData();for(let t=0;t<s;t++){if(null===l[c[t]]||e.isNone(t)){i[t]=null;continue}i[t]="";const n=r.getSplitted(t);for(let e=0;e<n.length;e++){const s=n.getCanonical(e);a.has(s)||(a.set(s,String.fromCharCode(o)),o++),i[t]+=a.get(s)}}let u={};if(t===nt.U.MONOMER_CHEMICAL_DISTANCE||t===nt.U.NEEDLEMANN_WUNSCH){const e=Array.from(a.keys()),t=await(0,me.GR)(e,n),s={};Object.entries(t.alphabetIndexes).forEach((([e,t])=>{s[a.get(e)]=t})),u={scoringMatrix:t.scoringMatrix,alphabetIndexes:s}}return{seqList:i,options:u}}var rt=n(6361),it=n(7983);function ot(e){const t=o.divH([],{style:{gap:"10px"}}),n=o.divV([o.divText(e.seqCol.name),o.divText(e.activityCol.name)]);return n.style.fontWeight="bold",n.style.display="flex",n.style.justifyContent="space-between",t.append(n),e.points.forEach((n=>{const s=o.divText(e.activityCol.get(n).toFixed(2));s.style.display="flex",s.style.justifyContent="left",s.style.paddingLeft="30px",t.append(o.divV([o.divText(e.seqCol.get(n)),s]))})),t}function at(e){const t=o.div();t.append(o.divText(e.seqCol.name,{style:{fontWeight:"bold"}}));const n=new Array(2);e.points.forEach(((t,s)=>{n[s]=e.activityCol.get(t)}));const s={},r=he.g.forColumn(e.seqCol),i=ct(r.getSplitted(e.points[0]),r.getSplitted(e.points[1]),r.units,s);return t.append(o.div(i,{style:{width:"300px",overflow:"scroll"}})),t.append(ut(s)),t.append(lt("Activity delta",Math.abs(n[0]-n[1]))),t.append(lt("Cliff",e.sali)),t}function lt(e,t){return o.divH([o.divText(`${e}: `,{style:{fontWeight:"bold",paddingRight:"5px"}}),o.divText(t.toFixed(2))],{style:{paddingTop:"10px"}})}function ct(e,t,n,s){const r=document.createElement("canvas"),i=r.getContext("2d");return r.height=30,Ue(i,0,0,0,30,ve()(e.canonicals).toArray(),ve()(t.canonicals).toArray(),n,!0,s),r}function ut(e){const t=o.div();if(Object.keys(e).length>0){const n=o.divV([]);n.append(o.divH([o.divText("Pos",{style:{fontWeight:"bold",width:"30px",borderBottom:"1px solid"}}),o.divText("Difference",{style:{fontWeight:"bold",borderBottom:"1px solid"}})]));for(const t of Object.keys(e))e[t].style.borderBottom="1px solid lightgray",n.append(o.divH([o.divText((parseInt(t)+1).toString(),{style:{width:"30px",borderBottom:"1px solid lightgray"}}),e[t]]));t.append(n)}return t}function ht(e,t){const n=a.Column.string("seq_diff",e.rowCount).init((n=>`${e.get(t[0],n)}#${e.get(t[1],n)}`));n.semType="MacromoleculeDifference",n.setTag(a.TAGS.UNITS,e.col(t[0]).getTag(a.TAGS.UNITS)),n.setTag("separator",e.col(t[0]).getTag("separator")),e.columns.add(n);const s=e.plot.grid();return s.col(t[0]).visible=!1,s.col(t[1]).visible=!1,s}class dt extends a.JsViewer{constructor(e){super(),this.name="",this.metricsProperties=["distanceMetric","fingerprint"],this.fingerprintChoices=["Morgan","Pattern"],this.initialized=!1,this.tags=[a.TAGS.UNITS,"aligned","separator","alphabet"],this.preComputeDistanceMatrix=!1,this.renderPromise=Promise.resolve(),this.fingerprint=this.string("fingerprint",this.fingerprintChoices[0],{choices:this.fingerprintChoices}),this.limit=this.int("limit",10),this.distanceMetric=this.string("distanceMetric",g.kg[0],{choices:g.kg}),this.moleculeColumnName=this.string("moleculeColumnName"),this.name=e}init(){this.initialized=!0}detach(){this.subs.forEach((e=>e.unsubscribe()))}async onTableAttached(){if(this.init(),this.dataFrame){this.preComputeDistanceMatrix=this.dataFrame.rowCount<=22e3,this.subs.push(a.debounce(this.dataFrame.onRowsRemoved,50).subscribe((e=>this.render(!0))));const e="diversity"!==this.name;this.subs.push(a.debounce(this.dataFrame.onCurrentRowChanged,50).subscribe((t=>this.render(e)))),this.subs.push(a.debounce(this.dataFrame.selection.onChanged,50).subscribe((e=>this.render(!1)))),this.subs.push(a.debounce(o.onSizeChanged(this.root),50).subscribe((e=>this.render(!1)))),this.moleculeColumn=this.dataFrame.columns.bySemType(a.SEMTYPE.MACROMOLECULE),this.moleculeColumnName=this.moleculeColumn?.name,this.getProperty("limit").fromOptions({min:1,max:this.dataFrame.rowCount})}this.render()}onPropertyChanged(e){if(super.onPropertyChanged(e),this.initialized){if("moleculeColumnName"===e.name){const t=this.dataFrame.col(e.get(this));t.semType===a.SEMTYPE.MACROMOLECULE&&(this.moleculeColumn=t)}this.render()}}render(e=!0){this.renderPromise=this.renderPromise.then((async()=>{this.computeRequested=this.computeRequested||e,await this.renderInt(e)}))}async renderInt(e){}beforeRender(){return!(!this.initialized||this.dataFrame&&this.moleculeColumnName&&this.dataFrame.col(this.moleculeColumnName).semType!==a.SEMTYPE.MACROMOLECULE&&(i.shell.error(`${this.moleculeColumnName} is not Macromolecule type`),1))}}var mt=n(7241),pt=n(1821);const ft={gapPenalty:1,matchScore:1,gapSymbol:he.lh[pt.r2.FASTA],localAlignment:!1};class gt extends dt{constructor(){super("similarity"),this.sketchedMolecule="",this.curIdx=0,this.molCol=null,this.idxs=null,this.scores=null,this.gridSelect=!1,this.targetMoleculeIdx=0,this.computeCompleted=new y.Subject,this.distanceMatrixComputed=!1,this.kPrevNeighbors=0,this.cutoff=this.float("cutoff",.01,{min:0,max:1}),this.hotSearch=this.bool("hotSearch",!0),this.similarColumnLabel=this.string("similarColumnLabel",null)}init(){this.hotSearch=!0,this.initialized=!0}async renderInt(e){if(this.beforeRender()&&this.moleculeColumn&&(this.curIdx=-1==this.dataFrame.currentRowIdx?0:this.dataFrame.currentRowIdx,e&&!this.gridSelect)){this.targetMoleculeIdx=-1==this.dataFrame.currentRowIdx?0:this.dataFrame.currentRowIdx;const e=he.g.forColumn(this.moleculeColumn);await(e.isHelm()?this.computeByChem():this.computeByMM());const t=null!=this.similarColumnLabel?this.similarColumnLabel:`similar (${this.moleculeColumnName})`;this.molCol=a.Column.string(t,this.idxs.length).init((e=>this.moleculeColumn?.get(this.idxs?.get(e)))),this.molCol.semType=a.SEMTYPE.MACROMOLECULE,this.tags.forEach((e=>this.molCol.setTag(e,this.moleculeColumn.getTag(e))));const n=a.DataFrame.fromColumns([this.idxs,this.molCol,this.scores]);n.onCurrentRowChanged.subscribe((e=>{this.dataFrame.currentRowIdx=n.col("indexes").get(n.currentRowIdx),setTimeout((()=>{this.createPropertyPanel(n)}),1e3),this.gridSelect=!0}));const s=n.plot.grid();s.col("indexes").visible=!1;const r=this.idxs?.getRawData().findIndex((e=>e==this.targetMoleculeIdx));s.cell("score",r).cell.value=null,i.shell.v.grid.root.addEventListener("click",(e=>{this.gridSelect=!1})),(0,ye.Y)(this.root,s.root),this.computeCompleted.next(!0)}}async computeByChem(){const e=await(0,mt.D)(this.moleculeColumn),t=(a.DataFrame.fromColumns([e]),await i.functions.call("Chem:callChemSimilaritySearch",{df:this.dataFrame,col:e,molecule:e.get(this.targetMoleculeIdx),metricName:this.distanceMetric,limit:this.limit,minScore:this.cutoff,fingerprint:this.fingerprint}));this.idxs=t.getCol("indexes"),this.scores=t.getCol("score")}async computeByMM(){const e=this.moleculeColumn.length,t=Math.min(this.limit,e-1);if(!this.knn||this.kPrevNeighbors!==t){const n=(await st(this.moleculeColumn,nt.U.LEVENSHTEIN)).seqList;this.kPrevNeighbors=t,this.knn=await(new k).getKNN(n,nt.U.LEVENSHTEIN,Math.min(this.limit,e-1))}const n=new Array(t).fill(0).map(((e,t)=>({idx:this.knn.knnIndexes[this.targetMoleculeIdx][t],score:1-this.knn.knnDistances[this.targetMoleculeIdx][t]})));n.sort(((e,t)=>t.score-e.score)),n.unshift({idx:this.targetMoleculeIdx,score:a.FLOAT_NULL}),this.idxs=a.Column.int("indexes",t+1).init((e=>n[e].idx)),this.scores=a.Column.float("score",t+1).init((e=>n[e].score))}createPropertyPanel(e){const t=o.div(),n={},s=this.molCol?.name,r=e.col(s),a=he.g.forColumn(this.moleculeColumn),l=he.g.forColumn(r),c=a.getSplitted(this.targetMoleculeIdx),u=l.getSplitted(e.currentRowIdx),h=function(e,t,n={}){const s={...ft,...n},r=e.length,i=t.length,o=Array(r+1).fill(0).map((()=>Array(i+1).fill(0)));let a=-9999,l=[1,1];for(let n=1;n<r+1;n++)for(let r=1;r<i+1;r++)o[n][r]=Math.max(0,o[n-1][r-1]+(e.getCanonical(n-1)===t.getCanonical(r-1)?s.matchScore:-s.matchScore),o[n-1][r]-s.gapPenalty,o[n][r-1]-s.gapPenalty),o[n][r]>=a&&(a=o[n][r],l=[n,r]);let c=s.localAlignment?l[0]:r,u=s.localAlignment?l[1]:i,h=new Array(0),d=new Array(0);for(;c>0&&u>0;){const n=Math.max(o[c-1][u-1],o[c-1][u],o[c][u-1]);o[c][u]==o[c-1][u-1]+s.matchScore&&n==o[c-1][u-1]?(h.push(e.getCanonical(c-1)),d.push(t.getCanonical(u-1)),c-=1,u-=1):o[c][u]==o[c-1][u]-s.gapPenalty?(d.push(s.gapSymbol),h.push(e.getCanonical(c-1)),c-=1):o[c][u]==o[c][u-1]-s.gapPenalty?(h.push(s.gapSymbol),d.push(t.getCanonical(u-1)),u-=1):(h.push(e.getCanonical(c-1)),d.push(t.getCanonical(u-1)),c-=1,u-=1)}h=[...Array.from(e.canonicals).splice(0,c),...h.reverse(),...s.localAlignment?Array.from(e.canonicals).splice(l[0],r):[]],d=[...Array.from(t.canonicals).splice(0,u),...d.reverse(),...s.localAlignment?Array.from(t.canonicals).splice(l[1],i):[]];const m=c,p=u;return m>p?d=[...new Array(m-p).fill(s.gapSymbol.valueOf()),...d]:h=[...new Array(p-m).fill(s.gapSymbol.valueOf()),...h],d.length>h.length?h.push(...new Array(d.length-h.length).fill(s.gapSymbol.valueOf())):d.push(...new Array(h.length-d.length).fill(s.gapSymbol.valueOf())),{seq1:h.join(""),seq2:d.join(""),seq1Splitted:new we.wx(h,s.gapSymbol),seq2Splitted:new we.wx(d,s.gapSymbol)}}(c,u),d=ct(h.seq1Splitted,h.seq2Splitted,l.units,n);t.append(o.div(d,{style:{width:"300px",overflow:"scroll"}})),c.length!==u.length&&t.append(o.divV([o.divText("Different sequence length:",{style:{fontWeight:"bold"}}),o.divText(`target: ${c.length} monomers`),o.divText(`selected: ${u.length} monomers`)],{style:{paddingBottom:"10px"}})),t.append(ut(n));const m=o.accordion(),p=o.element("i");p.className="grok-icon svg-icon svg-view-layout",m.addTitle(o.span([p,o.label("Similarity search")])),m.addPane("Differences",(()=>t),!0),i.shell.o=m.root}}var yt=n(279);class bt extends dt{constructor(){super("diversity"),this.renderMolIds=null,this.columnNames=[],this.computeCompleted=new y.Subject,this.diverseColumnLabel=this.string("diverseColumnLabel",null)}async renderInt(e){if(this.beforeRender()&&this.dataFrame&&e&&this.moleculeColumn){const e=he.g.forColumn(this.moleculeColumn);await(e.isFasta()?this.computeByMM():this.computeByChem());const t=null!=this.diverseColumnLabel?this.diverseColumnLabel:`diverse (${this.moleculeColumnName})`,n=a.Column.string(t,this.renderMolIds.length).init((e=>this.moleculeColumn?.get(this.renderMolIds[e])));n.semType=a.SEMTYPE.MACROMOLECULE,this.tags.forEach((e=>n.setTag(e,this.moleculeColumn.getTag(e))));const s=a.DataFrame.fromColumns([n]);s.onCurrentRowChanged.subscribe((e=>{this.dataFrame.currentRowIdx=this.renderMolIds[s.currentRowIdx]})),(0,ye.Y)(this.root,s.plot.grid().root),this.computeCompleted.next(!0)}}async computeByChem(){const e=await(0,mt.D)(this.moleculeColumn);a.DataFrame.fromColumns([e]),this.renderMolIds=await i.functions.call("Chem:callChemDiversitySearch",{col:e,metricName:this.distanceMetric,limit:this.limit,fingerprint:this.fingerprint})}async computeByMM(){const e=(await st(this.moleculeColumn,nt.U.LEVENSHTEIN)).seqList,t=new O(!0,!1),n=await t.calc(e,nt.U.LEVENSHTEIN);t.terminate();const s=this.moleculeColumn.length,r=(0,R.y)(s);this.renderMolIds=(0,yt.L)(s,Math.min(s,this.limit),((e,t)=>this.moleculeColumn.isNone(e)||this.moleculeColumn.isNone(t)?0:n[r(e,t)]))}}var vt=n(4004),wt=n(9943),Ct=n(5393),St=n(7572),At=n(3336),xt=n.n(At),Et=n(8710),It={};It.styleTagTransform=M(),It.setAttributes=E(),It.insert=A().bind(null,"head"),It.domAPI=C(),It.insertStyleElement=T(),v()(Et.Z,It),Et.Z&&Et.Z.locals&&Et.Z.locals;var Tt=n(6584),_t=n(3776),Mt=n(2428);async function $t(){await Pt.showDialog()}class Nt{constructor(e){this.eventManager=e}static async getContent(e){return Nt._instance||(Nt._instance=new Nt(e)),Nt._instance.widget||(Nt._instance.widget=await Nt._instance.createWidget()),Nt._instance.widget}async createWidget(){this.monomerLibFileManager=await _t.t.getInstance(this.eventManager);const e=await this.getWidgetContent();return this.eventManager.addLibraryFileRequested$.subscribe((async()=>await this.promptToAddLibraryFiles())),new a.Widget(e)}async getWidgetContent(){this.monomerLibFileManager=await _t.t.getInstance(this.eventManager);const e=await Lt.createControlsForm(this.eventManager);return xt()(e).addClass("monomer-lib-controls-form"),o.divV([e])}async promptToAddLibraryFiles(){a.Utils.openFile({accept:".json",open:async e=>{const t=await e.text(),n=e.name,s=a.TaskBarProgressIndicator.create(`Adding ${n} as a monomer library`);try{await this.monomerLibFileManager.addLibraryFile(t,n)}catch(e){i.shell.error(`File ${n} is not a valid monomer library, verify it is aligned to HELM JSON schema.`)}finally{s.close()}}})}}class Lt{constructor(e){this.eventManager=e,this.eventManager.updateUIControlsRequested$.subscribe((async()=>await this.updateControlsForm())),this.eventManager.librarySelectionRequested$.subscribe((async([e,t])=>await this.updateLibrarySelectionStatus(t,e)))}static async createControlsForm(e){const t=new Lt(e);return await t.initialize(),await t._createControlsForm()}async _createControlsForm(){this.monomerLibFileManager=await _t.t.getInstance(this.eventManager);const e=await this.createLibraryControls(),t=o.form(e);return xt()(t).addClass("monomer-lib-controls-form"),t}async initialize(){this.userLibSettings=await(0,Tt.nW)()}async updateControlsForm(){const e=await this._createControlsForm();xt()(".monomer-lib-controls-form").replaceWith(e)}async createLibraryControls(){return(await _t.t.getInstance(this.eventManager)).getValidLibraryPaths().map((e=>this.createLibInput(e)))}createLibInput(e){const t=!this.userLibSettings.exclude.includes(e),n=o.boolInput(e,t,(t=>this.eventManager.updateLibrarySelectionStatus(e,t)));o.tooltip.bind(n.root,`Include monomers from ${e}`);const s=o.iconFA("trash-alt",(()=>this.promptForLibraryDeletion(e)));return o.tooltip.bind(s,`Delete ${e}`),n.addOptions(s),n}async updateLibrarySelectionStatus(e,t){this.updateLibrarySettings(e,t),await(0,Tt.tW)(this.userLibSettings),await St.A.instance.loadLibraries(!0),i.shell.info("Monomer library user settings saved")}updateLibrarySettings(e,t){e?this.userLibSettings.exclude=this.userLibSettings.exclude.filter((e=>e!==t)):this.userLibSettings.exclude.includes(t)||this.userLibSettings.exclude.push(t)}promptForLibraryDeletion(e){o.dialog("Warning").add(o.divText(`Delete file ${e}?`)).onOK((async()=>{try{const t=a.TaskBarProgressIndicator.create(`Deleting ${e} library`);this.updateLibrarySelectionStatus(!1,e),await this.monomerLibFileManager.deleteLibraryFile(e),t.close()}catch(t){console.error(t),i.shell.error(`Failed to delete ${e} library`)}})).showModal(!1)}}class Pt{constructor(){this.closeDialogSubject$=new y.Subject}static async showDialog(){Pt._instance||(Pt._instance=new Pt,Pt._instance.closeDialogSubject$.subscribe((()=>{Pt._instance.dialog=void 0}))),Pt._instance.dialog||(Pt._instance.dialog=await Pt._instance.getDialog()),Pt._instance.dialog.show()}async getDialog(){const e=Mt.A.getInstance(),t=await Nt.getContent(e),n=o.dialog({title:"Manage monomer libraries",helpUrl:"/help/datagrok/solutions/domains/bio/bio.md#manage-monomer-libraries"});return xt()(n.root).css("width","350px"),n.clear(),n.addButton("Add",(()=>e.addLibraryFile()),void 0,"Upload new HELM monomer library"),n.add(t),n.onClose.subscribe((()=>this.closeDialogSubject$.next())),n}}var Rt,Ot=function(e,t,n,s){return new(n||(n=Promise))((function(r,i){function o(e){try{l(s.next(e))}catch(e){i(e)}}function a(e){try{l(s.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class kt{constructor(e,t,n=!1,s){var r;this.name="",this.description="",this._isAutomatic=!1,this._autoStartFirstStep=!1,this._currentStep=0,this._isStopped=!1,this._isCancelled=!1,this._isStepProcessed=!1,this._root=o.div([],{id:"demo-script",classes:"tutorials-root tutorials-track demo-app-script"}),this._steps=[],this._mainHeader=o.panel([],"tutorials-main-header"),this._header=o.h2(""),this._headerDiv=o.divH([],"tutorials-root-header"),this._stopStartBtn=o.button(o.iconFA("pause"),(()=>this._changeStopState()),"Play / pause"),this._restartBtn=o.button(o.iconFA("redo"),(()=>this._restartScript()),"Restart"),this._nextStepBtn=o.button(o.iconFA("play"),(()=>{this._isStepProcessed||this._nextStep()}),"Next step"),this._activity=o.panel([],"tutorials-root-description"),this._progressDiv=o.divV([],"tutorials-root-progress"),this._progress=o.element("progress"),this._progressSteps=o.divText(""),this._closeBtn=o.button(o.iconFA("chevron-left"),(()=>this._closeDock()),"Back to demo"),this.name=e,this.description=t,this._isAutomatic=n,this._autoStartFirstStep=null!==(r=null==s?void 0:s.autoStartFirstStep)&&void 0!==r&&r,this._progress.max=0,this._progress.value=1,kt.currentObject=this}get steps(){return this._steps}get stepNumber(){return this._steps.length}_addHeader(){this._createHeaderDiv(),this._createProgressDiv(),this._mainHeader.append(this._headerDiv,this._progressDiv)}_createHeaderDiv(){this._header.innerText=this.name,this._headerDiv.append(this._closeBtn),this._headerDiv.append(this._header),this._nextStepBtn.firstChild.className="grok-icon fas fa-play",this._headerDiv.append(this._isAutomatic?this._stopStartBtn:this._nextStepBtn)}_createProgressDiv(){this._progress.max=this.stepNumber,this._progressDiv.append(this._progress),this._progressSteps=o.divText(`Step: ${this._progress.value} of ${this.stepNumber}`),this._progressDiv.append(this._progressSteps)}_addDescription(){var e;this._activity.append(o.div(this.description,"tutorials-root-description"));for(let t=0;t<this.stepNumber;t++){let n=o.iconFA("clock");this._isAutomatic||0===t&&(n=o.iconFA("play",(()=>this._nextStep()),"Next step"),n.className="grok-icon fas fa-play");const s=o.div(this._steps[t].name,"grok-tutorial-entry-instruction"),r=o.div(null===(e=this._steps[t].options)||void 0===e?void 0:e.description,"grok-tutorial-step-description hidden"),i=o.divH([n,s],"grok-tutorial-entry");this._activity.append(i,r)}}_initRoot(){var e,t,n;i.shell.windows.showContextPanel=!0,i.shell.windows.showHelp=!1;const s=Array.from(i.shell.dockManager.rootNode.children)[0];this._node=i.shell.dockManager.dock(this._root,a.DOCK_TYPE.FILL,s,""),(null===(t=null===(e=s.parent.container.containerElement.firstElementChild)||void 0===e?void 0:e.lastElementChild)||void 0===t?void 0:t.classList.contains("tab-handle-list-container"))&&(null===(n=s.parent.container.containerElement.firstElementChild)||void 0===n||n.lastElementChild.remove()),this._node.container.containerElement.classList.add("tutorials-demo-script-container"),this._addHeader(),this._root.append(this._mainHeader),this._addDescription(),this._root.append(this._activity)}_nextStep(){var e,t;return Ot(this,void 0,void 0,(function*(){this._isStepProcessed=!0,this._isAutomatic||(this._nextStepBtn.classList.add("disabled"),this._nextStepBtn.firstChild.classList.add("fa-disabled"));const n=this._activity.getElementsByClassName("grok-tutorial-entry")[this._currentStep],s=this._activity.getElementsByClassName("grok-icon")[this._currentStep],r=this._activity.getElementsByClassName("grok-tutorial-step-description")[this._currentStep];s.className="grok-icon far fa-spinner-third fa-spin",r.classList.remove("hidden"),r.classList.add("visible");const i=n,a=(null===(e=this._steps[this._currentStep].options)||void 0===e?void 0:e.delay)?null===(t=this._steps[this._currentStep].options)||void 0===t?void 0:t.delay:2e3;yield this._steps[this._currentStep].func(),this._scrollTo(this._root,i.offsetTop-this._mainHeader.offsetHeight),this._isAutomatic&&(yield this._countdown(n,s,a),yield(0,We.gw)(a));const l=o.iconFA("check");if(s.replaceWith(l),l.className="grok-icon far fa-check",this._progress.value++,this._progressSteps.innerText=`Step: ${this._progress.value} of ${this.stepNumber}`,this._currentStep++,this._isStepProcessed=!1,this._currentStep!==this.stepNumber){if(!this._isAutomatic){const e=this._activity.getElementsByClassName("grok-icon")[this._currentStep],t=o.iconFA("play",(()=>this._nextStep()),"Next step");t.className="grok-icon fas fa-play",e.replaceWith(t),this._nextStepBtn.classList.remove("disabled"),this._nextStepBtn.firstChild.classList.remove("fa-disabled")}}else this._isAutomatic?this._stopStartBtn.replaceWith(this._restartBtn):this._nextStepBtn.replaceWith(this._restartBtn)}))}_startScript(){return Ot(this,void 0,void 0,(function*(){for(let e=this._currentStep;e<this.stepNumber&&!this._isStopped&&!this._isCancelled;e++)yield this._nextStep()}))}_scrollTo(e,t){e.focus(),e.scrollTop=t}_countdown(e,t,n){return Ot(this,void 0,void 0,(function*(){const s=o.div([],"demo-script-countdown");t.classList.add("hidden");let r=n/1e3;const i=this._createSVGIndicator(r);s.append(i),e.prepend(s);const a=setInterval((()=>{r--,0===r&&(clearInterval(a),s.remove(),t.classList.remove("hidden"),t.classList.add("visible"))}),1e3)}))}_createSVGIndicator(e){const t=document.createElementNS("http://www.w3.org/2000/svg","svg"),n=document.createElementNS("http://www.w3.org/2000/svg","circle");return n.setAttributeNS(null,"cx","7"),n.setAttributeNS(null,"cy","7"),n.setAttributeNS(null,"r","6"),n.setAttributeNS(null,"style",`animation: countdown ${e}s linear infinite forwards`),t.append(n),t}_changeStopState(){const e=this._stopStartBtn.getElementsByClassName("grok-icon");e[0].className="grok-icon fas fa-play",this._isStopped=!this._isStopped,this._isStopped||(e[0].className="grok-icon fal fa-pause",this._isStepProcessed||this._startScript())}_restartScript(){i.shell.dockManager.close(this._node),i.shell.closeAll(),this._clearRoot(),this._setInitParams(),this.start()}_clearRoot(){this._root=o.div([],{id:"demo-script",classes:"tutorials-root tutorials-track demo-app-script"}),this._mainHeader=o.panel([],"tutorials-main-header"),this._header=o.h2(""),this._headerDiv=o.divH([],"tutorials-root-header"),this._activity=o.panel([],"tutorials-root-description"),this._progressDiv=o.divV([],"tutorials-root-progress"),this._progress=o.element("progress"),this._progressSteps=o.divText(""),this._progress.max=0,this._progress.value=1}_setInitParams(){this._currentStep=0,this._isStopped=!1,this._isCancelled=!1,this._stopStartBtn.getElementsByClassName("grok-icon")[0].className="grok-icon fal fa-pause",this._nextStepBtn.classList.remove("disabled")}_closeDock(){i.shell.dockManager.close(this._node),this.cancelScript()}cancelScript(){this._isCancelled=!0,kt.currentObject=null}step(e,t,n){return this._steps[this.steps.length]={name:e,func:t,options:n},this}start(){return Ot(this,void 0,void 0,(function*(){this._initRoot(),i.shell.newView(this.name),this._isAutomatic?this._startScript():this._autoStartFirstStep&&(yield this._nextStep())}))}}function Ft(e){const t=e instanceof Error?e.message:e.toString(),n=e instanceof Error?e.stack:void 0;i.shell.error(t),ls.logger.error(e.message,void 0,n)}kt.currentObject=null,function(e){e.X="Embed_X",e.Y="Embed_Y"}(Rt||(Rt={}));const Gt="samples/FASTA_PT_activity.csv";async function Dt(){const e="Dendrogram",t=a.Func.find({package:e,name:"getTreeHelper"});if(0===t.length)throw new Error(`Package "${e}" must be installed for TreeHelper.`);return(await t[0].prepare().call()).getOutputParamValue()}async function Bt(){return await i.functions.call("Dendrogram:getDendrogramService",{})}var Vt=function(e,t,n,s){return new(n||(n=Promise))((function(r,i){function o(e){try{l(s.next(e))}catch(e){i(e)}}function a(e){try{l(s.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};function Ut(e,t,s){return Vt(this,void 0,void 0,(function*(){return new Promise((function(r,i){const o=new Worker(new URL(n.p+n.u(356),n.b));o.postMessage({distMatArray:e,n:t,methodCode:s}),o.onmessage=({data:{error:e,clusterMatrix:t}})=>{o.terminate(),e?i(e):r(t)}}))}))}var Ht,jt,Wt,Yt=function(e,t,n,s){return new(n||(n=Promise))((function(r,i){function o(e){try{l(s.next(e))}catch(e){i(e)}}function a(e){try{l(s.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};n(7905),function(e){e.ADD="ADD",e.SUB="SUB",e.MULT="MULT"}(Ht||(Ht={})),function(e){e.SQUARE="SQUARE",e.INVERSE="INVERSE",e.TRANSPOSE="TRANSPOSE",e.NORM="NORM",e.COLUMN_NORM="COLUMN_NORM"}(jt||(jt={})),function(e){e.SCALARMULT="SCALARMULT",e.SCALARADD="SCALARADD",e.SCALARPOW="SCALARPOW"}(Wt||(Wt={})),Object.prototype.toString;const Zt="samples/FASTA_PT_activity.csv",qt="sequence";const Kt="samples/FASTA_PT_activity.csv";var zt=n(8341);const Xt="samples/HELM.csv";var Jt=n(2568),Qt=n(525);class en{constructor(e,t,n={}){this.urlParams=e,this.funcName=t,this.options=n}async init(e){this.df=e,await this.buildView()}async buildView(){const e=ve()(this.urlParams.entries()).map((([e,t])=>`${e}=${encodeURIComponent(t)}`)).toArray().join("&");this.view=i.shell.addTableView(this.df),this.view.path=this.view.basePath=`func/${ls.name}.${this.funcName}?${e}`;const t={...this.options,sequenceColumnName:"sequence"};for(const[e,n]of this.urlParams.entries())switch(e){case Ke.bo.fixWidth:case Ke.bo.fitArea:t[e]=["1","on","true"].includes(n.toLowerCase());break;default:t[e]=n}const n=await this.view.dataFrame.plot.fromType("WebLogo",t);this.view.dockManager.dock(n,a.DOCK_TYPE.DOWN,null,"WebLogo",.35)}}class tn{get funcParams(){return{table:this.tableInput.value,sequence:this.seqColInput.value}}get paramsUI(){return this.funcParamsDiv}constructor(){this.tableInput=o.tableInput("Table",i.shell.tv.dataFrame,void 0,(()=>{this.onTableInputChanged()}));const e=this.tableInput.value.columns.bySemType(a.SEMTYPE.MACROMOLECULE),t={filter:e=>e.semType===a.SEMTYPE.MACROMOLECULE};this.seqColInput=o.columnInput("Sequence",this.tableInput.value,e,null,t),this.funcParamsDiv=o.inputs([this.tableInput,this.seqColInput],{style:{minWidth:"320px"}})}onTableInputChanged(){this.seqColInput=o.columnInput("Sequence",this.tableInput.value,this.tableInput.value.columns.bySemType(a.SEMTYPE.MACROMOLECULE))}}var nn=n(9416);class sn{constructor(e){this.monomerLib=e}getCappedRotatedMonomer(e,t){const n=this.monomerLib.getMonomer(e,t);return n?n.molfile:null}}const rn=new class{constructor(){this.tooltipHandlerTemp="tooltip-handler.Monomer"}},on={autoCrop:!0,autoCropMargin:0,suppressChiralText:!0};class an{constructor(e){this.gridCol=e,this.gridCol.grid.onCellTooltip(this.onCellTooltip.bind(this))}onCellTooltip(e,t,n){if(e.grid.dart!=this.gridCol.grid.dart||e.gridColumn.dart!=this.gridCol.dart||!e.tableColumn||!e.isTableCell)return!1;const s=e.tableColumn.getTag("alphabet"),r=e.cell.value,a="DNA"===s||"RNA"===s?"RNA":"PEPTIDE",l=new sn(cs().getBioLib()).getCappedRotatedMonomer(a,r),c=o.div(r),u=l?i.chem.svgMol(l,void 0,void 0,on):null,h=e.grid.canvas.getBoundingClientRect(),d=e.bounds.right+h.left-4,m=e.bounds.bottom+h.top-4;return o.tooltip.show(o.divV([c,...u?[u]:[]]),d,m),!0}static getOrCreate(e){let t=e.temp[rn.tooltipHandlerTemp];return t||(t=e.temp[rn.tooltipHandlerTemp]=new an(e)),t}}class ln extends a.GridCellRenderer{get name(){return Re.Of.MONOMER}get cellType(){return Re.Of.MONOMER}get defaultHeight(){return 15}get defaultWidth(){return 40}render(e,t,n,s,r,i,o){if(i.gridRow<0)return;an.getOrCreate(i.gridColumn),e.font="12px monospace",e.textBaseline="middle",e.textAlign="center";const a=(0,Me.py)(i.cell.column.getTag("alphabet")),l=i.cell.value;if(!l)return;const c=a.get(l);e.fillStyle=c,e.fillText((0,Me.GU)(l,6),t+s/2,n+r/2,s)}}class cn extends Map{get onPropertyChanged(){return this._onPropertyChanged}get MaxMonomerLength(){return super.get("MaxMonomerLength")}set MaxMonomerLength(e){super.set("MaxMonomerLength",e),this._onPropertyChanged.next("MaxMonomerLength")}get TooltipWebLogo(){return super.get("TooltipWebLogo")}set TooltipWebLogo(e){super.set("TooltipWebLogo",e),this._onPropertyChanged.next("TooltipWebLogo")}get DefaultSeparator(){return super.get("DefaultSeparator")}set DefaultSeparator(e){if(1!==e.length)throw new Error("The separator must be of length one.");super.set("DefaultSeparator",e),this._onPropertyChanged.next("DefaultSeparator")}constructor(e){super(Object.entries(e)),this._onPropertyChanged=new y.Subject}}class un extends a.Package{constructor(){super(...arguments),this._initialized=!1}get properties(){return this._properties}set properties(e){this._properties=e}get initialized(){return this._initialized}completeInit(){this._initialized=!0}handleErrorUI(e){const[t,n]=(0,ge.yf)(e);i.shell.error(t),this.logger.error(t,void 0,n)}}var hn=n(8770);class dn extends a.Widget{constructor(e){super(o.divV([])),this.viewed=!1,this.wlViewer=null,this.seqCol=e}async init(){const e=he.g.forColumn(this.seqCol),t=ls.properties.TooltipWebLogo,n=this.seqCol.getTag(Ye.DX.tooltipWebLogo);!1===t||["false","off","disable","disabled"].includes(n)||(this.wlViewer=await this.seqCol.dataFrame.plot.fromType("WebLogo",{sequenceColumnName:this.seqCol.name,backgroundColor:0,positionHeight:"Entropy",positionWidth:e.getAlphabetIsMultichar()?24:16,fixWidth:!0,fitArea:!1}),this.wlViewer.root.style.height="50px",this.root.appendChild(this.wlViewer.root),this.root.style.width="100%")}detach(){this.wlViewer&&(this.wlViewer.detach(),this.wlViewer=null),super.detach()}}const mn=OCL;class pn{constructor(e){const t=e.split("|");t.forEach((e=>this.validateConnectionItem(e))),this.connectionItems=t}validateConnectionItem(e){const t="(PEPTIDE|RNA)",n=new RegExp(`${t}[0-9]+,${t}[0-9]+,[0-9]+:R[0-9]+-[0-9]+:R[0-9]+`,"g");if(!e.match(n))throw new Error(`Cannot parse connection item from ${e}`)}getConnectionData(){const e=[];return this.connectionItems.forEach((t=>{const n=[],s=t.split(",");s[2].split("-").forEach(((e,t)=>{const r=s[t],i=e.split(":"),o={monomerIdx:parseInt(i[0])-1,rGroupId:parseInt(i[1].slice(1))};n.push({polymerId:r,bond:o})})),e.push(n)})),e}}class fn{constructor(e){this.simplePolymer=e,this.polymerType=this.getPolymerType(),this.idx=this.getIdx();const{monomers:t,monomerTypes:n}=this.getMonomerSymbolsAndTypes();this.monomers=t,this.monomerTypes=n}get id(){return this.polymerType+this.idx.toString()}getPolymerType(){const e=new RegExp("(PEPTIDE|RNA)[0-9]+{"),t=this.simplePolymer.match(e);if(!t)throw new Error(`Unsupported polymer type in ${this.simplePolymer}`);return t[1]}getIdx(){const e=new RegExp(`${this.polymerType}([0-9]+){`),t=this.simplePolymer.match(e);if(!t)throw new Error(`Cannot parse simple polymer id from ${this.simplePolymer}`);return parseInt(t[1])}getMonomerSymbolsAndTypes(){const e=new RegExp(`${this.polymerType}${this.idx}{|}`,"g"),t=this.simplePolymer.replace(e,"").split("."),n=[],s=[];return t.forEach((e=>{const t=e.split(/\(|\)/).map((e=>e.replace(/[\[\]]/g,"")));n.push(...t);const r=t.map(((e,t)=>t%2==0?"Backbone":"Branch"));s.push(...r)})),{monomers:n,monomerTypes:s}}getBondData(){const e=[],t=this.monomerTypes.map(((e,t)=>{if("Backbone"===e)return t})).filter((e=>void 0!==e)),n=this.monomerTypes.map(((e,t)=>{if("Branch"===e)return t})).filter((e=>void 0!==e));for(let n=0;n<t.length-1;n++){const s=t[n],r=t[n+1];e.push([{monomerIdx:s,rGroupId:2},{monomerIdx:r,rGroupId:1}])}for(let t=0;t<n.length;t++){const s=n[t],r=s-1;e.push([{monomerIdx:r,rGroupId:3},{monomerIdx:s,rGroupId:1}])}return e}}class gn{constructor(e){this.helmString=e;const t=this.helmString.split("$"),n=t[0].split("|");this.simplePolymers=n.map((e=>new fn(e))),""!==t[1]&&(this.connectionList=new pn(t[1])),this.bondData=this.getBondData(),this.bondedRGroupsMap=this.getBondedRGroupsMap()}getBondedRGroupsMap(){const e=new Map;return this.bondData.forEach((t=>{t.forEach((t=>{const n=t.monomerIdx,s=t.rGroupId;e.get(n)||e.set(n,[]),e.get(n).push(s)}))})),e}toString(){return this.helmString}getPolymerTypeByMonomerIdx(e){return this.getSimplePolymerByMonomerIdx(e).polymerType}getSimplePolymerByMonomerIdx(e){const t=this.getMonomerIdxShifts(),n=Object.values(t).sort(((e,t)=>e-t)).find((t=>e>=t));if(void 0===n)throw new Error(`Cannot find simple polymer for monomer ${e}`);const s=Object.keys(t).find((e=>t[e]===n));return this.simplePolymers.find((e=>e.id===s))}shiftBondMonomerIds(e,t){t.forEach((t=>{t.forEach((t=>{t.monomerIdx+=e}))}))}getMonomerIdxShifts(){const e={};let t=0;return this.simplePolymers.forEach((n=>{e[n.id]=t,t+=n.monomers.length})),e}getBondData(){const e=this.getMonomerIdxShifts(),t=[];return this.simplePolymers.forEach((n=>{const s=n.getBondData(),r=e[n.id];this.shiftBondMonomerIds(r,s),t.push(...s)})),this.connectionList&&this.connectionList.getConnectionData().forEach((n=>{const s=[];n.forEach((t=>{const n=e[t.polymerId],r=t.bond;r.monomerIdx+=n,s.push(r)})),t.push(s)})),t}}var yn=n(4067);class bn{constructor(e){this.monomerSymbol=e}shiftR1GroupToOrigin(){const e=this.rGroups.getAtomicIdx(1);if(null===e)throw new Error(`Cannot find R1 group for monomer ${this.monomerSymbol}`);const{x:t,y:n}=this.atoms.atomCoordinates[e];this.atoms.shift({x:-t,y:-n})}alignR2AlongX(){const e=this.rGroups.getAtomicIdx(2);if(null===e)throw new Error(`Cannot find R2 group for monomer ${this.monomerSymbol}`);const t=this.atoms.atomCoordinates[e],n=t.y/t.x,s=Math.atan(n);if(isNaN(s))throw new Error(`Cannot calculate angle for R2 group for monomer ${this.monomerSymbol}`);this.rotateCoordinates(-s)}shiftMonomerToDefaultPosition(){this.shiftR1GroupToOrigin(),null!==this.rGroups.getAtomicIdx(2)&&this.alignR2AlongX()}deleteBondLineWithSpecifiedRGroup(e){this.rGroups.deleteBondLineWithSpecifiedRGroup(e)}shiftCoordinates(e){this.atoms.shift(e)}rotateCoordinates(e){this.atoms.rotate(e)}getBondLines(){return this.bonds.getBondLines()}getAtomLines(){return this.atoms.atomLines}removeRGroups(e){this.rGroups.removeRGroups(e)}replaceRGroupWithAttachmentAtom(e,t){this.rGroups.replaceRGroupWithAttachmentAtom(e,t)}getAttachmentAtomByRGroupId(e){return this.rGroups.getAttachmentAtomIdByRGroupId(e)}shiftBonds(e){this.bonds.shift(e)}capRGroups(e){this.rGroups.capRGroups(e)}}class vn{constructor(e,t,n){this.atoms=t,this.bonds=n,this.rGroupBondPositionMap=new Map,this.rGroupIdToAtomicIndexMap=e.getRGroupIdToAtomicIdxMap()}getAtomicIdx(e){const t=this.rGroupIdToAtomicIndexMap.get(e);return void 0===t?null:t}removeRGroupsFromAtomBlock(e){e.forEach((e=>{if(void 0===this.rGroupIdToAtomicIndexMap.get(e))throw new Error(`Cannot find atomic index for R group ${e}`)}));const t=Array.from(this.rGroupIdToAtomicIndexMap.entries()).filter((([t,n])=>e.includes(t))).map((([e,t])=>t));this.atoms.deleteAtoms(t)}removeRGroups(e){this.removeRGroupsFromAtomBlock(e),e.forEach((e=>{const t=this.replaceRGroupInBondsByDummy(e);this.rGroupBondPositionMap.set(e,t)}))}replaceRGroupInBondsByDummy(e){const t=this.rGroupIdToAtomicIndexMap.get(e);if(this.rGroupBondPositionMap.has(e))throw new Error(`R group ${e} is already handled`);const n=this.bonds.getPositionsInBonds(t+1);if(0===n.length)throw new Error(`Cannot find position for R group ${e}`);if(n.length>1)throw new Error(`More than one position for R group ${e}`);const s=n[0];return this.bonds.replacePositionsInBondsByDummy([s]),this.bonds.removeAtomIdFromBonds(t+1),this.removeRGroupFromAtomicIdxMap(e,t),s}removeRGroupFromAtomicIdxMap(e,t){this.rGroupIdToAtomicIndexMap.delete(e);for(const[e,n]of this.rGroupIdToAtomicIndexMap)n>t&&this.rGroupIdToAtomicIndexMap.set(e,n-1)}deleteBondLineWithSpecifiedRGroup(e){const t=this.rGroupBondPositionMap.get(e);if(!t)throw new Error(`Cannot find position for R group ${e}`);const{bondLineIdx:n}=t;this.bonds.deleteBondLines([n]),this.rGroupBondPositionMap.delete(e),this.rGroupIdToAtomicIndexMap.delete(e),this.rGroupBondPositionMap.forEach((e=>{e.bondLineIdx>n&&(e.bondLineIdx-=1)}))}replaceRGroupWithAttachmentAtom(e,t){const n=this.rGroupBondPositionMap.get(e);if(!n)throw new Error(`Cannot find position for R group ${e}`);const{bondLineIdx:s,nodeIdx:r}=n;this.bonds.bondedAtoms[s][r]=t}getAttachmentAtomIdByRGroupId(e){const t=this.rGroupBondPositionMap.get(e);if(!t)throw new Error(`Cannot find position for R group ${e}`);const{bondLineIdx:n,nodeIdx:s}=t;return this.bonds.bondedAtoms[n][(s+1)%2]}capRGroups(e){this.rGroupIdToAtomicIndexMap.forEach(((t,n)=>{const s=e[n-1];"H"===s?(this.removeRGroups([n]),this.deleteBondLineWithSpecifiedRGroup(n)):this.atoms.replaceRGroupSymbolByElement(t,s)}))}}var wn=n(1793);class Cn{constructor(){this.coordinates=[],this.rawAtomLines=[]}get atomCoordinates(){return this.coordinates}replaceRGroupSymbolByElement(e,t){this.rawAtomLines[e]=this.rawAtomLines[e].replace(wn.Ox,t)}deleteAtoms(e){this.coordinates=this.coordinates.filter(((t,n)=>!e.includes(n))),this.rawAtomLines=this.rawAtomLines.filter(((t,n)=>!e.includes(n)))}shift(e){this.coordinates=this.coordinates.map((t=>{const n=t.x+e.x,s=t.y+e.y;if(isNaN(n)||isNaN(s))throw new Error(`Cannot shift coordinates by ${e.x}, ${e.y}`);return{x:n,y:s}}))}rotate(e){this.coordinates=this.coordinates.map((t=>{const n=t.x,s=t.y,r=n*Math.cos(e)-s*Math.sin(e),i=n*Math.sin(e)+s*Math.cos(e);if(isNaN(r)||isNaN(i))throw new Error(`Cannot rotate coordinates by ${e}`);return{x:r,y:i}}))}}class Sn extends Cn{constructor(e){super(),this.rawAtomLines=e.getAtomLines(),this.coordinates=this.rawAtomLines.map((e=>({x:parseFloat(e.substring(0,10)),y:parseFloat(e.substring(10,20))})))}get atomLines(){return this.rawAtomLines.map(((e,t)=>{const n=this.coordinates[t];return`${n.x.toFixed(4).padStart(10," ")}${n.y.toFixed(4).padStart(10," ")}${e.substring(20)}`}))}}class An{constructor(){this.bondedAtomPairs=[],this.rawBondLines=[]}get bondedAtoms(){return this.bondedAtomPairs}deleteBondLines(e){this.rawBondLines=this.rawBondLines.filter(((t,n)=>!e.includes(n))),this.bondedAtomPairs=this.bondedAtomPairs.filter(((t,n)=>!e.includes(n)))}getPositionsInBonds(e){const t=[];return this.bondedAtomPairs.forEach(((n,s)=>{n.forEach(((n,r)=>{n===e&&t.push({bondLineIdx:s,nodeIdx:r})}))})),t}replacePositionsInBondsByDummy(e,t){void 0===t&&(t=-1),e.forEach((e=>{const{bondLineIdx:n,nodeIdx:s}=e;this.bondedAtomPairs[n][s]=t}))}removeAtomIdFromBonds(e){this.bondedAtomPairs=this.bondedAtomPairs.map((t=>t.map((t=>t>e?t-1:t))))}shift(e){this.bondedAtomPairs=this.bondedAtomPairs.map((t=>t.map((t=>t+e))))}}class xn extends An{constructor(e){super(),this.rawBondLines=e.getBondLines(),this.bondedAtomPairs=this.rawBondLines.map((e=>[parseInt(e.substring(0,3)),parseInt(e.substring(3,6))]))}getBondLines(){return this.bondedAtomPairs.map(((e,t)=>{if(e.some((e=>-1===e)))throw new Error(`Bonded pair ${e} contains -1`);return`${e[0].toString().padStart(3," ")}${e[1].toString().padStart(3," ")}${this.rawBondLines[t].substring(6)}`}))}}class En extends bn{constructor(e,t){super(t);const n=yn._.getInstance(e);this.atoms=new Sn(n),this.bonds=new xn(n),this.rGroups=new vn(n,this.atoms,this.bonds),this.shiftMonomerToDefaultPosition()}}class In extends Cn{constructor(e){super(),this.molfileHandler=e,this.rawAtomLines=e.getAtomLines(),this.coordinates=this.getCoordinates()}getCoordinates(){const e=this.molfileHandler.x,t=this.molfileHandler.y;return Array.from(e).map(((e,n)=>({x:e,y:t[n]})))}get atomLines(){const e=/^(M V30 .*)(-?\d+\.\d+)( )(-?\d+\.\d+)( -?\d+\.\d+.*)$/,t=/\sRGROUPS=\(\d+(\s+\d+)*\)/;return this.rawAtomLines.map(((n,s)=>{const r=this.coordinates[s],i=r.x.toFixed(6),o=r.y.toFixed(6);return n.replace(e,((e,t,n,s,r,a)=>t+i+s+o+a)).replace(t,"")}))}}class Tn extends An{constructor(e){super(),this.molfileHandler=e,this.rawBondLines=e.getBondLines(),this.bondedAtomPairs=this.getBondedAtomPairs()}getBondedAtomPairs(){return this.molfileHandler.pairsOfBondedAtoms.map((e=>[e[0],e[1]]))}getBondLines(){const e=/^(M\s+V30\s+\d+\s+\d+\s+)(\d+)(\s+)(\d+)(.*)$/;return this.bondedAtomPairs.map(((t,n)=>{if(t.some((e=>-1===e)))throw new Error(`Bonded pair ${t} contains -1`);return this.rawBondLines[n].replace(e,((e,n,s,r,i,o)=>`${n}${t[0]}${r}${t[1]}${o}`))}))}}class _n extends bn{constructor(e,t){super(t);const n=yn._.getInstance(e);this.atoms=new In(n),this.bonds=new Tn(n),this.rGroups=new vn(n,this.atoms,this.bonds),this.shiftMonomerToDefaultPosition()}}class Mn{static getInstance(e,t){if(yn._.isMolfileV2K(e))return new En(e,t);if(yn._.isMolfileV3K(e))return new _n(e,t);throw new Error("Unsupported molfile version")}}class $n{constructor(e,t,n,s,r){this.monomerSymbol=e,this.monomerIdx=t,this.helm=n,this.capGroupElements=[];const i=this.getLibraryMonomerObject();let o=i.molfile;yn._.isMolfileV2K(o)&&(o=this.convertMolfileToV3KFormat(o,r)),this.molfileWrapper=Mn.getInstance(o,e),this.capGroupElements=this.getCapGroupElements(i),n.bondedRGroupsMap.has(t)&&this.removeRGroups(n.bondedRGroupsMap.get(t)),this.capRemainingRGroups(),this.shiftCoordinates(s)}convertMolfileToV3KFormat(e,t){return t.get_mol(e,JSON.stringify({mergeQueryHs:!0})).get_v3Kmolblock()}getLibraryMonomerObject(){const e=this.helm.getPolymerTypeByMonomerIdx(this.monomerIdx),t=St.A.instance.getBioLib().getMonomer(e,this.monomerSymbol);if(!t)throw new Error(`Monomer ${this.monomerSymbol} is not found in the library`);return t}getCapGroupElements(e){return e.rgroups.map((e=>(e.capGroupSMILES||e.capGroupSMILES).replace(/(\[|\]|\*|:|\d)/g,"")))}shiftCoordinates(e){this.molfileWrapper.shiftCoordinates(e)}getAtomLines(){return this.molfileWrapper.getAtomLines()}getBondLines(){return this.molfileWrapper.getBondLines()}removeRGroups(e){this.molfileWrapper.removeRGroups(e)}capRemainingRGroups(){this.molfileWrapper.capRGroups(this.capGroupElements)}replaceRGroupWithAttachmentAtom(e,t){this.molfileWrapper.replaceRGroupWithAttachmentAtom(e,t)}getAttachmentAtomByRGroupId(e){return this.molfileWrapper.getAttachmentAtomByRGroupId(e)}deleteBondLineWithSpecifiedRGroup(e){this.molfileWrapper.deleteBondLineWithSpecifiedRGroup(e)}shiftBonds(e){this.molfileWrapper.shiftBonds(e)}}class Nn{constructor(e,t){this.rdKitModule=t,this.monomerWrappers=[],this.helm=new gn(e)}addMonomer(e,t,n){const s=new $n(e,t,this.helm,n,this.rdKitModule);this.monomerWrappers.push(s)}getAtomNumberShifts(){const e=[];let t=0;return this.monomerWrappers.forEach((n=>{e.push(t),t+=n.getAtomLines().length})),e}restoreBondsBetweenMonomers(){this.helm.bondData.forEach((e=>{const t=e.map((e=>e.monomerIdx)),n=e.map((e=>e.rGroupId)),s=t.map((e=>this.monomerWrappers[e])),r=s[1].getAttachmentAtomByRGroupId(n[1]);s[0].replaceRGroupWithAttachmentAtom(n[0],r),s[1].deleteBondLineWithSpecifiedRGroup(n[1])}))}compileToMolfile(){const e=[],t=[],n=this.getAtomNumberShifts();this.monomerWrappers.forEach(((e,t)=>{e.shiftBonds(n[t])})),this.restoreBondsBetweenMonomers(),this.monomerWrappers.forEach((n=>{e.push(...n.getAtomLines()),t.push(...n.getBondLines())}));const s=e.length,r=t.length;return[this.getV3KHeader(s,r),this.getV3KAtomBlock(e),this.getV3KBondBlock(t),"M V30 END CTAB\nM END"].join("\n")}getV3KHeader(e,t){return`\n Datagrok\n\n 0 0 0 0 0 0 0 0 0 0999 V3000\nM V30 BEGIN CTAB\nM V30 COUNTS ${e} ${t} 0 0 0`}getV3KAtomBlock(e){const t=/^(M V30 )(\d+)( .*)$/;return["M V30 BEGIN ATOM",...e.map(((e,n)=>{const s=n+1;return e.replace(t,((e,t,n,r)=>t+s+r))})),"M V30 END ATOM"].join("\n")}getV3KBondBlock(e){const t=/^(M V30 )(\d+)( .*)$/;return["M V30 BEGIN BOND",...e.map(((e,n)=>{const s=n+1;return e.replace(t,((e,t,n,r)=>t+s+r))})),"M V30 END BOND"].join("\n")}}class Ln{constructor(e){this.molfileHandler=yn._.getInstance(e)}get monomerSymbols(){return this.molfileHandler.atomTypes}getMonomerShifts(e){return{x:this.molfileHandler.x[e],y:this.molfileHandler.y[e]}}}class Pn{constructor(e,t){this.helmColumn=e,this.df=t,this.helmColumn=e}async convertToSmiles(){const e=await this.getSmilesList(),t=this.df.columns.getUnusedName(`smiles(${this.helmColumn.name})`);return a.Column.fromStrings(t,e.map((e=>null===e?"":e)))}async getSmilesList(){return(await this.convertToMolfileV2KColumn()).toList().map((e=>a.chem.convert(e,a.chem.Notation.MolBlock,a.chem.Notation.Smiles)))}async getMolV3000ViaOCL(e,t){const n=e.map((e=>{if(null===e)return"";const t=e.get_molblock();return e.delete(),t})),s=new Array(n.length),r=a.TaskBarProgressIndicator.create("Handling chirality...");for(let e=0;e<n.length;e++){const t=mn.Molecule.fromMolfile(n[e]).toMolfileV3();s[e]=t.replace("STERAC1","STEABS");const i=e/n.length*100;r.update(i,`${i?.toFixed(2)}% of molecules completed`)}return r.close(),a.Column.fromStrings(t,s)}async convertToRdKitBeautifiedMolfileColumn(e){const t=await this.getSmilesList(),n=await i.functions.call("Chem:getRdKitModule"),s=t.map((e=>{if(""===e)return null;const t=n.get_mol(e);return t?(t.normalize_depiction(1),t.straighten_depiction(!0),t):null})),r=this.df.columns.getUnusedName(`molfile(${this.helmColumn.name})`);return e?await this.getMolV3000ViaOCL(s,r):a.Column.fromStrings(r,s.map((e=>{if(null===e)return"";const t=e.get_v3Kmolblock();return e.delete(),t})))}async convertToMolfileV2KColumn(){const e=await this.getPolymerGraphColumn(),t=await i.functions.call("Chem:getRdKitModule"),n=e.toList().map(((e,n)=>{const s=this.helmColumn.get(n);if(!s)return"";let r="";try{r=this.getPolymerMolfile(s,e,t)}catch(e){const[t,n]=(0,ge.yf)(e);ls.logger.error(t,void 0,n)}finally{return r}})),s=this.df.columns.getUnusedName(`molfileV2K(${this.helmColumn.name})`);return a.Column.fromList("string",s,n)}async getPolymerGraphColumn(){return await i.functions.call("HELM:getMolfiles",{col:this.helmColumn})}getPolymerMolfile(e,t,n){const s=new Ln(t),r=new Nn(e,n);return s.monomerSymbols.forEach(((e,t)=>{const n=s.getMonomerShifts(t);r.addMonomer(e,t,n)})),r.compileToMolfile()}}async function Rn(e,t,n){const s=new Pn(t,e),r=await s.convertToRdKitBeautifiedMolfileColumn(n);return r.semType=a.SEMTYPE.MOLECULE,r}const On="System:AppData/Bio/polytool-rules/",kn="Polytool";class Fn{constructor(e){this.helmColumn=e}getLinkedPositions(e,t){const n=e.map((e=>e.replace("[","").replace("]",""))),s=new Array(t.length);for(let e=0;e<t.length;e++){let r=!1,i=!1,o=!1,a=-1,l=-1;const c=`(${t[e].code})`;for(let s=0;s<n.length;s++)if(n[s].includes(c)){if(r){if(o&&n[s]==t[e].secondMonomer+c){i=!0,l=s;break}if(o||n[s]!=t[e].firstMonomer+c)continue;i=!0,l=s;break}if(n[s]==t[e].firstMonomer+c)r=!0,o=!0,a=s;else{if(n[s]!=t[e].secondMonomer+c)continue;r=!0,o=!1,a=s}}s[e]=r&&i?o?[a,l]:[l,a]:[-1,-1]}return s}getRules(e){const t=e.map((e=>e.rowCount)).reduce(((e,t)=>e+t)),n=new Array(t);let s=0;for(let t=0;t<e.length;t++){const r=e[t].columns.byName("code"),i=e[t].columns.byName("monomer1"),o=e[t].columns.byName("monomer2"),a=e[t].columns.byName("modification1"),l=e[t].columns.byName("modification2"),c=e[t].columns.byName("R1"),u=e[t].columns.byName("R2");for(let h=0;h<e[t].rowCount;h++,s++)n[s]={code:r.get(h),firstMonomer:i.get(h),secondMonomer:o.get(h),firstModification:a.get(h),secondModification:l.get(h),firstR:c.get(h),secondR:u.get(h)}}return n}getDimeric(e){const t=e.replace("PEPTIDE1{","").replace("}$$$$","").split("."),n=[];for(let e=0;e<t.length;e++)if(t[e].includes("(#2)")){t[e]=t[e].replace("(#2)","");const s=e+1;let r=0;for(let e=s+1;e<t.length;e++)if(t[e].includes("}")){r=e;break}t[s]=t[s].replace("{",""),t[r]=t[r].replace("}",""),n.push([s,r])}return[t,n]}getAllCycles(e,t,n){const s=[],r=[],i=[],o=[],a=e.length;for(let l=0;l<a;l++){if(-1==n[l][0])continue;const a=t[n[l][0]].replace("[","").replace("]",""),c=t[n[l][1]].replace("[","").replace("]","");t[n[l][0]]=t[n[l][0]].replace(a,e[l].firstModification),t[n[l][1]]=t[n[l][1]].replace(c,e[l].secondModification),s.push(n[l][0]+1),r.push(n[l][1]+1),i.push(e[l].firstR),o.push(e[l].secondR)}return[t,s,r,i,o]}getHelmCycle(e,t,n){let s="";for(let r=0;r<e.allPos1.length;r++)s+=0==r?`PEPTIDE${t},PEPTIDE${n},`:`|PEPTIDE${t},PEPTIDE${n},`,s+=`${e.allPos1[r]}:R${e.allAttaches1[r]}-${e.allPos2[r]}:R${e.allAttaches2[r]}`;return s}getTransformedHelm(e,t){const[n,s]=this.getDimeric(e),r=this.getLinkedPositions(n,t),[i,o,a,l,c]=this.getAllCycles(t,n,r);e="PEPTIDE1{";for(let t=0;t<i.length;t++)e+=t!=i.length-1?i[t]+".":i[t];e+="}";const u=new Array(s.length),h=new Array(s.length);for(let e=0;e<s.length;e++){let t=`|PEPTIDE${e+2}{`;const n=s[e][1]-s[e][0],r=[],c=[],d=[],m=[];for(let r=0;r<=n;r++){const o=r+s[e][0];t+=r!=n?i[o]+".":i[o]}t+="}";for(let t=0;t<o.length;t++)o[t]-1>=s[e][0]&&o[t]-1<=s[e][1]&&(r.push(o[t]-s[e][0]),c.push(a[t]-s[e][0]),d.push(l[t]),m.push(l[t]));const p=this.getHelmCycle({allPos1:r,allPos2:c,allAttaches1:d,allAttaches2:m},e+2,e+2);u[e]=t,h[e]=this.getHelmCycle({allPos1:[s[e][0]],allPos2:[1],allAttaches1:[1],allAttaches2:[1]},1,e+2),h.push(p)}for(let t=0;t<u.length;t++)e+=u[t];e+="$",e+=this.getHelmCycle({allPos1:o,allPos2:a,allAttaches1:l,allAttaches2:c},1,1);for(let t=0;t<h.length;t++)e+="|",e+=h[t];return e+"$$$"}transform(e){const t=this.getRules(e);return this.helmColumn.toList().map((e=>this.getTransformedHelm(e,t)))}}class Gn{constructor(){}static getInstance(e){return new Fn(e)}}async function Dn(e,t,n,s){const r=e.dataFrame,o=he.g.forColumn(e).convert(Me.r2.HELM),l=Gn.getInstance(o),c=new a.FileSource(On),u=new Array(n.length);for(let e=0;e<n.length;e++){const t=await c.readAsText(n[e].replace(On,""));u[e]=a.DataFrame.fromCsv(t)}const h=l.transform(u),d=r.columns.getUnusedName("transformed("+e.name+")"),m=a.Column.fromList("string",d,h);var p;(p=m).setTag("quality",a.SEMTYPE.MACROMOLECULE),p.setTag("aligned","SEQ"),p.setTag("alphabet","PT"),m.setTag("units",Me.r2.HELM);const f=await Rn(r,m,s);f.name=r.columns.getUnusedName("molfile("+e.name+")"),f.semType=a.SEMTYPE.MOLECULE,t&&(m.setTag("cell.renderer","helm"),r.columns.add(m)),r.columns.add(f,!0),await i.data.detectSemanticTypes(r)}var Bn=function(e,t,n,s){return new(n||(n=Promise))((function(r,i){function o(e){try{l(s.next(e))}catch(e){i(e)}}function a(e){try{l(s.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class Vn{constructor(e,t,n=".csv"){this.path=e,this.userStorageName=t,this.ext=n,"/"!==this.path[this.path.length-1]&&(this.path+="/"),"."!==this.ext[0]&&(this.ext="."+this.ext)}getUserSettings(){return Bn(this,void 0,void 0,(function*(){if(this.settings)return this.settings;const e=yield i.dapi.userDataStorage.getValue(this.userStorageName,"Settings",!0),t=e?JSON.parse(e):{excluded:[],explicit:[]};return t.explicit=t.explicit instanceof Array?t.explicit:[],t.excluded=t.excluded instanceof Array?t.excluded:[],this.settings=t}))}setUserSettings(e){return Bn(this,void 0,void 0,(function*(){this.settings=e,yield i.dapi.userDataStorage.postValue(this.userStorageName,"Settings",JSON.stringify(e),!0)}))}getAllAvailable(){return Bn(this,void 0,void 0,(function*(){return(yield i.dapi.files.list(this.path)).map((e=>e.fullPath.replace(`${this.path}`,"")))}))}getActive(){return Bn(this,void 0,void 0,(function*(){const e=yield this.getUserSettings();return e.explicit.length>0?e.explicit:(yield this.getAllAvailable()).filter((t=>!e.excluded.includes(t)))}))}createInput(e,t){const n=o.boolInput(e,t,(t=>this.updateSelectionStatus(e,t)));return n.addOptions(o.button(o.iconFA("trash"),(()=>{o.dialog({title:"Warning"}).add(o.divText(`Delete file '${e}'?`)).onOK((()=>{n.root.remove(),this.availableRemove(e)})).show()}),`Delete ${e}`)),n}getInputs(){return Bn(this,void 0,void 0,(function*(){const e=yield this.getAllAvailable(),t=yield this.getActive(),n=new Array(e.length);for(let s=0;s<e.length;s++){const r=t.includes(e[s]);n[s]=this.createInput(e[s],r)}return n}))}getForm(){return Bn(this,void 0,void 0,(function*(){const e=yield this.getInputs(),t=o.divV(e);return o.divV([t,o.button("ADD",(()=>Bn(this,void 0,void 0,(function*(){let e="";e=yield this.getNewAvailable(),""!==e&&t.append(this.createInput(e,!0).root)}))))])}))}updateSelectionStatus(e,t){return Bn(this,void 0,void 0,(function*(){const n=yield this.getUserSettings();if(!n.excluded.includes(e)!==t){if(t){const t=n.excluded.indexOf(e);t>-1&&n.excluded.splice(t,1)}else n.excluded.push(e);this.setUserSettings(n)}}))}availableRemove(e){return Bn(this,void 0,void 0,(function*(){const t=yield this.getUserSettings(),n=t.excluded.indexOf(e);n>-1&&t.excluded.splice(n,1),yield Promise.all([this.setUserSettings(t),i.dapi.files.delete(this.path+e)]),i.shell.info(`File ${e} successfully deleted`)}))}getNewAvailable(){return Bn(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{a.Utils.openFile({accept:this.ext,open:t=>Bn(this,void 0,void 0,(function*(){const n=t.name,s=yield t.arrayBuffer();yield i.dapi.files.write(this.path+`${t.name}`,new Uint8Array(s)),e(n)}))})}))}))}}class Un extends Vn{constructor(e,t,n){super(e,t,n)}}var Hn=n(1047);const jn={symbol:"Short Name",name:"Medium Name",smiles:"SMILES"},Wn=[{capGroupSMILES:"[*:1][H]",alternateId:"R1-H",capGroupName:"H",label:"R1"},{capGroupSMILES:"O[*:2]",alternateId:"R2-OH",capGroupName:"OH",label:"R2"},{capGroupSMILES:"[*:3][H]",alternateId:"R3-H",capGroupName:"H",label:"R3"}];class Yn{constructor(e){this.rawLib=e}isValid(){return this.rawLib.every((e=>"object"==typeof e&&Object.values(jn).every((t=>t in e&&"string"==typeof e[t]))))}getJsonMonomerLib(){const e=[];return this.rawLib.forEach((t=>{const n=this.prepareMonomer(t);e.push(n)})),e}prepareMonomer(e){const t={...Hn.Z2};Object.entries(jn).forEach((([n,s])=>{const r=e[s];t[n]=r}));let n="smiles";const s=e[jn[n]],r=new Zn(s),i=r.getCappedSmiles();return t[n]=i,n="rgroups",t[n]=qn.getRGroups(r.getNumberOfRGroups()),n="molfile",t[n]=new Kn(r.getSmilesWithRGroups()).getMolfile(),t}}class Zn{constructor(e){let t=0;this.smilesWithRGroups=e.replace(/\[R(\d+)\]/g,((e,n)=>(++t,`[${n}*]`))),this.numberOfRGroups=t}getSmilesWithRGroups(){return this.smilesWithRGroups}getCappedSmiles(){return this.capRGroups()}getNumberOfRGroups(){return this.numberOfRGroups}capRGroups(){let e=this.smilesWithRGroups.replace("[1*]","[H:1]");return e=e.replace("[2*]","[OH:2]"),e.replace("[3*]","[H:3]")}}class qn{constructor(){}static getRGroups(e){return Wn.slice(0,e)}}class Kn{constructor(e){this.smilesWithRGroups=e}getMolfile(){let e=a.chem.convert(this.smilesWithRGroups,a.chem.Notation.Smiles,a.chem.Notation.MolBlock);return e=this.restoreRGPLine(e),e=this.fixRGroupSymbols(e),e}restoreRGPLine(e){return e.replace("M ISO","M RGP")}fixRGroupSymbols(e){return e.replace(/\bR\b/g,"R#")}}class zn{constructor(e,t){this.fileName=e,this.fileContent=t,this.validateFileType();const n=a.DataFrame.fromCsv(this.fileContent),s=this.toJson(n);this.polyToolMonomerLib=new Yn(s),this.validateContent()}async getJson(){return this.polyToolMonomerLib.getJsonMonomerLib()}toJson(e){return Array.from({length:e.rowCount},((t,n)=>e.columns.names().reduce(((t,s)=>(t[s]=e.get(s,n),t)),{})))}validateFileType(){if(!this.fileName.endsWith(".csv"))throw new Error(`File ${this.fileName} is not an CSV file`)}validateContent(){if(!this.polyToolMonomerLib.isValid())throw new Error("Invalid format of CSV monomer lib")}}function Xn(e,t,n,s){const r=he.g.forColumn(e);let i=null,o=null;for(let e=0;e<r.posList.length;++e)r.posList[e]==t&&(i=e),r.posList[e]==n&&(o=e);if(null===i&&null!==t)throw new Error(`Start position ${t} not found.`);if(null===o&&null!==n)throw new Error(`End position ${n} not found.`);if(r.posList.length<o)throw new Error(`End position ${o} exceeds positions length`);const a=s||`${e.name}: (${t??""}-${n??""})`;return r.getRegion(i,o,a)}const Jn={df:a.DataFrame.fromCsv("seq,value\nATCCGTCGT,0.5\nTGTTCGTCA,0.4\nATGGTCGTA,0.7\nATCCGTGCA,0.1"),colName:"seq",positionNames:["1","1A","1C","2","4","4A","4B","5","6"].join(Me.CI),regions:[{name:"first region",start:"1",end:"2"},{name:"second region",start:"1C",end:"4"},{name:"overlapping second",start:"1C",end:"4A"},{name:"whole sequence",start:"1",end:"6"},{name:"bad start",start:"0",end:"6"},{name:"bad end",start:"1",end:"4C"},{name:"bad start & end",start:"0",end:"4C"}]};class Qn{constructor(e,t){this.urlParams=e,this.funcName=t}async init(e){this.data=e??Jn;const t=this.data.df.getCol(this.data.colName);this.data.positionNames&&t.setTag(".positionNames",this.data.positionNames),this.data.regions&&t.setTag(".regions",JSON.stringify(this.data.regions)),await this.buildView()}async buildView(){await i.data.detectSemanticTypes(this.data.df),this.view=i.shell.addTableView(this.data.df),this.view.path=this.view.basePath=`func/${ls.name}.${this.funcName}`;const e=await this.view.dataFrame.plot.fromType("WebLogo",{sequenceColumnName:this.data.colName});this.view.dockManager.dock(e,a.DOCK_TYPE.DOWN,null,"WebLogo",.35)}}class es{constructor(e){this.call=e,this.inputs=new class{},this.fixRegion=!1,this.defaultName=!0,this.defaultNameUpdating=!1;const t=e=>this.call.inputParams[e].property.description;this.inputs.table=o.tableInput("Table",this.call.inputParams.table.value??i.shell.tv.dataFrame,void 0,(()=>{}));const n=this.call.inputParams.sequence.value??this.inputs.table.value.columns.bySemType(a.SEMTYPE.MACROMOLECULE),s={filter:e=>e.semType===a.SEMTYPE.MACROMOLECULE};this.inputs.sequence=o.columnInput("Sequence",i.shell.tv.dataFrame,n,this.sequenceInputChanged.bind(this),s),this.inputs.start=o.choiceInput("Start",void 0,[],this.startInputChanged.bind(this)),this.inputs.end=o.choiceInput("End",void 0,[],this.endInputChanged.bind(this)),this.inputs.region=o.choiceInput("Region",null,[],this.regionInputChanged.bind(this)),this.inputs.name=o.stringInput("Column name",this.getDefaultName(),this.nameInputChanged.bind(this),{clearIcon:!0}),this.inputs.name.onInput(this.nameInputInput.bind(this));for(const e in this.call.inputParams)o.tooltip.bind(this.inputs[e].captionLabel,t(e));this.sequenceInputChanged()}sequenceInputChanged(){const e=this.inputs.sequence.value;e&&he.g.forColumn(e),this.updateRegionItems(),this.updateStartEndInputItems(),this.updateRegion(!0),this.updateNameInput()}regionInputChanged(){this.fixRegion=!0;try{const e=this.inputs.region.stringValue,t=e?JSON.parse(e):null;if(null!==t)this.inputs.start.value=t?.start,this.inputs.end.value=t?.end;else{const e=he.g.forColumn(this.inputs.sequence.value);this.inputs.start.value=e.posList[0],this.inputs.end.value=e.posList[e.posList.length-1]}}finally{this.fixRegion=!1}}startInputChanged(){this.updateRegion(!1),this.updateNameInput()}endInputChanged(){this.updateRegion(!1),this.updateNameInput()}nameInputChanged(){this.defaultNameUpdating||(this.defaultName=!1)}nameInputInput(){this.inputs.name.value||(this.defaultName=!0,this.inputs.name.input.focus())}updateStartEndInputItems(){const e=this.inputs.sequence.value,t=e?he.g.forColumn(e):null,n=this.inputs.start.input,s=this.inputs.end.input;for(let e=n.options.length-1;e>=0;--e)n.options.remove(e);for(let e=s.options.length-1;e>=0;--e)s.options.remove(e);for(const e of t?.posList??[]){const t=document.createElement("option"),r=document.createElement("option");t.text=r.text=e,t.value=r.value=e,n.options.add(t),s.options.add(r)}n.value=t?.posList[0]??"",s.value=t?.posList[t?.posList.length-1]??""}updateRegionItems(){const e=this.inputs.sequence.value,t=e?e.getTag(".regions"):null,n=t?JSON.parse(t):null,s=this.inputs.region.input;for(let e=s.options.length-1;e>=0;--e)s.options.remove(e);const r=document.createElement("option");if(r.text="",r.value=JSON.stringify(null),s.options.add(r),null!=n){this.inputs.region.root.style.removeProperty("display");for(const e of n){const t=document.createElement("option");t.text=`${e.name}: ${e.start}-${e.end}`,t.value=JSON.stringify(e),s.options.add(t)}}else this.inputs.region.root.style.display="none"}updateRegion(e){const t=this.inputs.start.stringValue??"",n=this.inputs.end.stringValue??"";if(!this.fixRegion){const e=this.inputs.region.input;e.selectedIndex=-1;for(let s=e.options.length-1;s>=0;--s){const r=e.options[s],i=JSON.parse(r.value);i&&t===i.start&&n===i.end&&(e.selectedIndex=s)}}}updateNameInput(){this.defaultNameUpdating=!0;try{this.defaultName&&(this.inputs.name.value=this.getDefaultName())}finally{this.defaultNameUpdating=!1}}getDefaultName(){const e=this.inputs.region.stringValue,t=e?JSON.parse(e):null,n=this.inputs.sequence.value,s=this.inputs.start.stringValue??"",r=this.inputs.end.stringValue??"";return null!=t?`${n.name}(${t.name}): ${t.start}-${t.end}`:`${n?.name}: (${s}-${r})`}getParams(){return{table:this.inputs.table.value,sequence:this.inputs.sequence.value,start:this.getStart(),end:this.getEnd(),name:this.getName()}}getStart(){return this.inputs.start.stringValue}getEnd(){return this.inputs.end.stringValue}getName(){const e=this.inputs.name.stringValue;return""==e?null:e}dialog(){const e=o.inputs(Object.values(this.inputs),{style:{minWidth:"320px"}});o.dialog({title:"Get Region"}).add(e).onOK((()=>{(async()=>{const e=this.getParams();await this.call.func.prepare(e).call(!0)})().catch((e=>{ls.handleErrorUI(e)}))})).show()}widget(){const e=o.inputs(Object.entries(this.inputs).filter((([e,t])=>!["table","sequence"].includes(e))).map((([e,t])=>t))),t=o.button("Get Region",(()=>{(async()=>{const e=this.getParams();await this.call.func.prepare(e).call(!0)})().catch((e=>{ls.handleErrorUI(e)}))}));return a.Widget.fromRoot(o.divV([e,o.div(t)]))}}var ts=n(8601);class ns{constructor(){this.maxIterations={uiName:"Max iterations",value:0,tooltip:"Maximum iterations for MCL process.Default is \n 0 which will construct the clusters with plain sparse matrix. Values greater than 0 will \n perform MCL with the given number of iterations and will result in trans-cluster activity cliff lines."},this.useWebGPU={uiName:"Use WebGPU",value:!1,tooltip:"Use WebGPU for MCL calculation. (Experimental)",type:"boolean"}}}class ss extends p{constructor(e={}){super({...e,enableMCL:!0});const t=this.tableInput.value.columns.numerical;this.activitiesInput=o.columnInput("Activities",this.tableInput.value,a.Utils.firstOrNull(t),null,{filter:e=>Array.from(t).includes(e)}),this.activitiesInputRoot=this.activitiesInput.root,this.similarityInput=o.intInput("Similarity cutoff",80),this.methodsParams[d]=new ns}onTableInputChanged(){if(super.onTableInputChanged(),this.activitiesInputRoot){o.empty(this.activitiesInputRoot);const e=this.tableInput.value.columns.numerical;this.activitiesInput=o.columnInput("Activities",this.tableInput.value,a.Utils.firstOrNull(e),null,{filter:t=>Array.from(e).includes(t)}),Array.from(this.activitiesInput.root.children).forEach((e=>this.activitiesInputRoot.append(e)))}}getEditor(){return o.div([this.tableInput,this.colInputRoot,this.preprocessingFunctionInputRoot,this.preprocessingFuncSettingsDiv,this.activitiesInputRoot,this.similarityMetricInputRoot,this.methodInput,this.methodSettingsDiv,this.similarityMetricInputRoot,this.similarityInput],{style:{minWidth:"320px"},classes:"ui-form"})}getParams(){return{...super.getParams(),activities:this.activitiesInput.value,similarityThreshold:this.similarityInput.value}}}function rs(e){const t=["Embed_X","Embed_Y"],n=e.columns.names().filter((e=>e.includes(t[0]))).length+1;return t.map((e=>`${e}_${n}`))}var is=n(6286);class os{constructor(e){this.separator=e,this.separatorSplitter=(0,we.Ar)(this.separator),this.splitter=this._splitter.bind(this)}_splitter(e){const t=this.separatorSplitter(e);return new as(t.originals,he.lh[Me.r2.SEPARATOR])}}class as extends we.wx{get canonicals(){if(!this._canonicals){const e=this.length;this._canonicals=new Array(e);for(let t=0;t<e;++t)this._canonicals[t]=this.getCanonical(t)}return this._canonicals}getCanonical(e){if(this.isGap(e))return is.G2;let t=this.seqCList[e];if(null===t){const n=this.getOriginal(e);t=n,")"===n[n.length-1]&&(t=this.seqCList[e]=n.replace(/\(\d+\)$/,""))}return t}constructor(e,t){super(e,t),this._canonicals=null,this.seqCList=new Array(this.length).fill(null)}}const ls=new un;function cs(){return St.A.instance}let us=null;class hs{constructor(e){this._palette=e}get(e){return this._palette[e]}}async function ds(){ls.logger.debug("Bio: initBio(), started");const e=await i.functions.call("Chem:getRdKitModule");await Promise.all([(async()=>{await St.A.instance.loadLibraries()})(),(async()=>{const e=await ls.getProperties(),t=new cn(e);ls.properties=t})()]).finally((()=>{ls.completeInit()}));const t=St.A.instance.getBioLib(),n=[],s=[],r=t.getMonomerMolsByPolymerType("PEPTIDE");Object.keys(r).forEach((t=>{n.push(t);const i=r[t].replaceAll("#R","O "),o=e.get_mol(i),a=JSON.parse(o.get_descriptors()).CrippenClogP;s.push(a),o?.delete()}));const o=s.reduce(((e,t)=>e+t),0)/s.length||0,a={};for(let e=0;e<n.length;e++)a[n[e]]=s[e]<o?"#4682B4":"#DC143C";us=new hs(a),ls.logger.debug("Bio: initBio(), completed")}function ms(e){const t=new dn(e);return t.init().then((()=>{})).catch((e=>{const t=e instanceof Error?e.message:e.toString();i.shell.error(t)})),t}function ps(){return St.A.instance.getBioLib()}function fs(e){return he.g.forColumn(e)}function gs(e){const t="getRegionTopMenu",n=a.Func.find({package:ls.name,name:t});if(1!==n.length)throw new Error(`Package '${ls.name}' func '${t}' not found`);const s=n[0].prepare({table:e.dataFrame,sequence:e});return new es(s).widget()}async function ys(e){return async function(){const e=o.label("Manage monomer libraries");return xt()(e).addClass("d4-link-action"),e.onclick=async()=>await $t(),new a.Widget(e)}()}function bs(e){try{new es(e).dialog()}catch(e){const t=e instanceof Error?e.message:e.toString(),n=e instanceof Error?e.stack:void 0;i.shell.error(`Get region editor error: ${t}`),ls.logger.error(t,void 0,n)}}function vs(e){const t=new tn;o.dialog({title:"Split to Monomers"}).add(t.paramsUI).onOK((async()=>e.func.prepare(t.funcParams).call(!0))).show()}function ws(e){const t=new p({semtype:a.SEMTYPE.MACROMOLECULE});o.dialog({title:"Sequence Space"}).add(t.getEditor()).onOK((async()=>{const n=t.getParams();return e.func.prepare({molecules:n.col,table:n.table,methodName:n.methodName,similarityMetric:n.similarityMetric,plotEmbeddings:n.plotEmbeddings,options:n.options,preprocessingFunction:n.preprocessingFunction,clusterEmbeddings:n.clusterEmbeddings}).call()})).show()}function Cs(e){const t=new ss({semtype:a.SEMTYPE.MACROMOLECULE});o.dialog({title:"Activity Cliffs"}).add(t.getEditor()).onOK((async()=>{const n=t.getParams();return e.func.prepare({table:n.table,molecules:n.col,activities:n.activities,similarity:n.similarityThreshold,methodName:n.methodName,similarityMetric:n.similarityMetric,preprocessingFunction:n.preprocessingFunction,options:n.options}).call()})).show()}function Ss(){return new Be}function As(e){return function(e){const t=Array.from(e.dataFrame.columns).filter((e=>e.semType===a.SEMTYPE.MOLECULE)).map((e=>e.name));new Set(t).delete(e.name);const n=o.choiceInput("Monomer width",null!=e?.temp["monomer-width"]?e.temp["monomer-width"]:Le.short,[Le.short,Le.long],(t=>{e.temp["monomer-width"]=t,e.setTag(".mm.cellRenderer.settingsChanged",Pe.true),e.dataFrame.fireValuesChanged()}));n.setTooltip("In short mode, only the 'Max monomer length' characters are displayed, followed by .. if there are more");const s=parseInt(e.getTag(Ee.maxMonomerLength)),r=o.intInput("Max monomer length",isNaN(s)?ls.properties.MaxMonomerLength:s,(t=>{e.setTag(Ee.maxMonomerLength,t.toString()),e.setTag(".mm.cellRenderer.settingsChanged",Pe.true),e.dataFrame.fireValuesChanged()}));r.setTooltip(`The max length of monomer name displayed without shortening in '${Le.short}' monomer width mode.`);const i=o.intInput("Monomer margin",e.temp[".mm.cellRenderer.gapLength"]??0,(t=>{e.temp[".mm.cellRenderer.gapLength"]=t,e.setTag(".mm.cellRenderer.settingsChanged",Pe.true),e.dataFrame.fireValuesChanged()}));i.setTooltip("The size of margin between monomers (in pixels)");const l=o.boolInput("Color code",null==e?.temp["color-code"]||e.temp["color-code"],(t=>{e.temp["color-code"]=t,e.dataFrame.fireValuesChanged()}));l.setTooltip("Color code");const c=o.stringInput("Reference sequence",null!=e?.temp["reference-sequence"]?e?.temp["reference-sequence"]:"",(t=>{e.temp["reference-sequence"]=t,e.dataFrame.fireValuesChanged()}));c.setTooltip("Reference sequence is not empty, then the sequence will be render \nas a difference from the reference sequence");const u=o.boolInput("Compare with current",null==e?.temp["compare-with-current"]||e.temp["compare-with-current"],(t=>{e.temp["compare-with-current"]=t,e.dataFrame.fireValuesChanged()}));u.setTooltip('When on, all sequences get rendered in the "diff" mode');const h=o.inputs([n,r,i,c,l,u]);return new a.Widget(h)}(e)}function xs(e){return(0,hn.t)(e)}function Es(){return new Be}function Is(){return new Ve}function Ts(e,t,n,s,r){const i=new tt.k(s,r,n,t);return"Local alignment"==e?i.smithWaterman():i.needlemanWunch()}function _s(){return new Ke.OZ}function Ms(){return new et}function $s(e,t,n,s){return Xn(e,t??null,n??null,s??null)}async function Ns(e,t,n,s,r){const o=Xn(t,n??null,s??null,r??null);t.dataFrame.columns.add(o),await i.data.detectSemanticTypes(t.dataFrame)}async function Ls(e,t,n,s,r,u,h,d){if(!(0,Jt.n)(t,"Activity Cliffs"))return;const m=rs(e),p={units:t.getTag(a.TAGS.UNITS),aligned:t.getTag("aligned"),separator:t.getTag("separator"),alphabet:t.getTag("alphabet")},f=u,g=t,y=async()=>await ce(e,g,m,"Activity cliffs",n,s,f,r,{...d??{}},a.SEMTYPE.MACROMOLECULE,p,h,ot,at,ht),b=r===c.A.UMAP?2e5:2e4,v=r===c.A.UMAP?5e3:2e3;if(e.rowCount>b)return void i.shell.warning(`Too many rows, maximum for sequence activity cliffs is ${b}`);const w=a.TaskBarProgressIndicator.create("Running sequence activity cliffs ...");return new Promise(((t,n)=>{e.rowCount>v&&!d?.[l.sS]?o.dialog().add(o.divText("Activity cliffs analysis might take several minutes.\n Do you want to continue?")).onOK((async()=>{y().then((e=>t(e))).catch((e=>n(e)))})).onCancel((()=>{t(void 0)})).show():y().then((e=>t(e))).catch((e=>n(e)))})).catch((e=>{const[t,n]=(0,ge.yf)(e);throw ls.logger.error(t,void 0,n),e})).finally((()=>{w.close()}))}async function Ps(e,t,n=1,s=.6,r="Morgan"){if(e.semType!==a.SEMTYPE.MACROMOLECULE)return{entries:e.toList(),options:{}};const{seqList:i,options:o}=await st(e,t,r);return{entries:i,options:{...o,gapOpen:n,gapExtend:s}}}async function Rs(e,t){e.version!==e.temp["last-invalidated-version"]&&await(0,it.HV)(e,!1);const n=e.temp["monomeric-mols"],s=await i.functions.call("Chem:getMorganFingerprints",{molColumn:n}),r=new Array(s.length).fill(null);for(let e=0;e<s.length;e++){if(s.isNone(e)||!s.get(e))continue;const t=s.get(e);r[e]=G.Z.fromUint32Array(t.length,new Uint32Array(t.getBuffer().buffer))}return{entries:r,options:{}}}async function Os(e,t,s,r,c,u,h,d){if((0,Jt.n)(t,"Sequence Space"))return u||(u=a.Func.find({name:"macromoleculePreprocessingFunction",package:"Bio"})[0]),h??(h={}),await async function(e,t,s,r,c,u,h,d=!0,m=!1,p={preprocessingFuncArgs:[]},f={},g=null,y={}){const b={showXAxis:!1,showYAxis:!1,showXSelector:!1,showYSelector:!1};if(t.length!==r.length||t.length!==u.length||t.length!==c.length||t.length!==p.preprocessingFuncArgs.length)throw new Error("columns, metrics and preprocessing functions, weights and function argumentsmust have the same length");const v=i.shell.tableView(e.name)??i.shell.addTableView(e),w=async()=>{const w=a.TaskBarProgressIndicator.create(`Initializing ${f.scatterPlotName??"dimensionality reduction"} ...`);let C;try{const S=rs(e);function A(t,n,s){let r=null,i=null;e.columns.names().includes(S[0])?(r=e.columns.byName(S[0]),i=e.columns.byName(S[1])):(r=e.columns.add(a.Column.float(S[0],e.rowCount)),i=e.columns.add(a.Column.float(S[1],e.rowCount)),d&&!C&&(C=v.scatterPlot({...b,x:S[0],y:S[1],title:f.scatterPlotName??"Embedding space"}))),f[l.Ec]&&(C?.root&&o.setUpdateIndicator(C.root,!1),r.init((e=>s[0]?s[0][e]:void 0)),i.init((e=>s[1]?s[1][e]:void 0)));const c=t/n*100;w.update(c,`Running ${f.scatterPlotName??"dimensionality reduction"}... ${c.toFixed(0)}%`)}async function x(){e.columns.add(a.Column.float(S[0],e.rowCount)),e.columns.add(a.Column.float(S[1],e.rowCount));let n=null;d&&(C=v.scatterPlot({...b,x:S[0],y:S[1],title:f.scatterPlotName??"Embedding space"}),o.setUpdateIndicator(C.root,!0));const m=i.events.onViewerClosed.subscribe((e=>{const t=e.args.viewer;t?.getOptions()?.look?.title&&C?.getOptions()?.look?.title&&t?.getOptions()?.look?.title===C?.getOptions()?.look?.title&&(i.events.fireCustomEvent(B,{}),m.unsubscribe(),n?.(),w.close())})),g=new Promise((async(e,i)=>{try{n=e;const i=[];for(let e=0;e<u.length;++e){const n=u[e];if(p.distanceFnArgs||(p.distanceFnArgs=[]),n){const s=n.inputs[0].name,o=n.inputs[1].name,{entries:a,options:l}=await n.apply({[s]:t[e],[o]:r[e],...p.preprocessingFuncArgs[e]??{}});i.push({entries:a,options:l}),p.distanceFnArgs.push(l)}else{const n=t[e].toList(),s={};i.push({entries:n,options:s}),p.distanceFnArgs.push(s)}}e(await j(i.map((e=>e.entries)),s,r,c,h,p,f[l.sS]?void 0:A))}catch(e){i(e)}})),y=await g;return w.close(),m.unsubscribe(),y}const E=await x();if(m&&E){const I=a.TaskBarProgressIndicator.create("Clustering embeddings ...");try{const T=await function(e,t,s,r){return Yt(this,void 0,void 0,(function*(){return new Promise((function(i,o){const a=new Worker(new URL(n.p+n.u(796),n.b));a.postMessage({embedX:e,embedY:t,minPts:r,epsilon:s}),a.onmessage=({data:{error:e,clusters:t}})=>{a.terminate(),e?o(e):i(t)}}))}))}(E[0],E[1],p.dbScanEpsilon??.01,p.dbScanMinPts??4),_=e.columns.getUnusedName("Cluster (DBSCAN)");e.columns.addNewString(_).init((e=>T[e].toString())),C&&(C.props.colorColumnName=_)}catch(M){i.shell.error("Clustering embeddings failed"),console.error(M)}finally{I.close()}}if(E){const $=e.columns.byName(S[0]),N=e.columns.byName(S[1]);if($.init((e=>E[0][e])),N.init((e=>E[1][e])),g)try{const L=g.inputs[0].name,P=g.inputs[1].name;await g.prepare({[L]:$,[P]:N,...y}).call(!0)}catch(R){i.shell.error("Post-processing failed"),console.error(R)}if(C)return o.setUpdateIndicator(C.root,!1),C.helpUrl="/help/compute/sequence-space",C}}catch(O){i.shell.error("Dimensionality reduction failed"),console.error(O),w.close(),C&&o.setUpdateIndicator(C.root,!1)}};return new Promise((async(t,n)=>{try{if(f.fastRowCount&&e.rowCount>f.fastRowCount&&!f[l.sS])o.dialog().add(o.divText("Analysis might take several minutes. Do you want to continue?")).onOK((async()=>{try{const e=await w();t(e)}catch(e){n(e)}})).onCancel((()=>t(void 0))).show();else{const e=await w();t(e)}}catch(e){n(e)}}))}(e,[t],s,[r],[1],[u],"MANHATTAN",c,d??!1,{...h,preprocessingFuncArgs:[h.preprocessingFuncArgs??{}]},{fastRowCount:1e4,scatterPlotName:"Sequence space",bypassLargeDataWarning:h?.[l.sS]})}async function ks(e,t,n){const s=a.TaskBarProgressIndicator.create("Converting to atomic level ...");try{await async function(e,t,n){if(0===a.Func.find({package:"Chem",name:"getRdKitModule"}).length)return void i.shell.warning('Transformation to atomic level requires package "Chem" installed.');if(n){const n=he.g.forColumn(t);return n.isHelm()||(t=n.convert(Me.r2.HELM)),void async function(e,t){const n=await Rn(e,t);e.columns.add(n,!0),await i.data.detectSemanticTypes(e)}(e,t)}if(!(0,Jt.n)(t,"To Atomic Level"))return;const s=cs().getBioLib(),r=await(0,ts.i0)(e,t,s);null!==r.col&&(e.columns.add(r.col,!0),await i.data.detectSemanticTypes(e)),r.warnings&&r.warnings.length>0&&i.shell.warning(o.list(r.warnings))}(e,t,n)}finally{s.close()}}function Fs(){(0,Qt.K)()}async function Gs(e=null,t=null){return(0,Qt.K)({col:e,clustersCol:t})}async function Ds(){const e=i.shell.tv,t=e.dataFrame.columns.toList().filter((e=>e.semType==a.SEMTYPE.MACROMOLECULE&&(he.g.forColumn(e),!0))),n=async t=>{if(!(0,Jt.n)(t,"Composition"))return;const n=e.addViewer("WebLogo",{sequenceColumnName:t.name});i.shell.tv.dockManager.dock(n,a.DOCK_TYPE.DOWN,null,"Composition analysis",.25)};let s=null;if(0!=t.length){if(t.length>1){const e=t.map((e=>e.name)),s=t.find((e=>he.g.forColumn(e).isMsa())),r=o.choiceInput("Column",s?s.name:e[0],e);o.dialog({title:"Composition Analysis",helpUrl:"https://datagrok.ai/help/datagrok/solutions/domains/bio/#sequence-composition"}).add(o.div([r])).onOK((async()=>{const e=t.find((e=>e.name==r.value))??null;e&&await n(e)})).show()}else s=t[0];s&&await n(s)}else i.shell.error("Current table does not contain sequences")}function Bs(e){return new de.i(e).importFasta()}function Vs(e){return console.log(e),[]}function Us(){const e=(0,ye.B)()[0];(0,vt.O)(e)}async function Hs(){let e;try{e=await async function(){const e=i.shell.t.columns.bySemTypeAll(a.SEMTYPE.MACROMOLECULE);if(!e)throw new Error("No dataframe with macromolecule columns open");const t=o.columnInput("Column",i.shell.t,e[0],null,{filter:e=>e.semType===a.SEMTYPE.MACROMOLECULE}),n=o.boolInput("Get HELM",!0);o.tooltip.bind(n.root,"Add HELM column");const s=o.boolInput("Chirality engine",!1),r=new Un(On,kn,".csv"),l=await r.getForm(),c=o.div([t,n,s,"Rules used",l]);return o.dialog("Poly Tool").add(c).onOK((async()=>{const e=t.value;if(!e)return void i.shell.warning("No marcomolecule column chosen!");const o=await r.getActive();Dn(e,n.value,o,s.value)}))}(),e.show()}catch(e){i.shell.warning("To run PolyTool, open a dataframe with macromolecules")}}function js(){return new ln}async function Ws(e){const t=a.TaskBarProgressIndicator.create("Test detectMacromolecule..."),n=(await i.dapi.files.list(e,!0,"")).filter((e=>e.fileName.endsWith(".csv")));let s=0;const r=[];for(const o of n)try{const t=await i.dapi.files.readAsText(e+o.fullPath),n=a.DataFrame.fromCsv(t);for(const e of n.columns)await i.functions.call("Bio:detectMacromolecule",{col:e})===a.SEMTYPE.MACROMOLECULE&&r.push({file:o.path,result:"detected",column:e.name,message:`units: ${e.getTag(a.TAGS.UNITS)}`})}catch(e){r.push({file:o.path,result:"error",column:null,message:e instanceof Error?e.message:e.toString()})}finally{s+=1,t.update(100*s/n.length,`Test ${o.fileName}`)}i.shell.info("Test Demo:Files for detectMacromolecule finished."),t.close();const o=a.DataFrame.fromObjects(r);return o.name=`datasets_detectMacromolecule_${e}`,o}async function Ys(e,t){await(0,nn.n)(e,t)}function Zs(e){const t=he.g.forColumn(e).stats;return Object.keys(t.freq)}function qs(){return new gt}function Ks(){const e=i.shell.v,t=e.addViewer("Sequence Similarity Search");e.dockManager.dock(t,"down")}function zs(){return new bt}function Xs(){const e=i.shell.v,t=e.addViewer("Sequence Diversity Search");e.dockManager.dock(t,"down")}function Js(e){const t=(0,ye.B)();1===t.length?e.func.prepare({macromolecules:t[0]}).call(!0):new it.uH(t)}function Qs(e){i.shell.tv.getFiltersGroup({createDefaultFilters:!1}).updateOrAdd({type:"Bio:bioSubstructureFilter",column:e.name,columnName:e.name}),i.shell.tv.grid.scrollToCell(e,0)}async function er(e,t,n){return fe(e,t,n,ue.IDENTITY)}async function tr(e,t,n){return fe(e,t,n,ue.SIMILARITY)}async function nr(){$t()}function sr(){(0,wt.C2)()}function rr(){return new Ct.ST}async function ir(){const e=a.TaskBarProgressIndicator.create("WebLogo");try{const e=new URLSearchParams(window.location.search),t=new en(e,"webLogoLargeApp"),n=await ls.files.readCsv("data/sample_PT_100000x5.csv");await i.data.detectSemanticTypes(n),await t.init(n)}finally{e.close()}}async function or(){const e=a.TaskBarProgressIndicator.create("WebLogo ...");try{const e=new URLSearchParams(window.location.search),t=new en(e,"webLogoAggApp"),n=await ls.files.readCsv("samples/FASTA_PT_activity.csv");await i.data.detectSemanticTypes(n),await t.init(n)}finally{e.close()}}async function ar(){const e=a.TaskBarProgressIndicator.create("getRegion ...");try{const e=new URLSearchParams(window.location.search),t=new Qn(e,"getRegionApp");await t.init()}finally{e.close()}}async function lr(){const e=a.TaskBarProgressIndicator.create("getRegion ...");try{const e=new URLSearchParams(window.location.search),t=await ls.files.readCsv("samples/HELM_empty_vals.csv"),n=new Qn(e,"getRegionHelmApp");await n.init({df:t,colName:"HELM"})}finally{e.close()}}function cr(e,t){!function(e,t){const n=he.g.forColumn(e.column),s=Object.values(Me.r2).filter((e=>e!==n.units));t.group("Copy").items(s,(t=>{const n=e.column,s=e.rowIndex,r=he.g.forColumn(n),o=t===Me.r2.SEPARATOR?ls.properties.DefaultSeparator:void 0,a=r.getJoiner({notation:t,separator:o})(r.getSplitted(s));navigator.clipboard?(navigator.clipboard.writeText(a),i.shell.info(`Value of notation '${t}' copied to clipboard`)):i.shell.warning("The clipboard functionality requires a secure origin — either HTTPS or localhost")}))}(e,t)}async function ur(){await async function(){let e,t;try{const n=new kt("Similarity, Diversity","Sequence similarity tracking and evaluation dataset diversity");await n.step("Load DNA sequences",(async()=>{i.shell.windows.showContextPanel=!1,i.shell.windows.showProperties=!1,t=await ls.files.readCsv(Gt),e=i.shell.addTableView(t),e.grid.columns.byName("cluster").visible=!1,e.grid.columns.byName("sequence_id").visible=!1,e.grid.columns.byName("sequence").width=300,e.grid.columns.byName("activity").visible=!1,e.grid.columns.byName("is_cliff").visible=!1}),{description:"Load dataset with macromolecules of 'fasta' notation, 'DNA' alphabet.",delay:2e3}).step("Find the most similar sequences to the current one",(async()=>{const n=await t.plot.fromType("Sequence Similarity Search",{moleculeColumnName:"sequence",similarColumnLabel:"Similar to current"});e.dockManager.dock(n,a.DOCK_TYPE.RIGHT,null,"Similarity search",.35)}),{description:"Add 'Sequence Similarity Search' viewer.",delay:2e3}).step("Explore most diverse sequences in a dataset",(async()=>{const n=await t.plot.fromType("Sequence Diversity Search",{moleculeColumnName:"sequence",diverseColumnLabel:"Top diverse sequences of all data"});e.dockManager.dock(n,a.DOCK_TYPE.DOWN,null,"Diversity search",.27)}),{description:"Add 'Sequence Deversity Search' viewer.",delay:2e3}).step("Choose another sequence for similarity search",(async()=>{t.currentRowIdx=3}),{description:"Handling current row changed of data frame showing update of similar sequences.",delay:2e3}).step("One more sequence for similarity search",(async()=>{t.currentRowIdx=7}),{description:"Just one more sequence to search similar ones.",delay:2e3}).start()}catch(e){Ft(e)}}()}async function hr(){await async function(){let e,t,n,s,r;try{const o=new kt("Sequence Space","Exploring sequence space of Macromolecules, comparison with hierarchical clustering results");await o.step("Load DNA sequences",(async()=>{[s,e,t]=await Promise.all([ls.files.readCsv(Zt),Dt(),Bt()]),n=i.shell.addTableView(s),n.grid.props.rowHeight=22,n.grid.columns.byName("cluster").visible=!1,n.grid.columns.byName("sequence").width=200,n.grid.columns.byName("is_cliff").visible=!1,i.shell.windows.showContextPanel=!1,i.shell.windows.showProperties=!1}),{description:"Load dataset with macromolecules of 'fasta' notation, 'DNA' alphabet.",delay:2e3}).step("Build sequence space",(async()=>{r=await async function(e,t,n,s){let r;{const e=Object.values(Rt);for(let n=0;n<e.length;n++){const s=e[n];if(!t.col(s)){const r=n==e.length-1;t.columns.add(a.Column.float(s,t.rowCount),r)}}if(t.rowCount>=1){const s=t.getCol(n).toList(),r=Date.now();ls.logger.debug("Bio: demoBio01aUI(), calc reduceDimensionality start...");const i=await j([s],"UMAP",[rt.W.Levenshtein],[1],"MANHATTAN",{distanceFnArgs:[{}]}),o=Date.now();ls.logger.debug(`Bio: demoBio01aUI(), calc reduceDimensionality ET: ${(o-r)/1e3} s`);for(let n=0;n<e.length;n++){const s=e[n],r=t.getCol(s),o=i[n];r.init((e=>o[e]))}const a=Date.now();ls.logger.debug(`MLB: MlbVrSpaceBrowser.buildView(), postprocess reduceDimensionality ET: ${(a-o)/1e3} s`)}r=await t.plot.fromType(a.VIEWER.SCATTER_PLOT,{xColumnName:Rt.X,yColumnName:Rt.Y,lassoTool:!0})}return e.dockManager.dock(r,a.DOCK_TYPE.RIGHT,null,"Sequence Space",.35),r}(n,s,qt),r.setOptions({color:"activity"})}),{description:"Reduce sequence space dimensionality to display on 2D representation.",delay:2e3}).step("Cluster sequences",(async()=>{const r=await e.calcDistanceMatrix(s,[qt]),i=await Ut(r.data,s.rowCount,1),o=e.parseClusterMatrix(i);t.injectTreeForGrid(n.grid,o,void 0,150,void 0)}),{description:"Perform hierarchical clustering to reveal relationships between sequences.",delay:2e3}).step("Select a sequence",(async()=>{s.selection.set(65,!0)}),{description:"Handling selection of data frame row reflecting on linked viewers.",delay:2e3}).step("Select a bunch of sequences",(async()=>{[67,72,77,82,83,84,85,91,93].forEach((e=>s.selection.set(e,!0))),s.currentRowIdx=27}),{description:"Selecting a group of rows from a data frame to show their similarity and proximity to each other on a viewer..",delay:2e3}).start()}catch(e){Ft(e)}}()}async function dr(){await async function(){let e,t,n,s,r;const o=c.A.UMAP;try{const l=new kt("Activity Cliffs","Activity Cliffs analysis on Macromolecules data");await l.step("Load DNA sequences",(async()=>{i.shell.windows.showContextPanel=!1,i.shell.windows.showProperties=!1,[n,e,t]=await Promise.all([ls.files.readCsv(Kt),Dt(),Bt()]),s=i.shell.addTableView(n),s.grid.props.rowHeight=22,s.grid.columns.byName("cluster").visible=!1,s.grid.columns.byName("sequence").width=300,s.grid.columns.byName("is_cliff").visible=!1}),{description:"Load dataset with macromolecules of 'fasta' notation, 'DNA' alphabet.",delay:2e3}).step("Find activity cliffs",(async()=>{const e=a.Func.find({name:"macromoleculePreprocessingFunction",package:"Bio"})[0];r=await Ls(n,n.getCol("Sequence"),n.getCol("Activity"),80,o,nt.U.LEVENSHTEIN,e,{}),s.dockManager.dock(r,a.DOCK_TYPE.RIGHT,null,"Activity Cliffs",.35),xt()(r.root).find("button.scatter_plot_link,cliffs_grid").get()[0].click()}),{description:"Reveal similar sequences with a cliff of activity.",delay:2e3}).step("Cluster sequences",(async()=>{const r=a.TaskBarProgressIndicator.create("Running sequence clustering..."),i=await e.calcDistanceMatrix(n,["sequence"]),o=await Ut(i.data,n.rowCount,1),l=e.parseClusterMatrix(o);r.close(),t.injectTreeForGrid(s.grid,l,void 0,150,void 0),s.grid.columns.byName("Activity").scrollIntoView()}),{description:"Perform hierarchical clustering to reveal relationships between sequences.",delay:2e3}).step("Browse the cliff",(async()=>{const e=r.dataFrame.temp[".cliffsDfGrid"];e.dataFrame.rowCount>0&&(e.dataFrame.currentRowIdx=0)}),{description:"Zoom in to explore selected activity cliff details.",delay:2e3}).start()}catch(e){Ft(e)}}()}async function mr(){await async function(){const e="HELM";let t,n,s;try{await new kt("Atomic Level","Atomic level structure of Macromolecules").step("Loading Macromolecules notation 'Helm'",(async()=>{i.shell.windows.showContextPanel=!1,i.shell.windows.showProperties=!1,t=await ls.files.readCsv("samples/HELM.csv"),n=i.shell.addTableView(t);for(let t=0;t<n.grid.columns.length;t++){const s=n.grid.columns.byIndex(t);[e,"Activity"].includes(s.name)||(s.visible=!1)}}),{description:"Load dataset with macromolecules of 'fasta' notation, 'PT' alphabet (protein, aminoacids).",delay:2e3}).step("To atomic level",(async()=>{const n=t.getCol(e);await ks(t,n,!1)}),{description:"Get atomic level structures of Macromolecules.",delay:2e3}).step("Sketcher",(async()=>{const n=`molfile(${e})`;t.currentCell=t.cell(1,n);const r=t.currentCell.value,i=new a.chem.Sketcher(a.chem.SKETCHER_MODE.INPLACE);i.setMolFile(r),s=o.dialog().add(i).show(),await(0,We.gw)(3e3),s.close()}),{description:"Display atomic level structure within a sketcher.",delay:2e3}).start()}catch(e){Ft(e)}}()}async function pr(){await async function(){let e,t,n,s,r,o;const l="msa(HELM)",u=c.A.UMAP,h=(await zt.lp.getDockerContainer()).id,d=zt.lp.getDockerContainer();let m,p;try{const c=new kt("Helm, MSA, Sequence Space","MSA and composition analysis on Helm data");await c.step("Load peptides with non-natural aminoacids in 'HELM' notation",(async()=>{[m,t]=await Promise.all([(async()=>(await d).status)(),ls.files.readCsv(Xt)]),e=i.shell.addTableView(t),i.shell.windows.showContextPanel=!1,i.shell.windows.showProperties=!1,"started"===m||"checking"===m?(ls.logger.debug(`demoBio05UI(), PepSeA ('${zt.lp.dcName}') docker container status = '${m}'.`),p=Promise.resolve()):(ls.logger.warning(`demoBio05UI(), PepSeA ('${zt.lp.dcName}') docker container is trying to start...`),await i.dapi.docker.dockerContainers.run(h),p=async function(e,t,n=3e4,s){const r=window.performance.now(),o=new y.Subject,a=async()=>{const n=await i.dapi.docker.dockerContainers.find(e);return n.status===t&&o.next(n),n};let l;try{await(0,We.zg)(o,(e=>{const n=window.performance.now();s.debug(`awaitStatus(), docker container ('${e.name}') GET status = '${t}' in ${n-r} ms.`)}),(async()=>{const e=await a();s.debug(`awaitStatus(), docker container ('${e.name}') HAS status = '${e.status}'.`),l=window.setInterval(a,200)}),n)}finally{window.clearInterval(l)}}(h,"started",3e4,ls.logger))}),{description:"Load dataset with macromolecules of 'Helm' notation.",delay:2e3}).step("Align peptides with non-natural aminoacids with PepSeA",(async()=>{const e=a.TaskBarProgressIndicator.create("MSA by PepSeA ...");try{await p,n=t.getCol("HELM");const e=zt.Jy[0],r=1.53,o=0;if(s=await(0,zt.f3)(n,l,e,r,o,void 0),!s)throw new Error("Empty MSA result.");t.columns.add(s),await i.data.detectSemanticTypes(t)}finally{e.close()}}),{description:"Multiple sequence alignment (MSA) performed with PepSeA tool operating on non-natural aminoacids as well.",delay:2e3}).step("Build sequence space",(async()=>{const n=a.Func.find({package:"Bio",name:"macromoleculePreprocessingFunction"})[0];o=await Os(t,s,u,nt.U.LEVENSHTEIN,!0,n),e.dockManager.dock(o,a.DOCK_TYPE.RIGHT,null,"Sequence Space",.35)}),{description:"Reduce sequence space dimensionality to display on 2D representation.",delay:2e3}).step("Analyse sequence composition",(async()=>{r=await t.plot.fromType("WebLogo",{sequenceColumnName:l,positionWidth:40,maxHeight:50}),e.dockManager.dock(r,a.DOCK_TYPE.DOWN,null,"Composition analysis",.2)}),{description:"Composition analysis allows to reveal functional features of sequences like motifs, or variable loops.",delay:2e3}).start()}catch(e){Ft(e)}}()}async function fr(e,t){var n;(function(e){e.setTag("quality",a.SEMTYPE.MACROMOLECULE),e.setTag("aligned","SEQ"),e.setTag("alphabet","PT")})(n=t),n.setTag("units",Me.r2.SEPARATOR),n.setTag("separator","-"),await i.data.detectSemanticTypes(e)}async function gr(e){const t=await e.readAsString(),n=new zn(e.fileName,t),s=await n.getJson(),r=e.fileName.replace(/\.csv$/,".json"),i=JSON.stringify(s,null,2);a.Utils.download(r,i)}async function yr(e){const t=(0,me.Xk)(e),n=JSON.stringify(t);a.Utils.download(`${e.name}.json`,n)}async function br(e,t,n){const s=await e.readAsString();await async function(e,t,n){const s=a.TaskBarProgressIndicator.create("detectMacromolecule probe ...");try{let r=0;const o=await i.functions.call("Bio:detectMacromoleculeEnableStore");let l=0;for(let c=0;c<n;++c){const u=a.DataFrame.fromCsv(e),h=t?u.getCol(t):u.columns.byIndex(0);await i.functions.call("Bio:detectMacromolecule",{col:h})!==a.SEMTYPE.MACROMOLECULE&&(++l,console.warn(`Reject reason: ${o.last.rejectReason}`));const d=c/n;d-r>=.1&&(r=d,s.update(100*d,`detectMacromolecule probe ${l}/${c}/${n} ...`),await(0,We.gw)(0))}l>0?i.shell.warning(`detectMacromolecule failed ${l} / ${n}`):i.shell.info(`detectMacromolecule success ${n}`)}finally{s.close()}}(s,t,n)}function vr(e,t){e.temp[he.dm.notationProvider]=new os(t)}},9017:(e,t,n)=>{"use strict";n.d(t,{k:()=>i});class s{constructor(){this.value=0,this.parentI=0,this.parentJ=0}}class r{constructor(e,t,n){this.seq1=e,this.seq2=t,this.score=n}}class i{fillNeedleman(){for(let e=0;e<=this.len1;e++)this.dpGrid[e][0].value=-e*this.gap,this.dpGrid[e][0].parentI=e-1,this.dpGrid[e][0].parentJ=0;for(let e=1;e<=this.len2;e++)this.dpGrid[0][e].value=-e*this.gap,this.dpGrid[0][e].parentI=0,this.dpGrid[0][e].parentJ=e-1}fillOne(e,t){this.dpGrid[e][t].value=Math.max(this.dpGrid[e-1][t-1].value+this.scores[e-1][t-1],Math.max(this.dpGrid[e-1][t].value-this.gap,this.dpGrid[e][t-1].value-this.gap)),this.dpGrid[e][t].value==this.dpGrid[e-1][t-1].value+this.scores[e-1][t-1]?(this.dpGrid[e][t].parentI=e-1,this.dpGrid[e][t].parentJ=t-1):this.dpGrid[e][t].value==this.dpGrid[e-1][t].value-this.gap?(this.dpGrid[e][t].parentI=e-1,this.dpGrid[e][t].parentJ=t):(this.dpGrid[e][t].parentI=e,this.dpGrid[e][t].parentJ=t-1)}gridFromName(e){switch(e){case"BLOSUM45":this.alignGrid=this.BLOSUM45,this.connections=this.CONBLO,this.step=1;break;case"BLOSUM50":this.alignGrid=this.BLOSUM50,this.connections=this.CONBLO,this.step=1;break;case"BLOSUM62":this.alignGrid=this.BLOSUM62,this.connections=this.CONBLO,this.step=1;break;case"BLOSUM80":this.alignGrid=this.BLOSUM80,this.connections=this.CONBLO,this.step=1;break;case"BLOSUM90":this.alignGrid=this.BLOSUM90,this.connections=this.CONBLO,this.step=1;break;case"PAM30":this.alignGrid=this.PAM30,this.connections=this.CONBLO,this.step=1;break;case"PAM70":this.alignGrid=this.PAM70,this.connections=this.CONBLO,this.step=1;break;case"PAM250":this.alignGrid=this.PAM250,this.connections=this.CONBLO,this.step=1;break;case"NUCLEOTIDES":this.alignGrid=this.NUCLEOTIDES,this.connections=this.CONNUCL,this.step=1;break;case"TRANS":this.alignGrid=this.TRANS,this.connections=this.CONNUCL,this.step=1;break;case"SCHNEIDER":this.alignGrid=this.SCHNEIDER,this.connections=this.CONSCHN,this.step=3}this.fillScores()}constructResult(e,t){let n="",s="",i="";const o=this.dpGrid[e][t].value;for(let e=0;e<this.step;e++)i+="|";for(;e>0||t>0;){this.dpGrid[e][t].parentI==e?(n=i+n,s=this.seq2.substr((t-1)*this.step,this.step)+s):this.dpGrid[e][t].parentJ==t?(s=i+s,n=this.seq1.substr((e-1)*this.step,this.step)+n):(n=e-1>=0?this.seq1.substr((e-1)*this.step,this.step)+n:i+n,s=t-1>=0?this.seq2.substr((t-1)*this.step,this.step)+s:i+s);const r=e;e=this.dpGrid[e][t].parentI,t=this.dpGrid[r][t].parentJ}return new r(n,s,o)}fillScores(){this.scores=[];for(let e=0;e<this.len1;e++){this.scores.push([]);for(let t=0;t<this.len2;t++)this.scores[e].push(this.alignGrid[this.connections[this.seq1.substr(e*this.step,this.step)]][this.connections[this.seq2.substr(t*this.step,this.step)]])}}typeRec(){if(/[ATGC]*/.test(this.seq1)&&/[ATGC]*/.test(this.seq2))return"NUCLEOTIDES";if(/[ARNDCQEGHILKMFPSTWYVBZX*]*/.test(this.seq1)&&/[ARNDCQEGHILKMFPSTWYVBZX*]*/.test(this.seq2))return"BLOSUM62";throw Error("Can't recognize sequence type")}needlemanWunch(){this.dpGrid=[];for(let e=0;e<this.len1+1;e++){const e=[];for(let t=0;t<this.len2+1;t++)e.push(new s);this.dpGrid.push(e)}this.fillNeedleman();for(let e=1;e<=this.len1;e++)for(let t=1;t<=this.len2;t++)this.fillOne(e,t);return this.constructResult(this.len1,this.len2)}smithWaterman(){this.dpGrid=[];for(let e=0;e<this.len1+1;e++){const e=[];for(let t=0;t<this.len2+1;t++)e.push(new s);this.dpGrid.push(e)}let e=0,t=0,n=0;for(let s=1;s<=this.len1;s++)for(let r=1;r<=this.len2;r++)this.fillOne(s,r),this.dpGrid[s][r].value<=0?(this.dpGrid[s][r].value=0,this.dpGrid[s][r].parentI=0,this.dpGrid[s][r].parentJ=0):0==this.dpGrid[this.dpGrid[s][r].parentI][this.dpGrid[s][r].parentJ].value&&(this.dpGrid[s][r].parentI=0,this.dpGrid[s][r].parentJ=0),this.dpGrid[s][r].value>e&&(e=this.dpGrid[s][r].value,t=s,n=r);return this.constructResult(t,n)}setSequences(e,t){this.seq1=e,this.seq2=t,this.len1=this.seq1.length/this.step,this.len2=this.seq2.length/this.step,this.fillScores()}setGap(e){this.gap=e}setMethod(e=""){"AUTO"==e&&(e=this.typeRec()),this.gridFromName(e)}constructor(e,t,n,s=""){this.seq1="",this.seq2="",this.gap=1,this.len1=0,this.len2=0,this.step=1,this.alignGrid=[],this.scores=[],this.dpGrid=[],this.connections={},this.BLOSUM45=[[5,-2,-1,-2,-1,-1,-1,0,-2,-1,-1,-1,-1,-2,-1,1,0,-2,-2,0,-1,-1,0,-5],[-2,7,0,-1,-3,1,0,-2,0,-3,-2,3,-1,-2,-2,-1,-1,-2,-1,-2,-1,0,-1,-5],[-1,0,6,2,-2,0,0,0,1,-2,-3,0,-2,-2,-2,1,0,-4,-2,-3,4,0,-1,-5],[-2,-1,2,7,-3,0,2,-1,0,-4,-3,0,-3,-4,-1,0,-1,-4,-2,-3,5,1,-1,-5],[-1,-3,-2,-3,12,-3,-3,-3,-3,-3,-2,-3,-2,-2,-4,-1,-1,-5,-3,-1,-2,-3,-2,-5],[-1,1,0,0,-3,6,2,-2,1,-2,-2,1,0,-4,-1,0,-1,-2,-1,-3,0,4,-1,-5],[-1,0,0,2,-3,2,6,-2,0,-3,-2,1,-2,-3,0,0,-1,-3,-2,-3,1,4,-1,-5],[0,-2,0,-1,-3,-2,-2,7,-2,-4,-3,-2,-2,-3,-2,0,-2,-2,-3,-3,-1,-2,-1,-5],[-2,0,1,0,-3,1,0,-2,10,-3,-2,-1,0,-2,-2,-1,-2,-3,2,-3,0,0,-1,-5],[-1,-3,-2,-4,-3,-2,-3,-4,-3,5,2,-3,2,0,-2,-2,-1,-2,0,3,-3,-3,-1,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-8,-5,-11,-9,8,-1,-6,-1,-2,-8,-7,-2,-14,-6,2,-6,-6,-5,-17],[-6,-8,-7,-12,-15,-5,-9,-10,-6,-1,7,-8,1,-3,-7,-8,-7,-6,-7,-2,-9,-7,-6,-17],[-7,0,-1,-4,-14,-3,-4,-7,-6,-6,-8,7,-2,-14,-6,-4,-3,-12,-9,-9,-2,-4,-5,-17],[-5,-4,-9,-11,-13,-4,-7,-8,-10,-1,1,-2,11,-4,-8,-5,-4,-13,-11,-1,-10,-5,-5,-17],[-8,-9,-9,-15,-13,-13,-14,-9,-6,-2,-3,-14,-4,9,-10,-6,-9,-4,2,-8,-10,-13,-8,-17],[-2,-4,-6,-8,-8,-3,-5,-6,-4,-8,-7,-6,-8,-10,8,-2,-4,-14,-13,-6,-7,-4,-5,-17],[0,-3,0,-4,-3,-5,-4,-2,-6,-7,-8,-4,-5,-6,-2,6,0,-5,-7,-6,-1,-5,-3,-17],[-1,-6,-2,-5,-8,-5,-6,-6,-7,-2,-7,-3,-4,-9,-4,0,7,-13,-6,-3,-3,-6,-4,-17],[-13,-2,-8,-15,-15,-13,-17,-15,-7,-14,-6,-12,-13,-4,-14,-5,-13,13,-5,-15,-10,-14,-11,-17],[-8,-10,-4,-11,-4,-12,-8,-14,-3,-6,-7,-9,-11,2,-13,-7,-6,-5,10,-7,-6,-9,-7,-17],[-2,-8,-8,-8,-6,-7,-6,-5,-6,2,-2,-9,-1,-8,-6,-6,-3,-15,-7,7,-8,-6,-5,-17],[-3,-7,6,6,-12,-3,1,-3,-1,-6,-9,-2,-10,-10,-7,-1,-3,-10,-6,-8,6,0,-5,-17],[-3,-4,-3,1,-14,6,6,-5,-1,-6,-7,-4,-5,-13,-4,-5,-6,-14,-9,-6,0,6,-5,-17],[-3,-6,-3,-5,-9,-5,-5,-5,-5,-5,-6,-5,-5,-8,-5,-3,-4,-11,-7,-5,-5,-5,-5,-17],[-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-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-11.1,-11.1,-9,-6.9,-8.2,-9.1,-14,-11.4,-12.3,-12.1,-3.1,.2,-3.2,-2.2,-10.4,-9.1,-10.4,-11.5,-2.1,1.2,-1.1,-1.4,-9.4,-5.6,-8.1,-8,8.6,12.4,8.6,9.5,-50,-10.4,-50,-11.6,-7.2,-5.7,-7.5,-7.4,-50,-8.6,-15.7,-9.7,-3,-3.7,-3.2,-5.9],[-11.1,-11.9,-10.6,-11.3,-2.6,-4.1,-1.7,-3.5,-11.4,-9.6,-9.6,-9.2,3.7,2.5,1.6,2.5,-9.6,-12.3,-9.5,-11.8,-8,-9.4,-7.2,-9.3,-13.3,-12.8,-10.9,-12.6,-1.8,-2.9,-.8,-2.9,-8.6,-13,-7.4,-12.4,-.4,-2.3,1.3,-2,-8.1,-9.3,-5.4,-8.4,10,8.6,11.4,8.9,-50,-13.7,-50,-13.2,-6.1,-8.1,-5.5,-7.5,-50,-11.3,-12.7,-10.1,-1.6,-7.8,-.3,-7.2],[-11.4,-10,-12.7,-8.2,-3.1,-3.1,-2.8,-.9,-11.7,-7.3,-12.1,-5.8,3.6,3.6,-1.1,5.8,-9.4,-11.9,-10.7,-10,-8.5,-8.8,-8.2,-6.5,-13.9,-13,-12.9,-10.9,-3.1,-2.3,-3.2,-.2,-9.5,-10.8,-10.2,-8.2,-1.1,-1.3,-.8,1.2,-8.6,-7.8,-7.8,-5,9,9.5,8.9,12,-50,-13,-50,-10.3,-6.2,-7,-7.1,-5.4,-50,-9.3,-14,-8.2,-2.4,-6.3,-2.4,-3.9],[-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,33.3,-50,30.6,-50,-50,-50,-50,-50,29.2,-50,-50,-50,-50,-50,-50,-50],[-14.8,-6.2,-14.9,-7.6,-14.6,-11.6,-13,-12.2,-14,-9,-14.1,-10.1,-13.6,-11.2,-12.4,-12.5,-8.1,2.2,-8.7,.4,-15.3,-11.3,-13.2,-13.3,-11.9,-7.2,-11.8,-7.9,-10.7,-7.4,-10.8,-8.9,-15.5,-10.3,-15.5,-12.5,-14.5,-12.1,-11.9,-12.8,-18.3,-12.7,-16.4,-14.7,-14.2,-10.4,-13.7,-13,-50,15.1,-50,13.3,-9.9,-5.8,-8.9,-7.6,-50,-1.5,-7.8,-3,-8.1,3.6,-9.4,2],[-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,30.6,-50,35.2,-50,-50,-50,-50,-50,28.5,-50,-50,-50,-50,-50,-50,-50],[-13.8,-7.5,-14.4,-5.1,-12.6,-11.6,-11.5,-10.1,-13.2,-9.7,-12.7,-7.4,-11.9,-11.9,-11.5,-10.2,-7.2,.9,-8.6,2.6,-14.1,-12.8,-13.3,-11,-9.7,-8.4,-11.2,-5.3,-9.3,-8.7,-9.9,-7.1,-13.9,-11.2,-14.2,-8.9,-12.9,-12.6,-12.6,-10.9,-15.4,-13.8,-14.8,-11.4,-12.8,-11.6,-13.2,-10.3,-50,13.3,-50,15.2,-8.6,-7,-8.4,-4.8,-50,-3,-7.1,-.1,-7.3,2.3,-8.7,3.9],[-7.3,-6.3,-8.9,-5.5,2.9,.2,1.5,1.2,-8.5,-2.3,-10,-1.7,-5.6,-10.5,-5.5,-9.6,-4.3,-7.9,-6.1,-7.2,2.3,-.6,.5,-0,-8.9,-11,-9.4,-9.3,-4.6,-9.4,-7.3,-8.1,-7.8,-9.8,-8.9,-9.2,2.8,.1,1.2,.8,-5.9,-6.8,-5.9,-6.3,-4.1,-7.2,-6.1,-6.2,-50,-9.9,-50,-8.6,12.5,9.4,11,9.8,-50,-4.8,-8.7,-3.5,-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,-50,-50,-50,-50,33.3,-50,-50,-50,-50,-50,-50,-50],[-13,-7,-13.1,-8.3,-9.2,-6.5,-8.9,-7.6,-9.8,-.7,-9.2,-2.1,-12.4,-10.3,-12.4,-11.6,-9.5,-4.6,-10.4,-5.7,-13.6,-10.1,-11.4,-10.9,-6.5,-1.5,-6.2,-3.6,-12.8,-8,-12.3,-9.7,-16.5,-12.7,-15.6,-14.3,-8.7,-6,-7.1,-7.5,-9.5,-4.1,-8.4,-6.1,-11,-8.6,-11.3,-9.3,-50,-1.5,-50,-3,-4.8,-1.5,-4.2,-3.1,-50,16.4,-5.1,14.2,-10.1,-4.3,-10,-5.4],[-13.5,-16.3,-11.8,-15.5,-13.6,-15.3,-12.1,-16.1,-7.7,-13.3,-4.2,-12.6,-14.1,-16.2,-10.3,-15.4,-9.6,-11.6,-7.7,-9.8,-14.3,-17.5,-11.1,-17.2,-5.3,-7.1,-2.2,-7.1,-9.6,-11.9,-8.7,-11.4,-17.1,-20.6,-15.3,-19.9,-14.1,-14.8,-12.4,-16.5,-11.7,-12.8,-6.4,-13.4,-14.3,-15.7,-12.7,-14,-50,-7.8,-50,-7.1,-8.7,-11.3,-6.1,-11.4,-50,-5.1,18.6,-4.8,-8.6,-8.1,-4.5,-7.3],[-12.4,-8.2,-13,-5.9,-7.7,-7.8,-7.4,-5.8,-8.8,-2,-9.3,-.4,-11.6,-11.3,-11.6,-9.4,-8.9,-5.6,-10,-3.2,-11.5,-11.1,-10.5,-8.3,-6.3,-4.9,-6.7,-1.2,-10.6,-9.7,-11.3,-8,-14.8,-13.1,-15.5,-11.4,-7.5,-7.5,-7.1,-5.9,-8.4,-5.8,-8.1,-3.6,-9.9,-9.7,-10.1,-8.2,-50,-3,-50,-.1,-3.5,-3.3,-3.6,-.7,-50,14.2,-4.8,16.4,-8.9,-5.8,-8.9,-3.4],[-10.7,-13.2,-12.4,-11.6,-4.8,-8.4,-6.1,-7.2,-10.3,-11.8,-11,-11.6,2.8,-1.7,.7,-1.1,-6.2,-9.7,-7.3,-8.4,-5.3,-8.6,-6.1,-8.3,-10.5,-11.2,-9.8,-10.2,9.5,6.5,7.6,6.8,-12.1,-16,-13,-16.2,-5.2,-8.6,-7.1,-7.8,-12.5,-14.4,-12.1,-13,1.4,-3,-1.6,-2.4,-50,-8.1,-50,-7.3,-0,-5.4,-3.5,-4.6,-50,-10.1,-8.6,-8.9,13.2,-.9,9.7,-.3],[-18.1,-12.3,-19.4,-14.2,-12.2,-9.5,-11.5,-10.8,-17.9,-11.9,-18.2,-13.9,-6.4,-3.7,-6.8,-5.4,-12.8,-5.9,-13.6,-7.4,-13.7,-9.9,-12.9,-12.7,-16.2,-11.6,-15.2,-12.7,-3.2,.5,-3.3,-1.8,-18.9,-16.6,-18.8,-19.2,-12.5,-9.4,-10.6,-11.1,-17.3,-14.1,-16.2,-16,-7.9,-3.7,-7.8,-6.3,-50,3.6,-50,2.3,-8.6,-4.2,-8.4,-6.6,-50,-4.3,-8.1,-5.8,-.9,14.2,-1.8,11.6],[-11.8,-13.1,-11.5,-12,-6.2,-8.3,-5.4,-7.4,-11.8,-12.3,-11.1,-11.4,.5,-2.5,2.4,-1.6,-6.8,-9.9,-6.4,-8.9,-6.1,-8.6,-5,-7.8,-10.4,-11.6,-8.5,-9.9,8.2,6.4,8.7,6.9,-12.4,-17,-12.6,-15.8,-6.5,-8.5,-5,-7.8,-13.2,-13.6,-10.3,-13.7,-.7,-3.2,-.3,-2.4,-50,-9.4,-50,-8.7,-2.1,-5.6,-1.2,-4.9,-50,-10,-4.5,-8.9,9.7,-1.8,11.3,-.9],[-17.2,-13.3,-17.8,-11.6,-11,-11.1,-10.4,-9,-16,-12.7,-16.1,-11.1,-5.2,-5.4,-6,-3.3,-11.8,-7.3,-13.3,-5.9,-12.7,-11.9,-11.9,-9.3,-15.2,-15,-14.9,-11,-2.8,-1.8,-2.9,.4,-17.4,-18.4,-18.3,-15.9,-10.7,-11.2,-10.6,-9,-15.4,-14.8,-15.8,-13.3,-6.8,-5.9,-7.2,-3.9,-50,2,-50,3.9,-7,-6.8,-6.8,-3.9,-50,-5.4,-7.3,-3.4,-.3,11.6,-.9,14.1]],this.TRANS=[[5,0,0,4],[0,5,4,0],[0,4,5,0],[4,0,0,5]],this.CONBLO={A:0,R:1,N:2,D:3,C:4,Q:5,E:6,G:7,H:8,I:9,L:10,K:11,M:12,F:13,P:14,S:15,T:16,W:17,Y:18,V:19,B:20,Z:21,X:22,"*":23},this.CONNUCL={A:0,T:1,C:2,G:3},this.CONSCHN={AAA:0,AAC:1,AAG:2,AAT:3,ACA:4,ACC:5,ACG:6,ACT:7,AGA:8,AGC:9,AGG:10,AGT:11,ATA:12,ATC:13,ATG:14,ATT:15,CAA:16,CAC:17,CAG:18,CAT:19,CCA:20,CCC:21,CCG:22,CCT:23,CGA:24,CGC:25,CGG:26,CGT:27,CTA:28,CTC:29,CTG:30,CTT:31,GAA:32,GAC:33,GAG:34,GAT:35,GCA:36,GCC:37,GCG:38,GCT:39,GGA:40,GGC:41,GGG:42,GGT:43,GTA:44,GTC:45,GTG:46,GTT:47,TAA:48,TAC:49,TAG:50,TAT:51,TCA:52,TCC:53,TCG:54,TCT:55,TGA:56,TGC:57,TGG:58,TGT:59,TTA:60,TTC:61,TTG:62,TTT:63},this.setMethod(s),this.setSequences(e,t),this.setGap(n)}}},7983:(e,t,n)=>{"use strict";n.d(t,{HV:()=>p,QF:()=>m,pf:()=>d,uH:()=>h});var s=n(4469),r=n(3870),i=n(976),o=n(7241),a=n(4293),l=n(8467),c=n(8447);const u="substr_helm";class h{constructor(e){this.col=e[0],this.createUI()}editHelmLinkAction(){(0,a.Y)(this.inputsDiv,this.grid.root),r.tools.waitForElementInDom(this.grid.root).then((()=>{setTimeout((()=>{this.grid.cell(u,0).element.children[0].dispatchEvent(new KeyboardEvent("keydown",{key:"Enter"}))}),100)}))}updateInputs(){const e=this.units===c.r2.HELM?r.divV([this.columnsInput,this.editHelmLink]):this.units===c.r2.SEPARATOR?r.inputs([this.columnsInput,this.substructureInput,this.separatorInput]):r.inputs([this.columnsInput,this.substructureInput]);(0,a.Y)(this.inputsDiv,e)}updateNotationDiv(){this.units=this.col.getTag(i.TAGS.UNITS),this.separator=this.col.getTag("separator");const e=this.dialog.root.getElementsByClassName("notation-text")[0];e&&(e.textContent=`Notation: ${this.units}`)}createUI(){const e=s.shell.tv.dataFrame,t={filter:e=>e.semType===i.SEMTYPE.MACROMOLECULE};this.columnsInput=r.columnInput("Column",e,this.col,(e=>{this.col=e,this.updateNotationDiv(),this.updateInputs()}),t),this.substructureInput=r.stringInput("Substructure",""),this.editHelmLink=r.link("Edit helm",(()=>this.editHelmLinkAction()),void 0,{style:{position:"relative",left:"95px"}});const n=i.DataFrame.create(1);n.columns.addNewString(u).init((e=>"")),n.col(u).semType=this.col.semType,n.col(u).setTag(i.TAGS.UNITS,c.r2.HELM),this.grid=n.plot.grid(),this.separatorInput=r.stringInput("Separator",this.separator),this.inputsDiv=r.div(),this.units=this.col.getTag(i.TAGS.UNITS),this.separator=this.col.getTag("separator"),this.updateInputs(),this.dialog=r.dialog("Substructure Search").add(r.divV([r.divText(`Notation: ${this.units}`,"notation-text"),this.inputsDiv])).onOK((async()=>{let e,t=this.units===c.r2.HELM?n.get(u,0):this.substructureInput.value;this.units===c.r2.SEPARATOR&&this.separatorInput.value!==this.separator&&""!==this.separatorInput.value&&(t=t.replaceAll(this.separatorInput.value,this.separator)),e=this.units===c.r2.HELM?await m(t,this.col):d(t,this.col),this.col.dataFrame.filter.and(e)})).show()}}function d(e,t,n){const s=n?function(e,t){const n=`${t}`.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),s=e.charAt(0)===t,r=e.charAt(e.length-1)===t,i=e.replace(new RegExp(`^${n}|${n}$`,"g"),"");return s?r?`${n}${i}${n}`:`${n}${i}${n}|${n}${i}$`:r?`^${i}${n}|${n}${i}${n}`:`^${i}${n}|${n}${i}${n}|${n}${i}$`}(e,n):e,r=i.BitSet.create(t.length);for(let n=0;n<t.length;n++){const i=t.get(n);(i.match(s)||i===e)&&r.set(n,!0,!1)}return r}async function m(e,t){t.version!==t.temp["last-invalidated-version"]&&await p(t,!0);const n=i.Column.string("helm",1).init((t=>e));n.semType=i.SEMTYPE.MACROMOLECULE,n.setTag(i.TAGS.UNITS,c.r2.HELM);const r=await(0,o.D)(n,!0,t.temp["monomers-dict"]);return(await s.functions.call("Chem:searchSubstructure",{molStringsColumn:t.temp["monomeric-mols"],molString:r.get(0),molBlockFailover:""})).get(0)}async function p(e,t){const n=i.TaskBarProgressIndicator.create(`Invalidating molfiles for ${e.name}`);try{await(0,l.gw)(10);const n=new Map,s=await(0,o.D)(e,t,n);e.temp["monomeric-mols"]=s,e.temp["monomers-dict"]=n,e.temp["last-invalidated-version"]=e.version}finally{n.close()}}},2568:(e,t,n)=>{"use strict";n.d(t,{n:()=>o});var s=n(4469),r=n(976),i=n(8260);function o(e,t,n=[],o=[],a=!0){const[l,c]=function(e,t,n=[],o=[]){let a=!0,l="";const c=i.g.forColumn(e);if(e.semType!==r.SEMTYPE.MACROMOLECULE)s.shell.warning(t+" analysis is allowed for Macromolecules semantic type"),a=!1;else{const e=c.notation;if(n.length>0&&!n.some((t=>e.toUpperCase()==t.toUpperCase())))l=`${t} + ' analysis is allowed for Macromolecules with notation ${0==n.length?"any notation":`notation${n.length>1?"s":""} ${n.map((e=>`"${e}"`)).join(", ")} `}.`,a=!1;else if(!c.isHelm()){const e=c.alphabet;o.length>0&&!o.some((t=>e.toUpperCase()==t.toUpperCase()))&&(l=`${t} + ' analysis is allowed for Macromolecules with alphabet ${0==o.length?"any alphabet":`alphabet${o.length>1?"s":""} ${o.map((e=>`"${e}"`)).join(", ")}.`}.`,a=!1)}}return[a,l]}(e,t,n,o);return a&&!l&&s.shell.warning(c),l}},3553:(e,t,n)=>{"use strict";n.d(t,{Of:()=>i,WY:()=>c,jB:()=>u,rs:()=>a});var s,r,i,o,a,l=n(8341);!function(e){e.SPLIT_COL="~split",e.ACTIVITY="~activity",e.ACTIVITY_SCALED="activity_scaled",e.ALIGNED_SEQUENCE="~aligned_sequence",e.AMINO_ACID_RESIDUE="AAR",e.POSITION="Pos",e.P_VALUE="pValue",e.MEAN_DIFFERENCE="Mean difference"}(s||(s={})),function(e){e.AAR="AAR",e.POSITION="Pos",e.SELECTION="selection"}(r||(r={})),function(e){e.MONOMER="Monomer",e.MACROMOLECULE_DIFFERENCE="MacromoleculeDifference",e.ACTIVITY="activity",e.ACTIVITY_SCALED="activityScaled"}(i||(i={})),function(e){e.CELL_CHANGING="isCellChanging"}(o||(o={})),function(e){e.SEPARATOR="."}(a||(a={}));const c="3.3.1",u={pepsea:{gapOpen:1.53,gapExtend:0,method:l.Jy[0]},kalign:{gapOpen:-1,gapExtend:-1,terminalGap:-1}}},4004:(e,t,n)=>{"use strict";n.d(t,{O:()=>d});var s=n(976),r=n(3870),i=n(4469),o=n(3336),a=n.n(o),l=n(8447),c=n(8260);let u=null,h=[];function d(e){let t=e??i.shell.t.columns.bySemType("Macromolecule");if(!t)throw new Error("No column with Macromolecule semantic type found");let n=c.g.forColumn(t),o=n.notation;const d=r.divText("Current notation: "+o,{style:{"text-align":"center","font-weight":"bold","font-size":"14px",padding:"5px"}}),m=[l.r2.FASTA,l.r2.SEPARATOR,l.r2.HELM],p=r.columnInput("Column",i.shell.t,t,(e=>{e.semType===s.SEMTYPE.MACROMOLECULE?(t=e,n=c.g.forColumn(t),o=n.notation,o===l.r2.HELM&&(y.value="/"),d.textContent="Current notation: "+o,g=m.filter((e=>e!==o)),v=r.choiceInput("Convert to",g[0],g,b),b(),u?.clear(),u?.add(r.div([d,p.root,v.root,y.root]))):p.value=t})),f=["-",".","/"];let g=m.filter((e=>e!==o));const y=r.choiceInput("Separator",f[0],f),b=()=>{v.value!==l.r2.SEPARATOR?a()(y.root).hide():a()(y.root).show()};let v=r.choiceInput("Convert to",g[0],g,b);b(),v.onChanged((()=>{b()})),null==u&&(u=r.dialog("Convert Sequence Notation").add(r.div([d,p.root,v.root,y.root])).onOK((async()=>{const e=v.value,n=y.value??void 0;await async function(e,t,n){const s=c.g.forColumn(e).convert(t,n);e.dataFrame.columns.add(s);const r=await i.functions.call("Bio:detectMacromolecule",{col:s});return r&&(s.semType=r),await i.data.detectSemanticTypes(e.dataFrame),s}(t,e,n)})).show({x:350,y:100}),h.push(u.onClose.subscribe((e=>{h.forEach((e=>{e.unsubscribe()})),h=[],u=null}))))}},6032:(e,t,n)=>{"use strict";n.d(t,{Ns:()=>o});var s=n(4469),r=n(8467),i=n(8341);async function o(e=6e4){const t=await i.lp.getDockerContainer();await async function(e,t=6e4){let n=e,i=!1;for(let o=0;o<t/200;++o){if(null===n&&(n=await s.dapi.docker.dockerContainers.find(e.id)),a(n)){i=!0;break}switch(n.status){case"stopped":await s.dapi.docker.dockerContainers.run(n.id);break;case"pending change":case"changing":break;case"error":throw new Error("Docker container error state.")}n=null,await(0,r.gw)(200)}if(!i)throw new Error("Docker container start timeout.")}(t,e)}function a(e){return"checking"===e.status||"started"===e.status}},7572:(e,t,n)=>{"use strict";n.d(t,{A:()=>u});var s=n(4469),r=n(6584),i=n(2961),o=n(3776),a=n(2428),l=n(3649);async function c(){const e=a.A.getInstance();return(await o.t.getInstance(e)).getValidLibraryPaths()}class u{constructor(){this._monomerLib=new i.B({},"MAIN"),this.loadLibrariesPromise=Promise.resolve()}getBioLib(){return this._monomerLib}async loadLibraries(e=!1){return this.loadLibrariesPromise=this.loadLibrariesPromise.then((async()=>{try{const[t,n]=await Promise.all([c(),(0,r.nW)()]),s=t.filter((e=>{const t=!n.exclude.includes(e),s=0===n.explicit.length||n.explicit.includes(e);return t&&s})),o=await Promise.all(s.map((e=>this.readLibrary(r.BX,e).catch((t=>{const n=`Loading monomers from '${e}' error: ${t instanceof Error?t.message:t.toString()}`;return new i.B({},e,n)})))));this._monomerLib.updateLibs(o,e)}catch(e){const t=`Loading monomer libraries error: ${e instanceof Error?e.message:e.toString()}`;s.shell.warning(t);const n=e instanceof Error?e.stack:void 0;l._package.logger.error(t,void 0,n)}}))}async readLibrary(e,t){const n=a.A.getInstance(),s=await o.t.getInstance(n);return await s.loadLibraryFromFile(e,t)}async selectSpecifiedLibraries(e){const t=await this.getInvalidFileNames(e);if(t.length>0)throw new Error(`Cannot select libraries ${t}: no such library in the list`);const n=await(0,r.nW)();n.exclude=(await c()).filter((t=>!e.includes(t))),await(0,r.tW)(n)}async getInvalidFileNames(e){const t=await c();return e.filter((e=>!t.includes(e)))}static get instance(){return window.$monomerLibHelper||(window.$monomerLibHelper=new u),window.$monomerLibHelper}}},2428:(e,t,n)=>{"use strict";n.d(t,{A:()=>i});var s=n(701),r=n(442);class i{constructor(){this._libraryFilesUpdateSubject$=new s.BehaviorSubject([]),this._addLibraryFilesSubject$=new s.Subject,this._librarySelectionSubject$=new s.Subject}static getInstance(){return i._instance||(i._instance=new i),i._instance}getValidFilesPathList(){return this._libraryFilesUpdateSubject$.getValue()}async getValidLibraryPathsAsynchronously(){return new Promise((e=>{this._libraryFilesUpdateSubject$.pipe((0,r.skip)(1)).subscribe((t=>{e(t)}))}))}changeValidFilesPathList(e){this._libraryFilesUpdateSubject$.next(e)}get updateUIControlsRequested$(){return this._libraryFilesUpdateSubject$.pipe()}get updateValidLibraryFileListRequested$(){return this._libraryFilesUpdateSubject$.pipe()}get addLibraryFileRequested$(){return this._addLibraryFilesSubject$.pipe()}addLibraryFile(){this._addLibraryFilesSubject$.next()}get librarySelectionRequested$(){return this._librarySelectionSubject$}updateLibrarySelectionStatus(e,t){this._librarySelectionSubject$.next([e,t])}}},3776:(e,t,n)=>{"use strict";n.d(t,{t:()=>m});var s=n(4469),r=n(976),i=n(6584),o=n(2961),a=n(5128),l=n.n(a),c=n(3351),u=n.n(c);class h{constructor(e){this.helmMonomerSchema=e;const t=new(l())({allErrors:!0,strictTuples:!1});u()(t),this.validateMonomerSchema=t.compile(this.helmMonomerSchema)}validateFile(e,t){const n=this.parseJson(e);return null!==n&&(Array.isArray(n)?this.validateJsonContent(n,t):(console.warn("Bio: Monomer Library File Validator: Invalid JSON format: The file must contain an array of monomers."),!1))}parseJson(e){try{return JSON.parse(e)}catch(e){return console.error("Bio: Monomer Library File Validator: Invalid JSON format:",e),null}}validateJsonContent(e,t){let n=!0;for(const s of e)if(n=this.validateMonomerSchema(s),!n){console.warn(`Bio: Monomer Library File Validator:\nfile ${t}\n monomer violating JSON schema:`,s,"\nError reason: ",this.validateMonomerSchema.errors,`\nThere may be other errors in ${t} since the validation is stopped after the first error.`," Please, verify that the monomer library file satisfies the JSON schema");break}return n}}var d=n(7572);class m{constructor(e,t){this.libraryFileValidator=e,this.libraryEventManager=t,this.libraryEventManager.updateValidLibraryFileListRequested$.subscribe((async()=>{await this.updateValidLibraryList()}))}static async getInstance(e){return m.instancePromise||(m.instancePromise=(async()=>{const t=await s.dapi.files.readAsText("System:AppData/Bio/tests/libraries/HELMmonomerSchema.json"),n=JSON.parse(t),r=new h(n);return new m(r,e)})()),m.instancePromise}async addLibraryFile(e,t){try{if(await this.libraryFileExists(t))return void s.shell.error(`File ${t} already exists`);await this.validateAgainstHELM(e,t),await s.dapi.files.writeAsText(i.BX+`${t}`,e),await this.updateValidLibraryList(),await s.dapi.files.exists(i.BX+`${t}`)?s.shell.info(`Added ${t} HELM library`):s.shell.error(`Failed to add ${t} library`)}catch(e){console.error(e),s.shell.error(`Failed to add ${t} library`)}}async deleteLibraryFile(e){try{await s.dapi.files.delete(i.BX+`${e}`),await this.updateValidLibraryList(),s.shell.info(`Deleted ${e} library`)}catch(t){console.error(t),await s.dapi.files.exists(i.BX+`${e}`)?s.shell.error(`Failed to delete ${e} library`):s.shell.warning(`File ${e} already deleted, refresh the list`)}}async loadLibraryFromFile(e,t){let n=[];const s=new r.FileSource(e),i=await s.readAsText(t);n=JSON.parse(i);const a={},l=[];return n.forEach((e=>{l.includes(e.polymerType)||(a[e.polymerType]={},l.push(e.polymerType)),a[e.polymerType][e.symbol]=e})),new o.B(a,t)}getValidLibraryPaths(){return this.libraryEventManager.getValidFilesPathList()}async getValidLibraryPathsAsynchronously(){return await this.libraryEventManager.getValidLibraryPathsAsynchronously()}async libraryFileExists(e){return await s.dapi.files.exists(i.BX+`${e}`)}async updateValidLibraryList(){const e=[],t=await this.getFilePathsAtDefaultLocation();if(!this.fileListHasChanged(t))return;for(const n of t){if(!n.endsWith(".json")){e.push(n);continue}const t=await s.dapi.files.readAsText(i.BX+`${n}`);this.isValidHELMLibrary(t,n)||e.push(n)}const n=t.filter((t=>!e.includes(t)));if(this.fileListHasChanged(n)&&(this.libraryEventManager.changeValidFilesPathList(n),d.A.instance.loadLibraries(!0)),n.some((e=>!e.endsWith(".json")))&&console.warn(`Wrong validation: ${n}`),e.length>0){const t=`Invalid monomer library files in ${i.BX}, consider fixing or removing them: ${e.join(", ")}`;console.warn(t)}}fileListHasChanged(e){const t=this.libraryEventManager.getValidFilesPathList();return e.length!==t.length||e.some(((e,n)=>e!==t[n]))}async validateAgainstHELM(e,t){if(!this.isValidHELMLibrary(e,t))throw new Error(`File ${t} does not satisfy HELM standard`)}isValidHELMLibrary(e,t){return this.libraryFileValidator.validateFile(e,t)}async getFilePathsAtDefaultLocation(){const e=(await s.dapi.files.list(i.BX)).map((e=>e.fullPath)),t=[];for(const n of e)await s.dapi.files.exists(n)&&t.push(n);return t.map((e=>e.substring(i.BX.length)))}}},2961:(e,t,n)=>{"use strict";n.d(t,{B:()=>C});var s=n(4469),r=n(3870),i=n(701),o=n(4067),a=n(3379),l=n.n(a),c=n(7795),u=n.n(c),h=n(569),d=n.n(h),m=n(3565),p=n.n(m),f=n(9216),g=n.n(f),y=n(4589),b=n.n(y),v=n(8277),w={};w.styleTagTransform=b(),w.setAttributes=p(),w.insert=d().bind(null,"head"),w.domAPI=u(),w.insertStyleElement=g(),l()(v.Z,w),v.Z&&v.Z.locals&&v.Z.locals;class C{constructor(e,t=undefined,n=undefined){this.source=t,this.error=n,this._monomers={},this._onChanged=new i.Subject,this._monomers=e;for(const[e,t]of Object.entries(this._monomers))for(const[e,n]of Object.entries(t))n.lib=this}getMonomer(e,t){return e in this._monomers&&t in this._monomers[e]?this._monomers[e][t]:null}getPolymerTypes(){return Object.keys(this._monomers)}getMonomerMolsByPolymerType(e){const t={};return Object.keys(this._monomers[e]??{}).forEach((n=>{t[n]=this._monomers[e][n].molfile})),t}getMonomerSymbolsByType(e){return Object.keys(this._monomers[e])}getMonomerSymbolsByRGroup(e,t,n){let s=this.getMonomerSymbolsByType(t).map((e=>this.getMonomer(t,e)));return s=s.filter((e=>null!==e)),0===s.length?[]:(s=s.filter((t=>{if(!t?.rgroups)return!1;let n=t?.rgroups.length>=e;return o._.getInstance(t.molfile).atomTypes.map(((e,t)=>"R#"===e?t:-1)).filter((e=>-1!==e)),n&&(n=!0),n})),s.map((e=>e?.symbol)))}get onChanged(){return this._onChanged}_updateInt(e){const t=e.getPolymerTypes(),n=this.getPolymerTypes();t.forEach((t=>{n.includes(t)||(this._monomers[t]={}),e.getMonomerSymbolsByType(t).forEach((n=>{this._monomers[t][n]=e.getMonomer(t,n)}))}))}update(e){this._updateInt(e),this._onChanged.next()}updateLibs(e,t=!1){t&&(this._monomers={});for(const t of e)t.error||this._updateInt(t);this._onChanged.next()}clear(){this._monomers={},this._onChanged.next()}getTooltip(e,t){const n=r.div([],{classes:"ui-form ui-tooltip"}),i=this.getMonomer(e,t);if(i){const e=e=>r.label(e,{classes:"ui-input-label"});n.append(r.div([e("Name"),r.divText(i.name,{classes:"ui-input-text"})],{classes:"ui-input-root"}));const t={autoCrop:!0,autoCropMargin:0,suppressChiralText:!0};i.molfile?n.append(r.div([e("Mol file"),s.chem.svgMol(i.molfile,void 0,void 0,t)],{classes:"ui-input-root"})):i.smiles?n.append(r.div([e("Smiles"),s.chem.svgMol(i.smiles,void 0,void 0,t)],{classes:"ui-input-root"})):n.append(r.div([e("No structure")],{classes:"ui-input-root"})),n.append(r.div([e("Source"),r.divText(i.lib?.source??"unknown",{classes:"ui-input-text"})],{classes:"ui-input-root"}))}else n.append(r.divText("Monomer not found"));return n}}},525:(e,t,n)=>{"use strict";n.d(t,{K:()=>M});var s=n(4469),r=n(976),i=n(3870),o=n(8447),a=n(8260),l=n(6098),c=n(8341),u=n(2568),h=n(3553),d=n(6032),m=n(3649),p=n(3379),f=n.n(p),g=n(7795),y=n.n(g),b=n(569),v=n.n(b),w=n(3565),C=n.n(w),S=n(9216),A=n.n(S),x=n(4589),E=n.n(x),I=n(9564),T={};T.styleTagTransform=E(),T.setAttributes=C(),T.insert=v().bind(null,"head"),T.domAPI=y(),T.insertStyleElement=A(),f()(I.Z,T),I.Z&&I.Z.locals&&I.Z.locals;class _ extends Error{constructor(e,t){super(e,t)}}async function M(e={}){return new Promise((async(t,n)=>{var o,a,l;e.clustersCol??(e.clustersCol=null),e.pepsea??(e.pepsea={}),(o=e.pepsea).method??(o.method=h.jB.pepsea.method),(a=e.pepsea).gapOpen??(a.gapOpen=h.jB.pepsea.gapOpen),(l=e.pepsea).gapExtend??(l.gapExtend=h.jB.pepsea.gapExtend);const u=e.col?.dataFrame??s.shell.t,d=e.col??u.columns.bySemType(r.SEMTYPE.MACROMOLECULE);if(null==d){const e="MSAError: dataset doesn't conain any Macromolecule column";s.shell.warning(e),n(new _(e))}const m=i.choiceInput("Method",e.pepsea.method,c.Jy);m.setTooltip("Alignment method");const p=i.floatInput("Terminal gap",e?.kalign?.terminalGap??null);p.setTooltip("Penalty for opening a gap at the beginning or end of the sequence");const f=i.p(`Kalign version: ${h.WY}`,"kalign-version"),g=i.floatInput("Gap open",e.pepsea.gapOpen);g.setTooltip("Gap opening penalty at group-to-group alignment");const y=i.floatInput("Gap extend",e.pepsea.gapExtend);y.setTooltip("Gap extension penalty to skip the alignment");const b=i.inputs([g,y,p]),v=i.button("Alignment parameters",(()=>{b.hidden=!b.hidden,[g,y,p].forEach((e=>{e.root.style.removeProperty("max-width"),e.captionLabel.style.removeProperty("max-width")}))}),"Adjust alignment parameters such as penalties for opening and extending gaps");v.classList.add("msa-params-button"),b.hidden=!0,v.prepend(i.icons.settings((()=>null)));const w=[m.root.style],C=[p.root.style,f.style];let S;const A=i.columnInput("Sequence",u,d,(async()=>{S=await N(A.value,u,w,C,m,x,g,y,p)}),{filter:e=>e.semType===r.SEMTYPE.MACROMOLECULE});A.setTooltip("Sequences column to use for alignment");const x=i.columnInput("Clusters",u,e.clustersCol);if(x.nullable=!0,A.fireChanged(),e.col)return S=await N(e.col,u,w,C,m,x,g,y,p),void await $(A,u,S,t,n);i.dialog("MSA").add(A).add(x).add(m).add(b).add(v).add(f).onOK((async()=>{await $(A,u,S,t,n)})).show()}))}async function $(e,t,n,i,o){let a=null;const l=r.TaskBarProgressIndicator.create("Analyze for MSA ...");try{if(e.fireChanged(),e.value.semType!==r.SEMTYPE.MACROMOLECULE)throw new Error("Chosen column has to be of Macromolecule semantic type");if(void 0===n)throw new Error("Invalid column format");if(a=await n(),null==a)return o("PepSeA container has not started");t.columns.add(a),await s.data.detectSemanticTypes(t),i(a)}catch(e){const t=e instanceof Error?e.message:e.toString();s.shell.error(t),o(e)}finally{l.close()}}async function N(e,t,n,i,p,f,g,y,b){try{if(e.semType!==r.SEMTYPE.MACROMOLECULE)return;const s=t.columns.getUnusedName(`msa(${e.name})`);if((0,u.n)(e,e.name,[o.r2.FASTA,o.r2.SEPARATOR],["DNA","RNA","PT"],!1)){L(n,i,"kalign"),g.value=null,y.value=null,b.value=null;const t=a.g.forColumn(e),r=t.isFasta()?e:t.convert(o.r2.FASTA);return async()=>await(0,l.U)(r,!1,s,f.value)}if((0,u.n)(e,e.name,[o.r2.HELM],[],!1))return L(n,i,"pepsea"),g.value??(g.value=h.jB.pepsea.gapOpen),y.value??(y.value=h.jB.pepsea.gapExtend),async()=>(await(0,d.Ns)(),(0,c.f3)(e,s,p.value,g.value,y.value,f.value));if((0,u.n)(e,e.name,[o.r2.SEPARATOR],["UN"],!1)){const t=a.g.forColumn(e).convert(o.r2.HELM);return L(n,i,"pepsea"),g.value??(g.value=h.jB.pepsea.gapOpen),y.value??(y.value=h.jB.pepsea.gapExtend),async()=>(await(0,d.Ns)(),(0,c.f3)(t,s,p.value,g.value,y.value,f.value))}return g.value=null,y.value=null,b.value=null,void L(n,i,"kalign")}catch(e){const t=e instanceof Error?e.message:e.toString();s.shell.error(t),m._package.logger.error(t)}}function L(e,t,n){if("kalign"===n){for(const t of e)t.display="none";for(const e of t)e.removeProperty("display")}else{for(const e of t)e.display="none";for(const t of e)t.removeProperty("display")}}},6098:(e,t,n)=>{"use strict";n.d(t,{U:()=>R});var s=n(976),r=n(5226);const i=Symbol("Comlink.proxy"),o=Symbol("Comlink.endpoint"),a=Symbol("Comlink.releaseProxy"),l=Symbol("Comlink.thrown"),c=e=>"object"==typeof e&&null!==e||"function"==typeof e,u=new Map([["proxy",{canHandle:e=>c(e)&&e[i],serialize(e){const{port1:t,port2:n}=new MessageChannel;return h(e,t),[n,[n]]},deserialize:e=>(e.start(),m(e))}],["throw",{canHandle:e=>c(e)&&l in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}}]]);function h(e,t=self){t.addEventListener("message",(function n(s){if(!s||!s.data)return;const{id:r,type:o,path:a}=Object.assign({path:[]},s.data),c=(s.data.argumentList||[]).map(w);let u;try{const t=a.slice(0,-1).reduce(((e,t)=>e[t]),e),n=a.reduce(((e,t)=>e[t]),e);switch(o){case"GET":u=n;break;case"SET":t[a.slice(-1)[0]]=w(s.data.value),u=!0;break;case"APPLY":u=n.apply(t,c);break;case"CONSTRUCT":u=function(e){return Object.assign(e,{[i]:!0})}(new n(...c));break;case"ENDPOINT":{const{port1:t,port2:n}=new MessageChannel;h(e,n),u=function(e,t){return b.set(e,t),e}(t,[t])}break;case"RELEASE":u=void 0;break;default:return}}catch(e){u={value:e,[l]:0}}Promise.resolve(u).catch((e=>({value:e,[l]:0}))).then((e=>{const[s,i]=v(e);t.postMessage(Object.assign(Object.assign({},s),{id:r}),i),"RELEASE"===o&&(t.removeEventListener("message",n),d(t))}))})),t.start&&t.start()}function d(e){(function(e){return"MessagePort"===e.constructor.name})(e)&&e.close()}function m(e,t){return f(e,[],t)}function p(e){if(e)throw new Error("Proxy has been released and is not useable")}function f(e,t=[],n=function(){}){let s=!1;const r=new Proxy(n,{get(n,i){if(p(s),i===a)return()=>C(e,{type:"RELEASE",path:t.map((e=>e.toString()))}).then((()=>{d(e),s=!0}));if("then"===i){if(0===t.length)return{then:()=>r};const n=C(e,{type:"GET",path:t.map((e=>e.toString()))}).then(w);return n.then.bind(n)}return f(e,[...t,i])},set(n,r,i){p(s);const[o,a]=v(i);return C(e,{type:"SET",path:[...t,r].map((e=>e.toString())),value:o},a).then(w)},apply(n,r,i){p(s);const a=t[t.length-1];if(a===o)return C(e,{type:"ENDPOINT"}).then(w);if("bind"===a)return f(e,t.slice(0,-1));const[l,c]=y(i);return C(e,{type:"APPLY",path:t.map((e=>e.toString())),argumentList:l},c).then(w)},construct(n,r){p(s);const[i,o]=y(r);return C(e,{type:"CONSTRUCT",path:t.map((e=>e.toString())),argumentList:i},o).then(w)}});return r}function g(e){return Array.prototype.concat.apply([],e)}function y(e){const t=e.map(v);return[t.map((e=>e[0])),g(t.map((e=>e[1])))]}const b=new WeakMap;function v(e){for(const[t,n]of u)if(n.canHandle(e)){const[s,r]=n.serialize(e);return[{type:"HANDLER",name:t,value:s},r]}return[{type:"RAW",value:e},b.get(e)||[]]}function w(e){switch(e.type){case"HANDLER":return u.get(e.name).deserialize(e.value);case"RAW":return e.value}}function C(e,t,n){return new Promise((s=>{const r=new Array(4).fill(0).map((()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16))).join("-");e.addEventListener("message",(function t(n){!n.data||!n.data.id||n.data.id!==r||(e.removeEventListener("message",t),s(n.data))})),e.start&&e.start(),e.postMessage(Object.assign({id:r},t),n)}))}const S="KGZ1bmN0aW9uKCl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ZSJscyI6cmV0dXJuIHQuZnMuaXNGaWxlKGkub2JqZWN0Lm1vZGUpP3QuZnMuc3RhdChyKTp0LmZzLnJlYWRkaXIocik7Y2FzZSJkb3dubG9hZCI6Y29uc3Qgcz1uZXcgQmxvYihbdGhpcy5jYXQocildKTtyZXR1cm4gVVJMLmNyZWF0ZU9iamVjdFVSTChzKX1yZXR1cm4hMX0sX2xvZyhlKXtpZighdC5jb25maWcuZGVidWcpcmV0dXJuO2xldCByPVsuLi5hcmd1bWVudHNdO3Iuc2hpZnQoKSxjb25zb2xlLmxvZyhgJWNbV2ViV29ya2VyXSVjICR7ZX1gLCJmb250LXdlaWdodDpib2xkIiwiIiwuLi5yKX19O3codCl9KSgpOwo=",A=typeof window<"u"&&window.Blob&&new Blob([atob(S)],{type:"text/javascript;charset=utf-8"});function x(){const e=A&&(window.URL||window.webkitURL).createObjectURL(A);try{return e?new Worker(e):new Worker("data:application/javascript;base64,"+S)}finally{e&&(window.URL||window.webkitURL).revokeObjectURL(e)}}const E={urlCDN:"https://biowasm.com/cdn/v3",urlCDNStg:"https://stg.biowasm.com/cdn/v3",dirShared:"/shared",dirMounted:"/mnt",dirData:"/data",printInterleaved:!0,callback:null,debug:!1,env:"prd"};class I{constructor(e,t={}){if(null==e)throw"Expecting array of tools as input to Aioli constructor.";return Array.isArray(e)||(e=[e]),t=Object.assign({},E,t),e=e.map(this._parseTool),"stg"===t.env&&(t.urlCDN=t.urlCDNStg),this.tools=e,this.config=t,null!=this.config.callback&&(this.callback=this.config.callback),delete this.config.callback,this.init()}async init(){const e=new x;this.callback&&(e.onmessage=e=>{"biowasm"===e.data.type&&this.callback(e.data.value)});const t=m(e);return t.tools=this.tools,t.config=this.config,await t.init(),t}_parseTool(e){if("string"!=typeof e)return e;const t=e.split("/");if(2!=t.length&&3!=t.length)throw"Expecting '<tool>/<version>' or '<tool>/<program>/<version>'";return{tool:t[0],program:3==t.length?t[1]:t[0],version:t[t.length-1]}}}var T=n(850);class _{static getAvailableScales(){return Object.entries(this.scales).map((([e,t])=>e))}static getScale(e){return(0,T.hu)(!(void 0===this.scales[e]),`Scale '${e}' was not found.`),this.scales[e]}}_.scales={WimleyWhite:{"-":0,A:.17,C:-.24,D:-.07,E:-.01,F:-1.13,G:.01,H:.17,I:-.31,K:.99,L:-.56,M:-.23,N:.42,P:.45,Q:.58,R:.81,S:.13,T:.14,V:.07,W:-1.85,Y:-.94},categorial:{"-":0,A:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,K:9,L:10,M:11,N:12,P:13,Q:14,R:15,S:16,T:17,V:18,W:19,Y:20}};class M{constructor(e="categorial"){this.aa2num=_.getScale(e),this.num2aa={},Object.entries(this.aa2num).forEach((([e,t])=>this.num2aa[t]=e))}static _truncateSequence(e){let t=0,n=e.length;const s=["NH2","COOH"];if(e.startsWith(s[0])){const n=s[0].length;(0,T.hu)("-"==e[n],`Wrong sequence format: ${s[0]} without following '-' in '${e}'.`),t=n}if(e.endsWith(s[1])){const t=s[1].length+1;(0,T.hu)("-"==e[n-t],`Wrong sequence format: ${s[1]} without '-' precending in '${e}'.`),n-=t}return e.substring(t,n)}static _dropDefises(e){return e.replace(/(-)([^-]+)/g,"$2")}static clean(e){return M._dropDefises(M._truncateSequence(e))}encode(e){const t=e.length,n=new Array(t).fill(0);for(let s=0;s<t;++s){const t=e[s];(0,T.hu)(t in this.aa2num,`Unknown char '${t}' found in sequence '${e}'`),n[s]=this.encodeLettter(t)}return n}encodeLettter(e){return this.aa2num[e]}decode(e){let t="";for(let n=0;n<e.length;++n){const s=e[n];(0,T.hu)(s in this.num2aa,`Unknown code '${s}' found in vector '${e}'`),t+=this.num2aa[s]}return t}}var $=n(3553);const N="input.fa",L="result.fasta";function P(e){return e.reduce(((e,t,n)=>e+`>sample${n+1}\n${t}\n`),"")}async function R(e,t=!1,n="",i=null,o,a,l){let c=e.toList();t&&(c=c.map((e=>M.clean(e).replace(/\-/g,""))));const u=e.length;i??(i=s.Column.string("Clusters",u).init("0")),i.type!=s.COLUMN_TYPE.STRING&&(i=i.convertTo(s.TYPE.STRING)),i.compact();const h=i.categories,d=i.getRawData(),m=new Array(h.length),p=new Array(h.length);for(let e=0;e<u;++e){const t=d[e];(m[t]??(m[t]=[])).push(c[e]),(p[t]??(p[t]=[])).push(e)}const f=await new I(["base/1.0.0",{tool:"kalign",version:$.WY,reinit:!0}]),g=s.Column.string(n,u);for(let e=0;e<h.length;++e){const t=P(m[e]);await f.fs.writeFile(N,t);const n=`${void 0!==o?` --gpo ${o}`:""}${void 0!==a?` --gpe ${a}`:""}${void 0!==l?` --tgpe ${l}`:""}`,s=await f.exec(`kalign ${N} -f fasta -o ${L}${n}`);console.warn(s);const i=await f.cat(L);if(!i)throw new Error("kalign output no result");const c=new r.i(i).sequencesArray,u=p[e];for(let e=0;e<c.length;++e)g.set(u[e],c[e])}const y=e.getTag(s.TAGS.UNITS),b=e.getTag("alphabet");return g.setTag(s.TAGS.UNITS,y),g.setTag("aligned","SEQ.MSA"),g.setTag("alphabet",b),g.semType=s.SEMTYPE.MACROMOLECULE,g}},8341:(e,t,n)=>{"use strict";n.d(t,{Jy:()=>c,f3:()=>h,lp:()=>l});var s=n(4469),r=n(976),i=n(8447),o=n(3553),a=n(3649);const l=new class{constructor(){this.dcName="bio"}async getDockerContainer(){return await s.dapi.docker.dockerContainers.filter(this.dcName).first()}},c=["mafft --auto","mafft","linsi","ginsi","einsi","fftns","fftnsi","nwns","nwnsi"],u=["AlignedSeq","AlignedSubpeptide","HELM","ID","PolymerID"];async function h(e,t,n="ginsi",s=1.53,a=0,c=null,h){const m=await l.getDockerContainer();if("started"!==m.status&&"checking"!==m.status)throw new Error("PepSeA container has not started yet");const p=e.length;c??(c=r.Column.int("Clusters",p).init(0)),c.type!=r.COLUMN_TYPE.STRING&&(c=c.convertTo(r.TYPE.STRING));const f=c.categories,g=new Array(f.length);for(let t=0;t<p;++t){const n=c.get(t);if(""===n)continue;const s=f.indexOf(n),r=e.get(t);r&&(g[s]??(g[s]=[])).push({ID:t.toString(),HELM:r})}const y=new Array(p);for(const e of g){const t=(await d(m.id,e,n,s,a,h)).Alignment;for(const e of t)y[parseInt(e.ID)]=Object.entries(e).filter((e=>!u.includes(e[0]))).map((e=>"-"!==e[1]?e[1]:"")).join(o.rs.SEPARATOR)}const b=r.Column.fromStrings(t,y);return b.setTag(r.TAGS.UNITS,i.r2.SEPARATOR),b.setTag("separator",o.rs.SEPARATOR),b.setTag("aligned","SEQ.MSA"),b.setTag("alphabet","UN"),b.setTag(".alphabetIsMultichar","true"),b.semType=r.SEMTYPE.MACROMOLECULE,b}async function d(e,t,n,r,i,o){const l={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(t)},c=`/align?method=${n}&gap_open=${r}&gap_extend=${i}`;let u;if("fetchProxy"in s.dapi.docker.dockerContainers){const t=window.performance.now(),n=await s.dapi.docker.dockerContainers.fetchProxy(e,c,l),r=window.performance.now();a._package.logger.debug(`Bio: requestAlignedObjects() dockerContainers.fetchProxy(), ET: ${r-t} ms`);const i="application/json"===n.headers.get("content-type");if(!n.ok&&i){const e=await n.json(),t=e["pepsea-error"];if(t)throw new Error(`PepSeA error: ${t}`);const s=e["datagrok-error"];if(s)throw new Error(`Datagrok error: ${s}`);throw new Error(n.statusText)}if(!n.ok&&!i){const e=await n.text();throw new Error(`Error: ${e}`)}if(!i){const e=await n.text();throw new Error(`Error: PepSeA expected JSON response, got '${e}'.`)}u=await n.json()}else{const t=await s.dapi.docker.dockerContainers.request(e,c,l);if(!t)throw new Error("Empty response");u=JSON.parse(t);const n=u["pepsea-error"];if(n)throw new Error(`PepSeA error: ${n}`);const r=u["datagrok-error"];if(r)throw new Error(`Datagrok error: ${r}`)}if("pepsea-stderr"in u){const e=u["pepsea-stderr"];o?.warning(e)}return u}},9943:(e,t,n)=>{"use strict";n.d(t,{C2:()=>u});var s=n(976),r=n(3870),i=n(4469),o=n(6414),a=n.n(o),l=n(8260);const c=60;function u(){const e=i.shell.tv.grid,t=a().count(0).take(e.columns.length).map((t=>e.columns.byIndex(t))).filter((e=>!!e.column&&e.column.semType!==s.SEMTYPE.MACROMOLECULE)).toArray(),n=t.find((e=>-1!==e.name.toLowerCase().indexOf("id"))),o=n?[n.name]:[],u=r.multiChoiceInput("Seq id columns",o,t.map((e=>e.name))),d=a().count(0).take(e.columns.length).map((t=>e.columns.byIndex(t))).filter((e=>{const t=e.column;return!(!t||t.semType!==s.SEMTYPE.MACROMOLECULE)&&l.g.forColumn(t).isFasta()})).toArray(),m=d.length>0?d[0].name:[],p=r.choiceInput("Seq column",m,d.map((e=>e.name))),f=r.intInput("FASTA line width",c);r.dialog({title:"Save as FASTA"}).add(r.inputs([u,p,f])).onOK((()=>{const t=u.value?u.value.map((t=>e.columns.byName(t).column)):[],n=p.value?e.columns.byName(p.value).column:null,s=f.value??c;n||i.shell.warning("Seq column is mandatory to save as FASTA.");const r=function(e,t,n=c,s="\n"){const r=l.g.forColumn(t),i=[];for(let o=0;o<t.length;o++){const t=e.map((e=>e.get(o).toString())).join("|"),a=h(r.getSplitted(o),n);i.push(`>${t}${s}`);for(const e of a)i.push(`${e}${s}`)}return"".concat(...i)}(t,n,s),o=document.createElement("a");o.setAttribute("href",`data:text/plain;charset=utf-8,${encodeURIComponent(r)}`),o.setAttribute("download",`${e.dataFrame.name}.fasta`),o.click()})).show()}function h(e,t=c){let n=0;const s=e.length,r=[];for(;n<s;){const s=a()(e.originals).slice(n,n+t).toArray(),i=s.map((e=>e.length>1?`[${e}]`:e)).reduce(((e,t)=>e+t),"");r.push(i),n+=s.length}return r}},9416:(e,t,n)=>{"use strict";n.d(t,{n:()=>c});var s=n(4469),r=n(976),i=n(8467),o=n(2568),a=n(8457),l=n(3553);async function c(e,t){if(await(0,i.gw)(10),!(0,o.n)(t,"Sequence space"))return e;const n=(0,a.O)(t);n.name="splitToMonomers";const c=t.dataFrame;for(const e of n.columns)e.semType=l.Of.MONOMER,e.setTag("alphabet",t.getTag("alphabet"));const u=/(\d+)(?: \((\d+)\))?/,h=e=>{u.lastIndex=0;const t=e.match(u);return t?`${t[1]} (${parseInt(t[2]??0)+1})`:e};for(let e=0;e<n.columns.length;e++){const s=n.columns.byIndex(e);s.semType=l.Of.MONOMER,s.setTag("alphabet",t.getTag("alphabet"));const r=100;let i=0;for(;c.columns.byName(s.name)&&i<r;)s.name=h(s.name),i++;c.columns.add(s)}await s.data.detectSemanticTypes(c);for(let e=0;e<n.columns.length;e++){const t=n.columns.byIndex(e);t.setTag(r.TAGS.CELL_RENDERER,"Monomer"),t.setTag(".use-as-filter","false")}return c}},4293:(e,t,n)=>{"use strict";n.d(t,{B:()=>i,Y:()=>o});var s=n(4469),r=n(976);function i(){const e=s.shell.t.columns.bySemTypeAll(r.SEMTYPE.MACROMOLECULE);if(null!==e)return e;s.shell.error("Current table does not contain macromolecules")}function o(e,t){e.innerHTML="",e.append(t)}},8415:(e,t,n)=>{"use strict";n.d(t,{bo:()=>v,OZ:()=>T});var s=n(4469),r=n(3870),i=n(976),o=n(3336),a=n.n(o),l=n(6414),c=n.n(l),u=n(701),h=n(8260),d=n(8447),m=n(9298);function p(e){var t;return"string"==typeof e||e instanceof String?e:("object"==typeof e||e instanceof Object)&&"$thrownJsError"in e?p(e.$thrownJsError):e instanceof Error?null!==(t=e.stack)&&void 0!==t?t:e.message:e.toString()}var f=n(6286),g=n(8467),y=n(172);var b,v,w=n(8770),C=n(3649);HTMLCanvasElement.prototype.getCursorPosition=function(e,t){const n=this.getBoundingClientRect();return new i.Point((e.clientX-n.left)*t,(e.clientY-n.top)*t)},i.Rect.prototype.contains=function(e,t){return this.left<=e&&e<=this.right&&this.top<=t&&t<=this.bottom};class S{constructor(e=0,t){this.valueList=null,this.valueIdx=0,this.value=this.rowCount=e,this.bounds=t}push(e){this.valueList||(this.valueList=new Array(this.rowCount),this.valueIdx=0),this.valueList[this.valueIdx]=e,++this.valueIdx}aggregate(e){this.value=e(this.valueList)??0,this.valueList=null}}class A{get label(){return this._label?this._label:this.name}constructor(e,t,n,s){this.pos=e,this.name=t,this.sumRowCount=0,this._freqs=n??{},s?.sumRowCount&&(this.sumRowCount=s.sumRowCount),s?.sumValueForHeight&&(this.sumPlotValue=s.sumValueForHeight),s?.label&&(this._label=s.label)}getMonomers(){return Object.keys(this._freqs)}hasMonomer(e){return e in this._freqs}getFreq(e){let t=this._freqs[e];return t||(t=this._freqs[e]=new S),t}aggregate(e){const t=function(e){return t=>{const n=function(e){let t;const n="agg";return t=e instanceof Float32Array?i.Column.fromFloat32Array(n,e):e instanceof Int32Array?i.Column.fromInt32Array(n,e):i.Column.fromList(i.COLUMN_TYPE.FLOAT,n,e),t}(t);return n.aggregate(e)}}(e);for(const[e,n]of Object.entries(this._freqs))n.aggregate(t)}getMinValue(){return Math.min(...Object.values(this._freqs).map((e=>e.value)))}calcPlotValue(e){for(const t of Object.values(this._freqs))t.plotValue=t.value-e}calcHeights(e){this.sumPlotValue=0;for(const e of Object.values(this._freqs))this.sumPlotValue+=e.plotValue;if(this.sumPlotValueForHeight=0,e===m.ES.Entropy){const e=Object.keys(this._freqs).length,t=.01*this.sumPlotValue,n=t/e;for(const e of Object.values(this._freqs)){const s=(e.plotValue+n)/(this.sumPlotValue+t);this.sumPlotValueForHeight+=-s*Math.log2(s)}}else if(e===m.ES.full)for(const[e,t]of Object.entries(this._freqs)){const e=t.plotValue/this.sumPlotValue;this.sumPlotValueForHeight+=e}}calcScreen(e,t,n,s,r,o,a,l,c){const u=s===m.ES.Entropy?n*(r-this.sumPlotValueForHeight)/r:n;let h=c*l+(n-u-1);const d=Object.entries(this._freqs).sort(((e,t)=>e[0]!==f.G2&&t[0]!==f.G2?t[1].value-e[1].value:e[0]===f.G2&&t[0]===f.G2?0:e[0]===f.G2?-1:1));for(const[n,s]of d){const n=u*s.plotValue/this.sumPlotValue;s.bounds=new i.Rect((e-t)*l*o,h,a*l,n),h+=n}}render(e,t,n,s,r){for(const[i,o]of Object.entries(this._freqs))if(i!==f.G2){const a=(0,d.GU)(i,5),l=o.bounds,c=l.left;e.resetTransform(),e.strokeStyle="lightgray",e.lineWidth=1,e.rect(c,l.top,l.width,l.height),e.fillStyle=r.get(i)??r.get("other"),e.textAlign="left",e.font=t;const u=e.measureText(a);e.setTransform(l.width/u.width,0,0,l.height/s,c,l.top),e.fillText(a,0,-n)}}getMonomerAt(e,t){const n=Object.entries(this._freqs).find((([n,s])=>s.bounds.contains(e,t)));return n?n[0]:void 0}buildCompositionTable(e){if("-"in this._freqs)throw new Error("Unexpected monomer symbol '-'.");return(0,w._)(e,Object.assign({},...Object.entries(this._freqs).map((([e,t])=>({[e]:t.rowCount})))))}}!function(e){e.STYLE="Style",e.BEHAVIOR="Behavior",e.LAYOUT="Layout",e.DATA="Data"}(b||(b={})),function(e){e.sequenceColumnName="sequenceColumnName",e.valueAggrType="valueAggrType",e.valueColumnName="valueColumnName",e.startPositionName="startPositionName",e.endPositionName="endPositionName",e.skipEmptySequences="skipEmptySequences",e.skipEmptyPositions="skipEmptyPositions",e.shrinkEmptyTail="shrinkEmptyTail",e.backgroundColor="backgroundColor",e.positionHeight="positionHeight",e.positionWidth="positionWidth",e.verticalAlignment="verticalAlignment",e.horizontalAlignment="horizontalAlignment",e.fixWidth="fixWidth",e.fitArea="fitArea",e.minHeight="minHeight",e.maxHeight="maxHeight",e.showPositionLabels="showPositionLabels",e.positionMarginState="positionMarginState",e.positionMargin="positionMargin",e.filterSource="filterSource"}(v||(v={}));const x=m.vS;var E;!function(e){e[e.None=0]="None",e[e.Render=1]="Render",e[e.Layout=1]="Layout",e[e.Freqs=2]="Freqs"}(E||(E={}));const I=new class{constructor(){this.render=20}};class T extends i.JsViewer{get positionWidthWithMargin(){return this._positionWidthWithMargin}get Length(){return this.skipEmptyPositions?this.positions.length:this.startPosition<=this.endPosition?this.endPosition-this.startPosition+1:0}get positionMarginValue(){return this.positionMarginState===m.dE.AUTO&&!0===this.seqHandler.getAlphabetIsMultichar()||this.positionMarginState===m.dE.ON?this.positionMargin:0}constructor(){super(),this.viewed=!1,this.initialized=!1,this.palette=null,this.seqCol=null,this.positions=[],this.visibleSlider=!1,this.allowResize=!0,this.turnOfResizeForOneSetValue=!1,this.backgroundColor=4294967295,this.positionMargin=0,this.positionNames=[],this.positionLabels=void 0,this.startPosition=-1,this.endPosition=-1,this.error=null,this.viewerId=++T.viewerCounter,this.setDataInProgress=!1,this.viewSubs=[],this._onSizeChanged=new u.Subject,this._onFreqsCalculated=new u.Subject,this._onLayoutCalculated=new u.Subject,this.requestedRenderLevel=E.Freqs,this.renderRequest=new u.Subject,this._onRendered=new u.Subject,this.textBaseline="top",this.seqHandler=null,this.sequenceColumnName=this.string(v.sequenceColumnName,x.sequenceColumnName,{category:b.DATA});const e=[i.AGG.KEY,i.AGG.PIVOT,i.AGG.MISSING_VALUE_COUNT,i.AGG.SKEW,i.AGG.KURT,i.AGG.SELECTED_ROWS_COUNT],t=Object.values(i.AGG).filter((t=>!e.includes(t)));this.valueAggrType=this.string(v.valueAggrType,x.valueAggrType,{category:b.DATA,choices:t}),this.valueColumnName=this.string(v.valueColumnName,x.valueColumnName,{category:b.DATA}),this.startPositionName=this.string(v.startPositionName,x.startPositionName,{category:b.DATA}),this.endPositionName=this.string(v.endPositionName,x.endPositionName,{category:b.DATA}),this.skipEmptySequences=this.bool(v.skipEmptySequences,x.skipEmptySequences,{category:b.DATA}),this.skipEmptyPositions=this.bool(v.skipEmptyPositions,x.skipEmptyPositions,{category:b.DATA}),this.shrinkEmptyTail=this.bool(v.shrinkEmptyTail,x.shrinkEmptyTail,{category:b.DATA}),this.backgroundColor=this.int(v.backgroundColor,x.backgroundColor,{category:b.STYLE}),this.positionHeight=this.string(v.positionHeight,x.positionHeight,{category:b.STYLE,choices:Object.values(m.ES)}),this._positionWidth=this.positionWidth=this.float(v.positionWidth,x.positionWidth,{category:b.STYLE}),this.verticalAlignment=this.string(v.verticalAlignment,x.verticalAlignment,{category:b.LAYOUT,choices:Object.values(m.vw)}),this.horizontalAlignment=this.string(v.horizontalAlignment,x.horizontalAlignment,{category:b.LAYOUT,choices:Object.values(m.iD)}),this.fixWidth=this.bool(v.fixWidth,x.fixWidth,{category:b.LAYOUT,userEditable:!1}),this.fitArea=this.bool(v.fitArea,x.fitArea,{category:b.LAYOUT}),this.minHeight=this.float(v.minHeight,x.minHeight,{category:b.LAYOUT}),this.maxHeight=this.float(v.maxHeight,x.maxHeight,{category:b.LAYOUT}),this.showPositionLabels=this.bool(v.showPositionLabels,x.showPositionLabels,{category:b.LAYOUT}),this.positionMarginState=this.string(v.positionMarginState,x.positionMarginState,{category:b.LAYOUT,choices:Object.values(m.dE)});let n=0;"auto"===this.positionMarginState&&(n=4),this.positionMargin=this.int(v.positionMargin,n,{category:b.LAYOUT,min:0,max:16}),this.filterSource=this.string(v.filterSource,x.filterSource,{category:b.BEHAVIOR,choices:Object.values(m.Ct)}),this.slider=r.rangeSlider(0,100,0,20,!1,{style:"barbell"}),this.canvas=r.canvas(),this.canvas.classList.value="bio-wl-canvas",this.canvas.style.width="100%",this.viewSyncer=new y.c(C._package.logger)}viewerToLog(){return`WebLogoViewer<${this.viewerId}>`}setData(){const e=`${this.viewerToLog()}.setData()`;C._package.logger.debug(`${e}, in`),this.viewSyncer.sync(`${e}`,(async()=>{if(!this.setDataInProgress){this.setDataInProgress=!0;try{this.viewed&&(this.renderRequestSub.unsubscribe(),await this.destroyView(),this.viewed=!1),this.updateSeqCol(),this.updateEditors(),this.viewed||(await this.buildView(),this.viewed=!0)}finally{this.setDataInProgress=!1}}})),C._package.logger.debug(`${e}, out`)}async destroyView(){for(const e of this.viewSubs)e.unsubscribe();this.viewSubs=[];const e=this.dataFrame?"data":"null";C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.destroyView( dataFrame = ${e} ) start`),this.host.remove(),this.msgHost=void 0,this.host=void 0,C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.destroyView() end`)}async buildView(){const e=this.dataFrame?"data":"null";C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.buildView( dataFrame = ${e} ) start`),window.devicePixelRatio,this.viewSubs.push(i.debounce(this.renderRequest,I.render).subscribe(this.renderRequestOnDebounce.bind(this))),this.helpUrl="/help/visualize/viewers/web-logo.md",this.msgHost=r.div("No message",{classes:"bio-wl-msg"}),this.msgHost.style.display="none",this.canvas=r.canvas(),this.canvas.style.width="100%",this.slider.root.style.position="absolute",this.slider.root.style.zIndex="999",this.slider.root.style.display="none",this.slider.root.style.height="0.7em",this.visibleSlider=!1,this.host=r.div([this.msgHost,this.canvas],{classes:"bio-wl-host",style:{display:"flex",flexDirection:"row",flexWrap:"wrap"}}),this.root.append(this.host),this.root.append(this.slider.root),this.error&&(this.msgHost.innerText=this.error.message,r.tooltip.bind(this.msgHost,this.error.stack),this.msgHost.style.setProperty("display",null)),this.dataFrame&&(this.viewSubs.push(this.dataFrame.filter.onChanged.subscribe(this.dataFrameFilterOnChanged.bind(this))),this.viewSubs.push(this.dataFrame.selection.onChanged.subscribe(this.dataFrameSelectionOnChanged.bind(this)))),this.viewSubs.push(r.onSizeChanged(this.root).subscribe(this.rootOnSizeChanged.bind(this))),this.viewSubs.push(this.slider.onValuesChanged.subscribe(this.sliderOnValuesChanged.bind(this))),this.viewSubs.push((0,u.fromEvent)(this.canvas,"mousemove").subscribe(this.canvasOnMouseMove.bind(this))),this.viewSubs.push((0,u.fromEvent)(this.canvas,"mousedown").subscribe(this.canvasOnMouseDown.bind(this))),this.viewSubs.push((0,u.fromEvent)(this.canvas,"wheel").subscribe(this.canvasOnWheel.bind(this))),this.render(E.Freqs,"buildView"),C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.buildView() end`)}rootOnSizeChanged(){C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.rootOnSizeChanged(), start `),this.render(E.Layout,"rootOnSizeChanged")}updateEditors(){this.props.getProperty(v.valueColumnName).choices=c()(this.dataFrame.columns.numerical).map((e=>e.name)).toArray()}updateSeqCol(){if(this.dataFrame&&(this.seqCol=this.sequenceColumnName?this.dataFrame.col(this.sequenceColumnName):null,null==this.seqCol&&(this.seqCol=(0,d.up)(this.dataFrame),this.sequenceColumnName=this.seqCol?this.seqCol.name:null),this.seqCol)){try{this.seqHandler=h.g.forColumn(this.seqCol),this.palette=(0,d.dQ)(this.seqCol),this.render(E.Freqs,"updateSeqCol()"),this.error=null}catch(e){throw this.seqCol=null,this.error=e instanceof Error?e:new Error(e.toString()),e}this.seqCol||(this.seqHandler=null,this.positionNames=[],this.positionLabels=[],this.startPosition=-1,this.endPosition=-1,this.palette=null)}}getFilter(){let e;switch(this.filterSource){case m.Ct.Filtered:e=this.dataFrame.filter;break;case m.Ct.Selected:e=0===this.dataFrame.selection.trueCount?this.dataFrame.filter:this.dataFrame.selection}return e}setSliderVisibility(e){e?(this.slider.root.style.display="inherit",this.visibleSlider=!0):(this.slider.root.style.display="none",this.visibleSlider=!1)}calcLayout(e){this.host&&this.canvas&&this.slider&&(this.host.classList.remove("bio-wl-fixWidth","bio-wl-fitArea"),this.canvas.classList.remove("bio-wl-fixWidth","bio-wl-fitArea"),this._positionWidth=this.positionWidth,this._positionMargin=this.positionMargin,this._positionWidthWithMargin=this._positionWidth+this.positionMarginValue,this.fixWidth?this.calcLayoutFixWidth(e):this.fitArea?this.calcLayoutFitArea(e):this.calcLayoutNoFitArea(e),this.slider.root.style.width=`${this.host.clientWidth}px`)}calcLayoutFixWidth(e){if(!this.host||!this.canvas||!this.slider)return;this.host.classList.add("bio-wl-fixWidth"),this.canvas.classList.add("bio-wl-fitArea");const t=this._positionWidthWithMargin*this.Length,n=Math.min(Math.max(this.minHeight,this.root.clientHeight),this.maxHeight);this.host.style.justifyContent=m.iD.LEFT,this.host.style.removeProperty("margin-left"),this.host.style.removeProperty("margin-top"),this.host.style.width=this.canvas.style.width=`${t}px`,this.host.style.height=this.canvas.style.height=`${n}px`,this.host.style.left=this.canvas.style.left="0",this.host.style.top=this.canvas.style.top="0",this.host.style.setProperty("overflow","hidden","important"),this.slider.root.style.display="none",this.slider.setValues(0,Math.max(0,this.Length-1),0,Math.max(0,this.Length-1)),this.canvas.width=t*e,this.canvas.height=n*e}calcLayoutNoFitArea(e){if(!this.host||!this.canvas||!this.slider)return;const t=this._positionWidthWithMargin*this.Length,n=Math.min(Math.max(this.minHeight,this.root.clientHeight),this.maxHeight),s=Math.min(this.root.clientWidth,t);this.canvas.style.width=`${s}px`,this.canvas.style.height=`${n}px`,this.host.style.width=`${s}px`,this.host.style.height=`${this.root.clientHeight}px`,this.host.style.justifyContent=this.horizontalAlignment,this.host.style.alignContent=this.verticalAlignment===m.vw.TOP?"start":this.verticalAlignment===m.vw.MIDDLE?"center":this.verticalAlignment===m.vw.BOTTOM?"end":"inherit",this.root.clientHeight<this.minHeight&&(this.host.style.alignContent="start",this.host.style.width=`${s+6}px`),this.host.style.width=`${this.host}px`;const r=t>s;if(this.setSliderVisibility(r),r){this.slider.root.style.removeProperty("display"),this.host.style.justifyContent="left",this.host.style.height=this.root.clientHeight-this.slider.root.offsetHeight+"px",this.slider.root.style.top=`${this.host.offsetHeight}px`;let e=Math.min(Math.max(0,this.slider.min),this.Length-.001),t=Math.min(Math.max(0,this.slider.max),this.Length-.001);const n=this.root.clientWidth/this._positionWidthWithMargin;t=Math.min(Math.max(e,0)+n,this.Length-.001),e=Math.max(0,Math.min(t,this.Length-.001)-n),this.slider.setValues(0,Math.max(this.Length-.001),e,t)}else this.slider.setValues(0,Math.max(0,this.Length-.001),0,Math.max(0,this.Length-.001));this.canvas.width=s*e,this.canvas.height=n*e}calcLayoutFitArea(e){if(!this.host||!this.canvas||!this.slider)return;const t=this._positionWidth*this.Length,n=Math.min(Math.max(this.minHeight,this.root.clientHeight),this.maxHeight),s=t>0?(this.root.clientWidth-this.positionMarginValue*this.Length)/t:0,r=this.root.clientHeight/n,i=Math.max(1,Math.min(s,r));this._positionWidth=this.positionWidth*i,this._positionWidthWithMargin=this._positionWidth+this.positionMarginValue;const o=(this._positionWidth+this.positionMarginValue)*this.Length,a=i*n,l=Math.min(this.root.clientWidth,o);this.canvas.style.width=`${l}px`,this.canvas.style.height=`${a}px`,this.host.style.width=`${l}px`,this.host.style.height=`${this.root.clientHeight}px`,this.host.style.justifyContent=this.horizontalAlignment,this.host.style.alignContent=this.verticalAlignment===m.vw.TOP?"start":this.verticalAlignment===m.vw.MIDDLE?"center":this.verticalAlignment===m.vw.BOTTOM?"end":"inherit",this.root.clientHeight<this.minHeight&&(this.host.style.alignContent="start",this.host.style.width=`${l+6}px`),this.host.style.width=`${this.host}px`;const c=o>l;if(this.setSliderVisibility(c),c){this.slider.root.style.removeProperty("display"),this.host.style.justifyContent="left",this.host.style.height=this.root.clientHeight-this.slider.root.offsetHeight+"px",this.slider.root.style.top=`${this.host.offsetHeight}px`;let e=Math.min(Math.max(0,this.slider.min),this.Length-.001),t=Math.min(Math.max(0,this.slider.max),this.Length-.001);const n=this.root.clientWidth/this._positionWidthWithMargin;t=Math.min(Math.max(e,0)+n,this.Length-.001),e=Math.max(0,Math.min(t,this.Length-.001)-n),this.slider.setValues(0,Math.max(0,this.Length-.001),e,t)}else this.slider.setValues(0,Math.max(0,this.Length-.001),0,Math.max(0,this.Length-.001));this.canvas.width=l*e,this.canvas.height=a*e}onPropertyChanged(e){switch(super.onPropertyChanged(e),e.name){case v.sequenceColumnName:this.updateSeqCol();break;case v.sequenceColumnName:case v.startPositionName:case v.endPositionName:case v.filterSource:case v.shrinkEmptyTail:case v.skipEmptyPositions:case v.positionHeight:case v.valueColumnName:case v.valueAggrType:this.render(E.Freqs,`onPropertyChanged( ${e.name} )`);break;case v.minHeight:case v.maxHeight:case v.positionWidth:case v.showPositionLabels:case v.fixWidth:case v.fitArea:case v.horizontalAlignment:case v.verticalAlignment:case v.positionMargin:case v.positionMarginState:this.render(E.Layout,`onPropertyChanged(${e.name})`);break;case v.backgroundColor:this.render(E.Render,`onPropertyChanged(${e.name})`)}}onTableAttached(){C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.onTableAttached(), `),super.onTableAttached(),this.setData()}detach(){const e=`${this.viewerToLog()}.detach()`;C._package.logger.debug(`${e}, in`);const t=super.detach.bind(this);this.viewSyncer.sync(`${e}`,(async()=>{this.setDataInProgress||(this.viewed&&(await this.destroyView(),this.viewed=!1),t())})),C._package.logger.debug(`${e}, out`)}get onSizeChanged(){return this._onSizeChanged}get onFreqsCalculated(){return this._onFreqsCalculated}get onLayoutCalculated(){return this._onLayoutCalculated}getMonomer(e,t){const n=e.x,s=Math.floor(e.x/(this._positionWidthWithMargin*t)+Math.floor(this.slider.min)),r=this.positions[s];if(!r)return[null,null,null];const i=r.getMonomerAt(n,e.y);return void 0===i?[r,null,null]:[r,i,r.getFreq(i)]}_nullSequence(e="X"){return this.skipEmptySequences?"":new Array(this.Length).fill(e).join("")}_removeEmptyPositions(){this.skipEmptyPositions&&(this.positions=c()(this.positions).filter((e=>!e.hasMonomer(f.G2)||e.getFreq(f.G2).rowCount!==e.sumRowCount)).toArray())}render(e,t){C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.render( recalcLevelVal=${e}, reason='${t}' )`),this.requestedRenderLevel=Math.max(this.requestedRenderLevel,e),this.renderRequest.next(this.requestedRenderLevel)}async renderInt(e){if(C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.render.renderInt( renderLevel=${e} ), start `),this.msgHost&&(this.seqCol&&!this.palette?(this.msgHost.innerText=`Unknown palette (column semType: '${this.seqCol.semType}').`,this.msgHost.style.display=""):this.msgHost.style.display="none"),!this.seqCol||!this.dataFrame||!this.palette||null==this.host||null==this.slider)return;const t=window.devicePixelRatio,n=this.showPositionLabels?12:0;if(e>=E.Freqs&&(()=>{if(C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.render.calculateFreqsInt(), start `),!this.host||!this.seqCol||!this.dataFrame)return;const e=this.getFilter(),t=0===e.trueCount?this.seqHandler.maxLength:c().count(0).take(this.seqHandler.length).map((t=>{const n=this.seqHandler.getSplitted(t);return e.get(t)&&n?n.length:0})).reduce(((e,t)=>Math.max(e,t)),0),n=this.seqCol.getTag(".positionNames"),s=this.seqCol.getTag(".positionLabels");this.positionNames=n?n.split(d.CI).map((e=>e.trim())):[...Array(t).keys()].map((e=>`${e+1}`)),this.positionLabels=s?s.split(d.CI).map((e=>e.trim())):void 0,this.startPosition=this.startPositionName&&this.positionNames&&this.positionNames.includes(this.startPositionName)?this.positionNames.indexOf(this.startPositionName):0,this.endPosition=this.endPositionName&&this.positionNames&&this.positionNames.includes(this.endPositionName)?this.positionNames.indexOf(this.endPositionName):t-1;const r=this.startPosition<=this.endPosition?this.endPosition-this.startPosition+1:0;this.seqHandler=h.g.forColumn(this.seqCol);const o=this.startPosition<=this.endPosition?this.endPosition-this.startPosition+1:0;this.positions=new Array(o);for(let e=0;e<r;e++){const t=this.positionNames[this.startPosition+e],n=this.positionLabels?this.positionLabels[this.startPosition+e]:void 0;this.positions[e]=new A(this.startPosition+e,t,{},{label:n})}const a=this.dataFrame.rowCount;for(let t=0;t<r;++t){for(let n=0;n<a;++n)if(e.get(n)){const e=this.seqHandler.getSplitted(n),s=t<e.length?e.getCanonical(this.startPosition+t):this.seqHandler.defaultGapOriginal,r=this.seqHandler.defaultGapOriginal===s?f.G2:s,i=this.positions[t],o=i.getFreq(r);++i.sumRowCount,o.value=++o.rowCount}if(this.valueAggrType===i.AGG.TOTAL_COUNT)continue;let n=null;try{n=this.dataFrame.getCol(this.valueColumnName),n.matches("numerical")||(n=null)}catch{n=null}if(n){for(let s=0;s<a;++s)if(e.get(s)){const e=this.seqHandler.getSplitted(s).getCanonical(this.startPosition+t),r=n.get(s);this.positions[t].getFreq(e).push(r)}this.positions[t].aggregate(this.valueAggrType)}}const l=this.valueAggrType===i.AGG.TOTAL_COUNT?0:Math.min(0,Math.min(...this.positions.map((e=>e.getMinValue()))));for(let e=0;e<r;++e)this.positions[e].calcPlotValue(l),this.positions[e].calcHeights(this.positionHeight);this._removeEmptyPositions(),this._onFreqsCalculated.next()})(),this.calcLayout(t),-1===this.startPosition)return;const r=Math.max(Math.floor(this.slider.min),0),o=Math.min(this.positions.length-1,Math.floor(this.slider.max));e>=E.Layout&&((e,t,n,r)=>{C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.render.calculateLayoutInt(), start `);const o=this.canvas.height-r*n;let a;if(this.valueAggrType===i.AGG.TOTAL_COUNT){const e=this.getAlphabetSize();this.positionHeight==m.ES.Entropy&&null==e&&s.shell.error("WebLogo: alphabet is undefined."),a=Math.log2(e)}else a=Math.max(...c().count(e).takeWhile((e=>e<=t)).map((e=>this.positions[e].sumPlotValueForHeight)));for(let s=e;s<=t;++s)s in this.positions?this.positions[s].calcScreen(s,this.slider.min,o,this.positionHeight,a,this._positionWidthWithMargin,this._positionWidth,n,r):C._package.logger.warning(`Bio: WebLogoViewer<${this.viewerId}>.render.calculateLayoutInt() this.positions.length = ${this.positions.length}, jPos = ${s}`);C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.render.calculateLayoutInt(), end `),this._onLayoutCalculated.next()})(r,o,window.devicePixelRatio,n);const a=this.canvas.getContext("2d");if(a){a.save();try{this.Length,a.resetTransform(),a.fillStyle=function(e){const t=i.Color.a(e);return`#${(16777215&e).toString(16).padStart(6,"0")}`+t.toString(16).padStart(2,"0")}(this.backgroundColor),a.fillRect(0,0,this.canvas.width,this.canvas.height),a.textBaseline=this.textBaseline;const e=10*t;a.resetTransform(),a.fillStyle="black",a.textAlign="center",a.font=`${e.toFixed(1)}px Roboto, Roboto Local, sans-serif`,n>0&&this.positions.length>0&&function(e,t,n,s,r,i,o,a){e.save();try{e.textAlign="center";let l=null,c=null;for(let t=Math.floor(o);t<=Math.floor(a);t++){const n=i[t],s=e.measureText(n.name),r=s.actualBoundingBoxDescent-s.actualBoundingBoxAscent;l=null===l?s.width:Math.max(l,s.width),c=null===c?r:Math.max(c,r)}const u=l<s*t-2?1:(s*t-2)/l;for(let l=Math.floor(o);l<=Math.floor(a);l++){const a=i[l],h=(l-o)*n*t+s*t/2,d=(r*t-c)/2;e.setTransform(u,0,0,1,h,d),e.measureText(a.label),e.fillText(a.label,0,0)}}finally{e.restore()}}(a,t,this._positionWidthWithMargin,this._positionWidth,n,this.positions,this.slider.min,this.slider.max);const s="16px Roboto, Roboto Local, sans-serif",l=.25,c=12.2;for(let e=r;e<=o;e++)this.positions[e].render(a,s,l,c,this.palette)}finally{a.restore()}C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.render.renderInt( recalcLevel=${e} ), end`)}}renderRequestOnDebounce(e){const t=`${this.viewerToLog()}.renderRequestOnDebounce()`;"HTML"!==a()(this.root).offsetParent().get()[0]?.tagName?(this.requestedRenderLevel=E.None,this.viewSyncer.sync(t,(async()=>{await this.renderInt(e)}))):C._package.logger.warning(`${t}, $(this.root).offsetParent() is the 'HTML' tag.`)}getAlphabetSize(){return this.seqHandler?.getAlphabetSize()??0}sliderOnValuesChanged(e){try{const e={minRange:this.slider.minRange,min:this.slider.min,max:this.slider.max,maxRange:this.slider.maxRange};C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.sliderOnValuesChanged( ${JSON.stringify(e)} ), start`),this.render(E.Layout,"sliderOnValuesChanged")}catch(e){const t=p(e);C._package.logger.error(`Bio: WebLogoViewer<${this.viewerId}>.sliderOnValuesChanged() error:\n`+t)}}dataFrameFilterOnChanged(e){C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.dataFrameFilterChanged()`);try{this.filterSource===m.Ct.Filtered&&this.render(E.Freqs,"dataFrameFilterOnChanged")}catch(e){const t=p(e);C._package.logger.error(`Bio: WebLogoViewer<${this.viewerId}>.dataFrameFilterOnChanged() error:\n`+t)}}dataFrameSelectionOnChanged(e){C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.dataFrameSelectionOnChanged()`);try{this.filterSource===m.Ct.Selected&&this.render(E.Freqs,"dataFrameSelectionOnChanged")}catch(e){const t=p(e);C._package.logger.error(`Bio: WebLogoViewer<${this.viewerId}>.dataFrameSelectionOnChanged() error:\n`+t)}}canvasOnMouseMove(e){const t=window.devicePixelRatio;try{const n=e,s=this.canvas.getCursorPosition(n,t),[o,a]=this.getMonomer(s,t),l=this.showPositionLabels?12*t:0;if(null!==o&&null===a&&0<=s.y&&s.y<=l){const e=[r.divText(`Position ${o.label}`)];this.valueAggrType===i.AGG.TOTAL_COUNT&&e.push(o.buildCompositionTable(this.palette));const t=r.divV(e);r.tooltip.show(t,n.x+16,n.y+16)}else if(null!==o&&a&&this.dataFrame&&this.seqCol&&this.seqHandler){const e=o.getFreq(a),t=[r.div(`${a}`),r.div(`${e.rowCount} rows`)];this.valueAggrType!==i.AGG.TOTAL_COUNT&&t.push(r.div(`${this.valueAggrType}: ${e.value.toFixed(3)}`));const s=r.divV(t);r.tooltip.show(s,n.x+16,n.y+16)}else r.tooltip.hide()}catch(e){const t=p(e);C._package.logger.error(`Bio: WebLogoViewer<${this.viewerId}>.canvasOnMouseMove() error:\n`+t)}}canvasOnMouseDown(e){try{const t=e,n=window.devicePixelRatio,[s,r]=this.getMonomer(this.canvas.getCursorPosition(t,n),n);if(null!==s&&null!==r&&this.dataFrame&&this.seqCol&&this.seqHandler){const e=i.BitSet.create(this.dataFrame.selection.length,(e=>function(e,t,n,s,r,i){const o=t.getSplitted(s),a=i.pos<o.length?o.getCanonical(i.pos):null;return null!==a&&a===r}(this.dataFrame,this.seqHandler,this.getFilter(),e,r,s)));this.dataFrame.selection.init((t=>e.get(t)))}}catch(e){const t=p(e);C._package.logger.error(`Bio: WebLogoViewer<${this.viewerId}>.canvasOnMouseDown() error:\n`+t)}}canvasOnWheel(e){const t=window.devicePixelRatio;try{if(!this.visibleSlider)return;const n=this.canvas.width/(this._positionWidthWithMargin*t),s=e.deltaY/100*Math.max(Math.floor(n/5),1);this.slider.scrollBy(this.slider.min+s)}catch(e){const t=p(e);C._package.logger.error(`Bio: WebLogoViewer<${this.viewerId}>.canvasOnWheel() error:\n`+t)}}get onRendered(){return this._onRendered}invalidate(e){const t=`invalidate(${e?` <- ${e} `:""})`,n=`${this.viewerToLog()}.${t}`;this.render(E.None,t),this.viewSyncer.sync(`${n}`,(async()=>{this._onRendered.next()}))}async awaitRendered(e=5e3){await(0,g.zg)(this.onRendered,(()=>{}),(()=>{this.invalidate()}),e);const t=this.viewSyncer.resetErrors();if(t.length>0)throw t[0]}}T.residuesSet="nucleotides",T.viewerCounter=-1},8755:(e,t,n)=>{"use strict";n.d(t,{Y:()=>o,x:()=>i});var s=n(701),r=n(3649);class i{constructor(e,t=!0){return this.substructure=e,this.readOnly=t,new Proxy(this,{set:(e,t,n)=>{if(r._package.logger.debug(`BioFilterProps.set ${t.toString()}( '${n}' )`),this.readOnly)throw new Error("Properties are immutable.");return e[t]=n,!0}})}}class o{constructor(){this.onChanged=new s.Subject,this._propsChanging=!1}get props(){return this._props||(this._props=this.emptyProps),this._props}set props(e){this._propsChanging=!0;try{this._props=e,this.applyProps(),this.onChanged.next()}finally{this._propsChanging=!1}}saveProps(){const e={};for(const[t,n]of Object.entries(this.props))"_onChanged"!==t&&(e[t]=this.props[t]);return e}async detach(){}get filterSummary(){return this.props.substructure}get isFiltering(){return""!==this.props.substructure}resetFilter(){this.props=this.emptyProps,this.onChanged.next()}}},5393:(e,t,n)=>{"use strict";n.d(t,{ST:()=>x});var s=n(3870),r=n(976),i=n(4469),o=n(6414),a=n.n(o),l=n(701),c=n(8447),u=n(8467),h=n(8260),d=n(172),m=n(7983),p=n(8755),f=n(3336),g=n.n(f),y=n(7945),b=n(4293),v=n(3649);class w extends p.Y{viewerToLog(){return`HelmBioFilter<${this.viewerId}>`}get type(){return"HelmBioFilter"}constructor(){super(),this.emptyProps=new p.x(""),this._filterPanel=s.div("",{style:{cursor:"pointer"}}),this.viewerId=++w.viewerCounter,this.viewSubs=[],this.logger=v._package.logger}async detach(){await super.detach();for(const e of this.viewSubs)e.unsubscribe()}async attach(){this.viewerToLog();try{const e=await async function(){const e="Helm",t=r.Func.find({package:e,name:"getHelmHelper"});if(0===t.length)throw new Error(`Package '${e}' must be installed for HelmHelper.`);return(await t[0].prepare().call()).getOutputParamValue()}();let t,n;this.helmEditor=e.createHelmWebEditor(),this.logger.warning("TEST: HelmBioFilter.init().sync() waitForElementInDom waiting..."),await s.tools.waitForElementInDom(this._filterPanel),this.logger.warning("TEST: HelmBioFilter.init().sync() waitForElementInDom ready"),this.updateFilterPanel(),this.viewSubs.push((0,l.fromEvent)(this._filterPanel,"click").subscribe((()=>{t=s.div(),n=e.createWebEditorApp(t,this.props.substructure),s.dialog({showHeader:!1,showFooter:!0}).add(t).onOK((()=>{try{const e=n.canvas.getHelm(!0).replace(/<\/span>/g,"").replace(/<span style='background:#bbf;'>/g,"");this.props=new p.x(e)}catch(e){this.logger.error(e)}finally{g()(t).empty(),t=null,n=null}})).onCancel((()=>{g()(t).empty(),t=null,n=null})).show({modal:!0,fullScreen:!0})}))),this.viewSubs.push(s.onSizeChanged(this._filterPanel).subscribe((e=>{try{if(n){const e=n.canvas.getHelm(!0).replace(/<\/span>/g,"").replace(/<span style='background:#bbf;'>/g,"");this.updateFilterPanel(e)}}catch(e){const[t,n]=(0,y.yf)(e);this.logger.error(t,void 0,n)}})))}catch(e){const[t,n]=(0,y.yf)(e),r=this._filterPanel;r.innerText="error",r.classList.add("d4-error"),s.tooltip.bind(r,t)}}applyProps(){this.helmEditor&&this.updateFilterPanel(this.props.substructure)}get filterPanel(){return this._filterPanel}updateFilterPanel(e){if(!this.helmEditor)throw new Error("helmEditor is not created, the filter is not in dom yet");const t=this._filterPanel.parentElement.clientWidth<100?100:this._filterPanel.parentElement.clientWidth,n=t/2;if(e)(0,b.Y)(this._filterPanel,this.helmEditor.host),this.helmEditor.editor.setHelm(e),this.helmEditor.resizeEditor(t,n);else{const e=s.divText("Click to edit","helm-substructure-filter");(0,b.Y)(this._filterPanel,e)}}async substructureSearch(e){return await(0,u.gw)(10),await(0,m.QF)(this.props.substructure,e)}}w.viewerCounter=-1;const C="bio-substructure-filter";class S{constructor(e,t,n,s,r){this.props=e,this.filterId=t,this.dataFrameId=n,this.columnName=s,this.bitset=r}}class A extends p.x{constructor(e,t){super(e,!1),this.separator=t,this.readOnly=!0}}class x extends r.Filter{get calculating(){return"initial"==this.loader.style.display}set calculating(e){this.loader.style.display=e?"initial":"none"}get filterSummary(){return this.bioFilter.filterSummary}get isFiltering(){return super.isFiltering&&(this.bioFilter?.isFiltering??!1)}get isReadyToApplyFilter(){return!this.calculating&&null!=this.bitset}get debounceTime(){if(null==this.column)return 1e3;const e=this.column.length;return e<500?0:e>1e4?1e3:Math.floor((e-500)/9500*1e3)}constructor(){return super(),this.bioFilter=null,this.bitset=null,this.notation=void 0,this.filterId=++x.filterCounter,this.viewSubs=[],this._onRendered=new l.Subject,this.root=s.divV([]),this.loader=s.loader(),this.calculating=!1,this.filterSyncer=new d.c(this.logger=v._package.logger),new Proxy(this,{set:(e,t,n)=>(e[t]=n,!0)})}filterToLog(){return`BioSubstructureFilter<${this.filterId}>`}attach(e){const t=super.attach.bind(this),n=`${this.filterToLog()}.attach()`;this.filterSyncer.sync(n,(async()=>{t(e),this.column||(this.columnName?this.column=this.dataFrame.getCol(this.columnName):this.column=e.columns.bySemType(r.SEMTYPE.MACROMOLECULE)),h.g.forColumn(this.column),this.columnName??(this.columnName=this.column?.name),this.notation??(this.notation=this.column?.getTag(r.TAGS.UNITS)),this.bioFilter=this.notation===c.r2.FASTA?new E:this.notation===c.r2.SEPARATOR?new I(this.column.getTag("separator")):new w,this.root.appendChild(this.bioFilter.filterPanel),this.root.appendChild(this.loader),await this.bioFilter.attach(),this.viewSubs.push(r.debounce(this.bioFilter.onChanged,this.debounceTime).subscribe(this.bioFilterOnChangedDebounced.bind(this))),this.viewSubs.push(i.events.onResetFilterRequest.subscribe(this.grokEventsOnResetFilterRequest.bind(this))),this.viewSubs.push(i.events.onCustomEvent(C).subscribe(this.filterOnSync.bind(this)))}))}detach(){const e=super.detach.bind(this),t=`${this.filterToLog()}.detach()`;this.filterSyncer.sync(t,(async()=>{for(const e of this.viewSubs)e.unsubscribe();this.viewSubs=[],e(),this.bioFilter&&this.bioFilter.detach(),this.bioFilter=null}))}filterOnSync(e){e.filterId!==this.filterId&&e.dataFrameId===this.dataFrame.id&&e.columnName===this.columnName&&(this.bioFilter.props=e.props)}applyFilter(){const e=`${this.filterToLog()}.applyFilter()`;this.logger.debug(`${e}, IN`),this.bitset&&!this.isDetached&&this.dataFrame?.filter.and(this.bitset)}saveState(){const e=`${this.filterToLog()}.saveState()`,t=super.saveState();return this.logger.debug(`${e}, super.state = ${JSON.stringify(t)}`),t.props=this.bioFilter.saveProps(),t}applyState(e){const t=`${this.filterToLog()}.applyState()`;super.applyState(e),this.filterSyncer.sync(t,(async()=>{e.props&&this.bioFilter&&(this.bioFilter.props=e.props)}))}fireFilterSync(){const e=`${this.filterToLog()}.fireFilterSync()`;v._package.logger.debug(`${e}, bioFilter = ${this.bioFilter?this.bioFilter.constructor.name:"null"}`+(this.bioFilter?`, props = ${JSON.stringify(this.bioFilter.saveProps())}`:"")),i.events.fireCustomEvent(C,new S(this.bioFilter.props,this.filterId,this.dataFrame.id,this.columnName,this.bitset))}bioFilterOnChangedDebounced(){if(!this.dataFrame)return;const e=`${this.filterToLog()}.bioFilterOnChangedDebounced()`;if(v._package.logger.debug(`${e}, start, isFiltering = ${this.isFiltering}, props = ${JSON.stringify(this.bioFilter.saveProps())}`),!this.isFiltering)return this.bitset=null,void this.dataFrame.rows.requestFilter();a()(this.dataFrame.rows.filters).has(`${this.columnName}: ${this.filterSummary}`)||this.filterSyncer.sync(e,(async()=>{this.calculating=!0;try{v._package.logger.debug(`${e}, before substructureSearch`),this.bitset=await(this.bioFilter?.substructureSearch(this.column)),v._package.logger.debug(`${e}, after substructureSearch`),this.calculating=!1,this.fireFilterSync(),this.dataFrame?.rows.requestFilter()}finally{this.calculating=!1,v._package.logger.debug(`${e}, end`)}}))}grokEventsOnResetFilterRequest(){const e=`${this.filterToLog()}.grokEventsOnResetFilterRequest()`;v._package.logger.debug(`${e}`),this.bioFilter?.resetFilter()}get onRendered(){return this._onRendered}invalidate(e){const t=`${this.filterToLog()}.invalidate(${e?` <- ${e} `:""})`;this.filterSyncer.sync(t,(async()=>{this._onRendered.next()}))}async awaitRendered(e=1e4){const t=`awaitRendered( ${e} )`,n=`${this.filterToLog()}.${t}`;await(0,u.gw)(0),await(0,u.zg)(this.onRendered,(()=>{this.logger.debug(`${n}, _onRendered event caught`)}),(()=>{this.invalidate(t)}),e,`${n} ${e} timeout`);const s=this.filterSyncer.resetErrors();if(s.length>0)throw s[0]}}x.filterCounter=-1;class E extends p.Y{get type(){return"FastaBioFilter"}constructor(){super(),this.emptyProps=new p.x(""),this.substructureInput=s.stringInput("","",(()=>{this.props=new p.x(this.substructureInput.value),this._propsChanging||this.onChanged.next()}),{placeholder:"Substructure"})}applyProps(){this.substructureInput.value!==this.props.substructure&&(this.substructureInput.value=this.props.substructure)}get filterPanel(){return this.substructureInput.root}get isFiltering(){return""!==this.substructureInput.value}async substructureSearch(e){return(0,m.pf)(this.props.substructure,e)}async attach(){}async detach(){await super.detach()}}class I extends p.Y{get type(){return"SeparatorBioFilter"}constructor(e){super(),this.emptyProps=new A("",void 0),this.colSeparator="",this.substructureInput=s.stringInput("","",(()=>{this.props=new A(this.substructureInput.value,this.props.separator),this._propsChanging||this.onChanged.next()}),{placeholder:"Substructure"}),this.separatorInput=s.stringInput("",this.colSeparator=e,(()=>{const e=this.separatorInput.value?this.separatorInput.value:void 0;this.props=new A(this.props.substructure,e),this._propsChanging||this.onChanged.next()}),{placeholder:"Separator"})}applyProps(){this.substructureInput.value!==this.props.substructure&&(this.substructureInput.value=this.props.substructure);const e=this.props.separator??this.colSeparator;this.separatorInput.value!==e&&(this.separatorInput.value=e)}get filterSummary(){return this.props.separator?this.props.separator:this.colSeparator,`${this.props.substructure}, {sep}`}get isFiltering(){return""!==this.props.substructure}resetFilter(){this.props=new A("")}get filterPanel(){return s.divV([this.substructureInput.root,this.separatorInput.root])}get substructure(){return this.separatorInput.value&&this.separatorInput.value!==this.colSeparator?this.substructureInput.value.replaceAll(this.separatorInput.value,this.colSeparator):this.substructureInput.value}set substructure(e){this.substructureInput.value=e}async substructureSearch(e){return(0,m.pf)(this.substructure,e,this.colSeparator)}async attach(){}async detach(){await super.detach()}}},8770:(e,t,n)=>{"use strict";n.d(t,{_:()=>I,t:()=>E});var s=n(3870),r=n(976),i=n(6414),o=n.n(i),a=n(8447),l=n(7331),c=n(3379),u=n.n(c),h=n(7795),d=n.n(h),m=n(569),p=n.n(m),f=n(3565),g=n.n(f),y=n(9216),b=n.n(y),v=n(4589),w=n.n(v),C=n(5362),S={};S.styleTagTransform=w(),S.setAttributes=g(),S.insert=p().bind(null,"head"),S.domAPI=d(),S.insertStyleElement=b(),u()(C.Z,S),C.Z&&C.Z.locals&&C.Z.locals;var A=n(8260),x=n(6286);function E(e){const t=s.div();t.classList.add("macromolecule-cell-comp-analysis-host");const n=e.cell.column.tags.alphabet;let i=l.UE.Color;switch(n){case"DNA":case"RNA":i=(0,a.py)("DNA");break;case"PT":i=(0,a.py)("PT")}const c={},u=A.g.forColumn(e.cell.column),h=e.cell.rowIndex,d=u.getSplitted(h);o()(d.canonicals).filter((e=>e!==x.G2)).forEach((e=>{const t=c[e]||0;c[e]=t+1}));const m=I(i,c);return Array.from(m.rows).forEach((e=>{const t=e.getElementsByClassName("macromolecule-cell-comp-analysis-bar")[0].style.backgroundColor;e.cells[0].style.color=t})),t.appendChild(m),new r.Widget(t)}function I(e,t){let n=0,i=null;for(const e of Object.values(t))n+=e,i=null===i?e:Math.max(i,e);const o=i/n,a=Object.assign({},...Array.from(Object.entries(t)).sort(((e,t)=>t[1]-e[1])).map((([t,i])=>{const a=i/n,l=e.get(t),c=s.div("",{classes:"macromolecule-cell-comp-analysis-bar"});c.style.width=50*a/o+"px",c.style.backgroundColor=l,x.G2===t&&(c.style.borderWidth="1px",c.style.borderStyle="solid",c.style.borderColor=r.Color.toHtml(r.Color.lightGray));const u=x.G2===t?"-":t,h=s.div(`${(100*a).toFixed(2)}%`);return{[u]:s.div([c,h],{classes:"macromolecule-cell-comp-analysis-value"})}}))),l=s.tableFromMap(a);return Array.from(l.rows).forEach((e=>{const t=e.getElementsByClassName("macromolecule-cell-comp-analysis-bar")[0].style.backgroundColor;e.cells[0].style.color=t})),l}},540:function(e,t){!function(e){"use strict";function t(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];if(t.length>1){t[0]=t[0].slice(0,-1);for(var s=t.length-1,r=1;r<s;++r)t[r]=t[r].slice(1,-1);return t[s]=t[s].slice(1),t.join("")}return t[0]}function n(e){return"(?:"+e+")"}function s(e){return void 0===e?"undefined":null===e?"null":Object.prototype.toString.call(e).split(" ").pop().split("]").shift().toLowerCase()}function r(e){return e.toUpperCase()}function i(e){var s="[A-Za-z]",r="[0-9]",i=t(r,"[A-Fa-f]"),o=n(n("%[EFef]"+i+"%"+i+i+"%"+i+i)+"|"+n("%[89A-Fa-f]"+i+"%"+i+i)+"|"+n("%"+i+i)),a="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",l=t("[\\:\\/\\?\\#\\[\\]\\@]",a),c=e?"[\\uE000-\\uF8FF]":"[]",u=t(s,r,"[\\-\\.\\_\\~]",e?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]"),h=n(s+t(s,r,"[\\+\\-\\.]")+"*"),d=n(n(o+"|"+t(u,a,"[\\:]"))+"*"),m=(n(n("25[0-5]")+"|"+n("2[0-4]"+r)+"|"+n("1"+r+r)+"|"+n("[1-9]"+r)+"|"+r),n(n("25[0-5]")+"|"+n("2[0-4]"+r)+"|"+n("1"+r+r)+"|"+n("0?[1-9]"+r)+"|0?0?"+r)),p=n(m+"\\."+m+"\\."+m+"\\."+m),f=n(i+"{1,4}"),g=n(n(f+"\\:"+f)+"|"+p),y=n(n(f+"\\:")+"{6}"+g),b=n("\\:\\:"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+n("\\:("+P+")")+"?)")+"?("+D+"|"+B+"|"+U+"|"+H+")"),n("\\?("+j+")"),n("\\#("+W+")"),n(n("\\/\\/("+n("("+d+")@")+"?("+L+")"+n("\\:("+P+")")+"?)")+"?("+D+"|"+B+"|"+V+"|"+H+")"),n("\\?("+j+")"),n("\\#("+W+")"),n(n("\\/\\/("+n("("+d+")@")+"?("+L+")"+n("\\:("+P+")")+"?)")+"?("+D+"|"+B+"|"+U+"|"+H+")"),n("\\?("+j+")"),n("\\#("+W+")"),n("("+d+")@"),n("\\:("+P+")"),{NOT_SCHEME:new RegExp(t("[^]",s,r,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(t("[^\\%\\:]",u,a),"g"),NOT_HOST:new RegExp(t("[^\\%\\[\\]\\:]",u,a),"g"),NOT_PATH:new RegExp(t("[^\\%\\/\\:\\@]",u,a),"g"),NOT_PATH_NOSCHEME:new RegExp(t("[^\\%\\/\\@]",u,a),"g"),NOT_QUERY:new RegExp(t("[^\\%]",u,a,"[\\:\\@\\/\\?]",c),"g"),NOT_FRAGMENT:new RegExp(t("[^\\%]",u,a,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(t("[^]",u,a),"g"),UNRESERVED:new RegExp(u,"g"),OTHER_CHARS:new RegExp(t("[^\\%]",u,l),"g"),PCT_ENCODED:new RegExp(o,"g"),IPV4ADDRESS:new RegExp("^("+p+")$"),IPV6ADDRESS:new RegExp("^\\[?("+I+")"+n(n("\\%25|\\%(?!"+i+"{2})")+"("+T+")")+"?\\]?$")}}var o=i(!1),a=i(!0),l=function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var n=[],s=!0,r=!1,i=void 0;try{for(var o,a=e[Symbol.iterator]();!(s=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);s=!0);}catch(e){r=!0,i=e}finally{try{!s&&a.return&&a.return()}finally{if(r)throw i}}return n}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")},c=2147483647,u=36,h=/^xn--/,d=/[^\0-\x7E]/,m=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},f=Math.floor,g=String.fromCharCode;function y(e){throw new RangeError(p[e])}function b(e,t){var n=e.split("@"),s="";return n.length>1&&(s=n[0]+"@",e=n[1]),s+function(e,t){for(var n=[],s=e.length;s--;)n[s]=t(e[s]);return n}((e=e.replace(m,".")).split("."),t).join(".")}function v(e){for(var t=[],n=0,s=e.length;n<s;){var r=e.charCodeAt(n++);if(r>=55296&&r<=56319&&n<s){var i=e.charCodeAt(n++);56320==(64512&i)?t.push(((1023&r)<<10)+(1023&i)+65536):(t.push(r),n--)}else t.push(r)}return t}var w=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},C=function(e,t,n){var s=0;for(e=n?f(e/700):e>>1,e+=f(e/t);e>455;s+=u)e=f(e/35);return f(s+36*e/(e+38))},S=function(e){var t,n=[],s=e.length,r=0,i=128,o=72,a=e.lastIndexOf("-");a<0&&(a=0);for(var l=0;l<a;++l)e.charCodeAt(l)>=128&&y("not-basic"),n.push(e.charCodeAt(l));for(var h=a>0?a+1:0;h<s;){for(var d=r,m=1,p=u;;p+=u){h>=s&&y("invalid-input");var g=(t=e.charCodeAt(h++))-48<10?t-22:t-65<26?t-65:t-97<26?t-97:u;(g>=u||g>f((c-r)/m))&&y("overflow"),r+=g*m;var b=p<=o?1:p>=o+26?26:p-o;if(g<b)break;var v=u-b;m>f(c/v)&&y("overflow"),m*=v}var w=n.length+1;o=C(r-d,w,0==d),f(r/w)>c-i&&y("overflow"),i+=f(r/w),r%=w,n.splice(r++,0,i)}return String.fromCodePoint.apply(String,n)},A=function(e){var t=[],n=(e=v(e)).length,s=128,r=0,i=72,o=!0,a=!1,l=void 0;try{for(var h,d=e[Symbol.iterator]();!(o=(h=d.next()).done);o=!0){var m=h.value;m<128&&t.push(g(m))}}catch(e){a=!0,l=e}finally{try{!o&&d.return&&d.return()}finally{if(a)throw l}}var p=t.length,b=p;for(p&&t.push("-");b<n;){var S=c,A=!0,x=!1,E=void 0;try{for(var I,T=e[Symbol.iterator]();!(A=(I=T.next()).done);A=!0){var _=I.value;_>=s&&_<S&&(S=_)}}catch(e){x=!0,E=e}finally{try{!A&&T.return&&T.return()}finally{if(x)throw E}}var M=b+1;S-s>f((c-r)/M)&&y("overflow"),r+=(S-s)*M,s=S;var $=!0,N=!1,L=void 0;try{for(var P,R=e[Symbol.iterator]();!($=(P=R.next()).done);$=!0){var O=P.value;if(O<s&&++r>c&&y("overflow"),O==s){for(var k=r,F=u;;F+=u){var G=F<=i?1:F>=i+26?26:F-i;if(k<G)break;var D=k-G,B=u-G;t.push(g(w(G+D%B,0))),k=f(D/B)}t.push(g(w(k,0))),i=C(r,M,b==p),r=0,++b}}}catch(e){N=!0,L=e}finally{try{!$&&R.return&&R.return()}finally{if(N)throw L}}++r,++s}return t.join("")},x={version:"2.1.0",ucs2:{decode:v,encode:function(e){return String.fromCodePoint.apply(String,function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}(e))}},decode:S,encode:A,toASCII:function(e){return b(e,(function(e){return d.test(e)?"xn--"+A(e):e}))},toUnicode:function(e){return b(e,(function(e){return h.test(e)?S(e.slice(4).toLowerCase()):e}))}},E={};function I(e){var t=e.charCodeAt(0);return t<16?"%0"+t.toString(16).toUpperCase():t<128?"%"+t.toString(16).toUpperCase():t<2048?"%"+(t>>6|192).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase():"%"+(t>>12|224).toString(16).toUpperCase()+"%"+(t>>6&63|128).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase()}function T(e){for(var t="",n=0,s=e.length;n<s;){var r=parseInt(e.substr(n+1,2),16);if(r<128)t+=String.fromCharCode(r),n+=3;else if(r>=194&&r<224){if(s-n>=6){var i=parseInt(e.substr(n+4,2),16);t+=String.fromCharCode((31&r)<<6|63&i)}else t+=e.substr(n,6);n+=6}else if(r>=224){if(s-n>=9){var o=parseInt(e.substr(n+4,2),16),a=parseInt(e.substr(n+7,2),16);t+=String.fromCharCode((15&r)<<12|(63&o)<<6|63&a)}else t+=e.substr(n,9);n+=9}else t+=e.substr(n,3),n+=3}return t}function _(e,t){function n(e){var n=T(e);return n.match(t.UNRESERVED)?n:e}return e.scheme&&(e.scheme=String(e.scheme).replace(t.PCT_ENCODED,n).toLowerCase().replace(t.NOT_SCHEME,"")),void 0!==e.userinfo&&(e.userinfo=String(e.userinfo).replace(t.PCT_ENCODED,n).replace(t.NOT_USERINFO,I).replace(t.PCT_ENCODED,r)),void 0!==e.host&&(e.host=String(e.host).replace(t.PCT_ENCODED,n).toLowerCase().replace(t.NOT_HOST,I).replace(t.PCT_ENCODED,r)),void 0!==e.path&&(e.path=String(e.path).replace(t.PCT_ENCODED,n).replace(e.scheme?t.NOT_PATH:t.NOT_PATH_NOSCHEME,I).replace(t.PCT_ENCODED,r)),void 0!==e.query&&(e.query=String(e.query).replace(t.PCT_ENCODED,n).replace(t.NOT_QUERY,I).replace(t.PCT_ENCODED,r)),void 0!==e.fragment&&(e.fragment=String(e.fragment).replace(t.PCT_ENCODED,n).replace(t.NOT_FRAGMENT,I).replace(t.PCT_ENCODED,r)),e}function M(e){return e.replace(/^0*(.*)/,"$1")||"0"}function $(e,t){var n=e.match(t.IPV4ADDRESS)||[],s=l(n,2)[1];return s?s.split(".").map(M).join("."):e}function N(e,t){var n=e.match(t.IPV6ADDRESS)||[],s=l(n,3),r=s[1],i=s[2];if(r){for(var o=r.toLowerCase().split("::").reverse(),a=l(o,2),c=a[0],u=a[1],h=u?u.split(":").map(M):[],d=c.split(":").map(M),m=t.IPV4ADDRESS.test(d[d.length-1]),p=m?7:8,f=d.length-p,g=Array(p),y=0;y<p;++y)g[y]=h[y]||d[f+y]||"";m&&(g[p-1]=$(g[p-1],t));var b=g.reduce((function(e,t,n){if(!t||"0"===t){var s=e[e.length-1];s&&s.index+s.length===n?s.length++:e.push({index:n,length:1})}return e}),[]).sort((function(e,t){return t.length-e.length}))[0],v=void 0;if(b&&b.length>1){var w=g.slice(0,b.index),C=g.slice(b.index+b.length);v=w.join(":")+"::"+C.join(":")}else v=g.join(":");return i&&(v+="%"+i),v}return e}var L=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,P=void 0==="".match(/(){0}/)[1];function R(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={},s=!1!==t.iri?a:o;"suffix"===t.reference&&(e=(t.scheme?t.scheme+":":"")+"//"+e);var r=e.match(L);if(r){P?(n.scheme=r[1],n.userinfo=r[3],n.host=r[4],n.port=parseInt(r[5],10),n.path=r[6]||"",n.query=r[7],n.fragment=r[8],isNaN(n.port)&&(n.port=r[5])):(n.scheme=r[1]||void 0,n.userinfo=-1!==e.indexOf("@")?r[3]:void 0,n.host=-1!==e.indexOf("//")?r[4]:void 0,n.port=parseInt(r[5],10),n.path=r[6]||"",n.query=-1!==e.indexOf("?")?r[7]:void 0,n.fragment=-1!==e.indexOf("#")?r[8]:void 0,isNaN(n.port)&&(n.port=e.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?r[4]:void 0)),n.host&&(n.host=N($(n.host,s),s)),void 0!==n.scheme||void 0!==n.userinfo||void 0!==n.host||void 0!==n.port||n.path||void 0!==n.query?void 0===n.scheme?n.reference="relative":void 0===n.fragment?n.reference="absolute":n.reference="uri":n.reference="same-document",t.reference&&"suffix"!==t.reference&&t.reference!==n.reference&&(n.error=n.error||"URI is not a "+t.reference+" reference.");var i=E[(t.scheme||n.scheme||"").toLowerCase()];if(t.unicodeSupport||i&&i.unicodeSupport)_(n,s);else{if(n.host&&(t.domainHost||i&&i.domainHost))try{n.host=x.toASCII(n.host.replace(s.PCT_ENCODED,T).toLowerCase())}catch(e){n.error=n.error||"Host's domain name can not be converted to ASCII via punycode: "+e}_(n,o)}i&&i.parse&&i.parse(n,t)}else n.error=n.error||"URI can not be parsed.";return n}var O=/^\.\.?\//,k=/^\/\.(\/|$)/,F=/^\/\.\.(\/|$)/,G=/^\/?(?:.|\n)*?(?=\/|$)/;function D(e){for(var t=[];e.length;)if(e.match(O))e=e.replace(O,"");else if(e.match(k))e=e.replace(k,"/");else if(e.match(F))e=e.replace(F,"/"),t.pop();else if("."===e||".."===e)e="";else{var n=e.match(G);if(!n)throw new Error("Unexpected dot segment condition");var s=n[0];e=e.slice(s.length),t.push(s)}return t.join("")}function B(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.iri?a:o,s=[],r=E[(t.scheme||e.scheme||"").toLowerCase()];if(r&&r.serialize&&r.serialize(e,t),e.host)if(n.IPV6ADDRESS.test(e.host));else if(t.domainHost||r&&r.domainHost)try{e.host=t.iri?x.toUnicode(e.host):x.toASCII(e.host.replace(n.PCT_ENCODED,T).toLowerCase())}catch(n){e.error=e.error||"Host's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+n}_(e,n),"suffix"!==t.reference&&e.scheme&&(s.push(e.scheme),s.push(":"));var i=function(e,t){var n=!1!==t.iri?a:o,s=[];return void 0!==e.userinfo&&(s.push(e.userinfo),s.push("@")),void 0!==e.host&&s.push(N($(String(e.host),n),n).replace(n.IPV6ADDRESS,(function(e,t,n){return"["+t+(n?"%25"+n:"")+"]"}))),"number"!=typeof e.port&&"string"!=typeof e.port||(s.push(":"),s.push(String(e.port))),s.length?s.join(""):void 0}(e,t);if(void 0!==i&&("suffix"!==t.reference&&s.push("//"),s.push(i),e.path&&"/"!==e.path.charAt(0)&&s.push("/")),void 0!==e.path){var l=e.path;t.absolutePath||r&&r.absolutePath||(l=D(l)),void 0===i&&(l=l.replace(/^\/\//,"/%2F")),s.push(l)}return void 0!==e.query&&(s.push("?"),s.push(e.query)),void 0!==e.fragment&&(s.push("#"),s.push(e.fragment)),s.join("")}function V(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s={};return arguments[3]||(e=R(B(e,n),n),t=R(B(t,n),n)),!(n=n||{}).tolerant&&t.scheme?(s.scheme=t.scheme,s.userinfo=t.userinfo,s.host=t.host,s.port=t.port,s.path=D(t.path||""),s.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(s.userinfo=t.userinfo,s.host=t.host,s.port=t.port,s.path=D(t.path||""),s.query=t.query):(t.path?("/"===t.path.charAt(0)?s.path=D(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?s.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:s.path=t.path:s.path="/"+t.path,s.path=D(s.path)),s.query=t.query):(s.path=e.path,void 0!==t.query?s.query=t.query:s.query=e.query),s.userinfo=e.userinfo,s.host=e.host,s.port=e.port),s.scheme=e.scheme),s.fragment=t.fragment,s}function U(e,t){return e&&e.toString().replace(t&&t.iri?a.PCT_ENCODED:o.PCT_ENCODED,T)}var H={scheme:"http",domainHost:!0,parse:function(e,t){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e},serialize:function(e,t){var n="https"===String(e.scheme).toLowerCase();return e.port!==(n?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}},j={scheme:"https",domainHost:H.domainHost,parse:H.parse,serialize:H.serialize};function W(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}var Y={scheme:"ws",domainHost:!0,parse:function(e,t){var n=e;return n.secure=W(n),n.resourceName=(n.path||"/")+(n.query?"?"+n.query:""),n.path=void 0,n.query=void 0,n},serialize:function(e,t){if(e.port!==(W(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){var n=e.resourceName.split("?"),s=l(n,2),r=s[0],i=s[1];e.path=r&&"/"!==r?r:void 0,e.query=i,e.resourceName=void 0}return e.fragment=void 0,e}},Z={scheme:"wss",domainHost:Y.domainHost,parse:Y.parse,serialize:Y.serialize},q={},K="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",z="[0-9A-Fa-f]",X=n(n("%[EFef]"+z+"%"+z+z+"%"+z+z)+"|"+n("%[89A-Fa-f]"+z+"%"+z+z)+"|"+n("%"+z+z)),J=t("[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",'[\\"\\\\]'),Q=new RegExp(K,"g"),ee=new RegExp(X,"g"),te=new RegExp(t("[^]","[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]","[\\.]",'[\\"]',J),"g"),ne=new RegExp(t("[^]",K,"[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"),"g"),se=ne;function re(e){var t=T(e);return t.match(Q)?t:e}var ie={scheme:"mailto",parse:function(e,t){var n=e,s=n.to=n.path?n.path.split(","):[];if(n.path=void 0,n.query){for(var r=!1,i={},o=n.query.split("&"),a=0,l=o.length;a<l;++a){var c=o[a].split("=");switch(c[0]){case"to":for(var u=c[1].split(","),h=0,d=u.length;h<d;++h)s.push(u[h]);break;case"subject":n.subject=U(c[1],t);break;case"body":n.body=U(c[1],t);break;default:r=!0,i[U(c[0],t)]=U(c[1],t)}}r&&(n.headers=i)}n.query=void 0;for(var m=0,p=s.length;m<p;++m){var f=s[m].split("@");if(f[0]=U(f[0]),t.unicodeSupport)f[1]=U(f[1],t).toLowerCase();else try{f[1]=x.toASCII(U(f[1],t).toLowerCase())}catch(e){n.error=n.error||"Email address's domain name can not be converted to ASCII via punycode: "+e}s[m]=f.join("@")}return n},serialize:function(e,t){var n,s=e,i=null!=(n=e.to)?n instanceof Array?n:"number"!=typeof n.length||n.split||n.setInterval||n.call?[n]:Array.prototype.slice.call(n):[];if(i){for(var o=0,a=i.length;o<a;++o){var l=String(i[o]),c=l.lastIndexOf("@"),u=l.slice(0,c).replace(ee,re).replace(ee,r).replace(te,I),h=l.slice(c+1);try{h=t.iri?x.toUnicode(h):x.toASCII(U(h,t).toLowerCase())}catch(e){s.error=s.error||"Email address's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+e}i[o]=u+"@"+h}s.path=i.join(",")}var d=e.headers=e.headers||{};e.subject&&(d.subject=e.subject),e.body&&(d.body=e.body);var m=[];for(var p in d)d[p]!==q[p]&&m.push(p.replace(ee,re).replace(ee,r).replace(ne,I)+"="+d[p].replace(ee,re).replace(ee,r).replace(se,I));return m.length&&(s.query=m.join("&")),s}},oe=/^([^\:]+)\:(.*)/,ae={scheme:"urn",parse:function(e,t){var n=e.path&&e.path.match(oe),s=e;if(n){var r=t.scheme||s.scheme||"urn",i=n[1].toLowerCase(),o=n[2],a=r+":"+(t.nid||i),l=E[a];s.nid=i,s.nss=o,s.path=void 0,l&&(s=l.parse(s,t))}else s.error=s.error||"URN can not be parsed.";return s},serialize:function(e,t){var n=t.scheme||e.scheme||"urn",s=e.nid,r=n+":"+(t.nid||s),i=E[r];i&&(e=i.serialize(e,t));var o=e,a=e.nss;return o.path=(s||t.nid)+":"+a,o}},le=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,ce={scheme:"urn:uuid",parse:function(e,t){var n=e;return n.uuid=n.nss,n.nss=void 0,t.tolerant||n.uuid&&n.uuid.match(le)||(n.error=n.error||"UUID is not valid."),n},serialize:function(e,t){var n=e;return n.nss=(e.uuid||"").toLowerCase(),n}};E[H.scheme]=H,E[j.scheme]=j,E[Y.scheme]=Y,E[Z.scheme]=Z,E[ie.scheme]=ie,E[ae.scheme]=ae,E[ce.scheme]=ce,e.SCHEMES=E,e.pctEncChar=I,e.pctDecChars=T,e.parse=R,e.removeDotSegments=D,e.serialize=B,e.resolveComponents=V,e.resolve=function(e,t,n){var s=function(e,t){var n=e;if(t)for(var s in t)n[s]=t[s];return n}({scheme:"null"},n);return B(V(R(e,s),R(t,s),s,!0),s)},e.normalize=function(e,t){return"string"==typeof e?e=B(R(e,t),t):"object"===s(e)&&(e=R(B(e,t),t)),e},e.equal=function(e,t,n){return"string"==typeof e?e=B(R(e,n),n):"object"===s(e)&&(e=B(e,n)),"string"==typeof t?t=B(R(t,n),n):"object"===s(t)&&(t=B(t,n)),e===t},e.escapeComponent=function(e,t){return e&&e.toString().replace(t&&t.iri?a.ESCAPE:o.ESCAPE,I)},e.unescapeComponent=U,Object.defineProperty(e,"__esModule",{value:!0})}(t)},3336:e=>{"use strict";e.exports=$},976:e=>{"use strict";e.exports=DG},4469:e=>{"use strict";e.exports=grok},701:e=>{"use strict";e.exports=rxjs},442:e=>{"use strict";e.exports=rxjs.operators},3870:e=>{"use strict";e.exports=ui},6414:e=>{"use strict";e.exports=wu},4775:e=>{"use strict";e.exports=JSON.parse('{"$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON AnySchema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}')},996:e=>{"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/applicator","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/applicator":true},"$dynamicAnchor":"meta","title":"Applicator vocabulary meta-schema","type":["object","boolean"],"properties":{"prefixItems":{"$ref":"#/$defs/schemaArray"},"items":{"$dynamicRef":"#meta"},"contains":{"$dynamicRef":"#meta"},"additionalProperties":{"$dynamicRef":"#meta"},"properties":{"type":"object","additionalProperties":{"$dynamicRef":"#meta"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$dynamicRef":"#meta"},"propertyNames":{"format":"regex"},"default":{}},"dependentSchemas":{"type":"object","additionalProperties":{"$dynamicRef":"#meta"},"default":{}},"propertyNames":{"$dynamicRef":"#meta"},"if":{"$dynamicRef":"#meta"},"then":{"$dynamicRef":"#meta"},"else":{"$dynamicRef":"#meta"},"allOf":{"$ref":"#/$defs/schemaArray"},"anyOf":{"$ref":"#/$defs/schemaArray"},"oneOf":{"$ref":"#/$defs/schemaArray"},"not":{"$dynamicRef":"#meta"}},"$defs":{"schemaArray":{"type":"array","minItems":1,"items":{"$dynamicRef":"#meta"}}}}')},6795:e=>{"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/content","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/content":true},"$dynamicAnchor":"meta","title":"Content vocabulary meta-schema","type":["object","boolean"],"properties":{"contentEncoding":{"type":"string"},"contentMediaType":{"type":"string"},"contentSchema":{"$dynamicRef":"#meta"}}}')},235:e=>{"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/core","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/core":true},"$dynamicAnchor":"meta","title":"Core vocabulary meta-schema","type":["object","boolean"],"properties":{"$id":{"$ref":"#/$defs/uriReferenceString","$comment":"Non-empty fragments not allowed.","pattern":"^[^#]*#?$"},"$schema":{"$ref":"#/$defs/uriString"},"$ref":{"$ref":"#/$defs/uriReferenceString"},"$anchor":{"$ref":"#/$defs/anchorString"},"$dynamicRef":{"$ref":"#/$defs/uriReferenceString"},"$dynamicAnchor":{"$ref":"#/$defs/anchorString"},"$vocabulary":{"type":"object","propertyNames":{"$ref":"#/$defs/uriString"},"additionalProperties":{"type":"boolean"}},"$comment":{"type":"string"},"$defs":{"type":"object","additionalProperties":{"$dynamicRef":"#meta"}}},"$defs":{"anchorString":{"type":"string","pattern":"^[A-Za-z_][-A-Za-z0-9._]*$"},"uriString":{"type":"string","format":"uri"},"uriReferenceString":{"type":"string","format":"uri-reference"}}}')},2567:e=>{"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/format-annotation","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/format-annotation":true},"$dynamicAnchor":"meta","title":"Format vocabulary meta-schema for annotation results","type":["object","boolean"],"properties":{"format":{"type":"string"}}}')},1233:e=>{"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/meta-data","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/meta-data":true},"$dynamicAnchor":"meta","title":"Meta-data vocabulary meta-schema","type":["object","boolean"],"properties":{"title":{"type":"string"},"description":{"type":"string"},"default":true,"deprecated":{"type":"boolean","default":false},"readOnly":{"type":"boolean","default":false},"writeOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true}}}')},5568:e=>{"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/unevaluated","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/unevaluated":true},"$dynamicAnchor":"meta","title":"Unevaluated applicator vocabulary meta-schema","type":["object","boolean"],"properties":{"unevaluatedItems":{"$dynamicRef":"#meta"},"unevaluatedProperties":{"$dynamicRef":"#meta"}}}')},1968:e=>{"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/validation","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/validation":true},"$dynamicAnchor":"meta","title":"Validation vocabulary meta-schema","type":["object","boolean"],"properties":{"type":{"anyOf":[{"$ref":"#/$defs/simpleTypes"},{"type":"array","items":{"$ref":"#/$defs/simpleTypes"},"minItems":1,"uniqueItems":true}]},"const":true,"enum":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/$defs/nonNegativeInteger"},"minLength":{"$ref":"#/$defs/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"maxItems":{"$ref":"#/$defs/nonNegativeInteger"},"minItems":{"$ref":"#/$defs/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"maxContains":{"$ref":"#/$defs/nonNegativeInteger"},"minContains":{"$ref":"#/$defs/nonNegativeInteger","default":1},"maxProperties":{"$ref":"#/$defs/nonNegativeInteger"},"minProperties":{"$ref":"#/$defs/nonNegativeIntegerDefault0"},"required":{"$ref":"#/$defs/stringArray"},"dependentRequired":{"type":"object","additionalProperties":{"$ref":"#/$defs/stringArray"}}},"$defs":{"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"$ref":"#/$defs/nonNegativeInteger","default":0},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}}}')},2577:e=>{"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/schema","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/core":true,"https://json-schema.org/draft/2020-12/vocab/applicator":true,"https://json-schema.org/draft/2020-12/vocab/unevaluated":true,"https://json-schema.org/draft/2020-12/vocab/validation":true,"https://json-schema.org/draft/2020-12/vocab/meta-data":true,"https://json-schema.org/draft/2020-12/vocab/format-annotation":true,"https://json-schema.org/draft/2020-12/vocab/content":true},"$dynamicAnchor":"meta","title":"Core and Validation specifications meta-schema","allOf":[{"$ref":"meta/core"},{"$ref":"meta/applicator"},{"$ref":"meta/unevaluated"},{"$ref":"meta/validation"},{"$ref":"meta/meta-data"},{"$ref":"meta/format-annotation"},{"$ref":"meta/content"}],"type":["object","boolean"],"$comment":"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.","properties":{"definitions":{"$comment":"\\"definitions\\" has been replaced by \\"$defs\\".","type":"object","additionalProperties":{"$dynamicRef":"#meta"},"deprecated":true,"default":{}},"dependencies":{"$comment":"\\"dependencies\\" has been split and replaced by \\"dependentSchemas\\" and \\"dependentRequired\\" in order to serve their differing semantics.","type":"object","additionalProperties":{"anyOf":[{"$dynamicRef":"#meta"},{"$ref":"meta/validation#/$defs/stringArray"}]},"deprecated":true,"default":{}},"$recursiveAnchor":{"$comment":"\\"$recursiveAnchor\\" has been replaced by \\"$dynamicAnchor\\".","$ref":"meta/core#/$defs/anchorString","deprecated":true},"$recursiveRef":{"$comment":"\\"$recursiveRef\\" has been replaced by \\"$dynamicRef\\".","$ref":"meta/core#/$defs/uriReferenceString","deprecated":true}}}')},98:e=>{"use strict";e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}')}},t={};function n(s){var r=t[s];if(void 0!==r)return r.exports;var i=t[s]={id:s,loaded:!1,exports:{}};return e[s].call(i.exports,i,i.exports,n),i.loaded=!0,i.exports}n.m=e,n.amdO={},n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.u=e=>e+".js",n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;n.g.importScripts&&(e=n.g.location+"");var t=n.g.document;if(!e&&t&&(t.currentScript&&(e=t.currentScript.src),!e)){var s=t.getElementsByTagName("script");if(s.length)for(var r=s.length-1;r>-1&&!e;)e=s[r--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})(),n.b=document.baseURI||self.location.href,n.nc=void 0;var s=n(3649);bio=s})();
|
|
8
|
+
deps: ${n}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(e){const[t,n]=function({schema:e}){const t={},n={};for(const s in e)"__proto__"!==s&&((Array.isArray(e[s])?t:n)[s]=e[s]);return[t,n]}(e);a(e,t),l(e,n)}};function a(e,t=e.schema){const{gen:n,data:r,it:o}=e;if(0===Object.keys(t).length)return;const a=n.let("missing");for(const l in t){const c=t[l];if(0===c.length)continue;const u=(0,i.propertyInData)(n,r,l,o.opts.ownProperties);e.setParams({property:l,depsCount:c.length,deps:c.join(", ")}),o.allErrors?n.if(u,(()=>{for(const t of c)(0,i.checkReportMissingProp)(e,t)})):(n.if(s._`${u} && (${(0,i.checkMissingProp)(e,c,a)})`),(0,i.reportMissingProp)(e,a),n.else())}}function l(e,t=e.schema){const{gen:n,data:s,keyword:o,it:a}=e,l=n.name("valid");for(const c in t)(0,r.alwaysValidSchema)(a,t[c])||(n.if((0,i.propertyInData)(n,s,c,a.opts.ownProperties),(()=>{const t=e.subschema({keyword:o,schemaProp:c},l);e.mergeValidEvaluated(t,l)}),(()=>n.var(l,!0))),e.ok(l))}t.validatePropertyDeps=a,t.validateSchemaDeps=l,t.default=o},7274:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(7772),r={keyword:"dependentSchemas",type:"object",schemaType:"object",code:e=>(0,s.validateSchemaDeps)(e)};t.default=r},9434:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:e})=>s.str`must match "${e.ifClause}" schema`,params:({params:e})=>s._`{failingKeyword: ${e.ifClause}}`},code(e){const{gen:t,parentSchema:n,it:i}=e;void 0===n.then&&void 0===n.else&&(0,r.checkStrictMode)(i,'"if" without "then" and "else" is ignored');const a=o(i,"then"),l=o(i,"else");if(!a&&!l)return;const c=t.let("valid",!0),u=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}(),e.reset(),a&&l){const n=t.let("ifClause");e.setParams({ifClause:n}),t.if(u,h("then",n),h("else",n))}else a?t.if(u,h("then")):t.if((0,s.not)(u),h("else"));function h(n,r){return()=>{const i=e.subschema({keyword:n},u);t.assign(c,u),e.mergeValidEvaluated(i,c),r?t.assign(r,s._`${n}`):e.setParams({ifClause:n})}}e.pass(c,(()=>e.error(!0)))}};function o(e,t){const n=e.schema[t];return void 0!==n&&!(0,r.alwaysValidSchema)(e,n)}t.default=i},8200:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(4783),r=n(2924),i=n(4665),o=n(1119),a=n(9864),l=n(7772),c=n(3708),u=n(9351),h=n(6239),d=n(2296),m=n(2182),p=n(19),f=n(4200),g=n(1125),y=n(9434),b=n(6552);t.default=function(e=!1){const t=[m.default,p.default,f.default,g.default,y.default,b.default,c.default,u.default,l.default,h.default,d.default];return e?t.push(r.default,o.default):t.push(s.default,i.default),t.push(a.default),t}},4665:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;const s=n(3487),r=n(6776),i=n(412),o={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:n}=e;if(Array.isArray(t))return a(e,"additionalItems",t);n.items=!0,(0,r.alwaysValidSchema)(n,t)||e.ok((0,i.validateArray)(e))}};function a(e,t,n=e.schema){const{gen:i,parentSchema:o,data:a,keyword:l,it:c}=e;!function(e){const{opts:s,errSchemaPath:i}=c,o=n.length,a=o===e.minItems&&(o===e.maxItems||!1===e[t]);if(s.strictTuples&&!a){const e=`"${l}" is ${o}-tuple, but minItems or maxItems/${t} are not specified or different at path "${i}"`;(0,r.checkStrictMode)(c,e,s.strictTuples)}}(o),c.opts.unevaluated&&n.length&&!0!==c.items&&(c.items=r.mergeEvaluated.items(i,n.length,c.items));const u=i.name("valid"),h=i.const("len",s._`${a}.length`);n.forEach(((t,n)=>{(0,r.alwaysValidSchema)(c,t)||(i.if(s._`${h} > ${n}`,(()=>e.subschema({keyword:l,schemaProp:n,dataProp:n},u))),e.ok(u))}))}t.validateTuple=a,t.default=o},1119:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i=n(412),o=n(4783),a={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>s.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>s._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:n,it:s}=e,{prefixItems:a}=n;s.items=!0,(0,r.alwaysValidSchema)(s,t)||(a?(0,o.validateAdditionalItems)(e,a):e.ok((0,i.validateArray)(e)))}};t.default=a},2182:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(6776),r={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:n,it:r}=e;if((0,s.alwaysValidSchema)(r,n))return void e.fail();const i=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),e.failResult(i,(()=>e.reset()),(()=>e.error()))},error:{message:"must NOT be valid"}};t.default=r},4200:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:e})=>s._`{passingSchemas: ${e.passing}}`},code(e){const{gen:t,schema:n,parentSchema:i,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&i.discriminator)return;const a=n,l=t.let("valid",!1),c=t.let("passing",null),u=t.name("_valid");e.setParams({passing:c}),t.block((function(){a.forEach(((n,i)=>{let a;(0,r.alwaysValidSchema)(o,n)?t.var(u,!0):a=e.subschema({keyword:"oneOf",schemaProp:i,compositeRule:!0},u),i>0&&t.if(s._`${u} && ${l}`).assign(l,!1).assign(c,s._`[${c}, ${i}]`).else(),t.if(u,(()=>{t.assign(l,!0),t.assign(c,i),a&&e.mergeEvaluated(a,s.Name)}))}))})),e.result(l,(()=>e.reset()),(()=>e.error(!0)))}};t.default=i},2296:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(412),r=n(3487),i=n(6776),o=n(6776),a={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,data:a,parentSchema:l,it:c}=e,{opts:u}=c,h=(0,s.allSchemaProperties)(n),d=h.filter((e=>(0,i.alwaysValidSchema)(c,n[e])));if(0===h.length||d.length===h.length&&(!c.opts.unevaluated||!0===c.props))return;const m=u.strictSchema&&!u.allowMatchingProperties&&l.properties,p=t.name("valid");!0===c.props||c.props instanceof r.Name||(c.props=(0,o.evaluatedPropsToName)(t,c.props));const{props:f}=c;function g(e){for(const t in m)new RegExp(e).test(t)&&(0,i.checkStrictMode)(c,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function y(n){t.forIn("key",a,(i=>{t.if(r._`${(0,s.usePattern)(e,n)}.test(${i})`,(()=>{const s=d.includes(n);s||e.subschema({keyword:"patternProperties",schemaProp:n,dataProp:i,dataPropType:o.Type.Str},p),c.opts.unevaluated&&!0!==f?t.assign(r._`${f}[${i}]`,!0):s||c.allErrors||t.if((0,r.not)(p),(()=>t.break()))}))}))}!function(){for(const e of h)m&&g(e),c.allErrors?y(e):(t.var(p,!0),y(e),t.if(p))}()}};t.default=a},2924:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(4665),r={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,s.validateTuple)(e,"items")};t.default=r},6239:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(4815),r=n(412),i=n(6776),o=n(9351),a={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,parentSchema:a,data:l,it:c}=e;"all"===c.opts.removeAdditional&&void 0===a.additionalProperties&&o.default.code(new s.KeywordCxt(c,o.default,"additionalProperties"));const u=(0,r.allSchemaProperties)(n);for(const e of u)c.definedProperties.add(e);c.opts.unevaluated&&u.length&&!0!==c.props&&(c.props=i.mergeEvaluated.props(t,(0,i.toHash)(u),c.props));const h=u.filter((e=>!(0,i.alwaysValidSchema)(c,n[e])));if(0===h.length)return;const d=t.name("valid");for(const n of h)m(n)?p(n):(t.if((0,r.propertyInData)(t,l,n,c.opts.ownProperties)),p(n),c.allErrors||t.else().var(d,!0),t.endIf()),e.it.definedProperties.add(n),e.ok(d);function m(e){return c.opts.useDefaults&&!c.compositeRule&&void 0!==n[e].default}function p(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},d)}}};t.default=a},3708:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:e})=>s._`{propertyName: ${e.propertyName}}`},code(e){const{gen:t,schema:n,data:i,it:o}=e;if((0,r.alwaysValidSchema)(o,n))return;const a=t.name("valid");t.forIn("key",i,(n=>{e.setParams({propertyName:n}),e.subschema({keyword:"propertyNames",data:n,dataTypes:["string"],propertyName:n,compositeRule:!0},a),t.if((0,s.not)(a),(()=>{e.error(!0),o.allErrors||t.break()}))})),e.ok(a)}};t.default=i},6552:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(6776),r={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){void 0===t.if&&(0,s.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};t.default=r},412:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateUnion=t.validateArray=t.usePattern=t.callValidateCode=t.schemaProperties=t.allSchemaProperties=t.noPropertyInData=t.propertyInData=t.isOwnProperty=t.hasPropFunc=t.reportMissingProp=t.checkMissingProp=t.checkReportMissingProp=void 0;const s=n(3487),r=n(6776),i=n(2141),o=n(6776);function a(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:s._`Object.prototype.hasOwnProperty`})}function l(e,t,n){return s._`${a(e)}.call(${t}, ${n})`}function c(e,t,n,r){const i=s._`${t}${(0,s.getProperty)(n)} === undefined`;return r?(0,s.or)(i,(0,s.not)(l(e,t,n))):i}function u(e){return e?Object.keys(e).filter((e=>"__proto__"!==e)):[]}t.checkReportMissingProp=function(e,t){const{gen:n,data:r,it:i}=e;n.if(c(n,r,t,i.opts.ownProperties),(()=>{e.setParams({missingProperty:s._`${t}`},!0),e.error()}))},t.checkMissingProp=function({gen:e,data:t,it:{opts:n}},r,i){return(0,s.or)(...r.map((r=>(0,s.and)(c(e,t,r,n.ownProperties),s._`${i} = ${r}`))))},t.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},t.hasPropFunc=a,t.isOwnProperty=l,t.propertyInData=function(e,t,n,r){const i=s._`${t}${(0,s.getProperty)(n)} !== undefined`;return r?s._`${i} && ${l(e,t,n)}`:i},t.noPropertyInData=c,t.allSchemaProperties=u,t.schemaProperties=function(e,t){return u(t).filter((n=>!(0,r.alwaysValidSchema)(e,t[n])))},t.callValidateCode=function({schemaCode:e,data:t,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:a},it:l},c,u,h){const d=h?s._`${e}, ${t}, ${r}${o}`:t,m=[[i.default.instancePath,(0,s.strConcat)(i.default.instancePath,a)],[i.default.parentData,l.parentData],[i.default.parentDataProperty,l.parentDataProperty],[i.default.rootData,i.default.rootData]];l.opts.dynamicRef&&m.push([i.default.dynamicAnchors,i.default.dynamicAnchors]);const p=s._`${d}, ${n.object(...m)}`;return u!==s.nil?s._`${c}.call(${u}, ${p})`:s._`${c}(${p})`};const h=s._`new RegExp`;t.usePattern=function({gen:e,it:{opts:t}},n){const r=t.unicodeRegExp?"u":"",{regExp:i}=t.code,a=i(n,r);return e.scopeValue("pattern",{key:a.toString(),ref:a,code:s._`${"new RegExp"===i.code?h:(0,o.useFunc)(e,i)}(${n}, ${r})`})},t.validateArray=function(e){const{gen:t,data:n,keyword:i,it:o}=e,a=t.name("valid");if(o.allErrors){const e=t.let("valid",!0);return l((()=>t.assign(e,!1))),e}return t.var(a,!0),l((()=>t.break())),a;function l(o){const l=t.const("len",s._`${n}.length`);t.forRange("i",0,l,(n=>{e.subschema({keyword:i,dataProp:n,dataPropType:r.Type.Num},a),t.if((0,s.not)(a),o)}))}},t.validateUnion=function(e){const{gen:t,schema:n,keyword:i,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some((e=>(0,r.alwaysValidSchema)(o,e)))&&!o.opts.unevaluated)return;const a=t.let("valid",!1),l=t.name("_valid");t.block((()=>n.forEach(((n,r)=>{const o=e.subschema({keyword:i,schemaProp:r,compositeRule:!0},l);t.assign(a,s._`${a} || ${l}`),e.mergeValidEvaluated(o,l)||t.if((0,s.not)(a))})))),e.result(a,(()=>e.reset()),(()=>e.error(!0)))}},8386:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};t.default=n},5684:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(8386),r=n(8280),i=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",s.default,r.default];t.default=i},8280:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;const s=n(6646),r=n(412),i=n(3487),o=n(2141),a=n(5173),l=n(6776),c={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:n,it:r}=e,{baseId:o,schemaEnv:l,validateName:c,opts:d,self:m}=r,{root:p}=l;if(("#"===n||"#/"===n)&&o===p.baseId)return function(){if(l===p)return h(e,c,l,l.$async);const n=t.scopeValue("root",{ref:p});return h(e,i._`${n}.validate`,p,p.$async)}();const f=a.resolveRef.call(m,p,o,n);if(void 0===f)throw new s.default(r.opts.uriResolver,o,n);return f instanceof a.SchemaEnv?function(t){const n=u(e,t);h(e,n,t,t.$async)}(f):function(s){const r=t.scopeValue("schema",!0===d.code.source?{ref:s,code:(0,i.stringify)(s)}:{ref:s}),o=t.name("valid"),a=e.subschema({schema:s,dataTypes:[],schemaPath:i.nil,topSchemaRef:r,errSchemaPath:n},o);e.mergeEvaluated(a),e.ok(o)}(f)}};function u(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):i._`${n.scopeValue("wrapper",{ref:t})}.validate`}function h(e,t,n,s){const{gen:a,it:c}=e,{allErrors:u,schemaEnv:h,opts:d}=c,m=d.passContext?o.default.this:i.nil;function p(e){const t=i._`${e}.errors`;a.assign(o.default.vErrors,i._`${o.default.vErrors} === null ? ${t} : ${o.default.vErrors}.concat(${t})`),a.assign(o.default.errors,i._`${o.default.vErrors}.length`)}function f(e){var t;if(!c.opts.unevaluated)return;const s=null===(t=null==n?void 0:n.validate)||void 0===t?void 0:t.evaluated;if(!0!==c.props)if(s&&!s.dynamicProps)void 0!==s.props&&(c.props=l.mergeEvaluated.props(a,s.props,c.props));else{const t=a.var("props",i._`${e}.evaluated.props`);c.props=l.mergeEvaluated.props(a,t,c.props,i.Name)}if(!0!==c.items)if(s&&!s.dynamicItems)void 0!==s.items&&(c.items=l.mergeEvaluated.items(a,s.items,c.items));else{const t=a.var("items",i._`${e}.evaluated.items`);c.items=l.mergeEvaluated.items(a,t,c.items,i.Name)}}s?function(){if(!h.$async)throw new Error("async schema referenced by sync schema");const n=a.let("valid");a.try((()=>{a.code(i._`await ${(0,r.callValidateCode)(e,t,m)}`),f(t),u||a.assign(n,!0)}),(e=>{a.if(i._`!(${e} instanceof ${c.ValidationError})`,(()=>a.throw(e))),p(e),u||a.assign(n,!1)})),e.ok(n)}():e.result((0,r.callValidateCode)(e,t,m),(()=>f(t)),(()=>p(t)))}t.getValidate=u,t.callRef=h,t.default=c},1240:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(9306),i=n(5173),o=n(6776),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===r.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>s._`{error: ${e}, tag: ${n}, tagValue: ${t}}`},code(e){const{gen:t,data:n,schema:a,parentSchema:l,it:c}=e,{oneOf:u}=l;if(!c.opts.discriminator)throw new Error("discriminator: requires discriminator option");const h=a.propertyName;if("string"!=typeof h)throw new Error("discriminator: requires propertyName");if(a.mapping)throw new Error("discriminator: mapping is not supported");if(!u)throw new Error("discriminator: requires oneOf keyword");const d=t.let("valid",!1),m=t.const("tag",s._`${n}${(0,s.getProperty)(h)}`);function p(n){const r=t.name("valid"),i=e.subschema({keyword:"oneOf",schemaProp:n},r);return e.mergeEvaluated(i,s.Name),r}t.if(s._`typeof ${m} == "string"`,(()=>function(){const n=function(){var e;const t={},n=r(l);let s=!0;for(let t=0;t<u.length;t++){let l=u[t];(null==l?void 0:l.$ref)&&!(0,o.schemaHasRulesButRef)(l,c.self.RULES)&&(l=i.resolveRef.call(c.self,c.schemaEnv.root,c.baseId,null==l?void 0:l.$ref),l instanceof i.SchemaEnv&&(l=l.schema));const d=null===(e=null==l?void 0:l.properties)||void 0===e?void 0:e[h];if("object"!=typeof d)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${h}"`);s=s&&(n||r(l)),a(d,t)}if(!s)throw new Error(`discriminator: "${h}" must be required`);return t;function r({required:e}){return Array.isArray(e)&&e.includes(h)}function a(e,t){if(e.const)d(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${h}" must have "const" or "enum"`);for(const n of e.enum)d(n,t)}}function d(e,n){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${h}" values must be unique strings`);t[e]=n}}();t.if(!1);for(const e in n)t.elseIf(s._`${m} === ${e}`),t.assign(d,p(n[e]));t.else(),e.error(!1,{discrError:r.DiscrError.Mapping,tag:m,tagName:h}),t.endIf()}()),(()=>e.error(!1,{discrError:r.DiscrError.Tag,tag:m,tagName:h}))),e.ok(d)}};t.default=a},9306:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.DiscrError=void 0,(n=t.DiscrError||(t.DiscrError={})).Tag="tag",n.Mapping="mapping"},7299:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(5684),r=n(2649),i=n(8200),o=n(6121),a=n(1448),l=n(808),c=n(9502),u=n(6167),h=[o.default,s.default,r.default,(0,i.default)(!0),c.default,u.metadataVocabulary,u.contentVocabulary,a.default,l.default];t.default=h},3924:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(5684),r=n(2649),i=n(8200),o=n(9502),a=n(6167),l=[s.default,r.default,(0,i.default)(),o.default,a.metadataVocabulary,a.contentVocabulary];t.default=l},6215:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dynamicAnchor=void 0;const s=n(3487),r=n(2141),i=n(5173),o=n(8280),a={keyword:"$dynamicAnchor",schemaType:"string",code:e=>l(e,e.schema)};function l(e,t){const{gen:n,it:a}=e;a.schemaEnv.root.dynamicAnchors[t]=!0;const l=s._`${r.default.dynamicAnchors}${(0,s.getProperty)(t)}`,c="#"===a.errSchemaPath?a.validateName:function(e){const{schemaEnv:t,schema:n,self:s}=e.it,{root:r,baseId:a,localRefs:l,meta:c}=t.root,{schemaId:u}=s.opts,h=new i.SchemaEnv({schema:n,schemaId:u,root:r,baseId:a,localRefs:l,meta:c});return i.compileSchema.call(s,h),(0,o.getValidate)(e,h)}(e);n.if(s._`!${l}`,(()=>n.assign(l,c)))}t.dynamicAnchor=l,t.default=a},1919:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dynamicRef=void 0;const s=n(3487),r=n(2141),i=n(8280),o={keyword:"$dynamicRef",schemaType:"string",code:e=>a(e,e.schema)};function a(e,t){const{gen:n,keyword:o,it:a}=e;if("#"!==t[0])throw new Error(`"${o}" only supports hash fragment reference`);const l=t.slice(1);if(a.allErrors)c();else{const t=n.let("valid",!1);c(t),e.ok(t)}function c(e){if(a.schemaEnv.root.dynamicAnchors[l]){const t=n.let("_v",s._`${r.default.dynamicAnchors}${(0,s.getProperty)(l)}`);n.if(t,u(t,e),u(a.validateName,e))}else u(a.validateName,e)()}function u(t,s){return s?()=>n.block((()=>{(0,i.callRef)(e,t),n.let(s,!0)})):()=>(0,i.callRef)(e,t)}}t.dynamicRef=a,t.default=o},6121:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(6215),r=n(1919),i=n(4094),o=n(3944),a=[s.default,r.default,i.default,o.default];t.default=a},4094:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(6215),r=n(6776),i={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){e.schema?(0,s.dynamicAnchor)(e,""):(0,r.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};t.default=i},3944:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(1919),r={keyword:"$recursiveRef",schemaType:"string",code:e=>(0,s.dynamicRef)(e,e.schema)};t.default=r},9651:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>s.str`must match format "${e}"`,params:({schemaCode:e})=>s._`{format: ${e}}`},code(e,t){const{gen:n,data:r,$data:i,schema:o,schemaCode:a,it:l}=e,{opts:c,errSchemaPath:u,schemaEnv:h,self:d}=l;c.validateFormats&&(i?function(){const i=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),o=n.const("fDef",s._`${i}[${a}]`),l=n.let("fType"),u=n.let("format");n.if(s._`typeof ${o} == "object" && !(${o} instanceof RegExp)`,(()=>n.assign(l,s._`${o}.type || "string"`).assign(u,s._`${o}.validate`)),(()=>n.assign(l,s._`"string"`).assign(u,o))),e.fail$data((0,s.or)(!1===c.strictSchema?s.nil:s._`${a} && !${u}`,function(){const e=h.$async?s._`(${o}.async ? await ${u}(${r}) : ${u}(${r}))`:s._`${u}(${r})`,n=s._`(typeof ${u} == "function" ? ${e} : ${u}.test(${r}))`;return s._`${u} && ${u} !== true && ${l} === ${t} && !${n}`}()))}():function(){const i=d.formats[o];if(!i)return void function(){if(!1!==c.strictSchema)throw new Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}d.logger.warn(e())}();if(!0===i)return;const[a,l,m]=function(e){const t=e instanceof RegExp?(0,s.regexpCode)(e):c.code.formats?s._`${c.code.formats}${(0,s.getProperty)(o)}`:void 0,r=n.scopeValue("formats",{key:o,ref:e,code:t});return"object"!=typeof e||e instanceof RegExp?["string",e,r]:[e.type||"string",e.validate,s._`${r}.validate`]}(i);a===t&&e.pass(function(){if("object"==typeof i&&!(i instanceof RegExp)&&i.async){if(!h.$async)throw new Error("async format in sync schema");return s._`await ${m}(${r})`}return"function"==typeof l?s._`${m}(${r})`:s._`${m}.test(${r})`}())}())}};t.default=r},9502:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=[n(9651).default];t.default=s},6167:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.contentVocabulary=t.metadataVocabulary=void 0,t.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],t.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]},1448:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(8921),r=n(7274),i=n(3633),o=[s.default,r.default,i.default];t.default=o},808:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(1782),r=n(4641),i=[s.default,r.default];t.default=i},4641:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:{message:({params:{len:e}})=>s.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>s._`{limit: ${e}}`},code(e){const{gen:t,schema:n,data:i,it:o}=e,a=o.items||0;if(!0===a)return;const l=t.const("len",s._`${i}.length`);if(!1===n)e.setParams({len:a}),e.fail(s._`${l} > ${a}`);else if("object"==typeof n&&!(0,r.alwaysValidSchema)(o,n)){const n=t.var("valid",s._`${l} <= ${a}`);t.if((0,s.not)(n),(()=>function(n,i){t.forRange("i",i,l,(i=>{e.subschema({keyword:"unevaluatedItems",dataProp:i,dataPropType:r.Type.Num},n),o.allErrors||t.if((0,s.not)(n),(()=>t.break()))}))}(n,a))),e.ok(n)}o.items=!0}};t.default=i},1782:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i=n(2141),o={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:{message:"must NOT have unevaluated properties",params:({params:e})=>s._`{unevaluatedProperty: ${e.unevaluatedProperty}}`},code(e){const{gen:t,schema:n,data:o,errsCount:a,it:l}=e;if(!a)throw new Error("ajv implementation error");const{allErrors:c,props:u}=l;function h(i){if(!1===n)return e.setParams({unevaluatedProperty:i}),e.error(),void(c||t.break());if(!(0,r.alwaysValidSchema)(l,n)){const n=t.name("valid");e.subschema({keyword:"unevaluatedProperties",dataProp:i,dataPropType:r.Type.Str},n),c||t.if((0,s.not)(n),(()=>t.break()))}}u instanceof s.Name?t.if(s._`${u} !== true`,(()=>t.forIn("key",o,(e=>t.if(function(e,t){return s._`!${e} || !${e}[${t}]`}(u,e),(()=>h(e))))))):!0!==u&&t.forIn("key",o,(e=>void 0===u?h(e):t.if(function(e,t){const n=[];for(const r in e)!0===e[r]&&n.push(s._`${t} !== ${r}`);return(0,s.and)(...n)}(u,e),(()=>h(e))))),l.props=!0,e.ok(s._`${a} === ${i.default.errors}`)}};t.default=o},4693:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i=n(3510),o={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>s._`{allowedValue: ${e}}`},code(e){const{gen:t,data:n,$data:o,schemaCode:a,schema:l}=e;o||l&&"object"==typeof l?e.fail$data(s._`!${(0,r.useFunc)(t,i.default)}(${n}, ${a})`):e.fail(s._`${l} !== ${n}`)}};t.default=o},8921:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(7772),r={keyword:"dependentRequired",type:"object",schemaType:"object",error:s.error,code:e=>(0,s.validatePropertyDeps)(e)};t.default=r},966:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i=n(3510),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>s._`{allowedValues: ${e}}`},code(e){const{gen:t,data:n,$data:o,schema:a,schemaCode:l,it:c}=e;if(!o&&0===a.length)throw new Error("enum must have non-empty array");const u=a.length>=c.opts.loopEnum;let h;const d=()=>null!=h?h:h=(0,r.useFunc)(t,i.default);let m;if(u||o)m=t.let("valid"),e.block$data(m,(function(){t.assign(m,!1),t.forOf("v",l,(e=>t.if(s._`${d()}(${n}, ${e})`,(()=>t.assign(m,!0).break()))))}));else{if(!Array.isArray(a))throw new Error("ajv implementation error");const e=t.const("vSchema",l);m=(0,s.or)(...a.map(((t,r)=>function(e,t){const r=a[t];return"object"==typeof r&&null!==r?s._`${d()}(${n}, ${e}[${t}])`:s._`${n} === ${r}`}(e,r))))}e.pass(m)}};t.default=o},2649:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3983),r=n(430),i=n(3229),o=n(4336),a=n(498),l=n(3301),c=n(1687),u=n(2958),h=n(4693),d=n(966),m=[s.default,r.default,i.default,o.default,a.default,l.default,c.default,u.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},h.default,d.default];t.default=m},3633:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(6776),r={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:n}){void 0===t.contains&&(0,s.checkStrictMode)(n,`"${e}" without "contains" is ignored`)}};t.default=r},1687:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n="maxItems"===e?"more":"fewer";return s.str`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>s._`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:r}=e,i="maxItems"===t?s.operators.GT:s.operators.LT;e.fail$data(s._`${n}.length ${i} ${r}`)}};t.default=r},3229:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=n(6776),i=n(4499),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n="maxLength"===e?"more":"fewer";return s.str`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>s._`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:o,it:a}=e,l="maxLength"===t?s.operators.GT:s.operators.LT,c=!1===a.opts.unicode?s._`${n}.length`:s._`${(0,r.useFunc)(e.gen,i.default)}(${n})`;e.fail$data(s._`${c} ${l} ${o}`)}};t.default=o},3983:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r=s.operators,i={maximum:{okStr:"<=",ok:r.LTE,fail:r.GT},minimum:{okStr:">=",ok:r.GTE,fail:r.LT},exclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},exclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}},o={message:({keyword:e,schemaCode:t})=>s.str`must be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>s._`{comparison: ${i[e].okStr}, limit: ${t}}`},a={keyword:Object.keys(i),type:"number",schemaType:"number",$data:!0,error:o,code(e){const{keyword:t,data:n,schemaCode:r}=e;e.fail$data(s._`${n} ${i[t].fail} ${r} || isNaN(${n})`)}};t.default=a},498:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n="maxProperties"===e?"more":"fewer";return s.str`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>s._`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:r}=e,i="maxProperties"===t?s.operators.GT:s.operators.LT;e.fail$data(s._`Object.keys(${n}).length ${i} ${r}`)}};t.default=r},430:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3487),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>s.str`must be multiple of ${e}`,params:({schemaCode:e})=>s._`{multipleOf: ${e}}`},code(e){const{gen:t,data:n,schemaCode:r,it:i}=e,o=i.opts.multipleOfPrecision,a=t.let("res"),l=o?s._`Math.abs(Math.round(${a}) - ${a}) > 1e-${o}`:s._`${a} !== parseInt(${a})`;e.fail$data(s._`(${r} === 0 || (${a} = ${n}/${r}, ${l}))`)}};t.default=r},4336:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(412),r=n(3487),i={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>r.str`must match pattern "${e}"`,params:({schemaCode:e})=>r._`{pattern: ${e}}`},code(e){const{data:t,$data:n,schema:i,schemaCode:o,it:a}=e,l=a.opts.unicodeRegExp?"u":"",c=n?r._`(new RegExp(${o}, ${l}))`:(0,s.usePattern)(e,i);e.fail$data(r._`!${c}.test(${t})`)}};t.default=i},3301:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(412),r=n(3487),i=n(6776),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>r.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>r._`{missingProperty: ${e}}`},code(e){const{gen:t,schema:n,schemaCode:o,data:a,$data:l,it:c}=e,{opts:u}=c;if(!l&&0===n.length)return;const h=n.length>=u.loopRequired;if(c.allErrors?function(){if(h||l)e.block$data(r.nil,d);else for(const t of n)(0,s.checkReportMissingProp)(e,t)}():function(){const i=t.let("missing");if(h||l){const n=t.let("valid",!0);e.block$data(n,(()=>function(n,i){e.setParams({missingProperty:n}),t.forOf(n,o,(()=>{t.assign(i,(0,s.propertyInData)(t,a,n,u.ownProperties)),t.if((0,r.not)(i),(()=>{e.error(),t.break()}))}),r.nil)}(i,n))),e.ok(n)}else t.if((0,s.checkMissingProp)(e,n,i)),(0,s.reportMissingProp)(e,i),t.else()}(),u.strictRequired){const t=e.parentSchema.properties,{definedProperties:s}=e.it;for(const e of n)if(void 0===(null==t?void 0:t[e])&&!s.has(e)){const t=`required property "${e}" is not defined at "${c.schemaEnv.baseId+c.errSchemaPath}" (strictRequired)`;(0,i.checkStrictMode)(c,t,c.opts.strictRequired)}}function d(){t.forOf("prop",o,(n=>{e.setParams({missingProperty:n}),t.if((0,s.noPropertyInData)(t,a,n,u.ownProperties),(()=>e.error()))}))}}};t.default=o},2958:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(453),r=n(3487),i=n(6776),o=n(3510),a={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>r.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>r._`{i: ${e}, j: ${t}}`},code(e){const{gen:t,data:n,$data:a,schema:l,parentSchema:c,schemaCode:u,it:h}=e;if(!a&&!l)return;const d=t.let("valid"),m=c.items?(0,s.getSchemaTypes)(c.items):[];function p(i,o){const a=t.name("item"),l=(0,s.checkDataTypes)(m,a,h.opts.strictNumbers,s.DataType.Wrong),c=t.const("indices",r._`{}`);t.for(r._`;${i}--;`,(()=>{t.let(a,r._`${n}[${i}]`),t.if(l,r._`continue`),m.length>1&&t.if(r._`typeof ${a} == "string"`,r._`${a} += "_"`),t.if(r._`typeof ${c}[${a}] == "number"`,(()=>{t.assign(o,r._`${c}[${a}]`),e.error(),t.assign(d,!1).break()})).code(r._`${c}[${a}] = ${i}`)}))}function f(s,a){const l=(0,i.useFunc)(t,o.default),c=t.name("outer");t.label(c).for(r._`;${s}--;`,(()=>t.for(r._`${a} = ${s}; ${a}--;`,(()=>t.if(r._`${l}(${n}[${s}], ${n}[${a}])`,(()=>{e.error(),t.assign(d,!1).break(c)}))))))}e.block$data(d,(function(){const s=t.let("i",r._`${n}.length`),i=t.let("j");e.setParams({i:s,j:i}),t.assign(d,!0),t.if(r._`${s} > 1`,(()=>(m.length>0&&!m.some((e=>"object"===e||"array"===e))?p:f)(s,i)))}),r._`${u} === false`),e.ok(d)}};t.default=a},8277:(e,t,n)=>{"use strict";n.d(t,{Z:()=>a});var s=n(7537),r=n.n(s),i=n(3645),o=n.n(i)()(r());o.push([e.id,"\n.ui-form.ui-tooltip .ui-input-root > label.ui-input-label:not(:empty) {\n /* min-width: 30px; /* Breaks right margin /**/\n}\n\n.ui-form.ui-tooltip .ui-input-root > div.ui-input-text:not(:empty) {\n margin-top: 6px;\n}","",{version:3,sources:["webpack://./css/cell-renderer.css"],names:[],mappings:";AACA;IACI,8CAA8C;AAClD;;AAEA;IACI,eAAe;AACnB",sourcesContent:["\n.ui-form.ui-tooltip .ui-input-root > label.ui-input-label:not(:empty) {\n /* min-width: 30px; /* Breaks right margin /**/\n}\n\n.ui-form.ui-tooltip .ui-input-root > div.ui-input-text:not(:empty) {\n margin-top: 6px;\n}"],sourceRoot:""}]);const a=o},5362:(e,t,n)=>{"use strict";n.d(t,{Z:()=>a});var s=n(7537),r=n.n(s),i=n(3645),o=n.n(i)()(r());o.push([e.id,".macromolecule-cell-comp-analysis-host{\n max-height: 250px;\n overflow-y: scroll;\n}\n\n.macromolecule-cell-comp-analysis-bar{\n height: inherit;\n display: block;\n margin-top: 1.5px;\n margin-bottom: 1.5px;\n margin-right: 3px;\n}\n\n.macromolecule-cell-comp-analysis-value{\n display: flex;\n}","",{version:3,sources:["webpack://./css/composition-analysis.css"],names:[],mappings:"AAAA;IACI,iBAAiB;IACjB,kBAAkB;AACtB;;AAEA;IACI,eAAe;IACf,cAAc;IACd,iBAAiB;IACjB,oBAAoB;IACpB,iBAAiB;AACrB;;AAEA;IACI,aAAa;AACjB",sourcesContent:[".macromolecule-cell-comp-analysis-host{\n max-height: 250px;\n overflow-y: scroll;\n}\n\n.macromolecule-cell-comp-analysis-bar{\n height: inherit;\n display: block;\n margin-top: 1.5px;\n margin-bottom: 1.5px;\n margin-right: 3px;\n}\n\n.macromolecule-cell-comp-analysis-value{\n display: flex;\n}"],sourceRoot:""}]);const a=o},9564:(e,t,n)=>{"use strict";n.d(t,{Z:()=>a});var s=n(7537),r=n.n(s),i=n(3645),o=n.n(i)()(r());o.push([e.id,".kalign-version {\n margin-bottom: 0;\n text-align: end;\n font-size: 12px;\n opacity: 0.8;\n}\nbutton.msa-params-button.ui-btn {\n justify-content: end;\n}","",{version:3,sources:["webpack://./css/msa.css"],names:[],mappings:"AAAA;IACI,gBAAgB;IAChB,eAAe;IACf,eAAe;IACf,YAAY;AAChB;AACA;IACI,oBAAoB;AACxB",sourcesContent:[".kalign-version {\n margin-bottom: 0;\n text-align: end;\n font-size: 12px;\n opacity: 0.8;\n}\nbutton.msa-params-button.ui-btn {\n justify-content: end;\n}"],sourceRoot:""}]);const a=o},9414:(e,t,n)=>{"use strict";n.d(t,{Z:()=>a});var s=n(7537),r=n.n(s),i=n(3645),o=n.n(i)()(r());o.push([e.id,".scatter_plot_link {\n position: absolute!important;\n right: 10px;\n}\n\n.cliffs_grid {\n top: 10px;\n}\n\n.show_only_cliffs {\n top: 30px;\n}\n\n.ml-dim-reduction-settings-input i.grok-icon.grok-font-icon-settings {\n font-size: 18px;\n position: absolute;\n height: 28px;\n}\n","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/ml/css/styles.css"],names:[],mappings:"AAAA;IACI,4BAA4B;IAC5B,WAAW;AACf;;AAEA;IACI,SAAS;AACb;;AAEA;IACI,SAAS;AACb;;AAEA;IACI,eAAe;IACf,kBAAkB;IAClB,YAAY;AAChB",sourcesContent:[".scatter_plot_link {\n position: absolute!important;\n right: 10px;\n}\n\n.cliffs_grid {\n top: 10px;\n}\n\n.show_only_cliffs {\n top: 30px;\n}\n\n.ml-dim-reduction-settings-input i.grok-icon.grok-font-icon-settings {\n font-size: 18px;\n position: absolute;\n height: 28px;\n}\n"],sourceRoot:""}]);const a=o},8710:(e,t,n)=>{"use strict";n.d(t,{Z:()=>a});var s=n(7537),r=n.n(s),i=n(3645),o=n.n(i)()(r());o.push([e.id,".monomer-lib-controls-form {\n margin-left: auto;\n margin-right: auto;\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n}\n","",{version:3,sources:["webpack://./src/utils/monomer-lib/library-file-manager/style.css"],names:[],mappings:"AAAA;EACE,iBAAiB;EACjB,kBAAkB;EAClB,aAAa;EACb,sBAAsB;EACtB,mBAAmB;EACnB,WAAW;AACb",sourcesContent:[".monomer-lib-controls-form {\n margin-left: auto;\n margin-right: auto;\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n}\n"],sourceRoot:""}]);const a=o},3645:e=>{"use strict";e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var n="",s=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),s&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),s&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n})).join("")},t.i=function(e,n,s,r,i){"string"==typeof e&&(e=[[null,e,void 0]]);var o={};if(s)for(var a=0;a<this.length;a++){var l=this[a][0];null!=l&&(o[l]=!0)}for(var c=0;c<e.length;c++){var u=[].concat(e[c]);s&&o[u[0]]||(void 0!==i&&(void 0===u[5]||(u[1]="@layer".concat(u[5].length>0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=i),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),r&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=r):u[4]="".concat(r)),t.push(u))}},t}},7537:e=>{"use strict";e.exports=function(e){var t=e[1],n=e[3];if(!n)return t;if("function"==typeof btoa){var s=btoa(unescape(encodeURIComponent(JSON.stringify(n)))),r="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(s),i="/*# ".concat(r," */");return[t].concat([i]).join("\n")}return[t].join("\n")}},4063:e=>{"use strict";e.exports=function e(t,n){if(t===n)return!0;if(t&&n&&"object"==typeof t&&"object"==typeof n){if(t.constructor!==n.constructor)return!1;var s,r,i;if(Array.isArray(t)){if((s=t.length)!=n.length)return!1;for(r=s;0!=r--;)if(!e(t[r],n[r]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if((s=(i=Object.keys(t)).length)!==Object.keys(n).length)return!1;for(r=s;0!=r--;)if(!Object.prototype.hasOwnProperty.call(n,i[r]))return!1;for(r=s;0!=r--;){var o=i[r];if(!e(t[o],n[o]))return!1}return!0}return t!=t&&n!=n}},9133:function(e,t,n){var s;!function(t,r){var i={};!function(e){"use strict";e.__esModule=!0,e.digestLength=32,e.blockSize=64;var t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function n(e,n,s,r,i){for(var o,a,l,c,u,h,d,m,p,f,g,y,b;i>=64;){for(o=n[0],a=n[1],l=n[2],c=n[3],u=n[4],h=n[5],d=n[6],m=n[7],f=0;f<16;f++)g=r+4*f,e[f]=(255&s[g])<<24|(255&s[g+1])<<16|(255&s[g+2])<<8|255&s[g+3];for(f=16;f<64;f++)y=((p=e[f-2])>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,b=((p=e[f-15])>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,e[f]=(y+e[f-7]|0)+(b+e[f-16]|0);for(f=0;f<64;f++)y=(((u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7))+(u&h^~u&d)|0)+(m+(t[f]+e[f]|0)|0)|0,b=((o>>>2|o<<30)^(o>>>13|o<<19)^(o>>>22|o<<10))+(o&a^o&l^a&l)|0,m=d,d=h,h=u,u=c+y|0,c=l,l=a,a=o,o=y+b|0;n[0]+=o,n[1]+=a,n[2]+=l,n[3]+=c,n[4]+=u,n[5]+=h,n[6]+=d,n[7]+=m,r+=64,i-=64}return r}var s=function(){function t(){this.digestLength=e.digestLength,this.blockSize=e.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return t.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},t.prototype.clean=function(){for(var e=0;e<this.buffer.length;e++)this.buffer[e]=0;for(e=0;e<this.temp.length;e++)this.temp[e]=0;this.reset()},t.prototype.update=function(e,t){if(void 0===t&&(t=e.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var s=0;if(this.bytesHashed+=t,this.bufferLength>0){for(;this.bufferLength<64&&t>0;)this.buffer[this.bufferLength++]=e[s++],t--;64===this.bufferLength&&(n(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(t>=64&&(s=n(this.temp,this.state,e,s,t),t%=64);t>0;)this.buffer[this.bufferLength++]=e[s++],t--;return this},t.prototype.finish=function(e){if(!this.finished){var t=this.bytesHashed,s=this.bufferLength,r=t/536870912|0,i=t<<3,o=t%64<56?64:128;this.buffer[s]=128;for(var a=s+1;a<o-8;a++)this.buffer[a]=0;this.buffer[o-8]=r>>>24&255,this.buffer[o-7]=r>>>16&255,this.buffer[o-6]=r>>>8&255,this.buffer[o-5]=r>>>0&255,this.buffer[o-4]=i>>>24&255,this.buffer[o-3]=i>>>16&255,this.buffer[o-2]=i>>>8&255,this.buffer[o-1]=i>>>0&255,n(this.temp,this.state,this.buffer,0,o),this.finished=!0}for(a=0;a<8;a++)e[4*a+0]=this.state[a]>>>24&255,e[4*a+1]=this.state[a]>>>16&255,e[4*a+2]=this.state[a]>>>8&255,e[4*a+3]=this.state[a]>>>0&255;return this},t.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},t.prototype._saveState=function(e){for(var t=0;t<this.state.length;t++)e[t]=this.state[t]},t.prototype._restoreState=function(e,t){for(var n=0;n<this.state.length;n++)this.state[n]=e[n];this.bytesHashed=t,this.finished=!1,this.bufferLength=0},t}();e.Hash=s;var r=function(){function e(e){this.inner=new s,this.outer=new s,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var t=new Uint8Array(this.blockSize);if(e.length>this.blockSize)(new s).update(e).finish(t).clean();else for(var n=0;n<e.length;n++)t[n]=e[n];for(n=0;n<t.length;n++)t[n]^=54;for(this.inner.update(t),n=0;n<t.length;n++)t[n]^=106;for(this.outer.update(t),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate),n=0;n<t.length;n++)t[n]=0}return e.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},e.prototype.clean=function(){for(var e=0;e<this.istate.length;e++)this.ostate[e]=this.istate[e]=0;this.inner.clean(),this.outer.clean()},e.prototype.update=function(e){return this.inner.update(e),this},e.prototype.finish=function(e){return this.outer.finished?this.outer.finish(e):(this.inner.finish(e),this.outer.update(e,this.digestLength).finish(e)),this},e.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},e}();function i(e){var t=(new s).update(e),n=t.digest();return t.clean(),n}function o(e,t){var n=new r(e).update(t),s=n.digest();return n.clean(),s}function a(e,t,n,s){var r=s[0];if(0===r)throw new Error("hkdf: cannot expand more");t.reset(),r>1&&t.update(e),n&&t.update(n),t.update(s),t.finish(e),s[0]++}e.HMAC=r,e.hash=i,e.default=i,e.hmac=o;var l=new Uint8Array(e.digestLength);e.hkdf=function(e,t,n,s){void 0===t&&(t=l),void 0===s&&(s=32);for(var i=new Uint8Array([1]),c=o(t,e),u=new r(c),h=new Uint8Array(u.digestLength),d=h.length,m=new Uint8Array(s),p=0;p<s;p++)d===h.length&&(a(h,u,n,i),d=0),m[p]=h[d++];return u.clean(),h.fill(0),i.fill(0),m},e.pbkdf2=function(e,t,n,s){for(var i=new r(e),o=i.digestLength,a=new Uint8Array(4),l=new Uint8Array(o),c=new Uint8Array(o),u=new Uint8Array(s),h=0;h*o<s;h++){var d=h+1;a[0]=d>>>24&255,a[1]=d>>>16&255,a[2]=d>>>8&255,a[3]=d>>>0&255,i.reset(),i.update(t),i.update(a),i.finish(c);for(var m=0;m<o;m++)l[m]=c[m];for(m=2;m<=n;m++){i.reset(),i.update(c).finish(c);for(var p=0;p<o;p++)l[p]^=c[p]}for(m=0;m<o&&h*o+m<s;m++)u[h*o+m]=l[m]}for(h=0;h<o;h++)l[h]=c[h]=0;for(h=0;h<4;h++)a[h]=0;return i.clean(),u}}(i);var o=i.default;for(var a in i)o[a]=i[a];"object"==typeof e.exports?e.exports=o:void 0===(s=function(){return o}.call(i,n,i,e))||(e.exports=s)}()},1811:(e,t,n)=>{"use strict";n.d(t,{T:()=>r});const s=new Uint32Array(65536),r=(e,t)=>{if(e.length<t.length){const n=t;t=e,e=n}return 0===t.length?e.length:e.length<=32?((e,t)=>{const n=e.length,r=t.length,i=1<<n-1;let o=-1,a=0,l=n,c=n;for(;c--;)s[e.charCodeAt(c)]|=1<<c;for(c=0;c<r;c++){let e=s[t.charCodeAt(c)];const n=e|a;e|=(e&o)+o^o,a|=~(e|o),o&=e,a&i&&l++,o&i&&l--,a=a<<1|1,o=o<<1|~(n|a),a&=n}for(c=n;c--;)s[e.charCodeAt(c)]=0;return l})(e,t):((e,t)=>{const n=t.length,r=e.length,i=[],o=[],a=Math.ceil(n/32),l=Math.ceil(r/32);for(let e=0;e<a;e++)o[e]=-1,i[e]=0;let c=0;for(;c<l-1;c++){let a=0,l=-1;const u=32*c,h=Math.min(32,r)+u;for(let t=u;t<h;t++)s[e.charCodeAt(t)]|=1<<t;for(let e=0;e<n;e++){const n=s[t.charCodeAt(e)],r=o[e/32|0]>>>e&1,c=i[e/32|0]>>>e&1,u=n|a,h=((n|c)&l)+l^l|n|c;let d=a|~(h|l),m=l&h;d>>>31^r&&(o[e/32|0]^=1<<e),m>>>31^c&&(i[e/32|0]^=1<<e),d=d<<1|r,m=m<<1|c,l=m|~(u|d),a=d&u}for(let t=u;t<h;t++)s[e.charCodeAt(t)]=0}let u=0,h=-1;const d=32*c,m=Math.min(32,r-d)+d;for(let t=d;t<m;t++)s[e.charCodeAt(t)]|=1<<t;let p=r;for(let e=0;e<n;e++){const n=s[t.charCodeAt(e)],a=o[e/32|0]>>>e&1,l=i[e/32|0]>>>e&1,c=n|u,d=((n|l)&h)+h^h|n|l;let m=u|~(d|h),f=h&d;p+=m>>>r-1&1,p-=f>>>r-1&1,m>>>31^a&&(o[e/32|0]^=1<<e),f>>>31^l&&(i[e/32|0]^=1<<e),m=m<<1|a,f=f<<1|l,h=f|~(c|m),u=m&c}for(let t=d;t<m;t++)s[e.charCodeAt(t)]=0;return p})(e,t)}},3979:(e,t)=>{"use strict";t.H$=void 0,t.H$=function(e,t,n){var s=function(e,t,n){if(0===e.length||0===t.length)return 0;if(n&&!n.caseSensitive&&(e=e.toUpperCase(),t=t.toUpperCase()),e===t)return 1;for(var s=0,r=e.length,i=t.length,o=Math.floor(Math.max(r,i)/2)-1,a=new Array(r),l=new Array(i),c=0;c<r;c++)for(var u=Math.max(0,c-o);u<=Math.min(i,c+o+1);u++)if(!a[c]&&!l[u]&&e[c]===t[u]){++s,a[c]=l[u]=!0;break}if(0===s)return 0;var h=0,d=0;for(c=0;c<r;c++)if(a[c]){for(;!l[d];)d++;e.charAt(c)!==t.charAt(d++)&&h++}return(s/r+s/i+(s-(h/=2))/s)/3}(e,t,n),r=0;if(s>.7){for(var i=Math.min(e.length,t.length),o=0;e[o]===t[o]&&o<4&&o<i;)++r,o++;s+=.1*r*(1-s)}return s}},9461:e=>{"use strict";var t=e.exports=function(e,t,s){"function"==typeof t&&(s=t,t={}),n(t,"function"==typeof(s=t.cb||s)?s:s.pre||function(){},s.post||function(){},e,"",e)};function n(e,s,r,i,o,a,l,c,u,h){if(i&&"object"==typeof i&&!Array.isArray(i)){for(var d in s(i,o,a,l,c,u,h),i){var m=i[d];if(Array.isArray(m)){if(d in t.arrayKeywords)for(var p=0;p<m.length;p++)n(e,s,r,m[p],o+"/"+d+"/"+p,a,o,d,i,p)}else if(d in t.propsKeywords){if(m&&"object"==typeof m)for(var f in m)n(e,s,r,m[f],o+"/"+d+"/"+f.replace(/~/g,"~0").replace(/\//g,"~1"),a,o,d,i,f)}else(d in t.keywords||e.allKeys&&!(d in t.skipKeywords))&&n(e,s,r,m,o+"/"+d,a,o,d,i)}r(i,o,a,l,c,u,h)}}t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0}},3379:e=>{"use strict";var t=[];function n(e){for(var n=-1,s=0;s<t.length;s++)if(t[s].identifier===e){n=s;break}return n}function s(e,s){for(var i={},o=[],a=0;a<e.length;a++){var l=e[a],c=s.base?l[0]+s.base:l[0],u=i[c]||0,h="".concat(c," ").concat(u);i[c]=u+1;var d=n(h),m={css:l[1],media:l[2],sourceMap:l[3],supports:l[4],layer:l[5]};if(-1!==d)t[d].references++,t[d].updater(m);else{var p=r(m,s);s.byIndex=a,t.splice(a,0,{identifier:h,updater:p,references:1})}o.push(h)}return o}function r(e,t){var n=t.domAPI(t);return n.update(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap&&t.supports===e.supports&&t.layer===e.layer)return;n.update(e=t)}else n.remove()}}e.exports=function(e,r){var i=s(e=e||[],r=r||{});return function(e){e=e||[];for(var o=0;o<i.length;o++){var a=n(i[o]);t[a].references--}for(var l=s(e,r),c=0;c<i.length;c++){var u=n(i[c]);0===t[u].references&&(t[u].updater(),t.splice(u,1))}i=l}}},569:e=>{"use strict";var t={};e.exports=function(e,n){var s=function(e){if(void 0===t[e]){var n=document.querySelector(e);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(e){n=null}t[e]=n}return t[e]}(e);if(!s)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");s.appendChild(n)}},9216:e=>{"use strict";e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}},3565:(e,t,n)=>{"use strict";e.exports=function(e){var t=n.nc;t&&e.setAttribute("nonce",t)}},7795:e=>{"use strict";e.exports=function(e){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var t=e.insertStyleElement(e);return{update:function(n){!function(e,t,n){var s="";n.supports&&(s+="@supports (".concat(n.supports,") {")),n.media&&(s+="@media ".concat(n.media," {"));var r=void 0!==n.layer;r&&(s+="@layer".concat(n.layer.length>0?" ".concat(n.layer):""," {")),s+=n.css,r&&(s+="}"),n.media&&(s+="}"),n.supports&&(s+="}");var i=n.sourceMap;i&&"undefined"!=typeof btoa&&(s+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(i))))," */")),t.styleTagTransform(s,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}},4589:e=>{"use strict";e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}},7241:(e,t,n)=>{"use strict";n.d(t,{D:()=>c});var s=n(4469),r=n(976),i=n(3649),o=n(8260),a=n(6286);const l=31;async function c(e,t=!1,n){const a=o.g.forColumn(e);let c;n??(n=new Map);const h=a.isHelm()?(0,i.getHelmMonomers)(e):Object.keys(a.stats.freq).filter((e=>""!==e));for(let e=0;e<h.length;e++)n.has(h[e])||n.set(h[e],`${n.size+1}`);if(a.isHelm())c=await s.functions.call("HELM:getMolFiles",{col:e}),c=function(e,t,n=!1){const s=new Array(e.length);for(let r=0;r<e.length;r++){let i=0,o=0,a="\n Datagrok macromolecule handler\n\n 0 0 0 0 0 0 999 V3000\nM V30 BEGIN CTAB\n";const c=e.get(r);i=c.indexOf("\n",i)+1,i=c.indexOf("\n",i)+1,i=c.indexOf("\n",i)+1;const u=parseInt(c.substring(i,i+3)),h=parseInt(c.substring(i+3,i+6));a+=`M V30 COUNTS ${u} ${h} 0 0 0\n`,a+="M V30 BEGIN ATOM\n";for(let e=0;e<u;e++){i=c.indexOf("\n",i)+1+l,o=c.indexOf(" ",i);const s=c.substring(i,o);a+=n?`M V30 ${e+1} R${t.get(s)} 0.000 0.000 0 0\n`:`M V30 ${e+1} At 0.000 0.000 0 0 MASS=${t.get(s)}\n`}a+="M V30 END ATOM\n",a+="M V30 BEGIN BOND\n";for(let e=0;e<h;e++){i=c.indexOf("\n",i)+1;const t=parseInt(c.substring(i,i+3).trim()),n=parseInt(c.substring(i+3,i+6).trim());a+=`M V30 ${e+1} ${parseInt(c.substring(i+6,i+9).trim())} ${t} ${n}\n`}a+="M V30 END BOND\n",a+="M V30 END CTAB\n",a+="M END",s[r]=a}return s}(c,n,t);else{c=new Array(e.length);for(let s=0;s<e.length;s++){const e=u(a.getSplitted(s),n,t);c[s]=e}}return r.Column.fromStrings("monomericMols",c)}function u(e,t,n=!1){let s="\n Datagrok macromolecule handler\n\n 0 0 0 0 0 0 999 V3000\nM V30 BEGIN CTAB\n";s+=`M V30 COUNTS ${e.length} ${e.length?e.length-1:0} 0 0 0\n`,s+="M V30 BEGIN ATOM\n";for(let r=0;r<e.length;r++){const i=e.getCanonical(r);i!==a.G2&&(s+=n?`M V30 ${r+1} R${t.get(i)} 0.000 0.000 0 0\n`:`M V30 ${r+1} At 0.000 0.000 0 0 MASS=${t.get(i)}\n`)}s+="M V30 END ATOM\n",s+="M V30 BEGIN BOND\n";for(let t=0;t<e.length-1;t++)s+=`M V30 ${t+1} 1 ${t+1} ${t+2}\n`;return s+="M V30 END BOND\n",s+="M V30 END CTAB\n",s+="M END",s}},3649:(e,t,n)=>{"use strict";n.r(t),n.d(t,{GetRegionEditor:()=>bs,SeqActivityCliffsEditor:()=>Cs,SeqPaletteCustom:()=>hs,SequenceSpaceEditor:()=>ws,SplitToMonomersEditor:()=>vs,SubsequenceSearchTopMenu:()=>Qs,_package:()=>ls,activityCliffs:()=>Ls,addCopyMenu:()=>cr,alignSequences:()=>Gs,applyNotationProviderForCyclized:()=>vr,bioSubstructureFilter:()=>rr,compositionAnalysis:()=>Ds,compositionAnalysisWidget:()=>xs,convertDialog:()=>Us,createMonomerLibraryForPolyTool:()=>gr,demoBioActivityCliffs:()=>dr,demoBioAtomicLevel:()=>mr,demoBioHelmMsaSequenceSpace:()=>pr,demoBioSequenceSpace:()=>hr,demoBioSimilarityDiversity:()=>ur,detectMacromoleculeProbe:()=>br,diversitySearchTopMenu:()=>Xs,diversitySearchViewer:()=>zs,fastaSequenceCellRenderer:()=>Ss,getBioLib:()=>ps,getHelmMonomers:()=>Zs,getMonomerLibHelper:()=>cs,getRegion:()=>$s,getRegionApp:()=>ar,getRegionHelmApp:()=>lr,getRegionPanel:()=>gs,getRegionTopMenu:()=>Ns,getSeqHandler:()=>fs,helmPreprocessingFunction:()=>Rs,hydrophobPalette:()=>us,importBam:()=>Vs,importFasta:()=>Bs,initBio:()=>ds,libraryPanel:()=>ys,macroMolColumnPropertyPanel:()=>As,macromoleculeDifferenceCellRenderer:()=>Is,macromoleculePreprocessingFunction:()=>Ps,manageMonomerLibraries:()=>nr,monomerCellRenderer:()=>js,multipleSequenceAlignmentDialog:()=>Fs,polyTool:()=>Hs,polyToolColumnChoice:()=>fr,saveAsFasta:()=>sr,sdfToJsonLib:()=>yr,searchSubsequenceEditor:()=>Js,separatorSequenceCellRenderer:()=>Es,sequenceAlignment:()=>Ts,sequenceIdentityScoring:()=>er,sequenceSimilarityScoring:()=>tr,sequenceSpaceTopMenu:()=>Os,sequenceTooltip:()=>ms,similaritySearchTopMenu:()=>qs,similaritySearchViewer:()=>Ks,splitToMonomersTopMenu:()=>Ys,testDetectMacromolecule:()=>Ws,toAtomicLevel:()=>ks,vdRegionsViewer:()=>Ms,webLogoAggApp:()=>or,webLogoLargeApp:()=>ir,webLogoViewer:()=>_s});var s,r,i=n(4469),o=n(3870),a=n(976),l=n(3277),c=n(4628);(r=s||(s={})).EUCLIDEAN="EUCLIDEAN",r.MANHATTAN="MANHATTAN";class u{constructor(){this.learningRate={uiName:"Learninig rate",value:1,tooltip:"The initial learning rate for the embedding optimization"},this.nEpochs={uiName:"Epochs",value:0,tooltip:"The number of epochs to optimize embeddings via SGD. Computed automatically if set to 0"},this.nNeighbors={uiName:"Neighbors",value:15,tooltip:"The number of nearest neighbors to construct the fuzzy manifold"},this.spread={uiName:"Spread",value:1,tooltip:"The effective scale of embedded points, used with min distance to control \n the clumped/dispersed nature of the embedding"},this.minDist={uiName:"Min distance",value:.1,tooltip:"The effective minimum distance between embedded points, \n used with spread to control the clumped/dispersed nature of the embedding"},this.randomSeed={uiName:"Random seed",value:null,tooltip:"Random seed",type:"string"},this.useWebGPU={uiName:"Use WebGPU",value:!1,tooltip:"Use WebGPU for KNN computations (EXPERIMENTAL)",type:"boolean"}}}class h{constructor(){this.epsilon={uiName:"Epsilon",value:10,tooltip:"Epsilon is learning rate"},this.perplexity={uiName:"Perplexity",value:30,tooltip:"Roughly how many neighbors each point influences"}}}const d="MCL";a.SEMTYPE.MOLECULE,a.SEMTYPE.MACROMOLECULE;class m{constructor(){this.epsilon={uiName:"Epsilon",value:.01,tooltip:"Minimum distance between cluster points",min:0,max:2,step:.005},this.minPts={uiName:"Minimum points",value:4,tooltip:"Minimum number of points in cluster",min:1,max:1e3,step:1}}}class p{get algorithmOptions(){const e=this.methodsParams[this.methodInput.value],t={};return Object.keys(e).forEach((n=>{null!=e[n].value&&(t[n]=e[n].value)})),t}get dbScanOptions(){return{dbScanEpsilon:this.dbScanParams.epsilon.value??.01,dbScanMinPts:this.dbScanParams.minPts.value??4}}constructor(e={}){this.editorSettings={},this.plotEmbeddingsInput=o.boolInput("Plot embeddings",!0),this.clusterEmbeddingsInput=o.boolInput("Cluster embeddings",!0),this.preprocessingFunctionInputRoot=null,this.methods=[c.A.UMAP,c.A.T_SNE],this.columnFunctionsMap={},this.supportedFunctions={},this.availableMetrics=[],this.methodSettingsDiv=o.inputs([]),this.dbScanSettingsDiv=o.inputs([]),this.preprocessingFuncSettingsDiv=o.inputs([]),this.preprocessingFunctionSettings={},this.methodsParams={[c.A.UMAP]:new u,[c.A.T_SNE]:new h},this.dbScanParams=new m,this.editorSettings=e,this.editorSettings.enableMCL&&this.methods.push(d),a.Func.find({tags:[l.n3]}).forEach((e=>{const t=e.options.get(l.vO)??"",n=e.friendlyName??e.name,s=e.options.get(l.ts)??"",r=e.options.get(l.q6)??"",i=e.options.get(l.dB)??"";this.editorSettings.semtype&&!t.includes(this.editorSettings.semtype)||this.editorSettings.type&&!s.includes(this.editorSettings.type)||this.editorSettings.units&&!r.includes(this.editorSettings.units)||(this.supportedFunctions[n]={func:e,semTypes:t?t.split(","):[],types:s?s.split(","):[],units:r?r.split(","):[],distanceFunctions:i?i.split(","):[]})})),this.tableInput=o.tableInput("Table",i.shell.tv.dataFrame,i.shell.tables,(()=>{this.onTableInputChanged()})),this.onTableInputChanged(),this.regenerateColInput(),this.onColumnInputChanged();let t=!1,n=!1;this.methodInput=o.choiceInput("Method",c.A.UMAP,this.methods,(()=>{t&&this.createAlgorithmSettingsDiv(this.methodSettingsDiv,this.methodsParams[this.methodInput.value])})),this.methodSettingsIcon=o.icons.settings((()=>{t=!t,t?this.createAlgorithmSettingsDiv(this.methodSettingsDiv,this.methodsParams[this.methodInput.value]):o.empty(this.methodSettingsDiv)}),"Modify methods parameters"),this.dbScanSettingsIcon=o.icons.settings((()=>{n=!n,n?this.createAlgorithmSettingsDiv(this.dbScanSettingsDiv,this.dbScanParams):o.empty(this.dbScanSettingsDiv)}),"Modify clustering parameters"),this.clusterEmbeddingsInput.classList.add("ml-dim-reduction-settings-input"),this.clusterEmbeddingsInput.root.prepend(this.dbScanSettingsIcon),this.methodInput.root.classList.add("ml-dim-reduction-settings-input"),this.methodInput.root.prepend(this.methodSettingsIcon),this.methodSettingsDiv=o.inputs([]);const s=this.columnFunctionsMap[this.colInput.value.name];this.preprocessingFunctionInput=o.choiceInput("Encoding function",s[0],s,(()=>{this.onPreprocessingFunctionChanged()}));let r=!1;this.preprocessingFunctionInputRoot||(this.preprocessingFunctionInputRoot=this.preprocessingFunctionInput.root,r=!0),r||(o.empty(this.preprocessingFunctionInputRoot),Array.from(this.preprocessingFunctionInput.root.children).forEach((e=>this.preprocessingFunctionInputRoot.append(e)))),this.preprocessingFunctionInputRoot.classList.add("ml-dim-reduction-settings-input");let p=!1;this.preprocessingFuncSettingsIcon=o.icons.settings((async()=>{p?o.empty(this.preprocessingFuncSettingsDiv):await this.createPreprocessingFuncParamsDiv(this.preprocessingFuncSettingsDiv,this.supportedFunctions[this.preprocessingFunctionInput.value].func),p=!p}),"Modify encoding function parameters"),this.preprocessingFunctionInputRoot.prepend(this.preprocessingFuncSettingsIcon),this.similarityMetricInput=o.choiceInput("Similarity","",[],null),this.similarityMetricInput.nullable=!1,this.similarityMetricInputRoot||(this.similarityMetricInputRoot=this.similarityMetricInput.root),this.onPreprocessingFunctionChanged()}getColInput(){const e=this.tableInput.value?.columns.toList().find((e=>!!this.columnFunctionsMap[e.name]))??null,t=o.columnInput("Column",this.tableInput.value,e,(()=>this.onColumnInputChanged()),{filter:e=>!!this.columnFunctionsMap[e.name]});return this.colInputRoot||(this.colInputRoot=t.root),t}regenerateColInput(){let e=!1;this.colInputRoot&&(e=!0,o.empty(this.colInputRoot)),this.colInput=this.getColInput(),e&&Array.from(this.colInput.root.children).forEach((e=>this.colInputRoot.append(e))),this.onColumnInputChanged()}onTableInputChanged(){const e=this.tableInput.value;e&&(this.columnFunctionsMap={},e.columns.toList().forEach((e=>{Object.keys(this.supportedFunctions).forEach((t=>{const n=this.supportedFunctions[t].semTypes,s=this.supportedFunctions[t].types,r=this.supportedFunctions[t].units,i=!n.length||e.semType&&n.includes(e.semType),o=!s.length||s.includes(e.type),l=!r.length||e.getTag(a.TAGS.UNITS)&&r.includes(e.getTag(a.TAGS.UNITS));i&&o&&l&&(this.columnFunctionsMap[e.name]||(this.columnFunctionsMap[e.name]=[]),this.columnFunctionsMap[e.name].push(t))}))})),this.regenerateColInput())}onColumnInputChanged(){const e=this.colInput.value;if(!e)return;const t=this.columnFunctionsMap[e.name];this.preprocessingFunctionInput=o.choiceInput("Preprocessing function",t[0],t,(()=>{this.onPreprocessingFunctionChanged()}));let n=!1;this.preprocessingFunctionInputRoot||(this.preprocessingFunctionInputRoot=this.preprocessingFunctionInput.root,n=!0),n||(o.empty(this.preprocessingFunctionInputRoot),Array.from(this.preprocessingFunctionInput.root.children).forEach((e=>this.preprocessingFunctionInputRoot.append(e)))),this.onPreprocessingFunctionChanged()}onPreprocessingFunctionChanged(){o.empty(this.preprocessingFuncSettingsDiv),this.preprocessingFunctionSettings={};const e=this.preprocessingFunctionInput.value,t=this.supportedFunctions[e].distanceFunctions;this.availableMetrics=[...t],this.similarityMetricInput=o.choiceInput("Similarity",this.availableMetrics[0],this.availableMetrics,null),this.similarityMetricInput.nullable=!1,this.similarityMetricInputRoot||(this.similarityMetricInputRoot=this.similarityMetricInput.root),o.empty(this.similarityMetricInputRoot),Array.from(this.similarityMetricInput.root.children).forEach((e=>this.similarityMetricInputRoot.append(e))),this.preprocessingFuncSettingsIcon&&(this.supportedFunctions[e].func.inputs.length<3?this.preprocessingFuncSettingsIcon.style.display="none":this.preprocessingFuncSettingsIcon.style.display="flex")}createAlgorithmSettingsDiv(e,t){return o.empty(e),Object.keys(t).forEach((n=>{const s=t[n],r="string"===s.type?o.stringInput(s.uiName,s.value??"",(()=>{s.value=r.value})):"boolean"===s.type?o.boolInput(s.uiName,s.value??!1,(()=>{s.value=r.value})):o.floatInput(s.uiName,s.value,(()=>{s.value=r.value}));o.tooltip.bind(r.input??r.root,s.tooltip),e.append(r.root)})),e}async createPreprocessingFuncParamsDiv(e,t){if(o.empty(e),t.inputs.length<3)return o.div();const n=t.prepare(),s=await n.buildEditor(o.div());for(let r=2;r<t.inputs.length;r++){const i=t.inputs[r];(this.preprocessingFunctionSettings[i.name]||n.inputParams[t.inputs[r].name].value||i.defaultValue)&&(this.preprocessingFunctionSettings[i.name]=this.preprocessingFunctionSettings[i.name]??n.inputParams[i.name].value??i.defaultValue);const o=s.find((e=>e.property.name===i.name));o&&(null!==this.preprocessingFunctionSettings[i.name]&&void 0!==this.preprocessingFunctionSettings[i.name]&&(o.value=this.preprocessingFunctionSettings[i.name]),o.onChanged((()=>{this.preprocessingFunctionSettings[i.name]=o.value})),e.append(o.root))}return e}getEditor(){return o.div([this.tableInput,this.colInputRoot,this.preprocessingFunctionInputRoot,this.preprocessingFuncSettingsDiv,this.methodInput,this.methodSettingsDiv,this.similarityMetricInputRoot,this.plotEmbeddingsInput,this.clusterEmbeddingsInput,this.dbScanSettingsDiv],{style:{minWidth:"320px"},classes:"ui-form"})}getParams(){return{table:this.tableInput.value,col:this.colInput.value,methodName:this.methodInput.value,preprocessingFunction:this.supportedFunctions[this.preprocessingFunctionInput.value].func,similarityMetric:this.similarityMetricInput.value,plotEmbeddings:this.plotEmbeddingsInput.value,clusterEmbeddings:this.clusterEmbeddingsInput.value,options:{...this.algorithmOptions,...this.dbScanOptions,preprocessingFuncArgs:this.preprocessingFunctionSettings??{}}}}}var f=n(442),g=n(5697),y=n(701),b=n(3379),v=n.n(b),w=n(7795),C=n.n(w),S=n(569),A=n.n(S),x=n(3565),E=n.n(x),I=n(9216),T=n.n(I),_=n(4589),M=n.n(_),$=n(9414),N={};N.styleTagTransform=M(),N.setAttributes=E(),N.insert=A().bind(null,"head"),N.domAPI=C(),N.insertStyleElement=T(),v()($.Z,N),$.Z&&$.Z.locals&&$.Z.locals;const L=e=>null==e;function P(e,t,n,s){if(n>e[e.length-1])return;const r=e.findIndex((e=>n<e));e.pop(),e.splice(r,0,n),t.pop(),t.splice(r,0,s)}var R=n(6254);class O{constructor(e=!0,t=!0){const s=navigator.hardwareConcurrency;this._workerCount=e?Math.max(s-2,1):1,this._workers=new Array(this._workerCount).fill(null).map((()=>new Worker(new URL(n.p+n.u(65),n.b)))),this._terminateOnComplete=t}async calc(e,t,n=!0,r){return await this.calcMulti([e],[t],n,[r??{}],[1],s.MANHATTAN)}async calcMulti(e,t,n=!0,r=[{}],i=[1],o=s.MANHATTAN){if(e.length<1)throw new Error("values must contain at least one array");if(t.length!==e.length||r.length!==e.length||i.length!==e.length)throw new Error("values, fnNames, weights and opts must have the same length");return new Promise((async(s,a)=>{try{const a=e[0].length,l=new Array(this._workerCount),c=a*(a-1)/2;this._workerCount=Math.min(this._workerCount,c);const u=c/this._workerCount,h=new Float32Array(c);let d=0,m=1,p=0,f=Number.MIN_VALUE;for(let n=0;n<this._workerCount;n++){const s=Math.floor(n*u),g=n===this._workerCount-1?c:Math.floor((n+1)*u),y=d,b=m;n!==this._workerCount-1&&(d=a-2-Math.floor(Math.sqrt(-8*g+4*a*(a-1)-7)/2-.5),m=g-a*d+Math.floor((d+1)*(d+2)/2)),this._workers[n].postMessage({values:e,fnNames:t,startRow:y,startCol:b,chunckSize:g-s,opts:r,weights:i,aggregationMethod:o}),l[n]=new Promise(((e,t)=>{this._workers[n].onmessage=({data:{error:r,distanceMatrixData:i,min:o,max:a}})=>{this._terminateOnComplete&&setTimeout((()=>this._workers[n].terminate())),r?t(r):(h.set(i,s),o<p&&(p=o),a>f&&(f=a),e())}}))}await Promise.all(l),n&&h.forEach(((e,t)=>{h[t]=(e-p)/(f-p)})),s(h)}catch(e){a(e)}}))}terminate(){this._workers.forEach((e=>e.terminate()))}}class k{constructor(){this._workerCount=Math.max(navigator.hardwareConcurrency-2,1)}async calcMultiColumn(e,t,r,i=[{}],o=[1],a=s.EUCLIDEAN){const l=e[0].length*(e[0].length-1)/2,c=Math.floor(l/this._workerCount),u=e[0].length>2e4?await this.getMinimalThreshold(e,t,i,o,a):0;r<u&&(console.log(`using threshold ${u}`),r=u),i.forEach(((e,t)=>i[t].threshold=r));const h=new Array(this._workerCount),d=new Array(this._workerCount).fill(null).map((()=>new Worker(new URL(n.p+n.u(23),n.b))));for(let n=0;n<this._workerCount;n++)h[n]=new Promise(((s,u)=>{const h=n*c,m=n===this._workerCount-1?l:(n+1)*c;m<=h&&s({i:new Int32Array(0),j:new Int32Array(0),distance:new Float32Array(0),idx:n}),d[n].postMessage({values:e,startIdx:h,endIdx:m,threshold:r,fnNames:t,opts:i,weights:o,aggregationMethod:a}),d[n].onmessage=({data:{error:e,i:t,j:r,distance:i}})=>{e?(d[n].terminate(),u(e)):(d[n].terminate(),s({i:t,j:r,distance:i,idx:n}))}}));const m=await Promise.all(h),p=m.reduce(((e,t)=>e+t.i.length),0),f=new Int32Array(p),g=new Int32Array(p),y=new Float32Array(p);let b=0;for(const e of m)f.set(e.i,b),g.set(e.j,b),y.set(e.distance,b),b+=e.i.length;return{i:f,j:g,distance:y}}async calc(e,t,n,s={}){return await this.calcMultiColumn([e],[t],n,[s],[1])}async getKNN(e,t,n=15,s={}){return await this.multiColumnKNN([e],[t],n,[s],[1])}async getThresholdKNN(e,t,n=.8,s={}){return await this.multiColumnThresholdKnn([e],[t],n,[s],[1])}async multiColumnThresholdKnn(e,t,r=.8,i,o,a=s.EUCLIDEAN){if(e.length!==t.length||e.length!==i.length||e.length!==o.length)throw new Error("values, distance functions, options and weights arrays should have the same length");if(e.some((t=>t.length!==e[0].length)))throw new Error("all values arrays should have the same length");const l=e[0].length*(e[0].length-1)/2,c=Math.floor(l/this._workerCount),u=new Array(this._workerCount),h=new Array(this._workerCount).fill(null).map((()=>new Worker(new URL(n.p+n.u(427),n.b))));for(let n=0;n<this._workerCount;n++)u[n]=new Promise(((s,u)=>{const d=n*c,m=n===this._workerCount-1?l:(n+1)*c;m<=d&&s({knnDistances:new Array(0),knnIndexes:new Array(0)}),h[n].postMessage({values:e,startIdx:d,endIdx:m,fnNames:t,opts:i,threshold:r,weights:o,aggregationMethod:a}),h[n].onmessage=({data:{error:e,knnDistances:t,knnIndexes:r}})=>{e?(h[n].terminate(),u(e)):(h[n].terminate(),s({knnDistances:t,knnIndexes:r}))}}));const d=await Promise.all(u),m=new Int32Array(e[0].length);for(const t of d)for(let n=0;n<e[0].length;++n)m[n]+=t.knnIndexes[n]?.length??0;const p={knnDistances:new Array(e[0].length).fill(null).map(((e,t)=>new Array(m[t]))),knnIndexes:new Array(e[0].length).fill(null).map(((e,t)=>new Array(m[t])))};for(const t of d)for(let n=0;n<e[0].length;++n)for(let e=0;e<t.knnDistances[n]?.length;++e)p.knnDistances[n][m[n]-1]=t.knnDistances[n][e],p.knnIndexes[n][m[n]-1]=t.knnIndexes[n][e],m[n]-=1;return p}async multiColumnKNN(e,t,r=15,i,o,a=s.EUCLIDEAN){if(e.length!==t.length||e.length!==i.length||e.length!==o.length)throw new Error("values, distance functions, options and weights arrays should have the same length");if(e.some((t=>t.length!==e[0].length)))throw new Error("all values arrays should have the same length");const l=e[0].length*(e[0].length-1)/2,c=Math.floor(l/this._workerCount),u=new Array(this._workerCount),h=new Array(this._workerCount).fill(null).map((()=>new Worker(new URL(n.p+n.u(282),n.b))));for(let n=0;n<this._workerCount;n++)u[n]=new Promise(((s,u)=>{const d=n*c,m=n===this._workerCount-1?l:(n+1)*c;m<=d&&s({knnDistances:new Array(0),knnIndexes:new Array(0)}),h[n].postMessage({values:e,startIdx:d,endIdx:m,fnNames:t,opts:i,nNeighbours:r,weights:o,aggregationMethod:a}),h[n].onmessage=({data:{error:e,knnDistances:t,knnIndexes:r}})=>{e?(h[n].terminate(),u(e)):(h[n].terminate(),s({knnDistances:t,knnIndexes:r}))}}));const d=await Promise.all(u),m={knnDistances:new Array(e[0].length).fill(null).map((()=>new Array(r).fill(99999))),knnIndexes:new Array(e[0].length).fill(null).map((()=>new Array(r).fill(-1)))};for(const t of d)for(let n=0;n<e[0].length;++n)for(let e=0;e<t.knnDistances[n]?.length;++e)P(m.knnDistances[n],m.knnIndexes[n],t.knnDistances[n][e],t.knnIndexes[n][e]);return m}async getSampleDistances(e,t,r=[],i,o=s.EUCLIDEAN){const a=new Array(this._workerCount).fill(null).map((()=>new Worker(new URL(n.p+n.u(40),n.b))));try{const n=e[0].length*(e[0].length-1)/2,s=Math.floor(n/this._workerCount),l=1e6,c=Math.max(Math.min(n/1e3,l),Math.min(n,l)),u=Math.floor(c/this._workerCount),h=new Array(this._workerCount);for(let l=0;l<this._workerCount;l++)h[l]=new Promise(((c,h)=>{const d=l*s,m=l===this._workerCount-1?n:(l+1)*s;a[l].postMessage({values:e,startIdx:d,endIdx:m,sampleLength:u,fnNames:t,opts:r,weights:i,aggregationMethod:o}),a[l].onmessage=({data:{error:e,distance:t}})=>{a[l].terminate(),e?h(e):c({distance:t})}}));const d=await Promise.all(h),m=d.reduce(((e,t)=>e+t.distance.length),0),p=new Float32Array(m);let f=0;for(const e of d)p.set(e.distance,f),f+=e.distance.length;return p.sort(),p}catch(e){return a?.forEach((e=>e?.terminate())),console.error(e),new Float32Array(1).fill(.5)}}async getMinimalThreshold(e,t,n=[],r,i=s.EUCLIDEAN){try{const s=e.length*(e.length-1)/2,o=await this.getSampleDistances(e,t,n,r,i);return 1-o[Math.floor(7e7/s*o.length)]}catch(e){return console.error(e),.5}}static calcSync(e,t,n,s){const r=[],i=[],o=[];let a=0,l=0,c=0;const u=e.length*(e.length-1)/2;for(;a<u;){const t=L(e[l])||L(e[c])?1:n(e[l],e[c]);1-t>=s&&(r.push(l),i.push(c),o.push(t)),a++,c++,c===e.length&&(l++,c=l+1)}return{i:new Int32Array(r),j:new Int32Array(i),distance:new Float32Array(o)}}}var F,G=n(9657);!function(e){e.none="none",e.bold="bold",e.dashed="dashed"}(F||(F={}));class D{get currentLineId(){return this._currentLineIdx}set currentLineId(e){e!==this._currentLineIdx&&(this._currentLineIdx=e,this.sp.render(this.ctx))}set linesToRender(e){this.updateLines(e),this.sp.render(this.ctx)}set linesVisibility(e){this.visibility=e,this.sp.render(this.ctx)}constructor(e,t,n,s,r=F.none){var i;this._currentLineIdx=-1,this.lineClicked=new y.Subject,this.lineHover=new y.Subject,this.mouseOverLineId=-1,this.arrowWidth=15,this.sp=e,this.xAxisCol=this.sp.dataFrame.columns.byName(t),this.yAxisCol=this.sp.dataFrame.columns.byName(n),this.canvas=this.sp.getInfo().canvas,this.ctx=this.canvas.getContext("2d"),this.currentLineStyle=r,this.updateLines(s),this.visibility=null!==(i=s.visibility)&&void 0!==i?i:new G.Z(this.lines.from.length),s.visibility||this.visibility.setAll(!0,!1),s.arrowSize&&(this.arrowWidth=s.arrowSize),this.canvas.onmousedown=e=>{-1!==this.mouseOverLineId&&this.lineClicked.next({x:e.clientX,y:e.clientY,id:this.mouseOverLineId,event:e})},this.canvas.onmousemove=e=>{this.mouseOverLineId=this.checkCoordsOnLine(e.offsetX,e.offsetY),-1!==this.mouseOverLineId&&this.lineHover.next({x:e.clientX,y:e.clientY,id:this.mouseOverLineId,event:e})},e.onEvent("d4-before-draw-scene").subscribe((e=>{this.renderLines()}))}updateLines(e){this.lines=e,this.multipleLinesCounts=new Uint8Array(this.lines.from.length),e.skipMultiLineCalculation?this.multipleLinesCounts.fill(0):this.createMultiLinesIndices()}renderLines(){var e,t,n,s,r,i,o,a,l,c,u,h,d;const m=this.sp.getOptions().look,p=this.lines.colors||this.lines.width||this.lines.opacities||this.lines.drawArrowsArr;p||(this.ctx.lineWidth=null!==(e=this.lines.width)&&void 0!==e?e:1,this.ctx.strokeStyle=`rgba(${null!==(t=this.lines.color)&&void 0!==t?t:"0,128,0"},${null!==(n=this.lines.opacity)&&void 0!==n?n:1})`);const f=m.sizeColumnName?this.sp.dataFrame.col(m.sizeColumnName):null,g=this.sp.dataFrame.filter;for(let e=0;e<this.lines.from.length;e++)if(g.get(this.lines.from[e])&&g.get(this.lines.to[e])&&this.visibility.getBit(e)){let t=0;const{sizeFrom:n,sizeTo:g}=this.getMarkersSizes(m,f,e),y=this.sp.worldToScreen(this.xAxisCol.get(this.lines.from[e]),this.yAxisCol.get(this.lines.from[e]));let b=null==y?void 0:y.x,v=null==y?void 0:y.y;const w=this.sp.worldToScreen(this.xAxisCol.get(this.lines.to[e]),this.yAxisCol.get(this.lines.to[e]));let C=null==w?void 0:w.x,S=null==w?void 0:w.y;const A=Math.min(this.sp.viewBox.width,this.sp.viewBox.height);if(this.ctx.beginPath(),b&&v&&C&&S&&Math.hypot(C-b,S-v)/A>.01){if(p){const t=(null===(s=this.lines.colors)||void 0===s?void 0:s[e])?null===(r=this.lines.colors)||void 0===r?void 0:r[e]:"0,128,0",n=(null===(i=this.lines.opacities)||void 0===i?void 0:i[e])?null===(o=this.lines.opacities)||void 0===o?void 0:o[e]:1;this.ctx.strokeStyle=`rgba(${t},${n})`,this.ctx.lineWidth=(null===(a=this.lines.widths)||void 0===a?void 0:a[e])?null===(l=this.lines.widths)||void 0===l?void 0:l[e]:1}e===this._currentLineIdx&&this.toggleCurrentLineStyle(!0);const m=this.multipleLinesCounts[e];let f=null;if(m){t=this.getLineLength(b,v,C,S);const s=this.getPointOnDistance(b,v,C,S,g,t),r=this.getPointOnDistance(C,S,b,v,n,t);b=s.x,v=s.y,C=r.x,S=r.y,f=this.lines.from[e]>this.lines.to[e]?this.findControlPoint(m,b,v,C,S,e):this.findControlPoint(m,C,S,b,v,e),this.ctx.moveTo(b,v),this.ctx.quadraticCurveTo(f.x,f.y,C,S)}else this.ctx.moveTo(b,v),this.ctx.lineTo(C,S);if((null!==(c=this.lines.drawArrows)&&void 0!==c?c:null===(u=this.lines.drawArrowsArr)||void 0===u?void 0:u.getBit(e))&&(t||(t=this.getLineLength(b,v,C,S)),t>this.arrowWidth)){const e=m?null:this.getPointOnDistance(b,v,C,S,g,t),n=m?f.x:b,s=m?f.y:v;this.canvasArrow(this.ctx,null!==(h=null==e?void 0:e.x)&&void 0!==h?h:b,null!==(d=null==e?void 0:e.y)&&void 0!==d?d:v,n,s)}this.ctx.stroke(),this.ctx.closePath(),e===this._currentLineIdx&&this.toggleCurrentLineStyle(!1)}}this.fillLeftBottomRect()}toggleCurrentLineStyle(e){switch(this.currentLineStyle){case F.bold:e?this.ctx.lineWidth+=2:this.ctx.lineWidth-=2;break;case F.dashed:e?this.ctx.setLineDash([5,5]):this.ctx.setLineDash([]);break;default:return}}getMarkersSizes(e,t,n){let s=3,r=3;return t?(s=(e.markerMinSize+(e.markerMaxSize-e.markerMinSize)*t.scale(this.lines.from[n]))/2,r=(e.markerMinSize+(e.markerMaxSize-e.markerMinSize)*t.scale(this.lines.to[n]))/2):e.markerDefaultSize&&(s=e.markerDefaultSize/2,r=e.markerDefaultSize/2),{sizeFrom:s,sizeTo:r}}fillLeftBottomRect(){const e=new Path2D;e.rect(this.sp.yAxisBox.minX,this.sp.yAxisBox.maxY,this.sp.yAxisBox.width,this.sp.xAxisBox.height),this.ctx.fillStyle="white",this.ctx.beginPath(),this.ctx.fill(e),this.ctx.closePath()}createMultiLinesIndices(){const e=new G.Z(this.lines.from.length);e.setAll(!0);for(let t=-1;-1!==(t=e.findNext(t));){const n=t,s=this.lines.from[n],r=this.lines.to[n];let i=1;for(let n=t;-1!==(n=e.findNext(n));){const t=this.lines.from[n],o=this.lines.to[n];(t===s&&o===r||o===s&&t===r)&&(this.multipleLinesCounts[n]=++i,e.setBit(n,!1,!1))}i>1&&(this.multipleLinesCounts[n]=1),e.setBit(t,!1,!1)}}checkCoordsOnLine(e,t){let n=-1,s=null,r=null;const i=this.sp.getOptions().look,o=i.sizeColumnName?this.sp.dataFrame.col(i.sizeColumnName):null,a=this.sp.dataFrame.filter;for(let l=0;l<this.lines.from.length;l++)if(a.get(this.lines.from[l])&&a.get(this.lines.to[l])&&this.visibility.getBit(l)){const{sizeFrom:a,sizeTo:c}=this.getMarkersSizes(i,o,l),u=this.sp.worldToScreen(this.xAxisCol.get(this.lines.from[l]),this.yAxisCol.get(this.lines.from[l])),h=this.sp.worldToScreen(this.xAxisCol.get(this.lines.to[l]),this.yAxisCol.get(this.lines.to[l]));if(this.multipleLinesCounts[l]){const n=this.getLineLength(u.x,u.y,h.x,h.y),s=this.getPointOnDistance(u.x,u.y,h.x,h.y,c,n),i=this.getPointOnDistance(h.x,h.y,null==u?void 0:u.x,null==u?void 0:u.y,a,n),o=this.lines.from[l]>this.lines.to[l]?this.findControlPoint(this.multipleLinesCounts[l],s.x,s.y,i.x,i.y,l):this.findControlPoint(this.multipleLinesCounts[l],i.x,i.y,s.x,s.y,l);r=this.calculateDistToCurveLine(l,e,t,s,i,o)}else r=this.calculateDistToStraightLine(e,t,u,h);(!s&&null!==r&&r<5||s&&null!==r&&r<s)&&(s=r,n=l)}return n}calculateDistToStraightLine(e,t,n,s){const r=Math.min(n.x,s.x),i=Math.max(n.x,s.x),o=Math.min(n.y,s.y),a=Math.max(n.y,s.y);return e>=r-2&&e<=i+2&&t>=o-2&&t<=a+2?this.distToStraightLineSegment(e,t,n,s):null}distToStraightLineSegment(e,t,n,s){const r=(e,t,n,s)=>Math.pow(e-n,2)+Math.pow(t-s,2),i=r(n.x,n.y,s.x,s.y);if(0==i)return r(e,t,n.x,n.y);let o=((e-n.x)*(s.x-n.x)+(t-n.y)*(s.y-n.y))/i;return o=Math.max(0,Math.min(1,o)),r(e,t,n.x+o*(s.x-n.x),n.y+o*(s.y-n.y))}calculateDistToCurveLine(e,t,n,s,r,i){const o=Math.min(s.x,r.x,i.x),a=Math.max(s.x,r.x,i.x),l=Math.min(s.y,r.y,i.y),c=Math.max(s.y,r.y,i.y);if(t>=o-2&&t<=a+2&&n>=l-2&&n<=c+2){const e=a-o,u=c-l;return this.calculateDistToCurveInRect(t,n,s,i,r,e,u)}return null}calculateDistToCurveInRect(e,t,n,s,r,i,o){const a=Math.floor((i+o)/3),l=1/a,c=new Uint32Array(a),u=new Uint32Array(a),h=new Uint32Array(a);let d=null;const m=new G.Z(a);for(let i=0;i<c.length;i++){const o=i*l,a=Math.pow(1-o,2)*n.x+2*o*(1-o)*s.x+Math.pow(o,2)*r.x,m=Math.pow(1-o,2)*n.y+2*o*(1-o)*s.y+Math.pow(o,2)*r.y,p=Math.abs(e-a),f=Math.abs(t-m),g=p+f;(!d||d>g)&&(d=g),h[i]=Math.max(p,f),c[i]=a,u[i]=m}for(let e=0;e<c.length;e++)h[e]<d&&m.setBit(e,!0,!1);let p=null;for(let n=-1;-1!==(n=m.findNext(n));){const s=Math.hypot(c[n]-e,u[n]-t);(!p||p>s)&&(p=s)}return p}getLineLength(e,t,n,s){return Math.sqrt(Math.pow(n-e,2)+Math.pow(s-t,2))}getPointOnDistance(e,t,n,s,r,i){const o=n-r*((n-e)/i),l=s-r*((s-t)/i);return new a.Point(o,l)}findControlPoint(e,t,n,s,r,i){const o=t+(s-t)/2,l=n+(r-n)/2;let c=o-t,u=l-n;const h=Math.sqrt(c*c+u*u);c/=h,u/=h;const d=50*Math.ceil(e/2);return e%2==0?new a.Point(o+d/2*u,l-d/2*c):new a.Point(o-d/2*u,l+d/2*c)}canvasArrow(e,t,n,s,r){const i=Math.atan2(s-t,r-n)+Math.PI;e.moveTo(t-this.arrowWidth*Math.sin(i-Math.PI/10),n-this.arrowWidth*Math.cos(i-Math.PI/10)),e.lineTo(t,n),e.lineTo(t-this.arrowWidth*Math.sin(i+Math.PI/10),n-this.arrowWidth*Math.cos(i+Math.PI/10))}}const B="dimensionality-reducer-terminate-event";var V,U,H=n(850);async function j(e,t,s,r,o,a,l){let c=await async function(e,t,s,r,o,a,l){if(!a.distanceFnArgs)throw new Error("options.distanceFnArgs must be defined");if(e.length!==t.length||e.length!==a.distanceFnArgs.length||e.length!==r.length)throw new Error("data, metrics and options and weights must have the same length");return new Promise((function(c,u){const h=new Worker(new URL(n.p+n.u(42),n.b));h.postMessage({columnsData:e,distanceMetrics:t,method:s,options:a,weights:r,aggregationMethod:o});const d=i.events.onCustomEvent(B).subscribe((()=>{try{h?.terminate()}finally{d.unsubscribe()}}));h.onmessage=({data:{error:e,embedding:t,epochNum:n,epochsLength:s}})=>{L(n)||L(s)?(d.unsubscribe(),e?u(e):c(t),setTimeout((()=>h.terminate()),100)):l&&l(n,s,t)}}))}(e,s,t,r,o,a,l);return c=c.map((e=>(0,H.Fv)(e))),c}(U=V||(V={})).EUCLIDEAN="EUCLIDEAN",U.MANHATTAN="MANHATTAN";const W={[V.EUCLIDEAN]:function(e){return`\n var sum = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n sum = sum + distances[i] * distances[i] * computeInfo.weights[i] * computeInfo.weights[i];\n }\n return sqrt(sum);\n `},[V.MANHATTAN]:function(e){return`\n var sum = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n sum = sum + abs(distances[i]) * computeInfo.weights[i];\n }\n return sum;\n `}};var Y,Z;(Z=Y||(Y={})).HAMMING="Hamming",Z.EUCLIDEAN="Euclidean",Z.MANHATTAN="Manhattan",Z.TANIMOTO="Tanimoto",Z.LEVENSTEIN="Levenshtein",Z.NEEDLEMAN_WUNSCH="Needlemann-Wunsch",Z.MONOMER_CHEMICAL_DISTANCE="Monomer chemical distance",Z.SOKAL="Sokal",Z.COSINE="Cosine",Z.ASYMMETRIC="Asymmetric",Z.Difference="Difference",Z.OneHot="One-Hot";const K={[Y.HAMMING]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n let maxLength: u32 = max(aLength, bLength);\n let minLength: u32 = min(aLength, bLength);\n let sizeDiff: u32 = maxLength - minLength;\n \n let maxIntDistance = ceil(maxDistance * f32(maxLength)) - f32(sizeDiff);\n\n var diff: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n diff = diff + f32(a[i] != b[i]);\n if (diff > maxIntDistance) {\n return 1.0;\n }\n }\n diff += f32(sizeDiff);\n return diff / ${e};\n `},[Y.EUCLIDEAN]:function(e,t){return`\n var dist: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n dist = dist + f32(a[i] - b[i]) * f32(a[i] - b[i]);\n }\n return sqrt(dist);\n `},[Y.MANHATTAN]:function(e,t){return`\n var dist: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n dist = dist + abs(f32(a[i] - b[i]));\n }\n return dist;\n `},[Y.TANIMOTO]:function(e,t){return`\n var onBitsa: u32 = 0u;\n var onBitsb: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n onBitsa = onBitsa + countOneBits(a[i]);\n onBitsb = onBitsb + countOneBits(b[i]);\n }\n\n if (onBitsa == 0u && onBitsb == 0u) {\n return 0.0;\n }\n\n let totalOnBits = onBitsa + onBitsb;\n var commonBits: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n commonBits = commonBits + countOneBits(a[i] & b[i]);\n }\n\n return 1.0 - f32(commonBits) / f32(totalOnBits - commonBits);\n `},[Y.LEVENSTEIN]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n let maxLength: u32 = max(aLength, bLength);\n let minLength: u32 = min(aLength, bLength);\n\n let maxIntDistance = ceil(maxDistance * f32(maxLength));\n\n // we will store two arrays as matrix and swap the working indices per pass.\n // this way we can reduce memory usage per computation to just O(aLength)\n // the grid will have aLength + 1 columns and bLength + 1 rows\n // this will be guaranteed by iteration, but the array sizes must be known at compile time, so we will use a fixed size of maxArraySize\n var dynamicPassMat: array<array<f32, ${e+1}u>, 2>; // initialize to 0\n \n var prevIndex: u32 = 0;\n var curIndex: u32 = 1; // we will swap these indices per pass\n\n // initialize the first row\n for (var i = 0u; i <= aLength; i = i + 1u) {\n dynamicPassMat[prevIndex][i] = f32(i);\n }\n\n // iterate over the rows\n for (var i = 1u; i <= bLength; i = i + 1u) {\n dynamicPassMat[curIndex][0] = f32(i);\n var minEntry: f32 = f32(maxLength);\n let prevRow = &dynamicPassMat[prevIndex];\n let curRow = &dynamicPassMat[curIndex];\n let bMon = u32(b[i - 1]);\n for (var j = 1u; j <= aLength; j = j + 1u) {\n var cost: f32 = f32(a[j - 1] != bMon);\n var res: f32 = min(\n min(\n (*prevRow)[j] + 1.0, // deletion\n (*curRow)[j - 1] + 1.0, // insertion\n ),\n (*prevRow)[j - 1] + cost // substitution\n );\n (*curRow)[j] = res;\n if (res < minEntry) {\n minEntry = res;\n }\n }\n // swap the indices\n let temp: u32 = prevIndex;\n prevIndex = curIndex;\n curIndex = temp;\n if (minEntry > maxIntDistance) {\n return 1.0;\n }\n }\n\n return dynamicPassMat[prevIndex][aLength] / f32(maxLength);\n `},[Y.NEEDLEMAN_WUNSCH]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n let maxLength: u32 = max(aLength, bLength);\n let minLength: u32 = min(aLength, bLength);\n \n let maxIntDistance = ceil(maxDistance * f32(maxLength));\n // we will store two arrays as matrix and swap the working indices per pass.\n // this way we can reduce memory usage per computation to just O(aLength)\n // the grid will have aLength + 1 columns and bLength + 1 rows\n // this will be guaranteed by iteration, but the array sizes must be known at compile time, so we will use a fixed size of maxArraySize\n var dynamicPassMat: array<array<f32, ${e+1}u>, 2>; // initialize to 0\n \n // we need to keep track of which operation led to the current cell\n // i.e. whether we came from the left, top or diagonal to assign gap open/gap extend penalty\n var verticalGaps: array<u32, ${e+1}u>;\n var horizontalGaps: array<u32, ${e+1}u>;\n\n let gapOpenPenalty: f32 = suppInfo.gapOpenPenalty${t};\n let gapExtensionPenalty: f32 = suppInfo.gapExtensionPenalty${t};\n var prevIndex: u32 = 0;\n var curIndex: u32 = 1; // we will swap these indices per pass\n // initialize the first row\n for (var i = 0u; i <= aLength; i = i + 1u) {\n dynamicPassMat[prevIndex][i] = gapOpenPenalty + f32(i - 1) * gapExtensionPenalty;\n dynamicPassMat[curIndex][i] = 0.0;\n }\n dynamicPassMat[0][0] = 0.0;\n\n let simMatrix = &suppInfo.similarityMatrix${t}; // using pointers make things faster\n // iterate over the rows\n for (var i = 1u; i <= bLength; i = i + 1u) {\n let prevRow = &dynamicPassMat[prevIndex];\n let curRow = &dynamicPassMat[curIndex];\n (*curRow)[0] = gapOpenPenalty + f32(i - 1) * gapExtensionPenalty;\n var minEntry: f32 = f32(maxLength);\n let monB = u32(b[i - 1]);\n for (var j = 1u; j <= aLength; j = j + 1u) {\n let monA = u32(a[j - 1]);\n \n let cost: f32 = (*prevRow)[j - 1] + 1f - (*simMatrix)[monA][monB];\n var top = (*prevRow)[j]; // deletion\n if (verticalGaps[j] > 0) {\n top = top + gapExtensionPenalty;\n } else {\n top = top + gapOpenPenalty;\n }\n var left = (*curRow)[j - 1]; // insertion\n if (horizontalGaps[j - 1] > 0) {\n left = left + gapExtensionPenalty;\n } else {\n left = left + gapOpenPenalty;\n }\n var res: f32 = min(\n min(\n top, // deletion\n left, // insertion\n ),\n cost // substitution\n );\n (*curRow)[j] = res;\n if (res < minEntry) {\n minEntry = res;\n }\n // update the horizontal and vertical gaps\n if (res == cost) {\n verticalGaps[j] = 0;\n horizontalGaps[j] = 0;\n } else if (res == left) {\n verticalGaps[j] = 0;\n horizontalGaps[j] = 1;\n } else {\n verticalGaps[j] = 1;\n horizontalGaps[j] = 0;\n }\n }\n // swap the indices\n let temp: u32 = prevIndex;\n prevIndex = curIndex;\n curIndex = temp;\n if (minEntry > maxIntDistance) {\n return 1.0;\n }\n }\n return dynamicPassMat[prevIndex][aLength] / f32(maxLength);\n \n `},[Y.MONOMER_CHEMICAL_DISTANCE]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n let maxLength: u32 = max(aLength, bLength);\n let minLength: u32 = min(aLength, bLength);\n let sizeDiff: u32 = maxLength - minLength;\n \n let maxIntDistance = ceil(maxDistance * f32(maxLength)) - f32(sizeDiff);\n\n let simMatrix = &(suppInfo.similarityMatrix${t}); // using pointers make things faster\n var diff: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n diff = diff + 1.0 - (*simMatrix)[u32(a[i])][u32(b[i])];\n if (diff > maxIntDistance) {\n return 1.0;\n }\n }\n diff += f32(sizeDiff);\n return diff / ${e};\n `},[Y.SOKAL]:function(e,t){return`\n var onBitsa: u32 = 0u;\n var onBitsb: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n onBitsa = onBitsa + countOneBits(a[i]);\n onBitsb = onBitsb + countOneBits(b[i]);\n }\n let total = onBitsa + onBitsb;\n if (total == 0u) {\n return 1.0;\n }\n var commonBits: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n commonBits = commonBits + countOneBits(a[i] & b[i]);\n }\n return 1.0 - f32(commonBits) / f32(total * 2 - commonBits * 3);\n `},[Y.COSINE]:function(e,t){return`\n var onBitsa: u32 = 0u;\n var onBitsb: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n onBitsa = onBitsa + countOneBits(a[i]);\n onBitsb = onBitsb + countOneBits(b[i]);\n }\n let total = onBitsa * onBitsb; // p.s. here total is taken by multiplying\n if (total == 0u) {\n return 1.0;\n }\n var commonBits: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n commonBits = commonBits + countOneBits(a[i] & b[i]);\n }\n return 1.0 - f32(commonBits) / sqrt(f32(total));\n `},[Y.ASYMMETRIC]:function(e,t){return`\n var onBitsa: u32 = 0u;\n var onBitsb: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n onBitsa = onBitsa + countOneBits(a[i]);\n onBitsb = onBitsb + countOneBits(b[i]);\n }\n let min = min(onBitsa, onBitsb);\n if (min == 0u) {\n return 1.0;\n }\n var commonBits: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n commonBits = commonBits + countOneBits(a[i] & b[i]);\n }\n return 1.0 - f32(commonBits) / f32(min);\n `},[Y.Difference]:function(e,t){return`\n let range = suppInfo.range${t};\n return f32(abs(f32(a[0]) - f32(b[0])) / range);\n `},[Y.OneHot]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n if (aLength != bLength) {\n return 1.0;\n }\n for (var i = 0u; i < aLength; i = i + 1u) {\n if(a[i] != b[i]) {\n return 1.0;\n }\n }\n return 0.0;\n `}},q={[Y.HAMMING]:e=>Math.ceil(e/30),[Y.EUCLIDEAN]:e=>Math.ceil(e/30),[Y.MANHATTAN]:e=>Math.ceil(e/30),[Y.TANIMOTO]:e=>Math.ceil(e/60),[Y.SOKAL]:e=>Math.ceil(e/60),[Y.COSINE]:e=>Math.ceil(e/60),[Y.ASYMMETRIC]:e=>Math.ceil(e/60),[Y.LEVENSTEIN]:e=>Math.ceil(e*e/60),[Y.NEEDLEMAN_WUNSCH]:e=>Math.ceil(e*e/60),[Y.MONOMER_CHEMICAL_DISTANCE]:e=>Math.ceil(e/25),[Y.Difference]:e=>1,[Y.OneHot]:e=>Math.ceil(e/40)},z={STRING:new Set([Y.HAMMING,Y.LEVENSTEIN,Y.NEEDLEMAN_WUNSCH,Y.MONOMER_CHEMICAL_DISTANCE,Y.OneHot]),UINT32ARRAY:new Set([Y.HAMMING,Y.EUCLIDEAN,Y.MANHATTAN,Y.MONOMER_CHEMICAL_DISTANCE,Y.LEVENSTEIN,Y.NEEDLEMAN_WUNSCH,Y.TANIMOTO,Y.COSINE,Y.SOKAL,Y.ASYMMETRIC,Y.OneHot,Y.Difference]),INT32ARRAY:new Set([Y.EUCLIDEAN,Y.MANHATTAN,Y.OneHot,Y.Difference]),FLOAT32ARRAY:new Set([Y.EUCLIDEAN,Y.MANHATTAN,Y.Difference]),NUMBER:new Set([Y.EUCLIDEAN,Y.MANHATTAN,Y.Difference]),BITARRAY:new Set([Y.TANIMOTO,Y.COSINE,Y.SOKAL,Y.ASYMMETRIC])};var X=function(e,t,n,s){return new(n||(n=Promise))((function(r,i){function o(e){try{l(s.next(e))}catch(e){i(e)}}function a(e){try{l(s.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))},J=function(e,t,n,s){return new(n||(n=Promise))((function(r,i){function o(e){try{l(s.next(e))}catch(e){i(e)}}function a(e){try{l(s.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};function Q(e,t,n,s){return e.map(((e,s)=>`\n fn distanceScript${s}(aIndex: u32, bIndex: u32) -> f32 {\n let a = computeInfo.data${s}[aIndex];\n let b = computeInfo.data${s}[bIndex];\n let maxDistance: f32 = ${n};\n ${K[e](t[s],s)}\n }\n `)).join("\n")+"\n"+`\n fn combinedDistance(aIndex: u32, bIndex: u32) -> f32 {\n var distances: array<f32, ${e.length}>;\n ${e.map(((e,t)=>`distances[${t}] = distanceScript${t}(aIndex, bIndex);`)).join("\n")}\n ${W[s](e.length)}\n }\n \n `}let ee=0;const te="cliffsDf",ne=new y.Subject,se="activity_difference",re="SALI_index",ie="similarity",oe="line_index",ae=["1_molecule","2_molecule"],le="filterCliffs";async function ce(e,t,s,r,l,c,u,h,m,p,g,y,b,v,w,C){ee++;const S=c/100;let A,x=!1;const E=y.inputs,I=await y.apply({[E[0].name]:t,[E[1].name]:u,...m.preprocessingFuncArgs??{}});let T=[];if(h===d){const t=await function(e,t,s,r,i,o,a=10,l=!1){const c=new Worker(new URL(n.p+n.u(246),n.b));let u;return c.postMessage({data:e,threshold:t,weights:s,aggregationMethod:r,distanceFns:i,distanceFnArgs:o,maxIterations:a,useWebGPU:l}),{promise:new Promise(((e,t)=>{u=e,c.onmessage=t=>{setTimeout((()=>c.terminate()),100),e(t.data.res)},c.onerror=e=>{setTimeout((()=>c.terminate()),100),t(e)}})),terminate:()=>{try{u(null),c.terminate()}catch(e){console.error(e)}}}}([I.entries],c,[1],"MANHATTAN",[u],[I.options??{}],m?.maxIterations??5,m.useWebGPU??!1).promise;e.columns.addNewInt(e.columns.getUnusedName("MCL Cluster")).init((e=>t.clusters[e])),T=[t.embedX,t.embedY]}else T=await j([I.entries],h,[u],[1],"MANHATTAN",{...m,distanceFnArgs:[I.options??{}]});if(T.length!==s.length)throw new Error("Number of axes names should be equal to number of embedding dimensions");for(let t=0;t<T.length;++t)e.columns.addNewFloat(s[t]).init((e=>T[t][e]));let _=null;if(m.useWebGPU)try{_=await function(e,t=.8,n,s,r,i){return J(this,void 0,void 0,(function*(){const o=yield function(){return X(this,void 0,void 0,(function*(){const e=yield navigator.gpu.requestAdapter({powerPreference:"high-performance"});if(null==e)return null;const t=1e9,n=e.limits,s=n.maxBufferSize,r=n.maxStorageBufferBindingSize;try{return yield e.requestDevice({requiredLimits:{maxBufferSize:Math.min(s,t),maxStorageBufferBindingSize:Math.min(r,t)}})}catch(t){return console.error("Failed to create device with required limits",t),yield e.requestDevice()}}))}();if(!o)return null;const a=Object.values(Y);if(n.some((e=>!a.includes(e))))throw new Error("Invalid distance metrics provided: "+n.join(", "));if(!Object.values(V).includes(s))throw new Error("Invalid aggregation function provided: "+s);const l=1-t;if(i.length!==e.length||i.length!==n.length||i.length!==r.length)throw new Error("Options, weigths and distance functions must be provided for each column");if(e.some((t=>t.length!==e[0].length)))throw new Error("All entry lists must be the same length");const c=e.length,u=e[0].length,h=e.map(((e,t)=>function(e,t=Y.HAMMING,n,s={gapOpenPenalty:1,gapExtensionPenalty:.6}){var r,i;let o=null;const a=e.some((e=>"string"==typeof e))?(o="STRING",e.map((e=>new Uint32Array(e.split("").map((e=>e.charCodeAt(0))))))):e.some((e=>"number"==typeof e))?(o="NUMBER",e.map((e=>new Float32Array([e])))):"object"==typeof e[0]&&e.some((e=>"_data"in e&&"_length"in e))?(o="BITARRAY",e.map((e=>e._data))):e.some((e=>e instanceof Float32Array))?(o="FLOAT32ARRAY",e):e.some((e=>e instanceof Uint32Array))?(o="UINT32ARRAY",e):e.some((e=>e instanceof Int32Array))?(o="INT32ARRAY",e):void 0;if(!a||!o)throw new Error("Invalid entry type, could not determine entry type from input list");const l=a[0]instanceof Int32Array?"INT32ARRAY":a[0]instanceof Float32Array?"FLOAT32ARRAY":"UINT32ARRAY",c=new Uint32Array(a.map((e=>e.length)));if(!z[o]||!z[o].has(t))throw new Error(`Distance metric '${t}' not supported for entry type '${o}'`);const u=c.reduce(((e,t)=>Math.max(e,t)),0),h=q[t](u),d="INT32ARRAY"===l?Int32Array:"FLOAT32ARRAY"===l?Float32Array:Uint32Array,m=new d(a.length*u);a.forEach(((e,t)=>{m.set(e,t*u)}));let p="",f=0,g="FLOAT32ARRAY",y=null;if(t===Y.NEEDLEMAN_WUNSCH||t===Y.MONOMER_CHEMICAL_DISTANCE){let e=s.scoringMatrix&&s.alphabetIndexes?Object.keys(s.alphabetIndexes).reduce(((e,t)=>Math.max(e,t.charCodeAt(0))),0):-1;if(!s.alphabetIndexes||!s.scoringMatrix){for(let t=0;t<m.length;t++)m[t]>e&&(e=m[t]);s.scoringMatrix=new Array(e+1).fill(null).map((()=>new Array(e+1).fill(0))),s.alphabetIndexes={};for(let e=0;e<s.scoringMatrix.length;e++)s.scoringMatrix[e][e]=1,s.alphabetIndexes[String.fromCharCode(e)]=e}const t=(e+1)*(e+1),o=new Array(e+1).fill(null).map((()=>new Float32Array(e+1)));for(let t=0;t<e+1;t++)o[t][t]=1;const a=s.alphabetIndexes;for(const e of Object.keys(a))for(const t of Object.keys(a))e!==t&&(o[e.charCodeAt(0)][t.charCodeAt(0)]=s.scoringMatrix[a[e]][a[t]]);f=2+t,g="FLOAT32ARRAY",y=new Float32Array(f),y[0]=null!==(r=s.gapOpenPenalty)&&void 0!==r?r:1,y[1]=null!==(i=s.gapExtensionPenalty)&&void 0!==i?i:.6;let l=2;for(let e=0;e<o.length;e++)y.set(o[e],l),l+=o[e].length;p=`\n gapOpenPenalty${n}: f32,\n gapExtensionPenalty${n}: f32,\n similarityMatrix${n}: array<array<f32, ${e+1}>, ${e+1}>`}else if(t===Y.Difference){if(!s.range||"number"!=typeof s.range||s.range<=0){const e=m.reduce(((e,t)=>Math.min(e,t)),m[0]),t=m.reduce(((e,t)=>Math.max(e,t)),m[0]);s.range=t-e}if(s.range<=0)throw new Error("Invalid range for difference distance metric: "+s.range);f=1,g="FLOAT32ARRAY",y=new Float32Array([s.range]),p=`\n range${n}: f32`}const b=m instanceof Int32Array?"i32":m instanceof Float32Array?"f32":"u32",v=`data${n}: array<array<${b}, ${u}>, ${a.length}>`;return{flatSourceArray:m,sourceArraySize:m.length,maxEntryLen:u,arraySizes:c,complexity:h,suppInfoBuffer:y,suppInfoSize:f,suppInfoType:g,suppInfoStructWgsl:p,entryType:o,dataTypeWGSL:b,dataStructWgsl:v,EncodedArrayConstructor:d}}(e,n[t],t,i[t])));if(0===c)throw new Error("No columns provided. Please provide at least one column of data.");1===c&&(s=V.MANHATTAN);let d=h.map((e=>e.suppInfoStructWgsl)).filter((e=>!!e&&""!=e)).join(",\n"),m=!1;d&&""!=d.trim()||(m=!0,d="\ndummy: f32\n");const p=h.map((e=>e.dataStructWgsl)).filter((e=>!!e&&""!=e)).join(",\n"),f=new Uint32Array(c*u);h.forEach(((e,t)=>{f.set(e.arraySizes,t*u)}));const g=1e4,y=100,b=h.reduce(((e,t)=>e+t.complexity),0),v=Math.ceil(1e4/b),w=Math.ceil(Math.sqrt(Math.ceil(100))),C=10*w,S=u*(u-1)/2,A=Math.ceil(S/g),x=o.createShaderModule({label:"Sparse matrix compute shader",code:`\n // each thread will perform 100 iterations at one time, comparing 100 pairs of entries.\n // in total, each thread will perform at most ${A} comparisons.\n // first is the result struct, containing is, js, and distances. each array with length of 100,\n // and also integer for how many pairs were found to be below threshold.\n struct SparseResult {\n i: array<array<u32, 100>, 10000>,\n j: array<array<u32, 100>, 10000>,\n distances: array<array<f32, 100>, 10000>,\n found: array<u32, 10000>,\n done: array<u32, 10000>\n }\n // struct for the data\n struct ComputeInfo {\n // start at cols and rows, and end at cols and rows for each thread, these will be calculated on cpu and passed to gpu.\n startAtCols: array<u32, 10000>,\n startAtRows: array<u32, 10000>,\n endAtCols: array<u32, 10000>,\n endAtRows: array<u32, 10000>,\n\n // the ACTUALLY sizes of each entry\n entrySizes: array<array<u32, ${u}>, ${c}>,\n // the weights for each entry\n weights: array<f32, ${c}>,\n // the data for each entry\n ${p} // an example of the dataWgsl would be:\n //data0: array<array<u32,20>,100>,\n //data1: array<array<u32,20>,100>\n }\n\n // struct for the supplementary information\n struct SuppInfo {\n // struct containing all the supplementary info, like scoring matrix, alphabet indexes, range, etc.\n ${d}\n };\n\n @group(0) @binding(0) var<storage, read_write> computeInfo: ComputeInfo;\n @group(0) @binding(1) var<storage, read_write> suppInfo: SuppInfo;\n @group(0) @binding(2) var<storage, read_write> results: SparseResult;\n @compute @workgroup_size(10, 10) fn calcSparseMatrix(\n @builtin(global_invocation_id) id: vec3<u32>\n ) {\n ${m?"let otherDummy = suppInfo.dummy * 2;":""} // just to make sure that the suppInfo is not optimized out\n let threadCol = id.x;\n let threadRow = id.y;\n let linearIndex = threadRow * ${C} + threadCol;\n if (linearIndex >= 10000) {\n return; // if we are out of bounds, return\n } \n var startAtCol: u32 = computeInfo.startAtCols[linearIndex];\n var startAtRow: u32 = computeInfo.startAtRows[linearIndex];\n let endAtCol: u32 = min(computeInfo.endAtCols[linearIndex], ${u}u);\n let endAtRow: u32 = min(computeInfo.endAtRows[linearIndex], ${u}u);\n let is = &results.i[linearIndex];\n let js = &results.j[linearIndex];\n let distances = &results.distances[linearIndex];\n results.found[linearIndex] = 0; // initialize the found counter\n var found: u32 = 0;\n if (results.done[linearIndex] > 0) {\n return; // if we are done, return\n }\n for (var i = 0; i < ${v}; i++) {\n if (startAtCol >= endAtCol && startAtRow >= endAtRow) {\n results.done[linearIndex] = 1;\n break;\n }\n if (found >= 100) {\n break;\n }\n let dist = combinedDistance(startAtCol, startAtRow);\n if (dist <= ${l}) {\n (*is)[found] = startAtCol;\n (*js)[found] = startAtRow;\n (*distances)[found] = dist;\n found = found + 1;\n }\n startAtCol = startAtCol + 1;\n if (startAtCol >= ${u}u) {\n startAtRow += 1;\n startAtCol = startAtRow + 1;\n }\n }\n results.found[linearIndex] = found;\n // update the startAtCols and startAtRows\n computeInfo.startAtCols[linearIndex] = startAtCol;\n computeInfo.startAtRows[linearIndex] = startAtRow;\n\n }\n\n // this will generate the distance script for each distance metric and then combine them into one\n ${Q(n,h.map((e=>e.maxEntryLen)),l,s)}\n\n\n `}),E=o.createComputePipeline({label:"sparse matrix compute pipeline",layout:"auto",compute:{module:x,entryPoint:"calcSparseMatrix"}}),I=new Uint32Array(g),T=new Uint32Array(g),_=new Uint32Array(g),M=new Uint32Array(g),$=Math.floor(S/g);let N=0,L=1;console.time("GPUthreadStarts");for(let e=0;e<g;e++){const t=9999===e?S-1:(e+1)*$,n=u-2-Math.floor(Math.sqrt(-8*t+4*u*(u-1)-7)/2-.5),s=t-u*n+Math.floor((n+1)*(n+2)/2);I[e]=L,T[e]=N,_[e]=s,M[e]=n,N=n,L=s}console.timeEnd("GPUthreadStarts");const P=4e4+u*c+c+h.reduce(((e,t)=>e+t.sourceArraySize),0),R=h.reduce(((e,t)=>e+t.suppInfoSize),0),O=1e6,k=P*Uint32Array.BYTES_PER_ELEMENT;let F=k;const G=15&k;0!==G&&(F+=16-G);const D=o.createBuffer({label:"compute info buffer",size:F,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST,mappedAtCreation:!0}),B=D.getMappedRange();let U=0;new Uint32Array(B,U,g).set(I),U+=g*Uint32Array.BYTES_PER_ELEMENT,new Uint32Array(B,U,g).set(T),U+=g*Uint32Array.BYTES_PER_ELEMENT,new Uint32Array(B,U,g).set(_),U+=g*Uint32Array.BYTES_PER_ELEMENT,new Uint32Array(B,U,g).set(M),U+=g*Uint32Array.BYTES_PER_ELEMENT,new Uint32Array(B,U,f.length).set(f),U+=f.length*Uint32Array.BYTES_PER_ELEMENT,new Float32Array(B,U,c).set(r),U+=c*Float32Array.BYTES_PER_ELEMENT;for(const e of h){const t=e.EncodedArrayConstructor,n=e.sourceArraySize;new t(B,U,n).set(e.flatSourceArray),U+=n*t.BYTES_PER_ELEMENT}D.unmap();const H=R*Uint32Array.BYTES_PER_ELEMENT;let j=H;const W=15&H;0!==W&&(j+=16-W),j=Math.max(j,16);const Z=o.createBuffer({label:"supp info buffer",size:j,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST,mappedAtCreation:!0}),K=Z.getMappedRange();let J=0;for(const e of h)e.suppInfoBuffer&&e.suppInfoBuffer.byteLength>0&&e.suppInfoSize>0&&(new("UINT32ARRAY"===e.suppInfoType?Uint32Array:Float32Array)(K,J,e.suppInfoBuffer.length).set(e.suppInfoBuffer),J+=e.suppInfoBuffer.byteLength);0===J&&new Uint32Array(K,0,4).set([1,1,1,1]),Z.unmap();const ee=302e4*Uint32Array.BYTES_PER_ELEMENT;let te=ee;const ne=15ⅇ0!==ne&&(te+=16-ne);const se=o.createBuffer({label:"results buffer",size:te,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),re=o.createBindGroup({label:"bindGroup for sparse matrix buffer",layout:E.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:D}},{binding:1,resource:{buffer:Z}},{binding:2,resource:{buffer:se}}]}),ie=o.createBuffer({label:"results out buffer",size:se.size,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),oe=[],ae=[],le=[];let ce=!1;for(;!ce;){const e=o.createCommandEncoder({label:"distance encoder"}),t=e.beginComputePass({label:"distance compute pass"});t.setPipeline(E),t.setBindGroup(0,re),t.dispatchWorkgroups(w,w),t.end(),e.copyBufferToBuffer(se,0,ie,0,ie.size);const n=e.finish();o.queue.submit([n]),yield o.queue.onSubmittedWorkDone(),yield ie.mapAsync(GPUMapMode.READ);const s=ie.getMappedRange();let r=0;const i=new Uint32Array(s,r,O);r+=O*Uint32Array.BYTES_PER_ELEMENT;const a=new Uint32Array(s,r,O);r+=O*Uint32Array.BYTES_PER_ELEMENT;const l=new Float32Array(s,r,O);r+=O*Float32Array.BYTES_PER_ELEMENT;const c=new Uint32Array(s,r,g);r+=g*Uint32Array.BYTES_PER_ELEMENT,ce=new Uint32Array(s,r,g).every((e=>1===e));const u=c.reduce(((e,t)=>e+t),0),h=new Uint32Array(u),d=new Uint32Array(u),m=new Float32Array(u);let p=0;for(let e=0;e<c.length;e++){const t=c[e];0!==t&&(h.set(i.subarray(e*y,e*y+t),p),d.set(a.subarray(e*y,e*y+t),p),m.set(l.subarray(e*y,e*y+t),p),p+=t)}oe.push(h),ae.push(d),le.push(m),ie.unmap()}const ue=oe.reduce(((e,t)=>e+t.length),0),he=new Uint32Array(ue),de=new Uint32Array(ue),me=new Float32Array(ue);let pe=0;for(let e=0;e<oe.length;e++)he.set(oe[e],pe),de.set(ae[e],pe),me.set(le[e],pe),pe+=oe[e].length;return o.destroy(),{i:he,j:de,distance:me}}))}([I.entries],S,[u],V.MANHATTAN,[1],[I.options??{}])}catch(e){console.error(e)}_||(m.useWebGPU&&console.error("WebGPU sparse matrix calculation failed, falling back to CPU implementation"),_=await(new k).calc(I.entries,u,S,I.options));const M=await async function(e,t){const n=e.distance.map(((n,s)=>{const r=Math.abs(t.get(e.i[s])-t.get(e.j[s]));return 0!=n?r/n:1/0})),s=e.distance.map((e=>1-e)),r=e.i,i=e.j,o=new Set;return e.distance.forEach(((t,n)=>{o.add(e.i[n]),o.add(e.j[n])})),{simVals:s,saliVals:n,n1:r,n2:i,cliffsMolIds:o}}(_,l),$=function(e,t,n,s,r,i){const o=new Array(e).fill(0);for(let e=0;e!=n.length;++e)t[e]!=1/0&&(i.get(n[e])>i.get(s[e])?o[n[e]]+=t[e]:o[s[e]]+=t[e]);return a.Column.fromList("double",`sali_${r[0].substring(r[0].lastIndexOf("_"))}`,o)}(t.length,M.saliVals,M.n1,M.n2,s,l);e.columns.add($);const N=function(e,t){const n=a.BitSet.create(e.rowCount);for(let s=0;s<e.rowCount;s++)n.set(s,t.has(s));return n}(e,M.cliffsMolIds),L=function(e){const t=e.filter((e=>e!==1/0)),n=t.reduce(((e,t)=>Math.min(e,t)),Number.MAX_VALUE),s=t.reduce(((e,t)=>Math.max(e,t)),n);return{max:s,min:n}}(M.saliVals),P=.8/(L.max-L.min),R=i.shell.getTableView(e.name),O=R.addViewer(a.VIEWER.SCATTER_PLOT,{xColumnName:s[0],yColumnName:s[1],size:$.name,color:l.name,showXSelector:!1,showYSelector:!1,showSizeSelector:!1,showColorSelector:!1,markerMinSize:5,markerMaxSize:25,title:r}),G=function(e,t,n,s,r,i,o,l){const c={from:new Uint32Array(t.n1.length),to:new Uint32Array(t.n1.length),opacities:new Float32Array(t.n1.length),colors:new Array(t.n1.length),widths:new Float32Array(t.n1.length)};for(let n=0;n<t.n1.length;n++)c.from[n]=t.n1[n],c.to[n]=t.n2[n],c.opacities[n]=t.saliVals[n]===1/0?1:.2+(t.saliVals[n]-o.min)*l,c.colors[n]=e.selection.get(c.from[n])&&e.selection.get(c.to[n])?"255,255,0":"0,128,0",c.widths[n]=1;const u=a.DataFrame.create(c.from.length);return ae.forEach(((e,t)=>{u.columns.addNewString(e).init((e=>n.get(0===t?c.from[e]:c.to[e]))),function(e,t){Object.keys(t).forEach((n=>{e.tags[n]=t[n]}))}(u.col(e),i),u.col(e).semType=r})),u.columns.addNewFloat(se).init((e=>Math.abs(s.get(c.from[e])-s.get(c.to[e])))),u.columns.addNewInt(oe).init((e=>e)),u.columns.addNewFloat(re).init((e=>t.saliVals[e])),u.columns.addNewFloat(ie).init((e=>t.simVals[e])),u.name=`${te}${ee}`,{lines:c,linesDf:u}}(e,M,t,l,p,g,L,P);G.lines.skipMultiLineCalculation=!0,G.linesDf.col(re).setTag("description","Structure−Activity Landscape Index (activity difference divided by 1 minus similarity)");const B=new D(O,s[0],s[1],G.lines,F.none),U=w?w(G.linesDf,ae).sort([re],[!1]):G.linesDf.plot.grid().sort([re],[!1]);U.col(oe)&&(U.col(oe).visible=!1),e.temp[".cliffsDfGrid"]=U;const H=o.button(`${G.linesDf.rowCount} cliffs`,(()=>{R.dockManager.dock(U,"down",null,"Activity cliffs",C??.2)}));H.classList.add("scatter_plot_link","cliffs_grid"),O.root.append(H);const W=o.switchInput("Show only cliffs",!1,(()=>{W.value?(O.dataFrame.setTag(le,s[0]),e.filter.and(N),ne.next(s[0])):(O.dataFrame.setTag(le,""),e.filter.setAll(!0),ne.next(""))}));W.root.classList.add("scatter_plot_link","show_only_cliffs"),O.root.append(W.root),ne.subscribe((e=>{W.enabled=""===e||e===s[0]}));let Z=!1;O.onEvent("d4-before-draw-scene").subscribe((t=>{Z?Z=!1:W.value&&(setTimeout((()=>{e.filter.and(N)}),100),Z=!0)}));const K=i.events.onViewerClosed.subscribe((e=>{e.args.viewer===O&&(R.dockManager.close(U.root),K.unsubscribe(),R.subs=R.subs.filter((e=>e!==K)))}));return R.subs.push(K),G.linesDf.onCurrentCellChanged.subscribe((()=>{for(let e=0;e<G.linesDf.rowCount;e++)G.lines.widths[e]=e===G.linesDf.currentRowIdx?3:1;B.linesToRender=G.lines;const n=G.linesDf.currentCol&&G.linesDf.currentCol.name===ae[1]?G.lines.to:G.lines.from,r=-1!==G.linesDf.currentRowIdx?G.linesDf.currentRowIdx:null;if(O.dataFrame.currentRowIdx=r?n[r]:-1,null!==r){const n=G.linesDf.currentRowIdx;B.currentLineId=n;const{zoomLeft:a,zoomRight:c,zoomTop:u,zoomBottom:h}=function(e,t,n,s,r,i){const o=Math.abs(n-r),a=Math.abs(s-i),l=e/o,c=t/a,u=Math.min(l,c),h=e/u*5,d=t/u*5,m=(n<r?n:r)+o/2-h/2,p=(s>i?s:i)-a/2+d/2;return{zoomLeft:m,zoomRight:m+h,zoomTop:p,zoomBottom:p-d}}(O.viewport.width,O.viewport.height,O.dataFrame.get(s[0],G.lines.from[n]),O.dataFrame.get(s[1],G.lines.from[n]),O.dataFrame.get(s[0],G.lines.to[n]),O.dataFrame.get(s[1],G.lines.to[n]));O.zoom(a,u,c,h),W.value?e.filter.and(N):!0===W.enabled&&e.filter.setAll(!0),setTimeout((()=>{!function(e,t,n,s,r,a,l,c,u){const h=t.getPane("Cliff Details");o.empty(h.root);const d=u({points:[n,s],lineId:r,df:e,seqCol:a,activityCol:l,sali:c});h.root.append(d),setTimeout((()=>{i.shell.o=t.root}),500)}(e,A,G.lines.from[r],G.lines.to[r],r,t,l,G.linesDf.get(re,r),v);const n=O.dataFrame.getSortedOrder(R.grid.sortByColumns,R.grid.sortTypes);R.grid.scrollToCell(t.name,n.indexOf(O.dataFrame.currentRowIdx))}),1e3)}})),G.linesDf.onSelectionChanged.subscribe((t=>{setTimeout((()=>(()=>{const t=a.BitSet.create(e.rowCount);for(let e=0;e<G.linesDf.rowCount;e++){const n=G.linesDf.selection.get(e);n&&(t.set(G.lines.from[e],!0),t.set(G.lines.to[e],!0)),G.lines.colors[e]=n?"255,255,0":"0,128,0"}e.selection.copyFrom(t),B.linesToRender=G.lines})()),100)})),e.onSelectionChanged.subscribe((t=>{!1===e.selection.anyTrue&&"number"==typeof t&&(x?x=!1:(e=>{e.selection.setAll(!1);for(let e=0;e<G.lines.colors.length;e++)G.lines.colors[e]="0,128,0";B.linesToRender=G.lines})(U.dataFrame))})),B.lineClicked.subscribe((t=>{if(x=!0,B.currentLineId=t.id,-1!==t.id){const n=G.linesDf.selection.clone();setTimeout((()=>{t.event.ctrlKey?(n.set(t.id,!n.get(t.id)),G.linesDf.selection.copyFrom(n)):(G.linesDf.currentRowIdx!==t.id&&(G.linesDf.currentRowIdx=t.id,e.currentRowIdx=G.lines.from[t.id]),G.linesDf.selection.copyFrom(n));const s=G.linesDf.getSortedOrder(U.sortByColumns,U.sortTypes);U.scrollToCell(ae[0],s.indexOf(t.id))}),500)}})),B.lineHover.pipe((0,f.debounceTime)(500)).subscribe((n=>{-1!==n.id&&-1===e.mouseOverRowIdx&&o.tooltip.show(b({lineId:n.id,points:[G.lines.from[n.id],G.lines.to[n.id]],df:e,seqCol:t,activityCol:l}),n.x,n.y)})),O.addProperty("similarityLimit","double",S),A=function(){const e=o.accordion(),t=o.element("i");return t.className="grok-icon svg-icon svg-view-layout",e.addTitle(o.span([t,o.label("Activity cliffs")])),e.addPane("Cliff Details",(()=>o.divText("Cliff has not been selected")),!0),i.shell.o=e.root,e}(),O}var ue,he=n(8260),de=n(5226),me=n(7228),pe=n(8457);async function fe(e,t,n,s){const r=(0,pe.O)(t),i=he.g.forColumn(t).getNewColumnFromList("ref",[n]),o=he.g.forColumn(i).getSplitted(0),l=s===ue.IDENTITY?function(e,t){const n=t.columns.length,s=new Array(n),r=new Array(n),i=new Array(n);for(let o=0;o<n;++o){const n=t.columns.byIndex(o);s[o]=n.getRawData(),r[o]=n.categories.indexOf(""),i[o]=n.categories.indexOf(e.getOriginal(o)??"")}const o=a.Column.float("Identity",t.rowCount),l=o.getRawData();for(let n=0;n<t.rowCount;++n){l[n]=0;for(let t=0;t<e.length;++t)s[t][n]===i[t]&&++l[n];l[n]/=e.length}return o}(o,r):s===ue.SIMILARITY?await async function(e,t){const n=t.columns.toList();return await(0,me.Qx)(n,e)}(o,r):null;if(null===l)throw new Error(`In bio library: Unkown sequence scoring method: ${s}`);return l.name=e.columns.getUnusedName(l.name),e.columns.add(l),l}!function(e){e.IDENTITY="identity",e.SIMILARITY="similarity"}(ue||(ue={}));var ge=n(7945),ye=n(4293),be=n(6414),ve=n.n(be),we=n(2583);const Ce="rgb(100,100,100)",Se="#808080",Ae="rgb(0,0,0)",xe=we.GU;var Ee,Ie;function Te(e,t,n,s,r,i,o=Ce,a=0,l=!1,c=1,u="",h=!1,d=Ie.classic,m=[],p=0,f=null,g=null,y=null,b={}){r.textAlign="start";let v=i.substring(0),w=h?"":u;d===Ie.MSA&&(w="");let C=!0,S=!0,A="difference";if(null!=f&&null!=f.cell.column&&(C=f.cell.column.temp["color-code"]??!0,S=f.cell.column.temp["compare-with-current"]??!0,A=f.cell.column.temp["highlight-difference"]??"difference"),g){const e=g[p];S&&g.length>0&&"difference"===A&&(c=v==e?.3:c),S&&g.length>0&&"equal"===A&&(c=v!=e?.3:c)}null!=y&&(v=xe(v,y));const x=v+w;b[x]??(b[x]=r.measureText(x));let E=b[x];b[v]??(b[v]=r.measureText(v));let I=b[v].width;b[w]??(b[w]=r.measureText(w));const T=b[w].width,_=s/2-(E.fontBoundingBoxAscent+E.fontBoundingBoxDescent)/2+1;function M(n,s){const i=C?o:Ae;r.fillStyle=i,r.globalAlpha=c,d===Ie.classic&&(r.fillText(v,e+n,t+_),r.fillStyle=Se,r.fillText(w,e+s,t+_)),d===Ie.MSA&&r.fillText(v,e+n,t+_)}E=E.width,d===Ie.MSA&&(I=m[p],E=m[p]);const $=(m[p]??0)-(m[0]??0);if(l||E>n)return M($,$+I),e+$+I+T;{const t=(n-E)/2;return M(t,t+I),e+$+t+I}}!function(e){e.maxMonomerLength=".mm.cellRenderer.maxMonomerLength"}(Ee||(Ee={})),function(e){e.MSA="MSA",e.classic="classic"}(Ie||(Ie={}));var _e=n(9611),Me=n(8447),$e=n(7331);const Ne={DNA:"RNA",RNA:"RNA",PT:"PEPTIDE",UN:"PEPTIDE"};var Le;!function(e){e.long="long",e.short="short"}(Le||(Le={}));const Pe={true:"1",false:"0"};var Re=n(3553);const Oe="rgb(100,100,100)",ke=Me.GU;function Fe(e,t,n,s,r){return e?Math.max(Math.min(e.canvas.width/r-n,s)):Math.max(t.canvas.width/r-n,0)}function Ge(e){const t=!ve().enumerate(e).some((([t,n])=>t.length>1&&0!=n&&n!=e.length-1)),n=[],s=t?"":" ";for(const[t,r]of ve().enumerate(e)){let i=t;r<e.length&&(i+=`${t?"":"-"}${s}`),n.push(i)}return[n,t]}function De(e){let t=null,n=null;try{n=e.gridColumn}catch{n=null}if(t=n&&n.dart?n.temp:null,!t){let n=null;try{n=e.cell.column}catch{n=null}t=n?n.temp:null}if(null===t)throw new Error("Monomer placer store (GridColumn or Column) not found.");return t}class Be extends a.GridCellRenderer{constructor(){super(...arguments),this.padding=5}get name(){return"sequence"}get cellType(){return"sequence"}get defaultHeight(){return 30}get defaultWidth(){return 230}onClick(e,t){e.cell.column.temp["current-word"]=e.cell.value,e.grid.invalidate()}onMouseMove(e,t){const n=e.cell.column,s=De(e)[".mm.cellRenderer.monomerPlacer"];if(!s)return;const r=e.bounds,i=t.offsetX-e.gridColumn.left+(e.gridColumn.left-r.x),a=s.getPosition(e.tableRowIndex,i),l=he.g.forColumn(s.col).getSplitted(e.tableRowIndex).canonicals;if(null!==a&&a<l.length){const e=l[a],r=[o.div(e)];let i=s._monomerStructureMap[e];i=s._monomerStructureMap[e]=(()=>{const t=he.g.forColumn(n).alphabet??"UN",r=Ne[t];return s.props.monomerLib.getTooltip(r,e)})(),r.push(i),o.tooltip.show(o.divV(r),t.x+16,t.y+16)}else o.tooltip.hide()}render(e,t,n,s,r,i,o){let l,c=0,u=50;try{l=i.grid}catch(e){l=void 0;const[t,n]=(0,ge.yf)(e);ls.logger.error(t,void 0,n)}const h=i.cell.column;if(!l||!h)return;const d=h.temp,m=d["monomer-width"];if("short"===(null!=m?m:"short")){const e=parseInt(h.getTag(Ee.maxMonomerLength));u=(isNaN(e)?ls.properties?.MaxMonomerLength:e)??4}let p=De(i)[".mm.cellRenderer.monomerPlacer"];p||(p=new _e.A(l,h,(()=>{const e=he.g.forColumn(h);return{seqHandler:e,monomerCharWidth:7,separatorWidth:e.isMsa()?8:c,monomerToShort:ke,monomerLengthLimit:u,monomerLib:ps()}}))),h.tags[".mm.cellRenderer.settingsChanged"]===Pe.true&&(c=d[".mm.cellRenderer.gapLength"]??c,p.setMonomerLengthLimit(u),p.setSeparatorWidth(p.isMsa()?8:c),h.setTag(".mm.cellRenderer.settingsChanged",Pe.false));const[f,g]=p.getCellMonomerLengths(i.tableRowIndex);f.length,p.updated&&(De(i)[".mm.cellRenderer.monomerPlacer"]=p),e.save();try{const o=window.devicePixelRatio,l=-1!==i.gridRow?i.grid:null,c=(i.cell.value,i.cell.rowIndex),m=h.getTag("alphabet"),f=50;s=Fe(l,e,t,s,o),e.beginPath(),e.rect(t+this.padding,n+this.padding,s-this.padding-1,r-2*this.padding),e.clip(),e.font="12px monospace",e.textBaseline="top";const y=h.getTag(a.TAGS.UNITS),b=h.getTag("aligned"),v=(0,Me.py)(m),w=h.getTag("separator")??"",C=s/5,S=he.g.forColumn(h),A=d["reference-sequence"],x=d["current-word"];x&&-1===h?.dataFrame?.currentRowIdx&&(d["current-word"]=null);const E=(()=>{const e=S.getSplitter(C);return ve()(e(null!=A&&""!=A?A:x??"").originals).toArray()})(),I=S.getSplitted(c);let T=Oe,_=Ie.classic;b&&b.includes("MSA")&&y==Me.r2.SEPARATOR&&(_=Ie.MSA);for(let o=0;o<I.length;++o){const a=I.getOriginal(o);T=v.get(a),e.fillStyle=Oe;const l=o===I.length-1;if(Te(t+this.padding,n,s,r,e,a,T,0,!0,1,w,l,_,g,o,i,E,u,p._monomerLengthMap),f>s)break}}catch(e){const t=e instanceof Error?e.message:e?e.toString():"Error 'undefined'";ls.logger.error(`Bio: MacromoleculeSequenceCellRenderer.render() error: ${t}`)}finally{e.restore()}}}class Ve extends a.GridCellRenderer{get name(){return"MacromoleculeDifferenceCR"}get cellType(){return Re.Of.MACROMOLECULE_DIFFERENCE}get defaultHeight(){return 30}get defaultWidth(){return 230}render(e,t,n,s,r,i,o){const l=window.devicePixelRatio,c=i.grid,u=i.cell,h=i.tableColumn,d=u.value??"",m=h.tags.separator,p=h.tags[a.TAGS.UNITS];s=Fe(c,e,t,s,l);const[f,g]=d.split("#"),y=(0,we.vU)(p,m);Ue(e,t,n,s,r,ve()(y(f).canonicals).toArray(),ve()(y(g).canonicals).toArray(),p)}}function Ue(e,t,n,s,r,i,o,a,l,c){if(i.length!==o.length){const e=function(e,t){let n=0,s=0;const r=e.length>t.length?e:t,i=e.length>t.length?t:e;for(let e=0;e<i.length;e++)r[e]===i[e]&&n++;const o=r.length-i.length;for(let e=r.length-1;e>o;e--)r[e]===i[e-o]&&s++;const a=new Array(Math.abs(e.length-t.length)).fill(he.lh[Me.r2.FASTA]);function l(e){return n>s?e.concat(a):a.concat(e)}return e.length>t.length?t=l(ve()(t).toArray()):e=l(ve()(e).toArray()),{subParts1:e,subParts2:t}}(i,o);i=e.subParts1,o=e.subParts2}const u=e.measureText(Ge(i).join("")),h=e.measureText(Ge(o).join("")),d=Math.max(u.width,h.width);l&&(s=d+4*i.length,e.canvas.width=d+4*i.length);let m=Math.max(t,t+(s-(d+4*i.length))/2)+5;const p=Math.max(n,n+(r-28)/2);e.save(),e.beginPath(),e.rect(t,n,l?d+4*i.length:s,r),e.clip(),e.font="12px monospace",e.textBaseline="top";let f=$e.UE.Color;"HELM"!=a&&(f=(0,Me.py)(a.substring(a.length-2)));for(let t=0;t<i.length;t++){const n=i[t],a=o[t],l=f.get(n);if(n!=a){const i=f.get(a),o=Te(m,p-7,s,r,e,n,l,0,!0),u=Te(m,p+7,s,r,e,a,i,0,!0);m=Math.max(u,o),c&&(c[t]=He(n,a,l,i,p,7,r))}else m=Te(m,p,s,r,e,n,l,0,!0,.5);m+=4}e.restore()}function He(e,t,n,s,r,i,o){const a=document.createElement("canvas"),l=a.getContext("2d");l.font="12px monospace";const c=l.measureText(Ge([e]).join("")).width,u=l.measureText(Ge([t]).join("")).width,h=Math.max(c,u);return a.height=o,a.width=h+4,l.font="12px monospace",l.textBaseline="top",Te(0,r-i,h,o,l,e,n,0,!0),Te(0,r+i,h,o,l,t,s,0,!0),a}var je,We=n(8467),Ye=n(9298);!function(e){e.Unknown="unknown",e.FR="framework",e.CDR="cdr"}(je||(je={}));const Ze=new class{constructor(){this.regionTypes=[je.CDR],this.chains=["Heavy","Light"],this.skipEmptyPositions=!1,this.fitWidth=!1,this.positionWidth=16,this.positionHeight=Ye.ES.Entropy,this.filterSource=Ye.vS.filterSource}};var Ke=n(172),qe=n(8415);const ze=je;var Xe,Je;!function(e){e.STYLE="Style",e.BEHAVIOR="Behavior",e.LAYOUT="Layout",e.DATA="Data"}(Xe||(Xe={})),function(e){e.skipEmptyPositions="skipEmptyPositions",e.regionTypes="regionTypes",e.chains="chains",e.fitWidth="fitWidth",e.positionWidth="positionWidth",e.positionHeight="positionHeight",e.filterSource="filterSource"}(Je||(Je={}));const Qe=Ze;class et extends a.JsViewer{constructor(){super(),this.viewed=!1,this.regionsFg=null,this.regionsRoot=null,this.isOpened=!1,this.panelNode=null,this.regions=[],this.viewerId=++et.viewerCounter,this.setDataInProgress=!1,this.host=null,this.mainLayout=null,this.logos=[],this.viewSubs=[],this.calcSizeRequested=!1,this._onRendered=new y.Subject,this.skipEmptyPositions=this.bool(Je.skipEmptyPositions,Qe.skipEmptyPositions,{category:Xe.DATA}),this.regionTypes=this.stringList(Je.regionTypes,Qe.regionTypes,{category:Xe.DATA,choices:Object.values(ze).filter((e=>e!=ze.Unknown))}),this.chains=this.stringList(Je.chains,Qe.chains,{category:Xe.DATA,choices:["Heavy","Light"]}),this.fitWidth=this.bool(Je.fitWidth,Qe.fitWidth,{category:Xe.LAYOUT}),this.positionWidth=this.float(Je.positionWidth,Qe.positionWidth,{category:Xe.LAYOUT,editor:"slider",min:0,max:64,description:"Internal WebLogo viewers property width of position."}),this.positionHeight=this.string(Je.positionHeight,Qe.positionHeight,{category:Xe.LAYOUT,choices:Object.keys(Ye.ES)}),this.filterSource=this.string(Je.filterSource,Qe.filterSource,{category:Xe.BEHAVIOR,choices:Object.values(Ye.Ct)}),this.viewSyncer=new Ke.c(ls.logger)}viewerToLog(){return`VdRegionsViewer<${this.viewerId}>`}async init(){this.subs.push((0,y.fromEvent)(this.root,"mousemove").subscribe(this.rootOnMouseMove.bind(this)))}detach(){const e=`${this.viewerToLog()}.detach()`,t=super.detach.bind(this);this.viewSyncer.sync(`${e}`,(async()=>{this.setDataInProgress||(this.viewed&&(await this.destroyView("detach"),this.viewed=!1),t())}))}onTableAttached(){super.onTableAttached(),this.setData(this.regions)}onPropertyChanged(e){if(super.onPropertyChanged(e),e){switch(e.name){case Je.regionTypes:case Je.chains:this.setData(this.regions)}switch(e.name){case Je.skipEmptyPositions:for(let e=0;e<this.logos.length;++e)for(const t of this.chains)this.logos[e][t].setOptions({[qe.bo.skipEmptyPositions]:this.skipEmptyPositions});this.calcSize();break;case Je.fitWidth:case Je.positionWidth:this.calcSize();break;case Je.positionHeight:for(let e=0;e<this.logos.length;++e)for(const t of this.chains)this.logos[e][t].setOptions({[qe.bo.positionHeight]:this.positionHeight});this.calcSize();break;case Je.filterSource:this.filterSourceInput.value=this.filterSource;break;default:this.setData(this.regions)}}else console.warn("Bio: VdRegionsViewer.onPropertyChanged() property is null")}setData(e){const t=`${this.viewerToLog()}.setData()`;ls.logger.debug(`${t}, in, regions.length = ${e.length}`),this.viewSyncer.sync(`${t}`,(async()=>{if(!this.setDataInProgress){this.setDataInProgress=!0;try{this.viewed&&(await this.destroyView("setData"),this.viewed=!1),this.regions=e,this.viewed||(await this.buildView("setData"),this.viewed=!0)}finally{this.setDataInProgress=!1}}}))}async destroyView(e){ls.logger.debug(`Bio: VdRegionsViewer.destroyView( mainLayout = ${this.mainLayout?"value":"none"} ), purpose = '${e}', this.regions.length = ${this.regions.length}`),this.filterSourceInput&&o.empty(this.filterSourceInput.root),null!=this.mainLayout&&(this.mainLayout.remove(),this.host.remove(),this.host=null,this.mainLayout=null);for(const e of this.viewSubs)e.unsubscribe()}async buildView(e){ls.logger.debug(`Bio: VdRegionsViewer.buildView() begin, purpose = '${e}', this.regions.length = ${this.regions.length}`);const t=this.regions.filter((e=>this.regionTypes.includes(e.type))),n=Array.from(new Set(t.map((e=>e.order)))).sort(),s=[];for(let e=0;e<n.length;e++)for(const r of this.chains){const i=t.find((t=>t.order==n[e]&&t.chain==r));s.push((async()=>{const t=await this.dataFrame.plot.fromType("WebLogo",{sequenceColumnName:i.sequenceColumnName,startPositionName:i.positionStartName,endPositionName:i.positionEndName,fixWidth:!0,skipEmptyPositions:this.skipEmptyPositions,positionWidth:this.positionWidth,positionHeight:this.positionHeight,filterSource:this.filterSource});return t.onSizeChanged.subscribe((()=>{this.calcSize()})),[e,r,t]})())}const r=await Promise.all(s);this.logos=new Array(n.length);for(let e=0;e<n.length;++e)this.logos[e]={};for(const[e,t,n]of r)this.logos[e][t]=n,this.viewSubs.push(n.onFreqsCalculated.subscribe((()=>{this.calcSize()})));this.mainLayout=o.table(this.chains,(e=>[...n.length>0?[o.div(e,{style:{transform:"rotate(-90deg)",font:"12px Roboto, Roboto Local, sans-serif",textAlign:"center",width:"16px",marginTop:"24px",marginLeft:"6px"}})]:[],...[...Array(n.length).keys()].map((t=>{const n=this.logos[t][e];return n.root.style.height="100%",o.div([n.root],{style:{marginTop:"4px",marginBottom:"4px"}})}))]),["",...[...Array(n.length).keys()].map((e=>t.find((t=>t.order==n[e]&&t.chain==this.chains[0])).name||"Name"))]),this.mainLayout.className="mlb-vd-regions-viewer-table2",this.filterSourceInput=o.choiceInput("Data source",this.filterSource,Object.values(Ye.Ct),this.filterSourceInputOnValueChanged.bind(this)),this.filterSourceInput.root.style.position="absolute",this.filterSourceInput.root.style.right="9px",this.filterSourceInput.root.style.top="-4px",Math.ceil(255*Math.random()).toString(16),this.host=o.div([this.mainLayout,this.filterSourceInput.root],{}),this.root.appendChild(this.host),this.root.style.overflowX="auto",this.calcSize(),this.viewSubs.push(o.onSizeChanged(this.root).subscribe(this.rootOnSizeChanged.bind(this))),ls.logger.debug("Bio: VdRegionsViewer.buildView() end")}calcSize(){ls.logger.debug("Bio: VdRegionsViewer.calcSize(), start");const e=()=>{if(!this.host)return;const e=(this.root.clientHeight-54)/this.chains.length;let t=0;for(let n=0;n<this.logos.length;n++){for(const t of this.chains)this.logos[n][t].root.style.height=`${e}px`;t+=Math.max(...this.chains.map((e=>this.logos[n][e].Length)))}if(this.fitWidth){if(this.logos.length>0&&t>0){const e=22,n=13,s=9,r=(this.root.clientWidth-e-(this.logos.length-1)*s-n)/t;for(let e=0;e<this.logos.length;e++)for(const t of this.chains){const n=this.logos[e][t];n.setOptions({[qe.bo.positionWidth]:r-n.positionMarginValue}),n.root.style.width=r*n.Length+"px"}}this.host.style.setProperty("overflow","hidden","important")}else{for(let e=0;e<this.logos.length;e++)for(const t of this.chains)this.logos[e][t].setOptions({[qe.bo.positionWidth]:this.positionWidth});this.host.style.removeProperty("overflow")}0===this.positionWidth?this.host.style.setProperty("overflow-x","hidden","important"):this.host.style.removeProperty("overflow-x")};this.calcSizeRequested||(this.calcSizeRequested=!0,window.setTimeout((()=>{e(),this.calcSizeRequested=!1}),0))}rootOnSizeChanged(e){this.calcSize()}rootOnMouseMove(e){}filterSourceInputOnValueChanged(){const e=`${this.viewerToLog()}.filterSourceInputOnValueChanged()`,t=this.filterSourceInput.value;this.viewSyncer.sync(`${e}`,(async()=>{if(this.filterSource!==t){this.props.getProperty(Je.filterSource).set(this,t);for(let e=0;e<this.logos.length;e++)for(let t=0;t<this.chains.length;t++){const n=this.chains[t];this.logos[e][n].setOptions({[qe.bo.filterSource]:this.filterSource})}}}))}get onRendered(){return this._onRendered}invalidate(e){const t=`${this.viewerToLog()}.invalidate(${e?` <- ${e} `:""})`;this.viewSyncer.sync(`${t}`,(async()=>{this._onRendered.next()}))}async awaitRendered(e=5e3){await(0,We.zg)(this.onRendered,(()=>{}),(()=>{this.invalidate()}),e);const t=this.viewSyncer.resetErrors();if(t.length>0)throw t[0]}}et.viewerCounter=-1;var tt=n(9017),nt=n(708);async function st(e,t,n="Morgan"){const s=e.length,r=he.g.forColumn(e),i=Array(s);let o=1;const a=new Map,l=e.categories,c=e.getRawData();for(let t=0;t<s;t++){if(null===l[c[t]]||e.isNone(t)){i[t]=null;continue}i[t]="";const n=r.getSplitted(t);for(let e=0;e<n.length;e++){const s=n.getCanonical(e);a.has(s)||(a.set(s,String.fromCharCode(o)),o++),i[t]+=a.get(s)}}let u={};if(t===nt.U.MONOMER_CHEMICAL_DISTANCE||t===nt.U.NEEDLEMANN_WUNSCH){const e=Array.from(a.keys()),t=await(0,me.GR)(e,n),s={};Object.entries(t.alphabetIndexes).forEach((([e,t])=>{s[a.get(e)]=t})),u={scoringMatrix:t.scoringMatrix,alphabetIndexes:s}}return{seqList:i,options:u}}var rt=n(6361),it=n(7983);function ot(e){const t=o.divH([],{style:{gap:"10px"}}),n=o.divV([o.divText(e.seqCol.name),o.divText(e.activityCol.name)]);return n.style.fontWeight="bold",n.style.display="flex",n.style.justifyContent="space-between",t.append(n),e.points.forEach((n=>{const s=o.divText(e.activityCol.get(n).toFixed(2));s.style.display="flex",s.style.justifyContent="left",s.style.paddingLeft="30px",t.append(o.divV([o.divText(e.seqCol.get(n)),s]))})),t}function at(e){const t=o.div();t.append(o.divText(e.seqCol.name,{style:{fontWeight:"bold"}}));const n=new Array(2);e.points.forEach(((t,s)=>{n[s]=e.activityCol.get(t)}));const s={},r=he.g.forColumn(e.seqCol),i=ct(r.getSplitted(e.points[0]),r.getSplitted(e.points[1]),r.units,s);return t.append(o.div(i,{style:{width:"300px",overflow:"scroll"}})),t.append(ut(s)),t.append(lt("Activity delta",Math.abs(n[0]-n[1]))),t.append(lt("Cliff",e.sali)),t}function lt(e,t){return o.divH([o.divText(`${e}: `,{style:{fontWeight:"bold",paddingRight:"5px"}}),o.divText(t.toFixed(2))],{style:{paddingTop:"10px"}})}function ct(e,t,n,s){const r=document.createElement("canvas"),i=r.getContext("2d");return r.height=30,Ue(i,0,0,0,30,ve()(e.canonicals).toArray(),ve()(t.canonicals).toArray(),n,!0,s),r}function ut(e){const t=o.div();if(Object.keys(e).length>0){const n=o.divV([]);n.append(o.divH([o.divText("Pos",{style:{fontWeight:"bold",width:"30px",borderBottom:"1px solid"}}),o.divText("Difference",{style:{fontWeight:"bold",borderBottom:"1px solid"}})]));for(const t of Object.keys(e))e[t].style.borderBottom="1px solid lightgray",n.append(o.divH([o.divText((parseInt(t)+1).toString(),{style:{width:"30px",borderBottom:"1px solid lightgray"}}),e[t]]));t.append(n)}return t}function ht(e,t){const n=a.Column.string("seq_diff",e.rowCount).init((n=>`${e.get(t[0],n)}#${e.get(t[1],n)}`));n.semType="MacromoleculeDifference",n.setTag(a.TAGS.UNITS,e.col(t[0]).getTag(a.TAGS.UNITS)),n.setTag("separator",e.col(t[0]).getTag("separator")),e.columns.add(n);const s=e.plot.grid();return s.col(t[0]).visible=!1,s.col(t[1]).visible=!1,s}class dt extends a.JsViewer{constructor(e){super(),this.name="",this.metricsProperties=["distanceMetric","fingerprint"],this.fingerprintChoices=["Morgan","Pattern"],this.initialized=!1,this.tags=[a.TAGS.UNITS,"aligned","separator","alphabet"],this.preComputeDistanceMatrix=!1,this.renderPromise=Promise.resolve(),this.fingerprint=this.string("fingerprint",this.fingerprintChoices[0],{choices:this.fingerprintChoices}),this.limit=this.int("limit",10),this.distanceMetric=this.string("distanceMetric",g.kg[0],{choices:g.kg}),this.moleculeColumnName=this.string("moleculeColumnName"),this.name=e}init(){this.initialized=!0}detach(){this.subs.forEach((e=>e.unsubscribe()))}async onTableAttached(){if(this.init(),this.dataFrame){this.preComputeDistanceMatrix=this.dataFrame.rowCount<=22e3,this.subs.push(a.debounce(this.dataFrame.onRowsRemoved,50).subscribe((e=>this.render(!0))));const e="diversity"!==this.name;this.subs.push(a.debounce(this.dataFrame.onCurrentRowChanged,50).subscribe((t=>this.render(e)))),this.subs.push(a.debounce(this.dataFrame.selection.onChanged,50).subscribe((e=>this.render(!1)))),this.subs.push(a.debounce(o.onSizeChanged(this.root),50).subscribe((e=>this.render(!1)))),this.moleculeColumn=this.dataFrame.columns.bySemType(a.SEMTYPE.MACROMOLECULE),this.moleculeColumnName=this.moleculeColumn?.name,this.getProperty("limit").fromOptions({min:1,max:this.dataFrame.rowCount})}this.render()}onPropertyChanged(e){if(super.onPropertyChanged(e),this.initialized){if("moleculeColumnName"===e.name){const t=this.dataFrame.col(e.get(this));t.semType===a.SEMTYPE.MACROMOLECULE&&(this.moleculeColumn=t)}this.render()}}render(e=!0){this.renderPromise=this.renderPromise.then((async()=>{this.computeRequested=this.computeRequested||e,await this.renderInt(e)}))}async renderInt(e){}beforeRender(){return!(!this.initialized||this.dataFrame&&this.moleculeColumnName&&this.dataFrame.col(this.moleculeColumnName).semType!==a.SEMTYPE.MACROMOLECULE&&(i.shell.error(`${this.moleculeColumnName} is not Macromolecule type`),1))}}var mt=n(7241),pt=n(1821);const ft={gapPenalty:1,matchScore:1,gapSymbol:he.lh[pt.r2.FASTA],localAlignment:!1};class gt extends dt{constructor(){super("similarity"),this.sketchedMolecule="",this.curIdx=0,this.molCol=null,this.idxs=null,this.scores=null,this.gridSelect=!1,this.targetMoleculeIdx=0,this.computeCompleted=new y.Subject,this.distanceMatrixComputed=!1,this.kPrevNeighbors=0,this.cutoff=this.float("cutoff",.01,{min:0,max:1}),this.hotSearch=this.bool("hotSearch",!0),this.similarColumnLabel=this.string("similarColumnLabel",null)}init(){this.hotSearch=!0,this.initialized=!0}async renderInt(e){if(this.beforeRender()&&this.moleculeColumn&&(this.curIdx=-1==this.dataFrame.currentRowIdx?0:this.dataFrame.currentRowIdx,e&&!this.gridSelect)){this.targetMoleculeIdx=-1==this.dataFrame.currentRowIdx?0:this.dataFrame.currentRowIdx;const e=he.g.forColumn(this.moleculeColumn);await(e.isHelm()?this.computeByChem():this.computeByMM());const t=null!=this.similarColumnLabel?this.similarColumnLabel:`similar (${this.moleculeColumnName})`;this.molCol=a.Column.string(t,this.idxs.length).init((e=>this.moleculeColumn?.get(this.idxs?.get(e)))),this.molCol.semType=a.SEMTYPE.MACROMOLECULE,this.tags.forEach((e=>this.molCol.setTag(e,this.moleculeColumn.getTag(e))));const n=a.DataFrame.fromColumns([this.idxs,this.molCol,this.scores]);n.onCurrentRowChanged.subscribe((e=>{this.dataFrame.currentRowIdx=n.col("indexes").get(n.currentRowIdx),setTimeout((()=>{this.createPropertyPanel(n)}),1e3),this.gridSelect=!0}));const s=n.plot.grid();s.col("indexes").visible=!1;const r=this.idxs?.getRawData().findIndex((e=>e==this.targetMoleculeIdx));s.cell("score",r).cell.value=null,i.shell.v.grid.root.addEventListener("click",(e=>{this.gridSelect=!1})),(0,ye.Y)(this.root,s.root),this.computeCompleted.next(!0)}}async computeByChem(){const e=await(0,mt.D)(this.moleculeColumn),t=(a.DataFrame.fromColumns([e]),await i.functions.call("Chem:callChemSimilaritySearch",{df:this.dataFrame,col:e,molecule:e.get(this.targetMoleculeIdx),metricName:this.distanceMetric,limit:this.limit,minScore:this.cutoff,fingerprint:this.fingerprint}));this.idxs=t.getCol("indexes"),this.scores=t.getCol("score")}async computeByMM(){const e=this.moleculeColumn.length,t=Math.min(this.limit,e-1);if(!this.knn||this.kPrevNeighbors!==t){const n=(await st(this.moleculeColumn,nt.U.LEVENSHTEIN)).seqList;this.kPrevNeighbors=t,this.knn=await(new k).getKNN(n,nt.U.LEVENSHTEIN,Math.min(this.limit,e-1))}const n=new Array(t).fill(0).map(((e,t)=>({idx:this.knn.knnIndexes[this.targetMoleculeIdx][t],score:1-this.knn.knnDistances[this.targetMoleculeIdx][t]})));n.sort(((e,t)=>t.score-e.score)),n.unshift({idx:this.targetMoleculeIdx,score:a.FLOAT_NULL}),this.idxs=a.Column.int("indexes",t+1).init((e=>n[e].idx)),this.scores=a.Column.float("score",t+1).init((e=>n[e].score))}createPropertyPanel(e){const t=o.div(),n={},s=this.molCol?.name,r=e.col(s),a=he.g.forColumn(this.moleculeColumn),l=he.g.forColumn(r),c=a.getSplitted(this.targetMoleculeIdx),u=l.getSplitted(e.currentRowIdx),h=function(e,t,n={}){const s={...ft,...n},r=e.length,i=t.length,o=Array(r+1).fill(0).map((()=>Array(i+1).fill(0)));let a=-9999,l=[1,1];for(let n=1;n<r+1;n++)for(let r=1;r<i+1;r++)o[n][r]=Math.max(0,o[n-1][r-1]+(e.getCanonical(n-1)===t.getCanonical(r-1)?s.matchScore:-s.matchScore),o[n-1][r]-s.gapPenalty,o[n][r-1]-s.gapPenalty),o[n][r]>=a&&(a=o[n][r],l=[n,r]);let c=s.localAlignment?l[0]:r,u=s.localAlignment?l[1]:i,h=new Array(0),d=new Array(0);for(;c>0&&u>0;){const n=Math.max(o[c-1][u-1],o[c-1][u],o[c][u-1]);o[c][u]==o[c-1][u-1]+s.matchScore&&n==o[c-1][u-1]?(h.push(e.getCanonical(c-1)),d.push(t.getCanonical(u-1)),c-=1,u-=1):o[c][u]==o[c-1][u]-s.gapPenalty?(d.push(s.gapSymbol),h.push(e.getCanonical(c-1)),c-=1):o[c][u]==o[c][u-1]-s.gapPenalty?(h.push(s.gapSymbol),d.push(t.getCanonical(u-1)),u-=1):(h.push(e.getCanonical(c-1)),d.push(t.getCanonical(u-1)),c-=1,u-=1)}h=[...Array.from(e.canonicals).splice(0,c),...h.reverse(),...s.localAlignment?Array.from(e.canonicals).splice(l[0],r):[]],d=[...Array.from(t.canonicals).splice(0,u),...d.reverse(),...s.localAlignment?Array.from(t.canonicals).splice(l[1],i):[]];const m=c,p=u;return m>p?d=[...new Array(m-p).fill(s.gapSymbol.valueOf()),...d]:h=[...new Array(p-m).fill(s.gapSymbol.valueOf()),...h],d.length>h.length?h.push(...new Array(d.length-h.length).fill(s.gapSymbol.valueOf())):d.push(...new Array(h.length-d.length).fill(s.gapSymbol.valueOf())),{seq1:h.join(""),seq2:d.join(""),seq1Splitted:new we.wx(h,s.gapSymbol),seq2Splitted:new we.wx(d,s.gapSymbol)}}(c,u),d=ct(h.seq1Splitted,h.seq2Splitted,l.units,n);t.append(o.div(d,{style:{width:"300px",overflow:"scroll"}})),c.length!==u.length&&t.append(o.divV([o.divText("Different sequence length:",{style:{fontWeight:"bold"}}),o.divText(`target: ${c.length} monomers`),o.divText(`selected: ${u.length} monomers`)],{style:{paddingBottom:"10px"}})),t.append(ut(n));const m=o.accordion(),p=o.element("i");p.className="grok-icon svg-icon svg-view-layout",m.addTitle(o.span([p,o.label("Similarity search")])),m.addPane("Differences",(()=>t),!0),i.shell.o=m.root}}var yt=n(279);class bt extends dt{constructor(){super("diversity"),this.renderMolIds=null,this.columnNames=[],this.computeCompleted=new y.Subject,this.diverseColumnLabel=this.string("diverseColumnLabel",null)}async renderInt(e){if(this.beforeRender()&&this.dataFrame&&e&&this.moleculeColumn){const e=he.g.forColumn(this.moleculeColumn);await(e.isFasta()?this.computeByMM():this.computeByChem());const t=null!=this.diverseColumnLabel?this.diverseColumnLabel:`diverse (${this.moleculeColumnName})`,n=a.Column.string(t,this.renderMolIds.length).init((e=>this.moleculeColumn?.get(this.renderMolIds[e])));n.semType=a.SEMTYPE.MACROMOLECULE,this.tags.forEach((e=>n.setTag(e,this.moleculeColumn.getTag(e))));const s=a.DataFrame.fromColumns([n]);s.onCurrentRowChanged.subscribe((e=>{this.dataFrame.currentRowIdx=this.renderMolIds[s.currentRowIdx]})),(0,ye.Y)(this.root,s.plot.grid().root),this.computeCompleted.next(!0)}}async computeByChem(){const e=await(0,mt.D)(this.moleculeColumn);a.DataFrame.fromColumns([e]),this.renderMolIds=await i.functions.call("Chem:callChemDiversitySearch",{col:e,metricName:this.distanceMetric,limit:this.limit,fingerprint:this.fingerprint})}async computeByMM(){const e=(await st(this.moleculeColumn,nt.U.LEVENSHTEIN)).seqList,t=new O(!0,!1),n=await t.calc(e,nt.U.LEVENSHTEIN);t.terminate();const s=this.moleculeColumn.length,r=(0,R.y)(s);this.renderMolIds=(0,yt.L)(s,Math.min(s,this.limit),((e,t)=>this.moleculeColumn.isNone(e)||this.moleculeColumn.isNone(t)?0:n[r(e,t)]))}}var vt=n(4004),wt=n(9943),Ct=n(5393),St=n(7572),At=n(3336),xt=n.n(At),Et=n(8710),It={};It.styleTagTransform=M(),It.setAttributes=E(),It.insert=A().bind(null,"head"),It.domAPI=C(),It.insertStyleElement=T(),v()(Et.Z,It),Et.Z&&Et.Z.locals&&Et.Z.locals;var Tt=n(6584),_t=n(3776),Mt=n(2428);async function $t(){await Pt.showDialog()}class Nt{constructor(e){this.eventManager=e}static async getContent(e){return Nt._instance||(Nt._instance=new Nt(e)),Nt._instance.widget||(Nt._instance.widget=await Nt._instance.createWidget()),Nt._instance.widget}async createWidget(){this.monomerLibFileManager=await _t.t.getInstance(this.eventManager);const e=await this.getWidgetContent();return this.eventManager.addLibraryFileRequested$.subscribe((async()=>await this.promptToAddLibraryFiles())),new a.Widget(e)}async getWidgetContent(){this.monomerLibFileManager=await _t.t.getInstance(this.eventManager);const e=await Lt.createControlsForm(this.eventManager);return xt()(e).addClass("monomer-lib-controls-form"),o.divV([e])}async promptToAddLibraryFiles(){a.Utils.openFile({accept:".json",open:async e=>{const t=await e.text(),n=e.name,s=a.TaskBarProgressIndicator.create(`Adding ${n} as a monomer library`);try{await this.monomerLibFileManager.addLibraryFile(t,n)}catch(e){i.shell.error(`File ${n} is not a valid monomer library, verify it is aligned to HELM JSON schema.`)}finally{s.close()}}})}}class Lt{constructor(e){this.eventManager=e,this.eventManager.updateUIControlsRequested$.subscribe((async()=>await this.updateControlsForm())),this.eventManager.librarySelectionRequested$.subscribe((async([e,t])=>await this.updateLibrarySelectionStatus(t,e)))}static async createControlsForm(e){const t=new Lt(e);return await t.initialize(),await t._createControlsForm()}async _createControlsForm(){this.monomerLibFileManager=await _t.t.getInstance(this.eventManager);const e=await this.createLibraryControls(),t=o.form(e);return xt()(t).addClass("monomer-lib-controls-form"),t}async initialize(){this.userLibSettings=await(0,Tt.nW)()}async updateControlsForm(){const e=await this._createControlsForm();xt()(".monomer-lib-controls-form").replaceWith(e)}async createLibraryControls(){return(await _t.t.getInstance(this.eventManager)).getValidLibraryPaths().map((e=>this.createLibInput(e)))}createLibInput(e){const t=!this.userLibSettings.exclude.includes(e),n=o.boolInput(e,t,(t=>this.eventManager.updateLibrarySelectionStatus(e,t)));o.tooltip.bind(n.root,`Include monomers from ${e}`);const s=o.iconFA("trash-alt",(()=>this.promptForLibraryDeletion(e)));return o.tooltip.bind(s,`Delete ${e}`),n.addOptions(s),n}async updateLibrarySelectionStatus(e,t){this.updateLibrarySettings(e,t),await(0,Tt.tW)(this.userLibSettings),await St.A.instance.loadLibraries(!0),i.shell.info("Monomer library user settings saved")}updateLibrarySettings(e,t){e?this.userLibSettings.exclude=this.userLibSettings.exclude.filter((e=>e!==t)):this.userLibSettings.exclude.includes(t)||this.userLibSettings.exclude.push(t)}promptForLibraryDeletion(e){o.dialog("Warning").add(o.divText(`Delete file ${e}?`)).onOK((async()=>{try{const t=a.TaskBarProgressIndicator.create(`Deleting ${e} library`);this.updateLibrarySelectionStatus(!1,e),await this.monomerLibFileManager.deleteLibraryFile(e),t.close()}catch(t){console.error(t),i.shell.error(`Failed to delete ${e} library`)}})).showModal(!1)}}class Pt{constructor(){this.closeDialogSubject$=new y.Subject}static async showDialog(){Pt._instance||(Pt._instance=new Pt,Pt._instance.closeDialogSubject$.subscribe((()=>{Pt._instance.dialog=void 0}))),Pt._instance.dialog||(Pt._instance.dialog=await Pt._instance.getDialog()),Pt._instance.dialog.show()}async getDialog(){const e=Mt.A.getInstance(),t=await Nt.getContent(e),n=o.dialog({title:"Manage monomer libraries",helpUrl:"/help/datagrok/solutions/domains/bio/bio.md#manage-monomer-libraries"});return xt()(n.root).css("width","350px"),n.clear(),n.addButton("Add",(()=>e.addLibraryFile()),void 0,"Upload new HELM monomer library"),n.add(t),n.onClose.subscribe((()=>this.closeDialogSubject$.next())),n}}var Rt,Ot=function(e,t,n,s){return new(n||(n=Promise))((function(r,i){function o(e){try{l(s.next(e))}catch(e){i(e)}}function a(e){try{l(s.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class kt{constructor(e,t,n=!1,s){var r;this.name="",this.description="",this._isAutomatic=!1,this._autoStartFirstStep=!1,this._currentStep=0,this._isStopped=!1,this._isCancelled=!1,this._isStepProcessed=!1,this._root=o.div([],{id:"demo-script",classes:"tutorials-root tutorials-track demo-app-script"}),this._steps=[],this._mainHeader=o.panel([],"tutorials-main-header"),this._header=o.h2(""),this._headerDiv=o.divH([],"tutorials-root-header"),this._stopStartBtn=o.button(o.iconFA("pause"),(()=>this._changeStopState()),"Play / pause"),this._restartBtn=o.button(o.iconFA("redo"),(()=>this._restartScript()),"Restart"),this._nextStepBtn=o.button(o.iconFA("play"),(()=>{this._isStepProcessed||this._nextStep()}),"Next step"),this._activity=o.panel([],"tutorials-root-description"),this._progressDiv=o.divV([],"tutorials-root-progress"),this._progress=o.element("progress"),this._progressSteps=o.divText(""),this._closeBtn=o.button(o.iconFA("chevron-left"),(()=>this._closeDock()),"Back to demo"),this.name=e,this.description=t,this._isAutomatic=n,this._autoStartFirstStep=null!==(r=null==s?void 0:s.autoStartFirstStep)&&void 0!==r&&r,this._progress.max=0,this._progress.value=1,kt.currentObject=this}get steps(){return this._steps}get stepNumber(){return this._steps.length}_addHeader(){this._createHeaderDiv(),this._createProgressDiv(),this._mainHeader.append(this._headerDiv,this._progressDiv)}_createHeaderDiv(){this._header.innerText=this.name,this._headerDiv.append(this._closeBtn),this._headerDiv.append(this._header),this._nextStepBtn.firstChild.className="grok-icon fas fa-play",this._headerDiv.append(this._isAutomatic?this._stopStartBtn:this._nextStepBtn)}_createProgressDiv(){this._progress.max=this.stepNumber,this._progressDiv.append(this._progress),this._progressSteps=o.divText(`Step: ${this._progress.value} of ${this.stepNumber}`),this._progressDiv.append(this._progressSteps)}_addDescription(){var e;this._activity.append(o.div(this.description,"tutorials-root-description"));for(let t=0;t<this.stepNumber;t++){let n=o.iconFA("clock");this._isAutomatic||0===t&&(n=o.iconFA("play",(()=>this._nextStep()),"Next step"),n.className="grok-icon fas fa-play");const s=o.div(this._steps[t].name,"grok-tutorial-entry-instruction"),r=o.div(null===(e=this._steps[t].options)||void 0===e?void 0:e.description,"grok-tutorial-step-description hidden"),i=o.divH([n,s],"grok-tutorial-entry");this._activity.append(i,r)}}_initRoot(){var e,t,n;i.shell.windows.showContextPanel=!0,i.shell.windows.showHelp=!1;const s=Array.from(i.shell.dockManager.rootNode.children)[0];this._node=i.shell.dockManager.dock(this._root,a.DOCK_TYPE.FILL,s,""),(null===(t=null===(e=s.parent.container.containerElement.firstElementChild)||void 0===e?void 0:e.lastElementChild)||void 0===t?void 0:t.classList.contains("tab-handle-list-container"))&&(null===(n=s.parent.container.containerElement.firstElementChild)||void 0===n||n.lastElementChild.remove()),this._node.container.containerElement.classList.add("tutorials-demo-script-container"),this._addHeader(),this._root.append(this._mainHeader),this._addDescription(),this._root.append(this._activity)}_nextStep(){var e,t;return Ot(this,void 0,void 0,(function*(){this._isStepProcessed=!0,this._isAutomatic||(this._nextStepBtn.classList.add("disabled"),this._nextStepBtn.firstChild.classList.add("fa-disabled"));const n=this._activity.getElementsByClassName("grok-tutorial-entry")[this._currentStep],s=this._activity.getElementsByClassName("grok-icon")[this._currentStep],r=this._activity.getElementsByClassName("grok-tutorial-step-description")[this._currentStep];s.className="grok-icon far fa-spinner-third fa-spin",r.classList.remove("hidden"),r.classList.add("visible");const i=n,a=(null===(e=this._steps[this._currentStep].options)||void 0===e?void 0:e.delay)?null===(t=this._steps[this._currentStep].options)||void 0===t?void 0:t.delay:2e3;yield this._steps[this._currentStep].func(),this._scrollTo(this._root,i.offsetTop-this._mainHeader.offsetHeight),this._isAutomatic&&(yield this._countdown(n,s,a),yield(0,We.gw)(a));const l=o.iconFA("check");if(s.replaceWith(l),l.className="grok-icon far fa-check",this._progress.value++,this._progressSteps.innerText=`Step: ${this._progress.value} of ${this.stepNumber}`,this._currentStep++,this._isStepProcessed=!1,this._currentStep!==this.stepNumber){if(!this._isAutomatic){const e=this._activity.getElementsByClassName("grok-icon")[this._currentStep],t=o.iconFA("play",(()=>this._nextStep()),"Next step");t.className="grok-icon fas fa-play",e.replaceWith(t),this._nextStepBtn.classList.remove("disabled"),this._nextStepBtn.firstChild.classList.remove("fa-disabled")}}else this._isAutomatic?this._stopStartBtn.replaceWith(this._restartBtn):this._nextStepBtn.replaceWith(this._restartBtn)}))}_startScript(){return Ot(this,void 0,void 0,(function*(){for(let e=this._currentStep;e<this.stepNumber&&!this._isStopped&&!this._isCancelled;e++)yield this._nextStep()}))}_scrollTo(e,t){e.focus(),e.scrollTop=t}_countdown(e,t,n){return Ot(this,void 0,void 0,(function*(){const s=o.div([],"demo-script-countdown");t.classList.add("hidden");let r=n/1e3;const i=this._createSVGIndicator(r);s.append(i),e.prepend(s);const a=setInterval((()=>{r--,0===r&&(clearInterval(a),s.remove(),t.classList.remove("hidden"),t.classList.add("visible"))}),1e3)}))}_createSVGIndicator(e){const t=document.createElementNS("http://www.w3.org/2000/svg","svg"),n=document.createElementNS("http://www.w3.org/2000/svg","circle");return n.setAttributeNS(null,"cx","7"),n.setAttributeNS(null,"cy","7"),n.setAttributeNS(null,"r","6"),n.setAttributeNS(null,"style",`animation: countdown ${e}s linear infinite forwards`),t.append(n),t}_changeStopState(){const e=this._stopStartBtn.getElementsByClassName("grok-icon");e[0].className="grok-icon fas fa-play",this._isStopped=!this._isStopped,this._isStopped||(e[0].className="grok-icon fal fa-pause",this._isStepProcessed||this._startScript())}_restartScript(){i.shell.dockManager.close(this._node),i.shell.closeAll(),this._clearRoot(),this._setInitParams(),this.start()}_clearRoot(){this._root=o.div([],{id:"demo-script",classes:"tutorials-root tutorials-track demo-app-script"}),this._mainHeader=o.panel([],"tutorials-main-header"),this._header=o.h2(""),this._headerDiv=o.divH([],"tutorials-root-header"),this._activity=o.panel([],"tutorials-root-description"),this._progressDiv=o.divV([],"tutorials-root-progress"),this._progress=o.element("progress"),this._progressSteps=o.divText(""),this._progress.max=0,this._progress.value=1}_setInitParams(){this._currentStep=0,this._isStopped=!1,this._isCancelled=!1,this._stopStartBtn.getElementsByClassName("grok-icon")[0].className="grok-icon fal fa-pause",this._nextStepBtn.classList.remove("disabled")}_closeDock(){i.shell.dockManager.close(this._node),this.cancelScript()}cancelScript(){this._isCancelled=!0,kt.currentObject=null}step(e,t,n){return this._steps[this.steps.length]={name:e,func:t,options:n},this}start(){return Ot(this,void 0,void 0,(function*(){this._initRoot(),i.shell.newView(this.name),this._isAutomatic?this._startScript():this._autoStartFirstStep&&(yield this._nextStep())}))}}function Ft(e){const t=e instanceof Error?e.message:e.toString(),n=e instanceof Error?e.stack:void 0;i.shell.error(t),ls.logger.error(e.message,void 0,n)}kt.currentObject=null,function(e){e.X="Embed_X",e.Y="Embed_Y"}(Rt||(Rt={}));const Gt="samples/FASTA_PT_activity.csv";async function Dt(){const e="Dendrogram",t=a.Func.find({package:e,name:"getTreeHelper"});if(0===t.length)throw new Error(`Package "${e}" must be installed for TreeHelper.`);return(await t[0].prepare().call()).getOutputParamValue()}async function Bt(){return await i.functions.call("Dendrogram:getDendrogramService",{})}var Vt=function(e,t,n,s){return new(n||(n=Promise))((function(r,i){function o(e){try{l(s.next(e))}catch(e){i(e)}}function a(e){try{l(s.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};function Ut(e,t,s){return Vt(this,void 0,void 0,(function*(){return new Promise((function(r,i){const o=new Worker(new URL(n.p+n.u(356),n.b));o.postMessage({distMatArray:e,n:t,methodCode:s}),o.onmessage=({data:{error:e,clusterMatrix:t}})=>{o.terminate(),e?i(e):r(t)}}))}))}var Ht,jt,Wt,Yt=function(e,t,n,s){return new(n||(n=Promise))((function(r,i){function o(e){try{l(s.next(e))}catch(e){i(e)}}function a(e){try{l(s.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};n(7905),function(e){e.ADD="ADD",e.SUB="SUB",e.MULT="MULT"}(Ht||(Ht={})),function(e){e.SQUARE="SQUARE",e.INVERSE="INVERSE",e.TRANSPOSE="TRANSPOSE",e.NORM="NORM",e.COLUMN_NORM="COLUMN_NORM"}(jt||(jt={})),function(e){e.SCALARMULT="SCALARMULT",e.SCALARADD="SCALARADD",e.SCALARPOW="SCALARPOW"}(Wt||(Wt={})),Object.prototype.toString;const Zt="samples/FASTA_PT_activity.csv",Kt="sequence";const qt="samples/FASTA_PT_activity.csv";var zt=n(8341);const Xt="samples/HELM.csv";var Jt=n(2568),Qt=n(525);class en{constructor(e,t,n={}){this.urlParams=e,this.funcName=t,this.options=n}async init(e){this.df=e,await this.buildView()}async buildView(){const e=ve()(this.urlParams.entries()).map((([e,t])=>`${e}=${encodeURIComponent(t)}`)).toArray().join("&");this.view=i.shell.addTableView(this.df),this.view.path=this.view.basePath=`func/${ls.name}.${this.funcName}?${e}`;const t={...this.options,sequenceColumnName:"sequence"};for(const[e,n]of this.urlParams.entries())switch(e){case qe.bo.fixWidth:case qe.bo.fitArea:t[e]=["1","on","true"].includes(n.toLowerCase());break;default:t[e]=n}const n=await this.view.dataFrame.plot.fromType("WebLogo",t);this.view.dockManager.dock(n,a.DOCK_TYPE.DOWN,null,"WebLogo",.35)}}class tn{get funcParams(){return{table:this.tableInput.value,sequence:this.seqColInput.value}}get paramsUI(){return this.funcParamsDiv}constructor(){this.tableInput=o.tableInput("Table",i.shell.tv.dataFrame,void 0,(()=>{this.onTableInputChanged()}));const e=this.tableInput.value.columns.bySemType(a.SEMTYPE.MACROMOLECULE),t={filter:e=>e.semType===a.SEMTYPE.MACROMOLECULE};this.seqColInput=o.columnInput("Sequence",this.tableInput.value,e,null,t),this.funcParamsDiv=o.inputs([this.tableInput,this.seqColInput],{style:{minWidth:"320px"}})}onTableInputChanged(){this.seqColInput=o.columnInput("Sequence",this.tableInput.value,this.tableInput.value.columns.bySemType(a.SEMTYPE.MACROMOLECULE))}}var nn=n(9416);class sn{constructor(e){this.monomerLib=e}getCappedRotatedMonomer(e,t){const n=this.monomerLib.getMonomer(e,t);return n?n.molfile:null}}const rn=new class{constructor(){this.tooltipHandlerTemp="tooltip-handler.Monomer"}},on={autoCrop:!0,autoCropMargin:0,suppressChiralText:!0};class an{constructor(e){this.gridCol=e,this.gridCol.grid.onCellTooltip(this.onCellTooltip.bind(this))}onCellTooltip(e,t,n){if(e.grid.dart!=this.gridCol.grid.dart||e.gridColumn.dart!=this.gridCol.dart||!e.tableColumn||!e.isTableCell)return!1;const s=e.tableColumn.getTag("alphabet"),r=e.cell.value,a="DNA"===s||"RNA"===s?"RNA":"PEPTIDE",l=new sn(cs().getBioLib()).getCappedRotatedMonomer(a,r),c=o.div(r),u=l?i.chem.svgMol(l,void 0,void 0,on):null,h=e.grid.canvas.getBoundingClientRect(),d=e.bounds.right+h.left-4,m=e.bounds.bottom+h.top-4;return o.tooltip.show(o.divV([c,...u?[u]:[]]),d,m),!0}static getOrCreate(e){let t=e.temp[rn.tooltipHandlerTemp];return t||(t=e.temp[rn.tooltipHandlerTemp]=new an(e)),t}}class ln extends a.GridCellRenderer{get name(){return Re.Of.MONOMER}get cellType(){return Re.Of.MONOMER}get defaultHeight(){return 15}get defaultWidth(){return 40}render(e,t,n,s,r,i,o){if(i.gridRow<0)return;an.getOrCreate(i.gridColumn),e.font="12px monospace",e.textBaseline="middle",e.textAlign="center";const a=(0,Me.py)(i.cell.column.getTag("alphabet")),l=i.cell.value;if(!l)return;const c=a.get(l);e.fillStyle=c,e.fillText((0,Me.GU)(l,6),t+s/2,n+r/2,s)}}class cn extends Map{get onPropertyChanged(){return this._onPropertyChanged}get MaxMonomerLength(){return super.get("MaxMonomerLength")}set MaxMonomerLength(e){super.set("MaxMonomerLength",e),this._onPropertyChanged.next("MaxMonomerLength")}get TooltipWebLogo(){return super.get("TooltipWebLogo")}set TooltipWebLogo(e){super.set("TooltipWebLogo",e),this._onPropertyChanged.next("TooltipWebLogo")}get DefaultSeparator(){return super.get("DefaultSeparator")}set DefaultSeparator(e){if(1!==e.length)throw new Error("The separator must be of length one.");super.set("DefaultSeparator",e),this._onPropertyChanged.next("DefaultSeparator")}constructor(e){super(Object.entries(e)),this._onPropertyChanged=new y.Subject}}class un extends a.Package{constructor(){super(...arguments),this._initialized=!1}get properties(){return this._properties}set properties(e){this._properties=e}get initialized(){return this._initialized}completeInit(){this._initialized=!0}handleErrorUI(e){const[t,n]=(0,ge.yf)(e);i.shell.error(t),this.logger.error(t,void 0,n)}}var hn=n(8770);class dn extends a.Widget{constructor(e){super(o.divV([])),this.viewed=!1,this.wlViewer=null,this.seqCol=e}async init(){const e=he.g.forColumn(this.seqCol),t=ls.properties.TooltipWebLogo,n=this.seqCol.getTag(Ye.DX.tooltipWebLogo);!1===t||["false","off","disable","disabled"].includes(n)||(this.wlViewer=await this.seqCol.dataFrame.plot.fromType("WebLogo",{sequenceColumnName:this.seqCol.name,backgroundColor:0,positionHeight:"Entropy",positionWidth:e.getAlphabetIsMultichar()?24:16,fixWidth:!0,fitArea:!1}),this.wlViewer.root.style.height="50px",this.root.appendChild(this.wlViewer.root),this.root.style.width="100%")}detach(){this.wlViewer&&(this.wlViewer.detach(),this.wlViewer=null),super.detach()}}const mn=OCL;class pn{constructor(e){const t=e.split("|");t.forEach((e=>this.validateConnectionItem(e))),this.connectionItems=t}validateConnectionItem(e){const t="(PEPTIDE|RNA)",n=new RegExp(`${t}[0-9]+,${t}[0-9]+,[0-9]+:R[0-9]+-[0-9]+:R[0-9]+`,"g");if(!e.match(n))throw new Error(`Cannot parse connection item from ${e}`)}getConnectionData(){const e=[];return this.connectionItems.forEach((t=>{const n=[],s=t.split(",");s[2].split("-").forEach(((e,t)=>{const r=s[t],i=e.split(":"),o={monomerIdx:parseInt(i[0])-1,rGroupId:parseInt(i[1].slice(1))};n.push({polymerId:r,bond:o})})),e.push(n)})),e}}class fn{constructor(e){this.simplePolymer=e,this.polymerType=this.getPolymerType(),this.idx=this.getIdx();const{monomers:t,monomerTypes:n}=this.getMonomerSymbolsAndTypes();this.monomers=t,this.monomerTypes=n}get id(){return this.polymerType+this.idx.toString()}getPolymerType(){const e=new RegExp("(PEPTIDE|RNA)[0-9]+{"),t=this.simplePolymer.match(e);if(!t)throw new Error(`Unsupported polymer type in ${this.simplePolymer}`);return t[1]}getIdx(){const e=new RegExp(`${this.polymerType}([0-9]+){`),t=this.simplePolymer.match(e);if(!t)throw new Error(`Cannot parse simple polymer id from ${this.simplePolymer}`);return parseInt(t[1])}getMonomerSymbolsAndTypes(){const e=new RegExp(`${this.polymerType}${this.idx}{|}`,"g"),t=this.simplePolymer.replace(e,"").split("."),n=[],s=[];return t.forEach((e=>{const t=e.split(/\(|\)/).map((e=>e.replace(/[\[\]]/g,"")));n.push(...t);const r=t.map(((e,t)=>t%2==0?"Backbone":"Branch"));s.push(...r)})),{monomers:n,monomerTypes:s}}getBondData(){const e=[],t=this.monomerTypes.map(((e,t)=>{if("Backbone"===e)return t})).filter((e=>void 0!==e)),n=this.monomerTypes.map(((e,t)=>{if("Branch"===e)return t})).filter((e=>void 0!==e));for(let n=0;n<t.length-1;n++){const s=t[n],r=t[n+1];e.push([{monomerIdx:s,rGroupId:2},{monomerIdx:r,rGroupId:1}])}for(let t=0;t<n.length;t++){const s=n[t],r=s-1;e.push([{monomerIdx:r,rGroupId:3},{monomerIdx:s,rGroupId:1}])}return e}}class gn{constructor(e){this.helmString=e;const t=this.helmString.split("$"),n=t[0].split("|");this.simplePolymers=n.map((e=>new fn(e))),""!==t[1]&&(this.connectionList=new pn(t[1])),this.bondData=this.getBondData(),this.bondedRGroupsMap=this.getBondedRGroupsMap()}getBondedRGroupsMap(){const e=new Map;return this.bondData.forEach((t=>{t.forEach((t=>{const n=t.monomerIdx,s=t.rGroupId;e.get(n)||e.set(n,[]),e.get(n).push(s)}))})),e}toString(){return this.helmString}getPolymerTypeByMonomerIdx(e){return this.getSimplePolymerByMonomerIdx(e).polymerType}getSimplePolymerByMonomerIdx(e){const t=this.getMonomerIdxShifts(),n=Object.values(t).sort(((e,t)=>e-t)).find((t=>e>=t));if(void 0===n)throw new Error(`Cannot find simple polymer for monomer ${e}`);const s=Object.keys(t).find((e=>t[e]===n));return this.simplePolymers.find((e=>e.id===s))}shiftBondMonomerIds(e,t){t.forEach((t=>{t.forEach((t=>{t.monomerIdx+=e}))}))}getMonomerIdxShifts(){const e={};let t=0;return this.simplePolymers.forEach((n=>{e[n.id]=t,t+=n.monomers.length})),e}getBondData(){const e=this.getMonomerIdxShifts(),t=[];return this.simplePolymers.forEach((n=>{const s=n.getBondData(),r=e[n.id];this.shiftBondMonomerIds(r,s),t.push(...s)})),this.connectionList&&this.connectionList.getConnectionData().forEach((n=>{const s=[];n.forEach((t=>{const n=e[t.polymerId],r=t.bond;r.monomerIdx+=n,s.push(r)})),t.push(s)})),t}}var yn=n(4067);class bn{constructor(e){this.monomerSymbol=e}shiftR1GroupToOrigin(){const e=this.rGroups.getAtomicIdx(1);if(null===e)throw new Error(`Cannot find R1 group for monomer ${this.monomerSymbol}`);const{x:t,y:n}=this.atoms.atomCoordinates[e];this.atoms.shift({x:-t,y:-n})}alignR2AlongX(){const e=this.rGroups.getAtomicIdx(2);if(null===e)throw new Error(`Cannot find R2 group for monomer ${this.monomerSymbol}`);const t=this.atoms.atomCoordinates[e],n=t.y/t.x,s=Math.atan(n);if(isNaN(s))throw new Error(`Cannot calculate angle for R2 group for monomer ${this.monomerSymbol}`);this.rotateCoordinates(-s)}shiftMonomerToDefaultPosition(){this.shiftR1GroupToOrigin(),null!==this.rGroups.getAtomicIdx(2)&&this.alignR2AlongX()}deleteBondLineWithSpecifiedRGroup(e){this.rGroups.deleteBondLineWithSpecifiedRGroup(e)}shiftCoordinates(e){this.atoms.shift(e)}rotateCoordinates(e){this.atoms.rotate(e)}getBondLines(){return this.bonds.getBondLines()}getAtomLines(){return this.atoms.atomLines}removeRGroups(e){this.rGroups.removeRGroups(e)}replaceRGroupWithAttachmentAtom(e,t){this.rGroups.replaceRGroupWithAttachmentAtom(e,t)}getAttachmentAtomByRGroupId(e){return this.rGroups.getAttachmentAtomIdByRGroupId(e)}shiftBonds(e){this.bonds.shift(e)}capRGroups(e){this.rGroups.capRGroups(e)}}class vn{constructor(e,t,n){this.atoms=t,this.bonds=n,this.rGroupBondPositionMap=new Map,this.rGroupIdToAtomicIndexMap=e.getRGroupIdToAtomicIdxMap()}getAtomicIdx(e){const t=this.rGroupIdToAtomicIndexMap.get(e);return void 0===t?null:t}removeRGroupsFromAtomBlock(e){e.forEach((e=>{if(void 0===this.rGroupIdToAtomicIndexMap.get(e))throw new Error(`Cannot find atomic index for R group ${e}`)}));const t=Array.from(this.rGroupIdToAtomicIndexMap.entries()).filter((([t,n])=>e.includes(t))).map((([e,t])=>t));this.atoms.deleteAtoms(t)}removeRGroups(e){this.removeRGroupsFromAtomBlock(e),e.forEach((e=>{const t=this.replaceRGroupInBondsByDummy(e);this.rGroupBondPositionMap.set(e,t)}))}replaceRGroupInBondsByDummy(e){const t=this.rGroupIdToAtomicIndexMap.get(e);if(this.rGroupBondPositionMap.has(e))throw new Error(`R group ${e} is already handled`);const n=this.bonds.getPositionsInBonds(t+1);if(0===n.length)throw new Error(`Cannot find position for R group ${e}`);if(n.length>1)throw new Error(`More than one position for R group ${e}`);const s=n[0];return this.bonds.replacePositionsInBondsByDummy([s]),this.bonds.removeAtomIdFromBonds(t+1),this.removeRGroupFromAtomicIdxMap(e,t),s}removeRGroupFromAtomicIdxMap(e,t){this.rGroupIdToAtomicIndexMap.delete(e);for(const[e,n]of this.rGroupIdToAtomicIndexMap)n>t&&this.rGroupIdToAtomicIndexMap.set(e,n-1)}deleteBondLineWithSpecifiedRGroup(e){const t=this.rGroupBondPositionMap.get(e);if(!t)throw new Error(`Cannot find position for R group ${e}`);const{bondLineIdx:n}=t;this.bonds.deleteBondLines([n]),this.rGroupBondPositionMap.delete(e),this.rGroupIdToAtomicIndexMap.delete(e),this.rGroupBondPositionMap.forEach((e=>{e.bondLineIdx>n&&(e.bondLineIdx-=1)}))}replaceRGroupWithAttachmentAtom(e,t){const n=this.rGroupBondPositionMap.get(e);if(!n)throw new Error(`Cannot find position for R group ${e}`);const{bondLineIdx:s,nodeIdx:r}=n;this.bonds.bondedAtoms[s][r]=t}getAttachmentAtomIdByRGroupId(e){const t=this.rGroupBondPositionMap.get(e);if(!t)throw new Error(`Cannot find position for R group ${e}`);const{bondLineIdx:n,nodeIdx:s}=t;return this.bonds.bondedAtoms[n][(s+1)%2]}capRGroups(e){this.rGroupIdToAtomicIndexMap.forEach(((t,n)=>{const s=e[n-1];"H"===s?(this.removeRGroups([n]),this.deleteBondLineWithSpecifiedRGroup(n)):this.atoms.replaceRGroupSymbolByElement(t,s)}))}}var wn=n(1793);class Cn{constructor(){this.coordinates=[],this.rawAtomLines=[]}get atomCoordinates(){return this.coordinates}replaceRGroupSymbolByElement(e,t){this.rawAtomLines[e]=this.rawAtomLines[e].replace(wn.Ox,t)}deleteAtoms(e){this.coordinates=this.coordinates.filter(((t,n)=>!e.includes(n))),this.rawAtomLines=this.rawAtomLines.filter(((t,n)=>!e.includes(n)))}shift(e){this.coordinates=this.coordinates.map((t=>{const n=t.x+e.x,s=t.y+e.y;if(isNaN(n)||isNaN(s))throw new Error(`Cannot shift coordinates by ${e.x}, ${e.y}`);return{x:n,y:s}}))}rotate(e){this.coordinates=this.coordinates.map((t=>{const n=t.x,s=t.y,r=n*Math.cos(e)-s*Math.sin(e),i=n*Math.sin(e)+s*Math.cos(e);if(isNaN(r)||isNaN(i))throw new Error(`Cannot rotate coordinates by ${e}`);return{x:r,y:i}}))}}class Sn extends Cn{constructor(e){super(),this.rawAtomLines=e.getAtomLines(),this.coordinates=this.rawAtomLines.map((e=>({x:parseFloat(e.substring(0,10)),y:parseFloat(e.substring(10,20))})))}get atomLines(){return this.rawAtomLines.map(((e,t)=>{const n=this.coordinates[t];return`${n.x.toFixed(4).padStart(10," ")}${n.y.toFixed(4).padStart(10," ")}${e.substring(20)}`}))}}class An{constructor(){this.bondedAtomPairs=[],this.rawBondLines=[]}get bondedAtoms(){return this.bondedAtomPairs}deleteBondLines(e){this.rawBondLines=this.rawBondLines.filter(((t,n)=>!e.includes(n))),this.bondedAtomPairs=this.bondedAtomPairs.filter(((t,n)=>!e.includes(n)))}getPositionsInBonds(e){const t=[];return this.bondedAtomPairs.forEach(((n,s)=>{n.forEach(((n,r)=>{n===e&&t.push({bondLineIdx:s,nodeIdx:r})}))})),t}replacePositionsInBondsByDummy(e,t){void 0===t&&(t=-1),e.forEach((e=>{const{bondLineIdx:n,nodeIdx:s}=e;this.bondedAtomPairs[n][s]=t}))}removeAtomIdFromBonds(e){this.bondedAtomPairs=this.bondedAtomPairs.map((t=>t.map((t=>t>e?t-1:t))))}shift(e){this.bondedAtomPairs=this.bondedAtomPairs.map((t=>t.map((t=>t+e))))}}class xn extends An{constructor(e){super(),this.rawBondLines=e.getBondLines(),this.bondedAtomPairs=this.rawBondLines.map((e=>[parseInt(e.substring(0,3)),parseInt(e.substring(3,6))]))}getBondLines(){return this.bondedAtomPairs.map(((e,t)=>{if(e.some((e=>-1===e)))throw new Error(`Bonded pair ${e} contains -1`);return`${e[0].toString().padStart(3," ")}${e[1].toString().padStart(3," ")}${this.rawBondLines[t].substring(6)}`}))}}class En extends bn{constructor(e,t){super(t);const n=yn._.getInstance(e);this.atoms=new Sn(n),this.bonds=new xn(n),this.rGroups=new vn(n,this.atoms,this.bonds),this.shiftMonomerToDefaultPosition()}}class In extends Cn{constructor(e){super(),this.molfileHandler=e,this.rawAtomLines=e.getAtomLines(),this.coordinates=this.getCoordinates()}getCoordinates(){const e=this.molfileHandler.x,t=this.molfileHandler.y;return Array.from(e).map(((e,n)=>({x:e,y:t[n]})))}get atomLines(){const e=/^(M V30 [^-]*)(-?\d+\.\d+)( )(-?\d+\.\d+)( -?\d+\.\d+.*)$/,t=/\sRGROUPS=\(\d+(\s+\d+)*\)/;return this.rawAtomLines.map(((n,s)=>{const r=this.coordinates[s],i=r.x.toFixed(4)+"00",o=r.y.toFixed(4)+"00";return n.replace(e,((e,t,n,s,r,a)=>t+i+s+o+a)).replace(t,"")}))}}class Tn extends An{constructor(e){super(),this.molfileHandler=e,this.rawBondLines=e.getBondLines(),this.bondedAtomPairs=this.getBondedAtomPairs()}getBondedAtomPairs(){return this.molfileHandler.pairsOfBondedAtoms.map((e=>[e[0],e[1]]))}getBondLines(){const e=/^(M\s+V30\s+\d+\s+\d+\s+)(\d+)(\s+)(\d+)(.*)$/;return this.bondedAtomPairs.map(((t,n)=>{if(t.some((e=>-1===e)))throw new Error(`Bonded pair ${t} contains -1`);return this.rawBondLines[n].replace(e,((e,n,s,r,i,o)=>`${n}${t[0]}${r}${t[1]}${o}`))}))}}class _n extends bn{constructor(e,t){super(t);const n=yn._.getInstance(e);this.atoms=new In(n),this.bonds=new Tn(n),this.rGroups=new vn(n,this.atoms,this.bonds),this.shiftMonomerToDefaultPosition()}}class Mn{static getInstance(e,t){if(yn._.isMolfileV2K(e))return new En(e,t);if(yn._.isMolfileV3K(e))return new _n(e,t);throw new Error("Unsupported molfile version")}}class $n{constructor(e,t,n,s,r){this.monomerSymbol=e,this.monomerIdx=t,this.helm=n,this.capGroupElements=[];const i=this.getLibraryMonomerObject();let o=i.molfile;yn._.isMolfileV2K(o)&&(o=this.convertMolfileToV3KFormat(o,e,r)),this.molfileWrapper=Mn.getInstance(o,e),this.capGroupElements=this.getCapGroupElements(i),n.bondedRGroupsMap.has(t)&&this.removeRGroups(n.bondedRGroupsMap.get(t)),this.capRemainingRGroups(),this.shiftCoordinates(s)}convertMolfileToV3KFormat(e,t,n){let s=null;try{if(s=n.get_mol(e,JSON.stringify({mergeQueryHs:!0})),s)return s.get_v3Kmolblock();throw new Error(`Cannot convert ${t} to molV3000`)}finally{s?.delete()}}getLibraryMonomerObject(){const e=this.helm.getPolymerTypeByMonomerIdx(this.monomerIdx),t=St.A.instance.getBioLib().getMonomer(e,this.monomerSymbol);if(!t)throw new Error(`Monomer ${this.monomerSymbol} is not found in the library`);return t}getCapGroupElements(e){return e.rgroups.map((e=>(e.capGroupSMILES||e.capGroupSMILES).replace(/(\[|\]|\*|:|\d)/g,"")))}shiftCoordinates(e){this.molfileWrapper.shiftCoordinates(e)}getAtomLines(){return this.molfileWrapper.getAtomLines()}getBondLines(){return this.molfileWrapper.getBondLines()}removeRGroups(e){this.molfileWrapper.removeRGroups(e)}capRemainingRGroups(){this.molfileWrapper.capRGroups(this.capGroupElements)}replaceRGroupWithAttachmentAtom(e,t){this.molfileWrapper.replaceRGroupWithAttachmentAtom(e,t)}getAttachmentAtomByRGroupId(e){return this.molfileWrapper.getAttachmentAtomByRGroupId(e)}deleteBondLineWithSpecifiedRGroup(e){this.molfileWrapper.deleteBondLineWithSpecifiedRGroup(e)}shiftBonds(e){this.molfileWrapper.shiftBonds(e)}}class Nn{constructor(e,t){this.rdKitModule=t,this.monomerWrappers=[],this.helm=new gn(e)}addMonomer(e,t,n){const s=new $n(e,t,this.helm,n,this.rdKitModule);this.monomerWrappers.push(s)}getAtomNumberShifts(){const e=[];let t=0;return this.monomerWrappers.forEach((n=>{e.push(t),t+=n.getAtomLines().length})),e}restoreBondsBetweenMonomers(){this.helm.bondData.forEach((e=>{const t=e.map((e=>e.monomerIdx)),n=e.map((e=>e.rGroupId)),s=t.map((e=>this.monomerWrappers[e])),r=s[1].getAttachmentAtomByRGroupId(n[1]);s[0].replaceRGroupWithAttachmentAtom(n[0],r),s[1].deleteBondLineWithSpecifiedRGroup(n[1])}))}compileToMolfile(){const e=[],t=[],n=this.getAtomNumberShifts();this.monomerWrappers.forEach(((e,t)=>{e.shiftBonds(n[t])})),this.restoreBondsBetweenMonomers(),this.monomerWrappers.forEach((n=>{e.push(...n.getAtomLines()),t.push(...n.getBondLines())}));const s=e.length,r=t.length;return[this.getV3KHeader(s,r),this.getV3KAtomBlock(e),this.getV3KBondBlock(t),"M V30 END CTAB\nM END"].join("\n")}getV3KHeader(e,t){return`\n Datagrok\n\n 0 0 0 0 0 0 0 0 0 0999 V3000\nM V30 BEGIN CTAB\nM V30 COUNTS ${e} ${t} 0 0 1`}getV3KAtomBlock(e){const t=/^(M V30 )(\d+)( .*)$/;return["M V30 BEGIN ATOM",...e.map(((e,n)=>{const s=n+1;return e.replace(t,((e,t,n,r)=>t+s+r))})),"M V30 END ATOM"].join("\n")}getV3KBondBlock(e){const t=/^(M V30 )(\d+)( .*)$/;return["M V30 BEGIN BOND",...e.map(((e,n)=>{const s=n+1;return e.replace(t,((e,t,n,r)=>t+s+r))})),"M V30 END BOND"].join("\n")}}class Ln{constructor(e){this.molfileHandler=yn._.getInstance(e)}get monomerSymbols(){return this.molfileHandler.atomTypes}getMonomerShifts(e){return{x:this.molfileHandler.x[e],y:this.molfileHandler.y[e]}}}class Pn{constructor(e,t){this.helmColumn=e,this.df=t,this.helmColumn=e}async convertToSmiles(){const e=await this.getSmilesList(),t=this.df.columns.getUnusedName(`smiles(${this.helmColumn.name})`);return a.Column.fromStrings(t,e.map((e=>null===e?"":e)))}async getSmilesList(){return(await this.convertToMolfileV3KColumn()).toList().map((e=>a.chem.convert(e,a.chem.Notation.MolBlock,a.chem.Notation.Smiles)))}async getMolV3000ViaOCL(e,t){const n=e.map((e=>{if(null===e)return"";const t=e.get_v3Kmolblock();return e.delete(),t})),s=new Array(n.length),r=a.TaskBarProgressIndicator.create("Handling chirality...");for(let e=0;e<n.length;e++){const t=mn.Molecule.fromMolfile(n[e]).toMolfileV3();s[e]=t.replace("STERAC1","STEABS");const i=e/n.length*100;r.update(i,`${i?.toFixed(2)}% of molecules completed`)}return r.close(),a.Column.fromStrings(t,s)}async convertToRdKitBeautifiedMolfileColumn(e){const t=(await this.convertToMolfileV3KColumn()).toList(),n=await i.functions.call("Chem:getRdKitModule"),s=t.map((e=>{if(""===e)return null;const t=n.get_mol(e);return t?(t.set_new_coords(),t.normalize_depiction(1),t.straighten_depiction(!0),t):null})),r=this.df.columns.getUnusedName(`molfile(${this.helmColumn.name})`);return e?await this.getMolV3000ViaOCL(s,r):a.Column.fromStrings(r,s.map((e=>{if(null===e)return"";const t=e.get_v3Kmolblock();return e.delete(),t})))}async convertToMolfileV3KColumn(){const e=await this.getPolymerGraphColumn(),t=await i.functions.call("Chem:getRdKitModule"),n=e.toList().map(((e,n)=>{const s=this.helmColumn.get(n);if(!s)return"";let r="";try{r=this.getPolymerMolfile(s,e,t)}catch(e){const[t,n]=(0,ge.yf)(e);ls.logger.error(t,void 0,n)}finally{return r}})),s=this.df.columns.getUnusedName(`molfileV2K(${this.helmColumn.name})`);return a.Column.fromList("string",s,n)}async getPolymerGraphColumn(){return await i.functions.call("HELM:getMolfiles",{col:this.helmColumn})}getPolymerMolfile(e,t,n){const s=new Ln(t),r=new Nn(e,n);return s.monomerSymbols.forEach(((e,t)=>{const n=s.getMonomerShifts(t);r.addMonomer(e,t,n)})),r.compileToMolfile()}}async function Rn(e,t,n){const s=new Pn(t,e),r=await s.convertToRdKitBeautifiedMolfileColumn(n);return r.semType=a.SEMTYPE.MOLECULE,r}const On="System:AppData/Bio/polytool-rules/",kn="Polytool";class Fn{constructor(e){this.helmColumn=e}getLinkedPositions(e,t){const n=e.map((e=>e.replace("[","").replace("]",""))),s=new Array(t.length);for(let e=0;e<t.length;e++){let r=!1,i=!1,o=!1,a=-1,l=-1;const c=`(${t[e].code})`;for(let s=0;s<n.length;s++)if(n[s].includes(c)){if(r){if(o&&n[s]==t[e].secondMonomer+c){i=!0,l=s;break}if(o||n[s]!=t[e].firstMonomer+c)continue;i=!0,l=s;break}if(n[s]==t[e].firstMonomer+c)r=!0,o=!0,a=s;else{if(n[s]!=t[e].secondMonomer+c)continue;r=!0,o=!1,a=s}}s[e]=r&&i?o?[a,l]:[l,a]:[-1,-1]}return s}getRules(e){const t=e.map((e=>e.rowCount)).reduce(((e,t)=>e+t)),n=new Array(t);let s=0;for(let t=0;t<e.length;t++){const r=e[t].columns.byName("code"),i=e[t].columns.byName("monomer1"),o=e[t].columns.byName("monomer2"),a=e[t].columns.byName("modification1"),l=e[t].columns.byName("modification2"),c=e[t].columns.byName("R1"),u=e[t].columns.byName("R2");for(let h=0;h<e[t].rowCount;h++,s++)n[s]={code:r.get(h),firstMonomer:i.get(h),secondMonomer:o.get(h),firstModification:a.get(h),secondModification:l.get(h),firstR:c.get(h),secondR:u.get(h)}}return n}getDimeric(e){const t=e.replace("PEPTIDE1{","").replace("}$$$$","").split("."),n=[];for(let e=0;e<t.length;e++)if(t[e].includes("(#2)")){t[e]=t[e].replace("(#2)","");const s=e+1;let r=0;for(let e=s+1;e<t.length;e++)if(t[e].includes("}")){r=e;break}t[s]=t[s].replace("{",""),t[r]=t[r].replace("}",""),n.push([s,r])}return[t,n]}getAllCycles(e,t,n){const s=[],r=[],i=[],o=[],a=e.length;for(let l=0;l<a;l++){if(-1==n[l][0])continue;const a=t[n[l][0]].replace("[","").replace("]",""),c=t[n[l][1]].replace("[","").replace("]","");t[n[l][0]]=t[n[l][0]].replace(a,e[l].firstModification),t[n[l][1]]=t[n[l][1]].replace(c,e[l].secondModification),s.push(n[l][0]+1),r.push(n[l][1]+1),i.push(e[l].firstR),o.push(e[l].secondR)}return[t,s,r,i,o]}getHelmCycle(e,t,n){let s="";for(let r=0;r<e.allPos1.length;r++)s+=0==r?`PEPTIDE${t},PEPTIDE${n},`:`|PEPTIDE${t},PEPTIDE${n},`,s+=`${e.allPos1[r]}:R${e.allAttaches1[r]}-${e.allPos2[r]}:R${e.allAttaches2[r]}`;return s}getTransformedHelm(e,t){const[n,s]=this.getDimeric(e),r=this.getLinkedPositions(n,t),[i,o,a,l,c]=this.getAllCycles(t,n,r);e="PEPTIDE1{";for(let t=0;t<i.length;t++)e+=t!=i.length-1?i[t]+".":i[t];e+="}";const u=new Array(s.length),h=new Array(s.length);for(let e=0;e<s.length;e++){let t=`|PEPTIDE${e+2}{`;const n=s[e][1]-s[e][0],r=[],c=[],d=[],m=[];for(let r=0;r<=n;r++){const o=r+s[e][0];t+=r!=n?i[o]+".":i[o]}t+="}";for(let t=0;t<o.length;t++)o[t]-1>=s[e][0]&&o[t]-1<=s[e][1]&&(r.push(o[t]-s[e][0]),c.push(a[t]-s[e][0]),d.push(l[t]),m.push(l[t]));const p=this.getHelmCycle({allPos1:r,allPos2:c,allAttaches1:d,allAttaches2:m},e+2,e+2);u[e]=t,h[e]=this.getHelmCycle({allPos1:[s[e][0]],allPos2:[1],allAttaches1:[1],allAttaches2:[1]},1,e+2),h.push(p)}for(let t=0;t<u.length;t++)e+=u[t];e+="$",e+=this.getHelmCycle({allPos1:o,allPos2:a,allAttaches1:l,allAttaches2:c},1,1);for(let t=0;t<h.length;t++)e+="|",e+=h[t];return e+"$$$"}transform(e){const t=this.getRules(e);return this.helmColumn.toList().map((e=>this.getTransformedHelm(e,t)))}}class Gn{constructor(){}static getInstance(e){return new Fn(e)}}async function Dn(e,t,n,s){const r=e.dataFrame,o=he.g.forColumn(e).convert(Me.r2.HELM),l=Gn.getInstance(o),c=new a.FileSource(On),u=new Array(n.length);for(let e=0;e<n.length;e++){const t=await c.readAsText(n[e].replace(On,""));u[e]=a.DataFrame.fromCsv(t)}const h=l.transform(u),d=r.columns.getUnusedName("transformed("+e.name+")"),m=a.Column.fromList("string",d,h);var p;(p=m).setTag("quality",a.SEMTYPE.MACROMOLECULE),p.setTag("aligned","SEQ"),p.setTag("alphabet","PT"),m.setTag("units",Me.r2.HELM);const f=await Rn(r,m,s);f.name=r.columns.getUnusedName("molfile("+e.name+")"),f.semType=a.SEMTYPE.MOLECULE,t&&(m.setTag("cell.renderer","helm"),r.columns.add(m)),r.columns.add(f,!0),await i.data.detectSemanticTypes(r)}var Bn=function(e,t,n,s){return new(n||(n=Promise))((function(r,i){function o(e){try{l(s.next(e))}catch(e){i(e)}}function a(e){try{l(s.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class Vn{constructor(e,t,n=".csv"){this.path=e,this.userStorageName=t,this.ext=n,"/"!==this.path[this.path.length-1]&&(this.path+="/"),"."!==this.ext[0]&&(this.ext="."+this.ext)}getUserSettings(){return Bn(this,void 0,void 0,(function*(){if(this.settings)return this.settings;const e=yield i.dapi.userDataStorage.getValue(this.userStorageName,"Settings",!0),t=e?JSON.parse(e):{excluded:[],explicit:[]};return t.explicit=t.explicit instanceof Array?t.explicit:[],t.excluded=t.excluded instanceof Array?t.excluded:[],this.settings=t}))}setUserSettings(e){return Bn(this,void 0,void 0,(function*(){this.settings=e,yield i.dapi.userDataStorage.postValue(this.userStorageName,"Settings",JSON.stringify(e),!0)}))}getAllAvailable(){return Bn(this,void 0,void 0,(function*(){return(yield i.dapi.files.list(this.path)).map((e=>e.fullPath.replace(`${this.path}`,"")))}))}getActive(){return Bn(this,void 0,void 0,(function*(){const e=yield this.getUserSettings();return e.explicit.length>0?e.explicit:(yield this.getAllAvailable()).filter((t=>!e.excluded.includes(t)))}))}createInput(e,t){const n=o.boolInput(e,t,(t=>this.updateSelectionStatus(e,t)));return n.addOptions(o.button(o.iconFA("trash"),(()=>{o.dialog({title:"Warning"}).add(o.divText(`Delete file '${e}'?`)).onOK((()=>{n.root.remove(),this.availableRemove(e)})).show()}),`Delete ${e}`)),n}getInputs(){return Bn(this,void 0,void 0,(function*(){const e=yield this.getAllAvailable(),t=yield this.getActive(),n=new Array(e.length);for(let s=0;s<e.length;s++){const r=t.includes(e[s]);n[s]=this.createInput(e[s],r)}return n}))}getForm(){return Bn(this,void 0,void 0,(function*(){const e=yield this.getInputs(),t=o.divV(e);return o.divV([t,o.button("ADD",(()=>Bn(this,void 0,void 0,(function*(){let e="";e=yield this.getNewAvailable(),""!==e&&t.append(this.createInput(e,!0).root)}))))])}))}updateSelectionStatus(e,t){return Bn(this,void 0,void 0,(function*(){const n=yield this.getUserSettings();if(!n.excluded.includes(e)!==t){if(t){const t=n.excluded.indexOf(e);t>-1&&n.excluded.splice(t,1)}else n.excluded.push(e);this.setUserSettings(n)}}))}availableRemove(e){return Bn(this,void 0,void 0,(function*(){const t=yield this.getUserSettings(),n=t.excluded.indexOf(e);n>-1&&t.excluded.splice(n,1),yield Promise.all([this.setUserSettings(t),i.dapi.files.delete(this.path+e)]),i.shell.info(`File ${e} successfully deleted`)}))}getNewAvailable(){return Bn(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{a.Utils.openFile({accept:this.ext,open:t=>Bn(this,void 0,void 0,(function*(){const n=t.name,s=yield t.arrayBuffer();yield i.dapi.files.write(this.path+`${t.name}`,new Uint8Array(s)),e(n)}))})}))}))}}class Un extends Vn{constructor(e,t,n){super(e,t,n)}}var Hn=n(1047);const jn={symbol:"Short Name",name:"Medium Name",smiles:"SMILES"},Wn=[{capGroupSMILES:"[*:1][H]",alternateId:"R1-H",capGroupName:"H",label:"R1"},{capGroupSMILES:"O[*:2]",alternateId:"R2-OH",capGroupName:"OH",label:"R2"},{capGroupSMILES:"[*:3][H]",alternateId:"R3-H",capGroupName:"H",label:"R3"}];class Yn{constructor(e){this.rawLib=e}isValid(){return this.rawLib.every((e=>"object"==typeof e&&Object.values(jn).every((t=>t in e&&"string"==typeof e[t]))))}getJsonMonomerLib(){const e=[];return this.rawLib.forEach((t=>{const n=this.prepareMonomer(t);e.push(n)})),e}prepareMonomer(e){const t={...Hn.Z2};Object.entries(jn).forEach((([n,s])=>{const r=e[s];t[n]=r}));let n="smiles";const s=e[jn[n]],r=new Zn(s),i=r.getCappedSmiles();return t[n]=i,n="rgroups",t[n]=Kn.getRGroups(r.getNumberOfRGroups()),n="molfile",t[n]=new qn(r.getSmilesWithRGroups()).getMolfile(),t}}class Zn{constructor(e){let t=0;this.smilesWithRGroups=e.replace(/\[R(\d+)\]/g,((e,n)=>(++t,`[${n}*]`))),this.numberOfRGroups=t}getSmilesWithRGroups(){return this.smilesWithRGroups}getCappedSmiles(){return this.capRGroups()}getNumberOfRGroups(){return this.numberOfRGroups}capRGroups(){let e=this.smilesWithRGroups.replace("[1*]","[H:1]");return e=e.replace("[2*]","[OH:2]"),e.replace("[3*]","[H:3]")}}class Kn{constructor(){}static getRGroups(e){return Wn.slice(0,e)}}class qn{constructor(e){this.smilesWithRGroups=e}getMolfile(){let e=a.chem.convert(this.smilesWithRGroups,a.chem.Notation.Smiles,a.chem.Notation.MolBlock);return e=this.restoreRGPLine(e),e=this.fixRGroupSymbols(e),e}restoreRGPLine(e){return e.replace("M ISO","M RGP")}fixRGroupSymbols(e){return e.replace(/\bR\b/g,"R#")}}class zn{constructor(e,t){this.fileName=e,this.fileContent=t,this.validateFileType();const n=a.DataFrame.fromCsv(this.fileContent),s=this.toJson(n);this.polyToolMonomerLib=new Yn(s),this.validateContent()}async getJson(){return this.polyToolMonomerLib.getJsonMonomerLib()}toJson(e){return Array.from({length:e.rowCount},((t,n)=>e.columns.names().reduce(((t,s)=>(t[s]=e.get(s,n),t)),{})))}validateFileType(){if(!this.fileName.endsWith(".csv"))throw new Error(`File ${this.fileName} is not an CSV file`)}validateContent(){if(!this.polyToolMonomerLib.isValid())throw new Error("Invalid format of CSV monomer lib")}}function Xn(e,t,n,s){const r=he.g.forColumn(e);let i=null,o=null;for(let e=0;e<r.posList.length;++e)r.posList[e]==t&&(i=e),r.posList[e]==n&&(o=e);if(null===i&&null!==t)throw new Error(`Start position ${t} not found.`);if(null===o&&null!==n)throw new Error(`End position ${n} not found.`);if(r.posList.length<o)throw new Error(`End position ${o} exceeds positions length`);const a=s||`${e.name}: (${t??""}-${n??""})`;return r.getRegion(i,o,a)}const Jn={df:a.DataFrame.fromCsv("seq,value\nATCCGTCGT,0.5\nTGTTCGTCA,0.4\nATGGTCGTA,0.7\nATCCGTGCA,0.1"),colName:"seq",positionNames:["1","1A","1C","2","4","4A","4B","5","6"].join(Me.CI),regions:[{name:"first region",start:"1",end:"2"},{name:"second region",start:"1C",end:"4"},{name:"overlapping second",start:"1C",end:"4A"},{name:"whole sequence",start:"1",end:"6"},{name:"bad start",start:"0",end:"6"},{name:"bad end",start:"1",end:"4C"},{name:"bad start & end",start:"0",end:"4C"}]};class Qn{constructor(e,t){this.urlParams=e,this.funcName=t}async init(e){this.data=e??Jn;const t=this.data.df.getCol(this.data.colName);this.data.positionNames&&t.setTag(".positionNames",this.data.positionNames),this.data.regions&&t.setTag(".regions",JSON.stringify(this.data.regions)),await this.buildView()}async buildView(){await i.data.detectSemanticTypes(this.data.df),this.view=i.shell.addTableView(this.data.df),this.view.path=this.view.basePath=`func/${ls.name}.${this.funcName}`;const e=await this.view.dataFrame.plot.fromType("WebLogo",{sequenceColumnName:this.data.colName});this.view.dockManager.dock(e,a.DOCK_TYPE.DOWN,null,"WebLogo",.35)}}class es{constructor(e){this.call=e,this.inputs=new class{},this.fixRegion=!1,this.defaultName=!0,this.defaultNameUpdating=!1;const t=e=>this.call.inputParams[e].property.description;this.inputs.table=o.tableInput("Table",this.call.inputParams.table.value??i.shell.tv.dataFrame,void 0,(()=>{}));const n=this.call.inputParams.sequence.value??this.inputs.table.value.columns.bySemType(a.SEMTYPE.MACROMOLECULE),s={filter:e=>e.semType===a.SEMTYPE.MACROMOLECULE};this.inputs.sequence=o.columnInput("Sequence",i.shell.tv.dataFrame,n,this.sequenceInputChanged.bind(this),s),this.inputs.start=o.choiceInput("Start",void 0,[],this.startInputChanged.bind(this)),this.inputs.end=o.choiceInput("End",void 0,[],this.endInputChanged.bind(this)),this.inputs.region=o.choiceInput("Region",null,[],this.regionInputChanged.bind(this)),this.inputs.name=o.stringInput("Column name",this.getDefaultName(),this.nameInputChanged.bind(this),{clearIcon:!0}),this.inputs.name.onInput(this.nameInputInput.bind(this));for(const e in this.call.inputParams)o.tooltip.bind(this.inputs[e].captionLabel,t(e));this.sequenceInputChanged()}sequenceInputChanged(){const e=this.inputs.sequence.value;e&&he.g.forColumn(e),this.updateRegionItems(),this.updateStartEndInputItems(),this.updateRegion(!0),this.updateNameInput()}regionInputChanged(){this.fixRegion=!0;try{const e=this.inputs.region.stringValue,t=e?JSON.parse(e):null;if(null!==t)this.inputs.start.value=t?.start,this.inputs.end.value=t?.end;else{const e=he.g.forColumn(this.inputs.sequence.value);this.inputs.start.value=e.posList[0],this.inputs.end.value=e.posList[e.posList.length-1]}}finally{this.fixRegion=!1}}startInputChanged(){this.updateRegion(!1),this.updateNameInput()}endInputChanged(){this.updateRegion(!1),this.updateNameInput()}nameInputChanged(){this.defaultNameUpdating||(this.defaultName=!1)}nameInputInput(){this.inputs.name.value||(this.defaultName=!0,this.inputs.name.input.focus())}updateStartEndInputItems(){const e=this.inputs.sequence.value,t=e?he.g.forColumn(e):null,n=this.inputs.start.input,s=this.inputs.end.input;for(let e=n.options.length-1;e>=0;--e)n.options.remove(e);for(let e=s.options.length-1;e>=0;--e)s.options.remove(e);for(const e of t?.posList??[]){const t=document.createElement("option"),r=document.createElement("option");t.text=r.text=e,t.value=r.value=e,n.options.add(t),s.options.add(r)}n.value=t?.posList[0]??"",s.value=t?.posList[t?.posList.length-1]??""}updateRegionItems(){const e=this.inputs.sequence.value,t=e?e.getTag(".regions"):null,n=t?JSON.parse(t):null,s=this.inputs.region.input;for(let e=s.options.length-1;e>=0;--e)s.options.remove(e);const r=document.createElement("option");if(r.text="",r.value=JSON.stringify(null),s.options.add(r),null!=n){this.inputs.region.root.style.removeProperty("display");for(const e of n){const t=document.createElement("option");t.text=`${e.name}: ${e.start}-${e.end}`,t.value=JSON.stringify(e),s.options.add(t)}}else this.inputs.region.root.style.display="none"}updateRegion(e){const t=this.inputs.start.stringValue??"",n=this.inputs.end.stringValue??"";if(!this.fixRegion){const e=this.inputs.region.input;e.selectedIndex=-1;for(let s=e.options.length-1;s>=0;--s){const r=e.options[s],i=JSON.parse(r.value);i&&t===i.start&&n===i.end&&(e.selectedIndex=s)}}}updateNameInput(){this.defaultNameUpdating=!0;try{this.defaultName&&(this.inputs.name.value=this.getDefaultName())}finally{this.defaultNameUpdating=!1}}getDefaultName(){const e=this.inputs.region.stringValue,t=e?JSON.parse(e):null,n=this.inputs.sequence.value,s=this.inputs.start.stringValue??"",r=this.inputs.end.stringValue??"";return null!=t?`${n.name}(${t.name}): ${t.start}-${t.end}`:`${n?.name}: (${s}-${r})`}getParams(){return{table:this.inputs.table.value,sequence:this.inputs.sequence.value,start:this.getStart(),end:this.getEnd(),name:this.getName()}}getStart(){return this.inputs.start.stringValue}getEnd(){return this.inputs.end.stringValue}getName(){const e=this.inputs.name.stringValue;return""==e?null:e}dialog(){const e=o.inputs(Object.values(this.inputs),{style:{minWidth:"320px"}});o.dialog({title:"Get Region"}).add(e).onOK((()=>{(async()=>{const e=this.getParams();await this.call.func.prepare(e).call(!0)})().catch((e=>{ls.handleErrorUI(e)}))})).show()}widget(){const e=o.inputs(Object.entries(this.inputs).filter((([e,t])=>!["table","sequence"].includes(e))).map((([e,t])=>t))),t=o.button("Get Region",(()=>{(async()=>{const e=this.getParams();await this.call.func.prepare(e).call(!0)})().catch((e=>{ls.handleErrorUI(e)}))}));return a.Widget.fromRoot(o.divV([e,o.div(t)]))}}var ts=n(8601);class ns{constructor(){this.maxIterations={uiName:"Max iterations",value:0,tooltip:"Maximum iterations for MCL process.Default is \n 0 which will construct the clusters with plain sparse matrix. Values greater than 0 will \n perform MCL with the given number of iterations and will result in trans-cluster activity cliff lines."},this.useWebGPU={uiName:"Use WebGPU",value:!1,tooltip:"Use WebGPU for MCL calculation. (Experimental)",type:"boolean"}}}class ss extends p{constructor(e={}){super({...e,enableMCL:!0});const t=this.tableInput.value.columns.numerical;this.activitiesInput=o.columnInput("Activities",this.tableInput.value,a.Utils.firstOrNull(t),null,{filter:e=>Array.from(t).includes(e)}),this.activitiesInputRoot=this.activitiesInput.root,this.similarityInput=o.intInput("Similarity cutoff",80),this.methodsParams[d]=new ns}onTableInputChanged(){if(super.onTableInputChanged(),this.activitiesInputRoot){o.empty(this.activitiesInputRoot);const e=this.tableInput.value.columns.numerical;this.activitiesInput=o.columnInput("Activities",this.tableInput.value,a.Utils.firstOrNull(e),null,{filter:t=>Array.from(e).includes(t)}),Array.from(this.activitiesInput.root.children).forEach((e=>this.activitiesInputRoot.append(e)))}}getEditor(){return o.div([this.tableInput,this.colInputRoot,this.preprocessingFunctionInputRoot,this.preprocessingFuncSettingsDiv,this.activitiesInputRoot,this.similarityMetricInputRoot,this.methodInput,this.methodSettingsDiv,this.similarityMetricInputRoot,this.similarityInput],{style:{minWidth:"320px"},classes:"ui-form"})}getParams(){return{...super.getParams(),activities:this.activitiesInput.value,similarityThreshold:this.similarityInput.value}}}function rs(e){const t=["Embed_X","Embed_Y"],n=e.columns.names().filter((e=>e.includes(t[0]))).length+1;return t.map((e=>`${e}_${n}`))}var is=n(6286);class os{constructor(e){this.separator=e,this.separatorSplitter=(0,we.Ar)(this.separator),this.splitter=this._splitter.bind(this)}_splitter(e){const t=this.separatorSplitter(e);return new as(t.originals,he.lh[Me.r2.SEPARATOR])}}class as extends we.wx{get canonicals(){if(!this._canonicals){const e=this.length;this._canonicals=new Array(e);for(let t=0;t<e;++t)this._canonicals[t]=this.getCanonical(t)}return this._canonicals}getCanonical(e){if(this.isGap(e))return is.G2;let t=this.seqCList[e];if(null===t){const n=this.getOriginal(e);t=n,")"===n[n.length-1]&&(t=this.seqCList[e]=n.replace(/\(\d+\)$/,""))}return t}constructor(e,t){super(e,t),this._canonicals=null,this.seqCList=new Array(this.length).fill(null)}}const ls=new un;function cs(){return St.A.instance}let us=null;class hs{constructor(e){this._palette=e}get(e){return this._palette[e]}}async function ds(){ls.logger.debug("Bio: initBio(), started");const e=await i.functions.call("Chem:getRdKitModule");await Promise.all([(async()=>{await St.A.instance.loadLibraries()})(),(async()=>{const e=await ls.getProperties(),t=new cn(e);ls.properties=t})()]).finally((()=>{ls.completeInit()}));const t=St.A.instance.getBioLib(),n=[],s=[],r=t.getMonomerMolsByPolymerType("PEPTIDE");Object.keys(r).forEach((t=>{n.push(t);const i=r[t].replaceAll("#R","O "),o=e.get_mol(i),a=JSON.parse(o.get_descriptors()).CrippenClogP;s.push(a),o?.delete()}));const o=s.reduce(((e,t)=>e+t),0)/s.length||0,a={};for(let e=0;e<n.length;e++)a[n[e]]=s[e]<o?"#4682B4":"#DC143C";us=new hs(a),ls.logger.debug("Bio: initBio(), completed")}function ms(e){const t=new dn(e);return t.init().then((()=>{})).catch((e=>{const t=e instanceof Error?e.message:e.toString();i.shell.error(t)})),t}function ps(){return St.A.instance.getBioLib()}function fs(e){return he.g.forColumn(e)}function gs(e){const t="getRegionTopMenu",n=a.Func.find({package:ls.name,name:t});if(1!==n.length)throw new Error(`Package '${ls.name}' func '${t}' not found`);const s=n[0].prepare({table:e.dataFrame,sequence:e});return new es(s).widget()}async function ys(e){return async function(){const e=o.label("Manage monomer libraries");return xt()(e).addClass("d4-link-action"),e.onclick=async()=>await $t(),new a.Widget(e)}()}function bs(e){try{new es(e).dialog()}catch(e){const t=e instanceof Error?e.message:e.toString(),n=e instanceof Error?e.stack:void 0;i.shell.error(`Get region editor error: ${t}`),ls.logger.error(t,void 0,n)}}function vs(e){const t=new tn;o.dialog({title:"Split to Monomers"}).add(t.paramsUI).onOK((async()=>e.func.prepare(t.funcParams).call(!0))).show()}function ws(e){const t=new p({semtype:a.SEMTYPE.MACROMOLECULE});o.dialog({title:"Sequence Space"}).add(t.getEditor()).onOK((async()=>{const n=t.getParams();return e.func.prepare({molecules:n.col,table:n.table,methodName:n.methodName,similarityMetric:n.similarityMetric,plotEmbeddings:n.plotEmbeddings,options:n.options,preprocessingFunction:n.preprocessingFunction,clusterEmbeddings:n.clusterEmbeddings}).call()})).show()}function Cs(e){const t=new ss({semtype:a.SEMTYPE.MACROMOLECULE});o.dialog({title:"Activity Cliffs"}).add(t.getEditor()).onOK((async()=>{const n=t.getParams();return e.func.prepare({table:n.table,molecules:n.col,activities:n.activities,similarity:n.similarityThreshold,methodName:n.methodName,similarityMetric:n.similarityMetric,preprocessingFunction:n.preprocessingFunction,options:n.options}).call()})).show()}function Ss(){return new Be}function As(e){return function(e){const t=Array.from(e.dataFrame.columns).filter((e=>e.semType===a.SEMTYPE.MOLECULE)).map((e=>e.name));new Set(t).delete(e.name);const n=o.choiceInput("Monomer width",null!=e?.temp["monomer-width"]?e.temp["monomer-width"]:Le.short,[Le.short,Le.long],(t=>{e.temp["monomer-width"]=t,e.setTag(".mm.cellRenderer.settingsChanged",Pe.true),e.dataFrame.fireValuesChanged()}));n.setTooltip("In short mode, only the 'Max monomer length' characters are displayed, followed by .. if there are more");const s=parseInt(e.getTag(Ee.maxMonomerLength)),r=o.intInput("Max monomer length",isNaN(s)?ls.properties.MaxMonomerLength:s,(t=>{e.setTag(Ee.maxMonomerLength,t.toString()),e.setTag(".mm.cellRenderer.settingsChanged",Pe.true),e.dataFrame.fireValuesChanged()}));r.setTooltip(`The max length of monomer name displayed without shortening in '${Le.short}' monomer width mode.`);const i=o.intInput("Monomer margin",e.temp[".mm.cellRenderer.gapLength"]??0,(t=>{e.temp[".mm.cellRenderer.gapLength"]=t,e.setTag(".mm.cellRenderer.settingsChanged",Pe.true),e.dataFrame.fireValuesChanged()}));i.setTooltip("The size of margin between monomers (in pixels)");const l=o.boolInput("Color code",null==e?.temp["color-code"]||e.temp["color-code"],(t=>{e.temp["color-code"]=t,e.dataFrame.fireValuesChanged()}));l.setTooltip("Color code");const c=o.stringInput("Reference sequence",null!=e?.temp["reference-sequence"]?e?.temp["reference-sequence"]:"",(t=>{e.temp["reference-sequence"]=t,e.dataFrame.fireValuesChanged()}));c.setTooltip("Reference sequence is not empty, then the sequence will be render \nas a difference from the reference sequence");const u=o.boolInput("Compare with current",null==e?.temp["compare-with-current"]||e.temp["compare-with-current"],(t=>{e.temp["compare-with-current"]=t,e.dataFrame.fireValuesChanged()}));u.setTooltip('When on, all sequences get rendered in the "diff" mode');const h=o.inputs([n,r,i,c,l,u]);return new a.Widget(h)}(e)}function xs(e){return(0,hn.t)(e)}function Es(){return new Be}function Is(){return new Ve}function Ts(e,t,n,s,r){const i=new tt.k(s,r,n,t);return"Local alignment"==e?i.smithWaterman():i.needlemanWunch()}function _s(){return new qe.OZ}function Ms(){return new et}function $s(e,t,n,s){return Xn(e,t??null,n??null,s??null)}async function Ns(e,t,n,s,r){const o=Xn(t,n??null,s??null,r??null);t.dataFrame.columns.add(o),await i.data.detectSemanticTypes(t.dataFrame)}async function Ls(e,t,n,s,r,u,h,d){if(!(0,Jt.n)(t,"Activity Cliffs"))return;const m=rs(e),p={units:t.getTag(a.TAGS.UNITS),aligned:t.getTag("aligned"),separator:t.getTag("separator"),alphabet:t.getTag("alphabet")},f=u,g=t,y=async()=>await ce(e,g,m,"Activity cliffs",n,s,f,r,{...d??{}},a.SEMTYPE.MACROMOLECULE,p,h,ot,at,ht),b=r===c.A.UMAP?2e5:2e4,v=r===c.A.UMAP?5e3:2e3;if(e.rowCount>b)return void i.shell.warning(`Too many rows, maximum for sequence activity cliffs is ${b}`);const w=a.TaskBarProgressIndicator.create("Running sequence activity cliffs ...");return new Promise(((t,n)=>{e.rowCount>v&&!d?.[l.sS]?o.dialog().add(o.divText("Activity cliffs analysis might take several minutes.\n Do you want to continue?")).onOK((async()=>{y().then((e=>t(e))).catch((e=>n(e)))})).onCancel((()=>{t(void 0)})).show():y().then((e=>t(e))).catch((e=>n(e)))})).catch((e=>{const[t,n]=(0,ge.yf)(e);throw ls.logger.error(t,void 0,n),e})).finally((()=>{w.close()}))}async function Ps(e,t,n=1,s=.6,r="Morgan"){if(e.semType!==a.SEMTYPE.MACROMOLECULE)return{entries:e.toList(),options:{}};const{seqList:i,options:o}=await st(e,t,r);return{entries:i,options:{...o,gapOpen:n,gapExtend:s}}}async function Rs(e,t){e.version!==e.temp["last-invalidated-version"]&&await(0,it.HV)(e,!1);const n=e.temp["monomeric-mols"],s=await i.functions.call("Chem:getMorganFingerprints",{molColumn:n}),r=new Array(s.length).fill(null);for(let e=0;e<s.length;e++){if(s.isNone(e)||!s.get(e))continue;const t=s.get(e);r[e]=G.Z.fromUint32Array(t.length,new Uint32Array(t.getBuffer().buffer))}return{entries:r,options:{}}}async function Os(e,t,s,r,c,u,h,d){if((0,Jt.n)(t,"Sequence Space"))return u||(u=a.Func.find({name:"macromoleculePreprocessingFunction",package:"Bio"})[0]),h??(h={}),await async function(e,t,s,r,c,u,h,d=!0,m=!1,p={preprocessingFuncArgs:[]},f={},g=null,y={}){const b={showXAxis:!1,showYAxis:!1,showXSelector:!1,showYSelector:!1};if(t.length!==r.length||t.length!==u.length||t.length!==c.length||t.length!==p.preprocessingFuncArgs.length)throw new Error("columns, metrics and preprocessing functions, weights and function argumentsmust have the same length");const v=i.shell.tableView(e.name)??i.shell.addTableView(e),w=async()=>{const w=a.TaskBarProgressIndicator.create(`Initializing ${f.scatterPlotName??"dimensionality reduction"} ...`);let C;try{const S=rs(e);function A(t,n,s){let r=null,i=null;e.columns.names().includes(S[0])?(r=e.columns.byName(S[0]),i=e.columns.byName(S[1])):(r=e.columns.add(a.Column.float(S[0],e.rowCount)),i=e.columns.add(a.Column.float(S[1],e.rowCount)),d&&!C&&(C=v.scatterPlot({...b,x:S[0],y:S[1],title:f.scatterPlotName??"Embedding space"}))),f[l.Ec]&&(C?.root&&o.setUpdateIndicator(C.root,!1),r.init((e=>s[0]?s[0][e]:void 0)),i.init((e=>s[1]?s[1][e]:void 0)));const c=t/n*100;w.update(c,`Running ${f.scatterPlotName??"dimensionality reduction"}... ${c.toFixed(0)}%`)}async function x(){e.columns.add(a.Column.float(S[0],e.rowCount)),e.columns.add(a.Column.float(S[1],e.rowCount));let n=null;d&&(C=v.scatterPlot({...b,x:S[0],y:S[1],title:f.scatterPlotName??"Embedding space"}),o.setUpdateIndicator(C.root,!0));const m=i.events.onViewerClosed.subscribe((e=>{const t=e.args.viewer;t?.getOptions()?.look?.title&&C?.getOptions()?.look?.title&&t?.getOptions()?.look?.title===C?.getOptions()?.look?.title&&(i.events.fireCustomEvent(B,{}),m.unsubscribe(),n?.(),w.close())})),g=new Promise((async(e,i)=>{try{n=e;const i=[];for(let e=0;e<u.length;++e){const n=u[e];if(p.distanceFnArgs||(p.distanceFnArgs=[]),n){const s=n.inputs[0].name,o=n.inputs[1].name,{entries:a,options:l}=await n.apply({[s]:t[e],[o]:r[e],...p.preprocessingFuncArgs[e]??{}});i.push({entries:a,options:l}),p.distanceFnArgs.push(l)}else{const n=t[e].toList(),s={};i.push({entries:n,options:s}),p.distanceFnArgs.push(s)}}e(await j(i.map((e=>e.entries)),s,r,c,h,p,f[l.sS]?void 0:A))}catch(e){i(e)}})),y=await g;return w.close(),m.unsubscribe(),y}const E=await x();if(m&&E){const I=a.TaskBarProgressIndicator.create("Clustering embeddings ...");try{const T=await function(e,t,s,r){return Yt(this,void 0,void 0,(function*(){return new Promise((function(i,o){const a=new Worker(new URL(n.p+n.u(796),n.b));a.postMessage({embedX:e,embedY:t,minPts:r,epsilon:s}),a.onmessage=({data:{error:e,clusters:t}})=>{a.terminate(),e?o(e):i(t)}}))}))}(E[0],E[1],p.dbScanEpsilon??.01,p.dbScanMinPts??4),_=e.columns.getUnusedName("Cluster (DBSCAN)");e.columns.addNewString(_).init((e=>T[e].toString())),C&&(C.props.colorColumnName=_)}catch(M){i.shell.error("Clustering embeddings failed"),console.error(M)}finally{I.close()}}if(E){const $=e.columns.byName(S[0]),N=e.columns.byName(S[1]);if($.init((e=>E[0][e])),N.init((e=>E[1][e])),g)try{const L=g.inputs[0].name,P=g.inputs[1].name;await g.prepare({[L]:$,[P]:N,...y}).call(!0)}catch(R){i.shell.error("Post-processing failed"),console.error(R)}if(C)return o.setUpdateIndicator(C.root,!1),C.helpUrl="/help/compute/sequence-space",C}}catch(O){i.shell.error("Dimensionality reduction failed"),console.error(O),w.close(),C&&o.setUpdateIndicator(C.root,!1)}};return new Promise((async(t,n)=>{try{if(f.fastRowCount&&e.rowCount>f.fastRowCount&&!f[l.sS])o.dialog().add(o.divText("Analysis might take several minutes. Do you want to continue?")).onOK((async()=>{try{const e=await w();t(e)}catch(e){n(e)}})).onCancel((()=>t(void 0))).show();else{const e=await w();t(e)}}catch(e){n(e)}}))}(e,[t],s,[r],[1],[u],"MANHATTAN",c,d??!1,{...h,preprocessingFuncArgs:[h.preprocessingFuncArgs??{}]},{fastRowCount:1e4,scatterPlotName:"Sequence space",bypassLargeDataWarning:h?.[l.sS]})}async function ks(e,t,n){const s=a.TaskBarProgressIndicator.create("Converting to atomic level ...");try{await async function(e,t,n){if(0===a.Func.find({package:"Chem",name:"getRdKitModule"}).length)return void i.shell.warning('Transformation to atomic level requires package "Chem" installed.');if(n){const n=he.g.forColumn(t);return n.isHelm()||(t=n.convert(Me.r2.HELM)),void async function(e,t){const n=await Rn(e,t);e.columns.add(n,!0),await i.data.detectSemanticTypes(e)}(e,t)}if(!(0,Jt.n)(t,"To Atomic Level"))return;const s=cs().getBioLib(),r=await(0,ts.i0)(e,t,s);null!==r.col&&(e.columns.add(r.col,!0),await i.data.detectSemanticTypes(e)),r.warnings&&r.warnings.length>0&&i.shell.warning(o.list(r.warnings))}(e,t,n)}finally{s.close()}}function Fs(){(0,Qt.K)()}async function Gs(e=null,t=null){return(0,Qt.K)({col:e,clustersCol:t})}async function Ds(){const e=i.shell.tv,t=e.dataFrame.columns.toList().filter((e=>e.semType==a.SEMTYPE.MACROMOLECULE&&(he.g.forColumn(e),!0))),n=async t=>{if(!(0,Jt.n)(t,"Composition"))return;const n=e.addViewer("WebLogo",{sequenceColumnName:t.name});i.shell.tv.dockManager.dock(n,a.DOCK_TYPE.DOWN,null,"Composition analysis",.25)};let s=null;if(0!=t.length){if(t.length>1){const e=t.map((e=>e.name)),s=t.find((e=>he.g.forColumn(e).isMsa())),r=o.choiceInput("Column",s?s.name:e[0],e);o.dialog({title:"Composition Analysis",helpUrl:"https://datagrok.ai/help/datagrok/solutions/domains/bio/#sequence-composition"}).add(o.div([r])).onOK((async()=>{const e=t.find((e=>e.name==r.value))??null;e&&await n(e)})).show()}else s=t[0];s&&await n(s)}else i.shell.error("Current table does not contain sequences")}function Bs(e){return new de.i(e).importFasta()}function Vs(e){return console.log(e),[]}function Us(){const e=(0,ye.B)()[0];(0,vt.O)(e)}async function Hs(){let e;try{e=await async function(){const e=i.shell.t.columns.bySemTypeAll(a.SEMTYPE.MACROMOLECULE);if(!e)throw new Error("No dataframe with macromolecule columns open");const t=o.columnInput("Column",i.shell.t,e[0],null,{filter:e=>e.semType===a.SEMTYPE.MACROMOLECULE}),n=o.boolInput("Get HELM",!0);o.tooltip.bind(n.root,"Add HELM column");const s=o.boolInput("Chirality engine",!1),r=new Un(On,kn,".csv"),l=await r.getForm(),c=o.div([t,n,s,"Rules used",l]);return o.dialog("Poly Tool").add(c).onOK((async()=>{const e=t.value;if(!e)return void i.shell.warning("No marcomolecule column chosen!");const o=await r.getActive();Dn(e,n.value,o,s.value)}))}(),e.show()}catch(e){i.shell.warning("To run PolyTool, open a dataframe with macromolecules")}}function js(){return new ln}async function Ws(e){const t=a.TaskBarProgressIndicator.create("Test detectMacromolecule..."),n=(await i.dapi.files.list(e,!0,"")).filter((e=>e.fileName.endsWith(".csv")));let s=0;const r=[];for(const o of n)try{const t=await i.dapi.files.readAsText(e+o.fullPath),n=a.DataFrame.fromCsv(t);for(const e of n.columns)await i.functions.call("Bio:detectMacromolecule",{col:e})===a.SEMTYPE.MACROMOLECULE&&r.push({file:o.path,result:"detected",column:e.name,message:`units: ${e.getTag(a.TAGS.UNITS)}`})}catch(e){r.push({file:o.path,result:"error",column:null,message:e instanceof Error?e.message:e.toString()})}finally{s+=1,t.update(100*s/n.length,`Test ${o.fileName}`)}i.shell.info("Test Demo:Files for detectMacromolecule finished."),t.close();const o=a.DataFrame.fromObjects(r);return o.name=`datasets_detectMacromolecule_${e}`,o}async function Ys(e,t){await(0,nn.n)(e,t)}function Zs(e){const t=he.g.forColumn(e).stats;return Object.keys(t.freq)}function Ks(){return new gt}function qs(){const e=i.shell.v,t=e.addViewer("Sequence Similarity Search");e.dockManager.dock(t,"down")}function zs(){return new bt}function Xs(){const e=i.shell.v,t=e.addViewer("Sequence Diversity Search");e.dockManager.dock(t,"down")}function Js(e){const t=(0,ye.B)();1===t.length?e.func.prepare({macromolecules:t[0]}).call(!0):new it.uH(t)}function Qs(e){i.shell.tv.getFiltersGroup({createDefaultFilters:!1}).updateOrAdd({type:"Bio:bioSubstructureFilter",column:e.name,columnName:e.name}),i.shell.tv.grid.scrollToCell(e,0)}async function er(e,t,n){return fe(e,t,n,ue.IDENTITY)}async function tr(e,t,n){return fe(e,t,n,ue.SIMILARITY)}async function nr(){$t()}function sr(){(0,wt.C2)()}function rr(){return new Ct.ST}async function ir(){const e=a.TaskBarProgressIndicator.create("WebLogo");try{const e=new URLSearchParams(window.location.search),t=new en(e,"webLogoLargeApp"),n=await ls.files.readCsv("data/sample_PT_100000x5.csv");await i.data.detectSemanticTypes(n),await t.init(n)}finally{e.close()}}async function or(){const e=a.TaskBarProgressIndicator.create("WebLogo ...");try{const e=new URLSearchParams(window.location.search),t=new en(e,"webLogoAggApp"),n=await ls.files.readCsv("samples/FASTA_PT_activity.csv");await i.data.detectSemanticTypes(n),await t.init(n)}finally{e.close()}}async function ar(){const e=a.TaskBarProgressIndicator.create("getRegion ...");try{const e=new URLSearchParams(window.location.search),t=new Qn(e,"getRegionApp");await t.init()}finally{e.close()}}async function lr(){const e=a.TaskBarProgressIndicator.create("getRegion ...");try{const e=new URLSearchParams(window.location.search),t=await ls.files.readCsv("samples/HELM_empty_vals.csv"),n=new Qn(e,"getRegionHelmApp");await n.init({df:t,colName:"HELM"})}finally{e.close()}}function cr(e,t){!function(e,t){const n=he.g.forColumn(e.column),s=Object.values(Me.r2).filter((e=>e!==n.units));t.group("Copy").items(s,(t=>{const n=e.column,s=e.rowIndex,r=he.g.forColumn(n),o=t===Me.r2.SEPARATOR?ls.properties.DefaultSeparator:void 0,a=r.getJoiner({notation:t,separator:o})(r.getSplitted(s));navigator.clipboard?(navigator.clipboard.writeText(a),i.shell.info(`Value of notation '${t}' copied to clipboard`)):i.shell.warning("The clipboard functionality requires a secure origin — either HTTPS or localhost")}))}(e,t)}async function ur(){await async function(){let e,t;try{const n=new kt("Similarity, Diversity","Sequence similarity tracking and evaluation dataset diversity");await n.step("Load DNA sequences",(async()=>{i.shell.windows.showContextPanel=!1,i.shell.windows.showProperties=!1,t=await ls.files.readCsv(Gt),e=i.shell.addTableView(t),e.grid.columns.byName("cluster").visible=!1,e.grid.columns.byName("sequence_id").visible=!1,e.grid.columns.byName("sequence").width=300,e.grid.columns.byName("activity").visible=!1,e.grid.columns.byName("is_cliff").visible=!1}),{description:"Load dataset with macromolecules of 'fasta' notation, 'DNA' alphabet.",delay:2e3}).step("Find the most similar sequences to the current one",(async()=>{const n=await t.plot.fromType("Sequence Similarity Search",{moleculeColumnName:"sequence",similarColumnLabel:"Similar to current"});e.dockManager.dock(n,a.DOCK_TYPE.RIGHT,null,"Similarity search",.35)}),{description:"Add 'Sequence Similarity Search' viewer.",delay:2e3}).step("Explore most diverse sequences in a dataset",(async()=>{const n=await t.plot.fromType("Sequence Diversity Search",{moleculeColumnName:"sequence",diverseColumnLabel:"Top diverse sequences of all data"});e.dockManager.dock(n,a.DOCK_TYPE.DOWN,null,"Diversity search",.27)}),{description:"Add 'Sequence Deversity Search' viewer.",delay:2e3}).step("Choose another sequence for similarity search",(async()=>{t.currentRowIdx=3}),{description:"Handling current row changed of data frame showing update of similar sequences.",delay:2e3}).step("One more sequence for similarity search",(async()=>{t.currentRowIdx=7}),{description:"Just one more sequence to search similar ones.",delay:2e3}).start()}catch(e){Ft(e)}}()}async function hr(){await async function(){let e,t,n,s,r;try{const o=new kt("Sequence Space","Exploring sequence space of Macromolecules, comparison with hierarchical clustering results");await o.step("Load DNA sequences",(async()=>{[s,e,t]=await Promise.all([ls.files.readCsv(Zt),Dt(),Bt()]),n=i.shell.addTableView(s),n.grid.props.rowHeight=22,n.grid.columns.byName("cluster").visible=!1,n.grid.columns.byName("sequence").width=200,n.grid.columns.byName("is_cliff").visible=!1,i.shell.windows.showContextPanel=!1,i.shell.windows.showProperties=!1}),{description:"Load dataset with macromolecules of 'fasta' notation, 'DNA' alphabet.",delay:2e3}).step("Build sequence space",(async()=>{r=await async function(e,t,n,s){let r;{const e=Object.values(Rt);for(let n=0;n<e.length;n++){const s=e[n];if(!t.col(s)){const r=n==e.length-1;t.columns.add(a.Column.float(s,t.rowCount),r)}}if(t.rowCount>=1){const s=t.getCol(n).toList(),r=Date.now();ls.logger.debug("Bio: demoBio01aUI(), calc reduceDimensionality start...");const i=await j([s],"UMAP",[rt.W.Levenshtein],[1],"MANHATTAN",{distanceFnArgs:[{}]}),o=Date.now();ls.logger.debug(`Bio: demoBio01aUI(), calc reduceDimensionality ET: ${(o-r)/1e3} s`);for(let n=0;n<e.length;n++){const s=e[n],r=t.getCol(s),o=i[n];r.init((e=>o[e]))}const a=Date.now();ls.logger.debug(`MLB: MlbVrSpaceBrowser.buildView(), postprocess reduceDimensionality ET: ${(a-o)/1e3} s`)}r=await t.plot.fromType(a.VIEWER.SCATTER_PLOT,{xColumnName:Rt.X,yColumnName:Rt.Y,lassoTool:!0})}return e.dockManager.dock(r,a.DOCK_TYPE.RIGHT,null,"Sequence Space",.35),r}(n,s,Kt),r.setOptions({color:"activity"})}),{description:"Reduce sequence space dimensionality to display on 2D representation.",delay:2e3}).step("Cluster sequences",(async()=>{const r=await e.calcDistanceMatrix(s,[Kt]),i=await Ut(r.data,s.rowCount,1),o=e.parseClusterMatrix(i);t.injectTreeForGrid(n.grid,o,void 0,150,void 0)}),{description:"Perform hierarchical clustering to reveal relationships between sequences.",delay:2e3}).step("Select a sequence",(async()=>{s.selection.set(65,!0)}),{description:"Handling selection of data frame row reflecting on linked viewers.",delay:2e3}).step("Select a bunch of sequences",(async()=>{[67,72,77,82,83,84,85,91,93].forEach((e=>s.selection.set(e,!0))),s.currentRowIdx=27}),{description:"Selecting a group of rows from a data frame to show their similarity and proximity to each other on a viewer..",delay:2e3}).start()}catch(e){Ft(e)}}()}async function dr(){await async function(){let e,t,n,s,r;const o=c.A.UMAP;try{const l=new kt("Activity Cliffs","Activity Cliffs analysis on Macromolecules data");await l.step("Load DNA sequences",(async()=>{i.shell.windows.showContextPanel=!1,i.shell.windows.showProperties=!1,[n,e,t]=await Promise.all([ls.files.readCsv(qt),Dt(),Bt()]),s=i.shell.addTableView(n),s.grid.props.rowHeight=22,s.grid.columns.byName("cluster").visible=!1,s.grid.columns.byName("sequence").width=300,s.grid.columns.byName("is_cliff").visible=!1}),{description:"Load dataset with macromolecules of 'fasta' notation, 'DNA' alphabet.",delay:2e3}).step("Find activity cliffs",(async()=>{const e=a.Func.find({name:"macromoleculePreprocessingFunction",package:"Bio"})[0];r=await Ls(n,n.getCol("Sequence"),n.getCol("Activity"),80,o,nt.U.LEVENSHTEIN,e,{}),s.dockManager.dock(r,a.DOCK_TYPE.RIGHT,null,"Activity Cliffs",.35),xt()(r.root).find("button.scatter_plot_link,cliffs_grid").get()[0].click()}),{description:"Reveal similar sequences with a cliff of activity.",delay:2e3}).step("Cluster sequences",(async()=>{const r=a.TaskBarProgressIndicator.create("Running sequence clustering..."),i=await e.calcDistanceMatrix(n,["sequence"]),o=await Ut(i.data,n.rowCount,1),l=e.parseClusterMatrix(o);r.close(),t.injectTreeForGrid(s.grid,l,void 0,150,void 0),s.grid.columns.byName("Activity").scrollIntoView()}),{description:"Perform hierarchical clustering to reveal relationships between sequences.",delay:2e3}).step("Browse the cliff",(async()=>{const e=r.dataFrame.temp[".cliffsDfGrid"];e.dataFrame.rowCount>0&&(e.dataFrame.currentRowIdx=0)}),{description:"Zoom in to explore selected activity cliff details.",delay:2e3}).start()}catch(e){Ft(e)}}()}async function mr(){await async function(){const e="HELM";let t,n,s;try{await new kt("Atomic Level","Atomic level structure of Macromolecules").step("Loading Macromolecules notation 'Helm'",(async()=>{i.shell.windows.showContextPanel=!1,i.shell.windows.showProperties=!1,t=await ls.files.readCsv("samples/HELM.csv"),n=i.shell.addTableView(t);for(let t=0;t<n.grid.columns.length;t++){const s=n.grid.columns.byIndex(t);[e,"Activity"].includes(s.name)||(s.visible=!1)}}),{description:"Load dataset with macromolecules of 'fasta' notation, 'PT' alphabet (protein, aminoacids).",delay:2e3}).step("To atomic level",(async()=>{const n=t.getCol(e);await ks(t,n,!1)}),{description:"Get atomic level structures of Macromolecules.",delay:2e3}).step("Sketcher",(async()=>{const n=`molfile(${e})`;t.currentCell=t.cell(1,n);const r=t.currentCell.value,i=new a.chem.Sketcher(a.chem.SKETCHER_MODE.INPLACE);i.setMolFile(r),s=o.dialog().add(i).show(),await(0,We.gw)(3e3),s.close()}),{description:"Display atomic level structure within a sketcher.",delay:2e3}).start()}catch(e){Ft(e)}}()}async function pr(){await async function(){let e,t,n,s,r,o;const l="msa(HELM)",u=c.A.UMAP,h=(await zt.lp.getDockerContainer()).id,d=zt.lp.getDockerContainer();let m,p;try{const c=new kt("Helm, MSA, Sequence Space","MSA and composition analysis on Helm data");await c.step("Load peptides with non-natural aminoacids in 'HELM' notation",(async()=>{[m,t]=await Promise.all([(async()=>(await d).status)(),ls.files.readCsv(Xt)]),e=i.shell.addTableView(t),i.shell.windows.showContextPanel=!1,i.shell.windows.showProperties=!1,"started"===m||"checking"===m?(ls.logger.debug(`demoBio05UI(), PepSeA ('${zt.lp.dcName}') docker container status = '${m}'.`),p=Promise.resolve()):(ls.logger.warning(`demoBio05UI(), PepSeA ('${zt.lp.dcName}') docker container is trying to start...`),await i.dapi.docker.dockerContainers.run(h),p=async function(e,t,n=3e4,s){const r=window.performance.now(),o=new y.Subject,a=async()=>{const n=await i.dapi.docker.dockerContainers.find(e);return n.status===t&&o.next(n),n};let l;try{await(0,We.zg)(o,(e=>{const n=window.performance.now();s.debug(`awaitStatus(), docker container ('${e.name}') GET status = '${t}' in ${n-r} ms.`)}),(async()=>{const e=await a();s.debug(`awaitStatus(), docker container ('${e.name}') HAS status = '${e.status}'.`),l=window.setInterval(a,200)}),n)}finally{window.clearInterval(l)}}(h,"started",3e4,ls.logger))}),{description:"Load dataset with macromolecules of 'Helm' notation.",delay:2e3}).step("Align peptides with non-natural aminoacids with PepSeA",(async()=>{const e=a.TaskBarProgressIndicator.create("MSA by PepSeA ...");try{await p,n=t.getCol("HELM");const e=zt.Jy[0],r=1.53,o=0;if(s=await(0,zt.f3)(n,l,e,r,o,void 0),!s)throw new Error("Empty MSA result.");t.columns.add(s),await i.data.detectSemanticTypes(t)}finally{e.close()}}),{description:"Multiple sequence alignment (MSA) performed with PepSeA tool operating on non-natural aminoacids as well.",delay:2e3}).step("Build sequence space",(async()=>{const n=a.Func.find({package:"Bio",name:"macromoleculePreprocessingFunction"})[0];o=await Os(t,s,u,nt.U.LEVENSHTEIN,!0,n),e.dockManager.dock(o,a.DOCK_TYPE.RIGHT,null,"Sequence Space",.35)}),{description:"Reduce sequence space dimensionality to display on 2D representation.",delay:2e3}).step("Analyse sequence composition",(async()=>{r=await t.plot.fromType("WebLogo",{sequenceColumnName:l,positionWidth:40,maxHeight:50}),e.dockManager.dock(r,a.DOCK_TYPE.DOWN,null,"Composition analysis",.2)}),{description:"Composition analysis allows to reveal functional features of sequences like motifs, or variable loops.",delay:2e3}).start()}catch(e){Ft(e)}}()}async function fr(e,t){var n;(function(e){e.setTag("quality",a.SEMTYPE.MACROMOLECULE),e.setTag("aligned","SEQ"),e.setTag("alphabet","PT")})(n=t),n.setTag("units",Me.r2.SEPARATOR),n.setTag("separator","-"),await i.data.detectSemanticTypes(e)}async function gr(e){const t=await e.readAsString(),n=new zn(e.fileName,t),s=await n.getJson(),r=e.fileName.replace(/\.csv$/,".json"),i=JSON.stringify(s,null,2);a.Utils.download(r,i)}async function yr(e){const t=(0,me.Xk)(e),n=JSON.stringify(t);a.Utils.download(`${e.name}.json`,n)}async function br(e,t,n){const s=await e.readAsString();await async function(e,t,n){const s=a.TaskBarProgressIndicator.create("detectMacromolecule probe ...");try{let r=0;const o=await i.functions.call("Bio:detectMacromoleculeEnableStore");let l=0;for(let c=0;c<n;++c){const u=a.DataFrame.fromCsv(e),h=t?u.getCol(t):u.columns.byIndex(0);await i.functions.call("Bio:detectMacromolecule",{col:h})!==a.SEMTYPE.MACROMOLECULE&&(++l,console.warn(`Reject reason: ${o.last.rejectReason}`));const d=c/n;d-r>=.1&&(r=d,s.update(100*d,`detectMacromolecule probe ${l}/${c}/${n} ...`),await(0,We.gw)(0))}l>0?i.shell.warning(`detectMacromolecule failed ${l} / ${n}`):i.shell.info(`detectMacromolecule success ${n}`)}finally{s.close()}}(s,t,n)}function vr(e,t){e.temp[he.dm.notationProvider]=new os(t)}},9017:(e,t,n)=>{"use strict";n.d(t,{k:()=>i});class s{constructor(){this.value=0,this.parentI=0,this.parentJ=0}}class r{constructor(e,t,n){this.seq1=e,this.seq2=t,this.score=n}}class i{fillNeedleman(){for(let e=0;e<=this.len1;e++)this.dpGrid[e][0].value=-e*this.gap,this.dpGrid[e][0].parentI=e-1,this.dpGrid[e][0].parentJ=0;for(let e=1;e<=this.len2;e++)this.dpGrid[0][e].value=-e*this.gap,this.dpGrid[0][e].parentI=0,this.dpGrid[0][e].parentJ=e-1}fillOne(e,t){this.dpGrid[e][t].value=Math.max(this.dpGrid[e-1][t-1].value+this.scores[e-1][t-1],Math.max(this.dpGrid[e-1][t].value-this.gap,this.dpGrid[e][t-1].value-this.gap)),this.dpGrid[e][t].value==this.dpGrid[e-1][t-1].value+this.scores[e-1][t-1]?(this.dpGrid[e][t].parentI=e-1,this.dpGrid[e][t].parentJ=t-1):this.dpGrid[e][t].value==this.dpGrid[e-1][t].value-this.gap?(this.dpGrid[e][t].parentI=e-1,this.dpGrid[e][t].parentJ=t):(this.dpGrid[e][t].parentI=e,this.dpGrid[e][t].parentJ=t-1)}gridFromName(e){switch(e){case"BLOSUM45":this.alignGrid=this.BLOSUM45,this.connections=this.CONBLO,this.step=1;break;case"BLOSUM50":this.alignGrid=this.BLOSUM50,this.connections=this.CONBLO,this.step=1;break;case"BLOSUM62":this.alignGrid=this.BLOSUM62,this.connections=this.CONBLO,this.step=1;break;case"BLOSUM80":this.alignGrid=this.BLOSUM80,this.connections=this.CONBLO,this.step=1;break;case"BLOSUM90":this.alignGrid=this.BLOSUM90,this.connections=this.CONBLO,this.step=1;break;case"PAM30":this.alignGrid=this.PAM30,this.connections=this.CONBLO,this.step=1;break;case"PAM70":this.alignGrid=this.PAM70,this.connections=this.CONBLO,this.step=1;break;case"PAM250":this.alignGrid=this.PAM250,this.connections=this.CONBLO,this.step=1;break;case"NUCLEOTIDES":this.alignGrid=this.NUCLEOTIDES,this.connections=this.CONNUCL,this.step=1;break;case"TRANS":this.alignGrid=this.TRANS,this.connections=this.CONNUCL,this.step=1;break;case"SCHNEIDER":this.alignGrid=this.SCHNEIDER,this.connections=this.CONSCHN,this.step=3}this.fillScores()}constructResult(e,t){let n="",s="",i="";const o=this.dpGrid[e][t].value;for(let e=0;e<this.step;e++)i+="|";for(;e>0||t>0;){this.dpGrid[e][t].parentI==e?(n=i+n,s=this.seq2.substr((t-1)*this.step,this.step)+s):this.dpGrid[e][t].parentJ==t?(s=i+s,n=this.seq1.substr((e-1)*this.step,this.step)+n):(n=e-1>=0?this.seq1.substr((e-1)*this.step,this.step)+n:i+n,s=t-1>=0?this.seq2.substr((t-1)*this.step,this.step)+s:i+s);const r=e;e=this.dpGrid[e][t].parentI,t=this.dpGrid[r][t].parentJ}return new r(n,s,o)}fillScores(){this.scores=[];for(let e=0;e<this.len1;e++){this.scores.push([]);for(let t=0;t<this.len2;t++)this.scores[e].push(this.alignGrid[this.connections[this.seq1.substr(e*this.step,this.step)]][this.connections[this.seq2.substr(t*this.step,this.step)]])}}typeRec(){if(/[ATGC]*/.test(this.seq1)&&/[ATGC]*/.test(this.seq2))return"NUCLEOTIDES";if(/[ARNDCQEGHILKMFPSTWYVBZX*]*/.test(this.seq1)&&/[ARNDCQEGHILKMFPSTWYVBZX*]*/.test(this.seq2))return"BLOSUM62";throw Error("Can't recognize sequence type")}needlemanWunch(){this.dpGrid=[];for(let e=0;e<this.len1+1;e++){const e=[];for(let t=0;t<this.len2+1;t++)e.push(new s);this.dpGrid.push(e)}this.fillNeedleman();for(let e=1;e<=this.len1;e++)for(let t=1;t<=this.len2;t++)this.fillOne(e,t);return this.constructResult(this.len1,this.len2)}smithWaterman(){this.dpGrid=[];for(let e=0;e<this.len1+1;e++){const e=[];for(let t=0;t<this.len2+1;t++)e.push(new s);this.dpGrid.push(e)}let e=0,t=0,n=0;for(let s=1;s<=this.len1;s++)for(let r=1;r<=this.len2;r++)this.fillOne(s,r),this.dpGrid[s][r].value<=0?(this.dpGrid[s][r].value=0,this.dpGrid[s][r].parentI=0,this.dpGrid[s][r].parentJ=0):0==this.dpGrid[this.dpGrid[s][r].parentI][this.dpGrid[s][r].parentJ].value&&(this.dpGrid[s][r].parentI=0,this.dpGrid[s][r].parentJ=0),this.dpGrid[s][r].value>e&&(e=this.dpGrid[s][r].value,t=s,n=r);return this.constructResult(t,n)}setSequences(e,t){this.seq1=e,this.seq2=t,this.len1=this.seq1.length/this.step,this.len2=this.seq2.length/this.step,this.fillScores()}setGap(e){this.gap=e}setMethod(e=""){"AUTO"==e&&(e=this.typeRec()),this.gridFromName(e)}constructor(e,t,n,s=""){this.seq1="",this.seq2="",this.gap=1,this.len1=0,this.len2=0,this.step=1,this.alignGrid=[],this.scores=[],this.dpGrid=[],this.connections={},this.BLOSUM45=[[5,-2,-1,-2,-1,-1,-1,0,-2,-1,-1,-1,-1,-2,-1,1,0,-2,-2,0,-1,-1,0,-5],[-2,7,0,-1,-3,1,0,-2,0,-3,-2,3,-1,-2,-2,-1,-1,-2,-1,-2,-1,0,-1,-5],[-1,0,6,2,-2,0,0,0,1,-2,-3,0,-2,-2,-2,1,0,-4,-2,-3,4,0,-1,-5],[-2,-1,2,7,-3,0,2,-1,0,-4,-3,0,-3,-4,-1,0,-1,-4,-2,-3,5,1,-1,-5],[-1,-3,-2,-3,12,-3,-3,-3,-3,-3,-2,-3,-2,-2,-4,-1,-1,-5,-3,-1,-2,-3,-2,-5],[-1,1,0,0,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15.5,-11.4,-13.7,-3,-6.4,-4.1,-5.4,-9.6,-11.9,-10.5,-11.8,6.2,3.3,3.7,3.6,-50,-13.6,-50,-11.9,-5.6,-8.8,-7.2,-8.9,-50,-12.4,-14.1,-11.6,2.8,-6.4,.5,-5.2],[-13,-7.9,-13.2,-9.5,-4.6,-1.2,-4.1,-3.4,-12.5,-6.3,-12.5,-8.5,9.6,12.7,.2,10.5,-12.4,-11.6,-13.2,-12,-12.4,-10.1,-11.6,-12,-15.1,-13.1,-14.3,-13.4,-1.4,1.4,-1.6,-.5,-14.9,-14.3,-15.2,-16.8,-7.7,-4.7,-6.3,-6.6,-14.6,-10.8,-12.8,-13,2.3,6,2.5,3.6,-50,-11.2,-50,-11.9,-10.5,-9.2,-10.5,-10.5,-50,-10.3,-16.2,-11.3,-1.7,-3.7,-2.5,-5.4],[-7.1,-9.9,-5.7,-9,-.4,-3,.9,-2.3,-7.2,-8.3,-5.3,-8,3.5,.2,14.3,1,-7.3,-11.2,-6.9,-9.7,-8.5,-10.2,-7.7,-9.8,-10,-10.4,-8.4,-10.2,1,-.6,1.7,-.5,-11.1,-14.8,-9.7,-14.5,-3.7,-5.8,-3.1,-5.6,-10.4,-11.5,-8.2,-11.1,.6,-1.6,1.6,-1.1,-50,-12.4,-50,-11.5,-5.5,-8,-4.9,-7.2,-50,-12.4,-10.3,-11.6,.7,-6.8,2.4,-6],[-11.5,-9.6,-12.6,-7,-3.6,-3.3,-3.5,-.6,-11.6,-7.7,-11.9,-5.3,9.7,10.5,1,12.6,-12,-12.2,-12.5,-9.7,-11.1,-11.2,-11.9,-9.4,-12.9,-14.3,-14,-11.9,-1,-.4,-1.6,1.2,-13.9,-15.4,-13.7,-12.6,-6.2,-6.7,-6.3,-4.4,-13,-12.2,-13,-10.4,2.9,3.8,2.5,5.8,-50,-12.5,-50,-10.2,-9.6,-9.7,-9.6,-8.3,-50,-11.6,-15.4,-9.4,-1.1,-5.4,-1.6,-3.3],[.4,-5,-1.5,-4,-4.8,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5,8.9,12,-50,-13,-50,-10.3,-6.2,-7,-7.1,-5.4,-50,-9.3,-14,-8.2,-2.4,-6.3,-2.4,-3.9],[-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,33.3,-50,30.6,-50,-50,-50,-50,-50,29.2,-50,-50,-50,-50,-50,-50,-50],[-14.8,-6.2,-14.9,-7.6,-14.6,-11.6,-13,-12.2,-14,-9,-14.1,-10.1,-13.6,-11.2,-12.4,-12.5,-8.1,2.2,-8.7,.4,-15.3,-11.3,-13.2,-13.3,-11.9,-7.2,-11.8,-7.9,-10.7,-7.4,-10.8,-8.9,-15.5,-10.3,-15.5,-12.5,-14.5,-12.1,-11.9,-12.8,-18.3,-12.7,-16.4,-14.7,-14.2,-10.4,-13.7,-13,-50,15.1,-50,13.3,-9.9,-5.8,-8.9,-7.6,-50,-1.5,-7.8,-3,-8.1,3.6,-9.4,2],[-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,30.6,-50,35.2,-50,-50,-50,-50,-50,28.5,-50,-50,-50,-50,-50,-50,-50],[-13.8,-7.5,-14.4,-5.1,-12.6,-11.6,-11.5,-10.1,-13.2,-9.7,-12.7,-7.4,-11.9,-11.9,-11.5,-10.2,-7.2,.9,-8.6,2.6,-14.1,-12.8,-13.3,-11,-9.7,-8.4,-11.2,-5.3,-9.3,-8.7,-9.9,-7.1,-13.9,-11.2,-14.2,-8.9,-12.9,-12.6,-12.6,-10.9,-15.4,-13.8,-14.8,-11.4,-12.8,-11.6,-13.2,-10.3,-50,13.3,-50,15.2,-8.6,-7,-8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,-9.4,-9.4,-6.6,-9.6,-9.7,-10,-7.9,.7,.6,.8,2.3,-7.1,-6.5,-7.2,-5,-6.5,-7.4,-7.5,-5.4,-50,-7.6,-50,-4.8,9.8,10,10.2,12.1,-50,-3.1,-11.4,-.7,-4.6,-6.6,-4.9,-3.9],[-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,29.2,-50,28.5,-50,-50,-50,-50,-50,33.3,-50,-50,-50,-50,-50,-50,-50],[-13,-7,-13.1,-8.3,-9.2,-6.5,-8.9,-7.6,-9.8,-.7,-9.2,-2.1,-12.4,-10.3,-12.4,-11.6,-9.5,-4.6,-10.4,-5.7,-13.6,-10.1,-11.4,-10.9,-6.5,-1.5,-6.2,-3.6,-12.8,-8,-12.3,-9.7,-16.5,-12.7,-15.6,-14.3,-8.7,-6,-7.1,-7.5,-9.5,-4.1,-8.4,-6.1,-11,-8.6,-11.3,-9.3,-50,-1.5,-50,-3,-4.8,-1.5,-4.2,-3.1,-50,16.4,-5.1,14.2,-10.1,-4.3,-10,-5.4],[-13.5,-16.3,-11.8,-15.5,-13.6,-15.3,-12.1,-16.1,-7.7,-13.3,-4.2,-12.6,-14.1,-16.2,-10.3,-15.4,-9.6,-11.6,-7.7,-9.8,-14.3,-17.5,-11.1,-17.2,-5.3,-7.1,-2.2,-7.1,-9.6,-11.9,-8.7,-11.4,-17.1,-20.6,-15.3,-19.9,-14.1,-14.8,-12.4,-16.5,-11.7,-12.8,-6.4,-13.4,-14.3,-15.7,-12.7,-14,-50,-7.8,-50,-7.1,-8.7,-11.3,-6.1,-11.4,-50,-5.1,18.6,-4.8,-8.6,-8.1,-4.5,-7.3],[-12.4,-8.2,-13,-5.9,-7.7,-7.8,-7.4,-5.8,-8.8,-2,-9.3,-.4,-11.6,-11.3,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.6,-10.3,-13.7,-.7,-3.2,-.3,-2.4,-50,-9.4,-50,-8.7,-2.1,-5.6,-1.2,-4.9,-50,-10,-4.5,-8.9,9.7,-1.8,11.3,-.9],[-17.2,-13.3,-17.8,-11.6,-11,-11.1,-10.4,-9,-16,-12.7,-16.1,-11.1,-5.2,-5.4,-6,-3.3,-11.8,-7.3,-13.3,-5.9,-12.7,-11.9,-11.9,-9.3,-15.2,-15,-14.9,-11,-2.8,-1.8,-2.9,.4,-17.4,-18.4,-18.3,-15.9,-10.7,-11.2,-10.6,-9,-15.4,-14.8,-15.8,-13.3,-6.8,-5.9,-7.2,-3.9,-50,2,-50,3.9,-7,-6.8,-6.8,-3.9,-50,-5.4,-7.3,-3.4,-.3,11.6,-.9,14.1]],this.TRANS=[[5,0,0,4],[0,5,4,0],[0,4,5,0],[4,0,0,5]],this.CONBLO={A:0,R:1,N:2,D:3,C:4,Q:5,E:6,G:7,H:8,I:9,L:10,K:11,M:12,F:13,P:14,S:15,T:16,W:17,Y:18,V:19,B:20,Z:21,X:22,"*":23},this.CONNUCL={A:0,T:1,C:2,G:3},this.CONSCHN={AAA:0,AAC:1,AAG:2,AAT:3,ACA:4,ACC:5,ACG:6,ACT:7,AGA:8,AGC:9,AGG:10,AGT:11,ATA:12,ATC:13,ATG:14,ATT:15,CAA:16,CAC:17,CAG:18,CAT:19,CCA:20,CCC:21,CCG:22,CCT:23,CGA:24,CGC:25,CGG:26,CGT:27,CTA:28,CTC:29,CTG:30,CTT:31,GAA:32,GAC:33,GAG:34,GAT:35,GCA:36,GCC:37,GCG:38,GCT:39,GGA:40,GGC:41,GGG:42,GGT:43,GTA:44,GTC:45,GTG:46,GTT:47,TAA:48,TAC:49,TAG:50,TAT:51,TCA:52,TCC:53,TCG:54,TCT:55,TGA:56,TGC:57,TGG:58,TGT:59,TTA:60,TTC:61,TTG:62,TTT:63},this.setMethod(s),this.setSequences(e,t),this.setGap(n)}}},7983:(e,t,n)=>{"use strict";n.d(t,{HV:()=>p,QF:()=>m,pf:()=>d,uH:()=>h});var s=n(4469),r=n(3870),i=n(976),o=n(7241),a=n(4293),l=n(8467),c=n(8447);const u="substr_helm";class h{constructor(e){this.col=e[0],this.createUI()}editHelmLinkAction(){(0,a.Y)(this.inputsDiv,this.grid.root),r.tools.waitForElementInDom(this.grid.root).then((()=>{setTimeout((()=>{this.grid.cell(u,0).element.children[0].dispatchEvent(new KeyboardEvent("keydown",{key:"Enter"}))}),100)}))}updateInputs(){const e=this.units===c.r2.HELM?r.divV([this.columnsInput,this.editHelmLink]):this.units===c.r2.SEPARATOR?r.inputs([this.columnsInput,this.substructureInput,this.separatorInput]):r.inputs([this.columnsInput,this.substructureInput]);(0,a.Y)(this.inputsDiv,e)}updateNotationDiv(){this.units=this.col.getTag(i.TAGS.UNITS),this.separator=this.col.getTag("separator");const e=this.dialog.root.getElementsByClassName("notation-text")[0];e&&(e.textContent=`Notation: ${this.units}`)}createUI(){const e=s.shell.tv.dataFrame,t={filter:e=>e.semType===i.SEMTYPE.MACROMOLECULE};this.columnsInput=r.columnInput("Column",e,this.col,(e=>{this.col=e,this.updateNotationDiv(),this.updateInputs()}),t),this.substructureInput=r.stringInput("Substructure",""),this.editHelmLink=r.link("Edit helm",(()=>this.editHelmLinkAction()),void 0,{style:{position:"relative",left:"95px"}});const n=i.DataFrame.create(1);n.columns.addNewString(u).init((e=>"")),n.col(u).semType=this.col.semType,n.col(u).setTag(i.TAGS.UNITS,c.r2.HELM),this.grid=n.plot.grid(),this.separatorInput=r.stringInput("Separator",this.separator),this.inputsDiv=r.div(),this.units=this.col.getTag(i.TAGS.UNITS),this.separator=this.col.getTag("separator"),this.updateInputs(),this.dialog=r.dialog("Substructure Search").add(r.divV([r.divText(`Notation: ${this.units}`,"notation-text"),this.inputsDiv])).onOK((async()=>{let e,t=this.units===c.r2.HELM?n.get(u,0):this.substructureInput.value;this.units===c.r2.SEPARATOR&&this.separatorInput.value!==this.separator&&""!==this.separatorInput.value&&(t=t.replaceAll(this.separatorInput.value,this.separator)),e=this.units===c.r2.HELM?await m(t,this.col):d(t,this.col),this.col.dataFrame.filter.and(e)})).show()}}function d(e,t,n){const s=n?function(e,t){const n=`${t}`.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),s=e.charAt(0)===t,r=e.charAt(e.length-1)===t,i=e.replace(new RegExp(`^${n}|${n}$`,"g"),"");return s?r?`${n}${i}${n}`:`${n}${i}${n}|${n}${i}$`:r?`^${i}${n}|${n}${i}${n}`:`^${i}${n}|${n}${i}${n}|${n}${i}$`}(e,n):e,r=i.BitSet.create(t.length);for(let n=0;n<t.length;n++){const i=t.get(n);(i.match(s)||i===e)&&r.set(n,!0,!1)}return r}async function m(e,t){t.version!==t.temp["last-invalidated-version"]&&await p(t,!0);const n=i.Column.string("helm",1).init((t=>e));n.semType=i.SEMTYPE.MACROMOLECULE,n.setTag(i.TAGS.UNITS,c.r2.HELM);const r=await(0,o.D)(n,!0,t.temp["monomers-dict"]);return(await s.functions.call("Chem:searchSubstructure",{molStringsColumn:t.temp["monomeric-mols"],molString:r.get(0),molBlockFailover:""})).get(0)}async function p(e,t){const n=i.TaskBarProgressIndicator.create(`Invalidating molfiles for ${e.name}`);try{await(0,l.gw)(10);const n=new Map,s=await(0,o.D)(e,t,n);e.temp["monomeric-mols"]=s,e.temp["monomers-dict"]=n,e.temp["last-invalidated-version"]=e.version}finally{n.close()}}},2568:(e,t,n)=>{"use strict";n.d(t,{n:()=>o});var s=n(4469),r=n(976),i=n(8260);function o(e,t,n=[],o=[],a=!0){const[l,c]=function(e,t,n=[],o=[]){let a=!0,l="";const c=i.g.forColumn(e);if(e.semType!==r.SEMTYPE.MACROMOLECULE)s.shell.warning(t+" analysis is allowed for Macromolecules semantic type"),a=!1;else{const e=c.notation;if(n.length>0&&!n.some((t=>e.toUpperCase()==t.toUpperCase())))l=`${t} + ' analysis is allowed for Macromolecules with notation ${0==n.length?"any notation":`notation${n.length>1?"s":""} ${n.map((e=>`"${e}"`)).join(", ")} `}.`,a=!1;else if(!c.isHelm()){const e=c.alphabet;o.length>0&&!o.some((t=>e.toUpperCase()==t.toUpperCase()))&&(l=`${t} + ' analysis is allowed for Macromolecules with alphabet ${0==o.length?"any alphabet":`alphabet${o.length>1?"s":""} ${o.map((e=>`"${e}"`)).join(", ")}.`}.`,a=!1)}}return[a,l]}(e,t,n,o);return a&&!l&&s.shell.warning(c),l}},3553:(e,t,n)=>{"use strict";n.d(t,{Of:()=>i,WY:()=>c,jB:()=>u,rs:()=>a});var s,r,i,o,a,l=n(8341);!function(e){e.SPLIT_COL="~split",e.ACTIVITY="~activity",e.ACTIVITY_SCALED="activity_scaled",e.ALIGNED_SEQUENCE="~aligned_sequence",e.AMINO_ACID_RESIDUE="AAR",e.POSITION="Pos",e.P_VALUE="pValue",e.MEAN_DIFFERENCE="Mean difference"}(s||(s={})),function(e){e.AAR="AAR",e.POSITION="Pos",e.SELECTION="selection"}(r||(r={})),function(e){e.MONOMER="Monomer",e.MACROMOLECULE_DIFFERENCE="MacromoleculeDifference",e.ACTIVITY="activity",e.ACTIVITY_SCALED="activityScaled"}(i||(i={})),function(e){e.CELL_CHANGING="isCellChanging"}(o||(o={})),function(e){e.SEPARATOR="."}(a||(a={}));const c="3.3.1",u={pepsea:{gapOpen:1.53,gapExtend:0,method:l.Jy[0]},kalign:{gapOpen:-1,gapExtend:-1,terminalGap:-1}}},4004:(e,t,n)=>{"use strict";n.d(t,{O:()=>d});var s=n(976),r=n(3870),i=n(4469),o=n(3336),a=n.n(o),l=n(8447),c=n(8260);let u=null,h=[];function d(e){let t=e??i.shell.t.columns.bySemType("Macromolecule");if(!t)throw new Error("No column with Macromolecule semantic type found");let n=c.g.forColumn(t),o=n.notation;const d=r.divText("Current notation: "+o,{style:{"text-align":"center","font-weight":"bold","font-size":"14px",padding:"5px"}}),m=[l.r2.FASTA,l.r2.SEPARATOR,l.r2.HELM],p=r.columnInput("Column",i.shell.t,t,(e=>{e.semType===s.SEMTYPE.MACROMOLECULE?(t=e,n=c.g.forColumn(t),o=n.notation,o===l.r2.HELM&&(y.value="/"),d.textContent="Current notation: "+o,g=m.filter((e=>e!==o)),v=r.choiceInput("Convert to",g[0],g,b),b(),u?.clear(),u?.add(r.div([d,p.root,v.root,y.root]))):p.value=t})),f=["-",".","/"];let g=m.filter((e=>e!==o));const y=r.choiceInput("Separator",f[0],f),b=()=>{v.value!==l.r2.SEPARATOR?a()(y.root).hide():a()(y.root).show()};let v=r.choiceInput("Convert to",g[0],g,b);b(),v.onChanged((()=>{b()})),null==u&&(u=r.dialog("Convert Sequence Notation").add(r.div([d,p.root,v.root,y.root])).onOK((async()=>{const e=v.value,n=y.value??void 0;await async function(e,t,n){const s=c.g.forColumn(e).convert(t,n);e.dataFrame.columns.add(s);const r=await i.functions.call("Bio:detectMacromolecule",{col:s});return r&&(s.semType=r),await i.data.detectSemanticTypes(e.dataFrame),s}(t,e,n)})).show({x:350,y:100}),h.push(u.onClose.subscribe((e=>{h.forEach((e=>{e.unsubscribe()})),h=[],u=null}))))}},6032:(e,t,n)=>{"use strict";n.d(t,{Ns:()=>o});var s=n(4469),r=n(8467),i=n(8341);async function o(e=6e4){const t=await i.lp.getDockerContainer();await async function(e,t=6e4){let n=e,i=!1;for(let o=0;o<t/200;++o){if(null===n&&(n=await s.dapi.docker.dockerContainers.find(e.id)),a(n)){i=!0;break}switch(n.status){case"stopped":await s.dapi.docker.dockerContainers.run(n.id);break;case"pending change":case"changing":break;case"error":throw new Error("Docker container error state.")}n=null,await(0,r.gw)(200)}if(!i)throw new Error("Docker container start timeout.")}(t,e)}function a(e){return"checking"===e.status||"started"===e.status}},7572:(e,t,n)=>{"use strict";n.d(t,{A:()=>u});var s=n(4469),r=n(6584),i=n(2961),o=n(3776),a=n(2428),l=n(3649);async function c(){const e=a.A.getInstance();return(await o.t.getInstance(e)).getValidLibraryPaths()}class u{constructor(){this._monomerLib=new i.B({},"MAIN"),this.loadLibrariesPromise=Promise.resolve()}getBioLib(){return this._monomerLib}async loadLibraries(e=!1){return this.loadLibrariesPromise=this.loadLibrariesPromise.then((async()=>{try{const[t,n]=await Promise.all([c(),(0,r.nW)()]),s=t.filter((e=>{const t=!n.exclude.includes(e),s=0===n.explicit.length||n.explicit.includes(e);return t&&s})),o=await Promise.all(s.map((e=>this.readLibrary(r.BX,e).catch((t=>{const n=`Loading monomers from '${e}' error: ${t instanceof Error?t.message:t.toString()}`;return new i.B({},e,n)})))));this._monomerLib.updateLibs(o,e)}catch(e){const t=`Loading monomer libraries error: ${e instanceof Error?e.message:e.toString()}`;s.shell.warning(t);const n=e instanceof Error?e.stack:void 0;l._package.logger.error(t,void 0,n)}}))}async readLibrary(e,t){const n=a.A.getInstance(),s=await o.t.getInstance(n);return await s.loadLibraryFromFile(e,t)}async selectSpecifiedLibraries(e){const t=await this.getInvalidFileNames(e);if(t.length>0)throw new Error(`Cannot select libraries ${t}: no such library in the list`);const n=await(0,r.nW)();n.exclude=(await c()).filter((t=>!e.includes(t))),await(0,r.tW)(n)}async getInvalidFileNames(e){const t=await c();return e.filter((e=>!t.includes(e)))}static get instance(){return window.$monomerLibHelper||(window.$monomerLibHelper=new u),window.$monomerLibHelper}}},2428:(e,t,n)=>{"use strict";n.d(t,{A:()=>i});var s=n(701),r=n(442);class i{constructor(){this._libraryFilesUpdateSubject$=new s.BehaviorSubject([]),this._addLibraryFilesSubject$=new s.Subject,this._librarySelectionSubject$=new s.Subject}static getInstance(){return i._instance||(i._instance=new i),i._instance}getValidFilesPathList(){return this._libraryFilesUpdateSubject$.getValue()}async getValidLibraryPathsAsynchronously(){return new Promise((e=>{this._libraryFilesUpdateSubject$.pipe((0,r.skip)(1)).subscribe((t=>{e(t)}))}))}changeValidFilesPathList(e){this._libraryFilesUpdateSubject$.next(e)}get updateUIControlsRequested$(){return this._libraryFilesUpdateSubject$.pipe()}get updateValidLibraryFileListRequested$(){return this._libraryFilesUpdateSubject$.pipe()}get addLibraryFileRequested$(){return this._addLibraryFilesSubject$.pipe()}addLibraryFile(){this._addLibraryFilesSubject$.next()}get librarySelectionRequested$(){return this._librarySelectionSubject$}updateLibrarySelectionStatus(e,t){this._librarySelectionSubject$.next([e,t])}}},3776:(e,t,n)=>{"use strict";n.d(t,{t:()=>m});var s=n(4469),r=n(976),i=n(6584),o=n(2961),a=n(5128),l=n.n(a),c=n(3351),u=n.n(c);class h{constructor(e){this.helmMonomerSchema=e;const t=new(l())({allErrors:!0,strictTuples:!1});u()(t),this.validateMonomerSchema=t.compile(this.helmMonomerSchema)}validateFile(e,t){const n=this.parseJson(e);return null!==n&&(Array.isArray(n)?this.validateJsonContent(n,t):(console.warn("Bio: Monomer Library File Validator: Invalid JSON format: The file must contain an array of monomers."),!1))}parseJson(e){try{return JSON.parse(e)}catch(e){return console.error("Bio: Monomer Library File Validator: Invalid JSON format:",e),null}}validateJsonContent(e,t){let n=!0;for(const s of e)if(n=this.validateMonomerSchema(s),!n){console.warn(`Bio: Monomer Library File Validator:\nfile ${t}\n monomer violating JSON schema:`,s,"\nError reason: ",this.validateMonomerSchema.errors,`\nThere may be other errors in ${t} since the validation is stopped after the first error.`," Please, verify that the monomer library file satisfies the JSON schema");break}return n}}var d=n(7572);class m{constructor(e,t){this.libraryFileValidator=e,this.libraryEventManager=t,this.libraryEventManager.updateValidLibraryFileListRequested$.subscribe((async()=>{await this.updateValidLibraryList()}))}static async getInstance(e){return m.instancePromise||(m.instancePromise=(async()=>{const t=await s.dapi.files.readAsText("System:AppData/Bio/tests/libraries/HELMmonomerSchema.json"),n=JSON.parse(t),r=new h(n);return new m(r,e)})()),m.instancePromise}async addLibraryFile(e,t){try{if(await this.libraryFileExists(t))return void s.shell.error(`File ${t} already exists`);await this.validateAgainstHELM(e,t),await s.dapi.files.writeAsText(i.BX+`${t}`,e),await this.updateValidLibraryList(),await s.dapi.files.exists(i.BX+`${t}`)?s.shell.info(`Added ${t} HELM library`):s.shell.error(`Failed to add ${t} library`)}catch(e){console.error(e),s.shell.error(`Failed to add ${t} library`)}}async deleteLibraryFile(e){try{await s.dapi.files.delete(i.BX+`${e}`),await this.updateValidLibraryList(),s.shell.info(`Deleted ${e} library`)}catch(t){console.error(t),await s.dapi.files.exists(i.BX+`${e}`)?s.shell.error(`Failed to delete ${e} library`):s.shell.warning(`File ${e} already deleted, refresh the list`)}}async loadLibraryFromFile(e,t){let n=[];const s=new r.FileSource(e),i=await s.readAsText(t);n=JSON.parse(i);const a={},l=[];return n.forEach((e=>{l.includes(e.polymerType)||(a[e.polymerType]={},l.push(e.polymerType)),a[e.polymerType][e.symbol]=e})),new o.B(a,t)}getValidLibraryPaths(){return this.libraryEventManager.getValidFilesPathList()}async getValidLibraryPathsAsynchronously(){return await this.libraryEventManager.getValidLibraryPathsAsynchronously()}async libraryFileExists(e){return await s.dapi.files.exists(i.BX+`${e}`)}async updateValidLibraryList(){const e=[],t=await this.getFilePathsAtDefaultLocation();if(!this.fileListHasChanged(t))return;for(const n of t){if(!n.endsWith(".json")){e.push(n);continue}const t=await s.dapi.files.readAsText(i.BX+`${n}`);this.isValidHELMLibrary(t,n)||e.push(n)}const n=t.filter((t=>!e.includes(t)));if(this.fileListHasChanged(n)&&(this.libraryEventManager.changeValidFilesPathList(n),d.A.instance.loadLibraries(!0)),n.some((e=>!e.endsWith(".json")))&&console.warn(`Wrong validation: ${n}`),e.length>0){const t=`Invalid monomer library files in ${i.BX}, consider fixing or removing them: ${e.join(", ")}`;console.warn(t)}}fileListHasChanged(e){const t=this.libraryEventManager.getValidFilesPathList();return e.length!==t.length||e.some(((e,n)=>e!==t[n]))}async validateAgainstHELM(e,t){if(!this.isValidHELMLibrary(e,t))throw new Error(`File ${t} does not satisfy HELM standard`)}isValidHELMLibrary(e,t){return this.libraryFileValidator.validateFile(e,t)}async getFilePathsAtDefaultLocation(){const e=(await s.dapi.files.list(i.BX)).map((e=>e.fullPath)),t=[];for(const n of e)await s.dapi.files.exists(n)&&t.push(n);return t.map((e=>e.substring(i.BX.length)))}}},2961:(e,t,n)=>{"use strict";n.d(t,{B:()=>C});var s=n(4469),r=n(3870),i=n(701),o=n(4067),a=n(3379),l=n.n(a),c=n(7795),u=n.n(c),h=n(569),d=n.n(h),m=n(3565),p=n.n(m),f=n(9216),g=n.n(f),y=n(4589),b=n.n(y),v=n(8277),w={};w.styleTagTransform=b(),w.setAttributes=p(),w.insert=d().bind(null,"head"),w.domAPI=u(),w.insertStyleElement=g(),l()(v.Z,w),v.Z&&v.Z.locals&&v.Z.locals;class C{constructor(e,t=undefined,n=undefined){this.source=t,this.error=n,this._monomers={},this._onChanged=new i.Subject,this._monomers=e;for(const[e,t]of Object.entries(this._monomers))for(const[e,n]of Object.entries(t))n.lib=this}getMonomer(e,t){return e in this._monomers&&t in this._monomers[e]?this._monomers[e][t]:null}getPolymerTypes(){return Object.keys(this._monomers)}getMonomerMolsByPolymerType(e){const t={};return Object.keys(this._monomers[e]??{}).forEach((n=>{t[n]=this._monomers[e][n].molfile})),t}getMonomerSymbolsByType(e){return Object.keys(this._monomers[e])}getMonomerSymbolsByRGroup(e,t,n){let s=this.getMonomerSymbolsByType(t).map((e=>this.getMonomer(t,e)));return s=s.filter((e=>null!==e)),0===s.length?[]:(s=s.filter((t=>{if(!t?.rgroups)return!1;let n=t?.rgroups.length>=e;return o._.getInstance(t.molfile).atomTypes.map(((e,t)=>"R#"===e?t:-1)).filter((e=>-1!==e)),n&&(n=!0),n})),s.map((e=>e?.symbol)))}get onChanged(){return this._onChanged}_updateInt(e){const t=e.getPolymerTypes(),n=this.getPolymerTypes();t.forEach((t=>{n.includes(t)||(this._monomers[t]={}),e.getMonomerSymbolsByType(t).forEach((n=>{this._monomers[t][n]=e.getMonomer(t,n)}))}))}update(e){this._updateInt(e),this._onChanged.next()}updateLibs(e,t=!1){t&&(this._monomers={});for(const t of e)t.error||this._updateInt(t);this._onChanged.next()}clear(){this._monomers={},this._onChanged.next()}getTooltip(e,t){const n=r.div([],{classes:"ui-form ui-tooltip"}),i=this.getMonomer(e,t);if(i){const e=e=>r.label(e,{classes:"ui-input-label"});n.append(r.div([e("Name"),r.divText(i.name,{classes:"ui-input-text"})],{classes:"ui-input-root"}));const t={autoCrop:!0,autoCropMargin:0,suppressChiralText:!0};i.molfile?n.append(r.div([e("Mol file"),s.chem.svgMol(i.molfile,void 0,void 0,t)],{classes:"ui-input-root"})):i.smiles?n.append(r.div([e("Smiles"),s.chem.svgMol(i.smiles,void 0,void 0,t)],{classes:"ui-input-root"})):n.append(r.div([e("No structure")],{classes:"ui-input-root"})),n.append(r.div([e("Source"),r.divText(i.lib?.source??"unknown",{classes:"ui-input-text"})],{classes:"ui-input-root"}))}else n.append(r.divText("Monomer not found"));return n}}},525:(e,t,n)=>{"use strict";n.d(t,{K:()=>M});var s=n(4469),r=n(976),i=n(3870),o=n(8447),a=n(8260),l=n(6098),c=n(8341),u=n(2568),h=n(3553),d=n(6032),m=n(3649),p=n(3379),f=n.n(p),g=n(7795),y=n.n(g),b=n(569),v=n.n(b),w=n(3565),C=n.n(w),S=n(9216),A=n.n(S),x=n(4589),E=n.n(x),I=n(9564),T={};T.styleTagTransform=E(),T.setAttributes=C(),T.insert=v().bind(null,"head"),T.domAPI=y(),T.insertStyleElement=A(),f()(I.Z,T),I.Z&&I.Z.locals&&I.Z.locals;class _ extends Error{constructor(e,t){super(e,t)}}async function M(e={}){return new Promise((async(t,n)=>{var o,a,l;e.clustersCol??(e.clustersCol=null),e.pepsea??(e.pepsea={}),(o=e.pepsea).method??(o.method=h.jB.pepsea.method),(a=e.pepsea).gapOpen??(a.gapOpen=h.jB.pepsea.gapOpen),(l=e.pepsea).gapExtend??(l.gapExtend=h.jB.pepsea.gapExtend);const u=e.col?.dataFrame??s.shell.t,d=e.col??u.columns.bySemType(r.SEMTYPE.MACROMOLECULE);if(null==d){const e="MSAError: dataset doesn't conain any Macromolecule column";s.shell.warning(e),n(new _(e))}const m=i.choiceInput("Method",e.pepsea.method,c.Jy);m.setTooltip("Alignment method");const p=i.floatInput("Terminal gap",e?.kalign?.terminalGap??null);p.setTooltip("Penalty for opening a gap at the beginning or end of the sequence");const f=i.p(`Kalign version: ${h.WY}`,"kalign-version"),g=i.floatInput("Gap open",e.pepsea.gapOpen);g.setTooltip("Gap opening penalty at group-to-group alignment");const y=i.floatInput("Gap extend",e.pepsea.gapExtend);y.setTooltip("Gap extension penalty to skip the alignment");const b=i.inputs([g,y,p]),v=i.button("Alignment parameters",(()=>{b.hidden=!b.hidden,[g,y,p].forEach((e=>{e.root.style.removeProperty("max-width"),e.captionLabel.style.removeProperty("max-width")}))}),"Adjust alignment parameters such as penalties for opening and extending gaps");v.classList.add("msa-params-button"),b.hidden=!0,v.prepend(i.icons.settings((()=>null)));const w=[m.root.style],C=[p.root.style,f.style];let S;const A=i.columnInput("Sequence",u,d,(async()=>{S=await N(A.value,u,w,C,m,x,g,y,p)}),{filter:e=>e.semType===r.SEMTYPE.MACROMOLECULE});A.setTooltip("Sequences column to use for alignment");const x=i.columnInput("Clusters",u,e.clustersCol);if(x.nullable=!0,A.fireChanged(),e.col)return S=await N(e.col,u,w,C,m,x,g,y,p),void await $(A,u,S,t,n);i.dialog("MSA").add(A).add(x).add(m).add(b).add(v).add(f).onOK((async()=>{await $(A,u,S,t,n)})).show()}))}async function $(e,t,n,i,o){let a=null;const l=r.TaskBarProgressIndicator.create("Analyze for MSA ...");try{if(e.fireChanged(),e.value.semType!==r.SEMTYPE.MACROMOLECULE)throw new Error("Chosen column has to be of Macromolecule semantic type");if(void 0===n)throw new Error("Invalid column format");if(a=await n(),null==a)return o("PepSeA container has not started");t.columns.add(a),await s.data.detectSemanticTypes(t),i(a)}catch(e){const t=e instanceof Error?e.message:e.toString();s.shell.error(t),o(e)}finally{l.close()}}async function N(e,t,n,i,p,f,g,y,b){try{if(e.semType!==r.SEMTYPE.MACROMOLECULE)return;const s=t.columns.getUnusedName(`msa(${e.name})`);if((0,u.n)(e,e.name,[o.r2.FASTA,o.r2.SEPARATOR],["DNA","RNA","PT"],!1)){L(n,i,"kalign"),g.value=null,y.value=null,b.value=null;const t=a.g.forColumn(e),r=t.isFasta()?e:t.convert(o.r2.FASTA);return async()=>await(0,l.U)(r,!1,s,f.value)}if((0,u.n)(e,e.name,[o.r2.HELM],[],!1))return L(n,i,"pepsea"),g.value??(g.value=h.jB.pepsea.gapOpen),y.value??(y.value=h.jB.pepsea.gapExtend),async()=>(await(0,d.Ns)(),(0,c.f3)(e,s,p.value,g.value,y.value,f.value));if((0,u.n)(e,e.name,[o.r2.SEPARATOR],["UN"],!1)){const t=a.g.forColumn(e).convert(o.r2.HELM);return L(n,i,"pepsea"),g.value??(g.value=h.jB.pepsea.gapOpen),y.value??(y.value=h.jB.pepsea.gapExtend),async()=>(await(0,d.Ns)(),(0,c.f3)(t,s,p.value,g.value,y.value,f.value))}return g.value=null,y.value=null,b.value=null,void L(n,i,"kalign")}catch(e){const t=e instanceof Error?e.message:e.toString();s.shell.error(t),m._package.logger.error(t)}}function L(e,t,n){if("kalign"===n){for(const t of e)t.display="none";for(const e of t)e.removeProperty("display")}else{for(const e of t)e.display="none";for(const t of e)t.removeProperty("display")}}},6098:(e,t,n)=>{"use strict";n.d(t,{U:()=>R});var s=n(976),r=n(5226);const i=Symbol("Comlink.proxy"),o=Symbol("Comlink.endpoint"),a=Symbol("Comlink.releaseProxy"),l=Symbol("Comlink.thrown"),c=e=>"object"==typeof e&&null!==e||"function"==typeof e,u=new Map([["proxy",{canHandle:e=>c(e)&&e[i],serialize(e){const{port1:t,port2:n}=new MessageChannel;return h(e,t),[n,[n]]},deserialize:e=>(e.start(),m(e))}],["throw",{canHandle:e=>c(e)&&l in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}}]]);function h(e,t=self){t.addEventListener("message",(function n(s){if(!s||!s.data)return;const{id:r,type:o,path:a}=Object.assign({path:[]},s.data),c=(s.data.argumentList||[]).map(w);let u;try{const t=a.slice(0,-1).reduce(((e,t)=>e[t]),e),n=a.reduce(((e,t)=>e[t]),e);switch(o){case"GET":u=n;break;case"SET":t[a.slice(-1)[0]]=w(s.data.value),u=!0;break;case"APPLY":u=n.apply(t,c);break;case"CONSTRUCT":u=function(e){return Object.assign(e,{[i]:!0})}(new n(...c));break;case"ENDPOINT":{const{port1:t,port2:n}=new MessageChannel;h(e,n),u=function(e,t){return b.set(e,t),e}(t,[t])}break;case"RELEASE":u=void 0;break;default:return}}catch(e){u={value:e,[l]:0}}Promise.resolve(u).catch((e=>({value:e,[l]:0}))).then((e=>{const[s,i]=v(e);t.postMessage(Object.assign(Object.assign({},s),{id:r}),i),"RELEASE"===o&&(t.removeEventListener("message",n),d(t))}))})),t.start&&t.start()}function d(e){(function(e){return"MessagePort"===e.constructor.name})(e)&&e.close()}function m(e,t){return f(e,[],t)}function p(e){if(e)throw new Error("Proxy has been released and is not useable")}function f(e,t=[],n=function(){}){let s=!1;const r=new Proxy(n,{get(n,i){if(p(s),i===a)return()=>C(e,{type:"RELEASE",path:t.map((e=>e.toString()))}).then((()=>{d(e),s=!0}));if("then"===i){if(0===t.length)return{then:()=>r};const n=C(e,{type:"GET",path:t.map((e=>e.toString()))}).then(w);return n.then.bind(n)}return f(e,[...t,i])},set(n,r,i){p(s);const[o,a]=v(i);return C(e,{type:"SET",path:[...t,r].map((e=>e.toString())),value:o},a).then(w)},apply(n,r,i){p(s);const a=t[t.length-1];if(a===o)return C(e,{type:"ENDPOINT"}).then(w);if("bind"===a)return f(e,t.slice(0,-1));const[l,c]=y(i);return C(e,{type:"APPLY",path:t.map((e=>e.toString())),argumentList:l},c).then(w)},construct(n,r){p(s);const[i,o]=y(r);return C(e,{type:"CONSTRUCT",path:t.map((e=>e.toString())),argumentList:i},o).then(w)}});return r}function g(e){return Array.prototype.concat.apply([],e)}function y(e){const t=e.map(v);return[t.map((e=>e[0])),g(t.map((e=>e[1])))]}const b=new WeakMap;function v(e){for(const[t,n]of u)if(n.canHandle(e)){const[s,r]=n.serialize(e);return[{type:"HANDLER",name:t,value:s},r]}return[{type:"RAW",value:e},b.get(e)||[]]}function w(e){switch(e.type){case"HANDLER":return u.get(e.name).deserialize(e.value);case"RAW":return e.value}}function C(e,t,n){return new Promise((s=>{const r=new Array(4).fill(0).map((()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16))).join("-");e.addEventListener("message",(function t(n){!n.data||!n.data.id||n.data.id!==r||(e.removeEventListener("message",t),s(n.data))})),e.start&&e.start(),e.postMessage(Object.assign({id:r},t),n)}))}const S="KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2NvbnN0ICQ9U3ltYm9sKCJDb21saW5rLnByb3h5IiksQT1TeW1ib2woIkNvbWxpbmsuZW5kcG9pbnQiKSxSPVN5bWJvbCgiQ29tbGluay5yZWxlYXNlUHJveHkiKSx5PVN5bWJvbCgiQ29tbGluay50aHJvd24iKSxfPWU9PnR5cGVvZiBlPT0ib2JqZWN0IiYmZSE9PW51bGx8fHR5cGVvZiBlPT0iZnVuY3Rpb24iLEw9e2NhbkhhbmRsZTplPT5fKGUpJiZlWyRdLHNlcmlhbGl6ZShlKXtjb25zdHtwb3J0MTpyLHBvcnQyOml9PW5ldyBNZXNzYWdlQ2hhbm5lbDtyZXR1cm4gdyhlLHIpLFtpLFtpXV19LGRlc2VyaWFsaXplKGUpe3JldHVybiBlLnN0YXJ0KCksQyhlKX19LE89e2NhbkhhbmRsZTplPT5fKGUpJiZ5IGluIGUsc2VyaWFsaXplKHt2YWx1ZTplfSl7bGV0IHI7cmV0dXJuIGUgaW5zdGFuY2VvZiBFcnJvcj9yPXtpc0Vycm9yOiEwLHZhbHVlOnttZXNzYWdlOmUubWVzc2FnZSxuYW1lOmUubmFtZSxzdGFjazplLnN0YWNrfX06cj17aXNFcnJvcjohMSx2YWx1ZTplfSxbcixbXV19LGRlc2VyaWFsaXplKGUpe3Rocm93IGUuaXNFcnJvcj9PYmplY3QuYXNzaWduKG5ldy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pcihvKSxlLm1vdW50KHQuYmFzZS5tb2R1bGUuUFJPWFlGUyx7cm9vdDpzLGZzOml9LG8pKX19LF9maWxlb3AoZSxyKXt0Ll9sb2coYFJ1bm5pbmcgJHtlfSAke3J9YCk7Y29uc3QgaT10LmZzLmFuYWx5emVQYXRoKHIpO2lmKCFpLmV4aXN0cylyZXR1cm4gdC5fbG9nKGBGaWxlICR7cn0gbm90IGZvdW5kLmApLCExO3N3aXRjaChlKXtjYXNlImNhdCI6cmV0dXJuIHQuZnMucmVhZEZpbGUocix7ZW5jb2Rpbmc6InV0ZjgifSk7Y2FzZSJscyI6cmV0dXJuIHQuZnMuaXNGaWxlKGkub2JqZWN0Lm1vZGUpP3QuZnMuc3RhdChyKTp0LmZzLnJlYWRkaXIocik7Y2FzZSJkb3dubG9hZCI6Y29uc3Qgcz1uZXcgQmxvYihbdGhpcy5jYXQocildKTtyZXR1cm4gVVJMLmNyZWF0ZU9iamVjdFVSTChzKX1yZXR1cm4hMX0sX2xvZyhlKXtpZighdC5jb25maWcuZGVidWcpcmV0dXJuO2xldCByPVsuLi5hcmd1bWVudHNdO3Iuc2hpZnQoKSxjb25zb2xlLmxvZyhgJWNbV2ViV29ya2VyXSVjICR7ZX1gLCJmb250LXdlaWdodDpib2xkIiwiIiwuLi5yKX19O3codCl9KSgpOwo=",A=typeof window<"u"&&window.Blob&&new Blob([atob(S)],{type:"text/javascript;charset=utf-8"});function x(){const e=A&&(window.URL||window.webkitURL).createObjectURL(A);try{return e?new Worker(e):new Worker("data:application/javascript;base64,"+S)}finally{e&&(window.URL||window.webkitURL).revokeObjectURL(e)}}const E={urlCDN:"https://biowasm.com/cdn/v3",urlCDNStg:"https://stg.biowasm.com/cdn/v3",dirShared:"/shared",dirMounted:"/mnt",dirData:"/data",printInterleaved:!0,callback:null,debug:!1,env:"prd"};class I{constructor(e,t={}){if(null==e)throw"Expecting array of tools as input to Aioli constructor.";return Array.isArray(e)||(e=[e]),t=Object.assign({},E,t),e=e.map(this._parseTool),"stg"===t.env&&(t.urlCDN=t.urlCDNStg),this.tools=e,this.config=t,null!=this.config.callback&&(this.callback=this.config.callback),delete this.config.callback,this.init()}async init(){const e=new x;this.callback&&(e.onmessage=e=>{"biowasm"===e.data.type&&this.callback(e.data.value)});const t=m(e);return t.tools=this.tools,t.config=this.config,await t.init(),t}_parseTool(e){if("string"!=typeof e)return e;const t=e.split("/");if(2!=t.length&&3!=t.length)throw"Expecting '<tool>/<version>' or '<tool>/<program>/<version>'";return{tool:t[0],program:3==t.length?t[1]:t[0],version:t[t.length-1]}}}var T=n(850);class _{static getAvailableScales(){return Object.entries(this.scales).map((([e,t])=>e))}static getScale(e){return(0,T.hu)(!(void 0===this.scales[e]),`Scale '${e}' was not found.`),this.scales[e]}}_.scales={WimleyWhite:{"-":0,A:.17,C:-.24,D:-.07,E:-.01,F:-1.13,G:.01,H:.17,I:-.31,K:.99,L:-.56,M:-.23,N:.42,P:.45,Q:.58,R:.81,S:.13,T:.14,V:.07,W:-1.85,Y:-.94},categorial:{"-":0,A:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,K:9,L:10,M:11,N:12,P:13,Q:14,R:15,S:16,T:17,V:18,W:19,Y:20}};class M{constructor(e="categorial"){this.aa2num=_.getScale(e),this.num2aa={},Object.entries(this.aa2num).forEach((([e,t])=>this.num2aa[t]=e))}static _truncateSequence(e){let t=0,n=e.length;const s=["NH2","COOH"];if(e.startsWith(s[0])){const n=s[0].length;(0,T.hu)("-"==e[n],`Wrong sequence format: ${s[0]} without following '-' in '${e}'.`),t=n}if(e.endsWith(s[1])){const t=s[1].length+1;(0,T.hu)("-"==e[n-t],`Wrong sequence format: ${s[1]} without '-' precending in '${e}'.`),n-=t}return e.substring(t,n)}static _dropDefises(e){return e.replace(/(-)([^-]+)/g,"$2")}static clean(e){return M._dropDefises(M._truncateSequence(e))}encode(e){const t=e.length,n=new Array(t).fill(0);for(let s=0;s<t;++s){const t=e[s];(0,T.hu)(t in this.aa2num,`Unknown char '${t}' found in sequence '${e}'`),n[s]=this.encodeLettter(t)}return n}encodeLettter(e){return this.aa2num[e]}decode(e){let t="";for(let n=0;n<e.length;++n){const s=e[n];(0,T.hu)(s in this.num2aa,`Unknown code '${s}' found in vector '${e}'`),t+=this.num2aa[s]}return t}}var $=n(3553);const N="input.fa",L="result.fasta";function P(e){return e.reduce(((e,t,n)=>e+`>sample${n+1}\n${t}\n`),"")}async function R(e,t=!1,n="",i=null,o,a,l){let c=e.toList();t&&(c=c.map((e=>M.clean(e).replace(/\-/g,""))));const u=e.length;i??(i=s.Column.string("Clusters",u).init("0")),i.type!=s.COLUMN_TYPE.STRING&&(i=i.convertTo(s.TYPE.STRING)),i.compact();const h=i.categories,d=i.getRawData(),m=new Array(h.length),p=new Array(h.length);for(let e=0;e<u;++e){const t=d[e];(m[t]??(m[t]=[])).push(c[e]),(p[t]??(p[t]=[])).push(e)}const f=await new I(["base/1.0.0",{tool:"kalign",version:$.WY,reinit:!0}]),g=s.Column.string(n,u);for(let e=0;e<h.length;++e){const t=P(m[e]);await f.fs.writeFile(N,t);const n=`${void 0!==o?` --gpo ${o}`:""}${void 0!==a?` --gpe ${a}`:""}${void 0!==l?` --tgpe ${l}`:""}`,s=await f.exec(`kalign ${N} -f fasta -o ${L}${n}`);console.warn(s);const i=await f.cat(L);if(!i)throw new Error("kalign output no result");const c=new r.i(i).sequencesArray,u=p[e];for(let e=0;e<c.length;++e)g.set(u[e],c[e])}const y=e.getTag(s.TAGS.UNITS),b=e.getTag("alphabet");return g.setTag(s.TAGS.UNITS,y),g.setTag("aligned","SEQ.MSA"),g.setTag("alphabet",b),g.semType=s.SEMTYPE.MACROMOLECULE,g}},8341:(e,t,n)=>{"use strict";n.d(t,{Jy:()=>c,f3:()=>h,lp:()=>l});var s=n(4469),r=n(976),i=n(8447),o=n(3553),a=n(3649);const l=new class{constructor(){this.dcName="bio"}async getDockerContainer(){return await s.dapi.docker.dockerContainers.filter(this.dcName).first()}},c=["mafft --auto","mafft","linsi","ginsi","einsi","fftns","fftnsi","nwns","nwnsi"],u=["AlignedSeq","AlignedSubpeptide","HELM","ID","PolymerID"];async function h(e,t,n="ginsi",s=1.53,a=0,c=null,h){const m=await l.getDockerContainer();if("started"!==m.status&&"checking"!==m.status)throw new Error("PepSeA container has not started yet");const p=e.length;c??(c=r.Column.int("Clusters",p).init(0)),c.type!=r.COLUMN_TYPE.STRING&&(c=c.convertTo(r.TYPE.STRING));const f=c.categories,g=new Array(f.length);for(let t=0;t<p;++t){const n=c.get(t);if(""===n)continue;const s=f.indexOf(n),r=e.get(t);r&&(g[s]??(g[s]=[])).push({ID:t.toString(),HELM:r})}const y=new Array(p);for(const e of g){const t=(await d(m.id,e,n,s,a,h)).Alignment;for(const e of t)y[parseInt(e.ID)]=Object.entries(e).filter((e=>!u.includes(e[0]))).map((e=>"-"!==e[1]?e[1]:"")).join(o.rs.SEPARATOR)}const b=r.Column.fromStrings(t,y);return b.setTag(r.TAGS.UNITS,i.r2.SEPARATOR),b.setTag("separator",o.rs.SEPARATOR),b.setTag("aligned","SEQ.MSA"),b.setTag("alphabet","UN"),b.setTag(".alphabetIsMultichar","true"),b.semType=r.SEMTYPE.MACROMOLECULE,b}async function d(e,t,n,r,i,o){const l={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(t)},c=`/align?method=${n}&gap_open=${r}&gap_extend=${i}`;let u;if("fetchProxy"in s.dapi.docker.dockerContainers){const t=window.performance.now(),n=await s.dapi.docker.dockerContainers.fetchProxy(e,c,l),r=window.performance.now();a._package.logger.debug(`Bio: requestAlignedObjects() dockerContainers.fetchProxy(), ET: ${r-t} ms`);const i="application/json"===n.headers.get("content-type");if(!n.ok&&i){const e=await n.json(),t=e["pepsea-error"];if(t)throw new Error(`PepSeA error: ${t}`);const s=e["datagrok-error"];if(s)throw new Error(`Datagrok error: ${s}`);throw new Error(n.statusText)}if(!n.ok&&!i){const e=await n.text();throw new Error(`Error: ${e}`)}if(!i){const e=await n.text();throw new Error(`Error: PepSeA expected JSON response, got '${e}'.`)}u=await n.json()}else{const t=await s.dapi.docker.dockerContainers.request(e,c,l);if(!t)throw new Error("Empty response");u=JSON.parse(t);const n=u["pepsea-error"];if(n)throw new Error(`PepSeA error: ${n}`);const r=u["datagrok-error"];if(r)throw new Error(`Datagrok error: ${r}`)}if("pepsea-stderr"in u){const e=u["pepsea-stderr"];o?.warning(e)}return u}},9943:(e,t,n)=>{"use strict";n.d(t,{C2:()=>u});var s=n(976),r=n(3870),i=n(4469),o=n(6414),a=n.n(o),l=n(8260);const c=60;function u(){const e=i.shell.tv.grid,t=a().count(0).take(e.columns.length).map((t=>e.columns.byIndex(t))).filter((e=>!!e.column&&e.column.semType!==s.SEMTYPE.MACROMOLECULE)).toArray(),n=t.find((e=>-1!==e.name.toLowerCase().indexOf("id"))),o=n?[n.name]:[],u=r.multiChoiceInput("Seq id columns",o,t.map((e=>e.name))),d=a().count(0).take(e.columns.length).map((t=>e.columns.byIndex(t))).filter((e=>{const t=e.column;return!(!t||t.semType!==s.SEMTYPE.MACROMOLECULE)&&l.g.forColumn(t).isFasta()})).toArray(),m=d.length>0?d[0].name:[],p=r.choiceInput("Seq column",m,d.map((e=>e.name))),f=r.intInput("FASTA line width",c);r.dialog({title:"Save as FASTA"}).add(r.inputs([u,p,f])).onOK((()=>{const t=u.value?u.value.map((t=>e.columns.byName(t).column)):[],n=p.value?e.columns.byName(p.value).column:null,s=f.value??c;n||i.shell.warning("Seq column is mandatory to save as FASTA.");const r=function(e,t,n=c,s="\n"){const r=l.g.forColumn(t),i=[];for(let o=0;o<t.length;o++){const t=e.map((e=>e.get(o).toString())).join("|"),a=h(r.getSplitted(o),n);i.push(`>${t}${s}`);for(const e of a)i.push(`${e}${s}`)}return"".concat(...i)}(t,n,s),o=document.createElement("a");o.setAttribute("href",`data:text/plain;charset=utf-8,${encodeURIComponent(r)}`),o.setAttribute("download",`${e.dataFrame.name}.fasta`),o.click()})).show()}function h(e,t=c){let n=0;const s=e.length,r=[];for(;n<s;){const s=a()(e.originals).slice(n,n+t).toArray(),i=s.map((e=>e.length>1?`[${e}]`:e)).reduce(((e,t)=>e+t),"");r.push(i),n+=s.length}return r}},9416:(e,t,n)=>{"use strict";n.d(t,{n:()=>c});var s=n(4469),r=n(976),i=n(8467),o=n(2568),a=n(8457),l=n(3553);async function c(e,t){if(await(0,i.gw)(10),!(0,o.n)(t,"Sequence space"))return e;const n=(0,a.O)(t);n.name="splitToMonomers";const c=t.dataFrame;for(const e of n.columns)e.semType=l.Of.MONOMER,e.setTag("alphabet",t.getTag("alphabet"));const u=/(\d+)(?: \((\d+)\))?/,h=e=>{u.lastIndex=0;const t=e.match(u);return t?`${t[1]} (${parseInt(t[2]??0)+1})`:e};for(let e=0;e<n.columns.length;e++){const s=n.columns.byIndex(e);s.semType=l.Of.MONOMER,s.setTag("alphabet",t.getTag("alphabet"));const r=100;let i=0;for(;c.columns.byName(s.name)&&i<r;)s.name=h(s.name),i++;c.columns.add(s)}await s.data.detectSemanticTypes(c);for(let e=0;e<n.columns.length;e++){const t=n.columns.byIndex(e);t.setTag(r.TAGS.CELL_RENDERER,"Monomer"),t.setTag(".use-as-filter","false")}return c}},4293:(e,t,n)=>{"use strict";n.d(t,{B:()=>i,Y:()=>o});var s=n(4469),r=n(976);function i(){const e=s.shell.t.columns.bySemTypeAll(r.SEMTYPE.MACROMOLECULE);if(null!==e)return e;s.shell.error("Current table does not contain macromolecules")}function o(e,t){e.innerHTML="",e.append(t)}},8415:(e,t,n)=>{"use strict";n.d(t,{bo:()=>v,OZ:()=>T});var s=n(4469),r=n(3870),i=n(976),o=n(3336),a=n.n(o),l=n(6414),c=n.n(l),u=n(701),h=n(8260),d=n(8447),m=n(9298);function p(e){var t;return"string"==typeof e||e instanceof String?e:("object"==typeof e||e instanceof Object)&&"$thrownJsError"in e?p(e.$thrownJsError):e instanceof Error?null!==(t=e.stack)&&void 0!==t?t:e.message:e.toString()}var f=n(6286),g=n(8467),y=n(172);var b,v,w=n(8770),C=n(3649);HTMLCanvasElement.prototype.getCursorPosition=function(e,t){const n=this.getBoundingClientRect();return new i.Point((e.clientX-n.left)*t,(e.clientY-n.top)*t)},i.Rect.prototype.contains=function(e,t){return this.left<=e&&e<=this.right&&this.top<=t&&t<=this.bottom};class S{constructor(e=0,t){this.valueList=null,this.valueIdx=0,this.value=this.rowCount=e,this.bounds=t}push(e){this.valueList||(this.valueList=new Array(this.rowCount),this.valueIdx=0),this.valueList[this.valueIdx]=e,++this.valueIdx}aggregate(e){this.value=e(this.valueList)??0,this.valueList=null}}class A{get label(){return this._label?this._label:this.name}constructor(e,t,n,s){this.pos=e,this.name=t,this.sumRowCount=0,this._freqs=n??{},s?.sumRowCount&&(this.sumRowCount=s.sumRowCount),s?.sumValueForHeight&&(this.sumPlotValue=s.sumValueForHeight),s?.label&&(this._label=s.label)}getMonomers(){return Object.keys(this._freqs)}hasMonomer(e){return e in this._freqs}getFreq(e){let t=this._freqs[e];return t||(t=this._freqs[e]=new S),t}aggregate(e){const t=function(e){return t=>{const n=function(e){let t;const n="agg";return t=e instanceof Float32Array?i.Column.fromFloat32Array(n,e):e instanceof Int32Array?i.Column.fromInt32Array(n,e):i.Column.fromList(i.COLUMN_TYPE.FLOAT,n,e),t}(t);return n.aggregate(e)}}(e);for(const[e,n]of Object.entries(this._freqs))n.aggregate(t)}getMinValue(){return Math.min(...Object.values(this._freqs).map((e=>e.value)))}calcPlotValue(e){for(const t of Object.values(this._freqs))t.plotValue=t.value-e}calcHeights(e){this.sumPlotValue=0;for(const e of Object.values(this._freqs))this.sumPlotValue+=e.plotValue;if(this.sumPlotValueForHeight=0,e===m.ES.Entropy){const e=Object.keys(this._freqs).length,t=.01*this.sumPlotValue,n=t/e;for(const e of Object.values(this._freqs)){const s=(e.plotValue+n)/(this.sumPlotValue+t);this.sumPlotValueForHeight+=-s*Math.log2(s)}}else if(e===m.ES.full)for(const[e,t]of Object.entries(this._freqs)){const e=t.plotValue/this.sumPlotValue;this.sumPlotValueForHeight+=e}}calcScreen(e,t,n,s,r,o,a,l,c){const u=s===m.ES.Entropy?n*(r-this.sumPlotValueForHeight)/r:n;let h=c*l+(n-u-1);const d=Object.entries(this._freqs).sort(((e,t)=>e[0]!==f.G2&&t[0]!==f.G2?t[1].value-e[1].value:e[0]===f.G2&&t[0]===f.G2?0:e[0]===f.G2?-1:1));for(const[n,s]of d){const n=u*s.plotValue/this.sumPlotValue;s.bounds=new i.Rect((e-t)*l*o,h,a*l,n),h+=n}}render(e,t,n,s,r){for(const[i,o]of Object.entries(this._freqs))if(i!==f.G2){const a=(0,d.GU)(i,5),l=o.bounds,c=l.left;e.resetTransform(),e.strokeStyle="lightgray",e.lineWidth=1,e.rect(c,l.top,l.width,l.height),e.fillStyle=r.get(i)??r.get("other"),e.textAlign="left",e.font=t;const u=e.measureText(a);e.setTransform(l.width/u.width,0,0,l.height/s,c,l.top),e.fillText(a,0,-n)}}getMonomerAt(e,t){const n=Object.entries(this._freqs).find((([n,s])=>s.bounds.contains(e,t)));return n?n[0]:void 0}buildCompositionTable(e){if("-"in this._freqs)throw new Error("Unexpected monomer symbol '-'.");return(0,w._)(e,Object.assign({},...Object.entries(this._freqs).map((([e,t])=>({[e]:t.rowCount})))))}}!function(e){e.STYLE="Style",e.BEHAVIOR="Behavior",e.LAYOUT="Layout",e.DATA="Data"}(b||(b={})),function(e){e.sequenceColumnName="sequenceColumnName",e.valueAggrType="valueAggrType",e.valueColumnName="valueColumnName",e.startPositionName="startPositionName",e.endPositionName="endPositionName",e.skipEmptySequences="skipEmptySequences",e.skipEmptyPositions="skipEmptyPositions",e.shrinkEmptyTail="shrinkEmptyTail",e.backgroundColor="backgroundColor",e.positionHeight="positionHeight",e.positionWidth="positionWidth",e.verticalAlignment="verticalAlignment",e.horizontalAlignment="horizontalAlignment",e.fixWidth="fixWidth",e.fitArea="fitArea",e.minHeight="minHeight",e.maxHeight="maxHeight",e.showPositionLabels="showPositionLabels",e.positionMarginState="positionMarginState",e.positionMargin="positionMargin",e.filterSource="filterSource"}(v||(v={}));const x=m.vS;var E;!function(e){e[e.None=0]="None",e[e.Render=1]="Render",e[e.Layout=1]="Layout",e[e.Freqs=2]="Freqs"}(E||(E={}));const I=new class{constructor(){this.render=20}};class T extends i.JsViewer{get positionWidthWithMargin(){return this._positionWidthWithMargin}get Length(){return this.skipEmptyPositions?this.positions.length:this.startPosition<=this.endPosition?this.endPosition-this.startPosition+1:0}get positionMarginValue(){return this.positionMarginState===m.dE.AUTO&&!0===this.seqHandler.getAlphabetIsMultichar()||this.positionMarginState===m.dE.ON?this.positionMargin:0}constructor(){super(),this.viewed=!1,this.initialized=!1,this.palette=null,this.seqCol=null,this.positions=[],this.visibleSlider=!1,this.allowResize=!0,this.turnOfResizeForOneSetValue=!1,this.backgroundColor=4294967295,this.positionMargin=0,this.positionNames=[],this.positionLabels=void 0,this.startPosition=-1,this.endPosition=-1,this.error=null,this.viewerId=++T.viewerCounter,this.setDataInProgress=!1,this.viewSubs=[],this._onSizeChanged=new u.Subject,this._onFreqsCalculated=new u.Subject,this._onLayoutCalculated=new u.Subject,this.requestedRenderLevel=E.Freqs,this.renderRequest=new u.Subject,this._onRendered=new u.Subject,this.textBaseline="top",this.seqHandler=null,this.sequenceColumnName=this.string(v.sequenceColumnName,x.sequenceColumnName,{category:b.DATA});const e=[i.AGG.KEY,i.AGG.PIVOT,i.AGG.MISSING_VALUE_COUNT,i.AGG.SKEW,i.AGG.KURT,i.AGG.SELECTED_ROWS_COUNT],t=Object.values(i.AGG).filter((t=>!e.includes(t)));this.valueAggrType=this.string(v.valueAggrType,x.valueAggrType,{category:b.DATA,choices:t}),this.valueColumnName=this.string(v.valueColumnName,x.valueColumnName,{category:b.DATA}),this.startPositionName=this.string(v.startPositionName,x.startPositionName,{category:b.DATA}),this.endPositionName=this.string(v.endPositionName,x.endPositionName,{category:b.DATA}),this.skipEmptySequences=this.bool(v.skipEmptySequences,x.skipEmptySequences,{category:b.DATA}),this.skipEmptyPositions=this.bool(v.skipEmptyPositions,x.skipEmptyPositions,{category:b.DATA}),this.shrinkEmptyTail=this.bool(v.shrinkEmptyTail,x.shrinkEmptyTail,{category:b.DATA}),this.backgroundColor=this.int(v.backgroundColor,x.backgroundColor,{category:b.STYLE}),this.positionHeight=this.string(v.positionHeight,x.positionHeight,{category:b.STYLE,choices:Object.values(m.ES)}),this._positionWidth=this.positionWidth=this.float(v.positionWidth,x.positionWidth,{category:b.STYLE}),this.verticalAlignment=this.string(v.verticalAlignment,x.verticalAlignment,{category:b.LAYOUT,choices:Object.values(m.vw)}),this.horizontalAlignment=this.string(v.horizontalAlignment,x.horizontalAlignment,{category:b.LAYOUT,choices:Object.values(m.iD)}),this.fixWidth=this.bool(v.fixWidth,x.fixWidth,{category:b.LAYOUT,userEditable:!1}),this.fitArea=this.bool(v.fitArea,x.fitArea,{category:b.LAYOUT}),this.minHeight=this.float(v.minHeight,x.minHeight,{category:b.LAYOUT}),this.maxHeight=this.float(v.maxHeight,x.maxHeight,{category:b.LAYOUT}),this.showPositionLabels=this.bool(v.showPositionLabels,x.showPositionLabels,{category:b.LAYOUT}),this.positionMarginState=this.string(v.positionMarginState,x.positionMarginState,{category:b.LAYOUT,choices:Object.values(m.dE)});let n=0;"auto"===this.positionMarginState&&(n=4),this.positionMargin=this.int(v.positionMargin,n,{category:b.LAYOUT,min:0,max:16}),this.filterSource=this.string(v.filterSource,x.filterSource,{category:b.BEHAVIOR,choices:Object.values(m.Ct)}),this.slider=r.rangeSlider(0,100,0,20,!1,{style:"barbell"}),this.canvas=r.canvas(),this.canvas.classList.value="bio-wl-canvas",this.canvas.style.width="100%",this.viewSyncer=new y.c(C._package.logger)}viewerToLog(){return`WebLogoViewer<${this.viewerId}>`}setData(){const e=`${this.viewerToLog()}.setData()`;C._package.logger.debug(`${e}, in`),this.viewSyncer.sync(`${e}`,(async()=>{if(!this.setDataInProgress){this.setDataInProgress=!0;try{this.viewed&&(this.renderRequestSub.unsubscribe(),await this.destroyView(),this.viewed=!1),this.updateSeqCol(),this.updateEditors(),this.viewed||(await this.buildView(),this.viewed=!0)}finally{this.setDataInProgress=!1}}})),C._package.logger.debug(`${e}, out`)}async destroyView(){for(const e of this.viewSubs)e.unsubscribe();this.viewSubs=[];const e=this.dataFrame?"data":"null";C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.destroyView( dataFrame = ${e} ) start`),this.host.remove(),this.msgHost=void 0,this.host=void 0,C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.destroyView() end`)}async buildView(){const e=this.dataFrame?"data":"null";C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.buildView( dataFrame = ${e} ) start`),window.devicePixelRatio,this.viewSubs.push(i.debounce(this.renderRequest,I.render).subscribe(this.renderRequestOnDebounce.bind(this))),this.helpUrl="/help/visualize/viewers/web-logo.md",this.msgHost=r.div("No message",{classes:"bio-wl-msg"}),this.msgHost.style.display="none",this.canvas=r.canvas(),this.canvas.style.width="100%",this.slider.root.style.position="absolute",this.slider.root.style.zIndex="999",this.slider.root.style.display="none",this.slider.root.style.height="0.7em",this.visibleSlider=!1,this.host=r.div([this.msgHost,this.canvas],{classes:"bio-wl-host",style:{display:"flex",flexDirection:"row",flexWrap:"wrap"}}),this.root.append(this.host),this.root.append(this.slider.root),this.error&&(this.msgHost.innerText=this.error.message,r.tooltip.bind(this.msgHost,this.error.stack),this.msgHost.style.setProperty("display",null)),this.dataFrame&&(this.viewSubs.push(this.dataFrame.filter.onChanged.subscribe(this.dataFrameFilterOnChanged.bind(this))),this.viewSubs.push(this.dataFrame.selection.onChanged.subscribe(this.dataFrameSelectionOnChanged.bind(this)))),this.viewSubs.push(r.onSizeChanged(this.root).subscribe(this.rootOnSizeChanged.bind(this))),this.viewSubs.push(this.slider.onValuesChanged.subscribe(this.sliderOnValuesChanged.bind(this))),this.viewSubs.push((0,u.fromEvent)(this.canvas,"mousemove").subscribe(this.canvasOnMouseMove.bind(this))),this.viewSubs.push((0,u.fromEvent)(this.canvas,"mousedown").subscribe(this.canvasOnMouseDown.bind(this))),this.viewSubs.push((0,u.fromEvent)(this.canvas,"wheel").subscribe(this.canvasOnWheel.bind(this))),this.render(E.Freqs,"buildView"),C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.buildView() end`)}rootOnSizeChanged(){C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.rootOnSizeChanged(), start `),this.render(E.Layout,"rootOnSizeChanged")}updateEditors(){this.props.getProperty(v.valueColumnName).choices=c()(this.dataFrame.columns.numerical).map((e=>e.name)).toArray()}updateSeqCol(){if(this.dataFrame&&(this.seqCol=this.sequenceColumnName?this.dataFrame.col(this.sequenceColumnName):null,null==this.seqCol&&(this.seqCol=(0,d.up)(this.dataFrame),this.sequenceColumnName=this.seqCol?this.seqCol.name:null),this.seqCol)){try{this.seqHandler=h.g.forColumn(this.seqCol),this.palette=(0,d.dQ)(this.seqCol),this.render(E.Freqs,"updateSeqCol()"),this.error=null}catch(e){throw this.seqCol=null,this.error=e instanceof Error?e:new Error(e.toString()),e}this.seqCol||(this.seqHandler=null,this.positionNames=[],this.positionLabels=[],this.startPosition=-1,this.endPosition=-1,this.palette=null)}}getFilter(){let e;switch(this.filterSource){case m.Ct.Filtered:e=this.dataFrame.filter;break;case m.Ct.Selected:e=0===this.dataFrame.selection.trueCount?this.dataFrame.filter:this.dataFrame.selection}return e}setSliderVisibility(e){e?(this.slider.root.style.display="inherit",this.visibleSlider=!0):(this.slider.root.style.display="none",this.visibleSlider=!1)}calcLayout(e){this.host&&this.canvas&&this.slider&&(this.host.classList.remove("bio-wl-fixWidth","bio-wl-fitArea"),this.canvas.classList.remove("bio-wl-fixWidth","bio-wl-fitArea"),this._positionWidth=this.positionWidth,this._positionMargin=this.positionMargin,this._positionWidthWithMargin=this._positionWidth+this.positionMarginValue,this.fixWidth?this.calcLayoutFixWidth(e):this.fitArea?this.calcLayoutFitArea(e):this.calcLayoutNoFitArea(e),this.slider.root.style.width=`${this.host.clientWidth}px`)}calcLayoutFixWidth(e){if(!this.host||!this.canvas||!this.slider)return;this.host.classList.add("bio-wl-fixWidth"),this.canvas.classList.add("bio-wl-fitArea");const t=this._positionWidthWithMargin*this.Length,n=Math.min(Math.max(this.minHeight,this.root.clientHeight),this.maxHeight);this.host.style.justifyContent=m.iD.LEFT,this.host.style.removeProperty("margin-left"),this.host.style.removeProperty("margin-top"),this.host.style.width=this.canvas.style.width=`${t}px`,this.host.style.height=this.canvas.style.height=`${n}px`,this.host.style.left=this.canvas.style.left="0",this.host.style.top=this.canvas.style.top="0",this.host.style.setProperty("overflow","hidden","important"),this.slider.root.style.display="none",this.slider.setValues(0,Math.max(0,this.Length-1),0,Math.max(0,this.Length-1)),this.canvas.width=t*e,this.canvas.height=n*e}calcLayoutNoFitArea(e){if(!this.host||!this.canvas||!this.slider)return;const t=this._positionWidthWithMargin*this.Length,n=Math.min(Math.max(this.minHeight,this.root.clientHeight),this.maxHeight),s=Math.min(this.root.clientWidth,t);this.canvas.style.width=`${s}px`,this.canvas.style.height=`${n}px`,this.host.style.width=`${s}px`,this.host.style.height=`${this.root.clientHeight}px`,this.host.style.justifyContent=this.horizontalAlignment,this.host.style.alignContent=this.verticalAlignment===m.vw.TOP?"start":this.verticalAlignment===m.vw.MIDDLE?"center":this.verticalAlignment===m.vw.BOTTOM?"end":"inherit",this.root.clientHeight<this.minHeight&&(this.host.style.alignContent="start",this.host.style.width=`${s+6}px`),this.host.style.width=`${this.host}px`;const r=t>s;if(this.setSliderVisibility(r),r){this.slider.root.style.removeProperty("display"),this.host.style.justifyContent="left",this.host.style.height=this.root.clientHeight-this.slider.root.offsetHeight+"px",this.slider.root.style.top=`${this.host.offsetHeight}px`;let e=Math.min(Math.max(0,this.slider.min),this.Length-.001),t=Math.min(Math.max(0,this.slider.max),this.Length-.001);const n=this.root.clientWidth/this._positionWidthWithMargin;t=Math.min(Math.max(e,0)+n,this.Length-.001),e=Math.max(0,Math.min(t,this.Length-.001)-n),this.slider.setValues(0,Math.max(this.Length-.001),e,t)}else this.slider.setValues(0,Math.max(0,this.Length-.001),0,Math.max(0,this.Length-.001));this.canvas.width=s*e,this.canvas.height=n*e}calcLayoutFitArea(e){if(!this.host||!this.canvas||!this.slider)return;const t=this._positionWidth*this.Length,n=Math.min(Math.max(this.minHeight,this.root.clientHeight),this.maxHeight),s=t>0?(this.root.clientWidth-this.positionMarginValue*this.Length)/t:0,r=this.root.clientHeight/n,i=Math.max(1,Math.min(s,r));this._positionWidth=this.positionWidth*i,this._positionWidthWithMargin=this._positionWidth+this.positionMarginValue;const o=(this._positionWidth+this.positionMarginValue)*this.Length,a=i*n,l=Math.min(this.root.clientWidth,o);this.canvas.style.width=`${l}px`,this.canvas.style.height=`${a}px`,this.host.style.width=`${l}px`,this.host.style.height=`${this.root.clientHeight}px`,this.host.style.justifyContent=this.horizontalAlignment,this.host.style.alignContent=this.verticalAlignment===m.vw.TOP?"start":this.verticalAlignment===m.vw.MIDDLE?"center":this.verticalAlignment===m.vw.BOTTOM?"end":"inherit",this.root.clientHeight<this.minHeight&&(this.host.style.alignContent="start",this.host.style.width=`${l+6}px`),this.host.style.width=`${this.host}px`;const c=o>l;if(this.setSliderVisibility(c),c){this.slider.root.style.removeProperty("display"),this.host.style.justifyContent="left",this.host.style.height=this.root.clientHeight-this.slider.root.offsetHeight+"px",this.slider.root.style.top=`${this.host.offsetHeight}px`;let e=Math.min(Math.max(0,this.slider.min),this.Length-.001),t=Math.min(Math.max(0,this.slider.max),this.Length-.001);const n=this.root.clientWidth/this._positionWidthWithMargin;t=Math.min(Math.max(e,0)+n,this.Length-.001),e=Math.max(0,Math.min(t,this.Length-.001)-n),this.slider.setValues(0,Math.max(0,this.Length-.001),e,t)}else this.slider.setValues(0,Math.max(0,this.Length-.001),0,Math.max(0,this.Length-.001));this.canvas.width=l*e,this.canvas.height=a*e}onPropertyChanged(e){switch(super.onPropertyChanged(e),e.name){case v.sequenceColumnName:this.updateSeqCol();break;case v.sequenceColumnName:case v.startPositionName:case v.endPositionName:case v.filterSource:case v.shrinkEmptyTail:case v.skipEmptyPositions:case v.positionHeight:case v.valueColumnName:case v.valueAggrType:this.render(E.Freqs,`onPropertyChanged( ${e.name} )`);break;case v.minHeight:case v.maxHeight:case v.positionWidth:case v.showPositionLabels:case v.fixWidth:case v.fitArea:case v.horizontalAlignment:case v.verticalAlignment:case v.positionMargin:case v.positionMarginState:this.render(E.Layout,`onPropertyChanged(${e.name})`);break;case v.backgroundColor:this.render(E.Render,`onPropertyChanged(${e.name})`)}}onTableAttached(){C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.onTableAttached(), `),super.onTableAttached(),this.setData()}detach(){const e=`${this.viewerToLog()}.detach()`;C._package.logger.debug(`${e}, in`);const t=super.detach.bind(this);this.viewSyncer.sync(`${e}`,(async()=>{this.setDataInProgress||(this.viewed&&(await this.destroyView(),this.viewed=!1),t())})),C._package.logger.debug(`${e}, out`)}get onSizeChanged(){return this._onSizeChanged}get onFreqsCalculated(){return this._onFreqsCalculated}get onLayoutCalculated(){return this._onLayoutCalculated}getMonomer(e,t){const n=e.x,s=Math.floor(e.x/(this._positionWidthWithMargin*t)+Math.floor(this.slider.min)),r=this.positions[s];if(!r)return[null,null,null];const i=r.getMonomerAt(n,e.y);return void 0===i?[r,null,null]:[r,i,r.getFreq(i)]}_nullSequence(e="X"){return this.skipEmptySequences?"":new Array(this.Length).fill(e).join("")}_removeEmptyPositions(){this.skipEmptyPositions&&(this.positions=c()(this.positions).filter((e=>!e.hasMonomer(f.G2)||e.getFreq(f.G2).rowCount!==e.sumRowCount)).toArray())}render(e,t){C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.render( recalcLevelVal=${e}, reason='${t}' )`),this.requestedRenderLevel=Math.max(this.requestedRenderLevel,e),this.renderRequest.next(this.requestedRenderLevel)}async renderInt(e){if(C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.render.renderInt( renderLevel=${e} ), start `),this.msgHost&&(this.seqCol&&!this.palette?(this.msgHost.innerText=`Unknown palette (column semType: '${this.seqCol.semType}').`,this.msgHost.style.display=""):this.msgHost.style.display="none"),!this.seqCol||!this.dataFrame||!this.palette||null==this.host||null==this.slider)return;const t=window.devicePixelRatio,n=this.showPositionLabels?12:0;if(e>=E.Freqs&&(()=>{if(C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.render.calculateFreqsInt(), start `),!this.host||!this.seqCol||!this.dataFrame)return;const e=this.getFilter(),t=0===e.trueCount?this.seqHandler.maxLength:c().count(0).take(this.seqHandler.length).map((t=>{const n=this.seqHandler.getSplitted(t);return e.get(t)&&n?n.length:0})).reduce(((e,t)=>Math.max(e,t)),0),n=this.seqCol.getTag(".positionNames"),s=this.seqCol.getTag(".positionLabels");this.positionNames=n?n.split(d.CI).map((e=>e.trim())):[...Array(t).keys()].map((e=>`${e+1}`)),this.positionLabels=s?s.split(d.CI).map((e=>e.trim())):void 0,this.startPosition=this.startPositionName&&this.positionNames&&this.positionNames.includes(this.startPositionName)?this.positionNames.indexOf(this.startPositionName):0,this.endPosition=this.endPositionName&&this.positionNames&&this.positionNames.includes(this.endPositionName)?this.positionNames.indexOf(this.endPositionName):t-1;const r=this.startPosition<=this.endPosition?this.endPosition-this.startPosition+1:0;this.seqHandler=h.g.forColumn(this.seqCol);const o=this.startPosition<=this.endPosition?this.endPosition-this.startPosition+1:0;this.positions=new Array(o);for(let e=0;e<r;e++){const t=this.positionNames[this.startPosition+e],n=this.positionLabels?this.positionLabels[this.startPosition+e]:void 0;this.positions[e]=new A(this.startPosition+e,t,{},{label:n})}const a=this.dataFrame.rowCount;for(let t=0;t<r;++t){for(let n=0;n<a;++n)if(e.get(n)){const e=this.seqHandler.getSplitted(n),s=t<e.length?e.getCanonical(this.startPosition+t):this.seqHandler.defaultGapOriginal,r=this.seqHandler.defaultGapOriginal===s?f.G2:s,i=this.positions[t],o=i.getFreq(r);++i.sumRowCount,o.value=++o.rowCount}if(this.valueAggrType===i.AGG.TOTAL_COUNT)continue;let n=null;try{n=this.dataFrame.getCol(this.valueColumnName),n.matches("numerical")||(n=null)}catch{n=null}if(n){for(let s=0;s<a;++s)if(e.get(s)){const e=this.seqHandler.getSplitted(s).getCanonical(this.startPosition+t),r=n.get(s);this.positions[t].getFreq(e).push(r)}this.positions[t].aggregate(this.valueAggrType)}}const l=this.valueAggrType===i.AGG.TOTAL_COUNT?0:Math.min(0,Math.min(...this.positions.map((e=>e.getMinValue()))));for(let e=0;e<r;++e)this.positions[e].calcPlotValue(l),this.positions[e].calcHeights(this.positionHeight);this._removeEmptyPositions(),this._onFreqsCalculated.next()})(),this.calcLayout(t),-1===this.startPosition)return;const r=Math.max(Math.floor(this.slider.min),0),o=Math.min(this.positions.length-1,Math.floor(this.slider.max));e>=E.Layout&&((e,t,n,r)=>{C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.render.calculateLayoutInt(), start `);const o=this.canvas.height-r*n;let a;if(this.valueAggrType===i.AGG.TOTAL_COUNT){const e=this.getAlphabetSize();this.positionHeight==m.ES.Entropy&&null==e&&s.shell.error("WebLogo: alphabet is undefined."),a=Math.log2(e)}else a=Math.max(...c().count(e).takeWhile((e=>e<=t)).map((e=>this.positions[e].sumPlotValueForHeight)));for(let s=e;s<=t;++s)s in this.positions?this.positions[s].calcScreen(s,this.slider.min,o,this.positionHeight,a,this._positionWidthWithMargin,this._positionWidth,n,r):C._package.logger.warning(`Bio: WebLogoViewer<${this.viewerId}>.render.calculateLayoutInt() this.positions.length = ${this.positions.length}, jPos = ${s}`);C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.render.calculateLayoutInt(), end `),this._onLayoutCalculated.next()})(r,o,window.devicePixelRatio,n);const a=this.canvas.getContext("2d");if(a){a.save();try{this.Length,a.resetTransform(),a.fillStyle=function(e){const t=i.Color.a(e);return`#${(16777215&e).toString(16).padStart(6,"0")}`+t.toString(16).padStart(2,"0")}(this.backgroundColor),a.fillRect(0,0,this.canvas.width,this.canvas.height),a.textBaseline=this.textBaseline;const e=10*t;a.resetTransform(),a.fillStyle="black",a.textAlign="center",a.font=`${e.toFixed(1)}px Roboto, Roboto Local, sans-serif`,n>0&&this.positions.length>0&&function(e,t,n,s,r,i,o,a){e.save();try{e.textAlign="center";let l=null,c=null;for(let t=Math.floor(o);t<=Math.floor(a);t++){const n=i[t],s=e.measureText(n.name),r=s.actualBoundingBoxDescent-s.actualBoundingBoxAscent;l=null===l?s.width:Math.max(l,s.width),c=null===c?r:Math.max(c,r)}const u=l<s*t-2?1:(s*t-2)/l;for(let l=Math.floor(o);l<=Math.floor(a);l++){const a=i[l],h=(l-o)*n*t+s*t/2,d=(r*t-c)/2;e.setTransform(u,0,0,1,h,d),e.measureText(a.label),e.fillText(a.label,0,0)}}finally{e.restore()}}(a,t,this._positionWidthWithMargin,this._positionWidth,n,this.positions,this.slider.min,this.slider.max);const s="16px Roboto, Roboto Local, sans-serif",l=.25,c=12.2;for(let e=r;e<=o;e++)this.positions[e].render(a,s,l,c,this.palette)}finally{a.restore()}C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.render.renderInt( recalcLevel=${e} ), end`)}}renderRequestOnDebounce(e){const t=`${this.viewerToLog()}.renderRequestOnDebounce()`;"HTML"!==a()(this.root).offsetParent().get()[0]?.tagName?(this.requestedRenderLevel=E.None,this.viewSyncer.sync(t,(async()=>{await this.renderInt(e)}))):C._package.logger.warning(`${t}, $(this.root).offsetParent() is the 'HTML' tag.`)}getAlphabetSize(){return this.seqHandler?.getAlphabetSize()??0}sliderOnValuesChanged(e){try{const e={minRange:this.slider.minRange,min:this.slider.min,max:this.slider.max,maxRange:this.slider.maxRange};C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.sliderOnValuesChanged( ${JSON.stringify(e)} ), start`),this.render(E.Layout,"sliderOnValuesChanged")}catch(e){const t=p(e);C._package.logger.error(`Bio: WebLogoViewer<${this.viewerId}>.sliderOnValuesChanged() error:\n`+t)}}dataFrameFilterOnChanged(e){C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.dataFrameFilterChanged()`);try{this.filterSource===m.Ct.Filtered&&this.render(E.Freqs,"dataFrameFilterOnChanged")}catch(e){const t=p(e);C._package.logger.error(`Bio: WebLogoViewer<${this.viewerId}>.dataFrameFilterOnChanged() error:\n`+t)}}dataFrameSelectionOnChanged(e){C._package.logger.debug(`Bio: WebLogoViewer<${this.viewerId}>.dataFrameSelectionOnChanged()`);try{this.filterSource===m.Ct.Selected&&this.render(E.Freqs,"dataFrameSelectionOnChanged")}catch(e){const t=p(e);C._package.logger.error(`Bio: WebLogoViewer<${this.viewerId}>.dataFrameSelectionOnChanged() error:\n`+t)}}canvasOnMouseMove(e){const t=window.devicePixelRatio;try{const n=e,s=this.canvas.getCursorPosition(n,t),[o,a]=this.getMonomer(s,t),l=this.showPositionLabels?12*t:0;if(null!==o&&null===a&&0<=s.y&&s.y<=l){const e=[r.divText(`Position ${o.label}`)];this.valueAggrType===i.AGG.TOTAL_COUNT&&e.push(o.buildCompositionTable(this.palette));const t=r.divV(e);r.tooltip.show(t,n.x+16,n.y+16)}else if(null!==o&&a&&this.dataFrame&&this.seqCol&&this.seqHandler){const e=o.getFreq(a),t=[r.div(`${a}`),r.div(`${e.rowCount} rows`)];this.valueAggrType!==i.AGG.TOTAL_COUNT&&t.push(r.div(`${this.valueAggrType}: ${e.value.toFixed(3)}`));const s=r.divV(t);r.tooltip.show(s,n.x+16,n.y+16)}else r.tooltip.hide()}catch(e){const t=p(e);C._package.logger.error(`Bio: WebLogoViewer<${this.viewerId}>.canvasOnMouseMove() error:\n`+t)}}canvasOnMouseDown(e){try{const t=e,n=window.devicePixelRatio,[s,r]=this.getMonomer(this.canvas.getCursorPosition(t,n),n);if(null!==s&&null!==r&&this.dataFrame&&this.seqCol&&this.seqHandler){const e=i.BitSet.create(this.dataFrame.selection.length,(e=>function(e,t,n,s,r,i){const o=t.getSplitted(s),a=i.pos<o.length?o.getCanonical(i.pos):null;return null!==a&&a===r}(this.dataFrame,this.seqHandler,this.getFilter(),e,r,s)));this.dataFrame.selection.init((t=>e.get(t)))}}catch(e){const t=p(e);C._package.logger.error(`Bio: WebLogoViewer<${this.viewerId}>.canvasOnMouseDown() error:\n`+t)}}canvasOnWheel(e){const t=window.devicePixelRatio;try{if(!this.visibleSlider)return;const n=this.canvas.width/(this._positionWidthWithMargin*t),s=e.deltaY/100*Math.max(Math.floor(n/5),1);this.slider.scrollBy(this.slider.min+s)}catch(e){const t=p(e);C._package.logger.error(`Bio: WebLogoViewer<${this.viewerId}>.canvasOnWheel() error:\n`+t)}}get onRendered(){return this._onRendered}invalidate(e){const t=`invalidate(${e?` <- ${e} `:""})`,n=`${this.viewerToLog()}.${t}`;this.render(E.None,t),this.viewSyncer.sync(`${n}`,(async()=>{this._onRendered.next()}))}async awaitRendered(e=5e3){await(0,g.zg)(this.onRendered,(()=>{}),(()=>{this.invalidate()}),e);const t=this.viewSyncer.resetErrors();if(t.length>0)throw t[0]}}T.residuesSet="nucleotides",T.viewerCounter=-1},8755:(e,t,n)=>{"use strict";n.d(t,{Y:()=>o,x:()=>i});var s=n(701),r=n(3649);class i{constructor(e,t=!0){return this.substructure=e,this.readOnly=t,new Proxy(this,{set:(e,t,n)=>{if(r._package.logger.debug(`BioFilterProps.set ${t.toString()}( '${n}' )`),this.readOnly)throw new Error("Properties are immutable.");return e[t]=n,!0}})}}class o{constructor(){this.onChanged=new s.Subject,this._propsChanging=!1}get props(){return this._props||(this._props=this.emptyProps),this._props}set props(e){this._propsChanging=!0;try{this._props=e,this.applyProps(),this.onChanged.next()}finally{this._propsChanging=!1}}saveProps(){const e={};for(const[t,n]of Object.entries(this.props))"_onChanged"!==t&&(e[t]=this.props[t]);return e}async detach(){}get filterSummary(){return this.props.substructure}get isFiltering(){return""!==this.props.substructure}resetFilter(){this.props=this.emptyProps,this.onChanged.next()}}},5393:(e,t,n)=>{"use strict";n.d(t,{ST:()=>x});var s=n(3870),r=n(976),i=n(4469),o=n(6414),a=n.n(o),l=n(701),c=n(8447),u=n(8467),h=n(8260),d=n(172),m=n(7983),p=n(8755),f=n(3336),g=n.n(f),y=n(7945),b=n(4293),v=n(3649);class w extends p.Y{viewerToLog(){return`HelmBioFilter<${this.viewerId}>`}get type(){return"HelmBioFilter"}constructor(){super(),this.emptyProps=new p.x(""),this._filterPanel=s.div("",{style:{cursor:"pointer"}}),this.viewerId=++w.viewerCounter,this.viewSubs=[],this.logger=v._package.logger}async detach(){await super.detach();for(const e of this.viewSubs)e.unsubscribe()}async attach(){this.viewerToLog();try{const e=await async function(){const e="Helm",t=r.Func.find({package:e,name:"getHelmHelper"});if(0===t.length)throw new Error(`Package '${e}' must be installed for HelmHelper.`);return(await t[0].prepare().call()).getOutputParamValue()}();let t,n;this.helmEditor=e.createHelmWebEditor(),this.logger.warning("TEST: HelmBioFilter.init().sync() waitForElementInDom waiting..."),await s.tools.waitForElementInDom(this._filterPanel),this.logger.warning("TEST: HelmBioFilter.init().sync() waitForElementInDom ready"),this.updateFilterPanel(),this.viewSubs.push((0,l.fromEvent)(this._filterPanel,"click").subscribe((()=>{t=s.div(),n=e.createWebEditorApp(t,this.props.substructure),s.dialog({showHeader:!1,showFooter:!0}).add(t).onOK((()=>{try{const e=n.canvas.getHelm(!0).replace(/<\/span>/g,"").replace(/<span style='background:#bbf;'>/g,"");this.props=new p.x(e)}catch(e){this.logger.error(e)}finally{g()(t).empty(),t=null,n=null}})).onCancel((()=>{g()(t).empty(),t=null,n=null})).show({modal:!0,fullScreen:!0})}))),this.viewSubs.push(s.onSizeChanged(this._filterPanel).subscribe((e=>{try{if(n){const e=n.canvas.getHelm(!0).replace(/<\/span>/g,"").replace(/<span style='background:#bbf;'>/g,"");this.updateFilterPanel(e)}}catch(e){const[t,n]=(0,y.yf)(e);this.logger.error(t,void 0,n)}})))}catch(e){const[t,n]=(0,y.yf)(e),r=this._filterPanel;r.innerText="error",r.classList.add("d4-error"),s.tooltip.bind(r,t)}}applyProps(){this.helmEditor&&this.updateFilterPanel(this.props.substructure)}get filterPanel(){return this._filterPanel}updateFilterPanel(e){if(!this.helmEditor)throw new Error("helmEditor is not created, the filter is not in dom yet");const t=this._filterPanel.parentElement.clientWidth<100?100:this._filterPanel.parentElement.clientWidth,n=t/2;if(e)(0,b.Y)(this._filterPanel,this.helmEditor.host),this.helmEditor.editor.setHelm(e),this.helmEditor.resizeEditor(t,n);else{const e=s.divText("Click to edit","helm-substructure-filter");(0,b.Y)(this._filterPanel,e)}}async substructureSearch(e){return await(0,u.gw)(10),await(0,m.QF)(this.props.substructure,e)}}w.viewerCounter=-1;const C="bio-substructure-filter";class S{constructor(e,t,n,s,r){this.props=e,this.filterId=t,this.dataFrameId=n,this.columnName=s,this.bitset=r}}class A extends p.x{constructor(e,t){super(e,!1),this.separator=t,this.readOnly=!0}}class x extends r.Filter{get calculating(){return"initial"==this.loader.style.display}set calculating(e){this.loader.style.display=e?"initial":"none"}get filterSummary(){return this.bioFilter.filterSummary}get isFiltering(){return super.isFiltering&&(this.bioFilter?.isFiltering??!1)}get isReadyToApplyFilter(){return!this.calculating&&null!=this.bitset}get debounceTime(){if(null==this.column)return 1e3;const e=this.column.length;return e<500?0:e>1e4?1e3:Math.floor((e-500)/9500*1e3)}constructor(){return super(),this.bioFilter=null,this.bitset=null,this.notation=void 0,this.filterId=++x.filterCounter,this.viewSubs=[],this._onRendered=new l.Subject,this.root=s.divV([]),this.loader=s.loader(),this.calculating=!1,this.filterSyncer=new d.c(this.logger=v._package.logger),new Proxy(this,{set:(e,t,n)=>(e[t]=n,!0)})}filterToLog(){return`BioSubstructureFilter<${this.filterId}>`}attach(e){const t=super.attach.bind(this),n=`${this.filterToLog()}.attach()`;this.filterSyncer.sync(n,(async()=>{t(e),this.column||(this.columnName?this.column=this.dataFrame.getCol(this.columnName):this.column=e.columns.bySemType(r.SEMTYPE.MACROMOLECULE)),h.g.forColumn(this.column),this.columnName??(this.columnName=this.column?.name),this.notation??(this.notation=this.column?.getTag(r.TAGS.UNITS)),this.bioFilter=this.notation===c.r2.FASTA?new E:this.notation===c.r2.SEPARATOR?new I(this.column.getTag("separator")):new w,this.root.appendChild(this.bioFilter.filterPanel),this.root.appendChild(this.loader),await this.bioFilter.attach(),this.viewSubs.push(r.debounce(this.bioFilter.onChanged,this.debounceTime).subscribe(this.bioFilterOnChangedDebounced.bind(this))),this.viewSubs.push(i.events.onResetFilterRequest.subscribe(this.grokEventsOnResetFilterRequest.bind(this))),this.viewSubs.push(i.events.onCustomEvent(C).subscribe(this.filterOnSync.bind(this)))}))}detach(){const e=super.detach.bind(this),t=`${this.filterToLog()}.detach()`;this.filterSyncer.sync(t,(async()=>{for(const e of this.viewSubs)e.unsubscribe();this.viewSubs=[],e(),this.bioFilter&&this.bioFilter.detach(),this.bioFilter=null}))}filterOnSync(e){e.filterId!==this.filterId&&e.dataFrameId===this.dataFrame.id&&e.columnName===this.columnName&&(this.bioFilter.props=e.props)}applyFilter(){const e=`${this.filterToLog()}.applyFilter()`;this.logger.debug(`${e}, IN`),this.bitset&&!this.isDetached&&this.dataFrame?.filter.and(this.bitset)}saveState(){const e=`${this.filterToLog()}.saveState()`,t=super.saveState();return this.logger.debug(`${e}, super.state = ${JSON.stringify(t)}`),t.props=this.bioFilter.saveProps(),t}applyState(e){const t=`${this.filterToLog()}.applyState()`;super.applyState(e),this.filterSyncer.sync(t,(async()=>{e.props&&this.bioFilter&&(this.bioFilter.props=e.props)}))}fireFilterSync(){const e=`${this.filterToLog()}.fireFilterSync()`;v._package.logger.debug(`${e}, bioFilter = ${this.bioFilter?this.bioFilter.constructor.name:"null"}`+(this.bioFilter?`, props = ${JSON.stringify(this.bioFilter.saveProps())}`:"")),i.events.fireCustomEvent(C,new S(this.bioFilter.props,this.filterId,this.dataFrame.id,this.columnName,this.bitset))}bioFilterOnChangedDebounced(){if(!this.dataFrame)return;const e=`${this.filterToLog()}.bioFilterOnChangedDebounced()`;if(v._package.logger.debug(`${e}, start, isFiltering = ${this.isFiltering}, props = ${JSON.stringify(this.bioFilter.saveProps())}`),!this.isFiltering)return this.bitset=null,void this.dataFrame.rows.requestFilter();a()(this.dataFrame.rows.filters).has(`${this.columnName}: ${this.filterSummary}`)||this.filterSyncer.sync(e,(async()=>{this.calculating=!0;try{v._package.logger.debug(`${e}, before substructureSearch`),this.bitset=await(this.bioFilter?.substructureSearch(this.column)),v._package.logger.debug(`${e}, after substructureSearch`),this.calculating=!1,this.fireFilterSync(),this.dataFrame?.rows.requestFilter()}finally{this.calculating=!1,v._package.logger.debug(`${e}, end`)}}))}grokEventsOnResetFilterRequest(){const e=`${this.filterToLog()}.grokEventsOnResetFilterRequest()`;v._package.logger.debug(`${e}`),this.bioFilter?.resetFilter()}get onRendered(){return this._onRendered}invalidate(e){const t=`${this.filterToLog()}.invalidate(${e?` <- ${e} `:""})`;this.filterSyncer.sync(t,(async()=>{this._onRendered.next()}))}async awaitRendered(e=1e4){const t=`awaitRendered( ${e} )`,n=`${this.filterToLog()}.${t}`;await(0,u.gw)(0),await(0,u.zg)(this.onRendered,(()=>{this.logger.debug(`${n}, _onRendered event caught`)}),(()=>{this.invalidate(t)}),e,`${n} ${e} timeout`);const s=this.filterSyncer.resetErrors();if(s.length>0)throw s[0]}}x.filterCounter=-1;class E extends p.Y{get type(){return"FastaBioFilter"}constructor(){super(),this.emptyProps=new p.x(""),this.substructureInput=s.stringInput("","",(()=>{this.props=new p.x(this.substructureInput.value),this._propsChanging||this.onChanged.next()}),{placeholder:"Substructure"})}applyProps(){this.substructureInput.value!==this.props.substructure&&(this.substructureInput.value=this.props.substructure)}get filterPanel(){return this.substructureInput.root}get isFiltering(){return""!==this.substructureInput.value}async substructureSearch(e){return(0,m.pf)(this.props.substructure,e)}async attach(){}async detach(){await super.detach()}}class I extends p.Y{get type(){return"SeparatorBioFilter"}constructor(e){super(),this.emptyProps=new A("",void 0),this.colSeparator="",this.substructureInput=s.stringInput("","",(()=>{this.props=new A(this.substructureInput.value,this.props.separator),this._propsChanging||this.onChanged.next()}),{placeholder:"Substructure"}),this.separatorInput=s.stringInput("",this.colSeparator=e,(()=>{const e=this.separatorInput.value?this.separatorInput.value:void 0;this.props=new A(this.props.substructure,e),this._propsChanging||this.onChanged.next()}),{placeholder:"Separator"})}applyProps(){this.substructureInput.value!==this.props.substructure&&(this.substructureInput.value=this.props.substructure);const e=this.props.separator??this.colSeparator;this.separatorInput.value!==e&&(this.separatorInput.value=e)}get filterSummary(){return this.props.separator?this.props.separator:this.colSeparator,`${this.props.substructure}, {sep}`}get isFiltering(){return""!==this.props.substructure}resetFilter(){this.props=new A("")}get filterPanel(){return s.divV([this.substructureInput.root,this.separatorInput.root])}get substructure(){return this.separatorInput.value&&this.separatorInput.value!==this.colSeparator?this.substructureInput.value.replaceAll(this.separatorInput.value,this.colSeparator):this.substructureInput.value}set substructure(e){this.substructureInput.value=e}async substructureSearch(e){return(0,m.pf)(this.substructure,e,this.colSeparator)}async attach(){}async detach(){await super.detach()}}},8770:(e,t,n)=>{"use strict";n.d(t,{_:()=>I,t:()=>E});var s=n(3870),r=n(976),i=n(6414),o=n.n(i),a=n(8447),l=n(7331),c=n(3379),u=n.n(c),h=n(7795),d=n.n(h),m=n(569),p=n.n(m),f=n(3565),g=n.n(f),y=n(9216),b=n.n(y),v=n(4589),w=n.n(v),C=n(5362),S={};S.styleTagTransform=w(),S.setAttributes=g(),S.insert=p().bind(null,"head"),S.domAPI=d(),S.insertStyleElement=b(),u()(C.Z,S),C.Z&&C.Z.locals&&C.Z.locals;var A=n(8260),x=n(6286);function E(e){const t=s.div();t.classList.add("macromolecule-cell-comp-analysis-host");const n=e.cell.column.tags.alphabet;let i=l.UE.Color;switch(n){case"DNA":case"RNA":i=(0,a.py)("DNA");break;case"PT":i=(0,a.py)("PT")}const c={},u=A.g.forColumn(e.cell.column),h=e.cell.rowIndex,d=u.getSplitted(h);o()(d.canonicals).filter((e=>e!==x.G2)).forEach((e=>{const t=c[e]||0;c[e]=t+1}));const m=I(i,c);return Array.from(m.rows).forEach((e=>{const t=e.getElementsByClassName("macromolecule-cell-comp-analysis-bar")[0].style.backgroundColor;e.cells[0].style.color=t})),t.appendChild(m),new r.Widget(t)}function I(e,t){let n=0,i=null;for(const e of Object.values(t))n+=e,i=null===i?e:Math.max(i,e);const o=i/n,a=Object.assign({},...Array.from(Object.entries(t)).sort(((e,t)=>t[1]-e[1])).map((([t,i])=>{const a=i/n,l=e.get(t),c=s.div("",{classes:"macromolecule-cell-comp-analysis-bar"});c.style.width=50*a/o+"px",c.style.backgroundColor=l,x.G2===t&&(c.style.borderWidth="1px",c.style.borderStyle="solid",c.style.borderColor=r.Color.toHtml(r.Color.lightGray));const u=x.G2===t?"-":t,h=s.div(`${(100*a).toFixed(2)}%`);return{[u]:s.div([c,h],{classes:"macromolecule-cell-comp-analysis-value"})}}))),l=s.tableFromMap(a);return Array.from(l.rows).forEach((e=>{const t=e.getElementsByClassName("macromolecule-cell-comp-analysis-bar")[0].style.backgroundColor;e.cells[0].style.color=t})),l}},540:function(e,t){!function(e){"use strict";function t(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];if(t.length>1){t[0]=t[0].slice(0,-1);for(var s=t.length-1,r=1;r<s;++r)t[r]=t[r].slice(1,-1);return t[s]=t[s].slice(1),t.join("")}return t[0]}function n(e){return"(?:"+e+")"}function s(e){return void 0===e?"undefined":null===e?"null":Object.prototype.toString.call(e).split(" ").pop().split("]").shift().toLowerCase()}function r(e){return e.toUpperCase()}function i(e){var s="[A-Za-z]",r="[0-9]",i=t(r,"[A-Fa-f]"),o=n(n("%[EFef]"+i+"%"+i+i+"%"+i+i)+"|"+n("%[89A-Fa-f]"+i+"%"+i+i)+"|"+n("%"+i+i)),a="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",l=t("[\\:\\/\\?\\#\\[\\]\\@]",a),c=e?"[\\uE000-\\uF8FF]":"[]",u=t(s,r,"[\\-\\.\\_\\~]",e?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\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"+O+")",j=(n(D+"|"+B+"|"+V+"|"+U+"|"+H),n(n(O+"|"+t("[\\/\\?]",c))+"*")),W=n(n(O+"|[\\/\\?]")+"*"),Y=n(n("\\/\\/"+R+D)+"|"+B+"|"+U+"|"+H),Z=n(h+"\\:"+Y+n("\\?"+j)+"?"+n("\\#"+W)+"?"),K=n(n("\\/\\/"+R+D)+"|"+B+"|"+V+"|"+H),q=n(K+n("\\?"+j)+"?"+n("\\#"+W)+"?");return n(Z+"|"+q),n(h+"\\:"+Y+n("\\?"+j)+"?"),n(n("\\/\\/("+n("("+d+")@")+"?("+L+")"+n("\\:("+P+")")+"?)")+"?("+D+"|"+B+"|"+U+"|"+H+")"),n("\\?("+j+")"),n("\\#("+W+")"),n(n("\\/\\/("+n("("+d+")@")+"?("+L+")"+n("\\:("+P+")")+"?)")+"?("+D+"|"+B+"|"+V+"|"+H+")"),n("\\?("+j+")"),n("\\#("+W+")"),n(n("\\/\\/("+n("("+d+")@")+"?("+L+")"+n("\\:("+P+")")+"?)")+"?("+D+"|"+B+"|"+U+"|"+H+")"),n("\\?("+j+")"),n("\\#("+W+")"),n("("+d+")@"),n("\\:("+P+")"),{NOT_SCHEME:new RegExp(t("[^]",s,r,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(t("[^\\%\\:]",u,a),"g"),NOT_HOST:new RegExp(t("[^\\%\\[\\]\\:]",u,a),"g"),NOT_PATH:new RegExp(t("[^\\%\\/\\:\\@]",u,a),"g"),NOT_PATH_NOSCHEME:new RegExp(t("[^\\%\\/\\@]",u,a),"g"),NOT_QUERY:new RegExp(t("[^\\%]",u,a,"[\\:\\@\\/\\?]",c),"g"),NOT_FRAGMENT:new RegExp(t("[^\\%]",u,a,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(t("[^]",u,a),"g"),UNRESERVED:new RegExp(u,"g"),OTHER_CHARS:new RegExp(t("[^\\%]",u,l),"g"),PCT_ENCODED:new RegExp(o,"g"),IPV4ADDRESS:new RegExp("^("+p+")$"),IPV6ADDRESS:new RegExp("^\\[?("+I+")"+n(n("\\%25|\\%(?!"+i+"{2})")+"("+T+")")+"?\\]?$")}}var o=i(!1),a=i(!0),l=function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var n=[],s=!0,r=!1,i=void 0;try{for(var o,a=e[Symbol.iterator]();!(s=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);s=!0);}catch(e){r=!0,i=e}finally{try{!s&&a.return&&a.return()}finally{if(r)throw i}}return n}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")},c=2147483647,u=36,h=/^xn--/,d=/[^\0-\x7E]/,m=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},f=Math.floor,g=String.fromCharCode;function y(e){throw new RangeError(p[e])}function b(e,t){var n=e.split("@"),s="";return n.length>1&&(s=n[0]+"@",e=n[1]),s+function(e,t){for(var n=[],s=e.length;s--;)n[s]=t(e[s]);return n}((e=e.replace(m,".")).split("."),t).join(".")}function v(e){for(var t=[],n=0,s=e.length;n<s;){var r=e.charCodeAt(n++);if(r>=55296&&r<=56319&&n<s){var i=e.charCodeAt(n++);56320==(64512&i)?t.push(((1023&r)<<10)+(1023&i)+65536):(t.push(r),n--)}else t.push(r)}return t}var w=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},C=function(e,t,n){var s=0;for(e=n?f(e/700):e>>1,e+=f(e/t);e>455;s+=u)e=f(e/35);return f(s+36*e/(e+38))},S=function(e){var t,n=[],s=e.length,r=0,i=128,o=72,a=e.lastIndexOf("-");a<0&&(a=0);for(var l=0;l<a;++l)e.charCodeAt(l)>=128&&y("not-basic"),n.push(e.charCodeAt(l));for(var h=a>0?a+1:0;h<s;){for(var d=r,m=1,p=u;;p+=u){h>=s&&y("invalid-input");var g=(t=e.charCodeAt(h++))-48<10?t-22:t-65<26?t-65:t-97<26?t-97:u;(g>=u||g>f((c-r)/m))&&y("overflow"),r+=g*m;var b=p<=o?1:p>=o+26?26:p-o;if(g<b)break;var v=u-b;m>f(c/v)&&y("overflow"),m*=v}var w=n.length+1;o=C(r-d,w,0==d),f(r/w)>c-i&&y("overflow"),i+=f(r/w),r%=w,n.splice(r++,0,i)}return String.fromCodePoint.apply(String,n)},A=function(e){var t=[],n=(e=v(e)).length,s=128,r=0,i=72,o=!0,a=!1,l=void 0;try{for(var h,d=e[Symbol.iterator]();!(o=(h=d.next()).done);o=!0){var m=h.value;m<128&&t.push(g(m))}}catch(e){a=!0,l=e}finally{try{!o&&d.return&&d.return()}finally{if(a)throw l}}var p=t.length,b=p;for(p&&t.push("-");b<n;){var S=c,A=!0,x=!1,E=void 0;try{for(var I,T=e[Symbol.iterator]();!(A=(I=T.next()).done);A=!0){var _=I.value;_>=s&&_<S&&(S=_)}}catch(e){x=!0,E=e}finally{try{!A&&T.return&&T.return()}finally{if(x)throw E}}var M=b+1;S-s>f((c-r)/M)&&y("overflow"),r+=(S-s)*M,s=S;var $=!0,N=!1,L=void 0;try{for(var P,R=e[Symbol.iterator]();!($=(P=R.next()).done);$=!0){var O=P.value;if(O<s&&++r>c&&y("overflow"),O==s){for(var k=r,F=u;;F+=u){var G=F<=i?1:F>=i+26?26:F-i;if(k<G)break;var D=k-G,B=u-G;t.push(g(w(G+D%B,0))),k=f(D/B)}t.push(g(w(k,0))),i=C(r,M,b==p),r=0,++b}}}catch(e){N=!0,L=e}finally{try{!$&&R.return&&R.return()}finally{if(N)throw L}}++r,++s}return t.join("")},x={version:"2.1.0",ucs2:{decode:v,encode:function(e){return String.fromCodePoint.apply(String,function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}(e))}},decode:S,encode:A,toASCII:function(e){return b(e,(function(e){return d.test(e)?"xn--"+A(e):e}))},toUnicode:function(e){return b(e,(function(e){return h.test(e)?S(e.slice(4).toLowerCase()):e}))}},E={};function I(e){var t=e.charCodeAt(0);return t<16?"%0"+t.toString(16).toUpperCase():t<128?"%"+t.toString(16).toUpperCase():t<2048?"%"+(t>>6|192).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase():"%"+(t>>12|224).toString(16).toUpperCase()+"%"+(t>>6&63|128).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase()}function T(e){for(var t="",n=0,s=e.length;n<s;){var r=parseInt(e.substr(n+1,2),16);if(r<128)t+=String.fromCharCode(r),n+=3;else if(r>=194&&r<224){if(s-n>=6){var i=parseInt(e.substr(n+4,2),16);t+=String.fromCharCode((31&r)<<6|63&i)}else t+=e.substr(n,6);n+=6}else if(r>=224){if(s-n>=9){var o=parseInt(e.substr(n+4,2),16),a=parseInt(e.substr(n+7,2),16);t+=String.fromCharCode((15&r)<<12|(63&o)<<6|63&a)}else t+=e.substr(n,9);n+=9}else t+=e.substr(n,3),n+=3}return t}function _(e,t){function n(e){var n=T(e);return n.match(t.UNRESERVED)?n:e}return e.scheme&&(e.scheme=String(e.scheme).replace(t.PCT_ENCODED,n).toLowerCase().replace(t.NOT_SCHEME,"")),void 0!==e.userinfo&&(e.userinfo=String(e.userinfo).replace(t.PCT_ENCODED,n).replace(t.NOT_USERINFO,I).replace(t.PCT_ENCODED,r)),void 0!==e.host&&(e.host=String(e.host).replace(t.PCT_ENCODED,n).toLowerCase().replace(t.NOT_HOST,I).replace(t.PCT_ENCODED,r)),void 0!==e.path&&(e.path=String(e.path).replace(t.PCT_ENCODED,n).replace(e.scheme?t.NOT_PATH:t.NOT_PATH_NOSCHEME,I).replace(t.PCT_ENCODED,r)),void 0!==e.query&&(e.query=String(e.query).replace(t.PCT_ENCODED,n).replace(t.NOT_QUERY,I).replace(t.PCT_ENCODED,r)),void 0!==e.fragment&&(e.fragment=String(e.fragment).replace(t.PCT_ENCODED,n).replace(t.NOT_FRAGMENT,I).replace(t.PCT_ENCODED,r)),e}function M(e){return e.replace(/^0*(.*)/,"$1")||"0"}function $(e,t){var n=e.match(t.IPV4ADDRESS)||[],s=l(n,2)[1];return s?s.split(".").map(M).join("."):e}function N(e,t){var n=e.match(t.IPV6ADDRESS)||[],s=l(n,3),r=s[1],i=s[2];if(r){for(var o=r.toLowerCase().split("::").reverse(),a=l(o,2),c=a[0],u=a[1],h=u?u.split(":").map(M):[],d=c.split(":").map(M),m=t.IPV4ADDRESS.test(d[d.length-1]),p=m?7:8,f=d.length-p,g=Array(p),y=0;y<p;++y)g[y]=h[y]||d[f+y]||"";m&&(g[p-1]=$(g[p-1],t));var b=g.reduce((function(e,t,n){if(!t||"0"===t){var s=e[e.length-1];s&&s.index+s.length===n?s.length++:e.push({index:n,length:1})}return e}),[]).sort((function(e,t){return t.length-e.length}))[0],v=void 0;if(b&&b.length>1){var w=g.slice(0,b.index),C=g.slice(b.index+b.length);v=w.join(":")+"::"+C.join(":")}else v=g.join(":");return i&&(v+="%"+i),v}return e}var L=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,P=void 0==="".match(/(){0}/)[1];function R(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={},s=!1!==t.iri?a:o;"suffix"===t.reference&&(e=(t.scheme?t.scheme+":":"")+"//"+e);var r=e.match(L);if(r){P?(n.scheme=r[1],n.userinfo=r[3],n.host=r[4],n.port=parseInt(r[5],10),n.path=r[6]||"",n.query=r[7],n.fragment=r[8],isNaN(n.port)&&(n.port=r[5])):(n.scheme=r[1]||void 0,n.userinfo=-1!==e.indexOf("@")?r[3]:void 0,n.host=-1!==e.indexOf("//")?r[4]:void 0,n.port=parseInt(r[5],10),n.path=r[6]||"",n.query=-1!==e.indexOf("?")?r[7]:void 0,n.fragment=-1!==e.indexOf("#")?r[8]:void 0,isNaN(n.port)&&(n.port=e.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?r[4]:void 0)),n.host&&(n.host=N($(n.host,s),s)),void 0!==n.scheme||void 0!==n.userinfo||void 0!==n.host||void 0!==n.port||n.path||void 0!==n.query?void 0===n.scheme?n.reference="relative":void 0===n.fragment?n.reference="absolute":n.reference="uri":n.reference="same-document",t.reference&&"suffix"!==t.reference&&t.reference!==n.reference&&(n.error=n.error||"URI is not a "+t.reference+" reference.");var i=E[(t.scheme||n.scheme||"").toLowerCase()];if(t.unicodeSupport||i&&i.unicodeSupport)_(n,s);else{if(n.host&&(t.domainHost||i&&i.domainHost))try{n.host=x.toASCII(n.host.replace(s.PCT_ENCODED,T).toLowerCase())}catch(e){n.error=n.error||"Host's domain name can not be converted to ASCII via punycode: "+e}_(n,o)}i&&i.parse&&i.parse(n,t)}else n.error=n.error||"URI can not be parsed.";return n}var O=/^\.\.?\//,k=/^\/\.(\/|$)/,F=/^\/\.\.(\/|$)/,G=/^\/?(?:.|\n)*?(?=\/|$)/;function D(e){for(var t=[];e.length;)if(e.match(O))e=e.replace(O,"");else if(e.match(k))e=e.replace(k,"/");else if(e.match(F))e=e.replace(F,"/"),t.pop();else if("."===e||".."===e)e="";else{var n=e.match(G);if(!n)throw new Error("Unexpected dot segment condition");var s=n[0];e=e.slice(s.length),t.push(s)}return t.join("")}function B(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.iri?a:o,s=[],r=E[(t.scheme||e.scheme||"").toLowerCase()];if(r&&r.serialize&&r.serialize(e,t),e.host)if(n.IPV6ADDRESS.test(e.host));else if(t.domainHost||r&&r.domainHost)try{e.host=t.iri?x.toUnicode(e.host):x.toASCII(e.host.replace(n.PCT_ENCODED,T).toLowerCase())}catch(n){e.error=e.error||"Host's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+n}_(e,n),"suffix"!==t.reference&&e.scheme&&(s.push(e.scheme),s.push(":"));var i=function(e,t){var n=!1!==t.iri?a:o,s=[];return void 0!==e.userinfo&&(s.push(e.userinfo),s.push("@")),void 0!==e.host&&s.push(N($(String(e.host),n),n).replace(n.IPV6ADDRESS,(function(e,t,n){return"["+t+(n?"%25"+n:"")+"]"}))),"number"!=typeof e.port&&"string"!=typeof e.port||(s.push(":"),s.push(String(e.port))),s.length?s.join(""):void 0}(e,t);if(void 0!==i&&("suffix"!==t.reference&&s.push("//"),s.push(i),e.path&&"/"!==e.path.charAt(0)&&s.push("/")),void 0!==e.path){var l=e.path;t.absolutePath||r&&r.absolutePath||(l=D(l)),void 0===i&&(l=l.replace(/^\/\//,"/%2F")),s.push(l)}return void 0!==e.query&&(s.push("?"),s.push(e.query)),void 0!==e.fragment&&(s.push("#"),s.push(e.fragment)),s.join("")}function V(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s={};return arguments[3]||(e=R(B(e,n),n),t=R(B(t,n),n)),!(n=n||{}).tolerant&&t.scheme?(s.scheme=t.scheme,s.userinfo=t.userinfo,s.host=t.host,s.port=t.port,s.path=D(t.path||""),s.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(s.userinfo=t.userinfo,s.host=t.host,s.port=t.port,s.path=D(t.path||""),s.query=t.query):(t.path?("/"===t.path.charAt(0)?s.path=D(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?s.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:s.path=t.path:s.path="/"+t.path,s.path=D(s.path)),s.query=t.query):(s.path=e.path,void 0!==t.query?s.query=t.query:s.query=e.query),s.userinfo=e.userinfo,s.host=e.host,s.port=e.port),s.scheme=e.scheme),s.fragment=t.fragment,s}function U(e,t){return e&&e.toString().replace(t&&t.iri?a.PCT_ENCODED:o.PCT_ENCODED,T)}var H={scheme:"http",domainHost:!0,parse:function(e,t){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e},serialize:function(e,t){var n="https"===String(e.scheme).toLowerCase();return e.port!==(n?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}},j={scheme:"https",domainHost:H.domainHost,parse:H.parse,serialize:H.serialize};function W(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}var Y={scheme:"ws",domainHost:!0,parse:function(e,t){var n=e;return n.secure=W(n),n.resourceName=(n.path||"/")+(n.query?"?"+n.query:""),n.path=void 0,n.query=void 0,n},serialize:function(e,t){if(e.port!==(W(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){var n=e.resourceName.split("?"),s=l(n,2),r=s[0],i=s[1];e.path=r&&"/"!==r?r:void 0,e.query=i,e.resourceName=void 0}return e.fragment=void 0,e}},Z={scheme:"wss",domainHost:Y.domainHost,parse:Y.parse,serialize:Y.serialize},K={},q="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",z="[0-9A-Fa-f]",X=n(n("%[EFef]"+z+"%"+z+z+"%"+z+z)+"|"+n("%[89A-Fa-f]"+z+"%"+z+z)+"|"+n("%"+z+z)),J=t("[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",'[\\"\\\\]'),Q=new RegExp(q,"g"),ee=new RegExp(X,"g"),te=new RegExp(t("[^]","[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]","[\\.]",'[\\"]',J),"g"),ne=new RegExp(t("[^]",q,"[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"),"g"),se=ne;function re(e){var t=T(e);return t.match(Q)?t:e}var ie={scheme:"mailto",parse:function(e,t){var n=e,s=n.to=n.path?n.path.split(","):[];if(n.path=void 0,n.query){for(var r=!1,i={},o=n.query.split("&"),a=0,l=o.length;a<l;++a){var c=o[a].split("=");switch(c[0]){case"to":for(var u=c[1].split(","),h=0,d=u.length;h<d;++h)s.push(u[h]);break;case"subject":n.subject=U(c[1],t);break;case"body":n.body=U(c[1],t);break;default:r=!0,i[U(c[0],t)]=U(c[1],t)}}r&&(n.headers=i)}n.query=void 0;for(var m=0,p=s.length;m<p;++m){var f=s[m].split("@");if(f[0]=U(f[0]),t.unicodeSupport)f[1]=U(f[1],t).toLowerCase();else try{f[1]=x.toASCII(U(f[1],t).toLowerCase())}catch(e){n.error=n.error||"Email address's domain name can not be converted to ASCII via punycode: "+e}s[m]=f.join("@")}return n},serialize:function(e,t){var n,s=e,i=null!=(n=e.to)?n instanceof Array?n:"number"!=typeof n.length||n.split||n.setInterval||n.call?[n]:Array.prototype.slice.call(n):[];if(i){for(var o=0,a=i.length;o<a;++o){var l=String(i[o]),c=l.lastIndexOf("@"),u=l.slice(0,c).replace(ee,re).replace(ee,r).replace(te,I),h=l.slice(c+1);try{h=t.iri?x.toUnicode(h):x.toASCII(U(h,t).toLowerCase())}catch(e){s.error=s.error||"Email address's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+e}i[o]=u+"@"+h}s.path=i.join(",")}var d=e.headers=e.headers||{};e.subject&&(d.subject=e.subject),e.body&&(d.body=e.body);var m=[];for(var p in d)d[p]!==K[p]&&m.push(p.replace(ee,re).replace(ee,r).replace(ne,I)+"="+d[p].replace(ee,re).replace(ee,r).replace(se,I));return m.length&&(s.query=m.join("&")),s}},oe=/^([^\:]+)\:(.*)/,ae={scheme:"urn",parse:function(e,t){var n=e.path&&e.path.match(oe),s=e;if(n){var r=t.scheme||s.scheme||"urn",i=n[1].toLowerCase(),o=n[2],a=r+":"+(t.nid||i),l=E[a];s.nid=i,s.nss=o,s.path=void 0,l&&(s=l.parse(s,t))}else s.error=s.error||"URN can not be parsed.";return s},serialize:function(e,t){var n=t.scheme||e.scheme||"urn",s=e.nid,r=n+":"+(t.nid||s),i=E[r];i&&(e=i.serialize(e,t));var o=e,a=e.nss;return o.path=(s||t.nid)+":"+a,o}},le=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,ce={scheme:"urn:uuid",parse:function(e,t){var n=e;return n.uuid=n.nss,n.nss=void 0,t.tolerant||n.uuid&&n.uuid.match(le)||(n.error=n.error||"UUID is not valid."),n},serialize:function(e,t){var n=e;return n.nss=(e.uuid||"").toLowerCase(),n}};E[H.scheme]=H,E[j.scheme]=j,E[Y.scheme]=Y,E[Z.scheme]=Z,E[ie.scheme]=ie,E[ae.scheme]=ae,E[ce.scheme]=ce,e.SCHEMES=E,e.pctEncChar=I,e.pctDecChars=T,e.parse=R,e.removeDotSegments=D,e.serialize=B,e.resolveComponents=V,e.resolve=function(e,t,n){var s=function(e,t){var n=e;if(t)for(var s in t)n[s]=t[s];return n}({scheme:"null"},n);return B(V(R(e,s),R(t,s),s,!0),s)},e.normalize=function(e,t){return"string"==typeof e?e=B(R(e,t),t):"object"===s(e)&&(e=R(B(e,t),t)),e},e.equal=function(e,t,n){return"string"==typeof e?e=B(R(e,n),n):"object"===s(e)&&(e=B(e,n)),"string"==typeof t?t=B(R(t,n),n):"object"===s(t)&&(t=B(t,n)),e===t},e.escapeComponent=function(e,t){return e&&e.toString().replace(t&&t.iri?a.ESCAPE:o.ESCAPE,I)},e.unescapeComponent=U,Object.defineProperty(e,"__esModule",{value:!0})}(t)},3336:e=>{"use strict";e.exports=$},976:e=>{"use strict";e.exports=DG},4469:e=>{"use strict";e.exports=grok},701:e=>{"use strict";e.exports=rxjs},442:e=>{"use strict";e.exports=rxjs.operators},3870:e=>{"use strict";e.exports=ui},6414:e=>{"use strict";e.exports=wu},4775:e=>{"use strict";e.exports=JSON.parse('{"$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON AnySchema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}')},996:e=>{"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/applicator","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/applicator":true},"$dynamicAnchor":"meta","title":"Applicator vocabulary meta-schema","type":["object","boolean"],"properties":{"prefixItems":{"$ref":"#/$defs/schemaArray"},"items":{"$dynamicRef":"#meta"},"contains":{"$dynamicRef":"#meta"},"additionalProperties":{"$dynamicRef":"#meta"},"properties":{"type":"object","additionalProperties":{"$dynamicRef":"#meta"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$dynamicRef":"#meta"},"propertyNames":{"format":"regex"},"default":{}},"dependentSchemas":{"type":"object","additionalProperties":{"$dynamicRef":"#meta"},"default":{}},"propertyNames":{"$dynamicRef":"#meta"},"if":{"$dynamicRef":"#meta"},"then":{"$dynamicRef":"#meta"},"else":{"$dynamicRef":"#meta"},"allOf":{"$ref":"#/$defs/schemaArray"},"anyOf":{"$ref":"#/$defs/schemaArray"},"oneOf":{"$ref":"#/$defs/schemaArray"},"not":{"$dynamicRef":"#meta"}},"$defs":{"schemaArray":{"type":"array","minItems":1,"items":{"$dynamicRef":"#meta"}}}}')},6795:e=>{"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/content","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/content":true},"$dynamicAnchor":"meta","title":"Content vocabulary meta-schema","type":["object","boolean"],"properties":{"contentEncoding":{"type":"string"},"contentMediaType":{"type":"string"},"contentSchema":{"$dynamicRef":"#meta"}}}')},235:e=>{"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/core","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/core":true},"$dynamicAnchor":"meta","title":"Core vocabulary meta-schema","type":["object","boolean"],"properties":{"$id":{"$ref":"#/$defs/uriReferenceString","$comment":"Non-empty fragments not allowed.","pattern":"^[^#]*#?$"},"$schema":{"$ref":"#/$defs/uriString"},"$ref":{"$ref":"#/$defs/uriReferenceString"},"$anchor":{"$ref":"#/$defs/anchorString"},"$dynamicRef":{"$ref":"#/$defs/uriReferenceString"},"$dynamicAnchor":{"$ref":"#/$defs/anchorString"},"$vocabulary":{"type":"object","propertyNames":{"$ref":"#/$defs/uriString"},"additionalProperties":{"type":"boolean"}},"$comment":{"type":"string"},"$defs":{"type":"object","additionalProperties":{"$dynamicRef":"#meta"}}},"$defs":{"anchorString":{"type":"string","pattern":"^[A-Za-z_][-A-Za-z0-9._]*$"},"uriString":{"type":"string","format":"uri"},"uriReferenceString":{"type":"string","format":"uri-reference"}}}')},2567:e=>{"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/format-annotation","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/format-annotation":true},"$dynamicAnchor":"meta","title":"Format vocabulary meta-schema for annotation results","type":["object","boolean"],"properties":{"format":{"type":"string"}}}')},1233:e=>{"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/meta-data","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/meta-data":true},"$dynamicAnchor":"meta","title":"Meta-data vocabulary meta-schema","type":["object","boolean"],"properties":{"title":{"type":"string"},"description":{"type":"string"},"default":true,"deprecated":{"type":"boolean","default":false},"readOnly":{"type":"boolean","default":false},"writeOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true}}}')},5568:e=>{"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/unevaluated","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/unevaluated":true},"$dynamicAnchor":"meta","title":"Unevaluated applicator vocabulary meta-schema","type":["object","boolean"],"properties":{"unevaluatedItems":{"$dynamicRef":"#meta"},"unevaluatedProperties":{"$dynamicRef":"#meta"}}}')},1968:e=>{"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/validation","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/validation":true},"$dynamicAnchor":"meta","title":"Validation vocabulary meta-schema","type":["object","boolean"],"properties":{"type":{"anyOf":[{"$ref":"#/$defs/simpleTypes"},{"type":"array","items":{"$ref":"#/$defs/simpleTypes"},"minItems":1,"uniqueItems":true}]},"const":true,"enum":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/$defs/nonNegativeInteger"},"minLength":{"$ref":"#/$defs/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"maxItems":{"$ref":"#/$defs/nonNegativeInteger"},"minItems":{"$ref":"#/$defs/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"maxContains":{"$ref":"#/$defs/nonNegativeInteger"},"minContains":{"$ref":"#/$defs/nonNegativeInteger","default":1},"maxProperties":{"$ref":"#/$defs/nonNegativeInteger"},"minProperties":{"$ref":"#/$defs/nonNegativeIntegerDefault0"},"required":{"$ref":"#/$defs/stringArray"},"dependentRequired":{"type":"object","additionalProperties":{"$ref":"#/$defs/stringArray"}}},"$defs":{"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"$ref":"#/$defs/nonNegativeInteger","default":0},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}}}')},2577:e=>{"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/schema","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/core":true,"https://json-schema.org/draft/2020-12/vocab/applicator":true,"https://json-schema.org/draft/2020-12/vocab/unevaluated":true,"https://json-schema.org/draft/2020-12/vocab/validation":true,"https://json-schema.org/draft/2020-12/vocab/meta-data":true,"https://json-schema.org/draft/2020-12/vocab/format-annotation":true,"https://json-schema.org/draft/2020-12/vocab/content":true},"$dynamicAnchor":"meta","title":"Core and Validation specifications meta-schema","allOf":[{"$ref":"meta/core"},{"$ref":"meta/applicator"},{"$ref":"meta/unevaluated"},{"$ref":"meta/validation"},{"$ref":"meta/meta-data"},{"$ref":"meta/format-annotation"},{"$ref":"meta/content"}],"type":["object","boolean"],"$comment":"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.","properties":{"definitions":{"$comment":"\\"definitions\\" has been replaced by \\"$defs\\".","type":"object","additionalProperties":{"$dynamicRef":"#meta"},"deprecated":true,"default":{}},"dependencies":{"$comment":"\\"dependencies\\" has been split and replaced by \\"dependentSchemas\\" and \\"dependentRequired\\" in order to serve their differing semantics.","type":"object","additionalProperties":{"anyOf":[{"$dynamicRef":"#meta"},{"$ref":"meta/validation#/$defs/stringArray"}]},"deprecated":true,"default":{}},"$recursiveAnchor":{"$comment":"\\"$recursiveAnchor\\" has been replaced by \\"$dynamicAnchor\\".","$ref":"meta/core#/$defs/anchorString","deprecated":true},"$recursiveRef":{"$comment":"\\"$recursiveRef\\" has been replaced by \\"$dynamicRef\\".","$ref":"meta/core#/$defs/uriReferenceString","deprecated":true}}}')},98:e=>{"use strict";e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}')}},t={};function n(s){var r=t[s];if(void 0!==r)return r.exports;var i=t[s]={id:s,loaded:!1,exports:{}};return e[s].call(i.exports,i,i.exports,n),i.loaded=!0,i.exports}n.m=e,n.amdO={},n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.u=e=>e+".js",n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;n.g.importScripts&&(e=n.g.location+"");var t=n.g.document;if(!e&&t&&(t.currentScript&&(e=t.currentScript.src),!e)){var s=t.getElementsByTagName("script");if(s.length)for(var r=s.length-1;r>-1&&!e;)e=s[r--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})(),n.b=document.baseURI||self.location.href,n.nc=void 0;var s=n(3649);bio=s})();
|
|
9
9
|
//# sourceMappingURL=package.js.map
|