@milaboratories/pl-middle-layer 1.35.2 → 1.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Cs=Object.defineProperty;var _t=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),Kt=r=>{throw TypeError(r)};var Es=(r,e,t)=>e in r?Cs(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var S=(r,e,t)=>Es(r,typeof e!="symbol"?e+"":e,t);var Ht=(r,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Kt("Object expected");var s;t&&(s=e[_t("asyncDispose")]),s===void 0&&(s=e[_t("dispose")]),typeof s!="function"&&Kt("Object not disposable"),r.push([t,s,e])}else t&&r.push([t]);return e},qt=(r,e,t)=>{var s=typeof SuppressedError=="function"?SuppressedError:function(i,a,c,u){return u=Error(c),u.name="SuppressedError",u.error=i,u.suppressed=a,u},o=i=>e=t?new s(i,e,"An error was suppressed during disposal"):(t=!0,i),n=i=>{for(;i=r.pop();)try{var a=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(a).then(n,c=>(o(c),n()))}catch(c){o(c)}if(t)throw e};return n()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("@platforma-sdk/model"),q=require("@milaboratories/pl-model-middle-layer"),Wt=require("@milaboratories/pl-deployments"),We=require("undici"),W=require("@platforma-sdk/block-tools"),Z=require("node:fs"),K=require("node:path"),ks=require("yaml"),E=require("@milaboratories/ts-helpers"),ht=require("node:fs/promises"),Os=require("@milaboratories/resolve-helper"),f=require("@milaboratories/pl-client"),_e=require("@milaboratories/pl-tree"),j=require("@milaboratories/computable"),ee=require("node:crypto"),k=require("@milaboratories/pl-model-backend"),Br=require("lru-cache"),$s=require("node:worker_threads"),jr=require("denque"),Ts=require("@platforma-sdk/workflow-tengo"),x=require("canonicalize"),Is=require("node:assert"),$e=require("quickjs-emscripten"),Fs=require("@milaboratories/pl-errors"),As=require("remeda"),Vr=require("node:timers/promises"),te=require("@milaboratories/pl-drivers"),Ds=require("@milaboratories/pframes-rs-node"),Ls=require("node:diagnostics_channel");function xr(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const Ur=xr(ht),zt=xr(As);async function Xt(r){try{return await Ur.stat(r,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const Ns=[W.RegistryV1.PlPackageYamlConfigFile],Bs=[W.RegistryV1.PlPackageJsonConfigFile],Ct=["backend","dist","tengo","tpl","main.plj.gz"],Et=["config","dist","config.json"],Gr=["frontend","dist"],Yt="block-model/dist/config.json",js="block-ui/package.json",Vs=[Ct,Et,Ns,Bs,Gr];async function xs(r){return await Xt(K.join(r,...Et))!==void 0||await Xt(K.join(r,...Ct))!==void 0}function nt(r,e){const t=Os.tryResolve(r,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${r}`);return t}async function Qt(r,e){if(K.isAbsolute(r)||(r=K.resolve(r)),await xs(r))return{workflow:K.join(r,...Ct),config:K.join(r,...Et),ui:K.join(r,...Gr)};{const t=nt(r,Yt),s=nt(r,Yt),o=nt(r,js);return{workflow:t,config:s,ui:K.resolve(o,"..","dist")}}}async function Us(r){try{return await Z.promises.readFile(r,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Gs(r){try{return await Z.promises.stat(r,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function kt(r){let e=0n;for(const t of Vs){const s=K.join(r,...t),o=await Gs(s);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function ze(r){const e=await Z.promises.stat(r.components.workflow.main.file,{bigint:!0}),t=await Z.promises.stat(r.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class Ms{constructor(e,t,s){this.v2Provider=e,this.registries=t,this.http=s}async getPackagesForRoot(e){const t=[],s=e.spec;switch(s.type){case"remote-v1":{const o=this.http!==void 0?{dispatcher:this.http}:{},i=await(await We.request(`${s.url}/${W.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const a of i){const{organization:c,package:u,latestMeta:l,latestVersion:d}=a,h={organization:c,name:u,version:d},g={id:h,meta:{title:l.title??"No title",description:l.description??"No Description",organization:{name:c,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:h,registryUrl:s.url}};t.push({registryId:e.id,id:h,latestByChannel:{[q.AnyChannel]:g,[q.StableChannel]:g},allVersions:a.allVersions.map(R=>({version:R,channels:[]}))})}return t}case"remote-v2":return(await this.v2Provider.getRegistry(s.url).listBlockPacks()).map(o=>({...o,registryId:e.id}));case"local-dev":for(const o of await Z.promises.readdir(s.path,{withFileTypes:!0})){if(!o.isDirectory())continue;const n=K.join(s.path,o.name),i=await Us(K.join(n,W.RegistryV1.PlPackageYamlConfigFile));if(i!==void 0){const a=W.RegistryV1.PlPackageConfigData.parse(ks.parse(i)),c=await kt(n),u={organization:a.organization,name:a.package,version:"DEV"},l={id:u,meta:{title:a.meta.title??"No title",description:a.meta.description??"No Description",organization:{name:a.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:n,mtime:c}};t.push({registryId:e.id,id:u,latestByChannel:{[q.AnyChannel]:l,[q.StableChannel]:l},allVersions:[]})}else{let a=n,c=await W.tryLoadPackDescription(a);if(c===void 0){for(const u of["block","meta"])if(a=K.join(n,u),c=await W.tryLoadPackDescription(a),c!==void 0)break}if(c!==void 0){const u=await ze(c),l={id:c.id,meta:await W.BlockPackMetaEmbedAbsoluteBytes.parseAsync(c.meta),spec:{type:"dev-v2",folder:a,mtime:u}};t.push({registryId:e.id,id:c.id,latestByChannel:{[q.AnyChannel]:l,[q.StableChannel]:l},allVersions:[]})}}}return t;default:return E.assertNever(s)}}async listBlockPacks(){const e=[],t=[];for(const s of this.registries)t.push({...s,status:"online"}),e.push(...await this.getPackagesForRoot(s));return{registries:t,blockPacks:e}}async getOverview(e,t,s){var i;const o=(i=this.registries.find(a=>a.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,s)}}class Mr{constructor(e){S(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const s=new W.RegistryV2Reader(W.folderReaderByUrl(e,this.http));return this.registries.set(e,s),s}}const Js={type:"remote-v2",url:"https://blocks.pl-open.science/"},_s={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},Ks={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},Hs={groups:[{id:"default",label:"Default",blocks:[]}]},qs={stagingRefreshTimestamp:0,blocksInLimbo:[]},Ws={label:"New Project"},zs={name:"UserProject",version:"2"},Jr="SchemaVersion",_r="1",Ot="ProjectCreated",Te="ProjectLastModified",Ie="ProjectMeta",pe="ProjectStructure",Ke="BlockRenderingState",Xs="BlockFrontendState/",Ys=/^BlockFrontendState\/(?<blockid>.*)$/;function gt(r){return`${Xs}${r}`}const Qs="BlockArgsAuthor/";function mt(r){return`${Qs}${r}`}const vt="ProjectStructureAuthor";function Zs(r){const e=r.match(Ys);if(e!==null)return e.groups.blockid}const eo="__serviceTemplate_";function yt(r){return`${eo}${r}`}function J(r,e){return`${r}-${e}`}const to=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function ro(r){const e=r.match(to);if(e===null)return;const{blockId:t,fieldName:s}=e.groups;return{blockId:t,fieldName:s}}const so="projects",Kr={name:"Projects",version:"1"},oo=r=>f.resourceTypesEqual(r.type,Kr)?r.fields:[];async function no(r,e,t,s){const o=await _e.SynchronizedTreeState.init(r,e,{...s.ops.defaultTreeOptions,pruning:oo},s.logger);return{computable:j.Computable.make(i=>{const a=i.accessor(o.entry()).node(),c=t.getValue(i);if(a===void 0)return;const u=[];for(const l of a.listDynamicFields()){const d=a.traverse(l);if(d===void 0)continue;const h=E.notEmpty(d.getKeyValueAsJson(Ie)),g=E.notEmpty(d.getKeyValueAsJson(Ot)),R=E.notEmpty(d.getKeyValueAsJson(Te));u.push({id:l,rid:d.id,created:new Date(g),lastModified:new Date(R),opened:c.indexOf(d.id)>=0,meta:h})}return u.sort(l=>-l.lastModified.valueOf()),u}).withStableType(),tree:o}}const io={name:"EphRenderTemplate",version:"1"},ao={name:"RenderTemplate",version:"1"};function $t(r,e,t,s,o){if(o.length===0)throw new Error("Zero output names provided");const n=t?r.createEphemeral(io):r.createStruct(ao),i=f.field(n,"template"),a=f.field(n,"inputs");return r.createField(i,"Input",e),r.createField(a,"Input",f.Pl.createPlMap(r,s,t)),r.lockInputs(n),f.Pl.futureRecord(r,n,o,"Output","outputs/")}const co={name:"BContextEnd",version:"1"},lo={name:"BContext",version:"1"},uo="id",po="parent/",fo=["context","result"];function Zt(r,e,t){return $t(r,e,!0,t,fo)}function ho(r){const e=r.createEphemeral(co);return r.lock(e),e}function er(r,e){if(e.length===0)return ho(r);if(e.length===1)return e[0];const t=r.createEphemeral(lo);r.createField(f.field(t,uo),"Input",f.Pl.createPlString(r,ee.randomUUID()));for(let s=0;s<e.length;s++)r.createField(f.field(t,`${po}${s}`),"Input",e[s]);return r.lock(t),t}function Hr(r,e){const t=new Map,s=(o,n,i)=>{const a=ee.createHash("sha256");n.updateCacheKey(o,a,i);const c=a.digest("hex");if(!t.has(c)){const u=n.render(o,r,s,i);t.set(c,u)}return t.get(c)};return s(e.template,qr,e.hashToSource)}const tr={updateCacheKey(r,e,t){e.update(k.PlTemplateLibV1.type.name).update(k.PlTemplateLibV1.type.version).update(r.name).update(r.version).update(ve(r.name,t,r.sourceHash))},render(r,e,t,s){return e.createValue(k.PlTemplateLibV1.type,JSON.stringify(k.PlTemplateLibV1.fromV3Data(r,ve(r.name,s,r.sourceHash)).data))}},Ae={updateCacheKey(r,e,t){e.update(k.PlTemplateSoftwareV1.type.name).update(k.PlTemplateSoftwareV1.type.version).update(r.name).update(r.version).update(ve(r.name,t,r.sourceHash))},render(r,e,t,s){const o=k.PlTemplateSoftwareV1.fromV3Data(r,ve(r.name,s,r.sourceHash)),n=e.createStruct(k.PlTemplateSoftwareV1.type,o.data);return e.setKValue(n,k.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(o.name)),e.lock(n),n}},qr={updateCacheKey(r,e,t){e.update(k.PlTemplateV1.type.name).update(k.PlTemplateV1.type.version).update(r.hashOverride??"no-override").update(r.name).update(r.version).update(ve(r.name,t,r.sourceHash));const s=o=>(o.sort((n,i)=>n[0]===i[0]?0:n[0]<i[0]?-1:1),o);for(const[o,n]of s(Object.entries(r.libs??{})))e.update("lib:"+o),tr.updateCacheKey(n,e,t);for(const[o,n]of s(Object.entries(r.software??{})))e.update("soft:"+o),Ae.updateCacheKey(n,e,t);for(const[o,n]of s(Object.entries(r.assets??{})))e.update("asset:"+o),Ae.updateCacheKey(n,e,t);for(const[o,n]of s(Object.entries(r.templates??{})))e.update("tpl:"+o),this.updateCacheKey(n,e,t)},render(r,e,t,s){const o=e.createStruct(k.PlTemplateV1.type,JSON.stringify(k.PlTemplateV1.fromV3Data(r,ve(r.name,s,r.sourceHash)).data));for(const[a,c]of Object.entries(r.libs??{})){const u=k.PlTemplateV1.libField(o,a);e.createField(u,"Input"),e.setField(u,t(c,tr,s))}for(const[a,c]of Object.entries(r.software??{})){const u=k.PlTemplateV1.swField(o,a);e.createField(u,"Input"),e.setField(u,t(c,Ae,s))}for(const[a,c]of Object.entries(r.assets??{})){const u=k.PlTemplateV1.swField(o,a);e.createField(u,"Input"),e.setField(u,t(c,Ae,s))}for(const[a,c]of Object.entries(r.templates??{})){const u=k.PlTemplateV1.tplField(o,a);e.createField(u,"Input"),e.setField(u,t(c,qr,s))}if(e.lock(o),!r.hashOverride)return o;const n=e.createStruct(k.PlTemplateOverrideV1.type,JSON.stringify(k.PlTemplateOverrideV1.fromV3Data(r))),i=k.PlTemplateOverrideV1.tplField(n);return e.createField(i,"Service"),e.setField(i,o),e.lock(n),n}};function ve(r,e,t){return E.notEmpty(e[t],`trying to get "${r}" source: sources map doesn't contain source hash ${t}`)}function go(r,e){const t=k.parseTemplate(e.content),s=t.type;switch(s){case"pl.tengo-template.v2":return zr(r,t);case"pl.tengo-template.v3":return Hr(r,t);default:E.assertNever(s)}}function mo(r,e){const t=e.data,s=t.type;switch(s){case"pl.tengo-template.v2":return zr(r,t);case"pl.tengo-template.v3":return Hr(r,t);default:E.assertNever(s)}}const rr={hash(r,e){e.update(k.PlTemplateLibV1.type.name).update(k.PlTemplateLibV1.type.version).update(r.name).update(r.version).update(r.src)},render(r,e,t){return e.createValue(k.PlTemplateLibV1.type,JSON.stringify(k.PlTemplateLibV1.fromV2Data(r).data))}},De={hash(r,e){e.update(k.PlTemplateSoftwareV1.type.name).update(k.PlTemplateSoftwareV1.type.version).update(r.name).update(r.version).update(r.src)},render(r,e,t){const s=k.PlTemplateSoftwareV1.fromV2Data(r),o=e.createStruct(k.PlTemplateSoftwareV1.type,s.data);return e.setKValue(o,k.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(s.name)),e.lock(o),o}},Wr={hash(r,e){e.update(k.PlTemplateV1.type.name).update(k.PlTemplateV1.type.version).update(r.hashOverride??"no-override").update(r.name).update(r.version).update(r.src);const t=s=>(s.sort((o,n)=>o[0]===n[0]?0:o[0]<n[0]?-1:1),s);for(const[s,o]of t(Object.entries(r.libs??{})))e.update("lib:"+s),rr.hash(o,e);for(const[s,o]of t(Object.entries(r.software??{})))e.update("soft:"+s),De.hash(o,e);for(const[s,o]of t(Object.entries(r.assets??{})))e.update("asset:"+s),De.hash(o,e);for(const[s,o]of t(Object.entries(r.templates??{})))e.update("tpl:"+s),this.hash(o,e)},render(r,e,t){const s=e.createStruct(k.PlTemplateV1.type,JSON.stringify(k.PlTemplateV1.fromV2Data(r).data));for(const[i,a]of Object.entries(r.libs??{})){const c=k.PlTemplateV1.libField(s,i);e.createField(c,"Input"),e.setField(c,t(a,rr))}for(const[i,a]of Object.entries(r.software??{})){const c=k.PlTemplateV1.swField(s,i);e.createField(c,"Input"),e.setField(c,t(a,De))}for(const[i,a]of Object.entries(r.assets??{})){const c=k.PlTemplateV1.swField(s,i);e.createField(c,"Input"),e.setField(c,t(a,De))}for(const[i,a]of Object.entries(r.templates??{})){const c=k.PlTemplateV1.tplField(s,i);e.createField(c,"Input"),e.setField(c,t(a,Wr))}if(e.lock(s),!r.hashOverride)return s;const o=e.createStruct(k.PlTemplateOverrideV1.type,JSON.stringify(k.PlTemplateOverrideV1.fromV2Data(r))),n=k.PlTemplateOverrideV1.tplField(o);return e.createField(n,"Service"),e.setField(n,s),e.lock(o),o}};function zr(r,e){const t=new Map,s=(o,n)=>{const i=ee.createHash("sha256");n.hash(o,i);const a=i.digest("hex");if(!t.has(a)){const c=n.render(o,r,s);t.set(a,c)}return t.get(a)};return s(e,Wr)}const Xr={name:"TengoTemplateGet",version:"1"},Yr="registry",Qr="templateURI",Zr="template",vo={name:"TengoTemplatePack",version:"1"},yo={name:"TengoTemplatePackConvert",version:"1"},wo="templatePack",So="template";async function es(r){switch(r.type){case"from-file":return{type:"explicit",content:await Z.promises.readFile(r.path)};case"from-registry":case"explicit":return r;case"prepared":return r;default:return E.assertNever(r)}}function bo(r,e){const t=r.createStruct(Xr),s=f.field(t,Yr),o=f.field(t,Qr),n=f.field(t,Zr);return r.setField(s,r.createValue(f.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),r.setField(o,r.createValue(f.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function Xe(r,e){switch(e.type){case"from-registry":return bo(r,e);case"explicit":return go(r,e);case"prepared":return mo(r,e);default:return E.assertNever(e)}}const Tt={name:"Frontend/FromUrl",version:"1"},It={name:"Frontend/FromFolder",version:"1"};function Po(r,e){switch(e.type){case"url":return r.createValue(Tt,JSON.stringify({url:e.url}));case"local":return r.createValue(It,JSON.stringify({path:e.path,signature:e.signature}));default:return E.assertNever(e)}}class Ro{constructor(){S(this,"nextMessageId",0);S(this,"worker");S(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 $s.Worker(e,{workerData:{}});t.on("message",({id:s,data:o,error:n})=>{const{resolve:i,reject:a}=this.pendingRequests.get(s);this.pendingRequests.delete(s),n?a(new Error(n)):i(o)}),t.on("error",s=>{console.error("Worker error",s),this.rejectAllPendingRequests(s)})}rejectAllPendingRequests(e){Array.from(this.pendingRequests.values()).map(({reject:t})=>{t(e)})}async process(e,...t){return new Promise((s,o)=>{const n=++this.nextMessageId;this.pendingRequests.set(n,{resolve:s,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 Co={name:"BlockPackCustom",version:"1"},ts="template",rs="frontend";function sr(r){return r.endsWith("/")?r:`${r}/`}function Eo(r){return Buffer.from(r).toString("utf8")}function Le(r){return JSON.parse(Eo(r))}class ko{constructor(e,t,s){S(this,"remoteContentCache",new Br.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=s}async getBlockConfigContainer(e){switch(e.type){case"explicit":return e.config;case"prepared":return e.config;case"dev-v1":{const t=await Qt(e.folder),s=await Z.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(s)}case"dev-v2":{const t=await W.loadPackDescription(e.folder),s=await Z.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(s)}case"from-registry-v1":{const t=`${sr(e.registryUrl)}${W.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,s=await this.remoteContentCache.forceFetch(`${t}/config.json`);return Le(s)}case"from-registry-v2":{const s=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),o=await this.remoteContentCache.forceFetch(s.model.url);return Le(o)}default:return E.assertNever(e)}}async prepare(e){var o=[];try{if(e.type==="prepared")return e;const t=await this.prepareWithoutUnpacking(e);const s=Ht(o,new Ro,!0);return{...t,type:"prepared",template:{type:"prepared",data:await s.process("parseTemplate",t.template.content)}}}catch(n){var i=n,a=!0}finally{var c=qt(o,i,a);c&&await c}}async prepareWithoutUnpacking(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await Qt(e.folder),s=await Z.promises.readFile(t.workflow),o=JSON.parse(await Z.promises.readFile(t.config,"utf-8")),n=t.ui;return{type:"explicit",template:{type:"explicit",content:s},config:o,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:e}}case"dev-v2":{const t=await W.loadPackDescription(e.folder),s=JSON.parse(await Z.promises.readFile(t.components.model.file,{encoding:"utf-8"})),o=await Z.promises.readFile(t.components.workflow.main.file),n=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await ze(t)),{type:"explicit",template:{type:"explicit",content:o},config:s,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:i}}case"from-registry-v1":{const t=`${sr(e.registryUrl)}${W.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,s=`${t}/template.plj.gz`,o=await this.remoteContentCache.forceFetch(s),n=new Uint8Array(o),i=await this.remoteContentCache.forceFetch(`${t}/config.json`),a=Le(i);return{type:"explicit",template:{type:"explicit",content:n},config:a,frontend:{type:"url",url:`${t}/frontend.tgz`},source:e}}case"from-registry-v2":{const s=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),o=async()=>Le(await this.remoteContentCache.forceFetch(s.model.url)),n=async()=>await this.remoteContentCache.forceFetch(s.workflow.main.url),[i,a]=await Promise.all([o(),n()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(a)},config:i,frontend:{type:"url",url:s.ui.url},source:e}}default:return E.assertNever(e)}}}function Oo(r,e){const t={config:e.config,source:e.source},s=r.createStruct(Co,JSON.stringify(t));return r.createField(f.field(s,ts),"Input",Xe(r,e.template)),r.createField(f.field(s,rs),"Input",Po(r,e.frontend)),r.lock(s),s}function or(r,e){switch(e.type){case"prepared":return Oo(r,e);default:return E.assertNever(e.type)}}function Ne(r,e){return{__isRef:!0,blockId:r,name:e}}function $o(r){return typeof r=="object"&&r!==null&&"__isRef"in r&&r.__isRef===!0&&"blockId"in r&&"name"in r}function wt(r,e,t){const s=typeof e;switch(s){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if($o(e))t===void 0||t.has(e.blockId)?r.upstreams.add(e.blockId):r.missingReferences=!0;else if(Array.isArray(e))for(const o of e)wt(r,o,t);else for(const[,o]of Object.entries(e))wt(r,o,t);return;default:E.assertNever(s)}}function To(r,e){const t={upstreams:new Set,missingReferences:!1};return wt(t,r,e),t}function ae(r){return{*[Symbol.iterator](){for(const e of r.groups)for(const t of e.blocks)yield t}}}class ss{constructor(e){S(this,"nodes");this.nodes=e}traverseIds(e,...t){const s=new Set;return this.traverse(e,t,o=>s.add(o.id)),s}traverseIdsExcludingRoots(e,...t){const s=this.traverseIds(e,...t);for(const o of t)s.delete(o);return s}traverse(e,t,s){let o=[...t];const n=new Set(o);for(;o.length>0;){const i=[];for(const a of o){const c=this.nodes.get(a);s(c),c[e].forEach(u=>{n.has(u)||(n.add(u),i.push(u))})}o=i}}}function St(r){const e=new Map;let t;for(const{id:s}of ae(r)){const o={id:s,missingReferences:!1};e.set(s,o),t===void 0?o.upstream=new Set:(o.upstream=new Set([t.id]),t.downstream=new Set([o.id])),t=o}return t!==void 0&&(t.downstream=new Set),new ss(e)}function Je(r,e){const t=new Map,s=new Set;for(const{id:o}of ae(r)){const n=e(o);if(n===void 0)continue;const i=To(n,s),a={id:o,missingReferences:i.missingReferences,upstream:i.upstreams,downstream:new Set};t.set(o,a),i.upstreams.forEach(c=>t.get(c).downstream.add(o)),s.add(o)}return new ss(t)}function Io(r,e){if(r.size!==e.size)return!1;for(const t of r)if(!e.has(t))return!1;return!0}function bt(r,e){if(r.size>e.size)return bt(e,r);for(const t of r)if(e.has(t))return!0;return!1}function nr(r,e){const t=new Set,s=new Set,o=new Set;return r.nodes.forEach(n=>{const i=e.nodes.get(n.id);i===void 0?t.add(n.id):(!Io(n.upstream,i.upstream)||bt(n.upstream,o))&&o.add(n.id)}),e.nodes.forEach(n=>{r.nodes.has(n.id)?bt(n.upstream,o)&&o.add(n.id):s.add(n.id)}),{onlyInA:t,onlyInB:s,different:o}}let it;async function os(){if(it===void 0){const r=await es(Ts.Templates["pframes.export-pframe-for-ui"]);if(r.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=ee.createHash("sha256").update(r.content).digest("hex");it={spec:r,hash:e}}return it}function Fo(r,e,t){return $t(r,e,!0,{pf:t},["result"]).result}function at(r,e){let t=!1,s,o;return()=>{if(!t)return t=!0,s=r(),o=e(),o;const n=r();return s!==n&&(s=n,o=e()),e()}}class ir{constructor(e,t){S(this,"currentInputsC",at(()=>this.fields.currentArgs.modCount,()=>E.deepFreeze(JSON.parse(Buffer.from(this.fields.currentArgs.value).toString()))));S(this,"actualProductionInputsC",at(()=>{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 E.deepFreeze(JSON.parse(Buffer.from(e).toString()))}));S(this,"productionStaleC",at(()=>{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}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 currentInputs(){return this.currentInputsC()}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 actualProductionInputs(){return this.actualProductionInputsC()}getTemplate(e){return e.getFutureFieldValue(f.Pl.unwrapHolder(e,this.fields.blockPack.ref),ts,"Input")}}const Ao=r=>{throw new Error(`No new block info for ${r}`)};class He{constructor(e,t,s,o,n,i,a,c,u,l,d,h){S(this,"globalModCount",0);S(this,"fieldsChanged",!1);S(this,"lastModifiedChanged",!1);S(this,"structureChanged",!1);S(this,"metaChanged",!1);S(this,"renderingStateChanged",!1);S(this,"changedBlockFrontendStates",new Set);S(this,"blocksWithChangedInputs",new Set);S(this,"stagingGraph");S(this,"pendingProductionGraph");S(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=s,this.schema=o,this.lastModified=n,this.meta=i,this.struct=a,this.renderingState=c,this.blocksInLimbo=u,this.blockInfos=l,this.blockFrontendStates=d,this.ctxExportTplHolder=h}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=St(this.struct)),this.stagingGraph}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Je(this.struct,e=>this.getBlockInfo(e).currentInputs)),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Je(this.struct,e=>this.getBlockInfo(e).actualProductionInputs)),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(f.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of ae(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,s){const o=f.field(this.rid,J(e,t));if(s.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",s.ref):this.tx.setField(o,s.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...s},this.fieldsChanged=!0}setBlockField(e,t,s,o,n){this.setBlockFieldObj(e,t,{ref:s,status:o,value:n})}deleteBlockFields(e,...t){let s=!1;const o=this.getBlockInfo(e);for(const n of t){const i=o.fields;n in i&&(this.tx.removeField(f.field(this.rid,J(e,n))),delete i[n],this.fieldsChanged=!0,s=!0)}return s}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var s,o,n;const t=this.getBlockInfo(e).fields;((s=t.stagingOutput)==null?void 0:s.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 s,o,n;const t=this.getBlockInfo(e).fields;((s=t.prodOutput)==null?void 0:s.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 s,o;const t=this.getBlockInfo(e).fields;return((s=t.prodOutput)==null?void 0:s.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:s,args:o}of e){const n=this.getBlockInfo(s);JSON.parse(o);const i=Buffer.from(o);if(Buffer.compare(n.fields.currentArgs.value,i)===0)continue;const a=this.tx.createValue(f.Pl.JsonObject,i);this.setBlockField(s,"currentArgs",a,"Ready",i),this.blocksWithChangedInputs.add(s),t.push(s)}this.getStagingGraph().traverse("downstream",t,({id:s})=>this.resetStaging(s)),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(s=>{var n;const o=this.getBlockInfo(s);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(f.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),er(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(s=>{var n,i;const o=this.getBlockInfo(s);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(f.Pl.unwrapHolder(this.tx,o.fields.stagingCtx.ref)),((i=o.fields.prodCtx)==null?void 0:i.ref)!==void 0&&t.push(f.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),er(this.tx,t)}exportCtx(e){return Fo(this.tx,f.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),s=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=Zt(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(f.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(f.Pl.JsonBool,JSON.stringify(!1)),context:s});this.setBlockField(e,"stagingCtx",f.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),s=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=Zt(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(f.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(f.Pl.JsonBool,JSON.stringify(!0)),context:s});this.setBlockField(e,"prodCtx",f.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=Ao){const s=this.getStagingGraph(),o=this.getActualProductionGraph(),n=St(e),i=Je(e,u=>{var l;return(l=this.blockInfos.get(u))==null?void 0:l.actualProductionInputs}),a=nr(s,n),c=nr(o,i);for(const u of a.onlyInA){const{fields:l}=this.getBlockInfo(u);this.deleteBlockFields(u,...Object.keys(l)),this.blockInfos.delete(u),this.blocksInLimbo.delete(u)&&(this.renderingStateChanged=!0),this.blockFrontendStates.delete(u)&&this.changedBlockFrontendStates.add(u)}for(const u of a.onlyInB){const l=new ir(u,{});this.blockInfos.set(u,l);const d=t(u),h=or(this.tx,d.blockPack);this.setBlockField(u,"blockPack",f.Pl.wrapInHolder(this.tx,h),"NotReady"),this.setBlockFieldObj(u,"blockSettings",this.createJsonFieldValue(q.InitialBlockSettings)),this.setBlockFieldObj(u,"currentArgs",this.createJsonFieldValueByContent(d.args)),d.uiState&&(this.blockFrontendStates.set(u,d.uiState),this.changedBlockFrontendStates.add(u)),l.check()}for(const u of a.different)this.resetStaging(u);o.traverse("downstream",[...c.different],u=>{this.resetOrLimboProduction(u.id)}),(a.onlyInB.size>0||a.onlyInA.size>0||a.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,s){const o=this.structure;if(s===void 0)o.groups[o.groups.length-1].blocks.push(e);else{let n=!1;for(const i of o.groups){const a=i.blocks.findIndex(c=>c.id===s);if(!(a<0)){i.blocks.splice(a,0,e),n=!0;break}}if(!n)throw new Error(`Can't find element with id: ${s}`)}this.updateStructure(o,n=>{if(n!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let s=!1;for(const o of t.groups){const n=o.blocks.findIndex(i=>i.id===e);if(!(n<0)){o.blocks.splice(n,1),s=!0;break}}if(!s)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,s){const o=this.getBlockInfo(e);this.setBlockField(e,"blockPack",f.Pl.wrapInHolder(this.tx,or(this.tx,t)),"NotReady"),s!==void 0?(this.setArgs([{blockId:e,args:s.args}]),this.setUiState(e,s.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 s=new Set(e),o=this.getPendingProductionGraph();if(t)o.traverse("upstream",e,a=>{s.add(a.id)});else for(const a of s){const c=o.nodes.get(a);if(c===void 0)throw new Error(`Can't find block with id: ${a}`);for(const u of c.upstream)if(!s.has(u))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const a of ae(this.structure)){if(!s.has(a.id))continue;let c=this.getBlockInfo(a.id).requireProductionRendering||this.blocksInLimbo.has(a.id);if(!c){for(const u of o.nodes.get(a.id).upstream)if(n.has(u)){c=!0;break}}c&&(this.renderProductionFor(a.id),n.add(a.id))}const i=[...n];return o.traverse("downstream",i,a=>{n.has(a.id)||this.resetOrLimboProduction(a.id)}),this.getStagingGraph().traverse("downstream",i,({id:a})=>{i[0]!==a&&this.resetStaging(a)}),n.size>0&&this.updateLastModified(),n}stopProduction(...e){var i,a;const t=this.getActualProductionGraph(),s=new jr(e),o=new Set(e),n=[];for(;!s.isEmpty();){const c=s.shift(),u=this.getBlockInfo(c).fields;if(!(((i=u.prodOutput)==null?void 0:i.status)==="Ready"&&((a=u.prodCtx)==null?void 0:a.status)==="Ready")&&this.deleteBlockFields(c,"prodOutput","prodCtx","prodUiCtx","prodArgs")){n.push(c);for(const l of t.traverseIdsExcludingRoots("downstream",c))o.has(l)||(s.push(l),o.add(l))}}for(const c of t.traverseIdsExcludingRoots("downstream",...n))this.resetOrLimboProduction(c)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(o=>{let i=this.getBlockInfo(o.id).stagingRendered?0:1;o.upstream.forEach(a=>{const c=t.get(a);c!==0&&(i=Math.max(c+1,i))}),e(o.id,i),t.set(o.id,i)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,s=e===void 0?void 0:1+Math.max(0,t*e/1e3);let o=0;this.traverseWithStagingLag((n,i)=>{i!==0&&(s===void 0||i<=s)&&(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 s,o,n,i;((s=t.fields.prodCtx)==null?void 0:s.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,mt(t)):this.tx.setKValue(this.rid,mt(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,vt):this.tx.setKValue(this.rid,vt,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,Te,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,pe,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,Ie,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,gt(e)):this.tx.setKValue(this.rid,gt(e),t)}this.assignAuthorMarkers()}}static async load(e,t,s){const o=e.getResourceData(t,!0),n=e.getKValueJson(t,Jr),i=e.getKValueJson(t,Te),a=e.getKValueJson(t,Ie),c=e.getKValueJson(t,pe),u=e.getKValueJson(t,Ke),l=e.listKeyValuesString(t),[d,h,g,R,m,{stagingRefreshTimestamp:G,blocksInLimbo:N},U]=await Promise.all([o,n,i,a,c,u,l]);if(h!==_r)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${h}`);const F=new Map;for(const p of d.fields){const v=ro(p.name);if(v===void 0)continue;let w=F.get(v.blockId);w===void 0&&(w={id:v.blockId,fields:{}},F.set(v.blockId,w)),w.fields[v.fieldName]=f.isNullResourceId(p.value)?{modCount:0}:{modCount:0,ref:p.value}}const _=await os(),fe=yt(_.hash),B=d.fields.find(p=>p.name===fe);let ne;B!==void 0?ne=f.ensureResourceIdNotNull(B.value):(ne=f.Pl.wrapInHolder(e,Xe(e,_.spec)),e.createField(f.field(t,yt(_.hash)),"Dynamic",ne));const ue={stagingRefreshTimestamp:G},X=new Set(N),ce=new Map;for(const p of U){const v=Zs(p.key);v!==void 0&&ce.set(v,p.value)}const Q=[];F.forEach(({fields:p})=>{for(const[,v]of Object.entries(p))if(v.ref!==void 0){if(!f.isResource(v.ref)||f.isResourceRef(v.ref))throw new Error("unexpected behaviour");Q.push([v,e.getResourceData(v.ref,!1)])}});for(const[p,v]of Q){const w=await v;p.value=w.data,f.isNotNullResourceId(w.error)?p.status="Error":w.resourceReady||f.isNotNullResourceId(w.originalResourceId)?p.status="Ready":p.status="NotReady"}const V=new Map;F.forEach(({id:p,fields:v})=>V.set(p,new ir(p,v)));const H=new Set;for(const p of ae(m)){if(!V.has(p.id))throw new Error(`Inconsistent project structure: no inputs for ${p.id}`);H.add(p.id)}V.forEach(p=>{if(!H.has(p.id))throw new Error(`Inconsistent project structure: no structure entry for ${p.id}`);p.check()});const y=new He(t,e,s,h,g,R,m,ue,X,V,ce,ne);return y.fixProblemsAndMigrate(),y}}async function Do(r,e=Ws){const t=r.createEphemeral(zs);r.lock(t);const s=String(Date.now());r.setKValue(t,Jr,JSON.stringify(_r)),r.setKValue(t,Ot,s),r.setKValue(t,Te,s),r.setKValue(t,Ie,JSON.stringify(e)),r.setKValue(t,pe,JSON.stringify(Hs)),r.setKValue(t,Ke,JSON.stringify(qs));const o=await os();return r.createField(f.field(t,yt(o.hash)),"Dynamic",f.Pl.wrapInHolder(r,Xe(r,o.spec))),t}async function Be(r,e,t){return re(r,e,void 0,t)}async function re(r,e,t,s){if(r instanceof f.PlClient)return await r.withWriteTx("ProjectAction",async o=>{const n=await He.load(o,e,t),i=await s(n);return n.wasModified&&(n.save(),await o.commit()),i});{const o=await He.load(r,e,t),n=await s(o);return o.save(),n}}function*Lo(r){switch(r.type){case"Json":return;case"JsonPartitioned":for(const[,e]of Object.entries(r.parts))yield e;return;case"BinaryPartitioned":for(const[,{index:e,values:t}]of Object.entries(r.parts))yield e,yield t;return;default:E.assertNever(r)}}function ar(r,e){return Object.fromEntries(Object.entries(r).map(([t,s])=>[t,e(s,t)]))}function No(r,e){switch(r.type){case"Json":return{...r};case"JsonPartitioned":return{...r,parts:ar(r.parts,e)};case"BinaryPartitioned":return{...r,parts:ar(r.parts,t=>({index:e(t.index),values:e(t.values)}))};default:E.assertNever(r)}}const Bo=f.resourceType("PColumnData/JsonPartitioned","1"),jo=f.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Vo=f.resourceType("PColumnData/BinaryPartitioned","1"),xo=f.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),Uo=f.resourceType("PColumnData/Json","1");function Go(r){if(!r.getIsReadyOrError())throw new Error("Data not ready.");const e=r.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(f.resourceTypesEqual(r.resourceType,Uo)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(f.resourceTypesEqual(r.resourceType,Bo)){const t=e,s=Object.fromEntries(r.listInputFields().map(o=>[o,r.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:s}}else if(f.resourceTypesEqual(r.resourceType,jo)){const t=e,s={};for(const o of r.listInputFields()){const n=r.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const a of i){const c=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);s[c]=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:s}}else if(f.resourceTypesEqual(r.resourceType,Vo)){const t=e,s={};for(const o of r.listInputFields())if(o.endsWith(".index")){const n=o.slice(0,o.length-6);let i=s[n];i===void 0&&(i={},s[n]=i),i.index=r.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else if(o.endsWith(".values")){const n=o.slice(0,o.length-7);let i=s[n];i===void 0&&(i={},s[n]=i),i.values=r.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${o}`);for(const[o,n]of Object.entries(s)){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:s}}else if(f.resourceTypesEqual(r.resourceType,xo)){const t=e,s={};for(const o of r.listInputFields()){const n=r.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const a of i)if(a.endsWith(".index")){const c=a.slice(0,a.length-6),u=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);let l=s[u];l===void 0&&(l={},s[u]=l),s[u].index=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else if(a.endsWith(".values")){const c=a.slice(0,a.length-7),u=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);let l=s[u];l===void 0&&(l={},s[u]=l),s[u].values=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${a}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:s}}throw new Error(`unsupported resource type: ${f.resourceTypeToString(r.resourceType)}`)}function Mo(r,e){const t=r.axesSpec.length,s={};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}`);s[JSON.stringify(o)]=n}return{type:"Json",keyLength:t,data:s}}function Jo(r,e){const t=ee.createHash("sha256");return t.update(x(r)),t.update(String(f.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function cr(r,e){return x({__isRef:!0,blockId:r,name:e})}function _o(r,e){return x({resolvePath:r,name:e})}function ns(r,e=!0,t=!1,s=""){var a,c,u;const o=/^(?<name>.*)\.(?<type>spec|data)$/,n=new Map;for(const l of r.listInputFields()){const d=l.match(o);if(!d){if(e)throw new Error(`unexpected field name ${l}`);continue}let h=E.notEmpty((a=d.groups)==null?void 0:a.name);if(!h.startsWith(s)){if(e)throw new Error(`unexpected field name ${l}`);continue}h=h.slice(s.length);const g=E.notEmpty((c=d.groups)==null?void 0:c.type);let R=n.get(h);switch(R===void 0&&(R={},n.set(h,R)),g){case"spec":R.spec=(u=r.traverse({field:l,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:u.getDataAsJson();break;case"data":R.hasData=!0,R.data=()=>r.traverseOrError({field:l,ignoreError:t});break}}const i=r.getInputsLocked();if(i)for(const[,l]of n)l.data===void 0&&(l.hasData=!1);return{locked:i,results:n}}function Ko(r,e=!0,t="",s){if(!r.getIsReadyOrError())throw new Error("resource is not ready");const o=ns(r,e,!1,t);Is(o.locked);const n={};for(const[i,a]of o.results){if(a.spec===void 0)throw new Error(`no spec for key ${i}`);if(a.hasData!==!0||a.data===void 0)throw new Error(`no data for key ${i}`);const c=a.data();if(c===void 0)throw new Error(`no data for key ${i}`);if(!c.ok)throw c.error;n[i]={id:s.length===0?Jo(a.spec,c.value):_o(s,i),spec:a.spec,data:c.value}}return n}class Ft{constructor(e,t){S(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let s=!0;e:for(const o of t.values())for(const n of[o.prod,o.staging])if(n!==void 0){if(!n.locked){s=!1;break e}for(const i of n.results.values())if(i.spec===void 0){s=!1;break e}}this.allSpecsAvailable=s}getSpecByRef(e,t){var n,i,a,c,u,l;const s=this.blocks.get(e);if(s===void 0)return;let o=(a=(i=(n=s.prod)==null?void 0:n.results)==null?void 0:i.get(t))==null?void 0:a.spec;if(o!==void 0||(o=(l=(u=(c=s.staging)==null?void 0:c.results)==null?void 0:u.get(t))==null?void 0:l.spec,o!==void 0))return o;s.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):s.staging.locked?s.prod!==void 0&&!s.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var i,a,c;const s=this.blocks.get(e);if(s===void 0)return;const o=(a=(i=s.prod)==null?void 0:i.results)==null?void 0:a.get(t),n=(c=o==null?void 0:o.data)==null?void 0:c.call(o);if(o!==void 0&&o.spec!==void 0&&n!==void 0)return D.mapValueInVOE(n,u=>({id:cr(e,t),spec:o.spec,data:u}));o!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),s.prod!==void 0&&!s.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const s=this.getDataOrErrorByRef(e,t);if(!(s===void 0||!s.ok))return s.value}getData(){const e=this.getDataWithErrors(),t=[];for(const s of e.entries)s.obj.id!==void 0&&s.obj.data.ok&&t.push({ref:s.ref,obj:{id:s.obj.id,spec:s.obj.spec,data:s.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,s;const o=i=>{s===void 0&&(s=i),t=!1},n=(i,a,c)=>{if(c.spec!==void 0&&c.hasData===!0&&c.data!==void 0){const u=c.data();u!==void 0?e.push({ref:Ne(i,a),obj:{id:u.ok?cr(i,a):void 0,spec:c.spec,data:u}}):o(`no_data:${i}:${a}`)}};for(const[i,a]of this.blocks){const c=new Set;if(a.prod!==void 0){a.prod.locked||o(`prod_not_locked:${i}`);for(const[u,l]of a.prod.results)c.add(u),n(i,u,l)}if(a.staging!==void 0){a.staging.locked||o(`staging_not_locked:${i}`);for(const[u,l]of a.staging.results)c.has(u)||n(i,u,l)}}return{entries:e,isComplete:t,instabilityMarker:s}}getSpecs(){const e=[];let t=!0,s;const o=n=>{s===void 0&&(s=n),t=!1};for(const[n,i]of this.blocks){const a=new Set;if(i.staging!==void 0){i.staging.locked||o(`staging_not_locked:${n}`);for(const[c,u]of i.staging.results)u.spec!==void 0&&(e.push({ref:Ne(n,c),obj:u.spec}),a.add(c))}else o(`staging_not_rendered:${n}`);if(i.prod!==void 0){i.prod.locked||o(`prod_not_locked:${n}`);for(const[c,u]of i.prod.results)a.has(c)||u.spec!==void 0&&e.push({ref:Ne(n,c),obj:u.spec})}}return{entries:e,isComplete:t,instabilityMarker:s}}calculateOptions(e){const t=[];for(const s of this.blocks.values()){const o=new Set,n=i=>{for(const[a,c]of i.results)o.has(a)||c.spec===void 0||(o.add(a),D.executePSpecPredicate(e,c.spec)&&t.push({label:s.info.label+" / "+a,ref:Ne(s.info.id,a),spec:c.spec}))};s.staging!==void 0&&n(s.staging),s.prod!==void 0&&n(s.prod)}return t}static create(e,t,s){const o=e.accessor(t).node(),n=E.notEmpty(o.getKeyValueAsJson(pe)),a=St(n).traverseIds("upstream",s),c=new Map;for(const u of ae(n)){if(!a.has(u.id))continue;const l=lr(o.traverse({field:J(u.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:J(u.id,"prodUiCtx"),stableIfNotFound:!0})),d=lr(o.traverse({field:J(u.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:J(u.id,"stagingUiCtx")}));c.set(u.id,{info:u,prod:l,staging:d})}return new Ft(e,c)}}function lr(r,e){if(e===void 0)return r?{locked:!1,results:new Map}:void 0;if(e.ok)return ns(e.value,!1,!0)}function At(r,e){return{blockId:e,args:n=>E.notEmpty(n.accessor(r).node().traverse({field:J(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),activeArgs:n=>{var i;return(i=n.accessor(r).node().traverse({field:J(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:i.getDataAsString()},uiState:n=>n.accessor(r).node().getKeyValueAsString(gt(e)),blockMeta:n=>{const i=n.accessor(r).node(),a=E.notEmpty(i.getKeyValueAsJson(pe)),c=new Map;for(const u of ae(a))c.set(u.id,u);return c}}}function is(r,e){return{...At(r,e),prod:t=>{var s;return(s=t.accessor(r).node({ignoreError:!0}).traverse({field:J(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:s.persist()},staging:t=>{var o;const s=(o=t.accessor(r).node({ignoreError:!0}).traverse({field:J(e,"stagingOutput"),ignoreError:!0}))==null?void 0:o.persist();return s===void 0&&t.markUnstable("staging_not_rendered"),s},getResultsPool:t=>Ft.create(t,r,e)}}function*Y(r,e){switch(yield r,r.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*Y(r.cfg);return;case"MakeObject":for(const[,t]of Object.entries(r.template))yield*Y(t);return;case"MakeArray":for(const t of r.template)yield*Y(t);return;case"GetJsonField":case"GetResourceField":yield*Y(r.source),yield*Y(r.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*Y(r.source),yield*Y(r.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*Y(r.source);return;case"IsEmpty":yield*Y(r.arg);return;case"Not":yield*Y(r.operand);return;case"And":case"Or":yield*Y(r.operand1),yield*Y(r.operand2);return;default:E.assertNever(r)}}function Ho(r,e){const t={};for(const[s,o]of Object.entries(r))t[s]=e(o);return t}function Ce(r,e){return r===void 0?void 0:e(r)}function qo(r){switch(r.type){case"GetImportProgress":return!0;default:return!1}}function Wo(r){for(const e of Y(r))if(qo(e))return!0;return!1}function Ye(r){return{type:"ReturnResult",result:r}}function $(r){return()=>Ye(r)}const zo=r=>{const e={};for(const[t,s]of Object.entries(r))e[t]=s;return $(e)},Xo=r=>{const e=r.source;if(e===void 0)return $(void 0);const t=[];for(const s of e)s instanceof Array?t.push(...s):t.push(s);return $(t)},Yo=r=>{const e=r.source,t=r.field;return e===void 0||t===void 0?$(void 0):({cCtx:s})=>{var o;return Ye((o=s.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function as(r,e){const t={},s=r.length;for(let o=0;o<s;o++)t[String(o)]=e(r[o]);return t}function Qo(r,e){return t=>{const s=t.source;return s===void 0?$(void 0):()=>({type:"ScheduleSubroutine",subroutine:cs(s.length),args:as(s,o=>T({...r,[e.itVar]:o},e.mapping))})}}function cs(r){return e=>{const t=[];for(let s=0;s<r;s++)t.push(e[String(s)]);return $(t)}}function Zo(r,e){return t=>{const s=t.source;if(s===void 0)return $(void 0);const o={};for(const[n,i]of Object.entries(s)){const a={...r,[e.itVar]:i};o[n]=T(a,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:en,args:o})}}const en=r=>$(r),tn=r=>{const e=r.arg;return $(e===void 0?void 0:e.length===0)},rn=r=>{const e=r.operand;return $(e===void 0?void 0:!e)},sn=r=>{const e=r.operand1,t=r.operand2;return $(e===void 0||t===void 0?void 0:e&&t)},on=r=>{const e=r.operand1,t=r.operand2;return $(e===void 0||t===void 0?void 0:e||t)},nn=r=>{const e=r.source;return e===void 0?$(void 0):({cCtx:t})=>{var s;return Ye((s=t.accessor(e).node())==null?void 0:s.getDataAsJson())}},an=r=>{const e=r.source,t=r.field;return $(e===void 0||t===void 0?void 0:e[t])};function cn(r,e){return t=>{const s=t.source;return s===void 0?$(void 0):({cCtx:o})=>{const n=o.accessor(s).node(),i={};for(const a of n.listInputFields()){const c=n.traverse(a);if(c===void 0)i[a]=$(void 0);else{const u={...r,[e.itVar]:c.persist()};i[a]=T(u,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:ln,args:i}}}}const ln=r=>$(r),un=r=>{const e=r.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:j.Computable.make(s=>t.blobDriver.getDownloadedBlob(s.accessor(e).node().resourceInfo),{postprocessValue:async s=>{if(s!==void 0)return await t.blobDriver.getContent(s.handle)}})})},dn=r=>{const e=r.source;return e===void 0?$(void 0):({cCtx:t,drivers:s})=>{const o=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:j.Computable.make(()=>s.blobDriver.getDownloadedBlob(o),{postprocessValue:async n=>n===void 0?void 0:(await s.blobDriver.getContent(n.handle)).toString()})}}},pn=r=>{const e=r.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:j.Computable.make(s=>t.blobDriver.getDownloadedBlob(s.accessor(e).node().resourceInfo),{postprocessValue:async s=>{if(s==null)return;const o=await t.blobDriver.getContent(s.handle);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},fn=r=>{const e=r.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},hn=r=>{const e=r.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},gn=r=>e=>{const t=e.source;return t===void 0?$(void 0):({drivers:s})=>({type:"ScheduleComputable",computable:s.blobToURLDriver.extractArchiveAndGetURL(t,r)})},mn=r=>{const e=r.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},vn=r=>e=>{const t=e.source;return t===void 0?$(void 0):({drivers:s})=>({type:"ScheduleComputable",computable:s.logDriver.getLastLogs(t,r)})},yn=r=>e=>{const t=e.source;return t===void 0?$(void 0):({drivers:s})=>({type:"ScheduleComputable",computable:s.logDriver.getProgressLog(t,r)})},wn=r=>e=>{const t=e.source;return t===void 0?$(void 0):({drivers:s})=>({type:"ScheduleComputable",computable:s.logDriver.getProgressLogWithInfo(t,r)})},Sn=r=>{const e=r.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function T(r,e){switch(e.type){case"GetFromCtx":{const t=r[e.variable];return typeof t=="function"?s=>Ye(t(s.cCtx)):$(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:ds(t,r,e.cfg)});case"Immediate":return $(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:an,args:{source:T(r,e.source),field:T(r,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:Qo(r,e),args:{source:T(r,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:Zo(r,e),args:{source:T(r,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:zo,args:Ho(e.template,t=>T(r,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:cs(e.template.length),args:as(e.template,t=>T(r,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:Xo,args:{source:T(r,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:tn,args:{arg:T(r,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:rn,args:{operand:T(r,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:sn,args:{operand1:T(r,e.operand1),operand2:T(r,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:on,args:{operand1:T(r,e.operand1),operand2:T(r,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:cn(r,e),args:{source:T(r,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:Yo,args:{source:T(r,e.source),field:T(r,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:nn,args:{source:T(r,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:un,args:{source:T(r,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:dn,args:{source:T(r,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:pn,args:{source:T(r,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:fn,args:{source:T(r,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:hn,args:{source:T(r,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:gn(e.format),args:{source:T(r,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:mn,args:{source:T(r,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:vn(e.lines),args:{source:T(r,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:yn(e.patternToSearch),args:{source:T(r,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:wn(e.patternToSearch),args:{source:T(r,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:Sn,args:{source:T(r,e.source)}});default:return E.assertNever(e)}}const bn=["$prod","$staging"];function Pn(r){return{$blockId:r.blockId,$args:e=>JSON.parse(r.args(e)),$ui:e=>{const t=r.uiState(e);return t!==void 0?JSON.parse(t):void 0},$prod:r.prod,$staging:r.staging}}const ls=Symbol(),us="return",Rn={op:ls,arg:us};function Cn(r){return r.op==ls&&r.arg==us}function En(){return{pendingSubroutines:new Map}}function ur(r,e,t,s){const o=new jr(t),n=(a,c)=>{if(Cn(a))return e.result=c,!1;const u=E.notEmpty(e.pendingSubroutines.get(a.op));if(a.arg in u.args)throw new Error("argument already set");return u.args[a.arg]=c,u.argCounter--,u.argCounter===0&&(e.pendingSubroutines.delete(a.op),o.push({destination:u.destination,operation:u.subroutine(u.args)})),!0},i=[];e:for(;o.length>0;){const a=o.shift(),c=a.operation(r);switch(c.type){case"ReturnResult":if(!n(a.destination,c.result))break e;break;case"ScheduleSubroutine":{const u=Symbol(),l=Object.entries(c.args),d=l.length;if(d===0)o.push({destination:a.destination,operation:c.subroutine({})});else{for(const[h,g]of l)o.push({destination:{op:u,arg:h},operation:g});e.pendingSubroutines.set(u,{argCounter:d,args:{},subroutine:c.subroutine,destination:a.destination})}}break;case"ScheduleComputable":if(!s)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:a.destination,computable:c.computable});break;default:E.assertNever(c)}}return i}function kn(r,e,t,s={}){return ds(r,Pn(e),t,s)}function ds(r,e,t,s={}){const o=`${e.blockId}#`+x({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>bn.indexOf(n)===-1)),cfg:t});return j.Computable.makeRaw(n=>{const i={drivers:r,cCtx:n},a=En();return{ir:ur(i,a,[{destination:Rn,operation:T(e,t)}],!0),postprocessValue(u){const l=[];for(const R of u)l.push({destination:R.destination,operation:$(R.computable)});const d={drivers:r,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},h=new Map;for(const[R,m]of a.pendingSubroutines)h.set(R,{...m,args:{...m.args}});const g={result:a.result,pendingSubroutines:h};if(ur(d,g,l,!1),!("result"in g))throw new Error("illegal cfg rendering stack state, no result");return g.result}}},{...s,key:o})}function On(r){return r instanceof ArrayBuffer||ArrayBuffer.isView(r)}function dr(r){return r!==void 0?Buffer.from(r).toString("base64"):void 0}class qe{constructor(e,t,s,o,n,i){S(this,"callbackRegistry");S(this,"fnJSONStringify");S(this,"fnJSONParse");S(this,"computablesToResolve",{});S(this,"computableCtx");S(this,"accessors",new Map);S(this,"meta");S(this,"errorRepo",new $n);S(this,"_resultPool");if(this.scope=e,this.vm=t,this.blockCtx=s,this.env=o,this.deadlineSetter=n,this.computableCtx=i,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(a=>t.getProp(a,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(a=>t.getProp(a,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");this.meta=s.blockMeta(i),this.injectCtx()}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}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 qe.cleanErrorContext(t),t}finally{this.deadlineSetter(void 0)}}runCallback(e,...t){try{return this.deadlineSetter({currentExecutionTarget:e,deadline:Date.now()+1e4}),$e.Scope.withScope(s=>{const o=s.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,s)))))})}catch(s){throw qe.cleanErrorContext(s),this.errorRepo.getOriginal(s)}finally{this.deadlineSetter(void 0)}}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(s,o)=>{if(!this.accessors.has(s)){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(s,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(s,void 0)}return this.accessors.get(s)?s:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...s){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...s))}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 dr(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return dr(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,s,...o){const n=this.getAccessor(e);if(!n.getIsReadyOrError())return;const i=Ko(n,t,s,o),a={};for(const[c,u]of Object.entries(i))a[c]=D.mapPObjectData(u,l=>this.wrapAccessor(l));return a}registerComputable(e,t){const s=`${e}_${ee.randomUUID()}`;return this.computablesToResolve[s]=t,s}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",j.Computable.make(s=>this.env.driverKit.blobDriver.getDownloadedBlob(t,s),{postprocessValue:async s=>{if(s!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(s.handle)).toString("utf-8")}}))}getBlobContentAsBase64(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",j.Computable.make(s=>this.env.driverKit.blobDriver.getDownloadedBlob(t,s),{postprocessValue:async s=>{if(s!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(s.handle)).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 s=this.getAccessor(e).persist();return this.registerComputable("extractArchiveAndGetURL",this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(s,t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const s=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(s,t))}getProgressLog(e,t){const s=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(s,t))}getProgressLogWithInfo(e,t){const s=this.getAccessor(e).persist();return this.registerComputable("getProgressLogWithInfo",this.env.driverKit.logDriver.getProgressLogWithInfo(s,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=E.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,s=>this.wrapAccessor(s))}))}}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,s=>this.wrapAccessor(s))}}))}}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),s=>this.wrapAccessor(s))}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,s=>this.transformInputPData(s))),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,s=>this.transformInputPData(s))),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}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=ee.randomUUID();return this.accessors.set(t,e),t}}exportSingleValue(e,t){const s=this.tryExportSingleValue(e,t);if(s===void 0)throw new Error(`Can't export value: ${e===void 0?"undefined":JSON.stringify(e)}`);return s}tryExportSingleValue(e,t){let s,o=!1;switch(typeof e){case"string":s=this.vm.newString(e),o=!0;break;case"number":s=this.vm.newNumber(e),o=!0;break;case"undefined":s=this.vm.undefined;break;case"boolean":s=e?this.vm.true:this.vm.false;break;default:if(e===null){s=this.vm.null;break}if(On(e)){s=this.vm.newArrayBuffer(e),o=!0;break}return}return o&&t!=null?t.manage(s):s}exportObjectUniversal(e,t){const s=this.tryExportSingleValue(e,t);return s!==void 0?s:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const s=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(s):s}importObjectUniversal(e){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(s=>this.vm.getString(s));if(t!=="undefined")return JSON.parse(t)}injectCtx(){$e.Scope.withScope(e=>{const t=e.manage(this.vm.newObject()),s=this.blockCtx.args(this.computableCtx),o=this.blockCtx.activeArgs(this.computableCtx),n=this.blockCtx.uiState(this.computableCtx);this.vm.setProp(t,"args",e.manage(this.vm.newString(s))),n!==void 0&&this.vm.setProp(t,"uiState",e.manage(this.vm.newString(n))),o!==void 0&&this.vm.setProp(t,"activeArgs",e.manage(this.vm.newString(o))),this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(D.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e));const i=(a,c)=>{const u=(...l)=>{try{return c(...l)}catch(d){const h=this.errorRepo.setAndRecreateForQuickJS(d);throw this.vm.newError(h)}};this.vm.newFunction(a,u).consume(l=>this.vm.setProp(t,a,l)),this.vm.newFunction(a,c).consume(l=>this.vm.setProp(t,a+"__internal__",l))};i("getAccessorHandleByName",a=>this.exportSingleValue(this.getAccessorHandleByName(this.vm.getString(a)),void 0)),i("resolveWithCommon",(a,c,...u)=>this.exportSingleValue(this.resolveWithCommon(this.vm.getString(a),this.importObjectViaJson(c),...u.map(l=>this.importObjectViaJson(l))),void 0)),i("getResourceType",a=>this.exportObjectViaJson(this.getResourceType(this.vm.getString(a)),void 0)),i("getInputsLocked",a=>this.exportSingleValue(this.getInputsLocked(this.vm.getString(a)),void 0)),i("getOutputsLocked",a=>this.exportSingleValue(this.getOutputsLocked(this.vm.getString(a)),void 0)),i("getIsReadyOrError",a=>this.exportSingleValue(this.getIsReadyOrError(this.vm.getString(a)),void 0)),i("getIsFinal",a=>this.exportSingleValue(this.getIsFinal(this.vm.getString(a)),void 0)),i("getError",a=>this.exportSingleValue(this.getError(this.vm.getString(a)),void 0)),i("listInputFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("listOutputFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("listDynamicFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("getKeyValueBase64",(a,c)=>this.exportSingleValue(this.getKeyValueBase64(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getKeyValueAsString",(a,c)=>this.exportSingleValue(this.getKeyValueAsString(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getDataBase64",a=>this.exportSingleValue(this.getDataBase64(this.vm.getString(a)),void 0)),i("getDataAsString",a=>this.exportSingleValue(this.getDataAsString(this.vm.getString(a)),void 0)),i("parsePObjectCollection",(a,c,u,...l)=>this.exportObjectUniversal(this.parsePObjectCollection(this.vm.getString(a),this.vm.dump(c),this.vm.getString(u),...l.map(d=>this.vm.getString(d))),void 0)),i("getBlobContentAsBase64",a=>this.exportSingleValue(this.getBlobContentAsBase64(this.vm.getString(a)),void 0)),i("getBlobContentAsString",a=>this.exportSingleValue(this.getBlobContentAsString(this.vm.getString(a)),void 0)),i("getDownloadedBlobContentHandle",a=>this.exportSingleValue(this.getDownloadedBlobContentHandle(this.vm.getString(a)),void 0)),i("getOnDemandBlobContentHandle",a=>this.exportSingleValue(this.getOnDemandBlobContentHandle(this.vm.getString(a)),void 0)),i("extractArchiveAndGetURL",(a,c)=>this.exportSingleValue(this.extractArchiveAndGetURL(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getImportProgress",a=>this.exportSingleValue(this.getImportProgress(this.vm.getString(a)),void 0)),i("getLastLogs",(a,c)=>this.exportSingleValue(this.getLastLogs(this.vm.getString(a),this.vm.getNumber(c)),void 0)),i("getProgressLog",(a,c)=>this.exportSingleValue(this.getProgressLog(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getProgressLogWithInfo",(a,c)=>this.exportSingleValue(this.getProgressLogWithInfo(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getLogHandle",a=>this.exportSingleValue(this.getLogHandle(this.vm.getString(a)),void 0)),i("getBlockLabel",a=>this.exportSingleValue(this.getBlockLabel(this.vm.getString(a)),void 0)),i("getDataFromResultPool",()=>this.exportObjectUniversal(this.getDataFromResultPool(),void 0)),i("getDataWithErrorsFromResultPool",()=>this.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),i("getSpecsFromResultPool",()=>this.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),i("calculateOptions",a=>this.exportObjectUniversal(this.calculateOptions(this.importObjectViaJson(a)),void 0)),i("getSpecFromResultPoolByRef",(a,c)=>this.exportObjectUniversal(this.getSpecFromResultPoolByRef(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getDataFromResultPoolByRef",(a,c)=>this.exportObjectUniversal(this.getDataFromResultPoolByRef(this.vm.getString(a),this.vm.getString(c)),void 0)),i("createPFrame",a=>this.exportSingleValue(this.createPFrame(this.importObjectViaJson(a)),void 0)),i("createPTable",a=>this.exportSingleValue(this.createPTable(this.importObjectViaJson(a)),void 0)),i("getCurrentUnstableMarker",()=>this.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}class $n{constructor(){S(this,"errorIdToError",new Map)}setAndRecreateForQuickJS(e){const t=ee.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 $e.errors.QuickJSUnwrapError))return console.warn("ErrorRepo: quickJSError is not a QuickJSUnwrapError",f.stringifyWithResourceId(e)),e;if(!("name"in e.cause))return console.warn("ErrorRepo: quickJSError.cause is not an Error",f.stringifyWithResourceId(e)),e;const t=e.cause.name,s=t.slice(t.indexOf("/uuid:")+6);if(!s)throw new Error(`ErrorRepo: quickJSError.cause.name does not contain errorId: ${t}, ${f.stringifyWithResourceId(e)}`);const o=this.errorIdToError.get(s);if(o===void 0)throw new Error(`ErrorRepo: errorId not found: ${s}, ${f.stringifyWithResourceId(e)}`);return new Fs.PlQuickJSError(e,o)}}function Qe(r,e){return Ce(r.traverse({field:J(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:f.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const s=t.getDataAsJson(),o=D.extractConfig(s.config);return{bpId:t.resourceInfo.id.toString(),info:s,cfg:o}})}const je=process.env.MI_LOG_OUTPUT_STATUS;function Tn(r,e,t,s,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"),j.Computable.makeRaw(a=>{const c=new $e.Scope;a.addOnDestroy(()=>c.dispose());const u=c.manage(r.quickJs.newRuntime());u.setMemoryLimit(1024*1024*8),u.setMaxStackSize(1024*320);let l;u.setInterruptHandler(()=>l===void 0?!1:Date.now()>l.deadline);const d=c.manage(u.newContext()),h=new qe(c,d,e,r,m=>{l=m},a);h.evaluateBundle(s.content);const g=h.runCallback(t.handle);h.resetComputableCtx();let R=0;return je&&je!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:h.computablesToResolve,postprocessValue:(m,{unstableMarker:G,stable:N})=>{for(const[F,_]of Object.entries(m))h.runCallback(F,_);const U=h.importObjectUniversal(g);return R++,je&&(je!=="unstable-only"||!N)&&console.log(N?`Stable output ${t.handle} calculated ${U!==void 0?"defined":"undefined"}; (#${R})`:`Unstable output ${t.handle}; marker = ${G}; ${U!==void 0?"defined":"undefined"} (#${R})`),U}}},n)}function In(r){return D.isConfigLambda(r)?r.isActive===!0:Wo(r)}function Ee(r,e,t,s,o,n={}){if(D.isConfigLambda(t)){if(s===void 0)throw new Error("No code bundle.");return Tn(r,e,t,s,o,n)}else return kn(r.driverKit,e,t,n)}function Fn(r,e){if(r===e)return!0;if(r===void 0||e===void 0)return!1;const t=zt.omitBy((s,o)=>o.startsWith("__"));return zt.isDeepEqual(t(r),t(e))}function An(r,e,t){return j.Computable.make(s=>{var R,m,G,N,U,F,_,fe;const o=s.accessor(r).node(),n=E.notEmpty(o.getKeyValueAsJson(Ot)),i=E.notEmpty(o.getKeyValueAsJson(Te)),a=E.notEmpty(o.getKeyValueAsJson(Ie)),c=E.notEmpty(o.getKeyValueAsJson(pe)),u=E.notEmpty(o.getKeyValueAsJson(Ke)),l=new Map;for(const{id:B}of ae(c)){const ue=o.traverse({field:J(B,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson();let X;const ce=o.traverse({field:J(B,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(ce!==void 0){const Q=ce.getDataAsJson(),V=o.getField({field:J(B,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),H=o.getField({field:J(B,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});X={arguments:Q,stale:!Fn(ue,Q),outputError:V.error!==void 0||H.error!==void 0||((R=V.value)==null?void 0:R.getError())!==void 0||((m=H.value)==null?void 0:m.getError())!==void 0,outputsError:((G=V.error)==null?void 0:G.getDataAsString())??((U=(N=V.value)==null?void 0:N.getError())==null?void 0:U.getDataAsString()),exportsError:((F=H.error)==null?void 0:F.getDataAsString())??((fe=(_=H.value)==null?void 0:_.getError())==null?void 0:fe.getDataAsString()),finished:(V.value!==void 0&&V.value.getIsReadyOrError()||V.error!==void 0&&V.error.getIsReadyOrError())&&(H.value!==void 0&&H.value.getIsReadyOrError()||H.error!==void 0&&H.error.getIsReadyOrError())}}l.set(B,{currentArguments:ue,prod:X})}const d=Je(c,B=>l.get(B).currentArguments),h=new Set(u.blocksInLimbo),g=[...ae(c)].map(({id:B,label:ne,renderingMode:ue})=>{var b,C,I,O,L;const X=E.notEmpty(l.get(B)),ce=E.notEmpty(d.nodes.get(B));let Q="NotCalculated";X.prod!==void 0&&(h.has(B)?Q="Limbo":Q=X.prod.finished?"Done":"Running");const V=Qe(o,B),{sections:H,title:y,inputsValid:p,sdkVersion:v}=Ce(V,({bpId:M,cfg:A})=>{const le=At(r,B);return{sections:Ee(t,le,A.sections,A.code,M).wrap({recover:we=>(t.logger.error("Error in block model sections"),t.logger.error(we),[])}),title:Ce(A.title,we=>Ee(t,le,we,A.code,M).wrap({recover:Rs=>(t.logger.error("Error in block model title"),t.logger.error(Rs),"Invalid title")})),inputsValid:Ee(t,le,A.inputsValid,A.code,M).wrap({recover:we=>(t.logger.error("Error in block model argsValid"),t.logger.error(we),!1)}),sdkVersion:A.sdkVersion}})||{},w=o.traverse({field:J(B,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),P=Ce(V,({info:M})=>t.blockUpdateWatcher.get({currentSpec:M.source,settings:w}));return{projectResourceId:f.resourceIdToString(r.rid),id:B,label:y??ne,title:y??ne,renderingMode:ue,stale:((b=X.prod)==null?void 0:b.stale)!==!1||Q==="Limbo",missingReference:ce.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",B)],downstreams:[...d.traverseIdsExcludingRoots("downstream",B)],calculationStatus:Q,outputErrors:((C=X.prod)==null?void 0:C.outputError)===!0,outputsError:(I=X.prod)==null?void 0:I.outputsError,exportsError:(O=X.prod)==null?void 0:O.exportsError,settings:w,sections:H,inputsValid:p,updateInfo:{},currentBlockPack:(L=V==null?void 0:V.info)==null?void 0:L.source,updates:P,sdkVersion:v,navigationState:e.getState(B)}});return{meta:a,created:new Date(n),lastModified:new Date(i),authorMarker:o.getKeyValueAsJson(vt),blocks:g}},{postprocessValue:s=>{const o=new Set,n=new Set;return{...s,blocks:s.blocks.map(i=>{var l,d;i.inputsValid||o.add(i.id),i.stale&&n.add(i.id);const a=i.stale||i.upstreams.findIndex(h=>n.has(h))!==-1,c=(a||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(h=>o.has(h))===-1,u={...i,canRun:c,stale:a,updateSuggestions:((l=i.updates)==null?void 0:l.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete u.updates,u})}}}).withStableType()}function Dn(r,e){const t=r.node();if(f.resourceTypesEqual(t.resourceType,Tt)){const s=t.getDataAsJson();if(s===void 0)throw new Error("No resource data.");return e.frontendDownloadDriver.getPath(new URL(s.url)).withStableType()}else if(f.resourceTypesEqual(t.resourceType,It)){const s=t.getDataAsJson();if(s===void 0)throw new Error("No resource data.");return e.signer.verify(s.path,s.signature,`Frontend path signature mismatch for: ${s.path}`),s.path}else throw new Error(`Unsupported resource type: ${JSON.stringify(t.resourceType)}`)}function Ln(r,e){if(r!==void 0)return j.Computable.make(t=>Dn(t.accessor(r),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 Nn(r,e,t){return j.Computable.make(s=>{var a;const o=s.accessor(r).node(),n=Qe(o,e),i=(a=o.traverse({field:J(e,"blockPack"),assertFieldType:"Dynamic"},{field:f.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:rs,assertFieldType:"Input"}))==null?void 0:a.persist();return{path:Ln(i,t),sdkVersion:n==null?void 0:n.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function ps(r,e,t){if(t===void 0)return j.Computable.make(i=>ps(r,e,i),{key:`inputs#${f.resourceIdToString(r.rid)}#${e}`});const s=t.accessor(r).node(),o=At(r,e),n=o.uiState(t);return{author:s.getKeyValueAsJson(mt(e)),args:E.deepFreeze(JSON.parse(o.args(t))),ui:n!==void 0?E.deepFreeze(JSON.parse(n)):void 0}}function Bn(r,e,t){return j.Computable.make(s=>{const o=s.accessor(r).node(),n=is(r,e);return Ce(Qe(o,e),({cfg:i,bpId:a})=>{const c={};for(const[u,l]of Object.entries(i.outputs)){const d=Ee(t,n,l,i.code,a);c[u]=j.Computable.wrapError(d,1)}return c})},{key:"outputs#"+f.resourceIdToString(r.rid)+"#"+e}).withStableType()}function jn(r,e){return j.Computable.make(t=>{const s=t.accessor(r).node(),o=E.notEmpty(s.getKeyValueAsJson(pe)),n=[];for(const{id:i}of ae(o)){const a=Qe(s,i);if(a===void 0)continue;const c=Object.entries(a.cfg.outputs).map(([,l])=>l).filter(l=>In(l)).map(l=>l);if(c.length===0)continue;const u=is(s.persist(),i);for(const l of c)n.push(j.Computable.wrapError(Ee(e,u,l,a.cfg.code,a.bpId)))}return n})}class Vn{constructor(){S(this,"states",new Map)}setState(e,t){const s=this.states.get(e);if(s===void 0){this.states.set(e,{state:t,change:new j.ChangeSource});return}s.state={...t},s.change.markChanged()}readState(e,t){let s=this.states.get(t);return s===void 0&&(s={state:{...D.DefaultNavigationState},change:new j.ChangeSource},this.states.set(t,s)),s.change.attachWatcher(e.watcher),s.state}getState(e){return j.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 pr(r){return JSON.stringify(r,(e,t)=>typeof t=="bigint"?f.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 Ze{constructor(e,t,s){S(this,"rid");S(this,"overview");S(this,"navigationStates",new Vn);S(this,"blockComputables",new Map);S(this,"blockFrontends",new Map);S(this,"activeConfigs");S(this,"refreshLoopResult");S(this,"abortController",new AbortController);S(this,"destroyed",!1);this.env=e,this.projectTree=s,this.overview=An(s.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=jn(s.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await Be(this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await Vr.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(f.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!f.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,s,o=void 0,n=ee.randomUUID()){const i=await this.env.bpPreparer.prepare(t),a=await this.env.bpPreparer.getBlockConfigContainer(t),c=D.extractConfig(a);return await re(this.env.pl,this.rid,o,u=>u.addBlock({id:n,label:e,renderingMode:c.renderingMode},{args:x(c.initialArgs),uiState:x(c.initialUiState),blockPack:i},s)),await this.projectTree.refreshState(),n}async updateBlockPack(e,t,s=!1,o){const n=await this.env.bpPreparer.prepare(t),i=D.extractConfig(await this.env.bpPreparer.getBlockConfigContainer(t));await re(this.env.pl,this.rid,o,a=>a.migrateBlockPack(e,n,s?{args:x(i.initialArgs),uiState:x(i.initialUiState)}:void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await re(this.env.pl,this.rid,t,s=>s.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await re(this.env.pl,this.rid,t,s=>{const o=s.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(a=>{const c=n.blocks.find(u=>u.id===a);if(c===void 0)throw new Error(`Can't find block: ${a}`);return c})}]};s.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await Be(this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await Be(this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,s){await re(this.env.pl,this.rid,s,o=>o.setArgs([{blockId:e,args:x(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,s){await re(this.env.pl,this.rid,s,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,s,o){await re(this.env.pl,this.rid,o,n=>{n.setArgs([{blockId:e,args:x(t)}]),n.setUiState(e,x(s))}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await re(this.env.pl,this.rid,void 0,s=>{s.setBlockSettings(e,t)}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async s=>{const o=f.ensureResourceIdNotNull((await s.getField(f.field(this.rid,J(e,"blockPack")))).value),n=f.ensureResourceIdNotNull((await s.getField(f.field(o,f.Pl.HolderRefField))).value),i=await s.getResourceData(n,!1),a=D.extractConfig(JSON.parse(Buffer.from(E.notEmpty(i.data)).toString("utf-8")).config);await re(s,this.rid,t,c=>{c.setArgs([{blockId:e,args:x(a.initialArgs)}]),c.setUiState(e,x(a.initialUiState))}),await s.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===void 0){const s=Bn(this.projectTree.entry(),e,this.env),n={fullState:j.Computable.make(i=>({argsAndUiState:ps(this.projectTree.entry(),e,i),outputs:s,navigationState:this.navigationStates.getState(e),overview:this.overview}),{postprocessValue:i=>{var l,d,h;const a=(h=(d=(l=i.overview)==null?void 0:l.blocks)==null?void 0:d.find(g=>g.id==e))==null?void 0:h.sdkVersion,u=a&&Un(a)&&i.outputs!==void 0?Mn(i.outputs):i.outputs;return{...i.argsAndUiState,outputs:u,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 s=Nn(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,s),s}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.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){await Be(e.pl,t,o=>{});const s=await _e.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:xn},e.logger);if(e.ops.debugOps.dumpInitialTreeState){const o=s.dumpState();o.sort((i,a)=>{var c,u;return(((c=a.data)==null?void 0:c.byteLength)??0)-(((u=i.data)==null?void 0:u.byteLength)??0)});const n=_e.treeDumpStats(o);await ht.writeFile(`${f.resourceIdToString(t)}.json`,pr(o)),await ht.writeFile(`${f.resourceIdToString(t)}.stats.json`,pr(n))}return new Ze(e,t,s)}}function xn(r){switch(r.type.name){case"BlockPackCustom":return r.fields.filter(e=>e.name!=="template");case"UserProject":return r.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return r.fields}}function Un(r){return!Gn(r,"1.26.0")}function Gn(r,e){const t=r.split(".").map(Number),s=e.split(".").map(Number);return t[0]>s[0]||t[0]===s[0]&&t[1]>s[1]||t[0]===s[0]&&t[1]===s[1]&&t[2]>s[2]}function Mn(r){const e={};for(const[t,s]of Object.entries(r)){if(s.ok){e[t]=s;continue}e[t]={ok:!1,errors:s.errors.map(o=>typeof o=="string"?o:o.type=="PlError"&&o.fullMessage!==void 0?o.fullMessage:o.message),moreErrors:s.moreErrors}}return e}const Dt={logger:new E.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 Lt(r){return{blobDownloadPath:K.join(r,"download"),downloadBlobToURLPath:K.join(r,"downloadToURL")}}const fs={...Dt,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500,initialTreeLoadingTimeout:100*60*60*1e3},debugOps:{dumpInitialTreeState:!1},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function hs(r){return{...Lt(r),frontendDownloadPath:K.join(r,"frontend")}}function Jn(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Pt={exports:{}};const _n="2.0.0",gs=256,Kn=Number.MAX_SAFE_INTEGER||9007199254740991,Hn=16,qn=gs-6,Wn=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var et={MAX_LENGTH:gs,MAX_SAFE_COMPONENT_LENGTH:Hn,MAX_SAFE_BUILD_LENGTH:qn,MAX_SAFE_INTEGER:Kn,RELEASE_TYPES:Wn,SEMVER_SPEC_VERSION:_n,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2};const zn=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};var tt=zn;(function(r,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:s,MAX_LENGTH:o}=et,n=tt;e=r.exports={};const i=e.re=[],a=e.safeRe=[],c=e.src=[],u=e.safeSrc=[],l=e.t={};let d=0;const h="[a-zA-Z0-9-]",g=[["\\s",1],["\\d",o],[h,s]],R=G=>{for(const[N,U]of g)G=G.split(`${N}*`).join(`${N}{0,${U}}`).split(`${N}+`).join(`${N}{1,${U}}`);return G},m=(G,N,U)=>{const F=R(N),_=d++;n(G,_,N),l[G]=_,c[_]=N,u[_]=F,i[_]=new RegExp(N,U?"g":void 0),a[_]=new RegExp(F,U?"g":void 0)};m("NUMERICIDENTIFIER","0|[1-9]\\d*"),m("NUMERICIDENTIFIERLOOSE","\\d+"),m("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`),m("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})`),m("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASEIDENTIFIER",`(?:${c[l.NUMERICIDENTIFIER]}|${c[l.NONNUMERICIDENTIFIER]})`),m("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NUMERICIDENTIFIERLOOSE]}|${c[l.NONNUMERICIDENTIFIER]})`),m("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`),m("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`),m("BUILDIDENTIFIER",`${h}+`),m("BUILD",`(?:\\+(${c[l.BUILDIDENTIFIER]}(?:\\.${c[l.BUILDIDENTIFIER]})*))`),m("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`),m("FULL",`^${c[l.FULLPLAIN]}$`),m("LOOSEPLAIN",`[v=\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`),m("LOOSE",`^${c[l.LOOSEPLAIN]}$`),m("GTLT","((?:<|>)?=?)"),m("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),m("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\*`),m("XRANGEPLAIN",`[v=\\s]*(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?)?)?`),m("XRANGEPLAINLOOSE",`[v=\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?)?)?`),m("XRANGE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAIN]}$`),m("XRANGELOOSE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAINLOOSE]}$`),m("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),m("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\d])`),m("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?(?:${c[l.BUILD]})?(?:$|[^\\d])`),m("COERCERTL",c[l.COERCE],!0),m("COERCERTLFULL",c[l.COERCEFULL],!0),m("LONETILDE","(?:~>?)"),m("TILDETRIM",`(\\s*)${c[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",m("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`),m("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`),m("LONECARET","(?:\\^)"),m("CARETTRIM",`(\\s*)${c[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",m("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`),m("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`),m("COMPARATORLOOSE",`^${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]})$|^$`),m("COMPARATOR",`^${c[l.GTLT]}\\s*(${c[l.FULLPLAIN]})$|^$`),m("COMPARATORTRIM",`(\\s*)${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",m("HYPHENRANGE",`^\\s*(${c[l.XRANGEPLAIN]})\\s+-\\s+(${c[l.XRANGEPLAIN]})\\s*$`),m("HYPHENRANGELOOSE",`^\\s*(${c[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[l.XRANGEPLAINLOOSE]})\\s*$`),m("STAR","(<|>)?=?\\s*\\*"),m("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),m("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(Pt,Pt.exports);var Fe=Pt.exports;const Xn=Object.freeze({loose:!0}),Yn=Object.freeze({}),Qn=r=>r?typeof r!="object"?Xn:r:Yn;var Nt=Qn;const fr=/^[0-9]+$/,ms=(r,e)=>{const t=fr.test(r),s=fr.test(e);return t&&s&&(r=+r,e=+e),r===e?0:t&&!s?-1:s&&!t?1:r<e?-1:1},Zn=(r,e)=>ms(e,r);var vs={compareIdentifiers:ms,rcompareIdentifiers:Zn};const Ve=tt,{MAX_LENGTH:hr,MAX_SAFE_INTEGER:xe}=et,{safeRe:gr,safeSrc:mr,t:Ue}=Fe,ei=Nt,{compareIdentifiers:he}=vs;let ti=class ie{constructor(e,t){if(t=ei(t),e instanceof ie){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>hr)throw new TypeError(`version is longer than ${hr} characters`);Ve("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const s=e.trim().match(t.loose?gr[Ue.LOOSE]:gr[Ue.FULL]);if(!s)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+s[1],this.minor=+s[2],this.patch=+s[3],this.major>xe||this.major<0)throw new TypeError("Invalid major version");if(this.minor>xe||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>xe||this.patch<0)throw new TypeError("Invalid patch version");s[4]?this.prerelease=s[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){const n=+o;if(n>=0&&n<xe)return n}return o}):this.prerelease=[],this.build=s[5]?s[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(Ve("SemVer.compare",this.version,this.options,e),!(e instanceof ie)){if(typeof e=="string"&&e===this.version)return 0;e=new ie(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof ie||(e=new ie(e,this.options)),he(this.major,e.major)||he(this.minor,e.minor)||he(this.patch,e.patch)}comparePre(e){if(e instanceof ie||(e=new ie(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 s=this.prerelease[t],o=e.prerelease[t];if(Ve("prerelease compare",t,s,o),s===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(s===void 0)return-1;if(s===o)continue;return he(s,o)}while(++t)}compareBuild(e){e instanceof ie||(e=new ie(e,this.options));let t=0;do{const s=this.build[t],o=e.build[t];if(Ve("build compare",t,s,o),s===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(s===void 0)return-1;if(s===o)continue;return he(s,o)}while(++t)}inc(e,t,s){if(e.startsWith("pre")){if(!t&&s===!1)throw new Error("invalid increment argument: identifier is empty");if(t){const o=new RegExp(`^${this.options.loose?mr[Ue.PRERELEASELOOSE]:mr[Ue.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,s);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,s);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,s),this.inc("pre",t,s);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,s),this.inc("pre",t,s);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(s)?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(".")&&s===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(t){let n=[t,o];s===!1&&(n=[t]),he(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 z=ti;const vr=z,ri=(r,e,t=!1)=>{if(r instanceof vr)return r;try{return new vr(r,e)}catch(s){if(!t)return null;throw s}};var ye=ri;const si=ye,oi=(r,e)=>{const t=si(r,e);return t?t.version:null};var ni=oi;const ii=ye,ai=(r,e)=>{const t=ii(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};var ci=ai;const yr=z,li=(r,e,t,s,o)=>{typeof t=="string"&&(o=s,s=t,t=void 0);try{return new yr(r instanceof yr?r.version:r,t).inc(e,s,o).version}catch{return null}};var ui=li;const wr=ye,di=(r,e)=>{const t=wr(r,null,!0),s=wr(e,null,!0),o=t.compare(s);if(o===0)return null;const n=o>0,i=n?t:s,a=n?s:t,c=!!i.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(i)===0)return a.minor&&!a.patch?"minor":"patch"}const l=c?"pre":"";return t.major!==s.major?l+"major":t.minor!==s.minor?l+"minor":t.patch!==s.patch?l+"patch":"prerelease"};var pi=di;const fi=z,hi=(r,e)=>new fi(r,e).major;var gi=hi;const mi=z,vi=(r,e)=>new mi(r,e).minor;var yi=vi;const wi=z,Si=(r,e)=>new wi(r,e).patch;var bi=Si;const Pi=ye,Ri=(r,e)=>{const t=Pi(r,e);return t&&t.prerelease.length?t.prerelease:null};var Ci=Ri;const Sr=z,Ei=(r,e,t)=>new Sr(r,t).compare(new Sr(e,t));var se=Ei;const ki=se,Oi=(r,e,t)=>ki(e,r,t);var $i=Oi;const Ti=se,Ii=(r,e)=>Ti(r,e,!0);var Fi=Ii;const br=z,Ai=(r,e,t)=>{const s=new br(r,t),o=new br(e,t);return s.compare(o)||s.compareBuild(o)};var Bt=Ai;const Di=Bt,Li=(r,e)=>r.sort((t,s)=>Di(t,s,e));var Ni=Li;const Bi=Bt,ji=(r,e)=>r.sort((t,s)=>Bi(s,t,e));var Vi=ji;const xi=se,Ui=(r,e,t)=>xi(r,e,t)>0;var rt=Ui;const Gi=se,Mi=(r,e,t)=>Gi(r,e,t)<0;var jt=Mi;const Ji=se,_i=(r,e,t)=>Ji(r,e,t)===0;var ys=_i;const Ki=se,Hi=(r,e,t)=>Ki(r,e,t)!==0;var ws=Hi;const qi=se,Wi=(r,e,t)=>qi(r,e,t)>=0;var Vt=Wi;const zi=se,Xi=(r,e,t)=>zi(r,e,t)<=0;var xt=Xi;const Yi=ys,Qi=ws,Zi=rt,ea=Vt,ta=jt,ra=xt,sa=(r,e,t,s)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return Yi(r,t,s);case"!=":return Qi(r,t,s);case">":return Zi(r,t,s);case">=":return ea(r,t,s);case"<":return ta(r,t,s);case"<=":return ra(r,t,s);default:throw new TypeError(`Invalid operator: ${e}`)}};var Ss=sa;const oa=z,na=ye,{safeRe:Ge,t:Me}=Fe,ia=(r,e)=>{if(r instanceof oa)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?Ge[Me.COERCEFULL]:Ge[Me.COERCE]);else{const c=e.includePrerelease?Ge[Me.COERCERTLFULL]:Ge[Me.COERCERTL];let u;for(;(u=c.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||u.index+u[0].length!==t.index+t[0].length)&&(t=u),c.lastIndex=u.index+u[1].length+u[2].length;c.lastIndex=-1}if(t===null)return null;const s=t[2],o=t[3]||"0",n=t[4]||"0",i=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return na(`${s}.${o}.${n}${i}${a}`,e)};var aa=ia;class ca{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 la=ca,ct,Pr;function oe(){if(Pr)return ct;Pr=1;const r=/\s+/g;class e{constructor(p,v){if(v=o(v),p instanceof e)return p.loose===!!v.loose&&p.includePrerelease===!!v.includePrerelease?p:new e(p.raw,v);if(p instanceof n)return this.raw=p.value,this.set=[[p]],this.formatted=void 0,this;if(this.options=v,this.loose=!!v.loose,this.includePrerelease=!!v.includePrerelease,this.raw=p.trim().replace(r," "),this.set=this.raw.split("||").map(w=>this.parseRange(w.trim())).filter(w=>w.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const w=this.set[0];if(this.set=this.set.filter(P=>!m(P[0])),this.set.length===0)this.set=[w];else if(this.set.length>1){for(const P of this.set)if(P.length===1&&G(P[0])){this.set=[P];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let p=0;p<this.set.length;p++){p>0&&(this.formatted+="||");const v=this.set[p];for(let w=0;w<v.length;w++)w>0&&(this.formatted+=" "),this.formatted+=v[w].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(p){const w=((this.options.includePrerelease&&g)|(this.options.loose&&R))+":"+p,P=s.get(w);if(P)return P;const b=this.options.loose,C=b?c[u.HYPHENRANGELOOSE]:c[u.HYPHENRANGE];p=p.replace(C,V(this.options.includePrerelease)),i("hyphen replace",p),p=p.replace(c[u.COMPARATORTRIM],l),i("comparator trim",p),p=p.replace(c[u.TILDETRIM],d),i("tilde trim",p),p=p.replace(c[u.CARETTRIM],h),i("caret trim",p);let I=p.split(" ").map(A=>U(A,this.options)).join(" ").split(/\s+/).map(A=>Q(A,this.options));b&&(I=I.filter(A=>(i("loose invalid filter",A,this.options),!!A.match(c[u.COMPARATORLOOSE])))),i("range list",I);const O=new Map,L=I.map(A=>new n(A,this.options));for(const A of L){if(m(A))return[A];O.set(A.value,A)}O.size>1&&O.has("")&&O.delete("");const M=[...O.values()];return s.set(w,M),M}intersects(p,v){if(!(p instanceof e))throw new TypeError("a Range is required");return this.set.some(w=>N(w,v)&&p.set.some(P=>N(P,v)&&w.every(b=>P.every(C=>b.intersects(C,v)))))}test(p){if(!p)return!1;if(typeof p=="string")try{p=new a(p,this.options)}catch{return!1}for(let v=0;v<this.set.length;v++)if(H(this.set[v],p,this.options))return!0;return!1}}ct=e;const t=la,s=new t,o=Nt,n=st(),i=tt,a=z,{safeRe:c,t:u,comparatorTrimReplace:l,tildeTrimReplace:d,caretTrimReplace:h}=Fe,{FLAG_INCLUDE_PRERELEASE:g,FLAG_LOOSE:R}=et,m=y=>y.value==="<0.0.0-0",G=y=>y.value==="",N=(y,p)=>{let v=!0;const w=y.slice();let P=w.pop();for(;v&&w.length;)v=w.every(b=>P.intersects(b,p)),P=w.pop();return v},U=(y,p)=>(i("comp",y,p),y=B(y,p),i("caret",y),y=_(y,p),i("tildes",y),y=ue(y,p),i("xrange",y),y=ce(y,p),i("stars",y),y),F=y=>!y||y.toLowerCase()==="x"||y==="*",_=(y,p)=>y.trim().split(/\s+/).map(v=>fe(v,p)).join(" "),fe=(y,p)=>{const v=p.loose?c[u.TILDELOOSE]:c[u.TILDE];return y.replace(v,(w,P,b,C,I)=>{i("tilde",y,w,P,b,C,I);let O;return F(P)?O="":F(b)?O=`>=${P}.0.0 <${+P+1}.0.0-0`:F(C)?O=`>=${P}.${b}.0 <${P}.${+b+1}.0-0`:I?(i("replaceTilde pr",I),O=`>=${P}.${b}.${C}-${I} <${P}.${+b+1}.0-0`):O=`>=${P}.${b}.${C} <${P}.${+b+1}.0-0`,i("tilde return",O),O})},B=(y,p)=>y.trim().split(/\s+/).map(v=>ne(v,p)).join(" "),ne=(y,p)=>{i("caret",y,p);const v=p.loose?c[u.CARETLOOSE]:c[u.CARET],w=p.includePrerelease?"-0":"";return y.replace(v,(P,b,C,I,O)=>{i("caret",y,P,b,C,I,O);let L;return F(b)?L="":F(C)?L=`>=${b}.0.0${w} <${+b+1}.0.0-0`:F(I)?b==="0"?L=`>=${b}.${C}.0${w} <${b}.${+C+1}.0-0`:L=`>=${b}.${C}.0${w} <${+b+1}.0.0-0`:O?(i("replaceCaret pr",O),b==="0"?C==="0"?L=`>=${b}.${C}.${I}-${O} <${b}.${C}.${+I+1}-0`:L=`>=${b}.${C}.${I}-${O} <${b}.${+C+1}.0-0`:L=`>=${b}.${C}.${I}-${O} <${+b+1}.0.0-0`):(i("no pr"),b==="0"?C==="0"?L=`>=${b}.${C}.${I}${w} <${b}.${C}.${+I+1}-0`:L=`>=${b}.${C}.${I}${w} <${b}.${+C+1}.0-0`:L=`>=${b}.${C}.${I} <${+b+1}.0.0-0`),i("caret return",L),L})},ue=(y,p)=>(i("replaceXRanges",y,p),y.split(/\s+/).map(v=>X(v,p)).join(" ")),X=(y,p)=>{y=y.trim();const v=p.loose?c[u.XRANGELOOSE]:c[u.XRANGE];return y.replace(v,(w,P,b,C,I,O)=>{i("xRange",y,w,P,b,C,I,O);const L=F(b),M=L||F(C),A=M||F(I),le=A;return P==="="&&le&&(P=""),O=p.includePrerelease?"-0":"",L?P===">"||P==="<"?w="<0.0.0-0":w="*":P&&le?(M&&(C=0),I=0,P===">"?(P=">=",M?(b=+b+1,C=0,I=0):(C=+C+1,I=0)):P==="<="&&(P="<",M?b=+b+1:C=+C+1),P==="<"&&(O="-0"),w=`${P+b}.${C}.${I}${O}`):M?w=`>=${b}.0.0${O} <${+b+1}.0.0-0`:A&&(w=`>=${b}.${C}.0${O} <${b}.${+C+1}.0-0`),i("xRange return",w),w})},ce=(y,p)=>(i("replaceStars",y,p),y.trim().replace(c[u.STAR],"")),Q=(y,p)=>(i("replaceGTE0",y,p),y.trim().replace(c[p.includePrerelease?u.GTE0PRE:u.GTE0],"")),V=y=>(p,v,w,P,b,C,I,O,L,M,A,le)=>(F(w)?v="":F(P)?v=`>=${w}.0.0${y?"-0":""}`:F(b)?v=`>=${w}.${P}.0${y?"-0":""}`:C?v=`>=${v}`:v=`>=${v}${y?"-0":""}`,F(L)?O="":F(M)?O=`<${+L+1}.0.0-0`:F(A)?O=`<${L}.${+M+1}.0-0`:le?O=`<=${L}.${M}.${A}-${le}`:y?O=`<${L}.${M}.${+A+1}-0`:O=`<=${O}`,`${v} ${O}`.trim()),H=(y,p,v)=>{for(let w=0;w<y.length;w++)if(!y[w].test(p))return!1;if(p.prerelease.length&&!v.includePrerelease){for(let w=0;w<y.length;w++)if(i(y[w].semver),y[w].semver!==n.ANY&&y[w].semver.prerelease.length>0){const P=y[w].semver;if(P.major===p.major&&P.minor===p.minor&&P.patch===p.patch)return!0}return!1}return!0};return ct}var lt,Rr;function st(){if(Rr)return lt;Rr=1;const r=Symbol("SemVer ANY");class e{static get ANY(){return r}constructor(l,d){if(d=t(d),l instanceof e){if(l.loose===!!d.loose)return l;l=l.value}l=l.trim().split(/\s+/).join(" "),i("comparator",l,d),this.options=d,this.loose=!!d.loose,this.parse(l),this.semver===r?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(l){const d=this.options.loose?s[o.COMPARATORLOOSE]:s[o.COMPARATOR],h=l.match(d);if(!h)throw new TypeError(`Invalid comparator: ${l}`);this.operator=h[1]!==void 0?h[1]:"",this.operator==="="&&(this.operator=""),h[2]?this.semver=new a(h[2],this.options.loose):this.semver=r}toString(){return this.value}test(l){if(i("Comparator.test",l,this.options.loose),this.semver===r||l===r)return!0;if(typeof l=="string")try{l=new a(l,this.options)}catch{return!1}return n(l,this.operator,this.semver,this.options)}intersects(l,d){if(!(l instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(l.value,d).test(this.value):l.operator===""?l.value===""?!0:new c(this.value,d).test(l.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||l.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||l.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&l.operator.startsWith(">")||this.operator.startsWith("<")&&l.operator.startsWith("<")||this.semver.version===l.semver.version&&this.operator.includes("=")&&l.operator.includes("=")||n(this.semver,"<",l.semver,d)&&this.operator.startsWith(">")&&l.operator.startsWith("<")||n(this.semver,">",l.semver,d)&&this.operator.startsWith("<")&&l.operator.startsWith(">")))}}lt=e;const t=Nt,{safeRe:s,t:o}=Fe,n=Ss,i=tt,a=z,c=oe();return lt}const ua=oe(),da=(r,e,t)=>{try{e=new ua(e,t)}catch{return!1}return e.test(r)};var ot=da;const pa=oe(),fa=(r,e)=>new pa(r,e).set.map(t=>t.map(s=>s.value).join(" ").trim().split(" "));var ha=fa;const ga=z,ma=oe(),va=(r,e,t)=>{let s=null,o=null,n=null;try{n=new ma(e,t)}catch{return null}return r.forEach(i=>{n.test(i)&&(!s||o.compare(i)===-1)&&(s=i,o=new ga(s,t))}),s};var ya=va;const wa=z,Sa=oe(),ba=(r,e,t)=>{let s=null,o=null,n=null;try{n=new Sa(e,t)}catch{return null}return r.forEach(i=>{n.test(i)&&(!s||o.compare(i)===1)&&(s=i,o=new wa(s,t))}),s};var Pa=ba;const ut=z,Ra=oe(),Cr=rt,Ca=(r,e)=>{r=new Ra(r,e);let t=new ut("0.0.0");if(r.test(t)||(t=new ut("0.0.0-0"),r.test(t)))return t;t=null;for(let s=0;s<r.set.length;++s){const o=r.set[s];let n=null;o.forEach(i=>{const a=new ut(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!n||Cr(a,n))&&(n=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),n&&(!t||Cr(t,n))&&(t=n)}return t&&r.test(t)?t:null};var Ea=Ca;const ka=oe(),Oa=(r,e)=>{try{return new ka(r,e).range||"*"}catch{return null}};var $a=Oa;const Ta=z,bs=st(),{ANY:Ia}=bs,Fa=oe(),Aa=ot,Er=rt,kr=jt,Da=xt,La=Vt,Na=(r,e,t,s)=>{r=new Ta(r,s),e=new Fa(e,s);let o,n,i,a,c;switch(t){case">":o=Er,n=Da,i=kr,a=">",c=">=";break;case"<":o=kr,n=La,i=Er,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Aa(r,e,s))return!1;for(let u=0;u<e.set.length;++u){const l=e.set[u];let d=null,h=null;if(l.forEach(g=>{g.semver===Ia&&(g=new bs(">=0.0.0")),d=d||g,h=h||g,o(g.semver,d.semver,s)?d=g:i(g.semver,h.semver,s)&&(h=g)}),d.operator===a||d.operator===c||(!h.operator||h.operator===a)&&n(r,h.semver))return!1;if(h.operator===c&&i(r,h.semver))return!1}return!0};var Ut=Na;const Ba=Ut,ja=(r,e,t)=>Ba(r,e,">",t);var Va=ja;const xa=Ut,Ua=(r,e,t)=>xa(r,e,"<",t);var Ga=Ua;const Or=oe(),Ma=(r,e,t)=>(r=new Or(r,t),e=new Or(e,t),r.intersects(e,t));var Ja=Ma;const _a=ot,Ka=se;var Ha=(r,e,t)=>{const s=[];let o=null,n=null;const i=r.sort((l,d)=>Ka(l,d,t));for(const l of i)_a(l,e,t)?(n=l,o||(o=l)):(n&&s.push([o,n]),n=null,o=null);o&&s.push([o,null]);const a=[];for(const[l,d]of s)l===d?a.push(l):!d&&l===i[0]?a.push("*"):d?l===i[0]?a.push(`<=${d}`):a.push(`${l} - ${d}`):a.push(`>=${l}`);const c=a.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return c.length<u.length?c:e};const $r=oe(),Gt=st(),{ANY:dt}=Gt,Se=ot,Mt=se,qa=(r,e,t={})=>{if(r===e)return!0;r=new $r(r,t),e=new $r(e,t);let s=!1;e:for(const o of r.set){for(const n of e.set){const i=za(o,n,t);if(s=s||i!==null,i)continue e}if(s)return!1}return!0},Wa=[new Gt(">=0.0.0-0")],Tr=[new Gt(">=0.0.0")],za=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===dt){if(e.length===1&&e[0].semver===dt)return!0;t.includePrerelease?r=Wa:r=Tr}if(e.length===1&&e[0].semver===dt){if(t.includePrerelease)return!0;e=Tr}const s=new Set;let o,n;for(const g of r)g.operator===">"||g.operator===">="?o=Ir(o,g,t):g.operator==="<"||g.operator==="<="?n=Fr(n,g,t):s.add(g.semver);if(s.size>1)return null;let i;if(o&&n){if(i=Mt(o.semver,n.semver,t),i>0)return null;if(i===0&&(o.operator!==">="||n.operator!=="<="))return null}for(const g of s){if(o&&!Se(g,String(o),t)||n&&!Se(g,String(n),t))return null;for(const R of e)if(!Se(g,String(R),t))return!1;return!0}let a,c,u,l,d=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1,h=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 g of e){if(l=l||g.operator===">"||g.operator===">=",u=u||g.operator==="<"||g.operator==="<=",o){if(h&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===h.major&&g.semver.minor===h.minor&&g.semver.patch===h.patch&&(h=!1),g.operator===">"||g.operator===">="){if(a=Ir(o,g,t),a===g&&a!==o)return!1}else if(o.operator===">="&&!Se(o.semver,String(g),t))return!1}if(n){if(d&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===d.major&&g.semver.minor===d.minor&&g.semver.patch===d.patch&&(d=!1),g.operator==="<"||g.operator==="<="){if(c=Fr(n,g,t),c===g&&c!==n)return!1}else if(n.operator==="<="&&!Se(n.semver,String(g),t))return!1}if(!g.operator&&(n||o)&&i!==0)return!1}return!(o&&u&&!n&&i!==0||n&&l&&!o&&i!==0||h||d)},Ir=(r,e,t)=>{if(!r)return e;const s=Mt(r.semver,e.semver,t);return s>0?r:s<0||e.operator===">"&&r.operator===">="?e:r},Fr=(r,e,t)=>{if(!r)return e;const s=Mt(r.semver,e.semver,t);return s<0?r:s>0||e.operator==="<"&&r.operator==="<="?e:r};var Xa=qa;const pt=Fe,Ar=et,Ya=z,Dr=vs,Qa=ye,Za=ni,ec=ci,tc=ui,rc=pi,sc=gi,oc=yi,nc=bi,ic=Ci,ac=se,cc=$i,lc=Fi,uc=Bt,dc=Ni,pc=Vi,fc=rt,hc=jt,gc=ys,mc=ws,vc=Vt,yc=xt,wc=Ss,Sc=aa,bc=st(),Pc=oe(),Rc=ot,Cc=ha,Ec=ya,kc=Pa,Oc=Ea,$c=$a,Tc=Ut,Ic=Va,Fc=Ga,Ac=Ja,Dc=Ha,Lc=Xa;var Nc={parse:Qa,valid:Za,clean:ec,inc:tc,diff:rc,major:sc,minor:oc,patch:nc,prerelease:ic,compare:ac,rcompare:cc,compareLoose:lc,compareBuild:uc,sort:dc,rsort:pc,gt:fc,lt:hc,eq:gc,neq:mc,gte:vc,lte:yc,cmp:wc,coerce:Sc,Comparator:bc,Range:Pc,satisfies:Rc,toComparators:Cc,maxSatisfying:Ec,minSatisfying:kc,minVersion:Oc,validRange:$c,outside:Tc,gtr:Ic,ltr:Fc,intersects:Ac,simplifyRange:Dc,subset:Lc,SemVer:Ya,re:pt.re,src:pt.src,tokens:pt.t,SEMVER_SPEC_VERSION:Ar.SEMVER_SPEC_VERSION,RELEASE_TYPES:Ar.RELEASE_TYPES,compareIdentifiers:Dr.compareIdentifiers,rcompareIdentifiers:Dr.rcompareIdentifiers};const Bc=Jn(Nc),jc={minDelay:1500},Vc="__no_updates__";class xc extends j.PollComputablePool{constructor(t,s,o={}){super({...o,...jc},s);S(this,"http");S(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 Vc}}async readValue(t){var s,o;try{const n=t.currentSpec;switch(n.type){case"dev-v1":try{const i=await kt(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 W.tryLoadPackDescription(n.folder,this.logger);if(i===void 0)return{suggestions:[]};const a=await ze(i);return a===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:a},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:i,skipVersion:a}=t.settings;if(i==="patch")return{suggestions:[]};const c=this.registryProvider.getRegistry(n.registryUrl);let u=this.preferredUpdateChannel;if(u===void 0)if(n.channel===void 0)if(await c.getLatestOverview(n.id,q.StableChannel))u=q.StableChannel;else{if(await c.getLatestOverview(n.id,q.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${q.blockPackIdToString(n.id)}`),{suggestions:[]};u=q.AnyChannel}else u=n.channel;const l=await c.getUpdateSuggestions(n.id,u);if(l===void 0||l.length===0)return{suggestions:[]};l.reverse();let d;switch(i){case void 0:d=l[0].update;break;case"major":d=(s=l.find(R=>R.type!=="major"))==null?void 0:s.update;break;case"minor":d=(o=l.find(R=>R.type==="patch"))==null?void 0:o.update;break}const h=l.map(({type:R,update:m})=>({type:R,update:{...n,id:{...n.id,version:m}}}));if(d===void 0)return{suggestions:h};if(a!==void 0&&Bc.lte(d,a))return{suggestions:h};const g={...n,id:{...n.id,version:d}};return(async()=>{try{await c.getComponents(g.id)}catch(R){this.logger.warn(R)}})(),{suggestions:h,mainSuggestion:g}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(n){return this.logger.warn(n),{suggestions:[]}}}resultsEqual(t,s){return x(t)===x(s)}}class Lr{constructor(){S(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 s=this.resources.get(t);s===void 0&&(s={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,s)),s.refCount++;let o=!1;return{resource:s.resource,key:t,unref:()=>{o||(s.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 be;function de(){return be||(be={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0,dumpInitialTreeState:process.env.MI_DUMP_INITIAL_TREE_STATE!==void 0},process.env.MI_LOG_TREE_STAT&&(be.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),be)}function ke(r){return String(r.id)}const Uc=["Int","Long","Float","Double","String","Bytes"];function ft(r){const e=[],t=[];for(const s of r)s.type==="bySingleColumn"?(e.push(s),t.push({...s,type:"bySingleColumnV2"})):t.push(s);if(e.length>0){const s=JSON.stringify(e);console.warn(`type overriten from 'bySingleColumn' to 'bySingleColumnV2' for filters: ${s}`)}return t}const Pe=(r,e)=>typeof e=="bigint"?e.toString():e;class Gc{constructor(e,t,s,o){S(this,"rustPFrame");S(this,"blobIdToResource",new Map);S(this,"blobHandleComputables",new Map);S(this,"preloadBlob",async e=>{const t=e.map(s=>this.getOrCreateComputableForBlob(s));for(const s of t)await s.awaitStableFullValue()});S(this,"resolveBlob",async e=>{const t=this.getOrCreateComputableForBlob(e);return this.blobDriver.getLocalPath((await t.awaitStableValue()).handle)});S(this,"resolveBlobContent",async e=>{try{const t=this.getOrCreateComputableForBlob(e),s=this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);return await this.blobContentCache.forceFetch(s)}catch(t){const s=JSON.stringify(t);throw console.log(`resolveBlobContent catched error: ${s}`),t}});this.blobDriver=e,this.logger=t,this.blobContentCache=s;const n=(a,c)=>{switch(a){default:case"info":return this.logger.info(c);case"warn":return this.logger.warn(c);case"error":return this.logger.error(c)}};for(const a of o)for(const c of Lo(a.data))this.blobIdToResource.set(ke(c),c);const i=[...new Map(o.map(a=>({...a,data:No(a.data,ke)})).map(a=>[x(a),a])).values()];try{const a=new Ds.PFrame(de().logPFrameRequests?n:void 0);a.setDataSource(this);for(const c of i)a.addColumnSpec(c.id,c.spec),a.setColumnData(c.id,c.data);this.rustPFrame=a}catch(a){throw new Error(`Rust PFrame creation failed, columns: ${JSON.stringify(i)}, error: ${a}`)}}getOrCreateComputableForBlob(e){let t=this.blobHandleComputables.get(e);if(t!==void 0)return t;const s=this.blobIdToResource.get(e);if(s===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(s).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}[Symbol.dispose](){for(const e of this.blobHandleComputables.values())e.resetState();this.rustPFrame.dispose()}}class Mc{constructor(e){this.table=e}[Symbol.dispose](){this.table.then(e=>e.dispose())}}class Jc{constructor(e,t){S(this,"pFrames");S(this,"pTables");S(this,"blobContentCache");this.blobDriver=e,this.logger=t;const s=new Br.LRUCache({maxSize:1e9,fetchMethod:async o=>await Ur.readFile(o),sizeCalculation:o=>o.length});this.blobContentCache=s,this.pFrames=new class extends Lr{constructor(o,n){super(),this.blobDriver=o,this.logger=n}createNewResource(o){return de().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,Pe)}`),new Gc(this.blobDriver,this.logger,s,o)}calculateParamsKey(o){return Kc(o)}}(this.blobDriver,this.logger),this.pTables=new class extends Lr{constructor(o){super(),this.pFrames=o}createNewResource(o){const n=o.pFrameHandle;de().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,Pe)}`);const i=this.pFrames.getByKey(n).rustPFrame.createTable({src:Oe(o.def.src),filters:ft(o.def.filters)},o.signal).then(async a=>{if(o.def.sorting.length===0)return a;try{return await a.sort(o.def.sorting,o.signal)}finally{a.dispose()}});return new Mc(i)}calculateParamsKey(o){return _c(o)}}(this.pFrames)}createPFrame(e,t){const s=e.filter(n=>Uc.find(i=>i===n.spec.valueType)).map(n=>D.mapPObjectData(n,i=>_e.isPlTreeNodeAccessor(i)?Go(i):D.isDataInfo(i)?D.mapDataInfo(i,a=>a.resourceInfo):Mo(n.spec,i))),o=this.pFrames.acquire(s);return t.addOnDestroy(o.unref),o.key}createPTable(e,t,s){const o=this.createPFrame(D.extractAllColumns(e.src),t),n=D.mapPTableDef(e,a=>a.id),i=this.pTables.acquire({def:n,pFrameHandle:o,signal:s});return de().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${o}; pTableHandle = ${JSON.stringify(i)}): ${JSON.stringify(D.mapPTableDef(e,a=>a.spec),Pe)}`),t.addOnDestroy(i.unref),i.key}async findColumns(e,t){const s={...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).rustPFrame.findColumns(s)).hits.filter(n=>n.mappingVariants.length===0||n.mappingVariants.some(i=>i.qualifications.forHit.length===0&&i.qualifications.forQueries.every(a=>a.length===0))).map(n=>n.hit)}}async getColumnSpec(e,t){return await this.pFrames.getByKey(e).rustPFrame.getColumnSpec(t)}async listColumns(e){return await this.pFrames.getByKey(e).rustPFrame.listColumns()}async calculateTableData(e,t,s){return de().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,Pe)}`),await this.pFrames.getByKey(e).rustPFrame.createTable({src:Oe(t.src),filters:ft(t.filters)},s).then(async o=>{if(t.sorting.length===0)return o;try{return await o.sort(t.sorting,s)}finally{o.dispose()}}).then(async o=>{try{const n=o.getSpec(),i=await o.getData([...n.keys()]);return n.map((a,c)=>({spec:a,data:i[c]}))}finally{o.dispose()}})}async getUniqueValues(e,t,s){return de().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,Pe)}`),await this.pFrames.getByKey(e).rustPFrame.getUniqueValues({...t,filters:ft(t.filters)},s)}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,s){return await(await this.pTables.getByKey(e).table).getData(t,s)}}function Oe(r){switch(r.type){case"column":return{type:"column",columnId:r.column};case"slicedColumn":return{type:"slicedColumn",columnId:r.column,newId:r.newId,axisFilters:r.axisFilters};case"inner":case"full":return{type:r.type,entries:r.entries.map(e=>Oe(e))};case"outer":return{type:"outer",primary:Oe(r.primary),secondary:r.secondary.map(e=>Oe(e))};default:E.assertNever(r)}}function _c(r){const e=ee.createHash("sha256");return e.update(x(r)),e.digest().toString("hex")}function Kc(r){const e=[...r].map(s=>D.mapPObjectData(s,o=>{let n;const i=o.type;switch(i){case"Json":n={type:o.type,keyLength:o.keyLength,payload:Object.entries(o.data).map(([a,c])=>({key:a,value:c}))};break;case"JsonPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([a,c])=>({key:a,value:ke(c)}))};break;case"BinaryPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([a,c])=>({key:a,value:[ke(c.index),ke(c.values)]}))};break;default:throw Error(`unsupported resource type: ${JSON.stringify(i)}`)}return n.payload.sort((a,c)=>a.key.localeCompare(c.key)),n}));e.sort((s,o)=>s.id.localeCompare(o.id));const t=ee.createHash("sha256");return t.update(x(e)),t.digest().toString("hex")}async function Ps(r,e,t){const s={...Dt,...Lt(e),...t},o=new E.HmacSha256Signer(s.localSecret),n=te.createDownloadClient(s.logger,r,s.localProjections),i=te.createLogsClient(r,s.logger),a=te.createUploadBlobClient(r,s.logger),c=te.createUploadProgressClient(r,s.logger),u=new te.DownloadDriver(s.logger,n,i,s.blobDownloadPath,o,s.blobDriverOps),l=new te.DownloadBlobToURLDriver(s.logger,o,n,s.downloadBlobToURLPath,s.downloadBlobToURLDriverOps),d=new te.UploadDriver(s.logger,o,a,c,s.uploadDriverOps),h=new te.LogsStreamDriver(s.logger,i,s.logStreamDriverOps),g=new te.LogsDriver(s.logger,h,u),R=await te.LsDriver.init(s.logger,r,o,s.localProjections,s.openFileDialogCallback,s.virtualLocalStoragesOverride),m=new Jc(u,s.logger);return{blobDriver:u,blobToURLDriver:l,logDriver:g,lsDriver:R,signer:o,uploadDriver:d,pFrameDriver:m}}class Jt{constructor(e,t,s,o,n,i,a,c){S(this,"pl");S(this,"projectList");S(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=s,this.projectListResourceId=o,this.openedProjectsList=n,this.projectListTree=i,this.blockRegistryProvider=a,this.projectList=c,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=ee.randomUUID()){const s=await this.pl.withWriteTx("MLCreateProject",async o=>{const n=await Do(o,e);return o.createField(f.field(this.projectListResourceId,t),"Dynamic",n),await o.commit(),await f.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),s}async setProjectMeta(e,t,s){await re(this.pl,e,s,o=>{o.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(f.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 s=(await t.getField(f.field(this.projectListResourceId,e))).value;if(f.isNullResourceId(s))throw new Error("Unexpected project list structure.");return s})}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 Ze.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 E.HmacSha256Signer.generateSecret()}static async init(e,t,s){const o={...fs,...hs(t),...s};o.defaultTreeOptions.logStat=de().logTreeStats,o.debugOps.dumpInitialTreeState=de().dumpInitialTreeState;const n=await e.withWriteTx("MLInitialization",async m=>{const G=f.field(m.clientRoot,so);m.createField(G,"Dynamic");const N=await m.getField(G);if(f.isNullResourceId(N.value)){const U=m.createEphemeral(Kr);return m.lock(U),m.setField(G,U),await m.commit(),await U.globalId}else return N.value}),i=o.logger,a=await Ps(e,t,o),c=new We.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),u=new Mr(c),l=new ko(u,a.signer,c),d=new te.DownloadUrlDriver(i,e.httpDispatcher,o.frontendDownloadPath),h={pl:e,signer:a.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:c,ops:o,bpPreparer:l,frontendDownloadDriver:d,driverKit:a,blockUpdateWatcher:new xc(u,i,{minDelay:o.devBlockUpdateRecheckInterval,http:c,preferredUpdateChannel:o.preferredUpdateChannel}),quickJs:await $e.getQuickJS()},g=new j.WatchableValue([]),R=await no(e,n,g,h);return new Jt(h,a,a.signer,n,g,R.tree,u,R.computable)}}const Hc=["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"];async function qc(r,e={}){const t={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,...e},s=[];Hc.forEach(c=>{Ls.channel(c).subscribe(l=>{var h;const d=new Date().toISOString();(h=l==null?void 0:l.response)!=null&&h.headers&&(l.response.headers=l.response.headers.map(g=>g.toString())),s.push(JSON.stringify({timestamp:d,event:c,data:l}))})});const o={plPings:[],blockRegistryOverviewChecks:[],blockGARegistryOverviewChecks:[],blockRegistryUiChecks:[],blockGARegistryUiChecks:[],autoUpdateCdnChecks:[]},n=f.plAddressToConfig(r,{defaultRequestTimeout:t.pingTimeoutMs});o.plPings=await ge(t.pingCheckDurationMs,t.maxPingsPerSecond,async()=>{const u=await new f.UnauthenticatedPlClient(n).ping();return JSON.stringify(u).slice(0,t.bodyLimit)+"..."});const a=new f.UnauthenticatedPlClient(n).ll.httpDispatcher;return o.blockRegistryOverviewChecks=await ge(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Re(new URL(t.blockOverviewPath,t.blockRegistryUrl),t,a)),o.blockGARegistryOverviewChecks=await ge(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Re(new URL(t.blockOverviewPath,t.blockGARegistryUrl),t,a)),o.blockRegistryUiChecks=await ge(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Re(new URL(t.blockUiPath,t.blockRegistryUrl),t,a)),o.blockGARegistryUiChecks=await ge(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Re(new URL(t.blockUiPath,t.blockGARegistryUrl),t,a)),o.autoUpdateCdnChecks=await ge(t.autoUpdateCdnDurationMs,t.maxAutoUpdateCdnChecksPerSecond,async()=>await Re(t.autoUpdateCdnUrl,t,a)),Wc(o,r,t,s)}async function ge(r,e,t){const s=Rt(),o=[];for(;Nr(s)<r;){const n=Rt();let i;try{i={ok:!0,value:await t()}}catch(u){i={ok:!1,error:u}}const a=Nr(n);o.push({elapsedMs:a,response:i});const c=1e3/e-a;c>0&&await Vr.setTimeout(c)}return o}async function Re(r,e,t){const{body:s,statusCode:o}=await We.request(r,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),n=await s.text();return{statusCode:o,beginningOfBody:n.slice(0,e.bodyLimit)+"..."}}function Wc(r,e,t,s){const o=r.plPings.filter(a=>a.response.ok),n=r.plPings.filter(a=>!a.response.ok),i=[...new Set(o.map(a=>JSON.stringify(a.response.value)))];return`
1
+ "use strict";var Es=Object.defineProperty;var _t=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),Kt=r=>{throw TypeError(r)};var Cs=(r,e,t)=>e in r?Es(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var S=(r,e,t)=>Cs(r,typeof e!="symbol"?e+"":e,t);var Ht=(r,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Kt("Object expected");var s;t&&(s=e[_t("asyncDispose")]),s===void 0&&(s=e[_t("dispose")]),typeof s!="function"&&Kt("Object not disposable"),r.push([t,s,e])}else t&&r.push([t]);return e},qt=(r,e,t)=>{var s=typeof SuppressedError=="function"?SuppressedError:function(i,a,c,u){return u=Error(c),u.name="SuppressedError",u.error=i,u.suppressed=a,u},o=i=>e=t?new s(i,e,"An error was suppressed during disposal"):(t=!0,i),n=i=>{for(;i=r.pop();)try{var a=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(a).then(n,c=>(o(c),n()))}catch(c){o(c)}if(t)throw e};return n()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("@platforma-sdk/model"),q=require("@milaboratories/pl-model-middle-layer"),Wt=require("@milaboratories/pl-deployments"),We=require("undici"),W=require("@platforma-sdk/block-tools"),Z=require("node:fs"),K=require("node:path"),ks=require("yaml"),C=require("@milaboratories/ts-helpers"),ht=require("node:fs/promises"),Os=require("@milaboratories/resolve-helper"),f=require("@milaboratories/pl-client"),_e=require("@milaboratories/pl-tree"),j=require("@milaboratories/computable"),ee=require("node:crypto"),k=require("@milaboratories/pl-model-backend"),Br=require("lru-cache"),$s=require("node:worker_threads"),jr=require("denque"),Ts=require("@platforma-sdk/workflow-tengo"),x=require("canonicalize"),Is=require("node:assert"),$e=require("quickjs-emscripten"),Fs=require("@milaboratories/pl-errors"),As=require("remeda"),Vr=require("node:timers/promises"),te=require("@milaboratories/pl-drivers"),Ds=require("@milaboratories/pframes-rs-node"),Ls=require("node:diagnostics_channel");function xr(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const Ur=xr(ht),zt=xr(As);async function Xt(r){try{return await Ur.stat(r,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const Ns=[W.RegistryV1.PlPackageYamlConfigFile],Bs=[W.RegistryV1.PlPackageJsonConfigFile],Et=["backend","dist","tengo","tpl","main.plj.gz"],Ct=["config","dist","config.json"],Gr=["frontend","dist"],Yt="block-model/dist/config.json",js="block-ui/package.json",Vs=[Et,Ct,Ns,Bs,Gr];async function xs(r){return await Xt(K.join(r,...Ct))!==void 0||await Xt(K.join(r,...Et))!==void 0}function nt(r,e){const t=Os.tryResolve(r,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${r}`);return t}async function Qt(r,e){if(K.isAbsolute(r)||(r=K.resolve(r)),await xs(r))return{workflow:K.join(r,...Et),config:K.join(r,...Ct),ui:K.join(r,...Gr)};{const t=nt(r,Yt),s=nt(r,Yt),o=nt(r,js);return{workflow:t,config:s,ui:K.resolve(o,"..","dist")}}}async function Us(r){try{return await Z.promises.readFile(r,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Gs(r){try{return await Z.promises.stat(r,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function kt(r){let e=0n;for(const t of Vs){const s=K.join(r,...t),o=await Gs(s);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function ze(r){const e=await Z.promises.stat(r.components.workflow.main.file,{bigint:!0}),t=await Z.promises.stat(r.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class Ms{constructor(e,t,s){this.v2Provider=e,this.registries=t,this.http=s}async getPackagesForRoot(e){const t=[],s=e.spec;switch(s.type){case"remote-v1":{const o=this.http!==void 0?{dispatcher:this.http}:{},i=await(await We.request(`${s.url}/${W.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const a of i){const{organization:c,package:u,latestMeta:l,latestVersion:d}=a,h={organization:c,name:u,version:d},g={id:h,meta:{title:l.title??"No title",description:l.description??"No Description",organization:{name:c,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:h,registryUrl:s.url}};t.push({registryId:e.id,id:h,latestByChannel:{[q.AnyChannel]:g,[q.StableChannel]:g},allVersions:a.allVersions.map(R=>({version:R,channels:[]}))})}return t}case"remote-v2":return(await this.v2Provider.getRegistry(s.url).listBlockPacks()).map(o=>({...o,registryId:e.id}));case"local-dev":for(const o of await Z.promises.readdir(s.path,{withFileTypes:!0})){if(!o.isDirectory())continue;const n=K.join(s.path,o.name),i=await Us(K.join(n,W.RegistryV1.PlPackageYamlConfigFile));if(i!==void 0){const a=W.RegistryV1.PlPackageConfigData.parse(ks.parse(i)),c=await kt(n),u={organization:a.organization,name:a.package,version:"DEV"},l={id:u,meta:{title:a.meta.title??"No title",description:a.meta.description??"No Description",organization:{name:a.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:n,mtime:c}};t.push({registryId:e.id,id:u,latestByChannel:{[q.AnyChannel]:l,[q.StableChannel]:l},allVersions:[]})}else{let a=n,c=await W.tryLoadPackDescription(a);if(c===void 0){for(const u of["block","meta"])if(a=K.join(n,u),c=await W.tryLoadPackDescription(a),c!==void 0)break}if(c!==void 0){const u=await ze(c),l={id:c.id,meta:await W.BlockPackMetaEmbedAbsoluteBytes.parseAsync(c.meta),spec:{type:"dev-v2",folder:a,mtime:u}};t.push({registryId:e.id,id:c.id,latestByChannel:{[q.AnyChannel]:l,[q.StableChannel]:l},allVersions:[]})}}}return t;default:return C.assertNever(s)}}async listBlockPacks(){const e=[],t=[];for(const s of this.registries)t.push({...s,status:"online"}),e.push(...await this.getPackagesForRoot(s));return{registries:t,blockPacks:e}}async getOverview(e,t,s){var i;const o=(i=this.registries.find(a=>a.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,s)}}class Mr{constructor(e){S(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const s=new W.RegistryV2Reader(W.folderReaderByUrl(e,this.http));return this.registries.set(e,s),s}}const Js={type:"remote-v2",url:"https://blocks.pl-open.science/"},_s={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},Ks={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},Hs={groups:[{id:"default",label:"Default",blocks:[]}]},qs={stagingRefreshTimestamp:0,blocksInLimbo:[]},Ws={label:"New Project"},zs={name:"UserProject",version:"2"},Jr="SchemaVersion",_r="1",Ot="ProjectCreated",Te="ProjectLastModified",Ie="ProjectMeta",pe="ProjectStructure",Ke="BlockRenderingState",Xs="BlockFrontendState/",Ys=/^BlockFrontendState\/(?<blockid>.*)$/;function gt(r){return`${Xs}${r}`}const Qs="BlockArgsAuthor/";function mt(r){return`${Qs}${r}`}const vt="ProjectStructureAuthor";function Zs(r){const e=r.match(Ys);if(e!==null)return e.groups.blockid}const eo="__serviceTemplate_";function yt(r){return`${eo}${r}`}function J(r,e){return`${r}-${e}`}const to=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function ro(r){const e=r.match(to);if(e===null)return;const{blockId:t,fieldName:s}=e.groups;return{blockId:t,fieldName:s}}const so="projects",Kr={name:"Projects",version:"1"},oo=r=>f.resourceTypesEqual(r.type,Kr)?r.fields:[];async function no(r,e,t,s){const o=await _e.SynchronizedTreeState.init(r,e,{...s.ops.defaultTreeOptions,pruning:oo},s.logger);return{computable:j.Computable.make(i=>{const a=i.accessor(o.entry()).node(),c=t.getValue(i);if(a===void 0)return;const u=[];for(const l of a.listDynamicFields()){const d=a.traverse(l);if(d===void 0)continue;const h=C.notEmpty(d.getKeyValueAsJson(Ie)),g=C.notEmpty(d.getKeyValueAsJson(Ot)),R=C.notEmpty(d.getKeyValueAsJson(Te));u.push({id:l,rid:d.id,created:new Date(g),lastModified:new Date(R),opened:c.indexOf(d.id)>=0,meta:h})}return u.sort(l=>-l.lastModified.valueOf()),u}).withStableType(),tree:o}}const io={name:"EphRenderTemplate",version:"1"},ao={name:"RenderTemplate",version:"1"};function $t(r,e,t,s,o){if(o.length===0)throw new Error("Zero output names provided");const n=t?r.createEphemeral(io):r.createStruct(ao),i=f.field(n,"template"),a=f.field(n,"inputs");return r.createField(i,"Input",e),r.createField(a,"Input",f.Pl.createPlMap(r,s,t)),r.lockInputs(n),f.Pl.futureRecord(r,n,o,"Output","outputs/")}const co={name:"BContextEnd",version:"1"},lo={name:"BContext",version:"1"},uo="id",po="parent/",fo=["context","result"];function Zt(r,e,t){return $t(r,e,!0,t,fo)}function ho(r){const e=r.createEphemeral(co);return r.lock(e),e}function er(r,e){if(e.length===0)return ho(r);if(e.length===1)return e[0];const t=r.createEphemeral(lo);r.createField(f.field(t,uo),"Input",f.Pl.createPlString(r,ee.randomUUID()));for(let s=0;s<e.length;s++)r.createField(f.field(t,`${po}${s}`),"Input",e[s]);return r.lock(t),t}function Hr(r,e){const t=new Map,s=(o,n,i)=>{const a=ee.createHash("sha256");n.updateCacheKey(o,a,i);const c=a.digest("hex");if(!t.has(c)){const u=n.render(o,r,s,i);t.set(c,u)}return t.get(c)};return s(e.template,qr,e.hashToSource)}const tr={updateCacheKey(r,e,t){e.update(k.PlTemplateLibV1.type.name).update(k.PlTemplateLibV1.type.version).update(r.name).update(r.version).update(ve(r.name,t,r.sourceHash))},render(r,e,t,s){return e.createValue(k.PlTemplateLibV1.type,JSON.stringify(k.PlTemplateLibV1.fromV3Data(r,ve(r.name,s,r.sourceHash)).data))}},Ae={updateCacheKey(r,e,t){e.update(k.PlTemplateSoftwareV1.type.name).update(k.PlTemplateSoftwareV1.type.version).update(r.name).update(r.version).update(ve(r.name,t,r.sourceHash))},render(r,e,t,s){const o=k.PlTemplateSoftwareV1.fromV3Data(r,ve(r.name,s,r.sourceHash)),n=e.createStruct(k.PlTemplateSoftwareV1.type,o.data);return e.setKValue(n,k.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(o.name)),e.lock(n),n}},qr={updateCacheKey(r,e,t){e.update(k.PlTemplateV1.type.name).update(k.PlTemplateV1.type.version).update(r.hashOverride??"no-override").update(r.name).update(r.version).update(ve(r.name,t,r.sourceHash));const s=o=>(o.sort((n,i)=>n[0]===i[0]?0:n[0]<i[0]?-1:1),o);for(const[o,n]of s(Object.entries(r.libs??{})))e.update("lib:"+o),tr.updateCacheKey(n,e,t);for(const[o,n]of s(Object.entries(r.software??{})))e.update("soft:"+o),Ae.updateCacheKey(n,e,t);for(const[o,n]of s(Object.entries(r.assets??{})))e.update("asset:"+o),Ae.updateCacheKey(n,e,t);for(const[o,n]of s(Object.entries(r.templates??{})))e.update("tpl:"+o),this.updateCacheKey(n,e,t)},render(r,e,t,s){const o=e.createStruct(k.PlTemplateV1.type,JSON.stringify(k.PlTemplateV1.fromV3Data(r,ve(r.name,s,r.sourceHash)).data));for(const[a,c]of Object.entries(r.libs??{})){const u=k.PlTemplateV1.libField(o,a);e.createField(u,"Input"),e.setField(u,t(c,tr,s))}for(const[a,c]of Object.entries(r.software??{})){const u=k.PlTemplateV1.swField(o,a);e.createField(u,"Input"),e.setField(u,t(c,Ae,s))}for(const[a,c]of Object.entries(r.assets??{})){const u=k.PlTemplateV1.swField(o,a);e.createField(u,"Input"),e.setField(u,t(c,Ae,s))}for(const[a,c]of Object.entries(r.templates??{})){const u=k.PlTemplateV1.tplField(o,a);e.createField(u,"Input"),e.setField(u,t(c,qr,s))}if(e.lock(o),!r.hashOverride)return o;const n=e.createStruct(k.PlTemplateOverrideV1.type,JSON.stringify(k.PlTemplateOverrideV1.fromV3Data(r))),i=k.PlTemplateOverrideV1.tplField(n);return e.createField(i,"Service"),e.setField(i,o),e.lock(n),n}};function ve(r,e,t){return C.notEmpty(e[t],`trying to get "${r}" source: sources map doesn't contain source hash ${t}`)}function go(r,e){const t=k.parseTemplate(e.content),s=t.type;switch(s){case"pl.tengo-template.v2":return zr(r,t);case"pl.tengo-template.v3":return Hr(r,t);default:C.assertNever(s)}}function mo(r,e){const t=e.data,s=t.type;switch(s){case"pl.tengo-template.v2":return zr(r,t);case"pl.tengo-template.v3":return Hr(r,t);default:C.assertNever(s)}}const rr={hash(r,e){e.update(k.PlTemplateLibV1.type.name).update(k.PlTemplateLibV1.type.version).update(r.name).update(r.version).update(r.src)},render(r,e,t){return e.createValue(k.PlTemplateLibV1.type,JSON.stringify(k.PlTemplateLibV1.fromV2Data(r).data))}},De={hash(r,e){e.update(k.PlTemplateSoftwareV1.type.name).update(k.PlTemplateSoftwareV1.type.version).update(r.name).update(r.version).update(r.src)},render(r,e,t){const s=k.PlTemplateSoftwareV1.fromV2Data(r),o=e.createStruct(k.PlTemplateSoftwareV1.type,s.data);return e.setKValue(o,k.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(s.name)),e.lock(o),o}},Wr={hash(r,e){e.update(k.PlTemplateV1.type.name).update(k.PlTemplateV1.type.version).update(r.hashOverride??"no-override").update(r.name).update(r.version).update(r.src);const t=s=>(s.sort((o,n)=>o[0]===n[0]?0:o[0]<n[0]?-1:1),s);for(const[s,o]of t(Object.entries(r.libs??{})))e.update("lib:"+s),rr.hash(o,e);for(const[s,o]of t(Object.entries(r.software??{})))e.update("soft:"+s),De.hash(o,e);for(const[s,o]of t(Object.entries(r.assets??{})))e.update("asset:"+s),De.hash(o,e);for(const[s,o]of t(Object.entries(r.templates??{})))e.update("tpl:"+s),this.hash(o,e)},render(r,e,t){const s=e.createStruct(k.PlTemplateV1.type,JSON.stringify(k.PlTemplateV1.fromV2Data(r).data));for(const[i,a]of Object.entries(r.libs??{})){const c=k.PlTemplateV1.libField(s,i);e.createField(c,"Input"),e.setField(c,t(a,rr))}for(const[i,a]of Object.entries(r.software??{})){const c=k.PlTemplateV1.swField(s,i);e.createField(c,"Input"),e.setField(c,t(a,De))}for(const[i,a]of Object.entries(r.assets??{})){const c=k.PlTemplateV1.swField(s,i);e.createField(c,"Input"),e.setField(c,t(a,De))}for(const[i,a]of Object.entries(r.templates??{})){const c=k.PlTemplateV1.tplField(s,i);e.createField(c,"Input"),e.setField(c,t(a,Wr))}if(e.lock(s),!r.hashOverride)return s;const o=e.createStruct(k.PlTemplateOverrideV1.type,JSON.stringify(k.PlTemplateOverrideV1.fromV2Data(r))),n=k.PlTemplateOverrideV1.tplField(o);return e.createField(n,"Service"),e.setField(n,s),e.lock(o),o}};function zr(r,e){const t=new Map,s=(o,n)=>{const i=ee.createHash("sha256");n.hash(o,i);const a=i.digest("hex");if(!t.has(a)){const c=n.render(o,r,s);t.set(a,c)}return t.get(a)};return s(e,Wr)}const Xr={name:"TengoTemplateGet",version:"1"},Yr="registry",Qr="templateURI",Zr="template",vo={name:"TengoTemplatePack",version:"1"},yo={name:"TengoTemplatePackConvert",version:"1"},wo="templatePack",So="template";async function es(r){switch(r.type){case"from-file":return{type:"explicit",content:await Z.promises.readFile(r.path)};case"from-registry":case"explicit":return r;case"prepared":return r;default:return C.assertNever(r)}}function bo(r,e){const t=r.createStruct(Xr),s=f.field(t,Yr),o=f.field(t,Qr),n=f.field(t,Zr);return r.setField(s,r.createValue(f.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),r.setField(o,r.createValue(f.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function Xe(r,e){switch(e.type){case"from-registry":return bo(r,e);case"explicit":return go(r,e);case"prepared":return mo(r,e);default:return C.assertNever(e)}}const Tt={name:"Frontend/FromUrl",version:"1"},It={name:"Frontend/FromFolder",version:"1"};function Po(r,e){switch(e.type){case"url":return r.createValue(Tt,JSON.stringify({url:e.url}));case"local":return r.createValue(It,JSON.stringify({path:e.path,signature:e.signature}));default:return C.assertNever(e)}}class Ro{constructor(){S(this,"nextMessageId",0);S(this,"worker");S(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 $s.Worker(e,{workerData:{}});t.on("message",({id:s,data:o,error:n})=>{const{resolve:i,reject:a}=this.pendingRequests.get(s);this.pendingRequests.delete(s),n?a(new Error(n)):i(o)}),t.on("error",s=>{console.error("Worker error",s),this.rejectAllPendingRequests(s)})}rejectAllPendingRequests(e){Array.from(this.pendingRequests.values()).map(({reject:t})=>{t(e)})}async process(e,...t){return new Promise((s,o)=>{const n=++this.nextMessageId;this.pendingRequests.set(n,{resolve:s,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 Eo={name:"BlockPackCustom",version:"1"},ts="template",rs="frontend";function sr(r){return r.endsWith("/")?r:`${r}/`}function Co(r){return Buffer.from(r).toString("utf8")}function Le(r){return JSON.parse(Co(r))}class ko{constructor(e,t,s){S(this,"remoteContentCache",new Br.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=s}async getBlockConfigContainer(e){switch(e.type){case"explicit":return e.config;case"prepared":return e.config;case"dev-v1":{const t=await Qt(e.folder),s=await Z.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(s)}case"dev-v2":{const t=await W.loadPackDescription(e.folder),s=await Z.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(s)}case"from-registry-v1":{const t=`${sr(e.registryUrl)}${W.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,s=await this.remoteContentCache.forceFetch(`${t}/config.json`);return Le(s)}case"from-registry-v2":{const s=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),o=await this.remoteContentCache.forceFetch(s.model.url);return Le(o)}default:return C.assertNever(e)}}async prepare(e){var o=[];try{if(e.type==="prepared")return e;const t=await this.prepareWithoutUnpacking(e);const s=Ht(o,new Ro,!0);return{...t,type:"prepared",template:{type:"prepared",data:await s.process("parseTemplate",t.template.content)}}}catch(n){var i=n,a=!0}finally{var c=qt(o,i,a);c&&await c}}async prepareWithoutUnpacking(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await Qt(e.folder),s=await Z.promises.readFile(t.workflow),o=JSON.parse(await Z.promises.readFile(t.config,"utf-8")),n=t.ui;return{type:"explicit",template:{type:"explicit",content:s},config:o,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:e}}case"dev-v2":{const t=await W.loadPackDescription(e.folder),s=JSON.parse(await Z.promises.readFile(t.components.model.file,{encoding:"utf-8"})),o=await Z.promises.readFile(t.components.workflow.main.file),n=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await ze(t)),{type:"explicit",template:{type:"explicit",content:o},config:s,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:i}}case"from-registry-v1":{const t=`${sr(e.registryUrl)}${W.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,s=`${t}/template.plj.gz`,o=await this.remoteContentCache.forceFetch(s),n=new Uint8Array(o),i=await this.remoteContentCache.forceFetch(`${t}/config.json`),a=Le(i);return{type:"explicit",template:{type:"explicit",content:n},config:a,frontend:{type:"url",url:`${t}/frontend.tgz`},source:e}}case"from-registry-v2":{const s=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),o=async()=>Le(await this.remoteContentCache.forceFetch(s.model.url)),n=async()=>await this.remoteContentCache.forceFetch(s.workflow.main.url),[i,a]=await Promise.all([o(),n()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(a)},config:i,frontend:{type:"url",url:s.ui.url},source:e}}default:return C.assertNever(e)}}}function Oo(r,e){const t={config:e.config,source:e.source},s=r.createStruct(Eo,JSON.stringify(t));return r.createField(f.field(s,ts),"Input",Xe(r,e.template)),r.createField(f.field(s,rs),"Input",Po(r,e.frontend)),r.lock(s),s}function or(r,e){switch(e.type){case"prepared":return Oo(r,e);default:return C.assertNever(e.type)}}function Ne(r,e){return{__isRef:!0,blockId:r,name:e}}function $o(r){return typeof r=="object"&&r!==null&&"__isRef"in r&&r.__isRef===!0&&"blockId"in r&&"name"in r}function wt(r,e,t){const s=typeof e;switch(s){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if($o(e))t===void 0||t.has(e.blockId)?r.upstreams.add(e.blockId):r.missingReferences=!0;else if(Array.isArray(e))for(const o of e)wt(r,o,t);else for(const[,o]of Object.entries(e))wt(r,o,t);return;default:C.assertNever(s)}}function To(r,e){const t={upstreams:new Set,missingReferences:!1};return wt(t,r,e),t}function se(r){return{*[Symbol.iterator](){for(const e of r.groups)for(const t of e.blocks)yield t}}}class ss{constructor(e){S(this,"nodes");this.nodes=e}traverseIds(e,...t){const s=new Set;return this.traverse(e,t,o=>s.add(o.id)),s}traverseIdsExcludingRoots(e,...t){const s=this.traverseIds(e,...t);for(const o of t)s.delete(o);return s}traverse(e,t,s){let o=[...t];const n=new Set(o);for(;o.length>0;){const i=[];for(const a of o){const c=this.nodes.get(a);s(c),c[e].forEach(u=>{n.has(u)||(n.add(u),i.push(u))})}o=i}}}function St(r){const e=new Map;let t;for(const{id:s}of se(r)){const o={id:s,missingReferences:!1};e.set(s,o),t===void 0?o.directUpstream=o.upstream=new Set:(o.directUpstream=o.upstream=new Set([t.id]),t.directDownstream=t.downstream=new Set([o.id])),t=o}return t!==void 0&&(t.directDownstream=t.downstream=new Set),new ss(e)}function Je(r,e){const t=new Map,s=new ss(t),o=new Set;for(const{id:n}of se(r)){const i=e(n);if(i===void 0)continue;const a=To(i,o),c=s.traverseIds("directDownstream",...a.upstreams),u=new Set;for(const{id:d}of se(r)){if(d===n)break;if(c.has(d)){u.add(d);for(const h of s.traverseIdsExcludingRoots("upstream",d))u.delete(h)}}const l={id:n,missingReferences:a.missingReferences,upstream:u,directUpstream:a.upstreams,downstream:new Set,directDownstream:new Set};t.set(n,l),a.upstreams.forEach(d=>t.get(d).directDownstream.add(n)),u.forEach(d=>t.get(d).downstream.add(n)),o.add(n)}return s}function Io(r,e){if(r.size!==e.size)return!1;for(const t of r)if(!e.has(t))return!1;return!0}function bt(r,e){if(r.size>e.size)return bt(e,r);for(const t of r)if(e.has(t))return!0;return!1}function nr(r,e){const t=new Set,s=new Set,o=new Set;return r.nodes.forEach(n=>{const i=e.nodes.get(n.id);i===void 0?t.add(n.id):(!Io(n.upstream,i.upstream)||bt(n.upstream,o))&&o.add(n.id)}),e.nodes.forEach(n=>{r.nodes.has(n.id)?bt(n.upstream,o)&&o.add(n.id):s.add(n.id)}),{onlyInA:t,onlyInB:s,different:o}}let it;async function os(){if(it===void 0){const r=await es(Ts.Templates["pframes.export-pframe-for-ui"]);if(r.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=ee.createHash("sha256").update(r.content).digest("hex");it={spec:r,hash:e}}return it}function Fo(r,e,t){return $t(r,e,!0,{pf:t},["result"]).result}function at(r,e){let t=!1,s,o;return()=>{if(!t)return t=!0,s=r(),o=e(),o;const n=r();return s!==n&&(s=n,o=e()),e()}}class ir{constructor(e,t){S(this,"currentInputsC",at(()=>this.fields.currentArgs.modCount,()=>C.deepFreeze(JSON.parse(Buffer.from(this.fields.currentArgs.value).toString()))));S(this,"actualProductionInputsC",at(()=>{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 C.deepFreeze(JSON.parse(Buffer.from(e).toString()))}));S(this,"productionStaleC",at(()=>{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}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 currentInputs(){return this.currentInputsC()}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 actualProductionInputs(){return this.actualProductionInputsC()}getTemplate(e){return e.getFutureFieldValue(f.Pl.unwrapHolder(e,this.fields.blockPack.ref),ts,"Input")}}const Ao=r=>{throw new Error(`No new block info for ${r}`)};class He{constructor(e,t,s,o,n,i,a,c,u,l,d,h){S(this,"globalModCount",0);S(this,"fieldsChanged",!1);S(this,"lastModifiedChanged",!1);S(this,"structureChanged",!1);S(this,"metaChanged",!1);S(this,"renderingStateChanged",!1);S(this,"changedBlockFrontendStates",new Set);S(this,"blocksWithChangedInputs",new Set);S(this,"stagingGraph");S(this,"pendingProductionGraph");S(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=s,this.schema=o,this.lastModified=n,this.meta=i,this.struct=a,this.renderingState=c,this.blocksInLimbo=u,this.blockInfos=l,this.blockFrontendStates=d,this.ctxExportTplHolder=h}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=St(this.struct)),this.stagingGraph}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Je(this.struct,e=>this.getBlockInfo(e).currentInputs)),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Je(this.struct,e=>this.getBlockInfo(e).actualProductionInputs)),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(f.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of se(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,s){const o=f.field(this.rid,J(e,t));if(s.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",s.ref):this.tx.setField(o,s.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...s},this.fieldsChanged=!0}setBlockField(e,t,s,o,n){this.setBlockFieldObj(e,t,{ref:s,status:o,value:n})}deleteBlockFields(e,...t){let s=!1;const o=this.getBlockInfo(e);for(const n of t){const i=o.fields;n in i&&(this.tx.removeField(f.field(this.rid,J(e,n))),delete i[n],this.fieldsChanged=!0,s=!0)}return s}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var s,o,n;const t=this.getBlockInfo(e).fields;((s=t.stagingOutput)==null?void 0:s.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 s,o,n;const t=this.getBlockInfo(e).fields;((s=t.prodOutput)==null?void 0:s.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 s,o;const t=this.getBlockInfo(e).fields;return((s=t.prodOutput)==null?void 0:s.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:s,args:o}of e){const n=this.getBlockInfo(s);JSON.parse(o);const i=Buffer.from(o);if(Buffer.compare(n.fields.currentArgs.value,i)===0)continue;const a=this.tx.createValue(f.Pl.JsonObject,i);this.setBlockField(s,"currentArgs",a,"Ready",i),this.blocksWithChangedInputs.add(s),t.push(s)}this.getStagingGraph().traverse("downstream",t,({id:s})=>this.resetStaging(s)),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(s=>{var n;const o=this.getBlockInfo(s);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(f.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),er(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(s=>{var n,i;const o=this.getBlockInfo(s);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(f.Pl.unwrapHolder(this.tx,o.fields.stagingCtx.ref)),((i=o.fields.prodCtx)==null?void 0:i.ref)!==void 0&&t.push(f.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),er(this.tx,t)}exportCtx(e){return Fo(this.tx,f.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),s=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=Zt(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(f.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(f.Pl.JsonBool,JSON.stringify(!1)),context:s});this.setBlockField(e,"stagingCtx",f.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),s=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=Zt(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(f.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(f.Pl.JsonBool,JSON.stringify(!0)),context:s});this.setBlockField(e,"prodCtx",f.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=Ao){const s=this.getStagingGraph(),o=this.getActualProductionGraph(),n=St(e),i=Je(e,u=>{var l;return(l=this.blockInfos.get(u))==null?void 0:l.actualProductionInputs}),a=nr(s,n),c=nr(o,i);for(const u of a.onlyInA){const{fields:l}=this.getBlockInfo(u);this.deleteBlockFields(u,...Object.keys(l)),this.blockInfos.delete(u),this.blocksInLimbo.delete(u)&&(this.renderingStateChanged=!0),this.blockFrontendStates.delete(u)&&this.changedBlockFrontendStates.add(u)}for(const u of a.onlyInB){const l=new ir(u,{});this.blockInfos.set(u,l);const d=t(u),h=or(this.tx,d.blockPack);this.setBlockField(u,"blockPack",f.Pl.wrapInHolder(this.tx,h),"NotReady"),this.setBlockFieldObj(u,"blockSettings",this.createJsonFieldValue(q.InitialBlockSettings)),this.setBlockFieldObj(u,"currentArgs",this.createJsonFieldValueByContent(d.args)),d.uiState&&(this.blockFrontendStates.set(u,d.uiState),this.changedBlockFrontendStates.add(u)),l.check()}for(const u of a.different)this.resetStaging(u);o.traverse("downstream",[...c.different],u=>{this.resetOrLimboProduction(u.id)}),(a.onlyInB.size>0||a.onlyInA.size>0||a.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,s){const o=this.structure;if(s===void 0)o.groups[o.groups.length-1].blocks.push(e);else{let n=!1;for(const i of o.groups){const a=i.blocks.findIndex(c=>c.id===s);if(!(a<0)){i.blocks.splice(a,0,e),n=!0;break}}if(!n)throw new Error(`Can't find element with id: ${s}`)}this.updateStructure(o,n=>{if(n!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let s=!1;for(const o of t.groups){const n=o.blocks.findIndex(i=>i.id===e);if(!(n<0)){o.blocks.splice(n,1),s=!0;break}}if(!s)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,s){const o=this.getBlockInfo(e);this.setBlockField(e,"blockPack",f.Pl.wrapInHolder(this.tx,or(this.tx,t)),"NotReady"),s!==void 0?(this.setArgs([{blockId:e,args:s.args}]),this.setUiState(e,s.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 s=new Set(e),o=this.getPendingProductionGraph();if(t)o.traverse("upstream",e,a=>{s.add(a.id)});else for(const a of s){const c=o.nodes.get(a);if(c===void 0)throw new Error(`Can't find block with id: ${a}`);for(const u of c.upstream)if(!s.has(u))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const a of se(this.structure)){if(!s.has(a.id))continue;let c=this.getBlockInfo(a.id).requireProductionRendering||this.blocksInLimbo.has(a.id);if(!c){for(const u of o.nodes.get(a.id).upstream)if(n.has(u)){c=!0;break}}c&&(this.renderProductionFor(a.id),n.add(a.id))}const i=[...n];return o.traverse("downstream",i,a=>{n.has(a.id)||this.resetOrLimboProduction(a.id)}),this.getStagingGraph().traverse("downstream",i,({id:a})=>{i[0]!==a&&this.resetStaging(a)}),n.size>0&&this.updateLastModified(),n}stopProduction(...e){var i,a;const t=this.getActualProductionGraph(),s=new jr(e),o=new Set(e),n=[];for(;!s.isEmpty();){const c=s.shift(),u=this.getBlockInfo(c).fields;if(!(((i=u.prodOutput)==null?void 0:i.status)==="Ready"&&((a=u.prodCtx)==null?void 0:a.status)==="Ready")&&this.deleteBlockFields(c,"prodOutput","prodCtx","prodUiCtx","prodArgs")){n.push(c);for(const l of t.traverseIdsExcludingRoots("downstream",c))o.has(l)||(s.push(l),o.add(l))}}for(const c of t.traverseIdsExcludingRoots("downstream",...n))this.resetOrLimboProduction(c)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(o=>{let i=this.getBlockInfo(o.id).stagingRendered?0:1;o.upstream.forEach(a=>{const c=t.get(a);c!==0&&(i=Math.max(c+1,i))}),e(o.id,i),t.set(o.id,i)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,s=e===void 0?void 0:1+Math.max(0,t*e/1e3);let o=0;this.traverseWithStagingLag((n,i)=>{i!==0&&(s===void 0||i<=s)&&(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 s,o,n,i;((s=t.fields.prodCtx)==null?void 0:s.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,mt(t)):this.tx.setKValue(this.rid,mt(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,vt):this.tx.setKValue(this.rid,vt,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,Te,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,pe,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,Ie,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,gt(e)):this.tx.setKValue(this.rid,gt(e),t)}this.assignAuthorMarkers()}}static async load(e,t,s){const o=e.getResourceData(t,!0),n=e.getKValueJson(t,Jr),i=e.getKValueJson(t,Te),a=e.getKValueJson(t,Ie),c=e.getKValueJson(t,pe),u=e.getKValueJson(t,Ke),l=e.listKeyValuesString(t),[d,h,g,R,m,{stagingRefreshTimestamp:G,blocksInLimbo:N},U]=await Promise.all([o,n,i,a,c,u,l]);if(h!==_r)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${h}`);const F=new Map;for(const p of d.fields){const v=ro(p.name);if(v===void 0)continue;let w=F.get(v.blockId);w===void 0&&(w={id:v.blockId,fields:{}},F.set(v.blockId,w)),w.fields[v.fieldName]=f.isNullResourceId(p.value)?{modCount:0}:{modCount:0,ref:p.value}}const _=await os(),fe=yt(_.hash),B=d.fields.find(p=>p.name===fe);let ie;B!==void 0?ie=f.ensureResourceIdNotNull(B.value):(ie=f.Pl.wrapInHolder(e,Xe(e,_.spec)),e.createField(f.field(t,yt(_.hash)),"Dynamic",ie));const ue={stagingRefreshTimestamp:G},X=new Set(N),ce=new Map;for(const p of U){const v=Zs(p.key);v!==void 0&&ce.set(v,p.value)}const Q=[];F.forEach(({fields:p})=>{for(const[,v]of Object.entries(p))if(v.ref!==void 0){if(!f.isResource(v.ref)||f.isResourceRef(v.ref))throw new Error("unexpected behaviour");Q.push([v,e.getResourceData(v.ref,!1)])}});for(const[p,v]of Q){const w=await v;p.value=w.data,f.isNotNullResourceId(w.error)?p.status="Error":w.resourceReady||f.isNotNullResourceId(w.originalResourceId)?p.status="Ready":p.status="NotReady"}const V=new Map;F.forEach(({id:p,fields:v})=>V.set(p,new ir(p,v)));const H=new Set;for(const p of se(m)){if(!V.has(p.id))throw new Error(`Inconsistent project structure: no inputs for ${p.id}`);H.add(p.id)}V.forEach(p=>{if(!H.has(p.id))throw new Error(`Inconsistent project structure: no structure entry for ${p.id}`);p.check()});const y=new He(t,e,s,h,g,R,m,ue,X,V,ce,ie);return y.fixProblemsAndMigrate(),y}}async function Do(r,e=Ws){const t=r.createEphemeral(zs);r.lock(t);const s=String(Date.now());r.setKValue(t,Jr,JSON.stringify(_r)),r.setKValue(t,Ot,s),r.setKValue(t,Te,s),r.setKValue(t,Ie,JSON.stringify(e)),r.setKValue(t,pe,JSON.stringify(Hs)),r.setKValue(t,Ke,JSON.stringify(qs));const o=await os();return r.createField(f.field(t,yt(o.hash)),"Dynamic",f.Pl.wrapInHolder(r,Xe(r,o.spec))),t}async function Be(r,e,t){return re(r,e,void 0,t)}async function re(r,e,t,s){if(r instanceof f.PlClient)return await r.withWriteTx("ProjectAction",async o=>{const n=await He.load(o,e,t),i=await s(n);return n.wasModified&&(n.save(),await o.commit()),i});{const o=await He.load(r,e,t),n=await s(o);return o.save(),n}}function*Lo(r){switch(r.type){case"Json":return;case"JsonPartitioned":for(const[,e]of Object.entries(r.parts))yield e;return;case"BinaryPartitioned":for(const[,{index:e,values:t}]of Object.entries(r.parts))yield e,yield t;return;default:C.assertNever(r)}}function ar(r,e){return Object.fromEntries(Object.entries(r).map(([t,s])=>[t,e(s,t)]))}function No(r,e){switch(r.type){case"Json":return{...r};case"JsonPartitioned":return{...r,parts:ar(r.parts,e)};case"BinaryPartitioned":return{...r,parts:ar(r.parts,t=>({index:e(t.index),values:e(t.values)}))};default:C.assertNever(r)}}const Bo=f.resourceType("PColumnData/JsonPartitioned","1"),jo=f.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Vo=f.resourceType("PColumnData/BinaryPartitioned","1"),xo=f.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),Uo=f.resourceType("PColumnData/Json","1");function Go(r){if(!r.getIsReadyOrError())throw new Error("Data not ready.");const e=r.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(f.resourceTypesEqual(r.resourceType,Uo)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(f.resourceTypesEqual(r.resourceType,Bo)){const t=e,s=Object.fromEntries(r.listInputFields().map(o=>[o,r.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:s}}else if(f.resourceTypesEqual(r.resourceType,jo)){const t=e,s={};for(const o of r.listInputFields()){const n=r.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const a of i){const c=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);s[c]=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:s}}else if(f.resourceTypesEqual(r.resourceType,Vo)){const t=e,s={};for(const o of r.listInputFields())if(o.endsWith(".index")){const n=o.slice(0,o.length-6);let i=s[n];i===void 0&&(i={},s[n]=i),i.index=r.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else if(o.endsWith(".values")){const n=o.slice(0,o.length-7);let i=s[n];i===void 0&&(i={},s[n]=i),i.values=r.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${o}`);for(const[o,n]of Object.entries(s)){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:s}}else if(f.resourceTypesEqual(r.resourceType,xo)){const t=e,s={};for(const o of r.listInputFields()){const n=r.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const a of i)if(a.endsWith(".index")){const c=a.slice(0,a.length-6),u=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);let l=s[u];l===void 0&&(l={},s[u]=l),s[u].index=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else if(a.endsWith(".values")){const c=a.slice(0,a.length-7),u=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);let l=s[u];l===void 0&&(l={},s[u]=l),s[u].values=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${a}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:s}}throw new Error(`unsupported resource type: ${f.resourceTypeToString(r.resourceType)}`)}function Mo(r,e){const t=r.axesSpec.length,s={};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}`);s[JSON.stringify(o)]=n}return{type:"Json",keyLength:t,data:s}}function Jo(r,e){const t=ee.createHash("sha256");return t.update(x(r)),t.update(String(f.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function cr(r,e){return x({__isRef:!0,blockId:r,name:e})}function _o(r,e){return x({resolvePath:r,name:e})}function ns(r,e=!0,t=!1,s=""){var a,c,u;const o=/^(?<name>.*)\.(?<type>spec|data)$/,n=new Map;for(const l of r.listInputFields()){const d=l.match(o);if(!d){if(e)throw new Error(`unexpected field name ${l}`);continue}let h=C.notEmpty((a=d.groups)==null?void 0:a.name);if(!h.startsWith(s)){if(e)throw new Error(`unexpected field name ${l}`);continue}h=h.slice(s.length);const g=C.notEmpty((c=d.groups)==null?void 0:c.type);let R=n.get(h);switch(R===void 0&&(R={},n.set(h,R)),g){case"spec":R.spec=(u=r.traverse({field:l,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:u.getDataAsJson();break;case"data":R.hasData=!0,R.data=()=>r.traverseOrError({field:l,ignoreError:t});break}}const i=r.getInputsLocked();if(i)for(const[,l]of n)l.data===void 0&&(l.hasData=!1);return{locked:i,results:n}}function Ko(r,e=!0,t="",s){if(!r.getIsReadyOrError())throw new Error("resource is not ready");const o=ns(r,e,!1,t);Is(o.locked);const n={};for(const[i,a]of o.results){if(a.spec===void 0)throw new Error(`no spec for key ${i}`);if(a.hasData!==!0||a.data===void 0)throw new Error(`no data for key ${i}`);const c=a.data();if(c===void 0)throw new Error(`no data for key ${i}`);if(!c.ok)throw c.error;n[i]={id:s.length===0?Jo(a.spec,c.value):_o(s,i),spec:a.spec,data:c.value}}return n}class Ft{constructor(e,t){S(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let s=!0;e:for(const o of t.values())for(const n of[o.prod,o.staging])if(n!==void 0){if(!n.locked){s=!1;break e}for(const i of n.results.values())if(i.spec===void 0){s=!1;break e}}this.allSpecsAvailable=s}getSpecByRef(e,t){var n,i,a,c,u,l;const s=this.blocks.get(e);if(s===void 0)return;let o=(a=(i=(n=s.prod)==null?void 0:n.results)==null?void 0:i.get(t))==null?void 0:a.spec;if(o!==void 0||(o=(l=(u=(c=s.staging)==null?void 0:c.results)==null?void 0:u.get(t))==null?void 0:l.spec,o!==void 0))return o;s.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):s.staging.locked?s.prod!==void 0&&!s.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var i,a,c;const s=this.blocks.get(e);if(s===void 0)return;const o=(a=(i=s.prod)==null?void 0:i.results)==null?void 0:a.get(t),n=(c=o==null?void 0:o.data)==null?void 0:c.call(o);if(o!==void 0&&o.spec!==void 0&&n!==void 0)return D.mapValueInVOE(n,u=>({id:cr(e,t),spec:o.spec,data:u}));o!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),s.prod!==void 0&&!s.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const s=this.getDataOrErrorByRef(e,t);if(!(s===void 0||!s.ok))return s.value}getData(){const e=this.getDataWithErrors(),t=[];for(const s of e.entries)s.obj.id!==void 0&&s.obj.data.ok&&t.push({ref:s.ref,obj:{id:s.obj.id,spec:s.obj.spec,data:s.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,s;const o=i=>{s===void 0&&(s=i),t=!1},n=(i,a,c)=>{if(c.spec!==void 0&&c.hasData===!0&&c.data!==void 0){const u=c.data();u!==void 0?e.push({ref:Ne(i,a),obj:{id:u.ok?cr(i,a):void 0,spec:c.spec,data:u}}):o(`no_data:${i}:${a}`)}};for(const[i,a]of this.blocks){const c=new Set;if(a.prod!==void 0){a.prod.locked||o(`prod_not_locked:${i}`);for(const[u,l]of a.prod.results)c.add(u),n(i,u,l)}if(a.staging!==void 0){a.staging.locked||o(`staging_not_locked:${i}`);for(const[u,l]of a.staging.results)c.has(u)||n(i,u,l)}}return{entries:e,isComplete:t,instabilityMarker:s}}getSpecs(){const e=[];let t=!0,s;const o=n=>{s===void 0&&(s=n),t=!1};for(const[n,i]of this.blocks){const a=new Set;if(i.staging!==void 0){i.staging.locked||o(`staging_not_locked:${n}`);for(const[c,u]of i.staging.results)u.spec!==void 0&&(e.push({ref:Ne(n,c),obj:u.spec}),a.add(c))}else o(`staging_not_rendered:${n}`);if(i.prod!==void 0){i.prod.locked||o(`prod_not_locked:${n}`);for(const[c,u]of i.prod.results)a.has(c)||u.spec!==void 0&&e.push({ref:Ne(n,c),obj:u.spec})}}return{entries:e,isComplete:t,instabilityMarker:s}}calculateOptions(e){const t=[];for(const s of this.blocks.values()){const o=new Set,n=i=>{for(const[a,c]of i.results)o.has(a)||c.spec===void 0||(o.add(a),D.executePSpecPredicate(e,c.spec)&&t.push({label:s.info.label+" / "+a,ref:Ne(s.info.id,a),spec:c.spec}))};s.staging!==void 0&&n(s.staging),s.prod!==void 0&&n(s.prod)}return t}static create(e,t,s){const o=e.accessor(t).node(),n=C.notEmpty(o.getKeyValueAsJson(pe)),a=St(n).traverseIds("upstream",s),c=new Map;for(const u of se(n)){if(!a.has(u.id))continue;const l=lr(o.traverse({field:J(u.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:J(u.id,"prodUiCtx"),stableIfNotFound:!0})),d=lr(o.traverse({field:J(u.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:J(u.id,"stagingUiCtx")}));c.set(u.id,{info:u,prod:l,staging:d})}return new Ft(e,c)}}function lr(r,e){if(e===void 0)return r?{locked:!1,results:new Map}:void 0;if(e.ok)return ns(e.value,!1,!0)}function At(r,e){return{blockId:e,args:n=>C.notEmpty(n.accessor(r).node().traverse({field:J(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),activeArgs:n=>{var i;return(i=n.accessor(r).node().traverse({field:J(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:i.getDataAsString()},uiState:n=>n.accessor(r).node().getKeyValueAsString(gt(e)),blockMeta:n=>{const i=n.accessor(r).node(),a=C.notEmpty(i.getKeyValueAsJson(pe)),c=new Map;for(const u of se(a))c.set(u.id,u);return c}}}function is(r,e){return{...At(r,e),prod:t=>{var s;return(s=t.accessor(r).node({ignoreError:!0}).traverse({field:J(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:s.persist()},staging:t=>{var o;const s=(o=t.accessor(r).node({ignoreError:!0}).traverse({field:J(e,"stagingOutput"),ignoreError:!0}))==null?void 0:o.persist();return s===void 0&&t.markUnstable("staging_not_rendered"),s},getResultsPool:t=>Ft.create(t,r,e)}}function*Y(r,e){switch(yield r,r.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*Y(r.cfg);return;case"MakeObject":for(const[,t]of Object.entries(r.template))yield*Y(t);return;case"MakeArray":for(const t of r.template)yield*Y(t);return;case"GetJsonField":case"GetResourceField":yield*Y(r.source),yield*Y(r.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*Y(r.source),yield*Y(r.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*Y(r.source);return;case"IsEmpty":yield*Y(r.arg);return;case"Not":yield*Y(r.operand);return;case"And":case"Or":yield*Y(r.operand1),yield*Y(r.operand2);return;default:C.assertNever(r)}}function Ho(r,e){const t={};for(const[s,o]of Object.entries(r))t[s]=e(o);return t}function Ee(r,e){return r===void 0?void 0:e(r)}function qo(r){switch(r.type){case"GetImportProgress":return!0;default:return!1}}function Wo(r){for(const e of Y(r))if(qo(e))return!0;return!1}function Ye(r){return{type:"ReturnResult",result:r}}function $(r){return()=>Ye(r)}const zo=r=>{const e={};for(const[t,s]of Object.entries(r))e[t]=s;return $(e)},Xo=r=>{const e=r.source;if(e===void 0)return $(void 0);const t=[];for(const s of e)s instanceof Array?t.push(...s):t.push(s);return $(t)},Yo=r=>{const e=r.source,t=r.field;return e===void 0||t===void 0?$(void 0):({cCtx:s})=>{var o;return Ye((o=s.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function as(r,e){const t={},s=r.length;for(let o=0;o<s;o++)t[String(o)]=e(r[o]);return t}function Qo(r,e){return t=>{const s=t.source;return s===void 0?$(void 0):()=>({type:"ScheduleSubroutine",subroutine:cs(s.length),args:as(s,o=>T({...r,[e.itVar]:o},e.mapping))})}}function cs(r){return e=>{const t=[];for(let s=0;s<r;s++)t.push(e[String(s)]);return $(t)}}function Zo(r,e){return t=>{const s=t.source;if(s===void 0)return $(void 0);const o={};for(const[n,i]of Object.entries(s)){const a={...r,[e.itVar]:i};o[n]=T(a,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:en,args:o})}}const en=r=>$(r),tn=r=>{const e=r.arg;return $(e===void 0?void 0:e.length===0)},rn=r=>{const e=r.operand;return $(e===void 0?void 0:!e)},sn=r=>{const e=r.operand1,t=r.operand2;return $(e===void 0||t===void 0?void 0:e&&t)},on=r=>{const e=r.operand1,t=r.operand2;return $(e===void 0||t===void 0?void 0:e||t)},nn=r=>{const e=r.source;return e===void 0?$(void 0):({cCtx:t})=>{var s;return Ye((s=t.accessor(e).node())==null?void 0:s.getDataAsJson())}},an=r=>{const e=r.source,t=r.field;return $(e===void 0||t===void 0?void 0:e[t])};function cn(r,e){return t=>{const s=t.source;return s===void 0?$(void 0):({cCtx:o})=>{const n=o.accessor(s).node(),i={};for(const a of n.listInputFields()){const c=n.traverse(a);if(c===void 0)i[a]=$(void 0);else{const u={...r,[e.itVar]:c.persist()};i[a]=T(u,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:ln,args:i}}}}const ln=r=>$(r),un=r=>{const e=r.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:j.Computable.make(s=>t.blobDriver.getDownloadedBlob(s.accessor(e).node().resourceInfo),{postprocessValue:async s=>{if(s!==void 0)return await t.blobDriver.getContent(s.handle)}})})},dn=r=>{const e=r.source;return e===void 0?$(void 0):({cCtx:t,drivers:s})=>{const o=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:j.Computable.make(()=>s.blobDriver.getDownloadedBlob(o),{postprocessValue:async n=>n===void 0?void 0:(await s.blobDriver.getContent(n.handle)).toString()})}}},pn=r=>{const e=r.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:j.Computable.make(s=>t.blobDriver.getDownloadedBlob(s.accessor(e).node().resourceInfo),{postprocessValue:async s=>{if(s==null)return;const o=await t.blobDriver.getContent(s.handle);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},fn=r=>{const e=r.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},hn=r=>{const e=r.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},gn=r=>e=>{const t=e.source;return t===void 0?$(void 0):({drivers:s})=>({type:"ScheduleComputable",computable:s.blobToURLDriver.extractArchiveAndGetURL(t,r)})},mn=r=>{const e=r.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},vn=r=>e=>{const t=e.source;return t===void 0?$(void 0):({drivers:s})=>({type:"ScheduleComputable",computable:s.logDriver.getLastLogs(t,r)})},yn=r=>e=>{const t=e.source;return t===void 0?$(void 0):({drivers:s})=>({type:"ScheduleComputable",computable:s.logDriver.getProgressLog(t,r)})},wn=r=>e=>{const t=e.source;return t===void 0?$(void 0):({drivers:s})=>({type:"ScheduleComputable",computable:s.logDriver.getProgressLogWithInfo(t,r)})},Sn=r=>{const e=r.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function T(r,e){switch(e.type){case"GetFromCtx":{const t=r[e.variable];return typeof t=="function"?s=>Ye(t(s.cCtx)):$(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:ds(t,r,e.cfg)});case"Immediate":return $(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:an,args:{source:T(r,e.source),field:T(r,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:Qo(r,e),args:{source:T(r,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:Zo(r,e),args:{source:T(r,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:zo,args:Ho(e.template,t=>T(r,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:cs(e.template.length),args:as(e.template,t=>T(r,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:Xo,args:{source:T(r,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:tn,args:{arg:T(r,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:rn,args:{operand:T(r,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:sn,args:{operand1:T(r,e.operand1),operand2:T(r,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:on,args:{operand1:T(r,e.operand1),operand2:T(r,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:cn(r,e),args:{source:T(r,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:Yo,args:{source:T(r,e.source),field:T(r,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:nn,args:{source:T(r,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:un,args:{source:T(r,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:dn,args:{source:T(r,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:pn,args:{source:T(r,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:fn,args:{source:T(r,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:hn,args:{source:T(r,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:gn(e.format),args:{source:T(r,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:mn,args:{source:T(r,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:vn(e.lines),args:{source:T(r,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:yn(e.patternToSearch),args:{source:T(r,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:wn(e.patternToSearch),args:{source:T(r,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:Sn,args:{source:T(r,e.source)}});default:return C.assertNever(e)}}const bn=["$prod","$staging"];function Pn(r){return{$blockId:r.blockId,$args:e=>JSON.parse(r.args(e)),$ui:e=>{const t=r.uiState(e);return t!==void 0?JSON.parse(t):void 0},$prod:r.prod,$staging:r.staging}}const ls=Symbol(),us="return",Rn={op:ls,arg:us};function En(r){return r.op==ls&&r.arg==us}function Cn(){return{pendingSubroutines:new Map}}function ur(r,e,t,s){const o=new jr(t),n=(a,c)=>{if(En(a))return e.result=c,!1;const u=C.notEmpty(e.pendingSubroutines.get(a.op));if(a.arg in u.args)throw new Error("argument already set");return u.args[a.arg]=c,u.argCounter--,u.argCounter===0&&(e.pendingSubroutines.delete(a.op),o.push({destination:u.destination,operation:u.subroutine(u.args)})),!0},i=[];e:for(;o.length>0;){const a=o.shift(),c=a.operation(r);switch(c.type){case"ReturnResult":if(!n(a.destination,c.result))break e;break;case"ScheduleSubroutine":{const u=Symbol(),l=Object.entries(c.args),d=l.length;if(d===0)o.push({destination:a.destination,operation:c.subroutine({})});else{for(const[h,g]of l)o.push({destination:{op:u,arg:h},operation:g});e.pendingSubroutines.set(u,{argCounter:d,args:{},subroutine:c.subroutine,destination:a.destination})}}break;case"ScheduleComputable":if(!s)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:a.destination,computable:c.computable});break;default:C.assertNever(c)}}return i}function kn(r,e,t,s={}){return ds(r,Pn(e),t,s)}function ds(r,e,t,s={}){const o=`${e.blockId}#`+x({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>bn.indexOf(n)===-1)),cfg:t});return j.Computable.makeRaw(n=>{const i={drivers:r,cCtx:n},a=Cn();return{ir:ur(i,a,[{destination:Rn,operation:T(e,t)}],!0),postprocessValue(u){const l=[];for(const R of u)l.push({destination:R.destination,operation:$(R.computable)});const d={drivers:r,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},h=new Map;for(const[R,m]of a.pendingSubroutines)h.set(R,{...m,args:{...m.args}});const g={result:a.result,pendingSubroutines:h};if(ur(d,g,l,!1),!("result"in g))throw new Error("illegal cfg rendering stack state, no result");return g.result}}},{...s,key:o})}function On(r){return r instanceof ArrayBuffer||ArrayBuffer.isView(r)}function dr(r){return r!==void 0?Buffer.from(r).toString("base64"):void 0}class qe{constructor(e,t,s,o,n,i){S(this,"callbackRegistry");S(this,"fnJSONStringify");S(this,"fnJSONParse");S(this,"computablesToResolve",{});S(this,"computableCtx");S(this,"accessors",new Map);S(this,"meta");S(this,"errorRepo",new $n);S(this,"_resultPool");if(this.scope=e,this.vm=t,this.blockCtx=s,this.env=o,this.deadlineSetter=n,this.computableCtx=i,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(a=>t.getProp(a,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(a=>t.getProp(a,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");this.meta=s.blockMeta(i),this.injectCtx()}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}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 qe.cleanErrorContext(t),t}finally{this.deadlineSetter(void 0)}}runCallback(e,...t){try{return this.deadlineSetter({currentExecutionTarget:e,deadline:Date.now()+1e4}),$e.Scope.withScope(s=>{const o=s.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,s)))))})}catch(s){throw qe.cleanErrorContext(s),this.errorRepo.getOriginal(s)}finally{this.deadlineSetter(void 0)}}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(s,o)=>{if(!this.accessors.has(s)){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(s,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(s,void 0)}return this.accessors.get(s)?s:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...s){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...s))}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 dr(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return dr(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,s,...o){const n=this.getAccessor(e);if(!n.getIsReadyOrError())return;const i=Ko(n,t,s,o),a={};for(const[c,u]of Object.entries(i))a[c]=D.mapPObjectData(u,l=>this.wrapAccessor(l));return a}registerComputable(e,t){const s=`${e}_${ee.randomUUID()}`;return this.computablesToResolve[s]=t,s}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",j.Computable.make(s=>this.env.driverKit.blobDriver.getDownloadedBlob(t,s),{postprocessValue:async s=>{if(s!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(s.handle)).toString("utf-8")}}))}getBlobContentAsBase64(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",j.Computable.make(s=>this.env.driverKit.blobDriver.getDownloadedBlob(t,s),{postprocessValue:async s=>{if(s!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(s.handle)).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 s=this.getAccessor(e).persist();return this.registerComputable("extractArchiveAndGetURL",this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(s,t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const s=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(s,t))}getProgressLog(e,t){const s=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(s,t))}getProgressLogWithInfo(e,t){const s=this.getAccessor(e).persist();return this.registerComputable("getProgressLogWithInfo",this.env.driverKit.logDriver.getProgressLogWithInfo(s,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=C.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,s=>this.wrapAccessor(s))}))}}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,s=>this.wrapAccessor(s))}}))}}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),s=>this.wrapAccessor(s))}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,s=>this.transformInputPData(s))),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,s=>this.transformInputPData(s))),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}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=ee.randomUUID();return this.accessors.set(t,e),t}}exportSingleValue(e,t){const s=this.tryExportSingleValue(e,t);if(s===void 0)throw new Error(`Can't export value: ${e===void 0?"undefined":JSON.stringify(e)}`);return s}tryExportSingleValue(e,t){let s,o=!1;switch(typeof e){case"string":s=this.vm.newString(e),o=!0;break;case"number":s=this.vm.newNumber(e),o=!0;break;case"undefined":s=this.vm.undefined;break;case"boolean":s=e?this.vm.true:this.vm.false;break;default:if(e===null){s=this.vm.null;break}if(On(e)){s=this.vm.newArrayBuffer(e),o=!0;break}return}return o&&t!=null?t.manage(s):s}exportObjectUniversal(e,t){const s=this.tryExportSingleValue(e,t);return s!==void 0?s:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const s=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(s):s}importObjectUniversal(e){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(s=>this.vm.getString(s));if(t!=="undefined")return JSON.parse(t)}injectCtx(){$e.Scope.withScope(e=>{const t=e.manage(this.vm.newObject()),s=this.blockCtx.args(this.computableCtx),o=this.blockCtx.activeArgs(this.computableCtx),n=this.blockCtx.uiState(this.computableCtx);this.vm.setProp(t,"args",e.manage(this.vm.newString(s))),n!==void 0&&this.vm.setProp(t,"uiState",e.manage(this.vm.newString(n))),o!==void 0&&this.vm.setProp(t,"activeArgs",e.manage(this.vm.newString(o))),this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(D.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e));const i=(a,c)=>{const u=(...l)=>{try{return c(...l)}catch(d){const h=this.errorRepo.setAndRecreateForQuickJS(d);throw this.vm.newError(h)}};this.vm.newFunction(a,u).consume(l=>this.vm.setProp(t,a,l)),this.vm.newFunction(a,c).consume(l=>this.vm.setProp(t,a+"__internal__",l))};i("getAccessorHandleByName",a=>this.exportSingleValue(this.getAccessorHandleByName(this.vm.getString(a)),void 0)),i("resolveWithCommon",(a,c,...u)=>this.exportSingleValue(this.resolveWithCommon(this.vm.getString(a),this.importObjectViaJson(c),...u.map(l=>this.importObjectViaJson(l))),void 0)),i("getResourceType",a=>this.exportObjectViaJson(this.getResourceType(this.vm.getString(a)),void 0)),i("getInputsLocked",a=>this.exportSingleValue(this.getInputsLocked(this.vm.getString(a)),void 0)),i("getOutputsLocked",a=>this.exportSingleValue(this.getOutputsLocked(this.vm.getString(a)),void 0)),i("getIsReadyOrError",a=>this.exportSingleValue(this.getIsReadyOrError(this.vm.getString(a)),void 0)),i("getIsFinal",a=>this.exportSingleValue(this.getIsFinal(this.vm.getString(a)),void 0)),i("getError",a=>this.exportSingleValue(this.getError(this.vm.getString(a)),void 0)),i("listInputFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("listOutputFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("listDynamicFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("getKeyValueBase64",(a,c)=>this.exportSingleValue(this.getKeyValueBase64(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getKeyValueAsString",(a,c)=>this.exportSingleValue(this.getKeyValueAsString(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getDataBase64",a=>this.exportSingleValue(this.getDataBase64(this.vm.getString(a)),void 0)),i("getDataAsString",a=>this.exportSingleValue(this.getDataAsString(this.vm.getString(a)),void 0)),i("parsePObjectCollection",(a,c,u,...l)=>this.exportObjectUniversal(this.parsePObjectCollection(this.vm.getString(a),this.vm.dump(c),this.vm.getString(u),...l.map(d=>this.vm.getString(d))),void 0)),i("getBlobContentAsBase64",a=>this.exportSingleValue(this.getBlobContentAsBase64(this.vm.getString(a)),void 0)),i("getBlobContentAsString",a=>this.exportSingleValue(this.getBlobContentAsString(this.vm.getString(a)),void 0)),i("getDownloadedBlobContentHandle",a=>this.exportSingleValue(this.getDownloadedBlobContentHandle(this.vm.getString(a)),void 0)),i("getOnDemandBlobContentHandle",a=>this.exportSingleValue(this.getOnDemandBlobContentHandle(this.vm.getString(a)),void 0)),i("extractArchiveAndGetURL",(a,c)=>this.exportSingleValue(this.extractArchiveAndGetURL(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getImportProgress",a=>this.exportSingleValue(this.getImportProgress(this.vm.getString(a)),void 0)),i("getLastLogs",(a,c)=>this.exportSingleValue(this.getLastLogs(this.vm.getString(a),this.vm.getNumber(c)),void 0)),i("getProgressLog",(a,c)=>this.exportSingleValue(this.getProgressLog(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getProgressLogWithInfo",(a,c)=>this.exportSingleValue(this.getProgressLogWithInfo(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getLogHandle",a=>this.exportSingleValue(this.getLogHandle(this.vm.getString(a)),void 0)),i("getBlockLabel",a=>this.exportSingleValue(this.getBlockLabel(this.vm.getString(a)),void 0)),i("getDataFromResultPool",()=>this.exportObjectUniversal(this.getDataFromResultPool(),void 0)),i("getDataWithErrorsFromResultPool",()=>this.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),i("getSpecsFromResultPool",()=>this.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),i("calculateOptions",a=>this.exportObjectUniversal(this.calculateOptions(this.importObjectViaJson(a)),void 0)),i("getSpecFromResultPoolByRef",(a,c)=>this.exportObjectUniversal(this.getSpecFromResultPoolByRef(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getDataFromResultPoolByRef",(a,c)=>this.exportObjectUniversal(this.getDataFromResultPoolByRef(this.vm.getString(a),this.vm.getString(c)),void 0)),i("createPFrame",a=>this.exportSingleValue(this.createPFrame(this.importObjectViaJson(a)),void 0)),i("createPTable",a=>this.exportSingleValue(this.createPTable(this.importObjectViaJson(a)),void 0)),i("getCurrentUnstableMarker",()=>this.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}class $n{constructor(){S(this,"errorIdToError",new Map)}setAndRecreateForQuickJS(e){const t=ee.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 $e.errors.QuickJSUnwrapError))return console.warn("ErrorRepo: quickJSError is not a QuickJSUnwrapError",f.stringifyWithResourceId(e)),e;if(!("name"in e.cause))return console.warn("ErrorRepo: quickJSError.cause is not an Error",f.stringifyWithResourceId(e)),e;const t=e.cause.name,s=t.slice(t.indexOf("/uuid:")+6);if(!s)throw new Error(`ErrorRepo: quickJSError.cause.name does not contain errorId: ${t}, ${f.stringifyWithResourceId(e)}`);const o=this.errorIdToError.get(s);if(o===void 0)throw new Error(`ErrorRepo: errorId not found: ${s}, ${f.stringifyWithResourceId(e)}`);return new Fs.PlQuickJSError(e,o)}}function Qe(r,e){return Ee(r.traverse({field:J(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:f.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const s=t.getDataAsJson(),o=D.extractConfig(s.config);return{bpId:t.resourceInfo.id.toString(),info:s,cfg:o}})}const je=process.env.MI_LOG_OUTPUT_STATUS;function Tn(r,e,t,s,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"),j.Computable.makeRaw(a=>{const c=new $e.Scope;a.addOnDestroy(()=>c.dispose());const u=c.manage(r.quickJs.newRuntime());u.setMemoryLimit(1024*1024*8),u.setMaxStackSize(1024*320);let l;u.setInterruptHandler(()=>l===void 0?!1:Date.now()>l.deadline);const d=c.manage(u.newContext()),h=new qe(c,d,e,r,m=>{l=m},a);h.evaluateBundle(s.content);const g=h.runCallback(t.handle);h.resetComputableCtx();let R=0;return je&&je!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:h.computablesToResolve,postprocessValue:(m,{unstableMarker:G,stable:N})=>{for(const[F,_]of Object.entries(m))h.runCallback(F,_);const U=h.importObjectUniversal(g);return R++,je&&(je!=="unstable-only"||!N)&&console.log(N?`Stable output ${t.handle} calculated ${U!==void 0?"defined":"undefined"}; (#${R})`:`Unstable output ${t.handle}; marker = ${G}; ${U!==void 0?"defined":"undefined"} (#${R})`),U}}},n)}function In(r){return D.isConfigLambda(r)?r.isActive===!0:Wo(r)}function Ce(r,e,t,s,o,n={}){if(D.isConfigLambda(t)){if(s===void 0)throw new Error("No code bundle.");return Tn(r,e,t,s,o,n)}else return kn(r.driverKit,e,t,n)}function Fn(r,e){if(r===e)return!0;if(r===void 0||e===void 0)return!1;const t=zt.omitBy((s,o)=>o.startsWith("__"));return zt.isDeepEqual(t(r),t(e))}function An(r,e,t){return j.Computable.make(s=>{var R,m,G,N,U,F,_,fe;const o=s.accessor(r).node(),n=C.notEmpty(o.getKeyValueAsJson(Ot)),i=C.notEmpty(o.getKeyValueAsJson(Te)),a=C.notEmpty(o.getKeyValueAsJson(Ie)),c=C.notEmpty(o.getKeyValueAsJson(pe)),u=C.notEmpty(o.getKeyValueAsJson(Ke)),l=new Map;for(const{id:B}of se(c)){const ue=o.traverse({field:J(B,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson();let X;const ce=o.traverse({field:J(B,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(ce!==void 0){const Q=ce.getDataAsJson(),V=o.getField({field:J(B,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),H=o.getField({field:J(B,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});X={arguments:Q,stale:!Fn(ue,Q),outputError:V.error!==void 0||H.error!==void 0||((R=V.value)==null?void 0:R.getError())!==void 0||((m=H.value)==null?void 0:m.getError())!==void 0,outputsError:((G=V.error)==null?void 0:G.getDataAsString())??((U=(N=V.value)==null?void 0:N.getError())==null?void 0:U.getDataAsString()),exportsError:((F=H.error)==null?void 0:F.getDataAsString())??((fe=(_=H.value)==null?void 0:_.getError())==null?void 0:fe.getDataAsString()),finished:(V.value!==void 0&&V.value.getIsReadyOrError()||V.error!==void 0&&V.error.getIsReadyOrError())&&(H.value!==void 0&&H.value.getIsReadyOrError()||H.error!==void 0&&H.error.getIsReadyOrError())}}l.set(B,{currentArguments:ue,prod:X})}const d=Je(c,B=>l.get(B).currentArguments),h=new Set(u.blocksInLimbo),g=[...se(c)].map(({id:B,label:ie,renderingMode:ue})=>{var b,E,I,O,L;const X=C.notEmpty(l.get(B)),ce=C.notEmpty(d.nodes.get(B));let Q="NotCalculated";X.prod!==void 0&&(h.has(B)?Q="Limbo":Q=X.prod.finished?"Done":"Running");const V=Qe(o,B),{sections:H,title:y,inputsValid:p,sdkVersion:v}=Ee(V,({bpId:M,cfg:A})=>{const le=At(r,B);return{sections:Ce(t,le,A.sections,A.code,M).wrap({recover:we=>(t.logger.error("Error in block model sections"),t.logger.error(we),[])}),title:Ee(A.title,we=>Ce(t,le,we,A.code,M).wrap({recover:Rs=>(t.logger.error("Error in block model title"),t.logger.error(Rs),"Invalid title")})),inputsValid:Ce(t,le,A.inputsValid,A.code,M).wrap({recover:we=>(t.logger.error("Error in block model argsValid"),t.logger.error(we),!1)}),sdkVersion:A.sdkVersion}})||{},w=o.traverse({field:J(B,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),P=Ee(V,({info:M})=>t.blockUpdateWatcher.get({currentSpec:M.source,settings:w}));return{projectResourceId:f.resourceIdToString(r.rid),id:B,label:y??ie,title:y??ie,renderingMode:ue,stale:((b=X.prod)==null?void 0:b.stale)!==!1||Q==="Limbo",missingReference:ce.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",B)],downstreams:[...d.traverseIdsExcludingRoots("downstream",B)],calculationStatus:Q,outputErrors:((E=X.prod)==null?void 0:E.outputError)===!0,outputsError:(I=X.prod)==null?void 0:I.outputsError,exportsError:(O=X.prod)==null?void 0:O.exportsError,settings:w,sections:H,inputsValid:p,updateInfo:{},currentBlockPack:(L=V==null?void 0:V.info)==null?void 0:L.source,updates:P,sdkVersion:v,navigationState:e.getState(B)}});return{meta:a,created:new Date(n),lastModified:new Date(i),authorMarker:o.getKeyValueAsJson(vt),blocks:g}},{postprocessValue:s=>{const o=new Set,n=new Set;return{...s,blocks:s.blocks.map(i=>{var l,d;i.inputsValid||o.add(i.id),i.stale&&n.add(i.id);const a=i.stale||i.upstreams.findIndex(h=>n.has(h))!==-1,c=(a||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(h=>o.has(h))===-1,u={...i,canRun:c,stale:a,updateSuggestions:((l=i.updates)==null?void 0:l.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete u.updates,u})}}}).withStableType()}function Dn(r,e){const t=r.node();if(f.resourceTypesEqual(t.resourceType,Tt)){const s=t.getDataAsJson();if(s===void 0)throw new Error("No resource data.");return e.frontendDownloadDriver.getPath(new URL(s.url)).withStableType()}else if(f.resourceTypesEqual(t.resourceType,It)){const s=t.getDataAsJson();if(s===void 0)throw new Error("No resource data.");return e.signer.verify(s.path,s.signature,`Frontend path signature mismatch for: ${s.path}`),s.path}else throw new Error(`Unsupported resource type: ${JSON.stringify(t.resourceType)}`)}function Ln(r,e){if(r!==void 0)return j.Computable.make(t=>Dn(t.accessor(r),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 Nn(r,e,t){return j.Computable.make(s=>{var a;const o=s.accessor(r).node(),n=Qe(o,e),i=(a=o.traverse({field:J(e,"blockPack"),assertFieldType:"Dynamic"},{field:f.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:rs,assertFieldType:"Input"}))==null?void 0:a.persist();return{path:Ln(i,t),sdkVersion:n==null?void 0:n.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function ps(r,e,t){if(t===void 0)return j.Computable.make(i=>ps(r,e,i),{key:`inputs#${f.resourceIdToString(r.rid)}#${e}`});const s=t.accessor(r).node(),o=At(r,e),n=o.uiState(t);return{author:s.getKeyValueAsJson(mt(e)),args:C.deepFreeze(JSON.parse(o.args(t))),ui:n!==void 0?C.deepFreeze(JSON.parse(n)):void 0}}function Bn(r,e,t){return j.Computable.make(s=>{const o=s.accessor(r).node(),n=is(r,e);return Ee(Qe(o,e),({cfg:i,bpId:a})=>{const c={};for(const[u,l]of Object.entries(i.outputs)){const d=Ce(t,n,l,i.code,a);c[u]=j.Computable.wrapError(d,1)}return c})},{key:"outputs#"+f.resourceIdToString(r.rid)+"#"+e}).withStableType()}function jn(r,e){return j.Computable.make(t=>{const s=t.accessor(r).node(),o=C.notEmpty(s.getKeyValueAsJson(pe)),n=[];for(const{id:i}of se(o)){const a=Qe(s,i);if(a===void 0)continue;const c=Object.entries(a.cfg.outputs).map(([,l])=>l).filter(l=>In(l)).map(l=>l);if(c.length===0)continue;const u=is(s.persist(),i);for(const l of c)n.push(j.Computable.wrapError(Ce(e,u,l,a.cfg.code,a.bpId)))}return n})}class Vn{constructor(){S(this,"states",new Map)}setState(e,t){const s=this.states.get(e);if(s===void 0){this.states.set(e,{state:t,change:new j.ChangeSource});return}s.state={...t},s.change.markChanged()}readState(e,t){let s=this.states.get(t);return s===void 0&&(s={state:{...D.DefaultNavigationState},change:new j.ChangeSource},this.states.set(t,s)),s.change.attachWatcher(e.watcher),s.state}getState(e){return j.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 pr(r){return JSON.stringify(r,(e,t)=>typeof t=="bigint"?f.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 Ze{constructor(e,t,s){S(this,"rid");S(this,"overview");S(this,"navigationStates",new Vn);S(this,"blockComputables",new Map);S(this,"blockFrontends",new Map);S(this,"activeConfigs");S(this,"refreshLoopResult");S(this,"abortController",new AbortController);S(this,"destroyed",!1);this.env=e,this.projectTree=s,this.overview=An(s.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=jn(s.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await Be(this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await Vr.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(f.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!f.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,s,o=void 0,n=ee.randomUUID()){const i=await this.env.bpPreparer.prepare(t),a=await this.env.bpPreparer.getBlockConfigContainer(t),c=D.extractConfig(a);return await re(this.env.pl,this.rid,o,u=>u.addBlock({id:n,label:e,renderingMode:c.renderingMode},{args:x(c.initialArgs),uiState:x(c.initialUiState),blockPack:i},s)),await this.projectTree.refreshState(),n}async updateBlockPack(e,t,s=!1,o){const n=await this.env.bpPreparer.prepare(t),i=D.extractConfig(await this.env.bpPreparer.getBlockConfigContainer(t));await re(this.env.pl,this.rid,o,a=>a.migrateBlockPack(e,n,s?{args:x(i.initialArgs),uiState:x(i.initialUiState)}:void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await re(this.env.pl,this.rid,t,s=>s.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await re(this.env.pl,this.rid,t,s=>{const o=s.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(a=>{const c=n.blocks.find(u=>u.id===a);if(c===void 0)throw new Error(`Can't find block: ${a}`);return c})}]};s.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await Be(this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await Be(this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,s){await re(this.env.pl,this.rid,s,o=>o.setArgs([{blockId:e,args:x(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,s){await re(this.env.pl,this.rid,s,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,s,o){await re(this.env.pl,this.rid,o,n=>{n.setArgs([{blockId:e,args:x(t)}]),n.setUiState(e,x(s))}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await re(this.env.pl,this.rid,void 0,s=>{s.setBlockSettings(e,t)}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async s=>{const o=f.ensureResourceIdNotNull((await s.getField(f.field(this.rid,J(e,"blockPack")))).value),n=f.ensureResourceIdNotNull((await s.getField(f.field(o,f.Pl.HolderRefField))).value),i=await s.getResourceData(n,!1),a=D.extractConfig(JSON.parse(Buffer.from(C.notEmpty(i.data)).toString("utf-8")).config);await re(s,this.rid,t,c=>{c.setArgs([{blockId:e,args:x(a.initialArgs)}]),c.setUiState(e,x(a.initialUiState))}),await s.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===void 0){const s=Bn(this.projectTree.entry(),e,this.env),n={fullState:j.Computable.make(i=>({argsAndUiState:ps(this.projectTree.entry(),e,i),outputs:s,navigationState:this.navigationStates.getState(e),overview:this.overview}),{postprocessValue:i=>{var l,d,h;const a=(h=(d=(l=i.overview)==null?void 0:l.blocks)==null?void 0:d.find(g=>g.id==e))==null?void 0:h.sdkVersion,u=a&&Un(a)&&i.outputs!==void 0?Mn(i.outputs):i.outputs;return{...i.argsAndUiState,outputs:u,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 s=Nn(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,s),s}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.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){await Be(e.pl,t,o=>{});const s=await _e.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:xn},e.logger);if(e.ops.debugOps.dumpInitialTreeState){const o=s.dumpState();o.sort((i,a)=>{var c,u;return(((c=a.data)==null?void 0:c.byteLength)??0)-(((u=i.data)==null?void 0:u.byteLength)??0)});const n=_e.treeDumpStats(o);await ht.writeFile(`${f.resourceIdToString(t)}.json`,pr(o)),await ht.writeFile(`${f.resourceIdToString(t)}.stats.json`,pr(n))}return new Ze(e,t,s)}}function xn(r){switch(r.type.name){case"BlockPackCustom":return r.fields.filter(e=>e.name!=="template");case"UserProject":return r.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return r.fields}}function Un(r){return!Gn(r,"1.26.0")}function Gn(r,e){const t=r.split(".").map(Number),s=e.split(".").map(Number);return t[0]>s[0]||t[0]===s[0]&&t[1]>s[1]||t[0]===s[0]&&t[1]===s[1]&&t[2]>s[2]}function Mn(r){const e={};for(const[t,s]of Object.entries(r)){if(s.ok){e[t]=s;continue}e[t]={ok:!1,errors:s.errors.map(o=>typeof o=="string"?o:o.type=="PlError"&&o.fullMessage!==void 0?o.fullMessage:o.message),moreErrors:s.moreErrors}}return e}const Dt={logger:new C.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 Lt(r){return{blobDownloadPath:K.join(r,"download"),downloadBlobToURLPath:K.join(r,"downloadToURL")}}const fs={...Dt,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500,initialTreeLoadingTimeout:100*60*60*1e3},debugOps:{dumpInitialTreeState:!1},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function hs(r){return{...Lt(r),frontendDownloadPath:K.join(r,"frontend")}}function Jn(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Pt={exports:{}};const _n="2.0.0",gs=256,Kn=Number.MAX_SAFE_INTEGER||9007199254740991,Hn=16,qn=gs-6,Wn=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var et={MAX_LENGTH:gs,MAX_SAFE_COMPONENT_LENGTH:Hn,MAX_SAFE_BUILD_LENGTH:qn,MAX_SAFE_INTEGER:Kn,RELEASE_TYPES:Wn,SEMVER_SPEC_VERSION:_n,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2};const zn=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};var tt=zn;(function(r,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:s,MAX_LENGTH:o}=et,n=tt;e=r.exports={};const i=e.re=[],a=e.safeRe=[],c=e.src=[],u=e.safeSrc=[],l=e.t={};let d=0;const h="[a-zA-Z0-9-]",g=[["\\s",1],["\\d",o],[h,s]],R=G=>{for(const[N,U]of g)G=G.split(`${N}*`).join(`${N}{0,${U}}`).split(`${N}+`).join(`${N}{1,${U}}`);return G},m=(G,N,U)=>{const F=R(N),_=d++;n(G,_,N),l[G]=_,c[_]=N,u[_]=F,i[_]=new RegExp(N,U?"g":void 0),a[_]=new RegExp(F,U?"g":void 0)};m("NUMERICIDENTIFIER","0|[1-9]\\d*"),m("NUMERICIDENTIFIERLOOSE","\\d+"),m("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`),m("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})`),m("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASEIDENTIFIER",`(?:${c[l.NUMERICIDENTIFIER]}|${c[l.NONNUMERICIDENTIFIER]})`),m("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NUMERICIDENTIFIERLOOSE]}|${c[l.NONNUMERICIDENTIFIER]})`),m("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`),m("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`),m("BUILDIDENTIFIER",`${h}+`),m("BUILD",`(?:\\+(${c[l.BUILDIDENTIFIER]}(?:\\.${c[l.BUILDIDENTIFIER]})*))`),m("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`),m("FULL",`^${c[l.FULLPLAIN]}$`),m("LOOSEPLAIN",`[v=\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`),m("LOOSE",`^${c[l.LOOSEPLAIN]}$`),m("GTLT","((?:<|>)?=?)"),m("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),m("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\*`),m("XRANGEPLAIN",`[v=\\s]*(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?)?)?`),m("XRANGEPLAINLOOSE",`[v=\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?)?)?`),m("XRANGE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAIN]}$`),m("XRANGELOOSE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAINLOOSE]}$`),m("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),m("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\d])`),m("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?(?:${c[l.BUILD]})?(?:$|[^\\d])`),m("COERCERTL",c[l.COERCE],!0),m("COERCERTLFULL",c[l.COERCEFULL],!0),m("LONETILDE","(?:~>?)"),m("TILDETRIM",`(\\s*)${c[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",m("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`),m("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`),m("LONECARET","(?:\\^)"),m("CARETTRIM",`(\\s*)${c[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",m("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`),m("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`),m("COMPARATORLOOSE",`^${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]})$|^$`),m("COMPARATOR",`^${c[l.GTLT]}\\s*(${c[l.FULLPLAIN]})$|^$`),m("COMPARATORTRIM",`(\\s*)${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",m("HYPHENRANGE",`^\\s*(${c[l.XRANGEPLAIN]})\\s+-\\s+(${c[l.XRANGEPLAIN]})\\s*$`),m("HYPHENRANGELOOSE",`^\\s*(${c[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[l.XRANGEPLAINLOOSE]})\\s*$`),m("STAR","(<|>)?=?\\s*\\*"),m("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),m("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(Pt,Pt.exports);var Fe=Pt.exports;const Xn=Object.freeze({loose:!0}),Yn=Object.freeze({}),Qn=r=>r?typeof r!="object"?Xn:r:Yn;var Nt=Qn;const fr=/^[0-9]+$/,ms=(r,e)=>{const t=fr.test(r),s=fr.test(e);return t&&s&&(r=+r,e=+e),r===e?0:t&&!s?-1:s&&!t?1:r<e?-1:1},Zn=(r,e)=>ms(e,r);var vs={compareIdentifiers:ms,rcompareIdentifiers:Zn};const Ve=tt,{MAX_LENGTH:hr,MAX_SAFE_INTEGER:xe}=et,{safeRe:gr,safeSrc:mr,t:Ue}=Fe,ei=Nt,{compareIdentifiers:he}=vs;let ti=class ae{constructor(e,t){if(t=ei(t),e instanceof ae){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>hr)throw new TypeError(`version is longer than ${hr} characters`);Ve("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const s=e.trim().match(t.loose?gr[Ue.LOOSE]:gr[Ue.FULL]);if(!s)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+s[1],this.minor=+s[2],this.patch=+s[3],this.major>xe||this.major<0)throw new TypeError("Invalid major version");if(this.minor>xe||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>xe||this.patch<0)throw new TypeError("Invalid patch version");s[4]?this.prerelease=s[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){const n=+o;if(n>=0&&n<xe)return n}return o}):this.prerelease=[],this.build=s[5]?s[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(Ve("SemVer.compare",this.version,this.options,e),!(e instanceof ae)){if(typeof e=="string"&&e===this.version)return 0;e=new ae(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof ae||(e=new ae(e,this.options)),he(this.major,e.major)||he(this.minor,e.minor)||he(this.patch,e.patch)}comparePre(e){if(e instanceof ae||(e=new ae(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 s=this.prerelease[t],o=e.prerelease[t];if(Ve("prerelease compare",t,s,o),s===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(s===void 0)return-1;if(s===o)continue;return he(s,o)}while(++t)}compareBuild(e){e instanceof ae||(e=new ae(e,this.options));let t=0;do{const s=this.build[t],o=e.build[t];if(Ve("build compare",t,s,o),s===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(s===void 0)return-1;if(s===o)continue;return he(s,o)}while(++t)}inc(e,t,s){if(e.startsWith("pre")){if(!t&&s===!1)throw new Error("invalid increment argument: identifier is empty");if(t){const o=new RegExp(`^${this.options.loose?mr[Ue.PRERELEASELOOSE]:mr[Ue.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,s);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,s);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,s),this.inc("pre",t,s);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,s),this.inc("pre",t,s);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(s)?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(".")&&s===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(t){let n=[t,o];s===!1&&(n=[t]),he(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 z=ti;const vr=z,ri=(r,e,t=!1)=>{if(r instanceof vr)return r;try{return new vr(r,e)}catch(s){if(!t)return null;throw s}};var ye=ri;const si=ye,oi=(r,e)=>{const t=si(r,e);return t?t.version:null};var ni=oi;const ii=ye,ai=(r,e)=>{const t=ii(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};var ci=ai;const yr=z,li=(r,e,t,s,o)=>{typeof t=="string"&&(o=s,s=t,t=void 0);try{return new yr(r instanceof yr?r.version:r,t).inc(e,s,o).version}catch{return null}};var ui=li;const wr=ye,di=(r,e)=>{const t=wr(r,null,!0),s=wr(e,null,!0),o=t.compare(s);if(o===0)return null;const n=o>0,i=n?t:s,a=n?s:t,c=!!i.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(i)===0)return a.minor&&!a.patch?"minor":"patch"}const l=c?"pre":"";return t.major!==s.major?l+"major":t.minor!==s.minor?l+"minor":t.patch!==s.patch?l+"patch":"prerelease"};var pi=di;const fi=z,hi=(r,e)=>new fi(r,e).major;var gi=hi;const mi=z,vi=(r,e)=>new mi(r,e).minor;var yi=vi;const wi=z,Si=(r,e)=>new wi(r,e).patch;var bi=Si;const Pi=ye,Ri=(r,e)=>{const t=Pi(r,e);return t&&t.prerelease.length?t.prerelease:null};var Ei=Ri;const Sr=z,Ci=(r,e,t)=>new Sr(r,t).compare(new Sr(e,t));var oe=Ci;const ki=oe,Oi=(r,e,t)=>ki(e,r,t);var $i=Oi;const Ti=oe,Ii=(r,e)=>Ti(r,e,!0);var Fi=Ii;const br=z,Ai=(r,e,t)=>{const s=new br(r,t),o=new br(e,t);return s.compare(o)||s.compareBuild(o)};var Bt=Ai;const Di=Bt,Li=(r,e)=>r.sort((t,s)=>Di(t,s,e));var Ni=Li;const Bi=Bt,ji=(r,e)=>r.sort((t,s)=>Bi(s,t,e));var Vi=ji;const xi=oe,Ui=(r,e,t)=>xi(r,e,t)>0;var rt=Ui;const Gi=oe,Mi=(r,e,t)=>Gi(r,e,t)<0;var jt=Mi;const Ji=oe,_i=(r,e,t)=>Ji(r,e,t)===0;var ys=_i;const Ki=oe,Hi=(r,e,t)=>Ki(r,e,t)!==0;var ws=Hi;const qi=oe,Wi=(r,e,t)=>qi(r,e,t)>=0;var Vt=Wi;const zi=oe,Xi=(r,e,t)=>zi(r,e,t)<=0;var xt=Xi;const Yi=ys,Qi=ws,Zi=rt,ea=Vt,ta=jt,ra=xt,sa=(r,e,t,s)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return Yi(r,t,s);case"!=":return Qi(r,t,s);case">":return Zi(r,t,s);case">=":return ea(r,t,s);case"<":return ta(r,t,s);case"<=":return ra(r,t,s);default:throw new TypeError(`Invalid operator: ${e}`)}};var Ss=sa;const oa=z,na=ye,{safeRe:Ge,t:Me}=Fe,ia=(r,e)=>{if(r instanceof oa)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?Ge[Me.COERCEFULL]:Ge[Me.COERCE]);else{const c=e.includePrerelease?Ge[Me.COERCERTLFULL]:Ge[Me.COERCERTL];let u;for(;(u=c.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||u.index+u[0].length!==t.index+t[0].length)&&(t=u),c.lastIndex=u.index+u[1].length+u[2].length;c.lastIndex=-1}if(t===null)return null;const s=t[2],o=t[3]||"0",n=t[4]||"0",i=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return na(`${s}.${o}.${n}${i}${a}`,e)};var aa=ia;class ca{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 la=ca,ct,Pr;function ne(){if(Pr)return ct;Pr=1;const r=/\s+/g;class e{constructor(p,v){if(v=o(v),p instanceof e)return p.loose===!!v.loose&&p.includePrerelease===!!v.includePrerelease?p:new e(p.raw,v);if(p instanceof n)return this.raw=p.value,this.set=[[p]],this.formatted=void 0,this;if(this.options=v,this.loose=!!v.loose,this.includePrerelease=!!v.includePrerelease,this.raw=p.trim().replace(r," "),this.set=this.raw.split("||").map(w=>this.parseRange(w.trim())).filter(w=>w.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const w=this.set[0];if(this.set=this.set.filter(P=>!m(P[0])),this.set.length===0)this.set=[w];else if(this.set.length>1){for(const P of this.set)if(P.length===1&&G(P[0])){this.set=[P];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let p=0;p<this.set.length;p++){p>0&&(this.formatted+="||");const v=this.set[p];for(let w=0;w<v.length;w++)w>0&&(this.formatted+=" "),this.formatted+=v[w].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(p){const w=((this.options.includePrerelease&&g)|(this.options.loose&&R))+":"+p,P=s.get(w);if(P)return P;const b=this.options.loose,E=b?c[u.HYPHENRANGELOOSE]:c[u.HYPHENRANGE];p=p.replace(E,V(this.options.includePrerelease)),i("hyphen replace",p),p=p.replace(c[u.COMPARATORTRIM],l),i("comparator trim",p),p=p.replace(c[u.TILDETRIM],d),i("tilde trim",p),p=p.replace(c[u.CARETTRIM],h),i("caret trim",p);let I=p.split(" ").map(A=>U(A,this.options)).join(" ").split(/\s+/).map(A=>Q(A,this.options));b&&(I=I.filter(A=>(i("loose invalid filter",A,this.options),!!A.match(c[u.COMPARATORLOOSE])))),i("range list",I);const O=new Map,L=I.map(A=>new n(A,this.options));for(const A of L){if(m(A))return[A];O.set(A.value,A)}O.size>1&&O.has("")&&O.delete("");const M=[...O.values()];return s.set(w,M),M}intersects(p,v){if(!(p instanceof e))throw new TypeError("a Range is required");return this.set.some(w=>N(w,v)&&p.set.some(P=>N(P,v)&&w.every(b=>P.every(E=>b.intersects(E,v)))))}test(p){if(!p)return!1;if(typeof p=="string")try{p=new a(p,this.options)}catch{return!1}for(let v=0;v<this.set.length;v++)if(H(this.set[v],p,this.options))return!0;return!1}}ct=e;const t=la,s=new t,o=Nt,n=st(),i=tt,a=z,{safeRe:c,t:u,comparatorTrimReplace:l,tildeTrimReplace:d,caretTrimReplace:h}=Fe,{FLAG_INCLUDE_PRERELEASE:g,FLAG_LOOSE:R}=et,m=y=>y.value==="<0.0.0-0",G=y=>y.value==="",N=(y,p)=>{let v=!0;const w=y.slice();let P=w.pop();for(;v&&w.length;)v=w.every(b=>P.intersects(b,p)),P=w.pop();return v},U=(y,p)=>(i("comp",y,p),y=B(y,p),i("caret",y),y=_(y,p),i("tildes",y),y=ue(y,p),i("xrange",y),y=ce(y,p),i("stars",y),y),F=y=>!y||y.toLowerCase()==="x"||y==="*",_=(y,p)=>y.trim().split(/\s+/).map(v=>fe(v,p)).join(" "),fe=(y,p)=>{const v=p.loose?c[u.TILDELOOSE]:c[u.TILDE];return y.replace(v,(w,P,b,E,I)=>{i("tilde",y,w,P,b,E,I);let O;return F(P)?O="":F(b)?O=`>=${P}.0.0 <${+P+1}.0.0-0`:F(E)?O=`>=${P}.${b}.0 <${P}.${+b+1}.0-0`:I?(i("replaceTilde pr",I),O=`>=${P}.${b}.${E}-${I} <${P}.${+b+1}.0-0`):O=`>=${P}.${b}.${E} <${P}.${+b+1}.0-0`,i("tilde return",O),O})},B=(y,p)=>y.trim().split(/\s+/).map(v=>ie(v,p)).join(" "),ie=(y,p)=>{i("caret",y,p);const v=p.loose?c[u.CARETLOOSE]:c[u.CARET],w=p.includePrerelease?"-0":"";return y.replace(v,(P,b,E,I,O)=>{i("caret",y,P,b,E,I,O);let L;return F(b)?L="":F(E)?L=`>=${b}.0.0${w} <${+b+1}.0.0-0`:F(I)?b==="0"?L=`>=${b}.${E}.0${w} <${b}.${+E+1}.0-0`:L=`>=${b}.${E}.0${w} <${+b+1}.0.0-0`:O?(i("replaceCaret pr",O),b==="0"?E==="0"?L=`>=${b}.${E}.${I}-${O} <${b}.${E}.${+I+1}-0`:L=`>=${b}.${E}.${I}-${O} <${b}.${+E+1}.0-0`:L=`>=${b}.${E}.${I}-${O} <${+b+1}.0.0-0`):(i("no pr"),b==="0"?E==="0"?L=`>=${b}.${E}.${I}${w} <${b}.${E}.${+I+1}-0`:L=`>=${b}.${E}.${I}${w} <${b}.${+E+1}.0-0`:L=`>=${b}.${E}.${I} <${+b+1}.0.0-0`),i("caret return",L),L})},ue=(y,p)=>(i("replaceXRanges",y,p),y.split(/\s+/).map(v=>X(v,p)).join(" ")),X=(y,p)=>{y=y.trim();const v=p.loose?c[u.XRANGELOOSE]:c[u.XRANGE];return y.replace(v,(w,P,b,E,I,O)=>{i("xRange",y,w,P,b,E,I,O);const L=F(b),M=L||F(E),A=M||F(I),le=A;return P==="="&&le&&(P=""),O=p.includePrerelease?"-0":"",L?P===">"||P==="<"?w="<0.0.0-0":w="*":P&&le?(M&&(E=0),I=0,P===">"?(P=">=",M?(b=+b+1,E=0,I=0):(E=+E+1,I=0)):P==="<="&&(P="<",M?b=+b+1:E=+E+1),P==="<"&&(O="-0"),w=`${P+b}.${E}.${I}${O}`):M?w=`>=${b}.0.0${O} <${+b+1}.0.0-0`:A&&(w=`>=${b}.${E}.0${O} <${b}.${+E+1}.0-0`),i("xRange return",w),w})},ce=(y,p)=>(i("replaceStars",y,p),y.trim().replace(c[u.STAR],"")),Q=(y,p)=>(i("replaceGTE0",y,p),y.trim().replace(c[p.includePrerelease?u.GTE0PRE:u.GTE0],"")),V=y=>(p,v,w,P,b,E,I,O,L,M,A,le)=>(F(w)?v="":F(P)?v=`>=${w}.0.0${y?"-0":""}`:F(b)?v=`>=${w}.${P}.0${y?"-0":""}`:E?v=`>=${v}`:v=`>=${v}${y?"-0":""}`,F(L)?O="":F(M)?O=`<${+L+1}.0.0-0`:F(A)?O=`<${L}.${+M+1}.0-0`:le?O=`<=${L}.${M}.${A}-${le}`:y?O=`<${L}.${M}.${+A+1}-0`:O=`<=${O}`,`${v} ${O}`.trim()),H=(y,p,v)=>{for(let w=0;w<y.length;w++)if(!y[w].test(p))return!1;if(p.prerelease.length&&!v.includePrerelease){for(let w=0;w<y.length;w++)if(i(y[w].semver),y[w].semver!==n.ANY&&y[w].semver.prerelease.length>0){const P=y[w].semver;if(P.major===p.major&&P.minor===p.minor&&P.patch===p.patch)return!0}return!1}return!0};return ct}var lt,Rr;function st(){if(Rr)return lt;Rr=1;const r=Symbol("SemVer ANY");class e{static get ANY(){return r}constructor(l,d){if(d=t(d),l instanceof e){if(l.loose===!!d.loose)return l;l=l.value}l=l.trim().split(/\s+/).join(" "),i("comparator",l,d),this.options=d,this.loose=!!d.loose,this.parse(l),this.semver===r?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(l){const d=this.options.loose?s[o.COMPARATORLOOSE]:s[o.COMPARATOR],h=l.match(d);if(!h)throw new TypeError(`Invalid comparator: ${l}`);this.operator=h[1]!==void 0?h[1]:"",this.operator==="="&&(this.operator=""),h[2]?this.semver=new a(h[2],this.options.loose):this.semver=r}toString(){return this.value}test(l){if(i("Comparator.test",l,this.options.loose),this.semver===r||l===r)return!0;if(typeof l=="string")try{l=new a(l,this.options)}catch{return!1}return n(l,this.operator,this.semver,this.options)}intersects(l,d){if(!(l instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(l.value,d).test(this.value):l.operator===""?l.value===""?!0:new c(this.value,d).test(l.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||l.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||l.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&l.operator.startsWith(">")||this.operator.startsWith("<")&&l.operator.startsWith("<")||this.semver.version===l.semver.version&&this.operator.includes("=")&&l.operator.includes("=")||n(this.semver,"<",l.semver,d)&&this.operator.startsWith(">")&&l.operator.startsWith("<")||n(this.semver,">",l.semver,d)&&this.operator.startsWith("<")&&l.operator.startsWith(">")))}}lt=e;const t=Nt,{safeRe:s,t:o}=Fe,n=Ss,i=tt,a=z,c=ne();return lt}const ua=ne(),da=(r,e,t)=>{try{e=new ua(e,t)}catch{return!1}return e.test(r)};var ot=da;const pa=ne(),fa=(r,e)=>new pa(r,e).set.map(t=>t.map(s=>s.value).join(" ").trim().split(" "));var ha=fa;const ga=z,ma=ne(),va=(r,e,t)=>{let s=null,o=null,n=null;try{n=new ma(e,t)}catch{return null}return r.forEach(i=>{n.test(i)&&(!s||o.compare(i)===-1)&&(s=i,o=new ga(s,t))}),s};var ya=va;const wa=z,Sa=ne(),ba=(r,e,t)=>{let s=null,o=null,n=null;try{n=new Sa(e,t)}catch{return null}return r.forEach(i=>{n.test(i)&&(!s||o.compare(i)===1)&&(s=i,o=new wa(s,t))}),s};var Pa=ba;const ut=z,Ra=ne(),Er=rt,Ea=(r,e)=>{r=new Ra(r,e);let t=new ut("0.0.0");if(r.test(t)||(t=new ut("0.0.0-0"),r.test(t)))return t;t=null;for(let s=0;s<r.set.length;++s){const o=r.set[s];let n=null;o.forEach(i=>{const a=new ut(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!n||Er(a,n))&&(n=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),n&&(!t||Er(t,n))&&(t=n)}return t&&r.test(t)?t:null};var Ca=Ea;const ka=ne(),Oa=(r,e)=>{try{return new ka(r,e).range||"*"}catch{return null}};var $a=Oa;const Ta=z,bs=st(),{ANY:Ia}=bs,Fa=ne(),Aa=ot,Cr=rt,kr=jt,Da=xt,La=Vt,Na=(r,e,t,s)=>{r=new Ta(r,s),e=new Fa(e,s);let o,n,i,a,c;switch(t){case">":o=Cr,n=Da,i=kr,a=">",c=">=";break;case"<":o=kr,n=La,i=Cr,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Aa(r,e,s))return!1;for(let u=0;u<e.set.length;++u){const l=e.set[u];let d=null,h=null;if(l.forEach(g=>{g.semver===Ia&&(g=new bs(">=0.0.0")),d=d||g,h=h||g,o(g.semver,d.semver,s)?d=g:i(g.semver,h.semver,s)&&(h=g)}),d.operator===a||d.operator===c||(!h.operator||h.operator===a)&&n(r,h.semver))return!1;if(h.operator===c&&i(r,h.semver))return!1}return!0};var Ut=Na;const Ba=Ut,ja=(r,e,t)=>Ba(r,e,">",t);var Va=ja;const xa=Ut,Ua=(r,e,t)=>xa(r,e,"<",t);var Ga=Ua;const Or=ne(),Ma=(r,e,t)=>(r=new Or(r,t),e=new Or(e,t),r.intersects(e,t));var Ja=Ma;const _a=ot,Ka=oe;var Ha=(r,e,t)=>{const s=[];let o=null,n=null;const i=r.sort((l,d)=>Ka(l,d,t));for(const l of i)_a(l,e,t)?(n=l,o||(o=l)):(n&&s.push([o,n]),n=null,o=null);o&&s.push([o,null]);const a=[];for(const[l,d]of s)l===d?a.push(l):!d&&l===i[0]?a.push("*"):d?l===i[0]?a.push(`<=${d}`):a.push(`${l} - ${d}`):a.push(`>=${l}`);const c=a.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return c.length<u.length?c:e};const $r=ne(),Gt=st(),{ANY:dt}=Gt,Se=ot,Mt=oe,qa=(r,e,t={})=>{if(r===e)return!0;r=new $r(r,t),e=new $r(e,t);let s=!1;e:for(const o of r.set){for(const n of e.set){const i=za(o,n,t);if(s=s||i!==null,i)continue e}if(s)return!1}return!0},Wa=[new Gt(">=0.0.0-0")],Tr=[new Gt(">=0.0.0")],za=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===dt){if(e.length===1&&e[0].semver===dt)return!0;t.includePrerelease?r=Wa:r=Tr}if(e.length===1&&e[0].semver===dt){if(t.includePrerelease)return!0;e=Tr}const s=new Set;let o,n;for(const g of r)g.operator===">"||g.operator===">="?o=Ir(o,g,t):g.operator==="<"||g.operator==="<="?n=Fr(n,g,t):s.add(g.semver);if(s.size>1)return null;let i;if(o&&n){if(i=Mt(o.semver,n.semver,t),i>0)return null;if(i===0&&(o.operator!==">="||n.operator!=="<="))return null}for(const g of s){if(o&&!Se(g,String(o),t)||n&&!Se(g,String(n),t))return null;for(const R of e)if(!Se(g,String(R),t))return!1;return!0}let a,c,u,l,d=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1,h=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 g of e){if(l=l||g.operator===">"||g.operator===">=",u=u||g.operator==="<"||g.operator==="<=",o){if(h&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===h.major&&g.semver.minor===h.minor&&g.semver.patch===h.patch&&(h=!1),g.operator===">"||g.operator===">="){if(a=Ir(o,g,t),a===g&&a!==o)return!1}else if(o.operator===">="&&!Se(o.semver,String(g),t))return!1}if(n){if(d&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===d.major&&g.semver.minor===d.minor&&g.semver.patch===d.patch&&(d=!1),g.operator==="<"||g.operator==="<="){if(c=Fr(n,g,t),c===g&&c!==n)return!1}else if(n.operator==="<="&&!Se(n.semver,String(g),t))return!1}if(!g.operator&&(n||o)&&i!==0)return!1}return!(o&&u&&!n&&i!==0||n&&l&&!o&&i!==0||h||d)},Ir=(r,e,t)=>{if(!r)return e;const s=Mt(r.semver,e.semver,t);return s>0?r:s<0||e.operator===">"&&r.operator===">="?e:r},Fr=(r,e,t)=>{if(!r)return e;const s=Mt(r.semver,e.semver,t);return s<0?r:s>0||e.operator==="<"&&r.operator==="<="?e:r};var Xa=qa;const pt=Fe,Ar=et,Ya=z,Dr=vs,Qa=ye,Za=ni,ec=ci,tc=ui,rc=pi,sc=gi,oc=yi,nc=bi,ic=Ei,ac=oe,cc=$i,lc=Fi,uc=Bt,dc=Ni,pc=Vi,fc=rt,hc=jt,gc=ys,mc=ws,vc=Vt,yc=xt,wc=Ss,Sc=aa,bc=st(),Pc=ne(),Rc=ot,Ec=ha,Cc=ya,kc=Pa,Oc=Ca,$c=$a,Tc=Ut,Ic=Va,Fc=Ga,Ac=Ja,Dc=Ha,Lc=Xa;var Nc={parse:Qa,valid:Za,clean:ec,inc:tc,diff:rc,major:sc,minor:oc,patch:nc,prerelease:ic,compare:ac,rcompare:cc,compareLoose:lc,compareBuild:uc,sort:dc,rsort:pc,gt:fc,lt:hc,eq:gc,neq:mc,gte:vc,lte:yc,cmp:wc,coerce:Sc,Comparator:bc,Range:Pc,satisfies:Rc,toComparators:Ec,maxSatisfying:Cc,minSatisfying:kc,minVersion:Oc,validRange:$c,outside:Tc,gtr:Ic,ltr:Fc,intersects:Ac,simplifyRange:Dc,subset:Lc,SemVer:Ya,re:pt.re,src:pt.src,tokens:pt.t,SEMVER_SPEC_VERSION:Ar.SEMVER_SPEC_VERSION,RELEASE_TYPES:Ar.RELEASE_TYPES,compareIdentifiers:Dr.compareIdentifiers,rcompareIdentifiers:Dr.rcompareIdentifiers};const Bc=Jn(Nc),jc={minDelay:1500},Vc="__no_updates__";class xc extends j.PollComputablePool{constructor(t,s,o={}){super({...o,...jc},s);S(this,"http");S(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 Vc}}async readValue(t){var s,o;try{const n=t.currentSpec;switch(n.type){case"dev-v1":try{const i=await kt(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 W.tryLoadPackDescription(n.folder,this.logger);if(i===void 0)return{suggestions:[]};const a=await ze(i);return a===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:a},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:i,skipVersion:a}=t.settings;if(i==="patch")return{suggestions:[]};const c=this.registryProvider.getRegistry(n.registryUrl);let u=this.preferredUpdateChannel;if(u===void 0)if(n.channel===void 0)if(await c.getLatestOverview(n.id,q.StableChannel))u=q.StableChannel;else{if(await c.getLatestOverview(n.id,q.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${q.blockPackIdToString(n.id)}`),{suggestions:[]};u=q.AnyChannel}else u=n.channel;const l=await c.getUpdateSuggestions(n.id,u);if(l===void 0||l.length===0)return{suggestions:[]};l.reverse();let d;switch(i){case void 0:d=l[0].update;break;case"major":d=(s=l.find(R=>R.type!=="major"))==null?void 0:s.update;break;case"minor":d=(o=l.find(R=>R.type==="patch"))==null?void 0:o.update;break}const h=l.map(({type:R,update:m})=>({type:R,update:{...n,id:{...n.id,version:m}}}));if(d===void 0)return{suggestions:h};if(a!==void 0&&Bc.lte(d,a))return{suggestions:h};const g={...n,id:{...n.id,version:d}};return(async()=>{try{await c.getComponents(g.id)}catch(R){this.logger.warn(R)}})(),{suggestions:h,mainSuggestion:g}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(n){return this.logger.warn(n),{suggestions:[]}}}resultsEqual(t,s){return x(t)===x(s)}}class Lr{constructor(){S(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 s=this.resources.get(t);s===void 0&&(s={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,s)),s.refCount++;let o=!1;return{resource:s.resource,key:t,unref:()=>{o||(s.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 be;function de(){return be||(be={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0,dumpInitialTreeState:process.env.MI_DUMP_INITIAL_TREE_STATE!==void 0},process.env.MI_LOG_TREE_STAT&&(be.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),be)}function ke(r){return String(r.id)}const Uc=["Int","Long","Float","Double","String","Bytes"];function ft(r){const e=[],t=[];for(const s of r)s.type==="bySingleColumn"?(e.push(s),t.push({...s,type:"bySingleColumnV2"})):t.push(s);if(e.length>0){const s=JSON.stringify(e);console.warn(`type overriten from 'bySingleColumn' to 'bySingleColumnV2' for filters: ${s}`)}return t}const Pe=(r,e)=>typeof e=="bigint"?e.toString():e;class Gc{constructor(e,t,s,o){S(this,"rustPFrame");S(this,"blobIdToResource",new Map);S(this,"blobHandleComputables",new Map);S(this,"preloadBlob",async e=>{const t=e.map(s=>this.getOrCreateComputableForBlob(s));for(const s of t)await s.awaitStableFullValue()});S(this,"resolveBlob",async e=>{const t=this.getOrCreateComputableForBlob(e);return this.blobDriver.getLocalPath((await t.awaitStableValue()).handle)});S(this,"resolveBlobContent",async e=>{try{const t=this.getOrCreateComputableForBlob(e),s=this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);return await this.blobContentCache.forceFetch(s)}catch(t){const s=JSON.stringify(t);throw console.log(`resolveBlobContent catched error: ${s}`),t}});this.blobDriver=e,this.logger=t,this.blobContentCache=s;const n=(a,c)=>{switch(a){default:case"info":return this.logger.info(c);case"warn":return this.logger.warn(c);case"error":return this.logger.error(c)}};for(const a of o)for(const c of Lo(a.data))this.blobIdToResource.set(ke(c),c);const i=[...new Map(o.map(a=>({...a,data:No(a.data,ke)})).map(a=>[x(a),a])).values()];try{const a=new Ds.PFrame(de().logPFrameRequests?n:void 0);a.setDataSource(this);for(const c of i)a.addColumnSpec(c.id,c.spec),a.setColumnData(c.id,c.data);this.rustPFrame=a}catch(a){throw new Error(`Rust PFrame creation failed, columns: ${JSON.stringify(i)}, error: ${a}`)}}getOrCreateComputableForBlob(e){let t=this.blobHandleComputables.get(e);if(t!==void 0)return t;const s=this.blobIdToResource.get(e);if(s===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(s).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}[Symbol.dispose](){for(const e of this.blobHandleComputables.values())e.resetState();this.rustPFrame.dispose()}}class Mc{constructor(e){this.table=e}[Symbol.dispose](){this.table.then(e=>e.dispose())}}class Jc{constructor(e,t){S(this,"pFrames");S(this,"pTables");S(this,"blobContentCache");this.blobDriver=e,this.logger=t;const s=new Br.LRUCache({maxSize:1e9,fetchMethod:async o=>await Ur.readFile(o),sizeCalculation:o=>o.length});this.blobContentCache=s,this.pFrames=new class extends Lr{constructor(o,n){super(),this.blobDriver=o,this.logger=n}createNewResource(o){return de().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,Pe)}`),new Gc(this.blobDriver,this.logger,s,o)}calculateParamsKey(o){return Kc(o)}}(this.blobDriver,this.logger),this.pTables=new class extends Lr{constructor(o){super(),this.pFrames=o}createNewResource(o){const n=o.pFrameHandle;de().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,Pe)}`);const i=this.pFrames.getByKey(n).rustPFrame.createTable({src:Oe(o.def.src),filters:ft(o.def.filters)},o.signal).then(async a=>{if(o.def.sorting.length===0)return a;try{return await a.sort(o.def.sorting,o.signal)}finally{a.dispose()}});return new Mc(i)}calculateParamsKey(o){return _c(o)}}(this.pFrames)}createPFrame(e,t){const s=e.filter(n=>Uc.find(i=>i===n.spec.valueType)).map(n=>D.mapPObjectData(n,i=>_e.isPlTreeNodeAccessor(i)?Go(i):D.isDataInfo(i)?D.mapDataInfo(i,a=>a.resourceInfo):Mo(n.spec,i))),o=this.pFrames.acquire(s);return t.addOnDestroy(o.unref),o.key}createPTable(e,t,s){const o=this.createPFrame(D.extractAllColumns(e.src),t),n=D.mapPTableDef(e,a=>a.id),i=this.pTables.acquire({def:n,pFrameHandle:o,signal:s});return de().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${o}; pTableHandle = ${JSON.stringify(i)}): ${JSON.stringify(D.mapPTableDef(e,a=>a.spec),Pe)}`),t.addOnDestroy(i.unref),i.key}async findColumns(e,t){const s={...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).rustPFrame.findColumns(s)).hits.filter(n=>n.mappingVariants.length===0||n.mappingVariants.some(i=>i.qualifications.forHit.length===0&&i.qualifications.forQueries.every(a=>a.length===0))).map(n=>n.hit)}}async getColumnSpec(e,t){return await this.pFrames.getByKey(e).rustPFrame.getColumnSpec(t)}async listColumns(e){return await this.pFrames.getByKey(e).rustPFrame.listColumns()}async calculateTableData(e,t,s){return de().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,Pe)}`),await this.pFrames.getByKey(e).rustPFrame.createTable({src:Oe(t.src),filters:ft(t.filters)},s).then(async o=>{if(t.sorting.length===0)return o;try{return await o.sort(t.sorting,s)}finally{o.dispose()}}).then(async o=>{try{const n=o.getSpec(),i=await o.getData([...n.keys()]);return n.map((a,c)=>({spec:a,data:i[c]}))}finally{o.dispose()}})}async getUniqueValues(e,t,s){return de().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,Pe)}`),await this.pFrames.getByKey(e).rustPFrame.getUniqueValues({...t,filters:ft(t.filters)},s)}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,s){return await(await this.pTables.getByKey(e).table).getData(t,s)}}function Oe(r){switch(r.type){case"column":return{type:"column",columnId:r.column};case"slicedColumn":return{type:"slicedColumn",columnId:r.column,newId:r.newId,axisFilters:r.axisFilters};case"inner":case"full":return{type:r.type,entries:r.entries.map(e=>Oe(e))};case"outer":return{type:"outer",primary:Oe(r.primary),secondary:r.secondary.map(e=>Oe(e))};default:C.assertNever(r)}}function _c(r){const e=ee.createHash("sha256");return e.update(x(r)),e.digest().toString("hex")}function Kc(r){const e=[...r].map(s=>D.mapPObjectData(s,o=>{let n;const i=o.type;switch(i){case"Json":n={type:o.type,keyLength:o.keyLength,payload:Object.entries(o.data).map(([a,c])=>({key:a,value:c}))};break;case"JsonPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([a,c])=>({key:a,value:ke(c)}))};break;case"BinaryPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([a,c])=>({key:a,value:[ke(c.index),ke(c.values)]}))};break;default:throw Error(`unsupported resource type: ${JSON.stringify(i)}`)}return n.payload.sort((a,c)=>a.key.localeCompare(c.key)),n}));e.sort((s,o)=>s.id.localeCompare(o.id));const t=ee.createHash("sha256");return t.update(x(e)),t.digest().toString("hex")}async function Ps(r,e,t){const s={...Dt,...Lt(e),...t},o=new C.HmacSha256Signer(s.localSecret),n=te.createDownloadClient(s.logger,r,s.localProjections),i=te.createLogsClient(r,s.logger),a=te.createUploadBlobClient(r,s.logger),c=te.createUploadProgressClient(r,s.logger),u=new te.DownloadDriver(s.logger,n,i,s.blobDownloadPath,o,s.blobDriverOps),l=new te.DownloadBlobToURLDriver(s.logger,o,n,s.downloadBlobToURLPath,s.downloadBlobToURLDriverOps),d=new te.UploadDriver(s.logger,o,a,c,s.uploadDriverOps),h=new te.LogsStreamDriver(s.logger,i,s.logStreamDriverOps),g=new te.LogsDriver(s.logger,h,u),R=await te.LsDriver.init(s.logger,r,o,s.localProjections,s.openFileDialogCallback,s.virtualLocalStoragesOverride),m=new Jc(u,s.logger);return{blobDriver:u,blobToURLDriver:l,logDriver:g,lsDriver:R,signer:o,uploadDriver:d,pFrameDriver:m}}class Jt{constructor(e,t,s,o,n,i,a,c){S(this,"pl");S(this,"projectList");S(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=s,this.projectListResourceId=o,this.openedProjectsList=n,this.projectListTree=i,this.blockRegistryProvider=a,this.projectList=c,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=ee.randomUUID()){const s=await this.pl.withWriteTx("MLCreateProject",async o=>{const n=await Do(o,e);return o.createField(f.field(this.projectListResourceId,t),"Dynamic",n),await o.commit(),await f.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),s}async setProjectMeta(e,t,s){await re(this.pl,e,s,o=>{o.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(f.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 s=(await t.getField(f.field(this.projectListResourceId,e))).value;if(f.isNullResourceId(s))throw new Error("Unexpected project list structure.");return s})}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 Ze.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 C.HmacSha256Signer.generateSecret()}static async init(e,t,s){const o={...fs,...hs(t),...s};o.defaultTreeOptions.logStat=de().logTreeStats,o.debugOps.dumpInitialTreeState=de().dumpInitialTreeState;const n=await e.withWriteTx("MLInitialization",async m=>{const G=f.field(m.clientRoot,so);m.createField(G,"Dynamic");const N=await m.getField(G);if(f.isNullResourceId(N.value)){const U=m.createEphemeral(Kr);return m.lock(U),m.setField(G,U),await m.commit(),await U.globalId}else return N.value}),i=o.logger,a=await Ps(e,t,o),c=new We.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),u=new Mr(c),l=new ko(u,a.signer,c),d=new te.DownloadUrlDriver(i,e.httpDispatcher,o.frontendDownloadPath),h={pl:e,signer:a.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:c,ops:o,bpPreparer:l,frontendDownloadDriver:d,driverKit:a,blockUpdateWatcher:new xc(u,i,{minDelay:o.devBlockUpdateRecheckInterval,http:c,preferredUpdateChannel:o.preferredUpdateChannel}),quickJs:await $e.getQuickJS()},g=new j.WatchableValue([]),R=await no(e,n,g,h);return new Jt(h,a,a.signer,n,g,R.tree,u,R.computable)}}const Hc=["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"];async function qc(r,e={}){const t={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,...e},s=[];Hc.forEach(c=>{Ls.channel(c).subscribe(l=>{var h;const d=new Date().toISOString();(h=l==null?void 0:l.response)!=null&&h.headers&&(l.response.headers=l.response.headers.map(g=>g.toString())),s.push(JSON.stringify({timestamp:d,event:c,data:l}))})});const o={plPings:[],blockRegistryOverviewChecks:[],blockGARegistryOverviewChecks:[],blockRegistryUiChecks:[],blockGARegistryUiChecks:[],autoUpdateCdnChecks:[]},n=f.plAddressToConfig(r,{defaultRequestTimeout:t.pingTimeoutMs});o.plPings=await ge(t.pingCheckDurationMs,t.maxPingsPerSecond,async()=>{const u=await new f.UnauthenticatedPlClient(n).ping();return JSON.stringify(u).slice(0,t.bodyLimit)+"..."});const a=new f.UnauthenticatedPlClient(n).ll.httpDispatcher;return o.blockRegistryOverviewChecks=await ge(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Re(new URL(t.blockOverviewPath,t.blockRegistryUrl),t,a)),o.blockGARegistryOverviewChecks=await ge(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Re(new URL(t.blockOverviewPath,t.blockGARegistryUrl),t,a)),o.blockRegistryUiChecks=await ge(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Re(new URL(t.blockUiPath,t.blockRegistryUrl),t,a)),o.blockGARegistryUiChecks=await ge(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Re(new URL(t.blockUiPath,t.blockGARegistryUrl),t,a)),o.autoUpdateCdnChecks=await ge(t.autoUpdateCdnDurationMs,t.maxAutoUpdateCdnChecksPerSecond,async()=>await Re(t.autoUpdateCdnUrl,t,a)),Wc(o,r,t,s)}async function ge(r,e,t){const s=Rt(),o=[];for(;Nr(s)<r;){const n=Rt();let i;try{i={ok:!0,value:await t()}}catch(u){i={ok:!1,error:u}}const a=Nr(n);o.push({elapsedMs:a,response:i});const c=1e3/e-a;c>0&&await Vr.setTimeout(c)}return o}async function Re(r,e,t){const{body:s,statusCode:o}=await We.request(r,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),n=await s.text();return{statusCode:o,beginningOfBody:n.slice(0,e.bodyLimit)+"..."}}function Wc(r,e,t,s){const o=r.plPings.filter(a=>a.response.ok),n=r.plPings.filter(a=>!a.response.ok),i=[...new Set(o.map(a=>JSON.stringify(a.response.value)))];return`
2
2
  Network report:
3
3
  pl endpoint: ${e};
4
4
  options: ${JSON.stringify(t,null,2)}.