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