@milaboratories/pl-middle-layer 1.23.2 → 1.23.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 os=Object.defineProperty;var ns=(s,e,t)=>e in s?os(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var S=(s,e,t)=>ns(s,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const x=require("@platforma-sdk/model"),U=require("@milaboratories/pl-model-middle-layer"),ae=require("undici"),_=require("@platforma-sdk/block-tools"),Z=require("node:fs"),W=require("node:path"),is=require("yaml"),E=require("@milaboratories/ts-helpers"),as=require("node:fs/promises"),cs=require("@milaboratories/resolve-helper"),f=require("@milaboratories/pl-client"),Ge=require("@milaboratories/pl-tree"),D=require("@milaboratories/computable"),ne=require("node:crypto"),A=require("@milaboratories/pl-model-backend"),br=require("denque"),ls=require("@platforma-sdk/workflow-tengo"),me=require("canonicalize"),us=require("node:assert"),Be=require("quickjs-emscripten"),Sr=require("node:timers/promises"),te=require("@milaboratories/pl-drivers"),ds=require("@milaboratories/pframes-node"),ps=require("lru-cache"),hs=require("node:diagnostics_channel");function fs(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 Pr=fs(as);async function jt(s){try{return await Pr.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const gs=[_.RegistryV1.PlPackageYamlConfigFile],ms=[_.RegistryV1.PlPackageJsonConfigFile],vt=["backend","dist","tengo","tpl","main.plj.gz"],yt=["config","dist","config.json"],Cr=["frontend","dist"],xt="block-model/dist/config.json",vs="block-ui/package.json",ys=[vt,yt,gs,ms,Cr];async function ws(s){return await jt(W.join(s,...yt))!==void 0||await jt(W.join(s,...vt))!==void 0}function Ze(s,e){const t=cs.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function Vt(s,e){if(W.isAbsolute(s)||(s=W.resolve(s)),await ws(s))return{workflow:W.join(s,...vt),config:W.join(s,...yt),ui:W.join(s,...Cr)};{const t=Ze(s,xt),r=Ze(s,xt),o=Ze(s,vs);return{workflow:t,config:r,ui:W.resolve(o,"..","dist")}}}async function bs(s){try{return await Z.promises.readFile(s,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}async function Ss(s){try{return await Z.promises.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}async function wt(s){let e=0n;for(const t of ys){const r=W.join(s,...t),o=await Ss(r);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function Je(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 Ps{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 ae.request(`${r.url}/${_.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const c of i){const{organization:a,package:l,latestMeta:u,latestVersion:d}=c,v={organization:a,name:l,version:d},h={id:v,meta:{title:u.title??"No title",description:u.description??"No Description",organization:{name:a,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:v,registryUrl:r.url}};t.push({registryId:e.id,id:v,latestByChannel:{[U.AnyChannel]:h,[U.StableChannel]:h},allVersions:c.allVersions.map(g=>({version:g,channels:[]}))})}return t;case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(c=>c.latestByChannel[U.StableChannel]?{...c,registryId:e.id}:{...c,latestByChannel:{...c.latestByChannel,[U.StableChannel]:(a=>a.spec.type==="from-registry-v2"?{...a,spec:{...a.spec,channel:U.StableChannel}}:a)(c.latestByChannel[U.AnyChannel])},registryId:e.id});case"local-dev":for(const c of await Z.promises.readdir(r.path,{withFileTypes:!0})){if(!c.isDirectory())continue;const a=W.join(r.path,c.name),l=await bs(W.join(a,_.RegistryV1.PlPackageYamlConfigFile));if(l!==void 0){const u=_.RegistryV1.PlPackageConfigData.parse(is.parse(l)),d=await wt(a),v={organization:u.organization,name:u.package,version:"DEV"},h={id:v,meta:{title:u.meta.title??"No title",description:u.meta.description??"No Description",organization:{name:u.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:a,mtime:d}};t.push({registryId:e.id,id:v,latestByChannel:{[U.AnyChannel]:h,[U.StableChannel]:h},allVersions:[]})}else{let u=a,d=await _.tryLoadPackDescription(u);if(d===void 0){for(const v of["block","meta"])if(u=W.join(a,v),d=await _.tryLoadPackDescription(u),d!==void 0)break}if(d!==void 0){const v=await Je(d),h={id:d.id,meta:await _.BlockPackMetaEmbedAbsoluteBytes.parseAsync(d.meta),spec:{type:"dev-v2",folder:u,mtime:v}};t.push({registryId:e.id,id:d.id,latestByChannel:{[U.AnyChannel]:h,[U.StableChannel]:h},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 Er{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 _.RegistryV2Reader(_.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const Cs={type:"remote-v2",url:"https://blocks.pl-open.science/"},Es={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},Rs={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},ks={groups:[{id:"default",label:"Default",blocks:[]}]},Os={stagingRefreshTimestamp:0,blocksInLimbo:[]},$s={label:"New Project"},Ts={name:"UserProject",version:"2"},Rr="SchemaVersion",kr="1",bt="ProjectCreated",Re="ProjectLastModified",ke="ProjectMeta",ue="ProjectStructure",je="BlockRenderingState",Is="BlockFrontendState/",Fs=/^BlockFrontendState\/(?<blockid>.*)$/;function ct(s){return`${Is}${s}`}const Ns="BlockArgsAuthor/";function lt(s){return`${Ns}${s}`}const ut="ProjectStructureAuthor";function As(s){const e=s.match(Fs);if(e!==null)return e.groups.blockid}const Ls="__serviceTemplate_";function dt(s){return`${Ls}${s}`}function J(s,e){return`${s}-${e}`}const Ds=/^(?<blockId>.*)-(?<fieldName>blockPack|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function Bs(s){const e=s.match(Ds);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const js="projects",Or={name:"Projects",version:"1"},xs=s=>f.resourceTypesEqual(s.type,Or)?s.fields:[];async function Vs(s,e,t,r){const o=await Ge.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:xs},r.logger);return{computable:D.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 v=E.notEmpty(d.getKeyValueAsJson(ke)),h=E.notEmpty(d.getKeyValueAsJson(bt)),g=E.notEmpty(d.getKeyValueAsJson(Re));l.push({id:u,rid:d.id,created:new Date(h),lastModified:new Date(g),opened:a.indexOf(d.id)>=0,meta:v})}return l.sort(u=>-u.lastModified.valueOf()),l}).withStableType(),tree:o}}const Us={name:"EphRenderTemplate",version:"1"},Gs={name:"RenderTemplate",version:"1"};function St(s,e,t,r,o){if(o.length===0)throw new Error("Zero output names provided");const n=t?s.createEphemeral(Us):s.createStruct(Gs),i=f.field(n,"template"),c=f.field(n,"inputs");return s.createField(i,"Input",e),s.createField(c,"Input",f.Pl.createPlMap(s,r,t)),s.lockInputs(n),f.Pl.futureRecord(s,n,o,"Output","outputs/")}const Js={name:"BContextEnd",version:"1"},Ms={name:"BContext",version:"1"},_s="id",Ks="parent/",Hs=["context","result"];function Ut(s,e,t){return St(s,e,!0,t,Hs)}function qs(s){const e=s.createEphemeral(Js);return s.lock(e),e}function Ws(s,e){if(e.length===0)return qs(s);if(e.length===1)return e[0];const t=s.createEphemeral(Ms);s.createField(f.field(t,_s),"Input",f.Pl.createPlString(s,ne.randomUUID()));for(let r=0;r<e.length;r++)s.createField(f.field(t,`${Ks}${r}`),"Input",e[r]);return s.lock(t),t}function zs(s,e){const t=A.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return Tr(s,t);default:E.assertNever(r)}}const $r={hash(s,e){e.update(A.PlTemplateLibV1.type.name).update(A.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue(A.PlTemplateLibV1.type,JSON.stringify(A.PlTemplateLibV1.fromV2Data(s).data))}},xe={hash(s,e){e.update(A.PlTemplateSoftwareV1.type.name).update(A.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=A.PlTemplateSoftwareV1.fromV2Data(s),o=e.createStruct(A.PlTemplateSoftwareV1.type,r.data);return e.setKValue(o,A.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(o),o}},Xs={hash(s,e){e.update(A.PlTemplateV1.type.name).update(A.PlTemplateV1.type.version).update(s.hashOverride??"").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),$r.hash(o,e);for(const[r,o]of t(Object.entries(s.software??{})))e.update("soft:"+r),xe.hash(o,e);for(const[r,o]of t(Object.entries(s.assets??{})))e.update("asset:"+r),xe.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){return e.createStruct(A.PlTemplateV1.type,JSON.stringify(A.PlTemplateV1.fromV2Data(s).data))}},Ys={hash(s,e){e.update(A.PlTemplateOverrideV1.type.name).update(A.PlTemplateOverrideV1.type.version).update(s.hashOverride??"")},render(s,e,t){return e.createStruct(A.PlTemplateOverrideV1.type,JSON.stringify(A.PlTemplateOverrideV1.fromV2Data(s)))}};function Tr(s,e,t){t||(t=new Map);const r=(c,a)=>{const l=ne.createHash("sha256");a.hash(c,l);const u=l.digest("hex");if(!t.has(u)){const d=a.render(c,s,r);t.set(u,d)}return t.get(u)},o=r(e,Xs);for(const[c,a]of Object.entries(e.libs??{})){const l=A.PlTemplateV1.libField(o,c);s.createField(l,"Input"),s.setField(l,r(a,$r))}for(const[c,a]of Object.entries(e.software??{})){const l=A.PlTemplateV1.swField(o,c);s.createField(l,"Input"),s.setField(l,r(a,xe))}for(const[c,a]of Object.entries(e.assets??{})){const l=A.PlTemplateV1.swField(o,c);s.createField(l,"Input"),s.setField(l,r(a,xe))}for(const[c,a]of Object.entries(e.templates??{})){const l=A.PlTemplateV1.tplField(o,c);s.createField(l,"Input"),s.setField(l,Tr(s,a,t))}if(s.lock(o),!e.hashOverride)return o;const n=r(e,Ys),i=A.PlTemplateOverrideV1.tplField(n);return s.createField(i,"Service"),s.setField(i,o),s.lock(o),n}const Ir={name:"TengoTemplateGet",version:"1"},Fr="registry",Nr="templateURI",Ar="template",Zs={name:"TengoTemplatePack",version:"1"},Qs={name:"TengoTemplatePackConvert",version:"1"},eo="templatePack",to="template";async function Lr(s){switch(s.type){case"from-file":return{type:"explicit",content:await Z.promises.readFile(s.path)};case"from-registry":case"explicit":return s;default:return E.assertNever(s)}}function ro(s,e){const t=s.createStruct(Ir),r=f.field(t,Fr),o=f.field(t,Nr),n=f.field(t,Ar);return s.setField(r,s.createValue(f.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(o,s.createValue(f.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function Me(s,e){switch(e.type){case"from-registry":return ro(s,e);case"explicit":return zs(s,e);default:return E.assertNever(e)}}const Pt={name:"Frontend/FromUrl",version:"1"},Ct={name:"Frontend/FromFolder",version:"1"};function so(s,e){switch(e.type){case"url":return s.createValue(Pt,JSON.stringify({url:e.url}));case"local":return s.createValue(Ct,JSON.stringify({path:e.path,signature:e.signature}));default:return E.assertNever(e)}}const oo={name:"BlockPackCustom",version:"1"},Dr="template",Br="frontend";function Gt(s){return s.endsWith("/")?s:`${s}/`}class no{constructor(e,t,r){this.v2RegistryProvider=e,this.signer=t,this.http=r}async getBlockConfigContainer(e){switch(e.type){case"explicit":return e.config;case"dev-v1":{const t=await Vt(e.folder),r=await Z.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await _.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=this.http!==void 0?{dispatcher:this.http}:{},r=`${Gt(e.registryUrl)}${_.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`;return await(await ae.request(`${r}/config.json`,t)).body.json()}case"from-registry-v2":{const t=this.http!==void 0?{dispatcher:this.http}:{},o=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id);return await(await ae.request(o.model.url,t)).body.json()}default:return E.assertNever(e)}}async prepare(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await Vt(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 _.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 Je(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=this.http!==void 0?{dispatcher:this.http}:{},r=`${Gt(e.registryUrl)}${_.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,o=`${r}/template.plj.gz`,n=await ae.request(o,t);if(n.statusCode!==200)throw new Error(`Block not found in registry (url = ${o} ; code = ${n.statusCode}): `+JSON.stringify(e));const i=new Uint8Array(await n.body.arrayBuffer()),a=await(await ae.request(`${r}/config.json`,t)).body.json();return{type:"explicit",template:{type:"explicit",content:i},config:a,frontend:{type:"url",url:`${r}/frontend.tgz`},source:e}}case"from-registry-v2":{const t=this.http!==void 0?{dispatcher:this.http}:{},o=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),n=async()=>await(await ae.request(o.model.url,t)).body.json(),i=async()=>await(await ae.request(o.workflow.main.url,t)).body.arrayBuffer(),[c,a]=await Promise.all([n(),i()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(a)},config:c,frontend:{type:"url",url:o.ui.url},source:e}}default:return E.assertNever(e)}}}function io(s,e){const t={config:e.config,source:e.source},r=s.createStruct(oo,JSON.stringify(t));return s.createField(f.field(r,Dr),"Input",Me(s,e.template)),s.createField(f.field(r,Br),"Input",so(s,e.frontend)),s.lock(r),r}function Jt(s,e){switch(e.type){case"explicit":return io(s,e);default:return E.assertNever(e.type)}}function $e(s,e){return{__isRef:!0,blockId:s,name:e}}function ao(s){return typeof s=="object"&&s!==null&&s.__isRef===!0&&"blockId"in s&&"name"in s}function pt(s,e,t){const r=typeof e;switch(r){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if(ao(e))t===void 0||t.has(e.blockId)?s.upstreams.add(e.blockId):s.missingReferences=!0;else if(Array.isArray(e))for(const o of e)pt(s,o,t);else for(const[,o]of Object.entries(e))pt(s,o,t);return;default:E.assertNever(r)}}function co(s,e){const t={upstreams:new Set,missingReferences:!1};return pt(t,s,e),t}function oe(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class jr{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;){let 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 ht(s){const e=new Map;let t;for(const{id:r}of oe(s)){const o={id:r,missingReferences:!1};e.set(r,o),t===void 0?o.upstream=new Set:(o.upstream=new Set([t.id]),t.downstream=new Set([o.id])),t=o}return t!==void 0&&(t.downstream=new Set),new jr(e)}function De(s,e){const t=new Map,r=new Set;for(const{id:o}of oe(s)){const n=e(o);if(n===void 0)continue;const i=co(n,r),c={id:o,missingReferences:i.missingReferences,upstream:i.upstreams,downstream:new Set};t.set(o,c),i.upstreams.forEach(a=>t.get(a).downstream.add(o)),r.add(o)}return new jr(t)}function lo(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function ft(s,e){if(s.size>e.size)return ft(e,s);for(const t of s)if(e.has(t))return!0;return!1}function Mt(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):(!lo(n.upstream,i.upstream)||ft(n.upstream,o))&&o.add(n.id)}),e.nodes.forEach(n=>{s.nodes.has(n.id)?ft(n.upstream,o)&&o.add(n.id):r.add(n.id)}),{onlyInA:t,onlyInB:r,different:o}}let Qe;async function xr(){if(Qe===void 0){const s=await Lr(ls.Templates["pframes.export-pframe"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=ne.createHash("sha256").update(s.content).digest("hex");Qe={spec:s,hash:e}}return Qe}function uo(s,e,t){return St(s,e,!0,{pf:t},["result"]).result}function et(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 _t{constructor(e,t){S(this,"currentInputsC",et(()=>this.fields.currentArgs.modCount,()=>JSON.parse(Buffer.from(this.fields.currentArgs.value).toString())));S(this,"actualProductionInputsC",et(()=>{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 JSON.parse(Buffer.from(e).toString())}));S(this,"productionStaleC",et(()=>{var e;return`${this.fields.currentArgs.modCount}_${(e=this.fields.prodArgs)==null?void 0:e.modCount}`},()=>this.fields.prodArgs===void 0||Buffer.compare(this.fields.currentArgs.value,this.fields.prodArgs.value)!==0));this.id=e,this.fields=t}check(){if(this.fields.prodOutput===void 0!=(this.fields.prodCtx===void 0))throw new Error("inconsistent prod fields");if(this.fields.stagingOutput===void 0!=(this.fields.stagingCtx===void 0))throw new Error("inconsistent stage fields");if(this.fields.prodOutputPrevious===void 0!=(this.fields.prodCtxPrevious===void 0))throw new Error("inconsistent prod cache fields");if(this.fields.stagingOutputPrevious===void 0!=(this.fields.stagingCtxPrevious===void 0))throw new Error("inconsistent stage cache fields");if(this.fields.blockPack===void 0)throw new Error("no block pack field");if(this.fields.currentArgs===void 0)throw new Error("no current args field")}get currentInputs(){return this.currentInputsC()}get stagingRendered(){return this.fields.stagingCtx!==void 0}get productionRendered(){return this.fields.prodCtx!==void 0}get productionStale(){return this.productionRendered&&this.productionStaleC()}get requireProductionRendering(){return!this.productionRendered||this.productionStaleC()}get actualProductionInputs(){return this.actualProductionInputsC()}getTemplate(e){return e.getFutureFieldValue(f.Pl.unwrapHolder(e,this.fields.blockPack.ref),Dr,"Input")}}const po=s=>{throw new Error(`No new block info for ${s}`)};class Ve{constructor(e,t,r,o,n,i,c,a,l,u,d,v){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=v}fixProblems(){this.blockInfos.forEach(e=>{(e.fields.prodArgs===void 0||e.fields.prodOutput===void 0||e.fields.prodCtx===void 0)&&this.deleteBlockFields(e.id,"prodArgs","prodOutput","prodCtx")})}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=ht(this.struct)),this.stagingGraph}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=De(this.struct,e=>this.getBlockInfo(e).currentInputs)),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=De(this.struct,e=>this.getBlockInfo(e).actualProductionInputs)),this.actualProductionGraph}getBlockInfo(e){return E.notEmpty(this.blockInfos.get(e))}getBlock(e){for(const t of oe(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const o=f.field(this.rid,J(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(f.field(this.rid,J(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(f.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())}createCtx(e,t){const r=[];return e.forEach(o=>{const n=this.getBlockInfo(o);if(n.fields[t]===void 0||n.fields[t].ref===void 0)throw new Error("One of the upstreams staging is not rendered.");r.push(f.Pl.unwrapHolder(this.tx,n.fields[t].ref))}),Ws(this.tx,r)}exportCtx(e){return uo(this.tx,f.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createCtx(this.getStagingGraph().nodes.get(e).upstream,"stagingCtx");if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const o=t.getTemplate(this.tx),n=Ut(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(f.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(f.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",f.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"stagingOutput",n.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),r=this.createCtx(this.getPendingProductionGraph().nodes.get(e).upstream,"prodCtx");if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const o=t.getTemplate(this.tx),n=Ut(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(f.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(f.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",f.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"prodOutput",n.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=po){const r=this.getStagingGraph(),o=this.getActualProductionGraph(),n=ht(e),i=De(e,l=>{var u;return(u=this.blockInfos.get(l))==null?void 0:u.actualProductionInputs}),c=Mt(r,n),a=Mt(o,i);for(const l of c.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 c.onlyInB){const u=new _t(l,{});this.blockInfos.set(l,u);const d=t(l),v=Jt(this.tx,d.blockPack);this.setBlockField(l,"blockPack",f.Pl.wrapInHolder(this.tx,v),"NotReady");const h=Buffer.from(d.args),g=this.tx.createValue(f.Pl.JsonObject,h);this.setBlockField(l,"currentArgs",g,"Ready",h),d.uiState&&(this.blockFrontendStates.set(l,d.uiState),this.changedBlockFrontendStates.add(l)),u.check()}for(const l of c.different)this.resetStaging(l);o.traverse("downstream",[...a.different],l=>{this.resetOrLimboProduction(l.id)}),(c.onlyInB.size>0||c.onlyInA.size>0||c.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",f.Pl.wrapInHolder(this.tx,Jt(this.tx,t)),"NotReady"),r!==void 0?(this.setArgs([{blockId:e,args:r}]),this.setUiState(e,void 0)):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,i=>{r.add(i.id)});else for(const i of r){const c=o.nodes.get(i);if(c===void 0)throw new Error(`Can't find block with id: ${i}`);for(const a of c.upstream)if(!r.has(a))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const i of oe(this.structure)){if(!r.has(i.id))continue;let c=this.getBlockInfo(i.id).requireProductionRendering||this.blocksInLimbo.has(i.id);if(!c){for(const a of o.nodes.get(i.id).upstream)if(n.has(a)){c=!0;break}}c&&(this.renderProductionFor(i.id),n.add(i.id))}return o.traverse("downstream",[...n],i=>{n.has(i.id)||this.resetOrLimboProduction(i.id)}),n.size>0&&this.updateLastModified(),n}stopProduction(...e){var i,c;const t=this.getActualProductionGraph(),r=new br(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,lt(t)):this.tx.setKValue(this.rid,lt(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,ut):this.tx.setKValue(this.rid,ut,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,Re,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,ue,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,je,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,ke,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,ct(e)):this.tx.setKValue(this.rid,ct(e),t)}this.assignAuthorMarkers()}}static async load(e,t,r){const o=e.getResourceData(t,!0),n=e.getKValueJson(t,Rr),i=e.getKValueJson(t,Re),c=e.getKValueJson(t,ke),a=e.getKValueJson(t,ue),l=e.getKValueJson(t,je),u=e.listKeyValuesString(t),[d,v,h,g,F,{stagingRefreshTimestamp:N,blocksInLimbo:V},H]=await Promise.all([o,n,i,c,a,l,u]);if(v!==kr)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${v}`);const O=new Map;for(const p of d.fields){const w=Bs(p.name);if(w===void 0)continue;let m=O.get(w.blockId);m===void 0&&(m={id:w.blockId,fields:{}},O.set(w.blockId,m)),m.fields[w.fieldName]=f.isNullResourceId(p.value)?{modCount:0}:{modCount:0,ref:p.value}}const ce=await xr(),de=dt(ce.hash),L=d.fields.find(p=>p.name===de);let X;L!==void 0?X=f.ensureResourceIdNotNull(L.value):(X=f.Pl.wrapInHolder(e,Me(e,ce.spec)),e.createField(f.field(t,dt(ce.hash)),"Dynamic",X));const le={stagingRefreshTimestamp:N},q=new Set(V),M=new Map;for(const p of H){const w=As(p.key);w!==void 0&&M.set(w,p.value)}const G=[];O.forEach(({id:p,fields:w})=>{for(const[,m]of Object.entries(w))if(m.ref!==void 0){if(!f.isResource(m.ref)||f.isResourceRef(m.ref))throw new Error("unexpected behaviour");G.push([m,e.getResourceData(m.ref,!1)])}});for(const[p,w]of G){const m=await w;p.value=m.data,f.isNotNullResourceId(m.error)?p.status="Error":m.resourceReady||f.isNotNullResourceId(m.originalResourceId)?p.status="Ready":p.status="NotReady"}const Y=new Map;O.forEach(({id:p,fields:w})=>Y.set(p,new _t(p,w)));const pe=new Set;for(const p of oe(F)){if(!Y.has(p.id))throw new Error(`Inconsistent project structure: no inputs for ${p.id}`);pe.add(p.id)}Y.forEach(p=>{if(!pe.has(p.id))throw new Error(`Inconsistent project structure: no structure entry for ${p.id}`);p.check()});const y=new Ve(t,e,r,v,h,g,F,le,q,Y,M,X);return y.fixProblems(),y}}async function ho(s,e=$s){const t=s.createEphemeral(Ts);s.lock(t);const r=String(Date.now());s.setKValue(t,Rr,JSON.stringify(kr)),s.setKValue(t,bt,r),s.setKValue(t,Re,r),s.setKValue(t,ke,JSON.stringify(e)),s.setKValue(t,ue,JSON.stringify(ks)),s.setKValue(t,je,JSON.stringify(Os));const o=await xr();return s.createField(f.field(t,dt(o.hash)),"Dynamic",f.Pl.wrapInHolder(s,Me(s,o.spec))),t}async function tt(s,e,t){return se(s,e,void 0,t)}async function se(s,e,t,r){if(s instanceof f.PlClient)return await s.withWriteTx("ProjectAction",async o=>{const n=await Ve.load(o,e,t),i=await r(n);return n.wasModified&&(n.save(),await o.commit()),i});{const o=await Ve.load(s,e,t),n=await r(o);return o.save(),n}}function*fo(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 Kt(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function go(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:Kt(s.parts,e)};case"BinaryPartitioned":return{...s,parts:Kt(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:E.assertNever(s)}}const mo=f.resourceType("PColumnData/JsonPartitioned","1"),vo=f.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),yo=f.resourceType("PColumnData/BinaryPartitioned","1"),wo=f.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),bo=f.resourceType("PColumnData/Json","1");function So(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(f.resourceTypesEqual(s.resourceType,bo)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(f.resourceTypesEqual(s.resourceType,mo)){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(f.resourceTypesEqual(s.resourceType,vo)){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(f.resourceTypesEqual(s.resourceType,yo)){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(f.resourceTypesEqual(s.resourceType,wo)){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: ${f.resourceTypeToString(s.resourceType)}`)}function Po(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 Co(s,e){const t=ne.createHash("sha256");return t.update(me(s)),t.update(String(f.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function Ht(s,e){return me({__isRef:!0,blockId:s,name:e})}function Eo(s,e){return me({resolvePath:s,name:e})}function Vr(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 v=E.notEmpty((c=d.groups)==null?void 0:c.name);if(!v.startsWith(r)){if(e)throw new Error(`unexpected field name ${u}`);continue}v=v.slice(r.length);const h=E.notEmpty((a=d.groups)==null?void 0:a.type);let g=n.get(v);switch(g===void 0&&(g={},n.set(v,g)),h){case"spec":g.spec=(l=s.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:l.getDataAsJson();break;case"data":g.hasData=!0,g.data=()=>s.traverseOrError({field:u,ignoreError:t});default:continue}}const i=s.getInputsLocked();if(i)for(const[,u]of n)u.data===void 0&&(u.hasData=!1);return{locked:i,results:n}}function Ro(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const o=Vr(s,e,!1,t);us(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 new Ge.PlError(a.error);n[i]={id:r.length===0?Co(c.spec,a.value):Eo(r,i),spec:c.spec,data:a.value}}return n}class Et{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;let 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 x.mapValueInVOE(n,l=>({id:Ht(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:$e(i,c),obj:{id:l.ok?Ht(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:$e(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:$e(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),x.executePSpecPredicate(e,a.spec)&&t.push({label:r.info.label+" / "+c,ref:$e(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(ue)),c=ht(n).traverseIds("upstream",r),a=new Map;for(const l of oe(n)){if(!c.has(l.id))continue;const u=qt(o.traverse({field:J(l.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:J(l.id,"prodUiCtx"),stableIfNotFound:!0})),d=qt(o.traverse({field:J(l.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:J(l.id,"stagingUiCtx")}));a.set(l.id,{info:l,prod:u,staging:d})}return new Et(e,a)}}function qt(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return Vr(e.value,!1,!0)}function Rt(s,e){return{blockId:e,args:o=>E.notEmpty(o.accessor(s).node().traverse({field:J(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),uiState:o=>o.accessor(s).node().getKeyValueAsString(ct(e)),blockMeta:o=>{const n=o.accessor(s).node(),i=E.notEmpty(n.getKeyValueAsJson(ue)),c=new Map;for(const a of oe(i))c.set(a.id,a);return c}}}function Ur(s,e){return{...Rt(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:J(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:J(e,"stagingOutput"),ignoreError:!0}))==null?void 0:o.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>Et.create(t,s,e)}}function*z(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*z(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*z(t);return;case"MakeArray":for(const t of s.template)yield*z(t);return;case"GetJsonField":case"GetResourceField":yield*z(s.source),yield*z(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*z(s.source),yield*z(s.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetLogHandle":yield*z(s.source);return;case"IsEmpty":yield*z(s.arg);return;case"Not":yield*z(s.operand);return;case"And":case"Or":yield*z(s.operand1),yield*z(s.operand2);return;default:E.assertNever(s)}}function ko(s,e){const t={};for(const[r,o]of Object.entries(s))t[r]=e(o);return t}function Pe(s,e){return s===void 0?void 0:e(s)}function Oo(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function $o(s){for(const e of z(s))if(Oo(e))return!0;return!1}function _e(s){return{type:"ReturnResult",result:s}}function k(s){return()=>_e(s)}const To=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return k(e)},Io=s=>{const e=s.source;if(e===void 0)return k(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return k(t)},Fo=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?k(void 0):({cCtx:r})=>{var o;return _e((o=r.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function Gr(s,e){const t={},r=s.length;for(let o=0;o<r;o++)t[String(o)]=e(s[o]);return t}function No(s,e){return t=>{const r=t.source;return r===void 0?k(void 0):()=>({type:"ScheduleSubroutine",subroutine:Jr(r.length),args:Gr(r,o=>T({...s,[e.itVar]:o},e.mapping))})}}function Jr(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return k(t)}}function Ao(s,e){return t=>{const r=t.source;if(r===void 0)return k(void 0);const o={};for(const[n,i]of Object.entries(r)){const c={...s,[e.itVar]:i};o[n]=T(c,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:Lo,args:o})}}const Lo=s=>k(s),Do=s=>{const e=s.arg;return k(e===void 0?void 0:e.length===0)},Bo=s=>{const e=s.operand;return k(e===void 0?void 0:!e)},jo=s=>{const e=s.operand1,t=s.operand2;return k(e===void 0||t===void 0?void 0:e&&t)},xo=s=>{const e=s.operand1,t=s.operand2;return k(e===void 0||t===void 0?void 0:e||t)},Vo=s=>{const e=s.source;return e===void 0?k(void 0):({cCtx:t})=>{var r;return _e((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},Uo=s=>{const e=s.source,t=s.field;return k(e===void 0||t===void 0?void 0:e[t])};function Go(s,e){return t=>{const r=t.source;return r===void 0?k(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]=k(void 0);else{const l={...s,[e.itVar]:a.persist()};i[c]=T(l,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:Jo,args:i}}}}const Jo=s=>k(s),Mo=s=>{const e=s.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:D.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)}})})},_o=s=>{const e=s.source;return e===void 0?k(void 0):({cCtx:t,drivers:r})=>{const o=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:D.Computable.make(()=>r.blobDriver.getDownloadedBlob(o),{postprocessValue:async n=>n===void 0?void 0:(await r.blobDriver.getContent(n.handle)).toString()})}}},Ko=s=>{const e=s.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:D.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())}})})},Ho=s=>{const e=s.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},qo=s=>{const e=s.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},Wo=s=>{const e=s.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},zo=s=>e=>{const t=e.source;return t===void 0?k(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},Xo=s=>e=>{const t=e.source;return t===void 0?k(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},Yo=s=>{const e=s.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function T(s,e){switch(e.type){case"GetFromCtx":const t=s[e.variable];return typeof t=="function"?r=>_e(t(r.cCtx)):k(t);case"Isolate":return({drivers:r})=>({type:"ScheduleComputable",computable:Kr(r,s,e.cfg)});case"Immediate":return k(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:Uo,args:{source:T(s,e.source),field:T(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:No(s,e),args:{source:T(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:Ao(s,e),args:{source:T(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:To,args:ko(e.template,r=>T(s,r))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:Jr(e.template.length),args:Gr(e.template,r=>T(s,r))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:Io,args:{source:T(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:Do,args:{arg:T(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:Bo,args:{operand:T(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:jo,args:{operand1:T(s,e.operand1),operand2:T(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:xo,args:{operand1:T(s,e.operand1),operand2:T(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:Go(s,e),args:{source:T(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:Fo,args:{source:T(s,e.source),field:T(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Vo,args:{source:T(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Mo,args:{source:T(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:_o,args:{source:T(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Ko,args:{source:T(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Ho,args:{source:T(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:qo,args:{source:T(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:Wo,args:{source:T(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:zo(e.lines),args:{source:T(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:Xo(e.patternToSearch),args:{source:T(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:Yo,args:{source:T(s,e.source)}});default:return E.assertNever(e)}}const Zo=["$prod","$staging"];function Qo(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 Mr=Symbol(),_r="return",en={op:Mr,arg:_r};function tn(s){return s.op==Mr&&s.arg==_r}function rn(){return{pendingSubroutines:new Map}}function Wt(s,e,t,r){const o=new br(t),n=(c,a)=>{if(tn(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[v,h]of u)o.push({destination:{op:l,arg:v},operation:h});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 sn(s,e,t,r={}){return Kr(s,Qo(e),t,r)}function Kr(s,e,t,r={}){const o=`${e.blockId}#`+me({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>Zo.indexOf(n)===-1)),cfg:t});return D.Computable.makeRaw(n=>{const i={drivers:s,cCtx:n},c=rn();return{ir:Wt(i,c,[{destination:en,operation:T(e,t)}],!0),async postprocessValue(l){const u=[];for(const g of l)u.push({destination:g.destination,operation:k(g.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},v=new Map;for(const[g,F]of c.pendingSubroutines)v.set(g,{...F,args:{...F.args}});const h={result:c.result,pendingSubroutines:v};if(Wt(d,h,u,!1),!("result"in h))throw new Error("illegal cfg rendering stack state, no result");return h.result}}},{...r,key:o})}function on(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}function zt(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class Ue{constructor(e,t,r,o,n){S(this,"callbackRegistry");S(this,"fnJSONStringify");S(this,"fnJSONParse");S(this,"computablesToResolve",{});S(this,"computableCtx");S(this,"accessors",new Map);S(this,"meta");S(this,"_resultPool");if(this.scope=e,this.vm=t,this.blockCtx=r,this.env=o,this.computableCtx=n,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");this.meta=r.blockMeta(n),this.injectCtx()}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw Ue.cleanErrorContext(t),t}}runCallback(e,...t){try{return Be.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 Ue.cleanErrorContext(r),r}}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 zt(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return zt(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=Ro(n,t,r,o),c={};for(const[a,l]of Object.entries(i))c[a]=x.mapPObjectData(l,u=>this.wrapAccessor(u));return c}registerComputable(e,t){const r=`${e}_${ne.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",D.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",D.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))}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))}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:x.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:x.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 x.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=>x.mapPObjectData(t,r=>typeof r=="string"?this.getAccessor(r):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(x.mapPTableDef(e,t=>x.mapPObjectData(t,r=>typeof r=="string"?this.getAccessor(r):r)),this.computableCtx)}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=ne.randomUUID();return this.accessors.set(t,e),t}}exportSingleValue(e,t){const r=this.tryExportSingleValue(e,t);if(r===void 0)throw new Error(`Can't export value: ${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(on(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(){Be.Scope.withScope(e=>{const t=e.manage(this.vm.newObject()),r=this.blockCtx.args(this.computableCtx),o=this.blockCtx.uiState(this.computableCtx);this.vm.setProp(t,"args",e.manage(this.vm.newString(r))),o!==void 0&&this.vm.setProp(t,"uiState",e.manage(this.vm.newString(o))),this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(x.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e));const n=(i,c)=>{this.vm.newFunction(i,c).consume(a=>this.vm.setProp(t,i,a))};n("getAccessorHandleByName",i=>this.exportSingleValue(this.getAccessorHandleByName(this.vm.getString(i)),void 0)),n("resolveWithCommon",(i,c,...a)=>this.exportSingleValue(this.resolveWithCommon(this.vm.getString(i),this.importObjectViaJson(c),...a.map(l=>this.importObjectViaJson(l))),void 0)),n("getResourceType",i=>this.exportObjectViaJson(this.getResourceType(this.vm.getString(i)),void 0)),n("getInputsLocked",i=>this.exportSingleValue(this.getInputsLocked(this.vm.getString(i)),void 0)),n("getOutputsLocked",i=>this.exportSingleValue(this.getOutputsLocked(this.vm.getString(i)),void 0)),n("getIsReadyOrError",i=>this.exportSingleValue(this.getIsReadyOrError(this.vm.getString(i)),void 0)),n("getIsFinal",i=>this.exportSingleValue(this.getIsFinal(this.vm.getString(i)),void 0)),n("getError",i=>this.exportSingleValue(this.getError(this.vm.getString(i)),void 0)),n("listInputFields",i=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(i)),void 0)),n("listOutputFields",i=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(i)),void 0)),n("listDynamicFields",i=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(i)),void 0)),n("getKeyValueBase64",(i,c)=>this.exportSingleValue(this.getKeyValueBase64(this.vm.getString(i),this.vm.getString(c)),void 0)),n("getKeyValueAsString",(i,c)=>this.exportSingleValue(this.getKeyValueAsString(this.vm.getString(i),this.vm.getString(c)),void 0)),n("getDataBase64",i=>this.exportSingleValue(this.getDataBase64(this.vm.getString(i)),void 0)),n("getDataAsString",i=>this.exportSingleValue(this.getDataAsString(this.vm.getString(i)),void 0)),n("parsePObjectCollection",(i,c,a,...l)=>this.exportObjectUniversal(this.parsePObjectCollection(this.vm.getString(i),this.vm.dump(c),this.vm.getString(a),...l.map(this.vm.getString)),void 0)),n("getBlobContentAsBase64",i=>this.exportSingleValue(this.getBlobContentAsBase64(this.vm.getString(i)),void 0)),n("getBlobContentAsString",i=>this.exportSingleValue(this.getBlobContentAsString(this.vm.getString(i)),void 0)),n("getDownloadedBlobContentHandle",i=>this.exportSingleValue(this.getDownloadedBlobContentHandle(this.vm.getString(i)),void 0)),n("getOnDemandBlobContentHandle",i=>this.exportSingleValue(this.getOnDemandBlobContentHandle(this.vm.getString(i)),void 0)),n("getImportProgress",i=>this.exportSingleValue(this.getImportProgress(this.vm.getString(i)),void 0)),n("getLastLogs",(i,c)=>this.exportSingleValue(this.getLastLogs(this.vm.getString(i),this.vm.getNumber(c)),void 0)),n("getProgressLog",(i,c)=>this.exportSingleValue(this.getProgressLog(this.vm.getString(i),this.vm.getString(c)),void 0)),n("getLogHandle",i=>this.exportSingleValue(this.getLogHandle(this.vm.getString(i)),void 0)),n("getBlockLabel",i=>this.exportSingleValue(this.getBlockLabel(this.vm.getString(i)),void 0)),n("getDataFromResultPool",i=>this.exportObjectUniversal(this.getDataFromResultPool(),void 0)),n("getDataWithErrorsFromResultPool",i=>this.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),n("getSpecsFromResultPool",i=>this.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),n("calculateOptions",i=>this.exportObjectUniversal(this.calculateOptions(this.importObjectViaJson(i)),void 0)),n("getSpecFromResultPoolByRef",(i,c)=>this.exportObjectUniversal(this.getSpecFromResultPoolByRef(this.vm.getString(i),this.vm.getString(c)),void 0)),n("getDataFromResultPoolByRef",(i,c)=>this.exportObjectUniversal(this.getDataFromResultPoolByRef(this.vm.getString(i),this.vm.getString(c)),void 0)),n("createPFrame",i=>this.exportSingleValue(this.createPFrame(this.importObjectViaJson(i)),void 0)),n("createPTable",i=>this.exportSingleValue(this.createPTable(this.importObjectViaJson(i)),void 0)),n("getCurrentUnstableMarker",()=>this.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}function Ke(s,e){return Pe(s.traverse({field:J(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:f.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),o=x.extractConfig(r.config);return{bpId:t.resourceInfo.id.toString(),info:r,cfg:o}})}const Te=process.env.MI_LOG_OUTPUT_STATUS;function nn(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"),D.Computable.makeRaw(c=>{const a=new Be.Scope;c.addOnDestroy(()=>a.dispose());const l=a.manage(s.quickJs.newRuntime());l.setMemoryLimit(1024*640),l.setMaxStackSize(1024*320);const u=a.manage(l.newContext()),d=new Ue(a,u,e,s,c);d.evaluateBundle(r.content);const v=d.runCallback(t.handle);d.resetComputableCtx();let h=0;return Te&&Te!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:d.computablesToResolve,postprocessValue:async(g,{unstableMarker:F,stable:N})=>{for(const[H,O]of Object.entries(g))d.runCallback(H,O);const V=d.importObjectUniversal(v);return h++,Te&&(Te!=="unstable-only"||!N)&&console.log(N?`Stable output ${t.handle} calculated ${V!==void 0?"defined":"undefined"}; (#${h})`:`Unstable output ${t.handle}; marker = ${F}; ${V!==void 0?"defined":"undefined"} (#${h})`),V}}},n)}function an(s){return x.isConfigLambda(s)?s.isActive===!0:$o(s)}function Ce(s,e,t,r,o,n={}){if(x.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return nn(s,e,t,r,o,n)}else return sn(s.driverKit,e,t,n)}function cn(s,e,t){return D.Computable.make(r=>{var g,F,N,V,H,O,ce,de;const o=r.accessor(s).node(),n=E.notEmpty(o.getKeyValueAsJson(bt)),i=E.notEmpty(o.getKeyValueAsJson(Re)),c=E.notEmpty(o.getKeyValueAsJson(ke)),a=E.notEmpty(o.getKeyValueAsJson(ue)),l=E.notEmpty(o.getKeyValueAsJson(je)),u=new Map;for(const{id:L}of oe(a)){const X=o.traverse({field:J(L,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0});let le;const q=o.traverse({field:J(L,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(q!==void 0){const M=o.getField({field:J(L,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),G=o.getField({field:J(L,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});le={arguments:q.getDataAsJson(),stale:X.id!==q.id,outputError:M.error!==void 0||G.error!==void 0||((g=M.value)==null?void 0:g.getError())!==void 0||((F=G.value)==null?void 0:F.getError())!==void 0,outputsError:((N=M.error)==null?void 0:N.getDataAsString())??((H=(V=M.value)==null?void 0:V.getError())==null?void 0:H.getDataAsString()),exportsError:((O=G.error)==null?void 0:O.getDataAsString())??((de=(ce=G.value)==null?void 0:ce.getError())==null?void 0:de.getDataAsString()),finished:(M.value!==void 0&&M.value.getIsReadyOrError()||M.error!==void 0&&M.error.getIsReadyOrError())&&(G.value!==void 0&&G.value.getIsReadyOrError()||G.error!==void 0&&G.error.getIsReadyOrError())}}u.set(L,{currentArguments:X.getDataAsJson(),prod:le})}const d=De(a,L=>u.get(L).currentArguments),v=new Set(l.blocksInLimbo),h=[...oe(a)].map(({id:L,label:X,renderingMode:le})=>{var P,b,C,$,R;const q=E.notEmpty(u.get(L)),M=E.notEmpty(d.nodes.get(L));let G="NotCalculated";q.prod!==void 0&&(v.has(L)?G="Limbo":G=q.prod.finished?"Done":"Running");const Y=Ke(o,L),{sections:pe,title:y,inputsValid:p,sdkVersion:w}=Pe(Y,({bpId:I,cfg:B,info:j})=>{const ie=Rt(s,L);return{sections:Ce(t,ie,B.sections,B.code,I),title:Pe(B.title,ss=>Ce(t,ie,ss,B.code,I)),inputsValid:Ce(t,ie,B.inputsValid,B.code,I),sdkVersion:B.sdkVersion}})||{},m=Pe(Y,({info:I})=>t.blockUpdateWatcher.get(I.source));return{id:L,label:y??X,title:y??X,renderingMode:le,stale:((P=q.prod)==null?void 0:P.stale)!==!1||G==="Limbo",missingReference:M.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",L)],downstreams:[...d.traverseIdsExcludingRoots("downstream",L)],calculationStatus:G,outputErrors:((b=q.prod)==null?void 0:b.outputError)===!0,outputsError:(C=q.prod)==null?void 0:C.outputsError,exportsError:($=q.prod)==null?void 0:$.exportsError,sections:pe,inputsValid:p,currentBlockPack:(R=Y==null?void 0:Y.info)==null?void 0:R.source,updatedBlockPack:m,sdkVersion:w,navigationState:e.getState(L)}});return{meta:c,created:new Date(n),lastModified:new Date(i),authorMarker:o.getKeyValueAsJson(ut),blocks:h}},{postprocessValue:r=>{const o=new Set,n=new Set;return{...r,blocks:r.blocks.map(i=>{i.inputsValid||o.add(i.id),i.stale&&n.add(i.id);const c=i.stale||i.upstreams.findIndex(l=>n.has(l))!==-1,a=(c||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(l=>o.has(l))===-1;return{...i,canRun:a,stale:c}})}}}).withStableType()}function ln(s,e){const t=s.node();if(f.resourceTypesEqual(t.resourceType,Pt)){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(f.resourceTypesEqual(t.resourceType,Ct)){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 un(s,e){if(s!==void 0)return D.Computable.make(t=>ln(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 dn(s,e,t){return D.Computable.make(r=>{var c;const o=r.accessor(s).node(),n=Ke(o,e),i=(c=o.traverse({field:J(e,"blockPack"),assertFieldType:"Dynamic"},{field:f.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:Br,assertFieldType:"Input"}))==null?void 0:c.persist();return{path:un(i,t),sdkVersion:n==null?void 0:n.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function Hr(s,e,t){if(t===void 0)return D.Computable.make(i=>Hr(s,e,i),{key:`inputs#${f.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),o=Rt(s,e),n=o.uiState(t);return{author:r.getKeyValueAsJson(lt(e)),args:JSON.parse(o.args(t)),ui:n!==void 0?JSON.parse(n):void 0}}function pn(s,e,t){return D.Computable.make(r=>{const o=r.accessor(s).node(),n=Ur(s,e);return Pe(Ke(o,e),({cfg:i,bpId:c})=>{const a={};for(const[l,u]of Object.entries(i.outputs)){const d=Ce(t,n,u,i.code,c);a[l]=D.Computable.wrapError(d)}return a})},{key:"outputs#"+f.resourceIdToString(s.rid)+"#"+e}).withStableType()}function hn(s,e){return D.Computable.make(t=>{const r=t.accessor(s).node(),o=E.notEmpty(r.getKeyValueAsJson(ue)),n=[];for(const{id:i,renderingMode:c}of oe(o)){const a=Ke(r,i);if(a===void 0)continue;const l=Object.entries(a.cfg.outputs).map(([,d])=>d).filter(d=>an(d)).map(d=>d);if(l.length===0)continue;const u=Ur(r.persist(),i);for(const d of l)n.push(D.Computable.wrapError(Ce(e,u,d,a.cfg.code,a.bpId)))}return n})}class fn{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 D.ChangeSource});return}r.state={...t},r.change.markChanged()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...x.DefaultNavigationState},change:new D.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return D.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())}}class He{constructor(e,t,r){S(this,"rid");S(this,"overview");S(this,"navigationStates",new fn);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=cn(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=hn(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await tt(this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await Sr.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(f.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!f.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,o=void 0,n=ne.randomUUID()){const i=await this.env.bpPreparer.prepare(t),c=await this.env.bpPreparer.getBlockConfigContainer(t),a=x.extractConfig(c);return await se(this.env.pl,this.rid,o,l=>l.addBlock({id:n,label:e,renderingMode:a.renderingMode},{args:JSON.stringify(a.initialArgs),uiState:JSON.stringify(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=await this.env.bpPreparer.getBlockConfigContainer(t);await se(this.env.pl,this.rid,o,c=>c.migrateBlockPack(e,n,r?JSON.stringify(i.initialArgs):void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await se(this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await se(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 tt(this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await tt(this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await se(this.env.pl,this.rid,r,o=>o.setArgs([{blockId:e,args:JSON.stringify(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await se(this.env.pl,this.rid,r,o=>o.setUiState(e,t===void 0?void 0:JSON.stringify(t))),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,o){await se(this.env.pl,this.rid,o,n=>{n.setArgs([{blockId:e,args:JSON.stringify(t)}]),n.setUiState(e,JSON.stringify(r))}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async r=>{const o=f.ensureResourceIdNotNull((await r.getField(f.field(this.rid,J(e,"blockPack")))).value),n=f.ensureResourceIdNotNull((await r.getField(f.field(o,f.Pl.HolderRefField))).value),i=await r.getResourceData(n,!1),c=JSON.parse(Buffer.from(E.notEmpty(i.data)).toString("utf-8"));await se(r,this.rid,t,a=>{a.setArgs([{blockId:e,args:JSON.stringify(c.config.initialArgs)}]),a.setUiState(e,void 0)}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===void 0){const r=pn(this.projectTree.entry(),e,this.env),n={fullState:D.Computable.make(i=>({argsAndUiState:Hr(this.projectTree.entry(),e,i),outputs:r,navigationState:this.navigationStates.getState(e)}),{postprocessValue:i=>({...i.argsAndUiState,outputs:i.outputs,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=dn(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){const r=await Ge.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:gn},e.logger);return new He(e,t,r)}}function gn(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}}const kt={logger:new E.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:100*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}};function Ot(s){return{blobDownloadPath:W.join(s,"download")}}const qr={...kt,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function Wr(s){return{...Ot(s),frontendDownloadPath:W.join(s,"frontend")}}function mn(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var gt={exports:{}};const vn="2.0.0",zr=256,yn=Number.MAX_SAFE_INTEGER||9007199254740991,wn=16,bn=zr-6,Sn=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var qe={MAX_LENGTH:zr,MAX_SAFE_COMPONENT_LENGTH:wn,MAX_SAFE_BUILD_LENGTH:bn,MAX_SAFE_INTEGER:yn,RELEASE_TYPES:Sn,SEMVER_SPEC_VERSION:vn,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2};const Pn=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...s)=>console.error("SEMVER",...s):()=>{};var We=Pn;(function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:o}=qe,n=We;e=s.exports={};const i=e.re=[],c=e.safeRe=[],a=e.src=[],l=e.t={};let u=0;const d="[a-zA-Z0-9-]",v=[["\\s",1],["\\d",o],[d,r]],h=F=>{for(const[N,V]of v)F=F.split(`${N}*`).join(`${N}{0,${V}}`).split(`${N}+`).join(`${N}{1,${V}}`);return F},g=(F,N,V)=>{const H=h(N),O=u++;n(F,O,N),l[F]=O,a[O]=N,i[O]=new RegExp(N,V?"g":void 0),c[O]=new RegExp(H,V?"g":void 0)};g("NUMERICIDENTIFIER","0|[1-9]\\d*"),g("NUMERICIDENTIFIERLOOSE","\\d+"),g("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${d}*`),g("MAINVERSION",`(${a[l.NUMERICIDENTIFIER]})\\.(${a[l.NUMERICIDENTIFIER]})\\.(${a[l.NUMERICIDENTIFIER]})`),g("MAINVERSIONLOOSE",`(${a[l.NUMERICIDENTIFIERLOOSE]})\\.(${a[l.NUMERICIDENTIFIERLOOSE]})\\.(${a[l.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASEIDENTIFIER",`(?:${a[l.NUMERICIDENTIFIER]}|${a[l.NONNUMERICIDENTIFIER]})`),g("PRERELEASEIDENTIFIERLOOSE",`(?:${a[l.NUMERICIDENTIFIERLOOSE]}|${a[l.NONNUMERICIDENTIFIER]})`),g("PRERELEASE",`(?:-(${a[l.PRERELEASEIDENTIFIER]}(?:\\.${a[l.PRERELEASEIDENTIFIER]})*))`),g("PRERELEASELOOSE",`(?:-?(${a[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${a[l.PRERELEASEIDENTIFIERLOOSE]})*))`),g("BUILDIDENTIFIER",`${d}+`),g("BUILD",`(?:\\+(${a[l.BUILDIDENTIFIER]}(?:\\.${a[l.BUILDIDENTIFIER]})*))`),g("FULLPLAIN",`v?${a[l.MAINVERSION]}${a[l.PRERELEASE]}?${a[l.BUILD]}?`),g("FULL",`^${a[l.FULLPLAIN]}$`),g("LOOSEPLAIN",`[v=\\s]*${a[l.MAINVERSIONLOOSE]}${a[l.PRERELEASELOOSE]}?${a[l.BUILD]}?`),g("LOOSE",`^${a[l.LOOSEPLAIN]}$`),g("GTLT","((?:<|>)?=?)"),g("XRANGEIDENTIFIERLOOSE",`${a[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),g("XRANGEIDENTIFIER",`${a[l.NUMERICIDENTIFIER]}|x|X|\\*`),g("XRANGEPLAIN",`[v=\\s]*(${a[l.XRANGEIDENTIFIER]})(?:\\.(${a[l.XRANGEIDENTIFIER]})(?:\\.(${a[l.XRANGEIDENTIFIER]})(?:${a[l.PRERELEASE]})?${a[l.BUILD]}?)?)?`),g("XRANGEPLAINLOOSE",`[v=\\s]*(${a[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[l.XRANGEIDENTIFIERLOOSE]})(?:${a[l.PRERELEASELOOSE]})?${a[l.BUILD]}?)?)?`),g("XRANGE",`^${a[l.GTLT]}\\s*${a[l.XRANGEPLAIN]}$`),g("XRANGELOOSE",`^${a[l.GTLT]}\\s*${a[l.XRANGEPLAINLOOSE]}$`),g("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),g("COERCE",`${a[l.COERCEPLAIN]}(?:$|[^\\d])`),g("COERCEFULL",a[l.COERCEPLAIN]+`(?:${a[l.PRERELEASE]})?(?:${a[l.BUILD]})?(?:$|[^\\d])`),g("COERCERTL",a[l.COERCE],!0),g("COERCERTLFULL",a[l.COERCEFULL],!0),g("LONETILDE","(?:~>?)"),g("TILDETRIM",`(\\s*)${a[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",g("TILDE",`^${a[l.LONETILDE]}${a[l.XRANGEPLAIN]}$`),g("TILDELOOSE",`^${a[l.LONETILDE]}${a[l.XRANGEPLAINLOOSE]}$`),g("LONECARET","(?:\\^)"),g("CARETTRIM",`(\\s*)${a[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",g("CARET",`^${a[l.LONECARET]}${a[l.XRANGEPLAIN]}$`),g("CARETLOOSE",`^${a[l.LONECARET]}${a[l.XRANGEPLAINLOOSE]}$`),g("COMPARATORLOOSE",`^${a[l.GTLT]}\\s*(${a[l.LOOSEPLAIN]})$|^$`),g("COMPARATOR",`^${a[l.GTLT]}\\s*(${a[l.FULLPLAIN]})$|^$`),g("COMPARATORTRIM",`(\\s*)${a[l.GTLT]}\\s*(${a[l.LOOSEPLAIN]}|${a[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",g("HYPHENRANGE",`^\\s*(${a[l.XRANGEPLAIN]})\\s+-\\s+(${a[l.XRANGEPLAIN]})\\s*$`),g("HYPHENRANGELOOSE",`^\\s*(${a[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${a[l.XRANGEPLAINLOOSE]})\\s*$`),g("STAR","(<|>)?=?\\s*\\*"),g("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),g("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(gt,gt.exports);var Oe=gt.exports;const Cn=Object.freeze({loose:!0}),En=Object.freeze({}),Rn=s=>s?typeof s!="object"?Cn:s:En;var $t=Rn;const Xt=/^[0-9]+$/,Xr=(s,e)=>{const t=Xt.test(s),r=Xt.test(e);return t&&r&&(s=+s,e=+e),s===e?0:t&&!r?-1:r&&!t?1:s<e?-1:1},kn=(s,e)=>Xr(e,s);var Yr={compareIdentifiers:Xr,rcompareIdentifiers:kn};const Ie=We,{MAX_LENGTH:Yt,MAX_SAFE_INTEGER:Fe}=qe,{safeRe:Zt,t:Qt}=Oe,On=$t,{compareIdentifiers:he}=Yr;let $n=class re{constructor(e,t){if(t=On(t),e instanceof re){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>Yt)throw new TypeError(`version is longer than ${Yt} characters`);Ie("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const r=e.trim().match(t.loose?Zt[Qt.LOOSE]:Zt[Qt.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>Fe||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Fe||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Fe||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<Fe)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(Ie("SemVer.compare",this.version,this.options,e),!(e instanceof re)){if(typeof e=="string"&&e===this.version)return 0;e=new re(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof re||(e=new re(e,this.options)),he(this.major,e.major)||he(this.minor,e.minor)||he(this.patch,e.patch)}comparePre(e){if(e instanceof re||(e=new re(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(Ie("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 he(r,o)}while(++t)}compareBuild(e){e instanceof re||(e=new re(e,this.options));let t=0;do{const r=this.build[t],o=e.build[t];if(Ie("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 he(r,o)}while(++t)}inc(e,t,r){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"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(!t&&r===!1)throw new Error("invalid increment argument: identifier is empty");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]),he(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=n):this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};var K=$n;const er=K,Tn=(s,e,t=!1)=>{if(s instanceof er)return s;try{return new er(s,e)}catch(r){if(!t)return null;throw r}};var ve=Tn;const In=ve,Fn=(s,e)=>{const t=In(s,e);return t?t.version:null};var Nn=Fn;const An=ve,Ln=(s,e)=>{const t=An(s.trim().replace(/^[=v]+/,""),e);return t?t.version:null};var Dn=Ln;const tr=K,Bn=(s,e,t,r,o)=>{typeof t=="string"&&(o=r,r=t,t=void 0);try{return new tr(s instanceof tr?s.version:s,t).inc(e,r,o).version}catch{return null}};var jn=Bn;const rr=ve,xn=(s,e)=>{const t=rr(s,null,!0),r=rr(e,null,!0),o=t.compare(r);if(o===0)return null;const n=o>0,i=n?t:r,c=n?r:t,a=!!i.prerelease.length;if(!!c.prerelease.length&&!a)return!c.patch&&!c.minor?"major":i.patch?"patch":i.minor?"minor":"major";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 Vn=xn;const Un=K,Gn=(s,e)=>new Un(s,e).major;var Jn=Gn;const Mn=K,_n=(s,e)=>new Mn(s,e).minor;var Kn=_n;const Hn=K,qn=(s,e)=>new Hn(s,e).patch;var Wn=qn;const zn=ve,Xn=(s,e)=>{const t=zn(s,e);return t&&t.prerelease.length?t.prerelease:null};var Yn=Xn;const sr=K,Zn=(s,e,t)=>new sr(s,t).compare(new sr(e,t));var Q=Zn;const Qn=Q,ei=(s,e,t)=>Qn(e,s,t);var ti=ei;const ri=Q,si=(s,e)=>ri(s,e,!0);var oi=si;const or=K,ni=(s,e,t)=>{const r=new or(s,t),o=new or(e,t);return r.compare(o)||r.compareBuild(o)};var Tt=ni;const ii=Tt,ai=(s,e)=>s.sort((t,r)=>ii(t,r,e));var ci=ai;const li=Tt,ui=(s,e)=>s.sort((t,r)=>li(r,t,e));var di=ui;const pi=Q,hi=(s,e,t)=>pi(s,e,t)>0;var ze=hi;const fi=Q,gi=(s,e,t)=>fi(s,e,t)<0;var It=gi;const mi=Q,vi=(s,e,t)=>mi(s,e,t)===0;var Zr=vi;const yi=Q,wi=(s,e,t)=>yi(s,e,t)!==0;var Qr=wi;const bi=Q,Si=(s,e,t)=>bi(s,e,t)>=0;var Ft=Si;const Pi=Q,Ci=(s,e,t)=>Pi(s,e,t)<=0;var Nt=Ci;const Ei=Zr,Ri=Qr,ki=ze,Oi=Ft,$i=It,Ti=Nt,Ii=(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 Ei(s,t,r);case"!=":return Ri(s,t,r);case">":return ki(s,t,r);case">=":return Oi(s,t,r);case"<":return $i(s,t,r);case"<=":return Ti(s,t,r);default:throw new TypeError(`Invalid operator: ${e}`)}};var es=Ii;const Fi=K,Ni=ve,{safeRe:Ne,t:Ae}=Oe,Ai=(s,e)=>{if(s instanceof Fi)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?Ne[Ae.COERCEFULL]:Ne[Ae.COERCE]);else{const a=e.includePrerelease?Ne[Ae.COERCERTLFULL]:Ne[Ae.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 Ni(`${r}.${o}.${n}${i}${c}`,e)};var Li=Ai;class Di{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 Bi=Di,rt,nr;function ee(){if(nr)return rt;nr=1;const s=/\s+/g;class e{constructor(p,w){if(w=o(w),p instanceof e)return p.loose===!!w.loose&&p.includePrerelease===!!w.includePrerelease?p:new e(p.raw,w);if(p instanceof n)return this.raw=p.value,this.set=[[p]],this.formatted=void 0,this;if(this.options=w,this.loose=!!w.loose,this.includePrerelease=!!w.includePrerelease,this.raw=p.trim().replace(s," "),this.set=this.raw.split("||").map(m=>this.parseRange(m.trim())).filter(m=>m.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const m=this.set[0];if(this.set=this.set.filter(P=>!F(P[0])),this.set.length===0)this.set=[m];else if(this.set.length>1){for(const P of this.set)if(P.length===1&&N(P[0])){this.set=[P];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let p=0;p<this.set.length;p++){p>0&&(this.formatted+="||");const w=this.set[p];for(let m=0;m<w.length;m++)m>0&&(this.formatted+=" "),this.formatted+=w[m].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(p){const m=((this.options.includePrerelease&&h)|(this.options.loose&&g))+":"+p,P=r.get(m);if(P)return P;const b=this.options.loose,C=b?a[l.HYPHENRANGELOOSE]:a[l.HYPHENRANGE];p=p.replace(C,Y(this.options.includePrerelease)),i("hyphen replace",p),p=p.replace(a[l.COMPARATORTRIM],u),i("comparator trim",p),p=p.replace(a[l.TILDETRIM],d),i("tilde trim",p),p=p.replace(a[l.CARETTRIM],v),i("caret trim",p);let $=p.split(" ").map(j=>H(j,this.options)).join(" ").split(/\s+/).map(j=>G(j,this.options));b&&($=$.filter(j=>(i("loose invalid filter",j,this.options),!!j.match(a[l.COMPARATORLOOSE])))),i("range list",$);const R=new Map,I=$.map(j=>new n(j,this.options));for(const j of I){if(F(j))return[j];R.set(j.value,j)}R.size>1&&R.has("")&&R.delete("");const B=[...R.values()];return r.set(m,B),B}intersects(p,w){if(!(p instanceof e))throw new TypeError("a Range is required");return this.set.some(m=>V(m,w)&&p.set.some(P=>V(P,w)&&m.every(b=>P.every(C=>b.intersects(C,w)))))}test(p){if(!p)return!1;if(typeof p=="string")try{p=new c(p,this.options)}catch{return!1}for(let w=0;w<this.set.length;w++)if(pe(this.set[w],p,this.options))return!0;return!1}}rt=e;const t=Bi,r=new t,o=$t,n=Xe(),i=We,c=K,{safeRe:a,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:v}=Oe,{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:g}=qe,F=y=>y.value==="<0.0.0-0",N=y=>y.value==="",V=(y,p)=>{let w=!0;const m=y.slice();let P=m.pop();for(;w&&m.length;)w=m.every(b=>P.intersects(b,p)),P=m.pop();return w},H=(y,p)=>(i("comp",y,p),y=L(y,p),i("caret",y),y=ce(y,p),i("tildes",y),y=le(y,p),i("xrange",y),y=M(y,p),i("stars",y),y),O=y=>!y||y.toLowerCase()==="x"||y==="*",ce=(y,p)=>y.trim().split(/\s+/).map(w=>de(w,p)).join(" "),de=(y,p)=>{const w=p.loose?a[l.TILDELOOSE]:a[l.TILDE];return y.replace(w,(m,P,b,C,$)=>{i("tilde",y,m,P,b,C,$);let R;return O(P)?R="":O(b)?R=`>=${P}.0.0 <${+P+1}.0.0-0`:O(C)?R=`>=${P}.${b}.0 <${P}.${+b+1}.0-0`:$?(i("replaceTilde pr",$),R=`>=${P}.${b}.${C}-${$} <${P}.${+b+1}.0-0`):R=`>=${P}.${b}.${C} <${P}.${+b+1}.0-0`,i("tilde return",R),R})},L=(y,p)=>y.trim().split(/\s+/).map(w=>X(w,p)).join(" "),X=(y,p)=>{i("caret",y,p);const w=p.loose?a[l.CARETLOOSE]:a[l.CARET],m=p.includePrerelease?"-0":"";return y.replace(w,(P,b,C,$,R)=>{i("caret",y,P,b,C,$,R);let I;return O(b)?I="":O(C)?I=`>=${b}.0.0${m} <${+b+1}.0.0-0`:O($)?b==="0"?I=`>=${b}.${C}.0${m} <${b}.${+C+1}.0-0`:I=`>=${b}.${C}.0${m} <${+b+1}.0.0-0`:R?(i("replaceCaret pr",R),b==="0"?C==="0"?I=`>=${b}.${C}.${$}-${R} <${b}.${C}.${+$+1}-0`:I=`>=${b}.${C}.${$}-${R} <${b}.${+C+1}.0-0`:I=`>=${b}.${C}.${$}-${R} <${+b+1}.0.0-0`):(i("no pr"),b==="0"?C==="0"?I=`>=${b}.${C}.${$}${m} <${b}.${C}.${+$+1}-0`:I=`>=${b}.${C}.${$}${m} <${b}.${+C+1}.0-0`:I=`>=${b}.${C}.${$} <${+b+1}.0.0-0`),i("caret return",I),I})},le=(y,p)=>(i("replaceXRanges",y,p),y.split(/\s+/).map(w=>q(w,p)).join(" ")),q=(y,p)=>{y=y.trim();const w=p.loose?a[l.XRANGELOOSE]:a[l.XRANGE];return y.replace(w,(m,P,b,C,$,R)=>{i("xRange",y,m,P,b,C,$,R);const I=O(b),B=I||O(C),j=B||O($),ie=j;return P==="="&&ie&&(P=""),R=p.includePrerelease?"-0":"",I?P===">"||P==="<"?m="<0.0.0-0":m="*":P&&ie?(B&&(C=0),$=0,P===">"?(P=">=",B?(b=+b+1,C=0,$=0):(C=+C+1,$=0)):P==="<="&&(P="<",B?b=+b+1:C=+C+1),P==="<"&&(R="-0"),m=`${P+b}.${C}.${$}${R}`):B?m=`>=${b}.0.0${R} <${+b+1}.0.0-0`:j&&(m=`>=${b}.${C}.0${R} <${b}.${+C+1}.0-0`),i("xRange return",m),m})},M=(y,p)=>(i("replaceStars",y,p),y.trim().replace(a[l.STAR],"")),G=(y,p)=>(i("replaceGTE0",y,p),y.trim().replace(a[p.includePrerelease?l.GTE0PRE:l.GTE0],"")),Y=y=>(p,w,m,P,b,C,$,R,I,B,j,ie)=>(O(m)?w="":O(P)?w=`>=${m}.0.0${y?"-0":""}`:O(b)?w=`>=${m}.${P}.0${y?"-0":""}`:C?w=`>=${w}`:w=`>=${w}${y?"-0":""}`,O(I)?R="":O(B)?R=`<${+I+1}.0.0-0`:O(j)?R=`<${I}.${+B+1}.0-0`:ie?R=`<=${I}.${B}.${j}-${ie}`:y?R=`<${I}.${B}.${+j+1}-0`:R=`<=${R}`,`${w} ${R}`.trim()),pe=(y,p,w)=>{for(let m=0;m<y.length;m++)if(!y[m].test(p))return!1;if(p.prerelease.length&&!w.includePrerelease){for(let m=0;m<y.length;m++)if(i(y[m].semver),y[m].semver!==n.ANY&&y[m].semver.prerelease.length>0){const P=y[m].semver;if(P.major===p.major&&P.minor===p.minor&&P.patch===p.patch)return!0}return!1}return!0};return rt}var st,ir;function Xe(){if(ir)return st;ir=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],v=u.match(d);if(!v)throw new TypeError(`Invalid comparator: ${u}`);this.operator=v[1]!==void 0?v[1]:"",this.operator==="="&&(this.operator=""),v[2]?this.semver=new c(v[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(">")))}}st=e;const t=$t,{safeRe:r,t:o}=Oe,n=es,i=We,c=K,a=ee();return st}const ji=ee(),xi=(s,e,t)=>{try{e=new ji(e,t)}catch{return!1}return e.test(s)};var Ye=xi;const Vi=ee(),Ui=(s,e)=>new Vi(s,e).set.map(t=>t.map(r=>r.value).join(" ").trim().split(" "));var Gi=Ui;const Ji=K,Mi=ee(),_i=(s,e,t)=>{let r=null,o=null,n=null;try{n=new Mi(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===-1)&&(r=i,o=new Ji(r,t))}),r};var Ki=_i;const Hi=K,qi=ee(),Wi=(s,e,t)=>{let r=null,o=null,n=null;try{n=new qi(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===1)&&(r=i,o=new Hi(r,t))}),r};var zi=Wi;const ot=K,Xi=ee(),ar=ze,Yi=(s,e)=>{s=new Xi(s,e);let t=new ot("0.0.0");if(s.test(t)||(t=new ot("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 ot(i.semver.version);switch(i.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!n||ar(c,n))&&(n=c);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),n&&(!t||ar(t,n))&&(t=n)}return t&&s.test(t)?t:null};var Zi=Yi;const Qi=ee(),ea=(s,e)=>{try{return new Qi(s,e).range||"*"}catch{return null}};var ta=ea;const ra=K,ts=Xe(),{ANY:sa}=ts,oa=ee(),na=Ye,cr=ze,lr=It,ia=Nt,aa=Ft,ca=(s,e,t,r)=>{s=new ra(s,r),e=new oa(e,r);let o,n,i,c,a;switch(t){case">":o=cr,n=ia,i=lr,c=">",a=">=";break;case"<":o=lr,n=aa,i=cr,c="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(na(s,e,r))return!1;for(let l=0;l<e.set.length;++l){const u=e.set[l];let d=null,v=null;if(u.forEach(h=>{h.semver===sa&&(h=new ts(">=0.0.0")),d=d||h,v=v||h,o(h.semver,d.semver,r)?d=h:i(h.semver,v.semver,r)&&(v=h)}),d.operator===c||d.operator===a||(!v.operator||v.operator===c)&&n(s,v.semver))return!1;if(v.operator===a&&i(s,v.semver))return!1}return!0};var At=ca;const la=At,ua=(s,e,t)=>la(s,e,">",t);var da=ua;const pa=At,ha=(s,e,t)=>pa(s,e,"<",t);var fa=ha;const ur=ee(),ga=(s,e,t)=>(s=new ur(s,t),e=new ur(e,t),s.intersects(e,t));var ma=ga;const va=Ye,ya=Q;var wa=(s,e,t)=>{const r=[];let o=null,n=null;const i=s.sort((u,d)=>ya(u,d,t));for(const u of i)va(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 dr=ee(),Lt=Xe(),{ANY:nt}=Lt,ye=Ye,Dt=Q,ba=(s,e,t={})=>{if(s===e)return!0;s=new dr(s,t),e=new dr(e,t);let r=!1;e:for(const o of s.set){for(const n of e.set){const i=Pa(o,n,t);if(r=r||i!==null,i)continue e}if(r)return!1}return!0},Sa=[new Lt(">=0.0.0-0")],pr=[new Lt(">=0.0.0")],Pa=(s,e,t)=>{if(s===e)return!0;if(s.length===1&&s[0].semver===nt){if(e.length===1&&e[0].semver===nt)return!0;t.includePrerelease?s=Sa:s=pr}if(e.length===1&&e[0].semver===nt){if(t.includePrerelease)return!0;e=pr}const r=new Set;let o,n;for(const h of s)h.operator===">"||h.operator===">="?o=hr(o,h,t):h.operator==="<"||h.operator==="<="?n=fr(n,h,t):r.add(h.semver);if(r.size>1)return null;let i;if(o&&n){if(i=Dt(o.semver,n.semver,t),i>0)return null;if(i===0&&(o.operator!==">="||n.operator!=="<="))return null}for(const h of r){if(o&&!ye(h,String(o),t)||n&&!ye(h,String(n),t))return null;for(const g of e)if(!ye(h,String(g),t))return!1;return!0}let c,a,l,u,d=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1,v=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 h of e){if(u=u||h.operator===">"||h.operator===">=",l=l||h.operator==="<"||h.operator==="<=",o){if(v&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===v.major&&h.semver.minor===v.minor&&h.semver.patch===v.patch&&(v=!1),h.operator===">"||h.operator===">="){if(c=hr(o,h,t),c===h&&c!==o)return!1}else if(o.operator===">="&&!ye(o.semver,String(h),t))return!1}if(n){if(d&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===d.major&&h.semver.minor===d.minor&&h.semver.patch===d.patch&&(d=!1),h.operator==="<"||h.operator==="<="){if(a=fr(n,h,t),a===h&&a!==n)return!1}else if(n.operator==="<="&&!ye(n.semver,String(h),t))return!1}if(!h.operator&&(n||o)&&i!==0)return!1}return!(o&&l&&!n&&i!==0||n&&u&&!o&&i!==0||v||d)},hr=(s,e,t)=>{if(!s)return e;const r=Dt(s.semver,e.semver,t);return r>0?s:r<0||e.operator===">"&&s.operator===">="?e:s},fr=(s,e,t)=>{if(!s)return e;const r=Dt(s.semver,e.semver,t);return r<0?s:r>0||e.operator==="<"&&s.operator==="<="?e:s};var Ca=ba;const it=Oe,gr=qe,Ea=K,mr=Yr,Ra=ve,ka=Nn,Oa=Dn,$a=jn,Ta=Vn,Ia=Jn,Fa=Kn,Na=Wn,Aa=Yn,La=Q,Da=ti,Ba=oi,ja=Tt,xa=ci,Va=di,Ua=ze,Ga=It,Ja=Zr,Ma=Qr,_a=Ft,Ka=Nt,Ha=es,qa=Li,Wa=Xe(),za=ee(),Xa=Ye,Ya=Gi,Za=Ki,Qa=zi,ec=Zi,tc=ta,rc=At,sc=da,oc=fa,nc=ma,ic=wa,ac=Ca;var cc={parse:Ra,valid:ka,clean:Oa,inc:$a,diff:Ta,major:Ia,minor:Fa,patch:Na,prerelease:Aa,compare:La,rcompare:Da,compareLoose:Ba,compareBuild:ja,sort:xa,rsort:Va,gt:Ua,lt:Ga,eq:Ja,neq:Ma,gte:_a,lte:Ka,cmp:Ha,coerce:qa,Comparator:Wa,Range:za,satisfies:Xa,toComparators:Ya,maxSatisfying:Za,minSatisfying:Qa,minVersion:ec,validRange:tc,outside:rc,gtr:sc,ltr:oc,intersects:nc,simplifyRange:ic,subset:ac,SemVer:Ea,re:it.re,src:it.src,tokens:it.t,SEMVER_SPEC_VERSION:gr.SEMVER_SPEC_VERSION,RELEASE_TYPES:gr.RELEASE_TYPES,compareIdentifiers:mr.compareIdentifiers,rcompareIdentifiers:mr.rcompareIdentifiers};const lc=mn(cc),uc={minDelay:1500},dc="__no_updates__";class pc extends D.PollComputablePool{constructor(t,r,o={}){super({...o,...uc},r);S(this,"http");S(this,"preferredUpdateChannel");this.registryProvider=t,this.http=o.http,this.preferredUpdateChannel=o.preferredUpdateChannel}getKey(t){switch(t.type){case"dev-v1":return`dev_1_${t.folder}_${t.mtime}`;case"dev-v2":return`dev_2_${t.folder}_${t.mtime}`;case"from-registry-v2":return`from_registry_v2_${t.registryUrl}_${t.id.organization}_${t.id.name}_${t.id.version}`;default:return dc}}async readValue(t){try{switch(t.type){case"dev-v1":try{const r=await wt(t.folder);return r===t.mtime?void 0:{...t,mtime:r}}catch(r){this.logger.warn(r);return}case"dev-v2":try{const r=await _.tryLoadPackDescription(t.folder,this.logger);if(r===void 0)return;const o=await Je(r);return o===t.mtime?void 0:{...t,mtime:o}}catch(r){this.logger.warn(r);return}case"from-registry-v2":try{const r=this.registryProvider.getRegistry(t.registryUrl);let o;if(t.channel===void 0){const n=await r.getLatestOverview(t.id,U.StableChannel);if(n)o=n.spec;else{const i=await r.getLatestOverview(t.id,U.AnyChannel);if(i===void 0){this.logger.error(`No "any" channel record for ${U.blockPackIdToString(t.id)}`);return}o={...i.spec,channel:U.StableChannel}}}else{const n=this.preferredUpdateChannel??t.channel,i=await r.getLatestOverview(t.id,n);if(i)o=i.spec;else{this.logger.error(`Can't find update for ${U.blockPackIdToString(t.id)} in channel "${n}"`);return}}if(o.type!=="from-registry-v2")throw new Error(`Unexpected spec type ${o}.`);return lc.compare(o.id.version,t.id.version)<=0?void 0:((async()=>{try{await r.getComponents(o.id)}catch(n){this.logger.warn(n)}})(),o)}catch(r){this.logger.warn(r);return}default:return}}catch(r){this.logger.warn(r);return}}resultsEqual(t,r){if(t===void 0&&r===void 0)return!0;if(t===void 0||r===void 0||t.type!==r.type)return!1;switch(t.type){case"from-registry-v1":return r.type!=="from-registry-v1"?!1:t.registryUrl===r.registryUrl&&U.blockPackIdEquals(t.id,r.id);case"from-registry-v2":return r.type!=="from-registry-v2"?!1:t.registryUrl===r.registryUrl&&U.blockPackIdEquals(t.id,r.id);case"dev-v1":return r.type!=="dev-v1"?!1:t.folder===r.folder&&t.mtime===r.mtime;case"dev-v2":return r.type!=="dev-v2"?!1:t.folder===r.folder&&t.mtime===r.mtime;default:E.assertNever(t)}}}class vr{constructor(){S(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");if(t.refCount===0){this.resources.delete(e);const r=t.resource;r!=null&&typeof r[Symbol.dispose]=="function"&&r[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 we;function Se(){return we||(we={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0},process.env.MI_LOG_TREE_STAT&&(we.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),we)}function yr(s){return String(s.id)}const hc=["Int","Long","Float","Double","String","Bytes"];function at(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 s}const Le=(s,e)=>typeof e=="bigint"?e.toString():e;class fc{constructor(e,t,r){S(this,"pFrame",new ds.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.blobContentCache=t,this.columns=r,this.pFrame.setDataSource(this);for(const o of r){for(const i of fo(o.data))this.blobIdToResource.set(yr(i),i);const n=go(o.data,yr);try{this.pFrame.addColumnSpec(o.id,o.spec),this.pFrame.setColumnData(o.id,n)}catch(i){throw new Error(`Adding column ${o.id} to PFrame failed: ${i}; Spec: ${o.spec}, DataInfo: ${n}.`)}}}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 gc{constructor(e,t){S(this,"pFrames");S(this,"pTables");S(this,"blobContentCache");S(this,"concurrencyLimiter");this.blobDriver=e,this.logger=t;const r=new ps.LRUCache({maxSize:1e9,fetchMethod:async n=>await Pr.readFile(n),sizeCalculation:n=>n.length}),o=new E.ConcurrencyLimitingExecutor(1);this.blobContentCache=r,this.concurrencyLimiter=o,this.pFrames=new class extends vr{constructor(n){super(),this.blobDriver=n}createNewResource(n){return Se().logPFrameRequests&&t.info(`Create PFrame (${this.calculateParamsKey(n)}): ${JSON.stringify(n,Le)}`),new fc(this.blobDriver,r,n)}calculateParamsKey(n){return vc(n)}}(this.blobDriver),this.pTables=new class extends vr{constructor(n){super(),this.pFrames=n}async createNewResource(n){const i=this.pFrames.getByKey(n.pFrameHandle),c=await o.run(async()=>(Se().logPFrameRequests&&t.info(`Create PTable (${this.calculateParamsKey(n)}): ${JSON.stringify(n,Le)}`),await i.pFrame.createTable({src:Ee(n.def.src),filters:at(n.def.filters)})));return n.def.sorting.length!==0?c.sort(n.def.sorting):c}calculateParamsKey(n){return mc(n)}}(this.pFrames)}createPFrame(e,t){const r=e.filter(n=>hc.find(i=>i===n.spec.valueType)).map(n=>x.mapPObjectData(n,i=>Ge.isPlTreeNodeAccessor(i)?So(i):Po(n.spec,i))),o=this.pFrames.acquire(r);return t.addOnDestroy(o.unref),o.key}createPTable(e,t){const r=this.createPFrame(x.extractAllColumns(e.src),t),o=x.mapPTableDef(e,i=>i.id),n=this.pTables.acquire({def:o,pFrameHandle:r});return t.addOnDestroy(n.unref),n.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:t.compatibleWith,qualifications:[]}]:[]};return{hits:(await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.findColumns(r))).hits.map(o=>o.hit)}}async getColumnSpec(e,t){return await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.getColumnSpec(t))}async listColumns(e){return await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.listColumns())}async calculateTableData(e,t){let r=await this.concurrencyLimiter.run(async()=>(Se().logPFrameRequests&&this.logger.info(`calculateTableData, handle = ${e}, request = ${JSON.stringify(t,Le)}`),await this.pFrames.getByKey(e).pFrame.createTable({src:Ee(t.src),filters:at(t.filters)})));if(t.sorting.length>0){const i=await this.concurrencyLimiter.run(async()=>await r.sort(t.sorting));r.dispose(),r=i}const o=r.getSpec(),n=await this.concurrencyLimiter.run(async()=>await r.getData([...o.keys()]));return r.dispose(),o.map((i,c)=>({spec:i,data:n[c]}))}async getUniqueValues(e,t){return await this.concurrencyLimiter.run(async()=>(Se().logPFrameRequests&&this.logger.info(`getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,Le)}`),await this.pFrames.getByKey(e).pFrame.getUniqueValues({...t,filters:at(t.filters)})))}async getShape(e){return(await this.pTables.getByKey(e)).getShape()}async getSpec(e){return(await this.pTables.getByKey(e)).getSpec()}async getData(e,t,r){const o=await this.pTables.getByKey(e);return await this.concurrencyLimiter.run(async()=>await o.getData(t,r))}}function Ee(s){switch(s.type){case"column":return{type:"column",columnId:s.column,qualifications:[]};case"inner":case"full":return{type:s.type,entries:s.entries.map(e=>Ee(e))};case"outer":return{type:"outer",primary:Ee(s.primary),secondary:s.secondary.map(e=>Ee(e))};default:E.assertNever(s)}}function mc(s){const e=ne.createHash("sha256");return e.update(me(s.def)),e.digest().toString("hex")}function vc(s){const e=[...s].map(r=>x.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:a.id.toString()}))};break;case"BinaryPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([c,a])=>({key:c,value:[a.index.id.toString(),a.values.id.toString()]}))};break;default:throw Error(`unsupported resource type: ${i}`)}return n.payload.sort((c,a)=>c.key.localeCompare(a.key)),n}));e.sort((r,o)=>r.id.localeCompare(o.id));const t=ne.createHash("sha256");return t.update(me(e)),t.digest().toString("hex")}async function rs(s,e,t){const r={...kt,...Ot(e),...t},o=new E.HmacSha256Signer(r.localSecret),n=te.createDownloadClient(r.logger,s,r.localProjections),i=te.createLogsClient(s,r.logger),c=te.createUploadBlobClient(s,r.logger),a=te.createUploadProgressClient(s,r.logger),l=new te.DownloadDriver(r.logger,n,i,r.blobDownloadPath,o,r.blobDriverOps),u=new te.UploadDriver(r.logger,o,c,a,r.uploadDriverOps),d=new te.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),v=new te.LogsDriver(r.logger,d,l),h=await te.LsDriver.init(r.logger,s,o,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),g=new gc(l,r.logger);return{blobDriver:l,logDriver:v,lsDriver:h,signer:o,uploadDriver:u,pFrameDriver:g}}class Bt{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=ne.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async o=>{const n=await ho(o,e);return o.createField(f.field(this.projectListResourceId,t),"Dynamic",n),await o.commit(),await f.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await se(this.pl,e,r,async o=>{o.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(f.field(this.projectListResourceId,e)),await t.commit()}),await this.projectListTree.refreshState()}async projectIdToResourceId(e){return await this.pl.withReadTx("Project id to resource id",async t=>{const r=(await t.getField(f.field(this.projectListResourceId,e))).value;if(f.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 He.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={...qr,...Wr(t),...r};o.defaultTreeOptions.logStat=Se().logTreeStats;const n=await e.withWriteTx("MLInitialization",async F=>{const N=f.field(F.clientRoot,js);F.createField(N,"Dynamic");const V=await F.getField(N);if(f.isNullResourceId(V.value)){const H=F.createEphemeral(Or);return F.lock(H),F.setField(N,H),await F.commit(),await H.globalId}else return V.value}),i=o.logger,c=await rs(e,t,o),a=new ae.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),l=new Er(a),u=new no(l,c.signer,a),d=new te.DownloadUrlDriver(i,e.httpDispatcher,o.frontendDownloadPath),v={pl:e,signer:c.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:a,ops:o,bpPreparer:u,frontendDownloadDriver:d,driverKit:c,blockUpdateWatcher:new pc(l,i,{minDelay:o.devBlockUpdateRecheckInterval,http:a,preferredUpdateChannel:o.preferredUpdateChannel}),quickJs:await Be.getQuickJS()},h=new D.WatchableValue([]),g=await Vs(e,n,h,v);return new Bt(v,c,c.signer,n,h,g.tree,l,g.computable)}}const yc=["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 wc(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=[];yc.forEach(a=>{hs.channel(a).subscribe(u=>{var v;const d=new Date().toISOString();(v=u==null?void 0:u.response)!=null&&v.headers&&(u.response.headers=u.response.headers.map(h=>h.toString())),r.push(JSON.stringify({timestamp:d,event:a,data:u}))})});const o={plPings:[],blockRegistryOverviewChecks:[],blockGARegistryOverviewChecks:[],blockRegistryUiChecks:[],blockGARegistryUiChecks:[],autoUpdateCdnChecks:[]},n=f.plAddressToConfig(s,{defaultRequestTimeout:t.pingTimeoutMs});o.plPings=await fe(t.pingCheckDurationMs,t.maxPingsPerSecond,async()=>{const l=await new f.UnauthenticatedPlClient(n).ping();return JSON.stringify(l).slice(0,t.bodyLimit)+"..."});const c=new f.UnauthenticatedPlClient(n).ll.httpDispatcher;return o.blockRegistryOverviewChecks=await fe(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await be(new URL(t.blockOverviewPath,t.blockRegistryUrl),t,c)),o.blockGARegistryOverviewChecks=await fe(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await be(new URL(t.blockOverviewPath,t.blockGARegistryUrl),t,c)),o.blockRegistryUiChecks=await fe(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await be(new URL(t.blockUiPath,t.blockRegistryUrl),t,c)),o.blockGARegistryUiChecks=await fe(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await be(new URL(t.blockUiPath,t.blockGARegistryUrl),t,c)),o.autoUpdateCdnChecks=await fe(t.autoUpdateCdnDurationMs,t.maxAutoUpdateCdnChecksPerSecond,async()=>await be(t.autoUpdateCdnUrl,t,c)),bc(o,s,t,r)}async function fe(s,e,t){const r=mt(),o=[];for(;wr(r)<s;){const n=mt();let i;try{i={ok:!0,value:await t()}}catch(l){i={ok:!1,error:l}}const c=wr(n);o.push({elapsedMs:c,response:i});const a=1e3/e-c;a>0&&await Sr.setTimeout(a)}return o}async function be(s,e,t){const{body:r,statusCode:o}=await ae.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),n=await r.text();return{statusCode:o,beginningOfBody:n.slice(0,e.bodyLimit)+"..."}}function bc(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`
1
+ "use strict";var os=Object.defineProperty;var ns=(s,e,t)=>e in s?os(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var S=(s,e,t)=>ns(s,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const x=require("@platforma-sdk/model"),U=require("@milaboratories/pl-model-middle-layer"),ae=require("undici"),_=require("@platforma-sdk/block-tools"),Z=require("node:fs"),W=require("node:path"),is=require("yaml"),E=require("@milaboratories/ts-helpers"),as=require("node:fs/promises"),cs=require("@milaboratories/resolve-helper"),f=require("@milaboratories/pl-client"),Ge=require("@milaboratories/pl-tree"),D=require("@milaboratories/computable"),ne=require("node:crypto"),A=require("@milaboratories/pl-model-backend"),br=require("denque"),ls=require("@platforma-sdk/workflow-tengo"),me=require("canonicalize"),us=require("node:assert"),Be=require("quickjs-emscripten"),Sr=require("node:timers/promises"),te=require("@milaboratories/pl-drivers"),ds=require("@milaboratories/pframes-node"),ps=require("lru-cache"),hs=require("node:diagnostics_channel");function fs(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 Pr=fs(as);async function jt(s){try{return await Pr.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const gs=[_.RegistryV1.PlPackageYamlConfigFile],ms=[_.RegistryV1.PlPackageJsonConfigFile],vt=["backend","dist","tengo","tpl","main.plj.gz"],yt=["config","dist","config.json"],Cr=["frontend","dist"],xt="block-model/dist/config.json",vs="block-ui/package.json",ys=[vt,yt,gs,ms,Cr];async function ws(s){return await jt(W.join(s,...yt))!==void 0||await jt(W.join(s,...vt))!==void 0}function Ze(s,e){const t=cs.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function Vt(s,e){if(W.isAbsolute(s)||(s=W.resolve(s)),await ws(s))return{workflow:W.join(s,...vt),config:W.join(s,...yt),ui:W.join(s,...Cr)};{const t=Ze(s,xt),r=Ze(s,xt),o=Ze(s,vs);return{workflow:t,config:r,ui:W.resolve(o,"..","dist")}}}async function bs(s){try{return await Z.promises.readFile(s,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}async function Ss(s){try{return await Z.promises.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}async function wt(s){let e=0n;for(const t of ys){const r=W.join(s,...t),o=await Ss(r);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function Je(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 Ps{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 ae.request(`${r.url}/${_.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const c of i){const{organization:a,package:l,latestMeta:u,latestVersion:d}=c,v={organization:a,name:l,version:d},h={id:v,meta:{title:u.title??"No title",description:u.description??"No Description",organization:{name:a,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:v,registryUrl:r.url}};t.push({registryId:e.id,id:v,latestByChannel:{[U.AnyChannel]:h,[U.StableChannel]:h},allVersions:c.allVersions.map(g=>({version:g,channels:[]}))})}return t;case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(c=>c.latestByChannel[U.StableChannel]?{...c,registryId:e.id}:{...c,latestByChannel:{...c.latestByChannel,[U.StableChannel]:(a=>a.spec.type==="from-registry-v2"?{...a,spec:{...a.spec,channel:U.StableChannel}}:a)(c.latestByChannel[U.AnyChannel])},registryId:e.id});case"local-dev":for(const c of await Z.promises.readdir(r.path,{withFileTypes:!0})){if(!c.isDirectory())continue;const a=W.join(r.path,c.name),l=await bs(W.join(a,_.RegistryV1.PlPackageYamlConfigFile));if(l!==void 0){const u=_.RegistryV1.PlPackageConfigData.parse(is.parse(l)),d=await wt(a),v={organization:u.organization,name:u.package,version:"DEV"},h={id:v,meta:{title:u.meta.title??"No title",description:u.meta.description??"No Description",organization:{name:u.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:a,mtime:d}};t.push({registryId:e.id,id:v,latestByChannel:{[U.AnyChannel]:h,[U.StableChannel]:h},allVersions:[]})}else{let u=a,d=await _.tryLoadPackDescription(u);if(d===void 0){for(const v of["block","meta"])if(u=W.join(a,v),d=await _.tryLoadPackDescription(u),d!==void 0)break}if(d!==void 0){const v=await Je(d),h={id:d.id,meta:await _.BlockPackMetaEmbedAbsoluteBytes.parseAsync(d.meta),spec:{type:"dev-v2",folder:u,mtime:v}};t.push({registryId:e.id,id:d.id,latestByChannel:{[U.AnyChannel]:h,[U.StableChannel]:h},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 Er{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 _.RegistryV2Reader(_.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const Cs={type:"remote-v2",url:"https://blocks.pl-open.science/"},Es={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},Rs={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},ks={groups:[{id:"default",label:"Default",blocks:[]}]},Os={stagingRefreshTimestamp:0,blocksInLimbo:[]},$s={label:"New Project"},Ts={name:"UserProject",version:"2"},Rr="SchemaVersion",kr="1",bt="ProjectCreated",Re="ProjectLastModified",ke="ProjectMeta",ue="ProjectStructure",je="BlockRenderingState",Is="BlockFrontendState/",Fs=/^BlockFrontendState\/(?<blockid>.*)$/;function ct(s){return`${Is}${s}`}const Ns="BlockArgsAuthor/";function lt(s){return`${Ns}${s}`}const ut="ProjectStructureAuthor";function As(s){const e=s.match(Fs);if(e!==null)return e.groups.blockid}const Ls="__serviceTemplate_";function dt(s){return`${Ls}${s}`}function J(s,e){return`${s}-${e}`}const Ds=/^(?<blockId>.*)-(?<fieldName>blockPack|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function Bs(s){const e=s.match(Ds);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const js="projects",Or={name:"Projects",version:"1"},xs=s=>f.resourceTypesEqual(s.type,Or)?s.fields:[];async function Vs(s,e,t,r){const o=await Ge.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:xs},r.logger);return{computable:D.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 v=E.notEmpty(d.getKeyValueAsJson(ke)),h=E.notEmpty(d.getKeyValueAsJson(bt)),g=E.notEmpty(d.getKeyValueAsJson(Re));l.push({id:u,rid:d.id,created:new Date(h),lastModified:new Date(g),opened:a.indexOf(d.id)>=0,meta:v})}return l.sort(u=>-u.lastModified.valueOf()),l}).withStableType(),tree:o}}const Us={name:"EphRenderTemplate",version:"1"},Gs={name:"RenderTemplate",version:"1"};function St(s,e,t,r,o){if(o.length===0)throw new Error("Zero output names provided");const n=t?s.createEphemeral(Us):s.createStruct(Gs),i=f.field(n,"template"),c=f.field(n,"inputs");return s.createField(i,"Input",e),s.createField(c,"Input",f.Pl.createPlMap(s,r,t)),s.lockInputs(n),f.Pl.futureRecord(s,n,o,"Output","outputs/")}const Js={name:"BContextEnd",version:"1"},Ms={name:"BContext",version:"1"},_s="id",Ks="parent/",Hs=["context","result"];function Ut(s,e,t){return St(s,e,!0,t,Hs)}function qs(s){const e=s.createEphemeral(Js);return s.lock(e),e}function Ws(s,e){if(e.length===0)return qs(s);if(e.length===1)return e[0];const t=s.createEphemeral(Ms);s.createField(f.field(t,_s),"Input",f.Pl.createPlString(s,ne.randomUUID()));for(let r=0;r<e.length;r++)s.createField(f.field(t,`${Ks}${r}`),"Input",e[r]);return s.lock(t),t}function zs(s,e){const t=A.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return Tr(s,t);default:E.assertNever(r)}}const $r={hash(s,e){e.update(A.PlTemplateLibV1.type.name).update(A.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue(A.PlTemplateLibV1.type,JSON.stringify(A.PlTemplateLibV1.fromV2Data(s).data))}},xe={hash(s,e){e.update(A.PlTemplateSoftwareV1.type.name).update(A.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=A.PlTemplateSoftwareV1.fromV2Data(s),o=e.createStruct(A.PlTemplateSoftwareV1.type,r.data);return e.setKValue(o,A.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(o),o}},Xs={hash(s,e){e.update(A.PlTemplateV1.type.name).update(A.PlTemplateV1.type.version).update(s.hashOverride??"").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),$r.hash(o,e);for(const[r,o]of t(Object.entries(s.software??{})))e.update("soft:"+r),xe.hash(o,e);for(const[r,o]of t(Object.entries(s.assets??{})))e.update("asset:"+r),xe.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){return e.createStruct(A.PlTemplateV1.type,JSON.stringify(A.PlTemplateV1.fromV2Data(s).data))}},Ys={hash(s,e){e.update(A.PlTemplateOverrideV1.type.name).update(A.PlTemplateOverrideV1.type.version).update(s.hashOverride??"")},render(s,e,t){return e.createStruct(A.PlTemplateOverrideV1.type,JSON.stringify(A.PlTemplateOverrideV1.fromV2Data(s)))}};function Tr(s,e,t){t||(t=new Map);const r=(c,a)=>{const l=ne.createHash("sha256");a.hash(c,l);const u=l.digest("hex");if(!t.has(u)){const d=a.render(c,s,r);t.set(u,d)}return t.get(u)},o=r(e,Xs);for(const[c,a]of Object.entries(e.libs??{})){const l=A.PlTemplateV1.libField(o,c);s.createField(l,"Input"),s.setField(l,r(a,$r))}for(const[c,a]of Object.entries(e.software??{})){const l=A.PlTemplateV1.swField(o,c);s.createField(l,"Input"),s.setField(l,r(a,xe))}for(const[c,a]of Object.entries(e.assets??{})){const l=A.PlTemplateV1.swField(o,c);s.createField(l,"Input"),s.setField(l,r(a,xe))}for(const[c,a]of Object.entries(e.templates??{})){const l=A.PlTemplateV1.tplField(o,c);s.createField(l,"Input"),s.setField(l,Tr(s,a,t))}if(s.lock(o),!e.hashOverride)return o;const n=r(e,Ys),i=A.PlTemplateOverrideV1.tplField(n);return s.createField(i,"Service"),s.setField(i,o),s.lock(o),n}const Ir={name:"TengoTemplateGet",version:"1"},Fr="registry",Nr="templateURI",Ar="template",Zs={name:"TengoTemplatePack",version:"1"},Qs={name:"TengoTemplatePackConvert",version:"1"},eo="templatePack",to="template";async function Lr(s){switch(s.type){case"from-file":return{type:"explicit",content:await Z.promises.readFile(s.path)};case"from-registry":case"explicit":return s;default:return E.assertNever(s)}}function ro(s,e){const t=s.createStruct(Ir),r=f.field(t,Fr),o=f.field(t,Nr),n=f.field(t,Ar);return s.setField(r,s.createValue(f.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(o,s.createValue(f.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function Me(s,e){switch(e.type){case"from-registry":return ro(s,e);case"explicit":return zs(s,e);default:return E.assertNever(e)}}const Pt={name:"Frontend/FromUrl",version:"1"},Ct={name:"Frontend/FromFolder",version:"1"};function so(s,e){switch(e.type){case"url":return s.createValue(Pt,JSON.stringify({url:e.url}));case"local":return s.createValue(Ct,JSON.stringify({path:e.path,signature:e.signature}));default:return E.assertNever(e)}}const oo={name:"BlockPackCustom",version:"1"},Dr="template",Br="frontend";function Gt(s){return s.endsWith("/")?s:`${s}/`}class no{constructor(e,t,r){this.v2RegistryProvider=e,this.signer=t,this.http=r}async getBlockConfigContainer(e){switch(e.type){case"explicit":return e.config;case"dev-v1":{const t=await Vt(e.folder),r=await Z.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await _.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=this.http!==void 0?{dispatcher:this.http}:{},r=`${Gt(e.registryUrl)}${_.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`;return await(await ae.request(`${r}/config.json`,t)).body.json()}case"from-registry-v2":{const t=this.http!==void 0?{dispatcher:this.http}:{},o=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id);return await(await ae.request(o.model.url,t)).body.json()}default:return E.assertNever(e)}}async prepare(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await Vt(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 _.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 Je(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=this.http!==void 0?{dispatcher:this.http}:{},r=`${Gt(e.registryUrl)}${_.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,o=`${r}/template.plj.gz`,n=await ae.request(o,t);if(n.statusCode!==200)throw new Error(`Block not found in registry (url = ${o} ; code = ${n.statusCode}): `+JSON.stringify(e));const i=new Uint8Array(await n.body.arrayBuffer()),a=await(await ae.request(`${r}/config.json`,t)).body.json();return{type:"explicit",template:{type:"explicit",content:i},config:a,frontend:{type:"url",url:`${r}/frontend.tgz`},source:e}}case"from-registry-v2":{const t=this.http!==void 0?{dispatcher:this.http}:{},o=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),n=async()=>await(await ae.request(o.model.url,t)).body.json(),i=async()=>await(await ae.request(o.workflow.main.url,t)).body.arrayBuffer(),[c,a]=await Promise.all([n(),i()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(a)},config:c,frontend:{type:"url",url:o.ui.url},source:e}}default:return E.assertNever(e)}}}function io(s,e){const t={config:e.config,source:e.source},r=s.createStruct(oo,JSON.stringify(t));return s.createField(f.field(r,Dr),"Input",Me(s,e.template)),s.createField(f.field(r,Br),"Input",so(s,e.frontend)),s.lock(r),r}function Jt(s,e){switch(e.type){case"explicit":return io(s,e);default:return E.assertNever(e.type)}}function $e(s,e){return{__isRef:!0,blockId:s,name:e}}function ao(s){return typeof s=="object"&&s!==null&&s.__isRef===!0&&"blockId"in s&&"name"in s}function pt(s,e,t){const r=typeof e;switch(r){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if(ao(e))t===void 0||t.has(e.blockId)?s.upstreams.add(e.blockId):s.missingReferences=!0;else if(Array.isArray(e))for(const o of e)pt(s,o,t);else for(const[,o]of Object.entries(e))pt(s,o,t);return;default:E.assertNever(r)}}function co(s,e){const t={upstreams:new Set,missingReferences:!1};return pt(t,s,e),t}function oe(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class jr{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;){let 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 ht(s){const e=new Map;let t;for(const{id:r}of oe(s)){const o={id:r,missingReferences:!1};e.set(r,o),t===void 0?o.upstream=new Set:(o.upstream=new Set([t.id]),t.downstream=new Set([o.id])),t=o}return t!==void 0&&(t.downstream=new Set),new jr(e)}function De(s,e){const t=new Map,r=new Set;for(const{id:o}of oe(s)){const n=e(o);if(n===void 0)continue;const i=co(n,r),c={id:o,missingReferences:i.missingReferences,upstream:i.upstreams,downstream:new Set};t.set(o,c),i.upstreams.forEach(a=>t.get(a).downstream.add(o)),r.add(o)}return new jr(t)}function lo(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function ft(s,e){if(s.size>e.size)return ft(e,s);for(const t of s)if(e.has(t))return!0;return!1}function Mt(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):(!lo(n.upstream,i.upstream)||ft(n.upstream,o))&&o.add(n.id)}),e.nodes.forEach(n=>{s.nodes.has(n.id)?ft(n.upstream,o)&&o.add(n.id):r.add(n.id)}),{onlyInA:t,onlyInB:r,different:o}}let Qe;async function xr(){if(Qe===void 0){const s=await Lr(ls.Templates["pframes.export-pframe"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=ne.createHash("sha256").update(s.content).digest("hex");Qe={spec:s,hash:e}}return Qe}function uo(s,e,t){return St(s,e,!0,{pf:t},["result"]).result}function et(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 _t{constructor(e,t){S(this,"currentInputsC",et(()=>this.fields.currentArgs.modCount,()=>JSON.parse(Buffer.from(this.fields.currentArgs.value).toString())));S(this,"actualProductionInputsC",et(()=>{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 JSON.parse(Buffer.from(e).toString())}));S(this,"productionStaleC",et(()=>{var e;return`${this.fields.currentArgs.modCount}_${(e=this.fields.prodArgs)==null?void 0:e.modCount}`},()=>this.fields.prodArgs===void 0||Buffer.compare(this.fields.currentArgs.value,this.fields.prodArgs.value)!==0));this.id=e,this.fields=t}check(){if(this.fields.prodOutput===void 0!=(this.fields.prodCtx===void 0))throw new Error("inconsistent prod fields");if(this.fields.stagingOutput===void 0!=(this.fields.stagingCtx===void 0))throw new Error("inconsistent stage fields");if(this.fields.prodOutputPrevious===void 0!=(this.fields.prodCtxPrevious===void 0))throw new Error("inconsistent prod cache fields");if(this.fields.stagingOutputPrevious===void 0!=(this.fields.stagingCtxPrevious===void 0))throw new Error("inconsistent stage cache fields");if(this.fields.blockPack===void 0)throw new Error("no block pack field");if(this.fields.currentArgs===void 0)throw new Error("no current args field")}get currentInputs(){return this.currentInputsC()}get stagingRendered(){return this.fields.stagingCtx!==void 0}get productionRendered(){return this.fields.prodCtx!==void 0}get productionHasErrors(){var e;return((e=this.fields.prodUiCtx)==null?void 0:e.status)==="Error"}get requireProductionRendering(){return!this.productionRendered||this.productionStaleC()||this.productionHasErrors}get actualProductionInputs(){return this.actualProductionInputsC()}getTemplate(e){return e.getFutureFieldValue(f.Pl.unwrapHolder(e,this.fields.blockPack.ref),Dr,"Input")}}const po=s=>{throw new Error(`No new block info for ${s}`)};class Ve{constructor(e,t,r,o,n,i,c,a,l,u,d,v){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=v}fixProblems(){this.blockInfos.forEach(e=>{(e.fields.prodArgs===void 0||e.fields.prodOutput===void 0||e.fields.prodCtx===void 0)&&this.deleteBlockFields(e.id,"prodArgs","prodOutput","prodCtx")})}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=ht(this.struct)),this.stagingGraph}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=De(this.struct,e=>this.getBlockInfo(e).currentInputs)),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=De(this.struct,e=>this.getBlockInfo(e).actualProductionInputs)),this.actualProductionGraph}getBlockInfo(e){return E.notEmpty(this.blockInfos.get(e))}getBlock(e){for(const t of oe(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const o=f.field(this.rid,J(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(f.field(this.rid,J(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(f.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())}createCtx(e,t){const r=[];return e.forEach(o=>{const n=this.getBlockInfo(o);if(n.fields[t]===void 0||n.fields[t].ref===void 0)throw new Error("One of the upstreams staging is not rendered.");r.push(f.Pl.unwrapHolder(this.tx,n.fields[t].ref))}),Ws(this.tx,r)}exportCtx(e){return uo(this.tx,f.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createCtx(this.getStagingGraph().nodes.get(e).upstream,"stagingCtx");if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const o=t.getTemplate(this.tx),n=Ut(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(f.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(f.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",f.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"stagingOutput",n.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),r=this.createCtx(this.getPendingProductionGraph().nodes.get(e).upstream,"prodCtx");if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const o=t.getTemplate(this.tx),n=Ut(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(f.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(f.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",f.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"prodOutput",n.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=po){const r=this.getStagingGraph(),o=this.getActualProductionGraph(),n=ht(e),i=De(e,l=>{var u;return(u=this.blockInfos.get(l))==null?void 0:u.actualProductionInputs}),c=Mt(r,n),a=Mt(o,i);for(const l of c.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 c.onlyInB){const u=new _t(l,{});this.blockInfos.set(l,u);const d=t(l),v=Jt(this.tx,d.blockPack);this.setBlockField(l,"blockPack",f.Pl.wrapInHolder(this.tx,v),"NotReady");const h=Buffer.from(d.args),g=this.tx.createValue(f.Pl.JsonObject,h);this.setBlockField(l,"currentArgs",g,"Ready",h),d.uiState&&(this.blockFrontendStates.set(l,d.uiState),this.changedBlockFrontendStates.add(l)),u.check()}for(const l of c.different)this.resetStaging(l);o.traverse("downstream",[...a.different],l=>{this.resetOrLimboProduction(l.id)}),(c.onlyInB.size>0||c.onlyInA.size>0||c.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",f.Pl.wrapInHolder(this.tx,Jt(this.tx,t)),"NotReady"),r!==void 0?(this.setArgs([{blockId:e,args:r}]),this.setUiState(e,void 0)):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,i=>{r.add(i.id)});else for(const i of r){const c=o.nodes.get(i);if(c===void 0)throw new Error(`Can't find block with id: ${i}`);for(const a of c.upstream)if(!r.has(a))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const i of oe(this.structure)){if(!r.has(i.id))continue;let c=this.getBlockInfo(i.id).requireProductionRendering||this.blocksInLimbo.has(i.id);if(!c){for(const a of o.nodes.get(i.id).upstream)if(n.has(a)){c=!0;break}}c&&(this.renderProductionFor(i.id),n.add(i.id))}return o.traverse("downstream",[...n],i=>{n.has(i.id)||this.resetOrLimboProduction(i.id)}),n.size>0&&this.updateLastModified(),n}stopProduction(...e){var i,c;const t=this.getActualProductionGraph(),r=new br(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,lt(t)):this.tx.setKValue(this.rid,lt(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,ut):this.tx.setKValue(this.rid,ut,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,Re,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,ue,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,je,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,ke,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,ct(e)):this.tx.setKValue(this.rid,ct(e),t)}this.assignAuthorMarkers()}}static async load(e,t,r){const o=e.getResourceData(t,!0),n=e.getKValueJson(t,Rr),i=e.getKValueJson(t,Re),c=e.getKValueJson(t,ke),a=e.getKValueJson(t,ue),l=e.getKValueJson(t,je),u=e.listKeyValuesString(t),[d,v,h,g,F,{stagingRefreshTimestamp:N,blocksInLimbo:V},H]=await Promise.all([o,n,i,c,a,l,u]);if(v!==kr)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${v}`);const O=new Map;for(const p of d.fields){const w=Bs(p.name);if(w===void 0)continue;let m=O.get(w.blockId);m===void 0&&(m={id:w.blockId,fields:{}},O.set(w.blockId,m)),m.fields[w.fieldName]=f.isNullResourceId(p.value)?{modCount:0}:{modCount:0,ref:p.value}}const ce=await xr(),de=dt(ce.hash),L=d.fields.find(p=>p.name===de);let X;L!==void 0?X=f.ensureResourceIdNotNull(L.value):(X=f.Pl.wrapInHolder(e,Me(e,ce.spec)),e.createField(f.field(t,dt(ce.hash)),"Dynamic",X));const le={stagingRefreshTimestamp:N},q=new Set(V),M=new Map;for(const p of H){const w=As(p.key);w!==void 0&&M.set(w,p.value)}const G=[];O.forEach(({id:p,fields:w})=>{for(const[,m]of Object.entries(w))if(m.ref!==void 0){if(!f.isResource(m.ref)||f.isResourceRef(m.ref))throw new Error("unexpected behaviour");G.push([m,e.getResourceData(m.ref,!1)])}});for(const[p,w]of G){const m=await w;p.value=m.data,f.isNotNullResourceId(m.error)?p.status="Error":m.resourceReady||f.isNotNullResourceId(m.originalResourceId)?p.status="Ready":p.status="NotReady"}const Y=new Map;O.forEach(({id:p,fields:w})=>Y.set(p,new _t(p,w)));const pe=new Set;for(const p of oe(F)){if(!Y.has(p.id))throw new Error(`Inconsistent project structure: no inputs for ${p.id}`);pe.add(p.id)}Y.forEach(p=>{if(!pe.has(p.id))throw new Error(`Inconsistent project structure: no structure entry for ${p.id}`);p.check()});const y=new Ve(t,e,r,v,h,g,F,le,q,Y,M,X);return y.fixProblems(),y}}async function ho(s,e=$s){const t=s.createEphemeral(Ts);s.lock(t);const r=String(Date.now());s.setKValue(t,Rr,JSON.stringify(kr)),s.setKValue(t,bt,r),s.setKValue(t,Re,r),s.setKValue(t,ke,JSON.stringify(e)),s.setKValue(t,ue,JSON.stringify(ks)),s.setKValue(t,je,JSON.stringify(Os));const o=await xr();return s.createField(f.field(t,dt(o.hash)),"Dynamic",f.Pl.wrapInHolder(s,Me(s,o.spec))),t}async function tt(s,e,t){return se(s,e,void 0,t)}async function se(s,e,t,r){if(s instanceof f.PlClient)return await s.withWriteTx("ProjectAction",async o=>{const n=await Ve.load(o,e,t),i=await r(n);return n.wasModified&&(n.save(),await o.commit()),i});{const o=await Ve.load(s,e,t),n=await r(o);return o.save(),n}}function*fo(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 Kt(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function go(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:Kt(s.parts,e)};case"BinaryPartitioned":return{...s,parts:Kt(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:E.assertNever(s)}}const mo=f.resourceType("PColumnData/JsonPartitioned","1"),vo=f.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),yo=f.resourceType("PColumnData/BinaryPartitioned","1"),wo=f.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),bo=f.resourceType("PColumnData/Json","1");function So(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(f.resourceTypesEqual(s.resourceType,bo)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(f.resourceTypesEqual(s.resourceType,mo)){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(f.resourceTypesEqual(s.resourceType,vo)){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(f.resourceTypesEqual(s.resourceType,yo)){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(f.resourceTypesEqual(s.resourceType,wo)){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: ${f.resourceTypeToString(s.resourceType)}`)}function Po(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 Co(s,e){const t=ne.createHash("sha256");return t.update(me(s)),t.update(String(f.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function Ht(s,e){return me({__isRef:!0,blockId:s,name:e})}function Eo(s,e){return me({resolvePath:s,name:e})}function Vr(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 v=E.notEmpty((c=d.groups)==null?void 0:c.name);if(!v.startsWith(r)){if(e)throw new Error(`unexpected field name ${u}`);continue}v=v.slice(r.length);const h=E.notEmpty((a=d.groups)==null?void 0:a.type);let g=n.get(v);switch(g===void 0&&(g={},n.set(v,g)),h){case"spec":g.spec=(l=s.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:l.getDataAsJson();break;case"data":g.hasData=!0,g.data=()=>s.traverseOrError({field:u,ignoreError:t});default:continue}}const i=s.getInputsLocked();if(i)for(const[,u]of n)u.data===void 0&&(u.hasData=!1);return{locked:i,results:n}}function Ro(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const o=Vr(s,e,!1,t);us(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 new Ge.PlError(a.error);n[i]={id:r.length===0?Co(c.spec,a.value):Eo(r,i),spec:c.spec,data:a.value}}return n}class Et{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;let 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 x.mapValueInVOE(n,l=>({id:Ht(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:$e(i,c),obj:{id:l.ok?Ht(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:$e(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:$e(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),x.executePSpecPredicate(e,a.spec)&&t.push({label:r.info.label+" / "+c,ref:$e(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(ue)),c=ht(n).traverseIds("upstream",r),a=new Map;for(const l of oe(n)){if(!c.has(l.id))continue;const u=qt(o.traverse({field:J(l.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:J(l.id,"prodUiCtx"),stableIfNotFound:!0})),d=qt(o.traverse({field:J(l.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:J(l.id,"stagingUiCtx")}));a.set(l.id,{info:l,prod:u,staging:d})}return new Et(e,a)}}function qt(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return Vr(e.value,!1,!0)}function Rt(s,e){return{blockId:e,args:o=>E.notEmpty(o.accessor(s).node().traverse({field:J(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),uiState:o=>o.accessor(s).node().getKeyValueAsString(ct(e)),blockMeta:o=>{const n=o.accessor(s).node(),i=E.notEmpty(n.getKeyValueAsJson(ue)),c=new Map;for(const a of oe(i))c.set(a.id,a);return c}}}function Ur(s,e){return{...Rt(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:J(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:J(e,"stagingOutput"),ignoreError:!0}))==null?void 0:o.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>Et.create(t,s,e)}}function*z(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*z(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*z(t);return;case"MakeArray":for(const t of s.template)yield*z(t);return;case"GetJsonField":case"GetResourceField":yield*z(s.source),yield*z(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*z(s.source),yield*z(s.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetLogHandle":yield*z(s.source);return;case"IsEmpty":yield*z(s.arg);return;case"Not":yield*z(s.operand);return;case"And":case"Or":yield*z(s.operand1),yield*z(s.operand2);return;default:E.assertNever(s)}}function ko(s,e){const t={};for(const[r,o]of Object.entries(s))t[r]=e(o);return t}function Pe(s,e){return s===void 0?void 0:e(s)}function Oo(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function $o(s){for(const e of z(s))if(Oo(e))return!0;return!1}function _e(s){return{type:"ReturnResult",result:s}}function k(s){return()=>_e(s)}const To=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return k(e)},Io=s=>{const e=s.source;if(e===void 0)return k(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return k(t)},Fo=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?k(void 0):({cCtx:r})=>{var o;return _e((o=r.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function Gr(s,e){const t={},r=s.length;for(let o=0;o<r;o++)t[String(o)]=e(s[o]);return t}function No(s,e){return t=>{const r=t.source;return r===void 0?k(void 0):()=>({type:"ScheduleSubroutine",subroutine:Jr(r.length),args:Gr(r,o=>T({...s,[e.itVar]:o},e.mapping))})}}function Jr(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return k(t)}}function Ao(s,e){return t=>{const r=t.source;if(r===void 0)return k(void 0);const o={};for(const[n,i]of Object.entries(r)){const c={...s,[e.itVar]:i};o[n]=T(c,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:Lo,args:o})}}const Lo=s=>k(s),Do=s=>{const e=s.arg;return k(e===void 0?void 0:e.length===0)},Bo=s=>{const e=s.operand;return k(e===void 0?void 0:!e)},jo=s=>{const e=s.operand1,t=s.operand2;return k(e===void 0||t===void 0?void 0:e&&t)},xo=s=>{const e=s.operand1,t=s.operand2;return k(e===void 0||t===void 0?void 0:e||t)},Vo=s=>{const e=s.source;return e===void 0?k(void 0):({cCtx:t})=>{var r;return _e((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},Uo=s=>{const e=s.source,t=s.field;return k(e===void 0||t===void 0?void 0:e[t])};function Go(s,e){return t=>{const r=t.source;return r===void 0?k(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]=k(void 0);else{const l={...s,[e.itVar]:a.persist()};i[c]=T(l,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:Jo,args:i}}}}const Jo=s=>k(s),Mo=s=>{const e=s.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:D.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)}})})},_o=s=>{const e=s.source;return e===void 0?k(void 0):({cCtx:t,drivers:r})=>{const o=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:D.Computable.make(()=>r.blobDriver.getDownloadedBlob(o),{postprocessValue:async n=>n===void 0?void 0:(await r.blobDriver.getContent(n.handle)).toString()})}}},Ko=s=>{const e=s.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:D.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())}})})},Ho=s=>{const e=s.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},qo=s=>{const e=s.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},Wo=s=>{const e=s.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},zo=s=>e=>{const t=e.source;return t===void 0?k(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},Xo=s=>e=>{const t=e.source;return t===void 0?k(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},Yo=s=>{const e=s.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function T(s,e){switch(e.type){case"GetFromCtx":const t=s[e.variable];return typeof t=="function"?r=>_e(t(r.cCtx)):k(t);case"Isolate":return({drivers:r})=>({type:"ScheduleComputable",computable:Kr(r,s,e.cfg)});case"Immediate":return k(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:Uo,args:{source:T(s,e.source),field:T(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:No(s,e),args:{source:T(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:Ao(s,e),args:{source:T(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:To,args:ko(e.template,r=>T(s,r))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:Jr(e.template.length),args:Gr(e.template,r=>T(s,r))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:Io,args:{source:T(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:Do,args:{arg:T(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:Bo,args:{operand:T(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:jo,args:{operand1:T(s,e.operand1),operand2:T(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:xo,args:{operand1:T(s,e.operand1),operand2:T(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:Go(s,e),args:{source:T(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:Fo,args:{source:T(s,e.source),field:T(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Vo,args:{source:T(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Mo,args:{source:T(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:_o,args:{source:T(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Ko,args:{source:T(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Ho,args:{source:T(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:qo,args:{source:T(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:Wo,args:{source:T(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:zo(e.lines),args:{source:T(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:Xo(e.patternToSearch),args:{source:T(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:Yo,args:{source:T(s,e.source)}});default:return E.assertNever(e)}}const Zo=["$prod","$staging"];function Qo(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 Mr=Symbol(),_r="return",en={op:Mr,arg:_r};function tn(s){return s.op==Mr&&s.arg==_r}function rn(){return{pendingSubroutines:new Map}}function Wt(s,e,t,r){const o=new br(t),n=(c,a)=>{if(tn(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[v,h]of u)o.push({destination:{op:l,arg:v},operation:h});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 sn(s,e,t,r={}){return Kr(s,Qo(e),t,r)}function Kr(s,e,t,r={}){const o=`${e.blockId}#`+me({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>Zo.indexOf(n)===-1)),cfg:t});return D.Computable.makeRaw(n=>{const i={drivers:s,cCtx:n},c=rn();return{ir:Wt(i,c,[{destination:en,operation:T(e,t)}],!0),async postprocessValue(l){const u=[];for(const g of l)u.push({destination:g.destination,operation:k(g.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},v=new Map;for(const[g,F]of c.pendingSubroutines)v.set(g,{...F,args:{...F.args}});const h={result:c.result,pendingSubroutines:v};if(Wt(d,h,u,!1),!("result"in h))throw new Error("illegal cfg rendering stack state, no result");return h.result}}},{...r,key:o})}function on(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}function zt(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class Ue{constructor(e,t,r,o,n){S(this,"callbackRegistry");S(this,"fnJSONStringify");S(this,"fnJSONParse");S(this,"computablesToResolve",{});S(this,"computableCtx");S(this,"accessors",new Map);S(this,"meta");S(this,"_resultPool");if(this.scope=e,this.vm=t,this.blockCtx=r,this.env=o,this.computableCtx=n,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");this.meta=r.blockMeta(n),this.injectCtx()}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw Ue.cleanErrorContext(t),t}}runCallback(e,...t){try{return Be.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 Ue.cleanErrorContext(r),r}}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 zt(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return zt(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=Ro(n,t,r,o),c={};for(const[a,l]of Object.entries(i))c[a]=x.mapPObjectData(l,u=>this.wrapAccessor(u));return c}registerComputable(e,t){const r=`${e}_${ne.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",D.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",D.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))}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))}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:x.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:x.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 x.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=>x.mapPObjectData(t,r=>typeof r=="string"?this.getAccessor(r):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(x.mapPTableDef(e,t=>x.mapPObjectData(t,r=>typeof r=="string"?this.getAccessor(r):r)),this.computableCtx)}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=ne.randomUUID();return this.accessors.set(t,e),t}}exportSingleValue(e,t){const r=this.tryExportSingleValue(e,t);if(r===void 0)throw new Error(`Can't export value: ${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(on(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(){Be.Scope.withScope(e=>{const t=e.manage(this.vm.newObject()),r=this.blockCtx.args(this.computableCtx),o=this.blockCtx.uiState(this.computableCtx);this.vm.setProp(t,"args",e.manage(this.vm.newString(r))),o!==void 0&&this.vm.setProp(t,"uiState",e.manage(this.vm.newString(o))),this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(x.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e));const n=(i,c)=>{this.vm.newFunction(i,c).consume(a=>this.vm.setProp(t,i,a))};n("getAccessorHandleByName",i=>this.exportSingleValue(this.getAccessorHandleByName(this.vm.getString(i)),void 0)),n("resolveWithCommon",(i,c,...a)=>this.exportSingleValue(this.resolveWithCommon(this.vm.getString(i),this.importObjectViaJson(c),...a.map(l=>this.importObjectViaJson(l))),void 0)),n("getResourceType",i=>this.exportObjectViaJson(this.getResourceType(this.vm.getString(i)),void 0)),n("getInputsLocked",i=>this.exportSingleValue(this.getInputsLocked(this.vm.getString(i)),void 0)),n("getOutputsLocked",i=>this.exportSingleValue(this.getOutputsLocked(this.vm.getString(i)),void 0)),n("getIsReadyOrError",i=>this.exportSingleValue(this.getIsReadyOrError(this.vm.getString(i)),void 0)),n("getIsFinal",i=>this.exportSingleValue(this.getIsFinal(this.vm.getString(i)),void 0)),n("getError",i=>this.exportSingleValue(this.getError(this.vm.getString(i)),void 0)),n("listInputFields",i=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(i)),void 0)),n("listOutputFields",i=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(i)),void 0)),n("listDynamicFields",i=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(i)),void 0)),n("getKeyValueBase64",(i,c)=>this.exportSingleValue(this.getKeyValueBase64(this.vm.getString(i),this.vm.getString(c)),void 0)),n("getKeyValueAsString",(i,c)=>this.exportSingleValue(this.getKeyValueAsString(this.vm.getString(i),this.vm.getString(c)),void 0)),n("getDataBase64",i=>this.exportSingleValue(this.getDataBase64(this.vm.getString(i)),void 0)),n("getDataAsString",i=>this.exportSingleValue(this.getDataAsString(this.vm.getString(i)),void 0)),n("parsePObjectCollection",(i,c,a,...l)=>this.exportObjectUniversal(this.parsePObjectCollection(this.vm.getString(i),this.vm.dump(c),this.vm.getString(a),...l.map(this.vm.getString)),void 0)),n("getBlobContentAsBase64",i=>this.exportSingleValue(this.getBlobContentAsBase64(this.vm.getString(i)),void 0)),n("getBlobContentAsString",i=>this.exportSingleValue(this.getBlobContentAsString(this.vm.getString(i)),void 0)),n("getDownloadedBlobContentHandle",i=>this.exportSingleValue(this.getDownloadedBlobContentHandle(this.vm.getString(i)),void 0)),n("getOnDemandBlobContentHandle",i=>this.exportSingleValue(this.getOnDemandBlobContentHandle(this.vm.getString(i)),void 0)),n("getImportProgress",i=>this.exportSingleValue(this.getImportProgress(this.vm.getString(i)),void 0)),n("getLastLogs",(i,c)=>this.exportSingleValue(this.getLastLogs(this.vm.getString(i),this.vm.getNumber(c)),void 0)),n("getProgressLog",(i,c)=>this.exportSingleValue(this.getProgressLog(this.vm.getString(i),this.vm.getString(c)),void 0)),n("getLogHandle",i=>this.exportSingleValue(this.getLogHandle(this.vm.getString(i)),void 0)),n("getBlockLabel",i=>this.exportSingleValue(this.getBlockLabel(this.vm.getString(i)),void 0)),n("getDataFromResultPool",i=>this.exportObjectUniversal(this.getDataFromResultPool(),void 0)),n("getDataWithErrorsFromResultPool",i=>this.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),n("getSpecsFromResultPool",i=>this.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),n("calculateOptions",i=>this.exportObjectUniversal(this.calculateOptions(this.importObjectViaJson(i)),void 0)),n("getSpecFromResultPoolByRef",(i,c)=>this.exportObjectUniversal(this.getSpecFromResultPoolByRef(this.vm.getString(i),this.vm.getString(c)),void 0)),n("getDataFromResultPoolByRef",(i,c)=>this.exportObjectUniversal(this.getDataFromResultPoolByRef(this.vm.getString(i),this.vm.getString(c)),void 0)),n("createPFrame",i=>this.exportSingleValue(this.createPFrame(this.importObjectViaJson(i)),void 0)),n("createPTable",i=>this.exportSingleValue(this.createPTable(this.importObjectViaJson(i)),void 0)),n("getCurrentUnstableMarker",()=>this.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}function Ke(s,e){return Pe(s.traverse({field:J(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:f.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),o=x.extractConfig(r.config);return{bpId:t.resourceInfo.id.toString(),info:r,cfg:o}})}const Te=process.env.MI_LOG_OUTPUT_STATUS;function nn(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"),D.Computable.makeRaw(c=>{const a=new Be.Scope;c.addOnDestroy(()=>a.dispose());const l=a.manage(s.quickJs.newRuntime());l.setMemoryLimit(1024*640),l.setMaxStackSize(1024*320);const u=a.manage(l.newContext()),d=new Ue(a,u,e,s,c);d.evaluateBundle(r.content);const v=d.runCallback(t.handle);d.resetComputableCtx();let h=0;return Te&&Te!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:d.computablesToResolve,postprocessValue:async(g,{unstableMarker:F,stable:N})=>{for(const[H,O]of Object.entries(g))d.runCallback(H,O);const V=d.importObjectUniversal(v);return h++,Te&&(Te!=="unstable-only"||!N)&&console.log(N?`Stable output ${t.handle} calculated ${V!==void 0?"defined":"undefined"}; (#${h})`:`Unstable output ${t.handle}; marker = ${F}; ${V!==void 0?"defined":"undefined"} (#${h})`),V}}},n)}function an(s){return x.isConfigLambda(s)?s.isActive===!0:$o(s)}function Ce(s,e,t,r,o,n={}){if(x.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return nn(s,e,t,r,o,n)}else return sn(s.driverKit,e,t,n)}function cn(s,e,t){return D.Computable.make(r=>{var g,F,N,V,H,O,ce,de;const o=r.accessor(s).node(),n=E.notEmpty(o.getKeyValueAsJson(bt)),i=E.notEmpty(o.getKeyValueAsJson(Re)),c=E.notEmpty(o.getKeyValueAsJson(ke)),a=E.notEmpty(o.getKeyValueAsJson(ue)),l=E.notEmpty(o.getKeyValueAsJson(je)),u=new Map;for(const{id:L}of oe(a)){const X=o.traverse({field:J(L,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0});let le;const q=o.traverse({field:J(L,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(q!==void 0){const M=o.getField({field:J(L,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),G=o.getField({field:J(L,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});le={arguments:q.getDataAsJson(),stale:X.id!==q.id,outputError:M.error!==void 0||G.error!==void 0||((g=M.value)==null?void 0:g.getError())!==void 0||((F=G.value)==null?void 0:F.getError())!==void 0,outputsError:((N=M.error)==null?void 0:N.getDataAsString())??((H=(V=M.value)==null?void 0:V.getError())==null?void 0:H.getDataAsString()),exportsError:((O=G.error)==null?void 0:O.getDataAsString())??((de=(ce=G.value)==null?void 0:ce.getError())==null?void 0:de.getDataAsString()),finished:(M.value!==void 0&&M.value.getIsReadyOrError()||M.error!==void 0&&M.error.getIsReadyOrError())&&(G.value!==void 0&&G.value.getIsReadyOrError()||G.error!==void 0&&G.error.getIsReadyOrError())}}u.set(L,{currentArguments:X.getDataAsJson(),prod:le})}const d=De(a,L=>u.get(L).currentArguments),v=new Set(l.blocksInLimbo),h=[...oe(a)].map(({id:L,label:X,renderingMode:le})=>{var P,b,C,$,R;const q=E.notEmpty(u.get(L)),M=E.notEmpty(d.nodes.get(L));let G="NotCalculated";q.prod!==void 0&&(v.has(L)?G="Limbo":G=q.prod.finished?"Done":"Running");const Y=Ke(o,L),{sections:pe,title:y,inputsValid:p,sdkVersion:w}=Pe(Y,({bpId:I,cfg:B,info:j})=>{const ie=Rt(s,L);return{sections:Ce(t,ie,B.sections,B.code,I),title:Pe(B.title,ss=>Ce(t,ie,ss,B.code,I)),inputsValid:Ce(t,ie,B.inputsValid,B.code,I),sdkVersion:B.sdkVersion}})||{},m=Pe(Y,({info:I})=>t.blockUpdateWatcher.get(I.source));return{id:L,label:y??X,title:y??X,renderingMode:le,stale:((P=q.prod)==null?void 0:P.stale)!==!1||G==="Limbo",missingReference:M.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",L)],downstreams:[...d.traverseIdsExcludingRoots("downstream",L)],calculationStatus:G,outputErrors:((b=q.prod)==null?void 0:b.outputError)===!0,outputsError:(C=q.prod)==null?void 0:C.outputsError,exportsError:($=q.prod)==null?void 0:$.exportsError,sections:pe,inputsValid:p,currentBlockPack:(R=Y==null?void 0:Y.info)==null?void 0:R.source,updatedBlockPack:m,sdkVersion:w,navigationState:e.getState(L)}});return{meta:c,created:new Date(n),lastModified:new Date(i),authorMarker:o.getKeyValueAsJson(ut),blocks:h}},{postprocessValue:r=>{const o=new Set,n=new Set;return{...r,blocks:r.blocks.map(i=>{i.inputsValid||o.add(i.id),i.stale&&n.add(i.id);const c=i.stale||i.upstreams.findIndex(l=>n.has(l))!==-1,a=(c||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(l=>o.has(l))===-1;return{...i,canRun:a,stale:c}})}}}).withStableType()}function ln(s,e){const t=s.node();if(f.resourceTypesEqual(t.resourceType,Pt)){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(f.resourceTypesEqual(t.resourceType,Ct)){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 un(s,e){if(s!==void 0)return D.Computable.make(t=>ln(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 dn(s,e,t){return D.Computable.make(r=>{var c;const o=r.accessor(s).node(),n=Ke(o,e),i=(c=o.traverse({field:J(e,"blockPack"),assertFieldType:"Dynamic"},{field:f.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:Br,assertFieldType:"Input"}))==null?void 0:c.persist();return{path:un(i,t),sdkVersion:n==null?void 0:n.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function Hr(s,e,t){if(t===void 0)return D.Computable.make(i=>Hr(s,e,i),{key:`inputs#${f.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),o=Rt(s,e),n=o.uiState(t);return{author:r.getKeyValueAsJson(lt(e)),args:JSON.parse(o.args(t)),ui:n!==void 0?JSON.parse(n):void 0}}function pn(s,e,t){return D.Computable.make(r=>{const o=r.accessor(s).node(),n=Ur(s,e);return Pe(Ke(o,e),({cfg:i,bpId:c})=>{const a={};for(const[l,u]of Object.entries(i.outputs)){const d=Ce(t,n,u,i.code,c);a[l]=D.Computable.wrapError(d)}return a})},{key:"outputs#"+f.resourceIdToString(s.rid)+"#"+e}).withStableType()}function hn(s,e){return D.Computable.make(t=>{const r=t.accessor(s).node(),o=E.notEmpty(r.getKeyValueAsJson(ue)),n=[];for(const{id:i,renderingMode:c}of oe(o)){const a=Ke(r,i);if(a===void 0)continue;const l=Object.entries(a.cfg.outputs).map(([,d])=>d).filter(d=>an(d)).map(d=>d);if(l.length===0)continue;const u=Ur(r.persist(),i);for(const d of l)n.push(D.Computable.wrapError(Ce(e,u,d,a.cfg.code,a.bpId)))}return n})}class fn{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 D.ChangeSource});return}r.state={...t},r.change.markChanged()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...x.DefaultNavigationState},change:new D.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return D.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())}}class He{constructor(e,t,r){S(this,"rid");S(this,"overview");S(this,"navigationStates",new fn);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=cn(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=hn(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await tt(this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await Sr.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(f.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!f.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,o=void 0,n=ne.randomUUID()){const i=await this.env.bpPreparer.prepare(t),c=await this.env.bpPreparer.getBlockConfigContainer(t),a=x.extractConfig(c);return await se(this.env.pl,this.rid,o,l=>l.addBlock({id:n,label:e,renderingMode:a.renderingMode},{args:JSON.stringify(a.initialArgs),uiState:JSON.stringify(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=await this.env.bpPreparer.getBlockConfigContainer(t);await se(this.env.pl,this.rid,o,c=>c.migrateBlockPack(e,n,r?JSON.stringify(i.initialArgs):void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await se(this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await se(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 tt(this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await tt(this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await se(this.env.pl,this.rid,r,o=>o.setArgs([{blockId:e,args:JSON.stringify(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await se(this.env.pl,this.rid,r,o=>o.setUiState(e,t===void 0?void 0:JSON.stringify(t))),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,o){await se(this.env.pl,this.rid,o,n=>{n.setArgs([{blockId:e,args:JSON.stringify(t)}]),n.setUiState(e,JSON.stringify(r))}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async r=>{const o=f.ensureResourceIdNotNull((await r.getField(f.field(this.rid,J(e,"blockPack")))).value),n=f.ensureResourceIdNotNull((await r.getField(f.field(o,f.Pl.HolderRefField))).value),i=await r.getResourceData(n,!1),c=JSON.parse(Buffer.from(E.notEmpty(i.data)).toString("utf-8"));await se(r,this.rid,t,a=>{a.setArgs([{blockId:e,args:JSON.stringify(c.config.initialArgs)}]),a.setUiState(e,void 0)}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===void 0){const r=pn(this.projectTree.entry(),e,this.env),n={fullState:D.Computable.make(i=>({argsAndUiState:Hr(this.projectTree.entry(),e,i),outputs:r,navigationState:this.navigationStates.getState(e)}),{postprocessValue:i=>({...i.argsAndUiState,outputs:i.outputs,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=dn(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){const r=await Ge.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:gn},e.logger);return new He(e,t,r)}}function gn(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}}const kt={logger:new E.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:100*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}};function Ot(s){return{blobDownloadPath:W.join(s,"download")}}const qr={...kt,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function Wr(s){return{...Ot(s),frontendDownloadPath:W.join(s,"frontend")}}function mn(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var gt={exports:{}};const vn="2.0.0",zr=256,yn=Number.MAX_SAFE_INTEGER||9007199254740991,wn=16,bn=zr-6,Sn=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var qe={MAX_LENGTH:zr,MAX_SAFE_COMPONENT_LENGTH:wn,MAX_SAFE_BUILD_LENGTH:bn,MAX_SAFE_INTEGER:yn,RELEASE_TYPES:Sn,SEMVER_SPEC_VERSION:vn,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2};const Pn=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...s)=>console.error("SEMVER",...s):()=>{};var We=Pn;(function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:o}=qe,n=We;e=s.exports={};const i=e.re=[],c=e.safeRe=[],a=e.src=[],l=e.t={};let u=0;const d="[a-zA-Z0-9-]",v=[["\\s",1],["\\d",o],[d,r]],h=F=>{for(const[N,V]of v)F=F.split(`${N}*`).join(`${N}{0,${V}}`).split(`${N}+`).join(`${N}{1,${V}}`);return F},g=(F,N,V)=>{const H=h(N),O=u++;n(F,O,N),l[F]=O,a[O]=N,i[O]=new RegExp(N,V?"g":void 0),c[O]=new RegExp(H,V?"g":void 0)};g("NUMERICIDENTIFIER","0|[1-9]\\d*"),g("NUMERICIDENTIFIERLOOSE","\\d+"),g("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${d}*`),g("MAINVERSION",`(${a[l.NUMERICIDENTIFIER]})\\.(${a[l.NUMERICIDENTIFIER]})\\.(${a[l.NUMERICIDENTIFIER]})`),g("MAINVERSIONLOOSE",`(${a[l.NUMERICIDENTIFIERLOOSE]})\\.(${a[l.NUMERICIDENTIFIERLOOSE]})\\.(${a[l.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASEIDENTIFIER",`(?:${a[l.NUMERICIDENTIFIER]}|${a[l.NONNUMERICIDENTIFIER]})`),g("PRERELEASEIDENTIFIERLOOSE",`(?:${a[l.NUMERICIDENTIFIERLOOSE]}|${a[l.NONNUMERICIDENTIFIER]})`),g("PRERELEASE",`(?:-(${a[l.PRERELEASEIDENTIFIER]}(?:\\.${a[l.PRERELEASEIDENTIFIER]})*))`),g("PRERELEASELOOSE",`(?:-?(${a[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${a[l.PRERELEASEIDENTIFIERLOOSE]})*))`),g("BUILDIDENTIFIER",`${d}+`),g("BUILD",`(?:\\+(${a[l.BUILDIDENTIFIER]}(?:\\.${a[l.BUILDIDENTIFIER]})*))`),g("FULLPLAIN",`v?${a[l.MAINVERSION]}${a[l.PRERELEASE]}?${a[l.BUILD]}?`),g("FULL",`^${a[l.FULLPLAIN]}$`),g("LOOSEPLAIN",`[v=\\s]*${a[l.MAINVERSIONLOOSE]}${a[l.PRERELEASELOOSE]}?${a[l.BUILD]}?`),g("LOOSE",`^${a[l.LOOSEPLAIN]}$`),g("GTLT","((?:<|>)?=?)"),g("XRANGEIDENTIFIERLOOSE",`${a[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),g("XRANGEIDENTIFIER",`${a[l.NUMERICIDENTIFIER]}|x|X|\\*`),g("XRANGEPLAIN",`[v=\\s]*(${a[l.XRANGEIDENTIFIER]})(?:\\.(${a[l.XRANGEIDENTIFIER]})(?:\\.(${a[l.XRANGEIDENTIFIER]})(?:${a[l.PRERELEASE]})?${a[l.BUILD]}?)?)?`),g("XRANGEPLAINLOOSE",`[v=\\s]*(${a[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[l.XRANGEIDENTIFIERLOOSE]})(?:${a[l.PRERELEASELOOSE]})?${a[l.BUILD]}?)?)?`),g("XRANGE",`^${a[l.GTLT]}\\s*${a[l.XRANGEPLAIN]}$`),g("XRANGELOOSE",`^${a[l.GTLT]}\\s*${a[l.XRANGEPLAINLOOSE]}$`),g("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),g("COERCE",`${a[l.COERCEPLAIN]}(?:$|[^\\d])`),g("COERCEFULL",a[l.COERCEPLAIN]+`(?:${a[l.PRERELEASE]})?(?:${a[l.BUILD]})?(?:$|[^\\d])`),g("COERCERTL",a[l.COERCE],!0),g("COERCERTLFULL",a[l.COERCEFULL],!0),g("LONETILDE","(?:~>?)"),g("TILDETRIM",`(\\s*)${a[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",g("TILDE",`^${a[l.LONETILDE]}${a[l.XRANGEPLAIN]}$`),g("TILDELOOSE",`^${a[l.LONETILDE]}${a[l.XRANGEPLAINLOOSE]}$`),g("LONECARET","(?:\\^)"),g("CARETTRIM",`(\\s*)${a[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",g("CARET",`^${a[l.LONECARET]}${a[l.XRANGEPLAIN]}$`),g("CARETLOOSE",`^${a[l.LONECARET]}${a[l.XRANGEPLAINLOOSE]}$`),g("COMPARATORLOOSE",`^${a[l.GTLT]}\\s*(${a[l.LOOSEPLAIN]})$|^$`),g("COMPARATOR",`^${a[l.GTLT]}\\s*(${a[l.FULLPLAIN]})$|^$`),g("COMPARATORTRIM",`(\\s*)${a[l.GTLT]}\\s*(${a[l.LOOSEPLAIN]}|${a[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",g("HYPHENRANGE",`^\\s*(${a[l.XRANGEPLAIN]})\\s+-\\s+(${a[l.XRANGEPLAIN]})\\s*$`),g("HYPHENRANGELOOSE",`^\\s*(${a[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${a[l.XRANGEPLAINLOOSE]})\\s*$`),g("STAR","(<|>)?=?\\s*\\*"),g("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),g("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(gt,gt.exports);var Oe=gt.exports;const Cn=Object.freeze({loose:!0}),En=Object.freeze({}),Rn=s=>s?typeof s!="object"?Cn:s:En;var $t=Rn;const Xt=/^[0-9]+$/,Xr=(s,e)=>{const t=Xt.test(s),r=Xt.test(e);return t&&r&&(s=+s,e=+e),s===e?0:t&&!r?-1:r&&!t?1:s<e?-1:1},kn=(s,e)=>Xr(e,s);var Yr={compareIdentifiers:Xr,rcompareIdentifiers:kn};const Ie=We,{MAX_LENGTH:Yt,MAX_SAFE_INTEGER:Fe}=qe,{safeRe:Zt,t:Qt}=Oe,On=$t,{compareIdentifiers:he}=Yr;let $n=class re{constructor(e,t){if(t=On(t),e instanceof re){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>Yt)throw new TypeError(`version is longer than ${Yt} characters`);Ie("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const r=e.trim().match(t.loose?Zt[Qt.LOOSE]:Zt[Qt.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>Fe||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Fe||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Fe||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<Fe)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(Ie("SemVer.compare",this.version,this.options,e),!(e instanceof re)){if(typeof e=="string"&&e===this.version)return 0;e=new re(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof re||(e=new re(e,this.options)),he(this.major,e.major)||he(this.minor,e.minor)||he(this.patch,e.patch)}comparePre(e){if(e instanceof re||(e=new re(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(Ie("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 he(r,o)}while(++t)}compareBuild(e){e instanceof re||(e=new re(e,this.options));let t=0;do{const r=this.build[t],o=e.build[t];if(Ie("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 he(r,o)}while(++t)}inc(e,t,r){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"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(!t&&r===!1)throw new Error("invalid increment argument: identifier is empty");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]),he(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=n):this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};var K=$n;const er=K,Tn=(s,e,t=!1)=>{if(s instanceof er)return s;try{return new er(s,e)}catch(r){if(!t)return null;throw r}};var ve=Tn;const In=ve,Fn=(s,e)=>{const t=In(s,e);return t?t.version:null};var Nn=Fn;const An=ve,Ln=(s,e)=>{const t=An(s.trim().replace(/^[=v]+/,""),e);return t?t.version:null};var Dn=Ln;const tr=K,Bn=(s,e,t,r,o)=>{typeof t=="string"&&(o=r,r=t,t=void 0);try{return new tr(s instanceof tr?s.version:s,t).inc(e,r,o).version}catch{return null}};var jn=Bn;const rr=ve,xn=(s,e)=>{const t=rr(s,null,!0),r=rr(e,null,!0),o=t.compare(r);if(o===0)return null;const n=o>0,i=n?t:r,c=n?r:t,a=!!i.prerelease.length;if(!!c.prerelease.length&&!a)return!c.patch&&!c.minor?"major":i.patch?"patch":i.minor?"minor":"major";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 Vn=xn;const Un=K,Gn=(s,e)=>new Un(s,e).major;var Jn=Gn;const Mn=K,_n=(s,e)=>new Mn(s,e).minor;var Kn=_n;const Hn=K,qn=(s,e)=>new Hn(s,e).patch;var Wn=qn;const zn=ve,Xn=(s,e)=>{const t=zn(s,e);return t&&t.prerelease.length?t.prerelease:null};var Yn=Xn;const sr=K,Zn=(s,e,t)=>new sr(s,t).compare(new sr(e,t));var Q=Zn;const Qn=Q,ei=(s,e,t)=>Qn(e,s,t);var ti=ei;const ri=Q,si=(s,e)=>ri(s,e,!0);var oi=si;const or=K,ni=(s,e,t)=>{const r=new or(s,t),o=new or(e,t);return r.compare(o)||r.compareBuild(o)};var Tt=ni;const ii=Tt,ai=(s,e)=>s.sort((t,r)=>ii(t,r,e));var ci=ai;const li=Tt,ui=(s,e)=>s.sort((t,r)=>li(r,t,e));var di=ui;const pi=Q,hi=(s,e,t)=>pi(s,e,t)>0;var ze=hi;const fi=Q,gi=(s,e,t)=>fi(s,e,t)<0;var It=gi;const mi=Q,vi=(s,e,t)=>mi(s,e,t)===0;var Zr=vi;const yi=Q,wi=(s,e,t)=>yi(s,e,t)!==0;var Qr=wi;const bi=Q,Si=(s,e,t)=>bi(s,e,t)>=0;var Ft=Si;const Pi=Q,Ci=(s,e,t)=>Pi(s,e,t)<=0;var Nt=Ci;const Ei=Zr,Ri=Qr,ki=ze,Oi=Ft,$i=It,Ti=Nt,Ii=(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 Ei(s,t,r);case"!=":return Ri(s,t,r);case">":return ki(s,t,r);case">=":return Oi(s,t,r);case"<":return $i(s,t,r);case"<=":return Ti(s,t,r);default:throw new TypeError(`Invalid operator: ${e}`)}};var es=Ii;const Fi=K,Ni=ve,{safeRe:Ne,t:Ae}=Oe,Ai=(s,e)=>{if(s instanceof Fi)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?Ne[Ae.COERCEFULL]:Ne[Ae.COERCE]);else{const a=e.includePrerelease?Ne[Ae.COERCERTLFULL]:Ne[Ae.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 Ni(`${r}.${o}.${n}${i}${c}`,e)};var Li=Ai;class Di{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 Bi=Di,rt,nr;function ee(){if(nr)return rt;nr=1;const s=/\s+/g;class e{constructor(p,w){if(w=o(w),p instanceof e)return p.loose===!!w.loose&&p.includePrerelease===!!w.includePrerelease?p:new e(p.raw,w);if(p instanceof n)return this.raw=p.value,this.set=[[p]],this.formatted=void 0,this;if(this.options=w,this.loose=!!w.loose,this.includePrerelease=!!w.includePrerelease,this.raw=p.trim().replace(s," "),this.set=this.raw.split("||").map(m=>this.parseRange(m.trim())).filter(m=>m.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const m=this.set[0];if(this.set=this.set.filter(P=>!F(P[0])),this.set.length===0)this.set=[m];else if(this.set.length>1){for(const P of this.set)if(P.length===1&&N(P[0])){this.set=[P];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let p=0;p<this.set.length;p++){p>0&&(this.formatted+="||");const w=this.set[p];for(let m=0;m<w.length;m++)m>0&&(this.formatted+=" "),this.formatted+=w[m].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(p){const m=((this.options.includePrerelease&&h)|(this.options.loose&&g))+":"+p,P=r.get(m);if(P)return P;const b=this.options.loose,C=b?a[l.HYPHENRANGELOOSE]:a[l.HYPHENRANGE];p=p.replace(C,Y(this.options.includePrerelease)),i("hyphen replace",p),p=p.replace(a[l.COMPARATORTRIM],u),i("comparator trim",p),p=p.replace(a[l.TILDETRIM],d),i("tilde trim",p),p=p.replace(a[l.CARETTRIM],v),i("caret trim",p);let $=p.split(" ").map(j=>H(j,this.options)).join(" ").split(/\s+/).map(j=>G(j,this.options));b&&($=$.filter(j=>(i("loose invalid filter",j,this.options),!!j.match(a[l.COMPARATORLOOSE])))),i("range list",$);const R=new Map,I=$.map(j=>new n(j,this.options));for(const j of I){if(F(j))return[j];R.set(j.value,j)}R.size>1&&R.has("")&&R.delete("");const B=[...R.values()];return r.set(m,B),B}intersects(p,w){if(!(p instanceof e))throw new TypeError("a Range is required");return this.set.some(m=>V(m,w)&&p.set.some(P=>V(P,w)&&m.every(b=>P.every(C=>b.intersects(C,w)))))}test(p){if(!p)return!1;if(typeof p=="string")try{p=new c(p,this.options)}catch{return!1}for(let w=0;w<this.set.length;w++)if(pe(this.set[w],p,this.options))return!0;return!1}}rt=e;const t=Bi,r=new t,o=$t,n=Xe(),i=We,c=K,{safeRe:a,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:v}=Oe,{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:g}=qe,F=y=>y.value==="<0.0.0-0",N=y=>y.value==="",V=(y,p)=>{let w=!0;const m=y.slice();let P=m.pop();for(;w&&m.length;)w=m.every(b=>P.intersects(b,p)),P=m.pop();return w},H=(y,p)=>(i("comp",y,p),y=L(y,p),i("caret",y),y=ce(y,p),i("tildes",y),y=le(y,p),i("xrange",y),y=M(y,p),i("stars",y),y),O=y=>!y||y.toLowerCase()==="x"||y==="*",ce=(y,p)=>y.trim().split(/\s+/).map(w=>de(w,p)).join(" "),de=(y,p)=>{const w=p.loose?a[l.TILDELOOSE]:a[l.TILDE];return y.replace(w,(m,P,b,C,$)=>{i("tilde",y,m,P,b,C,$);let R;return O(P)?R="":O(b)?R=`>=${P}.0.0 <${+P+1}.0.0-0`:O(C)?R=`>=${P}.${b}.0 <${P}.${+b+1}.0-0`:$?(i("replaceTilde pr",$),R=`>=${P}.${b}.${C}-${$} <${P}.${+b+1}.0-0`):R=`>=${P}.${b}.${C} <${P}.${+b+1}.0-0`,i("tilde return",R),R})},L=(y,p)=>y.trim().split(/\s+/).map(w=>X(w,p)).join(" "),X=(y,p)=>{i("caret",y,p);const w=p.loose?a[l.CARETLOOSE]:a[l.CARET],m=p.includePrerelease?"-0":"";return y.replace(w,(P,b,C,$,R)=>{i("caret",y,P,b,C,$,R);let I;return O(b)?I="":O(C)?I=`>=${b}.0.0${m} <${+b+1}.0.0-0`:O($)?b==="0"?I=`>=${b}.${C}.0${m} <${b}.${+C+1}.0-0`:I=`>=${b}.${C}.0${m} <${+b+1}.0.0-0`:R?(i("replaceCaret pr",R),b==="0"?C==="0"?I=`>=${b}.${C}.${$}-${R} <${b}.${C}.${+$+1}-0`:I=`>=${b}.${C}.${$}-${R} <${b}.${+C+1}.0-0`:I=`>=${b}.${C}.${$}-${R} <${+b+1}.0.0-0`):(i("no pr"),b==="0"?C==="0"?I=`>=${b}.${C}.${$}${m} <${b}.${C}.${+$+1}-0`:I=`>=${b}.${C}.${$}${m} <${b}.${+C+1}.0-0`:I=`>=${b}.${C}.${$} <${+b+1}.0.0-0`),i("caret return",I),I})},le=(y,p)=>(i("replaceXRanges",y,p),y.split(/\s+/).map(w=>q(w,p)).join(" ")),q=(y,p)=>{y=y.trim();const w=p.loose?a[l.XRANGELOOSE]:a[l.XRANGE];return y.replace(w,(m,P,b,C,$,R)=>{i("xRange",y,m,P,b,C,$,R);const I=O(b),B=I||O(C),j=B||O($),ie=j;return P==="="&&ie&&(P=""),R=p.includePrerelease?"-0":"",I?P===">"||P==="<"?m="<0.0.0-0":m="*":P&&ie?(B&&(C=0),$=0,P===">"?(P=">=",B?(b=+b+1,C=0,$=0):(C=+C+1,$=0)):P==="<="&&(P="<",B?b=+b+1:C=+C+1),P==="<"&&(R="-0"),m=`${P+b}.${C}.${$}${R}`):B?m=`>=${b}.0.0${R} <${+b+1}.0.0-0`:j&&(m=`>=${b}.${C}.0${R} <${b}.${+C+1}.0-0`),i("xRange return",m),m})},M=(y,p)=>(i("replaceStars",y,p),y.trim().replace(a[l.STAR],"")),G=(y,p)=>(i("replaceGTE0",y,p),y.trim().replace(a[p.includePrerelease?l.GTE0PRE:l.GTE0],"")),Y=y=>(p,w,m,P,b,C,$,R,I,B,j,ie)=>(O(m)?w="":O(P)?w=`>=${m}.0.0${y?"-0":""}`:O(b)?w=`>=${m}.${P}.0${y?"-0":""}`:C?w=`>=${w}`:w=`>=${w}${y?"-0":""}`,O(I)?R="":O(B)?R=`<${+I+1}.0.0-0`:O(j)?R=`<${I}.${+B+1}.0-0`:ie?R=`<=${I}.${B}.${j}-${ie}`:y?R=`<${I}.${B}.${+j+1}-0`:R=`<=${R}`,`${w} ${R}`.trim()),pe=(y,p,w)=>{for(let m=0;m<y.length;m++)if(!y[m].test(p))return!1;if(p.prerelease.length&&!w.includePrerelease){for(let m=0;m<y.length;m++)if(i(y[m].semver),y[m].semver!==n.ANY&&y[m].semver.prerelease.length>0){const P=y[m].semver;if(P.major===p.major&&P.minor===p.minor&&P.patch===p.patch)return!0}return!1}return!0};return rt}var st,ir;function Xe(){if(ir)return st;ir=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],v=u.match(d);if(!v)throw new TypeError(`Invalid comparator: ${u}`);this.operator=v[1]!==void 0?v[1]:"",this.operator==="="&&(this.operator=""),v[2]?this.semver=new c(v[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(">")))}}st=e;const t=$t,{safeRe:r,t:o}=Oe,n=es,i=We,c=K,a=ee();return st}const ji=ee(),xi=(s,e,t)=>{try{e=new ji(e,t)}catch{return!1}return e.test(s)};var Ye=xi;const Vi=ee(),Ui=(s,e)=>new Vi(s,e).set.map(t=>t.map(r=>r.value).join(" ").trim().split(" "));var Gi=Ui;const Ji=K,Mi=ee(),_i=(s,e,t)=>{let r=null,o=null,n=null;try{n=new Mi(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===-1)&&(r=i,o=new Ji(r,t))}),r};var Ki=_i;const Hi=K,qi=ee(),Wi=(s,e,t)=>{let r=null,o=null,n=null;try{n=new qi(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===1)&&(r=i,o=new Hi(r,t))}),r};var zi=Wi;const ot=K,Xi=ee(),ar=ze,Yi=(s,e)=>{s=new Xi(s,e);let t=new ot("0.0.0");if(s.test(t)||(t=new ot("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 ot(i.semver.version);switch(i.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!n||ar(c,n))&&(n=c);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),n&&(!t||ar(t,n))&&(t=n)}return t&&s.test(t)?t:null};var Zi=Yi;const Qi=ee(),ea=(s,e)=>{try{return new Qi(s,e).range||"*"}catch{return null}};var ta=ea;const ra=K,ts=Xe(),{ANY:sa}=ts,oa=ee(),na=Ye,cr=ze,lr=It,ia=Nt,aa=Ft,ca=(s,e,t,r)=>{s=new ra(s,r),e=new oa(e,r);let o,n,i,c,a;switch(t){case">":o=cr,n=ia,i=lr,c=">",a=">=";break;case"<":o=lr,n=aa,i=cr,c="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(na(s,e,r))return!1;for(let l=0;l<e.set.length;++l){const u=e.set[l];let d=null,v=null;if(u.forEach(h=>{h.semver===sa&&(h=new ts(">=0.0.0")),d=d||h,v=v||h,o(h.semver,d.semver,r)?d=h:i(h.semver,v.semver,r)&&(v=h)}),d.operator===c||d.operator===a||(!v.operator||v.operator===c)&&n(s,v.semver))return!1;if(v.operator===a&&i(s,v.semver))return!1}return!0};var At=ca;const la=At,ua=(s,e,t)=>la(s,e,">",t);var da=ua;const pa=At,ha=(s,e,t)=>pa(s,e,"<",t);var fa=ha;const ur=ee(),ga=(s,e,t)=>(s=new ur(s,t),e=new ur(e,t),s.intersects(e,t));var ma=ga;const va=Ye,ya=Q;var wa=(s,e,t)=>{const r=[];let o=null,n=null;const i=s.sort((u,d)=>ya(u,d,t));for(const u of i)va(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 dr=ee(),Lt=Xe(),{ANY:nt}=Lt,ye=Ye,Dt=Q,ba=(s,e,t={})=>{if(s===e)return!0;s=new dr(s,t),e=new dr(e,t);let r=!1;e:for(const o of s.set){for(const n of e.set){const i=Pa(o,n,t);if(r=r||i!==null,i)continue e}if(r)return!1}return!0},Sa=[new Lt(">=0.0.0-0")],pr=[new Lt(">=0.0.0")],Pa=(s,e,t)=>{if(s===e)return!0;if(s.length===1&&s[0].semver===nt){if(e.length===1&&e[0].semver===nt)return!0;t.includePrerelease?s=Sa:s=pr}if(e.length===1&&e[0].semver===nt){if(t.includePrerelease)return!0;e=pr}const r=new Set;let o,n;for(const h of s)h.operator===">"||h.operator===">="?o=hr(o,h,t):h.operator==="<"||h.operator==="<="?n=fr(n,h,t):r.add(h.semver);if(r.size>1)return null;let i;if(o&&n){if(i=Dt(o.semver,n.semver,t),i>0)return null;if(i===0&&(o.operator!==">="||n.operator!=="<="))return null}for(const h of r){if(o&&!ye(h,String(o),t)||n&&!ye(h,String(n),t))return null;for(const g of e)if(!ye(h,String(g),t))return!1;return!0}let c,a,l,u,d=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1,v=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 h of e){if(u=u||h.operator===">"||h.operator===">=",l=l||h.operator==="<"||h.operator==="<=",o){if(v&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===v.major&&h.semver.minor===v.minor&&h.semver.patch===v.patch&&(v=!1),h.operator===">"||h.operator===">="){if(c=hr(o,h,t),c===h&&c!==o)return!1}else if(o.operator===">="&&!ye(o.semver,String(h),t))return!1}if(n){if(d&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===d.major&&h.semver.minor===d.minor&&h.semver.patch===d.patch&&(d=!1),h.operator==="<"||h.operator==="<="){if(a=fr(n,h,t),a===h&&a!==n)return!1}else if(n.operator==="<="&&!ye(n.semver,String(h),t))return!1}if(!h.operator&&(n||o)&&i!==0)return!1}return!(o&&l&&!n&&i!==0||n&&u&&!o&&i!==0||v||d)},hr=(s,e,t)=>{if(!s)return e;const r=Dt(s.semver,e.semver,t);return r>0?s:r<0||e.operator===">"&&s.operator===">="?e:s},fr=(s,e,t)=>{if(!s)return e;const r=Dt(s.semver,e.semver,t);return r<0?s:r>0||e.operator==="<"&&s.operator==="<="?e:s};var Ca=ba;const it=Oe,gr=qe,Ea=K,mr=Yr,Ra=ve,ka=Nn,Oa=Dn,$a=jn,Ta=Vn,Ia=Jn,Fa=Kn,Na=Wn,Aa=Yn,La=Q,Da=ti,Ba=oi,ja=Tt,xa=ci,Va=di,Ua=ze,Ga=It,Ja=Zr,Ma=Qr,_a=Ft,Ka=Nt,Ha=es,qa=Li,Wa=Xe(),za=ee(),Xa=Ye,Ya=Gi,Za=Ki,Qa=zi,ec=Zi,tc=ta,rc=At,sc=da,oc=fa,nc=ma,ic=wa,ac=Ca;var cc={parse:Ra,valid:ka,clean:Oa,inc:$a,diff:Ta,major:Ia,minor:Fa,patch:Na,prerelease:Aa,compare:La,rcompare:Da,compareLoose:Ba,compareBuild:ja,sort:xa,rsort:Va,gt:Ua,lt:Ga,eq:Ja,neq:Ma,gte:_a,lte:Ka,cmp:Ha,coerce:qa,Comparator:Wa,Range:za,satisfies:Xa,toComparators:Ya,maxSatisfying:Za,minSatisfying:Qa,minVersion:ec,validRange:tc,outside:rc,gtr:sc,ltr:oc,intersects:nc,simplifyRange:ic,subset:ac,SemVer:Ea,re:it.re,src:it.src,tokens:it.t,SEMVER_SPEC_VERSION:gr.SEMVER_SPEC_VERSION,RELEASE_TYPES:gr.RELEASE_TYPES,compareIdentifiers:mr.compareIdentifiers,rcompareIdentifiers:mr.rcompareIdentifiers};const lc=mn(cc),uc={minDelay:1500},dc="__no_updates__";class pc extends D.PollComputablePool{constructor(t,r,o={}){super({...o,...uc},r);S(this,"http");S(this,"preferredUpdateChannel");this.registryProvider=t,this.http=o.http,this.preferredUpdateChannel=o.preferredUpdateChannel}getKey(t){switch(t.type){case"dev-v1":return`dev_1_${t.folder}_${t.mtime}`;case"dev-v2":return`dev_2_${t.folder}_${t.mtime}`;case"from-registry-v2":return`from_registry_v2_${t.registryUrl}_${t.id.organization}_${t.id.name}_${t.id.version}`;default:return dc}}async readValue(t){try{switch(t.type){case"dev-v1":try{const r=await wt(t.folder);return r===t.mtime?void 0:{...t,mtime:r}}catch(r){this.logger.warn(r);return}case"dev-v2":try{const r=await _.tryLoadPackDescription(t.folder,this.logger);if(r===void 0)return;const o=await Je(r);return o===t.mtime?void 0:{...t,mtime:o}}catch(r){this.logger.warn(r);return}case"from-registry-v2":try{const r=this.registryProvider.getRegistry(t.registryUrl);let o;if(t.channel===void 0){const n=await r.getLatestOverview(t.id,U.StableChannel);if(n)o=n.spec;else{const i=await r.getLatestOverview(t.id,U.AnyChannel);if(i===void 0){this.logger.error(`No "any" channel record for ${U.blockPackIdToString(t.id)}`);return}o={...i.spec,channel:U.StableChannel}}}else{const n=this.preferredUpdateChannel??t.channel,i=await r.getLatestOverview(t.id,n);if(i)o=i.spec;else{this.logger.error(`Can't find update for ${U.blockPackIdToString(t.id)} in channel "${n}"`);return}}if(o.type!=="from-registry-v2")throw new Error(`Unexpected spec type ${o}.`);return lc.compare(o.id.version,t.id.version)<=0?void 0:((async()=>{try{await r.getComponents(o.id)}catch(n){this.logger.warn(n)}})(),o)}catch(r){this.logger.warn(r);return}default:return}}catch(r){this.logger.warn(r);return}}resultsEqual(t,r){if(t===void 0&&r===void 0)return!0;if(t===void 0||r===void 0||t.type!==r.type)return!1;switch(t.type){case"from-registry-v1":return r.type!=="from-registry-v1"?!1:t.registryUrl===r.registryUrl&&U.blockPackIdEquals(t.id,r.id);case"from-registry-v2":return r.type!=="from-registry-v2"?!1:t.registryUrl===r.registryUrl&&U.blockPackIdEquals(t.id,r.id);case"dev-v1":return r.type!=="dev-v1"?!1:t.folder===r.folder&&t.mtime===r.mtime;case"dev-v2":return r.type!=="dev-v2"?!1:t.folder===r.folder&&t.mtime===r.mtime;default:E.assertNever(t)}}}class vr{constructor(){S(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");if(t.refCount===0){this.resources.delete(e);const r=t.resource;r!=null&&typeof r[Symbol.dispose]=="function"&&r[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 we;function Se(){return we||(we={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0},process.env.MI_LOG_TREE_STAT&&(we.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),we)}function yr(s){return String(s.id)}const hc=["Int","Long","Float","Double","String","Bytes"];function at(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 s}const Le=(s,e)=>typeof e=="bigint"?e.toString():e;class fc{constructor(e,t,r){S(this,"pFrame",new ds.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.blobContentCache=t,this.columns=r,this.pFrame.setDataSource(this);for(const o of r){for(const i of fo(o.data))this.blobIdToResource.set(yr(i),i);const n=go(o.data,yr);try{this.pFrame.addColumnSpec(o.id,o.spec),this.pFrame.setColumnData(o.id,n)}catch(i){throw new Error(`Adding column ${o.id} to PFrame failed: ${i}; Spec: ${o.spec}, DataInfo: ${n}.`)}}}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 gc{constructor(e,t){S(this,"pFrames");S(this,"pTables");S(this,"blobContentCache");S(this,"concurrencyLimiter");this.blobDriver=e,this.logger=t;const r=new ps.LRUCache({maxSize:1e9,fetchMethod:async n=>await Pr.readFile(n),sizeCalculation:n=>n.length}),o=new E.ConcurrencyLimitingExecutor(1);this.blobContentCache=r,this.concurrencyLimiter=o,this.pFrames=new class extends vr{constructor(n){super(),this.blobDriver=n}createNewResource(n){return Se().logPFrameRequests&&t.info(`Create PFrame (${this.calculateParamsKey(n)}): ${JSON.stringify(n,Le)}`),new fc(this.blobDriver,r,n)}calculateParamsKey(n){return vc(n)}}(this.blobDriver),this.pTables=new class extends vr{constructor(n){super(),this.pFrames=n}async createNewResource(n){const i=this.pFrames.getByKey(n.pFrameHandle),c=await o.run(async()=>(Se().logPFrameRequests&&t.info(`Create PTable (${this.calculateParamsKey(n)}): ${JSON.stringify(n,Le)}`),await i.pFrame.createTable({src:Ee(n.def.src),filters:at(n.def.filters)})));return n.def.sorting.length!==0?c.sort(n.def.sorting):c}calculateParamsKey(n){return mc(n)}}(this.pFrames)}createPFrame(e,t){const r=e.filter(n=>hc.find(i=>i===n.spec.valueType)).map(n=>x.mapPObjectData(n,i=>Ge.isPlTreeNodeAccessor(i)?So(i):Po(n.spec,i))),o=this.pFrames.acquire(r);return t.addOnDestroy(o.unref),o.key}createPTable(e,t){const r=this.createPFrame(x.extractAllColumns(e.src),t),o=x.mapPTableDef(e,i=>i.id),n=this.pTables.acquire({def:o,pFrameHandle:r});return t.addOnDestroy(n.unref),n.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:t.compatibleWith,qualifications:[]}]:[]};return{hits:(await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.findColumns(r))).hits.map(o=>o.hit)}}async getColumnSpec(e,t){return await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.getColumnSpec(t))}async listColumns(e){return await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.listColumns())}async calculateTableData(e,t){let r=await this.concurrencyLimiter.run(async()=>(Se().logPFrameRequests&&this.logger.info(`calculateTableData, handle = ${e}, request = ${JSON.stringify(t,Le)}`),await this.pFrames.getByKey(e).pFrame.createTable({src:Ee(t.src),filters:at(t.filters)})));if(t.sorting.length>0){const i=await this.concurrencyLimiter.run(async()=>await r.sort(t.sorting));r.dispose(),r=i}const o=r.getSpec(),n=await this.concurrencyLimiter.run(async()=>await r.getData([...o.keys()]));return r.dispose(),o.map((i,c)=>({spec:i,data:n[c]}))}async getUniqueValues(e,t){return await this.concurrencyLimiter.run(async()=>(Se().logPFrameRequests&&this.logger.info(`getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,Le)}`),await this.pFrames.getByKey(e).pFrame.getUniqueValues({...t,filters:at(t.filters)})))}async getShape(e){return(await this.pTables.getByKey(e)).getShape()}async getSpec(e){return(await this.pTables.getByKey(e)).getSpec()}async getData(e,t,r){const o=await this.pTables.getByKey(e);return await this.concurrencyLimiter.run(async()=>await o.getData(t,r))}}function Ee(s){switch(s.type){case"column":return{type:"column",columnId:s.column,qualifications:[]};case"inner":case"full":return{type:s.type,entries:s.entries.map(e=>Ee(e))};case"outer":return{type:"outer",primary:Ee(s.primary),secondary:s.secondary.map(e=>Ee(e))};default:E.assertNever(s)}}function mc(s){const e=ne.createHash("sha256");return e.update(me(s.def)),e.digest().toString("hex")}function vc(s){const e=[...s].map(r=>x.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:a.id.toString()}))};break;case"BinaryPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([c,a])=>({key:c,value:[a.index.id.toString(),a.values.id.toString()]}))};break;default:throw Error(`unsupported resource type: ${i}`)}return n.payload.sort((c,a)=>c.key.localeCompare(a.key)),n}));e.sort((r,o)=>r.id.localeCompare(o.id));const t=ne.createHash("sha256");return t.update(me(e)),t.digest().toString("hex")}async function rs(s,e,t){const r={...kt,...Ot(e),...t},o=new E.HmacSha256Signer(r.localSecret),n=te.createDownloadClient(r.logger,s,r.localProjections),i=te.createLogsClient(s,r.logger),c=te.createUploadBlobClient(s,r.logger),a=te.createUploadProgressClient(s,r.logger),l=new te.DownloadDriver(r.logger,n,i,r.blobDownloadPath,o,r.blobDriverOps),u=new te.UploadDriver(r.logger,o,c,a,r.uploadDriverOps),d=new te.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),v=new te.LogsDriver(r.logger,d,l),h=await te.LsDriver.init(r.logger,s,o,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),g=new gc(l,r.logger);return{blobDriver:l,logDriver:v,lsDriver:h,signer:o,uploadDriver:u,pFrameDriver:g}}class Bt{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=ne.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async o=>{const n=await ho(o,e);return o.createField(f.field(this.projectListResourceId,t),"Dynamic",n),await o.commit(),await f.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await se(this.pl,e,r,async o=>{o.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(f.field(this.projectListResourceId,e)),await t.commit()}),await this.projectListTree.refreshState()}async projectIdToResourceId(e){return await this.pl.withReadTx("Project id to resource id",async t=>{const r=(await t.getField(f.field(this.projectListResourceId,e))).value;if(f.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 He.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={...qr,...Wr(t),...r};o.defaultTreeOptions.logStat=Se().logTreeStats;const n=await e.withWriteTx("MLInitialization",async F=>{const N=f.field(F.clientRoot,js);F.createField(N,"Dynamic");const V=await F.getField(N);if(f.isNullResourceId(V.value)){const H=F.createEphemeral(Or);return F.lock(H),F.setField(N,H),await F.commit(),await H.globalId}else return V.value}),i=o.logger,c=await rs(e,t,o),a=new ae.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),l=new Er(a),u=new no(l,c.signer,a),d=new te.DownloadUrlDriver(i,e.httpDispatcher,o.frontendDownloadPath),v={pl:e,signer:c.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:a,ops:o,bpPreparer:u,frontendDownloadDriver:d,driverKit:c,blockUpdateWatcher:new pc(l,i,{minDelay:o.devBlockUpdateRecheckInterval,http:a,preferredUpdateChannel:o.preferredUpdateChannel}),quickJs:await Be.getQuickJS()},h=new D.WatchableValue([]),g=await Vs(e,n,h,v);return new Bt(v,c,c.signer,n,h,g.tree,l,g.computable)}}const yc=["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 wc(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=[];yc.forEach(a=>{hs.channel(a).subscribe(u=>{var v;const d=new Date().toISOString();(v=u==null?void 0:u.response)!=null&&v.headers&&(u.response.headers=u.response.headers.map(h=>h.toString())),r.push(JSON.stringify({timestamp:d,event:a,data:u}))})});const o={plPings:[],blockRegistryOverviewChecks:[],blockGARegistryOverviewChecks:[],blockRegistryUiChecks:[],blockGARegistryUiChecks:[],autoUpdateCdnChecks:[]},n=f.plAddressToConfig(s,{defaultRequestTimeout:t.pingTimeoutMs});o.plPings=await fe(t.pingCheckDurationMs,t.maxPingsPerSecond,async()=>{const l=await new f.UnauthenticatedPlClient(n).ping();return JSON.stringify(l).slice(0,t.bodyLimit)+"..."});const c=new f.UnauthenticatedPlClient(n).ll.httpDispatcher;return o.blockRegistryOverviewChecks=await fe(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await be(new URL(t.blockOverviewPath,t.blockRegistryUrl),t,c)),o.blockGARegistryOverviewChecks=await fe(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await be(new URL(t.blockOverviewPath,t.blockGARegistryUrl),t,c)),o.blockRegistryUiChecks=await fe(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await be(new URL(t.blockUiPath,t.blockRegistryUrl),t,c)),o.blockGARegistryUiChecks=await fe(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await be(new URL(t.blockUiPath,t.blockGARegistryUrl),t,c)),o.autoUpdateCdnChecks=await fe(t.autoUpdateCdnDurationMs,t.maxAutoUpdateCdnChecksPerSecond,async()=>await be(t.autoUpdateCdnUrl,t,c)),bc(o,s,t,r)}async function fe(s,e,t){const r=mt(),o=[];for(;wr(r)<s;){const n=mt();let i;try{i={ok:!0,value:await t()}}catch(l){i={ok:!1,error:l}}const c=wr(n);o.push({elapsedMs:c,response:i});const a=1e3/e-c;a>0&&await Sr.setTimeout(a)}return o}async function be(s,e,t){const{body:r,statusCode:o}=await ae.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),n=await r.text();return{statusCode:o,beginningOfBody:n.slice(0,e.bodyLimit)+"..."}}function bc(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)}.