@milaboratories/pl-middle-layer 1.10.21 → 1.10.23
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/block_registry/index.d.ts +0 -1
- package/dist/block_registry/index.d.ts.map +1 -1
- package/dist/block_registry/registry-v2-provider.d.ts +9 -0
- package/dist/block_registry/registry-v2-provider.d.ts.map +1 -0
- package/dist/block_registry/registry.d.ts +6 -28
- package/dist/block_registry/registry.d.ts.map +1 -1
- package/dist/block_registry/watcher.d.ts.map +1 -1
- package/dist/block_registry/well_known_registries.d.ts +4 -3
- package/dist/block_registry/well_known_registries.d.ts.map +1 -1
- package/dist/index.d.ts +0 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +360 -340
- package/dist/index.mjs.map +1 -1
- package/dist/mutator/block-pack/block_pack.d.ts.map +1 -1
- package/dist/test/block_packs.d.ts.map +1 -1
- package/package.json +10 -9
- package/src/block_registry/index.ts +0 -1
- package/src/block_registry/registry-v2-provider.ts +16 -0
- package/src/block_registry/registry.test.ts +9 -30
- package/src/block_registry/registry.ts +84 -72
- package/src/block_registry/watcher.ts +6 -3
- package/src/block_registry/well_known_registries.ts +10 -7
- package/src/index.ts +0 -3
- package/src/middle_layer/middle_layer.test.ts +50 -38
- package/src/middle_layer/render.test.ts +5 -10
- package/src/mutator/block-pack/block_pack.test.ts +7 -10
- package/src/mutator/block-pack/block_pack.ts +13 -5
- package/src/test/block_packs.ts +10 -6
- package/dist/block_registry/registry_spec.d.ts +0 -12
- package/dist/block_registry/registry_spec.d.ts.map +0 -1
- package/src/block_registry/registry_spec.ts +0 -13
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/block_registry/index.ts"],"names":[],"mappings":"AAAA,cAAc,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/block_registry/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,yBAAyB,CAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { RegistryV2Reader } from '@platforma-sdk/block-tools';
|
|
2
|
+
import { Dispatcher } from 'undici';
|
|
3
|
+
export declare class V2RegistryProvider {
|
|
4
|
+
private readonly http;
|
|
5
|
+
private readonly registries;
|
|
6
|
+
constructor(http: Dispatcher);
|
|
7
|
+
getRegistry(url: string): RegistryV2Reader;
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=registry-v2-provider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"registry-v2-provider.d.ts","sourceRoot":"","sources":["../../src/block_registry/registry-v2-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEpC,qBAAa,kBAAkB;IAGjB,OAAO,CAAC,QAAQ,CAAC,IAAI;IAFjC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAuC;gBAErC,IAAI,EAAE,UAAU;IAEtC,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,gBAAgB;CAOlD"}
|
|
@@ -1,37 +1,15 @@
|
|
|
1
1
|
import { Dispatcher } from 'undici';
|
|
2
|
-
import { RegistrySpec } from './registry_spec';
|
|
3
|
-
import { BlockPackSpecAny } from '../model';
|
|
4
2
|
import { BlockPackDescriptionAbsolute } from '@platforma-sdk/block-tools';
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
* */
|
|
8
|
-
export type BlockPackMeta = {
|
|
9
|
-
title: string;
|
|
10
|
-
description: string;
|
|
11
|
-
[metaField: string]: unknown;
|
|
12
|
-
};
|
|
13
|
-
/**
|
|
14
|
-
* Information about specific package with specific organization and package names.
|
|
15
|
-
* Mainly contain information about latest version of the package.
|
|
16
|
-
* */
|
|
17
|
-
export type BlockPackPackageOverview = {
|
|
18
|
-
organization: string;
|
|
19
|
-
/** @deprecated */
|
|
20
|
-
package: string;
|
|
21
|
-
name: string;
|
|
22
|
-
latestVersion: string;
|
|
23
|
-
latestMeta: BlockPackMeta;
|
|
24
|
-
registryLabel: string;
|
|
25
|
-
latestSpec: BlockPackSpecAny;
|
|
26
|
-
otherVersions: string[];
|
|
27
|
-
};
|
|
3
|
+
import { V2RegistryProvider } from './registry-v2-provider';
|
|
4
|
+
import { BlockPackListing, RegistryEntry } from '@milaboratories/pl-model-middle-layer';
|
|
28
5
|
export declare function getDevV1PacketMtime(devPath: string): Promise<string>;
|
|
29
6
|
export declare function getDevV2PacketMtime(description: BlockPackDescriptionAbsolute): Promise<string>;
|
|
30
7
|
export declare class BlockPackRegistry {
|
|
31
|
-
private readonly
|
|
8
|
+
private readonly v2Provider;
|
|
9
|
+
private readonly registries;
|
|
32
10
|
private readonly http?;
|
|
33
|
-
constructor(
|
|
11
|
+
constructor(v2Provider: V2RegistryProvider, registries: RegistryEntry[], http?: Dispatcher | undefined);
|
|
34
12
|
private getPackagesForRoot;
|
|
35
|
-
|
|
13
|
+
listBlockPacks(): Promise<BlockPackListing>;
|
|
36
14
|
}
|
|
37
15
|
//# sourceMappingURL=registry.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/block_registry/registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAW,MAAM,QAAQ,CAAC;
|
|
1
|
+
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/block_registry/registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAW,MAAM,QAAQ,CAAC;AAE7C,OAAO,EACL,4BAA4B,EAG7B,MAAM,4BAA4B,CAAC;AAOpC,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EACL,gBAAgB,EAEhB,aAAa,EAGd,MAAM,uCAAuC,CAAC;AAwB/C,wBAAsB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAS1E;AAED,wBAAsB,mBAAmB,CACvC,WAAW,EAAE,4BAA4B,GACxC,OAAO,CAAC,MAAM,CAAC,CAOjB;AAED,qBAAa,iBAAiB;IAE1B,OAAO,CAAC,QAAQ,CAAC,UAAU;IAC3B,OAAO,CAAC,QAAQ,CAAC,UAAU;IAC3B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC;gBAFL,UAAU,EAAE,kBAAkB,EAC9B,UAAU,EAAE,aAAa,EAAE,EAC3B,IAAI,CAAC,EAAE,UAAU,YAAA;YAGtB,kBAAkB;IA6GnB,cAAc,IAAI,OAAO,CAAC,gBAAgB,CAAC;CASzD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"watcher.d.ts","sourceRoot":"","sources":["../../src/block_registry/watcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC7E,OAAO,EAAE,aAAa,EAAE,MAAM,uCAAuC,CAAC;AACtE,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAIpC,eAAO,MAAM,4BAA4B,EAAE,WAE1C,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG,OAAO,CAAC,WAAW,CAAC,GAAG;IAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,UAAU,CAAA;CAAE,CAAC;AAI1F,qBAAa,kBAAmB,SAAQ,kBAAkB,CACxD,aAAa,EACb,aAAa,GAAG,SAAS,CAC1B;IACC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAa;gBAEvB,GAAG,GAAE,qBAA0B;IAK3C,SAAS,CAAC,MAAM,CAAC,GAAG,EAAE,aAAa,GAAG,MAAM;
|
|
1
|
+
{"version":3,"file":"watcher.d.ts","sourceRoot":"","sources":["../../src/block_registry/watcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC7E,OAAO,EAAE,aAAa,EAAE,MAAM,uCAAuC,CAAC;AACtE,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAIpC,eAAO,MAAM,4BAA4B,EAAE,WAE1C,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG,OAAO,CAAC,WAAW,CAAC,GAAG;IAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,UAAU,CAAA;CAAE,CAAC;AAI1F,qBAAa,kBAAmB,SAAQ,kBAAkB,CACxD,aAAa,EACb,aAAa,GAAG,SAAS,CAC1B;IACC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAa;gBAEvB,GAAG,GAAE,qBAA0B;IAK3C,SAAS,CAAC,MAAM,CAAC,GAAG,EAAE,aAAa,GAAG,MAAM;cAW5B,SAAS,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC;IAuBjF,SAAS,CAAC,YAAY,CACpB,IAAI,EAAE,aAAa,GAAG,SAAS,EAC/B,IAAI,EAAE,aAAa,GAAG,SAAS,GAC9B,OAAO;CAYX"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { RegistrySpec } from '
|
|
2
|
-
export declare const
|
|
3
|
-
export declare const
|
|
1
|
+
import { RegistrySpec } from '@milaboratories/pl-model-middle-layer';
|
|
2
|
+
export declare const CentralBlockRegistry: RegistrySpec;
|
|
3
|
+
export declare const V1CentralRegistry: RegistrySpec;
|
|
4
|
+
export declare const V1CentralDevSnapshotRegistry: RegistrySpec;
|
|
4
5
|
//# sourceMappingURL=well_known_registries.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"well_known_registries.d.ts","sourceRoot":"","sources":["../../src/block_registry/well_known_registries.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"well_known_registries.d.ts","sourceRoot":"","sources":["../../src/block_registry/well_known_registries.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,uCAAuC,CAAC;AAErE,eAAO,MAAM,oBAAoB,EAAE,YAGlC,CAAC;AAEF,eAAO,MAAM,iBAAiB,EAAE,YAG/B,CAAC;AAEF,eAAO,MAAM,4BAA4B,EAAE,YAG1C,CAAC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -9,5 +9,4 @@ export type { FieldType, ResourceType } from '@milaboratories/pl-client';
|
|
|
9
9
|
export * from './mutator/template/template_loading';
|
|
10
10
|
export * from './mutator/template/render_template';
|
|
11
11
|
export * from './model/template_spec';
|
|
12
|
-
export { type BlockPackMeta } from './block_registry';
|
|
13
12
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,cAAc,uCAAuC,CAAC;AAEtD,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,SAAS,CAAC;AAGxB,OAAO,EAAE,KAAK,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAGhD,cAAc,2BAA2B,CAAC;AAC1C,YAAY,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAGzE,cAAc,qCAAqC,CAAC;AACpD,cAAc,oCAAoC,CAAC;AACnD,cAAc,uBAAuB,CAAC
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,cAAc,uCAAuC,CAAC;AAEtD,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,SAAS,CAAC;AAGxB,OAAO,EAAE,KAAK,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAGhD,cAAc,2BAA2B,CAAC;AAC1C,YAAY,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAGzE,cAAc,qCAAqC,CAAC;AACpD,cAAc,oCAAoC,CAAC;AACnD,cAAc,uBAAuB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Lt=Object.defineProperty;var Jt=(o,e,t)=>e in o?Lt(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var p=(o,e,t)=>Jt(o,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const F=require("@platforma-sdk/model"),He=require("@milaboratories/pl-model-middle-layer"),re=require("undici"),N=require("@platforma-sdk/block-tools"),j=require("node:fs"),I=require("node:path"),Mt=require("yaml"),f=require("@milaboratories/ts-helpers"),Kt=require("node:fs/promises"),Ut=require("@milaboratories/resolve-helper"),l=require("@milaboratories/pl-client"),Be=require("@milaboratories/pl-tree"),S=require("@milaboratories/computable"),M=require("node:crypto"),it=require("denque"),$t=require("@platforma-sdk/workflow-tengo"),Oe=require("canonicalize"),Gt=require("node:assert"),ne=require("quickjs-emscripten"),Ht=require("node:timers/promises"),_t=require("node:os"),x=require("@milaboratories/pl-drivers"),qt=require("@milaboratories/pframes-node");function at(o){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const t in o)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>o[t]})}}return e.default=o,Object.freeze(e)}const Wt=at(Kt),ct=at(_t);async function _e(o){try{return await Wt.stat(o,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const zt=[N.RegistryV1.PlPackageYamlConfigFile],Yt=[N.RegistryV1.PlPackageJsonConfigFile],De=["backend","dist","tengo","tpl","main.plj.gz"],Te=["config","dist","config.json"],ut=["frontend","dist"],qe="block-model/dist/config.json",Qt="block-ui/package.json",Zt=[De,Te,zt,Yt,ut];async function Xt(o){return await _e(I.join(o,...Te))!==void 0||await _e(I.join(o,...De))!==void 0}function ge(o,e){const t=Ut.tryResolve(o,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${o}`);return t}async function We(o,e){if(I.isAbsolute(o)||(o=I.resolve(o)),await Xt(o))return{workflow:I.join(o,...De),config:I.join(o,...Te),ui:I.join(o,...ut)};{const t=ge(o,qe),r=ge(o,qe),s=ge(o,Qt);return{workflow:t,config:r,ui:I.resolve(s,"..","dist")}}}async function er(o){try{return await j.promises.readFile(o,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}async function tr(o){try{return await j.promises.stat(o,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}async function Ee(o){let e=0n;for(const t of Zt){const r=I.join(o,...t),s=await tr(r);s!==void 0&&e<s.mtimeNs&&(e=s.mtimeNs)}return e.toString()}async function le(o){const e=await j.promises.stat(o.components.workflow.file,{bigint:!0}),t=await j.promises.stat(o.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class rr{constructor(e,t){this.registrySpecs=e,this.http=t}async getPackagesForRoot(e){const t=[];switch(e.type){case"remote_v1":const r=this.http!==void 0?{dispatcher:this.http}:{},n=await(await re.request(`${e.url}/${N.RegistryV1.GlobalOverviewPath}`,r)).body.json();for(const i of n){const{organization:a,package:u,latestMeta:c,latestVersion:d}=i;t.push({organization:a,package:u,name:u,latestVersion:d,latestMeta:c,registryLabel:e.label,latestSpec:{type:"from-registry-v1",registryUrl:e.url,organization:a,package:u,version:d},otherVersions:i.allVersions})}return t;case"folder_with_dev_packages":for(const i of await j.promises.readdir(e.path,{withFileTypes:!0})){if(!i.isDirectory())continue;const a=I.join(e.path,i.name),u=await er(I.join(a,N.RegistryV1.PlPackageYamlConfigFile));if(u!==void 0){const d=N.RegistryV1.PlPackageConfigData.parse(Mt.parse(u)),h=await Ee(a);t.push({organization:d.organization,package:d.package,name:d.package,latestVersion:"DEV",latestMeta:d.meta,registryLabel:e.label,latestSpec:{type:"dev-v1",folder:a,mtime:h},otherVersions:[]})}const c=await N.tryLoadPackDescription(a);if(c!==void 0){const d=await le(c);t.push({organization:c.id.organization,package:c.id.name,name:c.id.name,latestVersion:`${c.id.version}-DEV`,latestMeta:c.meta,registryLabel:e.label,latestSpec:{type:"dev-v2",folder:a,mtime:d},otherVersions:[]})}}return t;default:return f.assertNever(e)}}async getPackagesOverview(){const e=[];for(const t of this.registrySpecs)e.push(...await this.getPackagesForRoot(t));return e}}const or={type:"remote_v1",label:"Central Release Registry",url:"https://block.registry.platforma.bio/releases"},sr={type:"remote_v1",label:"Central Dev Snapshot registry",url:"https://block.registry.platforma.bio/dev"},nr={groups:[{id:"default",label:"Default",blocks:[]}]},ir={stagingRefreshTimestamp:0,blocksInLimbo:[]},ar={label:"New Project"},cr={name:"UserProject",version:"2"},lt="SchemaVersion",dt="1",je="ProjectCreated",z="ProjectLastModified",Y="ProjectMeta",G="ProjectStructure",ie="BlockRenderingState",ur="BlockFrontendState/",lr=/^BlockFrontendState\/(?<blockid>.*)$/;function be(o){return`${ur}${o}`}const dr="BlockArgsAuthor/";function we(o){return`${dr}${o}`}const Se="ProjectStructureAuthor";function pr(o){const e=o.match(lr);if(e!==null)return e.groups.blockid}const hr="__serviceTemplate_";function ke(o){return`${hr}${o}`}function P(o,e){return`${o}-${e}`}const fr=/^(?<blockId>.*)-(?<fieldName>blockPack|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function gr(o){const e=o.match(fr);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const mr="projects",pt={name:"Projects",version:"1"},vr=o=>l.resourceTypesEqual(o.type,pt)?o.fields:[];async function yr(o,e,t,r){const s=await Be.SynchronizedTreeState.init(o,e,{...r.ops.defaultTreeOptions,pruning:vr});return{computable:S.Computable.make(i=>{const a=i.accessor(s.entry()).node(),u=t.getValue(i);if(a===void 0)return;const c=[];for(const d of a.listDynamicFields()){const h=a.traverse(d);if(h===void 0)continue;const g=f.notEmpty(h.getKeyValueAsJson(Y)),v=f.notEmpty(h.getKeyValueAsJson(je)),w=f.notEmpty(h.getKeyValueAsJson(z));c.push({id:d,rid:h.id,created:new Date(v),lastModified:new Date(w),opened:u.indexOf(h.id)>=0,meta:g})}return c.sort(d=>-d.lastModified.valueOf()),c}).withStableType(),tree:s}}const br={name:"EphRenderTemplate",version:"1"},wr={name:"RenderTemplate",version:"1"};function xe(o,e,t,r,s){if(s.length===0)throw new Error("Zero output names provided");const n=t?o.createEphemeral(br):o.createStruct(wr),i=l.field(n,"template"),a=l.field(n,"inputs");return o.createField(i,"Input",e),o.createField(a,"Input",l.Pl.createPlMap(o,r,t)),o.lockInputs(n),l.Pl.futureRecord(o,n,s,"Output","outputs/")}const Sr={name:"BContextEnd",version:"1"},kr={name:"BContext",version:"1"},Pr="id",Cr="parent/",Fr=["context","result"];function ze(o,e,t){return xe(o,e,!0,t,Fr)}function Rr(o){const e=o.createEphemeral(Sr);return o.lock(e),e}function Br(o,e){if(e.length===0)return Rr(o);if(e.length===1)return e[0];const t=o.createEphemeral(kr);o.createField(l.field(t,Pr),"Input",l.Pl.createPlString(o,M.randomUUID()));for(let r=0;r<e.length;r++)o.createField(l.field(t,`${Cr}${r}`),"Input",e[r]);return o.lock(t),t}const ht={name:"TengoTemplateGet",version:"1"},ft="registry",gt="templateURI",mt="template",vt={name:"TengoTemplatePack",version:"1"},yt={name:"TengoTemplatePackConvert",version:"1"},bt="templatePack",wt="template";async function St(o){switch(o.type){case"from-file":return{type:"explicit",content:await j.promises.readFile(o.path)};case"from-registry":case"explicit":return o;default:return f.assertNever(o)}}function Or(o,e){const t=o.createStruct(ht),r=l.field(t,ft),s=l.field(t,gt),n=l.field(t,mt);return o.setField(r,o.createValue(l.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),o.setField(s,o.createValue(l.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function Dr(o,e){const t=o.createValue(vt,e.content),r=o.createStruct(yt),s=l.field(r,bt),n=l.field(r,wt);return o.setField(s,t),n}function de(o,e){switch(e.type){case"from-registry":return Or(o,e);case"explicit":return Dr(o,e);default:return f.assertNever(e)}}const Ae={name:"Frontend/FromUrl",version:"1"},Ie={name:"Frontend/FromFolder",version:"1"};function Tr(o,e){switch(e.type){case"url":return o.createValue(Ae,JSON.stringify({url:e.url}));case"local":return o.createValue(Ie,JSON.stringify({path:e.path,signature:e.signature}));default:return f.assertNever(e)}}const Er={name:"BlockPackCustom",version:"1"},kt="template",Pt="frontend";function Ye(o){return o.endsWith("/")?o:`${o}/`}class jr{constructor(e,t){this.signer=e,this.http=t}async getBlockConfig(e){switch(e.type){case"explicit":return e.config;case"dev":case"dev-v1":{const t=await We(e.folder),r=await j.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await N.loadPackDescription(e.folder),r=await j.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=`${Ye(e.registryUrl)}${N.RegistryV1.packageContentPrefix(e)}`;return await(await re.request(`${r}/config.json`,t)).body.json()}default:return f.assertNever(e)}}async prepare(e){switch(e.type){case"explicit":return e;case"dev":case"dev-v1":{const t=await We(e.folder),r=await j.promises.readFile(t.workflow),s=JSON.parse(await j.promises.readFile(t.config,"utf-8")),n=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:s,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:e}}case"dev-v2":{const t=await N.loadPackDescription(e.folder),r=JSON.parse(await j.promises.readFile(t.components.model.file,{encoding:"utf-8"})),s=await j.promises.readFile(t.components.workflow.file),n=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await le(t)),{type:"explicit",template:{type:"explicit",content:s},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=`${Ye(e.registryUrl)}${N.RegistryV1.packageContentPrefix(e)}`,s=`${r}/template.plj.gz`,n=await re.request(s,t);if(n.statusCode!==200)throw new Error(`Block not found in registry (url = ${s} ; code = ${n.statusCode}): `+JSON.stringify(e));const i=new Uint8Array(await n.body.arrayBuffer()),u=await(await re.request(`${r}/config.json`,t)).body.json();return{type:"explicit",template:{type:"explicit",content:i},config:u,frontend:{type:"url",url:`${r}/frontend.tgz`},source:e}}default:return f.assertNever(e)}}}function xr(o,e){const t={config:e.config,source:e.source},r=o.createStruct(Er,JSON.stringify(t));return o.createField(l.field(r,kt),"Input",de(o,e.template)),o.createField(l.field(r,Pt),"Input",Tr(o,e.frontend)),o.lock(r),r}function Qe(o,e){switch(e.type){case"explicit":return xr(o,e);default:return f.assertNever(e.type)}}function te(o,e){return{__isRef:!0,blockId:o,name:e}}function Ar(o){return typeof o=="object"&&o!==null&&o.__isRef===!0&&"blockId"in o&&"name"in o}function Pe(o,e,t){const r=typeof e;switch(r){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if(Ar(e))t===void 0||t.has(e.blockId)?o.upstreams.add(e.blockId):o.missingReferences=!0;else if(Array.isArray(e))for(const s of e)Pe(o,s,t);else for(const[,s]of Object.entries(e))Pe(o,s,t);return;default:f.assertNever(r)}}function Ir(o,e){const t={upstreams:new Set,missingReferences:!1};return Pe(t,o,e),t}function V(o){return{*[Symbol.iterator](){for(const e of o.groups)for(const t of e.blocks)yield t}}}class Ct{constructor(e){p(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,s=>r.add(s.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const s of t)r.delete(s);return r}traverse(e,t,r){let s=[...t];const n=new Set(s);for(;s.length>0;){let i=[];for(const a of s){const u=this.nodes.get(a);r(u),u[e].forEach(c=>{n.has(c)||(n.add(c),i.push(c))})}s=i}}}function Ce(o){const e=new Map;let t;for(const{id:r}of V(o)){const s={id:r,missingReferences:!1};e.set(r,s),t===void 0?s.upstream=new Set:(s.upstream=new Set([t.id]),t.downstream=new Set([s.id])),t=s}return t!==void 0&&(t.downstream=new Set),new Ct(e)}function oe(o,e){const t=new Map,r=new Set;for(const{id:s}of V(o)){const n=e(s);if(n===void 0)continue;const i=Ir(n,r),a={id:s,missingReferences:i.missingReferences,upstream:i.upstreams,downstream:new Set};t.set(s,a),i.upstreams.forEach(u=>t.get(u).downstream.add(s)),r.add(s)}return new Ct(t)}function Nr(o,e){if(o.size!==e.size)return!1;for(const t of o)if(!e.has(t))return!1;return!0}function Fe(o,e){if(o.size>e.size)return Fe(e,o);for(const t of o)if(e.has(t))return!0;return!1}function Ze(o,e){const t=new Set,r=new Set,s=new Set;return o.nodes.forEach(n=>{const i=e.nodes.get(n.id);i===void 0?t.add(n.id):(!Nr(n.upstream,i.upstream)||Fe(n.upstream,s))&&s.add(n.id)}),e.nodes.forEach(n=>{o.nodes.has(n.id)?Fe(n.upstream,s)&&s.add(n.id):r.add(n.id)}),{onlyInA:t,onlyInB:r,different:s}}let me;async function Ft(){if(me===void 0){const o=await St($t.Templates["pframes.export-pframe"]);if(o.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=M.createHash("sha256").update(o.content).digest("hex");me={spec:o,hash:e}}return me}function Vr(o,e,t){return xe(o,e,!0,{pf:t},["result"]).result}function ve(o,e){let t=!1,r,s;return()=>{if(!t)return t=!0,r=o(),s=e(),s;const n=o();return r!==n&&(r=n,s=e()),e()}}class Xe{constructor(e,t){p(this,"currentInputsC",ve(()=>this.fields.currentArgs.modCount,()=>JSON.parse(Buffer.from(this.fields.currentArgs.value).toString())));p(this,"actualProductionInputsC",ve(()=>{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())}));p(this,"productionStaleC",ve(()=>{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(l.Pl.unwrapHolder(e,this.fields.blockPack.ref),kt,"Input")}}const Lr=o=>{throw new Error(`No new block info for ${o}`)};class ae{constructor(e,t,r,s,n,i,a,u,c,d,h,g){p(this,"globalModCount",0);p(this,"fieldsChanged",!1);p(this,"lastModifiedChanged",!1);p(this,"structureChanged",!1);p(this,"metaChanged",!1);p(this,"renderingStateChanged",!1);p(this,"changedBlockFrontendStates",new Set);p(this,"blocksWithChangedInputs",new Set);p(this,"stagingGraph");p(this,"pendingProductionGraph");p(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=s,this.lastModified=n,this.meta=i,this.struct=a,this.renderingState=u,this.blocksInLimbo=c,this.blockInfos=d,this.blockFrontendStates=h,this.ctxExportTplHolder=g}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=Ce(this.struct)),this.stagingGraph}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=oe(this.struct,e=>this.getBlockInfo(e).currentInputs)),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=oe(this.struct,e=>this.getBlockInfo(e).actualProductionInputs)),this.actualProductionGraph}getBlockInfo(e){return f.notEmpty(this.blockInfos.get(e))}getBlock(e){for(const t of V(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const s=l.field(this.rid,P(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(s,"Dynamic",r.ref):this.tx.setField(s,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,s,n){this.setBlockFieldObj(e,t,{ref:r,status:s,value:n})}deleteBlockFields(e,...t){let r=!1;const s=this.getBlockInfo(e);for(const n of t){const i=s.fields;n in i&&(this.tx.removeField(l.field(this.rid,P(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,s,n;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((s=t.stagingCtx)==null?void 0:s.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,s,n;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((s=t.prodCtx)==null?void 0:s.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,s;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((s=t.prodCtx)==null?void 0:s.status)==="Ready"?this.blocksInLimbo.has(e)?!1:(this.blocksInLimbo.add(e),this.renderingStateChanged=!0,this.deleteBlockFields(e,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),!0):this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}setArgs(e){const t=[];for(const{blockId:r,args:s}of e){const n=this.getBlockInfo(r);JSON.parse(s);const i=Buffer.from(s);if(Buffer.compare(n.fields.currentArgs.value,i)===0)continue;const a=this.tx.createValue(l.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())}setBlockLabel(e,t){const r=this.structure;let s=!1;for(const n of V(r))if(n.id===e){n.label=t,s=!0;break}if(!s)throw new Error(`block ${e} not found`);this.updateStructure(r),this.updateLastModified()}createCtx(e,t){const r=[];return e.forEach(s=>{const n=this.getBlockInfo(s);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(l.Pl.unwrapHolder(this.tx,n.fields[t].ref))}),Br(this.tx,r)}exportCtx(e){return Vr(this.tx,l.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createCtx(this.getStagingGraph().nodes.get(e).upstream,"stagingCtx");if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const s=t.getTemplate(this.tx),n=ze(this.tx,s,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(l.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(l.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",l.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 s=t.getTemplate(this.tx),n=ze(this.tx,s,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(l.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(l.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",l.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=Lr){const r=this.getStagingGraph(),s=this.getActualProductionGraph(),n=Ce(e),i=oe(e,c=>{var d;return(d=this.blockInfos.get(c))==null?void 0:d.actualProductionInputs}),a=Ze(r,n),u=Ze(s,i);for(const c of a.onlyInA){const{fields:d}=this.getBlockInfo(c);this.deleteBlockFields(c,...Object.keys(d)),this.blockInfos.delete(c),this.blocksInLimbo.delete(c)&&(this.renderingStateChanged=!0),this.blockFrontendStates.delete(c)&&this.changedBlockFrontendStates.add(c)}for(const c of a.onlyInB){const d=new Xe(c,{});this.blockInfos.set(c,d);const h=t(c),g=Qe(this.tx,h.blockPack);this.setBlockField(c,"blockPack",l.Pl.wrapInHolder(this.tx,g),"NotReady");const v=Buffer.from(h.args),w=this.tx.createValue(l.Pl.JsonObject,v);this.setBlockField(c,"currentArgs",w,"Ready",v),d.check()}for(const c of a.different)this.resetStaging(c);s.traverse("downstream",[...u.different],c=>{this.resetOrLimboProduction(c.id)}),(a.onlyInB.size>0||a.onlyInA.size>0||a.different.size>0)&&this.resetStagingRefreshTimestamp(),this.struct=e,this.structureChanged=!0,this.stagingGraph=void 0,this.pendingProductionGraph=void 0,this.actualProductionGraph=void 0,this.updateLastModified()}addBlock(e,t,r){const s=this.structure;if(r===void 0)s.groups[s.groups.length-1].blocks.push(e);else{let n=!1;for(const i of s.groups){const a=i.blocks.findIndex(u=>u.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(s,n=>{if(n!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const s of t.groups){const n=s.blocks.findIndex(i=>i.id===e);if(!(n<0)){s.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 s=this.getBlockInfo(e);this.setBlockField(e,"blockPack",l.Pl.wrapInHolder(this.tx,Qe(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)),s.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:n})=>this.resetOrLimboProduction(n)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),s=this.getPendingProductionGraph();if(t)s.traverse("upstream",e,i=>{r.add(i.id)});else for(const i of r){const a=s.nodes.get(i);if(a===void 0)throw new Error(`Can't find block with id: ${i}`);for(const u of a.upstream)if(!r.has(u))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const i of V(this.structure)){if(!r.has(i.id))continue;let a=this.getBlockInfo(i.id).requireProductionRendering||this.blocksInLimbo.has(i.id);if(!a){for(const u of s.nodes.get(i.id).upstream)if(n.has(u)){a=!0;break}}a&&(this.renderProductionFor(i.id),n.add(i.id))}return s.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 it(e),s=new Set(e),n=[];for(;!r.isEmpty();){const u=r.shift(),c=this.getBlockInfo(u).fields;if(!(((i=c.prodOutput)==null?void 0:i.status)==="Ready"&&((a=c.prodCtx)==null?void 0:a.status)==="Ready")&&this.deleteBlockFields(u,"prodOutput","prodCtx","prodUiCtx","prodArgs")){n.push(u);for(const d of t.traverseIdsExcludingRoots("downstream",u))s.has(d)||(r.push(d),s.add(d))}}for(const u of t.traverseIdsExcludingRoots("downstream",...n))this.resetOrLimboProduction(u)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(s=>{let i=this.getBlockInfo(s.id).stagingRendered?0:1;s.upstream.forEach(a=>{const u=t.get(a);u!==0&&(i=Math.max(u+1,i))}),e(s.id,i),t.set(s.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 s=0;this.traverseWithStagingLag((n,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(n),s++)}),s>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,s,n,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((s=t.fields.prodOutput)==null?void 0:s.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((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,we(t)):this.tx.setKValue(this.rid,we(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,Se):this.tx.setKValue(this.rid,Se,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,z,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,G,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,ie,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,Y,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,be(e)):this.tx.setKValue(this.rid,be(e),t)}this.assignAuthorMarkers()}}static async load(e,t,r){const s=e.getResourceData(t,!0),n=e.getKValueJson(t,lt),i=e.getKValueJson(t,z),a=e.getKValueJson(t,Y),u=e.getKValueJson(t,G),c=e.getKValueJson(t,ie),d=e.listKeyValuesString(t),[h,g,v,w,R,{stagingRefreshTimestamp:U,blocksInLimbo:Q},Z]=await Promise.all([s,n,i,a,u,c,d]);if(g!==dt)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${g}`);const $=new Map;for(const b of h.fields){const O=gr(b.name);if(O===void 0)continue;let C=$.get(O.blockId);C===void 0&&(C={id:O.blockId,fields:{}},$.set(O.blockId,C)),C.fields[O.fieldName]=l.isNullResourceId(b.value)?{modCount:0}:{modCount:0,ref:b.value}}const H=await Ft(),X=ke(H.hash),k=h.fields.find(b=>b.name===X);let J;k!==void 0?J=l.ensureResourceIdNotNull(k.value):(J=l.Pl.wrapInHolder(e,de(e,H.spec)),e.createField(l.field(t,ke(H.hash)),"Dynamic",J));const _={stagingRefreshTimestamp:U},E=new Set(Q),D=new Map;for(const b of Z){const O=pr(b.key);O!==void 0&&D.set(O,b.value)}const B=[];$.forEach(({id:b,fields:O})=>{for(const[,C]of Object.entries(O))if(C.ref!==void 0){if(!l.isResource(C.ref)||l.isResourceRef(C.ref))throw new Error("unexpected behaviour");B.push([C,e.getResourceData(C.ref,!1)])}});for(const[b,O]of B){const C=await O;b.value=C.data,l.isNotNullResourceId(C.error)?b.status="Error":C.resourceReady||l.isNotNullResourceId(C.originalResourceId)?b.status="Ready":b.status="NotReady"}const K=new Map;$.forEach(({id:b,fields:O})=>K.set(b,new Xe(b,O)));const L=new Set;for(const b of V(R)){if(!K.has(b.id))throw new Error(`Inconsistent project structure: no inputs for ${b.id}`);L.add(b.id)}K.forEach(b=>{if(!L.has(b.id))throw new Error(`Inconsistent project structure: no structure entry for ${b.id}`);b.check()});const ee=new ae(t,e,r,g,v,w,R,_,E,K,D,J);return ee.fixProblems(),ee}}async function Jr(o,e=ar){const t=o.createEphemeral(cr);o.lock(t);const r=String(Date.now());o.setKValue(t,lt,JSON.stringify(dt)),o.setKValue(t,je,r),o.setKValue(t,z,r),o.setKValue(t,Y,JSON.stringify(e)),o.setKValue(t,G,JSON.stringify(nr)),o.setKValue(t,ie,JSON.stringify(ir));const s=await Ft();return o.createField(l.field(t,ke(s.hash)),"Dynamic",l.Pl.wrapInHolder(o,de(o,s.spec))),t}async function ye(o,e,t){return A(o,e,void 0,t)}async function A(o,e,t,r){if(o instanceof l.PlClient)return await o.withWriteTx("ProjectAction",async s=>{const n=await ae.load(s,e,t),i=await r(n);return n.wasModified&&(n.save(),await s.commit()),i});{const s=await ae.load(o,e,t),n=await r(s);return s.save(),n}}function*Mr(o){switch(o.type){case"Json":return;case"JsonPartitioned":for(const[,e]of Object.entries(o.parts))yield e;return;case"BinaryPartitioned":for(const[,{index:e,values:t}]of Object.entries(o.parts))yield e,yield t;return;default:f.assertNever(o)}}function et(o,e){return Object.fromEntries(Object.entries(o).map(([t,r])=>[t,e(r,t)]))}function Kr(o,e){switch(o.type){case"Json":return{...o};case"JsonPartitioned":return{...o,parts:et(o.parts,e)};case"BinaryPartitioned":return{...o,parts:et(o.parts,t=>({index:e(t.index),values:e(t.values)}))};default:f.assertNever(o)}}const Ur=l.resourceType("PColumnData/JsonPartitioned","1"),$r=l.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Gr=l.resourceType("PColumnData/BinaryPartitioned","1"),Hr=l.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),_r=l.resourceType("PColumnData/Json","1");function qr(o){if(!o.getIsReadyOrError())throw new Error("Data not ready.");const e=o.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(l.resourceTypesEqual(o.resourceType,_r)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(l.resourceTypesEqual(o.resourceType,Ur)){const t=e,r=Object.fromEntries(o.listInputFields().map(s=>[s,o.traverse({field:s,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(l.resourceTypesEqual(o.resourceType,$r)){const t=e,r={};for(const s of o.listInputFields()){const n=o.traverse({field:s,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${s}`);for(const a of i){const u=s.slice(0,s.length-1)+","+a.slice(1,a.length);r[u]=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(l.resourceTypesEqual(o.resourceType,Gr)){const t=e,r={};for(const s of o.listInputFields())if(s.endsWith(".index")){const n=s.slice(0,s.length-6);let i=r[n];i===void 0&&(i={},r[n]=i),i.index=o.traverse({field:s,errorIfFieldNotSet:!0}).resourceInfo}else if(s.endsWith(".values")){const n=s.slice(0,s.length-7);let i=r[n];i===void 0&&(i={},r[n]=i),i.values=o.traverse({field:s,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${s}`);for(const[s,n]of Object.entries(r)){if(n.index===void 0)throw new Error(`no index for part ${s}`);if(n.values===void 0)throw new Error(`no values for part ${s}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(l.resourceTypesEqual(o.resourceType,Hr)){const t=e,r={};for(const s of o.listInputFields()){const n=o.traverse({field:s,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${s}`);for(const a of i)if(a.endsWith(".index")){const u=a.slice(0,a.length-6),c=s.slice(0,s.length-1)+","+u.slice(1,u.length);let d=r[c];d===void 0&&(d={},r[c]=d),r[c].index=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else if(a.endsWith(".values")){const u=a.slice(0,a.length-7),c=s.slice(0,s.length-1)+","+u.slice(1,u.length);let d=r[c];d===void 0&&(d={},r[c]=d),r[c].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: ${l.resourceTypeToString(o.resourceType)}`)}function Rt(o,e){const t=M.createHash("sha256");return t.update(Oe(o)),t.update(String(l.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function Bt(o,e=!0,t=!1,r=""){var a,u,c;const s=/^(?<name>.*)\.(?<type>spec|data)$/,n=new Map;for(const d of o.listInputFields()){const h=d.match(s);if(!h){if(e)throw new Error(`unexpected field name ${d}`);continue}let g=f.notEmpty((a=h.groups)==null?void 0:a.name);if(!g.startsWith(r)){if(e)throw new Error(`unexpected field name ${d}`);continue}g=g.slice(r.length);const v=f.notEmpty((u=h.groups)==null?void 0:u.type);let w=n.get(g);switch(w===void 0&&(w={},n.set(g,w)),v){case"spec":w.spec=(c=o.traverse({field:d,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:c.getDataAsJson();break;case"data":w.hasData=!0,w.data=()=>o.traverseOrError({field:d,ignoreError:t});default:continue}}const i=o.getInputsLocked();if(i)for(const[,d]of n)d.data===void 0&&(d.hasData=!1);return{locked:i,results:n}}function Wr(o,e=!0,t=""){if(!o.getIsReadyOrError())throw new Error("resource is not ready");const r=Bt(o,e,!1,t);Gt(r.locked);const s={};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 Be.PlError(a.error);s[n]={id:Rt(i.spec,a.value),spec:i.spec,data:a.value}}return s}class Ne{constructor(e,t){p(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const s of t.values())for(const n of[s.prod,s.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}getBlockLabel(e){var t,r;return f.notEmpty((r=(t=this.blocks.get(e))==null?void 0:t.info)==null?void 0:r.label,`block "${e}" not found`)}getData(){const e=this.getDataWithErrors(),t=[];for(const r of e.entries)r.obj.id!==void 0&&r.obj.data.ok&&t.push({ref:r.ref,obj:{id:r.obj.id,spec:r.obj.spec,data:r.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,r;const s=i=>{r===void 0&&(r=i),t=!1},n=(i,a,u)=>{if(u.spec!==void 0&&u.hasData===!0&&u.data!==void 0){const c=u.data();c!==void 0?e.push({ref:te(i,a),obj:{id:c.ok?Rt(u.spec,c.value):void 0,spec:u.spec,data:c}}):s(`no_data:${i}:${a}`)}};for(const[i,a]of this.blocks){const u=new Set;if(a.prod!==void 0){a.prod.locked||s(`prod_not_locked:${i}`);for(const[c,d]of a.prod.results)u.add(c),n(i,c,d)}if(a.staging!==void 0){a.staging.locked||s(`staging_not_locked:${i}`);for(const[c,d]of a.staging.results)u.has(c)||n(i,c,d)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const s=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||s(`staging_not_locked:${n}`);for(const[u,c]of i.staging.results)c.spec!==void 0&&(e.push({ref:te(n,u),obj:c.spec}),a.add(u))}else s(`staging_not_rendered:${n}`);if(i.prod!==void 0){i.prod.locked||s(`prod_not_locked:${n}`);for(const[u,c]of i.prod.results)a.has(u)||c.spec!==void 0&&e.push({ref:te(n,u),obj:c.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const s=new Set,n=i=>{for(const[a,u]of i.results)s.has(a)||u.spec===void 0||(s.add(a),F.executePSpecPredicate(e,u.spec)&&t.push({label:r.info.label+" / "+a,ref:te(r.info.id,a),spec:u.spec}))};r.staging!==void 0&&n(r.staging),r.prod!==void 0&&n(r.prod)}return t}static create(e,t,r){const s=e.accessor(t).node(),n=f.notEmpty(s.getKeyValueAsJson(G)),a=Ce(n).traverseIds("upstream",r),u=new Map;for(const c of V(n)){if(!a.has(c.id))continue;const d=tt(s.traverse({field:P(c.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,s.traverseOrError({field:P(c.id,"prodUiCtx"),stableIfNotFound:!0})),h=tt(s.traverse({field:P(c.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,s.traverseOrError({field:P(c.id,"stagingUiCtx")}));u.set(c.id,{info:c,prod:d,staging:h})}return new Ne(e,u)}}function tt(o,e){if(e===void 0)return o?{locked:!1,results:new Map}:void 0;if(e.ok)return Bt(e.value,!1,!0)}function Ve(o,e){const t=o.persist(),r=f.notEmpty(o.traverse({field:P(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),s=o.getKeyValueAsString(be(e));return{blockId:e,args:r,uiState:s,blockMeta:n=>{const i=n.accessor(t).node(),a=f.notEmpty(i.getKeyValueAsJson(G)),u=new Map;for(const c of V(a))u.set(c.id,c);return u}}}function Ot(o,e){const t=o.persist();return{...Ve(o,e),prod:r=>{var s;return(s=r.accessor(t).node({ignoreError:!0}).traverse({field:P(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:s.persist()},staging:r=>{var n;const s=(n=r.accessor(t).node({ignoreError:!0}).traverse({field:P(e,"stagingOutput"),ignoreError:!0}))==null?void 0:n.persist();return s===void 0&&r.markUnstable("staging_not_rendered"),s},getResultsPool:r=>Ne.create(r,t,e)}}function*T(o,e){switch(yield o,o.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*T(o.cfg);return;case"MakeObject":for(const[,t]of Object.entries(o.template))yield*T(t);return;case"MakeArray":for(const t of o.template)yield*T(t);return;case"GetJsonField":case"GetResourceField":yield*T(o.source),yield*T(o.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*T(o.source),yield*T(o.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetLogHandle":yield*T(o.source);return;case"IsEmpty":yield*T(o.arg);return;case"Not":yield*T(o.operand);return;case"And":case"Or":yield*T(o.operand1),yield*T(o.operand2);return;default:f.assertNever(o)}}function zr(o,e){const t={};for(const[r,s]of Object.entries(o))t[r]=e(s);return t}function ce(o,e){return o===void 0?void 0:e(o)}function Yr(o){switch(o.type){case"GetImportProgress":return!0;default:return!1}}function Qr(o){for(const e of T(o))if(Yr(e))return!0;return!1}function pe(o){return{type:"ReturnResult",result:o}}function m(o){return()=>pe(o)}const Zr=o=>{const e={};for(const[t,r]of Object.entries(o))e[t]=r;return m(e)},Xr=o=>{const e=o.source;if(e===void 0)return m(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return m(t)},eo=o=>{const e=o.source,t=o.field;return e===void 0||t===void 0?m(void 0):({cCtx:r})=>{var s;return pe((s=r.accessor(e).node().traverse(t))==null?void 0:s.persist())}};function Dt(o,e){const t={},r=o.length;for(let s=0;s<r;s++)t[String(s)]=e(o[s]);return t}function to(o,e){return t=>{const r=t.source;return r===void 0?m(void 0):()=>({type:"ScheduleSubroutine",subroutine:Tt(r.length),args:Dt(r,s=>y({...o,[e.itVar]:s},e.mapping))})}}function Tt(o){return e=>{const t=[];for(let r=0;r<o;r++)t.push(e[String(r)]);return m(t)}}function ro(o,e){return t=>{const r=t.source;if(r===void 0)return m(void 0);const s={};for(const[n,i]of Object.entries(r)){const a={...o,[e.itVar]:i};s[n]=y(a,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:oo,args:s})}}const oo=o=>m(o),so=o=>{const e=o.arg;return m(e===void 0?void 0:e.length===0)},no=o=>{const e=o.operand;return m(e===void 0?void 0:!e)},io=o=>{const e=o.operand1,t=o.operand2;return m(e===void 0||t===void 0?void 0:e&&t)},ao=o=>{const e=o.operand1,t=o.operand2;return m(e===void 0||t===void 0?void 0:e||t)},co=o=>{const e=o.source;return e===void 0?m(void 0):({cCtx:t})=>{var r;return pe((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},uo=o=>{const e=o.source,t=o.field;return m(e===void 0||t===void 0?void 0:e[t])};function lo(o,e){return t=>{const r=t.source;return r===void 0?m(void 0):({cCtx:s})=>{const n=s.accessor(r).node(),i={};for(const a of n.listInputFields()){const u=n.traverse(a);if(u===void 0)i[a]=m(void 0);else{const c={...o,[e.itVar]:u.persist()};i[a]=y(c,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:po,args:i}}}}const po=o=>m(o),ho=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:S.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r!==void 0)return await t.blobDriver.getContent(r.handle)}})})},fo=o=>{const e=o.source;return e===void 0?m(void 0):({cCtx:t,drivers:r})=>{const s=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:S.Computable.make(()=>r.blobDriver.getDownloadedBlob(s),{postprocessValue:async n=>n===void 0?void 0:(await r.blobDriver.getContent(n.handle)).toString()})}}},go=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:S.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r==null)return;const s=await t.blobDriver.getContent(r.handle);if(s!=null)return JSON.parse(Buffer.from(s).toString())}})})},mo=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},vo=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},yo=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},bo=o=>e=>{const t=e.source;return t===void 0?m(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,o)})},wo=o=>e=>{const t=e.source;return t===void 0?m(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,o)})},So=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function y(o,e){switch(e.type){case"GetFromCtx":const t=o[e.variable];return typeof t=="function"?r=>pe(t(r.cCtx)):(t===void 0&&console.log("asdasd"),m(t));case"Isolate":return({drivers:r})=>({type:"ScheduleComputable",computable:At(r,o,e.cfg)});case"Immediate":return m(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:uo,args:{source:y(o,e.source),field:y(o,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:to(o,e),args:{source:y(o,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:ro(o,e),args:{source:y(o,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:Zr,args:zr(e.template,r=>y(o,r))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:Tt(e.template.length),args:Dt(e.template,r=>y(o,r))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:Xr,args:{source:y(o,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:so,args:{arg:y(o,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:no,args:{operand:y(o,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:io,args:{operand1:y(o,e.operand1),operand2:y(o,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:ao,args:{operand1:y(o,e.operand1),operand2:y(o,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:lo(o,e),args:{source:y(o,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:eo,args:{source:y(o,e.source),field:y(o,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:co,args:{source:y(o,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:ho,args:{source:y(o,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:fo,args:{source:y(o,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:go,args:{source:y(o,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:mo,args:{source:y(o,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:vo,args:{source:y(o,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:yo,args:{source:y(o,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:bo(e.lines),args:{source:y(o,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:wo(e.patternToSearch),args:{source:y(o,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:So,args:{source:y(o,e.source)}});default:return f.assertNever(e)}}const ko=["$prod","$staging"];function Po(o){return{$blockId:o.blockId,$args:JSON.parse(o.args),$ui:o.uiState!==void 0?JSON.parse(o.uiState):void 0,$prod:o.prod,$staging:o.staging}}const Et=Symbol(),jt="return",Co={op:Et,arg:jt};function Fo(o){return o.op==Et&&o.arg==jt}function Ro(){return{pendingSubroutines:new Map}}function rt(o,e,t,r){const s=new it(t),n=(a,u)=>{if(Fo(a))return e.result=u,!1;const c=f.notEmpty(e.pendingSubroutines.get(a.op));if(a.arg in c.args)throw new Error("argument already set");return c.args[a.arg]=u,c.argCounter--,c.argCounter===0&&(e.pendingSubroutines.delete(a.op),s.push({destination:c.destination,operation:c.subroutine(c.args)})),!0},i=[];e:for(;s.length>0;){const a=s.shift(),u=a.operation(o);switch(u.type){case"ReturnResult":if(!n(a.destination,u.result))break e;break;case"ScheduleSubroutine":const c=Symbol(),d=Object.entries(u.args),h=d.length;if(h===0)s.push({destination:a.destination,operation:u.subroutine({})});else{for(const[g,v]of d)s.push({destination:{op:c,arg:g},operation:v});e.pendingSubroutines.set(c,{argCounter:h,args:{},subroutine:u.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:u.computable});break;default:f.assertNever(u)}}return i}function xt(o,e,t,r={}){return At(o,Po(e),t,r)}function At(o,e,t,r={}){const s=Oe({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>ko.indexOf(n)===-1)),cfg:t});return S.Computable.makeRaw(n=>{const i={drivers:o,cCtx:n},a=Ro();return{ir:rt(i,a,[{destination:Co,operation:y(e,t)}],!0),async postprocessValue(c,d){const h=[];for(const R of c)h.push({destination:R.destination,operation:m(R.computable)});const g={drivers:o,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},v=new Map;for(const[R,U]of a.pendingSubroutines)v.set(R,{...U,args:{...U.args}});const w={result:a.result,pendingSubroutines:v};if(rt(g,w,h,!1),!("result"in w))throw new Error("illegal cfg rendering stack state, no result");return w.result}}},{...r,key:s})}function Bo(o){return o instanceof ArrayBuffer||ArrayBuffer.isView(o)}function ot(o){return o!==void 0?Buffer.from(o).toString("base64"):void 0}class ue{constructor(e,t,r,s,n){p(this,"callbackRegistry");p(this,"fnJSONStringify");p(this,"fnJSONParse");p(this,"computablesToResolve",{});p(this,"computableCtx");p(this,"accessors",new Map);p(this,"meta");p(this,"_resultPool");if(this.scope=e,this.vm=t,this.blockCtx=r,this.env=s,this.computableCtx=n,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");this.meta=r.blockMeta(n),this.injectCtx()}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw ue.cleanErrorContext(t),t}}runCallback(e,...t){try{return ne.Scope.withScope(r=>{const s=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(s)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(s,this.vm.undefined,...t.map(n=>this.exportObjectUniversal(n,r)))))})}catch(r){throw ue.cleanErrorContext(r),r}}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,s)=>{if(!this.accessors.has(r)){const n=this.blockCtx[s];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 ot(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return ot(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r){const s=this.getAccessor(e);if(!s.getIsReadyOrError())return;const n=Wr(s,t,r),i={};for(const[a,u]of Object.entries(n))i[a]=F.mapPObjectData(u,c=>this.wrapAccessor(c));return i}registerComputable(e,t){const r=`${e}_${M.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",S.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("utf-8")}}))}getBlobContentAsBase64(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",S.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("base64")}}))}getDownloadedBlobContentHandle(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getDownloadedBlobContentHandle",this.env.driverKit.blobDriver.getDownloadedBlob(t))}getOnDemandBlobContentHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getOnDemandBlobContentHandle",this.env.driverKit.blobDriver.getOnDemandBlob(t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(r,t))}getProgressLog(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(r,t))}getLogHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getLogHandle",this.env.driverKit.logDriver.getLogHandle(t))}getBlockLabel(e){const t=this.meta.get(e);if(t===void 0)throw new Error(`Block ${e} not found.`);return t.label}get resultPool(){if(this._resultPool===void 0){if(this.computableCtx===void 0)throw new Error("can't use result pool in this context (most porbably called from the future mapper)");this._resultPool=f.notEmpty(this.blockCtx.getResultsPool,"getResultsPool")(this.computableCtx)}return this._resultPool}calculateOptions(e){return this.resultPool.calculateOptions(e)}getDataFromResultPool(){const e=this.resultPool.getData();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:F.mapPObjectData(t.obj,r=>this.wrapAccessor(r))}))}}getDataWithErrorsFromResultPool(){const e=this.resultPool.getDataWithErrors();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:{id:t.obj.id,spec:t.obj.spec,data:F.mapValueInVOE(t.obj.data,r=>this.wrapAccessor(r))}}))}}getSpecsFromResultPool(){const e=this.resultPool.getSpecs();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`specs_from_pool_incomplete:${e.instabilityMarker}`),e}createPFrame(e){if(this.computableCtx===void 0)throw new Error("can't instantiate PFrames from this context (most porbably called from the future mapper)");return this.env.driverKit.pFrameDriver.createPFrame(e.map(t=>F.mapPObjectData(t,r=>this.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(F.mapPTableDef(e,t=>F.mapPObjectData(t,r=>this.getAccessor(r))),this.computableCtx)}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=M.randomUUID();return this.accessors.set(t,e),t}}exportSingleValue(e,t){const r=this.tryExportSingleValue(e,t);if(r===void 0)throw new Error(`Can't export value: ${e}`);return r}tryExportSingleValue(e,t){let r,s=!1;switch(typeof e){case"string":r=this.vm.newString(e),s=!0;break;case"number":r=this.vm.newNumber(e),s=!0;break;case"undefined":r=this.vm.undefined;break;case"boolean":r=e?this.vm.true:this.vm.false;break;default:if(e===null){r=this.vm.null;break}if(Bo(e)){r=this.vm.newArrayBuffer(e),s=!0;break}return}return s&&t!=null?t.manage(r):r}exportObjectUniversal(e,t){const r=this.tryExportSingleValue(e,t);return r!==void 0?r:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const r=this.vm.newString(JSON.stringify(e)).consume(s=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,s)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){switch(this.vm.typeof(e)){case"undefined":return;case"boolean":case"number":case"string":return this.vm.dump(e);default:return this.importObjectViaJson(e)}}importObjectViaJson(e){const t=this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify,this.vm.undefined,e)).consume(r=>this.vm.getString(r));if(t!=="undefined")return JSON.parse(t)}injectCtx(){ne.Scope.withScope(e=>{const t=e.manage(this.vm.newObject());this.vm.setProp(t,"args",e.manage(this.vm.newString(this.blockCtx.args))),this.blockCtx.uiState!==void 0&&this.vm.setProp(t,"uiState",e.manage(this.vm.newString(this.blockCtx.uiState))),this.vm.setProp(t,"callbackRegistry",this.callbackRegistry);const r=(s,n)=>{this.vm.newFunction(s,n).consume(i=>this.vm.setProp(t,s,i))};r("getAccessorHandleByName",s=>this.exportSingleValue(this.getAccessorHandleByName(this.vm.getString(s)),void 0)),r("resolveWithCommon",(s,n,...i)=>this.exportSingleValue(this.resolveWithCommon(this.vm.getString(s),this.importObjectViaJson(n),...i.map(a=>this.importObjectViaJson(a))),void 0)),r("getResourceType",s=>this.exportObjectViaJson(this.getResourceType(this.vm.getString(s)),void 0)),r("getInputsLocked",s=>this.exportSingleValue(this.getInputsLocked(this.vm.getString(s)),void 0)),r("getOutputsLocked",s=>this.exportSingleValue(this.getOutputsLocked(this.vm.getString(s)),void 0)),r("getIsReadyOrError",s=>this.exportSingleValue(this.getIsReadyOrError(this.vm.getString(s)),void 0)),r("getIsFinal",s=>this.exportSingleValue(this.getIsFinal(this.vm.getString(s)),void 0)),r("getError",s=>this.exportSingleValue(this.getError(this.vm.getString(s)),void 0)),r("listInputFields",s=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(s)),void 0)),r("listOutputFields",s=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(s)),void 0)),r("listDynamicFields",s=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(s)),void 0)),r("getKeyValueBase64",(s,n)=>this.exportSingleValue(this.getKeyValueBase64(this.vm.getString(s),this.vm.getString(n)),void 0)),r("getKeyValueAsString",(s,n)=>this.exportSingleValue(this.getKeyValueAsString(this.vm.getString(s),this.vm.getString(n)),void 0)),r("getDataBase64",s=>this.exportSingleValue(this.getDataBase64(this.vm.getString(s)),void 0)),r("getDataAsString",s=>this.exportSingleValue(this.getDataAsString(this.vm.getString(s)),void 0)),r("parsePObjectCollection",(s,n,i)=>this.exportObjectUniversal(this.parsePObjectCollection(this.vm.getString(s),this.vm.dump(n),this.vm.getString(i)),void 0)),r("getBlobContentAsBase64",s=>this.exportSingleValue(this.getBlobContentAsBase64(this.vm.getString(s)),void 0)),r("getBlobContentAsString",s=>this.exportSingleValue(this.getBlobContentAsString(this.vm.getString(s)),void 0)),r("getDownloadedBlobContentHandle",s=>this.exportSingleValue(this.getDownloadedBlobContentHandle(this.vm.getString(s)),void 0)),r("getOnDemandBlobContentHandle",s=>this.exportSingleValue(this.getOnDemandBlobContentHandle(this.vm.getString(s)),void 0)),r("getImportProgress",s=>this.exportSingleValue(this.getImportProgress(this.vm.getString(s)),void 0)),r("getLastLogs",(s,n)=>this.exportSingleValue(this.getLastLogs(this.vm.getString(s),this.vm.getNumber(n)),void 0)),r("getProgressLog",(s,n)=>this.exportSingleValue(this.getProgressLog(this.vm.getString(s),this.vm.getString(n)),void 0)),r("getLogHandle",s=>this.exportSingleValue(this.getLogHandle(this.vm.getString(s)),void 0)),r("getBlockLabel",s=>this.exportSingleValue(this.getBlockLabel(this.vm.getString(s)),void 0)),r("getDataFromResultPool",s=>this.exportObjectUniversal(this.getDataFromResultPool(),void 0)),r("getDataWithErrorsFromResultPool",s=>this.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),r("getSpecsFromResultPool",s=>this.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),r("calculateOptions",s=>this.exportObjectUniversal(this.calculateOptions(this.importObjectViaJson(s)),void 0)),r("createPFrame",s=>this.exportSingleValue(this.createPFrame(this.importObjectViaJson(s)),void 0)),r("createPTable",s=>this.exportSingleValue(this.createPTable(this.importObjectViaJson(s)),void 0)),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}function Oo(o,e,t,r,s={}){return S.Computable.makeRaw(n=>{const i=new ne.Scope;n.addOnDestroy(()=>i.dispose());const a=i.manage(o.quickJs.newRuntime());a.setMemoryLimit(1024*640),a.setMaxStackSize(1024*320);const u=i.manage(a.newContext()),c=new ue(i,u,e,o,n);c.evaluateBundle(r.content);const d=c.runCallback(t);return c.resetComputableCtx(),{ir:c.computablesToResolve,postprocessValue:async h=>{for(const[g,v]of Object.entries(h))c.runCallback(g,v);return c.importObjectUniversal(d)}}},s)}function Re(o,e,t,r,s={}){if(F.isFunctionHandle(t)){if(r===void 0)throw new Error("No code bundle.");return Oo(o,e,t,r,s)}else return xt(o.driverKit,e,t,s)}function Do(o,e,t){return S.Computable.make(r=>{var w,R,U,Q,Z,$,H,X;const s=r.accessor(o).node(),n=f.notEmpty(s.getKeyValueAsJson(je)),i=f.notEmpty(s.getKeyValueAsJson(z)),a=f.notEmpty(s.getKeyValueAsJson(Y)),u=f.notEmpty(s.getKeyValueAsJson(G)),c=f.notEmpty(s.getKeyValueAsJson(ie)),d=new Map;for(const{id:k}of V(u)){const J=s.traverse({field:P(k,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0});let _;const E=s.traverse({field:P(k,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(E!==void 0){const D=s.getField({field:P(k,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),B=s.getField({field:P(k,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});_={arguments:E.getDataAsJson(),stale:J.id!==E.id,outputError:D.error!==void 0||B.error!==void 0||((w=D.value)==null?void 0:w.getError())!==void 0||((R=B.value)==null?void 0:R.getError())!==void 0,outputsError:((U=D.error)==null?void 0:U.getDataAsString())??((Z=(Q=D.value)==null?void 0:Q.getError())==null?void 0:Z.getDataAsString()),exportsError:(($=B.error)==null?void 0:$.getDataAsString())??((X=(H=B.value)==null?void 0:H.getError())==null?void 0:X.getDataAsString()),finished:(D.value!==void 0&&D.value.getIsReadyOrError()||D.error!==void 0&&D.error.getIsReadyOrError())&&(B.value!==void 0&&B.value.getIsReadyOrError()||B.error!==void 0&&B.error.getIsReadyOrError())}}d.set(k,{currentArguments:J.getDataAsJson(),prod:_})}const h=oe(u,k=>d.get(k).currentArguments),g=new Set(c.blocksInLimbo),v=[...V(u)].map(({id:k,label:J,renderingMode:_})=>{var Me,Ke,Ue,$e;const E=f.notEmpty(d.get(k)),D=f.notEmpty(h.nodes.get(k));let B="NotCalculated";E.prod!==void 0&&(g.has(k)?B="Limbo":B=E.prod.finished?"Done":"Running");const K=s.traverse({field:P(k,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:l.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),L=K==null?void 0:K.getDataAsJson(),{sections:ee,inputsValid:b,sdkVersion:O}=ce(L==null?void 0:L.config,fe=>{const q=F.normalizeBlockConfig(fe),Ge=Ve(s,k);return{sections:Re(t,Ge,q.sections,q.code),inputsValid:Re(t,Ge,q.inputsValid,q.code),sdkVersion:q.sdkVersion}})||{},C=ce(L,fe=>t.blockUpdateWatcher.get(fe.source,r));return{id:k,label:J,renderingMode:_,stale:((Me=E.prod)==null?void 0:Me.stale)!==!1||B==="Limbo",missingReference:D.missingReferences,upstreams:[...h.traverseIdsExcludingRoots("upstream",k)],downstreams:[...h.traverseIdsExcludingRoots("downstream",k)],calculationStatus:B,outputErrors:((Ke=E.prod)==null?void 0:Ke.outputError)===!0,outputsError:(Ue=E.prod)==null?void 0:Ue.outputsError,exportsError:($e=E.prod)==null?void 0:$e.exportsError,sections:ee,inputsValid:b,currentBlockPack:L==null?void 0:L.source,updatedBlockPack:C,sdkVersion:O,navigationState:e.getState(k)}});return{meta:a,created:new Date(n),lastModified:new Date(i),authorMarker:s.getKeyValueAsJson(Se),blocks:v}},{postprocessValue:r=>{const s=new Set,n=new Set;return{...r,blocks:r.blocks.map(i=>{i.inputsValid||s.add(i.id),i.stale&&n.add(i.id);const a=i.stale||i.upstreams.findIndex(c=>n.has(c))!==-1,u=a&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(c=>s.has(c))===-1;return{...i,canRun:u,stale:a}})}}}).withStableType()}function It(o,e){var t,r;return ce((r=(t=o.traverse({field:P(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:l.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}))==null?void 0:t.getDataAsJson())==null?void 0:r.config,s=>F.normalizeBlockConfig(s))}function To(o,e){const t=o.node();if(l.resourceTypesEqual(t.resourceType,Ae)){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(l.resourceTypesEqual(t.resourceType,Ie)){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 Eo(o,e){if(o!==void 0)return S.Computable.make(t=>To(t.accessor(o),e),{postprocessValue:t=>{if(t!==void 0){if(typeof t=="string")return t;if(t.error!==void 0)throw new Error(t.error);return t.path}}}).withStableType()}function jo(o,e,t){return S.Computable.make(r=>{var a;const s=r.accessor(o).node(),n=It(s,e),i=(a=s.traverse({field:P(e,"blockPack"),assertFieldType:"Dynamic"},{field:l.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:Pt,assertFieldType:"Input"}))==null?void 0:a.persist();return{path:Eo(i,t),sdkVersion:n==null?void 0:n.sdkVersion}},{mode:"StableOnlyLive"})}function xo(o,e,t){return S.Computable.make(r=>{const s=r.accessor(o).node(),n=Ve(s,e);return{author:s.getKeyValueAsJson(we(e)),args:JSON.parse(n.args),ui:n.uiState!==void 0?JSON.parse(n.uiState):void 0}},{key:"inputs#"+l.resourceIdToString(o.rid)+e})}function Ao(o,e,t){return S.Computable.make(r=>{const s=r.accessor(o).node(),n=Ot(s,e),i=It(s,e);return ce(i,a=>{const u={};for(const[c,d]of Object.entries(a.outputs))u[c]=S.Computable.wrapError(Re(t,n,d,a.code));return u})},{key:"outputs#"+l.resourceIdToString(o.rid)+e}).withStableType()}function Io(o,e){return S.Computable.make(t=>{const r=t.accessor(o).node(),s=f.notEmpty(r.getKeyValueAsJson(G)),n=[];for(const{id:i,renderingMode:a}of V(s)){const u=r.traverse({field:P(i,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:l.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),c=u==null?void 0:u.getDataAsJson();if((c==null?void 0:c.config)===void 0)continue;const d=F.normalizeBlockConfig(c.config),h=Object.entries(d.outputs).map(([,v])=>v).filter(v=>!F.isFunctionHandle(v)&&Qr(v)).map(v=>v);if(h.length===0)continue;const g=Ot(r,i);for(const v of h)n.push(S.Computable.wrapError(xt(e.driverKit,g,v)))}return n})}class No{constructor(){p(this,"states",new Map)}setState(e,t){const r=this.states.get(e);if(r===void 0){this.states.set(e,{state:t,change:new S.ChangeSource});return}r.state={...t},r.change.markChanged()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...F.DefaultNavigationState},change:new S.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return S.Computable.make(t=>this.readState(t,e),{key:`navigationState#${e}`})}deleteBlock(e){const t=this.states.get(e);t!==void 0&&(this.states.delete(e),t.change.markChanged())}}class he{constructor(e,t,r){p(this,"rid");p(this,"overview");p(this,"navigationStates",new No);p(this,"blockComputables",new Map);p(this,"blockFrontends",new Map);p(this,"activeConfigs");p(this,"refreshLoopResult");p(this,"abortController",new AbortController);p(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=Do(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=Io(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await ye(this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await Ht.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(l.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!l.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,s=void 0,n=M.randomUUID()){const i=await this.env.bpPreparer.prepare(t),a=await this.env.bpPreparer.getBlockConfig(t);return await A(this.env.pl,this.rid,s,u=>u.addBlock({id:n,label:e,renderingMode:a.renderingMode},{args:JSON.stringify(a.initialArgs),blockPack:i},r)),await this.projectTree.refreshState(),n}async updateBlockPack(e,t,r=!1,s){const n=await this.env.bpPreparer.prepare(t),i=await this.env.bpPreparer.getBlockConfig(t);await A(this.env.pl,this.rid,s,a=>a.migrateBlockPack(e,n,r?JSON.stringify(i.initialArgs):void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await A(this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await A(this.env.pl,this.rid,t,r=>{const s=r.structure;if(s.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const n=s.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 u=n.blocks.find(c=>c.id===a);if(u===void 0)throw new Error(`Can't find block: ${a}`);return u})}]};r.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await ye(this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await ye(this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockLabel(e,t,r){await A(this.env.pl,this.rid,r,s=>{s.setBlockLabel(e,t)}),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await A(this.env.pl,this.rid,r,s=>s.setArgs([{blockId:e,args:JSON.stringify(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await A(this.env.pl,this.rid,r,s=>s.setUiState(e,t===void 0?void 0:JSON.stringify(t))),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,s){await A(this.env.pl,this.rid,s,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 s=l.ensureResourceIdNotNull((await r.getField(l.field(this.rid,P(e,"blockPack")))).value),n=l.ensureResourceIdNotNull((await r.getField(l.field(s,l.Pl.HolderRefField))).value),i=await r.getResourceData(n,!1),a=JSON.parse(Buffer.from(f.notEmpty(i.data)).toString("utf-8"));await A(r,this.rid,t,u=>{u.setArgs([{blockId:e,args:JSON.stringify(a.config.initialArgs)}]),u.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=Ao(this.projectTree.entry(),e,this.env),n={fullState:S.Computable.make(i=>({argsAndUiState:xo(this.projectTree.entry(),e),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=jo(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 Be.SynchronizedTreeState.init(e.pl,t,e.ops.defaultTreeOptions);return new he(e,t,r)}}const Le={platformLocalStorageNameToPath:{},localStorageNameToPath:{local:ct.homedir()},blobDriverOps:{cacheSoftSizeBytes:100*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}},Nt={...Le,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5},Vo={minDelay:1500},Lo="__no_updates__";class Jo extends S.PollComputablePool{constructor(t={}){super({...t,...Vo});p(this,"http");this.http=t.http}getKey(t){switch(t.type){case"dev":case"dev-v1":return`dev_1_${t.folder}_${t.mtime}`;case"dev-v2":return`dev_2_${t.folder}_${t.mtime}`;default:return Lo}}async readValue(t){try{switch(t.type){case"dev":case"dev-v1":{const r=await Ee(t.folder);return r===t.mtime?void 0:{...t,mtime:r}}case"dev-v2":{const r=await N.tryLoadPackDescription(t.folder);if(r===void 0)return;const s=await le(r);return s===t.mtime?void 0:{...t,mtime:s}}default:return}}catch{return}}resultsEqual(t,r){if(t===void 0&&r===void 0)return!0;if(t===void 0||r===void 0)return!1;if(t.type==="from-registry-v1"||r.type==="from-registry-v1")throw new Error("Unexpected, not yet supported.");return t.folder===r.folder&&t.mtime===r.mtime}}class st{constructor(){p(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");if(t.refCount===0){this.resources.delete(e);const r=t.resource;r!=null&&typeof r[Symbol.dispose]=="function"&&r[Symbol.dispose]()}}acquire(e){const t=this.calculateParamsKey(e);let r=this.resources.get(t);r===void 0&&(r={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,r)),r.refCount++;let s=!1;return{resource:r.resource,key:t,unref:()=>{s||(r.refCount--,s=!0,this.check(t))}}}getByKey(e){if(!this.resources.has(e))throw new Error(`resource not found, key = ${e}`);return this.resources.get(e).resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}function nt(o){return String(o.id)}class Mo{constructor(e,t){p(this,"pFrame",new qt.PFrame);p(this,"blobIdToResource",new Map);p(this,"blobHandleComputables",new Map);p(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue()});p(this,"resolveBlob",async e=>{const t=this.getOrCreateComputableForBlob(e);return this.blobDriver.getLocalPath((await t.awaitStableValue()).handle)});this.blobDriver=e,this.columns=t,this.pFrame.setDataSource(this);for(const r of t){for(const n of Mr(r.data))this.blobIdToResource.set(nt(n),n);const s=Kr(r.data,nt);try{this.pFrame.addColumnSpec(r.id,r.spec),this.pFrame.setColumnData(r.id,s)}catch(n){throw new Error(`Adding column ${r.id} to PFrame failed: ${n}; Spec: ${r.spec}, DataInfo: ${s}.`)}}}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 Ko{constructor(e){p(this,"pFrames");p(this,"pTables");this.blobDriver=e,this.pFrames=new class extends st{constructor(t){super(),this.blobDriver=t}createNewResource(t){return new Mo(this.blobDriver,t)}calculateParamsKey(t){return $o(t)}}(this.blobDriver),this.pTables=new class extends st{constructor(t){super(),this.pFrames=t}async createNewResource(t){const s=await this.pFrames.getByKey(t.pFrameHandle).pFrame.createTable({src:W(t.def.src),filters:t.def.filters});return t.def.sorting.length!==0?s.sort(t.def.sorting):s}calculateParamsKey(t){return Uo(t)}}(this.pFrames)}createPFrame(e,t){const r=e.map(n=>F.mapPObjectData(n,i=>qr(i))),s=this.pFrames.acquire(r);return t.addOnDestroy(s.unref),s.key}createPTable(e,t){const r=this.createPFrame(Go(e.src),t),s=F.mapPTableDef(e,i=>i.id),n=this.pTables.acquire({def:s,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.pFrames.getByKey(e).pFrame.findColumns(r)).hits.map(s=>s.hit)}}async getColumnSpec(e,t){return this.pFrames.getByKey(e).pFrame.getColumnSpec(t)}async listColumns(e){return this.pFrames.getByKey(e).pFrame.listColumns()}async calculateTableData(e,t){let r=await this.pFrames.getByKey(e).pFrame.createTable({src:W(t.src),filters:t.filters});if(t.sorting.length>0){const i=await r.sort(t.sorting);r.dispose(),r=i}const s=r.getSpec(),n=await r.getData([...s.keys()]);return r.dispose(),s.map((i,a)=>({spec:i,data:n[a]}))}async getUniqueValues(e,t){return await this.pFrames.getByKey(e).pFrame.getUniqueValues(t)}async getShape(e){return(await this.pTables.getByKey(e)).getShape()}async getSpec(e){return(await this.pTables.getByKey(e)).getSpec()}async getData(e,t,r){return(await this.pTables.getByKey(e)).getData(t,r)}}function W(o){switch(o.type){case"column":return{type:"column",columnId:o.column,qualifications:[]};case"inner":case"full":return{type:o.type,entries:o.entries.map(e=>W(e))};case"outer":return{type:"outer",primary:W(o.primary),secondary:o.secondary.map(e=>W(e))};default:f.assertNever(o)}}function Uo(o){const e=M.createHash("sha256");return e.update(o.pFrameHandle),e.update(Oe(o.def)),e.digest().toString("hex")}function $o(o){const e=o.map(s=>s.id).sort(),t=M.createHash("sha256");let r="";for(const s of e)r!==s&&(t.update(s),r=s);return t.digest().toString("hex")}function Go(o){const e=new Map;return se(o,e),[...e.values()]}function se(o,e){switch(o.type){case"column":e.set(o.column.id,o.column);return;case"full":case"inner":for(const t of o.entries)se(t,e);return;case"outer":se(o.primary,e);for(const t of o.secondary)se(t,e);return;default:f.assertNever(o)}}async function Vt(o,e,t){const r={...Le,...t};Ho(e,r);const s=new f.HmacSha256Signer(r.localSecret),n=x.createDownloadClient(e,o,r.platformLocalStorageNameToPath),i=x.createLogsClient(o,e),a=x.createUploadBlobClient(o,e),u=x.createUploadProgressClient(o,e),c=x.createLsFilesClient(o,e),d=new x.DownloadDriver(e,n,i,r.blobDownloadPath,s,r.blobDriverOps),h=new x.UploadDriver(e,s,a,u,r.uploadDriverOps),g=new x.LogsStreamDriver(i,r.logStreamDriverOps),v=new x.LogsDriver(g,d),w=new x.LsDriver(e,c,o,s,r.localStorageNameToPath),R=new Ko(d);return{blobDriver:d,logDriver:v,lsDriver:w,signer:s,uploadDriver:h,pFrameDriver:R}}function Ho(o,e){e.localStorageNameToPath.local!=ct.homedir()&&o.warn(`'local' storage with homedir was overwrote: ${e.localStorageNameToPath.local}`);const t=Object.keys(e.platformLocalStorageNameToPath),r=Object.keys(e.localStorageNameToPath).find(s=>t.includes(s));if(r)throw new Error(`Platform local storages include one or more local storages: ${r}. Note that we automatically included 'local' storage with user's home directory.`)}class Je{constructor(e,t,r,s,n,i,a){p(this,"pl");p(this,"projectList");p(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=s,this.openedProjectsList=n,this.projectListTree=i,this.projectList=a,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=M.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async s=>{const n=await Jr(s,e);return s.createField(l.field(this.projectListResourceId,t),"Dynamic",n),await s.commit(),await l.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await A(this.pl,e,r,async s=>{s.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(l.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(l.field(this.projectListResourceId,e))).value;if(l.isNullResourceId(r))throw new Error("Unexpected project list structure.");return r})}async ensureProjectRid(e){return typeof e=="string"?await this.projectIdToResourceId(e):e}async openProject(e){const t=await this.ensureProjectRid(e);if(this.openedProjectsByRid.has(t))throw new Error(`Project ${t} already opened`);this.openedProjectsByRid.set(t,await he.init(this.env,t)),this.openedProjectsList.setValue([...this.openedProjectsByRid.keys()])}async closeProject(e){const t=this.openedProjectsByRid.get(e);if(t===void 0)throw new Error(`Project ${e} not found among opened projects`);this.openedProjectsByRid.delete(e),await t.destroy(),this.openedProjectsList.setValue([...this.openedProjectsByRid.keys()])}getOpenedProject(e){const t=this.openedProjectsByRid.get(e);if(t===void 0)throw new Error(`Project ${e} not found among opened projects`);return t}async close(){await Promise.all([...this.openedProjectsByRid.values()].map(e=>e.destroy())),this.env.quickJs,await this.projectListTree.terminate()}async closeAndAwaitTermination(){await this.close()}static generateLocalSecret(){return f.HmacSha256Signer.generateSecret()}static async init(e,t){const r={...Nt,...t},s=await e.withWriteTx("MLInitialization",async g=>{const v=l.field(g.clientRoot,mr);g.createField(v,"Dynamic");const w=await g.getField(v);if(l.isNullResourceId(w.value)){const R=g.createEphemeral(pt);return g.lock(R),g.setField(v,R),await g.commit(),await R.globalId}else return w.value}),n=new f.ConsoleLoggerAdapter(console),i=await Vt(e,n,r),a=new jr(i.signer),u=new x.DownloadUrlDriver(n,e.httpDispatcher,r.frontendDownloadPath),c={pl:e,signer:i.signer,ops:r,bpPreparer:a,frontendDownloadDriver:u,driverKit:i,blockUpdateWatcher:new Jo({minDelay:r.devBlockUpdateRecheckInterval,http:e.httpDispatcher}),quickJs:await ne.getQuickJS()},d=new S.WatchableValue([]),h=await yr(e,s,d,c);return new Je(c,i,i.signer,s,d,h.tree,h.computable)}}exports.BlockPackRegistry=rr;exports.CentralDevSnapshotRegistry=sr;exports.CentralRegistry=or;exports.DefaultDriverKitOps=Le;exports.DefaultMiddleLayerOps=Nt;exports.FrontendFromFolderResourceType=Ie;exports.FrontendFromUrlResourceType=Ae;exports.MiddleLayer=Je;exports.Project=he;exports.TengoTemplateGet=ht;exports.TengoTemplateGetRegistry=ft;exports.TengoTemplateGetTemplate=mt;exports.TengoTemplateGetTemplateURI=gt;exports.TengoTemplatePack=vt;exports.TengoTemplatePackConvert=yt;exports.TengoTemplatePackConvertTemplate=wt;exports.TengoTemplatePackConvertTemplatePack=bt;exports.createRenderTemplate=xe;exports.getDevV1PacketMtime=Ee;exports.getDevV2PacketMtime=le;exports.initDriverKit=Vt;exports.loadTemplate=de;exports.prepareTemplateSpec=St;Object.keys(F).forEach(o=>{o!=="default"&&!Object.prototype.hasOwnProperty.call(exports,o)&&Object.defineProperty(exports,o,{enumerable:!0,get:()=>F[o]})});Object.keys(He).forEach(o=>{o!=="default"&&!Object.prototype.hasOwnProperty.call(exports,o)&&Object.defineProperty(exports,o,{enumerable:!0,get:()=>He[o]})});Object.keys(l).forEach(o=>{o!=="default"&&!Object.prototype.hasOwnProperty.call(exports,o)&&Object.defineProperty(exports,o,{enumerable:!0,get:()=>l[o]})});
|
|
1
|
+
"use strict";var Lt=Object.defineProperty;var Jt=(o,e,t)=>e in o?Lt(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var p=(o,e,t)=>Jt(o,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const F=require("@platforma-sdk/model"),He=require("@milaboratories/pl-model-middle-layer"),re=require("undici"),x=require("@platforma-sdk/block-tools"),j=require("node:fs"),N=require("node:path"),Kt=require("yaml"),g=require("@milaboratories/ts-helpers"),Mt=require("node:fs/promises"),Ut=require("@milaboratories/resolve-helper"),l=require("@milaboratories/pl-client"),Be=require("@milaboratories/pl-tree"),S=require("@milaboratories/computable"),K=require("node:crypto"),it=require("denque"),$t=require("@platforma-sdk/workflow-tengo"),Oe=require("canonicalize"),Gt=require("node:assert"),ne=require("quickjs-emscripten"),Ht=require("node:timers/promises"),_t=require("node:os"),A=require("@milaboratories/pl-drivers"),qt=require("@milaboratories/pframes-node");function at(o){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const t in o)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>o[t]})}}return e.default=o,Object.freeze(e)}const zt=at(Mt),ct=at(_t);async function _e(o){try{return await zt.stat(o,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const Wt=[x.RegistryV1.PlPackageYamlConfigFile],Yt=[x.RegistryV1.PlPackageJsonConfigFile],Te=["backend","dist","tengo","tpl","main.plj.gz"],De=["config","dist","config.json"],ut=["frontend","dist"],qe="block-model/dist/config.json",Qt="block-ui/package.json",Zt=[Te,De,Wt,Yt,ut];async function Xt(o){return await _e(N.join(o,...De))!==void 0||await _e(N.join(o,...Te))!==void 0}function ge(o,e){const t=Ut.tryResolve(o,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${o}`);return t}async function ze(o,e){if(N.isAbsolute(o)||(o=N.resolve(o)),await Xt(o))return{workflow:N.join(o,...Te),config:N.join(o,...De),ui:N.join(o,...ut)};{const t=ge(o,qe),r=ge(o,qe),s=ge(o,Qt);return{workflow:t,config:r,ui:N.resolve(s,"..","dist")}}}async function er(o){try{return await j.promises.readFile(o,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}async function tr(o){try{return await j.promises.stat(o,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}async function Ee(o){let e=0n;for(const t of Zt){const r=N.join(o,...t),s=await tr(r);s!==void 0&&e<s.mtimeNs&&(e=s.mtimeNs)}return e.toString()}async function le(o){const e=await j.promises.stat(o.components.workflow.main.file,{bigint:!0}),t=await j.promises.stat(o.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class rr{constructor(e,t,r){this.v2Provider=e,this.registries=t,this.http=r}async getPackagesForRoot(e){const t=[],r=e.spec;switch(r.type){case"remote-v1":const s=this.http!==void 0?{dispatcher:this.http}:{},i=await(await re.request(`${r.url}/${x.RegistryV1.GlobalOverviewPath}`,s)).body.json();for(const a of i){const{organization:u,package:c,latestMeta:d,latestVersion:h}=a,f={organization:u,name:c,version:h};t.push({registryId:e.id,id:f,meta:{title:d.title??"No title",description:d.description??"No Description",organization:{name:u,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:f,registryUrl:r.url},otherVersions:a.allVersions})}return t;case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(a=>({...a,registryId:e.id}));case"local-dev":for(const a of await j.promises.readdir(r.path,{withFileTypes:!0})){if(!a.isDirectory())continue;const u=N.join(r.path,a.name),c=await er(N.join(u,x.RegistryV1.PlPackageYamlConfigFile));if(c!==void 0){const d=x.RegistryV1.PlPackageConfigData.parse(Kt.parse(c)),h=await Ee(u),f={organization:d.organization,name:d.package,version:"DEV"};t.push({registryId:e.id,id:f,meta:{title:d.meta.title??"No title",description:d.meta.description??"No Description",organization:{name:d.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:u,mtime:h},otherVersions:[]})}else{const d=await x.tryLoadPackDescription(u);if(d!==void 0){const h=await le(d);t.push({registryId:e.id,id:d.id,meta:await x.BlockPackMetaEmbedAbsoluteBytes.parseAsync(d.meta),spec:{type:"dev-v2",folder:u,mtime:h},otherVersions:[]})}}}return t;default:return g.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}}}const or={type:"remote-v2",url:"https://blocks.pl-open.science/releases"},sr={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},nr={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},ir={groups:[{id:"default",label:"Default",blocks:[]}]},ar={stagingRefreshTimestamp:0,blocksInLimbo:[]},cr={label:"New Project"},ur={name:"UserProject",version:"2"},lt="SchemaVersion",dt="1",je="ProjectCreated",W="ProjectLastModified",Y="ProjectMeta",G="ProjectStructure",ie="BlockRenderingState",lr="BlockFrontendState/",dr=/^BlockFrontendState\/(?<blockid>.*)$/;function be(o){return`${lr}${o}`}const pr="BlockArgsAuthor/";function we(o){return`${pr}${o}`}const Se="ProjectStructureAuthor";function hr(o){const e=o.match(dr);if(e!==null)return e.groups.blockid}const fr="__serviceTemplate_";function ke(o){return`${fr}${o}`}function P(o,e){return`${o}-${e}`}const gr=/^(?<blockId>.*)-(?<fieldName>blockPack|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function mr(o){const e=o.match(gr);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const vr="projects",pt={name:"Projects",version:"1"},yr=o=>l.resourceTypesEqual(o.type,pt)?o.fields:[];async function br(o,e,t,r){const s=await Be.SynchronizedTreeState.init(o,e,{...r.ops.defaultTreeOptions,pruning:yr});return{computable:S.Computable.make(i=>{const a=i.accessor(s.entry()).node(),u=t.getValue(i);if(a===void 0)return;const c=[];for(const d of a.listDynamicFields()){const h=a.traverse(d);if(h===void 0)continue;const f=g.notEmpty(h.getKeyValueAsJson(Y)),v=g.notEmpty(h.getKeyValueAsJson(je)),w=g.notEmpty(h.getKeyValueAsJson(W));c.push({id:d,rid:h.id,created:new Date(v),lastModified:new Date(w),opened:u.indexOf(h.id)>=0,meta:f})}return c.sort(d=>-d.lastModified.valueOf()),c}).withStableType(),tree:s}}const wr={name:"EphRenderTemplate",version:"1"},Sr={name:"RenderTemplate",version:"1"};function xe(o,e,t,r,s){if(s.length===0)throw new Error("Zero output names provided");const n=t?o.createEphemeral(wr):o.createStruct(Sr),i=l.field(n,"template"),a=l.field(n,"inputs");return o.createField(i,"Input",e),o.createField(a,"Input",l.Pl.createPlMap(o,r,t)),o.lockInputs(n),l.Pl.futureRecord(o,n,s,"Output","outputs/")}const kr={name:"BContextEnd",version:"1"},Pr={name:"BContext",version:"1"},Cr="id",Fr="parent/",Rr=["context","result"];function We(o,e,t){return xe(o,e,!0,t,Rr)}function Br(o){const e=o.createEphemeral(kr);return o.lock(e),e}function Or(o,e){if(e.length===0)return Br(o);if(e.length===1)return e[0];const t=o.createEphemeral(Pr);o.createField(l.field(t,Cr),"Input",l.Pl.createPlString(o,K.randomUUID()));for(let r=0;r<e.length;r++)o.createField(l.field(t,`${Fr}${r}`),"Input",e[r]);return o.lock(t),t}const ht={name:"TengoTemplateGet",version:"1"},ft="registry",gt="templateURI",mt="template",vt={name:"TengoTemplatePack",version:"1"},yt={name:"TengoTemplatePackConvert",version:"1"},bt="templatePack",wt="template";async function St(o){switch(o.type){case"from-file":return{type:"explicit",content:await j.promises.readFile(o.path)};case"from-registry":case"explicit":return o;default:return g.assertNever(o)}}function Tr(o,e){const t=o.createStruct(ht),r=l.field(t,ft),s=l.field(t,gt),n=l.field(t,mt);return o.setField(r,o.createValue(l.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),o.setField(s,o.createValue(l.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function Dr(o,e){const t=o.createValue(vt,e.content),r=o.createStruct(yt),s=l.field(r,bt),n=l.field(r,wt);return o.setField(s,t),n}function de(o,e){switch(e.type){case"from-registry":return Tr(o,e);case"explicit":return Dr(o,e);default:return g.assertNever(e)}}const Ae={name:"Frontend/FromUrl",version:"1"},Ie={name:"Frontend/FromFolder",version:"1"};function Er(o,e){switch(e.type){case"url":return o.createValue(Ae,JSON.stringify({url:e.url}));case"local":return o.createValue(Ie,JSON.stringify({path:e.path,signature:e.signature}));default:return g.assertNever(e)}}const jr={name:"BlockPackCustom",version:"1"},kt="template",Pt="frontend";function Ye(o){return o.endsWith("/")?o:`${o}/`}class xr{constructor(e,t){this.signer=e,this.http=t}async getBlockConfig(e){switch(e.type){case"explicit":return e.config;case"dev-v1":{const t=await ze(e.folder),r=await j.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await x.loadPackDescription(e.folder),r=await j.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=`${Ye(e.registryUrl)}${x.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`;return await(await re.request(`${r}/config.json`,t)).body.json()}case"from-registry-v2":throw new Error("NOT YET SUPPORTED!");default:return g.assertNever(e)}}async prepare(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await ze(e.folder),r=await j.promises.readFile(t.workflow),s=JSON.parse(await j.promises.readFile(t.config,"utf-8")),n=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:s,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:e}}case"dev-v2":{const t=await x.loadPackDescription(e.folder),r=JSON.parse(await j.promises.readFile(t.components.model.file,{encoding:"utf-8"})),s=await j.promises.readFile(t.components.workflow.main.file),n=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await le(t)),{type:"explicit",template:{type:"explicit",content:s},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=`${Ye(e.registryUrl)}${x.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,s=`${r}/template.plj.gz`,n=await re.request(s,t);if(n.statusCode!==200)throw new Error(`Block not found in registry (url = ${s} ; code = ${n.statusCode}): `+JSON.stringify(e));const i=new Uint8Array(await n.body.arrayBuffer()),u=await(await re.request(`${r}/config.json`,t)).body.json();return{type:"explicit",template:{type:"explicit",content:i},config:u,frontend:{type:"url",url:`${r}/frontend.tgz`},source:e}}case"from-registry-v2":throw new Error("NOT YET SUPPORTED!");default:return g.assertNever(e)}}}function Ar(o,e){const t={config:e.config,source:e.source},r=o.createStruct(jr,JSON.stringify(t));return o.createField(l.field(r,kt),"Input",de(o,e.template)),o.createField(l.field(r,Pt),"Input",Er(o,e.frontend)),o.lock(r),r}function Qe(o,e){switch(e.type){case"explicit":return Ar(o,e);default:return g.assertNever(e.type)}}function te(o,e){return{__isRef:!0,blockId:o,name:e}}function Ir(o){return typeof o=="object"&&o!==null&&o.__isRef===!0&&"blockId"in o&&"name"in o}function Pe(o,e,t){const r=typeof e;switch(r){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if(Ir(e))t===void 0||t.has(e.blockId)?o.upstreams.add(e.blockId):o.missingReferences=!0;else if(Array.isArray(e))for(const s of e)Pe(o,s,t);else for(const[,s]of Object.entries(e))Pe(o,s,t);return;default:g.assertNever(r)}}function Nr(o,e){const t={upstreams:new Set,missingReferences:!1};return Pe(t,o,e),t}function V(o){return{*[Symbol.iterator](){for(const e of o.groups)for(const t of e.blocks)yield t}}}class Ct{constructor(e){p(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,s=>r.add(s.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const s of t)r.delete(s);return r}traverse(e,t,r){let s=[...t];const n=new Set(s);for(;s.length>0;){let i=[];for(const a of s){const u=this.nodes.get(a);r(u),u[e].forEach(c=>{n.has(c)||(n.add(c),i.push(c))})}s=i}}}function Ce(o){const e=new Map;let t;for(const{id:r}of V(o)){const s={id:r,missingReferences:!1};e.set(r,s),t===void 0?s.upstream=new Set:(s.upstream=new Set([t.id]),t.downstream=new Set([s.id])),t=s}return t!==void 0&&(t.downstream=new Set),new Ct(e)}function oe(o,e){const t=new Map,r=new Set;for(const{id:s}of V(o)){const n=e(s);if(n===void 0)continue;const i=Nr(n,r),a={id:s,missingReferences:i.missingReferences,upstream:i.upstreams,downstream:new Set};t.set(s,a),i.upstreams.forEach(u=>t.get(u).downstream.add(s)),r.add(s)}return new Ct(t)}function Vr(o,e){if(o.size!==e.size)return!1;for(const t of o)if(!e.has(t))return!1;return!0}function Fe(o,e){if(o.size>e.size)return Fe(e,o);for(const t of o)if(e.has(t))return!0;return!1}function Ze(o,e){const t=new Set,r=new Set,s=new Set;return o.nodes.forEach(n=>{const i=e.nodes.get(n.id);i===void 0?t.add(n.id):(!Vr(n.upstream,i.upstream)||Fe(n.upstream,s))&&s.add(n.id)}),e.nodes.forEach(n=>{o.nodes.has(n.id)?Fe(n.upstream,s)&&s.add(n.id):r.add(n.id)}),{onlyInA:t,onlyInB:r,different:s}}let me;async function Ft(){if(me===void 0){const o=await St($t.Templates["pframes.export-pframe"]);if(o.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=K.createHash("sha256").update(o.content).digest("hex");me={spec:o,hash:e}}return me}function Lr(o,e,t){return xe(o,e,!0,{pf:t},["result"]).result}function ve(o,e){let t=!1,r,s;return()=>{if(!t)return t=!0,r=o(),s=e(),s;const n=o();return r!==n&&(r=n,s=e()),e()}}class Xe{constructor(e,t){p(this,"currentInputsC",ve(()=>this.fields.currentArgs.modCount,()=>JSON.parse(Buffer.from(this.fields.currentArgs.value).toString())));p(this,"actualProductionInputsC",ve(()=>{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())}));p(this,"productionStaleC",ve(()=>{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(l.Pl.unwrapHolder(e,this.fields.blockPack.ref),kt,"Input")}}const Jr=o=>{throw new Error(`No new block info for ${o}`)};class ae{constructor(e,t,r,s,n,i,a,u,c,d,h,f){p(this,"globalModCount",0);p(this,"fieldsChanged",!1);p(this,"lastModifiedChanged",!1);p(this,"structureChanged",!1);p(this,"metaChanged",!1);p(this,"renderingStateChanged",!1);p(this,"changedBlockFrontendStates",new Set);p(this,"blocksWithChangedInputs",new Set);p(this,"stagingGraph");p(this,"pendingProductionGraph");p(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=s,this.lastModified=n,this.meta=i,this.struct=a,this.renderingState=u,this.blocksInLimbo=c,this.blockInfos=d,this.blockFrontendStates=h,this.ctxExportTplHolder=f}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=Ce(this.struct)),this.stagingGraph}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=oe(this.struct,e=>this.getBlockInfo(e).currentInputs)),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=oe(this.struct,e=>this.getBlockInfo(e).actualProductionInputs)),this.actualProductionGraph}getBlockInfo(e){return g.notEmpty(this.blockInfos.get(e))}getBlock(e){for(const t of V(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const s=l.field(this.rid,P(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(s,"Dynamic",r.ref):this.tx.setField(s,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,s,n){this.setBlockFieldObj(e,t,{ref:r,status:s,value:n})}deleteBlockFields(e,...t){let r=!1;const s=this.getBlockInfo(e);for(const n of t){const i=s.fields;n in i&&(this.tx.removeField(l.field(this.rid,P(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,s,n;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((s=t.stagingCtx)==null?void 0:s.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,s,n;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((s=t.prodCtx)==null?void 0:s.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,s;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((s=t.prodCtx)==null?void 0:s.status)==="Ready"?this.blocksInLimbo.has(e)?!1:(this.blocksInLimbo.add(e),this.renderingStateChanged=!0,this.deleteBlockFields(e,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),!0):this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}setArgs(e){const t=[];for(const{blockId:r,args:s}of e){const n=this.getBlockInfo(r);JSON.parse(s);const i=Buffer.from(s);if(Buffer.compare(n.fields.currentArgs.value,i)===0)continue;const a=this.tx.createValue(l.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())}setBlockLabel(e,t){const r=this.structure;let s=!1;for(const n of V(r))if(n.id===e){n.label=t,s=!0;break}if(!s)throw new Error(`block ${e} not found`);this.updateStructure(r),this.updateLastModified()}createCtx(e,t){const r=[];return e.forEach(s=>{const n=this.getBlockInfo(s);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(l.Pl.unwrapHolder(this.tx,n.fields[t].ref))}),Or(this.tx,r)}exportCtx(e){return Lr(this.tx,l.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createCtx(this.getStagingGraph().nodes.get(e).upstream,"stagingCtx");if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const s=t.getTemplate(this.tx),n=We(this.tx,s,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(l.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(l.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",l.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 s=t.getTemplate(this.tx),n=We(this.tx,s,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(l.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(l.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",l.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=Jr){const r=this.getStagingGraph(),s=this.getActualProductionGraph(),n=Ce(e),i=oe(e,c=>{var d;return(d=this.blockInfos.get(c))==null?void 0:d.actualProductionInputs}),a=Ze(r,n),u=Ze(s,i);for(const c of a.onlyInA){const{fields:d}=this.getBlockInfo(c);this.deleteBlockFields(c,...Object.keys(d)),this.blockInfos.delete(c),this.blocksInLimbo.delete(c)&&(this.renderingStateChanged=!0),this.blockFrontendStates.delete(c)&&this.changedBlockFrontendStates.add(c)}for(const c of a.onlyInB){const d=new Xe(c,{});this.blockInfos.set(c,d);const h=t(c),f=Qe(this.tx,h.blockPack);this.setBlockField(c,"blockPack",l.Pl.wrapInHolder(this.tx,f),"NotReady");const v=Buffer.from(h.args),w=this.tx.createValue(l.Pl.JsonObject,v);this.setBlockField(c,"currentArgs",w,"Ready",v),d.check()}for(const c of a.different)this.resetStaging(c);s.traverse("downstream",[...u.different],c=>{this.resetOrLimboProduction(c.id)}),(a.onlyInB.size>0||a.onlyInA.size>0||a.different.size>0)&&this.resetStagingRefreshTimestamp(),this.struct=e,this.structureChanged=!0,this.stagingGraph=void 0,this.pendingProductionGraph=void 0,this.actualProductionGraph=void 0,this.updateLastModified()}addBlock(e,t,r){const s=this.structure;if(r===void 0)s.groups[s.groups.length-1].blocks.push(e);else{let n=!1;for(const i of s.groups){const a=i.blocks.findIndex(u=>u.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(s,n=>{if(n!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const s of t.groups){const n=s.blocks.findIndex(i=>i.id===e);if(!(n<0)){s.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 s=this.getBlockInfo(e);this.setBlockField(e,"blockPack",l.Pl.wrapInHolder(this.tx,Qe(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)),s.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:n})=>this.resetOrLimboProduction(n)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),s=this.getPendingProductionGraph();if(t)s.traverse("upstream",e,i=>{r.add(i.id)});else for(const i of r){const a=s.nodes.get(i);if(a===void 0)throw new Error(`Can't find block with id: ${i}`);for(const u of a.upstream)if(!r.has(u))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const i of V(this.structure)){if(!r.has(i.id))continue;let a=this.getBlockInfo(i.id).requireProductionRendering||this.blocksInLimbo.has(i.id);if(!a){for(const u of s.nodes.get(i.id).upstream)if(n.has(u)){a=!0;break}}a&&(this.renderProductionFor(i.id),n.add(i.id))}return s.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 it(e),s=new Set(e),n=[];for(;!r.isEmpty();){const u=r.shift(),c=this.getBlockInfo(u).fields;if(!(((i=c.prodOutput)==null?void 0:i.status)==="Ready"&&((a=c.prodCtx)==null?void 0:a.status)==="Ready")&&this.deleteBlockFields(u,"prodOutput","prodCtx","prodUiCtx","prodArgs")){n.push(u);for(const d of t.traverseIdsExcludingRoots("downstream",u))s.has(d)||(r.push(d),s.add(d))}}for(const u of t.traverseIdsExcludingRoots("downstream",...n))this.resetOrLimboProduction(u)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(s=>{let i=this.getBlockInfo(s.id).stagingRendered?0:1;s.upstream.forEach(a=>{const u=t.get(a);u!==0&&(i=Math.max(u+1,i))}),e(s.id,i),t.set(s.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 s=0;this.traverseWithStagingLag((n,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(n),s++)}),s>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,s,n,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((s=t.fields.prodOutput)==null?void 0:s.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((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,we(t)):this.tx.setKValue(this.rid,we(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,Se):this.tx.setKValue(this.rid,Se,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,W,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,G,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,ie,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,Y,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,be(e)):this.tx.setKValue(this.rid,be(e),t)}this.assignAuthorMarkers()}}static async load(e,t,r){const s=e.getResourceData(t,!0),n=e.getKValueJson(t,lt),i=e.getKValueJson(t,W),a=e.getKValueJson(t,Y),u=e.getKValueJson(t,G),c=e.getKValueJson(t,ie),d=e.listKeyValuesString(t),[h,f,v,w,R,{stagingRefreshTimestamp:U,blocksInLimbo:Q},Z]=await Promise.all([s,n,i,a,u,c,d]);if(f!==dt)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${f}`);const $=new Map;for(const b of h.fields){const O=mr(b.name);if(O===void 0)continue;let C=$.get(O.blockId);C===void 0&&(C={id:O.blockId,fields:{}},$.set(O.blockId,C)),C.fields[O.fieldName]=l.isNullResourceId(b.value)?{modCount:0}:{modCount:0,ref:b.value}}const H=await Ft(),X=ke(H.hash),k=h.fields.find(b=>b.name===X);let J;k!==void 0?J=l.ensureResourceIdNotNull(k.value):(J=l.Pl.wrapInHolder(e,de(e,H.spec)),e.createField(l.field(t,ke(H.hash)),"Dynamic",J));const _={stagingRefreshTimestamp:U},E=new Set(Q),T=new Map;for(const b of Z){const O=hr(b.key);O!==void 0&&T.set(O,b.value)}const B=[];$.forEach(({id:b,fields:O})=>{for(const[,C]of Object.entries(O))if(C.ref!==void 0){if(!l.isResource(C.ref)||l.isResourceRef(C.ref))throw new Error("unexpected behaviour");B.push([C,e.getResourceData(C.ref,!1)])}});for(const[b,O]of B){const C=await O;b.value=C.data,l.isNotNullResourceId(C.error)?b.status="Error":C.resourceReady||l.isNotNullResourceId(C.originalResourceId)?b.status="Ready":b.status="NotReady"}const M=new Map;$.forEach(({id:b,fields:O})=>M.set(b,new Xe(b,O)));const L=new Set;for(const b of V(R)){if(!M.has(b.id))throw new Error(`Inconsistent project structure: no inputs for ${b.id}`);L.add(b.id)}M.forEach(b=>{if(!L.has(b.id))throw new Error(`Inconsistent project structure: no structure entry for ${b.id}`);b.check()});const ee=new ae(t,e,r,f,v,w,R,_,E,M,T,J);return ee.fixProblems(),ee}}async function Kr(o,e=cr){const t=o.createEphemeral(ur);o.lock(t);const r=String(Date.now());o.setKValue(t,lt,JSON.stringify(dt)),o.setKValue(t,je,r),o.setKValue(t,W,r),o.setKValue(t,Y,JSON.stringify(e)),o.setKValue(t,G,JSON.stringify(ir)),o.setKValue(t,ie,JSON.stringify(ar));const s=await Ft();return o.createField(l.field(t,ke(s.hash)),"Dynamic",l.Pl.wrapInHolder(o,de(o,s.spec))),t}async function ye(o,e,t){return I(o,e,void 0,t)}async function I(o,e,t,r){if(o instanceof l.PlClient)return await o.withWriteTx("ProjectAction",async s=>{const n=await ae.load(s,e,t),i=await r(n);return n.wasModified&&(n.save(),await s.commit()),i});{const s=await ae.load(o,e,t),n=await r(s);return s.save(),n}}function*Mr(o){switch(o.type){case"Json":return;case"JsonPartitioned":for(const[,e]of Object.entries(o.parts))yield e;return;case"BinaryPartitioned":for(const[,{index:e,values:t}]of Object.entries(o.parts))yield e,yield t;return;default:g.assertNever(o)}}function et(o,e){return Object.fromEntries(Object.entries(o).map(([t,r])=>[t,e(r,t)]))}function Ur(o,e){switch(o.type){case"Json":return{...o};case"JsonPartitioned":return{...o,parts:et(o.parts,e)};case"BinaryPartitioned":return{...o,parts:et(o.parts,t=>({index:e(t.index),values:e(t.values)}))};default:g.assertNever(o)}}const $r=l.resourceType("PColumnData/JsonPartitioned","1"),Gr=l.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Hr=l.resourceType("PColumnData/BinaryPartitioned","1"),_r=l.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),qr=l.resourceType("PColumnData/Json","1");function zr(o){if(!o.getIsReadyOrError())throw new Error("Data not ready.");const e=o.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(l.resourceTypesEqual(o.resourceType,qr)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(l.resourceTypesEqual(o.resourceType,$r)){const t=e,r=Object.fromEntries(o.listInputFields().map(s=>[s,o.traverse({field:s,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(l.resourceTypesEqual(o.resourceType,Gr)){const t=e,r={};for(const s of o.listInputFields()){const n=o.traverse({field:s,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${s}`);for(const a of i){const u=s.slice(0,s.length-1)+","+a.slice(1,a.length);r[u]=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(l.resourceTypesEqual(o.resourceType,Hr)){const t=e,r={};for(const s of o.listInputFields())if(s.endsWith(".index")){const n=s.slice(0,s.length-6);let i=r[n];i===void 0&&(i={},r[n]=i),i.index=o.traverse({field:s,errorIfFieldNotSet:!0}).resourceInfo}else if(s.endsWith(".values")){const n=s.slice(0,s.length-7);let i=r[n];i===void 0&&(i={},r[n]=i),i.values=o.traverse({field:s,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${s}`);for(const[s,n]of Object.entries(r)){if(n.index===void 0)throw new Error(`no index for part ${s}`);if(n.values===void 0)throw new Error(`no values for part ${s}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(l.resourceTypesEqual(o.resourceType,_r)){const t=e,r={};for(const s of o.listInputFields()){const n=o.traverse({field:s,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${s}`);for(const a of i)if(a.endsWith(".index")){const u=a.slice(0,a.length-6),c=s.slice(0,s.length-1)+","+u.slice(1,u.length);let d=r[c];d===void 0&&(d={},r[c]=d),r[c].index=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else if(a.endsWith(".values")){const u=a.slice(0,a.length-7),c=s.slice(0,s.length-1)+","+u.slice(1,u.length);let d=r[c];d===void 0&&(d={},r[c]=d),r[c].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: ${l.resourceTypeToString(o.resourceType)}`)}function Rt(o,e){const t=K.createHash("sha256");return t.update(Oe(o)),t.update(String(l.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function Bt(o,e=!0,t=!1,r=""){var a,u,c;const s=/^(?<name>.*)\.(?<type>spec|data)$/,n=new Map;for(const d of o.listInputFields()){const h=d.match(s);if(!h){if(e)throw new Error(`unexpected field name ${d}`);continue}let f=g.notEmpty((a=h.groups)==null?void 0:a.name);if(!f.startsWith(r)){if(e)throw new Error(`unexpected field name ${d}`);continue}f=f.slice(r.length);const v=g.notEmpty((u=h.groups)==null?void 0:u.type);let w=n.get(f);switch(w===void 0&&(w={},n.set(f,w)),v){case"spec":w.spec=(c=o.traverse({field:d,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:c.getDataAsJson();break;case"data":w.hasData=!0,w.data=()=>o.traverseOrError({field:d,ignoreError:t});default:continue}}const i=o.getInputsLocked();if(i)for(const[,d]of n)d.data===void 0&&(d.hasData=!1);return{locked:i,results:n}}function Wr(o,e=!0,t=""){if(!o.getIsReadyOrError())throw new Error("resource is not ready");const r=Bt(o,e,!1,t);Gt(r.locked);const s={};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 Be.PlError(a.error);s[n]={id:Rt(i.spec,a.value),spec:i.spec,data:a.value}}return s}class Ne{constructor(e,t){p(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const s of t.values())for(const n of[s.prod,s.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}getBlockLabel(e){var t,r;return g.notEmpty((r=(t=this.blocks.get(e))==null?void 0:t.info)==null?void 0:r.label,`block "${e}" not found`)}getData(){const e=this.getDataWithErrors(),t=[];for(const r of e.entries)r.obj.id!==void 0&&r.obj.data.ok&&t.push({ref:r.ref,obj:{id:r.obj.id,spec:r.obj.spec,data:r.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,r;const s=i=>{r===void 0&&(r=i),t=!1},n=(i,a,u)=>{if(u.spec!==void 0&&u.hasData===!0&&u.data!==void 0){const c=u.data();c!==void 0?e.push({ref:te(i,a),obj:{id:c.ok?Rt(u.spec,c.value):void 0,spec:u.spec,data:c}}):s(`no_data:${i}:${a}`)}};for(const[i,a]of this.blocks){const u=new Set;if(a.prod!==void 0){a.prod.locked||s(`prod_not_locked:${i}`);for(const[c,d]of a.prod.results)u.add(c),n(i,c,d)}if(a.staging!==void 0){a.staging.locked||s(`staging_not_locked:${i}`);for(const[c,d]of a.staging.results)u.has(c)||n(i,c,d)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const s=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||s(`staging_not_locked:${n}`);for(const[u,c]of i.staging.results)c.spec!==void 0&&(e.push({ref:te(n,u),obj:c.spec}),a.add(u))}else s(`staging_not_rendered:${n}`);if(i.prod!==void 0){i.prod.locked||s(`prod_not_locked:${n}`);for(const[u,c]of i.prod.results)a.has(u)||c.spec!==void 0&&e.push({ref:te(n,u),obj:c.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const s=new Set,n=i=>{for(const[a,u]of i.results)s.has(a)||u.spec===void 0||(s.add(a),F.executePSpecPredicate(e,u.spec)&&t.push({label:r.info.label+" / "+a,ref:te(r.info.id,a),spec:u.spec}))};r.staging!==void 0&&n(r.staging),r.prod!==void 0&&n(r.prod)}return t}static create(e,t,r){const s=e.accessor(t).node(),n=g.notEmpty(s.getKeyValueAsJson(G)),a=Ce(n).traverseIds("upstream",r),u=new Map;for(const c of V(n)){if(!a.has(c.id))continue;const d=tt(s.traverse({field:P(c.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,s.traverseOrError({field:P(c.id,"prodUiCtx"),stableIfNotFound:!0})),h=tt(s.traverse({field:P(c.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,s.traverseOrError({field:P(c.id,"stagingUiCtx")}));u.set(c.id,{info:c,prod:d,staging:h})}return new Ne(e,u)}}function tt(o,e){if(e===void 0)return o?{locked:!1,results:new Map}:void 0;if(e.ok)return Bt(e.value,!1,!0)}function Ve(o,e){const t=o.persist(),r=g.notEmpty(o.traverse({field:P(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),s=o.getKeyValueAsString(be(e));return{blockId:e,args:r,uiState:s,blockMeta:n=>{const i=n.accessor(t).node(),a=g.notEmpty(i.getKeyValueAsJson(G)),u=new Map;for(const c of V(a))u.set(c.id,c);return u}}}function Ot(o,e){const t=o.persist();return{...Ve(o,e),prod:r=>{var s;return(s=r.accessor(t).node({ignoreError:!0}).traverse({field:P(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:s.persist()},staging:r=>{var n;const s=(n=r.accessor(t).node({ignoreError:!0}).traverse({field:P(e,"stagingOutput"),ignoreError:!0}))==null?void 0:n.persist();return s===void 0&&r.markUnstable("staging_not_rendered"),s},getResultsPool:r=>Ne.create(r,t,e)}}function*D(o,e){switch(yield o,o.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*D(o.cfg);return;case"MakeObject":for(const[,t]of Object.entries(o.template))yield*D(t);return;case"MakeArray":for(const t of o.template)yield*D(t);return;case"GetJsonField":case"GetResourceField":yield*D(o.source),yield*D(o.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*D(o.source),yield*D(o.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetLogHandle":yield*D(o.source);return;case"IsEmpty":yield*D(o.arg);return;case"Not":yield*D(o.operand);return;case"And":case"Or":yield*D(o.operand1),yield*D(o.operand2);return;default:g.assertNever(o)}}function Yr(o,e){const t={};for(const[r,s]of Object.entries(o))t[r]=e(s);return t}function ce(o,e){return o===void 0?void 0:e(o)}function Qr(o){switch(o.type){case"GetImportProgress":return!0;default:return!1}}function Zr(o){for(const e of D(o))if(Qr(e))return!0;return!1}function pe(o){return{type:"ReturnResult",result:o}}function m(o){return()=>pe(o)}const Xr=o=>{const e={};for(const[t,r]of Object.entries(o))e[t]=r;return m(e)},eo=o=>{const e=o.source;if(e===void 0)return m(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return m(t)},to=o=>{const e=o.source,t=o.field;return e===void 0||t===void 0?m(void 0):({cCtx:r})=>{var s;return pe((s=r.accessor(e).node().traverse(t))==null?void 0:s.persist())}};function Tt(o,e){const t={},r=o.length;for(let s=0;s<r;s++)t[String(s)]=e(o[s]);return t}function ro(o,e){return t=>{const r=t.source;return r===void 0?m(void 0):()=>({type:"ScheduleSubroutine",subroutine:Dt(r.length),args:Tt(r,s=>y({...o,[e.itVar]:s},e.mapping))})}}function Dt(o){return e=>{const t=[];for(let r=0;r<o;r++)t.push(e[String(r)]);return m(t)}}function oo(o,e){return t=>{const r=t.source;if(r===void 0)return m(void 0);const s={};for(const[n,i]of Object.entries(r)){const a={...o,[e.itVar]:i};s[n]=y(a,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:so,args:s})}}const so=o=>m(o),no=o=>{const e=o.arg;return m(e===void 0?void 0:e.length===0)},io=o=>{const e=o.operand;return m(e===void 0?void 0:!e)},ao=o=>{const e=o.operand1,t=o.operand2;return m(e===void 0||t===void 0?void 0:e&&t)},co=o=>{const e=o.operand1,t=o.operand2;return m(e===void 0||t===void 0?void 0:e||t)},uo=o=>{const e=o.source;return e===void 0?m(void 0):({cCtx:t})=>{var r;return pe((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},lo=o=>{const e=o.source,t=o.field;return m(e===void 0||t===void 0?void 0:e[t])};function po(o,e){return t=>{const r=t.source;return r===void 0?m(void 0):({cCtx:s})=>{const n=s.accessor(r).node(),i={};for(const a of n.listInputFields()){const u=n.traverse(a);if(u===void 0)i[a]=m(void 0);else{const c={...o,[e.itVar]:u.persist()};i[a]=y(c,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:ho,args:i}}}}const ho=o=>m(o),fo=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:S.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r!==void 0)return await t.blobDriver.getContent(r.handle)}})})},go=o=>{const e=o.source;return e===void 0?m(void 0):({cCtx:t,drivers:r})=>{const s=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:S.Computable.make(()=>r.blobDriver.getDownloadedBlob(s),{postprocessValue:async n=>n===void 0?void 0:(await r.blobDriver.getContent(n.handle)).toString()})}}},mo=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:S.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r==null)return;const s=await t.blobDriver.getContent(r.handle);if(s!=null)return JSON.parse(Buffer.from(s).toString())}})})},vo=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},yo=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},bo=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},wo=o=>e=>{const t=e.source;return t===void 0?m(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,o)})},So=o=>e=>{const t=e.source;return t===void 0?m(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,o)})},ko=o=>{const e=o.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function y(o,e){switch(e.type){case"GetFromCtx":const t=o[e.variable];return typeof t=="function"?r=>pe(t(r.cCtx)):(t===void 0&&console.log("asdasd"),m(t));case"Isolate":return({drivers:r})=>({type:"ScheduleComputable",computable:At(r,o,e.cfg)});case"Immediate":return m(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:lo,args:{source:y(o,e.source),field:y(o,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:ro(o,e),args:{source:y(o,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:oo(o,e),args:{source:y(o,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:Xr,args:Yr(e.template,r=>y(o,r))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:Dt(e.template.length),args:Tt(e.template,r=>y(o,r))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:eo,args:{source:y(o,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:no,args:{arg:y(o,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:io,args:{operand:y(o,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:ao,args:{operand1:y(o,e.operand1),operand2:y(o,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:co,args:{operand1:y(o,e.operand1),operand2:y(o,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:po(o,e),args:{source:y(o,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:to,args:{source:y(o,e.source),field:y(o,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:uo,args:{source:y(o,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:fo,args:{source:y(o,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:go,args:{source:y(o,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:mo,args:{source:y(o,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:vo,args:{source:y(o,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:yo,args:{source:y(o,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:bo,args:{source:y(o,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:wo(e.lines),args:{source:y(o,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:So(e.patternToSearch),args:{source:y(o,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:ko,args:{source:y(o,e.source)}});default:return g.assertNever(e)}}const Po=["$prod","$staging"];function Co(o){return{$blockId:o.blockId,$args:JSON.parse(o.args),$ui:o.uiState!==void 0?JSON.parse(o.uiState):void 0,$prod:o.prod,$staging:o.staging}}const Et=Symbol(),jt="return",Fo={op:Et,arg:jt};function Ro(o){return o.op==Et&&o.arg==jt}function Bo(){return{pendingSubroutines:new Map}}function rt(o,e,t,r){const s=new it(t),n=(a,u)=>{if(Ro(a))return e.result=u,!1;const c=g.notEmpty(e.pendingSubroutines.get(a.op));if(a.arg in c.args)throw new Error("argument already set");return c.args[a.arg]=u,c.argCounter--,c.argCounter===0&&(e.pendingSubroutines.delete(a.op),s.push({destination:c.destination,operation:c.subroutine(c.args)})),!0},i=[];e:for(;s.length>0;){const a=s.shift(),u=a.operation(o);switch(u.type){case"ReturnResult":if(!n(a.destination,u.result))break e;break;case"ScheduleSubroutine":const c=Symbol(),d=Object.entries(u.args),h=d.length;if(h===0)s.push({destination:a.destination,operation:u.subroutine({})});else{for(const[f,v]of d)s.push({destination:{op:c,arg:f},operation:v});e.pendingSubroutines.set(c,{argCounter:h,args:{},subroutine:u.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:u.computable});break;default:g.assertNever(u)}}return i}function xt(o,e,t,r={}){return At(o,Co(e),t,r)}function At(o,e,t,r={}){const s=Oe({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>Po.indexOf(n)===-1)),cfg:t});return S.Computable.makeRaw(n=>{const i={drivers:o,cCtx:n},a=Bo();return{ir:rt(i,a,[{destination:Fo,operation:y(e,t)}],!0),async postprocessValue(c,d){const h=[];for(const R of c)h.push({destination:R.destination,operation:m(R.computable)});const f={drivers:o,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},v=new Map;for(const[R,U]of a.pendingSubroutines)v.set(R,{...U,args:{...U.args}});const w={result:a.result,pendingSubroutines:v};if(rt(f,w,h,!1),!("result"in w))throw new Error("illegal cfg rendering stack state, no result");return w.result}}},{...r,key:s})}function Oo(o){return o instanceof ArrayBuffer||ArrayBuffer.isView(o)}function ot(o){return o!==void 0?Buffer.from(o).toString("base64"):void 0}class ue{constructor(e,t,r,s,n){p(this,"callbackRegistry");p(this,"fnJSONStringify");p(this,"fnJSONParse");p(this,"computablesToResolve",{});p(this,"computableCtx");p(this,"accessors",new Map);p(this,"meta");p(this,"_resultPool");if(this.scope=e,this.vm=t,this.blockCtx=r,this.env=s,this.computableCtx=n,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");this.meta=r.blockMeta(n),this.injectCtx()}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw ue.cleanErrorContext(t),t}}runCallback(e,...t){try{return ne.Scope.withScope(r=>{const s=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(s)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(s,this.vm.undefined,...t.map(n=>this.exportObjectUniversal(n,r)))))})}catch(r){throw ue.cleanErrorContext(r),r}}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,s)=>{if(!this.accessors.has(r)){const n=this.blockCtx[s];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 ot(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return ot(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r){const s=this.getAccessor(e);if(!s.getIsReadyOrError())return;const n=Wr(s,t,r),i={};for(const[a,u]of Object.entries(n))i[a]=F.mapPObjectData(u,c=>this.wrapAccessor(c));return i}registerComputable(e,t){const r=`${e}_${K.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",S.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("utf-8")}}))}getBlobContentAsBase64(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",S.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("base64")}}))}getDownloadedBlobContentHandle(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getDownloadedBlobContentHandle",this.env.driverKit.blobDriver.getDownloadedBlob(t))}getOnDemandBlobContentHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getOnDemandBlobContentHandle",this.env.driverKit.blobDriver.getOnDemandBlob(t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(r,t))}getProgressLog(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(r,t))}getLogHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getLogHandle",this.env.driverKit.logDriver.getLogHandle(t))}getBlockLabel(e){const t=this.meta.get(e);if(t===void 0)throw new Error(`Block ${e} not found.`);return t.label}get resultPool(){if(this._resultPool===void 0){if(this.computableCtx===void 0)throw new Error("can't use result pool in this context (most porbably called from the future mapper)");this._resultPool=g.notEmpty(this.blockCtx.getResultsPool,"getResultsPool")(this.computableCtx)}return this._resultPool}calculateOptions(e){return this.resultPool.calculateOptions(e)}getDataFromResultPool(){const e=this.resultPool.getData();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:F.mapPObjectData(t.obj,r=>this.wrapAccessor(r))}))}}getDataWithErrorsFromResultPool(){const e=this.resultPool.getDataWithErrors();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:{id:t.obj.id,spec:t.obj.spec,data:F.mapValueInVOE(t.obj.data,r=>this.wrapAccessor(r))}}))}}getSpecsFromResultPool(){const e=this.resultPool.getSpecs();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`specs_from_pool_incomplete:${e.instabilityMarker}`),e}createPFrame(e){if(this.computableCtx===void 0)throw new Error("can't instantiate PFrames from this context (most porbably called from the future mapper)");return this.env.driverKit.pFrameDriver.createPFrame(e.map(t=>F.mapPObjectData(t,r=>this.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(F.mapPTableDef(e,t=>F.mapPObjectData(t,r=>this.getAccessor(r))),this.computableCtx)}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=K.randomUUID();return this.accessors.set(t,e),t}}exportSingleValue(e,t){const r=this.tryExportSingleValue(e,t);if(r===void 0)throw new Error(`Can't export value: ${e}`);return r}tryExportSingleValue(e,t){let r,s=!1;switch(typeof e){case"string":r=this.vm.newString(e),s=!0;break;case"number":r=this.vm.newNumber(e),s=!0;break;case"undefined":r=this.vm.undefined;break;case"boolean":r=e?this.vm.true:this.vm.false;break;default:if(e===null){r=this.vm.null;break}if(Oo(e)){r=this.vm.newArrayBuffer(e),s=!0;break}return}return s&&t!=null?t.manage(r):r}exportObjectUniversal(e,t){const r=this.tryExportSingleValue(e,t);return r!==void 0?r:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const r=this.vm.newString(JSON.stringify(e)).consume(s=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,s)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){switch(this.vm.typeof(e)){case"undefined":return;case"boolean":case"number":case"string":return this.vm.dump(e);default:return this.importObjectViaJson(e)}}importObjectViaJson(e){const t=this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify,this.vm.undefined,e)).consume(r=>this.vm.getString(r));if(t!=="undefined")return JSON.parse(t)}injectCtx(){ne.Scope.withScope(e=>{const t=e.manage(this.vm.newObject());this.vm.setProp(t,"args",e.manage(this.vm.newString(this.blockCtx.args))),this.blockCtx.uiState!==void 0&&this.vm.setProp(t,"uiState",e.manage(this.vm.newString(this.blockCtx.uiState))),this.vm.setProp(t,"callbackRegistry",this.callbackRegistry);const r=(s,n)=>{this.vm.newFunction(s,n).consume(i=>this.vm.setProp(t,s,i))};r("getAccessorHandleByName",s=>this.exportSingleValue(this.getAccessorHandleByName(this.vm.getString(s)),void 0)),r("resolveWithCommon",(s,n,...i)=>this.exportSingleValue(this.resolveWithCommon(this.vm.getString(s),this.importObjectViaJson(n),...i.map(a=>this.importObjectViaJson(a))),void 0)),r("getResourceType",s=>this.exportObjectViaJson(this.getResourceType(this.vm.getString(s)),void 0)),r("getInputsLocked",s=>this.exportSingleValue(this.getInputsLocked(this.vm.getString(s)),void 0)),r("getOutputsLocked",s=>this.exportSingleValue(this.getOutputsLocked(this.vm.getString(s)),void 0)),r("getIsReadyOrError",s=>this.exportSingleValue(this.getIsReadyOrError(this.vm.getString(s)),void 0)),r("getIsFinal",s=>this.exportSingleValue(this.getIsFinal(this.vm.getString(s)),void 0)),r("getError",s=>this.exportSingleValue(this.getError(this.vm.getString(s)),void 0)),r("listInputFields",s=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(s)),void 0)),r("listOutputFields",s=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(s)),void 0)),r("listDynamicFields",s=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(s)),void 0)),r("getKeyValueBase64",(s,n)=>this.exportSingleValue(this.getKeyValueBase64(this.vm.getString(s),this.vm.getString(n)),void 0)),r("getKeyValueAsString",(s,n)=>this.exportSingleValue(this.getKeyValueAsString(this.vm.getString(s),this.vm.getString(n)),void 0)),r("getDataBase64",s=>this.exportSingleValue(this.getDataBase64(this.vm.getString(s)),void 0)),r("getDataAsString",s=>this.exportSingleValue(this.getDataAsString(this.vm.getString(s)),void 0)),r("parsePObjectCollection",(s,n,i)=>this.exportObjectUniversal(this.parsePObjectCollection(this.vm.getString(s),this.vm.dump(n),this.vm.getString(i)),void 0)),r("getBlobContentAsBase64",s=>this.exportSingleValue(this.getBlobContentAsBase64(this.vm.getString(s)),void 0)),r("getBlobContentAsString",s=>this.exportSingleValue(this.getBlobContentAsString(this.vm.getString(s)),void 0)),r("getDownloadedBlobContentHandle",s=>this.exportSingleValue(this.getDownloadedBlobContentHandle(this.vm.getString(s)),void 0)),r("getOnDemandBlobContentHandle",s=>this.exportSingleValue(this.getOnDemandBlobContentHandle(this.vm.getString(s)),void 0)),r("getImportProgress",s=>this.exportSingleValue(this.getImportProgress(this.vm.getString(s)),void 0)),r("getLastLogs",(s,n)=>this.exportSingleValue(this.getLastLogs(this.vm.getString(s),this.vm.getNumber(n)),void 0)),r("getProgressLog",(s,n)=>this.exportSingleValue(this.getProgressLog(this.vm.getString(s),this.vm.getString(n)),void 0)),r("getLogHandle",s=>this.exportSingleValue(this.getLogHandle(this.vm.getString(s)),void 0)),r("getBlockLabel",s=>this.exportSingleValue(this.getBlockLabel(this.vm.getString(s)),void 0)),r("getDataFromResultPool",s=>this.exportObjectUniversal(this.getDataFromResultPool(),void 0)),r("getDataWithErrorsFromResultPool",s=>this.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),r("getSpecsFromResultPool",s=>this.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),r("calculateOptions",s=>this.exportObjectUniversal(this.calculateOptions(this.importObjectViaJson(s)),void 0)),r("createPFrame",s=>this.exportSingleValue(this.createPFrame(this.importObjectViaJson(s)),void 0)),r("createPTable",s=>this.exportSingleValue(this.createPTable(this.importObjectViaJson(s)),void 0)),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}function To(o,e,t,r,s={}){return S.Computable.makeRaw(n=>{const i=new ne.Scope;n.addOnDestroy(()=>i.dispose());const a=i.manage(o.quickJs.newRuntime());a.setMemoryLimit(1024*640),a.setMaxStackSize(1024*320);const u=i.manage(a.newContext()),c=new ue(i,u,e,o,n);c.evaluateBundle(r.content);const d=c.runCallback(t);return c.resetComputableCtx(),{ir:c.computablesToResolve,postprocessValue:async h=>{for(const[f,v]of Object.entries(h))c.runCallback(f,v);return c.importObjectUniversal(d)}}},s)}function Re(o,e,t,r,s={}){if(F.isFunctionHandle(t)){if(r===void 0)throw new Error("No code bundle.");return To(o,e,t,r,s)}else return xt(o.driverKit,e,t,s)}function Do(o,e,t){return S.Computable.make(r=>{var w,R,U,Q,Z,$,H,X;const s=r.accessor(o).node(),n=g.notEmpty(s.getKeyValueAsJson(je)),i=g.notEmpty(s.getKeyValueAsJson(W)),a=g.notEmpty(s.getKeyValueAsJson(Y)),u=g.notEmpty(s.getKeyValueAsJson(G)),c=g.notEmpty(s.getKeyValueAsJson(ie)),d=new Map;for(const{id:k}of V(u)){const J=s.traverse({field:P(k,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0});let _;const E=s.traverse({field:P(k,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(E!==void 0){const T=s.getField({field:P(k,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),B=s.getField({field:P(k,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});_={arguments:E.getDataAsJson(),stale:J.id!==E.id,outputError:T.error!==void 0||B.error!==void 0||((w=T.value)==null?void 0:w.getError())!==void 0||((R=B.value)==null?void 0:R.getError())!==void 0,outputsError:((U=T.error)==null?void 0:U.getDataAsString())??((Z=(Q=T.value)==null?void 0:Q.getError())==null?void 0:Z.getDataAsString()),exportsError:(($=B.error)==null?void 0:$.getDataAsString())??((X=(H=B.value)==null?void 0:H.getError())==null?void 0:X.getDataAsString()),finished:(T.value!==void 0&&T.value.getIsReadyOrError()||T.error!==void 0&&T.error.getIsReadyOrError())&&(B.value!==void 0&&B.value.getIsReadyOrError()||B.error!==void 0&&B.error.getIsReadyOrError())}}d.set(k,{currentArguments:J.getDataAsJson(),prod:_})}const h=oe(u,k=>d.get(k).currentArguments),f=new Set(c.blocksInLimbo),v=[...V(u)].map(({id:k,label:J,renderingMode:_})=>{var Ke,Me,Ue,$e;const E=g.notEmpty(d.get(k)),T=g.notEmpty(h.nodes.get(k));let B="NotCalculated";E.prod!==void 0&&(f.has(k)?B="Limbo":B=E.prod.finished?"Done":"Running");const M=s.traverse({field:P(k,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:l.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),L=M==null?void 0:M.getDataAsJson(),{sections:ee,inputsValid:b,sdkVersion:O}=ce(L==null?void 0:L.config,fe=>{const q=F.normalizeBlockConfig(fe),Ge=Ve(s,k);return{sections:Re(t,Ge,q.sections,q.code),inputsValid:Re(t,Ge,q.inputsValid,q.code),sdkVersion:q.sdkVersion}})||{},C=ce(L,fe=>t.blockUpdateWatcher.get(fe.source,r));return{id:k,label:J,renderingMode:_,stale:((Ke=E.prod)==null?void 0:Ke.stale)!==!1||B==="Limbo",missingReference:T.missingReferences,upstreams:[...h.traverseIdsExcludingRoots("upstream",k)],downstreams:[...h.traverseIdsExcludingRoots("downstream",k)],calculationStatus:B,outputErrors:((Me=E.prod)==null?void 0:Me.outputError)===!0,outputsError:(Ue=E.prod)==null?void 0:Ue.outputsError,exportsError:($e=E.prod)==null?void 0:$e.exportsError,sections:ee,inputsValid:b,currentBlockPack:L==null?void 0:L.source,updatedBlockPack:C,sdkVersion:O,navigationState:e.getState(k)}});return{meta:a,created:new Date(n),lastModified:new Date(i),authorMarker:s.getKeyValueAsJson(Se),blocks:v}},{postprocessValue:r=>{const s=new Set,n=new Set;return{...r,blocks:r.blocks.map(i=>{i.inputsValid||s.add(i.id),i.stale&&n.add(i.id);const a=i.stale||i.upstreams.findIndex(c=>n.has(c))!==-1,u=a&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(c=>s.has(c))===-1;return{...i,canRun:u,stale:a}})}}}).withStableType()}function It(o,e){var t,r;return ce((r=(t=o.traverse({field:P(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:l.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}))==null?void 0:t.getDataAsJson())==null?void 0:r.config,s=>F.normalizeBlockConfig(s))}function Eo(o,e){const t=o.node();if(l.resourceTypesEqual(t.resourceType,Ae)){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(l.resourceTypesEqual(t.resourceType,Ie)){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 jo(o,e){if(o!==void 0)return S.Computable.make(t=>Eo(t.accessor(o),e),{postprocessValue:t=>{if(t!==void 0){if(typeof t=="string")return t;if(t.error!==void 0)throw new Error(t.error);return t.path}}}).withStableType()}function xo(o,e,t){return S.Computable.make(r=>{var a;const s=r.accessor(o).node(),n=It(s,e),i=(a=s.traverse({field:P(e,"blockPack"),assertFieldType:"Dynamic"},{field:l.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:Pt,assertFieldType:"Input"}))==null?void 0:a.persist();return{path:jo(i,t),sdkVersion:n==null?void 0:n.sdkVersion}},{mode:"StableOnlyLive"})}function Ao(o,e,t){return S.Computable.make(r=>{const s=r.accessor(o).node(),n=Ve(s,e);return{author:s.getKeyValueAsJson(we(e)),args:JSON.parse(n.args),ui:n.uiState!==void 0?JSON.parse(n.uiState):void 0}},{key:"inputs#"+l.resourceIdToString(o.rid)+e})}function Io(o,e,t){return S.Computable.make(r=>{const s=r.accessor(o).node(),n=Ot(s,e),i=It(s,e);return ce(i,a=>{const u={};for(const[c,d]of Object.entries(a.outputs))u[c]=S.Computable.wrapError(Re(t,n,d,a.code));return u})},{key:"outputs#"+l.resourceIdToString(o.rid)+e}).withStableType()}function No(o,e){return S.Computable.make(t=>{const r=t.accessor(o).node(),s=g.notEmpty(r.getKeyValueAsJson(G)),n=[];for(const{id:i,renderingMode:a}of V(s)){const u=r.traverse({field:P(i,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:l.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),c=u==null?void 0:u.getDataAsJson();if((c==null?void 0:c.config)===void 0)continue;const d=F.normalizeBlockConfig(c.config),h=Object.entries(d.outputs).map(([,v])=>v).filter(v=>!F.isFunctionHandle(v)&&Zr(v)).map(v=>v);if(h.length===0)continue;const f=Ot(r,i);for(const v of h)n.push(S.Computable.wrapError(xt(e.driverKit,f,v)))}return n})}class Vo{constructor(){p(this,"states",new Map)}setState(e,t){const r=this.states.get(e);if(r===void 0){this.states.set(e,{state:t,change:new S.ChangeSource});return}r.state={...t},r.change.markChanged()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...F.DefaultNavigationState},change:new S.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return S.Computable.make(t=>this.readState(t,e),{key:`navigationState#${e}`})}deleteBlock(e){const t=this.states.get(e);t!==void 0&&(this.states.delete(e),t.change.markChanged())}}class he{constructor(e,t,r){p(this,"rid");p(this,"overview");p(this,"navigationStates",new Vo);p(this,"blockComputables",new Map);p(this,"blockFrontends",new Map);p(this,"activeConfigs");p(this,"refreshLoopResult");p(this,"abortController",new AbortController);p(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=Do(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=No(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await ye(this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await Ht.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(l.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!l.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,s=void 0,n=K.randomUUID()){const i=await this.env.bpPreparer.prepare(t),a=await this.env.bpPreparer.getBlockConfig(t);return await I(this.env.pl,this.rid,s,u=>u.addBlock({id:n,label:e,renderingMode:a.renderingMode},{args:JSON.stringify(a.initialArgs),blockPack:i},r)),await this.projectTree.refreshState(),n}async updateBlockPack(e,t,r=!1,s){const n=await this.env.bpPreparer.prepare(t),i=await this.env.bpPreparer.getBlockConfig(t);await I(this.env.pl,this.rid,s,a=>a.migrateBlockPack(e,n,r?JSON.stringify(i.initialArgs):void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await I(this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await I(this.env.pl,this.rid,t,r=>{const s=r.structure;if(s.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const n=s.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 u=n.blocks.find(c=>c.id===a);if(u===void 0)throw new Error(`Can't find block: ${a}`);return u})}]};r.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await ye(this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await ye(this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockLabel(e,t,r){await I(this.env.pl,this.rid,r,s=>{s.setBlockLabel(e,t)}),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await I(this.env.pl,this.rid,r,s=>s.setArgs([{blockId:e,args:JSON.stringify(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await I(this.env.pl,this.rid,r,s=>s.setUiState(e,t===void 0?void 0:JSON.stringify(t))),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,s){await I(this.env.pl,this.rid,s,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 s=l.ensureResourceIdNotNull((await r.getField(l.field(this.rid,P(e,"blockPack")))).value),n=l.ensureResourceIdNotNull((await r.getField(l.field(s,l.Pl.HolderRefField))).value),i=await r.getResourceData(n,!1),a=JSON.parse(Buffer.from(g.notEmpty(i.data)).toString("utf-8"));await I(r,this.rid,t,u=>{u.setArgs([{blockId:e,args:JSON.stringify(a.config.initialArgs)}]),u.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=Io(this.projectTree.entry(),e,this.env),n={fullState:S.Computable.make(i=>({argsAndUiState:Ao(this.projectTree.entry(),e),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=xo(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,r),r}return t}async destroy(){this.destroyed=!0,this.abortController.abort(),await this.refreshLoopResult,await this.projectTree.terminate(),this.overview.resetState(),this.blockFrontends.forEach(e=>e.resetState()),this.blockComputables.forEach(e=>{e.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){const r=await Be.SynchronizedTreeState.init(e.pl,t,e.ops.defaultTreeOptions);return new he(e,t,r)}}const Le={platformLocalStorageNameToPath:{},localStorageNameToPath:{local:ct.homedir()},blobDriverOps:{cacheSoftSizeBytes:100*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}},Nt={...Le,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5},Lo={minDelay:1500},Jo="__no_updates__";class Ko extends S.PollComputablePool{constructor(t={}){super({...t,...Lo});p(this,"http");this.http=t.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}`;default:return Jo}}async readValue(t){try{switch(t.type){case"dev-v1":{const r=await Ee(t.folder);return r===t.mtime?void 0:{...t,mtime:r}}case"dev-v2":{const r=await x.tryLoadPackDescription(t.folder);if(r===void 0)return;const s=await le(r);return s===t.mtime?void 0:{...t,mtime:s}}default:return}}catch{return}}resultsEqual(t,r){if(t===void 0&&r===void 0)return!0;if(t===void 0||r===void 0)return!1;if(t.type==="from-registry-v1"||r.type==="from-registry-v1"||t.type==="from-registry-v2"||r.type==="from-registry-v2")throw new Error("Unexpected, not yet supported.");return t.folder===r.folder&&t.mtime===r.mtime}}class st{constructor(){p(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");if(t.refCount===0){this.resources.delete(e);const r=t.resource;r!=null&&typeof r[Symbol.dispose]=="function"&&r[Symbol.dispose]()}}acquire(e){const t=this.calculateParamsKey(e);let r=this.resources.get(t);r===void 0&&(r={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,r)),r.refCount++;let s=!1;return{resource:r.resource,key:t,unref:()=>{s||(r.refCount--,s=!0,this.check(t))}}}getByKey(e){if(!this.resources.has(e))throw new Error(`resource not found, key = ${e}`);return this.resources.get(e).resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}function nt(o){return String(o.id)}class Mo{constructor(e,t){p(this,"pFrame",new qt.PFrame);p(this,"blobIdToResource",new Map);p(this,"blobHandleComputables",new Map);p(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue()});p(this,"resolveBlob",async e=>{const t=this.getOrCreateComputableForBlob(e);return this.blobDriver.getLocalPath((await t.awaitStableValue()).handle)});this.blobDriver=e,this.columns=t,this.pFrame.setDataSource(this);for(const r of t){for(const n of Mr(r.data))this.blobIdToResource.set(nt(n),n);const s=Ur(r.data,nt);try{this.pFrame.addColumnSpec(r.id,r.spec),this.pFrame.setColumnData(r.id,s)}catch(n){throw new Error(`Adding column ${r.id} to PFrame failed: ${n}; Spec: ${r.spec}, DataInfo: ${s}.`)}}}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 Uo{constructor(e){p(this,"pFrames");p(this,"pTables");this.blobDriver=e,this.pFrames=new class extends st{constructor(t){super(),this.blobDriver=t}createNewResource(t){return new Mo(this.blobDriver,t)}calculateParamsKey(t){return Go(t)}}(this.blobDriver),this.pTables=new class extends st{constructor(t){super(),this.pFrames=t}async createNewResource(t){const s=await this.pFrames.getByKey(t.pFrameHandle).pFrame.createTable({src:z(t.def.src),filters:t.def.filters});return t.def.sorting.length!==0?s.sort(t.def.sorting):s}calculateParamsKey(t){return $o(t)}}(this.pFrames)}createPFrame(e,t){const r=e.map(n=>F.mapPObjectData(n,i=>zr(i))),s=this.pFrames.acquire(r);return t.addOnDestroy(s.unref),s.key}createPTable(e,t){const r=this.createPFrame(Ho(e.src),t),s=F.mapPTableDef(e,i=>i.id),n=this.pTables.acquire({def:s,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.pFrames.getByKey(e).pFrame.findColumns(r)).hits.map(s=>s.hit)}}async getColumnSpec(e,t){return this.pFrames.getByKey(e).pFrame.getColumnSpec(t)}async listColumns(e){return this.pFrames.getByKey(e).pFrame.listColumns()}async calculateTableData(e,t){let r=await this.pFrames.getByKey(e).pFrame.createTable({src:z(t.src),filters:t.filters});if(t.sorting.length>0){const i=await r.sort(t.sorting);r.dispose(),r=i}const s=r.getSpec(),n=await r.getData([...s.keys()]);return r.dispose(),s.map((i,a)=>({spec:i,data:n[a]}))}async getUniqueValues(e,t){return await this.pFrames.getByKey(e).pFrame.getUniqueValues(t)}async getShape(e){return(await this.pTables.getByKey(e)).getShape()}async getSpec(e){return(await this.pTables.getByKey(e)).getSpec()}async getData(e,t,r){return(await this.pTables.getByKey(e)).getData(t,r)}}function z(o){switch(o.type){case"column":return{type:"column",columnId:o.column,qualifications:[]};case"inner":case"full":return{type:o.type,entries:o.entries.map(e=>z(e))};case"outer":return{type:"outer",primary:z(o.primary),secondary:o.secondary.map(e=>z(e))};default:g.assertNever(o)}}function $o(o){const e=K.createHash("sha256");return e.update(o.pFrameHandle),e.update(Oe(o.def)),e.digest().toString("hex")}function Go(o){const e=o.map(s=>s.id).sort(),t=K.createHash("sha256");let r="";for(const s of e)r!==s&&(t.update(s),r=s);return t.digest().toString("hex")}function Ho(o){const e=new Map;return se(o,e),[...e.values()]}function se(o,e){switch(o.type){case"column":e.set(o.column.id,o.column);return;case"full":case"inner":for(const t of o.entries)se(t,e);return;case"outer":se(o.primary,e);for(const t of o.secondary)se(t,e);return;default:g.assertNever(o)}}async function Vt(o,e,t){const r={...Le,...t};_o(e,r);const s=new g.HmacSha256Signer(r.localSecret),n=A.createDownloadClient(e,o,r.platformLocalStorageNameToPath),i=A.createLogsClient(o,e),a=A.createUploadBlobClient(o,e),u=A.createUploadProgressClient(o,e),c=A.createLsFilesClient(o,e),d=new A.DownloadDriver(e,n,i,r.blobDownloadPath,s,r.blobDriverOps),h=new A.UploadDriver(e,s,a,u,r.uploadDriverOps),f=new A.LogsStreamDriver(i,r.logStreamDriverOps),v=new A.LogsDriver(f,d),w=new A.LsDriver(e,c,o,s,r.localStorageNameToPath),R=new Uo(d);return{blobDriver:d,logDriver:v,lsDriver:w,signer:s,uploadDriver:h,pFrameDriver:R}}function _o(o,e){e.localStorageNameToPath.local!=ct.homedir()&&o.warn(`'local' storage with homedir was overwrote: ${e.localStorageNameToPath.local}`);const t=Object.keys(e.platformLocalStorageNameToPath),r=Object.keys(e.localStorageNameToPath).find(s=>t.includes(s));if(r)throw new Error(`Platform local storages include one or more local storages: ${r}. Note that we automatically included 'local' storage with user's home directory.`)}class Je{constructor(e,t,r,s,n,i,a){p(this,"pl");p(this,"projectList");p(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=s,this.openedProjectsList=n,this.projectListTree=i,this.projectList=a,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=K.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async s=>{const n=await Kr(s,e);return s.createField(l.field(this.projectListResourceId,t),"Dynamic",n),await s.commit(),await l.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await I(this.pl,e,r,async s=>{s.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(l.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(l.field(this.projectListResourceId,e))).value;if(l.isNullResourceId(r))throw new Error("Unexpected project list structure.");return r})}async ensureProjectRid(e){return typeof e=="string"?await this.projectIdToResourceId(e):e}async openProject(e){const t=await this.ensureProjectRid(e);if(this.openedProjectsByRid.has(t))throw new Error(`Project ${t} already opened`);this.openedProjectsByRid.set(t,await he.init(this.env,t)),this.openedProjectsList.setValue([...this.openedProjectsByRid.keys()])}async closeProject(e){const t=this.openedProjectsByRid.get(e);if(t===void 0)throw new Error(`Project ${e} not found among opened projects`);this.openedProjectsByRid.delete(e),await t.destroy(),this.openedProjectsList.setValue([...this.openedProjectsByRid.keys()])}getOpenedProject(e){const t=this.openedProjectsByRid.get(e);if(t===void 0)throw new Error(`Project ${e} not found among opened projects`);return t}async close(){await Promise.all([...this.openedProjectsByRid.values()].map(e=>e.destroy())),this.env.quickJs,await this.projectListTree.terminate()}async closeAndAwaitTermination(){await this.close()}static generateLocalSecret(){return g.HmacSha256Signer.generateSecret()}static async init(e,t){const r={...Nt,...t},s=await e.withWriteTx("MLInitialization",async f=>{const v=l.field(f.clientRoot,vr);f.createField(v,"Dynamic");const w=await f.getField(v);if(l.isNullResourceId(w.value)){const R=f.createEphemeral(pt);return f.lock(R),f.setField(v,R),await f.commit(),await R.globalId}else return w.value}),n=new g.ConsoleLoggerAdapter(console),i=await Vt(e,n,r),a=new xr(i.signer),u=new A.DownloadUrlDriver(n,e.httpDispatcher,r.frontendDownloadPath),c={pl:e,signer:i.signer,ops:r,bpPreparer:a,frontendDownloadDriver:u,driverKit:i,blockUpdateWatcher:new Ko({minDelay:r.devBlockUpdateRecheckInterval,http:e.httpDispatcher}),quickJs:await ne.getQuickJS()},d=new S.WatchableValue([]),h=await br(e,s,d,c);return new Je(c,i,i.signer,s,d,h.tree,h.computable)}}exports.BlockPackRegistry=rr;exports.CentralBlockRegistry=or;exports.DefaultDriverKitOps=Le;exports.DefaultMiddleLayerOps=Nt;exports.FrontendFromFolderResourceType=Ie;exports.FrontendFromUrlResourceType=Ae;exports.MiddleLayer=Je;exports.Project=he;exports.TengoTemplateGet=ht;exports.TengoTemplateGetRegistry=ft;exports.TengoTemplateGetTemplate=mt;exports.TengoTemplateGetTemplateURI=gt;exports.TengoTemplatePack=vt;exports.TengoTemplatePackConvert=yt;exports.TengoTemplatePackConvertTemplate=wt;exports.TengoTemplatePackConvertTemplatePack=bt;exports.V1CentralDevSnapshotRegistry=nr;exports.V1CentralRegistry=sr;exports.createRenderTemplate=xe;exports.getDevV1PacketMtime=Ee;exports.getDevV2PacketMtime=le;exports.initDriverKit=Vt;exports.loadTemplate=de;exports.prepareTemplateSpec=St;Object.keys(F).forEach(o=>{o!=="default"&&!Object.prototype.hasOwnProperty.call(exports,o)&&Object.defineProperty(exports,o,{enumerable:!0,get:()=>F[o]})});Object.keys(He).forEach(o=>{o!=="default"&&!Object.prototype.hasOwnProperty.call(exports,o)&&Object.defineProperty(exports,o,{enumerable:!0,get:()=>He[o]})});Object.keys(l).forEach(o=>{o!=="default"&&!Object.prototype.hasOwnProperty.call(exports,o)&&Object.defineProperty(exports,o,{enumerable:!0,get:()=>l[o]})});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|