@milaboratories/pl-middle-layer 1.37.2 → 1.37.4

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 qt=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),Wt=s=>{throw TypeError(s)};var ks=(s,e,t)=>e in s?Cs(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var S=(s,e,t)=>ks(s,typeof e!="symbol"?e+"":e,t);var zt=(s,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Wt("Object expected");var r;t&&(r=e[qt("asyncDispose")]),r===void 0&&(r=e[qt("dispose")]),typeof r!="function"&&Wt("Object not disposable"),s.push([t,r,e])}else t&&s.push([t]);return e},Xt=(s,e,t)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,c,a,l){return l=Error(a),l.name="SuppressedError",l.error=i,l.suppressed=c,l},n=i=>e=t?new r(i,e,"An error was suppressed during disposal"):(t=!0,i),o=i=>{for(;i=s.pop();)try{var c=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(c).then(o,a=>(n(a),o()))}catch(a){n(a)}if(t)throw e};return o()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const F=require("@platforma-sdk/model"),W=require("@milaboratories/pl-model-middle-layer"),Yt=require("@milaboratories/pl-deployments"),ze=require("undici"),z=require("@platforma-sdk/block-tools"),Z=require("node:fs"),J=require("node:path"),Os=require("yaml"),E=require("@milaboratories/ts-helpers"),ht=require("node:fs/promises"),Ts=require("@milaboratories/resolve-helper"),h=require("@milaboratories/pl-client"),He=require("@milaboratories/pl-tree"),V=require("@milaboratories/computable"),ee=require("node:crypto"),O=require("@milaboratories/pl-model-backend"),Et=require("lru-cache"),$s=require("node:worker_threads"),xr=require("denque"),Is=require("@platforma-sdk/workflow-tengo"),x=require("canonicalize"),Fs=require("node:assert"),pe=require("quickjs-emscripten"),As=require("@milaboratories/pl-errors"),Ls=require("remeda"),Ur=require("node:timers/promises"),ne=require("@milaboratories/pl-drivers"),Ds=require("@milaboratories/pframes-rs-node"),Ns=require("node:diagnostics_channel");function Ct(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const Bs=Ct(J),Gr=Ct(ht),Qt=Ct(Ls);async function Zt(s){try{return await Gr.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const js=[z.RegistryV1.PlPackageYamlConfigFile],Vs=[z.RegistryV1.PlPackageJsonConfigFile],kt=["backend","dist","tengo","tpl","main.plj.gz"],Ot=["config","dist","config.json"],Mr=["frontend","dist"],er="block-model/dist/config.json",xs="block-ui/package.json",Us=[kt,Ot,js,Vs,Mr];async function Gs(s){return await Zt(J.join(s,...Ot))!==void 0||await Zt(J.join(s,...kt))!==void 0}function ot(s,e){const t=Ts.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function tr(s,e){if(J.isAbsolute(s)||(s=J.resolve(s)),await Gs(s))return{workflow:J.join(s,...kt),config:J.join(s,...Ot),ui:J.join(s,...Mr)};{const t=ot(s,er),r=ot(s,er),n=ot(s,xs);return{workflow:t,config:r,ui:J.resolve(n,"..","dist")}}}async function Ms(s){try{return await Z.promises.readFile(s,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Js(s){try{return await Z.promises.stat(s,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Tt(s){let e=0n;for(const t of Us){const r=J.join(s,...t),n=await Js(r);n!==void 0&&e<n.mtimeNs&&(e=n.mtimeNs)}return e.toString()}async function Xe(s){const e=await Z.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await Z.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class _s{constructor(e,t,r){this.v2Provider=e,this.registries=t,this.http=r}async getPackagesForRoot(e){const t=[],r=e.spec;switch(r.type){case"remote-v1":{const n=this.http!==void 0?{dispatcher:this.http}:{},i=await(await ze.request(`${r.url}/${z.RegistryV1.GlobalOverviewPath}`,n)).body.json();for(const c of i){const{organization:a,package:l,latestMeta:u,latestVersion:d}=c,p={organization:a,name:l,version:d},f={id:p,meta:{title:u.title??"No title",description:u.description??"No Description",organization:{name:a,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:p,registryUrl:r.url}};t.push({registryId:e.id,id:p,latestByChannel:{[W.AnyChannel]:f,[W.StableChannel]:f},allVersions:c.allVersions.map(C=>({version:C,channels:[]}))})}return t}case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(n=>({...n,registryId:e.id}));case"local-dev":for(const n of await Z.promises.readdir(r.path,{withFileTypes:!0})){if(!n.isDirectory())continue;const o=J.join(r.path,n.name),i=await Ms(J.join(o,z.RegistryV1.PlPackageYamlConfigFile));if(i!==void 0){const c=z.RegistryV1.PlPackageConfigData.parse(Os.parse(i)),a=await Tt(o),l={organization:c.organization,name:c.package,version:"DEV"},u={id:l,meta:{title:c.meta.title??"No title",description:c.meta.description??"No Description",organization:{name:c.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:o,mtime:a}};t.push({registryId:e.id,id:l,latestByChannel:{[W.AnyChannel]:u,[W.StableChannel]:u},allVersions:[]})}else{let c=o,a=await z.tryLoadPackDescription(c);if(a===void 0){for(const l of["block","meta"])if(c=J.join(o,l),a=await z.tryLoadPackDescription(c),a!==void 0)break}if(a!==void 0){const l=await Xe(a),u={id:a.id,meta:await z.BlockPackMetaEmbedAbsoluteBytes.parseAsync(a.meta),spec:{type:"dev-v2",folder:c,mtime:l}};t.push({registryId:e.id,id:a.id,latestByChannel:{[W.AnyChannel]:u,[W.StableChannel]:u},allVersions:[]})}}}return t;default:return E.assertNever(r)}}async listBlockPacks(){const e=[],t=[];for(const r of this.registries)t.push({...r,status:"online"}),e.push(...await this.getPackagesForRoot(r));return{registries:t,blockPacks:e}}async getOverview(e,t,r){var i;const n=(i=this.registries.find(c=>c.id===e))==null?void 0:i.spec;if(!n)throw new Error(`Registry with id "${e}" not found`);if(n.type!=="remote-v2")throw new Error('Only "remote-v2" registries support specific package version overview retrieval.');return await this.v2Provider.getRegistry(n.url).getSpecificOverview(t,r)}}class Jr{constructor(e){S(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new z.RegistryV2Reader(z.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const Ks={type:"remote-v2",url:"https://blocks.pl-open.science/"},Hs={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},qs={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},Ws={groups:[{id:"default",label:"Default",blocks:[]}]},zs={stagingRefreshTimestamp:0,blocksInLimbo:[]},Xs={label:"New Project"},Ys={name:"UserProject",version:"2"},_r="SchemaVersion",Kr="1",$t="ProjectCreated",$e="ProjectLastModified",Ie="ProjectMeta",fe="ProjectStructure",qe="BlockRenderingState",Qs="BlockFrontendState/",Zs=/^BlockFrontendState\/(?<blockid>.*)$/;function gt(s){return`${Qs}${s}`}const en="BlockArgsAuthor/";function mt(s){return`${en}${s}`}const vt="ProjectStructureAuthor";function tn(s){const e=s.match(Zs);if(e!==null)return e.groups.blockid}const rn="__serviceTemplate_";function yt(s){return`${rn}${s}`}function _(s,e){return`${s}-${e}`}const sn=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function nn(s){const e=s.match(sn);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const on="projects",Hr={name:"Projects",version:"1"},an=s=>h.resourceTypesEqual(s.type,Hr)?s.fields:[];async function cn(s,e,t,r){const n=await He.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:an},r.logger);return{computable:V.Computable.make(i=>{const c=i.accessor(n.entry()).node(),a=t.getValue(i);if(c===void 0)return;const l=[];for(const u of c.listDynamicFields()){const d=c.traverse(u);if(d===void 0)continue;const p=E.notEmpty(d.getKeyValueAsJson(Ie)),f=E.notEmpty(d.getKeyValueAsJson($t)),C=E.notEmpty(d.getKeyValueAsJson($e));l.push({id:u,rid:d.id,created:new Date(f),lastModified:new Date(C),opened:a.indexOf(d.id)>=0,meta:p})}return l.sort(u=>-u.lastModified.valueOf()),l}).withStableType(),tree:n}}const ln={name:"EphRenderTemplate",version:"1"},un={name:"RenderTemplate",version:"1"};function It(s,e,t,r,n){if(n.length===0)throw new Error("Zero output names provided");const o=t?s.createEphemeral(ln):s.createStruct(un),i=h.field(o,"template"),c=h.field(o,"inputs");return s.createField(i,"Input",e),s.createField(c,"Input",h.Pl.createPlMap(s,r,t)),s.lockInputs(o),h.Pl.futureRecord(s,o,n,"Output","outputs/")}const dn={name:"BContextEnd",version:"1"},pn={name:"BContext",version:"1"},fn="id",hn="parent/",gn=["context","result"];function rr(s,e,t){return It(s,e,!0,t,gn)}function mn(s){const e=s.createEphemeral(dn);return s.lock(e),e}function sr(s,e){if(e.length===0)return mn(s);if(e.length===1)return e[0];const t=s.createEphemeral(pn);s.createField(h.field(t,fn),"Input",h.Pl.createPlString(s,ee.randomUUID()));for(let r=0;r<e.length;r++)s.createField(h.field(t,`${hn}${r}`),"Input",e[r]);return s.lock(t),t}function qr(s,e){const t=new Map,r=(n,o,i)=>{const c=ee.createHash("sha256");o.updateCacheKey(n,c,i);const a=c.digest("hex");if(!t.has(a)){const l=o.render(n,s,r,i);t.set(a,l)}return t.get(a)};return r(e.template,Wr,e.hashToSource)}const nr={updateCacheKey(s,e,t){e.update(O.PlTemplateLibV1.type.name).update(O.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(ye(s.name,t,s.sourceHash))},render(s,e,t,r){return e.createValue(O.PlTemplateLibV1.type,JSON.stringify(O.PlTemplateLibV1.fromV3Data(s,ye(s.name,r,s.sourceHash)).data))}},De={updateCacheKey(s,e,t){e.update(O.PlTemplateSoftwareV1.type.name).update(O.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(ye(s.name,t,s.sourceHash))},render(s,e,t,r){const n=O.PlTemplateSoftwareV1.fromV3Data(s,ye(s.name,r,s.sourceHash)),o=e.createStruct(O.PlTemplateSoftwareV1.type,n.data);return e.setKValue(o,O.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(n.name)),e.lock(o),o}},Wr={updateCacheKey(s,e,t){e.update(O.PlTemplateV1.type.name).update(O.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(ye(s.name,t,s.sourceHash));const r=n=>(n.sort((o,i)=>o[0]===i[0]?0:o[0]<i[0]?-1:1),n);for(const[n,o]of r(Object.entries(s.libs??{})))e.update("lib:"+n),nr.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.software??{})))e.update("soft:"+n),De.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.assets??{})))e.update("asset:"+n),De.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.templates??{})))e.update("tpl:"+n),this.updateCacheKey(o,e,t)},render(s,e,t,r){const n=e.createStruct(O.PlTemplateV1.type,JSON.stringify(O.PlTemplateV1.fromV3Data(s,ye(s.name,r,s.sourceHash)).data));for(const[c,a]of Object.entries(s.libs??{})){const l=O.PlTemplateV1.libField(n,c);e.createField(l,"Input"),e.setField(l,t(a,nr,r))}for(const[c,a]of Object.entries(s.software??{})){const l=O.PlTemplateV1.swField(n,c);e.createField(l,"Input"),e.setField(l,t(a,De,r))}for(const[c,a]of Object.entries(s.assets??{})){const l=O.PlTemplateV1.swField(n,c);e.createField(l,"Input"),e.setField(l,t(a,De,r))}for(const[c,a]of Object.entries(s.templates??{})){const l=O.PlTemplateV1.tplField(n,c);e.createField(l,"Input"),e.setField(l,t(a,Wr,r))}if(e.lock(n),!s.hashOverride)return n;const o=e.createStruct(O.PlTemplateOverrideV1.type,JSON.stringify(O.PlTemplateOverrideV1.fromV3Data(s))),i=O.PlTemplateOverrideV1.tplField(o);return e.createField(i,"Service"),e.setField(i,n),e.lock(o),o}};function ye(s,e,t){return E.notEmpty(e[t],`trying to get "${s}" source: sources map doesn't contain source hash ${t}`)}function vn(s,e){const t=O.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return Xr(s,t);case"pl.tengo-template.v3":return qr(s,t);default:E.assertNever(r)}}function yn(s,e){const t=e.data,r=t.type;switch(r){case"pl.tengo-template.v2":return Xr(s,t);case"pl.tengo-template.v3":return qr(s,t);default:E.assertNever(r)}}const or={hash(s,e){e.update(O.PlTemplateLibV1.type.name).update(O.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue(O.PlTemplateLibV1.type,JSON.stringify(O.PlTemplateLibV1.fromV2Data(s).data))}},Ne={hash(s,e){e.update(O.PlTemplateSoftwareV1.type.name).update(O.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=O.PlTemplateSoftwareV1.fromV2Data(s),n=e.createStruct(O.PlTemplateSoftwareV1.type,r.data);return e.setKValue(n,O.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(n),n}},zr={hash(s,e){e.update(O.PlTemplateV1.type.name).update(O.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(s.src);const t=r=>(r.sort((n,o)=>n[0]===o[0]?0:n[0]<o[0]?-1:1),r);for(const[r,n]of t(Object.entries(s.libs??{})))e.update("lib:"+r),or.hash(n,e);for(const[r,n]of t(Object.entries(s.software??{})))e.update("soft:"+r),Ne.hash(n,e);for(const[r,n]of t(Object.entries(s.assets??{})))e.update("asset:"+r),Ne.hash(n,e);for(const[r,n]of t(Object.entries(s.templates??{})))e.update("tpl:"+r),this.hash(n,e)},render(s,e,t){const r=e.createStruct(O.PlTemplateV1.type,JSON.stringify(O.PlTemplateV1.fromV2Data(s).data));for(const[i,c]of Object.entries(s.libs??{})){const a=O.PlTemplateV1.libField(r,i);e.createField(a,"Input"),e.setField(a,t(c,or))}for(const[i,c]of Object.entries(s.software??{})){const a=O.PlTemplateV1.swField(r,i);e.createField(a,"Input"),e.setField(a,t(c,Ne))}for(const[i,c]of Object.entries(s.assets??{})){const a=O.PlTemplateV1.swField(r,i);e.createField(a,"Input"),e.setField(a,t(c,Ne))}for(const[i,c]of Object.entries(s.templates??{})){const a=O.PlTemplateV1.tplField(r,i);e.createField(a,"Input"),e.setField(a,t(c,zr))}if(e.lock(r),!s.hashOverride)return r;const n=e.createStruct(O.PlTemplateOverrideV1.type,JSON.stringify(O.PlTemplateOverrideV1.fromV2Data(s))),o=O.PlTemplateOverrideV1.tplField(n);return e.createField(o,"Service"),e.setField(o,r),e.lock(n),n}};function Xr(s,e){const t=new Map,r=(n,o)=>{const i=ee.createHash("sha256");o.hash(n,i);const c=i.digest("hex");if(!t.has(c)){const a=o.render(n,s,r);t.set(c,a)}return t.get(c)};return r(e,zr)}const Yr={name:"TengoTemplateGet",version:"1"},Qr="registry",Zr="templateURI",es="template",wn={name:"TengoTemplatePack",version:"1"},bn={name:"TengoTemplatePackConvert",version:"1"},Sn="templatePack",Pn="template";async function ts(s){switch(s.type){case"from-file":return{type:"explicit",content:await Z.promises.readFile(s.path)};case"from-registry":case"explicit":return s;case"prepared":return s;default:return E.assertNever(s)}}function Rn(s,e){const t=s.createStruct(Yr),r=h.field(t,Qr),n=h.field(t,Zr),o=h.field(t,es);return s.setField(r,s.createValue(h.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(n,s.createValue(h.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),o}function Ye(s,e){switch(e.type){case"from-registry":return Rn(s,e);case"explicit":return vn(s,e);case"prepared":return yn(s,e);default:return E.assertNever(e)}}const Ft={name:"Frontend/FromUrl",version:"1"},At={name:"Frontend/FromFolder",version:"1"};function En(s,e){switch(e.type){case"url":return s.createValue(Ft,JSON.stringify({url:e.url}));case"local":return s.createValue(At,JSON.stringify({path:e.path,signature:e.signature}));default:return E.assertNever(e)}}class Cn{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__:J.resolve(void 0,"worker.js"),t=this.worker=new $s.Worker(e,{workerData:{}});t.on("message",({id:r,data:n,error:o})=>{const{resolve:i,reject:c}=this.pendingRequests.get(r);this.pendingRequests.delete(r),o?c(new Error(o)):i(n)}),t.on("error",r=>{console.error("Worker error",r),this.rejectAllPendingRequests(r)})}rejectAllPendingRequests(e){Array.from(this.pendingRequests.values()).map(({reject:t})=>{t(e)})}async process(e,...t){return new Promise((r,n)=>{const o=++this.nextMessageId;this.pendingRequests.set(o,{resolve:r,reject:n}),this.worker.postMessage({id:o,type:e,args:t})})}async terminate(){this.rejectAllPendingRequests(new Error("Worker terminated")),await this.worker.terminate()}[Symbol.asyncDispose](){return this.terminate()}}const kn={name:"BlockPackCustom",version:"1"},rs="template",ss="frontend";function ir(s){return s.endsWith("/")?s:`${s}/`}function On(s){return Buffer.from(s).toString("utf8")}function Be(s){return JSON.parse(On(s))}class Tn{constructor(e,t,r){S(this,"remoteContentCache",new Et.LRUCache({max:500,maxSize:128*1024*1024,fetchMethod:async e=>{const t=this.http!==void 0?{dispatcher:this.http}:{};return await(await ze.request(e,t)).body.arrayBuffer()},sizeCalculation:e=>e.byteLength}));this.v2RegistryProvider=e,this.signer=t,this.http=r}async getBlockConfigContainer(e){switch(e.type){case"explicit":return e.config;case"prepared":return e.config;case"dev-v1":{const t=await tr(e.folder),r=await Z.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await z.loadPackDescription(e.folder),r=await Z.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=`${ir(e.registryUrl)}${z.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=await this.remoteContentCache.forceFetch(`${t}/config.json`);return Be(r)}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),n=await this.remoteContentCache.forceFetch(r.model.url);return Be(n)}default:return E.assertNever(e)}}async prepare(e){var n=[];try{if(e.type==="prepared")return e;const t=await this.prepareWithoutUnpacking(e);const r=zt(n,new Cn,!0);return{...t,type:"prepared",template:{type:"prepared",data:await r.process("parseTemplate",t.template.content)}}}catch(o){var i=o,c=!0}finally{var a=Xt(n,i,c);a&&await a}}async prepareWithoutUnpacking(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await tr(e.folder),r=await Z.promises.readFile(t.workflow),n=JSON.parse(await Z.promises.readFile(t.config,"utf-8")),o=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:n,frontend:{type:"local",path:o,signature:this.signer.sign(o)},source:e}}case"dev-v2":{const t=await z.loadPackDescription(e.folder),r=JSON.parse(await Z.promises.readFile(t.components.model.file,{encoding:"utf-8"})),n=await Z.promises.readFile(t.components.workflow.main.file),o=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await Xe(t)),{type:"explicit",template:{type:"explicit",content:n},config:r,frontend:{type:"local",path:o,signature:this.signer.sign(o)},source:i}}case"from-registry-v1":{const t=`${ir(e.registryUrl)}${z.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=`${t}/template.plj.gz`,n=await this.remoteContentCache.forceFetch(r),o=new Uint8Array(n),i=await this.remoteContentCache.forceFetch(`${t}/config.json`),c=Be(i);return{type:"explicit",template:{type:"explicit",content:o},config:c,frontend:{type:"url",url:`${t}/frontend.tgz`},source:e}}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),n=async()=>Be(await this.remoteContentCache.forceFetch(r.model.url)),o=async()=>await this.remoteContentCache.forceFetch(r.workflow.main.url),[i,c]=await Promise.all([n(),o()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(c)},config:i,frontend:{type:"url",url:r.ui.url},source:e}}default:return E.assertNever(e)}}}function $n(s,e){const t={config:e.config,source:e.source},r=s.createStruct(kn,JSON.stringify(t));return s.createField(h.field(r,rs),"Input",Ye(s,e.template)),s.createField(h.field(r,ss),"Input",En(s,e.frontend)),s.lock(r),r}function ar(s,e){switch(e.type){case"prepared":return $n(s,e);default:return E.assertNever(e.type)}}function je(s,e,t){return{__isRef:!0,blockId:s,name:e}}function In(s){return typeof s=="object"&&s!==null&&"__isRef"in s&&s.__isRef===!0&&"blockId"in s&&"name"in s}function wt(s,e,t){const r=typeof e;switch(r){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if(In(e))t===void 0||t.has(e.blockId)?(s.upstreams.add(e.blockId),e.requireEnrichments&&s.upstreamsRequiringEnrichments.add(e.blockId)):s.missingReferences=!0;else if(Array.isArray(e))for(const n of e)wt(s,n,t);else for(const[,n]of Object.entries(e))wt(s,n,t);return;default:E.assertNever(r)}}function Fn(s,e){const t={upstreams:new Set,upstreamsRequiringEnrichments:new Set,missingReferences:!1};return wt(t,s,e),t}function ie(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class ns{constructor(e){S(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,n=>r.add(n.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const n of t)r.delete(n);return r}traverse(e,t,r){let n=[...t];const o=new Set(n);for(;n.length>0;){const i=[];for(const c of n){const a=this.nodes.get(c);r(a),a[e].forEach(l=>{o.has(l)||(o.add(l),i.push(l))})}n=i}}}function bt(s){const e=new Map;let t;for(const{id:r}of ie(s)){const n={id:r,missingReferences:!1};e.set(r,n),t===void 0?(n.directUpstream=n.upstream=new Set,n.enrichments=n.enrichmentTargets=new Set):(n.directUpstream=n.upstream=new Set([t.id]),t.directDownstream=t.downstream=new Set([n.id]),t.enrichments=t.enrichmentTargets=new Set),t=n}return t!==void 0&&(t.directDownstream=t.downstream=new Set),new ns(e)}function Ke(s,e){const t=new Map,r=new ns(t),n=new Set;for(const{id:o}of ie(s)){const i=e(o);if(i===void 0)continue;const c=Fn(i.args,n),a=new Set([...c.upstreams,...r.traverseIds("enrichments",...c.upstreamsRequiringEnrichments)]),l=new Set;for(const{id:p}of ie(s)){if(p===o)break;if(a.has(p)){l.add(p);for(const f of r.traverseIdsExcludingRoots("upstream",p))l.delete(f)}}const u=i.enrichmentTargets===void 0?new Set(c.upstreams):new Set(i.enrichmentTargets.map(p=>p.blockId)),d={id:o,missingReferences:c.missingReferences,upstream:l,directUpstream:c.upstreams,enrichmentTargets:u,downstream:new Set,directDownstream:new Set,enrichments:new Set};t.set(o,d),c.upstreams.forEach(p=>t.get(p).directDownstream.add(o)),l.forEach(p=>t.get(p).downstream.add(o)),u.forEach(p=>{var f;return(f=t.get(p))==null?void 0:f.enrichments.add(o)}),n.add(o)}return r}function An(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function St(s,e){if(s.size>e.size)return St(e,s);for(const t of s)if(e.has(t))return!0;return!1}function cr(s,e){const t=new Set,r=new Set,n=new Set;return s.nodes.forEach(o=>{const i=e.nodes.get(o.id);i===void 0?t.add(o.id):(!An(o.upstream,i.upstream)||St(o.upstream,n))&&n.add(o.id)}),e.nodes.forEach(o=>{s.nodes.has(o.id)?St(o.upstream,n)&&n.add(o.id):r.add(o.id)}),{onlyInA:t,onlyInB:r,different:n}}let it;async function os(){if(it===void 0){const s=await ts(Is.Templates["pframes.export-pframe-for-ui"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=ee.createHash("sha256").update(s.content).digest("hex");it={spec:s,hash:e}}return it}function Ln(s,e,t){return It(s,e,!0,{pf:t},["result"]).result}function at(s,e){let t=!1,r,n;return()=>{if(!t)return t=!0,r=s(),n=e(),n;const o=s();return r!==o&&(r=o,n=e()),e()}}class lr{constructor(e,t,r,n){S(this,"currentArgsC",at(()=>this.fields.currentArgs.modCount,()=>E.cachedDeserialize(this.fields.currentArgs.value)));S(this,"prodArgsC",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.cachedDeserialize(e)}));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,this.config=r,this.source=n}check(){if(this.fields.prodOutput===void 0!=(this.fields.prodCtx===void 0))throw new Error("inconsistent prod fields");if(this.fields.stagingOutput===void 0!=(this.fields.stagingCtx===void 0))throw new Error("inconsistent stage fields");if(this.fields.prodOutputPrevious===void 0!=(this.fields.prodCtxPrevious===void 0))throw new Error("inconsistent prod cache fields");if(this.fields.stagingOutputPrevious===void 0!=(this.fields.stagingCtxPrevious===void 0))throw new Error("inconsistent stage cache fields");if(this.fields.blockPack===void 0)throw new Error("no block pack field");if(this.fields.currentArgs===void 0)throw new Error("no current args field")}get currentArgs(){return this.currentArgsC()}get stagingRendered(){return this.fields.stagingCtx!==void 0}get productionRendered(){return this.fields.prodCtx!==void 0}get productionHasErrors(){var e;return((e=this.fields.prodUiCtx)==null?void 0:e.status)==="Error"}get requireProductionRendering(){return!this.productionRendered||this.productionStaleC()||this.productionHasErrors}get prodArgs(){return this.prodArgsC()}getTemplate(e){return e.getFutureFieldValue(h.Pl.unwrapHolder(e,this.fields.blockPack.ref),rs,"Input")}}const Dn=s=>{throw new Error(`No new block info for ${s}`)};class We{constructor(e,t,r,n,o,i,c,a,l,u,d,p,f){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=r,this.schema=n,this.lastModified=o,this.meta=i,this.struct=c,this.renderingState=a,this.blocksInLimbo=l,this.blockInfos=u,this.blockFrontendStates=d,this.ctxExportTplHolder=p,this.projectHelper=f}fixProblemsAndMigrate(){this.blockInfos.forEach(t=>{(t.fields.prodArgs===void 0||t.fields.prodOutput===void 0||t.fields.prodCtx===void 0)&&this.deleteBlockFields(t.id,"prodArgs","prodOutput","prodCtx")});let e;this.blockInfos.forEach(t=>{t.fields.blockSettings===void 0&&(e===void 0&&(e=this.createJsonFieldValue(W.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=bt(this.struct)),this.stagingGraph}getProductionGraphBlockInfo(e,t){const r=this.getBlockInfo(e);let n,o;if(t){if(r.fields.prodArgs===void 0)return;n=r.fields.prodArgs,o=r.prodArgs}else n=E.notEmpty(r.fields.currentArgs),o=r.currentArgs;const i=E.notEmpty(r.fields.blockPack);return h.isResourceId(n.ref)&&h.isResourceId(i.ref)?{args:o,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>o,{argsRid:n.ref,blockPackRid:i.ref})}:{args:o,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>o)}}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Ke(this.struct,e=>this.getProductionGraphBlockInfo(e,!1))),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Ke(this.struct,e=>this.getProductionGraphBlockInfo(e,!0))),this.actualProductionGraph}getBlockInfo(e){const t=this.blockInfos.get(e);if(t===void 0)throw new Error(`No such block: ${e}`);return t}createJsonFieldValueByContent(e){const t=Buffer.from(e);return{ref:this.tx.createValue(h.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of ie(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const n=h.field(this.rid,_(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(n,"Dynamic",r.ref):this.tx.setField(n,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,n,o){this.setBlockFieldObj(e,t,{ref:r,status:n,value:o})}deleteBlockFields(e,...t){let r=!1;const n=this.getBlockInfo(e);for(const o of t){const i=n.fields;o in i&&(this.tx.removeField(h.field(this.rid,_(e,o))),delete i[o],this.fieldsChanged=!0,r=!0)}return r}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var r,n,o;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((n=t.stagingCtx)==null?void 0:n.status)==="Ready"&&((o=t.stagingUiCtx)==null?void 0:o.status)==="Ready"&&(this.setBlockFieldObj(e,"stagingOutputPrevious",t.stagingOutput),this.setBlockFieldObj(e,"stagingCtxPrevious",t.stagingCtx),this.setBlockFieldObj(e,"stagingUiCtxPrevious",t.stagingUiCtx)),this.deleteBlockFields(e,"stagingOutput","stagingCtx","stagingUiCtx")&&this.resetStagingRefreshTimestamp()}resetProduction(e){var r,n,o;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((n=t.prodCtx)==null?void 0:n.status)==="Ready"&&((o=t.prodUiCtx)==null?void 0:o.status)==="Ready"&&(this.setBlockFieldObj(e,"prodOutputPrevious",t.prodOutput),this.setBlockFieldObj(e,"prodCtxPrevious",t.prodCtx),this.setBlockFieldObj(e,"prodUiCtxPrevious",t.prodUiCtx)),this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}resetOrLimboProduction(e){var r,n;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((n=t.prodCtx)==null?void 0:n.status)==="Ready"?this.blocksInLimbo.has(e)?!1:(this.blocksInLimbo.add(e),this.renderingStateChanged=!0,this.deleteBlockFields(e,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),!0):this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}setArgs(e){const t=[];for(const{blockId:r,args:n}of e){const o=this.getBlockInfo(r);JSON.parse(n);const i=Buffer.from(n);if(Buffer.compare(o.fields.currentArgs.value,i)===0)continue;const c=this.tx.createValue(h.Pl.JsonObject,i);this.setBlockField(r,"currentArgs",c,"Ready",i),this.blocksWithChangedInputs.add(r),t.push(r)}this.getStagingGraph().traverse("downstream",t,({id:r})=>this.resetStaging(r)),t.length>0&&this.updateLastModified()}setUiState(e,t){if(this.blockInfos.get(e)===void 0)throw new Error("no such block");this.blockFrontendStates.get(e)!==t&&(t===void 0?this.blockFrontendStates.delete(e):this.blockFrontendStates.set(e,t),this.changedBlockFrontendStates.add(e),this.blocksWithChangedInputs.add(e),this.updateLastModified())}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createProdCtx(e){const t=[];return e.forEach(r=>{var o;const n=this.getBlockInfo(r);if(((o=n.fields.prodCtx)==null?void 0:o.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(h.Pl.unwrapHolder(this.tx,n.fields.prodCtx.ref))}),sr(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(r=>{var o,i;const n=this.getBlockInfo(r);if(((o=n.fields.stagingCtx)==null?void 0:o.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(h.Pl.unwrapHolder(this.tx,n.fields.stagingCtx.ref)),((i=n.fields.prodCtx)==null?void 0:i.ref)!==void 0&&t.push(h.Pl.unwrapHolder(this.tx,n.fields.prodCtx.ref))}),sr(this.tx,t)}exportCtx(e){return Ln(this.tx,h.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createStagingCtx(this.getStagingGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const n=t.getTemplate(this.tx),o=rr(this.tx,n,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(h.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(h.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",h.Pl.wrapInEphHolder(this.tx,o.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(o.context),"NotReady"),this.setBlockField(e,"stagingOutput",o.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),r=this.createProdCtx(this.getPendingProductionGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const n=t.getTemplate(this.tx),o=rr(this.tx,n,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(h.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(h.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",h.Pl.wrapInEphHolder(this.tx,o.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(o.context),"NotReady"),this.setBlockField(e,"prodOutput",o.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=Dn){const r=this.getStagingGraph(),n=this.getActualProductionGraph(),o=bt(e),i=cr(r,o);for(const l of i.onlyInA){const{fields:u}=this.getBlockInfo(l);this.deleteBlockFields(l,...Object.keys(u)),this.blockInfos.delete(l),this.blocksInLimbo.delete(l)&&(this.renderingStateChanged=!0),this.blockFrontendStates.delete(l)&&this.changedBlockFrontendStates.add(l)}for(const l of i.onlyInB){const u=t(l),d=new lr(l,{},F.extractConfig(u.blockPack.config),u.blockPack.source);this.blockInfos.set(l,d);const p=ar(this.tx,u.blockPack);this.setBlockField(l,"blockPack",h.Pl.wrapInHolder(this.tx,p),"NotReady"),this.setBlockFieldObj(l,"blockSettings",this.createJsonFieldValue(W.InitialBlockSettings)),this.setBlockFieldObj(l,"currentArgs",this.createJsonFieldValueByContent(u.args)),u.uiState&&(this.blockFrontendStates.set(l,u.uiState),this.changedBlockFrontendStates.add(l)),d.check()}for(const l of i.different)this.resetStaging(l);const c=Ke(e,l=>this.getProductionGraphBlockInfo(l,!0)),a=cr(n,c);n.traverse("downstream",[...a.different],l=>{this.resetOrLimboProduction(l.id)}),(i.onlyInB.size>0||i.onlyInA.size>0||i.different.size>0)&&this.resetStagingRefreshTimestamp(),this.struct=e,this.structureChanged=!0,this.stagingGraph=void 0,this.pendingProductionGraph=void 0,this.actualProductionGraph=void 0,this.updateLastModified()}addBlock(e,t,r){const n=this.structure;if(r===void 0)n.groups[n.groups.length-1].blocks.push(e);else{let o=!1;for(const i of n.groups){const c=i.blocks.findIndex(a=>a.id===r);if(!(c<0)){i.blocks.splice(c,0,e),o=!0;break}}if(!o)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(n,o=>{if(o!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const n of t.groups){const o=n.blocks.findIndex(i=>i.id===e);if(!(o<0)){n.blocks.splice(o,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const n=this.getBlockInfo(e);this.setBlockField(e,"blockPack",h.Pl.wrapInHolder(this.tx,ar(this.tx,t)),"NotReady"),r!==void 0?(this.setArgs([{blockId:e,args:r.args}]),this.setUiState(e,r.uiState)):this.getStagingGraph().traverse("downstream",[e],({id:o})=>this.resetStaging(o)),n.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:o})=>this.resetOrLimboProduction(o)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),n=this.getPendingProductionGraph();if(t)n.traverse("upstream",e,c=>{r.add(c.id)});else for(const c of r){const a=n.nodes.get(c);if(a===void 0)throw new Error(`Can't find block with id: ${c}`);for(const l of a.upstream)if(!r.has(l))throw new Error("Can't render blocks not including all upstreams.")}const o=new Set;for(const c of ie(this.structure)){if(!r.has(c.id))continue;let a=this.getBlockInfo(c.id).requireProductionRendering||this.blocksInLimbo.has(c.id);if(!a){for(const l of n.nodes.get(c.id).upstream)if(o.has(l)){a=!0;break}}a&&(this.renderProductionFor(c.id),o.add(c.id))}const i=[...o];return n.traverse("downstream",i,c=>{o.has(c.id)||this.resetOrLimboProduction(c.id)}),this.getStagingGraph().traverse("downstream",i,({id:c})=>{i[0]!==c&&this.resetStaging(c)}),o.size>0&&this.updateLastModified(),o}stopProduction(...e){var i,c;const t=this.getActualProductionGraph(),r=new xr(e),n=new Set(e),o=[];for(;!r.isEmpty();){const a=r.shift(),l=this.getBlockInfo(a).fields;if(!(((i=l.prodOutput)==null?void 0:i.status)==="Ready"&&((c=l.prodCtx)==null?void 0:c.status)==="Ready")&&this.deleteBlockFields(a,"prodOutput","prodCtx","prodUiCtx","prodArgs")){o.push(a);for(const u of t.traverseIdsExcludingRoots("downstream",a))n.has(u)||(r.push(u),n.add(u))}}for(const a of t.traverseIdsExcludingRoots("downstream",...o))this.resetOrLimboProduction(a)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(n=>{let i=this.getBlockInfo(n.id).stagingRendered?0:1;n.upstream.forEach(c=>{const a=t.get(c);a!==0&&(i=Math.max(a+1,i))}),e(n.id,i),t.set(n.id,i)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,r=e===void 0?void 0:1+Math.max(0,t*e/1e3);let n=0;this.traverseWithStagingLag((o,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(o),n++)}),n>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,n,o,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((n=t.fields.prodOutput)==null?void 0:n.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((o=t.fields.stagingCtx)==null?void 0:o.status)==="Ready"&&((i=t.fields.stagingOutput)==null?void 0:i.status)==="Ready"&&this.deleteBlockFields(t.id,"stagingOutputPrevious","stagingCtxPrevious","stagingUiCtxPrevious")})}assignAuthorMarkers(){const e=this.author?JSON.stringify(this.author):void 0;for(const t of this.blocksWithChangedInputs)e===void 0?this.tx.deleteKValue(this.rid,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,$e,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,fe,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,qe,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,r,n){const o=t.getResourceData(r,!0),i=t.getKValueJson(r,_r),c=t.getKValueJson(r,$e),a=t.getKValueJson(r,Ie),l=t.getKValueJson(r,fe),u=t.getKValueJson(r,qe),d=t.listKeyValuesString(r),p=await o,f=new Map;for(const g of p.fields){const b=nn(g.name);if(b===void 0)continue;let v=f.get(b.blockId);v===void 0&&(v={id:b.blockId,fields:{}},f.set(b.blockId,v)),v.fields[b.fieldName]=h.isNullResourceId(g.value)?{modCount:0}:{modCount:0,ref:g.value}}const C=[];f.forEach(g=>{const b=g.fields;for(const[v,P]of Object.entries(b)){if(P.ref===void 0)continue;if(!h.isResource(P.ref)||h.isResourceRef(P.ref))throw new Error("unexpected behaviour");const T=v;C.push([g,T,P,t.getResourceData(P.ref,T=="blockPack")])}});const[w,j,N,U,{stagingRefreshTimestamp:A,blocksInLimbo:H},he]=await Promise.all([i,c,a,l,u,d]);if(w!==Kr)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${w}`);const B=[];for(const[g,b,v,P]of C){const T=await P;if(v.value=T.data,h.isNotNullResourceId(T.error)?v.status="Error":T.resourceReady||h.isNotNullResourceId(T.originalResourceId)?v.status="Ready":v.status="NotReady",b==="blockPack"){const k=T.fields.find(L=>L.name===h.Pl.HolderRefField);if(k===void 0)throw new Error("Block pack ref field is missing");B.push([g,t.getResourceData(h.ensureResourceIdNotNull(k.value),!1)])}}for(const[g,b]of B){const v=await b,P=E.cachedDeserialize(E.notEmpty(v.data));g.blockConfig=F.extractConfig(P.config),g.blockPack=P.source}const Y=await os(),te=yt(Y.hash),K=p.fields.find(g=>g.name===te);let re;K!==void 0?re=h.ensureResourceIdNotNull(K.value):(re=h.Pl.wrapInHolder(t,Ye(t,Y.spec)),t.createField(h.field(r,yt(Y.hash)),"Dynamic",re));const se={stagingRefreshTimestamp:A},M=new Set(H),q=new Map;for(const g of he){const b=tn(g.key);b!==void 0&&q.set(b,g.value)}const y=new Map;f.forEach(({id:g,fields:b,blockConfig:v,blockPack:P})=>y.set(g,new lr(g,b,E.notEmpty(v),E.notEmpty(P))));const m=new Set;for(const g of ie(U)){if(!y.has(g.id))throw new Error(`Inconsistent project structure: no inputs for ${g.id}`);m.add(g.id)}y.forEach(g=>{if(!m.has(g.id))throw new Error(`Inconsistent project structure: no structure entry for ${g.id}`);g.check()});const R=new We(r,t,n,w,j,N,U,se,M,y,q,re,e);return R.fixProblemsAndMigrate(),R}}async function Nn(s,e=Xs){const t=s.createEphemeral(Ys);s.lock(t);const r=String(Date.now());s.setKValue(t,_r,JSON.stringify(Kr)),s.setKValue(t,$t,r),s.setKValue(t,$e,r),s.setKValue(t,Ie,JSON.stringify(e)),s.setKValue(t,fe,JSON.stringify(Ws)),s.setKValue(t,qe,JSON.stringify(zs));const n=await os();return s.createField(h.field(t,yt(n.hash)),"Dynamic",h.Pl.wrapInHolder(s,Ye(s,n.spec))),t}async function Ve(s,e,t,r){return oe(s,e,t,void 0,r)}async function oe(s,e,t,r,n){if(e instanceof h.PlClient)return await e.withWriteTx("ProjectAction",async o=>{const i=await We.load(s,o,t,r),c=await n(i);return i.wasModified&&(i.save(),await o.commit()),c});{const o=await We.load(s,e,t,r),i=await n(o);return o.save(),i}}function*Bn(s){switch(s.type){case"Json":return;case"JsonPartitioned":for(const[,e]of Object.entries(s.parts))yield e;return;case"BinaryPartitioned":for(const[,{index:e,values:t}]of Object.entries(s.parts))yield e,yield t;return;default:E.assertNever(s)}}function ur(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function jn(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:ur(s.parts,e)};case"BinaryPartitioned":return{...s,parts:ur(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:E.assertNever(s)}}const Vn=h.resourceType("PColumnData/JsonPartitioned","1"),xn=h.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Un=h.resourceType("PColumnData/BinaryPartitioned","1"),Gn=h.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),Mn=h.resourceType("PColumnData/Json","1");function Jn(s){if(!s.getIsReadyOrError())throw new Error("Data not ready.");const e=s.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(h.resourceTypesEqual(s.resourceType,Mn)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(h.resourceTypesEqual(s.resourceType,Vn)){const t=e,r=Object.fromEntries(s.listInputFields().map(n=>[n,s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,xn)){const t=e,r={};for(const n of s.listInputFields()){const o=s.traverse({field:n,errorIfFieldNotSet:!0}),i=o.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${n}`);for(const c of i){const a=JSON.stringify([...JSON.parse(n),...JSON.parse(c)]);r[a]=o.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,Un)){const t=e,r={};for(const n of s.listInputFields())if(n.endsWith(".index")){const o=n.slice(0,n.length-6);let i=r[o];i===void 0&&(i={},r[o]=i),i.index=s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo}else if(n.endsWith(".values")){const o=n.slice(0,n.length-7);let i=r[o];i===void 0&&(i={},r[o]=i),i.values=s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${n}`);for(const[n,o]of Object.entries(r)){if(o.index===void 0)throw new Error(`no index for part ${n}`);if(o.values===void 0)throw new Error(`no values for part ${n}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,Gn)){const t=e,r={};for(const n of s.listInputFields()){const o=s.traverse({field:n,errorIfFieldNotSet:!0}),i=o.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${n}`);for(const c of i)if(c.endsWith(".index")){const a=c.slice(0,c.length-6),l=JSON.stringify([...JSON.parse(n),...JSON.parse(a)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].index=o.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}else if(c.endsWith(".values")){const a=c.slice(0,c.length-7),l=JSON.stringify([...JSON.parse(n),...JSON.parse(a)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].values=o.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${c}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}throw new Error(`unsupported resource type: ${h.resourceTypeToString(s.resourceType)}`)}function _n(s,e){const t=s.axesSpec.length,r={};for(const{key:n,val:o}of e){if(n.length!==t)throw new Error(`inline column key length ${n.length} differs from axes count ${t}`);r[JSON.stringify(n)]=o}return{type:"Json",keyLength:t,data:r}}function Kn(s,e){const t=ee.createHash("sha256");return t.update(x(s)),t.update(String(h.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function dr(s,e){return x({__isRef:!0,blockId:s,name:e})}function Hn(s,e){return x({resolvePath:s,name:e})}function is(s,e=!0,t=!1,r=""){var c,a,l;const n=/^(?<name>.*)\.(?<type>spec|data)$/,o=new Map;for(const u of s.listInputFields()){const d=u.match(n);if(!d){if(e)throw new Error(`unexpected field name ${u}`);continue}let p=E.notEmpty((c=d.groups)==null?void 0:c.name);if(!p.startsWith(r)){if(e)throw new Error(`unexpected field name ${u}`);continue}p=p.slice(r.length);const f=E.notEmpty((a=d.groups)==null?void 0:a.type);let C=o.get(p);switch(C===void 0&&(C={},o.set(p,C)),f){case"spec":C.spec=(l=s.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:l.getDataAsJson();break;case"data":C.hasData=!0,C.data=()=>s.traverseOrError({field:u,ignoreError:t});break}}const i=s.getInputsLocked();if(i)for(const[,u]of o)u.data===void 0&&(u.hasData=!1);return{locked:i,results:o}}function qn(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const n=is(s,e,!1,t);Fs(n.locked);const o={};for(const[i,c]of n.results){if(c.spec===void 0)throw new Error(`no spec for key ${i}`);if(c.hasData!==!0||c.data===void 0)throw new Error(`no data for key ${i}`);const a=c.data();if(a===void 0)throw new Error(`no data for key ${i}`);if(!a.ok)throw a.error;o[i]={id:r.length===0?Kn(c.spec,a.value):Hn(r,i),spec:c.spec,data:a.value}}return o}class Lt{constructor(e,t){S(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const n of t.values())for(const o of[n.prod,n.staging])if(o!==void 0){if(!o.locked){r=!1;break e}for(const i of o.results.values())if(i.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var o,i,c,a,l,u;const r=this.blocks.get(e);if(r===void 0)return;let n=(c=(i=(o=r.prod)==null?void 0:o.results)==null?void 0:i.get(t))==null?void 0:c.spec;if(n!==void 0||(n=(u=(l=(a=r.staging)==null?void 0:a.results)==null?void 0:l.get(t))==null?void 0:u.spec,n!==void 0))return n;r.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):r.staging.locked?r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var i,c,a;const r=this.blocks.get(e);if(r===void 0)return;const n=(c=(i=r.prod)==null?void 0:i.results)==null?void 0:c.get(t),o=(a=n==null?void 0:n.data)==null?void 0:a.call(n);if(n!==void 0&&n.spec!==void 0&&o!==void 0)return F.mapValueInVOE(o,l=>({id:dr(e,t),spec:n.spec,data:l}));n!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const r=this.getDataOrErrorByRef(e,t);if(!(r===void 0||!r.ok))return r.value}getData(){const e=this.getDataWithErrors(),t=[];for(const r of e.entries)r.obj.id!==void 0&&r.obj.data.ok&&t.push({ref:r.ref,obj:{id:r.obj.id,spec:r.obj.spec,data:r.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,r;const n=i=>{r===void 0&&(r=i),t=!1},o=(i,c,a)=>{if(a.spec!==void 0&&a.hasData===!0&&a.data!==void 0){const l=a.data();l!==void 0?e.push({ref:je(i,c),obj:{id:l.ok?dr(i,c):void 0,spec:a.spec,data:l}}):n(`no_data:${i}:${c}`)}};for(const[i,c]of this.blocks){const a=new Set;if(c.prod!==void 0){c.prod.locked||n(`prod_not_locked:${i}`);for(const[l,u]of c.prod.results)a.add(l),o(i,l,u)}if(c.staging!==void 0){c.staging.locked||n(`staging_not_locked:${i}`);for(const[l,u]of c.staging.results)a.has(l)||o(i,l,u)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const n=o=>{r===void 0&&(r=o),t=!1};for(const[o,i]of this.blocks){const c=new Set;if(i.staging!==void 0){i.staging.locked||n(`staging_not_locked:${o}`);for(const[a,l]of i.staging.results)l.spec!==void 0&&(e.push({ref:je(o,a),obj:l.spec}),c.add(a))}else n(`staging_not_rendered:${o}`);if(i.prod!==void 0){i.prod.locked||n(`prod_not_locked:${o}`);for(const[a,l]of i.prod.results)c.has(a)||l.spec!==void 0&&e.push({ref:je(o,a),obj:l.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const n=new Set,o=i=>{for(const[c,a]of i.results)n.has(c)||a.spec===void 0||(n.add(c),F.executePSpecPredicate(e,a.spec)&&t.push({label:r.info.label+" / "+c,ref:je(r.info.id,c),spec:a.spec}))};r.staging!==void 0&&o(r.staging),r.prod!==void 0&&o(r.prod)}return t}static create(e,t,r){const n=e.accessor(t).node(),o=E.notEmpty(n.getKeyValueAsJson(fe)),c=bt(o).traverseIds("upstream",r),a=new Map;for(const l of ie(o)){if(!c.has(l.id))continue;const u=pr(n.traverse({field:_(l.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,n.traverseOrError({field:_(l.id,"prodUiCtx"),stableIfNotFound:!0})),d=pr(n.traverse({field:_(l.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,n.traverseOrError({field:_(l.id,"stagingUiCtx")}));a.set(l.id,{info:l,prod:u,staging:d})}return new Lt(e,a)}}function pr(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return is(e.value,!1,!0)}function Dt(s,e){return{blockId:e,args:o=>E.notEmpty(o.accessor(s).node().traverse({field:_(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),activeArgs:o=>{var i;return(i=o.accessor(s).node().traverse({field:_(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:i.getDataAsString()},uiState:o=>o.accessor(s).node().getKeyValueAsString(gt(e)),blockMeta:o=>{const i=o.accessor(s).node(),c=E.notEmpty(i.getKeyValueAsJson(fe)),a=new Map;for(const l of ie(c))a.set(l.id,l);return a}}}function as(s,e){return{...Dt(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:_(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:r.persist()},staging:t=>{var n;const r=(n=t.accessor(s).node({ignoreError:!0}).traverse({field:_(e,"stagingOutput"),ignoreError:!0}))==null?void 0:n.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>Lt.create(t,s,e)}}function*Q(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*Q(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*Q(t);return;case"MakeArray":for(const t of s.template)yield*Q(t);return;case"GetJsonField":case"GetResourceField":yield*Q(s.source),yield*Q(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*Q(s.source),yield*Q(s.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"ExtractArchiveAndGetURL":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetProgressLogWithInfo":case"GetLogHandle":yield*Q(s.source);return;case"IsEmpty":yield*Q(s.arg);return;case"Not":yield*Q(s.operand);return;case"And":case"Or":yield*Q(s.operand1),yield*Q(s.operand2);return;default:E.assertNever(s)}}function Wn(s,e){const t={};for(const[r,n]of Object.entries(s))t[r]=e(n);return t}function Ce(s,e){return s===void 0?void 0:e(s)}function zn(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function Xn(s){for(const e of Q(s))if(zn(e))return!0;return!1}function Qe(s){return{type:"ReturnResult",result:s}}function $(s){return()=>Qe(s)}const Yn=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return $(e)},Qn=s=>{const e=s.source;if(e===void 0)return $(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return $(t)},Zn=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?$(void 0):({cCtx:r})=>{var n;return Qe((n=r.accessor(e).node().traverse(t))==null?void 0:n.persist())}};function cs(s,e){const t={},r=s.length;for(let n=0;n<r;n++)t[String(n)]=e(s[n]);return t}function eo(s,e){return t=>{const r=t.source;return r===void 0?$(void 0):()=>({type:"ScheduleSubroutine",subroutine:ls(r.length),args:cs(r,n=>I({...s,[e.itVar]:n},e.mapping))})}}function ls(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return $(t)}}function to(s,e){return t=>{const r=t.source;if(r===void 0)return $(void 0);const n={};for(const[o,i]of Object.entries(r)){const c={...s,[e.itVar]:i};n[o]=I(c,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:ro,args:n})}}const ro=s=>$(s),so=s=>{const e=s.arg;return $(e===void 0?void 0:e.length===0)},no=s=>{const e=s.operand;return $(e===void 0?void 0:!e)},oo=s=>{const e=s.operand1,t=s.operand2;return $(e===void 0||t===void 0?void 0:e&&t)},io=s=>{const e=s.operand1,t=s.operand2;return $(e===void 0||t===void 0?void 0:e||t)},ao=s=>{const e=s.source;return e===void 0?$(void 0):({cCtx:t})=>{var r;return Qe((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},co=s=>{const e=s.source,t=s.field;return $(e===void 0||t===void 0?void 0:e[t])};function lo(s,e){return t=>{const r=t.source;return r===void 0?$(void 0):({cCtx:n})=>{const o=n.accessor(r).node(),i={};for(const c of o.listInputFields()){const a=o.traverse(c);if(a===void 0)i[c]=$(void 0);else{const l={...s,[e.itVar]:a.persist()};i[c]=I(l,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:uo,args:i}}}}const uo=s=>$(s),po=s=>{const e=s.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:V.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r!==void 0)return await t.blobDriver.getContent(r.handle)}})})},fo=s=>{const e=s.source;return e===void 0?$(void 0):({cCtx:t,drivers:r})=>{const n=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:V.Computable.make(()=>r.blobDriver.getDownloadedBlob(n),{postprocessValue:async o=>o===void 0?void 0:(await r.blobDriver.getContent(o.handle)).toString()})}}},ho=s=>{const e=s.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:V.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r==null)return;const n=await t.blobDriver.getContent(r.handle);if(n!=null)return JSON.parse(Buffer.from(n).toString())}})})},go=s=>{const e=s.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},mo=s=>{const e=s.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},vo=s=>e=>{const t=e.source;return t===void 0?$(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.blobToURLDriver.extractArchiveAndGetURL(t,s)})},yo=s=>{const e=s.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},wo=s=>e=>{const t=e.source;return t===void 0?$(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},bo=s=>e=>{const t=e.source;return t===void 0?$(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},So=s=>e=>{const t=e.source;return t===void 0?$(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLogWithInfo(t,s)})},Po=s=>{const e=s.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function I(s,e){switch(e.type){case"GetFromCtx":{const t=s[e.variable];return typeof t=="function"?r=>Qe(t(r.cCtx)):$(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:ps(t,s,e.cfg)});case"Immediate":return $(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:co,args:{source:I(s,e.source),field:I(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:eo(s,e),args:{source:I(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:to(s,e),args:{source:I(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:Yn,args:Wn(e.template,t=>I(s,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:ls(e.template.length),args:cs(e.template,t=>I(s,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:Qn,args:{source:I(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:so,args:{arg:I(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:no,args:{operand:I(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:oo,args:{operand1:I(s,e.operand1),operand2:I(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:io,args:{operand1:I(s,e.operand1),operand2:I(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:lo(s,e),args:{source:I(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:Zn,args:{source:I(s,e.source),field:I(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:ao,args:{source:I(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:po,args:{source:I(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:fo,args:{source:I(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:ho,args:{source:I(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:go,args:{source:I(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:mo,args:{source:I(s,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:vo(e.format),args:{source:I(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:yo,args:{source:I(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:wo(e.lines),args:{source:I(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:bo(e.patternToSearch),args:{source:I(s,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:So(e.patternToSearch),args:{source:I(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:Po,args:{source:I(s,e.source)}});default:return E.assertNever(e)}}const Ro=["$prod","$staging"];function Eo(s){return{$blockId:s.blockId,$args:e=>JSON.parse(s.args(e)),$ui:e=>{const t=s.uiState(e);return t!==void 0?JSON.parse(t):void 0},$prod:s.prod,$staging:s.staging}}const us=Symbol(),ds="return",Co={op:us,arg:ds};function ko(s){return s.op==us&&s.arg==ds}function Oo(){return{pendingSubroutines:new Map}}function fr(s,e,t,r){const n=new xr(t),o=(c,a)=>{if(ko(c))return e.result=a,!1;const l=E.notEmpty(e.pendingSubroutines.get(c.op));if(c.arg in l.args)throw new Error("argument already set");return l.args[c.arg]=a,l.argCounter--,l.argCounter===0&&(e.pendingSubroutines.delete(c.op),n.push({destination:l.destination,operation:l.subroutine(l.args)})),!0},i=[];e:for(;n.length>0;){const c=n.shift(),a=c.operation(s);switch(a.type){case"ReturnResult":if(!o(c.destination,a.result))break e;break;case"ScheduleSubroutine":{const l=Symbol(),u=Object.entries(a.args),d=u.length;if(d===0)n.push({destination:c.destination,operation:a.subroutine({})});else{for(const[p,f]of u)n.push({destination:{op:l,arg:p},operation:f});e.pendingSubroutines.set(l,{argCounter:d,args:{},subroutine:a.subroutine,destination:c.destination})}}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:c.destination,computable:a.computable});break;default:E.assertNever(a)}}return i}function To(s,e,t,r={}){return ps(s,Eo(e),t,r)}function ps(s,e,t,r={}){const n=`${e.blockId}#`+x({ctx:Object.fromEntries(Object.entries(e).filter(([o])=>Ro.indexOf(o)===-1)),cfg:t});return V.Computable.makeRaw(o=>{const i={drivers:s,cCtx:o},c=Oo();return{ir:fr(i,c,[{destination:Co,operation:I(e,t)}],!0),postprocessValue(l){const u=[];for(const C of l)u.push({destination:C.destination,operation:$(C.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},p=new Map;for(const[C,w]of c.pendingSubroutines)p.set(C,{...w,args:{...w.args}});const f={result:c.result,pendingSubroutines:p};if(fr(d,f,u,!1),!("result"in f))throw new Error("illegal cfg rendering stack state, no result");return f.result}}},{...r,key:n})}function hr(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class $o{constructor(e,t,r,n){S(this,"computablesToResolve",{});S(this,"computableCtx");S(this,"accessors",new Map);S(this,"meta");S(this,"_resultPool");this.parent=e,this.blockCtx=t,this.env=r,this.computableCtx=n,this.meta=t.blockMeta(n)}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,n)=>{if(!this.accessors.has(r)){const o=this.blockCtx[n];if(o===void 0)throw new Error("Staging context not available");const i=o(this.computableCtx);i?this.accessors.set(r,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(r,void 0)}return this.accessors.get(r)?r:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...r){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...r))}getResourceType(e){return this.getAccessor(e).resourceType}getInputsLocked(e){return this.getAccessor(e).getInputsLocked()}getOutputsLocked(e){return this.getAccessor(e).getOutputsLocked()}getIsReadyOrError(e){return this.getAccessor(e).getIsReadyOrError()}getIsFinal(e){return this.getAccessor(e).getIsFinal()}getError(e){return this.wrapAccessor(this.getAccessor(e).getError())}listInputFields(e){return this.getAccessor(e).listInputFields()}listOutputFields(e){return this.getAccessor(e).listOutputFields()}listDynamicFields(e){return this.getAccessor(e).listDynamicFields()}getKeyValueBase64(e,t){return hr(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return hr(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r,...n){const o=this.getAccessor(e);if(!o.getIsReadyOrError())return;const i=qn(o,t,r,n),c={};for(const[a,l]of Object.entries(i))c[a]=F.mapPObjectData(l,u=>this.wrapAccessor(u));return c}registerComputable(e,t){const r=`${e}_${ee.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",V.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("utf-8")}}))}getBlobContentAsBase64(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",V.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.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 r=this.getAccessor(e).persist();return this.registerComputable("extractArchiveAndGetURL",this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(r,t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(r,t))}getProgressLog(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(r,t))}getProgressLogWithInfo(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLogWithInfo",this.env.driverKit.logDriver.getProgressLogWithInfo(r,t))}getLogHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getLogHandle",this.env.driverKit.logDriver.getLogHandle(t))}getBlockLabel(e){const t=this.meta.get(e);if(t===void 0)throw new Error(`Block ${e} not found.`);return t.label}get resultPool(){if(this._resultPool===void 0){if(this.computableCtx===void 0)throw new Error("can't use result pool in this context (most porbably called from the future mapper)");this._resultPool=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:F.mapPObjectData(t.obj,r=>this.wrapAccessor(r))}))}}getDataWithErrorsFromResultPool(){const e=this.resultPool.getDataWithErrors();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:{id:t.obj.id,spec:t.obj.spec,data:F.mapValueInVOE(t.obj.data,r=>this.wrapAccessor(r))}}))}}getSpecsFromResultPool(){const e=this.resultPool.getSpecs();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`specs_from_pool_incomplete:${e.instabilityMarker}`),e}getSpecFromResultPoolByRef(e,t){return this.resultPool.getSpecByRef(e,t)}getDataFromResultPoolByRef(e,t){return F.mapPObjectData(this.resultPool.getDataByRef(e,t),r=>this.wrapAccessor(r))}createPFrame(e){if(this.computableCtx===void 0)throw new Error("can't instantiate PFrames from this context (most porbably called from the future mapper)");return this.env.driverKit.pFrameDriver.createPFrame(e.map(t=>F.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}createPTable(e){if(this.computableCtx===void 0)throw new Error("can't instantiate PTable from this context (most porbably called from the future mapper)");return this.env.driverKit.pFrameDriver.createPTable(F.mapPTableDef(e,t=>F.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}transformInputPData(e){return typeof e=="string"?this.getAccessor(e):F.isDataInfo(e)?F.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}}injectCtx(e){const t=this.parent,r=t.vm;pe.Scope.withScope(n=>{const o=this.blockCtx.args(this.computableCtx),i=this.blockCtx.activeArgs(this.computableCtx),c=this.blockCtx.uiState(this.computableCtx);r.setProp(e,"args",n.manage(r.newString(o))),c!==void 0&&r.setProp(e,"uiState",n.manage(r.newString(c))),i!==void 0&&r.setProp(e,"activeArgs",n.manage(r.newString(i)));const a=(l,u)=>{const d=(...p)=>{try{return u(...p)}catch(f){const C=t.errorRepo.setAndRecreateForQuickJS(f);throw r.newError(C)}};r.newFunction(l,d).consume(p=>r.setProp(e,l,p)),r.newFunction(l,u).consume(p=>r.setProp(e,l+"__internal__",p))};a("getAccessorHandleByName",l=>t.exportSingleValue(this.getAccessorHandleByName(r.getString(l)),void 0)),a("resolveWithCommon",(l,u,...d)=>t.exportSingleValue(this.resolveWithCommon(r.getString(l),t.importObjectViaJson(u),...d.map(p=>t.importObjectViaJson(p))),void 0)),a("getResourceType",l=>t.exportObjectViaJson(this.getResourceType(r.getString(l)),void 0)),a("getInputsLocked",l=>t.exportSingleValue(this.getInputsLocked(r.getString(l)),void 0)),a("getOutputsLocked",l=>t.exportSingleValue(this.getOutputsLocked(r.getString(l)),void 0)),a("getIsReadyOrError",l=>t.exportSingleValue(this.getIsReadyOrError(r.getString(l)),void 0)),a("getIsFinal",l=>t.exportSingleValue(this.getIsFinal(r.getString(l)),void 0)),a("getError",l=>t.exportSingleValue(this.getError(r.getString(l)),void 0)),a("listInputFields",l=>t.exportObjectViaJson(this.listInputFields(r.getString(l)),void 0)),a("listOutputFields",l=>t.exportObjectViaJson(this.listInputFields(r.getString(l)),void 0)),a("listDynamicFields",l=>t.exportObjectViaJson(this.listInputFields(r.getString(l)),void 0)),a("getKeyValueBase64",(l,u)=>t.exportSingleValue(this.getKeyValueBase64(r.getString(l),r.getString(u)),void 0)),a("getKeyValueAsString",(l,u)=>t.exportSingleValue(this.getKeyValueAsString(r.getString(l),r.getString(u)),void 0)),a("getDataBase64",l=>t.exportSingleValue(this.getDataBase64(r.getString(l)),void 0)),a("getDataAsString",l=>t.exportSingleValue(this.getDataAsString(r.getString(l)),void 0)),a("parsePObjectCollection",(l,u,d,...p)=>t.exportObjectUniversal(this.parsePObjectCollection(r.getString(l),r.dump(u),r.getString(d),...p.map(f=>r.getString(f))),void 0)),a("getBlobContentAsBase64",l=>t.exportSingleValue(this.getBlobContentAsBase64(r.getString(l)),void 0)),a("getBlobContentAsString",l=>t.exportSingleValue(this.getBlobContentAsString(r.getString(l)),void 0)),a("getDownloadedBlobContentHandle",l=>t.exportSingleValue(this.getDownloadedBlobContentHandle(r.getString(l)),void 0)),a("getOnDemandBlobContentHandle",l=>t.exportSingleValue(this.getOnDemandBlobContentHandle(r.getString(l)),void 0)),a("extractArchiveAndGetURL",(l,u)=>t.exportSingleValue(this.extractArchiveAndGetURL(r.getString(l),r.getString(u)),void 0)),a("getImportProgress",l=>t.exportSingleValue(this.getImportProgress(r.getString(l)),void 0)),a("getLastLogs",(l,u)=>t.exportSingleValue(this.getLastLogs(r.getString(l),r.getNumber(u)),void 0)),a("getProgressLog",(l,u)=>t.exportSingleValue(this.getProgressLog(r.getString(l),r.getString(u)),void 0)),a("getProgressLogWithInfo",(l,u)=>t.exportSingleValue(this.getProgressLogWithInfo(r.getString(l),r.getString(u)),void 0)),a("getLogHandle",l=>t.exportSingleValue(this.getLogHandle(r.getString(l)),void 0)),a("getBlockLabel",l=>t.exportSingleValue(this.getBlockLabel(r.getString(l)),void 0)),a("getDataFromResultPool",()=>t.exportObjectUniversal(this.getDataFromResultPool(),void 0)),a("getDataWithErrorsFromResultPool",()=>t.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),a("getSpecsFromResultPool",()=>t.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),a("calculateOptions",l=>t.exportObjectUniversal(this.calculateOptions(t.importObjectViaJson(l)),void 0)),a("getSpecFromResultPoolByRef",(l,u)=>t.exportObjectUniversal(this.getSpecFromResultPoolByRef(r.getString(l),r.getString(u)),void 0)),a("getDataFromResultPoolByRef",(l,u)=>t.exportObjectUniversal(this.getDataFromResultPoolByRef(r.getString(l),r.getString(u)),void 0)),a("createPFrame",l=>t.exportSingleValue(this.createPFrame(t.importObjectViaJson(l)),void 0)),a("createPTable",l=>t.exportSingleValue(this.createPTable(t.importObjectViaJson(l)),void 0)),a("getCurrentUnstableMarker",()=>t.exportSingleValue(this.getCurrentUnstableMarker(),void 0))})}}function Io(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}class Fe{constructor(e,t,r,n){S(this,"callbackRegistry");S(this,"fnJSONStringify");S(this,"fnJSONParse");S(this,"errorRepo",new Fo);S(this,"computableHelper");if(this.scope=e,this.vm=t,this.deadlineSetter=r,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(o=>t.getProp(o,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(o=>t.getProp(o,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");n!==void 0&&(this.computableHelper=new $o(this,n.blockCtx,n.mlEnv,n.computableCtx)),this.injectCtx()}resetComputableCtx(){E.notEmpty(this.computableHelper,"Computable context helper is not initialized").resetComputableCtx()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.deadlineSetter({currentExecutionTarget:"evaluateBundle",deadline:Date.now()+1e4}),this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw Fe.cleanErrorContext(t),t}finally{this.deadlineSetter(void 0)}}runCallback(e,...t){try{return this.deadlineSetter({currentExecutionTarget:e,deadline:Date.now()+1e4}),pe.Scope.withScope(r=>{const n=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(n)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(n,this.vm.undefined,...t.map(o=>this.exportObjectUniversal(o,r)))))})}catch(r){throw Fe.cleanErrorContext(r),this.errorRepo.getOriginal(r)}finally{this.deadlineSetter(void 0)}}exportSingleValue(e,t){const r=this.tryExportSingleValue(e,t);if(r===void 0)throw new Error(`Can't export value: ${e===void 0?"undefined":JSON.stringify(e)}`);return r}tryExportSingleValue(e,t){let r,n=!1;switch(typeof e){case"string":r=this.vm.newString(e),n=!0;break;case"number":r=this.vm.newNumber(e),n=!0;break;case"undefined":r=this.vm.undefined;break;case"boolean":r=e?this.vm.true:this.vm.false;break;default:if(e===null){r=this.vm.null;break}if(Io(e)){r=this.vm.newArrayBuffer(e),n=!0;break}return}return n&&t!=null?t.manage(r):r}exportObjectUniversal(e,t){const r=this.tryExportSingleValue(e,t);return r!==void 0?r:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const r=this.vm.newString(JSON.stringify(e)).consume(n=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,n)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){switch(this.vm.typeof(e)){case"undefined":return;case"boolean":case"number":case"string":return this.vm.dump(e);default:return this.importObjectViaJson(e)}}importObjectViaJson(e){const t=this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify,this.vm.undefined,e)).consume(r=>this.vm.getString(r));if(t!=="undefined")return JSON.parse(t)}injectCtx(){pe.Scope.withScope(e=>{const t=e.manage(this.vm.newObject());this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(F.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e)),this.computableHelper!==void 0&&this.computableHelper.injectCtx(t),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}class Fo{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 pe.errors.QuickJSUnwrapError))return console.warn("ErrorRepo: quickJSError is not a QuickJSUnwrapError",h.stringifyWithResourceId(e)),e;if(!("name"in e.cause))return console.warn("ErrorRepo: quickJSError.cause is not an Error",h.stringifyWithResourceId(e)),e;const t=e.cause.name,r=t.slice(t.indexOf("/uuid:")+6);if(!r)throw new Error(`ErrorRepo: quickJSError.cause.name does not contain errorId: ${t}, ${h.stringifyWithResourceId(e)}`);const n=this.errorIdToError.get(r);if(n===void 0)throw new Error(`ErrorRepo: errorId not found: ${r}, ${h.stringifyWithResourceId(e)}`);return new As.PlQuickJSError(e,n)}}function Ae(s,e){return Ce(s.traverse({field:_(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:h.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),n=F.extractConfig(r.config);return{bpResourceId:t.resourceInfo.id,bpId:t.resourceInfo.id.toString(),info:r,cfg:n}})}const xe=process.env.MI_LOG_OUTPUT_STATUS;function Ao(s,e,t,r,n,o={}){const i=`${e.blockId}#lambda#${n}#${t.handle}`;return o={...o,key:i},o.mode===void 0&&t.retentive===!0&&(o.mode="StableOnlyRetentive"),V.Computable.makeRaw(c=>{const a=new pe.Scope;c.addOnDestroy(()=>a.dispose());const l=a.manage(s.quickJs.newRuntime());l.setMemoryLimit(1024*1024*8),l.setMaxStackSize(1024*320);let u;l.setInterruptHandler(()=>u===void 0?!1:Date.now()>u.deadline);const d=a.manage(l.newContext()),p=new Fe(a,d,w=>{u=w},{computableCtx:c,blockCtx:e,mlEnv:s});p.evaluateBundle(r.content);const f=p.runCallback(t.handle);p.resetComputableCtx();let C=0;return xe&&xe!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:p.computableHelper.computablesToResolve,postprocessValue:(w,{unstableMarker:j,stable:N})=>{for(const[A,H]of Object.entries(w))p.runCallback(A,H);const U=p.importObjectUniversal(f);return C++,xe&&(xe!=="unstable-only"||!N)&&console.log(N?`Stable output ${t.handle} calculated ${U!==void 0?"defined":"undefined"}; (#${C})`:`Unstable output ${t.handle}; marker = ${j}; ${U!==void 0?"defined":"undefined"} (#${C})`),U}}},o)}function Lo(s,e,t,...r){const n=new pe.Scope;try{const o=n.manage(s.newRuntime());o.setMemoryLimit(1024*1024*8),o.setMaxStackSize(1024*320);let i;o.setInterruptHandler(()=>i===void 0?!1:Date.now()>i.deadline);const c=n.manage(o.newContext()),a=new Fe(n,c,l=>{i=l});return a.evaluateBundle(t.content),a.importObjectUniversal(a.runCallback(e.handle,...r))}finally{n.dispose()}}function Do(s){return F.isConfigLambda(s)?s.isActive===!0:Xn(s)}function ke(s,e,t,r,n,o={}){if(F.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return Ao(s,e,t,r,n,o)}else return To(s.driverKit,e,t,o)}function No(s,e){if(s===e)return!0;if(s===void 0||e===void 0)return!1;const t=Qt.omitBy((r,n)=>n.startsWith("__"));return Qt.isDeepEqual(t(s),t(e))}function Bo(s,e,t){return V.Computable.make(r=>{var C,w,j,N,U,A,H,he;const n=r.accessor(s).node(),o=E.notEmpty(n.getKeyValueAsJson($t)),i=E.notEmpty(n.getKeyValueAsJson($e)),c=E.notEmpty(n.getKeyValueAsJson(Ie)),a=E.notEmpty(n.getKeyValueAsJson(fe)),l=E.notEmpty(n.getKeyValueAsJson(qe)),u=new Map;for(const{id:B}of ie(a)){const Y=n.traverse({field:_(B,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}),te=Y.getDataAsJson();let K;const re=n.traverse({field:_(B,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(re!==void 0){const se=re.getDataAsJson(),M=n.getField({field:_(B,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),q=n.getField({field:_(B,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});K={arguments:se,stale:!No(te,se),outputError:M.error!==void 0||q.error!==void 0||((C=M.value)==null?void 0:C.getError())!==void 0||((w=q.value)==null?void 0:w.getError())!==void 0,outputsError:((j=M.error)==null?void 0:j.getDataAsString())??((U=(N=M.value)==null?void 0:N.getError())==null?void 0:U.getDataAsString()),exportsError:((A=q.error)==null?void 0:A.getDataAsString())??((he=(H=q.value)==null?void 0:H.getError())==null?void 0:he.getDataAsString()),finished:(M.value!==void 0&&M.value.getIsReadyOrError()||M.error!==void 0&&M.error.getIsReadyOrError())&&(q.value!==void 0&&q.value.getIsReadyOrError()||q.error!==void 0&&q.error.getIsReadyOrError())}}u.set(B,{currentArguments:te,prod:K,argsRid:Y.resourceInfo.id})}const d=Ke(a,B=>{const Y=Ae(n,B),te=u.get(B),K=te.currentArguments;return{args:K,enrichmentTargets:t.projectHelper.getEnrichmentTargets(()=>Y.cfg,()=>K,{argsRid:te.argsRid,blockPackRid:Y.bpResourceId})}}),p=new Set(l.blocksInLimbo),f=[...ie(a)].map(({id:B,label:Y,renderingMode:te})=>{var v,P,T,k,L;const K=E.notEmpty(u.get(B)),re=E.notEmpty(d.nodes.get(B));let se="NotCalculated";K.prod!==void 0&&(p.has(B)?se="Limbo":se=K.prod.finished?"Done":"Running");const M=Ae(n,B),{sections:q,title:y,inputsValid:m,sdkVersion:R}=Ce(M,({bpId:G,cfg:D})=>{const ue=Dt(s,B);return{sections:ke(t,ue,D.sections,D.code,G).wrap({recover:be=>(t.logger.error("Error in block model sections"),t.logger.error(be),[])}),title:Ce(D.title,be=>ke(t,ue,be,D.code,G).wrap({recover:Es=>(t.logger.error("Error in block model title"),t.logger.error(Es),"Invalid title")})),inputsValid:ke(t,ue,D.inputsValid,D.code,G).wrap({recover:be=>(t.logger.error("Error in block model argsValid"),t.logger.error(be),!1)}),sdkVersion:D.sdkVersion}})||{},g=n.traverse({field:_(B,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),b=Ce(M,({info:G})=>t.blockUpdateWatcher.get({currentSpec:G.source,settings:g}));return{projectResourceId:h.resourceIdToString(s.rid),id:B,label:y??Y,title:y??Y,renderingMode:te,stale:((v=K.prod)==null?void 0:v.stale)!==!1||se==="Limbo",missingReference:re.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",B)],downstreams:[...d.traverseIdsExcludingRoots("downstream",B)],calculationStatus:se,outputErrors:((P=K.prod)==null?void 0:P.outputError)===!0,outputsError:(T=K.prod)==null?void 0:T.outputsError,exportsError:(k=K.prod)==null?void 0:k.exportsError,settings:g,sections:q,inputsValid:m,updateInfo:{},currentBlockPack:(L=M==null?void 0:M.info)==null?void 0:L.source,updates:b,sdkVersion:R,navigationState:e.getState(B)}});return{meta:c,created:new Date(o),lastModified:new Date(i),authorMarker:n.getKeyValueAsJson(vt),blocks:f}},{postprocessValue:r=>{const n=new Set,o=new Set;return{...r,blocks:r.blocks.map(i=>{var u,d;i.inputsValid||n.add(i.id),i.stale&&o.add(i.id);const c=i.stale||i.upstreams.findIndex(p=>o.has(p))!==-1,a=(c||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(p=>n.has(p))===-1,l={...i,canRun:a,stale:c,updateSuggestions:((u=i.updates)==null?void 0:u.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete l.updates,l})}}}).withStableType()}function jo(s,e){const t=s.node();if(h.resourceTypesEqual(t.resourceType,Ft)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.frontendDownloadDriver.getPath(new URL(r.url)).withStableType()}else if(h.resourceTypesEqual(t.resourceType,At)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.signer.verify(r.path,r.signature,`Frontend path signature mismatch for: ${r.path}`),r.path}else throw new Error(`Unsupported resource type: ${JSON.stringify(t.resourceType)}`)}function Vo(s,e){if(s!==void 0)return V.Computable.make(t=>jo(t.accessor(s),e),{postprocessValue:t=>{if(t!==void 0){if(typeof t=="string")return t;if(t.error!==void 0)throw new Error(t.error);return t.path}}}).withStableType()}function xo(s,e,t){return V.Computable.make(r=>{var c;const n=r.accessor(s).node(),o=Ae(n,e),i=(c=n.traverse({field:_(e,"blockPack"),assertFieldType:"Dynamic"},{field:h.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:ss,assertFieldType:"Input"}))==null?void 0:c.persist();return{path:Vo(i,t),sdkVersion:o==null?void 0:o.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function fs(s,e,t){if(t===void 0)return V.Computable.make(i=>fs(s,e,i),{key:`inputs#${h.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),n=Dt(s,e),o=n.uiState(t);return{author:r.getKeyValueAsJson(mt(e)),args:E.deepFreeze(JSON.parse(n.args(t))),ui:o!==void 0?E.deepFreeze(JSON.parse(o)):void 0}}function Uo(s,e,t){return V.Computable.make(r=>{const n=r.accessor(s).node(),o=as(s,e);return Ce(Ae(n,e),({cfg:i,bpId:c})=>{const a={};for(const[l,u]of Object.entries(i.outputs)){const d=ke(t,o,u,i.code,c);a[l]=V.Computable.wrapError(d,1)}return a})},{key:"outputs#"+h.resourceIdToString(s.rid)+"#"+e}).withStableType()}function Go(s,e){return V.Computable.make(t=>{const r=t.accessor(s).node(),n=E.notEmpty(r.getKeyValueAsJson(fe)),o=[];for(const{id:i}of ie(n)){const c=Ae(r,i);if(c===void 0)continue;const a=Object.entries(c.cfg.outputs).map(([,u])=>u).filter(u=>Do(u)).map(u=>u);if(a.length===0)continue;const l=as(r.persist(),i);for(const u of a)o.push(V.Computable.wrapError(ke(e,l,u,c.cfg.code,c.bpId)))}return o})}class Mo{constructor(){S(this,"states",new Map)}setState(e,t){const r=this.states.get(e);if(r===void 0){this.states.set(e,{state:t,change:new V.ChangeSource});return}r.state={...t},r.change.markChanged()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...F.DefaultNavigationState},change:new V.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return V.Computable.make(t=>this.readState(t,e),{key:`navigationState#${e}`})}deleteBlock(e){const t=this.states.get(e);t!==void 0&&(this.states.delete(e),t.change.markChanged())}}function gr(s){return JSON.stringify(s,(e,t)=>typeof t=="bigint"?h.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,r){S(this,"rid");S(this,"overview");S(this,"navigationStates",new Mo);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=r,this.overview=Bo(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=Go(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await Ve(this.env.projectHelper,this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await Ur.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(h.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!h.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,n=void 0,o=ee.randomUUID()){const i=await this.env.bpPreparer.prepare(t),c=await this.env.bpPreparer.getBlockConfigContainer(t),a=F.extractConfig(c);return await oe(this.env.projectHelper,this.env.pl,this.rid,n,l=>l.addBlock({id:o,label:e,renderingMode:a.renderingMode},{args:x(a.initialArgs),uiState:x(a.initialUiState),blockPack:i},r)),await this.projectTree.refreshState(),o}async updateBlockPack(e,t,r=!1,n){const o=await this.env.bpPreparer.prepare(t),i=F.extractConfig(await this.env.bpPreparer.getBlockConfigContainer(t));await oe(this.env.projectHelper,this.env.pl,this.rid,n,c=>c.migrateBlockPack(e,o,r?{args:x(i.initialArgs),uiState:x(i.initialUiState)}:void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await oe(this.env.projectHelper,this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await oe(this.env.projectHelper,this.env.pl,this.rid,t,r=>{const n=r.structure;if(n.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const o=n.groups[0];if(o.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${o.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const i={groups:[{id:o.id,label:o.label,blocks:e.map(c=>{const a=o.blocks.find(l=>l.id===c);if(a===void 0)throw new Error(`Can't find block: ${c}`);return a})}]};r.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await Ve(this.env.projectHelper,this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await Ve(this.env.projectHelper,this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await oe(this.env.projectHelper,this.env.pl,this.rid,r,n=>n.setArgs([{blockId:e,args:x(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await oe(this.env.projectHelper,this.env.pl,this.rid,r,n=>n.setUiState(e,t===void 0?void 0:x(t))),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,n){await oe(this.env.projectHelper,this.env.pl,this.rid,n,o=>{o.setArgs([{blockId:e,args:x(t)}]),o.setUiState(e,x(r))}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await oe(this.env.projectHelper,this.env.pl,this.rid,void 0,r=>{r.setBlockSettings(e,t)}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async r=>{const n=h.ensureResourceIdNotNull((await r.getField(h.field(this.rid,_(e,"blockPack")))).value),o=h.ensureResourceIdNotNull((await r.getField(h.field(n,h.Pl.HolderRefField))).value),i=await r.getResourceData(o,!1),c=F.extractConfig(E.cachedDeserialize(E.notEmpty(i.data)).config);await oe(this.env.projectHelper,r,this.rid,t,a=>{a.setArgs([{blockId:e,args:x(c.initialArgs)}]),a.setUiState(e,x(c.initialUiState))}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===void 0){const r=Uo(this.projectTree.entry(),e,this.env),o={fullState:V.Computable.make(i=>({argsAndUiState:fs(this.projectTree.entry(),e,i),outputs:r,navigationState:this.navigationStates.getState(e),overview:this.overview}),{postprocessValue:i=>{var u,d,p;const c=(p=(d=(u=i.overview)==null?void 0:u.blocks)==null?void 0:d.find(f=>f.id==e))==null?void 0:p.sdkVersion,l=c&&_o(c)&&i.outputs!==void 0?Ho(i.outputs):i.outputs;return{...i.argsAndUiState,outputs:l,navigationState:i.navigationState}}}).withPreCalculatedValueTree()};return this.blockComputables.set(e,o),o}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=xo(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,r),r}return t}async destroy(){this.destroyed=!0,this.abortController.abort(),await this.refreshLoopResult,await this.projectTree.terminate(),this.overview.resetState(),this.blockFrontends.forEach(e=>e.resetState()),this.blockComputables.forEach(e=>{e.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){await Ve(e.projectHelper,e.pl,t,n=>{});const r=await He.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:Jo},e.logger);if(e.ops.debugOps.dumpInitialTreeState){const n=r.dumpState();n.sort((i,c)=>{var a,l;return(((a=c.data)==null?void 0:a.byteLength)??0)-(((l=i.data)==null?void 0:l.byteLength)??0)});const o=He.treeDumpStats(n);await ht.writeFile(`${h.resourceIdToString(t)}.json`,gr(n)),await ht.writeFile(`${h.resourceIdToString(t)}.stats.json`,gr(o))}return new Ze(e,t,r)}}function Jo(s){switch(s.type.name){case"BlockPackCustom":return s.fields.filter(e=>e.name!=="template");case"UserProject":return s.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return s.fields}}function _o(s){return!Ko(s,"1.26.0")}function Ko(s,e){const t=s.split(".").map(Number),r=e.split(".").map(Number);return t[0]>r[0]||t[0]===r[0]&&t[1]>r[1]||t[0]===r[0]&&t[1]===r[1]&&t[2]>r[2]}function Ho(s){const e={};for(const[t,r]of Object.entries(s)){if(r.ok){e[t]=r;continue}e[t]={ok:!1,errors:r.errors.map(n=>typeof n=="string"?n:n.type=="PlError"&&n.fullMessage!==void 0?n.fullMessage:n.message),moreErrors:r.moreErrors}}return e}const Nt={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 Bt(s){return{blobDownloadPath:J.join(s,"download"),downloadBlobToURLPath:J.join(s,"downloadToURL"),pframesSpillPath:J.join(s,"pframes")}}const hs={...Nt,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500,initialTreeLoadingTimeout:100*60*60*1e3},debugOps:{dumpInitialTreeState:!1},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function gs(s){return{...Bt(s),frontendDownloadPath:J.join(s,"frontend")}}function qo(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Pt={exports:{}};const Wo="2.0.0",ms=256,zo=Number.MAX_SAFE_INTEGER||9007199254740991,Xo=16,Yo=ms-6,Qo=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var et={MAX_LENGTH:ms,MAX_SAFE_COMPONENT_LENGTH:Xo,MAX_SAFE_BUILD_LENGTH:Yo,MAX_SAFE_INTEGER:zo,RELEASE_TYPES:Qo,SEMVER_SPEC_VERSION:Wo,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2};const Zo=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...s)=>console.error("SEMVER",...s):()=>{};var tt=Zo;(function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:n}=et,o=tt;e=s.exports={};const i=e.re=[],c=e.safeRe=[],a=e.src=[],l=e.safeSrc=[],u=e.t={};let d=0;const p="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",n],[p,r]],C=j=>{for(const[N,U]of f)j=j.split(`${N}*`).join(`${N}{0,${U}}`).split(`${N}+`).join(`${N}{1,${U}}`);return j},w=(j,N,U)=>{const A=C(N),H=d++;o(j,H,N),u[j]=H,a[H]=N,l[H]=A,i[H]=new RegExp(N,U?"g":void 0),c[H]=new RegExp(A,U?"g":void 0)};w("NUMERICIDENTIFIER","0|[1-9]\\d*"),w("NUMERICIDENTIFIERLOOSE","\\d+"),w("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),w("MAINVERSION",`(${a[u.NUMERICIDENTIFIER]})\\.(${a[u.NUMERICIDENTIFIER]})\\.(${a[u.NUMERICIDENTIFIER]})`),w("MAINVERSIONLOOSE",`(${a[u.NUMERICIDENTIFIERLOOSE]})\\.(${a[u.NUMERICIDENTIFIERLOOSE]})\\.(${a[u.NUMERICIDENTIFIERLOOSE]})`),w("PRERELEASEIDENTIFIER",`(?:${a[u.NUMERICIDENTIFIER]}|${a[u.NONNUMERICIDENTIFIER]})`),w("PRERELEASEIDENTIFIERLOOSE",`(?:${a[u.NUMERICIDENTIFIERLOOSE]}|${a[u.NONNUMERICIDENTIFIER]})`),w("PRERELEASE",`(?:-(${a[u.PRERELEASEIDENTIFIER]}(?:\\.${a[u.PRERELEASEIDENTIFIER]})*))`),w("PRERELEASELOOSE",`(?:-?(${a[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${a[u.PRERELEASEIDENTIFIERLOOSE]})*))`),w("BUILDIDENTIFIER",`${p}+`),w("BUILD",`(?:\\+(${a[u.BUILDIDENTIFIER]}(?:\\.${a[u.BUILDIDENTIFIER]})*))`),w("FULLPLAIN",`v?${a[u.MAINVERSION]}${a[u.PRERELEASE]}?${a[u.BUILD]}?`),w("FULL",`^${a[u.FULLPLAIN]}$`),w("LOOSEPLAIN",`[v=\\s]*${a[u.MAINVERSIONLOOSE]}${a[u.PRERELEASELOOSE]}?${a[u.BUILD]}?`),w("LOOSE",`^${a[u.LOOSEPLAIN]}$`),w("GTLT","((?:<|>)?=?)"),w("XRANGEIDENTIFIERLOOSE",`${a[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),w("XRANGEIDENTIFIER",`${a[u.NUMERICIDENTIFIER]}|x|X|\\*`),w("XRANGEPLAIN",`[v=\\s]*(${a[u.XRANGEIDENTIFIER]})(?:\\.(${a[u.XRANGEIDENTIFIER]})(?:\\.(${a[u.XRANGEIDENTIFIER]})(?:${a[u.PRERELEASE]})?${a[u.BUILD]}?)?)?`),w("XRANGEPLAINLOOSE",`[v=\\s]*(${a[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[u.XRANGEIDENTIFIERLOOSE]})(?:${a[u.PRERELEASELOOSE]})?${a[u.BUILD]}?)?)?`),w("XRANGE",`^${a[u.GTLT]}\\s*${a[u.XRANGEPLAIN]}$`),w("XRANGELOOSE",`^${a[u.GTLT]}\\s*${a[u.XRANGEPLAINLOOSE]}$`),w("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),w("COERCE",`${a[u.COERCEPLAIN]}(?:$|[^\\d])`),w("COERCEFULL",a[u.COERCEPLAIN]+`(?:${a[u.PRERELEASE]})?(?:${a[u.BUILD]})?(?:$|[^\\d])`),w("COERCERTL",a[u.COERCE],!0),w("COERCERTLFULL",a[u.COERCEFULL],!0),w("LONETILDE","(?:~>?)"),w("TILDETRIM",`(\\s*)${a[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",w("TILDE",`^${a[u.LONETILDE]}${a[u.XRANGEPLAIN]}$`),w("TILDELOOSE",`^${a[u.LONETILDE]}${a[u.XRANGEPLAINLOOSE]}$`),w("LONECARET","(?:\\^)"),w("CARETTRIM",`(\\s*)${a[u.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",w("CARET",`^${a[u.LONECARET]}${a[u.XRANGEPLAIN]}$`),w("CARETLOOSE",`^${a[u.LONECARET]}${a[u.XRANGEPLAINLOOSE]}$`),w("COMPARATORLOOSE",`^${a[u.GTLT]}\\s*(${a[u.LOOSEPLAIN]})$|^$`),w("COMPARATOR",`^${a[u.GTLT]}\\s*(${a[u.FULLPLAIN]})$|^$`),w("COMPARATORTRIM",`(\\s*)${a[u.GTLT]}\\s*(${a[u.LOOSEPLAIN]}|${a[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",w("HYPHENRANGE",`^\\s*(${a[u.XRANGEPLAIN]})\\s+-\\s+(${a[u.XRANGEPLAIN]})\\s*$`),w("HYPHENRANGELOOSE",`^\\s*(${a[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${a[u.XRANGEPLAINLOOSE]})\\s*$`),w("STAR","(<|>)?=?\\s*\\*"),w("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),w("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(Pt,Pt.exports);var Le=Pt.exports;const ei=Object.freeze({loose:!0}),ti=Object.freeze({}),ri=s=>s?typeof s!="object"?ei:s:ti;var jt=ri;const mr=/^[0-9]+$/,vs=(s,e)=>{const t=mr.test(s),r=mr.test(e);return t&&r&&(s=+s,e=+e),s===e?0:t&&!r?-1:r&&!t?1:s<e?-1:1},si=(s,e)=>vs(e,s);var ys={compareIdentifiers:vs,rcompareIdentifiers:si};const Ue=tt,{MAX_LENGTH:vr,MAX_SAFE_INTEGER:Ge}=et,{safeRe:yr,safeSrc:wr,t:Me}=Le,ni=jt,{compareIdentifiers:ge}=ys;let oi=class le{constructor(e,t){if(t=ni(t),e instanceof le){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>vr)throw new TypeError(`version is longer than ${vr} characters`);Ue("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const r=e.trim().match(t.loose?yr[Me.LOOSE]:yr[Me.FULL]);if(!r)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>Ge||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Ge||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Ge||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(n=>{if(/^[0-9]+$/.test(n)){const o=+n;if(o>=0&&o<Ge)return o}return n}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(Ue("SemVer.compare",this.version,this.options,e),!(e instanceof le)){if(typeof e=="string"&&e===this.version)return 0;e=new le(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof le||(e=new le(e,this.options)),ge(this.major,e.major)||ge(this.minor,e.minor)||ge(this.patch,e.patch)}comparePre(e){if(e instanceof le||(e=new le(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{const r=this.prerelease[t],n=e.prerelease[t];if(Ue("prerelease compare",t,r,n),r===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(r===void 0)return-1;if(r===n)continue;return ge(r,n)}while(++t)}compareBuild(e){e instanceof le||(e=new le(e,this.options));let t=0;do{const r=this.build[t],n=e.build[t];if(Ue("build compare",t,r,n),r===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(r===void 0)return-1;if(r===n)continue;return ge(r,n)}while(++t)}inc(e,t,r){if(e.startsWith("pre")){if(!t&&r===!1)throw new Error("invalid increment argument: identifier is empty");if(t){const n=new RegExp(`^${this.options.loose?wr[Me.PRERELEASELOOSE]:wr[Me.PRERELEASE]}$`),o=`-${t}`.match(n);if(!o||o[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,r),this.inc("pre",t,r);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const n=Number(r)?1:0;if(this.prerelease.length===0)this.prerelease=[n];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(t===this.prerelease.join(".")&&r===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(n)}}if(t){let o=[t,n];r===!1&&(o=[t]),ge(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=o):this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};var X=oi;const br=X,ii=(s,e,t=!1)=>{if(s instanceof br)return s;try{return new br(s,e)}catch(r){if(!t)return null;throw r}};var we=ii;const ai=we,ci=(s,e)=>{const t=ai(s,e);return t?t.version:null};var li=ci;const ui=we,di=(s,e)=>{const t=ui(s.trim().replace(/^[=v]+/,""),e);return t?t.version:null};var pi=di;const Sr=X,fi=(s,e,t,r,n)=>{typeof t=="string"&&(n=r,r=t,t=void 0);try{return new Sr(s instanceof Sr?s.version:s,t).inc(e,r,n).version}catch{return null}};var hi=fi;const Pr=we,gi=(s,e)=>{const t=Pr(s,null,!0),r=Pr(e,null,!0),n=t.compare(r);if(n===0)return null;const o=n>0,i=o?t:r,c=o?r:t,a=!!i.prerelease.length;if(!!c.prerelease.length&&!a){if(!c.patch&&!c.minor)return"major";if(c.compareMain(i)===0)return c.minor&&!c.patch?"minor":"patch"}const u=a?"pre":"";return t.major!==r.major?u+"major":t.minor!==r.minor?u+"minor":t.patch!==r.patch?u+"patch":"prerelease"};var mi=gi;const vi=X,yi=(s,e)=>new vi(s,e).major;var wi=yi;const bi=X,Si=(s,e)=>new bi(s,e).minor;var Pi=Si;const Ri=X,Ei=(s,e)=>new Ri(s,e).patch;var Ci=Ei;const ki=we,Oi=(s,e)=>{const t=ki(s,e);return t&&t.prerelease.length?t.prerelease:null};var Ti=Oi;const Rr=X,$i=(s,e,t)=>new Rr(s,t).compare(new Rr(e,t));var ae=$i;const Ii=ae,Fi=(s,e,t)=>Ii(e,s,t);var Ai=Fi;const Li=ae,Di=(s,e)=>Li(s,e,!0);var Ni=Di;const Er=X,Bi=(s,e,t)=>{const r=new Er(s,t),n=new Er(e,t);return r.compare(n)||r.compareBuild(n)};var Vt=Bi;const ji=Vt,Vi=(s,e)=>s.sort((t,r)=>ji(t,r,e));var xi=Vi;const Ui=Vt,Gi=(s,e)=>s.sort((t,r)=>Ui(r,t,e));var Mi=Gi;const Ji=ae,_i=(s,e,t)=>Ji(s,e,t)>0;var rt=_i;const Ki=ae,Hi=(s,e,t)=>Ki(s,e,t)<0;var xt=Hi;const qi=ae,Wi=(s,e,t)=>qi(s,e,t)===0;var ws=Wi;const zi=ae,Xi=(s,e,t)=>zi(s,e,t)!==0;var bs=Xi;const Yi=ae,Qi=(s,e,t)=>Yi(s,e,t)>=0;var Ut=Qi;const Zi=ae,ea=(s,e,t)=>Zi(s,e,t)<=0;var Gt=ea;const ta=ws,ra=bs,sa=rt,na=Ut,oa=xt,ia=Gt,aa=(s,e,t,r)=>{switch(e){case"===":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s===t;case"!==":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s!==t;case"":case"=":case"==":return ta(s,t,r);case"!=":return ra(s,t,r);case">":return sa(s,t,r);case">=":return na(s,t,r);case"<":return oa(s,t,r);case"<=":return ia(s,t,r);default:throw new TypeError(`Invalid operator: ${e}`)}};var Ss=aa;const ca=X,la=we,{safeRe:Je,t:_e}=Le,ua=(s,e)=>{if(s instanceof ca)return s;if(typeof s=="number"&&(s=String(s)),typeof s!="string")return null;e=e||{};let t=null;if(!e.rtl)t=s.match(e.includePrerelease?Je[_e.COERCEFULL]:Je[_e.COERCE]);else{const a=e.includePrerelease?Je[_e.COERCERTLFULL]:Je[_e.COERCERTL];let l;for(;(l=a.exec(s))&&(!t||t.index+t[0].length!==s.length);)(!t||l.index+l[0].length!==t.index+t[0].length)&&(t=l),a.lastIndex=l.index+l[1].length+l[2].length;a.lastIndex=-1}if(t===null)return null;const r=t[2],n=t[3]||"0",o=t[4]||"0",i=e.includePrerelease&&t[5]?`-${t[5]}`:"",c=e.includePrerelease&&t[6]?`+${t[6]}`:"";return la(`${r}.${n}.${o}${i}${c}`,e)};var da=ua;class pa{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 n=this.map.keys().next().value;this.delete(n)}this.map.set(e,t)}return this}}var fa=pa,ct,Cr;function ce(){if(Cr)return ct;Cr=1;const s=/\s+/g;class e{constructor(m,R){if(R=n(R),m instanceof e)return m.loose===!!R.loose&&m.includePrerelease===!!R.includePrerelease?m:new e(m.raw,R);if(m instanceof o)return this.raw=m.value,this.set=[[m]],this.formatted=void 0,this;if(this.options=R,this.loose=!!R.loose,this.includePrerelease=!!R.includePrerelease,this.raw=m.trim().replace(s," "),this.set=this.raw.split("||").map(g=>this.parseRange(g.trim())).filter(g=>g.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const g=this.set[0];if(this.set=this.set.filter(b=>!w(b[0])),this.set.length===0)this.set=[g];else if(this.set.length>1){for(const b of this.set)if(b.length===1&&j(b[0])){this.set=[b];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let m=0;m<this.set.length;m++){m>0&&(this.formatted+="||");const R=this.set[m];for(let g=0;g<R.length;g++)g>0&&(this.formatted+=" "),this.formatted+=R[g].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(m){const g=((this.options.includePrerelease&&f)|(this.options.loose&&C))+":"+m,b=r.get(g);if(b)return b;const v=this.options.loose,P=v?a[l.HYPHENRANGELOOSE]:a[l.HYPHENRANGE];m=m.replace(P,M(this.options.includePrerelease)),i("hyphen replace",m),m=m.replace(a[l.COMPARATORTRIM],u),i("comparator trim",m),m=m.replace(a[l.TILDETRIM],d),i("tilde trim",m),m=m.replace(a[l.CARETTRIM],p),i("caret trim",m);let T=m.split(" ").map(D=>U(D,this.options)).join(" ").split(/\s+/).map(D=>se(D,this.options));v&&(T=T.filter(D=>(i("loose invalid filter",D,this.options),!!D.match(a[l.COMPARATORLOOSE])))),i("range list",T);const k=new Map,L=T.map(D=>new o(D,this.options));for(const D of L){if(w(D))return[D];k.set(D.value,D)}k.size>1&&k.has("")&&k.delete("");const G=[...k.values()];return r.set(g,G),G}intersects(m,R){if(!(m instanceof e))throw new TypeError("a Range is required");return this.set.some(g=>N(g,R)&&m.set.some(b=>N(b,R)&&g.every(v=>b.every(P=>v.intersects(P,R)))))}test(m){if(!m)return!1;if(typeof m=="string")try{m=new c(m,this.options)}catch{return!1}for(let R=0;R<this.set.length;R++)if(q(this.set[R],m,this.options))return!0;return!1}}ct=e;const t=fa,r=new t,n=jt,o=st(),i=tt,c=X,{safeRe:a,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:p}=Le,{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:C}=et,w=y=>y.value==="<0.0.0-0",j=y=>y.value==="",N=(y,m)=>{let R=!0;const g=y.slice();let b=g.pop();for(;R&&g.length;)R=g.every(v=>b.intersects(v,m)),b=g.pop();return R},U=(y,m)=>(i("comp",y,m),y=B(y,m),i("caret",y),y=H(y,m),i("tildes",y),y=te(y,m),i("xrange",y),y=re(y,m),i("stars",y),y),A=y=>!y||y.toLowerCase()==="x"||y==="*",H=(y,m)=>y.trim().split(/\s+/).map(R=>he(R,m)).join(" "),he=(y,m)=>{const R=m.loose?a[l.TILDELOOSE]:a[l.TILDE];return y.replace(R,(g,b,v,P,T)=>{i("tilde",y,g,b,v,P,T);let k;return A(b)?k="":A(v)?k=`>=${b}.0.0 <${+b+1}.0.0-0`:A(P)?k=`>=${b}.${v}.0 <${b}.${+v+1}.0-0`:T?(i("replaceTilde pr",T),k=`>=${b}.${v}.${P}-${T} <${b}.${+v+1}.0-0`):k=`>=${b}.${v}.${P} <${b}.${+v+1}.0-0`,i("tilde return",k),k})},B=(y,m)=>y.trim().split(/\s+/).map(R=>Y(R,m)).join(" "),Y=(y,m)=>{i("caret",y,m);const R=m.loose?a[l.CARETLOOSE]:a[l.CARET],g=m.includePrerelease?"-0":"";return y.replace(R,(b,v,P,T,k)=>{i("caret",y,b,v,P,T,k);let L;return A(v)?L="":A(P)?L=`>=${v}.0.0${g} <${+v+1}.0.0-0`:A(T)?v==="0"?L=`>=${v}.${P}.0${g} <${v}.${+P+1}.0-0`:L=`>=${v}.${P}.0${g} <${+v+1}.0.0-0`:k?(i("replaceCaret pr",k),v==="0"?P==="0"?L=`>=${v}.${P}.${T}-${k} <${v}.${P}.${+T+1}-0`:L=`>=${v}.${P}.${T}-${k} <${v}.${+P+1}.0-0`:L=`>=${v}.${P}.${T}-${k} <${+v+1}.0.0-0`):(i("no pr"),v==="0"?P==="0"?L=`>=${v}.${P}.${T}${g} <${v}.${P}.${+T+1}-0`:L=`>=${v}.${P}.${T}${g} <${v}.${+P+1}.0-0`:L=`>=${v}.${P}.${T} <${+v+1}.0.0-0`),i("caret return",L),L})},te=(y,m)=>(i("replaceXRanges",y,m),y.split(/\s+/).map(R=>K(R,m)).join(" ")),K=(y,m)=>{y=y.trim();const R=m.loose?a[l.XRANGELOOSE]:a[l.XRANGE];return y.replace(R,(g,b,v,P,T,k)=>{i("xRange",y,g,b,v,P,T,k);const L=A(v),G=L||A(P),D=G||A(T),ue=D;return b==="="&&ue&&(b=""),k=m.includePrerelease?"-0":"",L?b===">"||b==="<"?g="<0.0.0-0":g="*":b&&ue?(G&&(P=0),T=0,b===">"?(b=">=",G?(v=+v+1,P=0,T=0):(P=+P+1,T=0)):b==="<="&&(b="<",G?v=+v+1:P=+P+1),b==="<"&&(k="-0"),g=`${b+v}.${P}.${T}${k}`):G?g=`>=${v}.0.0${k} <${+v+1}.0.0-0`:D&&(g=`>=${v}.${P}.0${k} <${v}.${+P+1}.0-0`),i("xRange return",g),g})},re=(y,m)=>(i("replaceStars",y,m),y.trim().replace(a[l.STAR],"")),se=(y,m)=>(i("replaceGTE0",y,m),y.trim().replace(a[m.includePrerelease?l.GTE0PRE:l.GTE0],"")),M=y=>(m,R,g,b,v,P,T,k,L,G,D,ue)=>(A(g)?R="":A(b)?R=`>=${g}.0.0${y?"-0":""}`:A(v)?R=`>=${g}.${b}.0${y?"-0":""}`:P?R=`>=${R}`:R=`>=${R}${y?"-0":""}`,A(L)?k="":A(G)?k=`<${+L+1}.0.0-0`:A(D)?k=`<${L}.${+G+1}.0-0`:ue?k=`<=${L}.${G}.${D}-${ue}`:y?k=`<${L}.${G}.${+D+1}-0`:k=`<=${k}`,`${R} ${k}`.trim()),q=(y,m,R)=>{for(let g=0;g<y.length;g++)if(!y[g].test(m))return!1;if(m.prerelease.length&&!R.includePrerelease){for(let g=0;g<y.length;g++)if(i(y[g].semver),y[g].semver!==o.ANY&&y[g].semver.prerelease.length>0){const b=y[g].semver;if(b.major===m.major&&b.minor===m.minor&&b.patch===m.patch)return!0}return!1}return!0};return ct}var lt,kr;function st(){if(kr)return lt;kr=1;const s=Symbol("SemVer ANY");class e{static get ANY(){return s}constructor(u,d){if(d=t(d),u instanceof e){if(u.loose===!!d.loose)return u;u=u.value}u=u.trim().split(/\s+/).join(" "),i("comparator",u,d),this.options=d,this.loose=!!d.loose,this.parse(u),this.semver===s?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(u){const d=this.options.loose?r[n.COMPARATORLOOSE]:r[n.COMPARATOR],p=u.match(d);if(!p)throw new TypeError(`Invalid comparator: ${u}`);this.operator=p[1]!==void 0?p[1]:"",this.operator==="="&&(this.operator=""),p[2]?this.semver=new c(p[2],this.options.loose):this.semver=s}toString(){return this.value}test(u){if(i("Comparator.test",u,this.options.loose),this.semver===s||u===s)return!0;if(typeof u=="string")try{u=new c(u,this.options)}catch{return!1}return o(u,this.operator,this.semver,this.options)}intersects(u,d){if(!(u instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new a(u.value,d).test(this.value):u.operator===""?u.value===""?!0:new a(this.value,d).test(u.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||u.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||u.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&u.operator.startsWith(">")||this.operator.startsWith("<")&&u.operator.startsWith("<")||this.semver.version===u.semver.version&&this.operator.includes("=")&&u.operator.includes("=")||o(this.semver,"<",u.semver,d)&&this.operator.startsWith(">")&&u.operator.startsWith("<")||o(this.semver,">",u.semver,d)&&this.operator.startsWith("<")&&u.operator.startsWith(">")))}}lt=e;const t=jt,{safeRe:r,t:n}=Le,o=Ss,i=tt,c=X,a=ce();return lt}const ha=ce(),ga=(s,e,t)=>{try{e=new ha(e,t)}catch{return!1}return e.test(s)};var nt=ga;const ma=ce(),va=(s,e)=>new ma(s,e).set.map(t=>t.map(r=>r.value).join(" ").trim().split(" "));var ya=va;const wa=X,ba=ce(),Sa=(s,e,t)=>{let r=null,n=null,o=null;try{o=new ba(e,t)}catch{return null}return s.forEach(i=>{o.test(i)&&(!r||n.compare(i)===-1)&&(r=i,n=new wa(r,t))}),r};var Pa=Sa;const Ra=X,Ea=ce(),Ca=(s,e,t)=>{let r=null,n=null,o=null;try{o=new Ea(e,t)}catch{return null}return s.forEach(i=>{o.test(i)&&(!r||n.compare(i)===1)&&(r=i,n=new Ra(r,t))}),r};var ka=Ca;const ut=X,Oa=ce(),Or=rt,Ta=(s,e)=>{s=new Oa(s,e);let t=new ut("0.0.0");if(s.test(t)||(t=new ut("0.0.0-0"),s.test(t)))return t;t=null;for(let r=0;r<s.set.length;++r){const n=s.set[r];let o=null;n.forEach(i=>{const c=new ut(i.semver.version);switch(i.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!o||Or(c,o))&&(o=c);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),o&&(!t||Or(t,o))&&(t=o)}return t&&s.test(t)?t:null};var $a=Ta;const Ia=ce(),Fa=(s,e)=>{try{return new Ia(s,e).range||"*"}catch{return null}};var Aa=Fa;const La=X,Ps=st(),{ANY:Da}=Ps,Na=ce(),Ba=nt,Tr=rt,$r=xt,ja=Gt,Va=Ut,xa=(s,e,t,r)=>{s=new La(s,r),e=new Na(e,r);let n,o,i,c,a;switch(t){case">":n=Tr,o=ja,i=$r,c=">",a=">=";break;case"<":n=$r,o=Va,i=Tr,c="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Ba(s,e,r))return!1;for(let l=0;l<e.set.length;++l){const u=e.set[l];let d=null,p=null;if(u.forEach(f=>{f.semver===Da&&(f=new Ps(">=0.0.0")),d=d||f,p=p||f,n(f.semver,d.semver,r)?d=f:i(f.semver,p.semver,r)&&(p=f)}),d.operator===c||d.operator===a||(!p.operator||p.operator===c)&&o(s,p.semver))return!1;if(p.operator===a&&i(s,p.semver))return!1}return!0};var Mt=xa;const Ua=Mt,Ga=(s,e,t)=>Ua(s,e,">",t);var Ma=Ga;const Ja=Mt,_a=(s,e,t)=>Ja(s,e,"<",t);var Ka=_a;const Ir=ce(),Ha=(s,e,t)=>(s=new Ir(s,t),e=new Ir(e,t),s.intersects(e,t));var qa=Ha;const Wa=nt,za=ae;var Xa=(s,e,t)=>{const r=[];let n=null,o=null;const i=s.sort((u,d)=>za(u,d,t));for(const u of i)Wa(u,e,t)?(o=u,n||(n=u)):(o&&r.push([n,o]),o=null,n=null);n&&r.push([n,null]);const c=[];for(const[u,d]of r)u===d?c.push(u):!d&&u===i[0]?c.push("*"):d?u===i[0]?c.push(`<=${d}`):c.push(`${u} - ${d}`):c.push(`>=${u}`);const a=c.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return a.length<l.length?a:e};const Fr=ce(),Jt=st(),{ANY:dt}=Jt,Se=nt,_t=ae,Ya=(s,e,t={})=>{if(s===e)return!0;s=new Fr(s,t),e=new Fr(e,t);let r=!1;e:for(const n of s.set){for(const o of e.set){const i=Za(n,o,t);if(r=r||i!==null,i)continue e}if(r)return!1}return!0},Qa=[new Jt(">=0.0.0-0")],Ar=[new Jt(">=0.0.0")],Za=(s,e,t)=>{if(s===e)return!0;if(s.length===1&&s[0].semver===dt){if(e.length===1&&e[0].semver===dt)return!0;t.includePrerelease?s=Qa:s=Ar}if(e.length===1&&e[0].semver===dt){if(t.includePrerelease)return!0;e=Ar}const r=new Set;let n,o;for(const f of s)f.operator===">"||f.operator===">="?n=Lr(n,f,t):f.operator==="<"||f.operator==="<="?o=Dr(o,f,t):r.add(f.semver);if(r.size>1)return null;let i;if(n&&o){if(i=_t(n.semver,o.semver,t),i>0)return null;if(i===0&&(n.operator!==">="||o.operator!=="<="))return null}for(const f of r){if(n&&!Se(f,String(n),t)||o&&!Se(f,String(o),t))return null;for(const C of e)if(!Se(f,String(C),t))return!1;return!0}let c,a,l,u,d=o&&!t.includePrerelease&&o.semver.prerelease.length?o.semver:!1,p=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1;d&&d.prerelease.length===1&&o.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(const f of e){if(u=u||f.operator===">"||f.operator===">=",l=l||f.operator==="<"||f.operator==="<=",n){if(p&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===p.major&&f.semver.minor===p.minor&&f.semver.patch===p.patch&&(p=!1),f.operator===">"||f.operator===">="){if(c=Lr(n,f,t),c===f&&c!==n)return!1}else if(n.operator===">="&&!Se(n.semver,String(f),t))return!1}if(o){if(d&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===d.major&&f.semver.minor===d.minor&&f.semver.patch===d.patch&&(d=!1),f.operator==="<"||f.operator==="<="){if(a=Dr(o,f,t),a===f&&a!==o)return!1}else if(o.operator==="<="&&!Se(o.semver,String(f),t))return!1}if(!f.operator&&(o||n)&&i!==0)return!1}return!(n&&l&&!o&&i!==0||o&&u&&!n&&i!==0||p||d)},Lr=(s,e,t)=>{if(!s)return e;const r=_t(s.semver,e.semver,t);return r>0?s:r<0||e.operator===">"&&s.operator===">="?e:s},Dr=(s,e,t)=>{if(!s)return e;const r=_t(s.semver,e.semver,t);return r<0?s:r>0||e.operator==="<"&&s.operator==="<="?e:s};var ec=Ya;const pt=Le,Nr=et,tc=X,Br=ys,rc=we,sc=li,nc=pi,oc=hi,ic=mi,ac=wi,cc=Pi,lc=Ci,uc=Ti,dc=ae,pc=Ai,fc=Ni,hc=Vt,gc=xi,mc=Mi,vc=rt,yc=xt,wc=ws,bc=bs,Sc=Ut,Pc=Gt,Rc=Ss,Ec=da,Cc=st(),kc=ce(),Oc=nt,Tc=ya,$c=Pa,Ic=ka,Fc=$a,Ac=Aa,Lc=Mt,Dc=Ma,Nc=Ka,Bc=qa,jc=Xa,Vc=ec;var xc={parse:rc,valid:sc,clean:nc,inc:oc,diff:ic,major:ac,minor:cc,patch:lc,prerelease:uc,compare:dc,rcompare:pc,compareLoose:fc,compareBuild:hc,sort:gc,rsort:mc,gt:vc,lt:yc,eq:wc,neq:bc,gte:Sc,lte:Pc,cmp:Rc,coerce:Ec,Comparator:Cc,Range:kc,satisfies:Oc,toComparators:Tc,maxSatisfying:$c,minSatisfying:Ic,minVersion:Fc,validRange:Ac,outside:Lc,gtr:Dc,ltr:Nc,intersects:Bc,simplifyRange:jc,subset:Vc,SemVer:tc,re:pt.re,src:pt.src,tokens:pt.t,SEMVER_SPEC_VERSION:Nr.SEMVER_SPEC_VERSION,RELEASE_TYPES:Nr.RELEASE_TYPES,compareIdentifiers:Br.compareIdentifiers,rcompareIdentifiers:Br.rcompareIdentifiers};const Uc=qo(xc),Gc={minDelay:1500},Mc="__no_updates__";class Jc extends V.PollComputablePool{constructor(t,r,n={}){super({...n,...Gc},r);S(this,"http");S(this,"preferredUpdateChannel");this.registryProvider=t,this.http=n.http,this.preferredUpdateChannel=n.preferredUpdateChannel}getKey(t){switch(t.currentSpec.type){case"dev-v1":return`dev_1_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"dev-v2":return`dev_2_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"from-registry-v2":return`from_registry_v2_${x(t)}`;default:return Mc}}async readValue(t){var r,n;try{const o=t.currentSpec;switch(o.type){case"dev-v1":try{const i=await Tt(o.folder);return i===o.mtime?{suggestions:[]}:{mainSuggestion:{...o,mtime:i},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"dev-v2":try{const i=await z.tryLoadPackDescription(o.folder,this.logger);if(i===void 0)return{suggestions:[]};const c=await Xe(i);return c===o.mtime?{suggestions:[]}:{mainSuggestion:{...o,mtime:c},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:i,skipVersion:c}=t.settings;if(i==="patch")return{suggestions:[]};const a=this.registryProvider.getRegistry(o.registryUrl);let l=this.preferredUpdateChannel;if(l===void 0)if(o.channel===void 0)if(await a.getLatestOverview(o.id,W.StableChannel))l=W.StableChannel;else{if(await a.getLatestOverview(o.id,W.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${W.blockPackIdToString(o.id)}`),{suggestions:[]};l=W.AnyChannel}else l=o.channel;const u=await a.getUpdateSuggestions(o.id,l);if(u===void 0||u.length===0)return{suggestions:[]};u.reverse();let d;switch(i){case void 0:d=u[0].update;break;case"major":d=(r=u.find(C=>C.type!=="major"))==null?void 0:r.update;break;case"minor":d=(n=u.find(C=>C.type==="patch"))==null?void 0:n.update;break}const p=u.map(({type:C,update:w})=>({type:C,update:{...o,id:{...o.id,version:w}}}));if(d===void 0)return{suggestions:p};if(c!==void 0&&Uc.lte(d,c))return{suggestions:p};const f={...o,id:{...o.id,version:d}};return(async()=>{try{await a.getComponents(f.id)}catch(C){this.logger.warn(C)}})(),{suggestions:p,mainSuggestion:f}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(o){return this.logger.warn(o),{suggestions:[]}}}resultsEqual(t,r){return x(t)===x(r)}}class jr{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),(n=>n!=null&&typeof n[Symbol.dispose]=="function")(t.resource)&&t.resource[Symbol.dispose]())}acquire(e){const t=this.calculateParamsKey(e);let r=this.resources.get(t);r===void 0&&(r={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,r)),r.refCount++;let n=!1;return{resource:r.resource,key:t,unref:()=>{n||(r.refCount--,n=!0,this.check(t))}}}getByKey(e){if(!this.resources.has(e))throw new Error(`resource not found, key = ${e}`);return this.resources.get(e).resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}let Pe;function de(){return Pe||(Pe={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0,dumpInitialTreeState:process.env.MI_DUMP_INITIAL_TREE_STATE!==void 0},process.env.MI_LOG_TREE_STAT&&(Pe.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),Pe)}function Oe(s){return String(s.id)}const _c=["Int","Long","Float","Double","String","Bytes"];function ft(s){const e=[],t=[];for(const r of s)r.type==="bySingleColumn"?(e.push(r),t.push({...r,type:"bySingleColumnV2"})):t.push(r);if(e.length>0){const r=JSON.stringify(e);console.warn(`type overriten from 'bySingleColumn' to 'bySingleColumnV2' for filters: ${r}`)}return t}const Re=(s,e)=>typeof e=="bigint"?e.toString():e;class Kc{constructor(e,t,r,n,o){S(this,"pFrame");S(this,"blobIdToResource",new Map);S(this,"blobHandleComputables",new Map);S(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.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),r=this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);return await this.blobContentCache.forceFetch(r)}catch(t){const r=JSON.stringify(t);throw console.log(`resolveBlobContent catched error: ${r}`),t}});this.blobDriver=e,this.logger=t,this.spillPath=r,this.blobContentCache=n;const i=(a,l)=>this.logger[a](l);for(const a of o)for(const l of Bn(a.data))this.blobIdToResource.set(Oe(l),l);const c=[...new Map(o.map(a=>({...a,data:jn(a.data,Oe)})).map(a=>[x(a),a])).values()];try{const a=new Ds.PFrame(this.spillPath,de().logPFrameRequests?i:void 0);a.setDataSource(this);for(const l of c)a.addColumnSpec(l.id,l.spec),a.setColumnData(l.id,l.data);this.pFrame=a}catch(a){throw new Error(`Rust PFrame creation failed, columns: ${JSON.stringify(c)}, error: ${a}`)}}getOrCreateComputableForBlob(e){let t=this.blobHandleComputables.get(e);if(t!==void 0)return t;const r=this.blobIdToResource.get(e);if(r===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(r).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}[Symbol.dispose](){for(const e of this.blobHandleComputables.values())e.resetState();this.pFrame.dispose()}}class Hc{constructor(e){this.table=e}[Symbol.dispose](){this.table.then(e=>e.dispose())}}class Kt{constructor(e,t,r){S(this,"pFrames");S(this,"pTables");S(this,"concurrencyLimiter");this.blobDriver=e,this.logger=t,this.spillPath=r;const n=new Et.LRUCache({maxSize:1e9,fetchMethod:async i=>await Gr.readFile(i),sizeCalculation:i=>i.length}),o=new E.ConcurrencyLimitingExecutor(4);this.concurrencyLimiter=o,this.pFrames=new class extends jr{constructor(i,c,a){super(),this.blobDriver=i,this.logger=c,this.spillPath=a}createNewResource(i){return de().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(i)}): ${JSON.stringify(i,Re)}`),new Kc(this.blobDriver,this.logger,this.spillPath,n,i)}calculateParamsKey(i){return Wc(i)}}(this.blobDriver,this.logger,this.spillPath),this.pTables=new class extends jr{constructor(i){super(),this.pFrames=i}createNewResource(i){const c=i.pFrameHandle;de().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(i)}): ${JSON.stringify(i,Re)}`);const a=o.run(async()=>await this.pFrames.getByKey(c).pFrame.createTable({src:Te(i.def.src),filters:ft(i.def.filters)},i.signal)).then(async l=>{if(i.def.sorting.length===0)return l;try{return o.run(async()=>await l.sort(i.def.sorting,i.signal))}finally{l.dispose()}});return new Hc(a)}calculateParamsKey(i){return qc(i)}}(this.pFrames)}static async init(e,t,r){const n=Bs.resolve(r);return await E.emptyDir(n),new Kt(e,t,n)}createPFrame(e,t){const r=e.filter(o=>_c.find(i=>i===o.spec.valueType)).map(o=>F.mapPObjectData(o,i=>He.isPlTreeNodeAccessor(i)?Jn(i):F.isDataInfo(i)?F.mapDataInfo(i,c=>c.resourceInfo):_n(o.spec,i))),n=this.pFrames.acquire(r);return t.addOnDestroy(n.unref),n.key}createPTable(e,t,r){const n=this.createPFrame(F.extractAllColumns(e.src),t),o=F.mapPTableDef(e,c=>c.id),i=this.pTables.acquire({def:o,pFrameHandle:n,signal:r});return de().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${n}; pTableHandle = ${JSON.stringify(i)}): ${JSON.stringify(F.mapPTableDef(e,c=>c.spec),Re)}`),t.addOnDestroy(i.unref),i.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:[...new Map(t.compatibleWith.map(o=>[x(o),o])).values()],qualifications:[]}]:[]};return{hits:(await this.pFrames.getByKey(e).pFrame.findColumns(r)).hits.filter(o=>o.mappingVariants.length===0||o.mappingVariants.some(i=>i.qualifications.forHit.length===0&&i.qualifications.forQueries.every(c=>c.length===0))).map(o=>o.hit)}}async getColumnSpec(e,t){return await this.pFrames.getByKey(e).pFrame.getColumnSpec(t)}async listColumns(e){return await this.pFrames.getByKey(e).pFrame.listColumns()}async calculateTableData(e,t,r){return de().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,Re)}`),await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.createTable({src:Te(t.src),filters:ft(t.filters)},r)).then(async n=>{if(t.sorting.length===0)return n;try{return await this.concurrencyLimiter.run(async()=>await n.sort(t.sorting,r))}finally{n.dispose()}}).then(async n=>{try{const o=n.getSpec(),i=await this.concurrencyLimiter.run(async()=>await n.getData([...o.keys()]));return o.map((c,a)=>({spec:c,data:i[a]}))}finally{n.dispose()}})}async getUniqueValues(e,t,r){return de().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,Re)}`),await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.getUniqueValues({...t,filters:ft(t.filters)},r))}async getShape(e){return(await this.pTables.getByKey(e).table).getShape()}async getSpec(e){return(await this.pTables.getByKey(e).table).getSpec()}async getData(e,t,r){const n=await this.pTables.getByKey(e).table;return await this.concurrencyLimiter.run(async()=>await n.getData(t,r))}}function Te(s){switch(s.type){case"column":return{type:"column",columnId:s.column};case"slicedColumn":return{type:"slicedColumn",columnId:s.column,newId:s.newId,axisFilters:s.axisFilters};case"inner":case"full":return{type:s.type,entries:s.entries.map(e=>Te(e))};case"outer":return{type:"outer",primary:Te(s.primary),secondary:s.secondary.map(e=>Te(e))};default:E.assertNever(s)}}function qc(s){const e=ee.createHash("sha256");return e.update(x(s)),e.digest().toString("hex")}function Wc(s){const e=[...s].map(r=>F.mapPObjectData(r,n=>{let o;const i=n.type;switch(i){case"Json":o={type:n.type,keyLength:n.keyLength,payload:Object.entries(n.data).map(([c,a])=>({key:c,value:a}))};break;case"JsonPartitioned":o={type:n.type,keyLength:n.partitionKeyLength,payload:Object.entries(n.parts).map(([c,a])=>({key:c,value:Oe(a)}))};break;case"BinaryPartitioned":o={type:n.type,keyLength:n.partitionKeyLength,payload:Object.entries(n.parts).map(([c,a])=>({key:c,value:[Oe(a.index),Oe(a.values)]}))};break;default:throw Error(`unsupported resource type: ${JSON.stringify(i)}`)}return o.payload.sort((c,a)=>c.key.localeCompare(a.key)),o}));e.sort((r,n)=>r.id.localeCompare(n.id));const t=ee.createHash("sha256");return t.update(x(e)),t.digest().toString("hex")}async function Rs(s,e,t){const r={...Nt,...Bt(e),...t},n=new E.HmacSha256Signer(r.localSecret),o=ne.createDownloadClient(r.logger,s,r.localProjections),i=ne.createLogsClient(s,r.logger),c=ne.createUploadBlobClient(s,r.logger),a=ne.createUploadProgressClient(s,r.logger),l=new ne.DownloadDriver(r.logger,o,i,r.blobDownloadPath,n,r.blobDriverOps),u=new ne.DownloadBlobToURLDriver(r.logger,n,o,r.downloadBlobToURLPath,r.downloadBlobToURLDriverOps),d=new ne.UploadDriver(r.logger,n,c,a,r.uploadDriverOps),p=new ne.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),f=new ne.LogsDriver(r.logger,p,l),C=await ne.LsDriver.init(r.logger,s,n,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),w=await Kt.init(l,r.logger,r.pframesSpillPath);return{blobDriver:l,blobToURLDriver:u,logDriver:f,lsDriver:C,signer:n,uploadDriver:d,pFrameDriver:w}}class zc{constructor(e){S(this,"enrichmentTargetsCache",new Et.LRUCache({max:256,memoMethod:(e,t,{context:r})=>({value:this.calculateEnrichmentTargets(r)})}));this.quickJs=e}calculateEnrichmentTargets(e){const t=e.blockConfig();if(t.enrichmentTargets===void 0)return;const r=e.args();return Lo(this.quickJs,t.enrichmentTargets,t.code,r)}getEnrichmentTargets(e,t,r){const n={blockConfig:e,args:t};if(r===void 0)return this.calculateEnrichmentTargets(n);const o=`${r.argsRid}:${r.blockPackRid}`;return this.enrichmentTargetsCache.memo(o,{context:n}).value}}class Ht{constructor(e,t,r,n,o,i,c,a){S(this,"pl");S(this,"projectList");S(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=n,this.openedProjectsList=o,this.projectListTree=i,this.blockRegistryProvider=c,this.projectList=a,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=ee.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async n=>{const o=await Nn(n,e);return n.createField(h.field(this.projectListResourceId,t),"Dynamic",o),await n.commit(),await h.toGlobalResourceId(o)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await oe(this.env.projectHelper,this.pl,e,r,n=>{n.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(h.field(this.projectListResourceId,e)),await t.commit()}),await this.projectListTree.refreshState()}async projectIdToResourceId(e){return await this.pl.withReadTx("Project id to resource id",async t=>{const r=(await t.getField(h.field(this.projectListResourceId,e))).value;if(h.isNullResourceId(r))throw new Error("Unexpected project list structure.");return r})}async ensureProjectRid(e){return typeof e=="string"?await this.projectIdToResourceId(e):e}async openProject(e){const t=await this.ensureProjectRid(e);if(this.openedProjectsByRid.has(t))throw new Error(`Project ${t} already opened`);this.openedProjectsByRid.set(t,await 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,r){const n={...hs,...gs(t),...r};n.defaultTreeOptions.logStat=de().logTreeStats,n.debugOps.dumpInitialTreeState=de().dumpInitialTreeState;const o=await e.withWriteTx("MLInitialization",async j=>{const N=h.field(j.clientRoot,on);j.createField(N,"Dynamic");const U=await j.getField(N);if(h.isNullResourceId(U.value)){const A=j.createEphemeral(Hr);return j.lock(A),j.setField(N,A),await j.commit(),await A.globalId}else return U.value}),i=n.logger,c=await Rs(e,t,n),a=new ze.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),l=new Jr(a),u=new Tn(l,c.signer,a),d=new ne.DownloadUrlDriver(i,e.httpDispatcher,n.frontendDownloadPath),p=await pe.getQuickJS(),f={pl:e,signer:c.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:a,ops:n,bpPreparer:u,frontendDownloadDriver:d,driverKit:c,blockUpdateWatcher:new Jc(l,i,{minDelay:n.devBlockUpdateRecheckInterval,http:a,preferredUpdateChannel:n.preferredUpdateChannel}),quickJs:p,projectHelper:new zc(p)},C=new V.WatchableValue([]),w=await cn(e,o,C,f);return new Ht(f,c,c.signer,o,C,w.tree,l,w.computable)}}const Xc=["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 Yc(s,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},r=[];Xc.forEach(a=>{Ns.channel(a).subscribe(u=>{var p;const d=new Date().toISOString();(p=u==null?void 0:u.response)!=null&&p.headers&&(u.response.headers=u.response.headers.map(f=>f.toString())),r.push(JSON.stringify({timestamp:d,event:a,data:u}))})});const n={plPings:[],blockRegistryOverviewChecks:[],blockGARegistryOverviewChecks:[],blockRegistryUiChecks:[],blockGARegistryUiChecks:[],autoUpdateCdnChecks:[]},o=h.plAddressToConfig(s,{defaultRequestTimeout:t.pingTimeoutMs});n.plPings=await me(t.pingCheckDurationMs,t.maxPingsPerSecond,async()=>{const l=await new h.UnauthenticatedPlClient(o).ping();return JSON.stringify(l).slice(0,t.bodyLimit)+"..."});const c=new h.UnauthenticatedPlClient(o).ll.httpDispatcher;return n.blockRegistryOverviewChecks=await me(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Ee(new URL(t.blockOverviewPath,t.blockRegistryUrl),t,c)),n.blockGARegistryOverviewChecks=await me(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Ee(new URL(t.blockOverviewPath,t.blockGARegistryUrl),t,c)),n.blockRegistryUiChecks=await me(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Ee(new URL(t.blockUiPath,t.blockRegistryUrl),t,c)),n.blockGARegistryUiChecks=await me(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Ee(new URL(t.blockUiPath,t.blockGARegistryUrl),t,c)),n.autoUpdateCdnChecks=await me(t.autoUpdateCdnDurationMs,t.maxAutoUpdateCdnChecksPerSecond,async()=>await Ee(t.autoUpdateCdnUrl,t,c)),Qc(n,s,t,r)}async function me(s,e,t){const r=Rt(),n=[];for(;Vr(r)<s;){const o=Rt();let i;try{i={ok:!0,value:await t()}}catch(l){i={ok:!1,error:l}}const c=Vr(o);n.push({elapsedMs:c,response:i});const a=1e3/e-c;a>0&&await Ur.setTimeout(a)}return n}async function Ee(s,e,t){const{body:r,statusCode:n}=await ze.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),o=await r.text();return{statusCode:n,beginningOfBody:o.slice(0,e.bodyLimit)+"..."}}function Qc(s,e,t,r){const n=s.plPings.filter(c=>c.response.ok),o=s.plPings.filter(c=>!c.response.ok),i=[...new Set(n.map(c=>JSON.stringify(c.response.value)))];return`
1
+ "use strict";var Cs=Object.defineProperty;var qt=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),Wt=s=>{throw TypeError(s)};var ks=(s,e,t)=>e in s?Cs(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var S=(s,e,t)=>ks(s,typeof e!="symbol"?e+"":e,t);var zt=(s,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Wt("Object expected");var r;t&&(r=e[qt("asyncDispose")]),r===void 0&&(r=e[qt("dispose")]),typeof r!="function"&&Wt("Object not disposable"),s.push([t,r,e])}else t&&s.push([t]);return e},Xt=(s,e,t)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,c,a,l){return l=Error(a),l.name="SuppressedError",l.error=i,l.suppressed=c,l},o=i=>e=t?new r(i,e,"An error was suppressed during disposal"):(t=!0,i),n=i=>{for(;i=s.pop();)try{var c=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(c).then(n,a=>(o(a),n()))}catch(a){o(a)}if(t)throw e};return n()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const F=require("@platforma-sdk/model"),W=require("@milaboratories/pl-model-middle-layer"),Yt=require("@milaboratories/pl-deployments"),ze=require("undici"),z=require("@platforma-sdk/block-tools"),Z=require("node:fs"),J=require("node:path"),Os=require("yaml"),E=require("@milaboratories/ts-helpers"),ht=require("node:fs/promises"),Ts=require("@milaboratories/resolve-helper"),h=require("@milaboratories/pl-client"),He=require("@milaboratories/pl-tree"),V=require("@milaboratories/computable"),ee=require("node:crypto"),O=require("@milaboratories/pl-model-backend"),Et=require("lru-cache"),$s=require("node:worker_threads"),xr=require("denque"),Is=require("@platforma-sdk/workflow-tengo"),x=require("canonicalize"),Fs=require("node:assert"),pe=require("quickjs-emscripten"),As=require("@milaboratories/pl-errors"),Ls=require("remeda"),Ur=require("node:timers/promises"),oe=require("@milaboratories/pl-drivers"),Ds=require("@milaboratories/pframes-rs-node"),Ns=require("node:diagnostics_channel");function Ct(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const Bs=Ct(J),Gr=Ct(ht),Qt=Ct(Ls);async function Zt(s){try{return await Gr.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const js=[z.RegistryV1.PlPackageYamlConfigFile],Vs=[z.RegistryV1.PlPackageJsonConfigFile],kt=["backend","dist","tengo","tpl","main.plj.gz"],Ot=["config","dist","config.json"],Mr=["frontend","dist"],er="block-model/dist/config.json",xs="block-ui/package.json",Us=[kt,Ot,js,Vs,Mr];async function Gs(s){return await Zt(J.join(s,...Ot))!==void 0||await Zt(J.join(s,...kt))!==void 0}function nt(s,e){const t=Ts.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function tr(s,e){if(J.isAbsolute(s)||(s=J.resolve(s)),await Gs(s))return{workflow:J.join(s,...kt),config:J.join(s,...Ot),ui:J.join(s,...Mr)};{const t=nt(s,er),r=nt(s,er),o=nt(s,xs);return{workflow:t,config:r,ui:J.resolve(o,"..","dist")}}}async function Ms(s){try{return await Z.promises.readFile(s,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Js(s){try{return await Z.promises.stat(s,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Tt(s){let e=0n;for(const t of Us){const r=J.join(s,...t),o=await Js(r);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function Xe(s){const e=await Z.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await Z.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class _s{constructor(e,t,r){this.v2Provider=e,this.registries=t,this.http=r}async getPackagesForRoot(e){const t=[],r=e.spec;switch(r.type){case"remote-v1":{const o=this.http!==void 0?{dispatcher:this.http}:{},i=await(await ze.request(`${r.url}/${z.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const c of i){const{organization:a,package:l,latestMeta:u,latestVersion:d}=c,p={organization:a,name:l,version:d},f={id:p,meta:{title:u.title??"No title",description:u.description??"No Description",organization:{name:a,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:p,registryUrl:r.url}};t.push({registryId:e.id,id:p,latestByChannel:{[W.AnyChannel]:f,[W.StableChannel]:f},allVersions:c.allVersions.map(C=>({version:C,channels:[]}))})}return t}case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(o=>({...o,registryId:e.id}));case"local-dev":for(const o of await Z.promises.readdir(r.path,{withFileTypes:!0})){if(!o.isDirectory())continue;const n=J.join(r.path,o.name),i=await Ms(J.join(n,z.RegistryV1.PlPackageYamlConfigFile));if(i!==void 0){const c=z.RegistryV1.PlPackageConfigData.parse(Os.parse(i)),a=await Tt(n),l={organization:c.organization,name:c.package,version:"DEV"},u={id:l,meta:{title:c.meta.title??"No title",description:c.meta.description??"No Description",organization:{name:c.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:n,mtime:a}};t.push({registryId:e.id,id:l,latestByChannel:{[W.AnyChannel]:u,[W.StableChannel]:u},allVersions:[]})}else{let c=n,a=await z.tryLoadPackDescription(c);if(a===void 0){for(const l of["block","meta"])if(c=J.join(n,l),a=await z.tryLoadPackDescription(c),a!==void 0)break}if(a!==void 0){const l=await Xe(a),u={id:a.id,meta:await z.BlockPackMetaEmbedAbsoluteBytes.parseAsync(a.meta),spec:{type:"dev-v2",folder:c,mtime:l}};t.push({registryId:e.id,id:a.id,latestByChannel:{[W.AnyChannel]:u,[W.StableChannel]:u},allVersions:[]})}}}return t;default:return E.assertNever(r)}}async listBlockPacks(){const e=[],t=[];for(const r of this.registries)t.push({...r,status:"online"}),e.push(...await this.getPackagesForRoot(r));return{registries:t,blockPacks:e}}async getOverview(e,t,r){var i;const o=(i=this.registries.find(c=>c.id===e))==null?void 0:i.spec;if(!o)throw new Error(`Registry with id "${e}" not found`);if(o.type!=="remote-v2")throw new Error('Only "remote-v2" registries support specific package version overview retrieval.');return await this.v2Provider.getRegistry(o.url).getSpecificOverview(t,r)}}class Jr{constructor(e){S(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new z.RegistryV2Reader(z.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const Ks={type:"remote-v2",url:"https://blocks.pl-open.science/"},Hs={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},qs={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},Ws={groups:[{id:"default",label:"Default",blocks:[]}]},zs={stagingRefreshTimestamp:0,blocksInLimbo:[]},Xs={label:"New Project"},Ys={name:"UserProject",version:"2"},_r="SchemaVersion",Kr="1",$t="ProjectCreated",$e="ProjectLastModified",Ie="ProjectMeta",fe="ProjectStructure",qe="BlockRenderingState",Qs="BlockFrontendState/",Zs=/^BlockFrontendState\/(?<blockid>.*)$/;function gt(s){return`${Qs}${s}`}const eo="BlockArgsAuthor/";function mt(s){return`${eo}${s}`}const vt="ProjectStructureAuthor";function to(s){const e=s.match(Zs);if(e!==null)return e.groups.blockid}const ro="__serviceTemplate_";function yt(s){return`${ro}${s}`}function _(s,e){return`${s}-${e}`}const so=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function oo(s){const e=s.match(so);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const no="projects",Hr={name:"Projects",version:"1"},io=s=>h.resourceTypesEqual(s.type,Hr)?s.fields:[];async function ao(s,e,t,r){const o=await He.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:io},r.logger);return{computable:V.Computable.make(i=>{const c=i.accessor(o.entry()).node(),a=t.getValue(i);if(c===void 0)return;const l=[];for(const u of c.listDynamicFields()){const d=c.traverse(u);if(d===void 0)continue;const p=E.notEmpty(d.getKeyValueAsJson(Ie)),f=E.notEmpty(d.getKeyValueAsJson($t)),C=E.notEmpty(d.getKeyValueAsJson($e));l.push({id:u,rid:d.id,created:new Date(f),lastModified:new Date(C),opened:a.indexOf(d.id)>=0,meta:p})}return l.sort(u=>-u.lastModified.valueOf()),l}).withStableType(),tree:o}}const co={name:"EphRenderTemplate",version:"1"},lo={name:"RenderTemplate",version:"1"};function It(s,e,t,r,o){if(o.length===0)throw new Error("Zero output names provided");const n=t?s.createEphemeral(co):s.createStruct(lo),i=h.field(n,"template"),c=h.field(n,"inputs");return s.createField(i,"Input",e),s.createField(c,"Input",h.Pl.createPlMap(s,r,t)),s.lockInputs(n),h.Pl.futureRecord(s,n,o,"Output","outputs/")}const uo={name:"BContextEnd",version:"1"},po={name:"BContext",version:"1"},fo="id",ho="parent/",go=["context","result"];function rr(s,e,t){return It(s,e,!0,t,go)}function mo(s){const e=s.createEphemeral(uo);return s.lock(e),e}function sr(s,e){if(e.length===0)return mo(s);if(e.length===1)return e[0];const t=s.createEphemeral(po);s.createField(h.field(t,fo),"Input",h.Pl.createPlString(s,ee.randomUUID()));for(let r=0;r<e.length;r++)s.createField(h.field(t,`${ho}${r}`),"Input",e[r]);return s.lock(t),t}function qr(s,e){const t=new Map,r=(o,n,i)=>{const c=ee.createHash("sha256");n.updateCacheKey(o,c,i);const a=c.digest("hex");if(!t.has(a)){const l=n.render(o,s,r,i);t.set(a,l)}return t.get(a)};return r(e.template,Wr,e.hashToSource)}const or={updateCacheKey(s,e,t){e.update(O.PlTemplateLibV1.type.name).update(O.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(ye(s.name,t,s.sourceHash))},render(s,e,t,r){return e.createValue(O.PlTemplateLibV1.type,JSON.stringify(O.PlTemplateLibV1.fromV3Data(s,ye(s.name,r,s.sourceHash)).data))}},De={updateCacheKey(s,e,t){e.update(O.PlTemplateSoftwareV1.type.name).update(O.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(ye(s.name,t,s.sourceHash))},render(s,e,t,r){const o=O.PlTemplateSoftwareV1.fromV3Data(s,ye(s.name,r,s.sourceHash)),n=e.createStruct(O.PlTemplateSoftwareV1.type,o.data);return e.setKValue(n,O.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(o.name)),e.lock(n),n}},Wr={updateCacheKey(s,e,t){e.update(O.PlTemplateV1.type.name).update(O.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(ye(s.name,t,s.sourceHash));const r=o=>(o.sort((n,i)=>n[0]===i[0]?0:n[0]<i[0]?-1:1),o);for(const[o,n]of r(Object.entries(s.libs??{})))e.update("lib:"+o),or.updateCacheKey(n,e,t);for(const[o,n]of r(Object.entries(s.software??{})))e.update("soft:"+o),De.updateCacheKey(n,e,t);for(const[o,n]of r(Object.entries(s.assets??{})))e.update("asset:"+o),De.updateCacheKey(n,e,t);for(const[o,n]of r(Object.entries(s.templates??{})))e.update("tpl:"+o),this.updateCacheKey(n,e,t)},render(s,e,t,r){const o=e.createStruct(O.PlTemplateV1.type,JSON.stringify(O.PlTemplateV1.fromV3Data(s,ye(s.name,r,s.sourceHash)).data));for(const[c,a]of Object.entries(s.libs??{})){const l=O.PlTemplateV1.libField(o,c);e.createField(l,"Input"),e.setField(l,t(a,or,r))}for(const[c,a]of Object.entries(s.software??{})){const l=O.PlTemplateV1.swField(o,c);e.createField(l,"Input"),e.setField(l,t(a,De,r))}for(const[c,a]of Object.entries(s.assets??{})){const l=O.PlTemplateV1.swField(o,c);e.createField(l,"Input"),e.setField(l,t(a,De,r))}for(const[c,a]of Object.entries(s.templates??{})){const l=O.PlTemplateV1.tplField(o,c);e.createField(l,"Input"),e.setField(l,t(a,Wr,r))}if(e.lock(o),!s.hashOverride)return o;const n=e.createStruct(O.PlTemplateOverrideV1.type,JSON.stringify(O.PlTemplateOverrideV1.fromV3Data(s))),i=O.PlTemplateOverrideV1.tplField(n);return e.createField(i,"Service"),e.setField(i,o),e.lock(n),n}};function ye(s,e,t){return E.notEmpty(e[t],`trying to get "${s}" source: sources map doesn't contain source hash ${t}`)}function vo(s,e){const t=O.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return Xr(s,t);case"pl.tengo-template.v3":return qr(s,t);default:E.assertNever(r)}}function yo(s,e){const t=e.data,r=t.type;switch(r){case"pl.tengo-template.v2":return Xr(s,t);case"pl.tengo-template.v3":return qr(s,t);default:E.assertNever(r)}}const nr={hash(s,e){e.update(O.PlTemplateLibV1.type.name).update(O.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue(O.PlTemplateLibV1.type,JSON.stringify(O.PlTemplateLibV1.fromV2Data(s).data))}},Ne={hash(s,e){e.update(O.PlTemplateSoftwareV1.type.name).update(O.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=O.PlTemplateSoftwareV1.fromV2Data(s),o=e.createStruct(O.PlTemplateSoftwareV1.type,r.data);return e.setKValue(o,O.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(o),o}},zr={hash(s,e){e.update(O.PlTemplateV1.type.name).update(O.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(s.src);const t=r=>(r.sort((o,n)=>o[0]===n[0]?0:o[0]<n[0]?-1:1),r);for(const[r,o]of t(Object.entries(s.libs??{})))e.update("lib:"+r),nr.hash(o,e);for(const[r,o]of t(Object.entries(s.software??{})))e.update("soft:"+r),Ne.hash(o,e);for(const[r,o]of t(Object.entries(s.assets??{})))e.update("asset:"+r),Ne.hash(o,e);for(const[r,o]of t(Object.entries(s.templates??{})))e.update("tpl:"+r),this.hash(o,e)},render(s,e,t){const r=e.createStruct(O.PlTemplateV1.type,JSON.stringify(O.PlTemplateV1.fromV2Data(s).data));for(const[i,c]of Object.entries(s.libs??{})){const a=O.PlTemplateV1.libField(r,i);e.createField(a,"Input"),e.setField(a,t(c,nr))}for(const[i,c]of Object.entries(s.software??{})){const a=O.PlTemplateV1.swField(r,i);e.createField(a,"Input"),e.setField(a,t(c,Ne))}for(const[i,c]of Object.entries(s.assets??{})){const a=O.PlTemplateV1.swField(r,i);e.createField(a,"Input"),e.setField(a,t(c,Ne))}for(const[i,c]of Object.entries(s.templates??{})){const a=O.PlTemplateV1.tplField(r,i);e.createField(a,"Input"),e.setField(a,t(c,zr))}if(e.lock(r),!s.hashOverride)return r;const o=e.createStruct(O.PlTemplateOverrideV1.type,JSON.stringify(O.PlTemplateOverrideV1.fromV2Data(s))),n=O.PlTemplateOverrideV1.tplField(o);return e.createField(n,"Service"),e.setField(n,r),e.lock(o),o}};function Xr(s,e){const t=new Map,r=(o,n)=>{const i=ee.createHash("sha256");n.hash(o,i);const c=i.digest("hex");if(!t.has(c)){const a=n.render(o,s,r);t.set(c,a)}return t.get(c)};return r(e,zr)}const Yr={name:"TengoTemplateGet",version:"1"},Qr="registry",Zr="templateURI",es="template",wo={name:"TengoTemplatePack",version:"1"},bo={name:"TengoTemplatePackConvert",version:"1"},So="templatePack",Po="template";async function ts(s){switch(s.type){case"from-file":return{type:"explicit",content:await Z.promises.readFile(s.path)};case"from-registry":case"explicit":return s;case"prepared":return s;default:return E.assertNever(s)}}function Ro(s,e){const t=s.createStruct(Yr),r=h.field(t,Qr),o=h.field(t,Zr),n=h.field(t,es);return s.setField(r,s.createValue(h.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(o,s.createValue(h.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function Ye(s,e){switch(e.type){case"from-registry":return Ro(s,e);case"explicit":return vo(s,e);case"prepared":return yo(s,e);default:return E.assertNever(e)}}const Ft={name:"Frontend/FromUrl",version:"1"},At={name:"Frontend/FromFolder",version:"1"};function Eo(s,e){switch(e.type){case"url":return s.createValue(Ft,JSON.stringify({url:e.url}));case"local":return s.createValue(At,JSON.stringify({path:e.path,signature:e.signature}));default:return E.assertNever(e)}}class Co{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__:J.resolve(void 0,"worker.js"),t=this.worker=new $s.Worker(e,{workerData:{}});t.on("message",({id:r,data:o,error:n})=>{const{resolve:i,reject:c}=this.pendingRequests.get(r);this.pendingRequests.delete(r),n?c(new Error(n)):i(o)}),t.on("error",r=>{console.error("Worker error",r),this.rejectAllPendingRequests(r)})}rejectAllPendingRequests(e){Array.from(this.pendingRequests.values()).map(({reject:t})=>{t(e)})}async process(e,...t){return new Promise((r,o)=>{const n=++this.nextMessageId;this.pendingRequests.set(n,{resolve:r,reject:o}),this.worker.postMessage({id:n,type:e,args:t})})}async terminate(){this.rejectAllPendingRequests(new Error("Worker terminated")),await this.worker.terminate()}[Symbol.asyncDispose](){return this.terminate()}}const ko={name:"BlockPackCustom",version:"1"},rs="template",ss="frontend";function ir(s){return s.endsWith("/")?s:`${s}/`}function Oo(s){return Buffer.from(s).toString("utf8")}function Be(s){return JSON.parse(Oo(s))}class To{constructor(e,t,r){S(this,"remoteContentCache",new Et.LRUCache({max:500,maxSize:128*1024*1024,fetchMethod:async e=>{const t=this.http!==void 0?{dispatcher:this.http}:{};return await(await ze.request(e,t)).body.arrayBuffer()},sizeCalculation:e=>e.byteLength}));this.v2RegistryProvider=e,this.signer=t,this.http=r}async getBlockConfigContainer(e){switch(e.type){case"explicit":return e.config;case"prepared":return e.config;case"dev-v1":{const t=await tr(e.folder),r=await Z.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await z.loadPackDescription(e.folder),r=await Z.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=`${ir(e.registryUrl)}${z.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=await this.remoteContentCache.forceFetch(`${t}/config.json`);return Be(r)}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),o=await this.remoteContentCache.forceFetch(r.model.url);return Be(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 r=zt(o,new Co,!0);return{...t,type:"prepared",template:{type:"prepared",data:await r.process("parseTemplate",t.template.content)}}}catch(n){var i=n,c=!0}finally{var a=Xt(o,i,c);a&&await a}}async prepareWithoutUnpacking(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await tr(e.folder),r=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:r},config:o,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:e}}case"dev-v2":{const t=await z.loadPackDescription(e.folder),r=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 Xe(t)),{type:"explicit",template:{type:"explicit",content:o},config:r,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:i}}case"from-registry-v1":{const t=`${ir(e.registryUrl)}${z.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=`${t}/template.plj.gz`,o=await this.remoteContentCache.forceFetch(r),n=new Uint8Array(o),i=await this.remoteContentCache.forceFetch(`${t}/config.json`),c=Be(i);return{type:"explicit",template:{type:"explicit",content:n},config:c,frontend:{type:"url",url:`${t}/frontend.tgz`},source:e}}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),o=async()=>Be(await this.remoteContentCache.forceFetch(r.model.url)),n=async()=>await this.remoteContentCache.forceFetch(r.workflow.main.url),[i,c]=await Promise.all([o(),n()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(c)},config:i,frontend:{type:"url",url:r.ui.url},source:e}}default:return E.assertNever(e)}}}function $o(s,e){const t={config:e.config,source:e.source},r=s.createStruct(ko,JSON.stringify(t));return s.createField(h.field(r,rs),"Input",Ye(s,e.template)),s.createField(h.field(r,ss),"Input",Eo(s,e.frontend)),s.lock(r),r}function ar(s,e){switch(e.type){case"prepared":return $o(s,e);default:return E.assertNever(e.type)}}function je(s,e,t){return{__isRef:!0,blockId:s,name:e}}function Io(s){return typeof s=="object"&&s!==null&&"__isRef"in s&&s.__isRef===!0&&"blockId"in s&&"name"in s}function wt(s,e,t){const r=typeof e;switch(r){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if(Io(e))t===void 0||t.has(e.blockId)?(s.upstreams.add(e.blockId),e.requireEnrichments&&s.upstreamsRequiringEnrichments.add(e.blockId)):s.missingReferences=!0;else if(Array.isArray(e))for(const o of e)wt(s,o,t);else for(const[,o]of Object.entries(e))wt(s,o,t);return;default:E.assertNever(r)}}function Fo(s,e){const t={upstreams:new Set,upstreamsRequiringEnrichments:new Set,missingReferences:!1};return wt(t,s,e),t}function ie(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class os{constructor(e){S(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,o=>r.add(o.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const o of t)r.delete(o);return r}traverse(e,t,r){let o=[...t];const n=new Set(o);for(;o.length>0;){const i=[];for(const c of o){const a=this.nodes.get(c);r(a),a[e].forEach(l=>{n.has(l)||(n.add(l),i.push(l))})}o=i}}}function bt(s){const e=new Map;let t;for(const{id:r}of ie(s)){const o={id:r,missingReferences:!1};e.set(r,o),t===void 0?(o.directUpstream=o.upstream=new Set,o.enrichments=o.enrichmentTargets=new Set):(o.directUpstream=o.upstream=new Set([t.id]),t.directDownstream=t.downstream=new Set([o.id]),t.enrichments=t.enrichmentTargets=new Set),t=o}return t!==void 0&&(t.directDownstream=t.downstream=new Set),new os(e)}function Ke(s,e){const t=new Map,r=new os(t),o=new Set;for(const{id:n}of ie(s)){const i=e(n);if(i===void 0)continue;const c=Fo(i.args,o),a=new Set([...c.upstreams,...r.traverseIds("enrichments",...c.upstreamsRequiringEnrichments)]),l=new Set;for(const{id:p}of ie(s)){if(p===n)break;if(a.has(p)){l.add(p);for(const f of r.traverseIdsExcludingRoots("upstream",p))l.delete(f)}}const u=i.enrichmentTargets===void 0?new Set(c.upstreams):new Set(i.enrichmentTargets.map(p=>p.blockId)),d={id:n,missingReferences:c.missingReferences,upstream:l,directUpstream:c.upstreams,enrichmentTargets:u,downstream:new Set,directDownstream:new Set,enrichments:new Set};t.set(n,d),c.upstreams.forEach(p=>t.get(p).directDownstream.add(n)),l.forEach(p=>t.get(p).downstream.add(n)),u.forEach(p=>{var f;return(f=t.get(p))==null?void 0:f.enrichments.add(n)}),o.add(n)}return r}function Ao(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function St(s,e){if(s.size>e.size)return St(e,s);for(const t of s)if(e.has(t))return!0;return!1}function cr(s,e){const t=new Set,r=new Set,o=new Set;return s.nodes.forEach(n=>{const i=e.nodes.get(n.id);i===void 0?t.add(n.id):(!Ao(n.upstream,i.upstream)||St(n.upstream,o))&&o.add(n.id)}),e.nodes.forEach(n=>{s.nodes.has(n.id)?St(n.upstream,o)&&o.add(n.id):r.add(n.id)}),{onlyInA:t,onlyInB:r,different:o}}let it;async function ns(){if(it===void 0){const s=await ts(Is.Templates["pframes.export-pframe-for-ui"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=ee.createHash("sha256").update(s.content).digest("hex");it={spec:s,hash:e}}return it}function Lo(s,e,t){return It(s,e,!0,{pf:t},["result"]).result}function at(s,e){let t=!1,r,o;return()=>{if(!t)return t=!0,r=s(),o=e(),o;const n=s();return r!==n&&(r=n,o=e()),e()}}class lr{constructor(e,t,r,o){S(this,"currentArgsC",at(()=>this.fields.currentArgs.modCount,()=>E.cachedDeserialize(this.fields.currentArgs.value)));S(this,"prodArgsC",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.cachedDeserialize(e)}));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,this.config=r,this.source=o}check(){if(this.fields.prodOutput===void 0!=(this.fields.prodCtx===void 0))throw new Error("inconsistent prod fields");if(this.fields.stagingOutput===void 0!=(this.fields.stagingCtx===void 0))throw new Error("inconsistent stage fields");if(this.fields.prodOutputPrevious===void 0!=(this.fields.prodCtxPrevious===void 0))throw new Error("inconsistent prod cache fields");if(this.fields.stagingOutputPrevious===void 0!=(this.fields.stagingCtxPrevious===void 0))throw new Error("inconsistent stage cache fields");if(this.fields.blockPack===void 0)throw new Error("no block pack field");if(this.fields.currentArgs===void 0)throw new Error("no current args field")}get currentArgs(){return this.currentArgsC()}get stagingRendered(){return this.fields.stagingCtx!==void 0}get productionRendered(){return this.fields.prodCtx!==void 0}get productionHasErrors(){var e;return((e=this.fields.prodUiCtx)==null?void 0:e.status)==="Error"}get requireProductionRendering(){return!this.productionRendered||this.productionStaleC()||this.productionHasErrors}get prodArgs(){return this.prodArgsC()}getTemplate(e){return e.getFutureFieldValue(h.Pl.unwrapHolder(e,this.fields.blockPack.ref),rs,"Input")}}const Do=s=>{throw new Error(`No new block info for ${s}`)};class We{constructor(e,t,r,o,n,i,c,a,l,u,d,p,f){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=r,this.schema=o,this.lastModified=n,this.meta=i,this.struct=c,this.renderingState=a,this.blocksInLimbo=l,this.blockInfos=u,this.blockFrontendStates=d,this.ctxExportTplHolder=p,this.projectHelper=f}fixProblemsAndMigrate(){this.blockInfos.forEach(t=>{(t.fields.prodArgs===void 0||t.fields.prodOutput===void 0||t.fields.prodCtx===void 0)&&this.deleteBlockFields(t.id,"prodArgs","prodOutput","prodCtx")});let e;this.blockInfos.forEach(t=>{t.fields.blockSettings===void 0&&(e===void 0&&(e=this.createJsonFieldValue(W.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=bt(this.struct)),this.stagingGraph}getProductionGraphBlockInfo(e,t){const r=this.getBlockInfo(e);let o,n;if(t){if(r.fields.prodArgs===void 0)return;o=r.fields.prodArgs,n=r.prodArgs}else o=E.notEmpty(r.fields.currentArgs),n=r.currentArgs;const i=E.notEmpty(r.fields.blockPack);return h.isResourceId(o.ref)&&h.isResourceId(i.ref)?{args:n,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>n,{argsRid:o.ref,blockPackRid:i.ref})}:{args:n,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>n)}}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Ke(this.struct,e=>this.getProductionGraphBlockInfo(e,!1))),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Ke(this.struct,e=>this.getProductionGraphBlockInfo(e,!0))),this.actualProductionGraph}getBlockInfo(e){const t=this.blockInfos.get(e);if(t===void 0)throw new Error(`No such block: ${e}`);return t}createJsonFieldValueByContent(e){const t=Buffer.from(e);return{ref:this.tx.createValue(h.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of ie(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const o=h.field(this.rid,_(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(o,"Dynamic",r.ref):this.tx.setField(o,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,o,n){this.setBlockFieldObj(e,t,{ref:r,status:o,value:n})}deleteBlockFields(e,...t){let r=!1;const o=this.getBlockInfo(e);for(const n of t){const i=o.fields;n in i&&(this.tx.removeField(h.field(this.rid,_(e,n))),delete i[n],this.fieldsChanged=!0,r=!0)}return r}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((o=t.stagingCtx)==null?void 0:o.status)==="Ready"&&((n=t.stagingUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"stagingOutputPrevious",t.stagingOutput),this.setBlockFieldObj(e,"stagingCtxPrevious",t.stagingCtx),this.setBlockFieldObj(e,"stagingUiCtxPrevious",t.stagingUiCtx)),this.deleteBlockFields(e,"stagingOutput","stagingCtx","stagingUiCtx")&&this.resetStagingRefreshTimestamp()}resetProduction(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"&&((n=t.prodUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"prodOutputPrevious",t.prodOutput),this.setBlockFieldObj(e,"prodCtxPrevious",t.prodCtx),this.setBlockFieldObj(e,"prodUiCtxPrevious",t.prodUiCtx)),this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}resetOrLimboProduction(e){var r,o;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"?this.blocksInLimbo.has(e)?!1:(this.blocksInLimbo.add(e),this.renderingStateChanged=!0,this.deleteBlockFields(e,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),!0):this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}setArgs(e){const t=[];for(const{blockId:r,args:o}of e){const n=this.getBlockInfo(r);JSON.parse(o);const i=Buffer.from(o);if(Buffer.compare(n.fields.currentArgs.value,i)===0)continue;const c=this.tx.createValue(h.Pl.JsonObject,i);this.setBlockField(r,"currentArgs",c,"Ready",i),this.blocksWithChangedInputs.add(r),t.push(r)}this.getStagingGraph().traverse("downstream",t,({id:r})=>this.resetStaging(r)),t.length>0&&this.updateLastModified()}setUiState(e,t){if(this.blockInfos.get(e)===void 0)throw new Error("no such block");this.blockFrontendStates.get(e)!==t&&(t===void 0?this.blockFrontendStates.delete(e):this.blockFrontendStates.set(e,t),this.changedBlockFrontendStates.add(e),this.blocksWithChangedInputs.add(e),this.updateLastModified())}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createProdCtx(e){const t=[];return e.forEach(r=>{var n;const o=this.getBlockInfo(r);if(((n=o.fields.prodCtx)==null?void 0:n.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(h.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),sr(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(r=>{var n,i;const o=this.getBlockInfo(r);if(((n=o.fields.stagingCtx)==null?void 0:n.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(h.Pl.unwrapHolder(this.tx,o.fields.stagingCtx.ref)),((i=o.fields.prodCtx)==null?void 0:i.ref)!==void 0&&t.push(h.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),sr(this.tx,t)}exportCtx(e){return Lo(this.tx,h.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createStagingCtx(this.getStagingGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const o=t.getTemplate(this.tx),n=rr(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(h.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(h.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",h.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"stagingOutput",n.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),r=this.createProdCtx(this.getPendingProductionGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const o=t.getTemplate(this.tx),n=rr(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(h.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(h.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",h.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=Do){const r=this.getStagingGraph(),o=this.getActualProductionGraph(),n=bt(e),i=cr(r,n);for(const l of i.onlyInA){const{fields:u}=this.getBlockInfo(l);this.deleteBlockFields(l,...Object.keys(u)),this.blockInfos.delete(l),this.blocksInLimbo.delete(l)&&(this.renderingStateChanged=!0),this.blockFrontendStates.delete(l)&&this.changedBlockFrontendStates.add(l)}for(const l of i.onlyInB){const u=t(l),d=new lr(l,{},F.extractConfig(u.blockPack.config),u.blockPack.source);this.blockInfos.set(l,d);const p=ar(this.tx,u.blockPack);this.setBlockField(l,"blockPack",h.Pl.wrapInHolder(this.tx,p),"NotReady"),this.setBlockFieldObj(l,"blockSettings",this.createJsonFieldValue(W.InitialBlockSettings)),this.setBlockFieldObj(l,"currentArgs",this.createJsonFieldValueByContent(u.args)),u.uiState&&(this.blockFrontendStates.set(l,u.uiState),this.changedBlockFrontendStates.add(l)),d.check()}for(const l of i.different)this.resetStaging(l);const c=Ke(e,l=>this.getProductionGraphBlockInfo(l,!0)),a=cr(o,c);o.traverse("downstream",[...a.different],l=>{this.resetOrLimboProduction(l.id)}),(i.onlyInB.size>0||i.onlyInA.size>0||i.different.size>0)&&this.resetStagingRefreshTimestamp(),this.struct=e,this.structureChanged=!0,this.stagingGraph=void 0,this.pendingProductionGraph=void 0,this.actualProductionGraph=void 0,this.updateLastModified()}addBlock(e,t,r){const o=this.structure;if(r===void 0)o.groups[o.groups.length-1].blocks.push(e);else{let n=!1;for(const i of o.groups){const c=i.blocks.findIndex(a=>a.id===r);if(!(c<0)){i.blocks.splice(c,0,e),n=!0;break}}if(!n)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(o,n=>{if(n!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const o of t.groups){const n=o.blocks.findIndex(i=>i.id===e);if(!(n<0)){o.blocks.splice(n,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const o=this.getBlockInfo(e);this.setBlockField(e,"blockPack",h.Pl.wrapInHolder(this.tx,ar(this.tx,t)),"NotReady"),r!==void 0?(this.setArgs([{blockId:e,args:r.args}]),this.setUiState(e,r.uiState)):this.getStagingGraph().traverse("downstream",[e],({id:n})=>this.resetStaging(n)),o.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:n})=>this.resetOrLimboProduction(n)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),o=this.getPendingProductionGraph();if(t)o.traverse("upstream",e,c=>{r.add(c.id)});else for(const c of r){const a=o.nodes.get(c);if(a===void 0)throw new Error(`Can't find block with id: ${c}`);for(const l of a.upstream)if(!r.has(l))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const c of ie(this.structure)){if(!r.has(c.id))continue;let a=this.getBlockInfo(c.id).requireProductionRendering||this.blocksInLimbo.has(c.id);if(!a){for(const l of o.nodes.get(c.id).upstream)if(n.has(l)){a=!0;break}}a&&(this.renderProductionFor(c.id),n.add(c.id))}const i=[...n];return o.traverse("downstream",i,c=>{n.has(c.id)||this.resetOrLimboProduction(c.id)}),this.getStagingGraph().traverse("downstream",i,({id:c})=>{i[0]!==c&&this.resetStaging(c)}),n.size>0&&this.updateLastModified(),n}stopProduction(...e){var i,c;const t=this.getActualProductionGraph(),r=new xr(e),o=new Set(e),n=[];for(;!r.isEmpty();){const a=r.shift(),l=this.getBlockInfo(a).fields;if(!(((i=l.prodOutput)==null?void 0:i.status)==="Ready"&&((c=l.prodCtx)==null?void 0:c.status)==="Ready")&&this.deleteBlockFields(a,"prodOutput","prodCtx","prodUiCtx","prodArgs")){n.push(a);for(const u of t.traverseIdsExcludingRoots("downstream",a))o.has(u)||(r.push(u),o.add(u))}}for(const a of t.traverseIdsExcludingRoots("downstream",...n))this.resetOrLimboProduction(a)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(o=>{let i=this.getBlockInfo(o.id).stagingRendered?0:1;o.upstream.forEach(c=>{const a=t.get(c);a!==0&&(i=Math.max(a+1,i))}),e(o.id,i),t.set(o.id,i)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,r=e===void 0?void 0:1+Math.max(0,t*e/1e3);let o=0;this.traverseWithStagingLag((n,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(n),o++)}),o>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,o,n,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((o=t.fields.prodOutput)==null?void 0:o.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((n=t.fields.stagingCtx)==null?void 0:n.status)==="Ready"&&((i=t.fields.stagingOutput)==null?void 0:i.status)==="Ready"&&this.deleteBlockFields(t.id,"stagingOutputPrevious","stagingCtxPrevious","stagingUiCtxPrevious")})}assignAuthorMarkers(){const e=this.author?JSON.stringify(this.author):void 0;for(const t of this.blocksWithChangedInputs)e===void 0?this.tx.deleteKValue(this.rid,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,$e,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,fe,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,qe,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,r,o){const n=t.getResourceData(r,!0),i=t.getKValueJson(r,_r),c=t.getKValueJson(r,$e),a=t.getKValueJson(r,Ie),l=t.getKValueJson(r,fe),u=t.getKValueJson(r,qe),d=t.listKeyValuesString(r),p=await n,f=new Map;for(const g of p.fields){const b=oo(g.name);if(b===void 0)continue;let v=f.get(b.blockId);v===void 0&&(v={id:b.blockId,fields:{}},f.set(b.blockId,v)),v.fields[b.fieldName]=h.isNullResourceId(g.value)?{modCount:0}:{modCount:0,ref:g.value}}const C=[];f.forEach(g=>{const b=g.fields;for(const[v,P]of Object.entries(b)){if(P.ref===void 0)continue;if(!h.isResource(P.ref)||h.isResourceRef(P.ref))throw new Error("unexpected behaviour");const T=v;C.push([g,T,P,t.getResourceData(P.ref,T=="blockPack")])}});const[w,j,N,U,{stagingRefreshTimestamp:A,blocksInLimbo:H},he]=await Promise.all([i,c,a,l,u,d]);if(w!==Kr)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${w}`);const B=[];for(const[g,b,v,P]of C){const T=await P;if(v.value=T.data,h.isNotNullResourceId(T.error)?v.status="Error":T.resourceReady||h.isNotNullResourceId(T.originalResourceId)?v.status="Ready":v.status="NotReady",b==="blockPack"){const k=T.fields.find(L=>L.name===h.Pl.HolderRefField);if(k===void 0)throw new Error("Block pack ref field is missing");B.push([g,t.getResourceData(h.ensureResourceIdNotNull(k.value),!1)])}}for(const[g,b]of B){const v=await b,P=E.cachedDeserialize(E.notEmpty(v.data));g.blockConfig=F.extractConfig(P.config),g.blockPack=P.source}const Y=await ns(),te=yt(Y.hash),K=p.fields.find(g=>g.name===te);let re;K!==void 0?re=h.ensureResourceIdNotNull(K.value):(re=h.Pl.wrapInHolder(t,Ye(t,Y.spec)),t.createField(h.field(r,yt(Y.hash)),"Dynamic",re));const se={stagingRefreshTimestamp:A},M=new Set(H),q=new Map;for(const g of he){const b=to(g.key);b!==void 0&&q.set(b,g.value)}const y=new Map;f.forEach(({id:g,fields:b,blockConfig:v,blockPack:P})=>y.set(g,new lr(g,b,E.notEmpty(v),E.notEmpty(P))));const m=new Set;for(const g of ie(U)){if(!y.has(g.id))throw new Error(`Inconsistent project structure: no inputs for ${g.id}`);m.add(g.id)}y.forEach(g=>{if(!m.has(g.id))throw new Error(`Inconsistent project structure: no structure entry for ${g.id}`);g.check()});const R=new We(r,t,o,w,j,N,U,se,M,y,q,re,e);return R.fixProblemsAndMigrate(),R}}async function No(s,e=Xs){const t=s.createEphemeral(Ys);s.lock(t);const r=String(Date.now());s.setKValue(t,_r,JSON.stringify(Kr)),s.setKValue(t,$t,r),s.setKValue(t,$e,r),s.setKValue(t,Ie,JSON.stringify(e)),s.setKValue(t,fe,JSON.stringify(Ws)),s.setKValue(t,qe,JSON.stringify(zs));const o=await ns();return s.createField(h.field(t,yt(o.hash)),"Dynamic",h.Pl.wrapInHolder(s,Ye(s,o.spec))),t}async function Ve(s,e,t,r){return ne(s,e,t,void 0,r)}async function ne(s,e,t,r,o){if(e instanceof h.PlClient)return await e.withWriteTx("ProjectAction",async n=>{const i=await We.load(s,n,t,r),c=await o(i);return i.wasModified&&(i.save(),await n.commit()),c});{const n=await We.load(s,e,t,r),i=await o(n);return n.save(),i}}function*Bo(s){switch(s.type){case"Json":return;case"JsonPartitioned":for(const[,e]of Object.entries(s.parts))yield e;return;case"BinaryPartitioned":for(const[,{index:e,values:t}]of Object.entries(s.parts))yield e,yield t;return;default:E.assertNever(s)}}function ur(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function jo(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:ur(s.parts,e)};case"BinaryPartitioned":return{...s,parts:ur(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:E.assertNever(s)}}const Vo=h.resourceType("PColumnData/JsonPartitioned","1"),xo=h.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Uo=h.resourceType("PColumnData/BinaryPartitioned","1"),Go=h.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),Mo=h.resourceType("PColumnData/Json","1");function Jo(s){if(!s.getIsReadyOrError())throw new Error("Data not ready.");const e=s.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(h.resourceTypesEqual(s.resourceType,Mo)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(h.resourceTypesEqual(s.resourceType,Vo)){const t=e,r=Object.fromEntries(s.listInputFields().map(o=>[o,s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,xo)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const c of i){const a=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);r[a]=n.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,Uo)){const t=e,r={};for(const o of s.listInputFields())if(o.endsWith(".index")){const n=o.slice(0,o.length-6);let i=r[n];i===void 0&&(i={},r[n]=i),i.index=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else if(o.endsWith(".values")){const n=o.slice(0,o.length-7);let i=r[n];i===void 0&&(i={},r[n]=i),i.values=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${o}`);for(const[o,n]of Object.entries(r)){if(n.index===void 0)throw new Error(`no index for part ${o}`);if(n.values===void 0)throw new Error(`no values for part ${o}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,Go)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const c of i)if(c.endsWith(".index")){const a=c.slice(0,c.length-6),l=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].index=n.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}else if(c.endsWith(".values")){const a=c.slice(0,c.length-7),l=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].values=n.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${c}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}throw new Error(`unsupported resource type: ${h.resourceTypeToString(s.resourceType)}`)}function _o(s,e){const t=s.axesSpec.length,r={};for(const{key:o,val:n}of e){if(o.length!==t)throw new Error(`inline column key length ${o.length} differs from axes count ${t}`);r[JSON.stringify(o)]=n}return{type:"Json",keyLength:t,data:r}}function Ko(s,e){const t=ee.createHash("sha256");return t.update(x(s)),t.update(String(h.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function dr(s,e){return x({__isRef:!0,blockId:s,name:e})}function Ho(s,e){return x({resolvePath:s,name:e})}function is(s,e=!0,t=!1,r=""){var c,a,l;const o=/^(?<name>.*)\.(?<type>spec|data)$/,n=new Map;for(const u of s.listInputFields()){const d=u.match(o);if(!d){if(e)throw new Error(`unexpected field name ${u}`);continue}let p=E.notEmpty((c=d.groups)==null?void 0:c.name);if(!p.startsWith(r)){if(e)throw new Error(`unexpected field name ${u}`);continue}p=p.slice(r.length);const f=E.notEmpty((a=d.groups)==null?void 0:a.type);let C=n.get(p);switch(C===void 0&&(C={},n.set(p,C)),f){case"spec":C.spec=(l=s.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:l.getDataAsJson();break;case"data":C.hasData=!0,C.data=()=>s.traverseOrError({field:u,ignoreError:t});break}}const i=s.getInputsLocked();if(i)for(const[,u]of n)u.data===void 0&&(u.hasData=!1);return{locked:i,results:n}}function qo(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const o=is(s,e,!1,t);Fs(o.locked);const n={};for(const[i,c]of o.results){if(c.spec===void 0)throw new Error(`no spec for key ${i}`);if(c.hasData!==!0||c.data===void 0)throw new Error(`no data for key ${i}`);const a=c.data();if(a===void 0)throw new Error(`no data for key ${i}`);if(!a.ok)throw a.error;n[i]={id:r.length===0?Ko(c.spec,a.value):Ho(r,i),spec:c.spec,data:a.value}}return n}class Lt{constructor(e,t){S(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const o of t.values())for(const n of[o.prod,o.staging])if(n!==void 0){if(!n.locked){r=!1;break e}for(const i of n.results.values())if(i.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var n,i,c,a,l,u;const r=this.blocks.get(e);if(r===void 0)return;let o=(c=(i=(n=r.prod)==null?void 0:n.results)==null?void 0:i.get(t))==null?void 0:c.spec;if(o!==void 0||(o=(u=(l=(a=r.staging)==null?void 0:a.results)==null?void 0:l.get(t))==null?void 0:u.spec,o!==void 0))return o;r.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):r.staging.locked?r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var i,c,a;const r=this.blocks.get(e);if(r===void 0)return;const o=(c=(i=r.prod)==null?void 0:i.results)==null?void 0:c.get(t),n=(a=o==null?void 0:o.data)==null?void 0:a.call(o);if(o!==void 0&&o.spec!==void 0&&n!==void 0)return F.mapValueInVOE(n,l=>({id:dr(e,t),spec:o.spec,data:l}));o!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const r=this.getDataOrErrorByRef(e,t);if(!(r===void 0||!r.ok))return r.value}getData(){const e=this.getDataWithErrors(),t=[];for(const r of e.entries)r.obj.id!==void 0&&r.obj.data.ok&&t.push({ref:r.ref,obj:{id:r.obj.id,spec:r.obj.spec,data:r.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,r;const o=i=>{r===void 0&&(r=i),t=!1},n=(i,c,a)=>{if(a.spec!==void 0&&a.hasData===!0&&a.data!==void 0){const l=a.data();l!==void 0?e.push({ref:je(i,c),obj:{id:l.ok?dr(i,c):void 0,spec:a.spec,data:l}}):o(`no_data:${i}:${c}`)}};for(const[i,c]of this.blocks){const a=new Set;if(c.prod!==void 0){c.prod.locked||o(`prod_not_locked:${i}`);for(const[l,u]of c.prod.results)a.add(l),n(i,l,u)}if(c.staging!==void 0){c.staging.locked||o(`staging_not_locked:${i}`);for(const[l,u]of c.staging.results)a.has(l)||n(i,l,u)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const o=n=>{r===void 0&&(r=n),t=!1};for(const[n,i]of this.blocks){const c=new Set;if(i.staging!==void 0){i.staging.locked||o(`staging_not_locked:${n}`);for(const[a,l]of i.staging.results)l.spec!==void 0&&(e.push({ref:je(n,a),obj:l.spec}),c.add(a))}else o(`staging_not_rendered:${n}`);if(i.prod!==void 0){i.prod.locked||o(`prod_not_locked:${n}`);for(const[a,l]of i.prod.results)c.has(a)||l.spec!==void 0&&e.push({ref:je(n,a),obj:l.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const o=new Set,n=i=>{for(const[c,a]of i.results)o.has(c)||a.spec===void 0||(o.add(c),F.executePSpecPredicate(e,a.spec)&&t.push({label:r.info.label+" / "+c,ref:je(r.info.id,c),spec:a.spec}))};r.staging!==void 0&&n(r.staging),r.prod!==void 0&&n(r.prod)}return t}static create(e,t,r){const o=e.accessor(t).node(),n=E.notEmpty(o.getKeyValueAsJson(fe)),c=bt(n).traverseIds("upstream",r),a=new Map;for(const l of ie(n)){if(!c.has(l.id))continue;const u=pr(o.traverse({field:_(l.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:_(l.id,"prodUiCtx"),stableIfNotFound:!0})),d=pr(o.traverse({field:_(l.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:_(l.id,"stagingUiCtx")}));a.set(l.id,{info:l,prod:u,staging:d})}return new Lt(e,a)}}function pr(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return is(e.value,!1,!0)}function Dt(s,e){return{blockId:e,args:n=>E.notEmpty(n.accessor(s).node().traverse({field:_(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),activeArgs:n=>{var i;return(i=n.accessor(s).node().traverse({field:_(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:i.getDataAsString()},uiState:n=>n.accessor(s).node().getKeyValueAsString(gt(e)),blockMeta:n=>{const i=n.accessor(s).node(),c=E.notEmpty(i.getKeyValueAsJson(fe)),a=new Map;for(const l of ie(c))a.set(l.id,l);return a}}}function as(s,e){return{...Dt(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:_(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:r.persist()},staging:t=>{var o;const r=(o=t.accessor(s).node({ignoreError:!0}).traverse({field:_(e,"stagingOutput"),ignoreError:!0}))==null?void 0:o.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>Lt.create(t,s,e)}}function*Q(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*Q(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*Q(t);return;case"MakeArray":for(const t of s.template)yield*Q(t);return;case"GetJsonField":case"GetResourceField":yield*Q(s.source),yield*Q(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*Q(s.source),yield*Q(s.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"ExtractArchiveAndGetURL":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetProgressLogWithInfo":case"GetLogHandle":yield*Q(s.source);return;case"IsEmpty":yield*Q(s.arg);return;case"Not":yield*Q(s.operand);return;case"And":case"Or":yield*Q(s.operand1),yield*Q(s.operand2);return;default:E.assertNever(s)}}function Wo(s,e){const t={};for(const[r,o]of Object.entries(s))t[r]=e(o);return t}function Ce(s,e){return s===void 0?void 0:e(s)}function zo(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function Xo(s){for(const e of Q(s))if(zo(e))return!0;return!1}function Qe(s){return{type:"ReturnResult",result:s}}function $(s){return()=>Qe(s)}const Yo=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return $(e)},Qo=s=>{const e=s.source;if(e===void 0)return $(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return $(t)},Zo=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?$(void 0):({cCtx:r})=>{var o;return Qe((o=r.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function cs(s,e){const t={},r=s.length;for(let o=0;o<r;o++)t[String(o)]=e(s[o]);return t}function en(s,e){return t=>{const r=t.source;return r===void 0?$(void 0):()=>({type:"ScheduleSubroutine",subroutine:ls(r.length),args:cs(r,o=>I({...s,[e.itVar]:o},e.mapping))})}}function ls(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return $(t)}}function tn(s,e){return t=>{const r=t.source;if(r===void 0)return $(void 0);const o={};for(const[n,i]of Object.entries(r)){const c={...s,[e.itVar]:i};o[n]=I(c,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:rn,args:o})}}const rn=s=>$(s),sn=s=>{const e=s.arg;return $(e===void 0?void 0:e.length===0)},on=s=>{const e=s.operand;return $(e===void 0?void 0:!e)},nn=s=>{const e=s.operand1,t=s.operand2;return $(e===void 0||t===void 0?void 0:e&&t)},an=s=>{const e=s.operand1,t=s.operand2;return $(e===void 0||t===void 0?void 0:e||t)},cn=s=>{const e=s.source;return e===void 0?$(void 0):({cCtx:t})=>{var r;return Qe((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},ln=s=>{const e=s.source,t=s.field;return $(e===void 0||t===void 0?void 0:e[t])};function un(s,e){return t=>{const r=t.source;return r===void 0?$(void 0):({cCtx:o})=>{const n=o.accessor(r).node(),i={};for(const c of n.listInputFields()){const a=n.traverse(c);if(a===void 0)i[c]=$(void 0);else{const l={...s,[e.itVar]:a.persist()};i[c]=I(l,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:dn,args:i}}}}const dn=s=>$(s),pn=s=>{const e=s.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:V.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r!==void 0)return await t.blobDriver.getContent(r.handle)}})})},fn=s=>{const e=s.source;return e===void 0?$(void 0):({cCtx:t,drivers:r})=>{const o=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:V.Computable.make(()=>r.blobDriver.getDownloadedBlob(o),{postprocessValue:async n=>n===void 0?void 0:(await r.blobDriver.getContent(n.handle)).toString()})}}},hn=s=>{const e=s.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:V.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r==null)return;const o=await t.blobDriver.getContent(r.handle);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},gn=s=>{const e=s.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},mn=s=>{const e=s.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},vn=s=>e=>{const t=e.source;return t===void 0?$(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.blobToURLDriver.extractArchiveAndGetURL(t,s)})},yn=s=>{const e=s.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},wn=s=>e=>{const t=e.source;return t===void 0?$(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},bn=s=>e=>{const t=e.source;return t===void 0?$(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},Sn=s=>e=>{const t=e.source;return t===void 0?$(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLogWithInfo(t,s)})},Pn=s=>{const e=s.source;return e===void 0?$(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function I(s,e){switch(e.type){case"GetFromCtx":{const t=s[e.variable];return typeof t=="function"?r=>Qe(t(r.cCtx)):$(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:ps(t,s,e.cfg)});case"Immediate":return $(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:ln,args:{source:I(s,e.source),field:I(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:en(s,e),args:{source:I(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:tn(s,e),args:{source:I(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:Yo,args:Wo(e.template,t=>I(s,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:ls(e.template.length),args:cs(e.template,t=>I(s,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:Qo,args:{source:I(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:sn,args:{arg:I(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:on,args:{operand:I(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:nn,args:{operand1:I(s,e.operand1),operand2:I(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:an,args:{operand1:I(s,e.operand1),operand2:I(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:un(s,e),args:{source:I(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:Zo,args:{source:I(s,e.source),field:I(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:cn,args:{source:I(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:pn,args:{source:I(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:fn,args:{source:I(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:hn,args:{source:I(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:gn,args:{source:I(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:mn,args:{source:I(s,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:vn(e.format),args:{source:I(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:yn,args:{source:I(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:wn(e.lines),args:{source:I(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:bn(e.patternToSearch),args:{source:I(s,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:Sn(e.patternToSearch),args:{source:I(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:Pn,args:{source:I(s,e.source)}});default:return E.assertNever(e)}}const Rn=["$prod","$staging"];function En(s){return{$blockId:s.blockId,$args:e=>JSON.parse(s.args(e)),$ui:e=>{const t=s.uiState(e);return t!==void 0?JSON.parse(t):void 0},$prod:s.prod,$staging:s.staging}}const us=Symbol(),ds="return",Cn={op:us,arg:ds};function kn(s){return s.op==us&&s.arg==ds}function On(){return{pendingSubroutines:new Map}}function fr(s,e,t,r){const o=new xr(t),n=(c,a)=>{if(kn(c))return e.result=a,!1;const l=E.notEmpty(e.pendingSubroutines.get(c.op));if(c.arg in l.args)throw new Error("argument already set");return l.args[c.arg]=a,l.argCounter--,l.argCounter===0&&(e.pendingSubroutines.delete(c.op),o.push({destination:l.destination,operation:l.subroutine(l.args)})),!0},i=[];e:for(;o.length>0;){const c=o.shift(),a=c.operation(s);switch(a.type){case"ReturnResult":if(!n(c.destination,a.result))break e;break;case"ScheduleSubroutine":{const l=Symbol(),u=Object.entries(a.args),d=u.length;if(d===0)o.push({destination:c.destination,operation:a.subroutine({})});else{for(const[p,f]of u)o.push({destination:{op:l,arg:p},operation:f});e.pendingSubroutines.set(l,{argCounter:d,args:{},subroutine:a.subroutine,destination:c.destination})}}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:c.destination,computable:a.computable});break;default:E.assertNever(a)}}return i}function Tn(s,e,t,r={}){return ps(s,En(e),t,r)}function ps(s,e,t,r={}){const o=`${e.blockId}#`+x({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>Rn.indexOf(n)===-1)),cfg:t});return V.Computable.makeRaw(n=>{const i={drivers:s,cCtx:n},c=On();return{ir:fr(i,c,[{destination:Cn,operation:I(e,t)}],!0),postprocessValue(l){const u=[];for(const C of l)u.push({destination:C.destination,operation:$(C.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},p=new Map;for(const[C,w]of c.pendingSubroutines)p.set(C,{...w,args:{...w.args}});const f={result:c.result,pendingSubroutines:p};if(fr(d,f,u,!1),!("result"in f))throw new Error("illegal cfg rendering stack state, no result");return f.result}}},{...r,key:o})}function hr(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class $n{constructor(e,t,r,o){S(this,"computablesToResolve",{});S(this,"computableCtx");S(this,"accessors",new Map);S(this,"meta");S(this,"_resultPool");this.parent=e,this.blockCtx=t,this.env=r,this.computableCtx=o,this.meta=t.blockMeta(o)}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,o)=>{if(!this.accessors.has(r)){const n=this.blockCtx[o];if(n===void 0)throw new Error("Staging context not available");const i=n(this.computableCtx);i?this.accessors.set(r,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(r,void 0)}return this.accessors.get(r)?r:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...r){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...r))}getResourceType(e){return this.getAccessor(e).resourceType}getInputsLocked(e){return this.getAccessor(e).getInputsLocked()}getOutputsLocked(e){return this.getAccessor(e).getOutputsLocked()}getIsReadyOrError(e){return this.getAccessor(e).getIsReadyOrError()}getIsFinal(e){return this.getAccessor(e).getIsFinal()}getError(e){return this.wrapAccessor(this.getAccessor(e).getError())}listInputFields(e){return this.getAccessor(e).listInputFields()}listOutputFields(e){return this.getAccessor(e).listOutputFields()}listDynamicFields(e){return this.getAccessor(e).listDynamicFields()}getKeyValueBase64(e,t){return hr(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return hr(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r,...o){const n=this.getAccessor(e);if(!n.getIsReadyOrError())return;const i=qo(n,t,r,o),c={};for(const[a,l]of Object.entries(i))c[a]=F.mapPObjectData(l,u=>this.wrapAccessor(u));return c}registerComputable(e,t){const r=`${e}_${ee.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",V.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("utf-8")}}))}getBlobContentAsBase64(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",V.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.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 r=this.getAccessor(e).persist();return this.registerComputable("extractArchiveAndGetURL",this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(r,t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(r,t))}getProgressLog(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(r,t))}getProgressLogWithInfo(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLogWithInfo",this.env.driverKit.logDriver.getProgressLogWithInfo(r,t))}getLogHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getLogHandle",this.env.driverKit.logDriver.getLogHandle(t))}getBlockLabel(e){const t=this.meta.get(e);if(t===void 0)throw new Error(`Block ${e} not found.`);return t.label}get resultPool(){if(this._resultPool===void 0){if(this.computableCtx===void 0)throw new Error("can't use result pool in this context (most porbably called from the future mapper)");this._resultPool=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:F.mapPObjectData(t.obj,r=>this.wrapAccessor(r))}))}}getDataWithErrorsFromResultPool(){const e=this.resultPool.getDataWithErrors();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:{id:t.obj.id,spec:t.obj.spec,data:F.mapValueInVOE(t.obj.data,r=>this.wrapAccessor(r))}}))}}getSpecsFromResultPool(){const e=this.resultPool.getSpecs();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`specs_from_pool_incomplete:${e.instabilityMarker}`),e}getSpecFromResultPoolByRef(e,t){return this.resultPool.getSpecByRef(e,t)}getDataFromResultPoolByRef(e,t){return F.mapPObjectData(this.resultPool.getDataByRef(e,t),r=>this.wrapAccessor(r))}createPFrame(e){if(this.computableCtx===void 0)throw new Error("can't instantiate PFrames from this context (most porbably called from the future mapper)");return this.env.driverKit.pFrameDriver.createPFrame(e.map(t=>F.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}createPTable(e){if(this.computableCtx===void 0)throw new Error("can't instantiate PTable from this context (most porbably called from the future mapper)");return this.env.driverKit.pFrameDriver.createPTable(F.mapPTableDef(e,t=>F.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}transformInputPData(e){return typeof e=="string"?this.getAccessor(e):F.isDataInfo(e)?F.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}}injectCtx(e){const t=this.parent,r=t.vm;pe.Scope.withScope(o=>{const n=this.blockCtx.args(this.computableCtx),i=this.blockCtx.activeArgs(this.computableCtx),c=this.blockCtx.uiState(this.computableCtx);r.setProp(e,"args",o.manage(r.newString(n))),c!==void 0&&r.setProp(e,"uiState",o.manage(r.newString(c))),i!==void 0&&r.setProp(e,"activeArgs",o.manage(r.newString(i)));const a=(l,u)=>{const d=(...p)=>{try{return u(...p)}catch(f){const C=t.errorRepo.setAndRecreateForQuickJS(f);throw r.newError(C)}};r.newFunction(l,d).consume(p=>r.setProp(e,l,p)),r.newFunction(l,u).consume(p=>r.setProp(e,l+"__internal__",p))};a("getAccessorHandleByName",l=>t.exportSingleValue(this.getAccessorHandleByName(r.getString(l)),void 0)),a("resolveWithCommon",(l,u,...d)=>t.exportSingleValue(this.resolveWithCommon(r.getString(l),t.importObjectViaJson(u),...d.map(p=>t.importObjectViaJson(p))),void 0)),a("getResourceType",l=>t.exportObjectViaJson(this.getResourceType(r.getString(l)),void 0)),a("getInputsLocked",l=>t.exportSingleValue(this.getInputsLocked(r.getString(l)),void 0)),a("getOutputsLocked",l=>t.exportSingleValue(this.getOutputsLocked(r.getString(l)),void 0)),a("getIsReadyOrError",l=>t.exportSingleValue(this.getIsReadyOrError(r.getString(l)),void 0)),a("getIsFinal",l=>t.exportSingleValue(this.getIsFinal(r.getString(l)),void 0)),a("getError",l=>t.exportSingleValue(this.getError(r.getString(l)),void 0)),a("listInputFields",l=>t.exportObjectViaJson(this.listInputFields(r.getString(l)),void 0)),a("listOutputFields",l=>t.exportObjectViaJson(this.listInputFields(r.getString(l)),void 0)),a("listDynamicFields",l=>t.exportObjectViaJson(this.listInputFields(r.getString(l)),void 0)),a("getKeyValueBase64",(l,u)=>t.exportSingleValue(this.getKeyValueBase64(r.getString(l),r.getString(u)),void 0)),a("getKeyValueAsString",(l,u)=>t.exportSingleValue(this.getKeyValueAsString(r.getString(l),r.getString(u)),void 0)),a("getDataBase64",l=>t.exportSingleValue(this.getDataBase64(r.getString(l)),void 0)),a("getDataAsString",l=>t.exportSingleValue(this.getDataAsString(r.getString(l)),void 0)),a("parsePObjectCollection",(l,u,d,...p)=>t.exportObjectUniversal(this.parsePObjectCollection(r.getString(l),r.dump(u),r.getString(d),...p.map(f=>r.getString(f))),void 0)),a("getBlobContentAsBase64",l=>t.exportSingleValue(this.getBlobContentAsBase64(r.getString(l)),void 0)),a("getBlobContentAsString",l=>t.exportSingleValue(this.getBlobContentAsString(r.getString(l)),void 0)),a("getDownloadedBlobContentHandle",l=>t.exportSingleValue(this.getDownloadedBlobContentHandle(r.getString(l)),void 0)),a("getOnDemandBlobContentHandle",l=>t.exportSingleValue(this.getOnDemandBlobContentHandle(r.getString(l)),void 0)),a("extractArchiveAndGetURL",(l,u)=>t.exportSingleValue(this.extractArchiveAndGetURL(r.getString(l),r.getString(u)),void 0)),a("getImportProgress",l=>t.exportSingleValue(this.getImportProgress(r.getString(l)),void 0)),a("getLastLogs",(l,u)=>t.exportSingleValue(this.getLastLogs(r.getString(l),r.getNumber(u)),void 0)),a("getProgressLog",(l,u)=>t.exportSingleValue(this.getProgressLog(r.getString(l),r.getString(u)),void 0)),a("getProgressLogWithInfo",(l,u)=>t.exportSingleValue(this.getProgressLogWithInfo(r.getString(l),r.getString(u)),void 0)),a("getLogHandle",l=>t.exportSingleValue(this.getLogHandle(r.getString(l)),void 0)),a("getBlockLabel",l=>t.exportSingleValue(this.getBlockLabel(r.getString(l)),void 0)),a("getDataFromResultPool",()=>t.exportObjectUniversal(this.getDataFromResultPool(),void 0)),a("getDataWithErrorsFromResultPool",()=>t.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),a("getSpecsFromResultPool",()=>t.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),a("calculateOptions",l=>t.exportObjectUniversal(this.calculateOptions(t.importObjectViaJson(l)),void 0)),a("getSpecFromResultPoolByRef",(l,u)=>t.exportObjectUniversal(this.getSpecFromResultPoolByRef(r.getString(l),r.getString(u)),void 0)),a("getDataFromResultPoolByRef",(l,u)=>t.exportObjectUniversal(this.getDataFromResultPoolByRef(r.getString(l),r.getString(u)),void 0)),a("createPFrame",l=>t.exportSingleValue(this.createPFrame(t.importObjectViaJson(l)),void 0)),a("createPTable",l=>t.exportSingleValue(this.createPTable(t.importObjectViaJson(l)),void 0)),a("getCurrentUnstableMarker",()=>t.exportSingleValue(this.getCurrentUnstableMarker(),void 0))})}}function In(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}class Fe{constructor(e,t,r,o){S(this,"callbackRegistry");S(this,"fnJSONStringify");S(this,"fnJSONParse");S(this,"errorRepo",new Fn);S(this,"computableHelper");if(this.scope=e,this.vm=t,this.deadlineSetter=r,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(n=>t.getProp(n,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(n=>t.getProp(n,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");o!==void 0&&(this.computableHelper=new $n(this,o.blockCtx,o.mlEnv,o.computableCtx)),this.injectCtx()}resetComputableCtx(){E.notEmpty(this.computableHelper,"Computable context helper is not initialized").resetComputableCtx()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.deadlineSetter({currentExecutionTarget:"evaluateBundle",deadline:Date.now()+1e4}),this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw Fe.cleanErrorContext(t),t}finally{this.deadlineSetter(void 0)}}runCallback(e,...t){try{return this.deadlineSetter({currentExecutionTarget:e,deadline:Date.now()+1e4}),pe.Scope.withScope(r=>{const o=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(o)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(o,this.vm.undefined,...t.map(n=>this.exportObjectUniversal(n,r)))))})}catch(r){throw Fe.cleanErrorContext(r),this.errorRepo.getOriginal(r)}finally{this.deadlineSetter(void 0)}}exportSingleValue(e,t){const r=this.tryExportSingleValue(e,t);if(r===void 0)throw new Error(`Can't export value: ${e===void 0?"undefined":JSON.stringify(e)}`);return r}tryExportSingleValue(e,t){let r,o=!1;switch(typeof e){case"string":r=this.vm.newString(e),o=!0;break;case"number":r=this.vm.newNumber(e),o=!0;break;case"undefined":r=this.vm.undefined;break;case"boolean":r=e?this.vm.true:this.vm.false;break;default:if(e===null){r=this.vm.null;break}if(In(e)){r=this.vm.newArrayBuffer(e),o=!0;break}return}return o&&t!=null?t.manage(r):r}exportObjectUniversal(e,t){const r=this.tryExportSingleValue(e,t);return r!==void 0?r:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const r=this.vm.newString(JSON.stringify(e)).consume(o=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,o)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){switch(this.vm.typeof(e)){case"undefined":return;case"boolean":case"number":case"string":return this.vm.dump(e);default:return this.importObjectViaJson(e)}}importObjectViaJson(e){const t=this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify,this.vm.undefined,e)).consume(r=>this.vm.getString(r));if(t!=="undefined")return JSON.parse(t)}injectCtx(){pe.Scope.withScope(e=>{const t=e.manage(this.vm.newObject());this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(F.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e)),this.computableHelper!==void 0&&this.computableHelper.injectCtx(t),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}class Fn{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 pe.errors.QuickJSUnwrapError))return console.warn("ErrorRepo: quickJSError is not a QuickJSUnwrapError",h.stringifyWithResourceId(e)),e;if(!("name"in e.cause))return console.warn("ErrorRepo: quickJSError.cause is not an Error",h.stringifyWithResourceId(e)),e;const t=e.cause.name,r=t.slice(t.indexOf("/uuid:")+6);if(!r)throw new Error(`ErrorRepo: quickJSError.cause.name does not contain errorId: ${t}, ${h.stringifyWithResourceId(e)}`);const o=this.errorIdToError.get(r);if(o===void 0)throw new Error(`ErrorRepo: errorId not found: ${r}, ${h.stringifyWithResourceId(e)}`);return new As.PlQuickJSError(e,o)}}function Ae(s,e){return Ce(s.traverse({field:_(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:h.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),o=F.extractConfig(r.config);return{bpResourceId:t.resourceInfo.id,bpId:t.resourceInfo.id.toString(),info:r,cfg:o}})}const xe=process.env.MI_LOG_OUTPUT_STATUS;function An(s,e,t,r,o,n={}){const i=`${e.blockId}#lambda#${o}#${t.handle}`;return n={...n,key:i},n.mode===void 0&&t.retentive===!0&&(n.mode="StableOnlyRetentive"),V.Computable.makeRaw(c=>{const a=new pe.Scope;c.addOnDestroy(()=>a.dispose());const l=a.manage(s.quickJs.newRuntime());l.setMemoryLimit(1024*1024*8),l.setMaxStackSize(1024*320);let u;l.setInterruptHandler(()=>u===void 0?!1:Date.now()>u.deadline);const d=a.manage(l.newContext()),p=new Fe(a,d,w=>{u=w},{computableCtx:c,blockCtx:e,mlEnv:s});p.evaluateBundle(r.content);const f=p.runCallback(t.handle);p.resetComputableCtx();let C=0;return xe&&xe!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:p.computableHelper.computablesToResolve,postprocessValue:(w,{unstableMarker:j,stable:N})=>{for(const[A,H]of Object.entries(w))p.runCallback(A,H);const U=p.importObjectUniversal(f);return C++,xe&&(xe!=="unstable-only"||!N)&&console.log(N?`Stable output ${t.handle} calculated ${U!==void 0?"defined":"undefined"}; (#${C})`:`Unstable output ${t.handle}; marker = ${j}; ${U!==void 0?"defined":"undefined"} (#${C})`),U}}},n)}function Ln(s,e,t,...r){const o=new pe.Scope;try{const n=o.manage(s.newRuntime());n.setMemoryLimit(1024*1024*8),n.setMaxStackSize(1024*320);let i;n.setInterruptHandler(()=>i===void 0?!1:Date.now()>i.deadline);const c=o.manage(n.newContext()),a=new Fe(o,c,l=>{i=l});return a.evaluateBundle(t.content),a.importObjectUniversal(a.runCallback(e.handle,...r))}finally{o.dispose()}}function Dn(s){return F.isConfigLambda(s)?s.isActive===!0:Xo(s)}function ke(s,e,t,r,o,n={}){if(F.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return An(s,e,t,r,o,n)}else return Tn(s.driverKit,e,t,n)}function Nn(s,e){if(s===e)return!0;if(s===void 0||e===void 0)return!1;const t=Qt.omitBy((r,o)=>o.startsWith("__"));return Qt.isDeepEqual(t(s),t(e))}function Bn(s,e,t){return V.Computable.make(r=>{var C,w,j,N,U,A,H,he;const o=r.accessor(s).node(),n=E.notEmpty(o.getKeyValueAsJson($t)),i=E.notEmpty(o.getKeyValueAsJson($e)),c=E.notEmpty(o.getKeyValueAsJson(Ie)),a=E.notEmpty(o.getKeyValueAsJson(fe)),l=E.notEmpty(o.getKeyValueAsJson(qe)),u=new Map;for(const{id:B}of ie(a)){const Y=o.traverse({field:_(B,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}),te=Y.getDataAsJson();let K;const re=o.traverse({field:_(B,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(re!==void 0){const se=re.getDataAsJson(),M=o.getField({field:_(B,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),q=o.getField({field:_(B,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});K={arguments:se,stale:!Nn(te,se),outputError:M.error!==void 0||q.error!==void 0||((C=M.value)==null?void 0:C.getError())!==void 0||((w=q.value)==null?void 0:w.getError())!==void 0,outputsError:((j=M.error)==null?void 0:j.getDataAsString())??((U=(N=M.value)==null?void 0:N.getError())==null?void 0:U.getDataAsString()),exportsError:((A=q.error)==null?void 0:A.getDataAsString())??((he=(H=q.value)==null?void 0:H.getError())==null?void 0:he.getDataAsString()),finished:(M.value!==void 0&&M.value.getIsReadyOrError()||M.error!==void 0&&M.error.getIsReadyOrError())&&(q.value!==void 0&&q.value.getIsReadyOrError()||q.error!==void 0&&q.error.getIsReadyOrError())}}u.set(B,{currentArguments:te,prod:K,argsRid:Y.resourceInfo.id})}const d=Ke(a,B=>{const Y=Ae(o,B),te=u.get(B),K=te.currentArguments;return{args:K,enrichmentTargets:t.projectHelper.getEnrichmentTargets(()=>Y.cfg,()=>K,{argsRid:te.argsRid,blockPackRid:Y.bpResourceId})}}),p=new Set(l.blocksInLimbo),f=[...ie(a)].map(({id:B,label:Y,renderingMode:te})=>{var v,P,T,k,L;const K=E.notEmpty(u.get(B)),re=E.notEmpty(d.nodes.get(B));let se="NotCalculated";K.prod!==void 0&&(p.has(B)?se="Limbo":se=K.prod.finished?"Done":"Running");const M=Ae(o,B),{sections:q,title:y,inputsValid:m,sdkVersion:R}=Ce(M,({bpId:G,cfg:D})=>{const ue=Dt(s,B);return{sections:ke(t,ue,D.sections,D.code,G).wrap({recover:be=>(t.logger.error("Error in block model sections"),t.logger.error(be),[])}),title:Ce(D.title,be=>ke(t,ue,be,D.code,G).wrap({recover:Es=>(t.logger.error("Error in block model title"),t.logger.error(Es),"Invalid title")})),inputsValid:ke(t,ue,D.inputsValid,D.code,G).wrap({recover:be=>(t.logger.error("Error in block model argsValid"),t.logger.error(be),!1)}),sdkVersion:D.sdkVersion}})||{},g=o.traverse({field:_(B,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),b=Ce(M,({info:G})=>t.blockUpdateWatcher.get({currentSpec:G.source,settings:g}));return{projectResourceId:h.resourceIdToString(s.rid),id:B,label:y??Y,title:y??Y,renderingMode:te,stale:((v=K.prod)==null?void 0:v.stale)!==!1||se==="Limbo",missingReference:re.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",B)],downstreams:[...d.traverseIdsExcludingRoots("downstream",B)],calculationStatus:se,outputErrors:((P=K.prod)==null?void 0:P.outputError)===!0,outputsError:(T=K.prod)==null?void 0:T.outputsError,exportsError:(k=K.prod)==null?void 0:k.exportsError,settings:g,sections:q,inputsValid:m,updateInfo:{},currentBlockPack:(L=M==null?void 0:M.info)==null?void 0:L.source,updates:b,sdkVersion:R,navigationState:e.getState(B)}});return{meta:c,created:new Date(n),lastModified:new Date(i),authorMarker:o.getKeyValueAsJson(vt),blocks:f}},{postprocessValue:r=>{const o=new Set,n=new Set;return{...r,blocks:r.blocks.map(i=>{var u,d;i.inputsValid||o.add(i.id),i.stale&&n.add(i.id);const c=i.stale||i.upstreams.findIndex(p=>n.has(p))!==-1,a=(c||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(p=>o.has(p))===-1,l={...i,canRun:a,stale:c,updateSuggestions:((u=i.updates)==null?void 0:u.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete l.updates,l})}}}).withStableType()}function jn(s,e){const t=s.node();if(h.resourceTypesEqual(t.resourceType,Ft)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.frontendDownloadDriver.getPath(new URL(r.url)).withStableType()}else if(h.resourceTypesEqual(t.resourceType,At)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.signer.verify(r.path,r.signature,`Frontend path signature mismatch for: ${r.path}`),r.path}else throw new Error(`Unsupported resource type: ${JSON.stringify(t.resourceType)}`)}function Vn(s,e){if(s!==void 0)return V.Computable.make(t=>jn(t.accessor(s),e),{postprocessValue:t=>{if(t!==void 0){if(typeof t=="string")return t;if(t.error!==void 0)throw new Error(t.error);return t.path}}}).withStableType()}function xn(s,e,t){return V.Computable.make(r=>{var c;const o=r.accessor(s).node(),n=Ae(o,e),i=(c=o.traverse({field:_(e,"blockPack"),assertFieldType:"Dynamic"},{field:h.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:ss,assertFieldType:"Input"}))==null?void 0:c.persist();return{path:Vn(i,t),sdkVersion:n==null?void 0:n.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function fs(s,e,t){if(t===void 0)return V.Computable.make(i=>fs(s,e,i),{key:`inputs#${h.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),o=Dt(s,e),n=o.uiState(t);return{author:r.getKeyValueAsJson(mt(e)),args:E.deepFreeze(JSON.parse(o.args(t))),ui:n!==void 0?E.deepFreeze(JSON.parse(n)):void 0}}function Un(s,e,t){return V.Computable.make(r=>{const o=r.accessor(s).node(),n=as(s,e);return Ce(Ae(o,e),({cfg:i,bpId:c})=>{const a={};for(const[l,u]of Object.entries(i.outputs)){const d=ke(t,n,u,i.code,c);a[l]=V.Computable.wrapError(d,1)}return a})},{key:"outputs#"+h.resourceIdToString(s.rid)+"#"+e}).withStableType()}function Gn(s,e){return V.Computable.make(t=>{const r=t.accessor(s).node(),o=E.notEmpty(r.getKeyValueAsJson(fe)),n=[];for(const{id:i}of ie(o)){const c=Ae(r,i);if(c===void 0)continue;const a=Object.entries(c.cfg.outputs).map(([,u])=>u).filter(u=>Dn(u)).map(u=>u);if(a.length===0)continue;const l=as(r.persist(),i);for(const u of a)n.push(V.Computable.wrapError(ke(e,l,u,c.cfg.code,c.bpId)))}return n})}class Mn{constructor(){S(this,"states",new Map)}setState(e,t){const r=this.states.get(e);if(r===void 0){this.states.set(e,{state:t,change:new V.ChangeSource});return}r.state={...t},r.change.markChanged()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...F.DefaultNavigationState},change:new V.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return V.Computable.make(t=>this.readState(t,e),{key:`navigationState#${e}`})}deleteBlock(e){const t=this.states.get(e);t!==void 0&&(this.states.delete(e),t.change.markChanged())}}function gr(s){return JSON.stringify(s,(e,t)=>typeof t=="bigint"?h.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,r){S(this,"rid");S(this,"overview");S(this,"navigationStates",new Mn);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=r,this.overview=Bn(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=Gn(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await Ve(this.env.projectHelper,this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await Ur.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(h.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!h.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,o=void 0,n=ee.randomUUID()){const i=await this.env.bpPreparer.prepare(t),c=await this.env.bpPreparer.getBlockConfigContainer(t),a=F.extractConfig(c);return await ne(this.env.projectHelper,this.env.pl,this.rid,o,l=>l.addBlock({id:n,label:e,renderingMode:a.renderingMode},{args:x(a.initialArgs),uiState:x(a.initialUiState),blockPack:i},r)),await this.projectTree.refreshState(),n}async updateBlockPack(e,t,r=!1,o){const n=await this.env.bpPreparer.prepare(t),i=F.extractConfig(await this.env.bpPreparer.getBlockConfigContainer(t));await ne(this.env.projectHelper,this.env.pl,this.rid,o,c=>c.migrateBlockPack(e,n,r?{args:x(i.initialArgs),uiState:x(i.initialUiState)}:void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await ne(this.env.projectHelper,this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await ne(this.env.projectHelper,this.env.pl,this.rid,t,r=>{const o=r.structure;if(o.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const n=o.groups[0];if(n.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${n.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const i={groups:[{id:n.id,label:n.label,blocks:e.map(c=>{const a=n.blocks.find(l=>l.id===c);if(a===void 0)throw new Error(`Can't find block: ${c}`);return a})}]};r.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await Ve(this.env.projectHelper,this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await Ve(this.env.projectHelper,this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await ne(this.env.projectHelper,this.env.pl,this.rid,r,o=>o.setArgs([{blockId:e,args:x(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await ne(this.env.projectHelper,this.env.pl,this.rid,r,o=>o.setUiState(e,t===void 0?void 0:x(t))),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,o){await ne(this.env.projectHelper,this.env.pl,this.rid,o,n=>{n.setArgs([{blockId:e,args:x(t)}]),n.setUiState(e,x(r))}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await ne(this.env.projectHelper,this.env.pl,this.rid,void 0,r=>{r.setBlockSettings(e,t)}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async r=>{const o=h.ensureResourceIdNotNull((await r.getField(h.field(this.rid,_(e,"blockPack")))).value),n=h.ensureResourceIdNotNull((await r.getField(h.field(o,h.Pl.HolderRefField))).value),i=await r.getResourceData(n,!1),c=F.extractConfig(E.cachedDeserialize(E.notEmpty(i.data)).config);await ne(this.env.projectHelper,r,this.rid,t,a=>{a.setArgs([{blockId:e,args:x(c.initialArgs)}]),a.setUiState(e,x(c.initialUiState))}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===void 0){const r=Un(this.projectTree.entry(),e,this.env),n={fullState:V.Computable.make(i=>({argsAndUiState:fs(this.projectTree.entry(),e,i),outputs:r,navigationState:this.navigationStates.getState(e),overview:this.overview}),{postprocessValue:i=>{var u,d,p;const c=(p=(d=(u=i.overview)==null?void 0:u.blocks)==null?void 0:d.find(f=>f.id==e))==null?void 0:p.sdkVersion,l=c&&_n(c)&&i.outputs!==void 0?Hn(i.outputs):i.outputs;return{...i.argsAndUiState,outputs:l,navigationState:i.navigationState}}}).withPreCalculatedValueTree()};return this.blockComputables.set(e,n),n}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=xn(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,r),r}return t}async destroy(){this.destroyed=!0,this.abortController.abort(),await this.refreshLoopResult,await this.projectTree.terminate(),this.overview.resetState(),this.blockFrontends.forEach(e=>e.resetState()),this.blockComputables.forEach(e=>{e.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){await Ve(e.projectHelper,e.pl,t,o=>{});const r=await He.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:Jn},e.logger);if(e.ops.debugOps.dumpInitialTreeState){const o=r.dumpState();o.sort((i,c)=>{var a,l;return(((a=c.data)==null?void 0:a.byteLength)??0)-(((l=i.data)==null?void 0:l.byteLength)??0)});const n=He.treeDumpStats(o);await ht.writeFile(`${h.resourceIdToString(t)}.json`,gr(o)),await ht.writeFile(`${h.resourceIdToString(t)}.stats.json`,gr(n))}return new Ze(e,t,r)}}function Jn(s){switch(s.type.name){case"BlockPackCustom":return s.fields.filter(e=>e.name!=="template");case"UserProject":return s.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return s.fields}}function _n(s){return!Kn(s,"1.26.0")}function Kn(s,e){const t=s.split(".").map(Number),r=e.split(".").map(Number);return t[0]>r[0]||t[0]===r[0]&&t[1]>r[1]||t[0]===r[0]&&t[1]===r[1]&&t[2]>r[2]}function Hn(s){const e={};for(const[t,r]of Object.entries(s)){if(r.ok){e[t]=r;continue}e[t]={ok:!1,errors:r.errors.map(o=>typeof o=="string"?o:o.type=="PlError"&&o.fullMessage!==void 0?o.fullMessage:o.message),moreErrors:r.moreErrors}}return e}const Nt={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 Bt(s){return{blobDownloadPath:J.join(s,"download"),downloadBlobToURLPath:J.join(s,"downloadToURL"),pframesSpillPath:J.join(s,"pframes")}}const hs={...Nt,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500,initialTreeLoadingTimeout:100*60*60*1e3},debugOps:{dumpInitialTreeState:!1},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function gs(s){return{...Bt(s),frontendDownloadPath:J.join(s,"frontend")}}function qn(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Pt={exports:{}};const Wn="2.0.0",ms=256,zn=Number.MAX_SAFE_INTEGER||9007199254740991,Xn=16,Yn=ms-6,Qn=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var et={MAX_LENGTH:ms,MAX_SAFE_COMPONENT_LENGTH:Xn,MAX_SAFE_BUILD_LENGTH:Yn,MAX_SAFE_INTEGER:zn,RELEASE_TYPES:Qn,SEMVER_SPEC_VERSION:Wn,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)?(...s)=>console.error("SEMVER",...s):()=>{};var tt=Zn;(function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:o}=et,n=tt;e=s.exports={};const i=e.re=[],c=e.safeRe=[],a=e.src=[],l=e.safeSrc=[],u=e.t={};let d=0;const p="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",o],[p,r]],C=j=>{for(const[N,U]of f)j=j.split(`${N}*`).join(`${N}{0,${U}}`).split(`${N}+`).join(`${N}{1,${U}}`);return j},w=(j,N,U)=>{const A=C(N),H=d++;n(j,H,N),u[j]=H,a[H]=N,l[H]=A,i[H]=new RegExp(N,U?"g":void 0),c[H]=new RegExp(A,U?"g":void 0)};w("NUMERICIDENTIFIER","0|[1-9]\\d*"),w("NUMERICIDENTIFIERLOOSE","\\d+"),w("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),w("MAINVERSION",`(${a[u.NUMERICIDENTIFIER]})\\.(${a[u.NUMERICIDENTIFIER]})\\.(${a[u.NUMERICIDENTIFIER]})`),w("MAINVERSIONLOOSE",`(${a[u.NUMERICIDENTIFIERLOOSE]})\\.(${a[u.NUMERICIDENTIFIERLOOSE]})\\.(${a[u.NUMERICIDENTIFIERLOOSE]})`),w("PRERELEASEIDENTIFIER",`(?:${a[u.NUMERICIDENTIFIER]}|${a[u.NONNUMERICIDENTIFIER]})`),w("PRERELEASEIDENTIFIERLOOSE",`(?:${a[u.NUMERICIDENTIFIERLOOSE]}|${a[u.NONNUMERICIDENTIFIER]})`),w("PRERELEASE",`(?:-(${a[u.PRERELEASEIDENTIFIER]}(?:\\.${a[u.PRERELEASEIDENTIFIER]})*))`),w("PRERELEASELOOSE",`(?:-?(${a[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${a[u.PRERELEASEIDENTIFIERLOOSE]})*))`),w("BUILDIDENTIFIER",`${p}+`),w("BUILD",`(?:\\+(${a[u.BUILDIDENTIFIER]}(?:\\.${a[u.BUILDIDENTIFIER]})*))`),w("FULLPLAIN",`v?${a[u.MAINVERSION]}${a[u.PRERELEASE]}?${a[u.BUILD]}?`),w("FULL",`^${a[u.FULLPLAIN]}$`),w("LOOSEPLAIN",`[v=\\s]*${a[u.MAINVERSIONLOOSE]}${a[u.PRERELEASELOOSE]}?${a[u.BUILD]}?`),w("LOOSE",`^${a[u.LOOSEPLAIN]}$`),w("GTLT","((?:<|>)?=?)"),w("XRANGEIDENTIFIERLOOSE",`${a[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),w("XRANGEIDENTIFIER",`${a[u.NUMERICIDENTIFIER]}|x|X|\\*`),w("XRANGEPLAIN",`[v=\\s]*(${a[u.XRANGEIDENTIFIER]})(?:\\.(${a[u.XRANGEIDENTIFIER]})(?:\\.(${a[u.XRANGEIDENTIFIER]})(?:${a[u.PRERELEASE]})?${a[u.BUILD]}?)?)?`),w("XRANGEPLAINLOOSE",`[v=\\s]*(${a[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[u.XRANGEIDENTIFIERLOOSE]})(?:${a[u.PRERELEASELOOSE]})?${a[u.BUILD]}?)?)?`),w("XRANGE",`^${a[u.GTLT]}\\s*${a[u.XRANGEPLAIN]}$`),w("XRANGELOOSE",`^${a[u.GTLT]}\\s*${a[u.XRANGEPLAINLOOSE]}$`),w("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),w("COERCE",`${a[u.COERCEPLAIN]}(?:$|[^\\d])`),w("COERCEFULL",a[u.COERCEPLAIN]+`(?:${a[u.PRERELEASE]})?(?:${a[u.BUILD]})?(?:$|[^\\d])`),w("COERCERTL",a[u.COERCE],!0),w("COERCERTLFULL",a[u.COERCEFULL],!0),w("LONETILDE","(?:~>?)"),w("TILDETRIM",`(\\s*)${a[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",w("TILDE",`^${a[u.LONETILDE]}${a[u.XRANGEPLAIN]}$`),w("TILDELOOSE",`^${a[u.LONETILDE]}${a[u.XRANGEPLAINLOOSE]}$`),w("LONECARET","(?:\\^)"),w("CARETTRIM",`(\\s*)${a[u.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",w("CARET",`^${a[u.LONECARET]}${a[u.XRANGEPLAIN]}$`),w("CARETLOOSE",`^${a[u.LONECARET]}${a[u.XRANGEPLAINLOOSE]}$`),w("COMPARATORLOOSE",`^${a[u.GTLT]}\\s*(${a[u.LOOSEPLAIN]})$|^$`),w("COMPARATOR",`^${a[u.GTLT]}\\s*(${a[u.FULLPLAIN]})$|^$`),w("COMPARATORTRIM",`(\\s*)${a[u.GTLT]}\\s*(${a[u.LOOSEPLAIN]}|${a[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",w("HYPHENRANGE",`^\\s*(${a[u.XRANGEPLAIN]})\\s+-\\s+(${a[u.XRANGEPLAIN]})\\s*$`),w("HYPHENRANGELOOSE",`^\\s*(${a[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${a[u.XRANGEPLAINLOOSE]})\\s*$`),w("STAR","(<|>)?=?\\s*\\*"),w("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),w("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(Pt,Pt.exports);var Le=Pt.exports;const ei=Object.freeze({loose:!0}),ti=Object.freeze({}),ri=s=>s?typeof s!="object"?ei:s:ti;var jt=ri;const mr=/^[0-9]+$/,vs=(s,e)=>{const t=mr.test(s),r=mr.test(e);return t&&r&&(s=+s,e=+e),s===e?0:t&&!r?-1:r&&!t?1:s<e?-1:1},si=(s,e)=>vs(e,s);var ys={compareIdentifiers:vs,rcompareIdentifiers:si};const Ue=tt,{MAX_LENGTH:vr,MAX_SAFE_INTEGER:Ge}=et,{safeRe:yr,safeSrc:wr,t:Me}=Le,oi=jt,{compareIdentifiers:ge}=ys;let ni=class le{constructor(e,t){if(t=oi(t),e instanceof le){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>vr)throw new TypeError(`version is longer than ${vr} characters`);Ue("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const r=e.trim().match(t.loose?yr[Me.LOOSE]:yr[Me.FULL]);if(!r)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>Ge||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Ge||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Ge||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){const n=+o;if(n>=0&&n<Ge)return n}return o}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(Ue("SemVer.compare",this.version,this.options,e),!(e instanceof le)){if(typeof e=="string"&&e===this.version)return 0;e=new le(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof le||(e=new le(e,this.options)),ge(this.major,e.major)||ge(this.minor,e.minor)||ge(this.patch,e.patch)}comparePre(e){if(e instanceof le||(e=new le(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{const r=this.prerelease[t],o=e.prerelease[t];if(Ue("prerelease compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return ge(r,o)}while(++t)}compareBuild(e){e instanceof le||(e=new le(e,this.options));let t=0;do{const r=this.build[t],o=e.build[t];if(Ue("build compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return ge(r,o)}while(++t)}inc(e,t,r){if(e.startsWith("pre")){if(!t&&r===!1)throw new Error("invalid increment argument: identifier is empty");if(t){const o=new RegExp(`^${this.options.loose?wr[Me.PRERELEASELOOSE]:wr[Me.PRERELEASE]}$`),n=`-${t}`.match(o);if(!n||n[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,r),this.inc("pre",t,r);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const o=Number(r)?1:0;if(this.prerelease.length===0)this.prerelease=[o];else{let n=this.prerelease.length;for(;--n>=0;)typeof this.prerelease[n]=="number"&&(this.prerelease[n]++,n=-2);if(n===-1){if(t===this.prerelease.join(".")&&r===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(t){let n=[t,o];r===!1&&(n=[t]),ge(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 X=ni;const br=X,ii=(s,e,t=!1)=>{if(s instanceof br)return s;try{return new br(s,e)}catch(r){if(!t)return null;throw r}};var we=ii;const ai=we,ci=(s,e)=>{const t=ai(s,e);return t?t.version:null};var li=ci;const ui=we,di=(s,e)=>{const t=ui(s.trim().replace(/^[=v]+/,""),e);return t?t.version:null};var pi=di;const Sr=X,fi=(s,e,t,r,o)=>{typeof t=="string"&&(o=r,r=t,t=void 0);try{return new Sr(s instanceof Sr?s.version:s,t).inc(e,r,o).version}catch{return null}};var hi=fi;const Pr=we,gi=(s,e)=>{const t=Pr(s,null,!0),r=Pr(e,null,!0),o=t.compare(r);if(o===0)return null;const n=o>0,i=n?t:r,c=n?r:t,a=!!i.prerelease.length;if(!!c.prerelease.length&&!a){if(!c.patch&&!c.minor)return"major";if(c.compareMain(i)===0)return c.minor&&!c.patch?"minor":"patch"}const u=a?"pre":"";return t.major!==r.major?u+"major":t.minor!==r.minor?u+"minor":t.patch!==r.patch?u+"patch":"prerelease"};var mi=gi;const vi=X,yi=(s,e)=>new vi(s,e).major;var wi=yi;const bi=X,Si=(s,e)=>new bi(s,e).minor;var Pi=Si;const Ri=X,Ei=(s,e)=>new Ri(s,e).patch;var Ci=Ei;const ki=we,Oi=(s,e)=>{const t=ki(s,e);return t&&t.prerelease.length?t.prerelease:null};var Ti=Oi;const Rr=X,$i=(s,e,t)=>new Rr(s,t).compare(new Rr(e,t));var ae=$i;const Ii=ae,Fi=(s,e,t)=>Ii(e,s,t);var Ai=Fi;const Li=ae,Di=(s,e)=>Li(s,e,!0);var Ni=Di;const Er=X,Bi=(s,e,t)=>{const r=new Er(s,t),o=new Er(e,t);return r.compare(o)||r.compareBuild(o)};var Vt=Bi;const ji=Vt,Vi=(s,e)=>s.sort((t,r)=>ji(t,r,e));var xi=Vi;const Ui=Vt,Gi=(s,e)=>s.sort((t,r)=>Ui(r,t,e));var Mi=Gi;const Ji=ae,_i=(s,e,t)=>Ji(s,e,t)>0;var rt=_i;const Ki=ae,Hi=(s,e,t)=>Ki(s,e,t)<0;var xt=Hi;const qi=ae,Wi=(s,e,t)=>qi(s,e,t)===0;var ws=Wi;const zi=ae,Xi=(s,e,t)=>zi(s,e,t)!==0;var bs=Xi;const Yi=ae,Qi=(s,e,t)=>Yi(s,e,t)>=0;var Ut=Qi;const Zi=ae,ea=(s,e,t)=>Zi(s,e,t)<=0;var Gt=ea;const ta=ws,ra=bs,sa=rt,oa=Ut,na=xt,ia=Gt,aa=(s,e,t,r)=>{switch(e){case"===":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s===t;case"!==":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s!==t;case"":case"=":case"==":return ta(s,t,r);case"!=":return ra(s,t,r);case">":return sa(s,t,r);case">=":return oa(s,t,r);case"<":return na(s,t,r);case"<=":return ia(s,t,r);default:throw new TypeError(`Invalid operator: ${e}`)}};var Ss=aa;const ca=X,la=we,{safeRe:Je,t:_e}=Le,ua=(s,e)=>{if(s instanceof ca)return s;if(typeof s=="number"&&(s=String(s)),typeof s!="string")return null;e=e||{};let t=null;if(!e.rtl)t=s.match(e.includePrerelease?Je[_e.COERCEFULL]:Je[_e.COERCE]);else{const a=e.includePrerelease?Je[_e.COERCERTLFULL]:Je[_e.COERCERTL];let l;for(;(l=a.exec(s))&&(!t||t.index+t[0].length!==s.length);)(!t||l.index+l[0].length!==t.index+t[0].length)&&(t=l),a.lastIndex=l.index+l[1].length+l[2].length;a.lastIndex=-1}if(t===null)return null;const r=t[2],o=t[3]||"0",n=t[4]||"0",i=e.includePrerelease&&t[5]?`-${t[5]}`:"",c=e.includePrerelease&&t[6]?`+${t[6]}`:"";return la(`${r}.${o}.${n}${i}${c}`,e)};var da=ua;class pa{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 fa=pa,ct,Cr;function ce(){if(Cr)return ct;Cr=1;const s=/\s+/g;class e{constructor(m,R){if(R=o(R),m instanceof e)return m.loose===!!R.loose&&m.includePrerelease===!!R.includePrerelease?m:new e(m.raw,R);if(m instanceof n)return this.raw=m.value,this.set=[[m]],this.formatted=void 0,this;if(this.options=R,this.loose=!!R.loose,this.includePrerelease=!!R.includePrerelease,this.raw=m.trim().replace(s," "),this.set=this.raw.split("||").map(g=>this.parseRange(g.trim())).filter(g=>g.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const g=this.set[0];if(this.set=this.set.filter(b=>!w(b[0])),this.set.length===0)this.set=[g];else if(this.set.length>1){for(const b of this.set)if(b.length===1&&j(b[0])){this.set=[b];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let m=0;m<this.set.length;m++){m>0&&(this.formatted+="||");const R=this.set[m];for(let g=0;g<R.length;g++)g>0&&(this.formatted+=" "),this.formatted+=R[g].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(m){const g=((this.options.includePrerelease&&f)|(this.options.loose&&C))+":"+m,b=r.get(g);if(b)return b;const v=this.options.loose,P=v?a[l.HYPHENRANGELOOSE]:a[l.HYPHENRANGE];m=m.replace(P,M(this.options.includePrerelease)),i("hyphen replace",m),m=m.replace(a[l.COMPARATORTRIM],u),i("comparator trim",m),m=m.replace(a[l.TILDETRIM],d),i("tilde trim",m),m=m.replace(a[l.CARETTRIM],p),i("caret trim",m);let T=m.split(" ").map(D=>U(D,this.options)).join(" ").split(/\s+/).map(D=>se(D,this.options));v&&(T=T.filter(D=>(i("loose invalid filter",D,this.options),!!D.match(a[l.COMPARATORLOOSE])))),i("range list",T);const k=new Map,L=T.map(D=>new n(D,this.options));for(const D of L){if(w(D))return[D];k.set(D.value,D)}k.size>1&&k.has("")&&k.delete("");const G=[...k.values()];return r.set(g,G),G}intersects(m,R){if(!(m instanceof e))throw new TypeError("a Range is required");return this.set.some(g=>N(g,R)&&m.set.some(b=>N(b,R)&&g.every(v=>b.every(P=>v.intersects(P,R)))))}test(m){if(!m)return!1;if(typeof m=="string")try{m=new c(m,this.options)}catch{return!1}for(let R=0;R<this.set.length;R++)if(q(this.set[R],m,this.options))return!0;return!1}}ct=e;const t=fa,r=new t,o=jt,n=st(),i=tt,c=X,{safeRe:a,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:p}=Le,{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:C}=et,w=y=>y.value==="<0.0.0-0",j=y=>y.value==="",N=(y,m)=>{let R=!0;const g=y.slice();let b=g.pop();for(;R&&g.length;)R=g.every(v=>b.intersects(v,m)),b=g.pop();return R},U=(y,m)=>(i("comp",y,m),y=B(y,m),i("caret",y),y=H(y,m),i("tildes",y),y=te(y,m),i("xrange",y),y=re(y,m),i("stars",y),y),A=y=>!y||y.toLowerCase()==="x"||y==="*",H=(y,m)=>y.trim().split(/\s+/).map(R=>he(R,m)).join(" "),he=(y,m)=>{const R=m.loose?a[l.TILDELOOSE]:a[l.TILDE];return y.replace(R,(g,b,v,P,T)=>{i("tilde",y,g,b,v,P,T);let k;return A(b)?k="":A(v)?k=`>=${b}.0.0 <${+b+1}.0.0-0`:A(P)?k=`>=${b}.${v}.0 <${b}.${+v+1}.0-0`:T?(i("replaceTilde pr",T),k=`>=${b}.${v}.${P}-${T} <${b}.${+v+1}.0-0`):k=`>=${b}.${v}.${P} <${b}.${+v+1}.0-0`,i("tilde return",k),k})},B=(y,m)=>y.trim().split(/\s+/).map(R=>Y(R,m)).join(" "),Y=(y,m)=>{i("caret",y,m);const R=m.loose?a[l.CARETLOOSE]:a[l.CARET],g=m.includePrerelease?"-0":"";return y.replace(R,(b,v,P,T,k)=>{i("caret",y,b,v,P,T,k);let L;return A(v)?L="":A(P)?L=`>=${v}.0.0${g} <${+v+1}.0.0-0`:A(T)?v==="0"?L=`>=${v}.${P}.0${g} <${v}.${+P+1}.0-0`:L=`>=${v}.${P}.0${g} <${+v+1}.0.0-0`:k?(i("replaceCaret pr",k),v==="0"?P==="0"?L=`>=${v}.${P}.${T}-${k} <${v}.${P}.${+T+1}-0`:L=`>=${v}.${P}.${T}-${k} <${v}.${+P+1}.0-0`:L=`>=${v}.${P}.${T}-${k} <${+v+1}.0.0-0`):(i("no pr"),v==="0"?P==="0"?L=`>=${v}.${P}.${T}${g} <${v}.${P}.${+T+1}-0`:L=`>=${v}.${P}.${T}${g} <${v}.${+P+1}.0-0`:L=`>=${v}.${P}.${T} <${+v+1}.0.0-0`),i("caret return",L),L})},te=(y,m)=>(i("replaceXRanges",y,m),y.split(/\s+/).map(R=>K(R,m)).join(" ")),K=(y,m)=>{y=y.trim();const R=m.loose?a[l.XRANGELOOSE]:a[l.XRANGE];return y.replace(R,(g,b,v,P,T,k)=>{i("xRange",y,g,b,v,P,T,k);const L=A(v),G=L||A(P),D=G||A(T),ue=D;return b==="="&&ue&&(b=""),k=m.includePrerelease?"-0":"",L?b===">"||b==="<"?g="<0.0.0-0":g="*":b&&ue?(G&&(P=0),T=0,b===">"?(b=">=",G?(v=+v+1,P=0,T=0):(P=+P+1,T=0)):b==="<="&&(b="<",G?v=+v+1:P=+P+1),b==="<"&&(k="-0"),g=`${b+v}.${P}.${T}${k}`):G?g=`>=${v}.0.0${k} <${+v+1}.0.0-0`:D&&(g=`>=${v}.${P}.0${k} <${v}.${+P+1}.0-0`),i("xRange return",g),g})},re=(y,m)=>(i("replaceStars",y,m),y.trim().replace(a[l.STAR],"")),se=(y,m)=>(i("replaceGTE0",y,m),y.trim().replace(a[m.includePrerelease?l.GTE0PRE:l.GTE0],"")),M=y=>(m,R,g,b,v,P,T,k,L,G,D,ue)=>(A(g)?R="":A(b)?R=`>=${g}.0.0${y?"-0":""}`:A(v)?R=`>=${g}.${b}.0${y?"-0":""}`:P?R=`>=${R}`:R=`>=${R}${y?"-0":""}`,A(L)?k="":A(G)?k=`<${+L+1}.0.0-0`:A(D)?k=`<${L}.${+G+1}.0-0`:ue?k=`<=${L}.${G}.${D}-${ue}`:y?k=`<${L}.${G}.${+D+1}-0`:k=`<=${k}`,`${R} ${k}`.trim()),q=(y,m,R)=>{for(let g=0;g<y.length;g++)if(!y[g].test(m))return!1;if(m.prerelease.length&&!R.includePrerelease){for(let g=0;g<y.length;g++)if(i(y[g].semver),y[g].semver!==n.ANY&&y[g].semver.prerelease.length>0){const b=y[g].semver;if(b.major===m.major&&b.minor===m.minor&&b.patch===m.patch)return!0}return!1}return!0};return ct}var lt,kr;function st(){if(kr)return lt;kr=1;const s=Symbol("SemVer ANY");class e{static get ANY(){return s}constructor(u,d){if(d=t(d),u instanceof e){if(u.loose===!!d.loose)return u;u=u.value}u=u.trim().split(/\s+/).join(" "),i("comparator",u,d),this.options=d,this.loose=!!d.loose,this.parse(u),this.semver===s?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(u){const d=this.options.loose?r[o.COMPARATORLOOSE]:r[o.COMPARATOR],p=u.match(d);if(!p)throw new TypeError(`Invalid comparator: ${u}`);this.operator=p[1]!==void 0?p[1]:"",this.operator==="="&&(this.operator=""),p[2]?this.semver=new c(p[2],this.options.loose):this.semver=s}toString(){return this.value}test(u){if(i("Comparator.test",u,this.options.loose),this.semver===s||u===s)return!0;if(typeof u=="string")try{u=new c(u,this.options)}catch{return!1}return n(u,this.operator,this.semver,this.options)}intersects(u,d){if(!(u instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new a(u.value,d).test(this.value):u.operator===""?u.value===""?!0:new a(this.value,d).test(u.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||u.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||u.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&u.operator.startsWith(">")||this.operator.startsWith("<")&&u.operator.startsWith("<")||this.semver.version===u.semver.version&&this.operator.includes("=")&&u.operator.includes("=")||n(this.semver,"<",u.semver,d)&&this.operator.startsWith(">")&&u.operator.startsWith("<")||n(this.semver,">",u.semver,d)&&this.operator.startsWith("<")&&u.operator.startsWith(">")))}}lt=e;const t=jt,{safeRe:r,t:o}=Le,n=Ss,i=tt,c=X,a=ce();return lt}const ha=ce(),ga=(s,e,t)=>{try{e=new ha(e,t)}catch{return!1}return e.test(s)};var ot=ga;const ma=ce(),va=(s,e)=>new ma(s,e).set.map(t=>t.map(r=>r.value).join(" ").trim().split(" "));var ya=va;const wa=X,ba=ce(),Sa=(s,e,t)=>{let r=null,o=null,n=null;try{n=new ba(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===-1)&&(r=i,o=new wa(r,t))}),r};var Pa=Sa;const Ra=X,Ea=ce(),Ca=(s,e,t)=>{let r=null,o=null,n=null;try{n=new Ea(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===1)&&(r=i,o=new Ra(r,t))}),r};var ka=Ca;const ut=X,Oa=ce(),Or=rt,Ta=(s,e)=>{s=new Oa(s,e);let t=new ut("0.0.0");if(s.test(t)||(t=new ut("0.0.0-0"),s.test(t)))return t;t=null;for(let r=0;r<s.set.length;++r){const o=s.set[r];let n=null;o.forEach(i=>{const c=new ut(i.semver.version);switch(i.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!n||Or(c,n))&&(n=c);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),n&&(!t||Or(t,n))&&(t=n)}return t&&s.test(t)?t:null};var $a=Ta;const Ia=ce(),Fa=(s,e)=>{try{return new Ia(s,e).range||"*"}catch{return null}};var Aa=Fa;const La=X,Ps=st(),{ANY:Da}=Ps,Na=ce(),Ba=ot,Tr=rt,$r=xt,ja=Gt,Va=Ut,xa=(s,e,t,r)=>{s=new La(s,r),e=new Na(e,r);let o,n,i,c,a;switch(t){case">":o=Tr,n=ja,i=$r,c=">",a=">=";break;case"<":o=$r,n=Va,i=Tr,c="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Ba(s,e,r))return!1;for(let l=0;l<e.set.length;++l){const u=e.set[l];let d=null,p=null;if(u.forEach(f=>{f.semver===Da&&(f=new Ps(">=0.0.0")),d=d||f,p=p||f,o(f.semver,d.semver,r)?d=f:i(f.semver,p.semver,r)&&(p=f)}),d.operator===c||d.operator===a||(!p.operator||p.operator===c)&&n(s,p.semver))return!1;if(p.operator===a&&i(s,p.semver))return!1}return!0};var Mt=xa;const Ua=Mt,Ga=(s,e,t)=>Ua(s,e,">",t);var Ma=Ga;const Ja=Mt,_a=(s,e,t)=>Ja(s,e,"<",t);var Ka=_a;const Ir=ce(),Ha=(s,e,t)=>(s=new Ir(s,t),e=new Ir(e,t),s.intersects(e,t));var qa=Ha;const Wa=ot,za=ae;var Xa=(s,e,t)=>{const r=[];let o=null,n=null;const i=s.sort((u,d)=>za(u,d,t));for(const u of i)Wa(u,e,t)?(n=u,o||(o=u)):(n&&r.push([o,n]),n=null,o=null);o&&r.push([o,null]);const c=[];for(const[u,d]of r)u===d?c.push(u):!d&&u===i[0]?c.push("*"):d?u===i[0]?c.push(`<=${d}`):c.push(`${u} - ${d}`):c.push(`>=${u}`);const a=c.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return a.length<l.length?a:e};const Fr=ce(),Jt=st(),{ANY:dt}=Jt,Se=ot,_t=ae,Ya=(s,e,t={})=>{if(s===e)return!0;s=new Fr(s,t),e=new Fr(e,t);let r=!1;e:for(const o of s.set){for(const n of e.set){const i=Za(o,n,t);if(r=r||i!==null,i)continue e}if(r)return!1}return!0},Qa=[new Jt(">=0.0.0-0")],Ar=[new Jt(">=0.0.0")],Za=(s,e,t)=>{if(s===e)return!0;if(s.length===1&&s[0].semver===dt){if(e.length===1&&e[0].semver===dt)return!0;t.includePrerelease?s=Qa:s=Ar}if(e.length===1&&e[0].semver===dt){if(t.includePrerelease)return!0;e=Ar}const r=new Set;let o,n;for(const f of s)f.operator===">"||f.operator===">="?o=Lr(o,f,t):f.operator==="<"||f.operator==="<="?n=Dr(n,f,t):r.add(f.semver);if(r.size>1)return null;let i;if(o&&n){if(i=_t(o.semver,n.semver,t),i>0)return null;if(i===0&&(o.operator!==">="||n.operator!=="<="))return null}for(const f of r){if(o&&!Se(f,String(o),t)||n&&!Se(f,String(n),t))return null;for(const C of e)if(!Se(f,String(C),t))return!1;return!0}let c,a,l,u,d=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1,p=o&&!t.includePrerelease&&o.semver.prerelease.length?o.semver:!1;d&&d.prerelease.length===1&&n.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(const f of e){if(u=u||f.operator===">"||f.operator===">=",l=l||f.operator==="<"||f.operator==="<=",o){if(p&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===p.major&&f.semver.minor===p.minor&&f.semver.patch===p.patch&&(p=!1),f.operator===">"||f.operator===">="){if(c=Lr(o,f,t),c===f&&c!==o)return!1}else if(o.operator===">="&&!Se(o.semver,String(f),t))return!1}if(n){if(d&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===d.major&&f.semver.minor===d.minor&&f.semver.patch===d.patch&&(d=!1),f.operator==="<"||f.operator==="<="){if(a=Dr(n,f,t),a===f&&a!==n)return!1}else if(n.operator==="<="&&!Se(n.semver,String(f),t))return!1}if(!f.operator&&(n||o)&&i!==0)return!1}return!(o&&l&&!n&&i!==0||n&&u&&!o&&i!==0||p||d)},Lr=(s,e,t)=>{if(!s)return e;const r=_t(s.semver,e.semver,t);return r>0?s:r<0||e.operator===">"&&s.operator===">="?e:s},Dr=(s,e,t)=>{if(!s)return e;const r=_t(s.semver,e.semver,t);return r<0?s:r>0||e.operator==="<"&&s.operator==="<="?e:s};var ec=Ya;const pt=Le,Nr=et,tc=X,Br=ys,rc=we,sc=li,oc=pi,nc=hi,ic=mi,ac=wi,cc=Pi,lc=Ci,uc=Ti,dc=ae,pc=Ai,fc=Ni,hc=Vt,gc=xi,mc=Mi,vc=rt,yc=xt,wc=ws,bc=bs,Sc=Ut,Pc=Gt,Rc=Ss,Ec=da,Cc=st(),kc=ce(),Oc=ot,Tc=ya,$c=Pa,Ic=ka,Fc=$a,Ac=Aa,Lc=Mt,Dc=Ma,Nc=Ka,Bc=qa,jc=Xa,Vc=ec;var xc={parse:rc,valid:sc,clean:oc,inc:nc,diff:ic,major:ac,minor:cc,patch:lc,prerelease:uc,compare:dc,rcompare:pc,compareLoose:fc,compareBuild:hc,sort:gc,rsort:mc,gt:vc,lt:yc,eq:wc,neq:bc,gte:Sc,lte:Pc,cmp:Rc,coerce:Ec,Comparator:Cc,Range:kc,satisfies:Oc,toComparators:Tc,maxSatisfying:$c,minSatisfying:Ic,minVersion:Fc,validRange:Ac,outside:Lc,gtr:Dc,ltr:Nc,intersects:Bc,simplifyRange:jc,subset:Vc,SemVer:tc,re:pt.re,src:pt.src,tokens:pt.t,SEMVER_SPEC_VERSION:Nr.SEMVER_SPEC_VERSION,RELEASE_TYPES:Nr.RELEASE_TYPES,compareIdentifiers:Br.compareIdentifiers,rcompareIdentifiers:Br.rcompareIdentifiers};const Uc=qn(xc),Gc={minDelay:1500},Mc="__no_updates__";class Jc extends V.PollComputablePool{constructor(t,r,o={}){super({...o,...Gc},r);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 Mc}}async readValue(t){var r,o;try{const n=t.currentSpec;switch(n.type){case"dev-v1":try{const i=await Tt(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 z.tryLoadPackDescription(n.folder,this.logger);if(i===void 0)return{suggestions:[]};const c=await Xe(i);return c===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:c},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:i,skipVersion:c}=t.settings;if(i==="patch")return{suggestions:[]};const a=this.registryProvider.getRegistry(n.registryUrl);let l=this.preferredUpdateChannel;if(l===void 0)if(n.channel===void 0)if(await a.getLatestOverview(n.id,W.StableChannel))l=W.StableChannel;else{if(await a.getLatestOverview(n.id,W.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${W.blockPackIdToString(n.id)}`),{suggestions:[]};l=W.AnyChannel}else l=n.channel;const u=await a.getUpdateSuggestions(n.id,l);if(u===void 0||u.length===0)return{suggestions:[]};u.reverse();let d;switch(i){case void 0:d=u[0].update;break;case"major":d=(r=u.find(C=>C.type!=="major"))==null?void 0:r.update;break;case"minor":d=(o=u.find(C=>C.type==="patch"))==null?void 0:o.update;break}const p=u.map(({type:C,update:w})=>({type:C,update:{...n,id:{...n.id,version:w}}}));if(d===void 0)return{suggestions:p};if(c!==void 0&&Uc.lte(d,c))return{suggestions:p};const f={...n,id:{...n.id,version:d}};return(async()=>{try{await a.getComponents(f.id)}catch(C){this.logger.warn(C)}})(),{suggestions:p,mainSuggestion:f}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(n){return this.logger.warn(n),{suggestions:[]}}}resultsEqual(t,r){return x(t)===x(r)}}class jr{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 r=this.resources.get(t);r===void 0&&(r={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,r)),r.refCount++;let o=!1;return{resource:r.resource,key:t,unref:()=>{o||(r.refCount--,o=!0,this.check(t))}}}getByKey(e){if(!this.resources.has(e))throw new Error(`resource not found, key = ${e}`);return this.resources.get(e).resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}let Pe;function de(){return Pe||(Pe={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0,dumpInitialTreeState:process.env.MI_DUMP_INITIAL_TREE_STATE!==void 0},process.env.MI_LOG_TREE_STAT&&(Pe.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),Pe)}function Oe(s){return String(s.id)}const _c=["Int","Long","Float","Double","String","Bytes"];function ft(s){const e=[],t=[];for(const r of s)r.type==="bySingleColumn"?(e.push(r),t.push({...r,type:"bySingleColumnV2"})):t.push(r);if(e.length>0){const r=JSON.stringify(e);console.warn(`type overriten from 'bySingleColumn' to 'bySingleColumnV2' for filters: ${r}`)}return t}const Re=(s,e)=>typeof e=="bigint"?e.toString():e;class Kc{constructor(e,t,r,o,n){S(this,"pFrame");S(this,"blobIdToResource",new Map);S(this,"blobHandleComputables",new Map);S(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.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),r=this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);return await this.blobContentCache.forceFetch(r)}catch(t){const r=JSON.stringify(t);throw console.log(`resolveBlobContent catched error: ${r}`),t}});this.blobDriver=e,this.logger=t,this.spillPath=r,this.blobContentCache=o;const i=(a,l)=>this.logger[a](l);for(const a of n)for(const l of Bo(a.data))this.blobIdToResource.set(Oe(l),l);const c=[...new Map(n.map(a=>({...a,data:jo(a.data,Oe)})).map(a=>[x(a),a])).values()];try{const a=new Ds.PFrame(this.spillPath,de().logPFrameRequests?i:void 0);a.setDataSource(this);for(const l of c)a.addColumnSpec(l.id,l.spec),a.setColumnData(l.id,l.data);this.pFrame=a}catch(a){throw new Error(`Rust PFrame creation failed, columns: ${JSON.stringify(c)}, error: ${a}`)}}getOrCreateComputableForBlob(e){let t=this.blobHandleComputables.get(e);if(t!==void 0)return t;const r=this.blobIdToResource.get(e);if(r===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(r).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}[Symbol.dispose](){for(const e of this.blobHandleComputables.values())e.resetState();this.pFrame.dispose()}}class Hc{constructor(e){this.table=e}[Symbol.dispose](){this.table.then(e=>e.dispose())}}class Kt{constructor(e,t,r){S(this,"pFrames");S(this,"pTables");S(this,"concurrencyLimiter");this.blobDriver=e,this.logger=t,this.spillPath=r;const o=new Et.LRUCache({maxSize:1e9,fetchMethod:async i=>await Gr.readFile(i),sizeCalculation:i=>i.length}),n=new E.ConcurrencyLimitingExecutor(4);this.concurrencyLimiter=n,this.pFrames=new class extends jr{constructor(i,c,a){super(),this.blobDriver=i,this.logger=c,this.spillPath=a}createNewResource(i){return de().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(i)}): ${JSON.stringify(i,Re)}`),new Kc(this.blobDriver,this.logger,this.spillPath,o,i)}calculateParamsKey(i){return Wc(i)}}(this.blobDriver,this.logger,this.spillPath),this.pTables=new class extends jr{constructor(i){super(),this.pFrames=i}createNewResource(i){const c=i.pFrameHandle;de().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(i)}): ${JSON.stringify(i,Re)}`);const a=n.run(async()=>await this.pFrames.getByKey(c).pFrame.createTable({src:Te(i.def.src),filters:ft(i.def.filters)},i.signal)).then(async l=>{if(i.def.sorting.length===0)return l;try{return n.run(async()=>await l.sort(i.def.sorting,i.signal))}finally{l.dispose()}});return new Hc(a)}calculateParamsKey(i){return qc(i)}}(this.pFrames)}static async init(e,t,r){const o=Bs.resolve(r);return await E.emptyDir(o),new Kt(e,t,o)}createPFrame(e,t){const r=e.filter(n=>_c.find(i=>i===n.spec.valueType)).map(n=>F.mapPObjectData(n,i=>He.isPlTreeNodeAccessor(i)?Jo(i):F.isDataInfo(i)?F.mapDataInfo(i,c=>c.resourceInfo):_o(n.spec,i))),o=this.pFrames.acquire(r);return t.addOnDestroy(o.unref),o.key}createPTable(e,t,r){const o=this.createPFrame(F.extractAllColumns(e.src),t),n=F.mapPTableDef(e,c=>c.id),i=this.pTables.acquire({def:n,pFrameHandle:o,signal:r});return de().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${o}; pTableHandle = ${JSON.stringify(i)}): ${JSON.stringify(F.mapPTableDef(e,c=>c.spec),Re)}`),t.addOnDestroy(i.unref),i.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:[...new Map(t.compatibleWith.map(n=>[x(n),n])).values()],qualifications:[]}]:[]};return{hits:(await this.pFrames.getByKey(e).pFrame.findColumns(r)).hits.filter(n=>n.mappingVariants.length===0||n.mappingVariants.some(i=>i.qualifications.forHit.length===0&&i.qualifications.forQueries.every(c=>c.length===0))).map(n=>n.hit)}}async getColumnSpec(e,t){return await this.pFrames.getByKey(e).pFrame.getColumnSpec(t)}async listColumns(e){return await this.pFrames.getByKey(e).pFrame.listColumns()}async calculateTableData(e,t,r){return de().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,Re)}`),await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.createTable({src:Te(t.src),filters:ft(t.filters)},r)).then(async o=>{if(t.sorting.length===0)return o;try{return await this.concurrencyLimiter.run(async()=>await o.sort(t.sorting,r))}finally{o.dispose()}}).then(async o=>{try{const n=o.getSpec(),i=await this.concurrencyLimiter.run(async()=>await o.getData([...n.keys()],void 0,r));return n.map((c,a)=>({spec:c,data:i[a]}))}finally{o.dispose()}})}async getUniqueValues(e,t,r){return de().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,Re)}`),await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.getUniqueValues({...t,filters:ft(t.filters)},r))}async getShape(e){return(await this.pTables.getByKey(e).table).getShape()}async getSpec(e){return(await this.pTables.getByKey(e).table).getSpec()}async getData(e,t,r,o){const n=await this.pTables.getByKey(e).table;return await this.concurrencyLimiter.run(async()=>await n.getData(t,r,o))}}function Te(s){switch(s.type){case"column":return{type:"column",columnId:s.column};case"slicedColumn":return{type:"slicedColumn",columnId:s.column,newId:s.newId,axisFilters:s.axisFilters};case"inner":case"full":return{type:s.type,entries:s.entries.map(e=>Te(e))};case"outer":return{type:"outer",primary:Te(s.primary),secondary:s.secondary.map(e=>Te(e))};default:E.assertNever(s)}}function qc(s){const e=ee.createHash("sha256");return e.update(x(s)),e.digest().toString("hex")}function Wc(s){const e=[...s].map(r=>F.mapPObjectData(r,o=>{let n;const i=o.type;switch(i){case"Json":n={type:o.type,keyLength:o.keyLength,payload:Object.entries(o.data).map(([c,a])=>({key:c,value:a}))};break;case"JsonPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([c,a])=>({key:c,value:Oe(a)}))};break;case"BinaryPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([c,a])=>({key:c,value:[Oe(a.index),Oe(a.values)]}))};break;default:throw Error(`unsupported resource type: ${JSON.stringify(i)}`)}return n.payload.sort((c,a)=>c.key.localeCompare(a.key)),n}));e.sort((r,o)=>r.id.localeCompare(o.id));const t=ee.createHash("sha256");return t.update(x(e)),t.digest().toString("hex")}async function Rs(s,e,t){const r={...Nt,...Bt(e),...t},o=new E.HmacSha256Signer(r.localSecret),n=oe.createDownloadClient(r.logger,s,r.localProjections),i=oe.createLogsClient(s,r.logger),c=oe.createUploadBlobClient(s,r.logger),a=oe.createUploadProgressClient(s,r.logger),l=new oe.DownloadDriver(r.logger,n,i,r.blobDownloadPath,o,r.blobDriverOps),u=new oe.DownloadBlobToURLDriver(r.logger,o,n,r.downloadBlobToURLPath,r.downloadBlobToURLDriverOps),d=new oe.UploadDriver(r.logger,o,c,a,r.uploadDriverOps),p=new oe.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),f=new oe.LogsDriver(r.logger,p,l),C=await oe.LsDriver.init(r.logger,s,o,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),w=await Kt.init(l,r.logger,r.pframesSpillPath);return{blobDriver:l,blobToURLDriver:u,logDriver:f,lsDriver:C,signer:o,uploadDriver:d,pFrameDriver:w}}class zc{constructor(e){S(this,"enrichmentTargetsCache",new Et.LRUCache({max:256,memoMethod:(e,t,{context:r})=>({value:this.calculateEnrichmentTargets(r)})}));this.quickJs=e}calculateEnrichmentTargets(e){const t=e.blockConfig();if(t.enrichmentTargets===void 0)return;const r=e.args();return Ln(this.quickJs,t.enrichmentTargets,t.code,r)}getEnrichmentTargets(e,t,r){const o={blockConfig:e,args:t};if(r===void 0)return this.calculateEnrichmentTargets(o);const n=`${r.argsRid}:${r.blockPackRid}`;return this.enrichmentTargetsCache.memo(n,{context:o}).value}}class Ht{constructor(e,t,r,o,n,i,c,a){S(this,"pl");S(this,"projectList");S(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=o,this.openedProjectsList=n,this.projectListTree=i,this.blockRegistryProvider=c,this.projectList=a,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=ee.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async o=>{const n=await No(o,e);return o.createField(h.field(this.projectListResourceId,t),"Dynamic",n),await o.commit(),await h.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await ne(this.env.projectHelper,this.pl,e,r,o=>{o.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(h.field(this.projectListResourceId,e)),await t.commit()}),await this.projectListTree.refreshState()}async projectIdToResourceId(e){return await this.pl.withReadTx("Project id to resource id",async t=>{const r=(await t.getField(h.field(this.projectListResourceId,e))).value;if(h.isNullResourceId(r))throw new Error("Unexpected project list structure.");return r})}async ensureProjectRid(e){return typeof e=="string"?await this.projectIdToResourceId(e):e}async openProject(e){const t=await this.ensureProjectRid(e);if(this.openedProjectsByRid.has(t))throw new Error(`Project ${t} already opened`);this.openedProjectsByRid.set(t,await 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,r){const o={...hs,...gs(t),...r};o.defaultTreeOptions.logStat=de().logTreeStats,o.debugOps.dumpInitialTreeState=de().dumpInitialTreeState;const n=await e.withWriteTx("MLInitialization",async j=>{const N=h.field(j.clientRoot,no);j.createField(N,"Dynamic");const U=await j.getField(N);if(h.isNullResourceId(U.value)){const A=j.createEphemeral(Hr);return j.lock(A),j.setField(N,A),await j.commit(),await A.globalId}else return U.value}),i=o.logger,c=await Rs(e,t,o),a=new ze.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),l=new Jr(a),u=new To(l,c.signer,a),d=new oe.DownloadUrlDriver(i,e.httpDispatcher,o.frontendDownloadPath),p=await pe.getQuickJS(),f={pl:e,signer:c.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:a,ops:o,bpPreparer:u,frontendDownloadDriver:d,driverKit:c,blockUpdateWatcher:new Jc(l,i,{minDelay:o.devBlockUpdateRecheckInterval,http:a,preferredUpdateChannel:o.preferredUpdateChannel}),quickJs:p,projectHelper:new zc(p)},C=new V.WatchableValue([]),w=await ao(e,n,C,f);return new Ht(f,c,c.signer,n,C,w.tree,l,w.computable)}}const Xc=["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 Yc(s,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},r=[];Xc.forEach(a=>{Ns.channel(a).subscribe(u=>{var p;const d=new Date().toISOString();(p=u==null?void 0:u.response)!=null&&p.headers&&(u.response.headers=u.response.headers.map(f=>f.toString())),r.push(JSON.stringify({timestamp:d,event:a,data:u}))})});const o={plPings:[],blockRegistryOverviewChecks:[],blockGARegistryOverviewChecks:[],blockRegistryUiChecks:[],blockGARegistryUiChecks:[],autoUpdateCdnChecks:[]},n=h.plAddressToConfig(s,{defaultRequestTimeout:t.pingTimeoutMs});o.plPings=await me(t.pingCheckDurationMs,t.maxPingsPerSecond,async()=>{const l=await new h.UnauthenticatedPlClient(n).ping();return JSON.stringify(l).slice(0,t.bodyLimit)+"..."});const c=new h.UnauthenticatedPlClient(n).ll.httpDispatcher;return o.blockRegistryOverviewChecks=await me(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Ee(new URL(t.blockOverviewPath,t.blockRegistryUrl),t,c)),o.blockGARegistryOverviewChecks=await me(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Ee(new URL(t.blockOverviewPath,t.blockGARegistryUrl),t,c)),o.blockRegistryUiChecks=await me(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Ee(new URL(t.blockUiPath,t.blockRegistryUrl),t,c)),o.blockGARegistryUiChecks=await me(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Ee(new URL(t.blockUiPath,t.blockGARegistryUrl),t,c)),o.autoUpdateCdnChecks=await me(t.autoUpdateCdnDurationMs,t.maxAutoUpdateCdnChecksPerSecond,async()=>await Ee(t.autoUpdateCdnUrl,t,c)),Qc(o,s,t,r)}async function me(s,e,t){const r=Rt(),o=[];for(;Vr(r)<s;){const n=Rt();let i;try{i={ok:!0,value:await t()}}catch(l){i={ok:!1,error:l}}const c=Vr(n);o.push({elapsedMs:c,response:i});const a=1e3/e-c;a>0&&await Ur.setTimeout(a)}return o}async function Ee(s,e,t){const{body:r,statusCode:o}=await ze.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),n=await r.text();return{statusCode:o,beginningOfBody:n.slice(0,e.bodyLimit)+"..."}}function Qc(s,e,t,r){const o=s.plPings.filter(c=>c.response.ok),n=s.plPings.filter(c=>!c.response.ok),i=[...new Set(o.map(c=>JSON.stringify(c.response.value)))];return`
2
2
  Network report:
3
3
  pl endpoint: ${e};
4
4
  options: ${JSON.stringify(t,null,2)}.
@@ -31,7 +31,7 @@ Auto-update CDN dumps:
31
31
  ${JSON.stringify(s.autoUpdateCdnChecks,null,2)}
32
32
 
33
33
  Platforma pings error dumps:
34
- ${JSON.stringify(o,null,2)}
34
+ ${JSON.stringify(n,null,2)}
35
35
 
36
36
  Platforma pings success dump examples:
37
37
  ${JSON.stringify(i,null,2)}
@@ -39,11 +39,11 @@ ${JSON.stringify(i,null,2)}
39
39
  Undici logs:
40
40
  ${r.join(`
41
41
  `)}
42
- `}function ve(s){const e=s.filter(n=>n.response.ok),{mean:t,median:r}=Zc(s);return`
42
+ `}function ve(s){const e=s.filter(o=>o.response.ok),{mean:t,median:r}=Zc(s);return`
43
43
  total: ${s.length};
44
44
  successes: ${e.length};
45
45
  errors: ${s.length-e.length};
46
46
  mean in ms: ${t};
47
47
  median in ms: ${r};
48
- `}function Zc(s){const e=s.map(n=>n.elapsedMs),t=e.reduce((n,o)=>n+o)/e.length;let r;if(e.length>0){const n=Math.floor(e.length/2);r=e.length%2?e[n]:(e[n-1]+e[n])/2}return{mean:t,median:r}}function Rt(){return Date.now()}function Vr(s){return Rt()-s}exports.BlockPackRegistry=_s;exports.CentralBlockRegistry=Ks;exports.DefaultDriverKitOpsPaths=Bt;exports.DefaultDriverKitOpsSettings=Nt;exports.DefaultMiddleLayerOpsPaths=gs;exports.DefaultMiddleLayerOpsSettings=hs;exports.FrontendFromFolderResourceType=At;exports.FrontendFromUrlResourceType=Ft;exports.MiddleLayer=Ht;exports.Project=Ze;exports.TengoTemplateGet=Yr;exports.TengoTemplateGetRegistry=Qr;exports.TengoTemplateGetTemplate=es;exports.TengoTemplateGetTemplateURI=Zr;exports.TengoTemplatePack=wn;exports.TengoTemplatePackConvert=bn;exports.TengoTemplatePackConvertTemplate=Pn;exports.TengoTemplatePackConvertTemplatePack=Sn;exports.V1CentralDevSnapshotRegistry=qs;exports.V1CentralRegistry=Hs;exports.V2RegistryProvider=Jr;exports.checkNetwork=Yc;exports.createRenderTemplate=It;exports.getDevV1PacketMtime=Tt;exports.getDevV2PacketMtime=Xe;exports.initDriverKit=Rs;exports.loadTemplate=Ye;exports.prepareTemplateSpec=ts;Object.keys(F).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>F[s]})});Object.keys(W).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>W[s]})});Object.keys(Yt).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>Yt[s]})});Object.keys(h).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>h[s]})});
48
+ `}function Zc(s){const e=s.map(o=>o.elapsedMs),t=e.reduce((o,n)=>o+n)/e.length;let r;if(e.length>0){const o=Math.floor(e.length/2);r=e.length%2?e[o]:(e[o-1]+e[o])/2}return{mean:t,median:r}}function Rt(){return Date.now()}function Vr(s){return Rt()-s}exports.BlockPackRegistry=_s;exports.CentralBlockRegistry=Ks;exports.DefaultDriverKitOpsPaths=Bt;exports.DefaultDriverKitOpsSettings=Nt;exports.DefaultMiddleLayerOpsPaths=gs;exports.DefaultMiddleLayerOpsSettings=hs;exports.FrontendFromFolderResourceType=At;exports.FrontendFromUrlResourceType=Ft;exports.MiddleLayer=Ht;exports.Project=Ze;exports.TengoTemplateGet=Yr;exports.TengoTemplateGetRegistry=Qr;exports.TengoTemplateGetTemplate=es;exports.TengoTemplateGetTemplateURI=Zr;exports.TengoTemplatePack=wo;exports.TengoTemplatePackConvert=bo;exports.TengoTemplatePackConvertTemplate=Po;exports.TengoTemplatePackConvertTemplatePack=So;exports.V1CentralDevSnapshotRegistry=qs;exports.V1CentralRegistry=Hs;exports.V2RegistryProvider=Jr;exports.checkNetwork=Yc;exports.createRenderTemplate=It;exports.getDevV1PacketMtime=Tt;exports.getDevV2PacketMtime=Xe;exports.initDriverKit=Rs;exports.loadTemplate=Ye;exports.prepareTemplateSpec=ts;Object.keys(F).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>F[s]})});Object.keys(W).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>W[s]})});Object.keys(Yt).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>Yt[s]})});Object.keys(h).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>h[s]})});
49
49
  //# sourceMappingURL=index.js.map