@milaboratories/pl-middle-layer 1.15.13 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../../src/cfg_render/executor.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,UAAU,EAAiB,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAC/F,OAAO,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAG3C,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AA6KlE,2CAA2C;AAC3C,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,oBAAoB,EAC7B,IAAI,EAAE,eAAe,EACrB,GAAG,EAAE,GAAG,EACR,GAAG,GAAE,OAAO,CAAC,sBAAsB,CAAM,GACxC,UAAU,CAAC,OAAO,CAAC,CAErB;AAED,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,oBAAoB,EAC7B,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,GAAG,EAAE,GAAG,EACR,GAAG,GAAE,OAAO,CAAC,sBAAsB,CAAM,GACxC,UAAU,CAAC,OAAO,CAAC,CAuDrB"}
1
+ {"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../../src/cfg_render/executor.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,UAAU,EAAiB,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAC/F,OAAO,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAG3C,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AA4KlE,2CAA2C;AAC3C,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,oBAAoB,EAC7B,IAAI,EAAE,eAAe,EACrB,GAAG,EAAE,GAAG,EACR,GAAG,GAAE,OAAO,CAAC,sBAAsB,CAAM,GACxC,UAAU,CAAC,OAAO,CAAC,CAErB;AAED,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,oBAAoB,EAC7B,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,GAAG,EAAE,GAAG,EACR,GAAG,GAAE,OAAO,CAAC,sBAAsB,CAAM,GACxC,UAAU,CAAC,OAAO,CAAC,CAuDrB"}
package/dist/index.js CHANGED
@@ -1,34 +1,34 @@
1
- "use strict";var zt=Object.defineProperty;var Yt=(s,e,t)=>e in s?zt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var g=(s,e,t)=>Yt(s,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("@platforma-sdk/model"),ee=require("@milaboratories/pl-model-middle-layer"),K=require("undici"),D=require("@platforma-sdk/block-tools"),N=require("node:fs"),T=require("node:path"),Qt=require("yaml"),f=require("@milaboratories/ts-helpers"),Zt=require("node:fs/promises"),Xt=require("@milaboratories/resolve-helper"),d=require("@milaboratories/pl-client"),Ne=require("@milaboratories/pl-tree"),S=require("@milaboratories/computable"),G=require("node:crypto"),ht=require("denque"),er=require("@platforma-sdk/workflow-tengo"),Ie=require("canonicalize"),tr=require("node:assert"),pe=require("quickjs-emscripten"),ft=require("node:timers/promises"),U=require("@milaboratories/pl-drivers"),rr=require("@milaboratories/pframes-node"),sr=require("lru-cache"),or=require("node:diagnostics_channel");function ir(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 mt=ir(Zt);async function Xe(s){try{return await mt.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const nr=[D.RegistryV1.PlPackageYamlConfigFile],ar=[D.RegistryV1.PlPackageJsonConfigFile],Ve=["backend","dist","tengo","tpl","main.plj.gz"],Le=["config","dist","config.json"],vt=["frontend","dist"],et="block-model/dist/config.json",cr="block-ui/package.json",lr=[Ve,Le,nr,ar,vt];async function ur(s){return await Xe(T.join(s,...Le))!==void 0||await Xe(T.join(s,...Ve))!==void 0}function ke(s,e){const t=Xt.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function tt(s,e){if(T.isAbsolute(s)||(s=T.resolve(s)),await ur(s))return{workflow:T.join(s,...Ve),config:T.join(s,...Le),ui:T.join(s,...vt)};{const t=ke(s,et),r=ke(s,et),o=ke(s,cr);return{workflow:t,config:r,ui:T.resolve(o,"..","dist")}}}async function dr(s){try{return await N.promises.readFile(s,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}async function pr(s){try{return await N.promises.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}async function Ue(s){let e=0n;for(const t of lr){const r=T.join(s,...t),o=await pr(r);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function me(s){const e=await N.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await N.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class gr{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}:{},n=await(await K.request(`${r.url}/${D.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const a of n){const{organization:c,package:l,latestMeta:u,latestVersion:p}=a,h={organization:c,name:l,version:p};t.push({registryId:e.id,id:h,meta:{title:u.title??"No title",description:u.description??"No Description",organization:{name:c,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:h,registryUrl:r.url},otherVersions:a.allVersions})}return t;case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(a=>({...a,registryId:e.id}));case"local-dev":for(const a of await N.promises.readdir(r.path,{withFileTypes:!0})){if(!a.isDirectory())continue;const c=T.join(r.path,a.name),l=await dr(T.join(c,D.RegistryV1.PlPackageYamlConfigFile));if(l!==void 0){const u=D.RegistryV1.PlPackageConfigData.parse(Qt.parse(l)),p=await Ue(c),h={organization:u.organization,name:u.package,version:"DEV"};t.push({registryId:e.id,id:h,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:c,mtime:p},otherVersions:[]})}else{let u=c,p=await D.tryLoadPackDescription(u);if(p===void 0){for(const h of["block","meta"])if(u=T.join(c,h),p=await D.tryLoadPackDescription(u),p!==void 0)break}if(p!==void 0){const h=await me(p);t.push({registryId:e.id,id:p.id,meta:await D.BlockPackMetaEmbedAbsoluteBytes.parseAsync(p.meta),spec:{type:"dev-v2",folder:u,mtime:h},otherVersions:[]})}}}return t;default:return f.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}}}class yt{constructor(e){g(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new D.RegistryV2Reader(D.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const hr={type:"remote-v2",url:"https://blocks.pl-open.science/"},fr={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},mr={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},vr={groups:[{id:"default",label:"Default",blocks:[]}]},yr={stagingRefreshTimestamp:0,blocksInLimbo:[]},br={label:"New Project"},wr={name:"UserProject",version:"2"},bt="SchemaVersion",wt="1",Je="ProjectCreated",oe="ProjectLastModified",ie="ProjectMeta",W="ProjectStructure",ge="BlockRenderingState",Sr="BlockFrontendState/",kr=/^BlockFrontendState\/(?<blockid>.*)$/;function Oe(s){return`${Sr}${s}`}const Cr="BlockArgsAuthor/";function Fe(s){return`${Cr}${s}`}const Be="ProjectStructureAuthor";function Pr(s){const e=s.match(kr);if(e!==null)return e.groups.blockid}const Rr="__serviceTemplate_";function De(s){return`${Rr}${s}`}function R(s,e){return`${s}-${e}`}const Or=/^(?<blockId>.*)-(?<fieldName>blockPack|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function Fr(s){const e=s.match(Or);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const Br="projects",St={name:"Projects",version:"1"},Dr=s=>d.resourceTypesEqual(s.type,St)?s.fields:[];async function Tr(s,e,t,r){const o=await Ne.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:Dr},r.logger);return{computable:S.Computable.make(n=>{const a=n.accessor(o.entry()).node(),c=t.getValue(n);if(a===void 0)return;const l=[];for(const u of a.listDynamicFields()){const p=a.traverse(u);if(p===void 0)continue;const h=f.notEmpty(p.getKeyValueAsJson(ie)),v=f.notEmpty(p.getKeyValueAsJson(Je)),w=f.notEmpty(p.getKeyValueAsJson(oe));l.push({id:u,rid:p.id,created:new Date(v),lastModified:new Date(w),opened:c.indexOf(p.id)>=0,meta:h})}return l.sort(u=>-u.lastModified.valueOf()),l}).withStableType(),tree:o}}const xr={name:"EphRenderTemplate",version:"1"},Er={name:"RenderTemplate",version:"1"};function Me(s,e,t,r,o){if(o.length===0)throw new Error("Zero output names provided");const i=t?s.createEphemeral(xr):s.createStruct(Er),n=d.field(i,"template"),a=d.field(i,"inputs");return s.createField(n,"Input",e),s.createField(a,"Input",d.Pl.createPlMap(s,r,t)),s.lockInputs(i),d.Pl.futureRecord(s,i,o,"Output","outputs/")}const jr={name:"BContextEnd",version:"1"},Ar={name:"BContext",version:"1"},Nr="id",Ir="parent/",Vr=["context","result"];function rt(s,e,t){return Me(s,e,!0,t,Vr)}function Lr(s){const e=s.createEphemeral(jr);return s.lock(e),e}function Ur(s,e){if(e.length===0)return Lr(s);if(e.length===1)return e[0];const t=s.createEphemeral(Ar);s.createField(d.field(t,Nr),"Input",d.Pl.createPlString(s,G.randomUUID()));for(let r=0;r<e.length;r++)s.createField(d.field(t,`${Ir}${r}`),"Input",e[r]);return s.lock(t),t}const kt={name:"TengoTemplateGet",version:"1"},Ct="registry",Pt="templateURI",Rt="template",Ot={name:"TengoTemplatePack",version:"1"},Ft={name:"TengoTemplatePackConvert",version:"1"},Bt="templatePack",Dt="template";async function Tt(s){switch(s.type){case"from-file":return{type:"explicit",content:await N.promises.readFile(s.path)};case"from-registry":case"explicit":return s;default:return f.assertNever(s)}}function Jr(s,e){const t=s.createStruct(kt),r=d.field(t,Ct),o=d.field(t,Pt),i=d.field(t,Rt);return s.setField(r,s.createValue(d.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(o,s.createValue(d.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),i}function Mr(s,e){const t=s.createValue(Ot,e.content),r=s.createStruct(Ft),o=d.field(r,Bt),i=d.field(r,Dt);return s.setField(o,t),i}function ve(s,e){switch(e.type){case"from-registry":return Jr(s,e);case"explicit":return Mr(s,e);default:return f.assertNever(e)}}const $e={name:"Frontend/FromUrl",version:"1"},Ke={name:"Frontend/FromFolder",version:"1"};function $r(s,e){switch(e.type){case"url":return s.createValue($e,JSON.stringify({url:e.url}));case"local":return s.createValue(Ke,JSON.stringify({path:e.path,signature:e.signature}));default:return f.assertNever(e)}}const Kr={name:"BlockPackCustom",version:"1"},xt="template",Et="frontend";function st(s){return s.endsWith("/")?s:`${s}/`}class Gr{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 tt(e.folder),r=await N.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await D.loadPackDescription(e.folder),r=await N.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=`${st(e.registryUrl)}${D.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`;return await(await K.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 K.request(o.model.url,t)).body.json()}default:return f.assertNever(e)}}async prepare(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await tt(e.folder),r=await N.promises.readFile(t.workflow),o=JSON.parse(await N.promises.readFile(t.config,"utf-8")),i=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:o,frontend:{type:"local",path:i,signature:this.signer.sign(i)},source:e}}case"dev-v2":{const t=await D.loadPackDescription(e.folder),r=JSON.parse(await N.promises.readFile(t.components.model.file,{encoding:"utf-8"})),o=await N.promises.readFile(t.components.workflow.main.file),i=t.components.ui.folder,n={...e};return e.mtime===void 0&&(n.mtime=await me(t)),{type:"explicit",template:{type:"explicit",content:o},config:r,frontend:{type:"local",path:i,signature:this.signer.sign(i)},source:n}}case"from-registry-v1":{const t=this.http!==void 0?{dispatcher:this.http}:{},r=`${st(e.registryUrl)}${D.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,o=`${r}/template.plj.gz`,i=await K.request(o,t);if(i.statusCode!==200)throw new Error(`Block not found in registry (url = ${o} ; code = ${i.statusCode}): `+JSON.stringify(e));const n=new Uint8Array(await i.body.arrayBuffer()),c=await(await K.request(`${r}/config.json`,t)).body.json();return{type:"explicit",template:{type:"explicit",content:n},config:c,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),i=async()=>await(await K.request(o.model.url,t)).body.json(),n=async()=>await(await K.request(o.workflow.main.url,t)).body.arrayBuffer(),[a,c]=await Promise.all([i(),n()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(c)},config:a,frontend:{type:"url",url:o.ui.url},source:e}}default:return f.assertNever(e)}}}function _r(s,e){const t={config:e.config,source:e.source},r=s.createStruct(Kr,JSON.stringify(t));return s.createField(d.field(r,xt),"Input",ve(s,e.template)),s.createField(d.field(r,Et),"Input",$r(s,e.frontend)),s.lock(r),r}function ot(s,e){switch(e.type){case"explicit":return _r(s,e);default:return f.assertNever(e.type)}}function ce(s,e){return{__isRef:!0,blockId:s,name:e}}function Hr(s){return typeof s=="object"&&s!==null&&s.__isRef===!0&&"blockId"in s&&"name"in s}function Te(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(Hr(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)Te(s,o,t);else for(const[,o]of Object.entries(e))Te(s,o,t);return;default:f.assertNever(r)}}function qr(s,e){const t={upstreams:new Set,missingReferences:!1};return Te(t,s,e),t}function M(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class jt{constructor(e){g(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 i=new Set(o);for(;o.length>0;){let n=[];for(const a of o){const c=this.nodes.get(a);r(c),c[e].forEach(l=>{i.has(l)||(i.add(l),n.push(l))})}o=n}}}function xe(s){const e=new Map;let t;for(const{id:r}of M(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 jt(e)}function ue(s,e){const t=new Map,r=new Set;for(const{id:o}of M(s)){const i=e(o);if(i===void 0)continue;const n=qr(i,r),a={id:o,missingReferences:n.missingReferences,upstream:n.upstreams,downstream:new Set};t.set(o,a),n.upstreams.forEach(c=>t.get(c).downstream.add(o)),r.add(o)}return new jt(t)}function Wr(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function Ee(s,e){if(s.size>e.size)return Ee(e,s);for(const t of s)if(e.has(t))return!0;return!1}function it(s,e){const t=new Set,r=new Set,o=new Set;return s.nodes.forEach(i=>{const n=e.nodes.get(i.id);n===void 0?t.add(i.id):(!Wr(i.upstream,n.upstream)||Ee(i.upstream,o))&&o.add(i.id)}),e.nodes.forEach(i=>{s.nodes.has(i.id)?Ee(i.upstream,o)&&o.add(i.id):r.add(i.id)}),{onlyInA:t,onlyInB:r,different:o}}let Ce;async function At(){if(Ce===void 0){const s=await Tt(er.Templates["pframes.export-pframe"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=G.createHash("sha256").update(s.content).digest("hex");Ce={spec:s,hash:e}}return Ce}function zr(s,e,t){return Me(s,e,!0,{pf:t},["result"]).result}function Pe(s,e){let t=!1,r,o;return()=>{if(!t)return t=!0,r=s(),o=e(),o;const i=s();return r!==i&&(r=i,o=e()),e()}}class nt{constructor(e,t){g(this,"currentInputsC",Pe(()=>this.fields.currentArgs.modCount,()=>JSON.parse(Buffer.from(this.fields.currentArgs.value).toString())));g(this,"actualProductionInputsC",Pe(()=>{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())}));g(this,"productionStaleC",Pe(()=>{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(d.Pl.unwrapHolder(e,this.fields.blockPack.ref),xt,"Input")}}const Yr=s=>{throw new Error(`No new block info for ${s}`)};class he{constructor(e,t,r,o,i,n,a,c,l,u,p,h){g(this,"globalModCount",0);g(this,"fieldsChanged",!1);g(this,"lastModifiedChanged",!1);g(this,"structureChanged",!1);g(this,"metaChanged",!1);g(this,"renderingStateChanged",!1);g(this,"changedBlockFrontendStates",new Set);g(this,"blocksWithChangedInputs",new Set);g(this,"stagingGraph");g(this,"pendingProductionGraph");g(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=o,this.lastModified=i,this.meta=n,this.struct=a,this.renderingState=c,this.blocksInLimbo=l,this.blockInfos=u,this.blockFrontendStates=p,this.ctxExportTplHolder=h}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=xe(this.struct)),this.stagingGraph}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=ue(this.struct,e=>this.getBlockInfo(e).currentInputs)),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=ue(this.struct,e=>this.getBlockInfo(e).actualProductionInputs)),this.actualProductionGraph}getBlockInfo(e){return f.notEmpty(this.blockInfos.get(e))}getBlock(e){for(const t of M(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const o=d.field(this.rid,R(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,i){this.setBlockFieldObj(e,t,{ref:r,status:o,value:i})}deleteBlockFields(e,...t){let r=!1;const o=this.getBlockInfo(e);for(const i of t){const n=o.fields;i in n&&(this.tx.removeField(d.field(this.rid,R(e,i))),delete n[i],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,i;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((o=t.stagingCtx)==null?void 0:o.status)==="Ready"&&((i=t.stagingUiCtx)==null?void 0:i.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,i;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"&&((i=t.prodUiCtx)==null?void 0:i.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 i=this.getBlockInfo(r);JSON.parse(o);const n=Buffer.from(o);if(Buffer.compare(i.fields.currentArgs.value,n)===0)continue;const a=this.tx.createValue(d.Pl.JsonObject,n);this.setBlockField(r,"currentArgs",a,"Ready",n),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 i=this.getBlockInfo(o);if(i.fields[t]===void 0||i.fields[t].ref===void 0)throw new Error("One of the upstreams staging is not rendered.");r.push(d.Pl.unwrapHolder(this.tx,i.fields[t].ref))}),Ur(this.tx,r)}exportCtx(e){return zr(this.tx,d.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),i=rt(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(d.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(d.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",d.Pl.wrapInEphHolder(this.tx,i.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(i.context),"NotReady"),this.setBlockField(e,"stagingOutput",i.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),i=rt(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(d.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(d.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",d.Pl.wrapInEphHolder(this.tx,i.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(i.context),"NotReady"),this.setBlockField(e,"prodOutput",i.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=Yr){const r=this.getStagingGraph(),o=this.getActualProductionGraph(),i=xe(e),n=ue(e,l=>{var u;return(u=this.blockInfos.get(l))==null?void 0:u.actualProductionInputs}),a=it(r,i),c=it(o,n);for(const l of a.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 a.onlyInB){const u=new nt(l,{});this.blockInfos.set(l,u);const p=t(l),h=ot(this.tx,p.blockPack);this.setBlockField(l,"blockPack",d.Pl.wrapInHolder(this.tx,h),"NotReady");const v=Buffer.from(p.args),w=this.tx.createValue(d.Pl.JsonObject,v);this.setBlockField(l,"currentArgs",w,"Ready",v),p.uiState&&(this.blockFrontendStates.set(l,p.uiState),this.changedBlockFrontendStates.add(l)),u.check()}for(const l of a.different)this.resetStaging(l);o.traverse("downstream",[...c.different],l=>{this.resetOrLimboProduction(l.id)}),(a.onlyInB.size>0||a.onlyInA.size>0||a.different.size>0)&&this.resetStagingRefreshTimestamp(),this.struct=e,this.structureChanged=!0,this.stagingGraph=void 0,this.pendingProductionGraph=void 0,this.actualProductionGraph=void 0,this.updateLastModified()}addBlock(e,t,r){const o=this.structure;if(r===void 0)o.groups[o.groups.length-1].blocks.push(e);else{let i=!1;for(const n of o.groups){const a=n.blocks.findIndex(c=>c.id===r);if(!(a<0)){n.blocks.splice(a,0,e),i=!0;break}}if(!i)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(o,i=>{if(i!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const o of t.groups){const i=o.blocks.findIndex(n=>n.id===e);if(!(i<0)){o.blocks.splice(i,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",d.Pl.wrapInHolder(this.tx,ot(this.tx,t)),"NotReady"),r!==void 0?(this.setArgs([{blockId:e,args:r}]),this.setUiState(e,void 0)):this.getStagingGraph().traverse("downstream",[e],({id:i})=>this.resetStaging(i)),o.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:i})=>this.resetOrLimboProduction(i)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),o=this.getPendingProductionGraph();if(t)o.traverse("upstream",e,n=>{r.add(n.id)});else for(const n of r){const a=o.nodes.get(n);if(a===void 0)throw new Error(`Can't find block with id: ${n}`);for(const c of a.upstream)if(!r.has(c))throw new Error("Can't render blocks not including all upstreams.")}const i=new Set;for(const n of M(this.structure)){if(!r.has(n.id))continue;let a=this.getBlockInfo(n.id).requireProductionRendering||this.blocksInLimbo.has(n.id);if(!a){for(const c of o.nodes.get(n.id).upstream)if(i.has(c)){a=!0;break}}a&&(this.renderProductionFor(n.id),i.add(n.id))}return o.traverse("downstream",[...i],n=>{i.has(n.id)||this.resetOrLimboProduction(n.id)}),i.size>0&&this.updateLastModified(),i}stopProduction(...e){var n,a;const t=this.getActualProductionGraph(),r=new ht(e),o=new Set(e),i=[];for(;!r.isEmpty();){const c=r.shift(),l=this.getBlockInfo(c).fields;if(!(((n=l.prodOutput)==null?void 0:n.status)==="Ready"&&((a=l.prodCtx)==null?void 0:a.status)==="Ready")&&this.deleteBlockFields(c,"prodOutput","prodCtx","prodUiCtx","prodArgs")){i.push(c);for(const u of t.traverseIdsExcludingRoots("downstream",c))o.has(u)||(r.push(u),o.add(u))}}for(const c of t.traverseIdsExcludingRoots("downstream",...i))this.resetOrLimboProduction(c)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(o=>{let n=this.getBlockInfo(o.id).stagingRendered?0:1;o.upstream.forEach(a=>{const c=t.get(a);c!==0&&(n=Math.max(c+1,n))}),e(o.id,n),t.set(o.id,n)})}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((i,n)=>{n!==0&&(r===void 0||n<=r)&&(this.renderStagingFor(i),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,i,n;((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"),((i=t.fields.stagingCtx)==null?void 0:i.status)==="Ready"&&((n=t.fields.stagingOutput)==null?void 0:n.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,Fe(t)):this.tx.setKValue(this.rid,Fe(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,Be):this.tx.setKValue(this.rid,Be,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,oe,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,W,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,ge,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,ie,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,Oe(e)):this.tx.setKValue(this.rid,Oe(e),t)}this.assignAuthorMarkers()}}static async load(e,t,r){const o=e.getResourceData(t,!0),i=e.getKValueJson(t,bt),n=e.getKValueJson(t,oe),a=e.getKValueJson(t,ie),c=e.getKValueJson(t,W),l=e.getKValueJson(t,ge),u=e.listKeyValuesString(t),[p,h,v,w,P,{stagingRefreshTimestamp:j,blocksInLimbo:$},I]=await Promise.all([o,i,n,a,c,l,u]);if(h!==wt)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${h}`);const H=new Map;for(const b of p.fields){const B=Fr(b.name);if(B===void 0)continue;let O=H.get(B.blockId);O===void 0&&(O={id:B.blockId,fields:{}},H.set(B.blockId,O)),O.fields[B.fieldName]=d.isNullResourceId(b.value)?{modCount:0}:{modCount:0,ref:b.value}}const z=await At(),ne=De(z.hash),k=p.fields.find(b=>b.name===ne);let V;k!==void 0?V=d.ensureResourceIdNotNull(k.value):(V=d.Pl.wrapInHolder(e,ve(e,z.spec)),e.createField(d.field(t,De(z.hash)),"Dynamic",V));const Y={stagingRefreshTimestamp:j},A=new Set($),x=new Map;for(const b of I){const B=Pr(b.key);B!==void 0&&x.set(B,b.value)}const F=[];H.forEach(({id:b,fields:B})=>{for(const[,O]of Object.entries(B))if(O.ref!==void 0){if(!d.isResource(O.ref)||d.isResourceRef(O.ref))throw new Error("unexpected behaviour");F.push([O,e.getResourceData(O.ref,!1)])}});for(const[b,B]of F){const O=await B;b.value=O.data,d.isNotNullResourceId(O.error)?b.status="Error":O.resourceReady||d.isNotNullResourceId(O.originalResourceId)?b.status="Ready":b.status="NotReady"}const _=new Map;H.forEach(({id:b,fields:B})=>_.set(b,new nt(b,B)));const L=new Set;for(const b of M(P)){if(!_.has(b.id))throw new Error(`Inconsistent project structure: no inputs for ${b.id}`);L.add(b.id)}_.forEach(b=>{if(!L.has(b.id))throw new Error(`Inconsistent project structure: no structure entry for ${b.id}`);b.check()});const ae=new he(t,e,r,h,v,w,P,Y,A,_,x,V);return ae.fixProblems(),ae}}async function Qr(s,e=br){const t=s.createEphemeral(wr);s.lock(t);const r=String(Date.now());s.setKValue(t,bt,JSON.stringify(wt)),s.setKValue(t,Je,r),s.setKValue(t,oe,r),s.setKValue(t,ie,JSON.stringify(e)),s.setKValue(t,W,JSON.stringify(vr)),s.setKValue(t,ge,JSON.stringify(yr));const o=await At();return s.createField(d.field(t,De(o.hash)),"Dynamic",d.Pl.wrapInHolder(s,ve(s,o.spec))),t}async function Re(s,e,t){return J(s,e,void 0,t)}async function J(s,e,t,r){if(s instanceof d.PlClient)return await s.withWriteTx("ProjectAction",async o=>{const i=await he.load(o,e,t),n=await r(i);return i.wasModified&&(i.save(),await o.commit()),n});{const o=await he.load(s,e,t),i=await r(o);return o.save(),i}}function*Zr(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:f.assertNever(s)}}function at(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function Xr(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:at(s.parts,e)};case"BinaryPartitioned":return{...s,parts:at(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:f.assertNever(s)}}const es=d.resourceType("PColumnData/JsonPartitioned","1"),ts=d.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),rs=d.resourceType("PColumnData/BinaryPartitioned","1"),ss=d.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),os=d.resourceType("PColumnData/Json","1");function is(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(d.resourceTypesEqual(s.resourceType,os)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(d.resourceTypesEqual(s.resourceType,es)){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(d.resourceTypesEqual(s.resourceType,ts)){const t=e,r={};for(const o of s.listInputFields()){const i=s.traverse({field:o,errorIfFieldNotSet:!0}),n=i.listInputFields();if(n===void 0)throw new Error(`no partition keys for super key ${o}`);for(const a of n){const c=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);r[c]=i.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(d.resourceTypesEqual(s.resourceType,rs)){const t=e,r={};for(const o of s.listInputFields())if(o.endsWith(".index")){const i=o.slice(0,o.length-6);let n=r[i];n===void 0&&(n={},r[i]=n),n.index=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else if(o.endsWith(".values")){const i=o.slice(0,o.length-7);let n=r[i];n===void 0&&(n={},r[i]=n),n.values=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${o}`);for(const[o,i]of Object.entries(r)){if(i.index===void 0)throw new Error(`no index for part ${o}`);if(i.values===void 0)throw new Error(`no values for part ${o}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(d.resourceTypesEqual(s.resourceType,ss)){const t=e,r={};for(const o of s.listInputFields()){const i=s.traverse({field:o,errorIfFieldNotSet:!0}),n=i.listInputFields();if(n===void 0)throw new Error(`no partition keys for super key ${o}`);for(const a of n)if(a.endsWith(".index")){const c=a.slice(0,a.length-6),l=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].index=i.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else if(a.endsWith(".values")){const c=a.slice(0,a.length-7),l=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].values=i.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${a}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}throw new Error(`unsupported resource type: ${d.resourceTypeToString(s.resourceType)}`)}function je(s,e){const t=G.createHash("sha256");return t.update(Ie(s)),t.update(String(d.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function Nt(s,e=!0,t=!1,r=""){var a,c,l;const o=/^(?<name>.*)\.(?<type>spec|data)$/,i=new Map;for(const u of s.listInputFields()){const p=u.match(o);if(!p){if(e)throw new Error(`unexpected field name ${u}`);continue}let h=f.notEmpty((a=p.groups)==null?void 0:a.name);if(!h.startsWith(r)){if(e)throw new Error(`unexpected field name ${u}`);continue}h=h.slice(r.length);const v=f.notEmpty((c=p.groups)==null?void 0:c.type);let w=i.get(h);switch(w===void 0&&(w={},i.set(h,w)),v){case"spec":w.spec=(l=s.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:l.getDataAsJson();break;case"data":w.hasData=!0,w.data=()=>s.traverseOrError({field:u,ignoreError:t});default:continue}}const n=s.getInputsLocked();if(n)for(const[,u]of i)u.data===void 0&&(u.hasData=!1);return{locked:n,results:i}}function ns(s,e=!0,t=""){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const r=Nt(s,e,!1,t);tr(r.locked);const o={};for(const[i,n]of r.results){if(n.spec===void 0)throw new Error(`no spec for key ${i}`);if(n.hasData!==!0||n.data===void 0)throw new Error(`no data for key ${i}`);const a=n.data();if(a===void 0)throw new Error(`no data for key ${i}`);if(!a.ok)throw new Ne.PlError(a.error);o[i]={id:je(n.spec,a.value),spec:n.spec,data:a.value}}return o}class Ge{constructor(e,t){g(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const o of t.values())for(const i of[o.prod,o.staging])if(i!==void 0){if(!i.locked){r=!1;break e}for(const n of i.results.values())if(n.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var i,n,a,c,l,u;const r=this.blocks.get(e);if(r===void 0)return;let o=(a=(n=(i=r.prod)==null?void 0:i.results)==null?void 0:n.get(t))==null?void 0:a.spec;if(o!==void 0||(o=(u=(l=(c=r.staging)==null?void 0:c.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 n,a,c;const r=this.blocks.get(e);if(r===void 0)return;let o=(a=(n=r.prod)==null?void 0:n.results)==null?void 0:a.get(t),i=(c=o==null?void 0:o.data)==null?void 0:c.call(o);if(o!==void 0&&o.spec!==void 0&&i!==void 0)return C.mapValueInVOE(i,l=>({id:je(o.spec,l),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=n=>{r===void 0&&(r=n),t=!1},i=(n,a,c)=>{if(c.spec!==void 0&&c.hasData===!0&&c.data!==void 0){const l=c.data();l!==void 0?e.push({ref:ce(n,a),obj:{id:l.ok?je(c.spec,l.value):void 0,spec:c.spec,data:l}}):o(`no_data:${n}:${a}`)}};for(const[n,a]of this.blocks){const c=new Set;if(a.prod!==void 0){a.prod.locked||o(`prod_not_locked:${n}`);for(const[l,u]of a.prod.results)c.add(l),i(n,l,u)}if(a.staging!==void 0){a.staging.locked||o(`staging_not_locked:${n}`);for(const[l,u]of a.staging.results)c.has(l)||i(n,l,u)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const o=i=>{r===void 0&&(r=i),t=!1};for(const[i,n]of this.blocks){const a=new Set;if(n.staging!==void 0){n.staging.locked||o(`staging_not_locked:${i}`);for(const[c,l]of n.staging.results)l.spec!==void 0&&(e.push({ref:ce(i,c),obj:l.spec}),a.add(c))}else o(`staging_not_rendered:${i}`);if(n.prod!==void 0){n.prod.locked||o(`prod_not_locked:${i}`);for(const[c,l]of n.prod.results)a.has(c)||l.spec!==void 0&&e.push({ref:ce(i,c),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,i=n=>{for(const[a,c]of n.results)o.has(a)||c.spec===void 0||(o.add(a),C.executePSpecPredicate(e,c.spec)&&t.push({label:r.info.label+" / "+a,ref:ce(r.info.id,a),spec:c.spec}))};r.staging!==void 0&&i(r.staging),r.prod!==void 0&&i(r.prod)}return t}static create(e,t,r){const o=e.accessor(t).node(),i=f.notEmpty(o.getKeyValueAsJson(W)),a=xe(i).traverseIds("upstream",r),c=new Map;for(const l of M(i)){if(!a.has(l.id))continue;const u=ct(o.traverse({field:R(l.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:R(l.id,"prodUiCtx"),stableIfNotFound:!0})),p=ct(o.traverse({field:R(l.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:R(l.id,"stagingUiCtx")}));c.set(l.id,{info:l,prod:u,staging:p})}return new Ge(e,c)}}function ct(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return Nt(e.value,!1,!0)}function _e(s,e){return{blockId:e,args:o=>f.notEmpty(o.accessor(s).node().traverse({field:R(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),uiState:o=>o.accessor(s).node().getKeyValueAsString(Oe(e)),blockMeta:o=>{const i=o.accessor(s).node(),n=f.notEmpty(i.getKeyValueAsJson(W)),a=new Map;for(const c of M(n))a.set(c.id,c);return a}}}function It(s,e){return{..._e(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:R(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:R(e,"stagingOutput"),ignoreError:!0}))==null?void 0:o.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>Ge.create(t,s,e)}}function*E(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*E(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*E(t);return;case"MakeArray":for(const t of s.template)yield*E(t);return;case"GetJsonField":case"GetResourceField":yield*E(s.source),yield*E(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*E(s.source),yield*E(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*E(s.source);return;case"IsEmpty":yield*E(s.arg);return;case"Not":yield*E(s.operand);return;case"And":case"Or":yield*E(s.operand1),yield*E(s.operand2);return;default:f.assertNever(s)}}function as(s,e){const t={};for(const[r,o]of Object.entries(s))t[r]=e(o);return t}function te(s,e){return s===void 0?void 0:e(s)}function cs(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function ls(s){for(const e of E(s))if(cs(e))return!0;return!1}function ye(s){return{type:"ReturnResult",result:s}}function m(s){return()=>ye(s)}const us=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return m(e)},ds=s=>{const e=s.source;if(e===void 0)return m(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return m(t)},ps=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?m(void 0):({cCtx:r})=>{var o;return ye((o=r.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function Vt(s,e){const t={},r=s.length;for(let o=0;o<r;o++)t[String(o)]=e(s[o]);return t}function gs(s,e){return t=>{const r=t.source;return r===void 0?m(void 0):()=>({type:"ScheduleSubroutine",subroutine:Lt(r.length),args:Vt(r,o=>y({...s,[e.itVar]:o},e.mapping))})}}function Lt(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return m(t)}}function hs(s,e){return t=>{const r=t.source;if(r===void 0)return m(void 0);const o={};for(const[i,n]of Object.entries(r)){const a={...s,[e.itVar]:n};o[i]=y(a,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:fs,args:o})}}const fs=s=>m(s),ms=s=>{const e=s.arg;return m(e===void 0?void 0:e.length===0)},vs=s=>{const e=s.operand;return m(e===void 0?void 0:!e)},ys=s=>{const e=s.operand1,t=s.operand2;return m(e===void 0||t===void 0?void 0:e&&t)},bs=s=>{const e=s.operand1,t=s.operand2;return m(e===void 0||t===void 0?void 0:e||t)},ws=s=>{const e=s.source;return e===void 0?m(void 0):({cCtx:t})=>{var r;return ye((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},Ss=s=>{const e=s.source,t=s.field;return m(e===void 0||t===void 0?void 0:e[t])};function ks(s,e){return t=>{const r=t.source;return r===void 0?m(void 0):({cCtx:o})=>{const i=o.accessor(r).node(),n={};for(const a of i.listInputFields()){const c=i.traverse(a);if(c===void 0)n[a]=m(void 0);else{const l={...s,[e.itVar]:c.persist()};n[a]=y(l,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:Cs,args:n}}}}const Cs=s=>m(s),Ps=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:S.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)}})})},Rs=s=>{const e=s.source;return e===void 0?m(void 0):({cCtx:t,drivers:r})=>{const o=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:S.Computable.make(()=>r.blobDriver.getDownloadedBlob(o),{postprocessValue:async i=>i===void 0?void 0:(await r.blobDriver.getContent(i.handle)).toString()})}}},Os=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:S.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())}})})},Fs=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},Bs=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},Ds=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},Ts=s=>e=>{const t=e.source;return t===void 0?m(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},xs=s=>e=>{const t=e.source;return t===void 0?m(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},Es=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function y(s,e){switch(e.type){case"GetFromCtx":const t=s[e.variable];return typeof t=="function"?r=>ye(t(r.cCtx)):m(t);case"Isolate":return({drivers:r})=>({type:"ScheduleComputable",computable:Mt(r,s,e.cfg)});case"Immediate":return m(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:Ss,args:{source:y(s,e.source),field:y(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:gs(s,e),args:{source:y(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:hs(s,e),args:{source:y(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:us,args:as(e.template,r=>y(s,r))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:Lt(e.template.length),args:Vt(e.template,r=>y(s,r))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:ds,args:{source:y(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:ms,args:{arg:y(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:vs,args:{operand:y(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:ys,args:{operand1:y(s,e.operand1),operand2:y(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:bs,args:{operand1:y(s,e.operand1),operand2:y(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:ks(s,e),args:{source:y(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:ps,args:{source:y(s,e.source),field:y(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:ws,args:{source:y(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Ps,args:{source:y(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:Rs,args:{source:y(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Os,args:{source:y(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Fs,args:{source:y(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Bs,args:{source:y(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:Ds,args:{source:y(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:Ts(e.lines),args:{source:y(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:xs(e.patternToSearch),args:{source:y(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:Es,args:{source:y(s,e.source)}});default:return f.assertNever(e)}}const js=["$prod","$staging"];function As(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 Ut=Symbol(),Jt="return",Ns={op:Ut,arg:Jt};function Is(s){return s.op==Ut&&s.arg==Jt}function Vs(){return{pendingSubroutines:new Map}}function lt(s,e,t,r){const o=new ht(t),i=(a,c)=>{if(Is(a))return e.result=c,!1;const l=f.notEmpty(e.pendingSubroutines.get(a.op));if(a.arg in l.args)throw new Error("argument already set");return l.args[a.arg]=c,l.argCounter--,l.argCounter===0&&(e.pendingSubroutines.delete(a.op),o.push({destination:l.destination,operation:l.subroutine(l.args)})),!0},n=[];e:for(;o.length>0;){const a=o.shift(),c=a.operation(s);switch(c.type){case"ReturnResult":if(!i(a.destination,c.result))break e;break;case"ScheduleSubroutine":const l=Symbol(),u=Object.entries(c.args),p=u.length;if(p===0)o.push({destination:a.destination,operation:c.subroutine({})});else{for(const[h,v]of u)o.push({destination:{op:l,arg:h},operation:v});e.pendingSubroutines.set(l,{argCounter:p,args:{},subroutine:c.subroutine,destination:a.destination})}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");n.push({destination:a.destination,computable:c.computable});break;default:f.assertNever(c)}}return n}function Ls(s,e,t,r={}){return Mt(s,As(e),t,r)}function Mt(s,e,t,r={}){const o=`${e.blockId}#`+Ie({ctx:Object.fromEntries(Object.entries(e).filter(([i])=>js.indexOf(i)===-1)),cfg:t});return S.Computable.makeRaw(i=>{const n={drivers:s,cCtx:i},a=Vs();return{ir:lt(n,a,[{destination:Ns,operation:y(e,t)}],!0),async postprocessValue(l){const u=[];for(const w of l)u.push({destination:w.destination,operation:m(w.computable)});const p={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},h=new Map;for(const[w,P]of a.pendingSubroutines)h.set(w,{...P,args:{...P.args}});const v={result:a.result,pendingSubroutines:h};if(lt(p,v,u,!1),!("result"in v))throw new Error("illegal cfg rendering stack state, no result");return v.result}}},{...r,key:o})}function Us(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}function ut(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class fe{constructor(e,t,r,o,i){g(this,"callbackRegistry");g(this,"fnJSONStringify");g(this,"fnJSONParse");g(this,"computablesToResolve",{});g(this,"computableCtx");g(this,"accessors",new Map);g(this,"meta");g(this,"_resultPool");if(this.scope=e,this.vm=t,this.blockCtx=r,this.env=o,this.computableCtx=i,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(n=>t.getProp(n,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(n=>t.getProp(n,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");this.meta=r.blockMeta(i),this.injectCtx()}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw fe.cleanErrorContext(t),t}}runCallback(e,...t){try{return pe.Scope.withScope(r=>{const o=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(o)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(o,this.vm.undefined,...t.map(i=>this.exportObjectUniversal(i,r)))))})}catch(r){throw fe.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 i=this.blockCtx[o];if(i===void 0)throw new Error("Staging context not available");const n=i(this.computableCtx);n?this.accessors.set(r,this.computableCtx.accessor(n).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 ut(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return ut(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r){const o=this.getAccessor(e);if(!o.getIsReadyOrError())return;const i=ns(o,t,r),n={};for(const[a,c]of Object.entries(i))n[a]=C.mapPObjectData(c,l=>this.wrapAccessor(l));return n}registerComputable(e,t){const r=`${e}_${G.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",S.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",S.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=f.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:C.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:C.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 C.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=>C.mapPObjectData(t,r=>this.getAccessor(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(C.mapPTableDef(e,t=>C.mapPObjectData(t,r=>this.getAccessor(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=G.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(Us(e)){r=this.vm.newArrayBuffer(e),o=!0;break}return}return o&&t!=null?t.manage(r):r}exportObjectUniversal(e,t){const r=this.tryExportSingleValue(e,t);return r!==void 0?r:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const r=this.vm.newString(JSON.stringify(e)).consume(o=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,o)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){switch(this.vm.typeof(e)){case"undefined":return;case"boolean":case"number":case"string":return this.vm.dump(e);default:return this.importObjectViaJson(e)}}importObjectViaJson(e){const t=this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify,this.vm.undefined,e)).consume(r=>this.vm.getString(r));if(t!=="undefined")return JSON.parse(t)}injectCtx(){pe.Scope.withScope(e=>{const t=e.manage(this.vm.newObject()),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);const i=(n,a)=>{this.vm.newFunction(n,a).consume(c=>this.vm.setProp(t,n,c))};i("getAccessorHandleByName",n=>this.exportSingleValue(this.getAccessorHandleByName(this.vm.getString(n)),void 0)),i("resolveWithCommon",(n,a,...c)=>this.exportSingleValue(this.resolveWithCommon(this.vm.getString(n),this.importObjectViaJson(a),...c.map(l=>this.importObjectViaJson(l))),void 0)),i("getResourceType",n=>this.exportObjectViaJson(this.getResourceType(this.vm.getString(n)),void 0)),i("getInputsLocked",n=>this.exportSingleValue(this.getInputsLocked(this.vm.getString(n)),void 0)),i("getOutputsLocked",n=>this.exportSingleValue(this.getOutputsLocked(this.vm.getString(n)),void 0)),i("getIsReadyOrError",n=>this.exportSingleValue(this.getIsReadyOrError(this.vm.getString(n)),void 0)),i("getIsFinal",n=>this.exportSingleValue(this.getIsFinal(this.vm.getString(n)),void 0)),i("getError",n=>this.exportSingleValue(this.getError(this.vm.getString(n)),void 0)),i("listInputFields",n=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(n)),void 0)),i("listOutputFields",n=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(n)),void 0)),i("listDynamicFields",n=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(n)),void 0)),i("getKeyValueBase64",(n,a)=>this.exportSingleValue(this.getKeyValueBase64(this.vm.getString(n),this.vm.getString(a)),void 0)),i("getKeyValueAsString",(n,a)=>this.exportSingleValue(this.getKeyValueAsString(this.vm.getString(n),this.vm.getString(a)),void 0)),i("getDataBase64",n=>this.exportSingleValue(this.getDataBase64(this.vm.getString(n)),void 0)),i("getDataAsString",n=>this.exportSingleValue(this.getDataAsString(this.vm.getString(n)),void 0)),i("parsePObjectCollection",(n,a,c)=>this.exportObjectUniversal(this.parsePObjectCollection(this.vm.getString(n),this.vm.dump(a),this.vm.getString(c)),void 0)),i("getBlobContentAsBase64",n=>this.exportSingleValue(this.getBlobContentAsBase64(this.vm.getString(n)),void 0)),i("getBlobContentAsString",n=>this.exportSingleValue(this.getBlobContentAsString(this.vm.getString(n)),void 0)),i("getDownloadedBlobContentHandle",n=>this.exportSingleValue(this.getDownloadedBlobContentHandle(this.vm.getString(n)),void 0)),i("getOnDemandBlobContentHandle",n=>this.exportSingleValue(this.getOnDemandBlobContentHandle(this.vm.getString(n)),void 0)),i("getImportProgress",n=>this.exportSingleValue(this.getImportProgress(this.vm.getString(n)),void 0)),i("getLastLogs",(n,a)=>this.exportSingleValue(this.getLastLogs(this.vm.getString(n),this.vm.getNumber(a)),void 0)),i("getProgressLog",(n,a)=>this.exportSingleValue(this.getProgressLog(this.vm.getString(n),this.vm.getString(a)),void 0)),i("getLogHandle",n=>this.exportSingleValue(this.getLogHandle(this.vm.getString(n)),void 0)),i("getBlockLabel",n=>this.exportSingleValue(this.getBlockLabel(this.vm.getString(n)),void 0)),i("getDataFromResultPool",n=>this.exportObjectUniversal(this.getDataFromResultPool(),void 0)),i("getDataWithErrorsFromResultPool",n=>this.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),i("getSpecsFromResultPool",n=>this.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),i("calculateOptions",n=>this.exportObjectUniversal(this.calculateOptions(this.importObjectViaJson(n)),void 0)),i("getSpecFromResultPoolByRef",(n,a)=>this.exportObjectUniversal(this.getSpecFromResultPoolByRef(this.vm.getString(n),this.vm.getString(a)),void 0)),i("getDataFromResultPoolByRef",(n,a)=>this.exportObjectUniversal(this.getDataFromResultPoolByRef(this.vm.getString(n),this.vm.getString(a)),void 0)),i("createPFrame",n=>this.exportSingleValue(this.createPFrame(this.importObjectViaJson(n)),void 0)),i("createPTable",n=>this.exportSingleValue(this.createPTable(this.importObjectViaJson(n)),void 0)),i("getCurrentUnstableMarker",()=>this.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}function $t(s,e){var t,r;return te((r=(t=s.traverse({field:R(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:d.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}))==null?void 0:t.getDataAsJson())==null?void 0:r.config,o=>C.extractConfig(o))}const le=process.env.MI_LOG_OUTPUT_STATUS;function Js(s,e,t,r,o={}){const i=`${e.blockId}#lambda#${t.handle}`;return o={...o,key:i},o.mode===void 0&&t.retentive===!0&&(o.mode="StableOnlyRetentive"),S.Computable.makeRaw(n=>{const a=new pe.Scope;n.addOnDestroy(()=>a.dispose());const c=a.manage(s.quickJs.newRuntime());c.setMemoryLimit(1024*640),c.setMaxStackSize(1024*320);const l=a.manage(c.newContext()),u=new fe(a,l,e,s,n);u.evaluateBundle(r.content);const p=u.runCallback(t.handle);u.resetComputableCtx();let h=0;return le&&le!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:u.computablesToResolve,postprocessValue:async(v,{unstableMarker:w,stable:P})=>{for(const[$,I]of Object.entries(v))u.runCallback($,I);const j=u.importObjectUniversal(p);return h++,le&&(le!=="unstable-only"||!P)&&console.log(P?`Stable output ${t.handle} calculated ${j!==void 0?"defined":"undefined"}; (#${h})`:`Unstable output ${t.handle}; marker = ${w}; ${j!==void 0?"defined":"undefined"} (#${h})`),j}}},o)}function Ms(s){return C.isConfigLambda(s)?s.isActive===!0:ls(s)}function re(s,e,t,r,o={}){if(C.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return Js(s,e,t,r,o)}else return Ls(s.driverKit,e,t,o)}function $s(s,e,t){return S.Computable.make(r=>{var w,P,j,$,I,H,z,ne;const o=r.accessor(s).node(),i=f.notEmpty(o.getKeyValueAsJson(Je)),n=f.notEmpty(o.getKeyValueAsJson(oe)),a=f.notEmpty(o.getKeyValueAsJson(ie)),c=f.notEmpty(o.getKeyValueAsJson(W)),l=f.notEmpty(o.getKeyValueAsJson(ge)),u=new Map;for(const{id:k}of M(c)){const V=o.traverse({field:R(k,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0});let Y;const A=o.traverse({field:R(k,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(A!==void 0){const x=o.getField({field:R(k,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),F=o.getField({field:R(k,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});Y={arguments:A.getDataAsJson(),stale:V.id!==A.id,outputError:x.error!==void 0||F.error!==void 0||((w=x.value)==null?void 0:w.getError())!==void 0||((P=F.value)==null?void 0:P.getError())!==void 0,outputsError:((j=x.error)==null?void 0:j.getDataAsString())??((I=($=x.value)==null?void 0:$.getError())==null?void 0:I.getDataAsString()),exportsError:((H=F.error)==null?void 0:H.getDataAsString())??((ne=(z=F.value)==null?void 0:z.getError())==null?void 0:ne.getDataAsString()),finished:(x.value!==void 0&&x.value.getIsReadyOrError()||x.error!==void 0&&x.error.getIsReadyOrError())&&(F.value!==void 0&&F.value.getIsReadyOrError()||F.error!==void 0&&F.error.getIsReadyOrError())}}u.set(k,{currentArguments:V.getDataAsJson(),prod:Y})}const p=ue(c,k=>u.get(k).currentArguments),h=new Set(l.blocksInLimbo),v=[...M(c)].map(({id:k,label:V,renderingMode:Y})=>{var ze,Ye,Qe,Ze;const A=f.notEmpty(u.get(k)),x=f.notEmpty(p.nodes.get(k));let F="NotCalculated";A.prod!==void 0&&(h.has(k)?F="Limbo":F=A.prod.finished?"Done":"Running");const _=o.traverse({field:R(k,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:d.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),L=_==null?void 0:_.getDataAsJson(),{sections:ae,title:b,inputsValid:B,sdkVersion:O}=te(L==null?void 0:L.config,we=>{const q=C.extractConfig(we),Se=_e(s,k);return{sections:re(t,Se,q.sections,q.code),title:te(q.title,Wt=>re(t,Se,Wt,q.code)),inputsValid:re(t,Se,q.inputsValid,q.code),sdkVersion:q.sdkVersion}})||{},qt=te(L,we=>t.blockUpdateWatcher.get(we.source));return{id:k,label:b??V,title:b??V,renderingMode:Y,stale:((ze=A.prod)==null?void 0:ze.stale)!==!1||F==="Limbo",missingReference:x.missingReferences,upstreams:[...p.traverseIdsExcludingRoots("upstream",k)],downstreams:[...p.traverseIdsExcludingRoots("downstream",k)],calculationStatus:F,outputErrors:((Ye=A.prod)==null?void 0:Ye.outputError)===!0,outputsError:(Qe=A.prod)==null?void 0:Qe.outputsError,exportsError:(Ze=A.prod)==null?void 0:Ze.exportsError,sections:ae,inputsValid:B,currentBlockPack:L==null?void 0:L.source,updatedBlockPack:qt,sdkVersion:O,navigationState:e.getState(k)}});return{meta:a,created:new Date(i),lastModified:new Date(n),authorMarker:o.getKeyValueAsJson(Be),blocks:v}},{postprocessValue:r=>{const o=new Set,i=new Set;return{...r,blocks:r.blocks.map(n=>{n.inputsValid||o.add(n.id),n.stale&&i.add(n.id);const a=n.stale||n.upstreams.findIndex(l=>i.has(l))!==-1,c=(a||n.outputErrors)&&!!n.inputsValid&&!n.missingReference&&n.upstreams.findIndex(l=>o.has(l))===-1;return{...n,canRun:c,stale:a}})}}}).withStableType()}function Ks(s,e){const t=s.node();if(d.resourceTypesEqual(t.resourceType,$e)){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(d.resourceTypesEqual(t.resourceType,Ke)){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 Gs(s,e){if(s!==void 0)return S.Computable.make(t=>Ks(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 _s(s,e,t){return S.Computable.make(r=>{var a;const o=r.accessor(s).node(),i=$t(o,e),n=(a=o.traverse({field:R(e,"blockPack"),assertFieldType:"Dynamic"},{field:d.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:Et,assertFieldType:"Input"}))==null?void 0:a.persist();return{path:Gs(n,t),sdkVersion:i==null?void 0:i.sdkVersion}},{mode:"StableOnlyLive"})}function Kt(s,e,t){if(t===void 0)return S.Computable.make(n=>Kt(s,e,n),{key:`inputs#${d.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),o=_e(s,e),i=o.uiState(t);return{author:r.getKeyValueAsJson(Fe(e)),args:JSON.parse(o.args(t)),ui:i!==void 0?JSON.parse(i):void 0}}function Hs(s,e,t){return S.Computable.make(r=>{const o=r.accessor(s).node(),i=It(s,e),n=$t(o,e);return te(n,a=>{const c={};for(const[l,u]of Object.entries(a.outputs)){const p=re(t,i,u,a.code);c[l]=S.Computable.wrapError(p),console.log(`${l}: ${p.___wrapped_kernel___.key}`)}return c})},{key:"outputs#"+d.resourceIdToString(s.rid)+"#"+e}).withStableType()}function qs(s,e){return S.Computable.make(t=>{const r=t.accessor(s).node(),o=f.notEmpty(r.getKeyValueAsJson(W)),i=[];for(const{id:n,renderingMode:a}of M(o)){const c=r.traverse({field:R(n,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:d.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),l=c==null?void 0:c.getDataAsJson();if((l==null?void 0:l.config)===void 0)continue;const u=C.extractConfig(l.config),p=Object.entries(u.outputs).map(([,v])=>v).filter(v=>Ms(v)).map(v=>v);if(p.length===0)continue;const h=It(r.persist(),n);for(const v of p)i.push(S.Computable.wrapError(re(e,h,v,u.code)))}return i})}class Ws{constructor(){g(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 S.ChangeSource});return}r.state={...t},r.change.markChanged()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...C.DefaultNavigationState},change:new S.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return S.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 be{constructor(e,t,r){g(this,"rid");g(this,"overview");g(this,"navigationStates",new Ws);g(this,"blockComputables",new Map);g(this,"blockFrontends",new Map);g(this,"activeConfigs");g(this,"refreshLoopResult");g(this,"abortController",new AbortController);g(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=$s(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=qs(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await Re(this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await ft.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(d.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!d.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,o=void 0,i=G.randomUUID()){const n=await this.env.bpPreparer.prepare(t),a=await this.env.bpPreparer.getBlockConfigContainer(t),c=C.extractConfig(a);return await J(this.env.pl,this.rid,o,l=>l.addBlock({id:i,label:e,renderingMode:c.renderingMode},{args:JSON.stringify(c.initialArgs),uiState:JSON.stringify(c.initialUiState),blockPack:n},r)),await this.projectTree.refreshState(),i}async updateBlockPack(e,t,r=!1,o){const i=await this.env.bpPreparer.prepare(t),n=await this.env.bpPreparer.getBlockConfigContainer(t);await J(this.env.pl,this.rid,o,a=>a.migrateBlockPack(e,i,r?JSON.stringify(n.initialArgs):void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await J(this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await J(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 i=o.groups[0];if(i.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${i.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const n={groups:[{id:i.id,label:i.label,blocks:e.map(a=>{const c=i.blocks.find(l=>l.id===a);if(c===void 0)throw new Error(`Can't find block: ${a}`);return c})}]};r.updateStructure(n)}),await this.projectTree.refreshState()}async runBlock(e){await Re(this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await Re(this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await J(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 J(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 J(this.env.pl,this.rid,o,i=>{i.setArgs([{blockId:e,args:JSON.stringify(t)}]),i.setUiState(e,JSON.stringify(r))}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async r=>{const o=d.ensureResourceIdNotNull((await r.getField(d.field(this.rid,R(e,"blockPack")))).value),i=d.ensureResourceIdNotNull((await r.getField(d.field(o,d.Pl.HolderRefField))).value),n=await r.getResourceData(i,!1),a=JSON.parse(Buffer.from(f.notEmpty(n.data)).toString("utf-8"));await J(r,this.rid,t,c=>{c.setArgs([{blockId:e,args:JSON.stringify(a.config.initialArgs)}]),c.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=Hs(this.projectTree.entry(),e,this.env),i={fullState:S.Computable.make(n=>({argsAndUiState:Kt(this.projectTree.entry(),e,n),outputs:r,navigationState:this.navigationStates.getState(e)}),{postprocessValue:n=>({...n.argsAndUiState,outputs:n.outputs,navigationState:n.navigationState})}).withPreCalculatedValueTree()};return this.blockComputables.set(e,i),i}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=_s(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 Ne.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:zs},e.logger);return new be(e,t,r)}}function zs(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 He={logger:new f.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 qe(s){return{blobDownloadPath:T.join(s,"download")}}const Gt={...He,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function _t(s){return{...qe(s),frontendDownloadPath:T.join(s,"frontend")}}const Ys={minDelay:1500},Qs="__no_updates__";class Zs extends S.PollComputablePool{constructor(t,r,o={}){super({...o,...Ys},r);g(this,"http");this.registryProvider=t,this.http=o.http}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 Qs}}async readValue(t){var r;try{switch(t.type){case"dev-v1":try{const o=await Ue(t.folder);return o===t.mtime?void 0:{...t,mtime:o}}catch(o){this.logger.warn(o);return}case"dev-v2":try{const o=await D.tryLoadPackDescription(t.folder,this.logger);if(o===void 0)return;const i=await me(o);return i===t.mtime?void 0:{...t,mtime:i}}catch(o){this.logger.warn(o);return}case"from-registry-v2":try{const o=this.registryProvider.getRegistry(t.registryUrl),i=(r=await o.getOverviewForSpec(t.id))==null?void 0:r.spec;if((i==null?void 0:i.type)!=="from-registry-v2")throw new Error("Unexpected");return ee.blockPackIdEquals(i.id,t.id)?void 0:((async()=>{try{await o.getComponents(i.id)}catch(n){this.logger.warn(n)}})(),i)}catch(o){this.logger.warn(o);return}default:return}}catch(o){this.logger.warn(o);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&&ee.blockPackIdEquals(t.id,r.id);case"from-registry-v2":return r.type!=="from-registry-v2"?!1:t.registryUrl===r.registryUrl&&ee.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:f.assertNever(t)}}}class dt{constructor(){g(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}}function pt(s){return String(s.id)}const Xs=["Int","Long","Float","Double","String","Bytes"];class eo{constructor(e,t,r){g(this,"pFrame",new rr.PFrame);g(this,"blobIdToResource",new Map);g(this,"blobHandleComputables",new Map);g(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue()});g(this,"resolveBlob",async e=>{const t=this.getOrCreateComputableForBlob(e);return this.blobDriver.getLocalPath((await t.awaitStableValue()).handle)});g(this,"resolveBlobContent",async e=>{const t=this.getOrCreateComputableForBlob(e),r=this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);return await this.blobContentCache.forceFetch(r)});this.blobDriver=e,this.blobContentCache=t,this.columns=r,this.pFrame.setDataSource(this);for(const o of r){for(const n of Zr(o.data))this.blobIdToResource.set(pt(n),n);const i=Xr(o.data,pt);try{this.pFrame.addColumnSpec(o.id,o.spec),this.pFrame.setColumnData(o.id,i)}catch(n){throw new Error(`Adding column ${o.id} to PFrame failed: ${n}; Spec: ${o.spec}, DataInfo: ${i}.`)}}}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 to{constructor(e){g(this,"pFrames");g(this,"pTables");g(this,"blobContentCache");g(this,"concurrencyLimiter");this.blobDriver=e;const t=new sr.LRUCache({maxSize:1e9,fetchMethod:async o=>await mt.readFile(o),sizeCalculation:o=>o.length}),r=new f.ConcurrencyLimitingExecutor(1);this.blobContentCache=t,this.concurrencyLimiter=r,this.pFrames=new class extends dt{constructor(o){super(),this.blobDriver=o}createNewResource(o){return new eo(this.blobDriver,t,o)}calculateParamsKey(o){return so(o)}}(this.blobDriver),this.pTables=new class extends dt{constructor(o){super(),this.pFrames=o}async createNewResource(o){const i=this.pFrames.getByKey(o.pFrameHandle),n=await r.run(async()=>await i.pFrame.createTable({src:se(o.def.src),filters:o.def.filters}));return o.def.sorting.length!==0?n.sort(o.def.sorting):n}calculateParamsKey(o){return ro(o)}}(this.pFrames)}createPFrame(e,t){const r=e.filter(i=>Xs.find(n=>n===i.spec.valueType)).map(i=>C.mapPObjectData(i,n=>is(n))),o=this.pFrames.acquire(r);return t.addOnDestroy(o.unref),o.key}createPTable(e,t){const r=this.createPFrame(oo(e.src),t),o=C.mapPTableDef(e,n=>n.id),i=this.pTables.acquire({def:o,pFrameHandle:r});return t.addOnDestroy(i.unref),i.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()=>await this.pFrames.getByKey(e).pFrame.createTable({src:se(t.src),filters:t.filters}));if(t.sorting.length>0){const n=await this.concurrencyLimiter.run(async()=>await r.sort(t.sorting));r.dispose(),r=n}const o=r.getSpec(),i=await this.concurrencyLimiter.run(async()=>await r.getData([...o.keys()]));return r.dispose(),o.map((n,a)=>({spec:n,data:i[a]}))}async getUniqueValues(e,t){return await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.getUniqueValues(t))}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 se(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=>se(e))};case"outer":return{type:"outer",primary:se(s.primary),secondary:s.secondary.map(e=>se(e))};default:f.assertNever(s)}}function ro(s){const e=G.createHash("sha256");return e.update(s.pFrameHandle),e.update(Ie(s.def)),e.digest().toString("hex")}function so(s){const e=s.map(o=>o.id).sort(),t=G.createHash("sha256");let r="";for(const o of e)r!==o&&(t.update(o),r=o);return t.digest().toString("hex")}function oo(s){const e=new Map;return de(s,e),[...e.values()]}function de(s,e){switch(s.type){case"column":e.set(s.column.id,s.column);return;case"full":case"inner":for(const t of s.entries)de(t,e);return;case"outer":de(s.primary,e);for(const t of s.secondary)de(t,e);return;default:f.assertNever(s)}}async function Ht(s,e,t){const r={...He,...qe(e),...t},o=new f.HmacSha256Signer(r.localSecret),i=U.createDownloadClient(r.logger,s,r.localProjections),n=U.createLogsClient(s,r.logger),a=U.createUploadBlobClient(s,r.logger),c=U.createUploadProgressClient(s,r.logger),l=new U.DownloadDriver(r.logger,i,n,r.blobDownloadPath,o,r.blobDriverOps),u=new U.UploadDriver(r.logger,o,a,c,r.uploadDriverOps),p=new U.LogsStreamDriver(r.logger,n,r.logStreamDriverOps),h=new U.LogsDriver(r.logger,p,l),v=await U.LsDriver.init(r.logger,s,o,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),w=new to(l);return{blobDriver:l,logDriver:h,lsDriver:v,signer:o,uploadDriver:u,pFrameDriver:w}}class We{constructor(e,t,r,o,i,n,a,c){g(this,"pl");g(this,"projectList");g(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=o,this.openedProjectsList=i,this.projectListTree=n,this.blockRegistryProvider=a,this.projectList=c,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=G.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async o=>{const i=await Qr(o,e);return o.createField(d.field(this.projectListResourceId,t),"Dynamic",i),await o.commit(),await d.toGlobalResourceId(i)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await J(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(d.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(d.field(this.projectListResourceId,e))).value;if(d.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 be.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 f.HmacSha256Signer.generateSecret()}static async init(e,t,r){const o={...Gt,..._t(t),...r};process.env.MI_LOG_TREE_STAT&&(o.defaultTreeOptions.logStat=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request");const i=await e.withWriteTx("MLInitialization",async P=>{const j=d.field(P.clientRoot,Br);P.createField(j,"Dynamic");const $=await P.getField(j);if(d.isNullResourceId($.value)){const I=P.createEphemeral(St);return P.lock(I),P.setField(j,I),await P.commit(),await I.globalId}else return $.value}),n=o.logger,a=await Ht(e,t,o),c=new K.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),l=new yt(c),u=new Gr(l,a.signer,c),p=new U.DownloadUrlDriver(n,e.httpDispatcher,o.frontendDownloadPath),h={pl:e,signer:a.signer,logger:n,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:c,ops:o,bpPreparer:u,frontendDownloadDriver:p,driverKit:a,blockUpdateWatcher:new Zs(l,n,{minDelay:o.devBlockUpdateRecheckInterval,http:c}),quickJs:await pe.getQuickJS()},v=new S.WatchableValue([]),w=await Tr(e,i,v,h);return new We(h,a,a.signer,i,v,w.tree,l,w.computable)}}const io=["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 no(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=[];io.forEach(c=>{or.channel(c).subscribe(u=>{var h;const p=new Date().toISOString();(h=u==null?void 0:u.response)!=null&&h.headers&&(u.response.headers=u.response.headers.map(v=>v.toString())),r.push(JSON.stringify({timestamp:p,event:c,data:u}))})});const o={plPings:[],blockRegistryOverviewChecks:[],blockGARegistryOverviewChecks:[],blockRegistryUiChecks:[],blockGARegistryUiChecks:[],autoUpdateCdnChecks:[]},i=d.plAddressToConfig(s,{defaultRequestTimeout:t.pingTimeoutMs});o.plPings=await Q(t.pingCheckDurationMs,t.maxPingsPerSecond,async()=>{const l=await new d.UnauthenticatedPlClient(i).ping();return JSON.stringify(l).slice(0,t.bodyLimit)+"..."});const a=new d.UnauthenticatedPlClient(i).ll.httpDispatcher;return o.blockRegistryOverviewChecks=await Q(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await X(new URL(t.blockOverviewPath,t.blockRegistryUrl),t,a)),o.blockGARegistryOverviewChecks=await Q(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await X(new URL(t.blockOverviewPath,t.blockGARegistryUrl),t,a)),o.blockRegistryUiChecks=await Q(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await X(new URL(t.blockUiPath,t.blockRegistryUrl),t,a)),o.blockGARegistryUiChecks=await Q(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await X(new URL(t.blockUiPath,t.blockGARegistryUrl),t,a)),o.autoUpdateCdnChecks=await Q(t.autoUpdateCdnDurationMs,t.maxAutoUpdateCdnChecksPerSecond,async()=>await X(t.autoUpdateCdnUrl,t,a)),ao(o,s,t,r)}async function Q(s,e,t){const r=Ae(),o=[];for(;gt(r)<s;){const i=Ae();let n;try{n={ok:!0,value:await t()}}catch(l){n={ok:!1,error:l}}const a=gt(i);o.push({elapsedMs:a,response:n});const c=1e3/e-a;c>0&&await ft.setTimeout(c)}return o}async function X(s,e,t){const{body:r,statusCode:o}=await K.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),i=await r.text();return{statusCode:o,beginningOfBody:i.slice(0,e.bodyLimit)+"..."}}function ao(s,e,t,r){const o=s.plPings.filter(a=>a.response.ok),i=s.plPings.filter(a=>!a.response.ok),n=[...new Set(o.map(a=>JSON.stringify(a.response.value)))];return`
1
+ "use strict";var zt=Object.defineProperty;var Yt=(o,e,t)=>e in o?zt(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var g=(o,e,t)=>Yt(o,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("@platforma-sdk/model"),te=require("@milaboratories/pl-model-middle-layer"),G=require("undici"),D=require("@platforma-sdk/block-tools"),A=require("node:fs"),T=require("node:path"),Qt=require("yaml"),f=require("@milaboratories/ts-helpers"),Zt=require("node:fs/promises"),Xt=require("@milaboratories/resolve-helper"),d=require("@milaboratories/pl-client"),Ne=require("@milaboratories/pl-tree"),S=require("@milaboratories/computable"),_=require("node:crypto"),mt=require("denque"),er=require("@platforma-sdk/workflow-tengo"),Ve=require("canonicalize"),tr=require("node:assert"),ge=require("quickjs-emscripten"),vt=require("node:timers/promises"),J=require("@milaboratories/pl-drivers"),rr=require("@milaboratories/pframes-node"),or=require("lru-cache"),sr=require("node:diagnostics_channel");function ir(o){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const t in o)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>o[t]})}}return e.default=o,Object.freeze(e)}const yt=ir(Zt);async function tt(o){try{return await yt.stat(o,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const nr=[D.RegistryV1.PlPackageYamlConfigFile],ar=[D.RegistryV1.PlPackageJsonConfigFile],Le=["backend","dist","tengo","tpl","main.plj.gz"],Ue=["config","dist","config.json"],bt=["frontend","dist"],rt="block-model/dist/config.json",cr="block-ui/package.json",ur=[Le,Ue,nr,ar,bt];async function lr(o){return await tt(T.join(o,...Ue))!==void 0||await tt(T.join(o,...Le))!==void 0}function Ce(o,e){const t=Xt.tryResolve(o,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${o}`);return t}async function ot(o,e){if(T.isAbsolute(o)||(o=T.resolve(o)),await lr(o))return{workflow:T.join(o,...Le),config:T.join(o,...Ue),ui:T.join(o,...bt)};{const t=Ce(o,rt),r=Ce(o,rt),s=Ce(o,cr);return{workflow:t,config:r,ui:T.resolve(s,"..","dist")}}}async function dr(o){try{return await A.promises.readFile(o,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}async function pr(o){try{return await A.promises.stat(o,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}async function Je(o){let e=0n;for(const t of ur){const r=T.join(o,...t),s=await pr(r);s!==void 0&&e<s.mtimeNs&&(e=s.mtimeNs)}return e.toString()}async function ve(o){const e=await A.promises.stat(o.components.workflow.main.file,{bigint:!0}),t=await A.promises.stat(o.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class gr{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 s=this.http!==void 0?{dispatcher:this.http}:{},n=await(await G.request(`${r.url}/${D.RegistryV1.GlobalOverviewPath}`,s)).body.json();for(const a of n){const{organization:c,package:u,latestMeta:l,latestVersion:p}=a,h={organization:c,name:u,version:p};t.push({registryId:e.id,id:h,meta:{title:l.title??"No title",description:l.description??"No Description",organization:{name:c,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:h,registryUrl:r.url},otherVersions:a.allVersions})}return t;case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(a=>({...a,registryId:e.id}));case"local-dev":for(const a of await A.promises.readdir(r.path,{withFileTypes:!0})){if(!a.isDirectory())continue;const c=T.join(r.path,a.name),u=await dr(T.join(c,D.RegistryV1.PlPackageYamlConfigFile));if(u!==void 0){const l=D.RegistryV1.PlPackageConfigData.parse(Qt.parse(u)),p=await Je(c),h={organization:l.organization,name:l.package,version:"DEV"};t.push({registryId:e.id,id:h,meta:{title:l.meta.title??"No title",description:l.meta.description??"No Description",organization:{name:l.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:c,mtime:p},otherVersions:[]})}else{let l=c,p=await D.tryLoadPackDescription(l);if(p===void 0){for(const h of["block","meta"])if(l=T.join(c,h),p=await D.tryLoadPackDescription(l),p!==void 0)break}if(p!==void 0){const h=await ve(p);t.push({registryId:e.id,id:p.id,meta:await D.BlockPackMetaEmbedAbsoluteBytes.parseAsync(p.meta),spec:{type:"dev-v2",folder:l,mtime:h},otherVersions:[]})}}}return t;default:return f.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}}}class wt{constructor(e){g(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new D.RegistryV2Reader(D.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const hr={type:"remote-v2",url:"https://blocks.pl-open.science/"},fr={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},mr={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},vr={groups:[{id:"default",label:"Default",blocks:[]}]},yr={stagingRefreshTimestamp:0,blocksInLimbo:[]},br={label:"New Project"},wr={name:"UserProject",version:"2"},St="SchemaVersion",kt="1",Me="ProjectCreated",ie="ProjectLastModified",ne="ProjectMeta",q="ProjectStructure",he="BlockRenderingState",Sr="BlockFrontendState/",kr=/^BlockFrontendState\/(?<blockid>.*)$/;function Be(o){return`${Sr}${o}`}const Cr="BlockArgsAuthor/";function Fe(o){return`${Cr}${o}`}const De="ProjectStructureAuthor";function Pr(o){const e=o.match(kr);if(e!==null)return e.groups.blockid}const Rr="__serviceTemplate_";function Te(o){return`${Rr}${o}`}function F(o,e){return`${o}-${e}`}const Or=/^(?<blockId>.*)-(?<fieldName>blockPack|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function Br(o){const e=o.match(Or);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const Fr="projects",Ct={name:"Projects",version:"1"},Dr=o=>d.resourceTypesEqual(o.type,Ct)?o.fields:[];async function Tr(o,e,t,r){const s=await Ne.SynchronizedTreeState.init(o,e,{...r.ops.defaultTreeOptions,pruning:Dr},r.logger);return{computable:S.Computable.make(n=>{const a=n.accessor(s.entry()).node(),c=t.getValue(n);if(a===void 0)return;const u=[];for(const l of a.listDynamicFields()){const p=a.traverse(l);if(p===void 0)continue;const h=f.notEmpty(p.getKeyValueAsJson(ne)),y=f.notEmpty(p.getKeyValueAsJson(Me)),b=f.notEmpty(p.getKeyValueAsJson(ie));u.push({id:l,rid:p.id,created:new Date(y),lastModified:new Date(b),opened:c.indexOf(p.id)>=0,meta:h})}return u.sort(l=>-l.lastModified.valueOf()),u}).withStableType(),tree:s}}const xr={name:"EphRenderTemplate",version:"1"},Er={name:"RenderTemplate",version:"1"};function $e(o,e,t,r,s){if(s.length===0)throw new Error("Zero output names provided");const i=t?o.createEphemeral(xr):o.createStruct(Er),n=d.field(i,"template"),a=d.field(i,"inputs");return o.createField(n,"Input",e),o.createField(a,"Input",d.Pl.createPlMap(o,r,t)),o.lockInputs(i),d.Pl.futureRecord(o,i,s,"Output","outputs/")}const jr={name:"BContextEnd",version:"1"},Ar={name:"BContext",version:"1"},Ir="id",Nr="parent/",Vr=["context","result"];function st(o,e,t){return $e(o,e,!0,t,Vr)}function Lr(o){const e=o.createEphemeral(jr);return o.lock(e),e}function Ur(o,e){if(e.length===0)return Lr(o);if(e.length===1)return e[0];const t=o.createEphemeral(Ar);o.createField(d.field(t,Ir),"Input",d.Pl.createPlString(o,_.randomUUID()));for(let r=0;r<e.length;r++)o.createField(d.field(t,`${Nr}${r}`),"Input",e[r]);return o.lock(t),t}const Pt={name:"TengoTemplateGet",version:"1"},Rt="registry",Ot="templateURI",Bt="template",Ft={name:"TengoTemplatePack",version:"1"},Dt={name:"TengoTemplatePackConvert",version:"1"},Tt="templatePack",xt="template";async function Et(o){switch(o.type){case"from-file":return{type:"explicit",content:await A.promises.readFile(o.path)};case"from-registry":case"explicit":return o;default:return f.assertNever(o)}}function Jr(o,e){const t=o.createStruct(Pt),r=d.field(t,Rt),s=d.field(t,Ot),i=d.field(t,Bt);return o.setField(r,o.createValue(d.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),o.setField(s,o.createValue(d.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),i}function Mr(o,e){const t=o.createValue(Ft,e.content),r=o.createStruct(Dt),s=d.field(r,Tt),i=d.field(r,xt);return o.setField(s,t),i}function ye(o,e){switch(e.type){case"from-registry":return Jr(o,e);case"explicit":return Mr(o,e);default:return f.assertNever(e)}}const Ke={name:"Frontend/FromUrl",version:"1"},Ge={name:"Frontend/FromFolder",version:"1"};function $r(o,e){switch(e.type){case"url":return o.createValue(Ke,JSON.stringify({url:e.url}));case"local":return o.createValue(Ge,JSON.stringify({path:e.path,signature:e.signature}));default:return f.assertNever(e)}}const Kr={name:"BlockPackCustom",version:"1"},jt="template",At="frontend";function it(o){return o.endsWith("/")?o:`${o}/`}class Gr{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 ot(e.folder),r=await A.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await D.loadPackDescription(e.folder),r=await A.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=`${it(e.registryUrl)}${D.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`;return await(await G.request(`${r}/config.json`,t)).body.json()}case"from-registry-v2":{const t=this.http!==void 0?{dispatcher:this.http}:{},s=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id);return await(await G.request(s.model.url,t)).body.json()}default:return f.assertNever(e)}}async prepare(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await ot(e.folder),r=await A.promises.readFile(t.workflow),s=JSON.parse(await A.promises.readFile(t.config,"utf-8")),i=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:s,frontend:{type:"local",path:i,signature:this.signer.sign(i)},source:e}}case"dev-v2":{const t=await D.loadPackDescription(e.folder),r=JSON.parse(await A.promises.readFile(t.components.model.file,{encoding:"utf-8"})),s=await A.promises.readFile(t.components.workflow.main.file),i=t.components.ui.folder,n={...e};return e.mtime===void 0&&(n.mtime=await ve(t)),{type:"explicit",template:{type:"explicit",content:s},config:r,frontend:{type:"local",path:i,signature:this.signer.sign(i)},source:n}}case"from-registry-v1":{const t=this.http!==void 0?{dispatcher:this.http}:{},r=`${it(e.registryUrl)}${D.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,s=`${r}/template.plj.gz`,i=await G.request(s,t);if(i.statusCode!==200)throw new Error(`Block not found in registry (url = ${s} ; code = ${i.statusCode}): `+JSON.stringify(e));const n=new Uint8Array(await i.body.arrayBuffer()),c=await(await G.request(`${r}/config.json`,t)).body.json();return{type:"explicit",template:{type:"explicit",content:n},config:c,frontend:{type:"url",url:`${r}/frontend.tgz`},source:e}}case"from-registry-v2":{const t=this.http!==void 0?{dispatcher:this.http}:{},s=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),i=async()=>await(await G.request(s.model.url,t)).body.json(),n=async()=>await(await G.request(s.workflow.main.url,t)).body.arrayBuffer(),[a,c]=await Promise.all([i(),n()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(c)},config:a,frontend:{type:"url",url:s.ui.url},source:e}}default:return f.assertNever(e)}}}function _r(o,e){const t={config:e.config,source:e.source},r=o.createStruct(Kr,JSON.stringify(t));return o.createField(d.field(r,jt),"Input",ye(o,e.template)),o.createField(d.field(r,At),"Input",$r(o,e.frontend)),o.lock(r),r}function nt(o,e){switch(e.type){case"explicit":return _r(o,e);default:return f.assertNever(e.type)}}function ue(o,e){return{__isRef:!0,blockId:o,name:e}}function Hr(o){return typeof o=="object"&&o!==null&&o.__isRef===!0&&"blockId"in o&&"name"in o}function xe(o,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(Hr(e))t===void 0||t.has(e.blockId)?o.upstreams.add(e.blockId):o.missingReferences=!0;else if(Array.isArray(e))for(const s of e)xe(o,s,t);else for(const[,s]of Object.entries(e))xe(o,s,t);return;default:f.assertNever(r)}}function qr(o,e){const t={upstreams:new Set,missingReferences:!1};return xe(t,o,e),t}function $(o){return{*[Symbol.iterator](){for(const e of o.groups)for(const t of e.blocks)yield t}}}class It{constructor(e){g(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,s=>r.add(s.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const s of t)r.delete(s);return r}traverse(e,t,r){let s=[...t];const i=new Set(s);for(;s.length>0;){let n=[];for(const a of s){const c=this.nodes.get(a);r(c),c[e].forEach(u=>{i.has(u)||(i.add(u),n.push(u))})}s=n}}}function Ee(o){const e=new Map;let t;for(const{id:r}of $(o)){const s={id:r,missingReferences:!1};e.set(r,s),t===void 0?s.upstream=new Set:(s.upstream=new Set([t.id]),t.downstream=new Set([s.id])),t=s}return t!==void 0&&(t.downstream=new Set),new It(e)}function de(o,e){const t=new Map,r=new Set;for(const{id:s}of $(o)){const i=e(s);if(i===void 0)continue;const n=qr(i,r),a={id:s,missingReferences:n.missingReferences,upstream:n.upstreams,downstream:new Set};t.set(s,a),n.upstreams.forEach(c=>t.get(c).downstream.add(s)),r.add(s)}return new It(t)}function Wr(o,e){if(o.size!==e.size)return!1;for(const t of o)if(!e.has(t))return!1;return!0}function je(o,e){if(o.size>e.size)return je(e,o);for(const t of o)if(e.has(t))return!0;return!1}function at(o,e){const t=new Set,r=new Set,s=new Set;return o.nodes.forEach(i=>{const n=e.nodes.get(i.id);n===void 0?t.add(i.id):(!Wr(i.upstream,n.upstream)||je(i.upstream,s))&&s.add(i.id)}),e.nodes.forEach(i=>{o.nodes.has(i.id)?je(i.upstream,s)&&s.add(i.id):r.add(i.id)}),{onlyInA:t,onlyInB:r,different:s}}let Pe;async function Nt(){if(Pe===void 0){const o=await Et(er.Templates["pframes.export-pframe"]);if(o.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=_.createHash("sha256").update(o.content).digest("hex");Pe={spec:o,hash:e}}return Pe}function zr(o,e,t){return $e(o,e,!0,{pf:t},["result"]).result}function Re(o,e){let t=!1,r,s;return()=>{if(!t)return t=!0,r=o(),s=e(),s;const i=o();return r!==i&&(r=i,s=e()),e()}}class ct{constructor(e,t){g(this,"currentInputsC",Re(()=>this.fields.currentArgs.modCount,()=>JSON.parse(Buffer.from(this.fields.currentArgs.value).toString())));g(this,"actualProductionInputsC",Re(()=>{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())}));g(this,"productionStaleC",Re(()=>{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(d.Pl.unwrapHolder(e,this.fields.blockPack.ref),jt,"Input")}}const Yr=o=>{throw new Error(`No new block info for ${o}`)};class fe{constructor(e,t,r,s,i,n,a,c,u,l,p,h){g(this,"globalModCount",0);g(this,"fieldsChanged",!1);g(this,"lastModifiedChanged",!1);g(this,"structureChanged",!1);g(this,"metaChanged",!1);g(this,"renderingStateChanged",!1);g(this,"changedBlockFrontendStates",new Set);g(this,"blocksWithChangedInputs",new Set);g(this,"stagingGraph");g(this,"pendingProductionGraph");g(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=s,this.lastModified=i,this.meta=n,this.struct=a,this.renderingState=c,this.blocksInLimbo=u,this.blockInfos=l,this.blockFrontendStates=p,this.ctxExportTplHolder=h}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=Ee(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 f.notEmpty(this.blockInfos.get(e))}getBlock(e){for(const t of $(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const s=d.field(this.rid,F(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(s,"Dynamic",r.ref):this.tx.setField(s,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,s,i){this.setBlockFieldObj(e,t,{ref:r,status:s,value:i})}deleteBlockFields(e,...t){let r=!1;const s=this.getBlockInfo(e);for(const i of t){const n=s.fields;i in n&&(this.tx.removeField(d.field(this.rid,F(e,i))),delete n[i],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,s,i;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((s=t.stagingCtx)==null?void 0:s.status)==="Ready"&&((i=t.stagingUiCtx)==null?void 0:i.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,s,i;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((s=t.prodCtx)==null?void 0:s.status)==="Ready"&&((i=t.prodUiCtx)==null?void 0:i.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,s;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((s=t.prodCtx)==null?void 0:s.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:s}of e){const i=this.getBlockInfo(r);JSON.parse(s);const n=Buffer.from(s);if(Buffer.compare(i.fields.currentArgs.value,n)===0)continue;const a=this.tx.createValue(d.Pl.JsonObject,n);this.setBlockField(r,"currentArgs",a,"Ready",n),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(s=>{const i=this.getBlockInfo(s);if(i.fields[t]===void 0||i.fields[t].ref===void 0)throw new Error("One of the upstreams staging is not rendered.");r.push(d.Pl.unwrapHolder(this.tx,i.fields[t].ref))}),Ur(this.tx,r)}exportCtx(e){return zr(this.tx,d.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 s=t.getTemplate(this.tx),i=st(this.tx,s,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(d.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(d.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",d.Pl.wrapInEphHolder(this.tx,i.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(i.context),"NotReady"),this.setBlockField(e,"stagingOutput",i.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 s=t.getTemplate(this.tx),i=st(this.tx,s,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(d.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(d.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",d.Pl.wrapInEphHolder(this.tx,i.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(i.context),"NotReady"),this.setBlockField(e,"prodOutput",i.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=Yr){const r=this.getStagingGraph(),s=this.getActualProductionGraph(),i=Ee(e),n=de(e,u=>{var l;return(l=this.blockInfos.get(u))==null?void 0:l.actualProductionInputs}),a=at(r,i),c=at(s,n);for(const u of a.onlyInA){const{fields:l}=this.getBlockInfo(u);this.deleteBlockFields(u,...Object.keys(l)),this.blockInfos.delete(u),this.blocksInLimbo.delete(u)&&(this.renderingStateChanged=!0),this.blockFrontendStates.delete(u)&&this.changedBlockFrontendStates.add(u)}for(const u of a.onlyInB){const l=new ct(u,{});this.blockInfos.set(u,l);const p=t(u),h=nt(this.tx,p.blockPack);this.setBlockField(u,"blockPack",d.Pl.wrapInHolder(this.tx,h),"NotReady");const y=Buffer.from(p.args),b=this.tx.createValue(d.Pl.JsonObject,y);this.setBlockField(u,"currentArgs",b,"Ready",y),p.uiState&&(this.blockFrontendStates.set(u,p.uiState),this.changedBlockFrontendStates.add(u)),l.check()}for(const u of a.different)this.resetStaging(u);s.traverse("downstream",[...c.different],u=>{this.resetOrLimboProduction(u.id)}),(a.onlyInB.size>0||a.onlyInA.size>0||a.different.size>0)&&this.resetStagingRefreshTimestamp(),this.struct=e,this.structureChanged=!0,this.stagingGraph=void 0,this.pendingProductionGraph=void 0,this.actualProductionGraph=void 0,this.updateLastModified()}addBlock(e,t,r){const s=this.structure;if(r===void 0)s.groups[s.groups.length-1].blocks.push(e);else{let i=!1;for(const n of s.groups){const a=n.blocks.findIndex(c=>c.id===r);if(!(a<0)){n.blocks.splice(a,0,e),i=!0;break}}if(!i)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(s,i=>{if(i!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const s of t.groups){const i=s.blocks.findIndex(n=>n.id===e);if(!(i<0)){s.blocks.splice(i,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const s=this.getBlockInfo(e);this.setBlockField(e,"blockPack",d.Pl.wrapInHolder(this.tx,nt(this.tx,t)),"NotReady"),r!==void 0?(this.setArgs([{blockId:e,args:r}]),this.setUiState(e,void 0)):this.getStagingGraph().traverse("downstream",[e],({id:i})=>this.resetStaging(i)),s.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:i})=>this.resetOrLimboProduction(i)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),s=this.getPendingProductionGraph();if(t)s.traverse("upstream",e,n=>{r.add(n.id)});else for(const n of r){const a=s.nodes.get(n);if(a===void 0)throw new Error(`Can't find block with id: ${n}`);for(const c of a.upstream)if(!r.has(c))throw new Error("Can't render blocks not including all upstreams.")}const i=new Set;for(const n of $(this.structure)){if(!r.has(n.id))continue;let a=this.getBlockInfo(n.id).requireProductionRendering||this.blocksInLimbo.has(n.id);if(!a){for(const c of s.nodes.get(n.id).upstream)if(i.has(c)){a=!0;break}}a&&(this.renderProductionFor(n.id),i.add(n.id))}return s.traverse("downstream",[...i],n=>{i.has(n.id)||this.resetOrLimboProduction(n.id)}),i.size>0&&this.updateLastModified(),i}stopProduction(...e){var n,a;const t=this.getActualProductionGraph(),r=new mt(e),s=new Set(e),i=[];for(;!r.isEmpty();){const c=r.shift(),u=this.getBlockInfo(c).fields;if(!(((n=u.prodOutput)==null?void 0:n.status)==="Ready"&&((a=u.prodCtx)==null?void 0:a.status)==="Ready")&&this.deleteBlockFields(c,"prodOutput","prodCtx","prodUiCtx","prodArgs")){i.push(c);for(const l of t.traverseIdsExcludingRoots("downstream",c))s.has(l)||(r.push(l),s.add(l))}}for(const c of t.traverseIdsExcludingRoots("downstream",...i))this.resetOrLimboProduction(c)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(s=>{let n=this.getBlockInfo(s.id).stagingRendered?0:1;s.upstream.forEach(a=>{const c=t.get(a);c!==0&&(n=Math.max(c+1,n))}),e(s.id,n),t.set(s.id,n)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,r=e===void 0?void 0:1+Math.max(0,t*e/1e3);let s=0;this.traverseWithStagingLag((i,n)=>{n!==0&&(r===void 0||n<=r)&&(this.renderStagingFor(i),s++)}),s>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,s,i,n;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((s=t.fields.prodOutput)==null?void 0:s.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((i=t.fields.stagingCtx)==null?void 0:i.status)==="Ready"&&((n=t.fields.stagingOutput)==null?void 0:n.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,Fe(t)):this.tx.setKValue(this.rid,Fe(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,De):this.tx.setKValue(this.rid,De,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,ie,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,q,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,he,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,ne,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,Be(e)):this.tx.setKValue(this.rid,Be(e),t)}this.assignAuthorMarkers()}}static async load(e,t,r){const s=e.getResourceData(t,!0),i=e.getKValueJson(t,St),n=e.getKValueJson(t,ie),a=e.getKValueJson(t,ne),c=e.getKValueJson(t,q),u=e.getKValueJson(t,he),l=e.listKeyValuesString(t),[p,h,y,b,C,{stagingRefreshTimestamp:I,blocksInLimbo:N},V]=await Promise.all([s,i,n,a,c,u,l]);if(h!==kt)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${h}`);const K=new Map;for(const w of p.fields){const B=Br(w.name);if(B===void 0)continue;let R=K.get(B.blockId);R===void 0&&(R={id:B.blockId,fields:{}},K.set(B.blockId,R)),R.fields[B.fieldName]=d.isNullResourceId(w.value)?{modCount:0}:{modCount:0,ref:w.value}}const W=await Nt(),ae=Te(W.hash),k=p.fields.find(w=>w.name===ae);let L;k!==void 0?L=d.ensureResourceIdNotNull(k.value):(L=d.Pl.wrapInHolder(e,ye(e,W.spec)),e.createField(d.field(t,Te(W.hash)),"Dynamic",L));const z={stagingRefreshTimestamp:I},j=new Set(N),x=new Map;for(const w of V){const B=Pr(w.key);B!==void 0&&x.set(B,w.value)}const O=[];K.forEach(({id:w,fields:B})=>{for(const[,R]of Object.entries(B))if(R.ref!==void 0){if(!d.isResource(R.ref)||d.isResourceRef(R.ref))throw new Error("unexpected behaviour");O.push([R,e.getResourceData(R.ref,!1)])}});for(const[w,B]of O){const R=await B;w.value=R.data,d.isNotNullResourceId(R.error)?w.status="Error":R.resourceReady||d.isNotNullResourceId(R.originalResourceId)?w.status="Ready":w.status="NotReady"}const U=new Map;K.forEach(({id:w,fields:B})=>U.set(w,new ct(w,B)));const ce=new Set;for(const w of $(C)){if(!U.has(w.id))throw new Error(`Inconsistent project structure: no inputs for ${w.id}`);ce.add(w.id)}U.forEach(w=>{if(!ce.has(w.id))throw new Error(`Inconsistent project structure: no structure entry for ${w.id}`);w.check()});const Z=new fe(t,e,r,h,y,b,C,z,j,U,x,L);return Z.fixProblems(),Z}}async function Qr(o,e=br){const t=o.createEphemeral(wr);o.lock(t);const r=String(Date.now());o.setKValue(t,St,JSON.stringify(kt)),o.setKValue(t,Me,r),o.setKValue(t,ie,r),o.setKValue(t,ne,JSON.stringify(e)),o.setKValue(t,q,JSON.stringify(vr)),o.setKValue(t,he,JSON.stringify(yr));const s=await Nt();return o.createField(d.field(t,Te(s.hash)),"Dynamic",d.Pl.wrapInHolder(o,ye(o,s.spec))),t}async function Oe(o,e,t){return M(o,e,void 0,t)}async function M(o,e,t,r){if(o instanceof d.PlClient)return await o.withWriteTx("ProjectAction",async s=>{const i=await fe.load(s,e,t),n=await r(i);return i.wasModified&&(i.save(),await s.commit()),n});{const s=await fe.load(o,e,t),i=await r(s);return s.save(),i}}function*Zr(o){switch(o.type){case"Json":return;case"JsonPartitioned":for(const[,e]of Object.entries(o.parts))yield e;return;case"BinaryPartitioned":for(const[,{index:e,values:t}]of Object.entries(o.parts))yield e,yield t;return;default:f.assertNever(o)}}function ut(o,e){return Object.fromEntries(Object.entries(o).map(([t,r])=>[t,e(r,t)]))}function Xr(o,e){switch(o.type){case"Json":return{...o};case"JsonPartitioned":return{...o,parts:ut(o.parts,e)};case"BinaryPartitioned":return{...o,parts:ut(o.parts,t=>({index:e(t.index),values:e(t.values)}))};default:f.assertNever(o)}}const eo=d.resourceType("PColumnData/JsonPartitioned","1"),to=d.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),ro=d.resourceType("PColumnData/BinaryPartitioned","1"),oo=d.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),so=d.resourceType("PColumnData/Json","1");function io(o){if(!o.getIsReadyOrError())throw new Error("Data not ready.");const e=o.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(d.resourceTypesEqual(o.resourceType,so)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(d.resourceTypesEqual(o.resourceType,eo)){const t=e,r=Object.fromEntries(o.listInputFields().map(s=>[s,o.traverse({field:s,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(d.resourceTypesEqual(o.resourceType,to)){const t=e,r={};for(const s of o.listInputFields()){const i=o.traverse({field:s,errorIfFieldNotSet:!0}),n=i.listInputFields();if(n===void 0)throw new Error(`no partition keys for super key ${s}`);for(const a of n){const c=JSON.stringify([...JSON.parse(s),...JSON.parse(a)]);r[c]=i.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(d.resourceTypesEqual(o.resourceType,ro)){const t=e,r={};for(const s of o.listInputFields())if(s.endsWith(".index")){const i=s.slice(0,s.length-6);let n=r[i];n===void 0&&(n={},r[i]=n),n.index=o.traverse({field:s,errorIfFieldNotSet:!0}).resourceInfo}else if(s.endsWith(".values")){const i=s.slice(0,s.length-7);let n=r[i];n===void 0&&(n={},r[i]=n),n.values=o.traverse({field:s,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${s}`);for(const[s,i]of Object.entries(r)){if(i.index===void 0)throw new Error(`no index for part ${s}`);if(i.values===void 0)throw new Error(`no values for part ${s}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(d.resourceTypesEqual(o.resourceType,oo)){const t=e,r={};for(const s of o.listInputFields()){const i=o.traverse({field:s,errorIfFieldNotSet:!0}),n=i.listInputFields();if(n===void 0)throw new Error(`no partition keys for super key ${s}`);for(const a of n)if(a.endsWith(".index")){const c=a.slice(0,a.length-6),u=JSON.stringify([...JSON.parse(s),...JSON.parse(c)]);let l=r[u];l===void 0&&(l={},r[u]=l),r[u].index=i.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else if(a.endsWith(".values")){const c=a.slice(0,a.length-7),u=JSON.stringify([...JSON.parse(s),...JSON.parse(c)]);let l=r[u];l===void 0&&(l={},r[u]=l),r[u].values=i.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${a}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}throw new Error(`unsupported resource type: ${d.resourceTypeToString(o.resourceType)}`)}function Ae(o,e){const t=_.createHash("sha256");return t.update(Ve(o)),t.update(String(d.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function Vt(o,e=!0,t=!1,r=""){var a,c,u;const s=/^(?<name>.*)\.(?<type>spec|data)$/,i=new Map;for(const l of o.listInputFields()){const p=l.match(s);if(!p){if(e)throw new Error(`unexpected field name ${l}`);continue}let h=f.notEmpty((a=p.groups)==null?void 0:a.name);if(!h.startsWith(r)){if(e)throw new Error(`unexpected field name ${l}`);continue}h=h.slice(r.length);const y=f.notEmpty((c=p.groups)==null?void 0:c.type);let b=i.get(h);switch(b===void 0&&(b={},i.set(h,b)),y){case"spec":b.spec=(u=o.traverse({field:l,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:u.getDataAsJson();break;case"data":b.hasData=!0,b.data=()=>o.traverseOrError({field:l,ignoreError:t});default:continue}}const n=o.getInputsLocked();if(n)for(const[,l]of i)l.data===void 0&&(l.hasData=!1);return{locked:n,results:i}}function no(o,e=!0,t=""){if(!o.getIsReadyOrError())throw new Error("resource is not ready");const r=Vt(o,e,!1,t);tr(r.locked);const s={};for(const[i,n]of r.results){if(n.spec===void 0)throw new Error(`no spec for key ${i}`);if(n.hasData!==!0||n.data===void 0)throw new Error(`no data for key ${i}`);const a=n.data();if(a===void 0)throw new Error(`no data for key ${i}`);if(!a.ok)throw new Ne.PlError(a.error);s[i]={id:Ae(n.spec,a.value),spec:n.spec,data:a.value}}return s}class _e{constructor(e,t){g(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const s of t.values())for(const i of[s.prod,s.staging])if(i!==void 0){if(!i.locked){r=!1;break e}for(const n of i.results.values())if(n.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var i,n,a,c,u,l;const r=this.blocks.get(e);if(r===void 0)return;let s=(a=(n=(i=r.prod)==null?void 0:i.results)==null?void 0:n.get(t))==null?void 0:a.spec;if(s!==void 0||(s=(l=(u=(c=r.staging)==null?void 0:c.results)==null?void 0:u.get(t))==null?void 0:l.spec,s!==void 0))return s;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 n,a,c;const r=this.blocks.get(e);if(r===void 0)return;let s=(a=(n=r.prod)==null?void 0:n.results)==null?void 0:a.get(t),i=(c=s==null?void 0:s.data)==null?void 0:c.call(s);if(s!==void 0&&s.spec!==void 0&&i!==void 0)return P.mapValueInVOE(i,u=>({id:Ae(s.spec,u),spec:s.spec,data:u}));s!==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 s=n=>{r===void 0&&(r=n),t=!1},i=(n,a,c)=>{if(c.spec!==void 0&&c.hasData===!0&&c.data!==void 0){const u=c.data();u!==void 0?e.push({ref:ue(n,a),obj:{id:u.ok?Ae(c.spec,u.value):void 0,spec:c.spec,data:u}}):s(`no_data:${n}:${a}`)}};for(const[n,a]of this.blocks){const c=new Set;if(a.prod!==void 0){a.prod.locked||s(`prod_not_locked:${n}`);for(const[u,l]of a.prod.results)c.add(u),i(n,u,l)}if(a.staging!==void 0){a.staging.locked||s(`staging_not_locked:${n}`);for(const[u,l]of a.staging.results)c.has(u)||i(n,u,l)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const s=i=>{r===void 0&&(r=i),t=!1};for(const[i,n]of this.blocks){const a=new Set;if(n.staging!==void 0){n.staging.locked||s(`staging_not_locked:${i}`);for(const[c,u]of n.staging.results)u.spec!==void 0&&(e.push({ref:ue(i,c),obj:u.spec}),a.add(c))}else s(`staging_not_rendered:${i}`);if(n.prod!==void 0){n.prod.locked||s(`prod_not_locked:${i}`);for(const[c,u]of n.prod.results)a.has(c)||u.spec!==void 0&&e.push({ref:ue(i,c),obj:u.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const s=new Set,i=n=>{for(const[a,c]of n.results)s.has(a)||c.spec===void 0||(s.add(a),P.executePSpecPredicate(e,c.spec)&&t.push({label:r.info.label+" / "+a,ref:ue(r.info.id,a),spec:c.spec}))};r.staging!==void 0&&i(r.staging),r.prod!==void 0&&i(r.prod)}return t}static create(e,t,r){const s=e.accessor(t).node(),i=f.notEmpty(s.getKeyValueAsJson(q)),a=Ee(i).traverseIds("upstream",r),c=new Map;for(const u of $(i)){if(!a.has(u.id))continue;const l=lt(s.traverse({field:F(u.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,s.traverseOrError({field:F(u.id,"prodUiCtx"),stableIfNotFound:!0})),p=lt(s.traverse({field:F(u.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,s.traverseOrError({field:F(u.id,"stagingUiCtx")}));c.set(u.id,{info:u,prod:l,staging:p})}return new _e(e,c)}}function lt(o,e){if(e===void 0)return o?{locked:!1,results:new Map}:void 0;if(e.ok)return Vt(e.value,!1,!0)}function He(o,e){return{blockId:e,args:s=>f.notEmpty(s.accessor(o).node().traverse({field:F(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),uiState:s=>s.accessor(o).node().getKeyValueAsString(Be(e)),blockMeta:s=>{const i=s.accessor(o).node(),n=f.notEmpty(i.getKeyValueAsJson(q)),a=new Map;for(const c of $(n))a.set(c.id,c);return a}}}function Lt(o,e){return{...He(o,e),prod:t=>{var r;return(r=t.accessor(o).node({ignoreError:!0}).traverse({field:F(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:r.persist()},staging:t=>{var s;const r=(s=t.accessor(o).node({ignoreError:!0}).traverse({field:F(e,"stagingOutput"),ignoreError:!0}))==null?void 0:s.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>_e.create(t,o,e)}}function*E(o,e){switch(yield o,o.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*E(o.cfg);return;case"MakeObject":for(const[,t]of Object.entries(o.template))yield*E(t);return;case"MakeArray":for(const t of o.template)yield*E(t);return;case"GetJsonField":case"GetResourceField":yield*E(o.source),yield*E(o.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*E(o.source),yield*E(o.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*E(o.source);return;case"IsEmpty":yield*E(o.arg);return;case"Not":yield*E(o.operand);return;case"And":case"Or":yield*E(o.operand1),yield*E(o.operand2);return;default:f.assertNever(o)}}function ao(o,e){const t={};for(const[r,s]of Object.entries(o))t[r]=e(s);return t}function re(o,e){return o===void 0?void 0:e(o)}function co(o){switch(o.type){case"GetImportProgress":return!0;default:return!1}}function uo(o){for(const e of E(o))if(co(e))return!0;return!1}function be(o){return{type:"ReturnResult",result:o}}function m(o){return()=>be(o)}const lo=o=>{const e={};for(const[t,r]of Object.entries(o))e[t]=r;return m(e)},po=o=>{const e=o.source;if(e===void 0)return m(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return m(t)},go=o=>{const e=o.source,t=o.field;return e===void 0||t===void 0?m(void 0):({cCtx:r})=>{var s;return be((s=r.accessor(e).node().traverse(t))==null?void 0:s.persist())}};function Ut(o,e){const t={},r=o.length;for(let s=0;s<r;s++)t[String(s)]=e(o[s]);return t}function ho(o,e){return t=>{const r=t.source;return r===void 0?m(void 0):()=>({type:"ScheduleSubroutine",subroutine:Jt(r.length),args:Ut(r,s=>v({...o,[e.itVar]:s},e.mapping))})}}function Jt(o){return e=>{const t=[];for(let r=0;r<o;r++)t.push(e[String(r)]);return m(t)}}function fo(o,e){return t=>{const r=t.source;if(r===void 0)return m(void 0);const s={};for(const[i,n]of Object.entries(r)){const a={...o,[e.itVar]:n};s[i]=v(a,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:mo,args:s})}}const mo=o=>m(o),vo=o=>{const e=o.arg;return m(e===void 0?void 0:e.length===0)},yo=o=>{const e=o.operand;return m(e===void 0?void 0:!e)},bo=o=>{const e=o.operand1,t=o.operand2;return m(e===void 0||t===void 0?void 0:e&&t)},wo=o=>{const e=o.operand1,t=o.operand2;return m(e===void 0||t===void 0?void 0:e||t)},So=o=>{const e=o.source;return e===void 0?m(void 0):({cCtx:t})=>{var r;return be((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},ko=o=>{const e=o.source,t=o.field;return m(e===void 0||t===void 0?void 0:e[t])};function Co(o,e){return t=>{const r=t.source;return r===void 0?m(void 0):({cCtx:s})=>{const i=s.accessor(r).node(),n={};for(const a of i.listInputFields()){const c=i.traverse(a);if(c===void 0)n[a]=m(void 0);else{const u={...o,[e.itVar]:c.persist()};n[a]=v(u,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:Po,args:n}}}}const Po=o=>m(o),Ro=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:S.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)}})})},Oo=o=>{const e=o.source;return e===void 0?m(void 0):({cCtx:t,drivers:r})=>{const s=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:S.Computable.make(()=>r.blobDriver.getDownloadedBlob(s),{postprocessValue:async i=>i===void 0?void 0:(await r.blobDriver.getContent(i.handle)).toString()})}}},Bo=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:S.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r==null)return;const s=await t.blobDriver.getContent(r.handle);if(s!=null)return JSON.parse(Buffer.from(s).toString())}})})},Fo=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},Do=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},To=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},xo=o=>e=>{const t=e.source;return t===void 0?m(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,o)})},Eo=o=>e=>{const t=e.source;return t===void 0?m(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,o)})},jo=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function v(o,e){switch(e.type){case"GetFromCtx":const t=o[e.variable];return typeof t=="function"?r=>be(t(r.cCtx)):m(t);case"Isolate":return({drivers:r})=>({type:"ScheduleComputable",computable:Kt(r,o,e.cfg)});case"Immediate":return m(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:ko,args:{source:v(o,e.source),field:v(o,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:ho(o,e),args:{source:v(o,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:fo(o,e),args:{source:v(o,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:lo,args:ao(e.template,r=>v(o,r))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:Jt(e.template.length),args:Ut(e.template,r=>v(o,r))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:po,args:{source:v(o,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:vo,args:{arg:v(o,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:yo,args:{operand:v(o,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:bo,args:{operand1:v(o,e.operand1),operand2:v(o,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:wo,args:{operand1:v(o,e.operand1),operand2:v(o,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:Co(o,e),args:{source:v(o,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:go,args:{source:v(o,e.source),field:v(o,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:So,args:{source:v(o,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Ro,args:{source:v(o,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:Oo,args:{source:v(o,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Bo,args:{source:v(o,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Fo,args:{source:v(o,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Do,args:{source:v(o,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:To,args:{source:v(o,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:xo(e.lines),args:{source:v(o,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:Eo(e.patternToSearch),args:{source:v(o,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:jo,args:{source:v(o,e.source)}});default:return f.assertNever(e)}}const Ao=["$prod","$staging"];function Io(o){return{$blockId:o.blockId,$args:e=>JSON.parse(o.args(e)),$ui:e=>{const t=o.uiState(e);return t!==void 0?JSON.parse(t):void 0},$prod:o.prod,$staging:o.staging}}const Mt=Symbol(),$t="return",No={op:Mt,arg:$t};function Vo(o){return o.op==Mt&&o.arg==$t}function Lo(){return{pendingSubroutines:new Map}}function dt(o,e,t,r){const s=new mt(t),i=(a,c)=>{if(Vo(a))return e.result=c,!1;const u=f.notEmpty(e.pendingSubroutines.get(a.op));if(a.arg in u.args)throw new Error("argument already set");return u.args[a.arg]=c,u.argCounter--,u.argCounter===0&&(e.pendingSubroutines.delete(a.op),s.push({destination:u.destination,operation:u.subroutine(u.args)})),!0},n=[];e:for(;s.length>0;){const a=s.shift(),c=a.operation(o);switch(c.type){case"ReturnResult":if(!i(a.destination,c.result))break e;break;case"ScheduleSubroutine":const u=Symbol(),l=Object.entries(c.args),p=l.length;if(p===0)s.push({destination:a.destination,operation:c.subroutine({})});else{for(const[h,y]of l)s.push({destination:{op:u,arg:h},operation:y});e.pendingSubroutines.set(u,{argCounter:p,args:{},subroutine:c.subroutine,destination:a.destination})}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");n.push({destination:a.destination,computable:c.computable});break;default:f.assertNever(c)}}return n}function Uo(o,e,t,r={}){return Kt(o,Io(e),t,r)}function Kt(o,e,t,r={}){const s=`${e.blockId}#`+Ve({ctx:Object.fromEntries(Object.entries(e).filter(([i])=>Ao.indexOf(i)===-1)),cfg:t});return S.Computable.makeRaw(i=>{const n={drivers:o,cCtx:i},a=Lo();return{ir:dt(n,a,[{destination:No,operation:v(e,t)}],!0),async postprocessValue(u){const l=[];for(const b of u)l.push({destination:b.destination,operation:m(b.computable)});const p={drivers:o,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},h=new Map;for(const[b,C]of a.pendingSubroutines)h.set(b,{...C,args:{...C.args}});const y={result:a.result,pendingSubroutines:h};if(dt(p,y,l,!1),!("result"in y))throw new Error("illegal cfg rendering stack state, no result");return y.result}}},{...r,key:s})}function Jo(o){return o instanceof ArrayBuffer||ArrayBuffer.isView(o)}function pt(o){return o!==void 0?Buffer.from(o).toString("base64"):void 0}class me{constructor(e,t,r,s,i){g(this,"callbackRegistry");g(this,"fnJSONStringify");g(this,"fnJSONParse");g(this,"computablesToResolve",{});g(this,"computableCtx");g(this,"accessors",new Map);g(this,"meta");g(this,"_resultPool");if(this.scope=e,this.vm=t,this.blockCtx=r,this.env=s,this.computableCtx=i,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(n=>t.getProp(n,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(n=>t.getProp(n,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");this.meta=r.blockMeta(i),this.injectCtx()}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw me.cleanErrorContext(t),t}}runCallback(e,...t){try{return ge.Scope.withScope(r=>{const s=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(s)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(s,this.vm.undefined,...t.map(i=>this.exportObjectUniversal(i,r)))))})}catch(r){throw me.cleanErrorContext(r),r}}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,s)=>{if(!this.accessors.has(r)){const i=this.blockCtx[s];if(i===void 0)throw new Error("Staging context not available");const n=i(this.computableCtx);n?this.accessors.set(r,this.computableCtx.accessor(n).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 pt(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return pt(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r){const s=this.getAccessor(e);if(!s.getIsReadyOrError())return;const i=no(s,t,r),n={};for(const[a,c]of Object.entries(i))n[a]=P.mapPObjectData(c,u=>this.wrapAccessor(u));return n}registerComputable(e,t){const r=`${e}_${_.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",S.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",S.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=f.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:P.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:P.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 P.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=>P.mapPObjectData(t,r=>this.getAccessor(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(P.mapPTableDef(e,t=>P.mapPObjectData(t,r=>this.getAccessor(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=_.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,s=!1;switch(typeof e){case"string":r=this.vm.newString(e),s=!0;break;case"number":r=this.vm.newNumber(e),s=!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(Jo(e)){r=this.vm.newArrayBuffer(e),s=!0;break}return}return s&&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(s=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,s)));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(){ge.Scope.withScope(e=>{const t=e.manage(this.vm.newObject()),r=this.blockCtx.args(this.computableCtx),s=this.blockCtx.uiState(this.computableCtx);this.vm.setProp(t,"args",e.manage(this.vm.newString(r))),s!==void 0&&this.vm.setProp(t,"uiState",e.manage(this.vm.newString(s))),this.vm.setProp(t,"callbackRegistry",this.callbackRegistry);const i=(n,a)=>{this.vm.newFunction(n,a).consume(c=>this.vm.setProp(t,n,c))};i("getAccessorHandleByName",n=>this.exportSingleValue(this.getAccessorHandleByName(this.vm.getString(n)),void 0)),i("resolveWithCommon",(n,a,...c)=>this.exportSingleValue(this.resolveWithCommon(this.vm.getString(n),this.importObjectViaJson(a),...c.map(u=>this.importObjectViaJson(u))),void 0)),i("getResourceType",n=>this.exportObjectViaJson(this.getResourceType(this.vm.getString(n)),void 0)),i("getInputsLocked",n=>this.exportSingleValue(this.getInputsLocked(this.vm.getString(n)),void 0)),i("getOutputsLocked",n=>this.exportSingleValue(this.getOutputsLocked(this.vm.getString(n)),void 0)),i("getIsReadyOrError",n=>this.exportSingleValue(this.getIsReadyOrError(this.vm.getString(n)),void 0)),i("getIsFinal",n=>this.exportSingleValue(this.getIsFinal(this.vm.getString(n)),void 0)),i("getError",n=>this.exportSingleValue(this.getError(this.vm.getString(n)),void 0)),i("listInputFields",n=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(n)),void 0)),i("listOutputFields",n=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(n)),void 0)),i("listDynamicFields",n=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(n)),void 0)),i("getKeyValueBase64",(n,a)=>this.exportSingleValue(this.getKeyValueBase64(this.vm.getString(n),this.vm.getString(a)),void 0)),i("getKeyValueAsString",(n,a)=>this.exportSingleValue(this.getKeyValueAsString(this.vm.getString(n),this.vm.getString(a)),void 0)),i("getDataBase64",n=>this.exportSingleValue(this.getDataBase64(this.vm.getString(n)),void 0)),i("getDataAsString",n=>this.exportSingleValue(this.getDataAsString(this.vm.getString(n)),void 0)),i("parsePObjectCollection",(n,a,c)=>this.exportObjectUniversal(this.parsePObjectCollection(this.vm.getString(n),this.vm.dump(a),this.vm.getString(c)),void 0)),i("getBlobContentAsBase64",n=>this.exportSingleValue(this.getBlobContentAsBase64(this.vm.getString(n)),void 0)),i("getBlobContentAsString",n=>this.exportSingleValue(this.getBlobContentAsString(this.vm.getString(n)),void 0)),i("getDownloadedBlobContentHandle",n=>this.exportSingleValue(this.getDownloadedBlobContentHandle(this.vm.getString(n)),void 0)),i("getOnDemandBlobContentHandle",n=>this.exportSingleValue(this.getOnDemandBlobContentHandle(this.vm.getString(n)),void 0)),i("getImportProgress",n=>this.exportSingleValue(this.getImportProgress(this.vm.getString(n)),void 0)),i("getLastLogs",(n,a)=>this.exportSingleValue(this.getLastLogs(this.vm.getString(n),this.vm.getNumber(a)),void 0)),i("getProgressLog",(n,a)=>this.exportSingleValue(this.getProgressLog(this.vm.getString(n),this.vm.getString(a)),void 0)),i("getLogHandle",n=>this.exportSingleValue(this.getLogHandle(this.vm.getString(n)),void 0)),i("getBlockLabel",n=>this.exportSingleValue(this.getBlockLabel(this.vm.getString(n)),void 0)),i("getDataFromResultPool",n=>this.exportObjectUniversal(this.getDataFromResultPool(),void 0)),i("getDataWithErrorsFromResultPool",n=>this.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),i("getSpecsFromResultPool",n=>this.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),i("calculateOptions",n=>this.exportObjectUniversal(this.calculateOptions(this.importObjectViaJson(n)),void 0)),i("getSpecFromResultPoolByRef",(n,a)=>this.exportObjectUniversal(this.getSpecFromResultPoolByRef(this.vm.getString(n),this.vm.getString(a)),void 0)),i("getDataFromResultPoolByRef",(n,a)=>this.exportObjectUniversal(this.getDataFromResultPoolByRef(this.vm.getString(n),this.vm.getString(a)),void 0)),i("createPFrame",n=>this.exportSingleValue(this.createPFrame(this.importObjectViaJson(n)),void 0)),i("createPTable",n=>this.exportSingleValue(this.createPTable(this.importObjectViaJson(n)),void 0)),i("getCurrentUnstableMarker",()=>this.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}function we(o,e){return re(o.traverse({field:F(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:d.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),s=P.extractConfig(r.config);return{bpId:t.resourceInfo.id.toString(),info:r,cfg:s}})}const le=process.env.MI_LOG_OUTPUT_STATUS;function Mo(o,e,t,r,s,i={}){const n=`${e.blockId}#lambda#${s}#${t.handle}`;return i={...i,key:n},i.mode===void 0&&t.retentive===!0&&(i.mode="StableOnlyRetentive"),S.Computable.makeRaw(a=>{const c=new ge.Scope;a.addOnDestroy(()=>c.dispose());const u=c.manage(o.quickJs.newRuntime());u.setMemoryLimit(1024*640),u.setMaxStackSize(1024*320);const l=c.manage(u.newContext()),p=new me(c,l,e,o,a);p.evaluateBundle(r.content);const h=p.runCallback(t.handle);p.resetComputableCtx();let y=0;return le&&le!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:p.computablesToResolve,postprocessValue:async(b,{unstableMarker:C,stable:I})=>{for(const[V,K]of Object.entries(b))p.runCallback(V,K);const N=p.importObjectUniversal(h);return y++,le&&(le!=="unstable-only"||!I)&&console.log(I?`Stable output ${t.handle} calculated ${N!==void 0?"defined":"undefined"}; (#${y})`:`Unstable output ${t.handle}; marker = ${C}; ${N!==void 0?"defined":"undefined"} (#${y})`),N}}},i)}function $o(o){return P.isConfigLambda(o)?o.isActive===!0:uo(o)}function oe(o,e,t,r,s,i={}){if(P.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return Mo(o,e,t,r,s,i)}else return Uo(o.driverKit,e,t,i)}function Ko(o,e,t){return S.Computable.make(r=>{var b,C,I,N,V,K,W,ae;const s=r.accessor(o).node(),i=f.notEmpty(s.getKeyValueAsJson(Me)),n=f.notEmpty(s.getKeyValueAsJson(ie)),a=f.notEmpty(s.getKeyValueAsJson(ne)),c=f.notEmpty(s.getKeyValueAsJson(q)),u=f.notEmpty(s.getKeyValueAsJson(he)),l=new Map;for(const{id:k}of $(c)){const L=s.traverse({field:F(k,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0});let z;const j=s.traverse({field:F(k,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(j!==void 0){const x=s.getField({field:F(k,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),O=s.getField({field:F(k,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});z={arguments:j.getDataAsJson(),stale:L.id!==j.id,outputError:x.error!==void 0||O.error!==void 0||((b=x.value)==null?void 0:b.getError())!==void 0||((C=O.value)==null?void 0:C.getError())!==void 0,outputsError:((I=x.error)==null?void 0:I.getDataAsString())??((V=(N=x.value)==null?void 0:N.getError())==null?void 0:V.getDataAsString()),exportsError:((K=O.error)==null?void 0:K.getDataAsString())??((ae=(W=O.value)==null?void 0:W.getError())==null?void 0:ae.getDataAsString()),finished:(x.value!==void 0&&x.value.getIsReadyOrError()||x.error!==void 0&&x.error.getIsReadyOrError())&&(O.value!==void 0&&O.value.getIsReadyOrError()||O.error!==void 0&&O.error.getIsReadyOrError())}}l.set(k,{currentArguments:L.getDataAsJson(),prod:z})}const p=de(c,k=>l.get(k).currentArguments),h=new Set(u.blocksInLimbo),y=[...$(c)].map(({id:k,label:L,renderingMode:z})=>{var Ye,Qe,Ze,Xe,et;const j=f.notEmpty(l.get(k)),x=f.notEmpty(p.nodes.get(k));let O="NotCalculated";j.prod!==void 0&&(h.has(k)?O="Limbo":O=j.prod.finished?"Done":"Running");const U=we(s,k),{sections:ce,title:Z,inputsValid:w,sdkVersion:B}=re(U,({bpId:X,cfg:H,info:ls})=>{const ke=He(o,k);return{sections:oe(t,ke,H.sections,H.code,X),title:re(H.title,Wt=>oe(t,ke,Wt,H.code,X)),inputsValid:oe(t,ke,H.inputsValid,H.code,X),sdkVersion:H.sdkVersion}})||{},R=re(U,({info:X})=>t.blockUpdateWatcher.get(X.source));return{id:k,label:Z??L,title:Z??L,renderingMode:z,stale:((Ye=j.prod)==null?void 0:Ye.stale)!==!1||O==="Limbo",missingReference:x.missingReferences,upstreams:[...p.traverseIdsExcludingRoots("upstream",k)],downstreams:[...p.traverseIdsExcludingRoots("downstream",k)],calculationStatus:O,outputErrors:((Qe=j.prod)==null?void 0:Qe.outputError)===!0,outputsError:(Ze=j.prod)==null?void 0:Ze.outputsError,exportsError:(Xe=j.prod)==null?void 0:Xe.exportsError,sections:ce,inputsValid:w,currentBlockPack:(et=U==null?void 0:U.info)==null?void 0:et.source,updatedBlockPack:R,sdkVersion:B,navigationState:e.getState(k)}});return{meta:a,created:new Date(i),lastModified:new Date(n),authorMarker:s.getKeyValueAsJson(De),blocks:y}},{postprocessValue:r=>{const s=new Set,i=new Set;return{...r,blocks:r.blocks.map(n=>{n.inputsValid||s.add(n.id),n.stale&&i.add(n.id);const a=n.stale||n.upstreams.findIndex(u=>i.has(u))!==-1,c=(a||n.outputErrors)&&!!n.inputsValid&&!n.missingReference&&n.upstreams.findIndex(u=>s.has(u))===-1;return{...n,canRun:c,stale:a}})}}}).withStableType()}function Go(o,e){const t=o.node();if(d.resourceTypesEqual(t.resourceType,Ke)){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(d.resourceTypesEqual(t.resourceType,Ge)){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 _o(o,e){if(o!==void 0)return S.Computable.make(t=>Go(t.accessor(o),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 Ho(o,e,t){return S.Computable.make(r=>{var a;const s=r.accessor(o).node(),i=we(s,e),n=(a=s.traverse({field:F(e,"blockPack"),assertFieldType:"Dynamic"},{field:d.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:At,assertFieldType:"Input"}))==null?void 0:a.persist();return{path:_o(n,t),sdkVersion:i==null?void 0:i.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function Gt(o,e,t){if(t===void 0)return S.Computable.make(n=>Gt(o,e,n),{key:`inputs#${d.resourceIdToString(o.rid)}#${e}`});const r=t.accessor(o).node(),s=He(o,e),i=s.uiState(t);return{author:r.getKeyValueAsJson(Fe(e)),args:JSON.parse(s.args(t)),ui:i!==void 0?JSON.parse(i):void 0}}function qo(o,e,t){return S.Computable.make(r=>{const s=r.accessor(o).node(),i=Lt(o,e);return re(we(s,e),({cfg:n,bpId:a})=>{const c={};for(const[u,l]of Object.entries(n.outputs)){const p=oe(t,i,l,n.code,a);c[u]=S.Computable.wrapError(p)}return c})},{key:"outputs#"+d.resourceIdToString(o.rid)+"#"+e}).withStableType()}function Wo(o,e){return S.Computable.make(t=>{const r=t.accessor(o).node(),s=f.notEmpty(r.getKeyValueAsJson(q)),i=[];for(const{id:n,renderingMode:a}of $(s)){const c=we(r,n);if(c===void 0)continue;const u=Object.entries(c.cfg.outputs).map(([,p])=>p).filter(p=>$o(p)).map(p=>p);if(u.length===0)continue;const l=Lt(r.persist(),n);for(const p of u)i.push(S.Computable.wrapError(oe(e,l,p,c.cfg.code,c.bpId)))}return i})}class zo{constructor(){g(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 S.ChangeSource});return}r.state={...t},r.change.markChanged()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...P.DefaultNavigationState},change:new S.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return S.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 Se{constructor(e,t,r){g(this,"rid");g(this,"overview");g(this,"navigationStates",new zo);g(this,"blockComputables",new Map);g(this,"blockFrontends",new Map);g(this,"activeConfigs");g(this,"refreshLoopResult");g(this,"abortController",new AbortController);g(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=Ko(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=Wo(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await Oe(this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await vt.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(d.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!d.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,s=void 0,i=_.randomUUID()){const n=await this.env.bpPreparer.prepare(t),a=await this.env.bpPreparer.getBlockConfigContainer(t),c=P.extractConfig(a);return await M(this.env.pl,this.rid,s,u=>u.addBlock({id:i,label:e,renderingMode:c.renderingMode},{args:JSON.stringify(c.initialArgs),uiState:JSON.stringify(c.initialUiState),blockPack:n},r)),await this.projectTree.refreshState(),i}async updateBlockPack(e,t,r=!1,s){const i=await this.env.bpPreparer.prepare(t),n=await this.env.bpPreparer.getBlockConfigContainer(t);await M(this.env.pl,this.rid,s,a=>a.migrateBlockPack(e,i,r?JSON.stringify(n.initialArgs):void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await M(this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await M(this.env.pl,this.rid,t,r=>{const s=r.structure;if(s.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const i=s.groups[0];if(i.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${i.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const n={groups:[{id:i.id,label:i.label,blocks:e.map(a=>{const c=i.blocks.find(u=>u.id===a);if(c===void 0)throw new Error(`Can't find block: ${a}`);return c})}]};r.updateStructure(n)}),await this.projectTree.refreshState()}async runBlock(e){await Oe(this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await Oe(this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await M(this.env.pl,this.rid,r,s=>s.setArgs([{blockId:e,args:JSON.stringify(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await M(this.env.pl,this.rid,r,s=>s.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,s){await M(this.env.pl,this.rid,s,i=>{i.setArgs([{blockId:e,args:JSON.stringify(t)}]),i.setUiState(e,JSON.stringify(r))}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async r=>{const s=d.ensureResourceIdNotNull((await r.getField(d.field(this.rid,F(e,"blockPack")))).value),i=d.ensureResourceIdNotNull((await r.getField(d.field(s,d.Pl.HolderRefField))).value),n=await r.getResourceData(i,!1),a=JSON.parse(Buffer.from(f.notEmpty(n.data)).toString("utf-8"));await M(r,this.rid,t,c=>{c.setArgs([{blockId:e,args:JSON.stringify(a.config.initialArgs)}]),c.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=qo(this.projectTree.entry(),e,this.env),i={fullState:S.Computable.make(n=>({argsAndUiState:Gt(this.projectTree.entry(),e,n),outputs:r,navigationState:this.navigationStates.getState(e)}),{postprocessValue:n=>({...n.argsAndUiState,outputs:n.outputs,navigationState:n.navigationState})}).withPreCalculatedValueTree()};return this.blockComputables.set(e,i),i}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=Ho(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 Ne.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:Yo},e.logger);return new Se(e,t,r)}}function Yo(o){switch(o.type.name){case"BlockPackCustom":return o.fields.filter(e=>e.name!=="template");case"UserProject":return o.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return o.fields}}const qe={logger:new f.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 We(o){return{blobDownloadPath:T.join(o,"download")}}const _t={...qe,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function Ht(o){return{...We(o),frontendDownloadPath:T.join(o,"frontend")}}const Qo={minDelay:1500},Zo="__no_updates__";class Xo extends S.PollComputablePool{constructor(t,r,s={}){super({...s,...Qo},r);g(this,"http");this.registryProvider=t,this.http=s.http}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 Zo}}async readValue(t){var r;try{switch(t.type){case"dev-v1":try{const s=await Je(t.folder);return s===t.mtime?void 0:{...t,mtime:s}}catch(s){this.logger.warn(s);return}case"dev-v2":try{const s=await D.tryLoadPackDescription(t.folder,this.logger);if(s===void 0)return;const i=await ve(s);return i===t.mtime?void 0:{...t,mtime:i}}catch(s){this.logger.warn(s);return}case"from-registry-v2":try{const s=this.registryProvider.getRegistry(t.registryUrl),i=(r=await s.getOverviewForSpec(t.id))==null?void 0:r.spec;if((i==null?void 0:i.type)!=="from-registry-v2")throw new Error("Unexpected");return te.blockPackIdEquals(i.id,t.id)?void 0:((async()=>{try{await s.getComponents(i.id)}catch(n){this.logger.warn(n)}})(),i)}catch(s){this.logger.warn(s);return}default:return}}catch(s){this.logger.warn(s);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&&te.blockPackIdEquals(t.id,r.id);case"from-registry-v2":return r.type!=="from-registry-v2"?!1:t.registryUrl===r.registryUrl&&te.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:f.assertNever(t)}}}class gt{constructor(){g(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 s=!1;return{resource:r.resource,key:t,unref:()=>{s||(r.refCount--,s=!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}}function ht(o){return String(o.id)}const es=["Int","Long","Float","Double","String","Bytes"];class ts{constructor(e,t,r){g(this,"pFrame",new rr.PFrame);g(this,"blobIdToResource",new Map);g(this,"blobHandleComputables",new Map);g(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue()});g(this,"resolveBlob",async e=>{const t=this.getOrCreateComputableForBlob(e);return this.blobDriver.getLocalPath((await t.awaitStableValue()).handle)});g(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 s of r){for(const n of Zr(s.data))this.blobIdToResource.set(ht(n),n);const i=Xr(s.data,ht);try{this.pFrame.addColumnSpec(s.id,s.spec),this.pFrame.setColumnData(s.id,i)}catch(n){throw new Error(`Adding column ${s.id} to PFrame failed: ${n}; Spec: ${s.spec}, DataInfo: ${i}.`)}}}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 rs{constructor(e){g(this,"pFrames");g(this,"pTables");g(this,"blobContentCache");g(this,"concurrencyLimiter");this.blobDriver=e;const t=new or.LRUCache({maxSize:1e9,fetchMethod:async s=>await yt.readFile(s),sizeCalculation:s=>s.length}),r=new f.ConcurrencyLimitingExecutor(1);this.blobContentCache=t,this.concurrencyLimiter=r,this.pFrames=new class extends gt{constructor(s){super(),this.blobDriver=s}createNewResource(s){return new ts(this.blobDriver,t,s)}calculateParamsKey(s){return ss(s)}}(this.blobDriver),this.pTables=new class extends gt{constructor(s){super(),this.pFrames=s}async createNewResource(s){const i=this.pFrames.getByKey(s.pFrameHandle),n=await r.run(async()=>await i.pFrame.createTable({src:se(s.def.src),filters:s.def.filters}));return s.def.sorting.length!==0?n.sort(s.def.sorting):n}calculateParamsKey(s){return os(s)}}(this.pFrames)}createPFrame(e,t){const r=e.filter(i=>es.find(n=>n===i.spec.valueType)).map(i=>P.mapPObjectData(i,n=>io(n))),s=this.pFrames.acquire(r);return t.addOnDestroy(s.unref),s.key}createPTable(e,t){const r=this.createPFrame(is(e.src),t),s=P.mapPTableDef(e,n=>n.id),i=this.pTables.acquire({def:s,pFrameHandle:r});return t.addOnDestroy(i.unref),i.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(s=>s.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()=>await this.pFrames.getByKey(e).pFrame.createTable({src:se(t.src),filters:t.filters}));if(t.sorting.length>0){const n=await this.concurrencyLimiter.run(async()=>await r.sort(t.sorting));r.dispose(),r=n}const s=r.getSpec(),i=await this.concurrencyLimiter.run(async()=>await r.getData([...s.keys()]));return r.dispose(),s.map((n,a)=>({spec:n,data:i[a]}))}async getUniqueValues(e,t){return await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.getUniqueValues(t))}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 s=await this.pTables.getByKey(e);return await this.concurrencyLimiter.run(async()=>await s.getData(t,r))}}function se(o){switch(o.type){case"column":return{type:"column",columnId:o.column,qualifications:[]};case"inner":case"full":return{type:o.type,entries:o.entries.map(e=>se(e))};case"outer":return{type:"outer",primary:se(o.primary),secondary:o.secondary.map(e=>se(e))};default:f.assertNever(o)}}function os(o){const e=_.createHash("sha256");return e.update(o.pFrameHandle),e.update(Ve(o.def)),e.digest().toString("hex")}function ss(o){const e=o.map(s=>s.id).sort(),t=_.createHash("sha256");let r="";for(const s of e)r!==s&&(t.update(s),r=s);return t.digest().toString("hex")}function is(o){const e=new Map;return pe(o,e),[...e.values()]}function pe(o,e){switch(o.type){case"column":e.set(o.column.id,o.column);return;case"full":case"inner":for(const t of o.entries)pe(t,e);return;case"outer":pe(o.primary,e);for(const t of o.secondary)pe(t,e);return;default:f.assertNever(o)}}async function qt(o,e,t){const r={...qe,...We(e),...t},s=new f.HmacSha256Signer(r.localSecret),i=J.createDownloadClient(r.logger,o,r.localProjections),n=J.createLogsClient(o,r.logger),a=J.createUploadBlobClient(o,r.logger),c=J.createUploadProgressClient(o,r.logger),u=new J.DownloadDriver(r.logger,i,n,r.blobDownloadPath,s,r.blobDriverOps),l=new J.UploadDriver(r.logger,s,a,c,r.uploadDriverOps),p=new J.LogsStreamDriver(r.logger,n,r.logStreamDriverOps),h=new J.LogsDriver(r.logger,p,u),y=await J.LsDriver.init(r.logger,o,s,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),b=new rs(u);return{blobDriver:u,logDriver:h,lsDriver:y,signer:s,uploadDriver:l,pFrameDriver:b}}class ze{constructor(e,t,r,s,i,n,a,c){g(this,"pl");g(this,"projectList");g(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=s,this.openedProjectsList=i,this.projectListTree=n,this.blockRegistryProvider=a,this.projectList=c,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=_.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async s=>{const i=await Qr(s,e);return s.createField(d.field(this.projectListResourceId,t),"Dynamic",i),await s.commit(),await d.toGlobalResourceId(i)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await M(this.pl,e,r,async s=>{s.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(d.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(d.field(this.projectListResourceId,e))).value;if(d.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 Se.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 f.HmacSha256Signer.generateSecret()}static async init(e,t,r){const s={..._t,...Ht(t),...r};process.env.MI_LOG_TREE_STAT&&(s.defaultTreeOptions.logStat=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request");const i=await e.withWriteTx("MLInitialization",async C=>{const I=d.field(C.clientRoot,Fr);C.createField(I,"Dynamic");const N=await C.getField(I);if(d.isNullResourceId(N.value)){const V=C.createEphemeral(Ct);return C.lock(V),C.setField(I,V),await C.commit(),await V.globalId}else return N.value}),n=s.logger,a=await qt(e,t,s),c=new G.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),u=new wt(c),l=new Gr(u,a.signer,c),p=new J.DownloadUrlDriver(n,e.httpDispatcher,s.frontendDownloadPath),h={pl:e,signer:a.signer,logger:n,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:c,ops:s,bpPreparer:l,frontendDownloadDriver:p,driverKit:a,blockUpdateWatcher:new Xo(u,n,{minDelay:s.devBlockUpdateRecheckInterval,http:c}),quickJs:await ge.getQuickJS()},y=new S.WatchableValue([]),b=await Tr(e,i,y,h);return new ze(h,a,a.signer,i,y,b.tree,u,b.computable)}}const ns=["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 as(o,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=[];ns.forEach(c=>{sr.channel(c).subscribe(l=>{var h;const p=new Date().toISOString();(h=l==null?void 0:l.response)!=null&&h.headers&&(l.response.headers=l.response.headers.map(y=>y.toString())),r.push(JSON.stringify({timestamp:p,event:c,data:l}))})});const s={plPings:[],blockRegistryOverviewChecks:[],blockGARegistryOverviewChecks:[],blockRegistryUiChecks:[],blockGARegistryUiChecks:[],autoUpdateCdnChecks:[]},i=d.plAddressToConfig(o,{defaultRequestTimeout:t.pingTimeoutMs});s.plPings=await Y(t.pingCheckDurationMs,t.maxPingsPerSecond,async()=>{const u=await new d.UnauthenticatedPlClient(i).ping();return JSON.stringify(u).slice(0,t.bodyLimit)+"..."});const a=new d.UnauthenticatedPlClient(i).ll.httpDispatcher;return s.blockRegistryOverviewChecks=await Y(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await ee(new URL(t.blockOverviewPath,t.blockRegistryUrl),t,a)),s.blockGARegistryOverviewChecks=await Y(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await ee(new URL(t.blockOverviewPath,t.blockGARegistryUrl),t,a)),s.blockRegistryUiChecks=await Y(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await ee(new URL(t.blockUiPath,t.blockRegistryUrl),t,a)),s.blockGARegistryUiChecks=await Y(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await ee(new URL(t.blockUiPath,t.blockGARegistryUrl),t,a)),s.autoUpdateCdnChecks=await Y(t.autoUpdateCdnDurationMs,t.maxAutoUpdateCdnChecksPerSecond,async()=>await ee(t.autoUpdateCdnUrl,t,a)),cs(s,o,t,r)}async function Y(o,e,t){const r=Ie(),s=[];for(;ft(r)<o;){const i=Ie();let n;try{n={ok:!0,value:await t()}}catch(u){n={ok:!1,error:u}}const a=ft(i);s.push({elapsedMs:a,response:n});const c=1e3/e-a;c>0&&await vt.setTimeout(c)}return s}async function ee(o,e,t){const{body:r,statusCode:s}=await G.request(o,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),i=await r.text();return{statusCode:s,beginningOfBody:i.slice(0,e.bodyLimit)+"..."}}function cs(o,e,t,r){const s=o.plPings.filter(a=>a.response.ok),i=o.plPings.filter(a=>!a.response.ok),n=[...new Set(s.map(a=>JSON.stringify(a.response.value)))];return`
2
2
  Network report:
3
3
  pl endpoint: ${e};
4
4
  options: ${JSON.stringify(t,null,2)}.
5
5
 
6
- Platforma pings: ${Z(s.plPings)}
6
+ Platforma pings: ${Q(o.plPings)}
7
7
 
8
- Block registry overview responses: ${Z(s.blockRegistryOverviewChecks)}
8
+ Block registry overview responses: ${Q(o.blockRegistryOverviewChecks)}
9
9
 
10
- Block ga registry overview responses: ${Z(s.blockGARegistryOverviewChecks)}
10
+ Block ga registry overview responses: ${Q(o.blockGARegistryOverviewChecks)}
11
11
 
12
- Block registry ui responses: ${Z(s.blockRegistryUiChecks)}
12
+ Block registry ui responses: ${Q(o.blockRegistryUiChecks)}
13
13
 
14
- Block ga registry ui responses: ${Z(s.blockGARegistryUiChecks)}
14
+ Block ga registry ui responses: ${Q(o.blockGARegistryUiChecks)}
15
15
 
16
- Auto-update CDN responses: ${Z(s.autoUpdateCdnChecks)}
16
+ Auto-update CDN responses: ${Q(o.autoUpdateCdnChecks)}
17
17
 
18
18
  Block registry overview dumps:
19
- ${JSON.stringify(s.blockRegistryOverviewChecks,null,2)}
19
+ ${JSON.stringify(o.blockRegistryOverviewChecks,null,2)}
20
20
 
21
21
  Block ga registry overview dumps:
22
- ${JSON.stringify(s.blockGARegistryOverviewChecks,null,2)}
22
+ ${JSON.stringify(o.blockGARegistryOverviewChecks,null,2)}
23
23
 
24
24
  Block registry ui dumps:
25
- ${JSON.stringify(s.blockRegistryUiChecks,null,2)}
25
+ ${JSON.stringify(o.blockRegistryUiChecks,null,2)}
26
26
 
27
27
  Block ga registry ui dumps:
28
- ${JSON.stringify(s.blockGARegistryUiChecks,null,2)}
28
+ ${JSON.stringify(o.blockGARegistryUiChecks,null,2)}
29
29
 
30
30
  Auto-update CDN dumps:
31
- ${JSON.stringify(s.autoUpdateCdnChecks,null,2)}
31
+ ${JSON.stringify(o.autoUpdateCdnChecks,null,2)}
32
32
 
33
33
  Platforma pings error dumps:
34
34
  ${JSON.stringify(i,null,2)}
@@ -39,11 +39,11 @@ ${JSON.stringify(n,null,2)}
39
39
  Undici logs:
40
40
  ${r.join(`
41
41
  `)}
42
- `}function Z(s){const e=s.filter(o=>o.response.ok),{mean:t,median:r}=co(s);return`
43
- total: ${s.length};
42
+ `}function Q(o){const e=o.filter(s=>s.response.ok),{mean:t,median:r}=us(o);return`
43
+ total: ${o.length};
44
44
  successes: ${e.length};
45
- errors: ${s.length-e.length};
45
+ errors: ${o.length-e.length};
46
46
  mean in ms: ${t};
47
47
  median in ms: ${r};
48
- `}function co(s){const e=s.map(o=>o.elapsedMs),t=e.reduce((o,i)=>o+i)/e.length;let r;if(e.length>0){const o=Math.floor(e.length/2);r=e.length%2?e[o]:(e[o-1]+e[o])/2}return{mean:t,median:r}}function Ae(){return Date.now()}function gt(s){return Ae()-s}exports.BlockPackRegistry=gr;exports.CentralBlockRegistry=hr;exports.DefaultDriverKitOpsPaths=qe;exports.DefaultDriverKitOpsSettings=He;exports.DefaultMiddleLayerOpsPaths=_t;exports.DefaultMiddleLayerOpsSettings=Gt;exports.FrontendFromFolderResourceType=Ke;exports.FrontendFromUrlResourceType=$e;exports.MiddleLayer=We;exports.Project=be;exports.TengoTemplateGet=kt;exports.TengoTemplateGetRegistry=Ct;exports.TengoTemplateGetTemplate=Rt;exports.TengoTemplateGetTemplateURI=Pt;exports.TengoTemplatePack=Ot;exports.TengoTemplatePackConvert=Ft;exports.TengoTemplatePackConvertTemplate=Dt;exports.TengoTemplatePackConvertTemplatePack=Bt;exports.V1CentralDevSnapshotRegistry=mr;exports.V1CentralRegistry=fr;exports.V2RegistryProvider=yt;exports.checkNetwork=no;exports.createRenderTemplate=Me;exports.getDevV1PacketMtime=Ue;exports.getDevV2PacketMtime=me;exports.initDriverKit=Ht;exports.loadTemplate=ve;exports.prepareTemplateSpec=Tt;Object.keys(C).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>C[s]})});Object.keys(ee).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>ee[s]})});Object.keys(d).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>d[s]})});
48
+ `}function us(o){const e=o.map(s=>s.elapsedMs),t=e.reduce((s,i)=>s+i)/e.length;let r;if(e.length>0){const s=Math.floor(e.length/2);r=e.length%2?e[s]:(e[s-1]+e[s])/2}return{mean:t,median:r}}function Ie(){return Date.now()}function ft(o){return Ie()-o}exports.BlockPackRegistry=gr;exports.CentralBlockRegistry=hr;exports.DefaultDriverKitOpsPaths=We;exports.DefaultDriverKitOpsSettings=qe;exports.DefaultMiddleLayerOpsPaths=Ht;exports.DefaultMiddleLayerOpsSettings=_t;exports.FrontendFromFolderResourceType=Ge;exports.FrontendFromUrlResourceType=Ke;exports.MiddleLayer=ze;exports.Project=Se;exports.TengoTemplateGet=Pt;exports.TengoTemplateGetRegistry=Rt;exports.TengoTemplateGetTemplate=Bt;exports.TengoTemplateGetTemplateURI=Ot;exports.TengoTemplatePack=Ft;exports.TengoTemplatePackConvert=Dt;exports.TengoTemplatePackConvertTemplate=xt;exports.TengoTemplatePackConvertTemplatePack=Tt;exports.V1CentralDevSnapshotRegistry=mr;exports.V1CentralRegistry=fr;exports.V2RegistryProvider=wt;exports.checkNetwork=as;exports.createRenderTemplate=$e;exports.getDevV1PacketMtime=Je;exports.getDevV2PacketMtime=ve;exports.initDriverKit=qt;exports.loadTemplate=ye;exports.prepareTemplateSpec=Et;Object.keys(P).forEach(o=>{o!=="default"&&!Object.prototype.hasOwnProperty.call(exports,o)&&Object.defineProperty(exports,o,{enumerable:!0,get:()=>P[o]})});Object.keys(te).forEach(o=>{o!=="default"&&!Object.prototype.hasOwnProperty.call(exports,o)&&Object.defineProperty(exports,o,{enumerable:!0,get:()=>te[o]})});Object.keys(d).forEach(o=>{o!=="default"&&!Object.prototype.hasOwnProperty.call(exports,o)&&Object.defineProperty(exports,o,{enumerable:!0,get:()=>d[o]})});
49
49
  //# sourceMappingURL=index.js.map