@milaboratories/pl-middle-layer 1.37.59 → 1.37.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,25 +1,25 @@
1
- "use strict";var Ds=Object.defineProperty;var Xt=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),Yt=s=>{throw TypeError(s)};var As=(s,e,t)=>e in s?Ds(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var k=(s,e,t)=>As(s,typeof e!="symbol"?e+"":e,t);var Qt=(s,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Yt("Object expected");var r;t&&(r=e[Xt("asyncDispose")]),r===void 0&&(r=e[Xt("dispose")]),typeof r!="function"&&Yt("Object not disposable"),s.push([t,r,e])}else t&&s.push([t]);return e},Zt=(s,e,t)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,c,a,l){return l=Error(a),l.name="SuppressedError",l.error=i,l.suppressed=c,l},o=i=>e=t?new r(i,e,"An error was suppressed during disposal"):(t=!0,i),n=i=>{for(;i=s.pop();)try{var c=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(c).then(n,a=>(o(a),n()))}catch(a){o(a)}if(t)throw e};return n()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("@platforma-sdk/model"),z=require("@milaboratories/pl-model-middle-layer"),er=require("@milaboratories/pl-deployments"),tt=require("undici"),X=require("@platforma-sdk/block-tools"),te=require("node:fs"),M=require("node:path"),Ls=require("yaml"),S=require("@milaboratories/ts-helpers"),De=require("node:fs/promises"),Ns=require("@milaboratories/resolve-helper"),g=require("@milaboratories/pl-client"),Qe=require("@milaboratories/pl-tree"),V=require("@milaboratories/computable"),Z=require("node:crypto"),O=require("@milaboratories/pl-model-backend"),Mr=require("lru-cache"),Bs=require("node:worker_threads"),Gr=require("denque"),he=require("@platforma-sdk/workflow-tengo"),x=require("canonicalize"),js=require("node:assert"),ge=require("quickjs-emscripten"),Vs=require("@milaboratories/pl-errors"),xs=require("remeda"),_r=require("node:timers/promises"),J=require("@milaboratories/pl-drivers"),Kr=require("@milaboratories/pframes-rs-node"),Us=require("node:diagnostics_channel"),Js=require("node:stream/consumers"),Hr=require("node:os");function $t(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const Ms=$t(M),qr=$t(De),tr=$t(xs);async function rr(s){try{return await qr.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const Gs=[X.RegistryV1.PlPackageYamlConfigFile],_s=[X.RegistryV1.PlPackageJsonConfigFile],Tt=["backend","dist","tengo","tpl","main.plj.gz"],It=["config","dist","config.json"],Wr=["frontend","dist"],sr="block-model/dist/config.json",Ks="block-ui/package.json",Hs=[Tt,It,Gs,_s,Wr];async function qs(s){return await rr(M.join(s,...It))!==void 0||await rr(M.join(s,...Tt))!==void 0}function dt(s,e){const t=Ns.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function or(s,e){if(M.isAbsolute(s)||(s=M.resolve(s)),await qs(s))return{workflow:M.join(s,...Tt),config:M.join(s,...It),ui:M.join(s,...Wr)};{const t=dt(s,sr),r=dt(s,sr),o=dt(s,Ks);return{workflow:t,config:r,ui:M.resolve(o,"..","dist")}}}async function Ws(s){try{return await te.promises.readFile(s,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function zs(s){try{return await te.promises.stat(s,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Ft(s){let e=0n;for(const t of Hs){const r=M.join(s,...t),o=await zs(r);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function rt(s){const e=await te.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await te.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class Xs{constructor(e,t,r){this.v2Provider=e,this.registries=t,this.http=r}async getPackagesForRoot(e){const t=[],r=e.spec;switch(r.type){case"remote-v1":{const o=this.http!==void 0?{dispatcher:this.http}:{},i=await(await tt.request(`${r.url}/${X.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const c of i){const{organization:a,package:l,latestMeta:u,latestVersion:d}=c,p={organization:a,name:l,version:d},f={id:p,meta:{title:u.title??"No title",description:u.description??"No Description",organization:{name:a,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:p,registryUrl:r.url}};t.push({registryId:e.id,id:p,latestByChannel:{[z.AnyChannel]:f,[z.StableChannel]:f},allVersions:c.allVersions.map(P=>({version:P,channels:[]}))})}return t}case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(o=>({...o,registryId:e.id}));case"local-dev":for(const o of await te.promises.readdir(r.path,{withFileTypes:!0})){if(!o.isDirectory())continue;const n=M.join(r.path,o.name),i=await Ws(M.join(n,X.RegistryV1.PlPackageYamlConfigFile));if(i!==void 0){const c=X.RegistryV1.PlPackageConfigData.parse(Ls.parse(i)),a=await Ft(n),l={organization:c.organization,name:c.package,version:"DEV"},u={id:l,meta:{title:c.meta.title??"No title",description:c.meta.description??"No Description",organization:{name:c.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:n,mtime:a}};t.push({registryId:e.id,id:l,latestByChannel:{[z.AnyChannel]:u,[z.StableChannel]:u},allVersions:[]})}else{let c=n,a=await X.tryLoadPackDescription(c);if(a===void 0){for(const l of["block","meta"])if(c=M.join(n,l),a=await X.tryLoadPackDescription(c),a!==void 0)break}if(a!==void 0){const l=await rt(a),u={id:a.id,meta:await X.BlockPackMetaEmbedAbsoluteBytes.parseAsync(a.meta),spec:{type:"dev-v2",folder:c,mtime:l}};t.push({registryId:e.id,id:a.id,latestByChannel:{[z.AnyChannel]:u,[z.StableChannel]:u},allVersions:[]})}}}return t;default:return S.assertNever(r)}}async listBlockPacks(){const e=[],t=[];for(const r of this.registries)t.push({...r,status:"online"}),e.push(...await this.getPackagesForRoot(r));return{registries:t,blockPacks:e}}async getOverview(e,t,r){var i;const o=(i=this.registries.find(c=>c.id===e))==null?void 0:i.spec;if(!o)throw new Error(`Registry with id "${e}" not found`);if(o.type!=="remote-v2")throw new Error('Only "remote-v2" registries support specific package version overview retrieval.');return await this.v2Provider.getRegistry(o.url).getSpecificOverview(t,r)}}class zr{constructor(e){k(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new X.RegistryV2Reader(X.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const Ys={type:"remote-v2",url:"https://blocks.pl-open.science/"},Qs={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},Zs={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},eo={groups:[{id:"default",label:"Default",blocks:[]}]},to={stagingRefreshTimestamp:0,blocksInLimbo:[]},ro={label:"New Project"},so={name:"UserProject",version:"2"},Xr="SchemaVersion",Yr="1",Dt="ProjectCreated",Ae="ProjectLastModified",Le="ProjectMeta",de="ProjectStructure",Ze="BlockRenderingState",oo="BlockFrontendState/",no=/^BlockFrontendState\/(?<blockid>.*)$/;function bt(s){return`${oo}${s}`}const io="BlockArgsAuthor/";function St(s){return`${io}${s}`}const kt="ProjectStructureAuthor";function ao(s){const e=s.match(no);if(e!==null)return e.groups.blockid}const co="__serviceTemplate_";function Ct(s){return`${co}${s}`}function K(s,e){return`${s}-${e}`}const lo=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function uo(s){const e=s.match(lo);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const po="projects",Qr={name:"Projects",version:"1"},fo=s=>g.resourceTypesEqual(s.type,Qr)?s.fields:[];async function go(s,e,t,r){const o=await Qe.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:fo},r.logger);return{computable:V.Computable.make(i=>{const c=i.accessor(o.entry()).node(),a=t.getValue(i);if(c===void 0)return;const l=[];for(const u of c.listDynamicFields()){const d=c.traverse(u);if(d===void 0)continue;const p=S.notEmpty(d.getKeyValueAsJson(Le)),f=S.notEmpty(d.getKeyValueAsJson(Dt)),P=S.notEmpty(d.getKeyValueAsJson(Ae));l.push({id:u,rid:d.id,created:new Date(f),lastModified:new Date(P),opened:a.indexOf(d.id)>=0,meta:p})}return l.sort(u=>-u.lastModified.valueOf()),l}).withStableType(),tree:o}}const ho={name:"EphRenderTemplate",version:"1"},mo={name:"RenderTemplate",version:"1"};function st(s,e,t,r,o){if(o.length===0)throw new Error("Zero output names provided");const n=t?s.createEphemeral(ho):s.createStruct(mo),i=g.field(n,"template"),c=g.field(n,"inputs");return s.createField(i,"Input",e),s.createField(c,"Input",g.Pl.createPlMap(s,r,t)),s.lockInputs(n),g.Pl.futureRecord(s,n,o,"Output","outputs/")}const vo={name:"BContextEnd",version:"1"},yo={name:"BContext",version:"1"},wo="id",bo="parent/",So=["context","result"];function nr(s,e,t){return st(s,e,!0,t,So)}function ko(s){const e=s.createEphemeral(vo);return s.lock(e),e}function ir(s,e){if(e.length===0)return ko(s);if(e.length===1)return e[0];const t=s.createEphemeral(yo);s.createField(g.field(t,wo),"Input",g.Pl.createPlString(s,Z.randomUUID()));for(let r=0;r<e.length;r++)s.createField(g.field(t,`${bo}${r}`),"Input",e[r]);return s.lock(t),t}function Zr(s,e){const t=new Map,r=(o,n,i)=>{const c=Z.createHash("sha256");n.updateCacheKey(o,c,i);const a=c.digest("hex");if(!t.has(a)){const l=n.render(o,s,r,i);t.set(a,l)}return t.get(a)};return r(e.template,es,e.hashToSource)}const ar={updateCacheKey(s,e,t){e.update(O.PlTemplateLibV1.type.name).update(O.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(we(s.name,t,s.sourceHash))},render(s,e,t,r){return e.createValue(O.PlTemplateLibV1.type,JSON.stringify(O.PlTemplateLibV1.fromV3Data(s,we(s.name,r,s.sourceHash)).data))}},Ue={updateCacheKey(s,e,t){e.update(O.PlTemplateSoftwareV1.type.name).update(O.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(we(s.name,t,s.sourceHash))},render(s,e,t,r){const o=O.PlTemplateSoftwareV1.fromV3Data(s,we(s.name,r,s.sourceHash)),n=e.createStruct(O.PlTemplateSoftwareV1.type,o.data);return e.setKValue(n,O.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(o.name)),e.lock(n),n}},es={updateCacheKey(s,e,t){e.update(O.PlTemplateV1.type.name).update(O.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(we(s.name,t,s.sourceHash));const r=o=>(o.sort((n,i)=>n[0]===i[0]?0:n[0]<i[0]?-1:1),o);for(const[o,n]of r(Object.entries(s.libs??{})))e.update("lib:"+o),ar.updateCacheKey(n,e,t);for(const[o,n]of r(Object.entries(s.software??{})))e.update("soft:"+o),Ue.updateCacheKey(n,e,t);for(const[o,n]of r(Object.entries(s.assets??{})))e.update("asset:"+o),Ue.updateCacheKey(n,e,t);for(const[o,n]of r(Object.entries(s.templates??{})))e.update("tpl:"+o),this.updateCacheKey(n,e,t)},render(s,e,t,r){const o=e.createStruct(O.PlTemplateV1.type,JSON.stringify(O.PlTemplateV1.fromV3Data(s,we(s.name,r,s.sourceHash)).data));for(const[c,a]of Object.entries(s.libs??{})){const l=O.PlTemplateV1.libField(o,c);e.createField(l,"Input"),e.setField(l,t(a,ar,r))}for(const[c,a]of Object.entries(s.software??{})){const l=O.PlTemplateV1.swField(o,c);e.createField(l,"Input"),e.setField(l,t(a,Ue,r))}for(const[c,a]of Object.entries(s.assets??{})){const l=O.PlTemplateV1.swField(o,c);e.createField(l,"Input"),e.setField(l,t(a,Ue,r))}for(const[c,a]of Object.entries(s.templates??{})){const l=O.PlTemplateV1.tplField(o,c);e.createField(l,"Input"),e.setField(l,t(a,es,r))}if(e.lock(o),!s.hashOverride)return o;const n=e.createStruct(O.PlTemplateOverrideV1.type,JSON.stringify(O.PlTemplateOverrideV1.fromV3Data(s))),i=O.PlTemplateOverrideV1.tplField(n);return e.createField(i,"Service"),e.setField(i,o),e.lock(n),n}};function we(s,e,t){return S.notEmpty(e[t],`trying to get "${s}" source: sources map doesn't contain source hash ${t}`)}function Co(s,e){const t=O.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return rs(s,t);case"pl.tengo-template.v3":return Zr(s,t);default:S.assertNever(r)}}function Po(s,e){const t=e.data,r=t.type;switch(r){case"pl.tengo-template.v2":return rs(s,t);case"pl.tengo-template.v3":return Zr(s,t);default:S.assertNever(r)}}const cr={hash(s,e){e.update(O.PlTemplateLibV1.type.name).update(O.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue(O.PlTemplateLibV1.type,JSON.stringify(O.PlTemplateLibV1.fromV2Data(s).data))}},Je={hash(s,e){e.update(O.PlTemplateSoftwareV1.type.name).update(O.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=O.PlTemplateSoftwareV1.fromV2Data(s),o=e.createStruct(O.PlTemplateSoftwareV1.type,r.data);return e.setKValue(o,O.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(o),o}},ts={hash(s,e){e.update(O.PlTemplateV1.type.name).update(O.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(s.src);const t=r=>(r.sort((o,n)=>o[0]===n[0]?0:o[0]<n[0]?-1:1),r);for(const[r,o]of t(Object.entries(s.libs??{})))e.update("lib:"+r),cr.hash(o,e);for(const[r,o]of t(Object.entries(s.software??{})))e.update("soft:"+r),Je.hash(o,e);for(const[r,o]of t(Object.entries(s.assets??{})))e.update("asset:"+r),Je.hash(o,e);for(const[r,o]of t(Object.entries(s.templates??{})))e.update("tpl:"+r),this.hash(o,e)},render(s,e,t){const r=e.createStruct(O.PlTemplateV1.type,JSON.stringify(O.PlTemplateV1.fromV2Data(s).data));for(const[i,c]of Object.entries(s.libs??{})){const a=O.PlTemplateV1.libField(r,i);e.createField(a,"Input"),e.setField(a,t(c,cr))}for(const[i,c]of Object.entries(s.software??{})){const a=O.PlTemplateV1.swField(r,i);e.createField(a,"Input"),e.setField(a,t(c,Je))}for(const[i,c]of Object.entries(s.assets??{})){const a=O.PlTemplateV1.swField(r,i);e.createField(a,"Input"),e.setField(a,t(c,Je))}for(const[i,c]of Object.entries(s.templates??{})){const a=O.PlTemplateV1.tplField(r,i);e.createField(a,"Input"),e.setField(a,t(c,ts))}if(e.lock(r),!s.hashOverride)return r;const o=e.createStruct(O.PlTemplateOverrideV1.type,JSON.stringify(O.PlTemplateOverrideV1.fromV2Data(s))),n=O.PlTemplateOverrideV1.tplField(o);return e.createField(n,"Service"),e.setField(n,r),e.lock(o),o}};function rs(s,e){const t=new Map,r=(o,n)=>{const i=Z.createHash("sha256");n.hash(o,i);const c=i.digest("hex");if(!t.has(c)){const a=n.render(o,s,r);t.set(c,a)}return t.get(c)};return r(e,ts)}const ss={name:"TengoTemplateGet",version:"1"},os="registry",ns="templateURI",is="template",Ro={name:"TengoTemplatePack",version:"1"},Eo={name:"TengoTemplatePackConvert",version:"1"},Oo="templatePack",$o="template";async function At(s){switch(s.type){case"from-file":return{type:"explicit",content:await te.promises.readFile(s.path)};case"from-registry":case"explicit":return s;case"prepared":return s;default:return S.assertNever(s)}}function To(s,e){const t=s.createStruct(ss),r=g.field(t,os),o=g.field(t,ns),n=g.field(t,is);return s.setField(r,s.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(o,s.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function je(s,e){switch(e.type){case"from-registry":return To(s,e);case"explicit":return Co(s,e);case"prepared":return Po(s,e);default:return S.assertNever(e)}}const Lt={name:"Frontend/FromUrl",version:"1"},Nt={name:"Frontend/FromFolder",version:"1"};function Io(s,e){switch(e.type){case"url":return s.createValue(Lt,JSON.stringify({url:e.url}));case"local":return s.createValue(Nt,JSON.stringify({path:e.path,signature:e.signature}));default:return S.assertNever(e)}}class Fo{constructor(){k(this,"nextMessageId",0);k(this,"worker");k(this,"pendingRequests",new Map);const e=typeof global<"u"&&"__WORKER_PATH__"in global?global.__WORKER_PATH__:M.resolve(void 0,"worker.js"),t=this.worker=new Bs.Worker(e,{workerData:{}});t.on("message",({id:r,data:o,error:n})=>{const{resolve:i,reject:c}=this.pendingRequests.get(r);this.pendingRequests.delete(r),n?c(new Error(n)):i(o)}),t.on("error",r=>{console.error("Worker error",r),this.rejectAllPendingRequests(r)})}rejectAllPendingRequests(e){Array.from(this.pendingRequests.values()).map(({reject:t})=>{t(e)})}async process(e,...t){return new Promise((r,o)=>{const n=++this.nextMessageId;this.pendingRequests.set(n,{resolve:r,reject:o}),this.worker.postMessage({id:n,type:e,args:t})})}async terminate(){this.rejectAllPendingRequests(new Error("Worker terminated")),await this.worker.terminate()}[Symbol.asyncDispose](){return this.terminate()}}const Do={name:"BlockPackCustom",version:"1"},as="template",cs="frontend";function lr(s){return s.endsWith("/")?s:`${s}/`}function Ao(s){return Buffer.from(s).toString("utf8")}function Me(s){return JSON.parse(Ao(s))}class Lo{constructor(e,t,r){k(this,"remoteContentCache",new Mr.LRUCache({max:500,maxSize:128*1024*1024,fetchMethod:async e=>{const t=this.http!==void 0?{dispatcher:this.http}:{};return await(await tt.request(e,t)).body.arrayBuffer()},sizeCalculation:e=>e.byteLength}));this.v2RegistryProvider=e,this.signer=t,this.http=r}async getBlockConfigContainer(e){switch(e.type){case"explicit":return e.config;case"prepared":return e.config;case"dev-v1":{const t=await or(e.folder),r=await te.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await X.loadPackDescription(e.folder),r=await te.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=`${lr(e.registryUrl)}${X.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=await this.remoteContentCache.forceFetch(`${t}/config.json`);return Me(r)}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),o=await this.remoteContentCache.forceFetch(r.model.url);return Me(o)}default:return S.assertNever(e)}}async prepare(e){var o=[];try{if(e.type==="prepared")return e;const t=await this.prepareWithoutUnpacking(e);const r=Qt(o,new Fo,!0);return{...t,type:"prepared",template:{type:"prepared",data:await r.process("parseTemplate",t.template.content)}}}catch(n){var i=n,c=!0}finally{var a=Zt(o,i,c);a&&await a}}async prepareWithoutUnpacking(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await or(e.folder),r=await te.promises.readFile(t.workflow),o=JSON.parse(await te.promises.readFile(t.config,"utf-8")),n=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:o,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:e}}case"dev-v2":{const t=await X.loadPackDescription(e.folder),r=JSON.parse(await te.promises.readFile(t.components.model.file,{encoding:"utf-8"})),o=await te.promises.readFile(t.components.workflow.main.file),n=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await rt(t)),{type:"explicit",template:{type:"explicit",content:o},config:r,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:i}}case"from-registry-v1":{const t=`${lr(e.registryUrl)}${X.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=`${t}/template.plj.gz`,o=await this.remoteContentCache.forceFetch(r),n=new Uint8Array(o),i=await this.remoteContentCache.forceFetch(`${t}/config.json`),c=Me(i);return{type:"explicit",template:{type:"explicit",content:n},config:c,frontend:{type:"url",url:`${t}/frontend.tgz`},source:e}}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),o=async()=>Me(await this.remoteContentCache.forceFetch(r.model.url)),n=async()=>await this.remoteContentCache.forceFetch(r.workflow.main.url),[i,c]=await Promise.all([o(),n()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(c)},config:i,frontend:{type:"url",url:r.ui.url},source:e}}default:return S.assertNever(e)}}}function No(s,e){const t={config:e.config,source:e.source},r=s.createStruct(Do,JSON.stringify(t));return s.createField(g.field(r,as),"Input",je(s,e.template)),s.createField(g.field(r,cs),"Input",Io(s,e.frontend)),s.lock(r),r}function ur(s,e){switch(e.type){case"prepared":return No(s,e);default:return S.assertNever(e.type)}}function Ge(s,e,t){return{__isRef:!0,blockId:s,name:e}}function Bo(s){return typeof s=="object"&&s!==null&&"__isRef"in s&&s.__isRef===!0&&"blockId"in s&&"name"in s}function Pt(s,e,t){const r=typeof e;switch(r){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if(Bo(e))t===void 0||t.has(e.blockId)?(s.upstreams.add(e.blockId),e.requireEnrichments&&s.upstreamsRequiringEnrichments.add(e.blockId)):s.missingReferences=!0;else if(Array.isArray(e))for(const o of e)Pt(s,o,t);else for(const[,o]of Object.entries(e))Pt(s,o,t);return;default:S.assertNever(r)}}function jo(s,e){const t={upstreams:new Set,upstreamsRequiringEnrichments:new Set,missingReferences:!1};return Pt(t,s,e),t}function re(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class ls{constructor(e){k(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,o=>r.add(o.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const o of t)r.delete(o);return r}traverse(e,t,r){let o=[...t];const n=new Set(o);for(;o.length>0;){const i=[];for(const c of o){const a=this.nodes.get(c);r(a),a[e].forEach(l=>{n.has(l)||(n.add(l),i.push(l))})}o=i}}}function Rt(s){const e=new Map;let t;for(const{id:r}of re(s)){const o={id:r,missingReferences:!1};e.set(r,o),t===void 0?(o.directUpstream=o.upstream=new Set,o.enrichments=o.enrichmentTargets=new Set):(o.directUpstream=o.upstream=new Set([t.id]),t.directDownstream=t.downstream=new Set([o.id]),t.enrichments=t.enrichmentTargets=new Set),t=o}return t!==void 0&&(t.directDownstream=t.downstream=new Set),new ls(e)}function Ye(s,e){const t=new Map,r=new ls(t),o=new Set;for(const{id:n}of re(s)){const i=e(n);if(i===void 0)continue;const c=jo(i.args,o),a=new Set([...c.upstreams,...r.traverseIds("enrichments",...c.upstreamsRequiringEnrichments)]),l=new Set;for(const{id:p}of re(s)){if(p===n)break;if(a.has(p)){l.add(p);for(const f of r.traverseIdsExcludingRoots("upstream",p))l.delete(f)}}const u=i.enrichmentTargets===void 0?new Set(c.upstreams):new Set(i.enrichmentTargets.map(p=>p.blockId)),d={id:n,missingReferences:c.missingReferences,upstream:l,directUpstream:c.upstreams,enrichmentTargets:u,downstream:new Set,directDownstream:new Set,enrichments:new Set};t.set(n,d),c.upstreams.forEach(p=>t.get(p).directDownstream.add(n)),l.forEach(p=>t.get(p).downstream.add(n)),u.forEach(p=>{var f;return(f=t.get(p))==null?void 0:f.enrichments.add(n)}),o.add(n)}return r}function Vo(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function Et(s,e){if(s.size>e.size)return Et(e,s);for(const t of s)if(e.has(t))return!0;return!1}function dr(s,e){const t=new Set,r=new Set,o=new Set;return s.nodes.forEach(n=>{const i=e.nodes.get(n.id);i===void 0?t.add(n.id):(!Vo(n.upstream,i.upstream)||Et(n.upstream,o))&&o.add(n.id)}),e.nodes.forEach(n=>{s.nodes.has(n.id)?Et(n.upstream,o)&&o.add(n.id):r.add(n.id)}),{onlyInA:t,onlyInB:r,different:o}}let pt;async function us(){if(pt===void 0){const s=await At(he.Templates["pframes.export-pframe-for-ui"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=Z.createHash("sha256").update(s.content).digest("hex");pt={spec:s,hash:e}}return pt}function xo(s,e,t){return st(s,e,!0,{pf:t},["result"]).result}function ft(s,e){let t=!1,r,o;return()=>{if(!t)return t=!0,r=s(),o=e(),o;const n=s();return r!==n&&(r=n,o=e()),e()}}class pr{constructor(e,t,r,o){k(this,"currentArgsC",ft(()=>this.fields.currentArgs.modCount,()=>S.cachedDeserialize(this.fields.currentArgs.value)));k(this,"prodArgsC",ft(()=>{var e;return(e=this.fields.prodArgs)==null?void 0:e.modCount},()=>{var t;const e=(t=this.fields.prodArgs)==null?void 0:t.value;if(e!==void 0)return S.cachedDeserialize(e)}));k(this,"productionStaleC",ft(()=>{var e;return`${this.fields.currentArgs.modCount}_${(e=this.fields.prodArgs)==null?void 0:e.modCount}`},()=>this.fields.prodArgs===void 0||Buffer.compare(this.fields.currentArgs.value,this.fields.prodArgs.value)!==0));this.id=e,this.fields=t,this.config=r,this.source=o}check(){if(this.fields.prodOutput===void 0!=(this.fields.prodCtx===void 0))throw new Error("inconsistent prod fields");if(this.fields.stagingOutput===void 0!=(this.fields.stagingCtx===void 0))throw new Error("inconsistent stage fields");if(this.fields.prodOutputPrevious===void 0!=(this.fields.prodCtxPrevious===void 0))throw new Error("inconsistent prod cache fields");if(this.fields.stagingOutputPrevious===void 0!=(this.fields.stagingCtxPrevious===void 0))throw new Error("inconsistent stage cache fields");if(this.fields.blockPack===void 0)throw new Error("no block pack field");if(this.fields.currentArgs===void 0)throw new Error("no current args field")}get currentArgs(){return this.currentArgsC()}get stagingRendered(){return this.fields.stagingCtx!==void 0}get productionRendered(){return this.fields.prodCtx!==void 0}get productionHasErrors(){var e;return((e=this.fields.prodUiCtx)==null?void 0:e.status)==="Error"}get requireProductionRendering(){return!this.productionRendered||this.productionStaleC()||this.productionHasErrors}get prodArgs(){return this.prodArgsC()}getTemplate(e){return e.getFutureFieldValue(g.Pl.unwrapHolder(e,this.fields.blockPack.ref),as,"Input")}}const Uo=s=>{throw new Error(`No new block info for ${s}`)};class et{constructor(e,t,r,o,n,i,c,a,l,u,d,p,f){k(this,"globalModCount",0);k(this,"fieldsChanged",!1);k(this,"lastModifiedChanged",!1);k(this,"structureChanged",!1);k(this,"metaChanged",!1);k(this,"renderingStateChanged",!1);k(this,"changedBlockFrontendStates",new Set);k(this,"blocksWithChangedInputs",new Set);k(this,"stagingGraph");k(this,"pendingProductionGraph");k(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=o,this.lastModified=n,this.meta=i,this.struct=c,this.renderingState=a,this.blocksInLimbo=l,this.blockInfos=u,this.blockFrontendStates=d,this.ctxExportTplHolder=p,this.projectHelper=f}fixProblemsAndMigrate(){this.blockInfos.forEach(t=>{(t.fields.prodArgs===void 0||t.fields.prodOutput===void 0||t.fields.prodCtx===void 0)&&this.deleteBlockFields(t.id,"prodArgs","prodOutput","prodCtx")});let e;this.blockInfos.forEach(t=>{t.fields.blockSettings===void 0&&(e===void 0&&(e=this.createJsonFieldValue(z.InitialBlockSettings)),this.setBlockFieldObj(t.id,"blockSettings",e))})}get wasModified(){return this.lastModifiedChanged||this.structureChanged||this.fieldsChanged||this.metaChanged||this.renderingStateChanged||this.changedBlockFrontendStates.size>0}get structure(){return JSON.parse(JSON.stringify(this.struct))}getStagingGraph(){return this.stagingGraph===void 0&&(this.stagingGraph=Rt(this.struct)),this.stagingGraph}getProductionGraphBlockInfo(e,t){const r=this.getBlockInfo(e);let o,n;if(t){if(r.fields.prodArgs===void 0)return;o=r.fields.prodArgs,n=r.prodArgs}else o=S.notEmpty(r.fields.currentArgs),n=r.currentArgs;const i=S.notEmpty(r.fields.blockPack);return g.isResourceId(o.ref)&&g.isResourceId(i.ref)?{args:n,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>n,{argsRid:o.ref,blockPackRid:i.ref})}:{args:n,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>n)}}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Ye(this.struct,e=>this.getProductionGraphBlockInfo(e,!1))),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Ye(this.struct,e=>this.getProductionGraphBlockInfo(e,!0))),this.actualProductionGraph}getBlockInfo(e){const t=this.blockInfos.get(e);if(t===void 0)throw new Error(`No such block: ${e}`);return t}createJsonFieldValueByContent(e){const t=Buffer.from(e);return{ref:this.tx.createValue(g.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of re(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const o=g.field(this.rid,K(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(o,"Dynamic",r.ref):this.tx.setField(o,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,o,n){this.setBlockFieldObj(e,t,{ref:r,status:o,value:n})}deleteBlockFields(e,...t){let r=!1;const o=this.getBlockInfo(e);for(const n of t){const i=o.fields;n in i&&(this.tx.removeField(g.field(this.rid,K(e,n))),delete i[n],this.fieldsChanged=!0,r=!0)}return r}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((o=t.stagingCtx)==null?void 0:o.status)==="Ready"&&((n=t.stagingUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"stagingOutputPrevious",t.stagingOutput),this.setBlockFieldObj(e,"stagingCtxPrevious",t.stagingCtx),this.setBlockFieldObj(e,"stagingUiCtxPrevious",t.stagingUiCtx)),this.deleteBlockFields(e,"stagingOutput","stagingCtx","stagingUiCtx")&&this.resetStagingRefreshTimestamp()}resetProduction(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"&&((n=t.prodUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"prodOutputPrevious",t.prodOutput),this.setBlockFieldObj(e,"prodCtxPrevious",t.prodCtx),this.setBlockFieldObj(e,"prodUiCtxPrevious",t.prodUiCtx)),this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}resetOrLimboProduction(e){var r,o;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"?this.blocksInLimbo.has(e)?!1:(this.blocksInLimbo.add(e),this.renderingStateChanged=!0,this.deleteBlockFields(e,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),!0):this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}setArgs(e){const t=[];for(const{blockId:r,args:o}of e){const n=this.getBlockInfo(r);JSON.parse(o);const i=Buffer.from(o);if(Buffer.compare(n.fields.currentArgs.value,i)===0)continue;const c=this.tx.createValue(g.Pl.JsonObject,i);this.setBlockField(r,"currentArgs",c,"Ready",i),this.blocksWithChangedInputs.add(r),t.push(r)}this.getStagingGraph().traverse("downstream",t,({id:r})=>this.resetStaging(r)),t.length>0&&this.updateLastModified()}setUiState(e,t){if(this.blockInfos.get(e)===void 0)throw new Error("no such block");this.blockFrontendStates.get(e)!==t&&(t===void 0?this.blockFrontendStates.delete(e):this.blockFrontendStates.set(e,t),this.changedBlockFrontendStates.add(e),this.blocksWithChangedInputs.add(e),this.updateLastModified())}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createProdCtx(e){const t=[];return e.forEach(r=>{var n;const o=this.getBlockInfo(r);if(((n=o.fields.prodCtx)==null?void 0:n.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),ir(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(r=>{var n,i;const o=this.getBlockInfo(r);if(((n=o.fields.stagingCtx)==null?void 0:n.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,o.fields.stagingCtx.ref)),((i=o.fields.prodCtx)==null?void 0:i.ref)!==void 0&&t.push(g.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),ir(this.tx,t)}exportCtx(e){return xo(this.tx,g.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createStagingCtx(this.getStagingGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const o=t.getTemplate(this.tx),n=nr(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(g.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(g.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",g.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"stagingOutput",n.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),r=this.createProdCtx(this.getPendingProductionGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const o=t.getTemplate(this.tx),n=nr(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(g.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(g.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",g.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"prodOutput",n.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=Uo){const r=this.getStagingGraph(),o=this.getActualProductionGraph(),n=Rt(e),i=dr(r,n);for(const l of i.onlyInA){const{fields:u}=this.getBlockInfo(l);this.deleteBlockFields(l,...Object.keys(u)),this.blockInfos.delete(l),this.blocksInLimbo.delete(l)&&(this.renderingStateChanged=!0),this.blockFrontendStates.delete(l)&&this.changedBlockFrontendStates.add(l)}for(const l of i.onlyInB){const u=t(l),d=new pr(l,{},D.extractConfig(u.blockPack.config),u.blockPack.source);this.blockInfos.set(l,d);const p=ur(this.tx,u.blockPack);this.setBlockField(l,"blockPack",g.Pl.wrapInHolder(this.tx,p),"NotReady"),this.setBlockFieldObj(l,"blockSettings",this.createJsonFieldValue(z.InitialBlockSettings)),this.setBlockFieldObj(l,"currentArgs",this.createJsonFieldValueByContent(u.args)),u.uiState&&(this.blockFrontendStates.set(l,u.uiState),this.changedBlockFrontendStates.add(l)),d.check()}for(const l of i.different)this.resetStaging(l);const c=Ye(e,l=>this.getProductionGraphBlockInfo(l,!0)),a=dr(o,c);o.traverse("downstream",[...a.different],l=>{this.resetOrLimboProduction(l.id)}),(i.onlyInB.size>0||i.onlyInA.size>0||i.different.size>0)&&this.resetStagingRefreshTimestamp(),this.struct=e,this.structureChanged=!0,this.stagingGraph=void 0,this.pendingProductionGraph=void 0,this.actualProductionGraph=void 0,this.updateLastModified()}addBlock(e,t,r){const o=this.structure;if(r===void 0)o.groups[o.groups.length-1].blocks.push(e);else{let n=!1;for(const i of o.groups){const c=i.blocks.findIndex(a=>a.id===r);if(!(c<0)){i.blocks.splice(c,0,e),n=!0;break}}if(!n)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(o,n=>{if(n!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const o of t.groups){const n=o.blocks.findIndex(i=>i.id===e);if(!(n<0)){o.blocks.splice(n,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const o=this.getBlockInfo(e);this.setBlockField(e,"blockPack",g.Pl.wrapInHolder(this.tx,ur(this.tx,t)),"NotReady"),r!==void 0?(this.setArgs([{blockId:e,args:r.args}]),this.setUiState(e,r.uiState)):this.getStagingGraph().traverse("downstream",[e],({id:n})=>this.resetStaging(n)),o.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:n})=>this.resetOrLimboProduction(n)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),o=this.getPendingProductionGraph();if(t)o.traverse("upstream",e,c=>{r.add(c.id)});else for(const c of r){const a=o.nodes.get(c);if(a===void 0)throw new Error(`Can't find block with id: ${c}`);for(const l of a.upstream)if(!r.has(l))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const c of re(this.structure)){if(!r.has(c.id))continue;let a=this.getBlockInfo(c.id).requireProductionRendering||this.blocksInLimbo.has(c.id);if(!a){for(const l of o.nodes.get(c.id).upstream)if(n.has(l)){a=!0;break}}a&&(this.renderProductionFor(c.id),n.add(c.id))}const i=[...n];return o.traverse("downstream",i,c=>{n.has(c.id)||this.resetOrLimboProduction(c.id)}),this.getStagingGraph().traverse("downstream",i,({id:c})=>{i[0]!==c&&this.resetStaging(c)}),n.size>0&&this.updateLastModified(),n}stopProduction(...e){var i,c;const t=this.getActualProductionGraph(),r=new Gr(e),o=new Set(e),n=[];for(;!r.isEmpty();){const a=r.shift(),l=this.getBlockInfo(a).fields;if(!(((i=l.prodOutput)==null?void 0:i.status)==="Ready"&&((c=l.prodCtx)==null?void 0:c.status)==="Ready")&&this.deleteBlockFields(a,"prodOutput","prodCtx","prodUiCtx","prodArgs")){n.push(a);for(const u of t.traverseIdsExcludingRoots("downstream",a))o.has(u)||(r.push(u),o.add(u))}}for(const a of t.traverseIdsExcludingRoots("downstream",...n))this.resetOrLimboProduction(a)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(o=>{let i=this.getBlockInfo(o.id).stagingRendered?0:1;o.upstream.forEach(c=>{const a=t.get(c);a!==0&&(i=Math.max(a+1,i))}),e(o.id,i),t.set(o.id,i)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,r=e===void 0?void 0:1+Math.max(0,t*e/1e3);let o=0;this.traverseWithStagingLag((n,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(n),o++)}),o>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,o,n,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((o=t.fields.prodOutput)==null?void 0:o.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((n=t.fields.stagingCtx)==null?void 0:n.status)==="Ready"&&((i=t.fields.stagingOutput)==null?void 0:i.status)==="Ready"&&this.deleteBlockFields(t.id,"stagingOutputPrevious","stagingCtxPrevious","stagingUiCtxPrevious")})}assignAuthorMarkers(){const e=this.author?JSON.stringify(this.author):void 0;for(const t of this.blocksWithChangedInputs)e===void 0?this.tx.deleteKValue(this.rid,St(t)):this.tx.setKValue(this.rid,St(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,kt):this.tx.setKValue(this.rid,kt,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,Ae,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,de,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,Ze,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,Le,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,bt(e)):this.tx.setKValue(this.rid,bt(e),t)}this.assignAuthorMarkers()}}static async load(e,t,r,o){const n=t.getResourceData(r,!0),i=t.getKValueJson(r,Xr),c=t.getKValueJson(r,Ae),a=t.getKValueJson(r,Le),l=t.getKValueJson(r,de),u=t.getKValueJson(r,Ze),d=t.listKeyValuesString(r),p=await n,f=new Map;for(const h of p.fields){const b=uo(h.name);if(b===void 0)continue;let y=f.get(b.blockId);y===void 0&&(y={id:b.blockId,fields:{}},f.set(b.blockId,y)),y.fields[b.fieldName]=g.isNullResourceId(h.value)?{modCount:0}:{modCount:0,ref:h.value}}const P=[];f.forEach(h=>{const b=h.fields;for(const[y,C]of Object.entries(b)){if(C.ref===void 0)continue;if(!g.isResource(C.ref)||g.isResourceRef(C.ref))throw new Error("unexpected behaviour");const $=y;P.push([h,$,C,t.getResourceData(C.ref,$=="blockPack")])}});const[v,T,L,U,{stagingRefreshTimestamp:A,blocksInLimbo:q},me]=await Promise.all([i,c,a,l,u,d]);if(v!==Yr)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${v}`);const j=[];for(const[h,b,y,C]of P){const $=await C;if(y.value=$.data,g.isNotNullResourceId($.error)?y.status="Error":$.resourceReady||g.isNotNullResourceId($.originalResourceId)?y.status="Ready":y.status="NotReady",b==="blockPack"){const E=$.fields.find(N=>N.name===g.Pl.HolderRefField);if(E===void 0)throw new Error("Block pack ref field is missing");j.push([h,t.getResourceData(g.ensureResourceIdNotNull(E.value),!1)])}}for(const[h,b]of j){const y=await b,C=S.cachedDeserialize(S.notEmpty(y.data));h.blockConfig=D.extractConfig(C.config),h.blockPack=C.source}const Q=await us(),se=Ct(Q.hash),H=p.fields.find(h=>h.name===se);let oe;H!==void 0?oe=g.ensureResourceIdNotNull(H.value):(oe=g.Pl.wrapInHolder(t,je(t,Q.spec)),t.createField(g.field(r,Ct(Q.hash)),"Dynamic",oe));const ne={stagingRefreshTimestamp:A},_=new Set(q),W=new Map;for(const h of me){const b=ao(h.key);b!==void 0&&W.set(b,h.value)}const w=new Map;f.forEach(({id:h,fields:b,blockConfig:y,blockPack:C})=>w.set(h,new pr(h,b,S.notEmpty(y),S.notEmpty(C))));const m=new Set;for(const h of re(U)){if(!w.has(h.id))throw new Error(`Inconsistent project structure: no inputs for ${h.id}`);m.add(h.id)}w.forEach(h=>{if(!m.has(h.id))throw new Error(`Inconsistent project structure: no structure entry for ${h.id}`);h.check()});const R=new et(r,t,o,v,T,L,U,ne,_,w,W,oe,e);return R.fixProblemsAndMigrate(),R}}async function Jo(s,e=ro){const t=s.createEphemeral(so);s.lock(t);const r=String(Date.now());s.setKValue(t,Xr,JSON.stringify(Yr)),s.setKValue(t,Dt,r),s.setKValue(t,Ae,r),s.setKValue(t,Le,JSON.stringify(e)),s.setKValue(t,de,JSON.stringify(eo)),s.setKValue(t,Ze,JSON.stringify(to));const o=await us();return s.createField(g.field(t,Ct(o.hash)),"Dynamic",g.Pl.wrapInHolder(s,je(s,o.spec))),t}async function _e(s,e,t,r){return ie(s,e,t,void 0,r)}async function ie(s,e,t,r,o){if(e instanceof g.PlClient)return await e.withWriteTx("ProjectAction",async n=>{const i=await et.load(s,n,t,r),c=await o(i);return i.wasModified&&(i.save(),await n.commit()),c});{const n=await et.load(s,e,t,r),i=await o(n);return n.save(),i}}function*Mo(s){switch(s.type){case"Json":return;case"JsonPartitioned":for(const[,e]of Object.entries(s.parts))yield e;return;case"BinaryPartitioned":for(const[,{index:e,values:t}]of Object.entries(s.parts))yield e,yield t;return;default:S.assertNever(s)}}function fr(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function Go(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:fr(s.parts,e)};case"BinaryPartitioned":return{...s,parts:fr(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:S.assertNever(s)}}const _o=g.resourceType("PColumnData/JsonPartitioned","1"),Ko=g.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Ho=g.resourceType("PColumnData/BinaryPartitioned","1"),qo=g.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),Wo=g.resourceType("PColumnData/Json","1");function zo(s){if(!s.getIsReadyOrError())throw new Error("Data not ready.");const e=s.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(g.resourceTypesEqual(s.resourceType,Wo)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(g.resourceTypesEqual(s.resourceType,_o)){const t=e,r=Object.fromEntries(s.listInputFields().map(o=>[o,s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,Ko)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const c of i){const a=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);r[a]=n.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,Ho)){const t=e,r={};for(const o of s.listInputFields())if(o.endsWith(".index")){const n=o.slice(0,o.length-6);let i=r[n];i===void 0&&(i={},r[n]=i),i.index=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else if(o.endsWith(".values")){const n=o.slice(0,o.length-7);let i=r[n];i===void 0&&(i={},r[n]=i),i.values=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${o}`);for(const[o,n]of Object.entries(r)){if(n.index===void 0)throw new Error(`no index for part ${o}`);if(n.values===void 0)throw new Error(`no values for part ${o}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,qo)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const c of i)if(c.endsWith(".index")){const a=c.slice(0,c.length-6),l=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].index=n.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}else if(c.endsWith(".values")){const a=c.slice(0,c.length-7),l=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].values=n.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${c}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}throw new Error(`unsupported resource type: ${g.resourceTypeToString(s.resourceType)}`)}function Xo(s,e){const t=s.axesSpec.length,r={};for(const{key:o,val:n}of e){if(o.length!==t)throw new Error(`inline column key length ${o.length} differs from axes count ${t}`);r[JSON.stringify(o)]=n}return{type:"Json",keyLength:t,data:r}}function Yo(s,e){const t=Z.createHash("sha256");return t.update(x(s)),t.update(String(g.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function gr(s,e){return x({__isRef:!0,blockId:s,name:e})}function Qo(s,e){return x({resolvePath:s,name:e})}function ds(s,e=!0,t=!1,r=""){var c,a,l;const o=/^(?<name>.*)\.(?<type>spec|data)$/,n=new Map;for(const u of s.listInputFields()){const d=u.match(o);if(!d){if(e)throw new Error(`unexpected field name ${u}`);continue}let p=S.notEmpty((c=d.groups)==null?void 0:c.name);if(!p.startsWith(r)){if(e)throw new Error(`unexpected field name ${u}`);continue}p=p.slice(r.length);const f=S.notEmpty((a=d.groups)==null?void 0:a.type);let P=n.get(p);switch(P===void 0&&(P={},n.set(p,P)),f){case"spec":P.spec=(l=s.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:l.getDataAsJson();break;case"data":P.hasData=!0,P.data=()=>s.traverseOrError({field:u,ignoreError:t});break}}const i=s.getInputsLocked();if(i)for(const[,u]of n)u.data===void 0&&(u.hasData=!1);return{locked:i,results:n}}function Zo(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const o=ds(s,e,!1,t);js(o.locked);const n={};for(const[i,c]of o.results){if(c.spec===void 0)throw new Error(`no spec for key ${i}`);if(c.hasData!==!0||c.data===void 0)throw new Error(`no data for key ${i}`);const a=c.data();if(a===void 0)throw new Error(`no data for key ${i}`);if(!a.ok)throw a.error;n[i]={id:r.length===0?Yo(c.spec,a.value):Qo(r,i),spec:c.spec,data:a.value}}return n}class Bt{constructor(e,t){k(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const o of t.values())for(const n of[o.prod,o.staging])if(n!==void 0){if(!n.locked){r=!1;break e}for(const i of n.results.values())if(i.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var n,i,c,a,l,u;const r=this.blocks.get(e);if(r===void 0)return;let o=(c=(i=(n=r.prod)==null?void 0:n.results)==null?void 0:i.get(t))==null?void 0:c.spec;if(o!==void 0||(o=(u=(l=(a=r.staging)==null?void 0:a.results)==null?void 0:l.get(t))==null?void 0:u.spec,o!==void 0))return o;r.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):r.staging.locked?r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var i,c,a;const r=this.blocks.get(e);if(r===void 0)return;const o=(c=(i=r.prod)==null?void 0:i.results)==null?void 0:c.get(t),n=(a=o==null?void 0:o.data)==null?void 0:a.call(o);if(o!==void 0&&o.spec!==void 0&&n!==void 0)return D.mapValueInVOE(n,l=>({id:gr(e,t),spec:o.spec,data:l}));o!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const r=this.getDataOrErrorByRef(e,t);if(!(r===void 0||!r.ok))return r.value}getData(){const e=this.getDataWithErrors(),t=[];for(const r of e.entries)r.obj.id!==void 0&&r.obj.data.ok&&t.push({ref:r.ref,obj:{id:r.obj.id,spec:r.obj.spec,data:r.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,r;const o=i=>{r===void 0&&(r=i),t=!1},n=(i,c,a)=>{if(a.spec!==void 0&&a.hasData===!0&&a.data!==void 0){const l=a.data();l!==void 0?e.push({ref:Ge(i,c),obj:{id:l.ok?gr(i,c):void 0,spec:a.spec,data:l}}):o(`no_data:${i}:${c}`)}};for(const[i,c]of this.blocks){const a=new Set;if(c.prod!==void 0){c.prod.locked||o(`prod_not_locked:${i}`);for(const[l,u]of c.prod.results)a.add(l),n(i,l,u)}if(c.staging!==void 0){c.staging.locked||o(`staging_not_locked:${i}`);for(const[l,u]of c.staging.results)a.has(l)||n(i,l,u)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const o=n=>{r===void 0&&(r=n),t=!1};for(const[n,i]of this.blocks){const c=new Set;if(i.staging!==void 0){i.staging.locked||o(`staging_not_locked:${n}`);for(const[a,l]of i.staging.results)l.spec!==void 0&&(e.push({ref:Ge(n,a),obj:l.spec}),c.add(a))}else o(`staging_not_rendered:${n}`);if(i.prod!==void 0){i.prod.locked||o(`prod_not_locked:${n}`);for(const[a,l]of i.prod.results)c.has(a)||l.spec!==void 0&&e.push({ref:Ge(n,a),obj:l.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const o=new Set,n=i=>{for(const[c,a]of i.results)o.has(c)||a.spec===void 0||(o.add(c),D.executePSpecPredicate(e,a.spec)&&t.push({label:r.info.label+" / "+c,ref:Ge(r.info.id,c),spec:a.spec}))};r.staging!==void 0&&n(r.staging),r.prod!==void 0&&n(r.prod)}return t}static create(e,t,r){const o=e.accessor(t).node(),n=S.notEmpty(o.getKeyValueAsJson(de)),c=Rt(n).traverseIds("upstream",r),a=new Map;for(const l of re(n)){if(!c.has(l.id))continue;const u=hr(o.traverse({field:K(l.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:K(l.id,"prodUiCtx"),stableIfNotFound:!0})),d=hr(o.traverse({field:K(l.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:K(l.id,"stagingUiCtx")}));a.set(l.id,{info:l,prod:u,staging:d})}return new Bt(e,a)}}function hr(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return ds(e.value,!1,!0)}function jt(s,e){return{blockId:e,args:n=>S.notEmpty(n.accessor(s).node().traverse({field:K(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),activeArgs:n=>{var i;return(i=n.accessor(s).node().traverse({field:K(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:i.getDataAsString()},uiState:n=>n.accessor(s).node().getKeyValueAsString(bt(e)),blockMeta:n=>{const i=n.accessor(s).node(),c=S.notEmpty(i.getKeyValueAsJson(de)),a=new Map;for(const l of re(c))a.set(l.id,l);return a}}}function ps(s,e){return{...jt(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:K(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:r.persist()},staging:t=>{var o;const r=(o=t.accessor(s).node({ignoreError:!0}).traverse({field:K(e,"stagingOutput"),ignoreError:!0}))==null?void 0:o.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>Bt.create(t,s,e)}}function*ee(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*ee(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*ee(t);return;case"MakeArray":for(const t of s.template)yield*ee(t);return;case"GetJsonField":case"GetResourceField":yield*ee(s.source),yield*ee(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*ee(s.source),yield*ee(s.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"ExtractArchiveAndGetURL":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetProgressLogWithInfo":case"GetLogHandle":yield*ee(s.source);return;case"IsEmpty":yield*ee(s.arg);return;case"Not":yield*ee(s.operand);return;case"And":case"Or":yield*ee(s.operand1),yield*ee(s.operand2);return;default:S.assertNever(s)}}function en(s,e){const t={};for(const[r,o]of Object.entries(s))t[r]=e(o);return t}function $e(s,e){return s===void 0?void 0:e(s)}function tn(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function rn(s){for(const e of ee(s))if(tn(e))return!0;return!1}function ot(s){return{type:"ReturnResult",result:s}}function I(s){return()=>ot(s)}const sn=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return I(e)},on=s=>{const e=s.source;if(e===void 0)return I(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return I(t)},nn=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?I(void 0):({cCtx:r})=>{var o;return ot((o=r.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function fs(s,e){const t={},r=s.length;for(let o=0;o<r;o++)t[String(o)]=e(s[o]);return t}function an(s,e){return t=>{const r=t.source;return r===void 0?I(void 0):()=>({type:"ScheduleSubroutine",subroutine:gs(r.length),args:fs(r,o=>F({...s,[e.itVar]:o},e.mapping))})}}function gs(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return I(t)}}function cn(s,e){return t=>{const r=t.source;if(r===void 0)return I(void 0);const o={};for(const[n,i]of Object.entries(r)){const c={...s,[e.itVar]:i};o[n]=F(c,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:ln,args:o})}}const ln=s=>I(s),un=s=>{const e=s.arg;return I(e===void 0?void 0:e.length===0)},dn=s=>{const e=s.operand;return I(e===void 0?void 0:!e)},pn=s=>{const e=s.operand1,t=s.operand2;return I(e===void 0||t===void 0?void 0:e&&t)},fn=s=>{const e=s.operand1,t=s.operand2;return I(e===void 0||t===void 0?void 0:e||t)},gn=s=>{const e=s.source;return e===void 0?I(void 0):({cCtx:t})=>{var r;return ot((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},hn=s=>{const e=s.source,t=s.field;return I(e===void 0||t===void 0?void 0:e[t])};function mn(s,e){return t=>{const r=t.source;return r===void 0?I(void 0):({cCtx:o})=>{const n=o.accessor(r).node(),i={};for(const c of n.listInputFields()){const a=n.traverse(c);if(a===void 0)i[c]=I(void 0);else{const l={...s,[e.itVar]:a.persist()};i[c]=F(l,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:vn,args:i}}}}const vn=s=>I(s),yn=s=>e=>{const t=e.source;return t===void 0?I(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:V.Computable.make(o=>r.blobDriver.getDownloadedBlob(o.accessor(t).node().resourceInfo),{postprocessValue:async o=>{if(o!==void 0)return await r.blobDriver.getContent(o.handle,s)}})})},wn=s=>e=>{const t=e.source;return t===void 0?I(void 0):({cCtx:r,drivers:o})=>{const n=r.accessor(t).node().resourceInfo;return{type:"ScheduleComputable",computable:V.Computable.make(i=>o.blobDriver.getDownloadedBlob(n,i),{postprocessValue:async i=>i===void 0?void 0:(await o.blobDriver.getContent(i.handle,s)).toString()})}}},bn=s=>e=>{const t=e.source;return t===void 0?I(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:V.Computable.make(o=>r.blobDriver.getDownloadedBlob(o.accessor(t).node().resourceInfo,o),{postprocessValue:async o=>{if(o==null)return;const n=await r.blobDriver.getContent(o.handle,s);if(n!=null)return JSON.parse(Buffer.from(n).toString())}})})},Sn=s=>{const e=s.source;return e===void 0?I(void 0):t=>({type:"ScheduleComputable",computable:t.drivers.blobDriver.getDownloadedBlob(e)})},kn=s=>{const e=s.source;return e===void 0?I(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},Cn=s=>e=>{const t=e.source;return t===void 0?I(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.blobToURLDriver.extractArchiveAndGetURL(t,s)})},Pn=s=>{const e=s.source;return e===void 0?I(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},Rn=s=>e=>{const t=e.source;return t===void 0?I(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},En=s=>e=>{const t=e.source;return t===void 0?I(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},On=s=>e=>{const t=e.source;return t===void 0?I(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLogWithInfo(t,s)})},$n=s=>{const e=s.source;return e===void 0?I(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function F(s,e){switch(e.type){case"GetFromCtx":{const t=s[e.variable];return typeof t=="function"?r=>ot(t(r.cCtx)):I(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:vs(t,s,e.cfg)});case"Immediate":return I(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:hn,args:{source:F(s,e.source),field:F(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:an(s,e),args:{source:F(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:cn(s,e),args:{source:F(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:sn,args:en(e.template,t=>F(s,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:gs(e.template.length),args:fs(e.template,t=>F(s,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:on,args:{source:F(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:un,args:{arg:F(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:dn,args:{operand:F(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:pn,args:{operand1:F(s,e.operand1),operand2:F(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:fn,args:{operand1:F(s,e.operand1),operand2:F(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:mn(s,e),args:{source:F(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:nn,args:{source:F(s,e.source),field:F(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:gn,args:{source:F(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:yn(e.range),args:{source:F(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:wn(e.range),args:{source:F(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:bn(e.range),args:{source:F(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Sn,args:{source:F(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:kn,args:{source:F(s,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:Cn(e.format),args:{source:F(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:Pn,args:{source:F(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:Rn(e.lines),args:{source:F(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:En(e.patternToSearch),args:{source:F(s,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:On(e.patternToSearch),args:{source:F(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:$n,args:{source:F(s,e.source)}});default:return S.assertNever(e)}}const Tn=["$prod","$staging"];function In(s){return{$blockId:s.blockId,$args:e=>JSON.parse(s.args(e)),$ui:e=>{const t=s.uiState(e);return t!==void 0?JSON.parse(t):void 0},$prod:s.prod,$staging:s.staging}}const hs=Symbol(),ms="return",Fn={op:hs,arg:ms};function Dn(s){return s.op==hs&&s.arg==ms}function An(){return{pendingSubroutines:new Map}}function mr(s,e,t,r){const o=new Gr(t),n=(c,a)=>{if(Dn(c))return e.result=a,!1;const l=S.notEmpty(e.pendingSubroutines.get(c.op));if(c.arg in l.args)throw new Error("argument already set");return l.args[c.arg]=a,l.argCounter--,l.argCounter===0&&(e.pendingSubroutines.delete(c.op),o.push({destination:l.destination,operation:l.subroutine(l.args)})),!0},i=[];e:for(;o.length>0;){const c=o.shift(),a=c.operation(s);switch(a.type){case"ReturnResult":if(!n(c.destination,a.result))break e;break;case"ScheduleSubroutine":{const l=Symbol(),u=Object.entries(a.args),d=u.length;if(d===0)o.push({destination:c.destination,operation:a.subroutine({})});else{for(const[p,f]of u)o.push({destination:{op:l,arg:p},operation:f});e.pendingSubroutines.set(l,{argCounter:d,args:{},subroutine:a.subroutine,destination:c.destination})}}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:c.destination,computable:a.computable});break;default:S.assertNever(a)}}return i}function Ln(s,e,t,r={}){return vs(s,In(e),t,r)}function vs(s,e,t,r={}){const o=`${e.blockId}#`+x({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>Tn.indexOf(n)===-1)),cfg:t});return V.Computable.makeRaw(n=>{const i={drivers:s,cCtx:n},c=An();return{ir:mr(i,c,[{destination:Fn,operation:F(e,t)}],!0),postprocessValue(l){const u=[];for(const P of l)u.push({destination:P.destination,operation:I(P.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},p=new Map;for(const[P,v]of c.pendingSubroutines)p.set(P,{...v,args:{...v.args}});const f={result:c.result,pendingSubroutines:p};if(mr(d,f,u,!1),!("result"in f))throw new Error("illegal cfg rendering stack state, no result");return f.result}}},{...r,key:o})}function vr(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class Nn{constructor(e,t,r,o){k(this,"computablesToResolve",{});k(this,"computableCtx");k(this,"accessors",new Map);k(this,"meta");k(this,"_resultPool");this.parent=e,this.blockCtx=t,this.env=r,this.computableCtx=o,this.meta=t.blockMeta(o)}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,o)=>{if(!this.accessors.has(r)){const n=this.blockCtx[o];if(n===void 0)throw new Error("Staging context not available");const i=n(this.computableCtx);i?this.accessors.set(r,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(r,void 0)}return this.accessors.get(r)?r:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...r){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...r))}getResourceType(e){return this.getAccessor(e).resourceType}getInputsLocked(e){return this.getAccessor(e).getInputsLocked()}getOutputsLocked(e){return this.getAccessor(e).getOutputsLocked()}getIsReadyOrError(e){return this.getAccessor(e).getIsReadyOrError()}getIsFinal(e){return this.getAccessor(e).getIsFinal()}getError(e){return this.wrapAccessor(this.getAccessor(e).getError())}listInputFields(e){return this.getAccessor(e).listInputFields()}listOutputFields(e){return this.getAccessor(e).listOutputFields()}listDynamicFields(e){return this.getAccessor(e).listDynamicFields()}getKeyValueBase64(e,t){return vr(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return vr(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r,...o){const n=this.getAccessor(e);if(!n.getIsReadyOrError())return;const i=Zo(n,t,r,o),c={};for(const[a,l]of Object.entries(i))c[a]=D.mapPObjectData(l,u=>this.wrapAccessor(u));return c}registerComputable(e,t){const r=`${e}_${Z.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e,t){const r=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",V.Computable.make(o=>this.env.driverKit.blobDriver.getDownloadedBlob(r,o),{postprocessValue:async o=>{if(o!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(o.handle,t)).toString("utf-8")}}))}getBlobContentAsBase64(e,t){const r=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",V.Computable.make(o=>this.env.driverKit.blobDriver.getDownloadedBlob(r,o),{postprocessValue:async o=>{if(o!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(o.handle,t)).toString("base64")}}))}getDownloadedBlobContentHandle(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getDownloadedBlobContentHandle",this.env.driverKit.blobDriver.getDownloadedBlob(t))}getOnDemandBlobContentHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getOnDemandBlobContentHandle",this.env.driverKit.blobDriver.getOnDemandBlob(t))}extractArchiveAndGetURL(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("extractArchiveAndGetURL",this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(r,t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(r,t))}getProgressLog(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(r,t))}getProgressLogWithInfo(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLogWithInfo",this.env.driverKit.logDriver.getProgressLogWithInfo(r,t))}getLogHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getLogHandle",this.env.driverKit.logDriver.getLogHandle(t))}getBlockLabel(e){const t=this.meta.get(e);if(t===void 0)throw new Error(`Block ${e} not found.`);return t.label}get resultPool(){if(this._resultPool===void 0){if(this.computableCtx===void 0)throw new Error("can't use result pool in this context (most porbably called from the future mapper)");this._resultPool=S.notEmpty(this.blockCtx.getResultsPool,"getResultsPool")(this.computableCtx)}return this._resultPool}calculateOptions(e){return this.resultPool.calculateOptions(e)}getDataFromResultPool(){const e=this.resultPool.getData();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:D.mapPObjectData(t.obj,r=>this.wrapAccessor(r))}))}}getDataWithErrorsFromResultPool(){const e=this.resultPool.getDataWithErrors();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:{id:t.obj.id,spec:t.obj.spec,data:D.mapValueInVOE(t.obj.data,r=>this.wrapAccessor(r))}}))}}getSpecsFromResultPool(){const e=this.resultPool.getSpecs();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`specs_from_pool_incomplete:${e.instabilityMarker}`),e}getSpecFromResultPoolByRef(e,t){return this.resultPool.getSpecByRef(e,t)}getDataFromResultPoolByRef(e,t){return D.mapPObjectData(this.resultPool.getDataByRef(e,t),r=>this.wrapAccessor(r))}createPFrame(e){if(this.computableCtx===void 0)throw new Error("can't instantiate PFrames from this context (most porbably called from the future mapper)");return this.env.driverKit.pFrameDriver.createPFrame(e.map(t=>D.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}createPTable(e){if(this.computableCtx===void 0)throw new Error("can't instantiate PTable from this context (most porbably called from the future mapper)");return this.env.driverKit.pFrameDriver.createPTable(D.mapPTableDef(e,t=>D.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}transformInputPData(e){return typeof e=="string"?this.getAccessor(e):D.isDataInfo(e)?D.mapDataInfo(e,t=>this.getAccessor(t)):e}getCurrentUnstableMarker(){var e;return(e=this.computableCtx)==null?void 0:e.unstableMarker}logInfo(e){this.env.blockEventDispatcher.logInfo(this.blockCtx.blockId,e)}logWarn(e){this.env.blockEventDispatcher.logWarn(this.blockCtx.blockId,e)}logError(e){this.env.blockEventDispatcher.logError(this.blockCtx.blockId,e)}getAccessor(e){const t=this.accessors.get(e);if(t===void 0)throw new Error("No such accessor");return t}wrapAccessor(e){if(e!==void 0){const t=Z.randomUUID();return this.accessors.set(t,e),t}}injectCtx(e){const t=this.parent,r=t.vm;ge.Scope.withScope(o=>{const n=this.blockCtx.args(this.computableCtx),i=this.blockCtx.activeArgs(this.computableCtx),c=this.blockCtx.uiState(this.computableCtx);r.setProp(e,"args",o.manage(r.newString(n))),c!==void 0&&r.setProp(e,"uiState",o.manage(r.newString(c))),i!==void 0&&r.setProp(e,"activeArgs",o.manage(r.newString(i)));const a=(l,u)=>{const d=(...p)=>{try{return u(...p)}catch(f){const P=t.errorRepo.setAndRecreateForQuickJS(f);throw r.newError(P)}};r.newFunction(l,d).consume(p=>r.setProp(e,l,p)),r.newFunction(l,u).consume(p=>r.setProp(e,l+"__internal__",p))};a("getAccessorHandleByName",l=>t.exportSingleValue(this.getAccessorHandleByName(r.getString(l)),void 0)),a("resolveWithCommon",(l,u,...d)=>t.exportSingleValue(this.resolveWithCommon(r.getString(l),t.importObjectViaJson(u),...d.map(p=>t.importObjectViaJson(p))),void 0)),a("getResourceType",l=>t.exportObjectViaJson(this.getResourceType(r.getString(l)),void 0)),a("getInputsLocked",l=>t.exportSingleValue(this.getInputsLocked(r.getString(l)),void 0)),a("getOutputsLocked",l=>t.exportSingleValue(this.getOutputsLocked(r.getString(l)),void 0)),a("getIsReadyOrError",l=>t.exportSingleValue(this.getIsReadyOrError(r.getString(l)),void 0)),a("getIsFinal",l=>t.exportSingleValue(this.getIsFinal(r.getString(l)),void 0)),a("getError",l=>t.exportSingleValue(this.getError(r.getString(l)),void 0)),a("listInputFields",l=>t.exportObjectViaJson(this.listInputFields(r.getString(l)),void 0)),a("listOutputFields",l=>t.exportObjectViaJson(this.listInputFields(r.getString(l)),void 0)),a("listDynamicFields",l=>t.exportObjectViaJson(this.listInputFields(r.getString(l)),void 0)),a("getKeyValueBase64",(l,u)=>t.exportSingleValue(this.getKeyValueBase64(r.getString(l),r.getString(u)),void 0)),a("getKeyValueAsString",(l,u)=>t.exportSingleValue(this.getKeyValueAsString(r.getString(l),r.getString(u)),void 0)),a("getDataBase64",l=>t.exportSingleValue(this.getDataBase64(r.getString(l)),void 0)),a("getDataAsString",l=>t.exportSingleValue(this.getDataAsString(r.getString(l)),void 0)),a("parsePObjectCollection",(l,u,d,...p)=>t.exportObjectUniversal(this.parsePObjectCollection(r.getString(l),r.dump(u),r.getString(d),...p.map(f=>r.getString(f))),void 0)),a("getBlobContentAsBase64",(l,u)=>t.exportSingleValue(this.getBlobContentAsBase64(r.getString(l),t.importObjectUniversal(u)),void 0)),a("getBlobContentAsString",(l,u)=>t.exportSingleValue(this.getBlobContentAsString(r.getString(l),t.importObjectUniversal(u)),void 0)),a("getDownloadedBlobContentHandle",l=>t.exportSingleValue(this.getDownloadedBlobContentHandle(r.getString(l)),void 0)),a("getOnDemandBlobContentHandle",l=>t.exportSingleValue(this.getOnDemandBlobContentHandle(r.getString(l)),void 0)),a("extractArchiveAndGetURL",(l,u)=>t.exportSingleValue(this.extractArchiveAndGetURL(r.getString(l),r.getString(u)),void 0)),a("getImportProgress",l=>t.exportSingleValue(this.getImportProgress(r.getString(l)),void 0)),a("getLastLogs",(l,u)=>t.exportSingleValue(this.getLastLogs(r.getString(l),r.getNumber(u)),void 0)),a("getProgressLog",(l,u)=>t.exportSingleValue(this.getProgressLog(r.getString(l),r.getString(u)),void 0)),a("getProgressLogWithInfo",(l,u)=>t.exportSingleValue(this.getProgressLogWithInfo(r.getString(l),r.getString(u)),void 0)),a("getLogHandle",l=>t.exportSingleValue(this.getLogHandle(r.getString(l)),void 0)),a("getBlockLabel",l=>t.exportSingleValue(this.getBlockLabel(r.getString(l)),void 0)),a("getDataFromResultPool",()=>t.exportObjectUniversal(this.getDataFromResultPool(),void 0)),a("getDataWithErrorsFromResultPool",()=>t.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),a("getSpecsFromResultPool",()=>t.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),a("calculateOptions",l=>t.exportObjectUniversal(this.calculateOptions(t.importObjectViaJson(l)),void 0)),a("getSpecFromResultPoolByRef",(l,u)=>t.exportObjectUniversal(this.getSpecFromResultPoolByRef(r.getString(l),r.getString(u)),void 0)),a("getDataFromResultPoolByRef",(l,u)=>t.exportObjectUniversal(this.getDataFromResultPoolByRef(r.getString(l),r.getString(u)),void 0)),a("createPFrame",l=>t.exportSingleValue(this.createPFrame(t.importObjectViaJson(l)),void 0)),a("createPTable",l=>t.exportSingleValue(this.createPTable(t.importObjectViaJson(l)),void 0)),a("getCurrentUnstableMarker",()=>t.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),a("logInfo",l=>{this.logInfo(r.getString(l))}),a("logWarn",l=>{this.logWarn(r.getString(l))}),a("logError",l=>{this.logError(r.getString(l))})})}}function Bn(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}class Ne{constructor(e,t,r,o){k(this,"callbackRegistry");k(this,"fnJSONStringify");k(this,"fnJSONParse");k(this,"errorRepo",new jn);k(this,"computableHelper");if(this.scope=e,this.vm=t,this.deadlineSetter=r,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(n=>t.getProp(n,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(n=>t.getProp(n,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");o!==void 0&&(this.computableHelper=new Nn(this,o.blockCtx,o.mlEnv,o.computableCtx)),this.injectCtx()}resetComputableCtx(){S.notEmpty(this.computableHelper,"Computable context helper is not initialized").resetComputableCtx()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.deadlineSetter({currentExecutionTarget:"evaluateBundle",deadline:Date.now()+1e4}),this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw Ne.cleanErrorContext(t),t}finally{this.deadlineSetter(void 0)}}runCallback(e,...t){try{return this.deadlineSetter({currentExecutionTarget:e,deadline:Date.now()+1e4}),ge.Scope.withScope(r=>{const o=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(o)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(o,this.vm.undefined,...t.map(n=>this.exportObjectUniversal(n,r)))))})}catch(r){throw Ne.cleanErrorContext(r),this.errorRepo.getOriginal(r)}finally{this.deadlineSetter(void 0)}}exportSingleValue(e,t){const r=this.tryExportSingleValue(e,t);if(r===void 0)throw new Error(`Can't export value: ${e===void 0?"undefined":JSON.stringify(e)}`);return r}tryExportSingleValue(e,t){let r,o=!1;switch(typeof e){case"string":r=this.vm.newString(e),o=!0;break;case"number":r=this.vm.newNumber(e),o=!0;break;case"undefined":r=this.vm.undefined;break;case"boolean":r=e?this.vm.true:this.vm.false;break;default:if(e===null){r=this.vm.null;break}if(Bn(e)){r=this.vm.newArrayBuffer(e),o=!0;break}return}return o&&t!=null?t.manage(r):r}exportObjectUniversal(e,t){const r=this.tryExportSingleValue(e,t);return r!==void 0?r:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const r=this.vm.newString(JSON.stringify(e)).consume(o=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,o)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){if(e!==void 0)switch(this.vm.typeof(e)){case"undefined":return;case"boolean":case"number":case"string":return this.vm.dump(e);default:return this.importObjectViaJson(e)}}importObjectViaJson(e){const t=this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify,this.vm.undefined,e)).consume(r=>this.vm.getString(r));if(t!=="undefined")return JSON.parse(t)}injectCtx(){ge.Scope.withScope(e=>{const t=e.manage(this.vm.newObject());this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(D.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e)),this.computableHelper!==void 0&&this.computableHelper.injectCtx(t),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}class jn{constructor(){k(this,"errorIdToError",new Map)}setAndRecreateForQuickJS(e){const t=Z.randomUUID();return this.errorIdToError.set(t,e),e instanceof Error?{name:`${e.name}/uuid:${t}`,message:e.message}:{name:`UnknownErrorQuickJS/uuid:${t}`,message:`${e}`}}getOriginal(e){if(!(e instanceof ge.errors.QuickJSUnwrapError))return console.warn("ErrorRepo: quickJSError is not a QuickJSUnwrapError",g.stringifyWithResourceId(e)),e;if(!("name"in e.cause))return console.warn("ErrorRepo: quickJSError.cause is not an Error",g.stringifyWithResourceId(e)),e;const t=e.cause.name,r=t.slice(t.indexOf("/uuid:")+6);if(!r)throw new Error(`ErrorRepo: quickJSError.cause.name does not contain errorId: ${t}, ${g.stringifyWithResourceId(e)}`);const o=this.errorIdToError.get(r);if(o===void 0)throw new Error(`ErrorRepo: errorId not found: ${r}, ${g.stringifyWithResourceId(e)}`);return new Vs.PlQuickJSError(e,o)}}function Be(s,e){return $e(s.traverse({field:K(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),o=D.extractConfig(r.config);return{bpResourceId:t.resourceInfo.id,bpId:t.resourceInfo.id.toString(),info:r,cfg:o}})}const Ke=process.env.MI_LOG_OUTPUT_STATUS;function Vn(s,e,t,r,o,n={}){const i=`${e.blockId}#lambda#${o}#${t.handle}`;return n={...n,key:i},n.mode===void 0&&t.retentive===!0&&(n.mode="StableOnlyRetentive"),V.Computable.makeRaw(c=>{const a=new ge.Scope;c.addOnDestroy(()=>a.dispose());const l=a.manage(s.quickJs.newRuntime());l.setMemoryLimit(1024*1024*8),l.setMaxStackSize(1024*320);let u;l.setInterruptHandler(()=>u===void 0?!1:Date.now()>u.deadline);const d=a.manage(l.newContext()),p=new Ne(a,d,v=>{u=v},{computableCtx:c,blockCtx:e,mlEnv:s});p.evaluateBundle(r.content);const f=p.runCallback(t.handle);p.resetComputableCtx();let P=0;return Ke&&Ke!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:p.computableHelper.computablesToResolve,postprocessValue:(v,{unstableMarker:T,stable:L})=>{for(const[A,q]of Object.entries(v))p.runCallback(A,q);const U=p.importObjectUniversal(f);return P++,Ke&&(Ke!=="unstable-only"||!L)&&console.log(L?`Stable output ${t.handle} calculated ${U!==void 0?"defined":"undefined"}; (#${P})`:`Unstable output ${t.handle}; marker = ${T}; ${U!==void 0?"defined":"undefined"} (#${P})`),U}}},n)}function xn(s,e,t,...r){const o=new ge.Scope;try{const n=o.manage(s.newRuntime());n.setMemoryLimit(1024*1024*8),n.setMaxStackSize(1024*320);let i;n.setInterruptHandler(()=>i===void 0?!1:Date.now()>i.deadline);const c=o.manage(n.newContext()),a=new Ne(o,c,l=>{i=l});return a.evaluateBundle(t.content),a.importObjectUniversal(a.runCallback(e.handle,...r))}finally{o.dispose()}}function Un(s){return D.isConfigLambda(s)?s.isActive===!0:rn(s)}function Te(s,e,t,r,o,n={}){if(D.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return Vn(s,e,t,r,o,n)}else return Ln(s.driverKit,e,t,n)}function Jn(s,e){if(s===e)return!0;if(s===void 0||e===void 0)return!1;const t=tr.omitBy((r,o)=>o.startsWith("__"));return tr.isDeepEqual(t(s),t(e))}function Mn(s,e,t){return V.Computable.make(r=>{var P,v,T,L,U,A,q,me;const o=r.accessor(s).node(),n=S.notEmpty(o.getKeyValueAsJson(Dt)),i=S.notEmpty(o.getKeyValueAsJson(Ae)),c=S.notEmpty(o.getKeyValueAsJson(Le)),a=S.notEmpty(o.getKeyValueAsJson(de)),l=S.notEmpty(o.getKeyValueAsJson(Ze)),u=new Map;for(const{id:j}of re(a)){const Q=o.traverse({field:K(j,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}),se=Q.getDataAsJson();let H;const oe=o.traverse({field:K(j,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(oe!==void 0){const ne=oe.getDataAsJson(),_=o.getField({field:K(j,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),W=o.getField({field:K(j,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});H={arguments:ne,stale:!Jn(se,ne),outputError:_.error!==void 0||W.error!==void 0||((P=_.value)==null?void 0:P.getError())!==void 0||((v=W.value)==null?void 0:v.getError())!==void 0,outputsError:((T=_.error)==null?void 0:T.getDataAsString())??((U=(L=_.value)==null?void 0:L.getError())==null?void 0:U.getDataAsString()),exportsError:((A=W.error)==null?void 0:A.getDataAsString())??((me=(q=W.value)==null?void 0:q.getError())==null?void 0:me.getDataAsString()),finished:(_.value!==void 0&&_.value.getIsReadyOrError()||_.error!==void 0&&_.error.getIsReadyOrError())&&(W.value!==void 0&&W.value.getIsReadyOrError()||W.error!==void 0&&W.error.getIsReadyOrError())}}u.set(j,{currentArguments:se,prod:H,argsRid:Q.resourceInfo.id})}const d=Ye(a,j=>{const Q=Be(o,j),se=u.get(j),H=se.currentArguments;return{args:H,enrichmentTargets:t.projectHelper.getEnrichmentTargets(()=>Q.cfg,()=>H,{argsRid:se.argsRid,blockPackRid:Q.bpResourceId})}}),p=new Set(l.blocksInLimbo),f=[...re(a)].map(({id:j,label:Q,renderingMode:se})=>{var y,C,$,E,N;const H=S.notEmpty(u.get(j)),oe=S.notEmpty(d.nodes.get(j));let ne="NotCalculated";H.prod!==void 0&&(p.has(j)?ne="Limbo":ne=H.prod.finished?"Done":"Running");const _=Be(o,j),{sections:W,title:w,inputsValid:m,sdkVersion:R}=$e(_,({bpId:G,cfg:B})=>{const ue=jt(s,j);return{sections:Te(t,ue,B.sections,B.code,G).wrap({recover:Pe=>(t.logger.error("Error in block model sections"),t.logger.error(Pe),[])}),title:$e(B.title,Pe=>Te(t,ue,Pe,B.code,G).wrap({recover:Fs=>(t.logger.error("Error in block model title"),t.logger.error(Fs),"Invalid title")})),inputsValid:Te(t,ue,B.inputsValid,B.code,G).wrap({recover:Pe=>(t.logger.error("Error in block model argsValid"),t.logger.error(Pe),!1)}),sdkVersion:B.sdkVersion}})||{},h=o.traverse({field:K(j,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),b=$e(_,({info:G})=>t.blockUpdateWatcher.get({currentSpec:G.source,settings:h}));return{projectResourceId:g.resourceIdToString(s.rid),id:j,label:w??Q,title:w??Q,renderingMode:se,stale:((y=H.prod)==null?void 0:y.stale)!==!1||ne==="Limbo",missingReference:oe.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",j)],downstreams:[...d.traverseIdsExcludingRoots("downstream",j)],calculationStatus:ne,outputErrors:((C=H.prod)==null?void 0:C.outputError)===!0,outputsError:($=H.prod)==null?void 0:$.outputsError,exportsError:(E=H.prod)==null?void 0:E.exportsError,settings:h,sections:W,inputsValid:m,updateInfo:{},currentBlockPack:(N=_==null?void 0:_.info)==null?void 0:N.source,updates:b,sdkVersion:R,navigationState:e.getState(j)}});return{meta:c,created:new Date(n),lastModified:new Date(i),authorMarker:o.getKeyValueAsJson(kt),blocks:f}},{postprocessValue:r=>{const o=new Set,n=new Set;return{...r,blocks:r.blocks.map(i=>{var u,d;i.inputsValid||o.add(i.id),i.stale&&n.add(i.id);const c=i.stale||i.upstreams.findIndex(p=>n.has(p))!==-1,a=(c||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(p=>o.has(p))===-1,l={...i,canRun:a,stale:c,updateSuggestions:((u=i.updates)==null?void 0:u.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete l.updates,l})}}}).withStableType()}function Gn(s,e){const t=s.node();if(g.resourceTypesEqual(t.resourceType,Lt)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.frontendDownloadDriver.getPath(new URL(r.url)).withStableType()}else if(g.resourceTypesEqual(t.resourceType,Nt)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.signer.verify(r.path,r.signature,`Frontend path signature mismatch for: ${r.path}`),r.path}else throw new Error(`Unsupported resource type: ${JSON.stringify(t.resourceType)}`)}function _n(s,e){if(s!==void 0)return V.Computable.make(t=>Gn(t.accessor(s),e),{postprocessValue:t=>{if(t!==void 0){if(typeof t=="string")return t;if(t.error!==void 0)throw new Error(t.error);return t.path}}}).withStableType()}function Kn(s,e,t){return V.Computable.make(r=>{var c;const o=r.accessor(s).node(),n=Be(o,e),i=(c=o.traverse({field:K(e,"blockPack"),assertFieldType:"Dynamic"},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:cs,assertFieldType:"Input"}))==null?void 0:c.persist();return{path:_n(i,t),sdkVersion:n==null?void 0:n.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function ys(s,e,t){if(t===void 0)return V.Computable.make(i=>ys(s,e,i),{key:`inputs#${g.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),o=jt(s,e),n=o.uiState(t);return{author:r.getKeyValueAsJson(St(e)),args:S.deepFreeze(JSON.parse(o.args(t))),ui:n!==void 0?S.deepFreeze(JSON.parse(n)):void 0}}function Hn(s,e,t){return V.Computable.make(r=>{const o=r.accessor(s).node(),n=ps(s,e);return $e(Be(o,e),({cfg:i,bpId:c})=>{const a={};for(const[l,u]of Object.entries(i.outputs)){const d=Te(t,n,u,i.code,c);a[l]=V.Computable.wrapError(d,1)}return a})},{key:"outputs#"+g.resourceIdToString(s.rid)+"#"+e}).withStableType()}function qn(s,e){return V.Computable.make(t=>{const r=t.accessor(s).node(),o=S.notEmpty(r.getKeyValueAsJson(de)),n=[];for(const{id:i}of re(o)){const c=Be(r,i);if(c===void 0)continue;const a=Object.entries(c.cfg.outputs).map(([,u])=>u).filter(u=>Un(u)).map(u=>u);if(a.length===0)continue;const l=ps(r.persist(),i);for(const u of a)n.push(V.Computable.wrapError(Te(e,l,u,c.cfg.code,c.bpId)))}return n})}class Wn{constructor(){k(this,"states",new Map)}setState(e,t){const r=this.states.get(e);if(r===void 0){this.states.set(e,{state:t,change:new V.ChangeSource});return}r.state={...t},r.change.markChanged()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...D.DefaultNavigationState},change:new V.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return V.Computable.make(t=>this.readState(t,e),{key:`navigationState#${e}`})}deleteBlock(e){const t=this.states.get(e);t!==void 0&&(this.states.delete(e),t.change.markChanged())}}function zn(s){return V.Computable.make(e=>{const t=e.accessor(s).node(),r=S.notEmpty(t.getKeyValueAsJson(de));return{listOfBlocks:[...re(r)].map(o=>o.id)}})}function yr(s){return JSON.stringify(s,(e,t)=>typeof t=="bigint"?g.resourceIdToString(t):ArrayBuffer.isView(t)||t instanceof Int8Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array||t instanceof Float64Array||t instanceof BigInt64Array||t instanceof BigUint64Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"):Buffer.isBuffer(t)?t.toString("base64"):t)}class nt{constructor(e,t,r){k(this,"rid");k(this,"overview");k(this,"overviewLight");k(this,"navigationStates",new Wn);k(this,"blockComputables",new Map);k(this,"blockFrontends",new Map);k(this,"activeConfigs");k(this,"refreshLoopResult");k(this,"abortController",new AbortController);k(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=Mn(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.overviewLight=zn(r.entry()).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=qn(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await _e(this.env.projectHelper,this.env.pl,this.rid,r=>{r.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await _r.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal);const e=await this.overviewLight.getValue(),t=new Set(e.listOfBlocks);for(const r of this.blockComputables.keys())if(!t.has(r)){const o=this.blockComputables.get(r);o!=null&&o.fullState.resetState(),this.blockComputables.set(r,null)}}catch(e){if(g.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!g.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,o=void 0,n=Z.randomUUID()){const i=await this.env.bpPreparer.prepare(t),c=await this.env.bpPreparer.getBlockConfigContainer(t),a=D.extractConfig(c);return await ie(this.env.projectHelper,this.env.pl,this.rid,o,l=>l.addBlock({id:n,label:e,renderingMode:a.renderingMode},{args:x(a.initialArgs),uiState:x(a.initialUiState),blockPack:i},r)),await this.projectTree.refreshState(),n}async updateBlockPack(e,t,r=!1,o){const n=await this.env.bpPreparer.prepare(t),i=D.extractConfig(await this.env.bpPreparer.getBlockConfigContainer(t));await ie(this.env.projectHelper,this.env.pl,this.rid,o,c=>c.migrateBlockPack(e,n,r?{args:x(i.initialArgs),uiState:x(i.initialUiState)}:void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await ie(this.env.projectHelper,this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await ie(this.env.projectHelper,this.env.pl,this.rid,t,r=>{const o=r.structure;if(o.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const n=o.groups[0];if(n.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${n.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const i={groups:[{id:n.id,label:n.label,blocks:e.map(c=>{const a=n.blocks.find(l=>l.id===c);if(a===void 0)throw new Error(`Can't find block: ${c}`);return a})}]};r.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await _e(this.env.projectHelper,this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await _e(this.env.projectHelper,this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await ie(this.env.projectHelper,this.env.pl,this.rid,r,o=>o.setArgs([{blockId:e,args:x(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await ie(this.env.projectHelper,this.env.pl,this.rid,r,o=>o.setUiState(e,t===void 0?void 0:x(t))),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,o){await ie(this.env.projectHelper,this.env.pl,this.rid,o,n=>{n.setArgs([{blockId:e,args:x(t)}]),n.setUiState(e,x(r))}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await ie(this.env.projectHelper,this.env.pl,this.rid,void 0,r=>{r.setBlockSettings(e,t)}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async r=>{const o=g.ensureResourceIdNotNull((await r.getField(g.field(this.rid,K(e,"blockPack")))).value),n=g.ensureResourceIdNotNull((await r.getField(g.field(o,g.Pl.HolderRefField))).value),i=await r.getResourceData(n,!1),c=D.extractConfig(S.cachedDeserialize(S.notEmpty(i.data)).config);await ie(this.env.projectHelper,r,this.rid,t,a=>{a.setArgs([{blockId:e,args:x(c.initialArgs)}]),a.setUiState(e,x(c.initialUiState))}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===null)throw new Error(`Block ${e} is deleted`);if(t===void 0){const r=Hn(this.projectTree.entry(),e,this.env),n={fullState:V.Computable.make(i=>({argsAndUiState:ys(this.projectTree.entry(),e,i),outputs:r,navigationState:this.navigationStates.getState(e),overview:this.overview}),{postprocessValue:i=>{var u,d,p;const c=(p=(d=(u=i.overview)==null?void 0:u.blocks)==null?void 0:d.find(f=>f.id==e))==null?void 0:p.sdkVersion,l=c&&Yn(c)&&i.outputs!==void 0?Zn(i.outputs):i.outputs;return{...i.argsAndUiState,outputs:l,navigationState:i.navigationState}}}).withPreCalculatedValueTree()};return this.blockComputables.set(e,n),n}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=Kn(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,r),r}return t}async destroy(){this.destroyed=!0,this.abortController.abort(),await this.refreshLoopResult,await this.projectTree.terminate(),this.overview.resetState(),this.blockFrontends.forEach(e=>e.resetState()),this.blockComputables.forEach(e=>{e!==null&&e.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){await _e(e.projectHelper,e.pl,t,o=>{});const r=await Qe.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:Xn},e.logger);if(e.ops.debugOps.dumpInitialTreeState){const o=r.dumpState();o.sort((i,c)=>{var a,l;return(((a=c.data)==null?void 0:a.byteLength)??0)-(((l=i.data)==null?void 0:l.byteLength)??0)});const n=Qe.treeDumpStats(o);await De.writeFile(`${g.resourceIdToString(t)}.json`,yr(o)),await De.writeFile(`${g.resourceIdToString(t)}.stats.json`,yr(n))}return new nt(e,t,r)}}function Xn(s){switch(s.type.name){case"BlockPackCustom":return s.fields.filter(e=>e.name!=="template");case"UserProject":return s.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return s.fields}}function Yn(s){return!Qn(s,"1.26.0")}function Qn(s,e){const t=s.split(".").map(Number),r=e.split(".").map(Number);return t[0]>r[0]||t[0]===r[0]&&t[1]>r[1]||t[0]===r[0]&&t[1]===r[1]&&t[2]>r[2]}function Zn(s){const e={};for(const[t,r]of Object.entries(s)){if(r.ok){e[t]=r;continue}e[t]={ok:!1,errors:r.errors.map(o=>typeof o=="string"?o:o.type=="PlError"&&o.fullMessage!==void 0?o.fullMessage:o.message),moreErrors:r.moreErrors}}return e}const Vt={logger:new S.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:8*1024*1024*1024,nConcurrentDownloads:10},downloadBlobToURLDriverOps:{cacheSoftSizeBytes:100*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}};function xt(s){return{blobDownloadPath:M.join(s,"download"),downloadBlobToURLPath:M.join(s,"downloadToURL"),pframesSpillPath:M.join(s,"pframes")}}const ws={...Vt,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500,initialTreeLoadingTimeout:100*60*60*1e3},debugOps:{dumpInitialTreeState:!1},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function bs(s){return{...xt(s),frontendDownloadPath:M.join(s,"frontend")}}function ei(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Ot={exports:{}};const ti="2.0.0",Ss=256,ri=Number.MAX_SAFE_INTEGER||9007199254740991,si=16,oi=Ss-6,ni=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var it={MAX_LENGTH:Ss,MAX_SAFE_COMPONENT_LENGTH:si,MAX_SAFE_BUILD_LENGTH:oi,MAX_SAFE_INTEGER:ri,RELEASE_TYPES:ni,SEMVER_SPEC_VERSION:ti,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2};const ii=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...s)=>console.error("SEMVER",...s):()=>{};var at=ii;(function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:o}=it,n=at;e=s.exports={};const i=e.re=[],c=e.safeRe=[],a=e.src=[],l=e.safeSrc=[],u=e.t={};let d=0;const p="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",o],[p,r]],P=T=>{for(const[L,U]of f)T=T.split(`${L}*`).join(`${L}{0,${U}}`).split(`${L}+`).join(`${L}{1,${U}}`);return T},v=(T,L,U)=>{const A=P(L),q=d++;n(T,q,L),u[T]=q,a[q]=L,l[q]=A,i[q]=new RegExp(L,U?"g":void 0),c[q]=new RegExp(A,U?"g":void 0)};v("NUMERICIDENTIFIER","0|[1-9]\\d*"),v("NUMERICIDENTIFIERLOOSE","\\d+"),v("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),v("MAINVERSION",`(${a[u.NUMERICIDENTIFIER]})\\.(${a[u.NUMERICIDENTIFIER]})\\.(${a[u.NUMERICIDENTIFIER]})`),v("MAINVERSIONLOOSE",`(${a[u.NUMERICIDENTIFIERLOOSE]})\\.(${a[u.NUMERICIDENTIFIERLOOSE]})\\.(${a[u.NUMERICIDENTIFIERLOOSE]})`),v("PRERELEASEIDENTIFIER",`(?:${a[u.NUMERICIDENTIFIER]}|${a[u.NONNUMERICIDENTIFIER]})`),v("PRERELEASEIDENTIFIERLOOSE",`(?:${a[u.NUMERICIDENTIFIERLOOSE]}|${a[u.NONNUMERICIDENTIFIER]})`),v("PRERELEASE",`(?:-(${a[u.PRERELEASEIDENTIFIER]}(?:\\.${a[u.PRERELEASEIDENTIFIER]})*))`),v("PRERELEASELOOSE",`(?:-?(${a[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${a[u.PRERELEASEIDENTIFIERLOOSE]})*))`),v("BUILDIDENTIFIER",`${p}+`),v("BUILD",`(?:\\+(${a[u.BUILDIDENTIFIER]}(?:\\.${a[u.BUILDIDENTIFIER]})*))`),v("FULLPLAIN",`v?${a[u.MAINVERSION]}${a[u.PRERELEASE]}?${a[u.BUILD]}?`),v("FULL",`^${a[u.FULLPLAIN]}$`),v("LOOSEPLAIN",`[v=\\s]*${a[u.MAINVERSIONLOOSE]}${a[u.PRERELEASELOOSE]}?${a[u.BUILD]}?`),v("LOOSE",`^${a[u.LOOSEPLAIN]}$`),v("GTLT","((?:<|>)?=?)"),v("XRANGEIDENTIFIERLOOSE",`${a[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),v("XRANGEIDENTIFIER",`${a[u.NUMERICIDENTIFIER]}|x|X|\\*`),v("XRANGEPLAIN",`[v=\\s]*(${a[u.XRANGEIDENTIFIER]})(?:\\.(${a[u.XRANGEIDENTIFIER]})(?:\\.(${a[u.XRANGEIDENTIFIER]})(?:${a[u.PRERELEASE]})?${a[u.BUILD]}?)?)?`),v("XRANGEPLAINLOOSE",`[v=\\s]*(${a[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[u.XRANGEIDENTIFIERLOOSE]})(?:${a[u.PRERELEASELOOSE]})?${a[u.BUILD]}?)?)?`),v("XRANGE",`^${a[u.GTLT]}\\s*${a[u.XRANGEPLAIN]}$`),v("XRANGELOOSE",`^${a[u.GTLT]}\\s*${a[u.XRANGEPLAINLOOSE]}$`),v("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),v("COERCE",`${a[u.COERCEPLAIN]}(?:$|[^\\d])`),v("COERCEFULL",a[u.COERCEPLAIN]+`(?:${a[u.PRERELEASE]})?(?:${a[u.BUILD]})?(?:$|[^\\d])`),v("COERCERTL",a[u.COERCE],!0),v("COERCERTLFULL",a[u.COERCEFULL],!0),v("LONETILDE","(?:~>?)"),v("TILDETRIM",`(\\s*)${a[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",v("TILDE",`^${a[u.LONETILDE]}${a[u.XRANGEPLAIN]}$`),v("TILDELOOSE",`^${a[u.LONETILDE]}${a[u.XRANGEPLAINLOOSE]}$`),v("LONECARET","(?:\\^)"),v("CARETTRIM",`(\\s*)${a[u.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",v("CARET",`^${a[u.LONECARET]}${a[u.XRANGEPLAIN]}$`),v("CARETLOOSE",`^${a[u.LONECARET]}${a[u.XRANGEPLAINLOOSE]}$`),v("COMPARATORLOOSE",`^${a[u.GTLT]}\\s*(${a[u.LOOSEPLAIN]})$|^$`),v("COMPARATOR",`^${a[u.GTLT]}\\s*(${a[u.FULLPLAIN]})$|^$`),v("COMPARATORTRIM",`(\\s*)${a[u.GTLT]}\\s*(${a[u.LOOSEPLAIN]}|${a[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",v("HYPHENRANGE",`^\\s*(${a[u.XRANGEPLAIN]})\\s+-\\s+(${a[u.XRANGEPLAIN]})\\s*$`),v("HYPHENRANGELOOSE",`^\\s*(${a[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${a[u.XRANGEPLAINLOOSE]})\\s*$`),v("STAR","(<|>)?=?\\s*\\*"),v("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),v("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(Ot,Ot.exports);var Ve=Ot.exports;const ai=Object.freeze({loose:!0}),ci=Object.freeze({}),li=s=>s?typeof s!="object"?ai:s:ci;var Ut=li;const wr=/^[0-9]+$/,ks=(s,e)=>{const t=wr.test(s),r=wr.test(e);return t&&r&&(s=+s,e=+e),s===e?0:t&&!r?-1:r&&!t?1:s<e?-1:1},ui=(s,e)=>ks(e,s);var Cs={compareIdentifiers:ks,rcompareIdentifiers:ui};const He=at,{MAX_LENGTH:br,MAX_SAFE_INTEGER:qe}=it,{safeRe:Sr,safeSrc:kr,t:We}=Ve,di=Ut,{compareIdentifiers:ve}=Cs;let pi=class le{constructor(e,t){if(t=di(t),e instanceof le){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>br)throw new TypeError(`version is longer than ${br} characters`);He("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const r=e.trim().match(t.loose?Sr[We.LOOSE]:Sr[We.FULL]);if(!r)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>qe||this.major<0)throw new TypeError("Invalid major version");if(this.minor>qe||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>qe||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){const n=+o;if(n>=0&&n<qe)return n}return o}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(He("SemVer.compare",this.version,this.options,e),!(e instanceof le)){if(typeof e=="string"&&e===this.version)return 0;e=new le(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof le||(e=new le(e,this.options)),ve(this.major,e.major)||ve(this.minor,e.minor)||ve(this.patch,e.patch)}comparePre(e){if(e instanceof le||(e=new le(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{const r=this.prerelease[t],o=e.prerelease[t];if(He("prerelease compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return ve(r,o)}while(++t)}compareBuild(e){e instanceof le||(e=new le(e,this.options));let t=0;do{const r=this.build[t],o=e.build[t];if(He("build compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return ve(r,o)}while(++t)}inc(e,t,r){if(e.startsWith("pre")){if(!t&&r===!1)throw new Error("invalid increment argument: identifier is empty");if(t){const o=new RegExp(`^${this.options.loose?kr[We.PRERELEASELOOSE]:kr[We.PRERELEASE]}$`),n=`-${t}`.match(o);if(!n||n[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,r),this.inc("pre",t,r);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const o=Number(r)?1:0;if(this.prerelease.length===0)this.prerelease=[o];else{let n=this.prerelease.length;for(;--n>=0;)typeof this.prerelease[n]=="number"&&(this.prerelease[n]++,n=-2);if(n===-1){if(t===this.prerelease.join(".")&&r===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(t){let n=[t,o];r===!1&&(n=[t]),ve(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=n):this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};var Y=pi;const Cr=Y,fi=(s,e,t=!1)=>{if(s instanceof Cr)return s;try{return new Cr(s,e)}catch(r){if(!t)return null;throw r}};var be=fi;const gi=be,hi=(s,e)=>{const t=gi(s,e);return t?t.version:null};var mi=hi;const vi=be,yi=(s,e)=>{const t=vi(s.trim().replace(/^[=v]+/,""),e);return t?t.version:null};var wi=yi;const Pr=Y,bi=(s,e,t,r,o)=>{typeof t=="string"&&(o=r,r=t,t=void 0);try{return new Pr(s instanceof Pr?s.version:s,t).inc(e,r,o).version}catch{return null}};var Si=bi;const Rr=be,ki=(s,e)=>{const t=Rr(s,null,!0),r=Rr(e,null,!0),o=t.compare(r);if(o===0)return null;const n=o>0,i=n?t:r,c=n?r:t,a=!!i.prerelease.length;if(!!c.prerelease.length&&!a){if(!c.patch&&!c.minor)return"major";if(c.compareMain(i)===0)return c.minor&&!c.patch?"minor":"patch"}const u=a?"pre":"";return t.major!==r.major?u+"major":t.minor!==r.minor?u+"minor":t.patch!==r.patch?u+"patch":"prerelease"};var Ci=ki;const Pi=Y,Ri=(s,e)=>new Pi(s,e).major;var Ei=Ri;const Oi=Y,$i=(s,e)=>new Oi(s,e).minor;var Ti=$i;const Ii=Y,Fi=(s,e)=>new Ii(s,e).patch;var Di=Fi;const Ai=be,Li=(s,e)=>{const t=Ai(s,e);return t&&t.prerelease.length?t.prerelease:null};var Ni=Li;const Er=Y,Bi=(s,e,t)=>new Er(s,t).compare(new Er(e,t));var ae=Bi;const ji=ae,Vi=(s,e,t)=>ji(e,s,t);var xi=Vi;const Ui=ae,Ji=(s,e)=>Ui(s,e,!0);var Mi=Ji;const Or=Y,Gi=(s,e,t)=>{const r=new Or(s,t),o=new Or(e,t);return r.compare(o)||r.compareBuild(o)};var Jt=Gi;const _i=Jt,Ki=(s,e)=>s.sort((t,r)=>_i(t,r,e));var Hi=Ki;const qi=Jt,Wi=(s,e)=>s.sort((t,r)=>qi(r,t,e));var zi=Wi;const Xi=ae,Yi=(s,e,t)=>Xi(s,e,t)>0;var ct=Yi;const Qi=ae,Zi=(s,e,t)=>Qi(s,e,t)<0;var Mt=Zi;const ea=ae,ta=(s,e,t)=>ea(s,e,t)===0;var Ps=ta;const ra=ae,sa=(s,e,t)=>ra(s,e,t)!==0;var Rs=sa;const oa=ae,na=(s,e,t)=>oa(s,e,t)>=0;var Gt=na;const ia=ae,aa=(s,e,t)=>ia(s,e,t)<=0;var _t=aa;const ca=Ps,la=Rs,ua=ct,da=Gt,pa=Mt,fa=_t,ga=(s,e,t,r)=>{switch(e){case"===":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s===t;case"!==":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s!==t;case"":case"=":case"==":return ca(s,t,r);case"!=":return la(s,t,r);case">":return ua(s,t,r);case">=":return da(s,t,r);case"<":return pa(s,t,r);case"<=":return fa(s,t,r);default:throw new TypeError(`Invalid operator: ${e}`)}};var Es=ga;const ha=Y,ma=be,{safeRe:ze,t:Xe}=Ve,va=(s,e)=>{if(s instanceof ha)return s;if(typeof s=="number"&&(s=String(s)),typeof s!="string")return null;e=e||{};let t=null;if(!e.rtl)t=s.match(e.includePrerelease?ze[Xe.COERCEFULL]:ze[Xe.COERCE]);else{const a=e.includePrerelease?ze[Xe.COERCERTLFULL]:ze[Xe.COERCERTL];let l;for(;(l=a.exec(s))&&(!t||t.index+t[0].length!==s.length);)(!t||l.index+l[0].length!==t.index+t[0].length)&&(t=l),a.lastIndex=l.index+l[1].length+l[2].length;a.lastIndex=-1}if(t===null)return null;const r=t[2],o=t[3]||"0",n=t[4]||"0",i=e.includePrerelease&&t[5]?`-${t[5]}`:"",c=e.includePrerelease&&t[6]?`+${t[6]}`:"";return ma(`${r}.${o}.${n}${i}${c}`,e)};var ya=va;class wa{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){const o=this.map.keys().next().value;this.delete(o)}this.map.set(e,t)}return this}}var ba=wa,gt,$r;function ce(){if($r)return gt;$r=1;const s=/\s+/g;class e{constructor(m,R){if(R=o(R),m instanceof e)return m.loose===!!R.loose&&m.includePrerelease===!!R.includePrerelease?m:new e(m.raw,R);if(m instanceof n)return this.raw=m.value,this.set=[[m]],this.formatted=void 0,this;if(this.options=R,this.loose=!!R.loose,this.includePrerelease=!!R.includePrerelease,this.raw=m.trim().replace(s," "),this.set=this.raw.split("||").map(h=>this.parseRange(h.trim())).filter(h=>h.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const h=this.set[0];if(this.set=this.set.filter(b=>!v(b[0])),this.set.length===0)this.set=[h];else if(this.set.length>1){for(const b of this.set)if(b.length===1&&T(b[0])){this.set=[b];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let m=0;m<this.set.length;m++){m>0&&(this.formatted+="||");const R=this.set[m];for(let h=0;h<R.length;h++)h>0&&(this.formatted+=" "),this.formatted+=R[h].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(m){const h=((this.options.includePrerelease&&f)|(this.options.loose&&P))+":"+m,b=r.get(h);if(b)return b;const y=this.options.loose,C=y?a[l.HYPHENRANGELOOSE]:a[l.HYPHENRANGE];m=m.replace(C,_(this.options.includePrerelease)),i("hyphen replace",m),m=m.replace(a[l.COMPARATORTRIM],u),i("comparator trim",m),m=m.replace(a[l.TILDETRIM],d),i("tilde trim",m),m=m.replace(a[l.CARETTRIM],p),i("caret trim",m);let $=m.split(" ").map(B=>U(B,this.options)).join(" ").split(/\s+/).map(B=>ne(B,this.options));y&&($=$.filter(B=>(i("loose invalid filter",B,this.options),!!B.match(a[l.COMPARATORLOOSE])))),i("range list",$);const E=new Map,N=$.map(B=>new n(B,this.options));for(const B of N){if(v(B))return[B];E.set(B.value,B)}E.size>1&&E.has("")&&E.delete("");const G=[...E.values()];return r.set(h,G),G}intersects(m,R){if(!(m instanceof e))throw new TypeError("a Range is required");return this.set.some(h=>L(h,R)&&m.set.some(b=>L(b,R)&&h.every(y=>b.every(C=>y.intersects(C,R)))))}test(m){if(!m)return!1;if(typeof m=="string")try{m=new c(m,this.options)}catch{return!1}for(let R=0;R<this.set.length;R++)if(W(this.set[R],m,this.options))return!0;return!1}}gt=e;const t=ba,r=new t,o=Ut,n=lt(),i=at,c=Y,{safeRe:a,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:p}=Ve,{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:P}=it,v=w=>w.value==="<0.0.0-0",T=w=>w.value==="",L=(w,m)=>{let R=!0;const h=w.slice();let b=h.pop();for(;R&&h.length;)R=h.every(y=>b.intersects(y,m)),b=h.pop();return R},U=(w,m)=>(i("comp",w,m),w=j(w,m),i("caret",w),w=q(w,m),i("tildes",w),w=se(w,m),i("xrange",w),w=oe(w,m),i("stars",w),w),A=w=>!w||w.toLowerCase()==="x"||w==="*",q=(w,m)=>w.trim().split(/\s+/).map(R=>me(R,m)).join(" "),me=(w,m)=>{const R=m.loose?a[l.TILDELOOSE]:a[l.TILDE];return w.replace(R,(h,b,y,C,$)=>{i("tilde",w,h,b,y,C,$);let E;return A(b)?E="":A(y)?E=`>=${b}.0.0 <${+b+1}.0.0-0`:A(C)?E=`>=${b}.${y}.0 <${b}.${+y+1}.0-0`:$?(i("replaceTilde pr",$),E=`>=${b}.${y}.${C}-${$} <${b}.${+y+1}.0-0`):E=`>=${b}.${y}.${C} <${b}.${+y+1}.0-0`,i("tilde return",E),E})},j=(w,m)=>w.trim().split(/\s+/).map(R=>Q(R,m)).join(" "),Q=(w,m)=>{i("caret",w,m);const R=m.loose?a[l.CARETLOOSE]:a[l.CARET],h=m.includePrerelease?"-0":"";return w.replace(R,(b,y,C,$,E)=>{i("caret",w,b,y,C,$,E);let N;return A(y)?N="":A(C)?N=`>=${y}.0.0${h} <${+y+1}.0.0-0`:A($)?y==="0"?N=`>=${y}.${C}.0${h} <${y}.${+C+1}.0-0`:N=`>=${y}.${C}.0${h} <${+y+1}.0.0-0`:E?(i("replaceCaret pr",E),y==="0"?C==="0"?N=`>=${y}.${C}.${$}-${E} <${y}.${C}.${+$+1}-0`:N=`>=${y}.${C}.${$}-${E} <${y}.${+C+1}.0-0`:N=`>=${y}.${C}.${$}-${E} <${+y+1}.0.0-0`):(i("no pr"),y==="0"?C==="0"?N=`>=${y}.${C}.${$}${h} <${y}.${C}.${+$+1}-0`:N=`>=${y}.${C}.${$}${h} <${y}.${+C+1}.0-0`:N=`>=${y}.${C}.${$} <${+y+1}.0.0-0`),i("caret return",N),N})},se=(w,m)=>(i("replaceXRanges",w,m),w.split(/\s+/).map(R=>H(R,m)).join(" ")),H=(w,m)=>{w=w.trim();const R=m.loose?a[l.XRANGELOOSE]:a[l.XRANGE];return w.replace(R,(h,b,y,C,$,E)=>{i("xRange",w,h,b,y,C,$,E);const N=A(y),G=N||A(C),B=G||A($),ue=B;return b==="="&&ue&&(b=""),E=m.includePrerelease?"-0":"",N?b===">"||b==="<"?h="<0.0.0-0":h="*":b&&ue?(G&&(C=0),$=0,b===">"?(b=">=",G?(y=+y+1,C=0,$=0):(C=+C+1,$=0)):b==="<="&&(b="<",G?y=+y+1:C=+C+1),b==="<"&&(E="-0"),h=`${b+y}.${C}.${$}${E}`):G?h=`>=${y}.0.0${E} <${+y+1}.0.0-0`:B&&(h=`>=${y}.${C}.0${E} <${y}.${+C+1}.0-0`),i("xRange return",h),h})},oe=(w,m)=>(i("replaceStars",w,m),w.trim().replace(a[l.STAR],"")),ne=(w,m)=>(i("replaceGTE0",w,m),w.trim().replace(a[m.includePrerelease?l.GTE0PRE:l.GTE0],"")),_=w=>(m,R,h,b,y,C,$,E,N,G,B,ue)=>(A(h)?R="":A(b)?R=`>=${h}.0.0${w?"-0":""}`:A(y)?R=`>=${h}.${b}.0${w?"-0":""}`:C?R=`>=${R}`:R=`>=${R}${w?"-0":""}`,A(N)?E="":A(G)?E=`<${+N+1}.0.0-0`:A(B)?E=`<${N}.${+G+1}.0-0`:ue?E=`<=${N}.${G}.${B}-${ue}`:w?E=`<${N}.${G}.${+B+1}-0`:E=`<=${E}`,`${R} ${E}`.trim()),W=(w,m,R)=>{for(let h=0;h<w.length;h++)if(!w[h].test(m))return!1;if(m.prerelease.length&&!R.includePrerelease){for(let h=0;h<w.length;h++)if(i(w[h].semver),w[h].semver!==n.ANY&&w[h].semver.prerelease.length>0){const b=w[h].semver;if(b.major===m.major&&b.minor===m.minor&&b.patch===m.patch)return!0}return!1}return!0};return gt}var ht,Tr;function lt(){if(Tr)return ht;Tr=1;const s=Symbol("SemVer ANY");class e{static get ANY(){return s}constructor(u,d){if(d=t(d),u instanceof e){if(u.loose===!!d.loose)return u;u=u.value}u=u.trim().split(/\s+/).join(" "),i("comparator",u,d),this.options=d,this.loose=!!d.loose,this.parse(u),this.semver===s?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(u){const d=this.options.loose?r[o.COMPARATORLOOSE]:r[o.COMPARATOR],p=u.match(d);if(!p)throw new TypeError(`Invalid comparator: ${u}`);this.operator=p[1]!==void 0?p[1]:"",this.operator==="="&&(this.operator=""),p[2]?this.semver=new c(p[2],this.options.loose):this.semver=s}toString(){return this.value}test(u){if(i("Comparator.test",u,this.options.loose),this.semver===s||u===s)return!0;if(typeof u=="string")try{u=new c(u,this.options)}catch{return!1}return n(u,this.operator,this.semver,this.options)}intersects(u,d){if(!(u instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new a(u.value,d).test(this.value):u.operator===""?u.value===""?!0:new a(this.value,d).test(u.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||u.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||u.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&u.operator.startsWith(">")||this.operator.startsWith("<")&&u.operator.startsWith("<")||this.semver.version===u.semver.version&&this.operator.includes("=")&&u.operator.includes("=")||n(this.semver,"<",u.semver,d)&&this.operator.startsWith(">")&&u.operator.startsWith("<")||n(this.semver,">",u.semver,d)&&this.operator.startsWith("<")&&u.operator.startsWith(">")))}}ht=e;const t=Ut,{safeRe:r,t:o}=Ve,n=Es,i=at,c=Y,a=ce();return ht}const Sa=ce(),ka=(s,e,t)=>{try{e=new Sa(e,t)}catch{return!1}return e.test(s)};var ut=ka;const Ca=ce(),Pa=(s,e)=>new Ca(s,e).set.map(t=>t.map(r=>r.value).join(" ").trim().split(" "));var Ra=Pa;const Ea=Y,Oa=ce(),$a=(s,e,t)=>{let r=null,o=null,n=null;try{n=new Oa(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===-1)&&(r=i,o=new Ea(r,t))}),r};var Ta=$a;const Ia=Y,Fa=ce(),Da=(s,e,t)=>{let r=null,o=null,n=null;try{n=new Fa(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===1)&&(r=i,o=new Ia(r,t))}),r};var Aa=Da;const mt=Y,La=ce(),Ir=ct,Na=(s,e)=>{s=new La(s,e);let t=new mt("0.0.0");if(s.test(t)||(t=new mt("0.0.0-0"),s.test(t)))return t;t=null;for(let r=0;r<s.set.length;++r){const o=s.set[r];let n=null;o.forEach(i=>{const c=new mt(i.semver.version);switch(i.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!n||Ir(c,n))&&(n=c);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),n&&(!t||Ir(t,n))&&(t=n)}return t&&s.test(t)?t:null};var Ba=Na;const ja=ce(),Va=(s,e)=>{try{return new ja(s,e).range||"*"}catch{return null}};var xa=Va;const Ua=Y,Os=lt(),{ANY:Ja}=Os,Ma=ce(),Ga=ut,Fr=ct,Dr=Mt,_a=_t,Ka=Gt,Ha=(s,e,t,r)=>{s=new Ua(s,r),e=new Ma(e,r);let o,n,i,c,a;switch(t){case">":o=Fr,n=_a,i=Dr,c=">",a=">=";break;case"<":o=Dr,n=Ka,i=Fr,c="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Ga(s,e,r))return!1;for(let l=0;l<e.set.length;++l){const u=e.set[l];let d=null,p=null;if(u.forEach(f=>{f.semver===Ja&&(f=new Os(">=0.0.0")),d=d||f,p=p||f,o(f.semver,d.semver,r)?d=f:i(f.semver,p.semver,r)&&(p=f)}),d.operator===c||d.operator===a||(!p.operator||p.operator===c)&&n(s,p.semver))return!1;if(p.operator===a&&i(s,p.semver))return!1}return!0};var Kt=Ha;const qa=Kt,Wa=(s,e,t)=>qa(s,e,">",t);var za=Wa;const Xa=Kt,Ya=(s,e,t)=>Xa(s,e,"<",t);var Qa=Ya;const Ar=ce(),Za=(s,e,t)=>(s=new Ar(s,t),e=new Ar(e,t),s.intersects(e,t));var ec=Za;const tc=ut,rc=ae;var sc=(s,e,t)=>{const r=[];let o=null,n=null;const i=s.sort((u,d)=>rc(u,d,t));for(const u of i)tc(u,e,t)?(n=u,o||(o=u)):(n&&r.push([o,n]),n=null,o=null);o&&r.push([o,null]);const c=[];for(const[u,d]of r)u===d?c.push(u):!d&&u===i[0]?c.push("*"):d?u===i[0]?c.push(`<=${d}`):c.push(`${u} - ${d}`):c.push(`>=${u}`);const a=c.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return a.length<l.length?a:e};const Lr=ce(),Ht=lt(),{ANY:vt}=Ht,Re=ut,qt=ae,oc=(s,e,t={})=>{if(s===e)return!0;s=new Lr(s,t),e=new Lr(e,t);let r=!1;e:for(const o of s.set){for(const n of e.set){const i=ic(o,n,t);if(r=r||i!==null,i)continue e}if(r)return!1}return!0},nc=[new Ht(">=0.0.0-0")],Nr=[new Ht(">=0.0.0")],ic=(s,e,t)=>{if(s===e)return!0;if(s.length===1&&s[0].semver===vt){if(e.length===1&&e[0].semver===vt)return!0;t.includePrerelease?s=nc:s=Nr}if(e.length===1&&e[0].semver===vt){if(t.includePrerelease)return!0;e=Nr}const r=new Set;let o,n;for(const f of s)f.operator===">"||f.operator===">="?o=Br(o,f,t):f.operator==="<"||f.operator==="<="?n=jr(n,f,t):r.add(f.semver);if(r.size>1)return null;let i;if(o&&n){if(i=qt(o.semver,n.semver,t),i>0)return null;if(i===0&&(o.operator!==">="||n.operator!=="<="))return null}for(const f of r){if(o&&!Re(f,String(o),t)||n&&!Re(f,String(n),t))return null;for(const P of e)if(!Re(f,String(P),t))return!1;return!0}let c,a,l,u,d=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1,p=o&&!t.includePrerelease&&o.semver.prerelease.length?o.semver:!1;d&&d.prerelease.length===1&&n.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(const f of e){if(u=u||f.operator===">"||f.operator===">=",l=l||f.operator==="<"||f.operator==="<=",o){if(p&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===p.major&&f.semver.minor===p.minor&&f.semver.patch===p.patch&&(p=!1),f.operator===">"||f.operator===">="){if(c=Br(o,f,t),c===f&&c!==o)return!1}else if(o.operator===">="&&!Re(o.semver,String(f),t))return!1}if(n){if(d&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===d.major&&f.semver.minor===d.minor&&f.semver.patch===d.patch&&(d=!1),f.operator==="<"||f.operator==="<="){if(a=jr(n,f,t),a===f&&a!==n)return!1}else if(n.operator==="<="&&!Re(n.semver,String(f),t))return!1}if(!f.operator&&(n||o)&&i!==0)return!1}return!(o&&l&&!n&&i!==0||n&&u&&!o&&i!==0||p||d)},Br=(s,e,t)=>{if(!s)return e;const r=qt(s.semver,e.semver,t);return r>0?s:r<0||e.operator===">"&&s.operator===">="?e:s},jr=(s,e,t)=>{if(!s)return e;const r=qt(s.semver,e.semver,t);return r<0?s:r>0||e.operator==="<"&&s.operator==="<="?e:s};var ac=oc;const yt=Ve,Vr=it,cc=Y,xr=Cs,lc=be,uc=mi,dc=wi,pc=Si,fc=Ci,gc=Ei,hc=Ti,mc=Di,vc=Ni,yc=ae,wc=xi,bc=Mi,Sc=Jt,kc=Hi,Cc=zi,Pc=ct,Rc=Mt,Ec=Ps,Oc=Rs,$c=Gt,Tc=_t,Ic=Es,Fc=ya,Dc=lt(),Ac=ce(),Lc=ut,Nc=Ra,Bc=Ta,jc=Aa,Vc=Ba,xc=xa,Uc=Kt,Jc=za,Mc=Qa,Gc=ec,_c=sc,Kc=ac;var Hc={parse:lc,valid:uc,clean:dc,inc:pc,diff:fc,major:gc,minor:hc,patch:mc,prerelease:vc,compare:yc,rcompare:wc,compareLoose:bc,compareBuild:Sc,sort:kc,rsort:Cc,gt:Pc,lt:Rc,eq:Ec,neq:Oc,gte:$c,lte:Tc,cmp:Ic,coerce:Fc,Comparator:Dc,Range:Ac,satisfies:Lc,toComparators:Nc,maxSatisfying:Bc,minSatisfying:jc,minVersion:Vc,validRange:xc,outside:Uc,gtr:Jc,ltr:Mc,intersects:Gc,simplifyRange:_c,subset:Kc,SemVer:cc,re:yt.re,src:yt.src,tokens:yt.t,SEMVER_SPEC_VERSION:Vr.SEMVER_SPEC_VERSION,RELEASE_TYPES:Vr.RELEASE_TYPES,compareIdentifiers:xr.compareIdentifiers,rcompareIdentifiers:xr.rcompareIdentifiers};const qc=ei(Hc),Wc={minDelay:1500},zc="__no_updates__";class Xc extends V.PollComputablePool{constructor(t,r,o={}){super({...o,...Wc},r);k(this,"http");k(this,"preferredUpdateChannel");this.registryProvider=t,this.http=o.http,this.preferredUpdateChannel=o.preferredUpdateChannel}getKey(t){switch(t.currentSpec.type){case"dev-v1":return`dev_1_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"dev-v2":return`dev_2_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"from-registry-v2":return`from_registry_v2_${x(t)}`;default:return zc}}async readValue(t){var r,o;try{const n=t.currentSpec;switch(n.type){case"dev-v1":try{const i=await Ft(n.folder);return i===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:i},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"dev-v2":try{const i=await X.tryLoadPackDescription(n.folder,this.logger);if(i===void 0)return{suggestions:[]};const c=await rt(i);return c===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:c},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:i,skipVersion:c}=t.settings;if(i==="patch")return{suggestions:[]};const a=this.registryProvider.getRegistry(n.registryUrl);let l=this.preferredUpdateChannel;if(l===void 0)if(n.channel===void 0)if(await a.getLatestOverview(n.id,z.StableChannel))l=z.StableChannel;else{if(await a.getLatestOverview(n.id,z.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${z.blockPackIdToString(n.id)}`),{suggestions:[]};l=z.AnyChannel}else l=n.channel;const u=await a.getUpdateSuggestions(n.id,l);if(u===void 0||u.length===0)return{suggestions:[]};u.reverse();let d;switch(i){case void 0:d=u[0].update;break;case"major":d=(r=u.find(P=>P.type!=="major"))==null?void 0:r.update;break;case"minor":d=(o=u.find(P=>P.type==="patch"))==null?void 0:o.update;break}const p=u.map(({type:P,update:v})=>({type:P,update:{...n,id:{...n.id,version:v}}}));if(d===void 0)return{suggestions:p};if(c!==void 0&&qc.lte(d,c))return{suggestions:p};const f={...n,id:{...n.id,version:d}};return(async()=>{try{await a.getComponents(f.id)}catch(P){this.logger.warn(P)}})(),{suggestions:p,mainSuggestion:f}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(n){return this.logger.warn(n),{suggestions:[]}}}resultsEqual(t,r){return x(t)===x(r)}}class Ur{constructor(){k(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");t.refCount===0&&(this.resources.delete(e),(o=>o!=null&&typeof o[Symbol.dispose]=="function")(t.resource)&&t.resource[Symbol.dispose]())}acquire(e){const t=this.calculateParamsKey(e);let r=this.resources.get(t);r===void 0&&(r={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,r)),r.refCount++;let o=!1;return{resource:r.resource,key:t,unref:()=>{o||(r.refCount--,o=!0,this.check(t))}}}getByKey(e){if(!this.resources.has(e))throw new Error(`resource not found, key = ${e}`);return this.resources.get(e).resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}let Ee;function fe(){return Ee||(Ee={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0,dumpInitialTreeState:process.env.MI_DUMP_INITIAL_TREE_STATE!==void 0},process.env.MI_LOG_TREE_STAT&&(Ee.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),Ee)}function Ie(s){return String(s.id)}const Yc=["Int","Long","Float","Double","String","Bytes"];function wt(s){const e=[],t=[];for(const r of s)r.type==="bySingleColumn"?(e.push(r),t.push({...r,type:"bySingleColumnV2"})):t.push(r);if(e.length>0){const r=JSON.stringify(e);console.warn(`type overriten from 'bySingleColumn' to 'bySingleColumnV2' for filters: ${r}`)}return t}const Oe=(s,e)=>typeof e=="bigint"?e.toString():e;class Qc{constructor(e,t,r,o){k(this,"pFrame");k(this,"abortController",new AbortController);k(this,"blobIdToResource",new Map);k(this,"blobHandleComputables",new Map);k(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue()});k(this,"resolveBlob",async e=>{const t=this.getOrCreateComputableForBlob(e);return this.blobDriver.getLocalPath((await t.awaitStableValue()).handle)});k(this,"resolveBlobContent",async e=>{try{const t=this.getOrCreateComputableForBlob(e),r=this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);return await qr.readFile(r)}catch(t){const r=JSON.stringify(t);throw console.log(`resolveBlobContent catched error: ${r}`),t}});this.blobDriver=e,this.logger=t,this.spillPath=r;const n=(c,a)=>this.logger[c](a);for(const c of o)for(const a of Mo(c.data))this.blobIdToResource.set(Ie(a),a);const i=[...new Map(o.map(c=>({...c,data:Go(c.data,Ie)})).map(c=>[x(c),c])).values()];try{const c=new Kr.PFrame(this.spillPath,n);c.setDataSource(this);for(const a of i)c.addColumnSpec(a.id,a.spec),c.setColumnData(a.id,a.data);this.pFrame=c}catch(c){throw new Error(`Rust PFrame creation failed, columns: ${JSON.stringify(i)}, error: ${c}`)}}getOrCreateComputableForBlob(e){let t=this.blobHandleComputables.get(e);if(t!==void 0)return t;const r=this.blobIdToResource.get(e);if(r===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(r).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}get disposeSignal(){return this.abortController.signal}[Symbol.dispose](){this.abortController.abort();for(const e of this.blobHandleComputables.values())e.resetState();this.pFrame.dispose()}}class Zc{constructor(e,t){this.table=e,this.abortController=t}get disposeSignal(){return this.abortController.signal}[Symbol.dispose](){this.abortController.abort(),this.table.then(e=>e.dispose())}}class Wt{constructor(e,t,r){k(this,"pFrames");k(this,"pTables");k(this,"concurrencyLimiter");k(this,"getDataLimiter");this.blobDriver=e,this.logger=t,this.spillPath=r;const o=new S.ConcurrencyLimitingExecutor(1);this.concurrencyLimiter=o,this.getDataLimiter=new S.ConcurrencyLimitingExecutor(1),this.pFrames=new class extends Ur{constructor(n,i,c){super(),this.blobDriver=n,this.logger=i,this.spillPath=c}createNewResource(n){return fe().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(n)}): ${JSON.stringify(n,Oe)}`),new Qc(this.blobDriver,this.logger,this.spillPath,n)}calculateParamsKey(n){return tl(n)}}(this.blobDriver,this.logger,this.spillPath),this.pTables=new class extends Ur{constructor(n){super(),this.pFrames=n}createNewResource(n){const i=n.pFrameHandle;fe().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(n)}): ${JSON.stringify(n,Oe)}`);const c=this.pFrames.getByKey(i),a=new AbortController,l=AbortSignal.any([n.signal,a.signal,c.disposeSignal].filter(d=>!!d)),u=o.run(async()=>{const d=await c.pFrame.createTable({src:Fe(n.def.src),filters:wt(n.def.filters)},l);let p=d;if(n.def.sorting.length>0)try{p=await d.sort(n.def.sorting,l)}finally{d.dispose()}return p});return new Zc(u,a)}calculateParamsKey(n){return el(n)}}(this.pFrames)}async pprofDump(){return await Kr.PFrame.pprofDump()}static async init(e,t,r){const o=Ms.resolve(r);return await S.emptyDir(o),new Wt(e,t,o)}createPFrame(e,t){const r=e.filter(n=>Yc.find(i=>i===n.spec.valueType)).map(n=>D.mapPObjectData(n,i=>Qe.isPlTreeNodeAccessor(i)?zo(i):D.isDataInfo(i)?D.mapDataInfo(i,c=>c.resourceInfo):Xo(n.spec,i))),o=this.pFrames.acquire(r);return t.addOnDestroy(o.unref),o.key}createPTable(e,t,r){const o=this.createPFrame(D.extractAllColumns(e.src),t),n=D.mapPTableDef(e,c=>c.id),i=this.pTables.acquire({def:n,pFrameHandle:o,signal:r});return fe().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${o}; pTableHandle = ${JSON.stringify(i)}): ${JSON.stringify(D.mapPTableDef(e,c=>c.spec),Oe)}`),t.addOnDestroy(i.unref),i.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:[...new Map(t.compatibleWith.map(n=>[x(n),n])).values()],qualifications:[]}]:[]};return{hits:(await this.pFrames.getByKey(e).pFrame.findColumns(r)).hits.filter(n=>n.mappingVariants.length===0||n.mappingVariants.some(i=>i.qualifications.forHit.length===0&&i.qualifications.forQueries.every(c=>c.length===0))).map(n=>n.hit)}}async getColumnSpec(e,t){return await this.pFrames.getByKey(e).pFrame.getColumnSpec(t)}async listColumns(e){return await this.pFrames.getByKey(e).pFrame.listColumns()}async calculateTableData(e,t,r,o){return fe().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,Oe)}`),await this.concurrencyLimiter.run(async()=>{const n=this.pFrames.getByKey(e),i=AbortSignal.any([o,n.disposeSignal].filter(l=>!!l)),c=await n.pFrame.createTable({src:Fe(t.src),filters:wt(t.filters)},i);let a=c;if(t.sorting.length>0)try{a=await c.sort(t.sorting,i)}finally{c.dispose()}try{const l=a.getSpec(),u=await a.getData([...l.keys()],r,i);return l.map((d,p)=>({spec:d,data:u[p]}))}finally{a.dispose()}})}async getUniqueValues(e,t,r){return fe().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,Oe)}`),await this.concurrencyLimiter.run(async()=>{const o=this.pFrames.getByKey(e),n=AbortSignal.any([r,o.disposeSignal].filter(i=>!!i));return await o.pFrame.getUniqueValues({...t,filters:wt(t.filters)},n)})}async getShape(e){return(await this.pTables.getByKey(e).table).getShape()}async getSpec(e){return(await this.pTables.getByKey(e).table).getSpec()}async getData(e,t,r,o){return await this.getDataLimiter.run(async()=>{const n=this.pTables.getByKey(e),i=await n.table,c=AbortSignal.any([o,n.disposeSignal].filter(a=>!!a));return await i.getData(t,r,c)})}}function Fe(s){switch(s.type){case"column":return{type:"column",columnId:s.column};case"slicedColumn":return{type:"slicedColumn",columnId:s.column,newId:s.newId,axisFilters:s.axisFilters};case"inlineColumn":return{type:"inlineColumn",newId:s.column.id,spec:s.column.spec,dataInfo:{type:"Json",keyLength:s.column.spec.axesSpec.length,data:s.column.data.reduce((e,t)=>(e[JSON.stringify(t.key)]=t.val,e),{})}};case"inner":case"full":return{type:s.type,entries:s.entries.map(e=>Fe(e))};case"outer":return{type:"outer",primary:Fe(s.primary),secondary:s.secondary.map(e=>Fe(e))};default:S.assertNever(s)}}function el(s){const e=Z.createHash("sha256");return e.update(x(s)),e.digest().toString("hex")}function tl(s){const e=[...s].map(r=>D.mapPObjectData(r,o=>{let n;const i=o.type;switch(i){case"Json":n={type:o.type,keyLength:o.keyLength,payload:Object.entries(o.data).map(([c,a])=>({key:c,value:a}))};break;case"JsonPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([c,a])=>({key:c,value:Ie(a)}))};break;case"BinaryPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([c,a])=>({key:c,value:[Ie(a.index),Ie(a.values)]}))};break;default:throw Error(`unsupported resource type: ${JSON.stringify(i)}`)}return n.payload.sort((c,a)=>c.key.localeCompare(a.key)),n}));e.sort((r,o)=>r.id.localeCompare(o.id));const t=Z.createHash("sha256");return t.update(x(e)),t.digest().toString("hex")}async function $s(s,e,t){const r={...Vt,...xt(e),...t},o=new S.HmacSha256Signer(r.localSecret),n=J.createDownloadClient(r.logger,s,r.localProjections),i=J.createLogsClient(s,r.logger),c=J.createUploadBlobClient(s,r.logger),a=J.createUploadProgressClient(s,r.logger),l=await J.DownloadDriver.init(r.logger,n,i,r.blobDownloadPath,o,r.blobDriverOps),u=new J.DownloadBlobToURLDriver(r.logger,o,n,r.downloadBlobToURLPath,r.downloadBlobToURLDriverOps),d=new J.UploadDriver(r.logger,o,c,a,r.uploadDriverOps),p=new J.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),f=new J.LogsDriver(r.logger,p,l),P=await J.LsDriver.init(r.logger,s,o,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),v=await Wt.init(l,r.logger,r.pframesSpillPath);return{blobDriver:l,blobToURLDriver:u,logDriver:f,lsDriver:P,signer:o,uploadDriver:d,pFrameDriver:v}}class rl{constructor(e){k(this,"enrichmentTargetsCache",new Mr.LRUCache({max:256,memoMethod:(e,t,{context:r})=>({value:this.calculateEnrichmentTargets(r)})}));this.quickJs=e}calculateEnrichmentTargets(e){const t=e.blockConfig();if(t.enrichmentTargets===void 0)return;const r=e.args();return xn(this.quickJs,t.enrichmentTargets,t.code,r)}getEnrichmentTargets(e,t,r){const o={blockConfig:e,args:t};if(r===void 0)return this.calculateEnrichmentTargets(o);const n=`${r.argsRid}:${r.blockPackRid}`;return this.enrichmentTargetsCache.memo(n,{context:o}).value}}class zt{constructor(e,t,r,o,n,i,c,a){k(this,"pl");k(this,"projectList");k(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=o,this.openedProjectsList=n,this.projectListTree=i,this.blockRegistryProvider=c,this.projectList=a,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=Z.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async o=>{const n=await Jo(o,e);return o.createField(g.field(this.projectListResourceId,t),"Dynamic",n),await o.commit(),await g.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await ie(this.env.projectHelper,this.pl,e,r,o=>{o.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(g.field(this.projectListResourceId,e)),await t.commit()}),await this.projectListTree.refreshState()}async projectIdToResourceId(e){return await this.pl.withReadTx("Project id to resource id",async t=>{const r=(await t.getField(g.field(this.projectListResourceId,e))).value;if(g.isNullResourceId(r))throw new Error("Unexpected project list structure.");return r})}async ensureProjectRid(e){return typeof e=="string"?await this.projectIdToResourceId(e):e}async openProject(e){const t=await this.ensureProjectRid(e);if(this.openedProjectsByRid.has(t))throw new Error(`Project ${t} already opened`);this.openedProjectsByRid.set(t,await nt.init(this.env,t)),this.openedProjectsList.setValue([...this.openedProjectsByRid.keys()])}async closeProject(e){const t=this.openedProjectsByRid.get(e);if(t===void 0)throw new Error(`Project ${e} not found among opened projects`);this.openedProjectsByRid.delete(e),await t.destroy(),this.openedProjectsList.setValue([...this.openedProjectsByRid.keys()])}getOpenedProject(e){const t=this.openedProjectsByRid.get(e);if(t===void 0)throw new Error(`Project ${e} not found among opened projects`);return t}async close(){await Promise.all([...this.openedProjectsByRid.values()].map(e=>e.destroy())),await this.projectListTree.terminate(),await this.env.retryHttpDispatcher.destroy(),await this.pl.close()}async closeAndAwaitTermination(){await this.close()}static generateLocalSecret(){return S.HmacSha256Signer.generateSecret()}get blockEventDispatcher(){return this.env.blockEventDispatcher}static async init(e,t,r){const o={...ws,...bs(t),...r};o.defaultTreeOptions.logStat=fe().logTreeStats,o.debugOps.dumpInitialTreeState=fe().dumpInitialTreeState;const n=await e.withWriteTx("MLInitialization",async T=>{const L=g.field(T.clientRoot,po);T.createField(L,"Dynamic");const U=await T.getField(L);if(g.isNullResourceId(U.value)){const A=T.createEphemeral(Qr);return T.lock(A),T.setField(L,A),await T.commit(),await A.globalId}else return U.value}),i=o.logger,c=await $s(e,t,o),a=new tt.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),l=new zr(a),u=new Lo(l,c.signer,a),d=new J.DownloadUrlDriver(i,e.httpDispatcher,o.frontendDownloadPath),p=await ge.getQuickJS(),f={pl:e,blockEventDispatcher:new S.BlockEventDispatcher,signer:c.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:a,ops:o,bpPreparer:u,frontendDownloadDriver:d,driverKit:c,blockUpdateWatcher:new Xc(l,i,{minDelay:o.devBlockUpdateRecheckInterval,http:a,preferredUpdateChannel:o.preferredUpdateChannel}),quickJs:p,projectHelper:new rl(p)},P=new V.WatchableValue([]),v=await go(e,n,P,f);return new zt(f,c,c.signer,n,P,v.tree,l,v.computable)}}async function sl(s,e){return await Se(s.pingCheckDurationMs,s.maxPingsPerSecond,async()=>{const r=await new g.UnauthenticatedPlClient(e).ping();return JSON.stringify(r).slice(0,s.bodyLimit)+"..."})}async function ol(s,e){return await Se(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await xe(new URL(s.blockOverviewPath,s.blockRegistryUrl),s,e))}async function nl(s,e){return await Se(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await xe(new URL(s.blockOverviewPath,s.blockGARegistryUrl),s,e))}async function il(s,e){return await Se(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await xe(new URL(s.blockUiPath,s.blockRegistryUrl),s,e))}async function al(s,e){return await Se(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await xe(new URL(s.blockUiPath,s.blockGARegistryUrl),s,e))}async function cl(s,e){return await Se(s.autoUpdateCdnDurationMs,s.maxAutoUpdateCdnChecksPerSecond,async()=>await xe(s.autoUpdateCdnUrl,s,e))}async function Se(s,e,t){const r=Date.now(),o=[];for(;Jr(r)<s;){const n=Date.now();let i;try{i={ok:!0,value:await t()}}catch(l){i={ok:!1,error:l}}const c=Jr(n);o.push({elapsedMs:c,response:i});const a=1e3/e-c;a>0&&await _r.setTimeout(a)}return o}async function xe(s,e,t){const{body:r,statusCode:o}=await tt.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),n=await r.text();return{statusCode:o,beginningOfBody:n.slice(0,e.bodyLimit)+"..."}}function Jr(s){return Date.now()-s}function ye(s){const e=s.filter(i=>i.response.ok),t=s.length-e.length,{mean:r,median:o}=ll(s),n=`
1
+ "use strict";var In=Object.defineProperty;var Pr=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),Er=s=>{throw TypeError(s)};var Fn=(s,e,t)=>e in s?In(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var C=(s,e,t)=>Fn(s,typeof e!="symbol"?e+"":e,t);var Or=(s,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Er("Object expected");var r,n;t&&(r=e[Pr("asyncDispose")]),r===void 0&&(r=e[Pr("dispose")],t&&(n=r)),typeof r!="function"&&Er("Object not disposable"),n&&(r=function(){try{n.call(this)}catch(o){return Promise.reject(o)}}),s.push([t,r,e])}else t&&s.push([t]);return e},Tr=(s,e,t)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,c,a,l){return l=Error(a),l.name="SuppressedError",l.error=i,l.suppressed=c,l},n=i=>e=t?new r(i,e,"An error was suppressed during disposal"):(t=!0,i),o=i=>{for(;i=s.pop();)try{var c=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(c).then(o,a=>(n(a),o()))}catch(a){n(a)}if(t)throw e};return o()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V=require("@platforma-sdk/model"),Q=require("@milaboratories/pl-model-middle-layer"),Ir=require("@milaboratories/pl-deployments"),We=require("undici"),Z=require("@platforma-sdk/block-tools"),oe=require("node:fs"),K=require("node:path"),$n=require("yaml"),k=require("@milaboratories/ts-helpers"),Ie=require("node:fs/promises"),Dn=require("@milaboratories/resolve-helper"),g=require("@milaboratories/pl-client"),_e=require("@milaboratories/pl-tree"),M=require("@milaboratories/computable"),te=require("node:crypto"),D=require("@milaboratories/pl-model-backend"),qs=require("lru-cache"),Ln=require("node:worker_threads"),Ms=require("denque"),he=require("@platforma-sdk/workflow-tengo"),_=require("canonicalize"),An=require("node:assert"),ge=require("quickjs-emscripten"),Nn=require("@milaboratories/pl-errors"),Bn=require("remeda"),Gs=require("node:timers/promises"),W=require("@milaboratories/pl-drivers"),Js=require("@milaboratories/pframes-rs-node"),jn=require("node:diagnostics_channel"),xn=require("node:stream/consumers"),_s=require("node:os");function or(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const Vn=or(K),Ks=or(Ie),Fr=or(Bn);async function $r(s){try{return await Ks.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const Un=[Z.RegistryV1.PlPackageYamlConfigFile],qn=[Z.RegistryV1.PlPackageJsonConfigFile],ir=["backend","dist","tengo","tpl","main.plj.gz"],ar=["config","dist","config.json"],Hs=["frontend","dist"],Dr="block-model/dist/config.json",Mn="block-ui/package.json",Gn=[ir,ar,Un,qn,Hs];async function Jn(s){return await $r(K.join(s,...ar))!==void 0||await $r(K.join(s,...ir))!==void 0}function nt(s,e){const t=Dn.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function Lr(s,e){if(K.isAbsolute(s)||(s=K.resolve(s)),await Jn(s))return{workflow:K.join(s,...ir),config:K.join(s,...ar),ui:K.join(s,...Hs)};{const t=nt(s,Dr),r=nt(s,Dr),n=nt(s,Mn);return{workflow:t,config:r,ui:K.resolve(n,"..","dist")}}}async function _n(s){try{return await oe.promises.readFile(s,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Kn(s){try{return await oe.promises.stat(s,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function cr(s){let e=0n;for(const t of Gn){const r=K.join(s,...t),n=await Kn(r);n!==void 0&&e<n.mtimeNs&&(e=n.mtimeNs)}return e.toString()}async function ze(s){const e=await oe.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await oe.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class Hn{constructor(e,t,r){this.v2Provider=e,this.registries=t,this.http=r}async getPackagesForRoot(e){const t=[],r=e.spec;switch(r.type){case"remote-v1":{const n=this.http!==void 0?{dispatcher:this.http}:{},i=await(await We.request(`${r.url}/${Z.RegistryV1.GlobalOverviewPath}`,n)).body.json();for(const c of i){const{organization:a,package:l,latestMeta:u,latestVersion:d}=c,p={organization:a,name:l,version:d},f={id:p,meta:{title:u.title??"No title",description:u.description??"No Description",organization:{name:a,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:p,registryUrl:r.url}};t.push({registryId:e.id,id:p,latestByChannel:{[Q.AnyChannel]:f,[Q.StableChannel]:f},allVersions:c.allVersions.map(m=>({version:m,channels:[]}))})}return t}case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(n=>({...n,registryId:e.id}));case"local-dev":for(const n of await oe.promises.readdir(r.path,{withFileTypes:!0})){if(!n.isDirectory())continue;const o=K.join(r.path,n.name),i=await _n(K.join(o,Z.RegistryV1.PlPackageYamlConfigFile));if(i!==void 0){const c=Z.RegistryV1.PlPackageConfigData.parse($n.parse(i)),a=await cr(o),l={organization:c.organization,name:c.package,version:"DEV"},u={id:l,meta:{title:c.meta.title??"No title",description:c.meta.description??"No Description",organization:{name:c.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:o,mtime:a}};t.push({registryId:e.id,id:l,latestByChannel:{[Q.AnyChannel]:u,[Q.StableChannel]:u},allVersions:[]})}else{let c=o,a=await Z.tryLoadPackDescription(c);if(a===void 0){for(const l of["block","meta"])if(c=K.join(o,l),a=await Z.tryLoadPackDescription(c),a!==void 0)break}if(a!==void 0){const l=await ze(a),u={id:a.id,meta:await Z.BlockPackMetaEmbedAbsoluteBytes.parseAsync(a.meta),spec:{type:"dev-v2",folder:c,mtime:l}};t.push({registryId:e.id,id:a.id,latestByChannel:{[Q.AnyChannel]:u,[Q.StableChannel]:u},allVersions:[]})}}}return t;default:return k.assertNever(r)}}async listBlockPacks(){const e=[],t=[];for(const r of this.registries)t.push({...r,status:"online"}),e.push(...await this.getPackagesForRoot(r));return{registries:t,blockPacks:e}}async getOverview(e,t,r){var i;const n=(i=this.registries.find(c=>c.id===e))==null?void 0:i.spec;if(!n)throw new Error(`Registry with id "${e}" not found`);if(n.type!=="remote-v2")throw new Error('Only "remote-v2" registries support specific package version overview retrieval.');return await this.v2Provider.getRegistry(n.url).getSpecificOverview(t,r)}}class Ws{constructor(e){C(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new Z.RegistryV2Reader(Z.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const Wn={type:"remote-v2",url:"https://blocks.pl-open.science/"},zn={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},Xn={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},Yn={groups:[{id:"default",label:"Default",blocks:[]}]},Qn={stagingRefreshTimestamp:0,blocksInLimbo:[]},Zn={label:"New Project"},eo={name:"UserProject",version:"2"},zs="SchemaVersion",Xs="1",lr="ProjectCreated",Fe="ProjectLastModified",$e="ProjectMeta",de="ProjectStructure",Ke="BlockRenderingState",to="BlockFrontendState/",ro=/^BlockFrontendState\/(?<blockid>.*)$/;function Qt(s){return`${to}${s}`}const so="BlockArgsAuthor/";function Zt(s){return`${so}${s}`}const er="ProjectStructureAuthor";function no(s){const e=s.match(ro);if(e!==null)return e.groups.blockid}const oo="__serviceTemplate_";function tr(s){return`${oo}${s}`}function X(s,e){return`${s}-${e}`}const io=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function ao(s){const e=s.match(io);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const co="projects",Ys={name:"Projects",version:"1"},lo=s=>g.resourceTypesEqual(s.type,Ys)?s.fields:[];async function uo(s,e,t,r){const n=await _e.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:lo},r.logger);return{computable:M.Computable.make(i=>{const c=i.accessor(n.entry()).node(),a=t.getValue(i);if(c===void 0)return;const l=[];for(const u of c.listDynamicFields()){const d=c.traverse(u);if(d===void 0)continue;const p=k.notEmpty(d.getKeyValueAsJson($e)),f=k.notEmpty(d.getKeyValueAsJson(lr)),m=k.notEmpty(d.getKeyValueAsJson(Fe));l.push({id:u,rid:d.id,created:new Date(f),lastModified:new Date(m),opened:a.indexOf(d.id)>=0,meta:p})}return l.sort(u=>-u.lastModified.valueOf()),l}).withStableType(),tree:n}}const po={name:"EphRenderTemplate",version:"1"},fo={name:"RenderTemplate",version:"1"};function Xe(s,e,t,r,n){if(n.length===0)throw new Error("Zero output names provided");const o=t?s.createEphemeral(po):s.createStruct(fo),i=g.field(o,"template"),c=g.field(o,"inputs");return s.createField(i,"Input",e),s.createField(c,"Input",g.Pl.createPlMap(s,r,t)),s.lockInputs(o),g.Pl.futureRecord(s,o,n,"Output","outputs/")}const go={name:"BContextEnd",version:"1"},ho={name:"BContext",version:"1"},mo="id",vo="parent/",yo=["context","result"];function Ar(s,e,t){return Xe(s,e,!0,t,yo)}function wo(s){const e=s.createEphemeral(go);return s.lock(e),e}function Nr(s,e){if(e.length===0)return wo(s);if(e.length===1)return e[0];const t=s.createEphemeral(ho);s.createField(g.field(t,mo),"Input",g.Pl.createPlString(s,te.randomUUID()));for(let r=0;r<e.length;r++)s.createField(g.field(t,`${vo}${r}`),"Input",e[r]);return s.lock(t),t}function Qs(s,e){const t=new Map,r=(n,o,i)=>{const c=te.createHash("sha256");o.updateCacheKey(n,c,i);const a=c.digest("hex");if(!t.has(a)){const l=o.render(n,s,r,i);t.set(a,l)}return t.get(a)};return r(e.template,Zs,e.hashToSource)}const Br={updateCacheKey(s,e,t){e.update(D.PlTemplateLibV1.type.name).update(D.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(ve(s.name,t,s.sourceHash))},render(s,e,t,r){return e.createValue(D.PlTemplateLibV1.type,JSON.stringify(D.PlTemplateLibV1.fromV3Data(s,ve(s.name,r,s.sourceHash)).data))}},je={updateCacheKey(s,e,t){e.update(D.PlTemplateSoftwareV1.type.name).update(D.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(ve(s.name,t,s.sourceHash))},render(s,e,t,r){const n=D.PlTemplateSoftwareV1.fromV3Data(s,ve(s.name,r,s.sourceHash)),o=e.createStruct(D.PlTemplateSoftwareV1.type,n.data);return e.setKValue(o,D.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(n.name)),e.lock(o),o}},Zs={updateCacheKey(s,e,t){e.update(D.PlTemplateV1.type.name).update(D.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(ve(s.name,t,s.sourceHash));const r=n=>(n.sort((o,i)=>o[0]===i[0]?0:o[0]<i[0]?-1:1),n);for(const[n,o]of r(Object.entries(s.libs??{})))e.update("lib:"+n),Br.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.software??{})))e.update("soft:"+n),je.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.assets??{})))e.update("asset:"+n),je.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.templates??{})))e.update("tpl:"+n),this.updateCacheKey(o,e,t)},render(s,e,t,r){const n=e.createStruct(D.PlTemplateV1.type,JSON.stringify(D.PlTemplateV1.fromV3Data(s,ve(s.name,r,s.sourceHash)).data));for(const[c,a]of Object.entries(s.libs??{})){const l=D.PlTemplateV1.libField(n,c);e.createField(l,"Input"),e.setField(l,t(a,Br,r))}for(const[c,a]of Object.entries(s.software??{})){const l=D.PlTemplateV1.swField(n,c);e.createField(l,"Input"),e.setField(l,t(a,je,r))}for(const[c,a]of Object.entries(s.assets??{})){const l=D.PlTemplateV1.swField(n,c);e.createField(l,"Input"),e.setField(l,t(a,je,r))}for(const[c,a]of Object.entries(s.templates??{})){const l=D.PlTemplateV1.tplField(n,c);e.createField(l,"Input"),e.setField(l,t(a,Zs,r))}if(e.lock(n),!s.hashOverride)return n;const o=e.createStruct(D.PlTemplateOverrideV1.type,JSON.stringify(D.PlTemplateOverrideV1.fromV3Data(s))),i=D.PlTemplateOverrideV1.tplField(o);return e.createField(i,"Service"),e.setField(i,n),e.lock(o),o}};function ve(s,e,t){return k.notEmpty(e[t],`trying to get "${s}" source: sources map doesn't contain source hash ${t}`)}function bo(s,e){const t=D.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return tn(s,t);case"pl.tengo-template.v3":return Qs(s,t);default:k.assertNever(r)}}function So(s,e){const t=e.data,r=t.type;switch(r){case"pl.tengo-template.v2":return tn(s,t);case"pl.tengo-template.v3":return Qs(s,t);default:k.assertNever(r)}}const jr={hash(s,e){e.update(D.PlTemplateLibV1.type.name).update(D.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue(D.PlTemplateLibV1.type,JSON.stringify(D.PlTemplateLibV1.fromV2Data(s).data))}},xe={hash(s,e){e.update(D.PlTemplateSoftwareV1.type.name).update(D.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=D.PlTemplateSoftwareV1.fromV2Data(s),n=e.createStruct(D.PlTemplateSoftwareV1.type,r.data);return e.setKValue(n,D.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(n),n}},en={hash(s,e){e.update(D.PlTemplateV1.type.name).update(D.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(s.src);const t=r=>(r.sort((n,o)=>n[0]===o[0]?0:n[0]<o[0]?-1:1),r);for(const[r,n]of t(Object.entries(s.libs??{})))e.update("lib:"+r),jr.hash(n,e);for(const[r,n]of t(Object.entries(s.software??{})))e.update("soft:"+r),xe.hash(n,e);for(const[r,n]of t(Object.entries(s.assets??{})))e.update("asset:"+r),xe.hash(n,e);for(const[r,n]of t(Object.entries(s.templates??{})))e.update("tpl:"+r),this.hash(n,e)},render(s,e,t){const r=e.createStruct(D.PlTemplateV1.type,JSON.stringify(D.PlTemplateV1.fromV2Data(s).data));for(const[i,c]of Object.entries(s.libs??{})){const a=D.PlTemplateV1.libField(r,i);e.createField(a,"Input"),e.setField(a,t(c,jr))}for(const[i,c]of Object.entries(s.software??{})){const a=D.PlTemplateV1.swField(r,i);e.createField(a,"Input"),e.setField(a,t(c,xe))}for(const[i,c]of Object.entries(s.assets??{})){const a=D.PlTemplateV1.swField(r,i);e.createField(a,"Input"),e.setField(a,t(c,xe))}for(const[i,c]of Object.entries(s.templates??{})){const a=D.PlTemplateV1.tplField(r,i);e.createField(a,"Input"),e.setField(a,t(c,en))}if(e.lock(r),!s.hashOverride)return r;const n=e.createStruct(D.PlTemplateOverrideV1.type,JSON.stringify(D.PlTemplateOverrideV1.fromV2Data(s))),o=D.PlTemplateOverrideV1.tplField(n);return e.createField(o,"Service"),e.setField(o,r),e.lock(n),n}};function tn(s,e){const t=new Map,r=(n,o)=>{const i=te.createHash("sha256");o.hash(n,i);const c=i.digest("hex");if(!t.has(c)){const a=o.render(n,s,r);t.set(c,a)}return t.get(c)};return r(e,en)}const rn={name:"TengoTemplateGet",version:"1"},sn="registry",nn="templateURI",on="template",Ro={name:"TengoTemplatePack",version:"1"},ko={name:"TengoTemplatePackConvert",version:"1"},Co="templatePack",Po="template";async function ur(s){switch(s.type){case"from-file":return{type:"explicit",content:await oe.promises.readFile(s.path)};case"from-registry":case"explicit":return s;case"prepared":return s;default:return k.assertNever(s)}}function Eo(s,e){const t=s.createStruct(rn),r=g.field(t,sn),n=g.field(t,nn),o=g.field(t,on);return s.setField(r,s.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(n,s.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),o}function Ae(s,e){switch(e.type){case"from-registry":return Eo(s,e);case"explicit":return bo(s,e);case"prepared":return So(s,e);default:return k.assertNever(e)}}const dr={name:"Frontend/FromUrl",version:"1"},pr={name:"Frontend/FromFolder",version:"1"};function Oo(s,e){switch(e.type){case"url":return s.createValue(dr,JSON.stringify({url:e.url}));case"local":return s.createValue(pr,JSON.stringify({path:e.path,signature:e.signature}));default:return k.assertNever(e)}}class To{constructor(){C(this,"nextMessageId",0);C(this,"worker");C(this,"pendingRequests",new Map);const e=typeof global<"u"&&"__WORKER_PATH__"in global?global.__WORKER_PATH__:K.resolve(void 0,"worker.js"),t=this.worker=new Ln.Worker(e,{workerData:{}});t.on("message",({id:r,data:n,error:o})=>{const{resolve:i,reject:c}=this.pendingRequests.get(r);this.pendingRequests.delete(r),o?c(new Error(o)):i(n)}),t.on("error",r=>{console.error("Worker error",r),this.rejectAllPendingRequests(r)})}rejectAllPendingRequests(e){Array.from(this.pendingRequests.values()).map(({reject:t})=>{t(e)})}async process(e,...t){return new Promise((r,n)=>{const o=++this.nextMessageId;this.pendingRequests.set(o,{resolve:r,reject:n}),this.worker.postMessage({id:o,type:e,args:t})})}async terminate(){this.rejectAllPendingRequests(new Error("Worker terminated")),await this.worker.terminate()}[Symbol.asyncDispose](){return this.terminate()}}const Io={name:"BlockPackCustom",version:"1"},an="template",cn="frontend";function xr(s){return s.endsWith("/")?s:`${s}/`}function Fo(s){return Buffer.from(s).toString("utf8")}function Ve(s){return JSON.parse(Fo(s))}class $o{constructor(e,t,r){C(this,"remoteContentCache",new qs.LRUCache({max:500,maxSize:128*1024*1024,fetchMethod:async e=>{const t=this.http!==void 0?{dispatcher:this.http}:{};return await(await We.request(e,t)).body.arrayBuffer()},sizeCalculation:e=>e.byteLength}));this.v2RegistryProvider=e,this.signer=t,this.http=r}async getBlockConfigContainer(e){switch(e.type){case"explicit":return e.config;case"prepared":return e.config;case"dev-v1":{const t=await Lr(e.folder),r=await oe.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await Z.loadPackDescription(e.folder),r=await oe.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=`${xr(e.registryUrl)}${Z.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=await this.remoteContentCache.forceFetch(`${t}/config.json`);return Ve(r)}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),n=await this.remoteContentCache.forceFetch(r.model.url);return Ve(n)}default:return k.assertNever(e)}}async prepare(e){var n=[];try{if(e.type==="prepared")return e;const t=await this.prepareWithoutUnpacking(e);const r=Or(n,new To,!0);return{...t,type:"prepared",template:{type:"prepared",data:await r.process("parseTemplate",t.template.content)}}}catch(o){var i=o,c=!0}finally{var a=Tr(n,i,c);a&&await a}}async prepareWithoutUnpacking(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await Lr(e.folder),r=await oe.promises.readFile(t.workflow),n=JSON.parse(await oe.promises.readFile(t.config,"utf-8")),o=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:n,frontend:{type:"local",path:o,signature:this.signer.sign(o)},source:e}}case"dev-v2":{const t=await Z.loadPackDescription(e.folder),r=JSON.parse(await oe.promises.readFile(t.components.model.file,{encoding:"utf-8"})),n=await oe.promises.readFile(t.components.workflow.main.file),o=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await ze(t)),{type:"explicit",template:{type:"explicit",content:n},config:r,frontend:{type:"local",path:o,signature:this.signer.sign(o)},source:i}}case"from-registry-v1":{const t=`${xr(e.registryUrl)}${Z.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=`${t}/template.plj.gz`,n=await this.remoteContentCache.forceFetch(r),o=new Uint8Array(n),i=await this.remoteContentCache.forceFetch(`${t}/config.json`),c=Ve(i);return{type:"explicit",template:{type:"explicit",content:o},config:c,frontend:{type:"url",url:`${t}/frontend.tgz`},source:e}}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),n=async()=>Ve(await this.remoteContentCache.forceFetch(r.model.url)),o=async()=>await this.remoteContentCache.forceFetch(r.workflow.main.url),[i,c]=await Promise.all([n(),o()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(c)},config:i,frontend:{type:"url",url:r.ui.url},source:e}}default:return k.assertNever(e)}}}function Do(s,e){const t={config:e.config,source:e.source},r=s.createStruct(Io,JSON.stringify(t));return s.createField(g.field(r,an),"Input",Ae(s,e.template)),s.createField(g.field(r,cn),"Input",Oo(s,e.frontend)),s.lock(r),r}function Vr(s,e){switch(e.type){case"prepared":return Do(s,e);default:return k.assertNever(e.type)}}function Ue(s,e,t){return{__isRef:!0,blockId:s,name:e}}function Lo(s){return typeof s=="object"&&s!==null&&"__isRef"in s&&s.__isRef===!0&&"blockId"in s&&"name"in s}function rr(s,e,t){const r=typeof e;switch(r){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if(Lo(e))t===void 0||t.has(e.blockId)?(s.upstreams.add(e.blockId),e.requireEnrichments&&s.upstreamsRequiringEnrichments.add(e.blockId)):s.missingReferences=!0;else if(Array.isArray(e))for(const n of e)rr(s,n,t);else for(const[,n]of Object.entries(e))rr(s,n,t);return;default:k.assertNever(r)}}function Ao(s,e){const t={upstreams:new Set,upstreamsRequiringEnrichments:new Set,missingReferences:!1};return rr(t,s,e),t}function ie(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class ln{constructor(e){C(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,n=>r.add(n.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const n of t)r.delete(n);return r}traverse(e,t,r){let n=[...t];const o=new Set(n);for(;n.length>0;){const i=[];for(const c of n){const a=this.nodes.get(c);r(a),a[e].forEach(l=>{o.has(l)||(o.add(l),i.push(l))})}n=i}}}function sr(s){const e=new Map;let t;for(const{id:r}of ie(s)){const n={id:r,missingReferences:!1};e.set(r,n),t===void 0?(n.directUpstream=n.upstream=new Set,n.enrichments=n.enrichmentTargets=new Set):(n.directUpstream=n.upstream=new Set([t.id]),t.directDownstream=t.downstream=new Set([n.id]),t.enrichments=t.enrichmentTargets=new Set),t=n}return t!==void 0&&(t.directDownstream=t.downstream=new Set),new ln(e)}function Je(s,e){const t=new Map,r=new ln(t),n=new Set;for(const{id:o}of ie(s)){const i=e(o);if(i===void 0)continue;const c=Ao(i.args,n),a=new Set([...c.upstreams,...r.traverseIds("enrichments",...c.upstreamsRequiringEnrichments)]),l=new Set;for(const{id:p}of ie(s)){if(p===o)break;if(a.has(p)){l.add(p);for(const f of r.traverseIdsExcludingRoots("upstream",p))l.delete(f)}}const u=i.enrichmentTargets===void 0?new Set(c.upstreams):new Set(i.enrichmentTargets.map(p=>p.blockId)),d={id:o,missingReferences:c.missingReferences,upstream:l,directUpstream:c.upstreams,enrichmentTargets:u,downstream:new Set,directDownstream:new Set,enrichments:new Set};t.set(o,d),c.upstreams.forEach(p=>t.get(p).directDownstream.add(o)),l.forEach(p=>t.get(p).downstream.add(o)),u.forEach(p=>{var f;return(f=t.get(p))==null?void 0:f.enrichments.add(o)}),n.add(o)}return r}function No(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function nr(s,e){if(s.size>e.size)return nr(e,s);for(const t of s)if(e.has(t))return!0;return!1}function Ur(s,e){const t=new Set,r=new Set,n=new Set;return s.nodes.forEach(o=>{const i=e.nodes.get(o.id);i===void 0?t.add(o.id):(!No(o.upstream,i.upstream)||nr(o.upstream,n))&&n.add(o.id)}),e.nodes.forEach(o=>{s.nodes.has(o.id)?nr(o.upstream,n)&&n.add(o.id):r.add(o.id)}),{onlyInA:t,onlyInB:r,different:n}}let ot;async function un(){if(ot===void 0){const s=await ur(he.Templates["pframes.export-pframe-for-ui"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=te.createHash("sha256").update(s.content).digest("hex");ot={spec:s,hash:e}}return ot}function Bo(s,e,t){return Xe(s,e,!0,{pf:t},["result"]).result}function it(s,e){let t=!1,r,n;return()=>{if(!t)return t=!0,r=s(),n=e(),n;const o=s();return r!==o&&(r=o,n=e()),e()}}class qr{constructor(e,t,r,n){C(this,"currentArgsC",it(()=>this.fields.currentArgs.modCount,()=>k.cachedDeserialize(this.fields.currentArgs.value)));C(this,"prodArgsC",it(()=>{var e;return(e=this.fields.prodArgs)==null?void 0:e.modCount},()=>{var t;const e=(t=this.fields.prodArgs)==null?void 0:t.value;if(e!==void 0)return k.cachedDeserialize(e)}));C(this,"productionStaleC",it(()=>{var e;return`${this.fields.currentArgs.modCount}_${(e=this.fields.prodArgs)==null?void 0:e.modCount}`},()=>this.fields.prodArgs===void 0||Buffer.compare(this.fields.currentArgs.value,this.fields.prodArgs.value)!==0));this.id=e,this.fields=t,this.config=r,this.source=n}check(){if(this.fields.prodOutput===void 0!=(this.fields.prodCtx===void 0))throw new Error("inconsistent prod fields");if(this.fields.stagingOutput===void 0!=(this.fields.stagingCtx===void 0))throw new Error("inconsistent stage fields");if(this.fields.prodOutputPrevious===void 0!=(this.fields.prodCtxPrevious===void 0))throw new Error("inconsistent prod cache fields");if(this.fields.stagingOutputPrevious===void 0!=(this.fields.stagingCtxPrevious===void 0))throw new Error("inconsistent stage cache fields");if(this.fields.blockPack===void 0)throw new Error("no block pack field");if(this.fields.currentArgs===void 0)throw new Error("no current args field")}get currentArgs(){return this.currentArgsC()}get stagingRendered(){return this.fields.stagingCtx!==void 0}get productionRendered(){return this.fields.prodCtx!==void 0}get productionHasErrors(){var e;return((e=this.fields.prodUiCtx)==null?void 0:e.status)==="Error"}get requireProductionRendering(){return!this.productionRendered||this.productionStaleC()||this.productionHasErrors}get prodArgs(){return this.prodArgsC()}getTemplate(e){return e.getFutureFieldValue(g.Pl.unwrapHolder(e,this.fields.blockPack.ref),an,"Input")}}const jo=s=>{throw new Error(`No new block info for ${s}`)};class He{constructor(e,t,r,n,o,i,c,a,l,u,d,p,f){C(this,"globalModCount",0);C(this,"fieldsChanged",!1);C(this,"lastModifiedChanged",!1);C(this,"structureChanged",!1);C(this,"metaChanged",!1);C(this,"renderingStateChanged",!1);C(this,"changedBlockFrontendStates",new Set);C(this,"blocksWithChangedInputs",new Set);C(this,"stagingGraph");C(this,"pendingProductionGraph");C(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=n,this.lastModified=o,this.meta=i,this.struct=c,this.renderingState=a,this.blocksInLimbo=l,this.blockInfos=u,this.blockFrontendStates=d,this.ctxExportTplHolder=p,this.projectHelper=f}fixProblemsAndMigrate(){this.blockInfos.forEach(t=>{(t.fields.prodArgs===void 0||t.fields.prodOutput===void 0||t.fields.prodCtx===void 0)&&this.deleteBlockFields(t.id,"prodArgs","prodOutput","prodCtx")});let e;this.blockInfos.forEach(t=>{t.fields.blockSettings===void 0&&(e===void 0&&(e=this.createJsonFieldValue(Q.InitialBlockSettings)),this.setBlockFieldObj(t.id,"blockSettings",e))})}get wasModified(){return this.lastModifiedChanged||this.structureChanged||this.fieldsChanged||this.metaChanged||this.renderingStateChanged||this.changedBlockFrontendStates.size>0}get structure(){return JSON.parse(JSON.stringify(this.struct))}getStagingGraph(){return this.stagingGraph===void 0&&(this.stagingGraph=sr(this.struct)),this.stagingGraph}getProductionGraphBlockInfo(e,t){const r=this.getBlockInfo(e);let n,o;if(t){if(r.fields.prodArgs===void 0)return;n=r.fields.prodArgs,o=r.prodArgs}else n=k.notEmpty(r.fields.currentArgs),o=r.currentArgs;const i=k.notEmpty(r.fields.blockPack);return g.isResourceId(n.ref)&&g.isResourceId(i.ref)?{args:o,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>o,{argsRid:n.ref,blockPackRid:i.ref})}:{args:o,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>o)}}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Je(this.struct,e=>this.getProductionGraphBlockInfo(e,!1))),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Je(this.struct,e=>this.getProductionGraphBlockInfo(e,!0))),this.actualProductionGraph}getBlockInfo(e){const t=this.blockInfos.get(e);if(t===void 0)throw new Error(`No such block: ${e}`);return t}createJsonFieldValueByContent(e){const t=Buffer.from(e);return{ref:this.tx.createValue(g.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of ie(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const n=g.field(this.rid,X(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(n,"Dynamic",r.ref):this.tx.setField(n,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,n,o){this.setBlockFieldObj(e,t,{ref:r,status:n,value:o})}deleteBlockFields(e,...t){let r=!1;const n=this.getBlockInfo(e);for(const o of t){const i=n.fields;o in i&&(this.tx.removeField(g.field(this.rid,X(e,o))),delete i[o],this.fieldsChanged=!0,r=!0)}return r}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var r,n,o;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((n=t.stagingCtx)==null?void 0:n.status)==="Ready"&&((o=t.stagingUiCtx)==null?void 0:o.status)==="Ready"&&(this.setBlockFieldObj(e,"stagingOutputPrevious",t.stagingOutput),this.setBlockFieldObj(e,"stagingCtxPrevious",t.stagingCtx),this.setBlockFieldObj(e,"stagingUiCtxPrevious",t.stagingUiCtx)),this.deleteBlockFields(e,"stagingOutput","stagingCtx","stagingUiCtx")&&this.resetStagingRefreshTimestamp()}resetProduction(e){var r,n,o;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((n=t.prodCtx)==null?void 0:n.status)==="Ready"&&((o=t.prodUiCtx)==null?void 0:o.status)==="Ready"&&(this.setBlockFieldObj(e,"prodOutputPrevious",t.prodOutput),this.setBlockFieldObj(e,"prodCtxPrevious",t.prodCtx),this.setBlockFieldObj(e,"prodUiCtxPrevious",t.prodUiCtx)),this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}resetOrLimboProduction(e){var r,n;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((n=t.prodCtx)==null?void 0:n.status)==="Ready"?this.blocksInLimbo.has(e)?!1:(this.blocksInLimbo.add(e),this.renderingStateChanged=!0,this.deleteBlockFields(e,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),!0):this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}setArgs(e){const t=[];for(const{blockId:r,args:n}of e){const o=this.getBlockInfo(r);JSON.parse(n);const i=Buffer.from(n);if(Buffer.compare(o.fields.currentArgs.value,i)===0)continue;const c=this.tx.createValue(g.Pl.JsonObject,i);this.setBlockField(r,"currentArgs",c,"Ready",i),this.blocksWithChangedInputs.add(r),t.push(r)}this.getStagingGraph().traverse("downstream",t,({id:r})=>this.resetStaging(r)),t.length>0&&this.updateLastModified()}setUiState(e,t){if(this.blockInfos.get(e)===void 0)throw new Error("no such block");this.blockFrontendStates.get(e)!==t&&(t===void 0?this.blockFrontendStates.delete(e):this.blockFrontendStates.set(e,t),this.changedBlockFrontendStates.add(e),this.blocksWithChangedInputs.add(e),this.updateLastModified())}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createProdCtx(e){const t=[];return e.forEach(r=>{var o;const n=this.getBlockInfo(r);if(((o=n.fields.prodCtx)==null?void 0:o.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,n.fields.prodCtx.ref))}),Nr(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(r=>{var o,i;const n=this.getBlockInfo(r);if(((o=n.fields.stagingCtx)==null?void 0:o.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,n.fields.stagingCtx.ref)),((i=n.fields.prodCtx)==null?void 0:i.ref)!==void 0&&t.push(g.Pl.unwrapHolder(this.tx,n.fields.prodCtx.ref))}),Nr(this.tx,t)}exportCtx(e){return Bo(this.tx,g.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createStagingCtx(this.getStagingGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const n=t.getTemplate(this.tx),o=Ar(this.tx,n,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(g.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(g.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",g.Pl.wrapInEphHolder(this.tx,o.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(o.context),"NotReady"),this.setBlockField(e,"stagingOutput",o.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),r=this.createProdCtx(this.getPendingProductionGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const n=t.getTemplate(this.tx),o=Ar(this.tx,n,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(g.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(g.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",g.Pl.wrapInEphHolder(this.tx,o.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(o.context),"NotReady"),this.setBlockField(e,"prodOutput",o.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=jo){const r=this.getStagingGraph(),n=this.getActualProductionGraph(),o=sr(e),i=Ur(r,o);for(const l of i.onlyInA){const{fields:u}=this.getBlockInfo(l);this.deleteBlockFields(l,...Object.keys(u)),this.blockInfos.delete(l),this.blocksInLimbo.delete(l)&&(this.renderingStateChanged=!0),this.blockFrontendStates.delete(l)&&this.changedBlockFrontendStates.add(l)}for(const l of i.onlyInB){const u=t(l),d=new qr(l,{},V.extractConfig(u.blockPack.config),u.blockPack.source);this.blockInfos.set(l,d);const p=Vr(this.tx,u.blockPack);this.setBlockField(l,"blockPack",g.Pl.wrapInHolder(this.tx,p),"NotReady"),this.setBlockFieldObj(l,"blockSettings",this.createJsonFieldValue(Q.InitialBlockSettings)),this.setBlockFieldObj(l,"currentArgs",this.createJsonFieldValueByContent(u.args)),u.uiState&&(this.blockFrontendStates.set(l,u.uiState),this.changedBlockFrontendStates.add(l)),d.check()}for(const l of i.different)this.resetStaging(l);const c=Je(e,l=>this.getProductionGraphBlockInfo(l,!0)),a=Ur(n,c);n.traverse("downstream",[...a.different],l=>{this.resetOrLimboProduction(l.id)}),(i.onlyInB.size>0||i.onlyInA.size>0||i.different.size>0)&&this.resetStagingRefreshTimestamp(),this.struct=e,this.structureChanged=!0,this.stagingGraph=void 0,this.pendingProductionGraph=void 0,this.actualProductionGraph=void 0,this.updateLastModified()}addBlock(e,t,r){const n=this.structure;if(r===void 0)n.groups[n.groups.length-1].blocks.push(e);else{let o=!1;for(const i of n.groups){const c=i.blocks.findIndex(a=>a.id===r);if(!(c<0)){i.blocks.splice(c,0,e),o=!0;break}}if(!o)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(n,o=>{if(o!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const n of t.groups){const o=n.blocks.findIndex(i=>i.id===e);if(!(o<0)){n.blocks.splice(o,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const n=this.getBlockInfo(e);this.setBlockField(e,"blockPack",g.Pl.wrapInHolder(this.tx,Vr(this.tx,t)),"NotReady"),r!==void 0?(this.setArgs([{blockId:e,args:r.args}]),this.setUiState(e,r.uiState)):this.getStagingGraph().traverse("downstream",[e],({id:o})=>this.resetStaging(o)),n.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:o})=>this.resetOrLimboProduction(o)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),n=this.getPendingProductionGraph();if(t)n.traverse("upstream",e,c=>{r.add(c.id)});else for(const c of r){const a=n.nodes.get(c);if(a===void 0)throw new Error(`Can't find block with id: ${c}`);for(const l of a.upstream)if(!r.has(l))throw new Error("Can't render blocks not including all upstreams.")}const o=new Set;for(const c of ie(this.structure)){if(!r.has(c.id))continue;let a=this.getBlockInfo(c.id).requireProductionRendering||this.blocksInLimbo.has(c.id);if(!a){for(const l of n.nodes.get(c.id).upstream)if(o.has(l)){a=!0;break}}a&&(this.renderProductionFor(c.id),o.add(c.id))}const i=[...o];return n.traverse("downstream",i,c=>{o.has(c.id)||this.resetOrLimboProduction(c.id)}),this.getStagingGraph().traverse("downstream",i,({id:c})=>{i[0]!==c&&this.resetStaging(c)}),o.size>0&&this.updateLastModified(),o}stopProduction(...e){var i,c;const t=this.getActualProductionGraph(),r=new Ms(e),n=new Set(e),o=[];for(;!r.isEmpty();){const a=r.shift(),l=this.getBlockInfo(a).fields;if(!(((i=l.prodOutput)==null?void 0:i.status)==="Ready"&&((c=l.prodCtx)==null?void 0:c.status)==="Ready")&&this.deleteBlockFields(a,"prodOutput","prodCtx","prodUiCtx","prodArgs")){o.push(a);for(const u of t.traverseIdsExcludingRoots("downstream",a))n.has(u)||(r.push(u),n.add(u))}}for(const a of t.traverseIdsExcludingRoots("downstream",...o))this.resetOrLimboProduction(a)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(n=>{let i=this.getBlockInfo(n.id).stagingRendered?0:1;n.upstream.forEach(c=>{const a=t.get(c);a!==0&&(i=Math.max(a+1,i))}),e(n.id,i),t.set(n.id,i)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,r=e===void 0?void 0:1+Math.max(0,t*e/1e3);let n=0;this.traverseWithStagingLag((o,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(o),n++)}),n>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,n,o,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((n=t.fields.prodOutput)==null?void 0:n.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((o=t.fields.stagingCtx)==null?void 0:o.status)==="Ready"&&((i=t.fields.stagingOutput)==null?void 0:i.status)==="Ready"&&this.deleteBlockFields(t.id,"stagingOutputPrevious","stagingCtxPrevious","stagingUiCtxPrevious")})}assignAuthorMarkers(){const e=this.author?JSON.stringify(this.author):void 0;for(const t of this.blocksWithChangedInputs)e===void 0?this.tx.deleteKValue(this.rid,Zt(t)):this.tx.setKValue(this.rid,Zt(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,er):this.tx.setKValue(this.rid,er,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,Fe,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,de,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,Ke,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,$e,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,Qt(e)):this.tx.setKValue(this.rid,Qt(e),t)}this.assignAuthorMarkers()}}static async load(e,t,r,n){const o=t.getResourceData(r,!0),i=t.getKValueJson(r,zs),c=t.getKValueJson(r,Fe),a=t.getKValueJson(r,$e),l=t.getKValueJson(r,de),u=t.getKValueJson(r,Ke),d=t.listKeyValuesString(r),p=await o,f=new Map;for(const v of p.fields){const S=ao(v.name);if(S===void 0)continue;let w=f.get(S.blockId);w===void 0&&(w={id:S.blockId,fields:{}},f.set(S.blockId,w)),w.fields[S.fieldName]=g.isNullResourceId(v.value)?{modCount:0}:{modCount:0,ref:v.value}}const m=[];f.forEach(v=>{const S=v.fields;for(const[w,P]of Object.entries(S)){if(P.ref===void 0)continue;if(!g.isResource(P.ref)||g.isResourceRef(P.ref))throw new Error("unexpected behaviour");const $=w;m.push([v,$,P,t.getResourceData(P.ref,$=="blockPack")])}});const[h,R,I,j,{stagingRefreshTimestamp:L,blocksInLimbo:q},z]=await Promise.all([i,c,a,l,u,d]);if(h!==Xs)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${h}`);const T=[];for(const[v,S,w,P]of m){const $=await P;if(w.value=$.data,g.isNotNullResourceId($.error)?w.status="Error":$.resourceReady||g.isNotNullResourceId($.originalResourceId)?w.status="Ready":w.status="NotReady",S==="blockPack"){const F=$.fields.find(x=>x.name===g.Pl.HolderRefField);if(F===void 0)throw new Error("Block pack ref field is missing");T.push([v,t.getResourceData(g.ensureResourceIdNotNull(F.value),!1)])}}for(const[v,S]of T){const w=await S,P=k.cachedDeserialize(k.notEmpty(w.data));v.blockConfig=V.extractConfig(P.config),v.blockPack=P.source}const N=await un(),O=tr(N.hash),G=p.fields.find(v=>v.name===O);let re;G!==void 0?re=g.ensureResourceIdNotNull(G.value):(re=g.Pl.wrapInHolder(t,Ae(t,N.spec)),t.createField(g.field(r,tr(N.hash)),"Dynamic",re));const se={stagingRefreshTimestamp:L},H=new Set(q),Y=new Map;for(const v of z){const S=no(v.key);S!==void 0&&Y.set(S,v.value)}const b=new Map;f.forEach(({id:v,fields:S,blockConfig:w,blockPack:P})=>b.set(v,new qr(v,S,k.notEmpty(w),k.notEmpty(P))));const y=new Set;for(const v of ie(j)){if(!b.has(v.id))throw new Error(`Inconsistent project structure: no inputs for ${v.id}`);y.add(v.id)}b.forEach(v=>{if(!y.has(v.id))throw new Error(`Inconsistent project structure: no structure entry for ${v.id}`);v.check()});const E=new He(r,t,n,h,R,I,j,se,H,b,Y,re,e);return E.fixProblemsAndMigrate(),E}}async function xo(s,e=Zn){const t=s.createEphemeral(eo);s.lock(t);const r=String(Date.now());s.setKValue(t,zs,JSON.stringify(Xs)),s.setKValue(t,lr,r),s.setKValue(t,Fe,r),s.setKValue(t,$e,JSON.stringify(e)),s.setKValue(t,de,JSON.stringify(Yn)),s.setKValue(t,Ke,JSON.stringify(Qn));const n=await un();return s.createField(g.field(t,tr(n.hash)),"Dynamic",g.Pl.wrapInHolder(s,Ae(s,n.spec))),t}async function qe(s,e,t,r){return ae(s,e,t,void 0,r)}async function ae(s,e,t,r,n){if(e instanceof g.PlClient)return await e.withWriteTx("ProjectAction",async o=>{const i=await He.load(s,o,t,r),c=await n(i);return i.wasModified&&(i.save(),await o.commit()),c});{const o=await He.load(s,e,t,r),i=await n(o);return o.save(),i}}function*Vo(s){switch(s.type){case"Json":return;case"JsonPartitioned":for(const[,e]of Object.entries(s.parts))yield e;return;case"BinaryPartitioned":for(const[,{index:e,values:t}]of Object.entries(s.parts))yield e,yield t;return;default:k.assertNever(s)}}function Mr(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function Uo(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:Mr(s.parts,e)};case"BinaryPartitioned":return{...s,parts:Mr(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:k.assertNever(s)}}const qo=g.resourceType("PColumnData/JsonPartitioned","1"),Mo=g.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Go=g.resourceType("PColumnData/BinaryPartitioned","1"),Jo=g.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),_o=g.resourceType("PColumnData/Json","1");function Ko(s){if(!s.getIsReadyOrError())throw new Error("Data not ready.");const e=s.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(g.resourceTypesEqual(s.resourceType,_o)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(g.resourceTypesEqual(s.resourceType,qo)){const t=e,r=Object.fromEntries(s.listInputFields().map(n=>[n,s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,Mo)){const t=e,r={};for(const n of s.listInputFields()){const o=s.traverse({field:n,errorIfFieldNotSet:!0}),i=o.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${n}`);for(const c of i){const a=JSON.stringify([...JSON.parse(n),...JSON.parse(c)]);r[a]=o.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,Go)){const t=e,r={};for(const n of s.listInputFields())if(n.endsWith(".index")){const o=n.slice(0,n.length-6);let i=r[o];i===void 0&&(i={},r[o]=i),i.index=s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo}else if(n.endsWith(".values")){const o=n.slice(0,n.length-7);let i=r[o];i===void 0&&(i={},r[o]=i),i.values=s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${n}`);for(const[n,o]of Object.entries(r)){if(o.index===void 0)throw new Error(`no index for part ${n}`);if(o.values===void 0)throw new Error(`no values for part ${n}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,Jo)){const t=e,r={};for(const n of s.listInputFields()){const o=s.traverse({field:n,errorIfFieldNotSet:!0}),i=o.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${n}`);for(const c of i)if(c.endsWith(".index")){const a=c.slice(0,c.length-6),l=JSON.stringify([...JSON.parse(n),...JSON.parse(a)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].index=o.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}else if(c.endsWith(".values")){const a=c.slice(0,c.length-7),l=JSON.stringify([...JSON.parse(n),...JSON.parse(a)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].values=o.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${c}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}throw new Error(`unsupported resource type: ${g.resourceTypeToString(s.resourceType)}`)}function Ho(s,e){const t=s.axesSpec.length,r={};for(const{key:n,val:o}of e){if(n.length!==t)throw new Error(`inline column key length ${n.length} differs from axes count ${t}`);r[JSON.stringify(n)]=o}return{type:"Json",keyLength:t,data:r}}function Wo(s,e){const t=te.createHash("sha256");return t.update(_(s)),t.update(String(g.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function Gr(s,e){return _({__isRef:!0,blockId:s,name:e})}function zo(s,e){return _({resolvePath:s,name:e})}function dn(s,e=!0,t=!1,r=""){var c,a,l;const n=/^(?<name>.*)\.(?<type>spec|data)$/,o=new Map;for(const u of s.listInputFields()){const d=u.match(n);if(!d){if(e)throw new Error(`unexpected field name ${u}`);continue}let p=k.notEmpty((c=d.groups)==null?void 0:c.name);if(!p.startsWith(r)){if(e)throw new Error(`unexpected field name ${u}`);continue}p=p.slice(r.length);const f=k.notEmpty((a=d.groups)==null?void 0:a.type);let m=o.get(p);switch(m===void 0&&(m={},o.set(p,m)),f){case"spec":m.spec=(l=s.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:l.getDataAsJson();break;case"data":m.hasData=!0,m.data=()=>s.traverseOrError({field:u,ignoreError:t});break}}const i=s.getInputsLocked();if(i)for(const[,u]of o)u.data===void 0&&(u.hasData=!1);return{locked:i,results:o}}function Xo(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const n=dn(s,e,!1,t);An(n.locked);const o={};for(const[i,c]of n.results){if(c.spec===void 0)throw new Error(`no spec for key ${i}`);if(c.hasData!==!0||c.data===void 0)throw new Error(`no data for key ${i}`);const a=c.data();if(a===void 0)throw new Error(`no data for key ${i}`);if(!a.ok)throw a.error;o[i]={id:r.length===0?Wo(c.spec,a.value):zo(r,i),spec:c.spec,data:a.value}}return o}class fr{constructor(e,t){C(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const n of t.values())for(const o of[n.prod,n.staging])if(o!==void 0){if(!o.locked){r=!1;break e}for(const i of o.results.values())if(i.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var o,i,c,a,l,u;const r=this.blocks.get(e);if(r===void 0)return;let n=(c=(i=(o=r.prod)==null?void 0:o.results)==null?void 0:i.get(t))==null?void 0:c.spec;if(n!==void 0||(n=(u=(l=(a=r.staging)==null?void 0:a.results)==null?void 0:l.get(t))==null?void 0:u.spec,n!==void 0))return n;r.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):r.staging.locked?r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var i,c,a;const r=this.blocks.get(e);if(r===void 0)return;const n=(c=(i=r.prod)==null?void 0:i.results)==null?void 0:c.get(t),o=(a=n==null?void 0:n.data)==null?void 0:a.call(n);if(n!==void 0&&n.spec!==void 0&&o!==void 0)return V.mapValueInVOE(o,l=>({id:Gr(e,t),spec:n.spec,data:l}));n!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const r=this.getDataOrErrorByRef(e,t);if(!(r===void 0||!r.ok))return r.value}getData(){const e=this.getDataWithErrors(),t=[];for(const r of e.entries)r.obj.id!==void 0&&r.obj.data.ok&&t.push({ref:r.ref,obj:{id:r.obj.id,spec:r.obj.spec,data:r.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,r;const n=i=>{r===void 0&&(r=i),t=!1},o=(i,c,a)=>{if(a.spec!==void 0&&a.hasData===!0&&a.data!==void 0){const l=a.data();l!==void 0?e.push({ref:Ue(i,c),obj:{id:l.ok?Gr(i,c):void 0,spec:a.spec,data:l}}):n(`no_data:${i}:${c}`)}};for(const[i,c]of this.blocks){const a=new Set;if(c.prod!==void 0){c.prod.locked||n(`prod_not_locked:${i}`);for(const[l,u]of c.prod.results)a.add(l),o(i,l,u)}if(c.staging!==void 0){c.staging.locked||n(`staging_not_locked:${i}`);for(const[l,u]of c.staging.results)a.has(l)||o(i,l,u)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const n=o=>{r===void 0&&(r=o),t=!1};for(const[o,i]of this.blocks){const c=new Set;if(i.staging!==void 0){i.staging.locked||n(`staging_not_locked:${o}`);for(const[a,l]of i.staging.results)l.spec!==void 0&&(e.push({ref:Ue(o,a),obj:l.spec}),c.add(a))}else n(`staging_not_rendered:${o}`);if(i.prod!==void 0){i.prod.locked||n(`prod_not_locked:${o}`);for(const[a,l]of i.prod.results)c.has(a)||l.spec!==void 0&&e.push({ref:Ue(o,a),obj:l.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const n=new Set,o=i=>{for(const[c,a]of i.results)n.has(c)||a.spec===void 0||(n.add(c),V.executePSpecPredicate(e,a.spec)&&t.push({label:r.info.label+" / "+c,ref:Ue(r.info.id,c),spec:a.spec}))};r.staging!==void 0&&o(r.staging),r.prod!==void 0&&o(r.prod)}return t}static create(e,t,r){const n=e.accessor(t).node(),o=k.notEmpty(n.getKeyValueAsJson(de)),c=sr(o).traverseIds("upstream",r),a=new Map;for(const l of ie(o)){if(!c.has(l.id))continue;const u=Jr(n.traverse({field:X(l.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,n.traverseOrError({field:X(l.id,"prodUiCtx"),stableIfNotFound:!0})),d=Jr(n.traverse({field:X(l.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,n.traverseOrError({field:X(l.id,"stagingUiCtx")}));a.set(l.id,{info:l,prod:u,staging:d})}return new fr(e,a)}}function Jr(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return dn(e.value,!1,!0)}function gr(s,e){return{blockId:e,args:o=>k.notEmpty(o.accessor(s).node().traverse({field:X(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),activeArgs:o=>{var i;return(i=o.accessor(s).node().traverse({field:X(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:i.getDataAsString()},uiState:o=>o.accessor(s).node().getKeyValueAsString(Qt(e)),blockMeta:o=>{const i=o.accessor(s).node(),c=k.notEmpty(i.getKeyValueAsJson(de)),a=new Map;for(const l of ie(c))a.set(l.id,l);return a}}}function pn(s,e){return{...gr(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:X(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:r.persist()},staging:t=>{var n;const r=(n=t.accessor(s).node({ignoreError:!0}).traverse({field:X(e,"stagingOutput"),ignoreError:!0}))==null?void 0:n.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>fr.create(t,s,e)}}function*ne(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*ne(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*ne(t);return;case"MakeArray":for(const t of s.template)yield*ne(t);return;case"GetJsonField":case"GetResourceField":yield*ne(s.source),yield*ne(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*ne(s.source),yield*ne(s.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"ExtractArchiveAndGetURL":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetProgressLogWithInfo":case"GetLogHandle":yield*ne(s.source);return;case"IsEmpty":yield*ne(s.arg);return;case"Not":yield*ne(s.operand);return;case"And":case"Or":yield*ne(s.operand1),yield*ne(s.operand2);return;default:k.assertNever(s)}}function Yo(s,e){const t={};for(const[r,n]of Object.entries(s))t[r]=e(n);return t}function Pe(s,e){return s===void 0?void 0:e(s)}function Qo(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function Zo(s){for(const e of ne(s))if(Qo(e))return!0;return!1}function Ye(s){return{type:"ReturnResult",result:s}}function A(s){return()=>Ye(s)}const ei=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return A(e)},ti=s=>{const e=s.source;if(e===void 0)return A(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return A(t)},ri=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?A(void 0):({cCtx:r})=>{var n;return Ye((n=r.accessor(e).node().traverse(t))==null?void 0:n.persist())}};function fn(s,e){const t={},r=s.length;for(let n=0;n<r;n++)t[String(n)]=e(s[n]);return t}function si(s,e){return t=>{const r=t.source;return r===void 0?A(void 0):()=>({type:"ScheduleSubroutine",subroutine:gn(r.length),args:fn(r,n=>B({...s,[e.itVar]:n},e.mapping))})}}function gn(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return A(t)}}function ni(s,e){return t=>{const r=t.source;if(r===void 0)return A(void 0);const n={};for(const[o,i]of Object.entries(r)){const c={...s,[e.itVar]:i};n[o]=B(c,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:oi,args:n})}}const oi=s=>A(s),ii=s=>{const e=s.arg;return A(e===void 0?void 0:e.length===0)},ai=s=>{const e=s.operand;return A(e===void 0?void 0:!e)},ci=s=>{const e=s.operand1,t=s.operand2;return A(e===void 0||t===void 0?void 0:e&&t)},li=s=>{const e=s.operand1,t=s.operand2;return A(e===void 0||t===void 0?void 0:e||t)},ui=s=>{const e=s.source;return e===void 0?A(void 0):({cCtx:t})=>{var r;return Ye((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},di=s=>{const e=s.source,t=s.field;return A(e===void 0||t===void 0?void 0:e[t])};function pi(s,e){return t=>{const r=t.source;return r===void 0?A(void 0):({cCtx:n})=>{const o=n.accessor(r).node(),i={};for(const c of o.listInputFields()){const a=o.traverse(c);if(a===void 0)i[c]=A(void 0);else{const l={...s,[e.itVar]:a.persist()};i[c]=B(l,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:fi,args:i}}}}const fi=s=>A(s),gi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:M.Computable.make(n=>r.blobDriver.getDownloadedBlob(n.accessor(t).node().resourceInfo),{postprocessValue:async n=>{if(n!==void 0)return await r.blobDriver.getContent(n.handle,s)}})})},hi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({cCtx:r,drivers:n})=>{const o=r.accessor(t).node().resourceInfo;return{type:"ScheduleComputable",computable:M.Computable.make(i=>n.blobDriver.getDownloadedBlob(o,i),{postprocessValue:async i=>i===void 0?void 0:(await n.blobDriver.getContent(i.handle,s)).toString()})}}},mi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:M.Computable.make(n=>r.blobDriver.getDownloadedBlob(n.accessor(t).node().resourceInfo,n),{postprocessValue:async n=>{if(n==null)return;const o=await r.blobDriver.getContent(n.handle,s);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},vi=s=>{const e=s.source;return e===void 0?A(void 0):t=>({type:"ScheduleComputable",computable:t.drivers.blobDriver.getDownloadedBlob(e)})},yi=s=>{const e=s.source;return e===void 0?A(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},wi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.blobToURLDriver.extractArchiveAndGetURL(t,s)})},bi=s=>{const e=s.source;return e===void 0?A(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},Si=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},Ri=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},ki=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLogWithInfo(t,s)})},Ci=s=>{const e=s.source;return e===void 0?A(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function B(s,e){switch(e.type){case"GetFromCtx":{const t=s[e.variable];return typeof t=="function"?r=>Ye(t(r.cCtx)):A(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:vn(t,s,e.cfg)});case"Immediate":return A(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:di,args:{source:B(s,e.source),field:B(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:si(s,e),args:{source:B(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:ni(s,e),args:{source:B(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:ei,args:Yo(e.template,t=>B(s,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:gn(e.template.length),args:fn(e.template,t=>B(s,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:ti,args:{source:B(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:ii,args:{arg:B(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:ai,args:{operand:B(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:ci,args:{operand1:B(s,e.operand1),operand2:B(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:li,args:{operand1:B(s,e.operand1),operand2:B(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:pi(s,e),args:{source:B(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:ri,args:{source:B(s,e.source),field:B(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:ui,args:{source:B(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:gi(e.range),args:{source:B(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:hi(e.range),args:{source:B(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:mi(e.range),args:{source:B(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:vi,args:{source:B(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:yi,args:{source:B(s,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:wi(e.format),args:{source:B(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:bi,args:{source:B(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:Si(e.lines),args:{source:B(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:Ri(e.patternToSearch),args:{source:B(s,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:ki(e.patternToSearch),args:{source:B(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:Ci,args:{source:B(s,e.source)}});default:return k.assertNever(e)}}const Pi=["$prod","$staging"];function Ei(s){return{$blockId:s.blockId,$args:e=>JSON.parse(s.args(e)),$ui:e=>{const t=s.uiState(e);return t!==void 0?JSON.parse(t):void 0},$prod:s.prod,$staging:s.staging}}const hn=Symbol(),mn="return",Oi={op:hn,arg:mn};function Ti(s){return s.op==hn&&s.arg==mn}function Ii(){return{pendingSubroutines:new Map}}function _r(s,e,t,r){const n=new Ms(t),o=(c,a)=>{if(Ti(c))return e.result=a,!1;const l=k.notEmpty(e.pendingSubroutines.get(c.op));if(c.arg in l.args)throw new Error("argument already set");return l.args[c.arg]=a,l.argCounter--,l.argCounter===0&&(e.pendingSubroutines.delete(c.op),n.push({destination:l.destination,operation:l.subroutine(l.args)})),!0},i=[];e:for(;n.length>0;){const c=n.shift(),a=c.operation(s);switch(a.type){case"ReturnResult":if(!o(c.destination,a.result))break e;break;case"ScheduleSubroutine":{const l=Symbol(),u=Object.entries(a.args),d=u.length;if(d===0)n.push({destination:c.destination,operation:a.subroutine({})});else{for(const[p,f]of u)n.push({destination:{op:l,arg:p},operation:f});e.pendingSubroutines.set(l,{argCounter:d,args:{},subroutine:a.subroutine,destination:c.destination})}}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:c.destination,computable:a.computable});break;default:k.assertNever(a)}}return i}function Fi(s,e,t,r={}){return vn(s,Ei(e),t,r)}function vn(s,e,t,r={}){const n=`${e.blockId}#`+_({ctx:Object.fromEntries(Object.entries(e).filter(([o])=>Pi.indexOf(o)===-1)),cfg:t});return M.Computable.makeRaw(o=>{const i={drivers:s,cCtx:o},c=Ii();return{ir:_r(i,c,[{destination:Oi,operation:B(e,t)}],!0),postprocessValue(l){const u=[];for(const m of l)u.push({destination:m.destination,operation:A(m.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},p=new Map;for(const[m,h]of c.pendingSubroutines)p.set(m,{...h,args:{...h.args}});const f={result:c.result,pendingSubroutines:p};if(_r(d,f,u,!1),!("result"in f))throw new Error("illegal cfg rendering stack state, no result");return f.result}}},{...r,key:n})}function Kr(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class $i{constructor(e,t,r,n){C(this,"computablesToResolve",{});C(this,"computableCtx");C(this,"accessors",new Map);C(this,"meta");C(this,"_resultPool");this.parent=e,this.blockCtx=t,this.env=r,this.computableCtx=n,this.meta=t.blockMeta(n)}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,n)=>{if(!this.accessors.has(r)){const o=this.blockCtx[n];if(o===void 0)throw new Error("Staging context not available");const i=o(this.computableCtx);i?this.accessors.set(r,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(r,void 0)}return this.accessors.get(r)?r:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...r){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...r))}getResourceType(e){return this.getAccessor(e).resourceType}getInputsLocked(e){return this.getAccessor(e).getInputsLocked()}getOutputsLocked(e){return this.getAccessor(e).getOutputsLocked()}getIsReadyOrError(e){return this.getAccessor(e).getIsReadyOrError()}getIsFinal(e){return this.getAccessor(e).getIsFinal()}getError(e){return this.wrapAccessor(this.getAccessor(e).getError())}listInputFields(e){return this.getAccessor(e).listInputFields()}listOutputFields(e){return this.getAccessor(e).listOutputFields()}listDynamicFields(e){return this.getAccessor(e).listDynamicFields()}getKeyValueBase64(e,t){return Kr(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return Kr(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r,...n){const o=this.getAccessor(e);if(!o.getIsReadyOrError())return;const i=Xo(o,t,r,n),c={};for(const[a,l]of Object.entries(i))c[a]=V.mapPObjectData(l,u=>this.wrapAccessor(u));return c}registerComputable(e,t){const r=`${e}_${te.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e,t){const r=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",M.Computable.make(n=>this.env.driverKit.blobDriver.getDownloadedBlob(r,n),{postprocessValue:async n=>{if(n!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(n.handle,t)).toString("utf-8")}}))}getBlobContentAsBase64(e,t){const r=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",M.Computable.make(n=>this.env.driverKit.blobDriver.getDownloadedBlob(r,n),{postprocessValue:async n=>{if(n!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(n.handle,t)).toString("base64")}}))}getDownloadedBlobContentHandle(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getDownloadedBlobContentHandle",this.env.driverKit.blobDriver.getDownloadedBlob(t))}getOnDemandBlobContentHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getOnDemandBlobContentHandle",this.env.driverKit.blobDriver.getOnDemandBlob(t))}extractArchiveAndGetURL(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("extractArchiveAndGetURL",this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(r,t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(r,t))}getProgressLog(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(r,t))}getProgressLogWithInfo(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLogWithInfo",this.env.driverKit.logDriver.getProgressLogWithInfo(r,t))}getLogHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getLogHandle",this.env.driverKit.logDriver.getLogHandle(t))}getBlockLabel(e){const t=this.meta.get(e);if(t===void 0)throw new Error(`Block ${e} not found.`);return t.label}get resultPool(){if(this._resultPool===void 0){if(this.computableCtx===void 0)throw new Error("can't use result pool in this context (most porbably called from the future mapper)");this._resultPool=k.notEmpty(this.blockCtx.getResultsPool,"getResultsPool")(this.computableCtx)}return this._resultPool}calculateOptions(e){return this.resultPool.calculateOptions(e)}getDataFromResultPool(){const e=this.resultPool.getData();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:V.mapPObjectData(t.obj,r=>this.wrapAccessor(r))}))}}getDataWithErrorsFromResultPool(){const e=this.resultPool.getDataWithErrors();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:{id:t.obj.id,spec:t.obj.spec,data:V.mapValueInVOE(t.obj.data,r=>this.wrapAccessor(r))}}))}}getSpecsFromResultPool(){const e=this.resultPool.getSpecs();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`specs_from_pool_incomplete:${e.instabilityMarker}`),e}getSpecFromResultPoolByRef(e,t){return this.resultPool.getSpecByRef(e,t)}getDataFromResultPoolByRef(e,t){return V.mapPObjectData(this.resultPool.getDataByRef(e,t),r=>this.wrapAccessor(r))}createPFrame(e){if(this.computableCtx===void 0)throw new Error("can't instantiate PFrames from this context (most porbably called from the future mapper)");return this.env.driverKit.pFrameDriver.createPFrame(e.map(t=>V.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}createPTable(e){if(this.computableCtx===void 0)throw new Error("can't instantiate PTable from this context (most porbably called from the future mapper)");return this.env.driverKit.pFrameDriver.createPTable(V.mapPTableDef(e,t=>V.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}transformInputPData(e){return typeof e=="string"?this.getAccessor(e):V.isDataInfo(e)?V.mapDataInfo(e,t=>this.getAccessor(t)):e}getCurrentUnstableMarker(){var e;return(e=this.computableCtx)==null?void 0:e.unstableMarker}logInfo(e){this.env.blockEventDispatcher.logInfo(this.blockCtx.blockId,e)}logWarn(e){this.env.blockEventDispatcher.logWarn(this.blockCtx.blockId,e)}logError(e){this.env.blockEventDispatcher.logError(this.blockCtx.blockId,e)}getAccessor(e){const t=this.accessors.get(e);if(t===void 0)throw new Error("No such accessor");return t}wrapAccessor(e){if(e!==void 0){const t=te.randomUUID();return this.accessors.set(t,e),t}}injectCtx(e){const t=this.parent,r=t.vm;ge.Scope.withScope(n=>{const o=this.blockCtx.args(this.computableCtx),i=this.blockCtx.activeArgs(this.computableCtx),c=this.blockCtx.uiState(this.computableCtx);r.setProp(e,"args",n.manage(r.newString(o))),c!==void 0&&r.setProp(e,"uiState",n.manage(r.newString(c))),i!==void 0&&r.setProp(e,"activeArgs",n.manage(r.newString(i)));const a=(l,u)=>{const d=(...p)=>{try{return u(...p)}catch(f){const m=t.errorRepo.setAndRecreateForQuickJS(f);throw r.newError(m)}};r.newFunction(l,d).consume(p=>r.setProp(e,l,p)),r.newFunction(l,u).consume(p=>r.setProp(e,l+"__internal__",p))};a("getAccessorHandleByName",l=>t.exportSingleValue(this.getAccessorHandleByName(r.getString(l)),void 0)),a("resolveWithCommon",(l,u,...d)=>t.exportSingleValue(this.resolveWithCommon(r.getString(l),t.importObjectViaJson(u),...d.map(p=>t.importObjectViaJson(p))),void 0)),a("getResourceType",l=>t.exportObjectViaJson(this.getResourceType(r.getString(l)),void 0)),a("getInputsLocked",l=>t.exportSingleValue(this.getInputsLocked(r.getString(l)),void 0)),a("getOutputsLocked",l=>t.exportSingleValue(this.getOutputsLocked(r.getString(l)),void 0)),a("getIsReadyOrError",l=>t.exportSingleValue(this.getIsReadyOrError(r.getString(l)),void 0)),a("getIsFinal",l=>t.exportSingleValue(this.getIsFinal(r.getString(l)),void 0)),a("getError",l=>t.exportSingleValue(this.getError(r.getString(l)),void 0)),a("listInputFields",l=>t.exportObjectViaJson(this.listInputFields(r.getString(l)),void 0)),a("listOutputFields",l=>t.exportObjectViaJson(this.listInputFields(r.getString(l)),void 0)),a("listDynamicFields",l=>t.exportObjectViaJson(this.listInputFields(r.getString(l)),void 0)),a("getKeyValueBase64",(l,u)=>t.exportSingleValue(this.getKeyValueBase64(r.getString(l),r.getString(u)),void 0)),a("getKeyValueAsString",(l,u)=>t.exportSingleValue(this.getKeyValueAsString(r.getString(l),r.getString(u)),void 0)),a("getDataBase64",l=>t.exportSingleValue(this.getDataBase64(r.getString(l)),void 0)),a("getDataAsString",l=>t.exportSingleValue(this.getDataAsString(r.getString(l)),void 0)),a("parsePObjectCollection",(l,u,d,...p)=>t.exportObjectUniversal(this.parsePObjectCollection(r.getString(l),r.dump(u),r.getString(d),...p.map(f=>r.getString(f))),void 0)),a("getBlobContentAsBase64",(l,u)=>t.exportSingleValue(this.getBlobContentAsBase64(r.getString(l),t.importObjectUniversal(u)),void 0)),a("getBlobContentAsString",(l,u)=>t.exportSingleValue(this.getBlobContentAsString(r.getString(l),t.importObjectUniversal(u)),void 0)),a("getDownloadedBlobContentHandle",l=>t.exportSingleValue(this.getDownloadedBlobContentHandle(r.getString(l)),void 0)),a("getOnDemandBlobContentHandle",l=>t.exportSingleValue(this.getOnDemandBlobContentHandle(r.getString(l)),void 0)),a("extractArchiveAndGetURL",(l,u)=>t.exportSingleValue(this.extractArchiveAndGetURL(r.getString(l),r.getString(u)),void 0)),a("getImportProgress",l=>t.exportSingleValue(this.getImportProgress(r.getString(l)),void 0)),a("getLastLogs",(l,u)=>t.exportSingleValue(this.getLastLogs(r.getString(l),r.getNumber(u)),void 0)),a("getProgressLog",(l,u)=>t.exportSingleValue(this.getProgressLog(r.getString(l),r.getString(u)),void 0)),a("getProgressLogWithInfo",(l,u)=>t.exportSingleValue(this.getProgressLogWithInfo(r.getString(l),r.getString(u)),void 0)),a("getLogHandle",l=>t.exportSingleValue(this.getLogHandle(r.getString(l)),void 0)),a("getBlockLabel",l=>t.exportSingleValue(this.getBlockLabel(r.getString(l)),void 0)),a("getDataFromResultPool",()=>t.exportObjectUniversal(this.getDataFromResultPool(),void 0)),a("getDataWithErrorsFromResultPool",()=>t.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),a("getSpecsFromResultPool",()=>t.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),a("calculateOptions",l=>t.exportObjectUniversal(this.calculateOptions(t.importObjectViaJson(l)),void 0)),a("getSpecFromResultPoolByRef",(l,u)=>t.exportObjectUniversal(this.getSpecFromResultPoolByRef(r.getString(l),r.getString(u)),void 0)),a("getDataFromResultPoolByRef",(l,u)=>t.exportObjectUniversal(this.getDataFromResultPoolByRef(r.getString(l),r.getString(u)),void 0)),a("createPFrame",l=>t.exportSingleValue(this.createPFrame(t.importObjectViaJson(l)),void 0)),a("createPTable",l=>t.exportSingleValue(this.createPTable(t.importObjectViaJson(l)),void 0)),a("getCurrentUnstableMarker",()=>t.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),a("logInfo",l=>{this.logInfo(r.getString(l))}),a("logWarn",l=>{this.logWarn(r.getString(l))}),a("logError",l=>{this.logError(r.getString(l))})})}}function Di(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}class De{constructor(e,t,r,n){C(this,"callbackRegistry");C(this,"fnJSONStringify");C(this,"fnJSONParse");C(this,"errorRepo",new Li);C(this,"computableHelper");if(this.scope=e,this.vm=t,this.deadlineSetter=r,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(o=>t.getProp(o,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(o=>t.getProp(o,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");n!==void 0&&(this.computableHelper=new $i(this,n.blockCtx,n.mlEnv,n.computableCtx)),this.injectCtx()}resetComputableCtx(){k.notEmpty(this.computableHelper,"Computable context helper is not initialized").resetComputableCtx()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.deadlineSetter({currentExecutionTarget:"evaluateBundle",deadline:Date.now()+1e4}),this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw De.cleanErrorContext(t),t}finally{this.deadlineSetter(void 0)}}runCallback(e,...t){try{return this.deadlineSetter({currentExecutionTarget:e,deadline:Date.now()+1e4}),ge.Scope.withScope(r=>{const n=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(n)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(n,this.vm.undefined,...t.map(o=>this.exportObjectUniversal(o,r)))))})}catch(r){throw De.cleanErrorContext(r),this.errorRepo.getOriginal(r)}finally{this.deadlineSetter(void 0)}}exportSingleValue(e,t){const r=this.tryExportSingleValue(e,t);if(r===void 0)throw new Error(`Can't export value: ${e===void 0?"undefined":JSON.stringify(e)}`);return r}tryExportSingleValue(e,t){let r,n=!1;switch(typeof e){case"string":r=this.vm.newString(e),n=!0;break;case"number":r=this.vm.newNumber(e),n=!0;break;case"undefined":r=this.vm.undefined;break;case"boolean":r=e?this.vm.true:this.vm.false;break;default:if(e===null){r=this.vm.null;break}if(Di(e)){r=this.vm.newArrayBuffer(e),n=!0;break}return}return n&&t!=null?t.manage(r):r}exportObjectUniversal(e,t){const r=this.tryExportSingleValue(e,t);return r!==void 0?r:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const r=this.vm.newString(JSON.stringify(e)).consume(n=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,n)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){if(e!==void 0)switch(this.vm.typeof(e)){case"undefined":return;case"boolean":case"number":case"string":return this.vm.dump(e);default:return this.importObjectViaJson(e)}}importObjectViaJson(e){const t=this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify,this.vm.undefined,e)).consume(r=>this.vm.getString(r));if(t!=="undefined")return JSON.parse(t)}injectCtx(){ge.Scope.withScope(e=>{const t=e.manage(this.vm.newObject());this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(V.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e)),this.computableHelper!==void 0&&this.computableHelper.injectCtx(t),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}class Li{constructor(){C(this,"errorIdToError",new Map)}setAndRecreateForQuickJS(e){const t=te.randomUUID();return this.errorIdToError.set(t,e),e instanceof Error?{name:`${e.name}/uuid:${t}`,message:e.message}:{name:`UnknownErrorQuickJS/uuid:${t}`,message:`${e}`}}getOriginal(e){if(!(e instanceof ge.errors.QuickJSUnwrapError))return console.warn("ErrorRepo: quickJSError is not a QuickJSUnwrapError",g.stringifyWithResourceId(e)),e;if(!("name"in e.cause))return console.warn("ErrorRepo: quickJSError.cause is not an Error",g.stringifyWithResourceId(e)),e;const t=e.cause.name,r=t.slice(t.indexOf("/uuid:")+6);if(!r)throw new Error(`ErrorRepo: quickJSError.cause.name does not contain errorId: ${t}, ${g.stringifyWithResourceId(e)}`);const n=this.errorIdToError.get(r);if(n===void 0)throw new Error(`ErrorRepo: errorId not found: ${r}, ${g.stringifyWithResourceId(e)}`);return new Nn.PlQuickJSError(e,n)}}function Le(s,e){return Pe(s.traverse({field:X(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),n=V.extractConfig(r.config);return{bpResourceId:t.resourceInfo.id,bpId:t.resourceInfo.id.toString(),info:r,cfg:n}})}const Me=process.env.MI_LOG_OUTPUT_STATUS;function Ai(s,e,t,r,n,o={}){const i=`${e.blockId}#lambda#${n}#${t.handle}`;return o={...o,key:i},o.mode===void 0&&t.retentive===!0&&(o.mode="StableOnlyRetentive"),M.Computable.makeRaw(c=>{const a=new ge.Scope;c.addOnDestroy(()=>a.dispose());const l=a.manage(s.quickJs.newRuntime());l.setMemoryLimit(1024*1024*8),l.setMaxStackSize(1024*320);let u;l.setInterruptHandler(()=>u===void 0?!1:Date.now()>u.deadline);const d=a.manage(l.newContext()),p=new De(a,d,h=>{u=h},{computableCtx:c,blockCtx:e,mlEnv:s});p.evaluateBundle(r.content);const f=p.runCallback(t.handle);p.resetComputableCtx();let m=0;return Me&&Me!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:p.computableHelper.computablesToResolve,postprocessValue:(h,{unstableMarker:R,stable:I})=>{for(const[L,q]of Object.entries(h))p.runCallback(L,q);const j=p.importObjectUniversal(f);return m++,Me&&(Me!=="unstable-only"||!I)&&console.log(I?`Stable output ${t.handle} calculated ${j!==void 0?"defined":"undefined"}; (#${m})`:`Unstable output ${t.handle}; marker = ${R}; ${j!==void 0?"defined":"undefined"} (#${m})`),j}}},o)}function Ni(s,e,t,...r){const n=new ge.Scope;try{const o=n.manage(s.newRuntime());o.setMemoryLimit(1024*1024*8),o.setMaxStackSize(1024*320);let i;o.setInterruptHandler(()=>i===void 0?!1:Date.now()>i.deadline);const c=n.manage(o.newContext()),a=new De(n,c,l=>{i=l});return a.evaluateBundle(t.content),a.importObjectUniversal(a.runCallback(e.handle,...r))}finally{n.dispose()}}function Bi(s){return V.isConfigLambda(s)?s.isActive===!0:Zo(s)}function Ee(s,e,t,r,n,o={}){if(V.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return Ai(s,e,t,r,n,o)}else return Fi(s.driverKit,e,t,o)}function ji(s,e){if(s===e)return!0;if(s===void 0||e===void 0)return!1;const t=Fr.omitBy((r,n)=>n.startsWith("__"));return Fr.isDeepEqual(t(s),t(e))}function xi(s,e,t){return M.Computable.make(r=>{var m,h,R,I,j,L,q,z;const n=r.accessor(s).node(),o=k.notEmpty(n.getKeyValueAsJson(lr)),i=k.notEmpty(n.getKeyValueAsJson(Fe)),c=k.notEmpty(n.getKeyValueAsJson($e)),a=k.notEmpty(n.getKeyValueAsJson(de)),l=k.notEmpty(n.getKeyValueAsJson(Ke)),u=new Map;for(const{id:T}of ie(a)){const N=n.traverse({field:X(T,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}),O=N.getDataAsJson();let G;const re=n.traverse({field:X(T,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(re!==void 0){const se=re.getDataAsJson(),H=n.getField({field:X(T,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),Y=n.getField({field:X(T,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});G={arguments:se,stale:!ji(O,se),outputError:H.error!==void 0||Y.error!==void 0||((m=H.value)==null?void 0:m.getError())!==void 0||((h=Y.value)==null?void 0:h.getError())!==void 0,outputsError:((R=H.error)==null?void 0:R.getDataAsString())??((j=(I=H.value)==null?void 0:I.getError())==null?void 0:j.getDataAsString()),exportsError:((L=Y.error)==null?void 0:L.getDataAsString())??((z=(q=Y.value)==null?void 0:q.getError())==null?void 0:z.getDataAsString()),finished:(H.value!==void 0&&H.value.getIsReadyOrError()||H.error!==void 0&&H.error.getIsReadyOrError())&&(Y.value!==void 0&&Y.value.getIsReadyOrError()||Y.error!==void 0&&Y.error.getIsReadyOrError())}}u.set(T,{currentArguments:O,prod:G,argsRid:N.resourceInfo.id})}const d=Je(a,T=>{const N=Le(n,T),O=u.get(T),G=O.currentArguments;return{args:G,enrichmentTargets:t.projectHelper.getEnrichmentTargets(()=>N.cfg,()=>G,{argsRid:O.argsRid,blockPackRid:N.bpResourceId})}}),p=new Set(l.blocksInLimbo),f=[...ie(a)].map(({id:T,label:N,renderingMode:O})=>{var w,P,$,F,x;const G=k.notEmpty(u.get(T)),re=k.notEmpty(d.nodes.get(T));let se="NotCalculated";G.prod!==void 0&&(p.has(T)?se="Limbo":se=G.prod.finished?"Done":"Running");const H=Le(n,T),{sections:Y,title:b,inputsValid:y,sdkVersion:E}=Pe(H,({bpId:J,cfg:U})=>{const ue=gr(s,T);return{sections:Ee(t,ue,U.sections,U.code,J).wrap({recover:Re=>(t.logger.error("Error in block model sections"),t.logger.error(Re),[])}),title:Pe(U.title,Re=>Ee(t,ue,Re,U.code,J).wrap({recover:Tn=>(t.logger.error("Error in block model title"),t.logger.error(Tn),"Invalid title")})),inputsValid:Ee(t,ue,U.inputsValid,U.code,J).wrap({recover:Re=>(t.logger.error("Error in block model argsValid"),t.logger.error(Re),!1)}),sdkVersion:U.sdkVersion}})||{},v=n.traverse({field:X(T,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),S=Pe(H,({info:J})=>t.blockUpdateWatcher.get({currentSpec:J.source,settings:v}));return{projectResourceId:g.resourceIdToString(s.rid),id:T,label:b??N,title:b??N,renderingMode:O,stale:((w=G.prod)==null?void 0:w.stale)!==!1||se==="Limbo",missingReference:re.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",T)],downstreams:[...d.traverseIdsExcludingRoots("downstream",T)],calculationStatus:se,outputErrors:((P=G.prod)==null?void 0:P.outputError)===!0,outputsError:($=G.prod)==null?void 0:$.outputsError,exportsError:(F=G.prod)==null?void 0:F.exportsError,settings:v,sections:Y,inputsValid:y,updateInfo:{},currentBlockPack:(x=H==null?void 0:H.info)==null?void 0:x.source,updates:S,sdkVersion:E,navigationState:e.getState(T)}});return{meta:c,created:new Date(o),lastModified:new Date(i),authorMarker:n.getKeyValueAsJson(er),blocks:f}},{postprocessValue:r=>{const n=new Set,o=new Set;return{...r,blocks:r.blocks.map(i=>{var u,d;i.inputsValid||n.add(i.id),i.stale&&o.add(i.id);const c=i.stale||i.upstreams.findIndex(p=>o.has(p))!==-1,a=(c||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(p=>n.has(p))===-1,l={...i,canRun:a,stale:c,updateSuggestions:((u=i.updates)==null?void 0:u.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete l.updates,l})}}}).withStableType()}function Vi(s,e){const t=s.node();if(g.resourceTypesEqual(t.resourceType,dr)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.frontendDownloadDriver.getPath(new URL(r.url)).withStableType()}else if(g.resourceTypesEqual(t.resourceType,pr)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.signer.verify(r.path,r.signature,`Frontend path signature mismatch for: ${r.path}`),r.path}else throw new Error(`Unsupported resource type: ${JSON.stringify(t.resourceType)}`)}function Ui(s,e){if(s!==void 0)return M.Computable.make(t=>Vi(t.accessor(s),e),{postprocessValue:t=>{if(t!==void 0){if(typeof t=="string")return t;if(t.error!==void 0)throw new Error(t.error);return t.path}}}).withStableType()}function qi(s,e,t){return M.Computable.make(r=>{var c;const n=r.accessor(s).node(),o=Le(n,e),i=(c=n.traverse({field:X(e,"blockPack"),assertFieldType:"Dynamic"},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:cn,assertFieldType:"Input"}))==null?void 0:c.persist();return{path:Ui(i,t),sdkVersion:o==null?void 0:o.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function yn(s,e,t){if(t===void 0)return M.Computable.make(i=>yn(s,e,i),{key:`inputs#${g.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),n=gr(s,e),o=n.uiState(t);return{author:r.getKeyValueAsJson(Zt(e)),args:k.deepFreeze(JSON.parse(n.args(t))),ui:o!==void 0?k.deepFreeze(JSON.parse(o)):void 0}}function Mi(s,e,t){return M.Computable.make(r=>{const n=r.accessor(s).node(),o=pn(s,e);return Pe(Le(n,e),({cfg:i,bpId:c})=>{const a={};for(const[l,u]of Object.entries(i.outputs)){const d=Ee(t,o,u,i.code,c);a[l]=M.Computable.wrapError(d,1)}return a})},{key:"outputs#"+g.resourceIdToString(s.rid)+"#"+e}).withStableType()}function Gi(s,e){return M.Computable.make(t=>{const r=t.accessor(s).node(),n=k.notEmpty(r.getKeyValueAsJson(de)),o=[];for(const{id:i}of ie(n)){const c=Le(r,i);if(c===void 0)continue;const a=Object.entries(c.cfg.outputs).map(([,u])=>u).filter(u=>Bi(u)).map(u=>u);if(a.length===0)continue;const l=pn(r.persist(),i);for(const u of a)o.push(M.Computable.wrapError(Ee(e,l,u,c.cfg.code,c.bpId)))}return o})}class Ji{constructor(){C(this,"states",new Map)}setState(e,t){const r=this.states.get(e);if(r===void 0){this.states.set(e,{state:t,change:new M.ChangeSource});return}r.state={...t},r.change.markChanged()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...V.DefaultNavigationState},change:new M.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return M.Computable.make(t=>this.readState(t,e),{key:`navigationState#${e}`})}deleteBlock(e){const t=this.states.get(e);t!==void 0&&(this.states.delete(e),t.change.markChanged())}}function _i(s){return M.Computable.make(e=>{const t=e.accessor(s).node(),r=k.notEmpty(t.getKeyValueAsJson(de));return{listOfBlocks:[...ie(r)].map(n=>n.id)}})}function Hr(s){return JSON.stringify(s,(e,t)=>typeof t=="bigint"?g.resourceIdToString(t):ArrayBuffer.isView(t)||t instanceof Int8Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array||t instanceof Float64Array||t instanceof BigInt64Array||t instanceof BigUint64Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"):Buffer.isBuffer(t)?t.toString("base64"):t)}class Qe{constructor(e,t,r){C(this,"rid");C(this,"overview");C(this,"overviewLight");C(this,"navigationStates",new Ji);C(this,"blockComputables",new Map);C(this,"blockFrontends",new Map);C(this,"activeConfigs");C(this,"refreshLoopResult");C(this,"abortController",new AbortController);C(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=xi(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.overviewLight=_i(r.entry()).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=Gi(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await qe(this.env.projectHelper,this.env.pl,this.rid,r=>{r.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await Gs.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal);const e=await this.overviewLight.getValue(),t=new Set(e.listOfBlocks);for(const r of this.blockComputables.keys())if(!t.has(r)){const n=this.blockComputables.get(r);n!=null&&n.fullState.resetState(),this.blockComputables.set(r,null)}}catch(e){if(g.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!g.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,n=void 0,o=te.randomUUID()){const i=await this.env.bpPreparer.prepare(t),c=await this.env.bpPreparer.getBlockConfigContainer(t),a=V.extractConfig(c);return await ae(this.env.projectHelper,this.env.pl,this.rid,n,l=>l.addBlock({id:o,label:e,renderingMode:a.renderingMode},{args:_(a.initialArgs),uiState:_(a.initialUiState),blockPack:i},r)),await this.projectTree.refreshState(),o}async updateBlockPack(e,t,r=!1,n){const o=await this.env.bpPreparer.prepare(t),i=V.extractConfig(await this.env.bpPreparer.getBlockConfigContainer(t));await ae(this.env.projectHelper,this.env.pl,this.rid,n,c=>c.migrateBlockPack(e,o,r?{args:_(i.initialArgs),uiState:_(i.initialUiState)}:void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await ae(this.env.projectHelper,this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await ae(this.env.projectHelper,this.env.pl,this.rid,t,r=>{const n=r.structure;if(n.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const o=n.groups[0];if(o.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${o.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const i={groups:[{id:o.id,label:o.label,blocks:e.map(c=>{const a=o.blocks.find(l=>l.id===c);if(a===void 0)throw new Error(`Can't find block: ${c}`);return a})}]};r.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await qe(this.env.projectHelper,this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await qe(this.env.projectHelper,this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await ae(this.env.projectHelper,this.env.pl,this.rid,r,n=>n.setArgs([{blockId:e,args:_(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await ae(this.env.projectHelper,this.env.pl,this.rid,r,n=>n.setUiState(e,t===void 0?void 0:_(t))),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,n){await ae(this.env.projectHelper,this.env.pl,this.rid,n,o=>{o.setArgs([{blockId:e,args:_(t)}]),o.setUiState(e,_(r))}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await ae(this.env.projectHelper,this.env.pl,this.rid,void 0,r=>{r.setBlockSettings(e,t)}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async r=>{const n=g.ensureResourceIdNotNull((await r.getField(g.field(this.rid,X(e,"blockPack")))).value),o=g.ensureResourceIdNotNull((await r.getField(g.field(n,g.Pl.HolderRefField))).value),i=await r.getResourceData(o,!1),c=V.extractConfig(k.cachedDeserialize(k.notEmpty(i.data)).config);await ae(this.env.projectHelper,r,this.rid,t,a=>{a.setArgs([{blockId:e,args:_(c.initialArgs)}]),a.setUiState(e,_(c.initialUiState))}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===null)throw new Error(`Block ${e} is deleted`);if(t===void 0){const r=Mi(this.projectTree.entry(),e,this.env),o={fullState:M.Computable.make(i=>({argsAndUiState:yn(this.projectTree.entry(),e,i),outputs:r,navigationState:this.navigationStates.getState(e),overview:this.overview}),{postprocessValue:i=>{var u,d,p;const c=(p=(d=(u=i.overview)==null?void 0:u.blocks)==null?void 0:d.find(f=>f.id==e))==null?void 0:p.sdkVersion,l=c&&Hi(c)&&i.outputs!==void 0?zi(i.outputs):i.outputs;return{...i.argsAndUiState,outputs:l,navigationState:i.navigationState}}}).withPreCalculatedValueTree()};return this.blockComputables.set(e,o),o}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=qi(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,r),r}return t}async destroy(){this.destroyed=!0,this.abortController.abort(),await this.refreshLoopResult,await this.projectTree.terminate(),this.overview.resetState(),this.blockFrontends.forEach(e=>e.resetState()),this.blockComputables.forEach(e=>{e!==null&&e.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){await qe(e.projectHelper,e.pl,t,n=>{});const r=await _e.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:Ki},e.logger);if(e.ops.debugOps.dumpInitialTreeState){const n=r.dumpState();n.sort((i,c)=>{var a,l;return(((a=c.data)==null?void 0:a.byteLength)??0)-(((l=i.data)==null?void 0:l.byteLength)??0)});const o=_e.treeDumpStats(n);await Ie.writeFile(`${g.resourceIdToString(t)}.json`,Hr(n)),await Ie.writeFile(`${g.resourceIdToString(t)}.stats.json`,Hr(o))}return new Qe(e,t,r)}}function Ki(s){switch(s.type.name){case"BlockPackCustom":return s.fields.filter(e=>e.name!=="template");case"UserProject":return s.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return s.fields}}function Hi(s){return!Wi(s,"1.26.0")}function Wi(s,e){const t=s.split(".").map(Number),r=e.split(".").map(Number);return t[0]>r[0]||t[0]===r[0]&&t[1]>r[1]||t[0]===r[0]&&t[1]===r[1]&&t[2]>r[2]}function zi(s){const e={};for(const[t,r]of Object.entries(s)){if(r.ok){e[t]=r;continue}e[t]={ok:!1,errors:r.errors.map(n=>typeof n=="string"?n:n.type=="PlError"&&n.fullMessage!==void 0?n.fullMessage:n.message),moreErrors:r.moreErrors}}return e}const hr={logger:new k.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:8*1024*1024*1024,rangesCacheMaxSizeBytes:8*1024*1024*1024,nConcurrentDownloads:10},downloadBlobToURLDriverOps:{cacheSoftSizeBytes:1*1024*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}};function mr(s){return{blobDownloadPath:K.join(s,"download"),blobDownloadRangesCachePath:K.join(s,"downloadRangesCache"),downloadBlobToURLPath:K.join(s,"downloadToURL"),pframesSpillPath:K.join(s,"pframes")}}const wn={...hr,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500,initialTreeLoadingTimeout:100*60*60*1e3},debugOps:{dumpInitialTreeState:!1},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function bn(s){return{...mr(s),frontendDownloadPath:K.join(s,"frontend")}}function Xi(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Ge={exports:{}},at,Wr;function Ze(){if(Wr)return at;Wr=1;const s="2.0.0",e=256,t=Number.MAX_SAFE_INTEGER||9007199254740991,r=16,n=e-6;return at={MAX_LENGTH:e,MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_SAFE_INTEGER:t,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:s,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},at}var ct,zr;function et(){return zr||(zr=1,ct=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{}),ct}var Xr;function Ne(){return Xr||(Xr=1,function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:n}=Ze(),o=et();e=s.exports={};const i=e.re=[],c=e.safeRe=[],a=e.src=[],l=e.safeSrc=[],u=e.t={};let d=0;const p="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",n],[p,r]],m=R=>{for(const[I,j]of f)R=R.split(`${I}*`).join(`${I}{0,${j}}`).split(`${I}+`).join(`${I}{1,${j}}`);return R},h=(R,I,j)=>{const L=m(I),q=d++;o(R,q,I),u[R]=q,a[q]=I,l[q]=L,i[q]=new RegExp(I,j?"g":void 0),c[q]=new RegExp(L,j?"g":void 0)};h("NUMERICIDENTIFIER","0|[1-9]\\d*"),h("NUMERICIDENTIFIERLOOSE","\\d+"),h("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),h("MAINVERSION",`(${a[u.NUMERICIDENTIFIER]})\\.(${a[u.NUMERICIDENTIFIER]})\\.(${a[u.NUMERICIDENTIFIER]})`),h("MAINVERSIONLOOSE",`(${a[u.NUMERICIDENTIFIERLOOSE]})\\.(${a[u.NUMERICIDENTIFIERLOOSE]})\\.(${a[u.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASEIDENTIFIER",`(?:${a[u.NUMERICIDENTIFIER]}|${a[u.NONNUMERICIDENTIFIER]})`),h("PRERELEASEIDENTIFIERLOOSE",`(?:${a[u.NUMERICIDENTIFIERLOOSE]}|${a[u.NONNUMERICIDENTIFIER]})`),h("PRERELEASE",`(?:-(${a[u.PRERELEASEIDENTIFIER]}(?:\\.${a[u.PRERELEASEIDENTIFIER]})*))`),h("PRERELEASELOOSE",`(?:-?(${a[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${a[u.PRERELEASEIDENTIFIERLOOSE]})*))`),h("BUILDIDENTIFIER",`${p}+`),h("BUILD",`(?:\\+(${a[u.BUILDIDENTIFIER]}(?:\\.${a[u.BUILDIDENTIFIER]})*))`),h("FULLPLAIN",`v?${a[u.MAINVERSION]}${a[u.PRERELEASE]}?${a[u.BUILD]}?`),h("FULL",`^${a[u.FULLPLAIN]}$`),h("LOOSEPLAIN",`[v=\\s]*${a[u.MAINVERSIONLOOSE]}${a[u.PRERELEASELOOSE]}?${a[u.BUILD]}?`),h("LOOSE",`^${a[u.LOOSEPLAIN]}$`),h("GTLT","((?:<|>)?=?)"),h("XRANGEIDENTIFIERLOOSE",`${a[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h("XRANGEIDENTIFIER",`${a[u.NUMERICIDENTIFIER]}|x|X|\\*`),h("XRANGEPLAIN",`[v=\\s]*(${a[u.XRANGEIDENTIFIER]})(?:\\.(${a[u.XRANGEIDENTIFIER]})(?:\\.(${a[u.XRANGEIDENTIFIER]})(?:${a[u.PRERELEASE]})?${a[u.BUILD]}?)?)?`),h("XRANGEPLAINLOOSE",`[v=\\s]*(${a[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[u.XRANGEIDENTIFIERLOOSE]})(?:${a[u.PRERELEASELOOSE]})?${a[u.BUILD]}?)?)?`),h("XRANGE",`^${a[u.GTLT]}\\s*${a[u.XRANGEPLAIN]}$`),h("XRANGELOOSE",`^${a[u.GTLT]}\\s*${a[u.XRANGEPLAINLOOSE]}$`),h("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),h("COERCE",`${a[u.COERCEPLAIN]}(?:$|[^\\d])`),h("COERCEFULL",a[u.COERCEPLAIN]+`(?:${a[u.PRERELEASE]})?(?:${a[u.BUILD]})?(?:$|[^\\d])`),h("COERCERTL",a[u.COERCE],!0),h("COERCERTLFULL",a[u.COERCEFULL],!0),h("LONETILDE","(?:~>?)"),h("TILDETRIM",`(\\s*)${a[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",h("TILDE",`^${a[u.LONETILDE]}${a[u.XRANGEPLAIN]}$`),h("TILDELOOSE",`^${a[u.LONETILDE]}${a[u.XRANGEPLAINLOOSE]}$`),h("LONECARET","(?:\\^)"),h("CARETTRIM",`(\\s*)${a[u.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",h("CARET",`^${a[u.LONECARET]}${a[u.XRANGEPLAIN]}$`),h("CARETLOOSE",`^${a[u.LONECARET]}${a[u.XRANGEPLAINLOOSE]}$`),h("COMPARATORLOOSE",`^${a[u.GTLT]}\\s*(${a[u.LOOSEPLAIN]})$|^$`),h("COMPARATOR",`^${a[u.GTLT]}\\s*(${a[u.FULLPLAIN]})$|^$`),h("COMPARATORTRIM",`(\\s*)${a[u.GTLT]}\\s*(${a[u.LOOSEPLAIN]}|${a[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",h("HYPHENRANGE",`^\\s*(${a[u.XRANGEPLAIN]})\\s+-\\s+(${a[u.XRANGEPLAIN]})\\s*$`),h("HYPHENRANGELOOSE",`^\\s*(${a[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${a[u.XRANGEPLAINLOOSE]})\\s*$`),h("STAR","(<|>)?=?\\s*\\*"),h("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),h("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}(Ge,Ge.exports)),Ge.exports}var lt,Yr;function vr(){if(Yr)return lt;Yr=1;const s=Object.freeze({loose:!0}),e=Object.freeze({});return lt=r=>r?typeof r!="object"?s:r:e,lt}var ut,Qr;function Sn(){if(Qr)return ut;Qr=1;const s=/^[0-9]+$/,e=(r,n)=>{const o=s.test(r),i=s.test(n);return o&&i&&(r=+r,n=+n),r===n?0:o&&!i?-1:i&&!o?1:r<n?-1:1};return ut={compareIdentifiers:e,rcompareIdentifiers:(r,n)=>e(n,r)},ut}var dt,Zr;function ee(){if(Zr)return dt;Zr=1;const s=et(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:t}=Ze(),{safeRe:r,safeSrc:n,t:o}=Ne(),i=vr(),{compareIdentifiers:c}=Sn();class a{constructor(u,d){if(d=i(d),u instanceof a){if(u.loose===!!d.loose&&u.includePrerelease===!!d.includePrerelease)return u;u=u.version}else if(typeof u!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof u}".`);if(u.length>e)throw new TypeError(`version is longer than ${e} characters`);s("SemVer",u,d),this.options=d,this.loose=!!d.loose,this.includePrerelease=!!d.includePrerelease;const p=u.trim().match(d.loose?r[o.LOOSE]:r[o.FULL]);if(!p)throw new TypeError(`Invalid Version: ${u}`);if(this.raw=u,this.major=+p[1],this.minor=+p[2],this.patch=+p[3],this.major>t||this.major<0)throw new TypeError("Invalid major version");if(this.minor>t||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>t||this.patch<0)throw new TypeError("Invalid patch version");p[4]?this.prerelease=p[4].split(".").map(f=>{if(/^[0-9]+$/.test(f)){const m=+f;if(m>=0&&m<t)return m}return f}):this.prerelease=[],this.build=p[5]?p[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(u){if(s("SemVer.compare",this.version,this.options,u),!(u instanceof a)){if(typeof u=="string"&&u===this.version)return 0;u=new a(u,this.options)}return u.version===this.version?0:this.compareMain(u)||this.comparePre(u)}compareMain(u){return u instanceof a||(u=new a(u,this.options)),c(this.major,u.major)||c(this.minor,u.minor)||c(this.patch,u.patch)}comparePre(u){if(u instanceof a||(u=new a(u,this.options)),this.prerelease.length&&!u.prerelease.length)return-1;if(!this.prerelease.length&&u.prerelease.length)return 1;if(!this.prerelease.length&&!u.prerelease.length)return 0;let d=0;do{const p=this.prerelease[d],f=u.prerelease[d];if(s("prerelease compare",d,p,f),p===void 0&&f===void 0)return 0;if(f===void 0)return 1;if(p===void 0)return-1;if(p===f)continue;return c(p,f)}while(++d)}compareBuild(u){u instanceof a||(u=new a(u,this.options));let d=0;do{const p=this.build[d],f=u.build[d];if(s("build compare",d,p,f),p===void 0&&f===void 0)return 0;if(f===void 0)return 1;if(p===void 0)return-1;if(p===f)continue;return c(p,f)}while(++d)}inc(u,d,p){if(u.startsWith("pre")){if(!d&&p===!1)throw new Error("invalid increment argument: identifier is empty");if(d){const f=new RegExp(`^${this.options.loose?n[o.PRERELEASELOOSE]:n[o.PRERELEASE]}$`),m=`-${d}`.match(f);if(!m||m[1]!==d)throw new Error(`invalid identifier: ${d}`)}}switch(u){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",d,p);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",d,p);break;case"prepatch":this.prerelease.length=0,this.inc("patch",d,p),this.inc("pre",d,p);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",d,p),this.inc("pre",d,p);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const f=Number(p)?1:0;if(this.prerelease.length===0)this.prerelease=[f];else{let m=this.prerelease.length;for(;--m>=0;)typeof this.prerelease[m]=="number"&&(this.prerelease[m]++,m=-2);if(m===-1){if(d===this.prerelease.join(".")&&p===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(f)}}if(d){let m=[d,f];p===!1&&(m=[d]),c(this.prerelease[0],d)===0?isNaN(this.prerelease[1])&&(this.prerelease=m):this.prerelease=m}break}default:throw new Error(`invalid increment argument: ${u}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return dt=a,dt}var pt,es;function ye(){if(es)return pt;es=1;const s=ee();return pt=(t,r,n=!1)=>{if(t instanceof s)return t;try{return new s(t,r)}catch(o){if(!n)return null;throw o}},pt}var ft,ts;function Yi(){if(ts)return ft;ts=1;const s=ye();return ft=(t,r)=>{const n=s(t,r);return n?n.version:null},ft}var gt,rs;function Qi(){if(rs)return gt;rs=1;const s=ye();return gt=(t,r)=>{const n=s(t.trim().replace(/^[=v]+/,""),r);return n?n.version:null},gt}var ht,ss;function Zi(){if(ss)return ht;ss=1;const s=ee();return ht=(t,r,n,o,i)=>{typeof n=="string"&&(i=o,o=n,n=void 0);try{return new s(t instanceof s?t.version:t,n).inc(r,o,i).version}catch{return null}},ht}var mt,ns;function ea(){if(ns)return mt;ns=1;const s=ye();return mt=(t,r)=>{const n=s(t,null,!0),o=s(r,null,!0),i=n.compare(o);if(i===0)return null;const c=i>0,a=c?n:o,l=c?o:n,u=!!a.prerelease.length;if(!!l.prerelease.length&&!u){if(!l.patch&&!l.minor)return"major";if(l.compareMain(a)===0)return l.minor&&!l.patch?"minor":"patch"}const p=u?"pre":"";return n.major!==o.major?p+"major":n.minor!==o.minor?p+"minor":n.patch!==o.patch?p+"patch":"prerelease"},mt}var vt,os;function ta(){if(os)return vt;os=1;const s=ee();return vt=(t,r)=>new s(t,r).major,vt}var yt,is;function ra(){if(is)return yt;is=1;const s=ee();return yt=(t,r)=>new s(t,r).minor,yt}var wt,as;function sa(){if(as)return wt;as=1;const s=ee();return wt=(t,r)=>new s(t,r).patch,wt}var bt,cs;function na(){if(cs)return bt;cs=1;const s=ye();return bt=(t,r)=>{const n=s(t,r);return n&&n.prerelease.length?n.prerelease:null},bt}var St,ls;function ce(){if(ls)return St;ls=1;const s=ee();return St=(t,r,n)=>new s(t,n).compare(new s(r,n)),St}var Rt,us;function oa(){if(us)return Rt;us=1;const s=ce();return Rt=(t,r,n)=>s(r,t,n),Rt}var kt,ds;function ia(){if(ds)return kt;ds=1;const s=ce();return kt=(t,r)=>s(t,r,!0),kt}var Ct,ps;function yr(){if(ps)return Ct;ps=1;const s=ee();return Ct=(t,r,n)=>{const o=new s(t,n),i=new s(r,n);return o.compare(i)||o.compareBuild(i)},Ct}var Pt,fs;function aa(){if(fs)return Pt;fs=1;const s=yr();return Pt=(t,r)=>t.sort((n,o)=>s(n,o,r)),Pt}var Et,gs;function ca(){if(gs)return Et;gs=1;const s=yr();return Et=(t,r)=>t.sort((n,o)=>s(o,n,r)),Et}var Ot,hs;function tt(){if(hs)return Ot;hs=1;const s=ce();return Ot=(t,r,n)=>s(t,r,n)>0,Ot}var Tt,ms;function wr(){if(ms)return Tt;ms=1;const s=ce();return Tt=(t,r,n)=>s(t,r,n)<0,Tt}var It,vs;function Rn(){if(vs)return It;vs=1;const s=ce();return It=(t,r,n)=>s(t,r,n)===0,It}var Ft,ys;function kn(){if(ys)return Ft;ys=1;const s=ce();return Ft=(t,r,n)=>s(t,r,n)!==0,Ft}var $t,ws;function br(){if(ws)return $t;ws=1;const s=ce();return $t=(t,r,n)=>s(t,r,n)>=0,$t}var Dt,bs;function Sr(){if(bs)return Dt;bs=1;const s=ce();return Dt=(t,r,n)=>s(t,r,n)<=0,Dt}var Lt,Ss;function Cn(){if(Ss)return Lt;Ss=1;const s=Rn(),e=kn(),t=tt(),r=br(),n=wr(),o=Sr();return Lt=(c,a,l,u)=>{switch(a){case"===":return typeof c=="object"&&(c=c.version),typeof l=="object"&&(l=l.version),c===l;case"!==":return typeof c=="object"&&(c=c.version),typeof l=="object"&&(l=l.version),c!==l;case"":case"=":case"==":return s(c,l,u);case"!=":return e(c,l,u);case">":return t(c,l,u);case">=":return r(c,l,u);case"<":return n(c,l,u);case"<=":return o(c,l,u);default:throw new TypeError(`Invalid operator: ${a}`)}},Lt}var At,Rs;function la(){if(Rs)return At;Rs=1;const s=ee(),e=ye(),{safeRe:t,t:r}=Ne();return At=(o,i)=>{if(o instanceof s)return o;if(typeof o=="number"&&(o=String(o)),typeof o!="string")return null;i=i||{};let c=null;if(!i.rtl)c=o.match(i.includePrerelease?t[r.COERCEFULL]:t[r.COERCE]);else{const f=i.includePrerelease?t[r.COERCERTLFULL]:t[r.COERCERTL];let m;for(;(m=f.exec(o))&&(!c||c.index+c[0].length!==o.length);)(!c||m.index+m[0].length!==c.index+c[0].length)&&(c=m),f.lastIndex=m.index+m[1].length+m[2].length;f.lastIndex=-1}if(c===null)return null;const a=c[2],l=c[3]||"0",u=c[4]||"0",d=i.includePrerelease&&c[5]?`-${c[5]}`:"",p=i.includePrerelease&&c[6]?`+${c[6]}`:"";return e(`${a}.${l}.${u}${d}${p}`,i)},At}var Nt,ks;function ua(){if(ks)return Nt;ks=1;class s{constructor(){this.max=1e3,this.map=new Map}get(t){const r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){const o=this.map.keys().next().value;this.delete(o)}this.map.set(t,r)}return this}}return Nt=s,Nt}var Bt,Cs;function le(){if(Cs)return Bt;Cs=1;const s=/\s+/g;class e{constructor(y,E){if(E=n(E),y instanceof e)return y.loose===!!E.loose&&y.includePrerelease===!!E.includePrerelease?y:new e(y.raw,E);if(y instanceof o)return this.raw=y.value,this.set=[[y]],this.formatted=void 0,this;if(this.options=E,this.loose=!!E.loose,this.includePrerelease=!!E.includePrerelease,this.raw=y.trim().replace(s," "),this.set=this.raw.split("||").map(v=>this.parseRange(v.trim())).filter(v=>v.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const v=this.set[0];if(this.set=this.set.filter(S=>!h(S[0])),this.set.length===0)this.set=[v];else if(this.set.length>1){for(const S of this.set)if(S.length===1&&R(S[0])){this.set=[S];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let y=0;y<this.set.length;y++){y>0&&(this.formatted+="||");const E=this.set[y];for(let v=0;v<E.length;v++)v>0&&(this.formatted+=" "),this.formatted+=E[v].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(y){const v=((this.options.includePrerelease&&f)|(this.options.loose&&m))+":"+y,S=r.get(v);if(S)return S;const w=this.options.loose,P=w?a[l.HYPHENRANGELOOSE]:a[l.HYPHENRANGE];y=y.replace(P,H(this.options.includePrerelease)),i("hyphen replace",y),y=y.replace(a[l.COMPARATORTRIM],u),i("comparator trim",y),y=y.replace(a[l.TILDETRIM],d),i("tilde trim",y),y=y.replace(a[l.CARETTRIM],p),i("caret trim",y);let $=y.split(" ").map(U=>j(U,this.options)).join(" ").split(/\s+/).map(U=>se(U,this.options));w&&($=$.filter(U=>(i("loose invalid filter",U,this.options),!!U.match(a[l.COMPARATORLOOSE])))),i("range list",$);const F=new Map,x=$.map(U=>new o(U,this.options));for(const U of x){if(h(U))return[U];F.set(U.value,U)}F.size>1&&F.has("")&&F.delete("");const J=[...F.values()];return r.set(v,J),J}intersects(y,E){if(!(y instanceof e))throw new TypeError("a Range is required");return this.set.some(v=>I(v,E)&&y.set.some(S=>I(S,E)&&v.every(w=>S.every(P=>w.intersects(P,E)))))}test(y){if(!y)return!1;if(typeof y=="string")try{y=new c(y,this.options)}catch{return!1}for(let E=0;E<this.set.length;E++)if(Y(this.set[E],y,this.options))return!0;return!1}}Bt=e;const t=ua(),r=new t,n=vr(),o=rt(),i=et(),c=ee(),{safeRe:a,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:p}=Ne(),{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:m}=Ze(),h=b=>b.value==="<0.0.0-0",R=b=>b.value==="",I=(b,y)=>{let E=!0;const v=b.slice();let S=v.pop();for(;E&&v.length;)E=v.every(w=>S.intersects(w,y)),S=v.pop();return E},j=(b,y)=>(i("comp",b,y),b=T(b,y),i("caret",b),b=q(b,y),i("tildes",b),b=O(b,y),i("xrange",b),b=re(b,y),i("stars",b),b),L=b=>!b||b.toLowerCase()==="x"||b==="*",q=(b,y)=>b.trim().split(/\s+/).map(E=>z(E,y)).join(" "),z=(b,y)=>{const E=y.loose?a[l.TILDELOOSE]:a[l.TILDE];return b.replace(E,(v,S,w,P,$)=>{i("tilde",b,v,S,w,P,$);let F;return L(S)?F="":L(w)?F=`>=${S}.0.0 <${+S+1}.0.0-0`:L(P)?F=`>=${S}.${w}.0 <${S}.${+w+1}.0-0`:$?(i("replaceTilde pr",$),F=`>=${S}.${w}.${P}-${$} <${S}.${+w+1}.0-0`):F=`>=${S}.${w}.${P} <${S}.${+w+1}.0-0`,i("tilde return",F),F})},T=(b,y)=>b.trim().split(/\s+/).map(E=>N(E,y)).join(" "),N=(b,y)=>{i("caret",b,y);const E=y.loose?a[l.CARETLOOSE]:a[l.CARET],v=y.includePrerelease?"-0":"";return b.replace(E,(S,w,P,$,F)=>{i("caret",b,S,w,P,$,F);let x;return L(w)?x="":L(P)?x=`>=${w}.0.0${v} <${+w+1}.0.0-0`:L($)?w==="0"?x=`>=${w}.${P}.0${v} <${w}.${+P+1}.0-0`:x=`>=${w}.${P}.0${v} <${+w+1}.0.0-0`:F?(i("replaceCaret pr",F),w==="0"?P==="0"?x=`>=${w}.${P}.${$}-${F} <${w}.${P}.${+$+1}-0`:x=`>=${w}.${P}.${$}-${F} <${w}.${+P+1}.0-0`:x=`>=${w}.${P}.${$}-${F} <${+w+1}.0.0-0`):(i("no pr"),w==="0"?P==="0"?x=`>=${w}.${P}.${$}${v} <${w}.${P}.${+$+1}-0`:x=`>=${w}.${P}.${$}${v} <${w}.${+P+1}.0-0`:x=`>=${w}.${P}.${$} <${+w+1}.0.0-0`),i("caret return",x),x})},O=(b,y)=>(i("replaceXRanges",b,y),b.split(/\s+/).map(E=>G(E,y)).join(" ")),G=(b,y)=>{b=b.trim();const E=y.loose?a[l.XRANGELOOSE]:a[l.XRANGE];return b.replace(E,(v,S,w,P,$,F)=>{i("xRange",b,v,S,w,P,$,F);const x=L(w),J=x||L(P),U=J||L($),ue=U;return S==="="&&ue&&(S=""),F=y.includePrerelease?"-0":"",x?S===">"||S==="<"?v="<0.0.0-0":v="*":S&&ue?(J&&(P=0),$=0,S===">"?(S=">=",J?(w=+w+1,P=0,$=0):(P=+P+1,$=0)):S==="<="&&(S="<",J?w=+w+1:P=+P+1),S==="<"&&(F="-0"),v=`${S+w}.${P}.${$}${F}`):J?v=`>=${w}.0.0${F} <${+w+1}.0.0-0`:U&&(v=`>=${w}.${P}.0${F} <${w}.${+P+1}.0-0`),i("xRange return",v),v})},re=(b,y)=>(i("replaceStars",b,y),b.trim().replace(a[l.STAR],"")),se=(b,y)=>(i("replaceGTE0",b,y),b.trim().replace(a[y.includePrerelease?l.GTE0PRE:l.GTE0],"")),H=b=>(y,E,v,S,w,P,$,F,x,J,U,ue)=>(L(v)?E="":L(S)?E=`>=${v}.0.0${b?"-0":""}`:L(w)?E=`>=${v}.${S}.0${b?"-0":""}`:P?E=`>=${E}`:E=`>=${E}${b?"-0":""}`,L(x)?F="":L(J)?F=`<${+x+1}.0.0-0`:L(U)?F=`<${x}.${+J+1}.0-0`:ue?F=`<=${x}.${J}.${U}-${ue}`:b?F=`<${x}.${J}.${+U+1}-0`:F=`<=${F}`,`${E} ${F}`.trim()),Y=(b,y,E)=>{for(let v=0;v<b.length;v++)if(!b[v].test(y))return!1;if(y.prerelease.length&&!E.includePrerelease){for(let v=0;v<b.length;v++)if(i(b[v].semver),b[v].semver!==o.ANY&&b[v].semver.prerelease.length>0){const S=b[v].semver;if(S.major===y.major&&S.minor===y.minor&&S.patch===y.patch)return!0}return!1}return!0};return Bt}var jt,Ps;function rt(){if(Ps)return jt;Ps=1;const s=Symbol("SemVer ANY");class e{static get ANY(){return s}constructor(u,d){if(d=t(d),u instanceof e){if(u.loose===!!d.loose)return u;u=u.value}u=u.trim().split(/\s+/).join(" "),i("comparator",u,d),this.options=d,this.loose=!!d.loose,this.parse(u),this.semver===s?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(u){const d=this.options.loose?r[n.COMPARATORLOOSE]:r[n.COMPARATOR],p=u.match(d);if(!p)throw new TypeError(`Invalid comparator: ${u}`);this.operator=p[1]!==void 0?p[1]:"",this.operator==="="&&(this.operator=""),p[2]?this.semver=new c(p[2],this.options.loose):this.semver=s}toString(){return this.value}test(u){if(i("Comparator.test",u,this.options.loose),this.semver===s||u===s)return!0;if(typeof u=="string")try{u=new c(u,this.options)}catch{return!1}return o(u,this.operator,this.semver,this.options)}intersects(u,d){if(!(u instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new a(u.value,d).test(this.value):u.operator===""?u.value===""?!0:new a(this.value,d).test(u.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||u.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||u.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&u.operator.startsWith(">")||this.operator.startsWith("<")&&u.operator.startsWith("<")||this.semver.version===u.semver.version&&this.operator.includes("=")&&u.operator.includes("=")||o(this.semver,"<",u.semver,d)&&this.operator.startsWith(">")&&u.operator.startsWith("<")||o(this.semver,">",u.semver,d)&&this.operator.startsWith("<")&&u.operator.startsWith(">")))}}jt=e;const t=vr(),{safeRe:r,t:n}=Ne(),o=Cn(),i=et(),c=ee(),a=le();return jt}var xt,Es;function st(){if(Es)return xt;Es=1;const s=le();return xt=(t,r,n)=>{try{r=new s(r,n)}catch{return!1}return r.test(t)},xt}var Vt,Os;function da(){if(Os)return Vt;Os=1;const s=le();return Vt=(t,r)=>new s(t,r).set.map(n=>n.map(o=>o.value).join(" ").trim().split(" ")),Vt}var Ut,Ts;function pa(){if(Ts)return Ut;Ts=1;const s=ee(),e=le();return Ut=(r,n,o)=>{let i=null,c=null,a=null;try{a=new e(n,o)}catch{return null}return r.forEach(l=>{a.test(l)&&(!i||c.compare(l)===-1)&&(i=l,c=new s(i,o))}),i},Ut}var qt,Is;function fa(){if(Is)return qt;Is=1;const s=ee(),e=le();return qt=(r,n,o)=>{let i=null,c=null,a=null;try{a=new e(n,o)}catch{return null}return r.forEach(l=>{a.test(l)&&(!i||c.compare(l)===1)&&(i=l,c=new s(i,o))}),i},qt}var Mt,Fs;function ga(){if(Fs)return Mt;Fs=1;const s=ee(),e=le(),t=tt();return Mt=(n,o)=>{n=new e(n,o);let i=new s("0.0.0");if(n.test(i)||(i=new s("0.0.0-0"),n.test(i)))return i;i=null;for(let c=0;c<n.set.length;++c){const a=n.set[c];let l=null;a.forEach(u=>{const d=new s(u.semver.version);switch(u.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!l||t(d,l))&&(l=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${u.operator}`)}}),l&&(!i||t(i,l))&&(i=l)}return i&&n.test(i)?i:null},Mt}var Gt,$s;function ha(){if($s)return Gt;$s=1;const s=le();return Gt=(t,r)=>{try{return new s(t,r).range||"*"}catch{return null}},Gt}var Jt,Ds;function Rr(){if(Ds)return Jt;Ds=1;const s=ee(),e=rt(),{ANY:t}=e,r=le(),n=st(),o=tt(),i=wr(),c=Sr(),a=br();return Jt=(u,d,p,f)=>{u=new s(u,f),d=new r(d,f);let m,h,R,I,j;switch(p){case">":m=o,h=c,R=i,I=">",j=">=";break;case"<":m=i,h=a,R=o,I="<",j="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(n(u,d,f))return!1;for(let L=0;L<d.set.length;++L){const q=d.set[L];let z=null,T=null;if(q.forEach(N=>{N.semver===t&&(N=new e(">=0.0.0")),z=z||N,T=T||N,m(N.semver,z.semver,f)?z=N:R(N.semver,T.semver,f)&&(T=N)}),z.operator===I||z.operator===j||(!T.operator||T.operator===I)&&h(u,T.semver))return!1;if(T.operator===j&&R(u,T.semver))return!1}return!0},Jt}var _t,Ls;function ma(){if(Ls)return _t;Ls=1;const s=Rr();return _t=(t,r,n)=>s(t,r,">",n),_t}var Kt,As;function va(){if(As)return Kt;As=1;const s=Rr();return Kt=(t,r,n)=>s(t,r,"<",n),Kt}var Ht,Ns;function ya(){if(Ns)return Ht;Ns=1;const s=le();return Ht=(t,r,n)=>(t=new s(t,n),r=new s(r,n),t.intersects(r,n)),Ht}var Wt,Bs;function wa(){if(Bs)return Wt;Bs=1;const s=st(),e=ce();return Wt=(t,r,n)=>{const o=[];let i=null,c=null;const a=t.sort((p,f)=>e(p,f,n));for(const p of a)s(p,r,n)?(c=p,i||(i=p)):(c&&o.push([i,c]),c=null,i=null);i&&o.push([i,null]);const l=[];for(const[p,f]of o)p===f?l.push(p):!f&&p===a[0]?l.push("*"):f?p===a[0]?l.push(`<=${f}`):l.push(`${p} - ${f}`):l.push(`>=${p}`);const u=l.join(" || "),d=typeof r.raw=="string"?r.raw:String(r);return u.length<d.length?u:r},Wt}var zt,js;function ba(){if(js)return zt;js=1;const s=le(),e=rt(),{ANY:t}=e,r=st(),n=ce(),o=(d,p,f={})=>{if(d===p)return!0;d=new s(d,f),p=new s(p,f);let m=!1;e:for(const h of d.set){for(const R of p.set){const I=a(h,R,f);if(m=m||I!==null,I)continue e}if(m)return!1}return!0},i=[new e(">=0.0.0-0")],c=[new e(">=0.0.0")],a=(d,p,f)=>{if(d===p)return!0;if(d.length===1&&d[0].semver===t){if(p.length===1&&p[0].semver===t)return!0;f.includePrerelease?d=i:d=c}if(p.length===1&&p[0].semver===t){if(f.includePrerelease)return!0;p=c}const m=new Set;let h,R;for(const O of d)O.operator===">"||O.operator===">="?h=l(h,O,f):O.operator==="<"||O.operator==="<="?R=u(R,O,f):m.add(O.semver);if(m.size>1)return null;let I;if(h&&R){if(I=n(h.semver,R.semver,f),I>0)return null;if(I===0&&(h.operator!==">="||R.operator!=="<="))return null}for(const O of m){if(h&&!r(O,String(h),f)||R&&!r(O,String(R),f))return null;for(const G of p)if(!r(O,String(G),f))return!1;return!0}let j,L,q,z,T=R&&!f.includePrerelease&&R.semver.prerelease.length?R.semver:!1,N=h&&!f.includePrerelease&&h.semver.prerelease.length?h.semver:!1;T&&T.prerelease.length===1&&R.operator==="<"&&T.prerelease[0]===0&&(T=!1);for(const O of p){if(z=z||O.operator===">"||O.operator===">=",q=q||O.operator==="<"||O.operator==="<=",h){if(N&&O.semver.prerelease&&O.semver.prerelease.length&&O.semver.major===N.major&&O.semver.minor===N.minor&&O.semver.patch===N.patch&&(N=!1),O.operator===">"||O.operator===">="){if(j=l(h,O,f),j===O&&j!==h)return!1}else if(h.operator===">="&&!r(h.semver,String(O),f))return!1}if(R){if(T&&O.semver.prerelease&&O.semver.prerelease.length&&O.semver.major===T.major&&O.semver.minor===T.minor&&O.semver.patch===T.patch&&(T=!1),O.operator==="<"||O.operator==="<="){if(L=u(R,O,f),L===O&&L!==R)return!1}else if(R.operator==="<="&&!r(R.semver,String(O),f))return!1}if(!O.operator&&(R||h)&&I!==0)return!1}return!(h&&q&&!R&&I!==0||R&&z&&!h&&I!==0||N||T)},l=(d,p,f)=>{if(!d)return p;const m=n(d.semver,p.semver,f);return m>0?d:m<0||p.operator===">"&&d.operator===">="?p:d},u=(d,p,f)=>{if(!d)return p;const m=n(d.semver,p.semver,f);return m<0?d:m>0||p.operator==="<"&&d.operator==="<="?p:d};return zt=o,zt}var Xt,xs;function Sa(){if(xs)return Xt;xs=1;const s=Ne(),e=Ze(),t=ee(),r=Sn(),n=ye(),o=Yi(),i=Qi(),c=Zi(),a=ea(),l=ta(),u=ra(),d=sa(),p=na(),f=ce(),m=oa(),h=ia(),R=yr(),I=aa(),j=ca(),L=tt(),q=wr(),z=Rn(),T=kn(),N=br(),O=Sr(),G=Cn(),re=la(),se=rt(),H=le(),Y=st(),b=da(),y=pa(),E=fa(),v=ga(),S=ha(),w=Rr(),P=ma(),$=va(),F=ya(),x=wa(),J=ba();return Xt={parse:n,valid:o,clean:i,inc:c,diff:a,major:l,minor:u,patch:d,prerelease:p,compare:f,rcompare:m,compareLoose:h,compareBuild:R,sort:I,rsort:j,gt:L,lt:q,eq:z,neq:T,gte:N,lte:O,cmp:G,coerce:re,Comparator:se,Range:H,satisfies:Y,toComparators:b,maxSatisfying:y,minSatisfying:E,minVersion:v,validRange:S,outside:w,gtr:P,ltr:$,intersects:F,simplifyRange:x,subset:J,SemVer:t,re:s.re,src:s.src,tokens:s.t,SEMVER_SPEC_VERSION:e.SEMVER_SPEC_VERSION,RELEASE_TYPES:e.RELEASE_TYPES,compareIdentifiers:r.compareIdentifiers,rcompareIdentifiers:r.rcompareIdentifiers},Xt}var Ra=Sa();const ka=Xi(Ra),Ca={minDelay:1500},Pa="__no_updates__";class Ea extends M.PollComputablePool{constructor(t,r,n={}){super({...n,...Ca},r);C(this,"http");C(this,"preferredUpdateChannel");this.registryProvider=t,this.http=n.http,this.preferredUpdateChannel=n.preferredUpdateChannel}getKey(t){switch(t.currentSpec.type){case"dev-v1":return`dev_1_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"dev-v2":return`dev_2_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"from-registry-v2":return`from_registry_v2_${_(t)}`;default:return Pa}}async readValue(t){var r,n;try{const o=t.currentSpec;switch(o.type){case"dev-v1":try{const i=await cr(o.folder);return i===o.mtime?{suggestions:[]}:{mainSuggestion:{...o,mtime:i},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"dev-v2":try{const i=await Z.tryLoadPackDescription(o.folder,this.logger);if(i===void 0)return{suggestions:[]};const c=await ze(i);return c===o.mtime?{suggestions:[]}:{mainSuggestion:{...o,mtime:c},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:i,skipVersion:c}=t.settings;if(i==="patch")return{suggestions:[]};const a=this.registryProvider.getRegistry(o.registryUrl);let l=this.preferredUpdateChannel;if(l===void 0)if(o.channel===void 0)if(await a.getLatestOverview(o.id,Q.StableChannel))l=Q.StableChannel;else{if(await a.getLatestOverview(o.id,Q.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${Q.blockPackIdToString(o.id)}`),{suggestions:[]};l=Q.AnyChannel}else l=o.channel;const u=await a.getUpdateSuggestions(o.id,l);if(u===void 0||u.length===0)return{suggestions:[]};u.reverse();let d;switch(i){case void 0:d=u[0].update;break;case"major":d=(r=u.find(m=>m.type!=="major"))==null?void 0:r.update;break;case"minor":d=(n=u.find(m=>m.type==="patch"))==null?void 0:n.update;break}const p=u.map(({type:m,update:h})=>({type:m,update:{...o,id:{...o.id,version:h}}}));if(d===void 0)return{suggestions:p};if(c!==void 0&&ka.lte(d,c))return{suggestions:p};const f={...o,id:{...o.id,version:d}};return(async()=>{try{await a.getComponents(f.id)}catch(m){this.logger.warn(m)}})(),{suggestions:p,mainSuggestion:f}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(o){return this.logger.warn(o),{suggestions:[]}}}resultsEqual(t,r){return _(t)===_(r)}}class Vs{constructor(){C(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");t.refCount===0&&(this.resources.delete(e),(n=>n!=null&&typeof n[Symbol.dispose]=="function")(t.resource)&&t.resource[Symbol.dispose]())}acquire(e){const t=this.calculateParamsKey(e);let r=this.resources.get(t);r===void 0&&(r={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,r)),r.refCount++;let n=!1;return{resource:r.resource,key:t,unref:()=>{n||(r.refCount--,n=!0,this.check(t))}}}getByKey(e){if(!this.resources.has(e))throw new Error(`resource not found, key = ${e}`);return this.resources.get(e).resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}let ke;function fe(){return ke||(ke={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0,dumpInitialTreeState:process.env.MI_DUMP_INITIAL_TREE_STATE!==void 0},process.env.MI_LOG_TREE_STAT&&(ke.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),ke)}function Oe(s){return String(s.id)}const Oa=["Int","Long","Float","Double","String","Bytes"];function Yt(s){const e=[],t=[];for(const r of s)r.type==="bySingleColumn"?(e.push(r),t.push({...r,type:"bySingleColumnV2"})):t.push(r);if(e.length>0){const r=JSON.stringify(e);console.warn(`type overriten from 'bySingleColumn' to 'bySingleColumnV2' for filters: ${r}`)}return t}const Ce=(s,e)=>typeof e=="bigint"?e.toString():e;class Ta{constructor(e,t,r,n){C(this,"pFrame");C(this,"abortController",new AbortController);C(this,"blobIdToResource",new Map);C(this,"blobHandleComputables",new Map);C(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue()});C(this,"resolveBlob",async e=>{const t=this.getOrCreateComputableForBlob(e);return this.blobDriver.getLocalPath((await t.awaitStableValue()).handle)});C(this,"resolveBlobContent",async e=>{try{const t=this.getOrCreateComputableForBlob(e),r=this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);return await Ks.readFile(r)}catch(t){const r=JSON.stringify(t);throw console.log(`resolveBlobContent catched error: ${r}`),t}});this.blobDriver=e,this.logger=t,this.spillPath=r;const o=(c,a)=>this.logger[c](a);for(const c of n)for(const a of Vo(c.data))this.blobIdToResource.set(Oe(a),a);const i=[...new Map(n.map(c=>({...c,data:Uo(c.data,Oe)})).map(c=>[_(c),c])).values()];try{const c=new Js.PFrame(this.spillPath,o);c.setDataSource(this);for(const a of i)c.addColumnSpec(a.id,a.spec),c.setColumnData(a.id,a.data);this.pFrame=c}catch(c){throw new Error(`Rust PFrame creation failed, columns: ${JSON.stringify(i)}, error: ${c}`)}}getOrCreateComputableForBlob(e){let t=this.blobHandleComputables.get(e);if(t!==void 0)return t;const r=this.blobIdToResource.get(e);if(r===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(r).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}get disposeSignal(){return this.abortController.signal}[Symbol.dispose](){this.abortController.abort();for(const e of this.blobHandleComputables.values())e.resetState();this.pFrame.dispose()}}class Ia{constructor(e,t){this.table=e,this.abortController=t}get disposeSignal(){return this.abortController.signal}[Symbol.dispose](){this.abortController.abort(),this.table.then(e=>e.dispose())}}class kr{constructor(e,t,r){C(this,"pFrames");C(this,"pTables");C(this,"concurrencyLimiter");C(this,"getDataLimiter");this.blobDriver=e,this.logger=t,this.spillPath=r;const n=new k.ConcurrencyLimitingExecutor(1);this.concurrencyLimiter=n,this.getDataLimiter=new k.ConcurrencyLimitingExecutor(1),this.pFrames=new class extends Vs{constructor(o,i,c){super(),this.blobDriver=o,this.logger=i,this.spillPath=c}createNewResource(o){return fe().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,Ce)}`),new Ta(this.blobDriver,this.logger,this.spillPath,o)}calculateParamsKey(o){return $a(o)}}(this.blobDriver,this.logger,this.spillPath),this.pTables=new class extends Vs{constructor(o){super(),this.pFrames=o}createNewResource(o){const i=o.pFrameHandle;fe().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,Ce)}`);const c=this.pFrames.getByKey(i),a=new AbortController,l=AbortSignal.any([o.signal,a.signal,c.disposeSignal].filter(d=>!!d)),u=n.run(async()=>{const d=await c.pFrame.createTable({src:Te(o.def.src),filters:Yt(o.def.filters)},l);let p=d;if(o.def.sorting.length>0)try{p=await d.sort(o.def.sorting,l)}finally{d.dispose()}return p});return new Ia(u,a)}calculateParamsKey(o){return Fa(o)}}(this.pFrames)}async pprofDump(){return await Js.PFrame.pprofDump()}static async init(e,t,r){const n=Vn.resolve(r);return await k.emptyDir(n),new kr(e,t,n)}createPFrame(e,t){const r=e.filter(o=>Oa.find(i=>i===o.spec.valueType)).map(o=>V.mapPObjectData(o,i=>_e.isPlTreeNodeAccessor(i)?Ko(i):V.isDataInfo(i)?V.mapDataInfo(i,c=>c.resourceInfo):Ho(o.spec,i))),n=this.pFrames.acquire(r);return t.addOnDestroy(n.unref),n.key}createPTable(e,t,r){const n=this.createPFrame(V.extractAllColumns(e.src),t),o=V.mapPTableDef(e,c=>c.id),i=this.pTables.acquire({def:o,pFrameHandle:n,signal:r});return fe().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${n}; pTableHandle = ${JSON.stringify(i)}): ${JSON.stringify(V.mapPTableDef(e,c=>c.spec),Ce)}`),t.addOnDestroy(i.unref),i.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:[...new Map(t.compatibleWith.map(o=>[_(o),o])).values()],qualifications:[]}]:[]};return{hits:(await this.pFrames.getByKey(e).pFrame.findColumns(r)).hits.filter(o=>o.mappingVariants.length===0||o.mappingVariants.some(i=>i.qualifications.forHit.length===0&&i.qualifications.forQueries.every(c=>c.length===0))).map(o=>o.hit)}}async getColumnSpec(e,t){return await this.pFrames.getByKey(e).pFrame.getColumnSpec(t)}async listColumns(e){return await this.pFrames.getByKey(e).pFrame.listColumns()}async calculateTableData(e,t,r,n){return fe().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,Ce)}`),await this.concurrencyLimiter.run(async()=>{const o=this.pFrames.getByKey(e),i=AbortSignal.any([n,o.disposeSignal].filter(l=>!!l)),c=await o.pFrame.createTable({src:Te(t.src),filters:Yt(t.filters)},i);let a=c;if(t.sorting.length>0)try{a=await c.sort(t.sorting,i)}finally{c.dispose()}try{const l=a.getSpec(),u=await a.getData([...l.keys()],r,i);return l.map((d,p)=>({spec:d,data:u[p]}))}finally{a.dispose()}})}async getUniqueValues(e,t,r){return fe().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,Ce)}`),await this.concurrencyLimiter.run(async()=>{const n=this.pFrames.getByKey(e),o=AbortSignal.any([r,n.disposeSignal].filter(i=>!!i));return await n.pFrame.getUniqueValues({...t,filters:Yt(t.filters)},o)})}async getShape(e){return(await this.pTables.getByKey(e).table).getShape()}async getSpec(e){return(await this.pTables.getByKey(e).table).getSpec()}async getData(e,t,r,n){return await this.getDataLimiter.run(async()=>{const o=this.pTables.getByKey(e),i=await o.table,c=AbortSignal.any([n,o.disposeSignal].filter(a=>!!a));return await i.getData(t,r,c)})}}function Te(s){switch(s.type){case"column":return{type:"column",columnId:s.column};case"slicedColumn":return{type:"slicedColumn",columnId:s.column,newId:s.newId,axisFilters:s.axisFilters};case"inlineColumn":return{type:"inlineColumn",newId:s.column.id,spec:s.column.spec,dataInfo:{type:"Json",keyLength:s.column.spec.axesSpec.length,data:s.column.data.reduce((e,t)=>(e[JSON.stringify(t.key)]=t.val,e),{})}};case"inner":case"full":return{type:s.type,entries:s.entries.map(e=>Te(e))};case"outer":return{type:"outer",primary:Te(s.primary),secondary:s.secondary.map(e=>Te(e))};default:k.assertNever(s)}}function Fa(s){const e=te.createHash("sha256");return e.update(_(s)),e.digest().toString("hex")}function $a(s){const e=[...s].map(r=>V.mapPObjectData(r,n=>{let o;const i=n.type;switch(i){case"Json":o={type:n.type,keyLength:n.keyLength,payload:Object.entries(n.data).map(([c,a])=>({key:c,value:a}))};break;case"JsonPartitioned":o={type:n.type,keyLength:n.partitionKeyLength,payload:Object.entries(n.parts).map(([c,a])=>({key:c,value:Oe(a)}))};break;case"BinaryPartitioned":o={type:n.type,keyLength:n.partitionKeyLength,payload:Object.entries(n.parts).map(([c,a])=>({key:c,value:[Oe(a.index),Oe(a.values)]}))};break;default:throw Error(`unsupported resource type: ${JSON.stringify(i)}`)}return o.payload.sort((c,a)=>c.key.localeCompare(a.key)),o}));e.sort((r,n)=>r.id.localeCompare(n.id));const t=te.createHash("sha256");return t.update(_(e)),t.digest().toString("hex")}async function Pn(s,e,t){const r={...hr,...mr(e),...t},n=new k.HmacSha256Signer(r.localSecret),o=W.createDownloadClient(r.logger,s,r.localProjections),i=W.createLogsClient(s,r.logger),c=W.createUploadBlobClient(s,r.logger),a=W.createUploadProgressClient(s,r.logger),l=await W.DownloadDriver.init(r.logger,o,i,r.blobDownloadPath,r.blobDownloadRangesCachePath,n,r.blobDriverOps),u=new W.DownloadBlobToURLDriver(r.logger,n,o,r.downloadBlobToURLPath,r.downloadBlobToURLDriverOps),d=new W.UploadDriver(r.logger,n,c,a,r.uploadDriverOps),p=new W.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),f=new W.LogsDriver(r.logger,p,l),m=await W.LsDriver.init(r.logger,s,n,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),h=await kr.init(l,r.logger,r.pframesSpillPath);return{blobDriver:l,blobToURLDriver:u,logDriver:f,lsDriver:m,signer:n,uploadDriver:d,pFrameDriver:h}}class Da{constructor(e){C(this,"enrichmentTargetsCache",new qs.LRUCache({max:256,memoMethod:(e,t,{context:r})=>({value:this.calculateEnrichmentTargets(r)})}));this.quickJs=e}calculateEnrichmentTargets(e){const t=e.blockConfig();if(t.enrichmentTargets===void 0)return;const r=e.args();return Ni(this.quickJs,t.enrichmentTargets,t.code,r)}getEnrichmentTargets(e,t,r){const n={blockConfig:e,args:t};if(r===void 0)return this.calculateEnrichmentTargets(n);const o=`${r.argsRid}:${r.blockPackRid}`;return this.enrichmentTargetsCache.memo(o,{context:n}).value}}class Cr{constructor(e,t,r,n,o,i,c,a){C(this,"pl");C(this,"projectList");C(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=n,this.openedProjectsList=o,this.projectListTree=i,this.blockRegistryProvider=c,this.projectList=a,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=te.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async n=>{const o=await xo(n,e);return n.createField(g.field(this.projectListResourceId,t),"Dynamic",o),await n.commit(),await g.toGlobalResourceId(o)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await ae(this.env.projectHelper,this.pl,e,r,n=>{n.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(g.field(this.projectListResourceId,e)),await t.commit()}),await this.projectListTree.refreshState()}async projectIdToResourceId(e){return await this.pl.withReadTx("Project id to resource id",async t=>{const r=(await t.getField(g.field(this.projectListResourceId,e))).value;if(g.isNullResourceId(r))throw new Error("Unexpected project list structure.");return r})}async ensureProjectRid(e){return typeof e=="string"?await this.projectIdToResourceId(e):e}async openProject(e){const t=await this.ensureProjectRid(e);if(this.openedProjectsByRid.has(t))throw new Error(`Project ${t} already opened`);this.openedProjectsByRid.set(t,await Qe.init(this.env,t)),this.openedProjectsList.setValue([...this.openedProjectsByRid.keys()])}async closeProject(e){const t=this.openedProjectsByRid.get(e);if(t===void 0)throw new Error(`Project ${e} not found among opened projects`);this.openedProjectsByRid.delete(e),await t.destroy(),this.openedProjectsList.setValue([...this.openedProjectsByRid.keys()])}getOpenedProject(e){const t=this.openedProjectsByRid.get(e);if(t===void 0)throw new Error(`Project ${e} not found among opened projects`);return t}async close(){await Promise.all([...this.openedProjectsByRid.values()].map(e=>e.destroy())),await this.projectListTree.terminate(),await this.env.retryHttpDispatcher.destroy(),await this.pl.close()}async closeAndAwaitTermination(){await this.close()}static generateLocalSecret(){return k.HmacSha256Signer.generateSecret()}get blockEventDispatcher(){return this.env.blockEventDispatcher}static async init(e,t,r){const n={...wn,...bn(t),...r};n.defaultTreeOptions.logStat=fe().logTreeStats,n.debugOps.dumpInitialTreeState=fe().dumpInitialTreeState;const o=await e.withWriteTx("MLInitialization",async R=>{const I=g.field(R.clientRoot,co);R.createField(I,"Dynamic");const j=await R.getField(I);if(g.isNullResourceId(j.value)){const L=R.createEphemeral(Ys);return R.lock(L),R.setField(I,L),await R.commit(),await L.globalId}else return j.value}),i=n.logger,c=await Pn(e,t,n),a=new We.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),l=new Ws(a),u=new $o(l,c.signer,a),d=new W.DownloadUrlDriver(i,e.httpDispatcher,n.frontendDownloadPath),p=await ge.getQuickJS(),f={pl:e,blockEventDispatcher:new k.BlockEventDispatcher,signer:c.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:a,ops:n,bpPreparer:u,frontendDownloadDriver:d,driverKit:c,blockUpdateWatcher:new Ea(l,i,{minDelay:n.devBlockUpdateRecheckInterval,http:a,preferredUpdateChannel:n.preferredUpdateChannel}),quickJs:p,projectHelper:new Da(p)},m=new M.WatchableValue([]),h=await uo(e,o,m,f);return new Cr(f,c,c.signer,o,m,h.tree,l,h.computable)}}async function La(s,e){return await we(s.pingCheckDurationMs,s.maxPingsPerSecond,async()=>{const r=await new g.UnauthenticatedPlClient(e).ping();return JSON.stringify(r).slice(0,s.bodyLimit)+"..."})}async function Aa(s,e){return await we(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Be(new URL(s.blockOverviewPath,s.blockRegistryUrl),s,e))}async function Na(s,e){return await we(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Be(new URL(s.blockOverviewPath,s.blockGARegistryUrl),s,e))}async function Ba(s,e){return await we(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Be(new URL(s.blockUiPath,s.blockRegistryUrl),s,e))}async function ja(s,e){return await we(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Be(new URL(s.blockUiPath,s.blockGARegistryUrl),s,e))}async function xa(s,e){return await we(s.autoUpdateCdnDurationMs,s.maxAutoUpdateCdnChecksPerSecond,async()=>await Be(s.autoUpdateCdnUrl,s,e))}async function we(s,e,t){const r=Date.now(),n=[];for(;Us(r)<s;){const o=Date.now();let i;try{i={ok:!0,value:await t()}}catch(l){i={ok:!1,error:l}}const c=Us(o);n.push({elapsedMs:c,response:i});const a=1e3/e-c;a>0&&await Gs.setTimeout(a)}return n}async function Be(s,e,t){const{body:r,statusCode:n}=await We.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),o=await r.text();return{statusCode:n,beginningOfBody:o.slice(0,e.bodyLimit)+"..."}}function Us(s){return Date.now()-s}function me(s){const e=s.filter(i=>i.response.ok),t=s.length-e.length,{mean:r,median:n}=Va(s),o=`
2
2
  total: ${s.length};
3
3
  successes: ${e.length};
4
4
  errors: ${t};
5
5
  mean in ms: ${r};
6
- median in ms: ${o};
7
- `;return{ok:t===0,details:n}}function ll(s){const e=s.map(o=>o.elapsedMs).sort(),t=e.reduce((o,n)=>o+n)/e.length;let r;if(e.length>0){const o=Math.floor(e.length/2);r=e.length%2?e[o]:(e[o-1]+e[o])/2}return{mean:t,median:r}}async function ul(s,e,t){try{const r=await dl(s,e,t);return r!==`Hello, ${t}`?{status:"failed",message:`Template uploading failed: expected: ${t}, got: ${r}`}:{status:"ok",message:`Template uploading succeeded: ${r}`}}catch(r){return{status:"failed",message:`Template uploading failed: error occurred: ${r}`}}}async function dl(s,e,t){var o;const r=await ke(e,he.Templates["check_network.upload_template"],!0,n=>({name:n.createValue(g.Pl.JsonObject,JSON.stringify(t))}),["greeting"]);try{return JSON.parse(S.notEmpty((o=(await pe(e,r.greeting)).data)==null?void 0:o.toString()))}finally{r!=null&&await Ce(e,Object.values(r))}}async function pl(s,e,t,r,o,n){try{const i=await fl(s,e,t,r,o,n);return i.type.name!=="Blob"?{status:"failed",message:`File uploading failed: ${i.type.name}`}:{status:"ok",message:`File uploading succeeded: ${i.type.name}`}}catch(i){return{status:"failed",message:`File uploading failed: error occurred: ${i}`}}}async function fl(s,e,t,r,o,n){var a;const i=await t.getLocalFileHandle(n),c=await ke(o,he.Templates["check_network.upload_blob"],!0,l=>({file:l.createValue(g.Pl.JsonObject,JSON.stringify(i))}),["progress","file"]);try{const l=await pe(o,c.progress);if(J.isUpload(l)){const u=J.ImportFileHandleUploadData.parse(JSON.parse(S.notEmpty((a=l.data)==null?void 0:a.toString())));J.isSignMatch(e,u.localPath,u.pathSignature)&&await J.uploadBlob(s,r,l,u,()=>!1,{nPartsWithThisUploadSpeed:10,nPartsToIncreaseUpload:10,currentSpeed:10,maxSpeed:10})}return await pe(o,c.file)}finally{await Ce(o,Object.values(c))}}async function gl(s,e,t,r,o,n,i){try{const c=await hl(s,e,t,r,o,n);return c!==i?{status:"failed",message:`File downloading failed: expected: ${i}, got: ${c}`}:{status:"ok",message:`File downloading succeeded: ${c}`}}catch(c){return{status:"failed",message:`File downloading failed: error occurred: ${c}`}}}async function hl(s,e,t,r,o,n){var a;const i=await t.getLocalFileHandle(n),c=await ke(e,he.Templates["check_network.download_blob"],!0,l=>({file:l.createValue(g.Pl.JsonObject,JSON.stringify(i))}),["progress","file"]);try{const l=await pe(e,c.progress);await J.uploadBlob(s,r,l,J.ImportFileHandleUploadData.parse(JSON.parse(S.notEmpty((a=l.data)==null?void 0:a.toString()))),()=>!1,{nPartsWithThisUploadSpeed:1,nPartsToIncreaseUpload:1,currentSpeed:1,maxSpeed:1});const u=await pe(e,c.file),{content:d}=await o.downloadBlob(u);return await Js.text(d)}finally{await Ce(e,Object.values(c))}}async function ml(s){try{const e=await vl(s);return e!==`Hello from go binary
8
- `?{status:"failed",message:`Software check failed: got: ${e}`}:{status:"ok",message:`Software check succeeded: ${e}`}}catch(e){return{status:"failed",message:`Software check failed: error occurred: ${e}`}}}async function vl(s){var t;const e=await ke(s,he.Templates["check_network.run_hello_world"],!0,r=>({}),["greeting"]);try{return S.notEmpty((t=(await pe(s,e.greeting)).data)==null?void 0:t.toString())}finally{await Ce(s,Object.values(e))}}async function yl(s,e){try{const t=await wl(s,e);return t!==`Hello, ${e}!
9
- `?{status:"failed",message:`Python software check failed: got: ${t}`}:{status:"ok",message:`Python software check succeeded: ${t}`}}catch(t){return{status:"failed",message:`Python software check failed: error occurred: ${t}`}}}async function wl(s,e){var r;const t=await ke(s,he.Templates["check_network.run_hello_world_py"],!0,o=>({name:o.createValue(g.Pl.JsonObject,JSON.stringify(e))}),["greeting"]);try{return S.notEmpty((r=(await pe(s,t.greeting)).data)==null?void 0:r.toString())}finally{await Ce(s,Object.values(t))}}async function bl(s,e,t,r){var o,n;try{const i=await t.getStorageList(),c={};for(const a of i){const l=await Sl(t,a,r.nFilesToCheck,r.minFileSize,r.maxFileSize,r.minLsRequests);if(l.file===void 0){c[a.name]={status:"warn",message:`No file between ${r.minFileSize} and ${r.maxFileSize} bytes found in storage ${a.name}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`};continue}s.info(`Downloading file ${JSON.stringify(l)} from storage ${a.name}`);const u=await ke(e,he.Templates["check_network.create_workdir_from_storage"],!0,d=>({file:d.createValue(g.Pl.JsonObject,JSON.stringify(l.file.handle))}),["workdir"]);try{const d=await pe(e,u.workdir);d.type.name.startsWith("WorkingDirectory")?c[a.name]={status:"ok",message:`Workdir creation succeeded, size of file: ${(o=l.file)==null?void 0:o.size}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`}:c[a.name]={status:"failed",message:`Workdir creation failed: ${d.type.name}, size of file: ${(n=l.file)==null?void 0:n.size}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`}}finally{await Ce(e,Object.values(u))}}return c}catch(i){return{unknown:{status:"failed",message:`Download from every storage failed: error occurred: ${i}`}}}}async function Sl(s,e,t,r,o,n){const i=Ts(s,e,"",0);let c,a=0,l=0;for await(const{file:u,nLsRequests:d}of i){if(l=Math.max(l,d),a>=t&&l>n)return{file:c,nLsRequests:l,nCheckedFiles:a};if(a++,r<=u.size&&u.size<=o)return{file:u,nLsRequests:l,nCheckedFiles:a};u.size<r&&(c=u)}return{file:c,nLsRequests:l,nCheckedFiles:a}}async function*Ts(s,e,t,r){r++;const o=await s.listRemoteFilesWithAdditionalInfo(e.handle,t);for(const n of o.entries)if(n.type==="file"&&n.fullPath.startsWith(t))yield{file:n,nLsRequests:r};else if(n.type==="dir")for await(const i of Ts(s,e,n.fullPath,r))r=Math.max(i.nLsRequests,r),yield i}async function kl(){const s=M.join(Hr.tmpdir(),`check-network-big-temp-${Date.now()}.bin`),e=20*1024*1024,t=Z.randomBytes(e);return await De.appendFile(s,t),{filePath:s}}async function Cl(){const s=M.join(Hr.tmpdir(),`check-network-temp-${Date.now()}.txt`),e="Hello, world! "+new Date().toISOString();return await De.writeFile(s,e),{filePath:s,fileContent:e}}async function ke(s,e,t,r,o){return await s.withWriteTx("TemplateRender",async n=>{const i=await At(e),c=je(n,i),a=st(n,c,t,r(n),o),l={};for(const u of o){const d=g.field(s.clientRoot,u);n.createField(d,"Dynamic",a[u]),l[u]=await g.toGlobalFieldId(d)}return await n.commit(),l})}async function pe(s,e){return await g.poll(s,async t=>{const r=await t.tx.getField(e);if(g.isNotNullResourceId(r.error)){const o=await t.tx.getResourceData(r.error,!0);throw new Error(`getFieldValue of "${e.fieldName}" field failed: ${o.data}`)}if(g.isNullResourceId(r.value))throw new g.ContinuePolling;return await t.tx.getResourceData(r.value,!0)})}async function Ce(s,e){await s.withWriteTx("DeleteFields",async t=>{for(const r of e)t.resetField(r);await t.commit()})}async function Pl(s,e,t,r={}){const o=[];El.forEach(n=>{Us.channel(n).subscribe(c=>{var u,d;const a=new Date().toISOString(),l={...c};(u=l==null?void 0:l.response)!=null&&u.headers&&(l.response={...l.response},l.response.headers=l.response.headers.slice(),l.response.headers=l.response.headers.map(p=>p.toString())),(d=l==null?void 0:l.request)!=null&&d.body&&(l.request={...l.request},l.request.body="too big"),o.push(JSON.stringify({timestamp:a,event:n,data:l}))})});try{const{logger:n,plConfig:i,client:c,signer:a,downloadClient:l,uploadBlobClient:u,lsDriver:d,httpClient:p,ops:f}=await Is(s,e,t,r),{filePath:P,fileContent:v}=await Cl(),{filePath:T}=await kl(),L={plPings:await sl(f,i),blockRegistryOverviewChecks:await ol(f,p),blockGARegistryOverviewChecks:await nl(f,p),blockRegistryUiChecks:await il(f,p),blockGARegistryUiChecks:await al(f,p),autoUpdateCdnChecks:await cl(f,p),uploadTemplateCheck:await ul(n,c,"Jack"),uploadFileCheck:await pl(n,a,d,u,c,T),downloadFileCheck:await gl(n,c,d,u,l,P,v),softwareCheck:await ml(c),pythonSoftwareCheck:await yl(c,"Jack"),storageToDownloadReport:await bl(n,c,d,{minLsRequests:f.everyStorageMinLsRequests,bytesLimit:f.everyStorageBytesLimit,minFileSize:f.everyStorageMinFileSize,maxFileSize:f.everyStorageMaxFileSize,nFilesToCheck:f.everyStorageNFilesToCheck})};return Rl(L,s,f,o)}catch(n){return`Unhandled error while checking the network: ${n}`}}async function Is(s,e,t,r={}){const o={pingCheckDurationMs:1e4,pingTimeoutMs:3e3,maxPingsPerSecond:50,httpTimeoutMs:3e3,blockRegistryDurationMs:3e3,maxRegistryChecksPerSecond:1,blockRegistryUrl:"https://blocks.pl-open.science",blockGARegistryUrl:"https://blocks-ga.pl-open.science",blockOverviewPath:"v2/overview.json",blockUiPath:"v2/milaboratories/samples-and-data/1.7.0/ui.tgz",autoUpdateCdnDurationMs:5e3,maxAutoUpdateCdnChecksPerSecond:1,autoUpdateCdnUrl:"https://cdn.platforma.bio/software/platforma-desktop-v2/windows/amd64/latest.yml",bodyLimit:300,everyStorageBytesLimit:1024,everyStorageMinFileSize:1024,everyStorageMaxFileSize:209715200,everyStorageNFilesToCheck:300,everyStorageMinLsRequests:50,...r},n=g.plAddressToConfig(s,{defaultRequestTimeout:o.pingTimeoutMs});n.alternativeRoot=`check_network_${Z.randomUUID()}`;const i=new g.UnauthenticatedPlClient(n);let c={};e&&t&&(c=await i.login(e,t));const a=await g.PlClient.init(s,{authInformation:c}),l=i.ll.httpDispatcher,u=new S.ConsoleLoggerAdapter,d=new S.HmacSha256Signer("localSecret"),p=J.createDownloadClient(u,a,[]),f=J.createUploadBlobClient(a,u),P=await J.LsDriver.init(u,a,d,[],()=>Promise.resolve([]),[]);return{logger:u,plConfig:n,client:a,signer:d,downloadClient:p,uploadBlobClient:f,lsDriver:P,httpClient:l,ops:o,terminate:async()=>{p.close(),f.close(),await l.close(),await a.close()}}}function Rl(s,e,t,r){const o=s.plPings.filter(T=>T.response.ok),n=s.plPings.filter(T=>!T.response.ok),i=[...new Set(o.map(T=>JSON.stringify(T.response.value)))],c=T=>T?"OK":"FAILED",a=T=>T.status==="ok"?"OK":T.status==="warn"?"WARN":"FAILED",l=ye(s.plPings),u=ye(s.blockRegistryOverviewChecks),d=ye(s.blockGARegistryOverviewChecks),p=ye(s.blockRegistryUiChecks),f=ye(s.blockGARegistryUiChecks),P=ye(s.autoUpdateCdnChecks),v=Object.entries(s.storageToDownloadReport).map(([T,L])=>`${a(L)} ${T} storage check`).join(`
6
+ median in ms: ${n};
7
+ `;return{ok:t===0,details:o}}function Va(s){const e=s.map(n=>n.elapsedMs).sort(),t=e.reduce((n,o)=>n+o)/e.length;let r;if(e.length>0){const n=Math.floor(e.length/2);r=e.length%2?e[n]:(e[n-1]+e[n])/2}return{mean:t,median:r}}async function Ua(s,e,t){try{const r=await qa(s,e,t);return r!==`Hello, ${t}`?{status:"failed",message:`Template uploading failed: expected: ${t}, got: ${r}`}:{status:"ok",message:`Template uploading succeeded: ${r}`}}catch(r){return{status:"failed",message:`Template uploading failed: error occurred: ${r}`}}}async function qa(s,e,t){var n;const r=await be(e,he.Templates["check_network.upload_template"],!0,o=>({name:o.createValue(g.Pl.JsonObject,JSON.stringify(t))}),["greeting"]);try{return JSON.parse(k.notEmpty((n=(await pe(e,r.greeting)).data)==null?void 0:n.toString()))}finally{r!=null&&await Se(e,Object.values(r))}}async function Ma(s,e,t,r,n,o){try{const i=await Ga(s,e,t,r,n,o);return i.type.name!=="Blob"?{status:"failed",message:`File uploading failed: ${i.type.name}`}:{status:"ok",message:`File uploading succeeded: ${i.type.name}`}}catch(i){return{status:"failed",message:`File uploading failed: error occurred: ${i}`}}}async function Ga(s,e,t,r,n,o){var a;const i=await t.getLocalFileHandle(o),c=await be(n,he.Templates["check_network.upload_blob"],!0,l=>({file:l.createValue(g.Pl.JsonObject,JSON.stringify(i))}),["progress","file"]);try{const l=await pe(n,c.progress);if(W.isUpload(l)){const u=W.ImportFileHandleUploadData.parse(JSON.parse(k.notEmpty((a=l.data)==null?void 0:a.toString())));W.isSignMatch(e,u.localPath,u.pathSignature)&&await W.uploadBlob(s,r,l,u,()=>!1,{nPartsWithThisUploadSpeed:10,nPartsToIncreaseUpload:10,currentSpeed:10,maxSpeed:10})}return await pe(n,c.file)}finally{await Se(n,Object.values(c))}}async function Ja(s,e,t,r,n,o,i){try{const c=await _a(s,e,t,r,n,o);return c!==i?{status:"failed",message:`File downloading failed: expected: ${i}, got: ${c}`}:{status:"ok",message:`File downloading succeeded: ${c}`}}catch(c){return{status:"failed",message:`File downloading failed: error occurred: ${c}`}}}async function _a(s,e,t,r,n,o){var a;const i=await t.getLocalFileHandle(o),c=await be(e,he.Templates["check_network.download_blob"],!0,l=>({file:l.createValue(g.Pl.JsonObject,JSON.stringify(i))}),["progress","file"]);try{const l=await pe(e,c.progress);await W.uploadBlob(s,r,l,W.ImportFileHandleUploadData.parse(JSON.parse(k.notEmpty((a=l.data)==null?void 0:a.toString()))),()=>!1,{nPartsWithThisUploadSpeed:1,nPartsToIncreaseUpload:1,currentSpeed:1,maxSpeed:1});const u=await pe(e,c.file),{content:d}=await n.downloadBlob(u);return await xn.text(d)}finally{await Se(e,Object.values(c))}}async function Ka(s){try{const e=await Ha(s);return e!==`Hello from go binary
8
+ `?{status:"failed",message:`Software check failed: got: ${e}`}:{status:"ok",message:`Software check succeeded: ${e}`}}catch(e){return{status:"failed",message:`Software check failed: error occurred: ${e}`}}}async function Ha(s){var t;const e=await be(s,he.Templates["check_network.run_hello_world"],!0,r=>({}),["greeting"]);try{return k.notEmpty((t=(await pe(s,e.greeting)).data)==null?void 0:t.toString())}finally{await Se(s,Object.values(e))}}async function Wa(s,e){try{const t=await za(s,e);return t!==`Hello, ${e}!
9
+ `?{status:"failed",message:`Python software check failed: got: ${t}`}:{status:"ok",message:`Python software check succeeded: ${t}`}}catch(t){return{status:"failed",message:`Python software check failed: error occurred: ${t}`}}}async function za(s,e){var r;const t=await be(s,he.Templates["check_network.run_hello_world_py"],!0,n=>({name:n.createValue(g.Pl.JsonObject,JSON.stringify(e))}),["greeting"]);try{return k.notEmpty((r=(await pe(s,t.greeting)).data)==null?void 0:r.toString())}finally{await Se(s,Object.values(t))}}async function Xa(s,e,t,r){var n,o;try{const i=await t.getStorageList(),c={};for(const a of i){const l=await Ya(t,a,r.nFilesToCheck,r.minFileSize,r.maxFileSize,r.minLsRequests);if(l.file===void 0){c[a.name]={status:"warn",message:`No file between ${r.minFileSize} and ${r.maxFileSize} bytes found in storage ${a.name}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`};continue}s.info(`Downloading file ${JSON.stringify(l)} from storage ${a.name}`);const u=await be(e,he.Templates["check_network.create_workdir_from_storage"],!0,d=>({file:d.createValue(g.Pl.JsonObject,JSON.stringify(l.file.handle))}),["workdir"]);try{const d=await pe(e,u.workdir);d.type.name.startsWith("WorkingDirectory")?c[a.name]={status:"ok",message:`Workdir creation succeeded, size of file: ${(n=l.file)==null?void 0:n.size}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`}:c[a.name]={status:"failed",message:`Workdir creation failed: ${d.type.name}, size of file: ${(o=l.file)==null?void 0:o.size}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`}}finally{await Se(e,Object.values(u))}}return c}catch(i){return{unknown:{status:"failed",message:`Download from every storage failed: error occurred: ${i}`}}}}async function Ya(s,e,t,r,n,o){const i=En(s,e,"",0);let c,a=0,l=0;for await(const{file:u,nLsRequests:d}of i){if(l=Math.max(l,d),a>=t&&l>o)return{file:c,nLsRequests:l,nCheckedFiles:a};if(a++,r<=u.size&&u.size<=n)return{file:u,nLsRequests:l,nCheckedFiles:a};u.size<r&&(c=u)}return{file:c,nLsRequests:l,nCheckedFiles:a}}async function*En(s,e,t,r){r++;const n=await s.listRemoteFilesWithAdditionalInfo(e.handle,t);for(const o of n.entries)if(o.type==="file"&&o.fullPath.startsWith(t))yield{file:o,nLsRequests:r};else if(o.type==="dir")for await(const i of En(s,e,o.fullPath,r))r=Math.max(i.nLsRequests,r),yield i}async function Qa(){const s=K.join(_s.tmpdir(),`check-network-big-temp-${Date.now()}.bin`),e=20*1024*1024,t=te.randomBytes(e);return await Ie.appendFile(s,t),{filePath:s}}async function Za(){const s=K.join(_s.tmpdir(),`check-network-temp-${Date.now()}.txt`),e="Hello, world! "+new Date().toISOString();return await Ie.writeFile(s,e),{filePath:s,fileContent:e}}async function be(s,e,t,r,n){return await s.withWriteTx("TemplateRender",async o=>{const i=await ur(e),c=Ae(o,i),a=Xe(o,c,t,r(o),n),l={};for(const u of n){const d=g.field(s.clientRoot,u);o.createField(d,"Dynamic",a[u]),l[u]=await g.toGlobalFieldId(d)}return await o.commit(),l})}async function pe(s,e){return await g.poll(s,async t=>{const r=await t.tx.getField(e);if(g.isNotNullResourceId(r.error)){const n=await t.tx.getResourceData(r.error,!0);throw new Error(`getFieldValue of "${e.fieldName}" field failed: ${n.data}`)}if(g.isNullResourceId(r.value))throw new g.ContinuePolling;return await t.tx.getResourceData(r.value,!0)})}async function Se(s,e){await s.withWriteTx("DeleteFields",async t=>{for(const r of e)t.resetField(r);await t.commit()})}async function ec(s,e,t,r={}){const n=[];rc.forEach(o=>{jn.channel(o).subscribe(c=>{var u,d;const a=new Date().toISOString(),l={...c};(u=l==null?void 0:l.response)!=null&&u.headers&&(l.response={...l.response},l.response.headers=l.response.headers.slice(),l.response.headers=l.response.headers.map(p=>p.toString())),(d=l==null?void 0:l.request)!=null&&d.body&&(l.request={...l.request},l.request.body="too big"),n.push(JSON.stringify({timestamp:a,event:o,data:l}))})});try{const{logger:o,plConfig:i,client:c,signer:a,downloadClient:l,uploadBlobClient:u,lsDriver:d,httpClient:p,ops:f}=await On(s,e,t,r),{filePath:m,fileContent:h}=await Za(),{filePath:R}=await Qa(),I={plPings:await La(f,i),blockRegistryOverviewChecks:await Aa(f,p),blockGARegistryOverviewChecks:await Na(f,p),blockRegistryUiChecks:await Ba(f,p),blockGARegistryUiChecks:await ja(f,p),autoUpdateCdnChecks:await xa(f,p),uploadTemplateCheck:await Ua(o,c,"Jack"),uploadFileCheck:await Ma(o,a,d,u,c,R),downloadFileCheck:await Ja(o,c,d,u,l,m,h),softwareCheck:await Ka(c),pythonSoftwareCheck:await Wa(c,"Jack"),storageToDownloadReport:await Xa(o,c,d,{minLsRequests:f.everyStorageMinLsRequests,bytesLimit:f.everyStorageBytesLimit,minFileSize:f.everyStorageMinFileSize,maxFileSize:f.everyStorageMaxFileSize,nFilesToCheck:f.everyStorageNFilesToCheck})};return tc(I,s,f,n)}catch(o){return`Unhandled error while checking the network: ${o}`}}async function On(s,e,t,r={}){const n={pingCheckDurationMs:1e4,pingTimeoutMs:3e3,maxPingsPerSecond:50,httpTimeoutMs:3e3,blockRegistryDurationMs:3e3,maxRegistryChecksPerSecond:1,blockRegistryUrl:"https://blocks.pl-open.science",blockGARegistryUrl:"https://blocks-ga.pl-open.science",blockOverviewPath:"v2/overview.json",blockUiPath:"v2/milaboratories/samples-and-data/1.7.0/ui.tgz",autoUpdateCdnDurationMs:5e3,maxAutoUpdateCdnChecksPerSecond:1,autoUpdateCdnUrl:"https://cdn.platforma.bio/software/platforma-desktop-v2/windows/amd64/latest.yml",bodyLimit:300,everyStorageBytesLimit:1024,everyStorageMinFileSize:1024,everyStorageMaxFileSize:209715200,everyStorageNFilesToCheck:300,everyStorageMinLsRequests:50,...r},o=g.plAddressToConfig(s,{defaultRequestTimeout:n.pingTimeoutMs});o.alternativeRoot=`check_network_${te.randomUUID()}`;const i=new g.UnauthenticatedPlClient(o);let c={};e&&t&&(c=await i.login(e,t));const a=await g.PlClient.init(s,{authInformation:c}),l=i.ll.httpDispatcher,u=new k.ConsoleLoggerAdapter,d=new k.HmacSha256Signer("localSecret"),p=W.createDownloadClient(u,a,[]),f=W.createUploadBlobClient(a,u),m=await W.LsDriver.init(u,a,d,[],()=>Promise.resolve([]),[]);return{logger:u,plConfig:o,client:a,signer:d,downloadClient:p,uploadBlobClient:f,lsDriver:m,httpClient:l,ops:n,terminate:async()=>{p.close(),f.close(),await l.close(),await a.close()}}}function tc(s,e,t,r){const n=s.plPings.filter(R=>R.response.ok),o=s.plPings.filter(R=>!R.response.ok),i=[...new Set(n.map(R=>JSON.stringify(R.response.value)))],c=R=>R?"OK":"FAILED",a=R=>R.status==="ok"?"OK":R.status==="warn"?"WARN":"FAILED",l=me(s.plPings),u=me(s.blockRegistryOverviewChecks),d=me(s.blockGARegistryOverviewChecks),p=me(s.blockRegistryUiChecks),f=me(s.blockGARegistryUiChecks),m=me(s.autoUpdateCdnChecks),h=Object.entries(s.storageToDownloadReport).map(([R,I])=>`${a(I)} ${R} storage check`).join(`
10
10
  `);return`
11
11
  ${c(l.ok)} pings to Platforma Backend
12
12
  ${c(u.ok)} block registry overview
13
13
  ${c(d.ok)} block ga registry overview
14
14
  ${c(p.ok)} block registry ui
15
15
  ${c(f.ok)} block ga registry ui
16
- ${c(P.ok)} auto-update CDN
16
+ ${c(m.ok)} auto-update CDN
17
17
  ${a(s.uploadTemplateCheck)} upload template
18
18
  ${a(s.uploadFileCheck)} upload file
19
19
  ${a(s.downloadFileCheck)} download file
20
20
  ${a(s.softwareCheck)} software check
21
21
  ${a(s.pythonSoftwareCheck)} python software check
22
- ${v}
22
+ ${h}
23
23
 
24
24
  details:
25
25
  pl endpoint: ${e};
@@ -45,7 +45,7 @@ Block registry ui responses: ${p.details}
45
45
 
46
46
  Block ga registry ui responses: ${f.details}
47
47
 
48
- Auto-update CDN responses: ${P.details}
48
+ Auto-update CDN responses: ${m.details}
49
49
 
50
50
  dumps:
51
51
  Block registry overview dumps:
@@ -64,7 +64,7 @@ Auto-update CDN dumps:
64
64
  ${JSON.stringify(s.autoUpdateCdnChecks,null,2)}
65
65
 
66
66
  Platforma pings error dumps:
67
- ${JSON.stringify(n,null,2)}
67
+ ${JSON.stringify(o,null,2)}
68
68
 
69
69
  Platforma pings success dump examples:
70
70
  ${JSON.stringify(i,null,2)}
@@ -72,5 +72,5 @@ ${JSON.stringify(i,null,2)}
72
72
  Undici logs:
73
73
  ${r.join(`
74
74
  `)}
75
- `}const El=["undici:request:create","undici:request:bodySent","undici:request:headers","undici:request:error","undici:request:trailers","undici:client:sendHeaders","undici:client:beforeConnect","undici:client:connected","undici:client:connectError","undici:socket:close","undici:socket:connect","undici:socket:error","undici:pool:request","undici:pool:connect","undici:pool:disconnect","undici:pool:destroy","undici:dispatcher:request","undici:dispatcher:connect","undici:dispatcher:disconnect","undici:dispatcher:retry"];exports.BlockPackRegistry=Xs;exports.CentralBlockRegistry=Ys;exports.DefaultDriverKitOpsPaths=xt;exports.DefaultDriverKitOpsSettings=Vt;exports.DefaultMiddleLayerOpsPaths=bs;exports.DefaultMiddleLayerOpsSettings=ws;exports.FrontendFromFolderResourceType=Nt;exports.FrontendFromUrlResourceType=Lt;exports.MiddleLayer=zt;exports.Project=nt;exports.TengoTemplateGet=ss;exports.TengoTemplateGetRegistry=os;exports.TengoTemplateGetTemplate=is;exports.TengoTemplateGetTemplateURI=ns;exports.TengoTemplatePack=Ro;exports.TengoTemplatePackConvert=Eo;exports.TengoTemplatePackConvertTemplate=$o;exports.TengoTemplatePackConvertTemplatePack=Oo;exports.V1CentralDevSnapshotRegistry=Zs;exports.V1CentralRegistry=Qs;exports.V2RegistryProvider=zr;exports.checkNetwork=Pl;exports.createRenderTemplate=st;exports.getDevV1PacketMtime=Ft;exports.getDevV2PacketMtime=rt;exports.initDriverKit=$s;exports.initNetworkCheck=Is;exports.loadTemplate=je;exports.prepareTemplateSpec=At;Object.keys(D).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>D[s]})});Object.keys(z).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>z[s]})});Object.keys(er).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>er[s]})});Object.keys(g).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>g[s]})});
75
+ `}const rc=["undici:request:create","undici:request:bodySent","undici:request:headers","undici:request:error","undici:request:trailers","undici:client:sendHeaders","undici:client:beforeConnect","undici:client:connected","undici:client:connectError","undici:socket:close","undici:socket:connect","undici:socket:error","undici:pool:request","undici:pool:connect","undici:pool:disconnect","undici:pool:destroy","undici:dispatcher:request","undici:dispatcher:connect","undici:dispatcher:disconnect","undici:dispatcher:retry"];exports.BlockPackRegistry=Hn;exports.CentralBlockRegistry=Wn;exports.DefaultDriverKitOpsPaths=mr;exports.DefaultDriverKitOpsSettings=hr;exports.DefaultMiddleLayerOpsPaths=bn;exports.DefaultMiddleLayerOpsSettings=wn;exports.FrontendFromFolderResourceType=pr;exports.FrontendFromUrlResourceType=dr;exports.MiddleLayer=Cr;exports.Project=Qe;exports.TengoTemplateGet=rn;exports.TengoTemplateGetRegistry=sn;exports.TengoTemplateGetTemplate=on;exports.TengoTemplateGetTemplateURI=nn;exports.TengoTemplatePack=Ro;exports.TengoTemplatePackConvert=ko;exports.TengoTemplatePackConvertTemplate=Po;exports.TengoTemplatePackConvertTemplatePack=Co;exports.V1CentralDevSnapshotRegistry=Xn;exports.V1CentralRegistry=zn;exports.V2RegistryProvider=Ws;exports.checkNetwork=ec;exports.createRenderTemplate=Xe;exports.getDevV1PacketMtime=cr;exports.getDevV2PacketMtime=ze;exports.initDriverKit=Pn;exports.initNetworkCheck=On;exports.loadTemplate=Ae;exports.prepareTemplateSpec=ur;Object.keys(V).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>V[s]})});Object.keys(Q).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>Q[s]})});Object.keys(Ir).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>Ir[s]})});Object.keys(g).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>g[s]})});
76
76
  //# sourceMappingURL=index.js.map